aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.cz.toml5
-rw-r--r--.dockerignore14
-rw-r--r--.git_commit_template.txt50
-rw-r--r--.gitignore18
-rw-r--r--.gitmodules3
-rw-r--r--.pre-commit-config.yaml7
-rw-r--r--AUTHORS2
-rw-r--r--CHANGELOG.md1030
-rw-r--r--CMakeLists.txt105
-rw-r--r--Dockerfile.dev33
-rw-r--r--INFO.yaml9
-rw-r--r--Makefile279
-rw-r--r--README.md58
-rw-r--r--apps/.clang-format2
-rw-r--r--apps/CMakeLists.txt99
-rw-r--r--apps/cmake/packaging.cmake (renamed from apps/cmake/Modules/Packaging.cmake)25
-rw-r--r--apps/common-includes/hicn/apps/utils/logger.h46
-rw-r--r--apps/higet/CMakeLists.txt49
-rw-r--r--apps/higet/higet.cc96
-rw-r--r--apps/hiperf/CMakeLists.txt45
-rw-r--r--apps/hiperf/src/client.cc1448
-rw-r--r--apps/hiperf/src/client.h14
-rw-r--r--apps/hiperf/src/common.h315
-rw-r--r--apps/hiperf/src/forwarder_config.h97
-rw-r--r--apps/hiperf/src/forwarder_interface.cc676
-rw-r--r--apps/hiperf/src/forwarder_interface.h131
-rw-r--r--apps/hiperf/src/main.cc435
-rw-r--r--apps/hiperf/src/server.cc802
-rw-r--r--apps/hiperf/src/server.h5
-rw-r--r--apps/http-proxy/CMakeLists.txt73
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/CMakeLists.txt5
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/forwarder_config.h27
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/forwarder_interface.h36
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/http_1x_message_fast_parser.h2
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/http_proxy.h70
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/http_session.h42
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/icn_receiver.h17
-rw-r--r--apps/http-proxy/includes/hicn/http-proxy/utils.h11
-rw-r--r--apps/http-proxy/main.cc64
-rw-r--r--apps/http-proxy/src/forwarder_interface.cc48
-rw-r--r--apps/http-proxy/src/http_1x_message_fast_parser.cc7
-rw-r--r--apps/http-proxy/src/http_proxy.cc97
-rw-r--r--apps/http-proxy/src/http_session.cc74
-rw-r--r--apps/http-proxy/src/icn_receiver.cc48
-rw-r--r--apps/ping/.clang-format2
-rw-r--r--apps/ping/CMakeLists.txt39
-rw-r--r--apps/ping/src/ping_client.cc538
-rw-r--r--apps/ping/src/ping_server.cc311
m---------cmake0
-rw-r--r--cmake/Modules/BuildMacros.cmake300
-rw-r--r--cmake/Modules/FindAsio.cmake41
-rw-r--r--cmake/Modules/FindCURL.cmake69
-rw-r--r--cmake/Modules/FindCollectd.cmake41
-rw-r--r--cmake/Modules/FindGFlags.cmake36
-rw-r--r--cmake/Modules/FindGlog.cmake36
-rw-r--r--cmake/Modules/FindHicnLight.cmake40
-rw-r--r--cmake/Modules/FindHicnPlugin.cmake35
-rw-r--r--cmake/Modules/FindJsoncpp.cmake47
-rw-r--r--cmake/Modules/FindLibEvent.cmake55
-rw-r--r--cmake/Modules/FindLibconfig++.cmake43
-rw-r--r--cmake/Modules/FindLibconfig.cmake43
-rw-r--r--cmake/Modules/FindLibhicn.cmake52
-rwxr-xr-xcmake/Modules/FindLibhicnctrl.cmake45
-rw-r--r--cmake/Modules/FindLibmemif.cmake47
-rw-r--r--cmake/Modules/FindLibparc.cmake50
-rw-r--r--cmake/Modules/FindLibtransport.cmake49
-rw-r--r--cmake/Modules/FindLongBow.cmake55
-rw-r--r--cmake/Modules/FindPThread.cmake58
-rw-r--r--cmake/Modules/FindSafeVapi.cmake40
-rw-r--r--cmake/Modules/FindSysrepo.cmake46
-rw-r--r--cmake/Modules/FindVapiSafe.cmake40
-rw-r--r--cmake/Modules/FindVpp.cmake95
-rw-r--r--cmake/Modules/GTestImport.cmake45
-rw-r--r--cmake/Modules/License.txt12
-rw-r--r--cmake/Modules/Packager.cmake344
-rw-r--r--cmake/Modules/PostInstall.cmake83
-rw-r--r--cmake/Modules/ServiceScript.cmake42
-rw-r--r--cmake/Modules/WindowsMacros.cmake33
-rw-r--r--cmake/Modules/detectCacheSize.cmake21
-rw-r--r--ctrl/.clang-format (renamed from libtransport/cmake/Modules/TestMacros.cmake)6
-rw-r--r--ctrl/CMakeLists.txt18
-rw-r--r--ctrl/facemgr/CMakeLists.txt110
-rw-r--r--ctrl/facemgr/cmake/packaging.cmake (renamed from ctrl/facemgr/cmake/Modules/Packaging.cmake)22
-rw-r--r--ctrl/facemgr/config/facemgr.service2
-rwxr-xr-xctrl/facemgr/config/postinst4
-rwxr-xr-xctrl/facemgr/config/prerm4
-rwxr-xr-xctrl/facemgr/config/preun4
-rw-r--r--ctrl/facemgr/examples/mobility/mobility.c103
-rw-r--r--ctrl/facemgr/examples/updowncli/updowncli.c82
-rw-r--r--ctrl/facemgr/examples/updownsrv/updownsrv.c348
-rw-r--r--ctrl/facemgr/includes/CMakeLists.txt20
-rw-r--r--ctrl/facemgr/includes/facemgr.h3
-rw-r--r--ctrl/facemgr/includes/hicn/facemgr.h3
-rw-r--r--ctrl/facemgr/includes/hicn/facemgr/api.h68
-rw-r--r--ctrl/facemgr/includes/hicn/facemgr/cfg.h206
-rw-r--r--ctrl/facemgr/includes/hicn/facemgr/facelet.h317
-rw-r--r--ctrl/facemgr/includes/hicn/facemgr/loop.h35
-rw-r--r--ctrl/facemgr/src/CMakeLists.txt197
-rw-r--r--ctrl/facemgr/src/api.c3670
-rw-r--r--ctrl/facemgr/src/cache.c116
-rw-r--r--ctrl/facemgr/src/cache.h22
-rw-r--r--ctrl/facemgr/src/cfg.c1948
-rw-r--r--ctrl/facemgr/src/cfg_file.c1121
-rw-r--r--ctrl/facemgr/src/cfg_file.h6
-rw-r--r--ctrl/facemgr/src/common.h105
-rw-r--r--ctrl/facemgr/src/error.c7
-rw-r--r--ctrl/facemgr/src/error.h12
-rw-r--r--ctrl/facemgr/src/facelet.c2119
-rw-r--r--ctrl/facemgr/src/facelet_array.c3
-rw-r--r--ctrl/facemgr/src/facelet_array.h2
-rw-r--r--ctrl/facemgr/src/interface.c254
-rw-r--r--ctrl/facemgr/src/interface.h79
-rw-r--r--ctrl/facemgr/src/interfaces/CMakeLists.txt27
-rw-r--r--ctrl/facemgr/src/interfaces/android/CMakeLists.txt (renamed from ctrl/facemgr/src/interfaces/android_utility/CMakeLists.txt)11
-rw-r--r--ctrl/facemgr/src/interfaces/android/android.c294
-rw-r--r--ctrl/facemgr/src/interfaces/android/android.h39
-rw-r--r--ctrl/facemgr/src/interfaces/android_utility/android_utility.c138
-rw-r--r--ctrl/facemgr/src/interfaces/android_utility/android_utility.h48
-rw-r--r--ctrl/facemgr/src/interfaces/bonjour/CMakeLists.txt2
-rw-r--r--ctrl/facemgr/src/interfaces/bonjour/bonjour.c573
-rw-r--r--ctrl/facemgr/src/interfaces/bonjour/bonjour.h12
-rw-r--r--ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.c302
-rw-r--r--ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.h950
-rw-r--r--ctrl/facemgr/src/interfaces/dummy/CMakeLists.txt2
-rw-r--r--ctrl/facemgr/src/interfaces/dummy/dummy.c96
-rw-r--r--ctrl/facemgr/src/interfaces/dummy/dummy.h4
-rw-r--r--ctrl/facemgr/src/interfaces/hicn_light/CMakeLists.txt13
-rw-r--r--ctrl/facemgr/src/interfaces/hicn_light/hicn_light.c1140
-rw-r--r--ctrl/facemgr/src/interfaces/netlink/CMakeLists.txt2
-rw-r--r--ctrl/facemgr/src/interfaces/netlink/netlink.c782
-rw-r--r--ctrl/facemgr/src/interfaces/network_framework/CMakeLists.txt2
-rw-r--r--ctrl/facemgr/src/interfaces/network_framework/network_framework.c928
-rw-r--r--ctrl/facemgr/src/interfaces/network_framework/network_framework.h3
-rw-r--r--ctrl/facemgr/src/interfaces/priority_controller/CMakeLists.txt2
-rw-r--r--ctrl/facemgr/src/interfaces/priority_controller/priority_controller.c366
-rw-r--r--ctrl/facemgr/src/interfaces/priority_controller/priority_controller.h8
-rw-r--r--ctrl/facemgr/src/interfaces/updown/CMakeLists.txt2
-rw-r--r--ctrl/facemgr/src/interfaces/updown/updown.c173
-rw-r--r--ctrl/facemgr/src/loop_dispatcher.c60
-rw-r--r--ctrl/facemgr/src/loop_libevent.c563
-rw-r--r--ctrl/facemgr/src/main.c255
-rw-r--r--ctrl/libhicnctrl/CMakeLists.txt88
-rw-r--r--ctrl/libhicnctrl/cmake/packaging.cmake (renamed from ctrl/libhicnctrl/cmake/Modules/Packaging.cmake)10
-rw-r--r--ctrl/libhicnctrl/examples/Makefile2
-rw-r--r--ctrl/libhicnctrl/examples/create_face.c198
-rw-r--r--ctrl/libhicnctrl/examples/update_priority.c61
-rw-r--r--ctrl/libhicnctrl/includes/CMakeLists.txt39
-rw-r--r--ctrl/libhicnctrl/includes/ctrl.h2
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl.h3
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/action.h50
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/api.h680
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/callback.h13
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/command.h191
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/commands.h434
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/data.h150
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/face.h206
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/fw_interface.h135
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light.h549
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/object.h68
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/object_type.h58
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects.h17
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/active_interface.h44
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/base.h (renamed from hicn-light/src/hicn/strategies/loadBalancer.h)16
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/cache.h (renamed from hicn-light/src/hicn/config/controlUpdateConnection.h)31
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/connection.h64
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/face.h49
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/listener.h52
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/mapme.h59
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/policy.h40
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/punting.h41
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/route.h52
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/stats.h29
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/strategy.h46
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/objects/subscription.h83
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/parse.h116
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/route.h27
-rw-r--r--ctrl/libhicnctrl/includes/hicn/ctrl/socket.h174
-rw-r--r--ctrl/libhicnctrl/src/CMakeLists.txt215
-rw-r--r--ctrl/libhicnctrl/src/action.c41
-rw-r--r--ctrl/libhicnctrl/src/api.c1435
-rw-r--r--ctrl/libhicnctrl/src/api_private.h226
-rw-r--r--ctrl/libhicnctrl/src/cli.c883
-rw-r--r--ctrl/libhicnctrl/src/cli.h4
-rw-r--r--ctrl/libhicnctrl/src/command.c127
-rw-r--r--ctrl/libhicnctrl/src/commands/command_cache.c74
-rw-r--r--ctrl/libhicnctrl/src/commands/command_connection.c166
-rw-r--r--ctrl/libhicnctrl/src/commands/command_face.c167
-rw-r--r--ctrl/libhicnctrl/src/commands/command_listener.c144
-rw-r--r--ctrl/libhicnctrl/src/commands/command_mapme.c78
-rw-r--r--ctrl/libhicnctrl/src/commands/command_policy.c72
-rw-r--r--ctrl/libhicnctrl/src/commands/command_punting.c60
-rw-r--r--ctrl/libhicnctrl/src/commands/command_route.c187
-rw-r--r--ctrl/libhicnctrl/src/commands/command_stats.c (renamed from hicn-light/src/hicn/config/controlListPolicies.h)33
-rw-r--r--ctrl/libhicnctrl/src/commands/command_strategy.c66
-rw-r--r--ctrl/libhicnctrl/src/commands/command_subscription.c45
-rw-r--r--ctrl/libhicnctrl/src/data.c212
-rw-r--r--ctrl/libhicnctrl/src/face.c430
-rw-r--r--ctrl/libhicnctrl/src/fw_interface.c266
-rw-r--r--ctrl/libhicnctrl/src/hicnctrl.c400
-rw-r--r--ctrl/libhicnctrl/src/libhicnctrl-config.cmake.in8
-rw-r--r--ctrl/libhicnctrl/src/module.h159
-rw-r--r--ctrl/libhicnctrl/src/module_object.c1
-rw-r--r--ctrl/libhicnctrl/src/module_object.h10
-rw-r--r--ctrl/libhicnctrl/src/modules/CMakeLists.txt111
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light.c1435
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light.h59
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/base.h49
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/cache.c178
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/connection.c503
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/connection.h11
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/face.c165
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/face.h16
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/listener.c181
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/listener.h8
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/mapme.c68
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/mapme.h28
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/policy.c162
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/punting.c74
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/route.c177
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/route.h (renamed from hicn-light/src/hicn/config/controlMapMeRetx.h)20
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/stats.c113
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/stats.h24
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/strategy.c138
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/strategy.h8
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/subscription.c71
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/subscription.h8
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light/wldr.c3
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_light_api.c2278
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin.c248
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin/base.h36
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin/listener.c189
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin/listener.h28
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin/route.c552
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin/route.h28
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.c118
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.h28
-rw-r--r--ctrl/libhicnctrl/src/modules/hicn_plugin_api.c1305
-rw-r--r--ctrl/libhicnctrl/src/object.c62
-rw-r--r--ctrl/libhicnctrl/src/object_private.h57
-rw-r--r--ctrl/libhicnctrl/src/object_type.c (renamed from hicn-light/src/hicn/config/controlRemovePolicy.h)35
-rw-r--r--ctrl/libhicnctrl/src/object_vft.c44
-rw-r--r--ctrl/libhicnctrl/src/object_vft.h53
-rw-r--r--ctrl/libhicnctrl/src/objects/active_interface.c86
-rw-r--r--ctrl/libhicnctrl/src/objects/active_interface.h (renamed from hicn-light/src/hicn/config/controlRemovePunting.h)19
-rw-r--r--ctrl/libhicnctrl/src/objects/base.c (renamed from hicn-light/src/hicn/config/controlAdd.h)28
-rw-r--r--ctrl/libhicnctrl/src/objects/base.h27
-rw-r--r--ctrl/libhicnctrl/src/objects/connection.c298
-rw-r--r--ctrl/libhicnctrl/src/objects/connection.h (renamed from hicn-light/src/hicn/core/connectionState.h)29
-rw-r--r--ctrl/libhicnctrl/src/objects/face.c187
-rw-r--r--ctrl/libhicnctrl/src/objects/face.h30
-rw-r--r--ctrl/libhicnctrl/src/objects/listener.c208
-rw-r--r--ctrl/libhicnctrl/src/objects/listener.h30
-rw-r--r--ctrl/libhicnctrl/src/objects/mapme.c95
-rw-r--r--ctrl/libhicnctrl/src/objects/mapme.h30
-rw-r--r--ctrl/libhicnctrl/src/objects/route.c176
-rw-r--r--ctrl/libhicnctrl/src/objects/route.h30
-rw-r--r--ctrl/libhicnctrl/src/objects/stats.c108
-rw-r--r--ctrl/libhicnctrl/src/objects/stats.h29
-rw-r--r--ctrl/libhicnctrl/src/objects/strategy.c92
-rw-r--r--ctrl/libhicnctrl/src/objects/strategy.h29
-rw-r--r--ctrl/libhicnctrl/src/objects/subscription.c94
-rw-r--r--ctrl/libhicnctrl/src/objects/subscription.h (renamed from ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.h)19
-rw-r--r--ctrl/libhicnctrl/src/parse.c412
-rw-r--r--ctrl/libhicnctrl/src/request.c210
-rw-r--r--ctrl/libhicnctrl/src/request.h129
-rw-r--r--ctrl/libhicnctrl/src/route.c102
-rw-r--r--ctrl/libhicnctrl/src/socket.c308
-rw-r--r--ctrl/libhicnctrl/src/socket_private.h47
-rw-r--r--ctrl/libhicnctrl/src/test/CMakeLists.txt51
-rw-r--r--ctrl/libhicnctrl/src/test/common.cc13
-rw-r--r--ctrl/libhicnctrl/src/test/common.h51
-rw-r--r--ctrl/libhicnctrl/src/test/main.cc21
-rw-r--r--ctrl/libhicnctrl/src/test/test_data.cc97
-rw-r--r--ctrl/libhicnctrl/src/test/test_hicnlight_connection.cc132
-rw-r--r--ctrl/libhicnctrl/src/test/test_hicnlight_listener.cc138
-rw-r--r--ctrl/libhicnctrl/src/test/test_hicnlight_route.cc133
-rw-r--r--ctrl/libhicnctrl/src/util/hash.h379
-rw-r--r--ctrl/sysrepo-plugins/AUTHORS5
-rw-r--r--ctrl/sysrepo-plugins/CMakeLists.txt69
-rw-r--r--ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake31
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/CMakeLists.txt61
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt59
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c115
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c33
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.h59
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.c195
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.h42
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c21
-rw-r--r--ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.h31
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/CMakeLists.txt49
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/Doxyfile2494
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c120
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.h46
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c55
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.h91
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c607
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/mainpage.dox211
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c875
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h178
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.c21
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.h64
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/test/README.md32
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aface.xml7
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/apunt.xml6
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aroute.xml13
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dface.xml3
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dpunt.xml6
-rw-r--r--ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/droute.xml6
-rwxr-xr-xctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/test.py66
-rwxr-xr-xctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/Makefile2
-rwxr-xr-xctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/test.c290
-rw-r--r--ctrl/sysrepo-plugins/yang/hicn/hicn.yang247
-rw-r--r--ctrl/sysrepo-plugins/yang/hicn/rpc_call_samples.xml78
-rw-r--r--ctrl/sysrepo-plugins/yang/hicn/sysrepo_startup.xml11
-rw-r--r--ctrl/sysrepo-plugins/yang/ietf/iana-if-type@2014-05-08.yang1704
-rw-r--r--ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang1123
-rw-r--r--ctrl/sysrepo-plugins/yang/ietf/ietf-ip@2014-06-16.yang742
-rw-r--r--ctrl/sysrepo-plugins/yang/ietf/ietf-yang-types@2013-07-15.yang474
-rw-r--r--docs/etc/requirements.txt32
-rw-r--r--docs/source/1-architecture.md42
-rw-r--r--docs/source/apps.md1
-rw-r--r--docs/source/conf.py10
-rw-r--r--docs/source/control.md332
-rw-r--r--docs/source/hicn-light.md127
-rw-r--r--docs/source/index.rst71
-rw-r--r--docs/source/interface.md33
-rw-r--r--docs/source/packethicn.md36
-rw-r--r--docs/source/started.md143
-rw-r--r--docs/source/telemetry.md25
-rw-r--r--docs/source/transport.md339
-rw-r--r--docs/source/utils.md83
-rw-r--r--docs/source/vpp-plugin.md26
-rw-r--r--extras/CMakeLists.txt7
-rw-r--r--extras/libmemif/CMakeLists.txt43
-rw-r--r--extras/libmemif/CMakeLists1.patch75
-rw-r--r--extras/libmemif/CMakeLists2.patch44
-rw-r--r--extras/libmemif/cmake/Modules/Packaging.cmake44
-rw-r--r--extras/libyang/CMakeLists.txt42
-rw-r--r--extras/libyang/cmake/Modules/Packaging.cmake33
-rw-r--r--extras/libyang/libyang.patch50
-rw-r--r--extras/packethicn/CMakeLists.txt86
-rw-r--r--extras/packethicn/cmake/packaging.cmake (renamed from extras/packethicn/cmake/Modules/Packaging.cmake)6
-rw-r--r--extras/packethicn/packet-hicn.c256
-rw-r--r--extras/router-plugin/CMakeLists.txt102
-rw-r--r--extras/router-plugin/cmake/Modules/Packaging.cmake31
-rw-r--r--extras/router-plugin/devices/rtnetlink/mapper.c270
-rw-r--r--extras/router-plugin/devices/rtnetlink/mapper.h35
-rw-r--r--extras/router-plugin/devices/rtnetlink/netns.c787
-rw-r--r--extras/router-plugin/devices/rtnetlink/netns.h145
-rw-r--r--extras/router-plugin/devices/rtnetlink/rtnl.c604
-rw-r--r--extras/router-plugin/devices/rtnetlink/rtnl.h60
-rw-r--r--extras/router-plugin/devices/rtnetlink/test.c203
-rw-r--r--extras/router-plugin/rtinject/tap_inject.c380
-rw-r--r--extras/router-plugin/rtinject/tap_inject.h108
-rw-r--r--extras/router-plugin/rtinject/tap_inject_netlink.c285
-rw-r--r--extras/router-plugin/rtinject/tap_inject_node.c374
-rw-r--r--extras/router-plugin/rtinject/tap_inject_tap.c170
-rw-r--r--extras/sysrepo/CMakeLists.txt43
-rw-r--r--extras/sysrepo/cmake/Modules/Packaging.cmake35
-rw-r--r--extras/sysrepo/sysrepo.patch55
-rw-r--r--hicn-light/.clang-format (renamed from cmake/Modules/FindUncrustify.cmake)12
-rw-r--r--hicn-light/CMakeLists.txt137
-rw-r--r--hicn-light/cmake/packaging.cmake (renamed from hicn-light/cmake/Modules/Packaging.cmake)6
-rw-r--r--hicn-light/config/hicn-light.service2
-rwxr-xr-xhicn-light/config/post2
-rwxr-xr-xhicn-light/config/postinst4
-rwxr-xr-xhicn-light/config/prerm4
-rwxr-xr-xhicn-light/config/preun4
-rw-r--r--hicn-light/src/hicn/CMakeLists.txt119
-rw-r--r--hicn-light/src/hicn/base/CMakeLists.txt29
-rw-r--r--hicn-light/src/hicn/base/loop.c205
-rw-r--r--hicn-light/src/hicn/base/loop.h141
-rw-r--r--hicn-light/src/hicn/cli/CMakeLists.txt93
-rw-r--r--hicn-light/src/hicn/cli/color.c71
-rw-r--r--hicn-light/src/hicn/cli/color.h42
-rw-r--r--hicn-light/src/hicn/cli/hicnc.c237
-rw-r--r--hicn-light/src/hicn/cli/hicnd.c311
-rw-r--r--hicn-light/src/hicn/cli/hicns.c206
-rw-r--r--hicn-light/src/hicn/cli/logo.h37
-rw-r--r--hicn-light/src/hicn/command_line/CMakeLists.txt2
-rw-r--r--hicn-light/src/hicn/command_line/controller/CMakeLists.txt35
-rw-r--r--hicn-light/src/hicn/command_line/controller/hicnLightControl_main.c382
-rw-r--r--hicn-light/src/hicn/command_line/daemon/hicnLightDaemon_main.c414
-rw-r--r--hicn-light/src/hicn/config.h.in3
-rw-r--r--hicn-light/src/hicn/config/CMakeLists.txt114
-rw-r--r--hicn-light/src/hicn/config/commandOps.c72
-rw-r--r--hicn-light/src/hicn/config/commandOps.h132
-rw-r--r--hicn-light/src/hicn/config/commandParser.c221
-rw-r--r--hicn-light/src/hicn/config/commandParser.h200
-rw-r--r--hicn-light/src/hicn/config/commandReturn.h43
-rw-r--r--hicn-light/src/hicn/config/commands.c1737
-rw-r--r--hicn-light/src/hicn/config/commands.h165
-rw-r--r--hicn-light/src/hicn/config/configuration.c1564
-rw-r--r--hicn-light/src/hicn/config/configuration.h122
-rw-r--r--hicn-light/src/hicn/config/configurationFile.c314
-rw-r--r--hicn-light/src/hicn/config/configurationFile.h93
-rw-r--r--hicn-light/src/hicn/config/configurationListeners.c629
-rw-r--r--hicn-light/src/hicn/config/configurationListeners.h74
-rw-r--r--hicn-light/src/hicn/config/configuration_file.c135
-rw-r--r--hicn-light/src/hicn/config/configuration_file.h57
-rw-r--r--hicn-light/src/hicn/config/controlAdd.c128
-rw-r--r--hicn-light/src/hicn/config/controlAddConnection.c450
-rw-r--r--hicn-light/src/hicn/config/controlAddConnection.h31
-rw-r--r--hicn-light/src/hicn/config/controlAddListener.c201
-rw-r--r--hicn-light/src/hicn/config/controlAddListener.h30
-rw-r--r--hicn-light/src/hicn/config/controlAddPolicy.c183
-rw-r--r--hicn-light/src/hicn/config/controlAddPunting.c159
-rw-r--r--hicn-light/src/hicn/config/controlAddRoute.c162
-rw-r--r--hicn-light/src/hicn/config/controlAddRoute.h30
-rw-r--r--hicn-light/src/hicn/config/controlCache.c99
-rw-r--r--hicn-light/src/hicn/config/controlCache.h22
-rw-r--r--hicn-light/src/hicn/config/controlCacheClear.c90
-rw-r--r--hicn-light/src/hicn/config/controlCacheClear.h30
-rw-r--r--hicn-light/src/hicn/config/controlCacheServe.c108
-rw-r--r--hicn-light/src/hicn/config/controlCacheServe.h22
-rw-r--r--hicn-light/src/hicn/config/controlCacheStore.c109
-rw-r--r--hicn-light/src/hicn/config/controlCacheStore.h22
-rw-r--r--hicn-light/src/hicn/config/controlList.c130
-rw-r--r--hicn-light/src/hicn/config/controlList.h30
-rw-r--r--hicn-light/src/hicn/config/controlListConnections.c195
-rw-r--r--hicn-light/src/hicn/config/controlListConnections.h30
-rw-r--r--hicn-light/src/hicn/config/controlListInterfaces.c81
-rw-r--r--hicn-light/src/hicn/config/controlListInterfaces.h31
-rw-r--r--hicn-light/src/hicn/config/controlListListeners.c160
-rw-r--r--hicn-light/src/hicn/config/controlListListeners.h31
-rw-r--r--hicn-light/src/hicn/config/controlListPolicies.c250
-rw-r--r--hicn-light/src/hicn/config/controlListRoutes.c158
-rw-r--r--hicn-light/src/hicn/config/controlMapMe.c104
-rw-r--r--hicn-light/src/hicn/config/controlMapMe.h22
-rw-r--r--hicn-light/src/hicn/config/controlMapMeDiscovery.c109
-rw-r--r--hicn-light/src/hicn/config/controlMapMeDiscovery.h22
-rw-r--r--hicn-light/src/hicn/config/controlMapMeEnable.c107
-rw-r--r--hicn-light/src/hicn/config/controlMapMeEnable.h22
-rw-r--r--hicn-light/src/hicn/config/controlMapMeRetx.c101
-rw-r--r--hicn-light/src/hicn/config/controlMapMeTimescale.c102
-rw-r--r--hicn-light/src/hicn/config/controlMapMeTimescale.h22
-rw-r--r--hicn-light/src/hicn/config/controlQuit.c74
-rw-r--r--hicn-light/src/hicn/config/controlQuit.h29
-rw-r--r--hicn-light/src/hicn/config/controlRemove.c132
-rw-r--r--hicn-light/src/hicn/config/controlRemove.h29
-rw-r--r--hicn-light/src/hicn/config/controlRemoveConnection.c122
-rw-r--r--hicn-light/src/hicn/config/controlRemoveConnection.h31
-rw-r--r--hicn-light/src/hicn/config/controlRemoveListener.c123
-rw-r--r--hicn-light/src/hicn/config/controlRemoveListener.h31
-rw-r--r--hicn-light/src/hicn/config/controlRemovePolicy.c147
-rw-r--r--hicn-light/src/hicn/config/controlRemovePunting.c83
-rw-r--r--hicn-light/src/hicn/config/controlRemoveRoute.c154
-rw-r--r--hicn-light/src/hicn/config/controlRemoveRoute.h31
-rw-r--r--hicn-light/src/hicn/config/controlRoot.c173
-rw-r--r--hicn-light/src/hicn/config/controlRoot.h31
-rw-r--r--hicn-light/src/hicn/config/controlSet.c98
-rw-r--r--hicn-light/src/hicn/config/controlSet.h29
-rw-r--r--hicn-light/src/hicn/config/controlSetDebug.c81
-rw-r--r--hicn-light/src/hicn/config/controlSetDebug.h30
-rw-r--r--hicn-light/src/hicn/config/controlSetStrategy.c264
-rw-r--r--hicn-light/src/hicn/config/controlSetStrategy.h22
-rw-r--r--hicn-light/src/hicn/config/controlSetWldr.c131
-rw-r--r--hicn-light/src/hicn/config/controlSetWldr.h22
-rw-r--r--hicn-light/src/hicn/config/controlState.c243
-rw-r--r--hicn-light/src/hicn/config/controlState.h242
-rw-r--r--hicn-light/src/hicn/config/controlUnset.c85
-rw-r--r--hicn-light/src/hicn/config/controlUnset.h29
-rw-r--r--hicn-light/src/hicn/config/controlUnsetDebug.c83
-rw-r--r--hicn-light/src/hicn/config/controlUnsetDebug.h30
-rw-r--r--hicn-light/src/hicn/config/controlUpdate.c105
-rw-r--r--hicn-light/src/hicn/config/controlUpdateConnection.c154
-rw-r--r--hicn-light/src/hicn/config/symbolicNameTable.c191
-rw-r--r--hicn-light/src/hicn/config/symbolicNameTable.h131
-rw-r--r--hicn-light/src/hicn/content_store/CMakeLists.txt16
-rw-r--r--hicn-light/src/hicn/content_store/contentStoreEntry.c136
-rw-r--r--hicn-light/src/hicn/content_store/contentStoreEntry.h146
-rw-r--r--hicn-light/src/hicn/content_store/contentStoreInterface.c57
-rw-r--r--hicn-light/src/hicn/content_store/contentStoreInterface.h211
-rw-r--r--hicn-light/src/hicn/content_store/contentStoreLRU.c462
-rw-r--r--hicn-light/src/hicn/content_store/contentStoreLRU.h39
-rw-r--r--hicn-light/src/hicn/content_store/listLRU.c135
-rw-r--r--hicn-light/src/hicn/content_store/listLRU.h94
-rw-r--r--hicn-light/src/hicn/content_store/listTimeOrdered.c94
-rw-r--r--hicn-light/src/hicn/content_store/listTimeOrdered.h103
-rw-r--r--hicn-light/src/hicn/content_store/lru.c167
-rw-r--r--hicn-light/src/hicn/content_store/lru.h56
-rw-r--r--hicn-light/src/hicn/core/CMakeLists.txt76
-rw-r--r--hicn-light/src/hicn/core/address.c66
-rw-r--r--hicn-light/src/hicn/core/address.h141
-rw-r--r--hicn-light/src/hicn/core/address_pair.c43
-rw-r--r--hicn-light/src/hicn/core/address_pair.h66
-rw-r--r--hicn-light/src/hicn/core/connection.c573
-rw-r--r--hicn-light/src/hicn/core/connection.h328
-rw-r--r--hicn-light/src/hicn/core/connectionList.c68
-rw-r--r--hicn-light/src/hicn/core/connectionList.h70
-rw-r--r--hicn-light/src/hicn/core/connectionManager.c196
-rw-r--r--hicn-light/src/hicn/core/connectionManager.h37
-rw-r--r--hicn-light/src/hicn/core/connectionTable.c226
-rw-r--r--hicn-light/src/hicn/core/connectionTable.h99
-rw-r--r--hicn-light/src/hicn/core/connection_table.c240
-rw-r--r--hicn-light/src/hicn/core/connection_table.h257
-rw-r--r--hicn-light/src/hicn/core/connection_vft.c (renamed from libtransport/includes/hicn/transport/utils/move_wrapper.h)33
-rw-r--r--hicn-light/src/hicn/core/connection_vft.h54
-rw-r--r--hicn-light/src/hicn/core/content_store.c88
-rw-r--r--hicn-light/src/hicn/core/content_store.h108
-rw-r--r--hicn-light/src/hicn/core/dispatcher.c474
-rw-r--r--hicn-light/src/hicn/core/dispatcher.h288
-rw-r--r--hicn-light/src/hicn/core/fib.c743
-rw-r--r--hicn-light/src/hicn/core/fib.h86
-rw-r--r--hicn-light/src/hicn/core/fib_entry.c667
-rw-r--r--hicn-light/src/hicn/core/fib_entry.h208
-rw-r--r--hicn-light/src/hicn/core/forwarder.c1837
-rw-r--r--hicn-light/src/hicn/core/forwarder.h337
-rw-r--r--hicn-light/src/hicn/core/listener.c425
-rw-r--r--hicn-light/src/hicn/core/listener.h140
-rw-r--r--hicn-light/src/hicn/core/listener_table.c206
-rw-r--r--hicn-light/src/hicn/core/listener_table.h270
-rw-r--r--hicn-light/src/hicn/core/listener_vft.c (renamed from hicn-light/src/hicn/config/controlAddPolicy.h)31
-rw-r--r--hicn-light/src/hicn/core/listener_vft.h58
-rw-r--r--hicn-light/src/hicn/core/logger.c177
-rw-r--r--hicn-light/src/hicn/core/logger.h170
-rw-r--r--hicn-light/src/hicn/core/mapme.c1647
-rw-r--r--hicn-light/src/hicn/core/mapme.h107
-rw-r--r--hicn-light/src/hicn/core/message.c299
-rw-r--r--hicn-light/src/hicn/core/message.h180
-rw-r--r--hicn-light/src/hicn/core/messageHandler.h758
-rw-r--r--hicn-light/src/hicn/core/messagePacketType.h32
-rw-r--r--hicn-light/src/hicn/core/msgbuf.c55
-rw-r--r--hicn-light/src/hicn/core/msgbuf.h205
-rw-r--r--hicn-light/src/hicn/core/msgbuf_pool.c123
-rw-r--r--hicn-light/src/hicn/core/msgbuf_pool.h157
-rw-r--r--hicn-light/src/hicn/core/name.c264
-rw-r--r--hicn-light/src/hicn/core/name.h104
-rw-r--r--hicn-light/src/hicn/core/nameBitvector.c364
-rw-r--r--hicn-light/src/hicn/core/nameBitvector.h58
-rw-r--r--hicn-light/src/hicn/core/nexthops.c155
-rw-r--r--hicn-light/src/hicn/core/nexthops.h182
-rw-r--r--hicn-light/src/hicn/core/numberSet.c203
-rw-r--r--hicn-light/src/hicn/core/numberSet.h157
-rw-r--r--hicn-light/src/hicn/core/packet_cache.c884
-rw-r--r--hicn-light/src/hicn/core/packet_cache.h502
-rw-r--r--hicn-light/src/hicn/core/pit.c74
-rw-r--r--hicn-light/src/hicn/core/pit.h73
-rw-r--r--hicn-light/src/hicn/core/policy_stats.c202
-rw-r--r--hicn-light/src/hicn/core/policy_stats.h92
-rw-r--r--hicn-light/src/hicn/core/strategy.c60
-rw-r--r--hicn-light/src/hicn/core/strategy.h81
-rw-r--r--hicn-light/src/hicn/core/strategy_vft.c39
-rw-r--r--hicn-light/src/hicn/core/strategy_vft.h124
-rw-r--r--hicn-light/src/hicn/core/streamBuffer.c2
-rw-r--r--hicn-light/src/hicn/core/streamBuffer.h2
-rw-r--r--hicn-light/src/hicn/core/subscription.c118
-rw-r--r--hicn-light/src/hicn/core/subscription.h81
-rw-r--r--hicn-light/src/hicn/core/system.h9
-rw-r--r--hicn-light/src/hicn/core/ticks.h37
-rw-r--r--hicn-light/src/hicn/core/wldr.c109
-rw-r--r--hicn-light/src/hicn/core/wldr.h22
-rw-r--r--hicn-light/src/hicn/io/CMakeLists.txt44
-rw-r--r--hicn-light/src/hicn/io/addressPair.c129
-rw-r--r--hicn-light/src/hicn/io/addressPair.h128
-rw-r--r--hicn-light/src/hicn/io/base.c131
-rw-r--r--hicn-light/src/hicn/io/base.h37
-rw-r--r--hicn-light/src/hicn/io/hicn.c448
-rw-r--r--hicn-light/src/hicn/io/hicnConnection.c541
-rw-r--r--hicn-light/src/hicn/io/hicnConnection.h53
-rw-r--r--hicn-light/src/hicn/io/hicnListener.c673
-rw-r--r--hicn-light/src/hicn/io/hicnListener.h42
-rw-r--r--hicn-light/src/hicn/io/hicnTunnel.c106
-rw-r--r--hicn-light/src/hicn/io/hicnTunnel.h65
-rw-r--r--hicn-light/src/hicn/io/ioOperations.c100
-rw-r--r--hicn-light/src/hicn/io/ioOperations.h449
-rw-r--r--hicn-light/src/hicn/io/listener.h128
-rw-r--r--hicn-light/src/hicn/io/listenerSet.c182
-rw-r--r--hicn-light/src/hicn/io/listenerSet.h188
-rw-r--r--hicn-light/src/hicn/io/streamConnection.c773
-rw-r--r--hicn-light/src/hicn/io/streamConnection.h76
-rw-r--r--hicn-light/src/hicn/io/tcp.c532
-rw-r--r--hicn-light/src/hicn/io/tcpListener.c262
-rw-r--r--hicn-light/src/hicn/io/tcpListener.h40
-rw-r--r--hicn-light/src/hicn/io/tcpTunnel.c43
-rw-r--r--hicn-light/src/hicn/io/tcpTunnel.h42
-rw-r--r--hicn-light/src/hicn/io/udp.c565
-rw-r--r--hicn-light/src/hicn/io/udpConnection.c495
-rw-r--r--hicn-light/src/hicn/io/udpConnection.h53
-rw-r--r--hicn-light/src/hicn/io/udpListener.c653
-rw-r--r--hicn-light/src/hicn/io/udpListener.h35
-rw-r--r--hicn-light/src/hicn/io/udpTunnel.c105
-rw-r--r--hicn-light/src/hicn/io/udpTunnel.h42
-rw-r--r--hicn-light/src/hicn/messenger/CMakeLists.txt30
-rw-r--r--hicn-light/src/hicn/messenger/messenger.c171
-rw-r--r--hicn-light/src/hicn/messenger/messenger.h69
-rw-r--r--hicn-light/src/hicn/messenger/messengerRecipient.c62
-rw-r--r--hicn-light/src/hicn/messenger/messengerRecipient.h104
-rw-r--r--hicn-light/src/hicn/messenger/missive.c54
-rw-r--r--hicn-light/src/hicn/messenger/missive.h89
-rw-r--r--hicn-light/src/hicn/messenger/missiveDeque.c77
-rw-r--r--hicn-light/src/hicn/messenger/missiveDeque.h55
-rw-r--r--hicn-light/src/hicn/messenger/missiveType.h55
-rw-r--r--hicn-light/src/hicn/platforms/CMakeLists.txt2
-rw-r--r--hicn-light/src/hicn/platforms/README.txt3
-rw-r--r--hicn-light/src/hicn/platforms/android/system.c4
-rw-r--r--hicn-light/src/hicn/platforms/darwin/system.c6
-rw-r--r--hicn-light/src/hicn/platforms/linux/system.c67
-rw-r--r--hicn-light/src/hicn/platforms/windows/system.c446
-rw-r--r--hicn-light/src/hicn/platforms/windows/win_portability.c102
-rw-r--r--hicn-light/src/hicn/platforms/windows/win_portability.h88
-rw-r--r--hicn-light/src/hicn/processor/CMakeLists.txt38
-rw-r--r--hicn-light/src/hicn/processor/fib.c553
-rw-r--r--hicn-light/src/hicn/processor/fib.h45
-rw-r--r--hicn-light/src/hicn/processor/fibEntry.c894
-rw-r--r--hicn-light/src/hicn/processor/fibEntry.h166
-rw-r--r--hicn-light/src/hicn/processor/fibEntryList.c72
-rw-r--r--hicn-light/src/hicn/processor/fibEntryList.h96
-rw-r--r--hicn-light/src/hicn/processor/hashTableFunction.c47
-rw-r--r--hicn-light/src/hicn/processor/hashTableFunction.h73
-rw-r--r--hicn-light/src/hicn/processor/matchingRulesTable.c132
-rw-r--r--hicn-light/src/hicn/processor/matchingRulesTable.h113
-rw-r--r--hicn-light/src/hicn/processor/messageProcessor.c909
-rw-r--r--hicn-light/src/hicn/processor/messageProcessor.h206
-rw-r--r--hicn-light/src/hicn/processor/pit.c45
-rw-r--r--hicn-light/src/hicn/processor/pit.h114
-rw-r--r--hicn-light/src/hicn/processor/pitEntry.c142
-rw-r--r--hicn-light/src/hicn/processor/pitEntry.h164
-rw-r--r--hicn-light/src/hicn/processor/pitStandard.c305
-rw-r--r--hicn-light/src/hicn/processor/pitVerdict.h40
-rw-r--r--hicn-light/src/hicn/socket/CMakeLists.txt8
-rw-r--r--hicn-light/src/hicn/socket/api.c81
-rw-r--r--hicn-light/src/hicn/socket/api.h9
-rw-r--r--hicn-light/src/hicn/socket/ops.h18
-rw-r--r--hicn-light/src/hicn/socket/ops_linux.c131
-rw-r--r--hicn-light/src/hicn/strategies/CMakeLists.txt27
-rw-r--r--hicn-light/src/hicn/strategies/best_path.c353
-rw-r--r--hicn-light/src/hicn/strategies/best_path.h57
-rw-r--r--hicn-light/src/hicn/strategies/loadBalancer.c369
-rw-r--r--hicn-light/src/hicn/strategies/load_balancer.c148
-rw-r--r--hicn-light/src/hicn/strategies/load_balancer.h (renamed from hicn-light/src/hicn/config/controlUpdate.h)30
-rw-r--r--hicn-light/src/hicn/strategies/local_prefixes.c82
-rw-r--r--hicn-light/src/hicn/strategies/local_prefixes.h46
-rw-r--r--hicn-light/src/hicn/strategies/local_remote.c105
-rw-r--r--hicn-light/src/hicn/strategies/local_remote.h40
-rw-r--r--hicn-light/src/hicn/strategies/lowLatency.c851
-rw-r--r--hicn-light/src/hicn/strategies/lowLatency.h33
-rw-r--r--hicn-light/src/hicn/strategies/nexthopState.c212
-rw-r--r--hicn-light/src/hicn/strategies/nexthopState.h94
-rw-r--r--hicn-light/src/hicn/strategies/nexthopStateLowLatency.c386
-rw-r--r--hicn-light/src/hicn/strategies/nexthopStateLowLatency.h16
-rw-r--r--hicn-light/src/hicn/strategies/probe_generator.c113
-rw-r--r--hicn-light/src/hicn/strategies/probe_generator.h49
-rw-r--r--hicn-light/src/hicn/strategies/random.c77
-rw-r--r--hicn-light/src/hicn/strategies/random.h35
-rw-r--r--hicn-light/src/hicn/strategies/replication.c98
-rw-r--r--hicn-light/src/hicn/strategies/replication.h37
-rw-r--r--hicn-light/src/hicn/strategies/rnd.c211
-rw-r--r--hicn-light/src/hicn/strategies/strategyImpl.h73
-rw-r--r--hicn-light/src/hicn/test/CMakeLists.txt40
-rw-r--r--hicn-light/src/hicn/test/main.cc21
-rw-r--r--hicn-light/src/hicn/test/test-configuration.cc83
-rw-r--r--hicn-light/src/hicn/test/test-connection_table.cc301
-rw-r--r--hicn-light/src/hicn/test/test-ctrl.cc197
-rw-r--r--hicn-light/src/hicn/test/test-fib.cc338
-rw-r--r--hicn-light/src/hicn/test/test-listener_table.cc244
-rw-r--r--hicn-light/src/hicn/test/test-local_prefixes.cc252
-rw-r--r--hicn-light/src/hicn/test/test-loop.cc294
-rw-r--r--hicn-light/src/hicn/test/test-msgbuf_pool.cc191
-rw-r--r--hicn-light/src/hicn/test/test-nexthops.cc274
-rw-r--r--hicn-light/src/hicn/test/test-packet_cache.cc703
-rw-r--r--hicn-light/src/hicn/test/test-parser.cc71
-rw-r--r--hicn-light/src/hicn/test/test-probe_generator.cc154
-rw-r--r--hicn-light/src/hicn/test/test-strategy-best-path.cc107
-rw-r--r--hicn-light/src/hicn/test/test-strategy-load-balancing.cc152
-rw-r--r--hicn-light/src/hicn/test/test-strategy-local-remote.cc233
-rw-r--r--hicn-light/src/hicn/test/test-strategy-random.cc150
-rw-r--r--hicn-light/src/hicn/test/test-strategy-replication.cc162
-rw-r--r--hicn-light/src/hicn/test/test-subscription.cc204
-rw-r--r--hicn-light/src/hicn/test/test-utils.h26
-rw-r--r--hicn-light/src/hicn/test/test_hash.cc216
-rw-r--r--hicn-light/src/hicn/utils/CMakeLists.txt25
-rw-r--r--hicn-light/src/hicn/utils/address.c450
-rw-r--r--hicn-light/src/hicn/utils/address.h524
-rw-r--r--hicn-light/src/hicn/utils/addressList.c133
-rw-r--r--hicn-light/src/hicn/utils/addressList.h196
-rw-r--r--hicn-light/src/hicn/utils/commands.h434
-rw-r--r--hicn-light/src/hicn/utils/interface.c8
-rw-r--r--hicn-light/src/hicn/utils/interface.h9
-rw-r--r--hicn-light/src/hicn/utils/interfaceSet.c2
-rw-r--r--hicn-light/src/hicn/utils/interfaceSet.h2
-rw-r--r--hicn-light/src/hicn/utils/punting.c10
-rw-r--r--hicn-light/src/hicn/utils/punting.h21
-rw-r--r--hicn-light/src/hicn/utils/token.h4
-rw-r--r--hicn-light/src/hicn/utils/utils.c235
-rw-r--r--hicn-light/src/hicn/utils/utils.h70
-rw-r--r--hicn-plugin/.clang-format1
-rw-r--r--hicn-plugin/CMakeLists.txt53
-rw-r--r--hicn-plugin/cmake/Modules/Packaging.cmake56
-rw-r--r--hicn-plugin/cmake/packaging.cmake64
-rw-r--r--hicn-plugin/includes/vpp_plugins/hicn/CMakeLists.txt30
-rw-r--r--hicn-plugin/includes/vpp_plugins/hicn/error.h151
-rw-r--r--hicn-plugin/includes/vpp_plugins/hicn/hicn_all_api_h.h (renamed from hicn-plugin/src/hicn_all_api_h.h)4
-rw-r--r--hicn-plugin/includes/vpp_plugins/hicn/hicn_api.h (renamed from hicn-plugin/src/hicn_api.h)7
-rw-r--r--hicn-plugin/includes/vpp_plugins/hicn/hicn_enums.h (renamed from libtransport/src/protocols/fec_base.cc)12
-rw-r--r--hicn-plugin/includes/vpp_plugins/hicn/hicn_msg_enum.h (renamed from hicn-plugin/src/hicn_msg_enum.h)4
-rw-r--r--hicn-plugin/libvapi-safe/CMakeLists.txt128
-rw-r--r--hicn-plugin/libvapi-safe/includes/vapi/vapi_safe.h (renamed from hicn-light/src/hicn/config/controlAddPunting.h)23
-rw-r--r--hicn-plugin/libvapi-safe/libsafevapi-config.cmake.in8
-rw-r--r--hicn-plugin/libvapi-safe/src/vapi_safe.cc420
-rw-r--r--hicn-plugin/scripts/post20
-rw-r--r--hicn-plugin/scripts/postinst19
-rw-r--r--hicn-plugin/scripts/postun5
-rw-r--r--hicn-plugin/src/CMakeLists.txt460
-rw-r--r--hicn-plugin/src/cache_policies/cs_lru.c206
-rw-r--r--hicn-plugin/src/cache_policies/cs_lru.h42
-rw-r--r--hicn-plugin/src/cache_policies/cs_policy.h186
-rw-r--r--hicn-plugin/src/cli.c258
-rw-r--r--hicn-plugin/src/data_fwd.h12
-rw-r--r--hicn-plugin/src/data_fwd_node.c572
-rw-r--r--hicn-plugin/src/data_input_node.c248
-rw-r--r--hicn-plugin/src/data_pcslookup.h2
-rw-r--r--hicn-plugin/src/data_pcslookup_node.c92
-rw-r--r--hicn-plugin/src/error.c4
-rw-r--r--hicn-plugin/src/error.h108
-rw-r--r--hicn-plugin/src/face_db.h152
-rw-r--r--hicn-plugin/src/faces/app/address_mgr.c7
-rw-r--r--hicn-plugin/src/faces/app/address_mgr.h2
-rw-r--r--hicn-plugin/src/faces/app/face_app_cli.c13
-rw-r--r--hicn-plugin/src/faces/app/face_cons.c10
-rw-r--r--hicn-plugin/src/faces/app/face_cons.h2
-rw-r--r--hicn-plugin/src/faces/app/face_prod.c83
-rw-r--r--hicn-plugin/src/faces/app/face_prod.h8
-rw-r--r--hicn-plugin/src/faces/app/face_prod_node.c155
-rw-r--r--hicn-plugin/src/faces/face.c131
-rw-r--r--hicn-plugin/src/faces/face.h395
-rw-r--r--hicn-plugin/src/faces/face_cli.c14
-rw-r--r--hicn-plugin/src/faces/face_flags.h40
-rw-r--r--hicn-plugin/src/faces/face_node.c387
-rw-r--r--hicn-plugin/src/faces/face_node.h2
-rw-r--r--hicn-plugin/src/faces/iface_node.c405
-rw-r--r--hicn-plugin/src/faces/iface_node.h22
-rw-r--r--hicn-plugin/src/faces/inlines.h23
-rw-r--r--hicn-plugin/src/hashtb.c1006
-rw-r--r--hicn-plugin/src/hashtb.h536
-rw-r--r--hicn-plugin/src/hicn.api97
-rw-r--r--hicn-plugin/src/hicn.c48
-rw-r--r--hicn-plugin/src/hicn.h118
-rw-r--r--hicn-plugin/src/hicn_api.c106
-rw-r--r--hicn-plugin/src/hicn_api_test.c400
-rw-r--r--hicn-plugin/src/hicn_buffer_flags.h35
-rw-r--r--hicn-plugin/src/hicn_logging.h32
-rw-r--r--hicn-plugin/src/infra.c (renamed from hicn-light/src/hicn/strategies/rnd.h)18
-rw-r--r--hicn-plugin/src/infra.h8
-rw-r--r--hicn-plugin/src/interest_hitcs.h2
-rw-r--r--hicn-plugin/src/interest_hitcs_node.c121
-rw-r--r--hicn-plugin/src/interest_hitpit.h6
-rw-r--r--hicn-plugin/src/interest_hitpit_node.c162
-rw-r--r--hicn-plugin/src/interest_pcslookup.h12
-rw-r--r--hicn-plugin/src/interest_pcslookup_node.c521
-rw-r--r--hicn-plugin/src/mapme.h162
-rw-r--r--hicn-plugin/src/mapme_ack.h6
-rw-r--r--hicn-plugin/src/mapme_ack_node.c52
-rw-r--r--hicn-plugin/src/mapme_ctrl.h9
-rw-r--r--hicn-plugin/src/mapme_ctrl_node.c408
-rw-r--r--hicn-plugin/src/mapme_eventmgr.c109
-rw-r--r--hicn-plugin/src/mapme_eventmgr.h5
-rw-r--r--hicn-plugin/src/mgmt.c7
-rw-r--r--hicn-plugin/src/mgmt.h4
-rw-r--r--hicn-plugin/src/params.h10
-rw-r--r--hicn-plugin/src/parser.h131
-rw-r--r--hicn-plugin/src/pcs.c46
-rw-r--r--hicn-plugin/src/pcs.h1166
-rw-r--r--hicn-plugin/src/pg.c1323
-rw-r--r--hicn-plugin/src/pg.h144
-rw-r--r--hicn-plugin/src/pg_node.c1121
-rw-r--r--hicn-plugin/src/route.c250
-rw-r--r--hicn-plugin/src/route.h33
-rw-r--r--hicn-plugin/src/state.h56
-rw-r--r--hicn-plugin/src/strategies/dpo_lr.c139
-rw-r--r--hicn-plugin/src/strategies/dpo_lr.h122
-rw-r--r--hicn-plugin/src/strategies/dpo_mw.c48
-rw-r--r--hicn-plugin/src/strategies/dpo_mw.h37
-rw-r--r--hicn-plugin/src/strategies/dpo_rp.c145
-rw-r--r--hicn-plugin/src/strategies/dpo_rp.h130
-rw-r--r--hicn-plugin/src/strategies/dpo_rr.c42
-rw-r--r--hicn-plugin/src/strategies/dpo_rr.h37
-rw-r--r--hicn-plugin/src/strategies/strategy_lr.c136
-rw-r--r--hicn-plugin/src/strategies/strategy_lr.h (renamed from hicn-light/src/hicn/processor/pitStandard.h)36
-rw-r--r--hicn-plugin/src/strategies/strategy_mw.c37
-rw-r--r--hicn-plugin/src/strategies/strategy_mw.h2
-rw-r--r--hicn-plugin/src/strategies/strategy_mw_cli.c4
-rw-r--r--hicn-plugin/src/strategies/strategy_rp.c124
-rw-r--r--hicn-plugin/src/strategies/strategy_rp.h41
-rw-r--r--hicn-plugin/src/strategies/strategy_rr.c36
-rw-r--r--hicn-plugin/src/strategies/strategy_rr.h2
-rw-r--r--hicn-plugin/src/strategy.h11
-rw-r--r--hicn-plugin/src/strategy_dpo_ctx.c45
-rw-r--r--hicn-plugin/src/strategy_dpo_ctx.h9
-rw-r--r--hicn-plugin/src/strategy_dpo_manager.c35
-rw-r--r--hicn-plugin/src/strategy_dpo_manager.h13
-rw-r--r--hicn-plugin/src/strategy_node.c266
-rw-r--r--hicn-plugin/src/test/CMakeLists.txt67
-rw-r--r--hicn-plugin/src/test/main.c (renamed from ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.h)22
-rw-r--r--hicn-plugin/src/test/test_pcs.c622
-rw-r--r--hicn-plugin/src/test/vpp.c570
-rw-r--r--hicn-plugin/src/test/vpp.h21
-rw-r--r--hicn-plugin/src/udp_tunnels/udp_decap.h2
-rw-r--r--hicn-plugin/src/udp_tunnels/udp_decap_node.c107
-rw-r--r--hicn-plugin/src/udp_tunnels/udp_tunnel.c40
-rw-r--r--hicn-plugin/src/udp_tunnels/udp_tunnel.h35
-rw-r--r--hicn-plugin/src/utils.h2
-rw-r--r--hicn-plugin/vapi/CMakeLists.txt61
-rw-r--r--hicn-plugin/vapi/include/vapi/vapi_safe.h19
-rw-r--r--hicn-plugin/vapi/vapi_safe.c73
-rw-r--r--internal/cmake/Modules/CheckSafeC.cmake (renamed from cmake/Modules/IosMacros.cmake)16
-rw-r--r--internal/cmake/Modules/CheckSsl.cmake (renamed from libtransport/cmake/Modules/Ios.cmake)15
-rw-r--r--internal/cmake/Modules/FindCiscoSafeC.cmake54
-rw-r--r--internal/cmake/Modules/ImportInternal.cmake (renamed from libtransport/cmake/Modules/Android.cmake)18
-rw-r--r--internal/cmake/Modules/SetRelyGitRepo.cmake20
-rw-r--r--lib/.clang-format10
-rw-r--r--lib/CMakeLists.txt49
-rw-r--r--lib/cmake/packaging.cmake (renamed from lib/cmake/Modules/Packaging.cmake)16
-rw-r--r--lib/includes/CMakeLists.txt38
-rw-r--r--lib/includes/hicn/base.h348
-rw-r--r--lib/includes/hicn/common.h263
-rw-r--r--lib/includes/hicn/compat.h469
-rw-r--r--lib/includes/hicn/error.h31
-rw-r--r--lib/includes/hicn/face.h245
-rw-r--r--lib/includes/hicn/header.h129
-rw-r--r--lib/includes/hicn/hicn.h41
-rw-r--r--lib/includes/hicn/interest_manifest.h220
-rw-r--r--lib/includes/hicn/mapme.h114
-rw-r--r--lib/includes/hicn/name.h246
-rw-r--r--lib/includes/hicn/ops.h871
-rw-r--r--lib/includes/hicn/packet.h668
-rw-r--r--lib/includes/hicn/policy.h263
-rw-r--r--lib/includes/hicn/protocol/ah.h16
-rw-r--r--lib/includes/hicn/protocol/icmp.h12
-rw-r--r--lib/includes/hicn/protocol/icmprd.h12
-rw-r--r--lib/includes/hicn/protocol/ipv4.h49
-rw-r--r--lib/includes/hicn/protocol/ipv6.h36
-rw-r--r--lib/includes/hicn/protocol/new.h88
-rw-r--r--lib/includes/hicn/protocol/tcp.h102
-rw-r--r--lib/includes/hicn/protocol/udp.h4
-rw-r--r--lib/includes/hicn/strategy.h64
-rw-r--r--lib/includes/hicn/util/array.h323
-rw-r--r--lib/includes/hicn/util/bitmap.h332
-rw-r--r--lib/includes/hicn/util/hash.h368
-rw-r--r--lib/includes/hicn/util/ip_address.h211
-rw-r--r--lib/includes/hicn/util/khash.h826
-rw-r--r--lib/includes/hicn/util/log.h77
-rw-r--r--lib/includes/hicn/util/map.h444
-rw-r--r--lib/includes/hicn/util/pool.h292
-rw-r--r--lib/includes/hicn/util/ring.h227
-rw-r--r--lib/includes/hicn/util/set.h370
-rw-r--r--lib/includes/hicn/util/slab.h126
-rw-r--r--lib/includes/hicn/util/sstrncpy.h76
-rw-r--r--lib/includes/hicn/util/token.h8
-rw-r--r--lib/includes/hicn/util/types.h56
-rw-r--r--lib/includes/hicn/util/vector.h470
-rw-r--r--lib/includes/hicn/util/win_portability.h88
-rw-r--r--lib/includes/hicn/util/windows/dlfcn.h15
-rw-r--r--[-rwxr-xr-x]lib/includes/hicn/util/windows/windows_utils.h326
-rw-r--r--lib/includes/hicn/validation.h55
-rw-r--r--lib/src/CMakeLists.txt145
-rw-r--r--lib/src/base.c51
-rw-r--r--lib/src/common.c79
-rw-r--r--lib/src/compat.c1273
-rw-r--r--lib/src/error.c4
-rw-r--r--lib/src/face.c455
-rw-r--r--lib/src/libhicn-config.cmake.in12
-rw-r--r--lib/src/mapme.c111
-rw-r--r--lib/src/name.c741
-rw-r--r--lib/src/ops.c50
-rw-r--r--lib/src/ops.h979
-rw-r--r--lib/src/packet.c806
-rw-r--r--lib/src/policy.c70
-rw-r--r--lib/src/protocol.h (renamed from lib/includes/hicn/protocol.h)15
-rw-r--r--lib/src/protocol/ah.c200
-rw-r--r--lib/src/protocol/ah.h83
-rw-r--r--lib/src/protocol/icmp.c175
-rw-r--r--lib/src/protocol/icmp.h84
-rw-r--r--lib/src/protocol/icmprd.h72
-rw-r--r--lib/src/protocol/ipv4.c441
-rw-r--r--lib/src/protocol/ipv4.h112
-rw-r--r--lib/src/protocol/ipv6.c398
-rw-r--r--lib/src/protocol/ipv6.h86
-rw-r--r--lib/src/protocol/new.c563
-rw-r--r--lib/src/protocol/new.h95
-rw-r--r--lib/src/protocol/tcp.c429
-rw-r--r--lib/src/protocol/tcp.h165
-rw-r--r--lib/src/protocol/udp.c308
-rw-r--r--lib/src/protocol/udp.h44
-rw-r--r--lib/src/strategy.c22
-rw-r--r--lib/src/test/CMakeLists.txt55
-rw-r--r--lib/src/test/main.cc23
-rw-r--r--lib/src/test/test_bitmap.cc261
-rw-r--r--lib/src/test/test_interest_manifest.cc224
-rw-r--r--lib/src/test/test_ip_address.cc73
-rw-r--r--lib/src/test/test_khash.cc179
-rw-r--r--lib/src/test/test_name.cc401
-rw-r--r--lib/src/test/test_new_header.cc346
-rw-r--r--lib/src/test/test_pool.cc209
-rw-r--r--lib/src/test/test_ring.cc104
-rw-r--r--lib/src/test/test_slab.cc148
-rw-r--r--lib/src/test/test_udp_header.cc360
-rw-r--r--lib/src/test/test_validation.cc55
-rw-r--r--lib/src/test/test_vector.cc254
-rw-r--r--lib/src/util/ip_address.c373
-rw-r--r--lib/src/util/log.c247
-rw-r--r--lib/src/util/pool.c175
-rw-r--r--lib/src/util/ring.c (renamed from hicn-light/src/hicn/config/controlListRoutes.h)44
-rw-r--r--lib/src/util/slab.c203
-rw-r--r--lib/src/util/types.c56
-rw-r--r--lib/src/util/vector.c101
-rw-r--r--lib/src/util/windows/dlfcn.c84
-rw-r--r--libtransport/.clang-format2
-rw-r--r--libtransport/CMakeLists.txt96
-rw-r--r--libtransport/cmake/Modules/DefaultConfiguration.cmake30
-rw-r--r--libtransport/cmake/packaging.cmake (renamed from libtransport/cmake/Modules/Packaging.cmake)29
-rw-r--r--libtransport/includes/hicn/transport/CMakeLists.txt19
-rw-r--r--libtransport/includes/hicn/transport/auth/CMakeLists.txt3
-rw-r--r--libtransport/includes/hicn/transport/auth/common.h2
-rw-r--r--libtransport/includes/hicn/transport/auth/crypto_hash.h18
-rw-r--r--libtransport/includes/hicn/transport/auth/crypto_suite.h25
-rw-r--r--libtransport/includes/hicn/transport/auth/identity.h77
-rw-r--r--libtransport/includes/hicn/transport/auth/key_id.h2
-rw-r--r--libtransport/includes/hicn/transport/auth/policies.h4
-rw-r--r--libtransport/includes/hicn/transport/auth/signer.h28
-rw-r--r--libtransport/includes/hicn/transport/auth/verifier.h58
-rw-r--r--libtransport/includes/hicn/transport/core/CMakeLists.txt2
-rw-r--r--libtransport/includes/hicn/transport/core/asio_wrapper.h3
-rw-r--r--libtransport/includes/hicn/transport/core/connector.h88
-rw-r--r--libtransport/includes/hicn/transport/core/content_object.h40
-rw-r--r--libtransport/includes/hicn/transport/core/endpoint.h18
-rw-r--r--libtransport/includes/hicn/transport/core/global_object_pool.h14
-rw-r--r--libtransport/includes/hicn/transport/core/interest.h51
-rw-r--r--libtransport/includes/hicn/transport/core/io_module.h27
-rw-r--r--libtransport/includes/hicn/transport/core/name.h22
-rw-r--r--libtransport/includes/hicn/transport/core/packet.h248
-rw-r--r--libtransport/includes/hicn/transport/core/payload_type.h13
-rw-r--r--libtransport/includes/hicn/transport/core/prefix.h38
-rw-r--r--libtransport/includes/hicn/transport/errors/CMakeLists.txt2
-rw-r--r--libtransport/includes/hicn/transport/errors/errors.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/indexing_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/malformed_name_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/malformed_packet_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/not_implemented_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/null_pointer_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/runtime_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/tokenizer_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h2
-rw-r--r--libtransport/includes/hicn/transport/http/CMakeLists.txt2
-rw-r--r--libtransport/includes/hicn/transport/http/client_connection.h6
-rw-r--r--libtransport/includes/hicn/transport/http/default_values.h2
-rw-r--r--libtransport/includes/hicn/transport/http/facade.h2
-rw-r--r--libtransport/includes/hicn/transport/http/message.h2
-rw-r--r--libtransport/includes/hicn/transport/http/request.h2
-rw-r--r--libtransport/includes/hicn/transport/http/response.h2
-rw-r--r--libtransport/includes/hicn/transport/interfaces/CMakeLists.txt10
-rw-r--r--libtransport/includes/hicn/transport/interfaces/callbacks.h9
-rw-r--r--libtransport/includes/hicn/transport/interfaces/global_conf_interface.h16
-rw-r--r--libtransport/includes/hicn/transport/interfaces/notification.h (renamed from libtransport/src/interfaces/tls_socket_consumer.h)23
-rw-r--r--libtransport/includes/hicn/transport/interfaces/p2psecure_socket_consumer.h32
-rw-r--r--libtransport/includes/hicn/transport/interfaces/p2psecure_socket_producer.h35
-rw-r--r--libtransport/includes/hicn/transport/interfaces/portal.h108
-rw-r--r--libtransport/includes/hicn/transport/interfaces/publication_options.h4
-rw-r--r--libtransport/includes/hicn/transport/interfaces/socket_consumer.h33
-rw-r--r--libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h60
-rw-r--r--libtransport/includes/hicn/transport/interfaces/socket_options_keys.h74
-rw-r--r--libtransport/includes/hicn/transport/interfaces/socket_producer.h44
-rw-r--r--libtransport/includes/hicn/transport/interfaces/statistics.h62
-rw-r--r--libtransport/includes/hicn/transport/portability/CMakeLists.txt5
-rw-r--r--libtransport/includes/hicn/transport/portability/c_portability.h2
-rw-r--r--libtransport/includes/hicn/transport/portability/cache.h87
-rw-r--r--libtransport/includes/hicn/transport/portability/cpu.h40
-rw-r--r--libtransport/includes/hicn/transport/portability/endianess.h86
-rw-r--r--libtransport/includes/hicn/transport/portability/portability.h7
-rw-r--r--libtransport/includes/hicn/transport/portability/win_portability.h86
-rw-r--r--libtransport/includes/hicn/transport/utils/CMakeLists.txt5
-rw-r--r--libtransport/includes/hicn/transport/utils/array.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/branch_prediction.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/chrono_typedefs.h101
-rw-r--r--libtransport/includes/hicn/transport/utils/color.h95
-rw-r--r--libtransport/includes/hicn/transport/utils/conversions.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/daemonizator.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/event_thread.h47
-rw-r--r--libtransport/includes/hicn/transport/utils/fixed_block_allocator.h57
-rw-r--r--libtransport/includes/hicn/transport/utils/hash.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/linux.h4
-rw-r--r--libtransport/includes/hicn/transport/utils/literals.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/log.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/membuf.h1
-rw-r--r--libtransport/includes/hicn/transport/utils/noncopyable.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/object_pool.h21
-rw-r--r--libtransport/includes/hicn/transport/utils/ring_buffer.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/rtc_quality_score.h69
-rw-r--r--libtransport/includes/hicn/transport/utils/singleton.h15
-rw-r--r--libtransport/includes/hicn/transport/utils/spinlock.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/string_tokenizer.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/string_utils.h2
-rw-r--r--libtransport/includes/hicn/transport/utils/thread_pool.h42
-rw-r--r--libtransport/includes/hicn/transport/utils/traffic_generator.h72
-rw-r--r--libtransport/includes/hicn/transport/utils/uri.h2
-rw-r--r--libtransport/src/CMakeLists.txt166
-rw-r--r--libtransport/src/auth/CMakeLists.txt3
-rw-r--r--libtransport/src/auth/crypto_hash.cc150
-rw-r--r--libtransport/src/auth/crypto_suite.cc84
-rw-r--r--libtransport/src/auth/identity.cc288
-rw-r--r--libtransport/src/auth/signer.cc243
-rw-r--r--libtransport/src/auth/verifier.cc284
-rw-r--r--libtransport/src/config.h.in5
-rw-r--r--libtransport/src/core/CMakeLists.txt26
-rw-r--r--libtransport/src/core/constructor.cc36
-rw-r--r--libtransport/src/core/content_object.cc87
-rw-r--r--libtransport/src/core/errors.cc11
-rw-r--r--libtransport/src/core/errors.h7
-rw-r--r--libtransport/src/core/facade.h8
-rw-r--r--libtransport/src/core/global_configuration.cc1
-rw-r--r--libtransport/src/core/global_id_counter.h (renamed from libtransport/src/io_modules/forwarder/global_id_counter.h)0
-rw-r--r--libtransport/src/core/global_module_manager.h94
-rw-r--r--libtransport/src/core/global_workers.h45
-rw-r--r--libtransport/src/core/interest.cc143
-rw-r--r--libtransport/src/core/io_module.cc52
-rw-r--r--libtransport/src/core/local_connector.cc46
-rw-r--r--libtransport/src/core/local_connector.h50
-rw-r--r--libtransport/src/core/manifest.cc33
-rw-r--r--libtransport/src/core/manifest.h151
-rw-r--r--libtransport/src/core/manifest_format.h168
-rw-r--r--libtransport/src/core/manifest_format_fixed.cc370
-rw-r--r--libtransport/src/core/manifest_format_fixed.h250
-rw-r--r--libtransport/src/core/manifest_inline.h142
-rw-r--r--libtransport/src/core/memif_connector.cc503
-rw-r--r--libtransport/src/core/memif_connector.h (renamed from libtransport/src/io_modules/memif/memif_connector.h)72
-rw-r--r--libtransport/src/core/name.cc86
-rw-r--r--libtransport/src/core/packet.cc679
-rw-r--r--libtransport/src/core/pending_interest.cc74
-rw-r--r--libtransport/src/core/pending_interest.h72
-rw-r--r--libtransport/src/core/portal.cc14
-rw-r--r--libtransport/src/core/portal.h646
-rw-r--r--libtransport/src/core/prefix.cc305
-rw-r--r--libtransport/src/core/tcp_socket_connector.cc16
-rw-r--r--libtransport/src/core/tcp_socket_connector.h2
-rw-r--r--libtransport/src/core/udp_connector.cc371
-rw-r--r--libtransport/src/core/udp_connector.h (renamed from libtransport/src/io_modules/forwarder/udp_tunnel.h)41
-rw-r--r--libtransport/src/core/udp_listener.cc (renamed from libtransport/src/io_modules/forwarder/udp_tunnel_listener.cc)29
-rw-r--r--libtransport/src/core/udp_listener.h (renamed from libtransport/src/io_modules/forwarder/udp_tunnel_listener.h)14
-rw-r--r--libtransport/src/http/CMakeLists.txt2
-rw-r--r--libtransport/src/http/client_connection.cc26
-rw-r--r--libtransport/src/http/request.cc2
-rw-r--r--libtransport/src/http/response.cc2
-rw-r--r--libtransport/src/implementation/CMakeLists.txt15
-rw-r--r--libtransport/src/implementation/p2psecure_socket_consumer.cc400
-rw-r--r--libtransport/src/implementation/p2psecure_socket_consumer.h136
-rw-r--r--libtransport/src/implementation/p2psecure_socket_producer.cc376
-rw-r--r--libtransport/src/implementation/p2psecure_socket_producer.h119
-rw-r--r--libtransport/src/implementation/socket.cc20
-rw-r--r--libtransport/src/implementation/socket.h29
-rw-r--r--libtransport/src/implementation/socket_consumer.h232
-rw-r--r--libtransport/src/implementation/socket_producer.h246
-rw-r--r--libtransport/src/implementation/tls_rtc_socket_producer.cc208
-rw-r--r--libtransport/src/implementation/tls_rtc_socket_producer.h57
-rw-r--r--libtransport/src/implementation/tls_socket_consumer.cc368
-rw-r--r--libtransport/src/implementation/tls_socket_consumer.h113
-rw-r--r--libtransport/src/implementation/tls_socket_producer.cc551
-rw-r--r--libtransport/src/implementation/tls_socket_producer.h154
-rw-r--r--libtransport/src/interfaces/CMakeLists.txt18
-rw-r--r--libtransport/src/interfaces/callbacks.cc2
-rw-r--r--libtransport/src/interfaces/global_configuration.cc22
-rw-r--r--libtransport/src/interfaces/p2psecure_socket_consumer.cc37
-rw-r--r--libtransport/src/interfaces/p2psecure_socket_producer.cc33
-rw-r--r--libtransport/src/interfaces/portal.cc117
-rw-r--r--libtransport/src/interfaces/socket_consumer.cc44
-rw-r--r--libtransport/src/interfaces/socket_producer.cc46
-rw-r--r--libtransport/src/interfaces/tls_rtc_socket_producer.cc31
-rw-r--r--libtransport/src/interfaces/tls_rtc_socket_producer.h36
-rw-r--r--libtransport/src/interfaces/tls_socket_consumer.cc30
-rw-r--r--libtransport/src/interfaces/tls_socket_producer.cc30
-rw-r--r--libtransport/src/interfaces/tls_socket_producer.h36
-rw-r--r--libtransport/src/io_modules/CMakeLists.txt61
-rw-r--r--libtransport/src/io_modules/forwarder/CMakeLists.txt12
-rw-r--r--libtransport/src/io_modules/forwarder/errors.cc2
-rw-r--r--libtransport/src/io_modules/forwarder/forwarder.cc68
-rw-r--r--libtransport/src/io_modules/forwarder/forwarder.h32
-rw-r--r--libtransport/src/io_modules/forwarder/forwarder_module.cc24
-rw-r--r--libtransport/src/io_modules/forwarder/forwarder_module.h10
-rw-r--r--libtransport/src/io_modules/forwarder/udp_tunnel.cc290
-rw-r--r--libtransport/src/io_modules/hicn-light/CMakeLists.txt63
-rw-r--r--libtransport/src/io_modules/hicn-light/hicn_forwarder_module.cc282
-rw-r--r--libtransport/src/io_modules/hicn-light/hicn_forwarder_module.h150
-rw-r--r--libtransport/src/io_modules/loopback/local_face.cc68
-rw-r--r--libtransport/src/io_modules/loopback/local_face.h53
-rw-r--r--libtransport/src/io_modules/loopback/loopback_module.cc84
-rw-r--r--libtransport/src/io_modules/loopback/loopback_module.h70
-rw-r--r--libtransport/src/io_modules/memif/CMakeLists.txt38
-rw-r--r--libtransport/src/io_modules/memif/hicn_vapi.c49
-rw-r--r--libtransport/src/io_modules/memif/hicn_vapi.h14
-rw-r--r--libtransport/src/io_modules/memif/memif_connector.cc492
-rw-r--r--libtransport/src/io_modules/memif/memif_vapi.c7
-rw-r--r--libtransport/src/io_modules/memif/memif_vapi.h6
-rw-r--r--libtransport/src/io_modules/memif/vpp_forwarder_module.cc50
-rw-r--r--libtransport/src/io_modules/memif/vpp_forwarder_module.h13
-rw-r--r--libtransport/src/io_modules/raw_socket/raw_socket_connector.cc200
-rw-r--r--libtransport/src/io_modules/raw_socket/raw_socket_connector.h79
-rw-r--r--libtransport/src/io_modules/raw_socket/raw_socket_interface.cc56
-rw-r--r--libtransport/src/io_modules/raw_socket/raw_socket_interface.h61
-rw-r--r--libtransport/src/io_modules/udp/CMakeLists.txt32
-rw-r--r--libtransport/src/io_modules/udp/hicn_forwarder_module.cc181
-rw-r--r--libtransport/src/io_modules/udp/hicn_forwarder_module.h86
-rw-r--r--libtransport/src/io_modules/udp/udp_socket_connector.cc211
-rw-r--r--libtransport/src/io_modules/udp/udp_socket_connector.h88
-rw-r--r--libtransport/src/libhicntransport-config.cmake.in8
-rw-r--r--libtransport/src/protocols/CMakeLists.txt16
-rw-r--r--libtransport/src/protocols/byte_stream_reassembly.cc11
-rw-r--r--libtransport/src/protocols/byte_stream_reassembly.h5
-rw-r--r--libtransport/src/protocols/cbr.cc10
-rw-r--r--libtransport/src/protocols/cbr.h2
-rw-r--r--libtransport/src/protocols/congestion_window_protocol.h2
-rw-r--r--libtransport/src/protocols/data_processing_events.h2
-rw-r--r--libtransport/src/protocols/datagram_reassembly.cc7
-rw-r--r--libtransport/src/protocols/datagram_reassembly.h6
-rw-r--r--libtransport/src/protocols/errors.cc2
-rw-r--r--libtransport/src/protocols/errors.h2
-rw-r--r--libtransport/src/protocols/fec/CMakeLists.txt2
-rw-r--r--libtransport/src/protocols/fec/fec.cc182
-rw-r--r--libtransport/src/protocols/fec/rely.cc105
-rw-r--r--libtransport/src/protocols/fec/rely.h76
-rw-r--r--libtransport/src/protocols/fec/rs.cc166
-rw-r--r--libtransport/src/protocols/fec/rs.h126
-rw-r--r--libtransport/src/protocols/fec_base.h86
-rw-r--r--libtransport/src/protocols/incremental_indexer_bytestream.cc6
-rw-r--r--libtransport/src/protocols/incremental_indexer_bytestream.h12
-rw-r--r--libtransport/src/protocols/index_manager_bytestream.cc2
-rw-r--r--libtransport/src/protocols/index_manager_bytestream.h18
-rw-r--r--libtransport/src/protocols/indexer.cc35
-rw-r--r--libtransport/src/protocols/indexer.h26
-rw-r--r--libtransport/src/protocols/manifest_incremental_indexer_bytestream.cc80
-rw-r--r--libtransport/src/protocols/manifest_incremental_indexer_bytestream.h14
-rw-r--r--libtransport/src/protocols/prod_protocol_bytestream.cc265
-rw-r--r--libtransport/src/protocols/prod_protocol_bytestream.h11
-rw-r--r--libtransport/src/protocols/prod_protocol_rtc.cc834
-rw-r--r--libtransport/src/protocols/prod_protocol_rtc.h108
-rw-r--r--libtransport/src/protocols/production_protocol.cc141
-rw-r--r--libtransport/src/protocols/production_protocol.h35
-rw-r--r--libtransport/src/protocols/protocol.h73
-rw-r--r--libtransport/src/protocols/raaqm.cc37
-rw-r--r--libtransport/src/protocols/raaqm.h19
-rw-r--r--libtransport/src/protocols/raaqm_data_path.cc31
-rw-r--r--libtransport/src/protocols/raaqm_data_path.h16
-rw-r--r--libtransport/src/protocols/rate_estimation.cc101
-rw-r--r--libtransport/src/protocols/rate_estimation.h21
-rw-r--r--libtransport/src/protocols/reassembly.cc2
-rw-r--r--libtransport/src/protocols/reassembly.h14
-rw-r--r--libtransport/src/protocols/rtc/CMakeLists.txt23
-rw-r--r--libtransport/src/protocols/rtc/probe_handler.cc68
-rw-r--r--libtransport/src/protocols/rtc/probe_handler.h40
-rw-r--r--libtransport/src/protocols/rtc/rtc.cc754
-rw-r--r--libtransport/src/protocols/rtc/rtc.h30
-rw-r--r--libtransport/src/protocols/rtc/rtc_consts.h124
-rw-r--r--libtransport/src/protocols/rtc/rtc_data_path.cc110
-rw-r--r--libtransport/src/protocols/rtc/rtc_data_path.h31
-rw-r--r--libtransport/src/protocols/rtc/rtc_forwarding_strategy.cc217
-rw-r--r--libtransport/src/protocols/rtc/rtc_forwarding_strategy.h82
-rw-r--r--libtransport/src/protocols/rtc/rtc_indexer.h47
-rw-r--r--libtransport/src/protocols/rtc/rtc_ldr.cc593
-rw-r--r--libtransport/src/protocols/rtc/rtc_ldr.h109
-rw-r--r--libtransport/src/protocols/rtc/rtc_packet.h219
-rw-r--r--libtransport/src/protocols/rtc/rtc_rc.h12
-rw-r--r--libtransport/src/protocols/rtc/rtc_rc_congestion_detection.cc74
-rw-r--r--libtransport/src/protocols/rtc/rtc_rc_congestion_detection.h47
-rw-r--r--libtransport/src/protocols/rtc/rtc_rc_iat.cc287
-rw-r--r--libtransport/src/protocols/rtc/rtc_rc_iat.h93
-rw-r--r--libtransport/src/protocols/rtc/rtc_rc_queue.cc6
-rw-r--r--libtransport/src/protocols/rtc/rtc_rc_queue.h5
-rw-r--r--libtransport/src/protocols/rtc/rtc_reassembly.cc109
-rw-r--r--libtransport/src/protocols/rtc/rtc_reassembly.h21
-rw-r--r--libtransport/src/protocols/rtc/rtc_recovery_strategy.cc420
-rw-r--r--libtransport/src/protocols/rtc/rtc_recovery_strategy.h181
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_delay.cc147
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_delay.h55
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_fec_only.cc143
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_fec_only.h53
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_low_rate.cc174
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_low_rate.h71
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_recovery_off.cc65
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_recovery_off.h46
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_rtx_only.cc67
-rw-r--r--libtransport/src/protocols/rtc/rtc_rs_rtx_only.h46
-rw-r--r--libtransport/src/protocols/rtc/rtc_state.cc602
-rw-r--r--libtransport/src/protocols/rtc/rtc_state.h207
-rw-r--r--libtransport/src/protocols/rtc/rtc_verifier.cc248
-rw-r--r--libtransport/src/protocols/rtc/rtc_verifier.h96
-rw-r--r--libtransport/src/protocols/transport_protocol.cc157
-rw-r--r--libtransport/src/protocols/transport_protocol.h32
-rw-r--r--libtransport/src/test/CMakeLists.txt55
-rw-r--r--libtransport/src/test/main.cc1
-rw-r--r--libtransport/src/test/packet_samples.h15
-rw-r--r--libtransport/src/test/test_aggregated_header.cc624
-rw-r--r--libtransport/src/test/test_auth.cc223
-rw-r--r--libtransport/src/test/test_consumer_producer_rtc.cc37
-rw-r--r--libtransport/src/test/test_core_manifest.cc245
-rw-r--r--libtransport/src/test/test_event_thread.cc36
-rw-r--r--libtransport/src/test/test_fec_base_rely.cc454
-rw-r--r--libtransport/src/test/test_fec_base_rs.cc413
-rw-r--r--libtransport/src/test/test_fec_reedsolomon.cc122
-rw-r--r--libtransport/src/test/test_fec_rely_wrapper.cc131
-rw-r--r--libtransport/src/test/test_fixed_block_allocator.cc211
-rw-r--r--libtransport/src/test/test_interest.cc96
-rw-r--r--libtransport/src/test/test_memif_connector.cc152
-rw-r--r--libtransport/src/test/test_packet.cc540
-rw-r--r--libtransport/src/test/test_packet_allocator.cc132
-rw-r--r--libtransport/src/test/test_prefix.cc334
-rw-r--r--libtransport/src/test/test_quadloop.cc176
-rw-r--r--libtransport/src/test/test_quality_score.cc135
-rw-r--r--libtransport/src/test/test_sessions.cc77
-rw-r--r--libtransport/src/test/test_thread_pool.cc70
-rw-r--r--libtransport/src/test/test_traffic_generator.cc119
-rw-r--r--libtransport/src/transport.config2
-rw-r--r--libtransport/src/utils/CMakeLists.txt8
-rw-r--r--libtransport/src/utils/content_store.cc9
-rw-r--r--libtransport/src/utils/content_store.h5
-rw-r--r--libtransport/src/utils/daemonizator.cc2
-rw-r--r--libtransport/src/utils/deadline_timer.h57
-rw-r--r--libtransport/src/utils/epoll_event_reactor.cc190
-rw-r--r--libtransport/src/utils/epoll_event_reactor.h167
-rw-r--r--libtransport/src/utils/event_reactor.h2
-rw-r--r--libtransport/src/utils/fd_deadline_timer.h15
-rw-r--r--libtransport/src/utils/log.cc4
-rw-r--r--libtransport/src/utils/max_filter.h58
-rw-r--r--libtransport/src/utils/membuf.cc23
-rw-r--r--libtransport/src/utils/memory_pool_allocator.h2
-rw-r--r--libtransport/src/utils/min_filter.h8
-rw-r--r--libtransport/src/utils/stream_buffer.h2
-rw-r--r--libtransport/src/utils/string_tokenizer.cc2
-rw-r--r--libtransport/src/utils/suffix_strategy.h166
-rw-r--r--libtransport/src/utils/test.h2
-rw-r--r--libtransport/src/utils/traffic_generator.cc87
-rw-r--r--libtransport/src/utils/uri.cc2
-rw-r--r--libtransport/third-party/CMakeLists.txt82
-rw-r--r--libtransport/third-party/CMakeLists.txt.orig85
-rw-r--r--libtransport/third-party/CMakeLists.txt.rej21
-rw-r--r--libtransport/third-party/glog.patch2
-rw-r--r--libtransport/third-party/memif.patch52
-rw-r--r--scripts/Dockerfile.sonarcloud20
-rw-r--r--scripts/build-packages.sh65
-rw-r--r--scripts/build-sonar.sh26
-rw-r--r--scripts/checkstyle.sh104
-rw-r--r--scripts/docker-compose-sonar.yml18
-rw-r--r--scripts/functional-tests.sh35
-rw-r--r--scripts/functions.sh194
-rw-r--r--scripts/install-vpp.sh59
-rwxr-xr-xscripts/run-sonar.sh69
-rw-r--r--telemetry/.clang-format3
-rw-r--r--telemetry/CMakeLists.txt69
-rw-r--r--telemetry/cmake/packaging.cmake (renamed from telemetry/vpp-collectd/cmake/Modules/Packaging.cmake)6
-rw-r--r--telemetry/collectd.conf54
-rw-r--r--telemetry/data_model.h143
-rw-r--r--telemetry/hicn-light-collectd/CMakeLists.txt65
-rw-r--r--telemetry/hicn-light-collectd/hicn_light.c200
-rw-r--r--telemetry/kafka-collectd/CMakeLists.txt62
-rw-r--r--telemetry/kafka-collectd/format_influxdb.c190
-rw-r--r--telemetry/kafka-collectd/format_influxdb.h45
-rw-r--r--telemetry/kafka-collectd/write_kafka_line_protocol.c526
-rw-r--r--telemetry/third-party/CMakeLists.txt18
-rw-r--r--telemetry/vpp-collectd/CMakeLists.txt24
-rw-r--r--telemetry/vpp-collectd/common/README.md12
-rw-r--r--telemetry/vpp-collectd/common/common.h405
-rw-r--r--telemetry/vpp-collectd/common/meta_data.h71
-rw-r--r--telemetry/vpp-collectd/common/plugin.h485
-rw-r--r--telemetry/vpp-collectd/vpp-hicn/CMakeLists.txt90
-rw-r--r--telemetry/vpp-collectd/vpp-hicn/vpp_hicn.c177
-rw-r--r--telemetry/vpp-collectd/vpp/CMakeLists.txt68
-rw-r--r--telemetry/vpp-collectd/vpp/vpp.c103
-rw-r--r--tests/.env36
-rw-r--r--tests/1-node.yml32
-rw-r--r--tests/2-nodes-hicn-light.yml53
-rw-r--r--tests/2-nodes-vpp-bridge.yml114
-rw-r--r--tests/2-nodes-vpp-memif-local-remote.yml116
-rw-r--r--tests/2-nodes-vpp-memif-replication.yml124
-rw-r--r--tests/2-nodes-vpp-memif.yml116
-rw-r--r--tests/2-nodes.yml45
-rw-r--r--tests/Dockerfile.ci40
-rw-r--r--tests/Makefile42
-rw-r--r--tests/build.yml41
-rwxr-xr-xtests/channel.sh22
-rwxr-xr-xtests/config.sh700
-rw-r--r--tests/functional-tests/2-nodes-hicn-light.robot84
-rw-r--r--tests/functional-tests/2-nodes-vpp-bridge.robot53
-rw-r--r--tests/functional-tests/2-nodes-vpp-memif-replication.robot46
-rw-r--r--tests/functional-tests/2-nodes-vpp-memif.robot46
-rw-r--r--tests/functional-tests/hicn-light-control.robot48
-rw-r--r--tests/functional-tests/hicn-light-ping.robot30
-rw-r--r--tests/hiperf-local.sh21
-rw-r--r--tests/resources/libraries/robot/common.robot39
-rw-r--r--tests/resources/libraries/robot/runtest.robot293
-rw-r--r--tests/run-functional.sh (renamed from libtransport/src/io_modules/loopback/CMakeLists.txt)38
-rw-r--r--versions.cmake (renamed from hicn-light/src/hicn/command_line/daemon/CMakeLists.txt)29
1290 files changed, 95632 insertions, 97794 deletions
diff --git a/.cz.toml b/.cz.toml
new file mode 100644
index 000000000..ccd7a584f
--- /dev/null
+++ b/.cz.toml
@@ -0,0 +1,5 @@
+[tool]
+[tool.commitizen]
+name = "cz_conventional_commits"
+version = "3.14.0"
+tag_format = "v$version"
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 000000000..f6a0b57c5
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,14 @@
+**/report.xml
+**/build*
+**/.devcontainer
+**/.vscode
+**/docker/Dockerfile
+**/docker/Dockerfile.clang
+ci/Dockerfile*
+#**/deb
+**/*.tar
+**/.gitignore
+**/info.txt
+./install*
+.git
+**/debug*
diff --git a/.git_commit_template.txt b/.git_commit_template.txt
new file mode 100644
index 000000000..0adb02730
--- /dev/null
+++ b/.git_commit_template.txt
@@ -0,0 +1,50 @@
+<type>[optional scope]: <description>
+# |<---- Using a maximum of 50 characters ---->|
+
+Explain why this change is being made
+# |<---- Try to limit each line to a maximum of 72 characters ---->|
+
+Ticket: <JIRA #id>
+# Fixes: <offending-git-commit-id>
+# Change-Id: <sha1>
+# Signed-off-by: <email>
+#
+#
+# --- COMMIT END ---
+#
+# Type can be
+# feat (new feature)
+# fix (bug fix)
+# refactor (refactoring production code)
+# build (change to the build system)
+# style (formatting, missing semi colons, etc; no code change)
+# docs (changes to documentation)
+# test (adding or refactoring tests; no production code change)
+# ci (change to CI scripts/configuration)
+# chore (no production code change)
+# perf (performance improvement)
+# revert (revert a change)
+#
+# optional scope: Is the name of the feature, directory or file
+# being modified. Commits across multiple components
+# should be split.
+#
+# Fixes: If type is fix refers to the original commit (optional).
+# Ticket: Refers to JIRA ticket if it exists (optional).
+#
+# --------------------
+# Remember to:
+# Lowercase the description line.
+# Use the imperative mood in the description line.
+# Not end the subject line with a period.
+# Separate subject from body with a blank line.
+# Use the body to explain what and why vs. how.
+# Use multiple lines with "-" for bullet points in body.
+# --------------------
+# Usage:
+#
+# The template is automatically added to the current repository by
+# make deps.
+# (git config commit.template .git_commit_template.txt)
+#
+# -------------------- \ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 52ecb4eba..cbdd34811 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,19 @@
build*
-.ccls-cache/
+.cache/
compile_commands.json
+sonar*
+.scannerwork*
+deb
+info.txt
+.vscode
+.DS_Store
+
+# Local install
+install*
+
+# Robot
+tests/**/*.xml
+tests/**/*.html
+tests/**/*.log
+*.tar
+**/env \ No newline at end of file
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 000000000..55a6478e7
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "cmake"]
+ path = cmake
+ url = https://github.com/icn-team/cmake-modules.git
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 000000000..af94bbc3d
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,7 @@
+repos:
+- hooks:
+ - id: commitizen
+ stages:
+ - commit-msg
+ repo: https://github.com/commitizen-tools/commitizen
+ rev: v2.19.0
diff --git a/AUTHORS b/AUTHORS
index 8f67db1f5..535ea8297 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,8 +1,10 @@
Jordan Augé <jordan.auge@cisco.com>
Giovanna Carofiglio <gcarofig@cisco.com>
Alberto Compagno <acompagn@cisco.com>
+Enrico Loparco <eloparco@cisco.com>
Angelo Mantellini <manangel@cisco.com>
Luca Muscariello <lumuscar@cisco.com>
Michele Papalini <mpapal@cisco.com>
+Olivier Roques <oroques@cisco.com>
Jacques Samain <jsamain@cisco.com>
Mauro Sardara <msardara@cisco.com>
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 000000000..620933eb0
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,1030 @@
+## v3.14.0 (2022-07-18)
+
+### Feat
+
+- release 3.14 of hicn
+- move interest manifest inside libhicn to be reused by hicn-plugin
+- include wrapper asio files
+- include wrapper asio files
+- rewrite new PCS, backed by clib_bihash
+
+### Fix
+
+- **lib**: install interest manifest header
+- **hicn-light**: code style
+- **hicn-light**: fix connection table issue
+- **hicn-light**: fix connection table issue
+- **hicn-light**: fix crash on connection close
+- **hicn-light**: fix interest send on mac os
+- **transport**: fix udp connector for mac os
+- do not reuse vpp struct/macros in libhicn
+- **ci/docker-build-ios.sh**: accept ios dockerfile eula
+- **core**: add ifndef to compile on macos
+- **pcs.h**: align PCS entry to 64 bytes in place of CLIB_CACHELINE
+
+## v3.13.0 (2022-06-17)
+
+## v3.13.0b0 (2022-06-16)
+
+### Feat
+
+- release 3.13 of hicn
+- **transport**: codel style
+- **transport**: imporve switch between RTX and FEC with variable RTT
+- **transport**: improve fec for low rtt
+- **aggregated-interests**: fix multipath with aggregated interests
+- packet generator to assess performance
+- **hicn-light-collectd**: add per-face stats in collectd plugin
+- **hicn-light-collectd**: add per-face stats in forwarder
+- **hicn-light-collectd**: update cmake for vpp collectd plugins
+- **hicn-light-collectd**: modify kafka output collectd plugin to use influxdb format and do dispatching
+- **hicn-light-collectd**: use input collectd plugin to retrieve stats from forwarder
+- **hicn-light-collectd**: expose libhicnctrl api to retrieve hicn-light stats
+- **hicn-light-collectd**: setup cmake for hicn-light and kafka plugins
+- **transport**: set the expirtation time of the data packets using socket options
+- **libtransport**: use microseconds to improve RTT precision
+- **aggregated-interests**: enable aggregated interests at runtime
+- **aggregated-interests**: add aggregated interest support in transport
+- **hicn-plugin**: parse hicn packet only one time, as soon as it is received
+- **transport**: modify delay in delay strategy
+- **manifest**: improve encoding and decoding
+- **aggregated-interests**: add signature to interest manifest
+- **aggregated-interests**: add disaggregation and bitmap in interest manifest
+- **libhicn**: move common data structures in lib
+- **vector**: add missing api functions to vector data structure
+- **libhicn**: use same map data structure between hicn-light and hicn-ctrl
+- **libtransport**: remove all references to ntoh and hton
+- **packet-cache**: add CS clear in hicn-light
+- **portal.h**: modify PIT to register penging interests in both sides
+- **libtransport**: add global module manager and library constructor
+- multistream hiperf
+- **libtransport**: add cache prefetch support and test to assess performance
+- Add API to get/set ports in libhicn
+- add enumeration for packet type in libhicn
+- **pool**: remove unnecessary memset in pool and add script to test hiperf locally
+- **packet-cache**: avoid double lookups when possible
+- **packet-cache**: add two-level packet cache
+- **hicn-ping**: add interest manifest support in hicn-ping
+- sync build scripts with master-fdio
+- **auth**: use membuf
+
+### Fix
+
+- **hiperf**: fix buffer contention when using multiple producers
+- **manifest**: remove unnecessary debug assert
+- better organize flags in hicn-plugin
+- replace deprecated std::random_shuffle function
+- **transport**: use constant var in recovery strategy baeds on delay
+- **hiperf**: fix bandwidth computaton in hiperf
+- **manifest**: compilation error
+- **libhicnctrl**: fix name generation for new faces
+- **libhicnctrl**: fix name generation for new faces
+- fix memory corruption in msgbuf ids vector
+- **hicn-light**: fix hardcoded limit on number of pending connections
+- **hicn-light**: return error when not able to generate new connection name
+- **transport**: fix forwarder io module in transport
+- **auth**: invalid memory read in signer
+- **libtransport**: pass all required callbacks when creating connectors
+- fix htonll and ntohll in libhicn
+- **packet-cache**: add missing data prefix caching on content packet received
+- **production_protocol.h**: do not accept unvalid values of TRANSPORT_FEC_TYPE if environment variable is set
+- use proper function to compare elements in listener and conenction table
+- **docker**: do no use internal image in public dockerfile and remove old functional tests
+- **fec**: correctly compute the transport header size of each packet
+- **transport**: add rs fec header size also in the decoder
+- **transport**: fix max packet size in producer socket
+- **prod_protocol_rtc.cc**: check if fec_type is valid before using it
+- **hicnctrl**: fix route command validation
+
+### Perf
+
+- **transport**: reduce cpu usage at RTC consumer socket for loss detection
+
+### Refactor
+
+- **tls**: remove support for TLS
+- **manifest**: move decoding of manifest out of decoder constructor
+- move interest manifest header to libhicn and update log
+- refactor listener and connection table
+- **manifest**: improve manifest verification and performance
+
+## v3.12.2 (2022-06-01)
+
+### Fix
+
+- **lib/includes/hicn/util/bitmap.h**: correct include header
+
+## v3.12.1 (2022-06-01)
+
+### Fix
+
+- **cmake**: wrong version number in hicn
+
+## v3.12.0 (2022-05-31)
+
+### Feat
+
+- release 3.12 of hicn
+- **aggregated-interests**: add signature to interest manifest
+- **aggregated-interests**: add disaggregation and bitmap in interest manifest
+- **libhicn**: move common data structures in lib
+- **vector**: add missing api functions to vector data structure
+- **libhicn**: use same map data structure between hicn-light and hicn-ctrl
+- **libtransport**: remove all references to ntoh and hton
+- **packet-cache**: add CS clear in hicn-light
+- **portal.h**: modify PIT to register penging interests in both sides
+- **libtransport**: add global module manager and library constructor
+- multistream hiperf
+- **libtransport**: add cache prefetch support and test to assess performance
+- Add API to get/set ports in libhicn
+- add enumeration for packet type in libhicn
+- **pool**: remove unnecessary memset in pool and add script to test hiperf locally
+- **packet-cache**: avoid double lookups when possible
+- **packet-cache**: add two-level packet cache
+- **hicn-ping**: add interest manifest support in hicn-ping
+- sync build scripts with master-fdio
+- **auth**: use membuf
+
+### Fix
+
+- **libhicnctrl**: fix name generation for new faces
+- **libhicnctrl**: fix name generation for new faces
+- fix memory corruption in msgbuf ids vector
+- **hicn-light**: fix hardcoded limit on number of pending connections
+- **hicn-light**: return error when not able to generate new connection name
+- **transport**: fix forwarder io module in transport
+- **auth**: invalid memory read in signer
+- **libtransport**: pass all required callbacks when creating connectors
+- fix htonll and ntohll in libhicn
+- **packet-cache**: add missing data prefix caching on content packet received
+- **production_protocol.h**: do not accept unvalid values of TRANSPORT_FEC_TYPE if environment variable is set
+- use proper function to compare elements in listener and conenction table
+- **docker**: do no use internal image in public dockerfile and remove old functional tests
+- **fec**: correctly compute the transport header size of each packet
+- **transport**: add rs fec header size also in the decoder
+- **transport**: fix max packet size in producer socket
+- **prod_protocol_rtc.cc**: check if fec_type is valid before using it
+- **hicnctrl**: fix route command validation
+
+### Refactor
+
+- **manifest**: move decoding of manifest out of decoder constructor
+- move interest manifest header to libhicn and update log
+- refactor listener and connection table
+- **manifest**: improve manifest verification and performance
+
+## v3.11.3 (2022-04-18)
+
+### Feat
+
+- **manifest**: optimize manifest processing
+
+## v3.11.2 (2022-04-13)
+
+### Fix
+
+- **manifest**: do not iterate on full data buffer to compute ratio
+
+## v3.11.1 (2022-04-13)
+
+### Fix
+
+- **manifest**: ignore manifest entries of discarded unverified packets
+
+## v3.11.0 (2022-04-11)
+
+## v3.11.0b0 (2022-04-08)
+
+### Feat
+
+- release 3.11 of hicn
+- **manifest**: add FEC parameters to manifests
+- **manifest**: refactor verification process
+- **manifest**: report auth alerts in hiperf instead of aborting
+- **manifest**: remove FEC buffer callback in consumer
+- **manifest**: refactor and enable manifests by default
+- **manifest**: update manifest header with transport parameters
+- **manifest**: batch interests for first manifest from RTC producer
+- **manifest**: refactor processing of RTC manifests
+- **manifest**: update manifest-related socket options of consumers
+- **manifest**: update unit tests for manifests
+- **manifest**: pack manifest headers
+- **manifest**: verify FEC packets
+- **auth**: add consumer socket option to set max unverified delay
+- **manifest**: process manifests after full FEC decoding
+- **manifest**: manage forward jumps in RTC verifier
+- **fec**: remove useless fec codes
+- **rs**: add new code rate
+- **rs**: add new code rate
+- **rs**: add new code rate
+- **rs**: add new code rate
+- **libtransport**: increase internal packet cache size
+- remove internal cisco info in cmake
+- **manifest**: add option to set manifest capacity
+- **data_input_node.c**: add information about adj_index[VLIB_RX] on received data packets
+- **hicn-plugin**: upgrade to VPP 22.02
+
+### Refactor
+
+- **manifest**: change default manifest options to support low-rate
+- remove remaining traces of fec type option
+- **hiperf**: cosmetic update
+- **manifest**: apply code reviews
+- **auth**: change auth failed callback signature
+
+### Fix
+
+- **strategy-callbacks**: fix callback calls when transport is out of scope
+- **bitmap**: fix bitmap set operation
+- **transport**: avoid to add fec at start up if no loss is detected
+- **notifications**: add callbacks for forwarding/recovery strategy changes
+- **face_node.c**: ensure IPv6 loopback is not interpreted as IPv4 address
+- **manifest**: fix segfault with RS + manifests
+- **manifest**: support RS
+- **auth**: verify previously unverified packet signatures
+- **bytestream**: make manifest branch work with RAAQM
+- **pathlabel**: fix data path label in the hicn-light forwarder
+- **deps**: fix cisco openssl and safec dependencies inclusion
+- **udp_connector.cc**: call receive callback with correct parameters
+- cannot retrieve integer producer socket option
+- **fec.cc**: correct fec after wrong merge
+- **liiib/CMakeLists.txt**: correct typo
+
+## v3.10.0 (2022-04-02)
+
+### Feat
+
+- release 3.10 of hicn
+- **manifest**: refactor verification process
+- **manifest**: report auth alerts in hiperf instead of aborting
+- **manifest**: remove FEC buffer callback in consumer
+- **manifest**: refactor and enable manifests by default
+- **manifest**: update manifest header with transport parameters
+- **manifest**: batch interests for first manifest from RTC producer
+- **manifest**: refactor processing of RTC manifests
+- **manifest**: update manifest-related socket options of consumers
+- **manifest**: update unit tests for manifests
+- **manifest**: pack manifest headers
+- **manifest**: verify FEC packets
+- **auth**: add consumer socket option to set max unverified delay
+- **manifest**: process manifests after full FEC decoding
+- **manifest**: manage forward jumps in RTC verifier
+- **fec**: remove useless fec codes
+- **rs**: add new code rate
+- **rs**: add new code rate
+- **rs**: add new code rate
+- **rs**: add new code rate
+- **libtransport**: increase internal packet cache size
+- remove internal cisco info in cmake
+- **manifest**: add option to set manifest capacity
+- **hicn-plugin**: upgrade to VPP 22.02
+
+### Fix
+
+- **transport**: avoid to add fec at start up if no loss is detected
+- **notifications**: add callbacks for forwarding/recovery strategy changes
+- **face_node.c**: ensure IPv6 loopback is not interpreted as IPv4 address
+- **manifest**: fix segfault with RS + manifests
+- **manifest**: support RS
+- **auth**: verify previously unverified packet signatures
+- **bytestream**: make manifest branch work with RAAQM
+- **pathlabel**: fix data path label in the hicn-light forwarder
+- **deps**: fix cisco openssl and safec dependencies inclusion
+- **udp_connector.cc**: call receive callback with correct parameters
+- cannot retrieve integer producer socket option
+
+### Refactor
+
+- **hiperf**: cosmetic update
+- **manifest**: apply code reviews
+- **auth**: change auth failed callback signature
+
+## v3.9.1 (2022-03-21)
+
+### Fix
+
+- **route**: fix route creation failure when id instead of symbolic
+
+## v3.9.0 (2022-03-21)
+
+### Feat
+
+- release 3.9
+- **data_input_node.c**: add information about adj_index[VLIB_RX] on received data packets
+- **hicn-plugin**: upgrade to VPP 22.02
+
+### Fix
+
+- **liiib/CMakeLists.txt**: correct typo
+
+## v3.8.1 (2022-03-15)
+
+### Fix
+
+- **android-sdk**: upgrade android-sdk version
+
+## v3.8.0 (2022-03-14)
+
+## v3.8.0b0 (2022-03-12)
+
+### Feat
+
+- release 3.8 of hicn
+- **ci**: install correct VPP version in local ci scripts
+- **Makefile**: add conveniente targets to build/use docker container
+- **security**: define custom secure functions if not available
+- **security**: improve input validation
+- insert CPU info as compilation options
+
+### Refactor
+
+- **fec**: do not include FEC header when copying FEC payload
+- **auth**: clean up
+- **CMakeLists.txt**: global cleanup of CMakeLists files
+
+### Fix
+
+- **probe-generator**: return probe register time (fix probe generator test)
+- fix pool index validation and removal of current listener/connection
+- **strcpy_s**: fix warnings appearing after strcpy_s introduction
+- **security**: use secure version of strlen
+- **security**: use secure version of strcpy
+- **test-rs**: typo
+- **rs-test**: fix packet index size
+- **cmake**: add ciscossl path
+- **fec-rate**: set max loss rate to 0.95
+- **loss-rate**: init loss rate using the rtt probes
+
+## v3.7.2 (2022-02-25)
+
+### Feat
+
+- update android-sdk version to 2.0.6
+
+## v3.7.1 (2022-02-17)
+
+### Feat
+
+- use android-sdk image with librdkafka 1.8.2
+
+## v3.7.0 (2022-02-17)
+
+### Fix
+
+- **CS**: correctly forward packets coming from the CS
+
+## v3.7.0b0 (2022-02-14)
+
+### Feat
+
+- release 3.7 of hicn
+- **hicn-light-control**: distinguish between command and serialization errors
+- **pit**: code style
+- **pit**: code style
+- **pit**: do not send aggregated interests
+- **pit**: do not store state in the pit for interests with no nexthop
+- add arm and x86 support to hicn
+- **hicn-light-control**: add input validation in hicn-light-control parser
+- **hicn-ctrl**: add command for notification subscription in hicn-light-control
+- add vpp logs
+- **hicn-plugin**: return the list of created faces after running hicn_route_enable.
+- add constants for invalid face and invalid netdevice
+- **packet-cache**: use Name instead of name_key_t as hashtable key
+- **forwarder**: code style
+- **hicn-light**: fix mapme packet processing
+- **hicn-light**: remove commented code and missing initiliazations
+- **forwarder**: fix tests
+- **hicn-plugin**: add log
+- create prod image of hicn
+- **hicn-plugin**: allow UDP tunnels to be dynamically created upon interest reception.
+- **hicn-plugin**: add support for UDP tunnels in mapme
+- **strategy**: fix crash and nexthops compare
+- **strategy**: fix add local prefixes
+- **strategy**: add local prefixes and mapme updates to replication
+- **strategy**: code style
+- **strategy**: improve path switch
+- **transport**: improve path switch
+- **strategy**: set bestpath before send mapme message
+- **strategy**: send mapme update at the end of each probing phase
+- **hicn-light**: add support for strategy_add_local_prefix command from config file
+- **facemgr**: use separate sockets for control and polling hicn-light
+- **hicn-light**: close listener and connection file descriptors on forwarder stop
+- **hicnctrl**: add timeout for recv operations
+- **hicn-light**: remove hicnctrl connection from 'list connection' command output
+- **listeners**: set local listeners without using resolver
+- **doc**: update readme file
+- **doc**: update readme file and authors' list
+
+### Fix
+
+- **parser**: add cast to compile in android
+- **hicn-light-control**: fix missing error code in case of nack
+- **hicn-light-control**: remove sopport for old forwarder
+- **facemgr/libhicn**: Assigned value is garbage or undefined
+- **facemgr**: Remove the commented out code
+- **facemgr**: code/return will never be executed
+- check that face_output sends interest to a complete face
+- try not to keep a lock to dpo_ctx in each PIT entry.
+- log route creation/deletion failures in linhicnctrl
+- **memif_vapi.c**: initialize memif id before retrieving the next id to use.
+- **libvapi_safe**: implement vapi_disconnect API
+- **libhinctrl**: fix ring buffer management + refactor code
+- **facemgr/netlink**: leaked facelets for interfaces not up and running
+- **facemgr/hicn-light**: timerfd leak
+- **hicnctrl**: fix notification processing
+- **core::Portal**: ensure interest timeout handler refers to a valid Portal.
+- **rtc-transport**: ensure RTC is running and valid before executing timer handlers
+- **libhinctrl**: fix ring buffer management + refactor code
+- **listener-table**: forbid creation of listener for already-existing address
+- **connection-table**: fix multiple connections with same name
+- **hicn-light**: fixed uninitialized memory in parser code
+- **Jenkinsfile**: prod image is not created
+- initialize listener memory
+- **libhicnctrl**: remove useless size_in field in hicn_sock_request_t
+- propagate listener hashtable fix in connection table and packet cache
+- **listener-table**: fix listener removal from hashtable
+- **dockerfile**: tests failed due the wrong docker image
+- **rtc_state.h**: initialize rtc_state out of constructor
+- **rtc_state.h**: check if RTCState is valid before dereferencing it.
+- **hicn-light**: missing command_id in LIST command replies + cleanup
+- producer face deletion does not delete the route from fib 0
+- **hicn-plugin**: insert drop node in the next nodes of face-node
+- delete faces when lock count reaches 0
+- **libhicnctrl**: fix hardcoded AF_INET in hc_face_to_connection
+- **facemgr/android**: handle missing android information on down interfaces
+- **hicn-light**: fix memory leaks when forwarder is closed
+- **hicn-light**: fix forwarder receive
+- fix MacOS build errors
+
+### Perf
+
+- **hicn-light**: remove memory allocation inside name
+
+### Refactor
+
+- **packet-cache**: remove macro used in packet cache entry allocation
+- **facemgr/hicn-light**: refactor poll timer code
+
+## v3.6.8 (2022-02-10)
+
+### Fix
+
+- **mapme**: Ignore updates from current nexthop with lower sequence number
+
+## v3.6.7 (2022-02-09)
+
+### Fix
+
+- **hicn-plugin**: get input face using source address lookup in place of using a list of possible incoming faces
+
+## v3.6.6 (2022-02-08)
+
+### Fix
+
+- **hicn-plugin**: remove unused in_face_id from PCS
+- **hicn-plugin**: remove vector of in_face_id
+
+## v3.6.5 (2022-02-07)
+
+### Fix
+
+- **memif-connector**: signal send error up to application
+
+## v3.6.4 (2022-02-05)
+
+### Fix
+
+- add NH before deleting tfib entr
+
+## v3.6.3 (2022-02-05)
+
+### Fix
+
+- disable prints when hicn is compiled in release mode
+
+## v3.6.2 (2022-02-04)
+
+### Fix
+
+- **facemgr**: prevent incorrect free of facelet added to cache
+
+## v3.6.1 (2022-02-02)
+
+### Fix
+
+- use correct fib source when updating next hops with mapme
+
+## v3.6.0 (2022-02-01)
+
+### Fix
+
+- update cmake version
+- check that face_output sends interest to a complete face
+- try not to keep a lock to dpo_ctx in each PIT entry.
+- log route creation/deletion failures in linhicnctrl
+- **memif_vapi.c**: initialize memif id before retrieving the next id to use.
+- **libvapi_safe**: implement vapi_disconnect API
+- **libhinctrl**: fix ring buffer management + refactor code
+- **facemgr/netlink**: leaked facelets for interfaces not up and running
+- **facemgr/hicn-light**: timerfd leak
+- **hicnctrl**: fix notification processing
+- **core::Portal**: ensure interest timeout handler refers to a valid Portal.
+- **rtc-transport**: ensure RTC is running and valid before executing timer handlers
+- **libhinctrl**: fix ring buffer management + refactor code
+- **listener-table**: forbid creation of listener for already-existing address
+- **connection-table**: fix multiple connections with same name
+- **hicn-light**: fixed uninitialized memory in parser code
+- **Jenkinsfile**: prod image is not created
+- initialize listener memory
+- **libhicnctrl**: remove useless size_in field in hicn_sock_request_t
+- propagate listener hashtable fix in connection table and packet cache
+- **listener-table**: fix listener removal from hashtable
+- **dockerfile**: tests failed due the wrong docker image
+- **rtc_state.h**: initialize rtc_state out of constructor
+- **rtc_state.h**: check if RTCState is valid before dereferencing it.
+- **hicn-light**: missing command_id in LIST command replies + cleanup
+- producer face deletion does not delete the route from fib 0
+- **hicn-plugin**: insert drop node in the next nodes of face-node
+- delete faces when lock count reaches 0
+- **libhicnctrl**: fix hardcoded AF_INET in hc_face_to_connection
+- **facemgr/android**: handle missing android information on down interfaces
+- **hicn-light**: fix memory leaks when forwarder is closed
+- **hicn-light**: fix forwarder receive
+- fix MacOS build errors
+
+### Feat
+
+- release 3.6 of hicn
+- add vpp logs
+- **hicn-plugin**: return the list of created faces after running hicn_route_enable.
+- add constants for invalid face and invalid netdevice
+- **packet-cache**: use Name instead of name_key_t as hashtable key
+- **forwarder**: code style
+- **hicn-light**: fix mapme packet processing
+- **hicn-light**: remove commented code and missing initiliazations
+- **forwarder**: fix tests
+- **hicn-plugin**: add log
+- create prod image of hicn
+- **hicn-plugin**: allow UDP tunnels to be dynamically created upon interest reception.
+- **hicn-plugin**: add support for UDP tunnels in mapme
+- **strategy**: fix crash and nexthops compare
+- **strategy**: fix add local prefixes
+- **strategy**: add local prefixes and mapme updates to replication
+- **strategy**: code style
+- **strategy**: improve path switch
+- **transport**: improve path switch
+- **strategy**: set bestpath before send mapme message
+- **strategy**: send mapme update at the end of each probing phase
+- **hicn-light**: add support for strategy_add_local_prefix command from config file
+- **facemgr**: use separate sockets for control and polling hicn-light
+- **hicn-light**: close listener and connection file descriptors on forwarder stop
+- **hicnctrl**: add timeout for recv operations
+- **hicn-light**: remove hicnctrl connection from 'list connection' command output
+- **listeners**: set local listeners without using resolver
+- **doc**: update readme file
+- **doc**: update readme file and authors' list
+
+### Perf
+
+- **hicn-light**: remove memory allocation inside name
+
+### Refactor
+
+- **packet-cache**: remove macro used in packet cache entry allocation
+- **facemgr/hicn-light**: refactor poll timer code
+
+## v3.5.0 (2022-01-15)
+
+## v3.5.0b0 (2022-01-14)
+
+### Feat
+
+- release 3.5 of hicn
+- **quality-score**: expose quality score header file
+- **bytestream**: add segment size option for bytestream production
+- **strategy-map**: duplicate string before adding to strategy hashmap
+- **hicn-light-control**: add help command
+- **.cz.toml**: release 3.4
+
+### Fix
+
+- **msgbuf-pool**: fix crash in msgbuf release when debug log is set to trace
+- **hicn-light-control**: fix build error on android and clean hicn-light-control output
+
+## v3.4.3 (2021-12-20)
+
+### Fix
+
+- **facemgr/android**: adding mutex to protect facelet array across threads
+
+## v3.4.2 (2021-12-17)
+
+### Fix
+
+- **facemgr**: workaround for blocking operation preventing loop break
+
+## v3.4.1 (2021-12-16)
+
+### Fix
+
+- **transport**: do not generate NaN values for loss rate
+
+## v3.4.0 (2021-12-15)
+
+## v3.4.0b0 (2021-12-14)
+
+### Feat
+
+- **.cz.toml**: release 3.4
+- **libhicntransport**: split producer socket connect and start into 2 different APIs
+- facemgr: android interface as an alternative to netlink (targetSdk >= 30)
+- **functional-tests**: report output of test commands into robot report
+- **content-store**: report number of stale entries
+- **content-store**: add 'list cache' control command
+- **transport**: select forwarding strategy from transport
+- libtransport threading rework
+- hicn-light: add ring buffer for connection egress
+- **listener**: create local listeners using the "localhost" name
+- **hicn-light**: add default ipv6 listener
+- **test**: functional testing link model Signed-off-by: Luca Muscariello lumuscar@cisco.com
+- **test**: functional testing link model
+Signed-off-by: Luca Muscariello lumuscar@cisco.com
+- **content-store**: disable content store when capacity is set to 0
+- separate packet cache logic from debug prints and incorporate bugfix ICN-1127
+
+### Fix
+
+- **listener**: fix listener removal
+- misc android fixes
+- **production_protocol**: fix bugs in production protocols
+- ensure sendContentObject is called from portal thread
+- hicn-light/mapme: don't send adjacency updates to local faces
+- **loop**: stop loop in signal handler
+- fix access to uninitialized memory
+- facemgr/android: release all resources
+- **memif_connector.cc**: call reconnect_callback_ also from memif connector
+- **build-system**: generate correct cmake config files
+- **strategy**: avoid crash on new forwarding strategy selection
+
+### BREAKING CHANGE
+
+- this commit breaks the interface between transport and
+application. Calls to socket operations are not blocking anymore, so applications
+expecting a blocking behavior will need to be modified.
+
+## v3.3.2 (2021-12-10)
+
+### Fix
+
+- **transport**: init forwarding strategy selection
+
+## v3.3.1 (2021-12-10)
+
+### Feat
+
+- **libtransport**: make API of consumer and producer socket similar
+
+## v3.3.0 (2021-12-10)
+
+### Fix
+
+- specify componenet when installing cmake config files
+- **build-system**: generate correct cmake config files
+
+### Feat
+
+- release 3.3 of hicn
+- facemgr: android interface as an alternative to netlink (targetSdk >= 30)
+- **functional-tests**: report output of test commands into robot report
+- **content-store**: report number of stale entries
+- **content-store**: add 'list cache' control command
+- **transport**: select forwarding strategy from transport
+- libtransport threading rework
+- hicn-light: add ring buffer for connection egress
+- **listener**: create local listeners using the "localhost" name
+- **hicn-light**: add default ipv6 listener
+- **test**: functional testing link model Signed-off-by: Luca Muscariello lumuscar@cisco.com
+- **test**: functional testing link model
+Signed-off-by: Luca Muscariello lumuscar@cisco.com
+- **content-store**: disable content store when capacity is set to 0
+- separate packet cache logic from debug prints and incorporate bugfix ICN-1127
+
+### BREAKING CHANGE
+
+- this commit breaks the interface between transport and
+application. Calls to socket operations are not blocking anymore, so applications
+expecting a blocking behavior will need to be modified.
+
+## v3.2.3 (2021-12-06)
+
+### Feat
+
+- **Dockerfile.android**: add android verify job
+
+## v3.2.2 (2021-12-03)
+
+### Fix
+
+- revert removal for now to remain compatible with hicn_plugin_api #promote PATCH
+- fixed hc_route_t face_id / name attributes overlap
+- work around to create the right route
+- **strategy**: avoid crash on new forwarding strategy selection
+- **Dockerfile**: update base docker image of hicn
+
+## v3.2.1 (2021-12-02)
+
+### Fix
+
+- remove libparc dependency
+
+## v3.2.0 (2021-12-01)
+
+## v3.2.0b0 (2021-11-30)
+
+### Feat
+
+- **.cz.toml**: release 3.2 of hicn
+- trigger mapme updates from producer sockets to traverse nats
+
+### Fix
+
+- added check on listener and connection add
+- **listener**: handle listener creation failure
+- **packet-cache**: fix msgbuf acquire and release in cs update operations
+- libhicntrl: default to hicn-light-ng
+- hicn-light: don't disable MAP-Me messages
+- libhicn: always_inline macro compilation issues
+- libtransport : default to hicn-light-ng
+- hicn-light : consistent listener and connection types
+- **packet-cache**: fix collisions for names in packet cache
+- go back to the use of system clock for delay measurements instead of steady clock
+- **hash**: fix hash function usage
+- **hash**: replace hash function
+- **packet-cache**: fix wrong CS hit due to data name collision in pkt cache
+- consistently use std::chrono to enforce timestamp types
+- **Jenkinsfile**: re-enable publishing of robot tests on hicn
+- set default log level to info
+
+## v3.1.3 (2021-11-25)
+
+### Fix
+
+- **Jenkinsfile**: re-enable publishing of robot tests on hicn
+
+## v3.1.2 (2021-11-24)
+
+### Fix
+
+- **ctrl/CMakeLists.txt**: libfacemgr does not compile on android
+
+## v3.1.1 (2021-11-24)
+
+### Fix
+
+- **transport**: do not count the same packet multiple times as definitely lost
+
+## v3.1.0 (2021-11-24)
+
+### Fix
+
+- **strategy**: do not switch back to old path at the end of a probing pahse
+
+## v3.1.0b0 (2021-11-23)
+
+### Feat
+
+- release 3.1
+- **.cz.toml**: create relesa 3.0 hicn
+- **hiperf**: code style
+- **hiperf**: remove commented queue check
+- **hiperf**: fix compiling error
+- **hiperf**: do not start forwarder interfaces if not needed
+- **hiperf**: fix check to call best path
+- **hiperf**: new check to trigger best path
+- **hiperf**: add set strategy command
+- **hiperf**: add set strategy command
+- add cmake config for dependencies
+- add cmake config for dependencies
+- add cmake config for dependencies
+
+### Fix
+
+- **pipeline**: update pipeline version
+- fix bugs in sonar
+- **forwarder**: fix cmake
+- fix command linkage for forwarder and remove unnecessary debug prints
+- fix command registration for static lib
+- fix missing libevent dependency on macos
+
+## v3.0.0 (2021-11-23)
+
+### Fix
+
+- **pipeline**: update pipeline version
+
+## v3.0.0b0 (2021-11-19)
+
+### Feat
+
+- **.cz.toml**: create relesa 3.0 hicn
+- **transport**: fix error in setting fec to ask param
+- **transport**: add second threshold for loss rate
+- **transport**: add low rate transport strategy
+- **transport**: compute (network) loss rate per second
+- **libhicnctrl**: remove connection used to send commands
+- **libhicnctrl**: Add support for serialization of connection and subscription removal commands
+- **notification**: add notification processing
+- **notification**: update libhicnctrl to support notifications
+- **notification**: add retrieval of connections for a subscription
+- **strategy**: code style
+- **strategy**: add comment to log the issue with sendto
+- **strategy**: add test for probe generator
+- **strategy**: send probes at each interest
+- **strategy**: use batching mode to send probes
+- **strategy**: improve probing phase
+- **stategy**: improve probing in best path strategy
+- **stats**: Put additional stats and improve debug prints
+- **subscription**: Add support for subscribe/unsubscribe
+- **vector**: Add remove operation in vector
+- **forwarder**: Enable daemon mode in forwarder
+- **fec**: add metadata support to reedsolomon.
+
+### Fix
+
+- **Jenkinsfile**: change arch from x86_64 to amd64
+- fix build errors
+- GCC11 fixes and workarounds
+- **transport**: keep track of skipped interests
+- **transport**: count as lost the fec packets that are not recevied
+- **transport**: fix check to increase highest seq in order
+- **transport**: fix loss rate counters
+- select latest version of pipelines library
+- **addresses**: fix ipv6 addresses creation for listeners and connections
+- restore previous cmake submodule reference
+- fix circular dependency
+- **connection**: fix bug in connection name generation
+- set version of jenkins shared library to stable version #promote PATCH
+- use hicn as image name in all scripts #promote 2.9
+- **docker-gcc**: docker build script fails if env variables don't exist
+- use hicn as image name in all scripts #promote 2.9
+- Fix memory leakages and unreleased msgbufs in batch read
+- **vector**: fix bug on vector reallocation and add related test
+- **portal.h**: improve handling of unknown packet formats in libtransport.
+- **packet-cache**: Check if data received from the expected interface
+- **msgbuf-pool**: Fix release of msgbufs (after queue is emptied)
+- **pit-entry**: Reset nexthops during pit entry creation
+- Fix socket cleanup when receiving ack/nack
+- **strategy**: Fix symbol not found in libhicn
+- **forwarder**: Remove unused buffer allocations in release mode
+- **command**: Fix connection parsing in connection list command
+- **functional-tests**: Fix functional tests for hicn-light
+- **mapme**: fix nexthop slection on mapme update
+- **bitmap**: Fix bitmap set operation
+- **fib_entry**: code style
+- **fib_entry**: reset nexthop len if no local face is found
+- Use msgbuf ids instead of msgbuf pointers
+- start jenkins job
+
+### Perf
+
+- **RTX**: reduce wainting time for RTX in low rate flows
+
+## v2.9.6 (2021-11-18)
+
+### Fix
+
+- **Jenkinsfile**: change threshold test limits
+- **Packaging.cmake**: vpp deb dependency version is wrong
+
+## v2.9.5 (2021-11-17)
+
+### Fix
+
+- **Jenkinsfile**: change arch from x86_64 to amd64
+
+## v2.9.4 (2021-11-11)
+
+### Feat
+
+- **cmake**: update version of cmake
+- **cmake**: update version of cmake
+
+## v2.9.3 (2021-11-11)
+
+### Feat
+
+- add dockerfile for development
+
+## v2.9.2 (2021-11-10)
+
+### Fix
+
+- fix circular dependency #promote PATCH
+
+## v2.9.1 (2021-11-09)
+
+### Fix
+
+- set version of jenkins shared library to stable version #promote PATCH
+
+## v2.9.0 (2021-11-09)
+
+### Fix
+
+- use hicn as image name in all scripts #promote 2.9
+- **docker-gcc**: docker build script fails if env variables don't exist
+- use hicn as image name in all scripts #promote 2.9
+- start jenkins job
+- **README**: remove white spaces #promote 2.9 Signed-off-by: Angelo Mantellini <manangel@cisco.com>
+- **transport**: comment
+- **transport**: remove fec packets from pending interests
+- **transport**: do not use nacks to compute the avg RTT
+- **promote-2.9**: promote 2.9
+- **versions.cmake**: wrong dep versions
+- **Dockerfile-gcc**: pass branch name env variable to dockerfile
+- **cmake**: create packages with right version name and repo name corrected
+- **libconfig**: correct libconfig version
+- ICN-1047, adding Android support for hc_sock_create_forwarder
+- **libhicnctrl**: unused file descriptor was closed when freeing the libhicnctrl socket.
+- **vapi_safe**: groupp all vapi msg ids definitions under vapi_safe.c
+- **libhicnctrl**: initialize all the fields of the struct hc_data_t during instantiation.
+- **libhicnctrl**: fix initialization of vpp_vapi.
+- **libhicnctrl**: Update libhicnctrl from new forwarder
+- **portal.h**: improve handling of unknown packet formats in libtransport.
+- **rc.cc**: fix error in reed solomon fec when passing packets back to caller.
+- publish unit test reports for all tests executables
+- cleanup redundant file
+- **libhicnctrl**: add missing face.c to libhicnctrl source files
+- **Jenkinsfile**: fix version of jenkins shared library
+- **auth**: include fec header in packet signature
+- **CmakeLists.txt**: fix install path of projects.
+- **vpp-memif.yaml**: fix IPv6 memif connection between 2 VPPs involved in test.
+- **hicn-plugin**: include vapi source code in src and includes folders.
+- **cmake**: Fetch submodule containing modules as first action in root CMakeLists.txt
+
+### Feat
+
+- **add-build-number-to-deb-package-name**: Ref: SPT-759 Add build number to deb package name, if defined #promote 2.9
+- **versions.cmake**: correct versions of deps
+- **trasnport**: comment on RTT update
+- **trasnport**: keep prev rtt in case of no available samples
+- **trasnport**: remove moving avg from residual loss rate
+- **transport**: add avg rtt
+- create deb packages
+- upgrade to new pipelines library version
+- upgrade to new pipelines library version
+- **fec**: add metadata support to reedsolomon.
+- **Jenkinsfile**: Add robot threshold configuration.
+
+## v1.0.0 (2021-11-05)
+
+### Feat
+
+- **versions.cmake**: correct versions of deps
+- **trasnport**: comment on RTT update
+- **trasnport**: keep prev rtt in case of no available samples
+- **trasnport**: remove moving avg from residual loss rate
+- **transport**: add avg rtt
+- create deb packages
+- upgrade to new pipelines library version
+- upgrade to new pipelines library version
+- **fec**: add metadata support to reedsolomon.
+- **Jenkinsfile**: Add robot threshold configuration.
+
+### Fix
+
+- **versions.cmake**: wrong dep versions
+- **Dockerfile-gcc**: pass branch name env variable to dockerfile
+- **cmake**: create packages with right version name and repo name corrected
+- **libconfig**: correct libconfig version
+- ICN-1047, adding Android support for hc_sock_create_forwarder
+- **libhicnctrl**: unused file descriptor was closed when freeing the libhicnctrl socket.
+- **vapi_safe**: groupp all vapi msg ids definitions under vapi_safe.c
+- **libhicnctrl**: initialize all the fields of the struct hc_data_t during instantiation.
+- **libhicnctrl**: fix initialization of vpp_vapi.
+- **libhicnctrl**: Update libhicnctrl from new forwarder
+- **portal.h**: improve handling of unknown packet formats in libtransport.
+- **rc.cc**: fix error in reed solomon fec when passing packets back to caller.
+- publish unit test reports for all tests executables
+- cleanup redundant file
+- **libhicnctrl**: add missing face.c to libhicnctrl source files
+- **Jenkinsfile**: fix version of jenkins shared library
+- **auth**: include fec header in packet signature
+- **CmakeLists.txt**: fix install path of projects.
+- **vpp-memif.yaml**: fix IPv6 memif connection between 2 VPPs involved in test.
+- **hicn-plugin**: include vapi source code in src and includes folders.
+- **cmake**: Fetch submodule containing modules as first action in root CMakeLists.txt
+
+## v21.06-rc0 (2021-07-20)
+
+## v21.01-rc0 (2021-02-10)
+
+## v20.05-release (2020-11-11)
+
+## v20.01 (2020-01-30)
+
+## v19.08 (2019-08-14)
+
+## v19.04 (2019-04-29)
+
+## v19.01 (2019-01-25)
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8ad59c81d..26783d544 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,15 +11,85 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
+##############################################################
+# Compiler preferences
+##############################################################
+set(CMAKE_C_COMPILER_NAMES
+ clang-13
+ clang-12
+ clang-11
+ clang-10
+ clang-9
+ gcc-10
+ gcc-9
+ cc
+)
+
+set(CMAKE_CXX_COMPILER_NAMES
+ clang++-13
+ clang++-12
+ clang++-11
+ clang++-10
+ clang++-9
+ g++-10
+ g++-9
+ c++
+)
+
+##############################################################
+# Project and cmake version
+##############################################################
+cmake_minimum_required(VERSION 3.11 FATAL_ERROR)
project(hicn-fdio)
+##############################################################
+# Fetch submodules if needed
+##############################################################
+find_package(Git QUIET)
+if(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git")
+ # Update submodules as needed
+ option(GIT_SUBMODULE "Check submodules during build" ON)
+ if(GIT_SUBMODULE)
+ message(STATUS "Submodule update")
+ execute_process(
+ COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ RESULT_VARIABLE GIT_SUBMOD_RESULT
+ )
+
+ if(NOT GIT_SUBMOD_RESULT EQUAL "0")
+ message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
+ endif()
+ endif()
+endif()
+
+if(NOT EXISTS "${PROJECT_SOURCE_DIR}/cmake/Modules")
+ message(
+ FATAL_ERROR
+ "The submodules were not downloaded! GIT_SUBMODULE was turned off or failed. Please update submodules and try again."
+ )
+endif()
+
+##############################################################
+# CMake Modules
+##############################################################
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules")
+if(EXISTS "${PROJECT_SOURCE_DIR}/internal/cmake/Modules")
+ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/internal/cmake/Modules")
+ set(INTERNAL_ENVIRONMENT True)
+endif()
+include("${CMAKE_CURRENT_SOURCE_DIR}/versions.cmake")
+list(GET VPP_DEFAULT_VERSION 0 VPP_DEFAULT_VERSION)
+set(PREFIX_VERSION "${VPP_DEFAULT_VERSION}")
+string(REPLACE "-" ";" PREFIX_VERSION ${PREFIX_VERSION})
+list (GET PREFIX_VERSION 0 PREFIX_VERSION)
-set_property(GLOBAL PROPERTY USE_FOLDERS ON)
+include(CommonSetup)
-## Enabled components
+##############################################################
+# Enabled components
+##############################################################
option(BUILD_LIBHICN "Build the hicn core library" ON)
option(BUILD_HICNLIGHT "Build the hicn light forwarder" ON)
option(BUILD_LIBTRANSPORT "Build the hicn transport library" ON)
@@ -32,22 +102,20 @@ else ()
option(DISABLE_SHARED_LIBRARIES "Disable shared libraries" ON)
endif ()
option(BUILD_HICNPLUGIN "Build the hicn vpp plugin" OFF)
-option(BUILD_SYSREPOPLUGIN "Build the sysrepo plugin" OFF)
option(BUILD_EXTRAS "Build external projects" OFF)
option(BUILD_TELEMETRY "Build telemetry projects" OFF)
option(BUILD_TESTS "Build unit tests" OFF)
option(DISABLE_EXECUTABLES "Disable executables" OFF)
+
+##############################################################
+# Basic sanity checks
+##############################################################
if (BUILD_APPS AND NOT BUILD_LIBTRANSPORT)
message(STATUS "Libhicntransport required. Enabled by default.")
set (BUILD_LIBTRANSPORT ON)
endif()
-if (BUILD_SYSREPOPLUGIN AND NOT BUILD_HICNPLUGIN)
- message(STATUS "Hicn-plugin required. Enabled by default.")
- set (BUILD_HICNPLUGIN ON)
-endif()
-
if ((BUILD_HICNLIGHT OR
BUILD_LIBTRANSPORT OR
BUILD_APPS OR
@@ -61,9 +129,9 @@ endif()
list(APPEND dir_options
BUILD_LIBHICN
- BUILD_HICNLIGHT
BUILD_HICNPLUGIN
BUILD_CTRL
+ BUILD_HICNLIGHT
BUILD_LIBTRANSPORT
BUILD_APPS
BUILD_SYSREPOPLUGIN
@@ -77,11 +145,13 @@ set(BUILD_LIBTRANSPORT_DIR libtransport)
set(BUILD_APPS_DIR apps)
set(BUILD_CTRL_DIR ctrl)
set(BUILD_HICNPLUGIN_DIR hicn-plugin)
-set(BUILD_SYSREPOPLUGIN_DIR ctrl/sysrepo-plugins)
set(BUILD_EXTRAS_DIR extras/)
set(BUILD_TELEMETRY_DIR telemetry)
-## Add enabled components
+
+##############################################################
+# Add enabled components to the build
+##############################################################
foreach (opt ${dir_options})
if (${opt})
list(APPEND subdirs
@@ -90,7 +160,10 @@ foreach (opt ${dir_options})
endif()
endforeach()
-# Add unit tests
+
+##############################################################
+# Build gtest if tests are enabled
+##############################################################
if (BUILD_TESTS)
message(STATUS "Tests enabled.")
include (GTestImport)
@@ -105,10 +178,10 @@ endif()
message(STATUS "Building the following subprojects: ${subdirs}")
foreach(dir ${subdirs})
+ pr_title("Subproject" "${dir}")
add_subdirectory(${dir})
endforeach()
add_subdirectory(docs/doxygen)
-include(Packager)
-make_packages() \ No newline at end of file
+make_packages()
diff --git a/Dockerfile.dev b/Dockerfile.dev
new file mode 100644
index 000000000..ad7f99785
--- /dev/null
+++ b/Dockerfile.dev
@@ -0,0 +1,33 @@
+FROM ubuntu:focal
+ENV DEBIAN_FRONTEND=noninteractive
+WORKDIR /hicn-build
+
+ARG USERNAME=ubuntu
+ARG USER_UID=1000
+ARG USER_GID=${USER_UID}
+
+COPY Makefile versions.cmake ./
+COPY scripts scripts/
+
+USER root
+
+RUN apt update && apt-get install -y \
+ make \
+ sudo \
+ curl \
+ valgrind \
+ git \
+ zsh
+
+RUN make deps debug-tools
+
+# Add non-root user
+RUN groupadd --gid ${USER_GID} ${USERNAME} && \
+ useradd -s /bin/bash --uid ${USER_UID} --gid ${USER_GID} -m ${USERNAME} && \
+ echo ${USERNAME} ALL=\(root\) NOPASSWD:ALL >/etc/sudoers.d/${USERNAME} && \
+ chmod 0440 /etc/sudoers.d/${USERNAME}
+
+USER ${USERNAME}
+WORKDIR /home/${USERNAME}
+
+ENV DEBIAN_FRONTEND=
diff --git a/INFO.yaml b/INFO.yaml
index 30a00f793..681336975 100644
--- a/INFO.yaml
+++ b/INFO.yaml
@@ -8,7 +8,6 @@ project_lead: &hicn_ptl
email: 'lumuscar+fdio@cisco.com'
id: 'muscariello'
company: 'Cisco'
- timezone: ''
primary_contact: *hicn_ptl
issue_tracking:
type: 'jira'
@@ -38,12 +37,10 @@ committers:
company: 'Cisco'
email: 'acompagn+fdio@cisco.com'
id: 'acompagn'
- timezone: ''
- name: 'Jordan Augé'
company: 'Cisco'
email: 'jordan.auge+fdio@cisco.com'
id: 'jordan.auge'
- timezone: ''
- name: 'Michele Papalini'
company: 'Cisco'
email: 'micpapal+fdio@cisco.com'
@@ -56,12 +53,14 @@ committers:
company: 'Cisco'
email: 'jsamain+fdio@cisco.com'
id: 'jsamain'
- timezone: ''
- name: 'Angelo Mantellini'
company: 'Cisco'
email: 'manangel@cisco.com'
id: 'manang'
- timezone: ''
+ - name: 'Olivier Roques'
+ company: 'Cisco'
+ email: 'oroques+fdio@cisco.com'
+ id: 'oroques'
tsc:
# yamllint disable rule:line-length
approval: ''
diff --git a/Makefile b/Makefile
new file mode 100644
index 000000000..6c3f9617a
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,279 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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.
+
+
+export WS_ROOT=$(CURDIR)
+SHELL := /bin/bash
+FUNCTIONAL := tests/run-functional.sh
+MKDIR := mkdir -p
+RM := rm
+VERSIONFILE := $(CURDIR)/versions.cmake
+COMMIT_TEMPLATE_FILE = .git_commit_template.txt
+
+# Docker stuff
+DOCKER := docker
+DEV_IMAGE := hicn-dev-img
+DOCKERFILE := Dockerfile.dev
+DEV_CONTAINER := hicn-dev
+
+#
+# OS Detection
+#
+ifeq ($(shell uname),Darwin)
+OS_ID = macos
+OPENSSL_ROOT=/usr/local/opt/openssl@1.1
+else
+OS_ID = $(shell grep '^ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g')
+OS_VERSION_ID = $(shell grep '^VERSION_ID=' /etc/os-release | cut -f2- -d= | sed -e 's/\"//g')
+endif
+
+#
+# Git Repo detection
+#
+GIT_INFO = $(shell git -C . rev-parse 2>/dev/null; echo $$?)
+
+ifeq ($(shell uname),Darwin)
+BUILD_HICNPLUGIN := OFF
+PUNTING := OFF
+else
+BUILD_HICNPLUGIN := ON
+PUNTING := ON
+endif
+
+DEB_DEPENDS = cmake ninja-build unzip python3-ply libasio-dev
+DEB_DEPENDS += libconfig-dev libconfig++-dev libevent-dev
+DEB_DEPENDS += llvm-11-tools llvm-11 clang-11 vpp-dev libvppinfra-dev
+DEB_DEPENDS += vpp-plugin-core libcurl4-openssl-dev libssl-dev
+DEB_DEPENDS += doxygen
+
+DEBUG_DEPENDS = iproute2 iperf3 iputils-ping tcpdump gdb
+
+MACOS_DEPENDS = asio libconfig ninja openssl@1.1
+
+.PHONY = help
+help:
+ @echo "Targets"
+ @echo " dep - install software dependencies"
+ @echo " debug-tools - install debug dependencies"
+ @echo " build - build debug binaries. Optional argument: INSTALL_DIR"
+ @echo " build-release - build release binaries"
+ @echo " build-coverage - build with coverage metainformation"
+ @echo " wipe - wipe debug binaries"
+ @echo " wipe-release - wipe release binaries"
+ @echo " docs - build documentation"
+ @echo ""
+ @echo "Make Arguments:"
+ @echo " INSTALL_PREFIX=<path> - Install software at specified location."
+ @echo " BUILD_PATH=<path> - Path of build folder."
+ @echo " VPP_HOME=<path> - Path of VPP"
+ @echo " OPENSSL_ROOT=<path> - Path of Openssl installation"
+ @echo " ENABLE_RELY=<ON/OFF> - Enable/disable rely compilation"
+ @echo " SONAR_BUILD_WRAPPER=<path>" - Path of sonarqube build wrapper
+ @echo " SONAR_OUT_DIR=<path>" - Path of directory of sonarqube report
+ @echo "Current Arguments:"
+ @echo " INSTALL_PREFIX=$(INSTALL_PREFIX)"
+ @echo " VPP_HOME=$(VPP_HOME)"
+ @echo " OPENSSL_ROOT=$(OPENSSL_ROOT)"
+ @echo " ENABLE_RELY=$(ENABLE_RELY)"
+ @echo " SONAR_BUILD_WRAPPER=$(SONAR_BUILD_WRAPPER)"
+ @echo " SONAR_OUT_DIR=$(SONAR_OUT_DIR)"
+
+.PHONY = commit-template
+commit-template:
+ifeq ($(GIT_INFO),0)
+ git config commit.template $(COMMIT_TEMPLATE_FILE)
+endif
+
+.PHONY = vpp-dep
+vpp-dep:
+ VERSION_PATH=$(VERSIONFILE) sudo -E $(SHELL) scripts/install-vpp.sh
+
+.PHONY = dep
+dep: vpp-dep
+ifeq ($(shell uname),Darwin)
+ brew install $(MACOS_DEPENDS)
+else ifeq ($(filter ubuntu debian,$(OS_ID)),$(OS_ID))
+ @sudo -E apt-get update
+ @sudo -E apt-get $(APT_ARGS) -y install $(DEB_DEPENDS) --no-install-recommends
+else
+ @echo "Operating system not supported (yet)"
+endif
+
+.PHONY = deps
+deps: dep
+
+.PHONY = debug-tools
+debug-tools:
+ @sudo -E apt-get $(APT_ARGS) -y install $(DEBUG_DEPENDS) --no-install-recommends
+
+define build_folder
+ $(eval LOWER_BUILDTYPE=$(shell echo $(2) | tr A-Z a-z))
+ $(eval BUILD_FOLDER=$(or $(BUILD_PATH), $(WS_ROOT)/build-$(LOWER_BUILDTYPE)-$(OS_ID)))
+ $(1) := $$(BUILD_FOLDER)
+endef
+
+define install_folder
+ $(eval LOWER_BUILDTYPE=$(shell echo $(2) | tr A-Z a-z))
+ $(eval INSTALL_FOLDER=$(or $(INSTALL_PREFIX), $(WS_ROOT)/install-$(LOWER_BUILDTYPE)))
+ $(1) := $$(INSTALL_FOLDER)
+endef
+
+define configure
+ $(eval $(call build_folder,BUILD_FOLDER,$(1)))
+ $(eval PREFIX=$(or $(INSTALL_PREFIX), $(WS_ROOT)/install-$(LOWER_BUILDTYPE)))
+ $(eval COVERAGE=$(or $(COVERAGE), OFF))
+ $(eval VPP_HOME=$(or $(VPP_HOME), /usr))
+ $(eval ENABLE_RELY=$(or $(ENABLE_RELY), OFF))
+ $(MKDIR) $(BUILD_FOLDER)
+ cmake \
+ -B $(BUILD_FOLDER) \
+ -S $(WS_ROOT) \
+ -G Ninja \
+ -DCMAKE_INSTALL_PREFIX=$(PREFIX) \
+ -DCMAKE_BUILD_TYPE=$(1) \
+ -DBUILD_HICNLIGHT=ON \
+ -DBUILD_APPS=ON \
+ -DBUILD_SYSREPOPLUGIN=OFF \
+ -DBUILD_EXTRAS=OFF \
+ -DBUILD_TELEMETRY=OFF \
+ -DBUILD_CTRL=ON \
+ -DBUILD_HICNPLUGIN=$(BUILD_HICNPLUGIN) \
+ -DVPP_HOME=$(VPP_HOME) \
+ -DCOVERAGE=$(COVERAGE) \
+ -DENABLE_RELY=$(ENABLE_RELY) \
+ -DOPENSSL_ROOT_DIR=$(OPENSSL_ROOT) \
+ -DBUILD_TESTS=ON
+endef
+
+define install
+ $(eval $(call build_folder,BUILD_FOLDER,$(1)))
+ cmake --build $(BUILD_FOLDER) -- -j 4 install
+endef
+
+define build
+ $(eval $(call build_folder,BUILD_FOLDER,$(1)))
+ cmake --build $(BUILD_FOLDER) -- -j 4
+endef
+
+define build_coverage
+ $(eval $(call build_folder,BUILD_FOLDER,$(1)))
+ $(eval SONAR_OUT_DIR=$(or $(SONAR_OUT_DIR), $(WS_ROOT)/sonarqube-output))
+ $(SONAR_BUILD_WRAPPER) --out-dir $(SONAR_OUT_DIR) cmake --build $(BUILD_FOLDER) -- install
+endef
+
+define package
+ $(eval $(call build_folder,BUILD_FOLDER,$(1)))
+ cmake --build $(BUILD_FOLDER) -- package
+endef
+
+.PHONY: configure-debug
+configure-debug:
+ $(call configure,Debug,)
+
+.PHONY: configure-release
+configure-release:
+ $(call configure,Release,)
+
+.PHONY = build
+build: configure-debug
+ $(call build,Debug,)
+
+.PHONY = build-coverage
+build-coverage:
+ifndef SONAR_BUILD_WRAPPER
+ $(error SONAR_BUILD_WRAPPER is not set)
+endif
+ $(eval COVERAGE := ON)
+ $(call configure,Debug,)
+ $(call build_coverage,Debug,)
+
+.PHONY = build-release
+build-release: configure-release
+ $(call build,Release,)
+
+.PHONY = package
+package: build
+ $(call package,Debug,)
+
+.PHONY = package-release
+package-release: build-release
+ $(call package,Release,)
+
+.PHONY = install
+install: build
+ $(call install,Debug,)
+
+.PHONY = install-release
+install-release: build-release
+ $(call install,Release,)
+
+define wipe
+ $(eval $(call build_folder,BUILD_FOLDER,$(1)))
+ $(eval $(call install_folder,INSTALL_FOLDER,$(1)))
+ $(RM) -rf $(BUILD_FOLDER)
+ $(RM) -rf $(INSTALL_FOLDER)
+endef
+
+.PHONY = wipe
+wipe:
+ $(call wipe,Debug,)
+
+.PHONY = wipe-release
+wipe-release:
+ $(call wipe,Release,)
+
+define test
+ $(eval $(call build_folder,BUILD_FOLDER,$(1)))
+ cmake --build $(BUILD_FOLDER) -- test
+endef
+
+.PHONY = test-debug
+test-debug: build
+ $(call test, Debug,)
+
+.PHONY = test
+test: build-release
+ $(call test, Release,)
+
+.PHONY = functional
+functional:
+ $(SHELL) $(FUNCTIONAL)
+
+define documentation
+ python3 -m pip install --user virtualenv
+ python3 -m virtualenv env
+ (source $(WS_ROOT)/env/bin/activate; \
+ pip install -r $(WS_ROOT)/docs/etc/requirements.txt; \
+ cd docs; \
+ make html )
+endef
+
+.PHONY = doc
+doc:
+ $(call documentation,)
+
+
+.PHONY = docker
+docker:
+ $(DOCKER) build -t $(DEV_IMAGE) -f $(DOCKERFILE) ${PWD}
+ifeq ($(strip $(shell $(DOCKER) ps -q -f name=$(DEV_CONTAINER))),)
+ifneq ($(shell $(DOCKER) ps -aq -f status=exited -f name=$(DEV_CONTAINER)),)
+ docker rm $(DEV_CONTAINER)
+endif
+ $(DOCKER) run -dv ${PWD}:/workspace -w /workspace --name $(DEV_CONTAINER) --entrypoint=tail $(DEV_IMAGE) -f /dev/null
+endif
+ $(DOCKER) exec -it $(DEV_CONTAINER) bash
+
+.PHONY = wipe-docker
+wipe-docker:
+ $(DOCKER) rm --force $(DEV_CONTAINER)
diff --git a/README.md b/README.md
index 4ddd78fcf..98f57d61c 100644
--- a/README.md
+++ b/README.md
@@ -2,10 +2,13 @@
## Introduction
-hicn is an open source implementation of Cisco's hICN. It includes a network stack, that implements
-ICN forwarding path in IPv6, and a transport stack that implements two main transport protocols and
-a socket API. The transport protocols provide one reliable transport service implementation and a
-real-time transport service for audio/video media.
+This is an open source implementation of Cisco's hICN. It includes a network
+stack, that implements ICN forwarding path in IPv6, and a transport stack that
+implements reliable and unrelieable transport with congestion control and loss
+management by ARQ or FEC. It supports applications such as reliable multicast
+for ABR video, real-time video conferencing and on-line multiplayer games.
+The client stack has been tested on iOS and Android over Wi-Fi, LTE and Ethernet
+including multi-homing use cases.
## Directory layout
@@ -15,29 +18,27 @@ real-time transport service for audio/video media.
| hicn-plugin | VPP plugin |
| hicn-light | Lightweight packet forwarder |
| libtransport | Support library with transport layer and API |
-| utils | Tools for testing |
-| apps | Application examples using hicn stack |
+| apps | Application examples using hicn stack and tools |
| ctrl | Tools and libraries for network configuration and control |
-hicn plugin is a VPP plugin that implement hicn packet processing as specified in
-https://datatracker.ietf.org/doc/draft-muscariello-intarea-hicn/. The transport library is used to
-implement the hicn host stack and makes use of libmemif as high performance connector between
-transport and the network stack. The transport library makes use of VPP binary API to configure the
-local namespace (local face management).
+hicn plugin is a VPP plugin that implement hicn packet processing as specified
+in https://datatracker.ietf.org/doc/draft-muscariello-intarea-hicn/. The
+transport library is used to implement the hicn host stack and makes use of
+libmemif as high performance connector between transport and the network stack.
+The transport library makes use of VPP binary API to configure the local
+namespace (local face management).
## Supported platforms
-- Ubuntu 16.04 LTS (amd64)
-- Ubuntu 18.04 LTS (amd64, arm64)
-- CentOS 7 (x86_64)
-- Android 10
-- iOS 13
-- macOS 10.15
-- Windows 10
+- Ubuntu 20.04 LTS (amd64, arm64)
+- Android 10+
+- iOS 13+
+- macOS 10.15+
+- Windows 10+
## Binaries
-### Ubuntu 16/18 (amd64) and CentOS 7 (x86_64)
+### Ubuntu (amd64, arm64)
<https://packagecloud.io/fdio/release>
@@ -45,17 +46,12 @@ local namespace (local face management).
<https://hub.docker.com/u/icnteam>
-### Vagrant
-
-<https://app.vagrantup.com/icnteam/>
-
### Release note
-The current master branch provides the latest release which is compatible with the latest VPP stable.
-No other VPP releases are supported nor maintained. At every new VPP release distribution hicn
-master branch is updated to work with the latest stable release. All previous stable releases
-are discontinued and not maintained. The user who is interested in a specific release can always
-checkout the right code tree by searching the latest commit under a given git tag carrying the
-release version.
-
-
+The current master branch provides the latest release which is compatible with
+the latest VPP stable. No other VPP releases are supported nor maintained. At
+every new VPP release distribution hicn master branch is updated to work with
+the latest stable release. All previous stable releases are discontinued and not
+maintained. The user who is interested in a specific release can always checkout
+the right code tree by searching the latest commit under a given git tag
+carrying the release version.
diff --git a/apps/.clang-format b/apps/.clang-format
index cd21e2017..adc73c6fd 100644
--- a/apps/.clang-format
+++ b/apps/.clang-format
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2021 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/apps/CMakeLists.txt b/apps/CMakeLists.txt
index df1b9fc7c..b58e18f03 100644
--- a/apps/CMakeLists.txt
+++ b/apps/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,37 +11,67 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Project and cmake version
+##############################################################
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-set(CMAKE_CXX_STANDARD 14)
-
project(apps)
+
+##############################################################
+# C Standard
+##############################################################
+set(CMAKE_CXX_STANDARD 17)
+
+
+##############################################################
+# Cmake modules
+##############################################################
+include("${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake")
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
- "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
+ ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules
)
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
-endif ()
-
-include(BuildMacros)
-include(WindowsMacros)
+##############################################################
+# Libs and Bins names
+##############################################################
set(HICN_APPS hicn-apps CACHE INTERNAL "" FORCE)
+set(HIGET higet)
+set(HTTP_PROXY hicn-http-proxy)
+set(LIBHTTP_PROXY hicnhttpproxy)
+set(LIBHTTP_PROXY_STATIC ${LIBHTTP_PROXY}.static)
+
+##############################################################
+# Dependencies and third party libs
+##############################################################
find_package(Threads REQUIRED)
-find_package(Libconfig++ REQUIRED)
+find_package(Libconfig++ ${LIBCONFIG_DEFAULT_VERSION} REQUIRED)
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- find_package(Libtransport REQUIRED)
- find_package(Libhicn REQUIRED)
- find_package(hicnctrl REQUIRED)
+ include(CommonSetup)
+
+ find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
+ find_package(Libhicnctrl ${CURRENT_VERSION} REQUIRED NO_MODULE)
+ find_package(Libhicntransport ${CURRENT_VERSION} REQUIRED NO_MODULE)
+
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
+
+ list(APPEND LIBHICN_LIBRARIES hicn::hicn.${LIBTYPE})
+ list(APPEND LIBTRANSPORT_LIBRARIES hicn::hicntransport.${LIBTYPE})
+ list(APPEND LIBHICNCTRL_LIBRARIES hicn::hicnctrl.${LIBTYPE})
else()
if (DISABLE_SHARED_LIBRARIES)
- find_package(OpenSSL REQUIRED)
+ find_package(OpenSSL ${OPENSSL_DEFAULT_VERSION} REQUIRED)
set(LIBTRANSPORT_LIBRARIES ${LIBTRANSPORT_STATIC})
set(LIBHICN_LIBRARIES ${LIBHICN_STATIC})
set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_STATIC})
@@ -54,22 +84,33 @@ else()
list(APPEND DEPENDENCIES
${LIBTRANSPORT_LIBRARIES}
)
-endif()
-if (WIN32)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4200 /wd4996")
-endif ()
+ # glog
+ list(APPEND THIRD_PARTY_INCLUDE_DIRS
+ ${glog_BINARY_DIR}
+ ${glog_SOURCE_DIR}/src
+ )
+ list(APPEND THIRD_PARTY_DEPENDENCIES
+ glog
+ )
-include(Packaging)
+ set(COMMON_INCLUDE_DIRS
+ ${CMAKE_CURRENT_SOURCE_DIR}/common-includes
+ )
+endif()
-add_subdirectory(ping)
-add_subdirectory(hiperf)
-set(HIGET higet)
-set(HTTP_PROXY hicn-http-proxy)
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
-if (NOT WIN32)
- add_subdirectory(http-proxy)
-endif ()
+##############################################################
+# Subdirectories
+##############################################################
+add_subdirectory(ping)
+add_subdirectory(hiperf)
+add_subdirectory(http-proxy)
add_subdirectory(higet)
diff --git a/apps/cmake/Modules/Packaging.cmake b/apps/cmake/packaging.cmake
index 981eb728e..9142598ad 100644
--- a/apps/cmake/Modules/Packaging.cmake
+++ b/apps/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -18,21 +18,34 @@ useful for testing and debugging within a hicn network."
)
set(${HICN_APPS}_DEB_DEPENDENCIES
- "lib${LIBTRANSPORT} (>= stable_version), lib${LIBHICNCTRL} (>= stable_version)"
+ "lib${LIBTRANSPORT} (= stable_version), lib${LIBHICNCTRL} (= stable_version)"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${HICN_APPS}-dev_DEB_DEPENDENCIES
- "${HICN_APPS} (>= stable_version), lib${LIBTRANSPORT}-dev (>= stable_version), lib${LIBHICNCTRL}-dev (>= stable_version)"
+ "${HICN_APPS} (= stable_version), lib${LIBTRANSPORT}-dev (= stable_version), lib${LIBHICNCTRL}-dev (= stable_version)"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${HICN_APPS}_RPM_DEPENDENCIES
- "lib${LIBTRANSPORT} >= stable_version, lib${LIBHICNCTRL} >= stable_version"
+ "lib${LIBTRANSPORT} = stable_version, lib${LIBHICNCTRL} = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${HICN_APPS}-dev_RPM_DEPENDENCIES
- "${HICN_APPS} >= stable_version, lib${LIBTRANSPORT}-dev >= stable_version, lib${LIBHICNCTRL}-dev >= stable_version"
+ "${HICN_APPS} = stable_version, lib${LIBTRANSPORT}-dev = stable_version, lib${LIBHICNCTRL}-dev = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
-) \ No newline at end of file
+)
+
+if (INTERNAL_ENVIRONMENT)
+ include(CheckSsl)
+ CheckSsl()
+ set(${HICN_APPS}_DEB_DEPENDENCIES
+ "${${HICN_APPS}_DEB_DEPENDENCIES}, ${OPENSSL_DEPENDENCY}"
+ CACHE STRING "Dependencies for deb/rpm package."
+ )
+ set(${HICN_APPS}-dev_DEB_DEPENDENCIES
+ "${${HICN_APPS}-dev_DEB_DEPENDENCIES}, ${OPENSSL_DEPENDENCY_DEV}"
+ CACHE STRING "Dependencies for deb/rpm package."
+ )
+endif () \ No newline at end of file
diff --git a/apps/common-includes/hicn/apps/utils/logger.h b/apps/common-includes/hicn/apps/utils/logger.h
new file mode 100644
index 000000000..d2af988d9
--- /dev/null
+++ b/apps/common-includes/hicn/apps/utils/logger.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <glog/logging.h>
+
+#include <iostream>
+
+#define LoggerInfo() LOG(INFO)
+#define LoggerWarn() LOG(WARNING)
+#define LoggerErr() LOG(ERROR)
+#define LoggerFatal() LOG(FATAL)
+#define LoggerVerbose(level) VLOG((level))
+#define LoggerIsOn(level) VLOG_IS_ON((level))
+
+struct HicnLogger {
+ HicnLogger() {
+ // Set log level
+ const char *log_level = std::getenv("LOG_LEVEL");
+ if (log_level != nullptr) FLAGS_v = std::stol(std::string(log_level));
+
+ // Enable/disable prefix
+ const char *enable_log_prefix = std::getenv("ENABLE_LOG_PREFIX");
+ if (enable_log_prefix != nullptr &&
+ std::string(enable_log_prefix) == "OFF") {
+ FLAGS_log_prefix = false;
+ }
+
+ FLAGS_colorlogtostderr = true;
+ }
+};
+
+static HicnLogger logger; \ No newline at end of file
diff --git a/apps/higet/CMakeLists.txt b/apps/higet/CMakeLists.txt
index 8d112d3a3..791191872 100644
--- a/apps/higet/CMakeLists.txt
+++ b/apps/higet/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,43 +11,50 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-set(CMAKE_CXX_STANDARD 14)
-
-project(utils)
-
-find_package(Threads REQUIRED)
-
-set(CMAKE_MODULE_PATH
- ${CMAKE_MODULE_PATH}
- "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
-)
-
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
-endif ()
-
+##############################################################
+# Source files
+##############################################################
list(APPEND APPS_SRC
higet.cc
)
+
+##############################################################
+# Linker flags
+##############################################################
if (WIN32)
- set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:\"LIBCMT\"" )
+ set(CMAKE_EXE_LINKER_FLAGS
+ "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:\"LIBCMT\""
+ )
endif()
+
+##############################################################
+# Compiler options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Build higet
+##############################################################
if (NOT DISABLE_EXECUTABLES)
build_executable(${HIGET}
SOURCES ${APPS_SRC}
LINK_LIBRARIES
+ ${LIBHICN_LIBRARIES}
${LIBTRANSPORT_LIBRARIES}
${CMAKE_THREAD_LIBS_INIT}
${WSOCK32_LIBRARY}
${WS2_32_LIBRARY}
- DEPENDS ${LIBTRANSPORT_LIBRARIES}
+ INCLUDE_DIRS
+ PRIVATE ${THIRD_PARTY_INCLUDE_DIRS} ${COMMON_INCLUDE_DIRS}
+ DEPENDS ${LIBTRANSPORT_LIBRARIES} ${THIRD_PARTY_DEPENDENCIES}
COMPONENT ${HICN_APPS}
DEFINITIONS ${COMPILER_DEFINITIONS}
LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
endif ()
diff --git a/apps/higet/higet.cc b/apps/higet/higet.cc
index 9ae869731..77cbb52d2 100644
--- a/apps/higet/higet.cc
+++ b/apps/higet/higet.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,26 +13,20 @@
* limitations under the License.
*/
+#include <hicn/apps/utils/logger.h>
#include <hicn/transport/http/client_connection.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <algorithm>
+#include <asio.hpp>
#include <fstream>
#include <functional>
#include <map>
+#ifndef ASIO_STANDALONE
#define ASIO_STANDALONE
+#endif
#include <asio.hpp>
-#undef ASIO_STANDALONE
-
-#include <thread>
-
-typedef std::chrono::time_point<std::chrono::system_clock> Time;
-typedef std::chrono::milliseconds TimeDuration;
-
-Time t1;
-
-#define DEFAULT_BETA 0.99
-#define DEFAULT_GAMMA 0.07
namespace http {
@@ -48,16 +42,13 @@ class ReadBytesCallbackImplementation
static std::string chunk_separator;
public:
- ReadBytesCallbackImplementation(std::string file_name, long yet_downloaded)
+ ReadBytesCallbackImplementation(const std::string &file_name,
+ long yet_downloaded)
: file_name_(file_name),
temp_file_name_(file_name_ + ".temp"),
yet_downloaded_(yet_downloaded),
byte_downloaded_(yet_downloaded),
- chunked_(false),
- chunk_size_(0),
- work_(std::make_unique<asio::io_service::work>(io_service_)),
- thread_(
- std::make_unique<std::thread>([this]() { io_service_.run(); })) {
+ work_(std::make_unique<asio::io_service::work>(io_service_)) {
std::streambuf *buf;
if (file_name_ != "-") {
of_.open(temp_file_name_, std::ofstream::binary | std::ofstream::app);
@@ -69,12 +60,6 @@ class ReadBytesCallbackImplementation
out_ = new std::ostream(buf);
}
- ~ReadBytesCallbackImplementation() {
- if (thread_->joinable()) {
- thread_->join();
- }
- }
-
void onBytesReceived(std::unique_ptr<utils::MemBuf> &&buffer) {
auto buffer_ptr = buffer.release();
io_service_.post([this, buffer_ptr]() {
@@ -102,7 +87,7 @@ class ReadBytesCallbackImplementation
if (chunked_) {
if (chunk_size_ > 0) {
- out_->write((char *)payload->data(), chunk_size_);
+ out_->write((char *)payload->writableData(), chunk_size_);
payload->trimStart(chunk_size_);
if (payload->length() >= chunk_separator.size()) {
@@ -130,7 +115,7 @@ class ReadBytesCallbackImplementation
chunk_size_ -= payload->length();
}
- out_->write((char *)payload->data(), to_write);
+ out_->write((char *)payload->writableData(), to_write);
byte_downloaded_ += (long)to_write;
payload->trimStart(to_write);
@@ -140,7 +125,7 @@ class ReadBytesCallbackImplementation
}
}
} else {
- out_->write((char *)payload->data(), payload->length());
+ out_->write((char *)payload->writableData(), payload->length());
byte_downloaded_ += (long)payload->length();
}
@@ -175,13 +160,13 @@ class ReadBytesCallbackImplementation
}
print_bar(100, 100, true);
- std::cout << "\nDownloaded " << bytes << " bytes" << std::endl;
+ LoggerInfo() << "\nDownloaded " << bytes << " bytes";
}
work_.reset();
});
}
- void onError(const std::error_code ec) {
+ void onError(const std::error_code &ec) {
io_service_.post([this]() {
of_.close();
delete out_;
@@ -219,15 +204,13 @@ class ReadBytesCallbackImplementation
}
}
if (last) {
- std::cout << "] " << int(progress * 100.0) << " %" << std::endl
- << std::endl;
+ std::cout << "] " << int(progress * 100.0) << " %";
} else {
std::cout << "] " << int(progress * 100.0) << " %\r";
std::cout.flush();
}
}
- private:
std::string file_name_;
std::string temp_file_name_;
std::ostream *out_;
@@ -236,41 +219,36 @@ class ReadBytesCallbackImplementation
long content_size_;
bool first_chunk_read_ = false;
long byte_downloaded_ = 0;
- bool chunked_;
- std::size_t chunk_size_;
+ bool chunked_ = false;
+ std::size_t chunk_size_ = 0;
asio::io_service io_service_;
std::unique_ptr<asio::io_service::work> work_;
- std::unique_ptr<std::thread> thread_;
};
std::string ReadBytesCallbackImplementation::chunk_separator = "\r\n";
-long checkFileStatus(std::string file_name) {
+long checkFileStatus(const std::string &file_name) {
struct stat stat_buf;
std::string temp_file_name_ = file_name + ".temp";
int rc = stat(temp_file_name_.c_str(), &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
-void usage(char *program_name) {
- std::cerr << "usage:" << std::endl;
- std::cerr << program_name << " [option]... [url]..." << std::endl;
- std::cerr << program_name << " options:" << std::endl;
- std::cerr
- << "-O <out_put_path> = write documents to <out_put_file>"
- << std::endl;
- std::cerr << "-S = print server response"
- << std::endl;
- std::cerr << "-P = first word of the ipv6 name of "
- "the response"
- << std::endl;
- std::cerr << "example:" << std::endl;
- std::cerr << "\t" << program_name << " -O - http://origin/index.html"
- << std::endl;
- exit(EXIT_FAILURE);
+void usage(const char *program_name) {
+ LoggerInfo() << "usage:";
+ LoggerInfo() << program_name << " [option]... [url]...";
+ LoggerInfo() << program_name << " options:";
+ LoggerInfo()
+ << "-O <out_put_path> = write documents to <out_put_file>";
+ LoggerInfo() << "-S = print server response";
+ LoggerInfo()
+ << "-P = first word of the ipv6 name of "
+ "the response";
+ LoggerInfo() << "example:";
+ LoggerInfo() << "\t" << program_name << " -O - http://origin/index.html";
}
-int main(int argc, char **argv) {
+int http_main(int argc, char **argv) {
#ifdef _WIN32
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
@@ -299,20 +277,20 @@ int main(int argc, char **argv) {
case 'P':
conf.ipv6_first_word = optarg;
break;
- case 'h':
default:
usage(argv[0]);
- break;
+ exit(EXIT_FAILURE);
}
}
if (!argv[optind]) {
usage(argv[0]);
+ exit(EXIT_FAILURE);
}
name = argv[optind];
- std::cerr << "Using name " << name << " and name first word "
- << conf.ipv6_first_word << std::endl;
+ LoggerInfo() << "Using name " << name << " and name first word "
+ << conf.ipv6_first_word;
if (conf.file_name.empty()) {
conf.file_name = name.substr(1 + name.find_last_of("/"));
@@ -345,8 +323,6 @@ int main(int argc, char **argv) {
connection.setVerifier(verifier);
}
- t1 = std::chrono::system_clock::now();
-
http::ReadBytesCallbackImplementation readBytesCallback(conf.file_name,
yetDownloaded);
@@ -362,4 +338,4 @@ int main(int argc, char **argv) {
} // end namespace http
-int main(int argc, char **argv) { return http::main(argc, argv); }
+int main(int argc, char **argv) { return http::http_main(argc, argv); }
diff --git a/apps/hiperf/CMakeLists.txt b/apps/hiperf/CMakeLists.txt
index 564525e67..5a0dc3c06 100644
--- a/apps/hiperf/CMakeLists.txt
+++ b/apps/hiperf/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -12,33 +12,50 @@
# limitations under the License.
if (NOT DISABLE_EXECUTABLES)
+##############################################################
+# Source files
+##############################################################
list(APPEND HIPERF_SRC
${CMAKE_CURRENT_SOURCE_DIR}/src/client.cc
${CMAKE_CURRENT_SOURCE_DIR}/src/main.cc
${CMAKE_CURRENT_SOURCE_DIR}/src/server.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/src/forwarder_interface.cc
)
+
+##############################################################
+# Libraries
+##############################################################
list (APPEND HIPERF_LIBRARIES
- ${LIBTRANSPORT_LIBRARIES}
- ${LIBHICNCTRL_LIBRARIES}
- ${LIBHICN_LIBRARIES}
- ${CMAKE_THREAD_LIBS_INIT}
- ${LIBCONFIG_CPP_LIBRARIES}
- ${WSOCK32_LIBRARY}
- ${WS2_32_LIBRARY}
+ PRIVATE ${LIBTRANSPORT_LIBRARIES}
+ PRIVATE ${LIBHICNCTRL_LIBRARIES}
+ PRIVATE ${LIBHICN_LIBRARIES}
+ PRIVATE ${CMAKE_THREAD_LIBS_INIT}
+ PRIVATE ${LIBCONFIG_CPP_LIBRARIES}
+ PRIVATE ${WSOCK32_LIBRARY}
+ PRIVATE ${WS2_32_LIBRARY}
+ )
+
+##############################################################
+# Compiler options
+##############################################################
+ set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
)
+
+##############################################################
+# Build hiperf
+##############################################################
build_executable(hiperf
SOURCES ${HIPERF_SRC}
LINK_LIBRARIES ${HIPERF_LIBRARIES}
INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR}/src
- ${LIBTRANSPORT_INCLUDE_DIRS}
- ${LIBHICNCTRL_INCLUDE_DIRS}
- ${LIBCONFIG_CPP_INCLUDE_DIRS}
- DEPENDS ${DEPENDENCIES}
+ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src
+ PRIVATE ${LIBCONFIG_CPP_INCLUDE_DIRS}
+ PRIVATE ${THIRD_PARTY_INCLUDE_DIRS} ${COMMON_INCLUDE_DIRS}
+ DEPENDS ${DEPENDENCIES} ${THIRD_PARTY_DEPENDENCIES}
COMPONENT ${HICN_APPS}
LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
endif() \ No newline at end of file
diff --git a/apps/hiperf/src/client.cc b/apps/hiperf/src/client.cc
index 820ebf0ce..1ce5b4c55 100644
--- a/apps/hiperf/src/client.cc
+++ b/apps/hiperf/src/client.cc
@@ -14,8 +14,7 @@
*/
#include <client.h>
-#include <forwarder_config.h>
-#include <forwarder_interface.h>
+#include <hicn/transport/portability/endianess.h>
#include <libconfig.h++>
@@ -27,874 +26,857 @@ namespace hiperf {
class RTCCallback;
class Callback;
+using transport::auth::CryptoHashType;
+using transport::core::Packet;
+using transport::core::Prefix;
+using transport::interface::ConsumerCallbacksOptions;
+using transport::interface::ConsumerSocket;
+using transport::interface::GeneralTransportOptions;
+using transport::interface::ProducerSocket;
+using transport::interface::ProductionProtocolAlgorithms;
+using transport::interface::RaaqmTransportOptions;
+using transport::interface::RtcTransportOptions;
+using transport::interface::RtcTransportRecoveryStrategies;
+using transport::interface::StrategyCallback;
+using transport::interface::TransportStatistics;
+
/**
* Hiperf client class: configure and setup an hicn consumer following the
* ClientConfiguration.
*/
-class HIperfClient::Impl
-#ifdef FORWARDER_INTERFACE
- : ForwarderInterface::ICallback
-#endif
-{
- typedef std::chrono::time_point<std::chrono::steady_clock> Time;
- typedef std::chrono::microseconds TimeDuration;
-
+class HIperfClient::Impl {
friend class Callback;
friend class RTCCallback;
- struct nack_packet_t {
- uint64_t timestamp;
- uint32_t prod_rate;
- uint32_t prod_seg;
-
- inline uint64_t getTimestamp() const { return _ntohll(&timestamp); }
- inline void setTimestamp(uint64_t time) { timestamp = _htonll(&time); }
-
- inline uint32_t getProductionRate() const { return ntohl(prod_rate); }
- inline void setProductionRate(uint32_t rate) { prod_rate = htonl(rate); }
-
- inline uint32_t getProductionSegement() const { return ntohl(prod_seg); }
- inline void setProductionSegement(uint32_t seg) { prod_seg = htonl(seg); }
- };
-
- public:
- Impl(const hiperf::ClientConfiguration &conf)
- : configuration_(conf),
- total_duration_milliseconds_(0),
- old_bytes_value_(0),
- old_interest_tx_value_(0),
- old_fec_interest_tx_value_(0),
- old_fec_data_rx_value_(0),
- old_lost_data_value_(0),
- old_bytes_recovered_value_(0),
- old_definitely_lost_data_value_(0),
- old_retx_value_(0),
- old_sent_int_value_(0),
- old_received_nacks_value_(0),
- old_fec_pkt_(0),
- avg_data_delay_(0),
- delay_sample_(0),
- received_bytes_(0),
- received_data_pkt_(0),
- data_delays_(""),
- signals_(io_service_),
- rtc_callback_(*this),
- callback_(*this),
- socket_(io_service_),
- done_(false),
- switch_threshold_(~0)
-#ifdef FORWARDER_INTERFACE
- ,
- forwarder_interface_(io_service_, this)
-#endif
- {
+ static inline constexpr uint16_t klog2_header_counter() { return 4; }
+ static inline constexpr uint16_t kheader_counter_mask() {
+ return (1 << klog2_header_counter()) - 1;
}
- ~Impl() {}
+ class ConsumerContext
+ : public Base<ConsumerContext, ClientConfiguration, Impl>,
+ private ConsumerSocket::ReadCallback {
+ static inline const std::size_t kmtu = HIPERF_MTU;
- void checkReceivedRtcContent(ConsumerSocket &c,
- const ContentObject &contentObject) {}
+ public:
+ using ConfType = ClientConfiguration;
+ using ParentType = typename HIperfClient::Impl;
+ static inline auto getContextType() -> std::string {
+ return "ConsumerContext";
+ }
+
+ ConsumerContext(Impl &client, int consumer_identifier)
+ : Base(client, client.io_service_, consumer_identifier),
+ receive_buffer_(
+ utils::MemBuf::create(client.config_.receive_buffer_size_)),
+ socket_(client.io_service_),
+ payload_size_max_(PayloadSize(client.config_.packet_format_)
+ .getPayloadSizeMax(RTC_HEADER_SIZE)),
+ nb_iterations_(client.config_.nb_iterations_) {}
+
+ ConsumerContext(ConsumerContext &&other) noexcept
+ : Base(std::move(other)),
+ receive_buffer_(std::move(other.receive_buffer_)),
+ socket_(std::move(other.socket_)),
+ payload_size_max_(other.payload_size_max_),
+ remote_(std::move(other.remote_)),
+ nb_iterations_(other.nb_iterations_),
+ saved_stats_(std::move(other.saved_stats_)),
+ header_counter_(other.header_counter_),
+ first_(other.first_),
+ consumer_socket_(std::move(other.consumer_socket_)),
+ producer_socket_(std::move(other.producer_socket_)) {}
+
+ ~ConsumerContext() override = default;
+
+ /***************************************************************
+ * ConsumerSocket::ReadCallback implementation
+ ***************************************************************/
- void processLeavingInterest(ConsumerSocket &c, const Interest &interest) {}
+ bool isBufferMovable() noexcept override { return false; }
- void addFace(const std::string &local_address, uint16_t local_port,
- const std::string &remote_address, uint16_t remote_port,
- std::string interface);
+ void getReadBuffer(uint8_t **application_buffer,
+ size_t *max_length) override {
+ *application_buffer = receive_buffer_->writableData();
- void handleTimerExpiration(ConsumerSocket &c,
- const TransportStatistics &stats) {
- const char separator = ' ';
- const int width = 15;
+ if (configuration_.rtc_) {
+ *max_length = kmtu;
+ } else {
+ *max_length = configuration_.receive_buffer_size_;
+ }
+ }
- utils::TimePoint t2 = utils::SteadyClock::now();
- auto exact_duration =
- std::chrono::duration_cast<utils::Milliseconds>(t2 - t_stats_);
+ void readBufferAvailable(
+ std::unique_ptr<utils::MemBuf> &&buffer) noexcept override {
+ // Nothing to do here
+ auto ret = std::move(buffer);
+ }
- std::stringstream interval;
- interval << total_duration_milliseconds_ / 1000 << "-"
- << total_duration_milliseconds_ / 1000 +
- exact_duration.count() / 1000;
+ void readDataAvailable(std::size_t length) noexcept override {
+ if (configuration_.rtc_) {
+ saved_stats_.received_bytes_ += length;
+ saved_stats_.received_data_pkt_++;
- std::stringstream bytes_transferred;
- bytes_transferred << std::fixed << std::setprecision(3)
- << (stats.getBytesRecv() - old_bytes_value_) / 1000000.0
- << std::setfill(separator) << "[MB]";
+ // collecting delay stats. Just for performance testing
+ auto senderTimeStamp =
+ *reinterpret_cast<uint64_t *>(receive_buffer_->writableData());
- std::stringstream bandwidth;
- bandwidth << ((stats.getBytesRecv() - old_bytes_value_) * 8) /
- (exact_duration.count()) / 1000.0
- << std::setfill(separator) << "[Mbps]";
+ auto now = utils::SystemTime::nowMs().count();
+ auto new_delay = double(now - senderTimeStamp);
- std::stringstream window;
- window << stats.getAverageWindowSize() << std::setfill(separator)
- << "[Int]";
+ if (senderTimeStamp > now)
+ new_delay = -1 * double(senderTimeStamp - now);
- std::stringstream avg_rtt;
- avg_rtt << stats.getAverageRtt() << std::setfill(separator) << "[ms]";
+ saved_stats_.delay_sample_++;
+ saved_stats_.avg_data_delay_ =
+ saved_stats_.avg_data_delay_ +
+ (double(new_delay) - saved_stats_.avg_data_delay_) /
+ saved_stats_.delay_sample_;
- if (configuration_.rtc_) {
- // we get rtc stats more often, thus we need ms in the interval
- std::stringstream interval_ms;
- interval_ms << total_duration_milliseconds_ << "-"
- << total_duration_milliseconds_ + exact_duration.count();
-
- std::stringstream lost_data;
- lost_data << stats.getLostData() - old_lost_data_value_
- << std::setfill(separator) << "[pkt]";
-
- std::stringstream bytes_recovered_data;
- bytes_recovered_data << stats.getBytesRecoveredData() -
- old_bytes_recovered_value_
- << std::setfill(separator) << "[pkt]";
-
- std::stringstream definitely_lost_data;
- definitely_lost_data << stats.getDefinitelyLostData() -
- old_definitely_lost_data_value_
- << std::setfill(separator) << "[pkt]";
-
- std::stringstream data_delay;
- data_delay << avg_data_delay_ << std::setfill(separator) << "[ms]";
-
- std::stringstream received_data_pkt;
- received_data_pkt << received_data_pkt_ << std::setfill(separator)
- << "[pkt]";
-
- std::stringstream goodput;
- goodput << (received_bytes_ * 8.0) / (exact_duration.count()) / 1000.0
- << std::setfill(separator) << "[Mbps]";
-
- std::stringstream loss_rate;
- loss_rate << std::fixed << std::setprecision(2)
- << stats.getLossRatio() * 100.0 << std::setfill(separator)
- << "[%]";
-
- std::stringstream retx_sent;
- retx_sent << stats.getRetxCount() - old_retx_value_
- << std::setfill(separator) << "[pkt]";
-
- std::stringstream interest_sent;
- interest_sent << stats.getInterestTx() - old_sent_int_value_
- << std::setfill(separator) << "[pkt]";
-
- std::stringstream nacks;
- nacks << stats.getReceivedNacks() - old_received_nacks_value_
- << std::setfill(separator) << "[pkt]";
-
- std::stringstream fec_pkt;
- fec_pkt << stats.getReceivedFEC() - old_fec_pkt_
- << std::setfill(separator) << "[pkt]";
-
- std::stringstream queuing_delay;
- queuing_delay << stats.getQueuingDelay() << std::setfill(separator)
- << "[ms]";
-
-#ifdef FORWARDER_INTERFACE
- if (!done_ && stats.getQueuingDelay() >= switch_threshold_ &&
- total_duration_milliseconds_ > 1000) {
- std::cout << "Switching due to queuing delay" << std::endl;
- forwarder_interface_.createFaceAndRoutes(backup_routes_);
- forwarder_interface_.deleteFaceAndRoutes(main_routes_);
- std::swap(backup_routes_, main_routes_);
- done_ = true;
- }
-#endif
-
- // statistics not yet available in the transport
- // std::stringstream interest_fec_tx;
- // interest_fec_tx << stats.getInterestFecTxCount() -
- // old_fec_interest_tx_value_ << std::setfill(separator) << "[pkt]";
- // std::stringstream bytes_fec_recv;
- // bytes_fec_recv << stats.getBytesFecRecv() - old_fec_data_rx_value_
- // << std::setfill(separator) << "[bytes]";
- std::cout << std::left << std::setw(width) << "Interval";
- std::cout << std::left << std::setw(width) << "RecvData";
- std::cout << std::left << std::setw(width) << "Bandwidth";
- std::cout << std::left << std::setw(width) << "Goodput";
- std::cout << std::left << std::setw(width) << "LossRate";
- std::cout << std::left << std::setw(width) << "Retr";
- std::cout << std::left << std::setw(width) << "InterestSent";
- std::cout << std::left << std::setw(width) << "ReceivedNacks";
- std::cout << std::left << std::setw(width) << "SyncWnd";
- std::cout << std::left << std::setw(width) << "MinRtt";
- std::cout << std::left << std::setw(width) << "QueuingDelay";
- std::cout << std::left << std::setw(width) << "LostData";
- std::cout << std::left << std::setw(width) << "RecoveredData";
- std::cout << std::left << std::setw(width) << "DefinitelyLost";
- std::cout << std::left << std::setw(width) << "State";
- std::cout << std::left << std::setw(width) << "DataDelay";
- std::cout << std::left << std::setw(width) << "FecPkt" << std::endl;
-
- std::cout << std::left << std::setw(width) << interval_ms.str();
- std::cout << std::left << std::setw(width) << received_data_pkt.str();
- std::cout << std::left << std::setw(width) << bandwidth.str();
- std::cout << std::left << std::setw(width) << goodput.str();
- std::cout << std::left << std::setw(width) << loss_rate.str();
- std::cout << std::left << std::setw(width) << retx_sent.str();
- std::cout << std::left << std::setw(width) << interest_sent.str();
- std::cout << std::left << std::setw(width) << nacks.str();
- std::cout << std::left << std::setw(width) << window.str();
- std::cout << std::left << std::setw(width) << avg_rtt.str();
- std::cout << std::left << std::setw(width) << queuing_delay.str();
- std::cout << std::left << std::setw(width) << lost_data.str();
- std::cout << std::left << std::setw(width) << bytes_recovered_data.str();
- std::cout << std::left << std::setw(width) << definitely_lost_data.str();
- std::cout << std::left << std::setw(width) << stats.getCCStatus();
- std::cout << std::left << std::setw(width) << data_delay.str();
- std::cout << std::left << std::setw(width) << fec_pkt.str();
- std::cout << std::endl;
-
- if (configuration_.test_mode_) {
- if (data_delays_.size() > 0) data_delays_.pop_back();
-
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch())
- .count();
- std::cout << now << " DATA-DELAYS:[" << data_delays_ << "]"
- << std::endl;
- }
-
- // statistics not yet available in the transport
- // std::cout << std::left << std::setw(width) << interest_fec_tx.str();
- // std::cout << std::left << std::setw(width) << bytes_fec_recv.str();
- } else {
- std::cout << std::left << std::setw(width) << "Interval";
- std::cout << std::left << std::setw(width) << "Transfer";
- std::cout << std::left << std::setw(width) << "Bandwidth";
- std::cout << std::left << std::setw(width) << "Retr";
- std::cout << std::left << std::setw(width) << "Cwnd";
- std::cout << std::left << std::setw(width) << "AvgRtt" << std::endl;
-
- std::cout << std::left << std::setw(width) << interval.str();
- std::cout << std::left << std::setw(width) << bytes_transferred.str();
- std::cout << std::left << std::setw(width) << bandwidth.str();
- std::cout << std::left << std::setw(width) << stats.getRetxCount();
- std::cout << std::left << std::setw(width) << window.str();
- std::cout << std::left << std::setw(width) << avg_rtt.str() << std::endl;
- std::cout << std::endl;
- }
- total_duration_milliseconds_ += (uint32_t)exact_duration.count();
- old_bytes_value_ = stats.getBytesRecv();
- old_lost_data_value_ = stats.getLostData();
- old_bytes_recovered_value_ = stats.getBytesRecoveredData();
- old_definitely_lost_data_value_ = stats.getDefinitelyLostData();
- old_fec_interest_tx_value_ = stats.getInterestFecTxCount();
- old_fec_data_rx_value_ = stats.getBytesFecRecv();
- old_retx_value_ = stats.getRetxCount();
- old_sent_int_value_ = stats.getInterestTx();
- old_received_nacks_value_ = stats.getReceivedNacks();
- old_fec_pkt_ = stats.getReceivedFEC();
- delay_sample_ = 0;
- avg_data_delay_ = 0;
- received_bytes_ = 0;
- received_data_pkt_ = 0;
- data_delays_ = "";
-
- t_stats_ = utils::SteadyClock::now();
- }
+ if (configuration_.test_mode_) {
+ saved_stats_.data_delays_ += std::to_string(int(new_delay));
+ saved_stats_.data_delays_ += ",";
+ }
- bool parseConfig(const char *conf_file) {
- using namespace libconfig;
- Config cfg;
-
- try {
- cfg.readFile(conf_file);
- } catch (const FileIOException &fioex) {
- std::cerr << "I/O error while reading file." << std::endl;
- return false;
- } catch (const ParseException &pex) {
- std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine()
- << " - " << pex.getError() << std::endl;
- return false;
+ if (configuration_.relay_ && configuration_.parallel_flows_ == 1) {
+ producer_socket_->produceDatagram(
+ configuration_.relay_name_.makeName(),
+ receive_buffer_->writableData(),
+ length < payload_size_max_ ? length : payload_size_max_);
+ }
+ if (configuration_.output_stream_mode_ &&
+ configuration_.parallel_flows_ == 1) {
+ const uint8_t *start = receive_buffer_->writableData();
+ start += sizeof(uint64_t);
+ std::size_t pkt_len = length - sizeof(uint64_t);
+ socket_.send_to(asio::buffer(start, pkt_len), remote_);
+ }
+ }
}
- Setting &config = cfg.getRoot();
+ size_t maxBufferSize() const override {
+ return configuration_.rtc_ ? kmtu : configuration_.receive_buffer_size_;
+ }
- if (config.exists("switch_threshold")) {
- unsigned threshold;
- config.lookupValue("switch_threshold", threshold);
- switch_threshold_ = threshold;
+ void readError(const std::error_code &ec) noexcept override {
+ getOutputStream() << "Error " << ec.message()
+ << " while reading from socket" << std::endl;
+ parent_.io_service_.stop();
}
- // listeners
- if (config.exists("listeners")) {
- // get path where looking for modules
- const Setting &listeners = config.lookup("listeners");
- auto count = listeners.getLength();
+ void readSuccess(std::size_t total_size) noexcept override {
+ if (configuration_.rtc_) {
+ getOutputStream() << "Data successfully read" << std::endl;
+ } else {
+ auto t2 = utils::SteadyTime::now();
+ auto dt =
+ utils::SteadyTime::getDurationUs(saved_stats_.t_download_, t2);
+ auto usec = dt.count();
- for (int i = 0; i < count; i++) {
- const Setting &listener = listeners[i];
- ListenerConfig list;
- unsigned port;
- std::string interface;
+ getOutputStream() << "Content retrieved. Size: " << total_size
+ << " [Bytes]" << std::endl;
- list.name = listener.getName();
- listener.lookupValue("local_address", list.address);
- listener.lookupValue("local_port", port);
- listener.lookupValue("interface", list.interface);
- list.port = (uint16_t)(port);
+ getOutputStream() << "Elapsed Time: " << usec / 1000000.0
+ << " seconds -- "
+ << double(total_size * 8) * 1.0 / double(usec) * 1.0
+ << " [Mbps]" << std::endl;
- std::cout << "Adding listener " << list.name << ", ( " << list.address
- << ":" << list.port << ")" << std::endl;
- config_.addListener(std::move(list));
+ parent_.io_service_.stop();
}
}
- // connectors
- if (config.exists("connectors")) {
- // get path where looking for modules
- const Setting &connectors = config.lookup("connectors");
- auto count = connectors.getLength();
-
- for (int i = 0; i < count; i++) {
- const Setting &connector = connectors[i];
- ConnectorConfig conn;
-
- conn.name = connector.getName();
- unsigned port = 0;
-
- if (!connector.lookupValue("local_address", conn.local_address)) {
- conn.local_address = "";
- }
+ /***************************************************************
+ * End of ConsumerSocket::ReadCallback implementation
+ ***************************************************************/
- if (!connector.lookupValue("local_port", port)) {
- port = 0;
- }
-
- conn.local_port = (uint16_t)(port);
+ private:
+ struct SavedStatistics {
+ utils::SteadyTime::TimePoint t_stats_{};
+ utils::SteadyTime::TimePoint t_download_{};
+ uint32_t total_duration_milliseconds_{0};
+ uint64_t old_bytes_value_{0};
+ uint64_t old_interest_tx_value_{0};
+ uint64_t old_fec_interest_tx_value_{0};
+ uint64_t old_fec_data_rx_value_{0};
+ uint64_t old_lost_data_value_{0};
+ uint64_t old_bytes_recovered_value_{0};
+ uint64_t old_definitely_lost_data_value_{0};
+ uint64_t old_retx_value_{0};
+ uint64_t old_sent_int_value_{0};
+ uint64_t old_received_nacks_value_{0};
+ uint32_t old_fec_pkt_{0};
+ // IMPORTANT: to be used only for performance testing, when consumer and
+ // producer are synchronized. Used for rtc only at the moment
+ double avg_data_delay_{0};
+ uint32_t delay_sample_{0};
+ uint32_t received_bytes_{0};
+ uint32_t received_data_pkt_{0};
+ uint32_t auth_alerts_{0};
+ std::string data_delays_{""};
+ };
+
+ /***************************************************************
+ * Transport callbacks
+ ***************************************************************/
+
+ void checkReceivedRtcContent(
+ [[maybe_unused]] const ConsumerSocket &c,
+ [[maybe_unused]] const transport::core::ContentObject &content_object)
+ const {
+ // Nothing to do here
+ }
+
+ void processLeavingInterest(
+ const ConsumerSocket & /*c*/,
+ const transport::core::Interest & /*interest*/) const {
+ // Nothing to do here
+ }
+
+ transport::auth::VerificationPolicy onAuthFailed(
+ transport::auth::Suffix /*suffix*/,
+ transport::auth::VerificationPolicy /*policy*/) {
+ saved_stats_.auth_alerts_++;
+ return transport::auth::VerificationPolicy::ACCEPT;
+ }
+
+ void handleTimerExpiration([[maybe_unused]] const ConsumerSocket &c,
+ const TransportStatistics &stats) {
+ const char separator = ' ';
+ const int width = 18;
+
+ utils::SteadyTime::TimePoint t2 = utils::SteadyTime::Clock::now();
+ auto exact_duration =
+ utils::SteadyTime::getDurationMs(saved_stats_.t_stats_, t2);
- if (!connector.lookupValue("remote_address", conn.remote_address)) {
- std::cerr
- << "Error in configuration file: remote_address is a mandatory "
- "field of Connectors."
- << std::endl;
- return false;
+ std::stringstream interval_ms;
+ interval_ms << saved_stats_.total_duration_milliseconds_ << "-"
+ << saved_stats_.total_duration_milliseconds_ +
+ exact_duration.count();
+
+ std::stringstream bytes_transferred;
+ bytes_transferred << std::fixed << std::setprecision(3)
+ << double(stats.getBytesRecv() -
+ saved_stats_.old_bytes_value_) /
+ 1000000.0
+ << std::setfill(separator);
+
+ std::stringstream bandwidth;
+ bandwidth << (double(stats.getBytesRecv() -
+ saved_stats_.old_bytes_value_) *
+ 8) /
+ (exact_duration.count()) / 1000.0
+ << std::setfill(separator);
+
+ std::stringstream window;
+ window << stats.getAverageWindowSize() << std::setfill(separator);
+
+ std::stringstream avg_rtt;
+ avg_rtt << std::setprecision(3) << std::fixed << stats.getAverageRtt()
+ << std::setfill(separator);
+
+ if (configuration_.rtc_) {
+ std::stringstream lost_data;
+ lost_data << stats.getLostData() - saved_stats_.old_lost_data_value_
+ << std::setfill(separator);
+
+ std::stringstream bytes_recovered_data;
+ bytes_recovered_data << stats.getBytesRecoveredData() -
+ saved_stats_.old_bytes_recovered_value_
+ << std::setfill(separator);
+
+ std::stringstream definitely_lost_data;
+ definitely_lost_data << stats.getDefinitelyLostData() -
+ saved_stats_.old_definitely_lost_data_value_
+ << std::setfill(separator);
+
+ std::stringstream data_delay;
+ data_delay << std::fixed << std::setprecision(3)
+ << saved_stats_.avg_data_delay_ << std::setfill(separator);
+
+ std::stringstream received_data_pkt;
+ received_data_pkt << saved_stats_.received_data_pkt_
+ << std::setfill(separator);
+
+ std::stringstream goodput;
+ goodput << std::fixed << std::setprecision(3)
+ << (saved_stats_.received_bytes_ * 8.0) /
+ (exact_duration.count()) / 1000.0
+ << std::setfill(separator);
+
+ std::stringstream loss_rate;
+ loss_rate << std::fixed << std::setprecision(2)
+ << stats.getLossRatio() * 100.0 << std::setfill(separator);
+
+ std::stringstream retx_sent;
+ retx_sent << stats.getRetxCount() - saved_stats_.old_retx_value_
+ << std::setfill(separator);
+
+ std::stringstream interest_sent;
+ interest_sent << stats.getInterestTx() -
+ saved_stats_.old_sent_int_value_
+ << std::setfill(separator);
+
+ std::stringstream nacks;
+ nacks << stats.getReceivedNacks() -
+ saved_stats_.old_received_nacks_value_
+ << std::setfill(separator);
+
+ std::stringstream fec_pkt;
+ fec_pkt << stats.getReceivedFEC() - saved_stats_.old_fec_pkt_
+ << std::setfill(separator);
+
+ std::stringstream queuing_delay;
+ queuing_delay << std::fixed << std::setprecision(3)
+ << stats.getQueuingDelay() << std::setfill(separator);
+
+ std::stringstream residual_losses;
+ double rl_perc = stats.getResidualLossRate() * 100;
+ residual_losses << std::fixed << std::setprecision(2) << rl_perc
+ << std::setfill(separator);
+
+ std::stringstream quality_score;
+ quality_score << std::fixed << (int)stats.getQualityScore()
+ << std::setfill(separator);
+
+ std::stringstream alerts;
+ alerts << stats.getAlerts() << std::setfill(separator);
+
+ std::stringstream auth_alerts;
+ auth_alerts << saved_stats_.auth_alerts_ << std::setfill(separator);
+
+ if ((header_counter_ == 0 && configuration_.print_headers_) || first_) {
+ getOutputStream() << std::right << std::setw(width) << "Interval[ms]";
+ getOutputStream()
+ << std::right << std::setw(width) << "RecvData[pkt]";
+ getOutputStream()
+ << std::right << std::setw(width) << "Bandwidth[Mbps]";
+ getOutputStream()
+ << std::right << std::setw(width) << "Goodput[Mbps]";
+ getOutputStream() << std::right << std::setw(width) << "LossRate[%]";
+ getOutputStream() << std::right << std::setw(width) << "Retr[pkt]";
+ getOutputStream() << std::right << std::setw(width) << "InterestSent";
+ getOutputStream()
+ << std::right << std::setw(width) << "ReceivedNacks";
+ getOutputStream() << std::right << std::setw(width) << "SyncWnd[pkt]";
+ getOutputStream() << std::right << std::setw(width) << "MinRtt[ms]";
+ getOutputStream()
+ << std::right << std::setw(width) << "QueuingDelay[ms]";
+ getOutputStream()
+ << std::right << std::setw(width) << "LostData[pkt]";
+ getOutputStream()
+ << std::right << std::setw(width) << "RecoveredData";
+ getOutputStream()
+ << std::right << std::setw(width) << "DefinitelyLost";
+ getOutputStream() << std::right << std::setw(width) << "State";
+ getOutputStream()
+ << std::right << std::setw(width) << "DataDelay[ms]";
+ getOutputStream() << std::right << std::setw(width) << "FecPkt";
+ getOutputStream() << std::right << std::setw(width) << "Congestion";
+ getOutputStream()
+ << std::right << std::setw(width) << "ResidualLosses";
+ getOutputStream() << std::right << std::setw(width) << "QualityScore";
+ getOutputStream() << std::right << std::setw(width) << "Alerts";
+ getOutputStream()
+ << std::right << std::setw(width) << "AuthAlerts" << std::endl;
+
+ first_ = false;
}
- if (!connector.lookupValue("remote_port", port)) {
- std::cerr << "Error in configuration file: remote_port is a "
- "mandatory field of Connectors."
- << std::endl;
- return false;
+ getOutputStream() << std::right << std::setw(width)
+ << interval_ms.str();
+ getOutputStream() << std::right << std::setw(width)
+ << received_data_pkt.str();
+ getOutputStream() << std::right << std::setw(width) << bandwidth.str();
+ getOutputStream() << std::right << std::setw(width) << goodput.str();
+ getOutputStream() << std::right << std::setw(width) << loss_rate.str();
+ getOutputStream() << std::right << std::setw(width) << retx_sent.str();
+ getOutputStream() << std::right << std::setw(width)
+ << interest_sent.str();
+ getOutputStream() << std::right << std::setw(width) << nacks.str();
+ getOutputStream() << std::right << std::setw(width) << window.str();
+ getOutputStream() << std::right << std::setw(width) << avg_rtt.str();
+ getOutputStream() << std::right << std::setw(width)
+ << queuing_delay.str();
+ getOutputStream() << std::right << std::setw(width) << lost_data.str();
+ getOutputStream() << std::right << std::setw(width)
+ << bytes_recovered_data.str();
+ getOutputStream() << std::right << std::setw(width)
+ << definitely_lost_data.str();
+ getOutputStream() << std::right << std::setw(width)
+ << stats.getCCStatus();
+ getOutputStream() << std::right << std::setw(width) << data_delay.str();
+ getOutputStream() << std::right << std::setw(width) << fec_pkt.str();
+ getOutputStream() << std::right << std::setw(width)
+ << stats.isCongested();
+ getOutputStream() << std::right << std::setw(width)
+ << residual_losses.str();
+ getOutputStream() << std::right << std::setw(width)
+ << quality_score.str();
+ getOutputStream() << std::right << std::setw(width) << alerts.str();
+ getOutputStream() << std::right << std::setw(width) << auth_alerts.str()
+ << std::endl;
+
+ if (configuration_.test_mode_) {
+ if (saved_stats_.data_delays_.size() > 0)
+ saved_stats_.data_delays_.pop_back();
+
+ auto now = utils::SteadyTime::nowMs();
+ getOutputStream() << std::fixed << std::setprecision(0) << now.count()
+ << " DATA-DELAYS:[" << saved_stats_.data_delays_
+ << "]" << std::endl;
}
-
- if (!connector.lookupValue("interface", conn.interface)) {
- std::cerr << "Error in configuration file: interface is a "
- "mandatory field of Connectors."
- << std::endl;
- return false;
+ } else {
+ if ((header_counter_ == 0 && configuration_.print_headers_) || first_) {
+ getOutputStream() << std::right << std::setw(width) << "Interval[ms]";
+ getOutputStream() << std::right << std::setw(width) << "Transfer[MB]";
+ getOutputStream()
+ << std::right << std::setw(width) << "Bandwidth[Mbps]";
+ getOutputStream() << std::right << std::setw(width) << "Retr[pkt]";
+ getOutputStream() << std::right << std::setw(width) << "Cwnd[Int]";
+ getOutputStream()
+ << std::right << std::setw(width) << "AvgRtt[ms]" << std::endl;
+
+ first_ = false;
}
- conn.remote_port = (uint16_t)(port);
+ getOutputStream() << std::right << std::setw(width)
+ << interval_ms.str();
+ getOutputStream() << std::right << std::setw(width)
+ << bytes_transferred.str();
+ getOutputStream() << std::right << std::setw(width) << bandwidth.str();
+ getOutputStream() << std::right << std::setw(width)
+ << stats.getRetxCount();
+ getOutputStream() << std::right << std::setw(width) << window.str();
+ getOutputStream() << std::right << std::setw(width) << avg_rtt.str()
+ << std::endl;
+ }
- std::cout << "Adding connector " << conn.name << ", ("
- << conn.local_address << ":" << conn.local_port << " "
- << conn.remote_address << ":" << conn.remote_port << ")"
- << std::endl;
- config_.addConnector(conn.name, std::move(conn));
+ saved_stats_.total_duration_milliseconds_ +=
+ (uint32_t)exact_duration.count();
+ saved_stats_.old_bytes_value_ = stats.getBytesRecv();
+ saved_stats_.old_lost_data_value_ = stats.getLostData();
+ saved_stats_.old_bytes_recovered_value_ = stats.getBytesRecoveredData();
+ saved_stats_.old_definitely_lost_data_value_ =
+ stats.getDefinitelyLostData();
+ saved_stats_.old_fec_interest_tx_value_ = stats.getInterestFecTxCount();
+ saved_stats_.old_fec_data_rx_value_ = stats.getBytesFecRecv();
+ saved_stats_.old_retx_value_ = stats.getRetxCount();
+ saved_stats_.old_sent_int_value_ = stats.getInterestTx();
+ saved_stats_.old_received_nacks_value_ = stats.getReceivedNacks();
+ saved_stats_.old_fec_pkt_ = stats.getReceivedFEC();
+ saved_stats_.delay_sample_ = 0;
+ saved_stats_.avg_data_delay_ = 0;
+ saved_stats_.received_bytes_ = 0;
+ saved_stats_.received_data_pkt_ = 0;
+ saved_stats_.data_delays_ = "";
+ saved_stats_.t_stats_ = utils::SteadyTime::Clock::now();
+
+ header_counter_ = (header_counter_ + 1) & kheader_counter_mask();
+
+ if (--nb_iterations_ == 0) {
+ // We reached the maximum nb of runs. Stop now.
+ parent_.io_service_.stop();
}
}
- // Routes
- if (config.exists("routes")) {
- const Setting &routes = config.lookup("routes");
- auto count = routes.getLength();
+ /***************************************************************
+ * Setup functions
+ ***************************************************************/
- for (int i = 0; i < count; i++) {
- const Setting &route = routes[i];
- RouteConfig r;
- unsigned weight;
+ int setupRTCSocket() {
+ int ret = ERROR_SUCCESS;
- r.name = route.getName();
- route.lookupValue("prefix", r.prefix);
- route.lookupValue("weight", weight);
- route.lookupValue("main_connector", r.main_connector);
- route.lookupValue("backup_connector", r.backup_connector);
- r.weight = (uint16_t)(weight);
+ configuration_.transport_protocol_ = transport::interface::RTC;
- std::cout << "Adding route " << r.name << " " << r.prefix << " ("
- << r.main_connector << " " << r.backup_connector << " "
- << r.weight << ")" << std::endl;
- config_.addRoute(std::move(r));
+ if (configuration_.relay_ && configuration_.parallel_flows_ == 1) {
+ int production_protocol = ProductionProtocolAlgorithms::RTC_PROD;
+ producer_socket_ =
+ std::make_unique<ProducerSocket>(production_protocol);
+ producer_socket_->registerPrefix(configuration_.relay_name_);
+ producer_socket_->connect();
+ producer_socket_->start();
}
- }
- std::cout << "Ok" << std::endl;
-
- return true;
- }
-
- bool splitRoute(std::string route, std::string &prefix,
- uint8_t &prefix_length) {
- std::string delimiter = "/";
-
- size_t pos = 0;
- if ((pos = route.find(delimiter)) != std::string::npos) {
- prefix = route.substr(0, pos);
- route.erase(0, pos + delimiter.length());
- } else {
- return false;
- }
+ if (configuration_.output_stream_mode_ &&
+ configuration_.parallel_flows_ == 1) {
+ remote_ = asio::ip::udp::endpoint(
+ asio::ip::address::from_string("127.0.0.1"), configuration_.port_);
+ socket_.open(asio::ip::udp::v4());
+ }
- prefix_length = std::stoul(route.substr(0));
- return true;
- }
+ consumer_socket_ =
+ std::make_unique<ConsumerSocket>(configuration_.transport_protocol_);
-#ifdef FORWARDER_INTERFACE
- void onHicnServiceReady() override {
- std::cout << "Successfully connected to local forwarder!" << std::endl;
+ RtcTransportRecoveryStrategies recovery_strategy =
+ RtcTransportRecoveryStrategies::RTX_ONLY;
+ switch (configuration_.recovery_strategy_) {
+ case 1:
+ recovery_strategy = RtcTransportRecoveryStrategies::RECOVERY_OFF;
+ break;
+ case 2:
+ recovery_strategy = RtcTransportRecoveryStrategies::RTX_ONLY;
+ break;
+ case 3:
+ recovery_strategy = RtcTransportRecoveryStrategies::FEC_ONLY;
+ break;
+ case 4:
+ recovery_strategy = RtcTransportRecoveryStrategies::DELAY_BASED;
+ break;
+ case 5:
+ recovery_strategy = RtcTransportRecoveryStrategies::LOW_RATE;
+ break;
+ case 6:
+ recovery_strategy =
+ RtcTransportRecoveryStrategies::LOW_RATE_AND_BESTPATH;
+ break;
+ case 7:
+ recovery_strategy =
+ RtcTransportRecoveryStrategies::LOW_RATE_AND_REPLICATION;
+ break;
+ case 8:
+ recovery_strategy =
+ RtcTransportRecoveryStrategies::LOW_RATE_AND_ALL_FWD_STRATEGIES;
+ break;
+ case 9:
+ recovery_strategy =
+ RtcTransportRecoveryStrategies::FEC_ONLY_LOW_RES_LOSSES;
+ break;
+ case 10:
+ recovery_strategy =
+ RtcTransportRecoveryStrategies::DELAY_AND_BESTPATH;
+ break;
+ case 11:
+ recovery_strategy =
+ RtcTransportRecoveryStrategies::DELAY_AND_REPLICATION;
+ break;
+ default:
+ break;
+ }
- std::cout << "Setting up listeners" << std::endl;
- const char *config = getenv("FORWARDER_CONFIG");
+ ret = consumer_socket_->setSocketOption(
+ RtcTransportOptions::RECOVERY_STRATEGY,
+ static_cast<uint32_t>(recovery_strategy));
- if (config) {
- if (!parseConfig(config)) {
- return;
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
}
- // Create faces and route using first face in the list.
- auto &routes = config_.getRoutes();
- auto &connectors = config_.getConnectors();
+ ret = consumer_socket_->setSocketOption(
+ RtcTransportOptions::AGGREGATED_DATA,
+ configuration_.aggregated_data_);
- if (routes.size() == 0 || connectors.size() == 0) {
- std::cerr << "Nothing to configure" << std::endl;
- return;
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
}
- for (auto &route : routes) {
- auto the_connector_it = connectors.find(route.main_connector);
- if (the_connector_it == connectors.end()) {
- std::cerr << "No valid main connector found for route " << route.name
- << std::endl;
- continue;
- }
+ ret = consumer_socket_->setSocketOption(
+ RtcTransportOptions::CONTENT_SHARING_MODE,
+ configuration_.content_sharing_mode_);
- auto &the_connector = the_connector_it->second;
- auto route_info = std::make_shared<ForwarderInterface::RouteInfo>();
- route_info->family = AF_INET;
- route_info->local_addr = the_connector.local_address;
- route_info->local_port = the_connector.local_port;
- route_info->remote_addr = the_connector.remote_address;
- route_info->remote_port = the_connector.remote_port;
- route_info->interface = the_connector.interface;
- route_info->name = the_connector.name;
-
- std::string prefix;
- uint8_t prefix_length;
- auto ret = splitRoute(route.prefix, prefix, prefix_length);
-
- if (!ret) {
- std::cerr << "Error parsing route" << std::endl;
- return;
- }
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- route_info->route_addr = prefix;
- route_info->route_len = prefix_length;
-
- main_routes_.emplace_back(route_info);
-
- if (!route.backup_connector.empty()) {
- // Add also the backup route
- auto the_backup_connector_it =
- connectors.find(route.backup_connector);
- if (the_backup_connector_it == connectors.end()) {
- std::cerr << "No valid backup connector found for route "
- << route.name << std::endl;
- continue;
- }
-
- auto &the_backup_connector = the_backup_connector_it->second;
- auto backup_route_info =
- std::make_shared<ForwarderInterface::RouteInfo>();
- backup_route_info->family = AF_INET;
- backup_route_info->local_addr = the_backup_connector.local_address;
- backup_route_info->local_port = the_backup_connector.local_port;
- backup_route_info->remote_addr = the_backup_connector.remote_address;
- backup_route_info->remote_port = the_backup_connector.remote_port;
- backup_route_info->interface = the_backup_connector.interface;
- backup_route_info->name = the_backup_connector.name;
-
- std::string prefix;
- uint8_t prefix_length;
- auto ret = splitRoute(route.prefix, prefix, prefix_length);
-
- if (!ret) {
- std::cerr << "Error parsing route" << std::endl;
- return;
- }
-
- backup_route_info->route_addr = prefix;
- backup_route_info->route_len = prefix_length;
-
- backup_routes_.emplace_back(backup_route_info);
- }
+ ret = consumer_socket_->setSocketOption(
+ ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT,
+ (transport::interface::ConsumerContentObjectCallback)std::bind(
+ &Impl::ConsumerContext::checkReceivedRtcContent, this,
+ std::placeholders::_1, std::placeholders::_2));
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
}
- // Create main routes
- std::cout << "Creating main routes" << std::endl;
- forwarder_interface_.createFaceAndRoutes(main_routes_);
- }
- }
+ std::shared_ptr<TransportStatistics> transport_stats;
+ ret = consumer_socket_->getSocketOption(
+ transport::interface::OtherOptions::STATISTICS,
+ (TransportStatistics **)&transport_stats);
+ transport_stats->setAlpha(0.0);
- void onRouteConfigured(
- std::vector<ForwarderInterface::RouteInfoPtr> &route_info) override {
- std::cout << "Routes successfully configured!" << std::endl;
- }
-#endif
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- int setup() {
- int ret;
-
- if (configuration_.rtc_) {
- configuration_.transport_protocol_ = RTC;
- } else if (configuration_.window < 0) {
- configuration_.transport_protocol_ = RAAQM;
- } else {
- configuration_.transport_protocol_ = CBR;
+ return ERROR_SUCCESS;
}
- if (configuration_.relay_ && configuration_.rtc_) {
- int production_protocol = ProductionProtocolAlgorithms::RTC_PROD;
- producer_socket_ = std::make_unique<ProducerSocket>(production_protocol);
- producer_socket_->registerPrefix(configuration_.relay_name_);
- producer_socket_->connect();
- }
+ int setupRAAQMSocket() {
+ int ret = ERROR_SUCCESS;
- if (configuration_.output_stream_mode_ && configuration_.rtc_) {
- remote_ = asio::ip::udp::endpoint(
- asio::ip::address::from_string("127.0.0.1"), configuration_.port_);
- socket_.open(asio::ip::udp::v4());
- }
+ configuration_.transport_protocol_ = transport::interface::RAAQM;
- if (configuration_.secure_) {
- consumer_socket_ = std::make_unique<P2PSecureConsumerSocket>(
- RAAQM, configuration_.transport_protocol_);
- if (configuration_.producer_prefix_.getPrefixLength() == 0) {
- std::cerr << "ERROR -- Missing producer prefix on which perform the "
- "handshake."
- << std::endl;
- } else {
- P2PSecureConsumerSocket &secure_consumer_socket =
- *(static_cast<P2PSecureConsumerSocket *>(consumer_socket_.get()));
- secure_consumer_socket.registerPrefix(configuration_.producer_prefix_);
- }
- } else {
consumer_socket_ =
std::make_unique<ConsumerSocket>(configuration_.transport_protocol_);
- }
- consumer_socket_->setSocketOption(
- GeneralTransportOptions::INTEREST_LIFETIME,
- configuration_.interest_lifetime_);
-
-#if defined(DEBUG) && defined(__linux__)
- std::shared_ptr<transport::BasePortal> portal;
- consumer_socket_->getSocketOption(GeneralTransportOptions::PORTAL, portal);
- signals_ =
- std::make_unique<asio::signal_set>(portal->getIoService(), SIGUSR1);
- signals_->async_wait([this](const std::error_code &, const int &) {
- std::cout << "Signal SIGUSR1!" << std::endl;
- mtrace();
- });
-#endif
-
- if (consumer_socket_->setSocketOption(CURRENT_WINDOW_SIZE,
- configuration_.window) ==
- SOCKET_OPTION_NOT_SET) {
- std::cerr << "ERROR -- Impossible to set the size of the window."
- << std::endl;
- return ERROR_SETUP;
- }
-
- if (configuration_.transport_protocol_ == RAAQM &&
- configuration_.beta != -1.f) {
- if (consumer_socket_->setSocketOption(RaaqmTransportOptions::BETA_VALUE,
- configuration_.beta) ==
- SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
+ if (configuration_.beta_ != -1.f) {
+ ret = consumer_socket_->setSocketOption(
+ RaaqmTransportOptions::BETA_VALUE, configuration_.beta_);
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
}
- }
- if (configuration_.transport_protocol_ == RAAQM &&
- configuration_.drop_factor != -1.f) {
- if (consumer_socket_->setSocketOption(RaaqmTransportOptions::DROP_FACTOR,
- configuration_.drop_factor) ==
- SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
+ if (configuration_.drop_factor_ != -1.f) {
+ ret = consumer_socket_->setSocketOption(
+ RaaqmTransportOptions::DROP_FACTOR, configuration_.drop_factor_);
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
}
- }
- if (!configuration_.producer_certificate.empty()) {
- std::shared_ptr<Verifier> verifier = std::make_shared<AsymmetricVerifier>(
- configuration_.producer_certificate);
- if (consumer_socket_->setSocketOption(GeneralTransportOptions::VERIFIER,
- verifier) == SOCKET_OPTION_NOT_SET)
- return ERROR_SETUP;
+ return ERROR_SUCCESS;
}
- if (!configuration_.passphrase.empty()) {
- std::shared_ptr<Verifier> verifier =
- std::make_shared<SymmetricVerifier>(configuration_.passphrase);
- if (consumer_socket_->setSocketOption(GeneralTransportOptions::VERIFIER,
- verifier) == SOCKET_OPTION_NOT_SET)
- return ERROR_SETUP;
- }
+ int setupCBRSocket() {
+ configuration_.transport_protocol_ = transport::interface::CBR;
- ret = consumer_socket_->setSocketOption(
- ConsumerCallbacksOptions::INTEREST_OUTPUT,
- (ConsumerInterestCallback)std::bind(&Impl::processLeavingInterest, this,
- std::placeholders::_1,
- std::placeholders::_2));
+ consumer_socket_ =
+ std::make_unique<ConsumerSocket>(configuration_.transport_protocol_);
- if (ret == SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
+ return ERROR_SUCCESS;
}
- if (!configuration_.rtc_) {
- ret = consumer_socket_->setSocketOption(
- ConsumerCallbacksOptions::READ_CALLBACK, &callback_);
- } else {
- ret = consumer_socket_->setSocketOption(
- ConsumerCallbacksOptions::READ_CALLBACK, &rtc_callback_);
- }
+ public:
+ int setup() {
+ int ret;
+ std::shared_ptr<transport::auth::Verifier> verifier =
+ std::make_shared<transport::auth::VoidVerifier>();
+
+ if (configuration_.rtc_) {
+ ret = setupRTCSocket();
+ } else if (configuration_.window_ < 0) {
+ ret = setupRAAQMSocket();
+ } else {
+ ret = setupCBRSocket();
+ }
- if (ret == SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
- }
+ if (ret != ERROR_SUCCESS) {
+ return ret;
+ }
- if (configuration_.rtc_) {
ret = consumer_socket_->setSocketOption(
- ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT,
- (ConsumerContentObjectCallback)std::bind(
- &Impl::checkReceivedRtcContent, this, std::placeholders::_1,
- std::placeholders::_2));
+ GeneralTransportOptions::INTEREST_LIFETIME,
+ configuration_.interest_lifetime_);
if (ret == SOCKET_OPTION_NOT_SET) {
return ERROR_SETUP;
}
- }
-
- if (configuration_.rtc_) {
- std::shared_ptr<TransportStatistics> transport_stats;
- consumer_socket_->getSocketOption(
- OtherOptions::STATISTICS, (TransportStatistics **)&transport_stats);
- transport_stats->setAlpha(0.0);
- }
- ret = consumer_socket_->setSocketOption(
- ConsumerCallbacksOptions::STATS_SUMMARY,
- (ConsumerTimerCallback)std::bind(&Impl::handleTimerExpiration, this,
- std::placeholders::_1,
- std::placeholders::_2));
+ ret = consumer_socket_->setSocketOption(
+ GeneralTransportOptions::MANIFEST_FACTOR_RELEVANT,
+ configuration_.manifest_factor_relevant_);
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- if (ret == SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
- }
+ ret = consumer_socket_->setSocketOption(
+ GeneralTransportOptions::MANIFEST_FACTOR_ALERT,
+ configuration_.manifest_factor_alert_);
- if (consumer_socket_->setSocketOption(
- GeneralTransportOptions::STATS_INTERVAL,
- configuration_.report_interval_milliseconds_) ==
- SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
- }
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- consumer_socket_->connect();
+ ret = consumer_socket_->setSocketOption(
+ GeneralTransportOptions::PACKET_FORMAT,
+ configuration_.packet_format_);
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ getOutputStream() << "ERROR -- Impossible to set the packet format."
+ << std::endl;
+ return ERROR_SETUP;
+ }
- return ERROR_SUCCESS;
- }
+ ret = consumer_socket_->setSocketOption(
+ ConsumerCallbacksOptions::FWD_STRATEGY_CHANGE,
+ (StrategyCallback)[](
+ [[maybe_unused]] transport::interface::notification::Strategy
+ strategy){
+ // nothing to do
+ });
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- int run() {
- std::cout << "Starting download of " << configuration_.name << std::endl;
+ ret = consumer_socket_->setSocketOption(
+ ConsumerCallbacksOptions::REC_STRATEGY_CHANGE,
+ (StrategyCallback)[](
+ [[maybe_unused]] transport::interface::notification::Strategy
+ strategy){
+ // nothing to do
+ });
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- signals_.add(SIGINT);
- signals_.async_wait(
- [this](const std::error_code &, const int &) { io_service_.stop(); });
+ ret = consumer_socket_->setSocketOption(
+ transport::interface::CURRENT_WINDOW_SIZE, configuration_.window_);
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ getOutputStream()
+ << "ERROR -- Impossible to set the size of the window."
+ << std::endl;
+ return ERROR_SETUP;
+ }
- t_download_ = t_stats_ = std::chrono::steady_clock::now();
- consumer_socket_->asyncConsume(configuration_.name);
- io_service_.run();
+ if (!configuration_.producer_certificate_.empty()) {
+ verifier = std::make_shared<transport::auth::AsymmetricVerifier>(
+ configuration_.producer_certificate_);
+ }
- consumer_socket_->stop();
+ if (!configuration_.passphrase_.empty()) {
+ verifier = std::make_shared<transport::auth::SymmetricVerifier>(
+ configuration_.passphrase_);
+ }
- return ERROR_SUCCESS;
- }
+ verifier->setVerificationFailedCallback(
+ std::bind(&HIperfClient::Impl::ConsumerContext::onAuthFailed, this,
+ std::placeholders::_1, std::placeholders::_2));
- private:
- class RTCCallback : public ConsumerSocket::ReadCallback {
- static constexpr std::size_t mtu = 1500;
+ ret = consumer_socket_->setSocketOption(GeneralTransportOptions::VERIFIER,
+ verifier);
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- public:
- RTCCallback(Impl &hiperf_client) : client_(hiperf_client) {
- client_.configuration_.receive_buffer = utils::MemBuf::create(mtu);
- }
+ // Signer for aggregatd interests
+ std::shared_ptr<transport::auth::Signer> signer =
+ std::make_shared<transport::auth::VoidSigner>();
+ if (!configuration_.aggr_interest_passphrase_.empty()) {
+ signer = std::make_shared<transport::auth::SymmetricSigner>(
+ transport::auth::CryptoSuite::HMAC_SHA256,
+ configuration_.aggr_interest_passphrase_);
+ }
+ ret = consumer_socket_->setSocketOption(GeneralTransportOptions::SIGNER,
+ signer);
+ if (ret == SOCKET_OPTION_NOT_SET) return ERROR_SETUP;
- bool isBufferMovable() noexcept override { return false; }
+ if (configuration_.aggregated_interests_) {
+ ret = consumer_socket_->setSocketOption(
+ RtcTransportOptions::AGGREGATED_INTERESTS, true);
- void getReadBuffer(uint8_t **application_buffer,
- size_t *max_length) override {
- *application_buffer =
- client_.configuration_.receive_buffer->writableData();
- *max_length = mtu;
- }
+ if (ret == SOCKET_OPTION_NOT_SET) return ERROR_SETUP;
+ }
- void readDataAvailable(std::size_t length) noexcept override {
- client_.received_bytes_ += length;
- client_.received_data_pkt_++;
+ ret = consumer_socket_->setSocketOption(
+ ConsumerCallbacksOptions::INTEREST_OUTPUT,
+ (transport::interface::ConsumerInterestCallback)std::bind(
+ &ConsumerContext::processLeavingInterest, this,
+ std::placeholders::_1, std::placeholders::_2));
- // collecting delay stats. Just for performance testing
- uint64_t *senderTimeStamp =
- (uint64_t *)client_.configuration_.receive_buffer->writableData();
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch())
- .count();
- double new_delay = (double)(now - *senderTimeStamp);
+ ret = consumer_socket_->setSocketOption(
+ ConsumerCallbacksOptions::READ_CALLBACK, this);
- if (*senderTimeStamp > now)
- new_delay = -1 * (double)(*senderTimeStamp - now);
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
- client_.delay_sample_++;
- client_.avg_data_delay_ =
- client_.avg_data_delay_ +
- (new_delay - client_.avg_data_delay_) / client_.delay_sample_;
+ ret = consumer_socket_->setSocketOption(
+ ConsumerCallbacksOptions::STATS_SUMMARY,
+ (transport::interface::ConsumerTimerCallback)std::bind(
+ &Impl::ConsumerContext::handleTimerExpiration, this,
+ std::placeholders::_1, std::placeholders::_2));
- if (client_.configuration_.test_mode_) {
- client_.data_delays_ += std::to_string(int(new_delay));
- client_.data_delays_ += ",";
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
}
- if (client_.configuration_.relay_) {
- client_.producer_socket_->produceDatagram(
- client_.configuration_.relay_name_.getName(),
- client_.configuration_.receive_buffer->writableData(),
- length < 1400 ? length : 1400);
- }
- if (client_.configuration_.output_stream_mode_) {
- uint8_t *start =
- (uint8_t *)client_.configuration_.receive_buffer->writableData();
- start += sizeof(uint64_t);
- std::size_t pkt_len = length - sizeof(uint64_t);
- client_.socket_.send_to(asio::buffer(start, pkt_len), client_.remote_);
+ if (consumer_socket_->setSocketOption(
+ GeneralTransportOptions::STATS_INTERVAL,
+ configuration_.report_interval_milliseconds_) ==
+ SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
}
- }
- size_t maxBufferSize() const override { return mtu; }
+ consumer_socket_->connect();
- void readError(const std::error_code ec) noexcept override {
- std::cerr << "Error while reading from RTC socket" << std::endl;
- client_.io_service_.stop();
+ return ERROR_SUCCESS;
}
- void readSuccess(std::size_t total_size) noexcept override {
- std::cout << "Data successfully read" << std::endl;
- }
+ /***************************************************************
+ * Run functions
+ ***************************************************************/
- private:
- Impl &client_;
- };
+ int run() {
+ getOutputStream() << "Starting download of " << flow_name_ << std::endl;
- class Callback : public ConsumerSocket::ReadCallback {
- public:
- Callback(Impl &hiperf_client) : client_(hiperf_client) {
- client_.configuration_.receive_buffer =
- utils::MemBuf::create(client_.configuration_.receive_buffer_size_);
+ saved_stats_.t_download_ = saved_stats_.t_stats_ =
+ utils::SteadyTime::now();
+ consumer_socket_->consume(flow_name_);
+
+ return ERROR_SUCCESS;
}
- bool isBufferMovable() noexcept override { return false; }
+ // Members initialized by the constructor
+ std::shared_ptr<utils::MemBuf> receive_buffer_;
+ asio::ip::udp::socket socket_;
+ std::size_t payload_size_max_;
+ asio::ip::udp::endpoint remote_;
+ std::uint32_t nb_iterations_;
- void getReadBuffer(uint8_t **application_buffer,
- size_t *max_length) override {
- *application_buffer =
- client_.configuration_.receive_buffer->writableData();
- *max_length = client_.configuration_.receive_buffer_size_;
- }
+ // Members initialized by in-class initializer
+ SavedStatistics saved_stats_{};
+ uint16_t header_counter_{0};
+ bool first_{true};
+ std::unique_ptr<ConsumerSocket> consumer_socket_;
+ std::unique_ptr<ProducerSocket> producer_socket_;
+ };
- void readDataAvailable(std::size_t length) noexcept override {}
+ public:
+ explicit Impl(const hiperf::ClientConfiguration &conf)
+ : config_(conf), signals_(io_service_) {}
- void readBufferAvailable(
- std::unique_ptr<utils::MemBuf> &&buffer) noexcept override {}
+ virtual ~Impl() = default;
- size_t maxBufferSize() const override {
- return client_.configuration_.receive_buffer_size_;
+ int setup() {
+ int ret = ensureFlows(config_.name_, config_.parallel_flows_);
+ if (ret != ERROR_SUCCESS) {
+ return ret;
}
- void readError(const std::error_code ec) noexcept override {
- std::cerr << "Error " << ec.message() << " while reading from socket"
- << std::endl;
- client_.io_service_.stop();
- }
+ consumer_contexts_.reserve(config_.parallel_flows_);
+ for (uint32_t i = 0; i < config_.parallel_flows_; i++) {
+ auto &ctx = consumer_contexts_.emplace_back(*this, i);
+ ret = ctx.setup();
- void readSuccess(std::size_t total_size) noexcept override {
- Time t2 = std::chrono::steady_clock::now();
- TimeDuration dt =
- std::chrono::duration_cast<TimeDuration>(t2 - client_.t_download_);
- long usec = (long)dt.count();
+ if (ret) {
+ break;
+ }
+ }
- std::cout << "Content retrieved. Size: " << total_size << " [Bytes]"
- << std::endl;
+ return ret;
+ }
- std::cerr << "Elapsed Time: " << usec / 1000000.0 << " seconds -- "
- << (total_size * 8) * 1.0 / usec * 1.0 << " [Mbps]"
- << std::endl;
+ int run() {
+ signals_.add(SIGINT);
+ signals_.async_wait(
+ [this](const std::error_code &, const int &) { io_service_.stop(); });
- client_.io_service_.stop();
+ for (auto &consumer_context : consumer_contexts_) {
+ consumer_context.run();
}
- private:
- Impl &client_;
- };
+ io_service_.run();
+
+ return ERROR_SUCCESS;
+ }
- hiperf::ClientConfiguration configuration_;
- Time t_stats_;
- Time t_download_;
- uint32_t total_duration_milliseconds_;
- uint64_t old_bytes_value_;
- uint64_t old_interest_tx_value_;
- uint64_t old_fec_interest_tx_value_;
- uint64_t old_fec_data_rx_value_;
- uint64_t old_lost_data_value_;
- uint64_t old_bytes_recovered_value_;
- uint64_t old_definitely_lost_data_value_;
- uint32_t old_retx_value_;
- uint32_t old_sent_int_value_;
- uint32_t old_received_nacks_value_;
- uint32_t old_fec_pkt_;
-
- // IMPORTANT: to be used only for performance testing, when consumer and
- // producer are synchronized. Used for rtc only at the moment
- double avg_data_delay_;
- uint32_t delay_sample_;
-
- uint32_t received_bytes_;
- uint32_t received_data_pkt_;
-
- std::string data_delays_;
+ ClientConfiguration &getConfig() { return config_; }
+ private:
asio::io_service io_service_;
+ hiperf::ClientConfiguration config_;
asio::signal_set signals_;
- RTCCallback rtc_callback_;
- Callback callback_;
- std::unique_ptr<ConsumerSocket> consumer_socket_;
- std::unique_ptr<ProducerSocket> producer_socket_;
- asio::ip::udp::socket socket_;
- asio::ip::udp::endpoint remote_;
-
- ForwarderConfiguration config_;
- uint16_t switch_threshold_; /* ms */
- bool done_;
- std::vector<ForwarderInterface::RouteInfoPtr> main_routes_;
- std::vector<ForwarderInterface::RouteInfoPtr> backup_routes_;
-#ifdef FORWARDER_INTERFACE
- ForwarderInterface forwarder_interface_;
-#endif
+ std::vector<ConsumerContext> consumer_contexts_;
};
-HIperfClient::HIperfClient(const ClientConfiguration &conf) {
- impl_ = new Impl(conf);
-}
+HIperfClient::HIperfClient(const ClientConfiguration &conf)
+ : impl_(std::make_unique<Impl>(conf)) {}
-HIperfClient::~HIperfClient() { delete impl_; }
+HIperfClient::~HIperfClient() = default;
-int HIperfClient::setup() { return impl_->setup(); }
+int HIperfClient::setup() const { return impl_->setup(); }
-void HIperfClient::run() { impl_->run(); }
+void HIperfClient::run() const { impl_->run(); }
} // namespace hiperf
diff --git a/apps/hiperf/src/client.h b/apps/hiperf/src/client.h
index f45b9af43..beecbd473 100644
--- a/apps/hiperf/src/client.h
+++ b/apps/hiperf/src/client.h
@@ -16,19 +16,21 @@
#pragma once
#include <common.h>
+#include <hicn/transport/utils/noncopyable.h>
namespace hiperf {
-class HIperfClient {
+class HIperfClient : public ::utils::NonCopyable {
public:
- HIperfClient(const ClientConfiguration &conf);
+ explicit HIperfClient(const ClientConfiguration &conf);
+
~HIperfClient();
- int setup();
- void run();
+ int setup() const;
+ void run() const;
private:
class Impl;
- Impl *impl_;
+ std::unique_ptr<Impl> impl_;
};
-} // namespace hiperf \ No newline at end of file
+} // namespace hiperf
diff --git a/apps/hiperf/src/common.h b/apps/hiperf/src/common.h
index e6ba526f9..0f96bef1f 100644
--- a/apps/hiperf/src/common.h
+++ b/apps/hiperf/src/common.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,27 +15,28 @@
#pragma once
-#include <hicn/transport/auth/identity.h>
#include <hicn/transport/auth/signer.h>
#include <hicn/transport/config.h>
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/interest.h>
#include <hicn/transport/interfaces/global_conf_interface.h>
-#include <hicn/transport/interfaces/p2psecure_socket_consumer.h>
-#include <hicn/transport/interfaces/p2psecure_socket_producer.h>
#include <hicn/transport/interfaces/socket_consumer.h>
#include <hicn/transport/interfaces/socket_producer.h>
#include <hicn/transport/utils/chrono_typedefs.h>
+#include <hicn/transport/utils/color.h>
#include <hicn/transport/utils/literals.h>
#ifndef _WIN32
#include <hicn/transport/utils/daemonizator.h>
#endif
+#include <hicn/apps/utils/logger.h>
+
#include <asio.hpp>
#include <cmath>
#include <fstream>
#include <iomanip>
+#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
@@ -43,43 +44,151 @@
#ifndef ERROR_SUCCESS
#define ERROR_SUCCESS 0
#endif
-#define ERROR_SETUP -5
-#define MIN_PROBE_SEQ 0xefffffff
-
-using namespace transport::interface;
-using namespace transport::auth;
-using namespace transport::core;
-
-static inline uint64_t _ntohll(const uint64_t *input) {
- uint64_t return_val;
- uint8_t *tmp = (uint8_t *)&return_val;
-
- tmp[0] = *input >> 56;
- tmp[1] = *input >> 48;
- tmp[2] = *input >> 40;
- tmp[3] = *input >> 32;
- tmp[4] = *input >> 24;
- tmp[5] = *input >> 16;
- tmp[6] = *input >> 8;
- tmp[7] = *input >> 0;
-
- return return_val;
-}
+static constexpr int ERROR_SETUP = -5;
+static constexpr uint32_t MIN_PROBE_SEQ = 0xefffffff;
+static constexpr uint32_t RTC_HEADER_SIZE = 12;
+static constexpr uint32_t FEC_HEADER_MAX_SIZE = 36;
+static constexpr uint32_t HIPERF_MTU = 1500;
+
+namespace hiperf {
+
+using transport::core::Packet;
+using transport::core::Prefix;
+
+/**
+ * Logger
+ */
+template <typename D, typename ConfType, typename ParentType>
+class Base : public std::stringbuf, public std::ostream {
+ protected:
+ static inline const char separator[] = "| ";
+
+ Base(ParentType &parent, asio::io_service &io_service, int identifier)
+ : std::stringbuf(),
+ std::ostream(this),
+ parent_(parent),
+ configuration_(parent_.getConfig()),
+ io_service_(io_service),
+ identifier_(identifier),
+ name_id_(D::getContextType() + std::to_string(identifier_)),
+ flow_name_(configuration_.name_.makeNameWithIndex(identifier_)) {
+ std::stringstream begin;
+ std::stringstream end;
+ if (configuration_.colored_) {
+ begin << color_mod_ << bold_mod_;
+ end << end_mod_;
+ } else {
+ begin << "";
+ end << "";
+ }
+
+ begin << "|" << name_id_ << separator;
+ begin_ = begin.str();
+ end_ = end.str();
+ }
+
+ Base(Base &&other) noexcept
+ : parent_(other.parent_),
+ configuration_(other.configuration_),
+ io_service_(other.io_service_),
+ identifier_(other.identifier_),
+ name_id_(std::move(other.name_id_)),
+ flow_name_(other.flow_name_) {}
+
+ ~Base() {}
+
+ /***************************************************************
+ * std::stringbuf sync override
+ ***************************************************************/
+
+ int sync() override {
+ auto string = str();
+ asio::post(io_service_,
+ [this, string]() { LoggerInfo() << begin_ << string << end_; });
+ str("");
+
+ return 0;
+ }
+
+ std::ostream &getOutputStream() { return *this; }
-static inline uint64_t _htonll(const uint64_t *input) {
- return (_ntohll(input));
+ // Members initialized by the constructor
+ ParentType &parent_;
+ ConfType &configuration_;
+ asio::io_service &io_service_;
+ int identifier_;
+ std::string name_id_;
+ transport::core::Name flow_name_;
+ std::string begin_;
+ std::string end_;
+
+ // Members initialized by the in-class initializer
+ utils::ColorModifier color_mod_;
+ utils::ColorModifier bold_mod_{utils::ColorModifier::Code::BOLD};
+ utils::ColorModifier end_mod_{utils::ColorModifier::Code::RESET};
+};
+
+static inline int ensureFlows(const Prefix &prefix, std::size_t flows) {
+ int ret = ERROR_SUCCESS;
+
+ // Make sure the provided prefix length not allows to accomodate the
+ // provided number of flows.
+ uint16_t max_ip_addr_len_bits;
+ uint16_t log2_n_flow;
+ u64 max_n_flow;
+ if (prefix.getAddressFamily() == AF_INET) {
+ max_ip_addr_len_bits = IPV4_ADDR_LEN_BITS;
+ } else if (prefix.getAddressFamily() == AF_INET6) {
+ max_ip_addr_len_bits = IPV6_ADDR_LEN_BITS;
+ } else {
+ LoggerErr() << "Error: unknown address family.";
+ ret = ERROR_SETUP;
+ goto END;
+ }
+
+ log2_n_flow = max_ip_addr_len_bits - prefix.getPrefixLength();
+ max_n_flow = log2_n_flow < 64 ? (1 << log2_n_flow) : ~0ULL;
+
+ if (flows > max_n_flow) {
+ LoggerErr() << "Error: the provided prefix length does not allow to "
+ "accomodate the provided number of flows ("
+ << flows << " > " << max_n_flow << ").";
+ ret = ERROR_SETUP;
+ }
+
+END:
+ return ret;
}
-namespace hiperf {
+/**
+ * Class to retrieve the maximum payload size given the MTU and packet headers.
+ */
+class PayloadSize {
+ public:
+ PayloadSize(Packet::Format format, std::size_t mtu = HIPERF_MTU)
+ : mtu_(mtu), format_(format) {}
+
+ std::size_t getPayloadSizeMax(std::size_t transport_size = 0,
+ std::size_t fec_size = 0,
+ std::size_t signature_size = 0) {
+ return mtu_ - Packet::getHeaderSizeFromFormat(format_, signature_size) -
+ transport_size - fec_size;
+ }
+
+ private:
+ std::size_t mtu_;
+ Packet::Format format_;
+};
/**
* Class for handling the production rate for the RTC producer.
*/
class Rate {
public:
- Rate() : rate_kbps_(0) {}
+ Rate() {}
+ ~Rate() {}
- Rate(const std::string &rate) {
+ explicit Rate(const std::string &rate) {
std::size_t found = rate.find("kbps");
if (found != std::string::npos) {
rate_kbps_ = std::stof(rate.substr(0, found));
@@ -107,7 +216,7 @@ class Rate {
}
private:
- float rate_kbps_;
+ float rate_kbps_ = 0.0;
};
struct packet_t {
@@ -115,103 +224,71 @@ struct packet_t {
uint32_t size;
};
+struct Configuration {
+ Prefix name_{"b001::abcd/64"};
+ std::string passphrase_;
+ std::string aggr_interest_passphrase_;
+ bool rtc_{false};
+ uint16_t port_{0};
+ bool aggregated_data_{false};
+ Packet::Format packet_format_{
+ transport::interface::default_values::packet_format};
+ uint32_t parallel_flows_{1};
+ bool colored_{true};
+};
+
/**
* Container for command line configuration for hiperf client.
*/
-struct ClientConfiguration {
- ClientConfiguration()
- : name("b001::abcd", 0),
- beta(-1.f),
- drop_factor(-1.f),
- window(-1),
- producer_certificate(""),
- passphrase(""),
- receive_buffer(nullptr),
- receive_buffer_size_(128 * 1024),
- download_size(0),
- report_interval_milliseconds_(1000),
- transport_protocol_(CBR),
- rtc_(false),
- test_mode_(false),
- relay_(false),
- secure_(false),
- producer_prefix_(),
- interest_lifetime_(500),
- relay_name_("c001::abcd/64"),
- output_stream_mode_(false),
- port_(0) {}
-
- Name name;
- double beta;
- double drop_factor;
- double window;
- std::string producer_certificate;
- std::string passphrase;
- std::shared_ptr<utils::MemBuf> receive_buffer;
- std::size_t receive_buffer_size_;
- std::size_t download_size;
- std::uint32_t report_interval_milliseconds_;
- TransportProtocolAlgorithms transport_protocol_;
- bool rtc_;
- bool test_mode_;
- bool relay_;
- bool secure_;
+struct ClientConfiguration : Configuration {
+ double beta_{-1.f};
+ double drop_factor_{-1.f};
+ double window_{-1.f};
+ std::string producer_certificate_;
+ std::size_t receive_buffer_size_{128 * 1024};
+ std::uint32_t report_interval_milliseconds_{1000};
+ transport::interface::TransportProtocolAlgorithms transport_protocol_{
+ transport::interface::CBR};
+ bool test_mode_{false};
+ bool relay_{false};
Prefix producer_prefix_;
- uint32_t interest_lifetime_;
- Prefix relay_name_;
- bool output_stream_mode_;
- uint16_t port_;
+ uint32_t interest_lifetime_{500};
+ uint32_t manifest_factor_relevant_{100};
+ uint32_t manifest_factor_alert_{20};
+ Prefix relay_name_{"c001::abcd/64"};
+ bool output_stream_mode_{false};
+ uint32_t recovery_strategy_{4};
+ bool print_headers_{true};
+ std::uint32_t nb_iterations_{
+ std::numeric_limits<decltype(nb_iterations_)>::max()};
+ bool content_sharing_mode_{false};
+ bool aggregated_interests_{false};
};
/**
* Container for command line configuration for hiperf server.
*/
-struct ServerConfiguration {
- ServerConfiguration()
- : name("b001::abcd/64"),
- virtual_producer(true),
- manifest(false),
- live_production(false),
- content_lifetime(600000000_U32),
- download_size(20 * 1024 * 1024),
- hash_algorithm(CryptoHashType::SHA256),
- keystore_name(""),
- passphrase(""),
- keystore_password("cisco"),
- multiphase_produce_(false),
- rtc_(false),
- interactive_(false),
- trace_based_(false),
- trace_index_(0),
- trace_file_(nullptr),
- production_rate_(std::string("2048kbps")),
- payload_size_(1400),
- secure_(false),
- input_stream_mode_(false),
- port_(0) {}
-
- Prefix name;
- bool virtual_producer;
- bool manifest;
- bool live_production;
- std::uint32_t content_lifetime;
- std::uint32_t download_size;
- CryptoHashType hash_algorithm;
- std::string keystore_name;
- std::string passphrase;
- std::string keystore_password;
- bool multiphase_produce_;
- bool rtc_;
- bool interactive_;
- bool trace_based_;
- std::uint32_t trace_index_;
- char *trace_file_;
- Rate production_rate_;
- std::size_t payload_size_;
- bool secure_;
- bool input_stream_mode_;
- uint16_t port_;
+struct ServerConfiguration : Configuration {
+ bool virtual_producer_{true};
+ std::uint32_t manifest_max_capacity_{0};
+ bool live_production_{false};
+ std::uint32_t content_lifetime_{
+ transport::interface::default_values::content_object_expiry_time};
+ std::uint32_t download_size_{20 * 1024 * 1024};
+ transport::auth::CryptoHashType hash_algorithm_{
+ transport::auth::CryptoHashType::SHA256};
+ std::string keystore_name_;
+ std::string keystore_password_{"cisco"};
+ bool multiphase_produce_{false};
+ bool interactive_{false};
+ bool trace_based_{false};
+ std::uint32_t trace_index_{0};
+ char *trace_file_{nullptr};
+ Rate production_rate_{"2048kbps"};
+ std::size_t payload_size_{1384};
+ bool input_stream_mode_{false};
std::vector<struct packet_t> trace_;
+ std::string fec_type_;
};
} // namespace hiperf
diff --git a/apps/hiperf/src/forwarder_config.h b/apps/hiperf/src/forwarder_config.h
deleted file mode 100644
index 655ac3b66..000000000
--- a/apps/hiperf/src/forwarder_config.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace hiperf {
-
-struct ListenerConfig {
- std::string address;
- std::uint16_t port;
- std::string interface;
- std::string name;
-};
-
-struct ConnectorConfig {
- std::string local_address;
- std::uint16_t local_port;
- std::string remote_address;
- std::uint16_t remote_port;
- std::string interface;
- std::string name;
-};
-
-struct RouteConfig {
- std::string prefix;
- uint16_t weight;
- std::string main_connector;
- std::string backup_connector;
- std::string name;
-};
-
-class ForwarderConfiguration {
- public:
- ForwarderConfiguration() : n_threads_(1) {}
-
- bool empty() {
- return listeners_.empty() && connectors_.empty() && routes_.empty();
- }
-
- ForwarderConfiguration &setThreadNumber(std::size_t threads) {
- n_threads_ = threads;
- return *this;
- }
-
- std::size_t getThreadNumber() { return n_threads_; }
-
- template <typename... Args>
- ForwarderConfiguration &addListener(Args &&...args) {
- listeners_.emplace_back(std::forward<Args>(args)...);
- return *this;
- }
-
- template <typename... Args>
- ForwarderConfiguration &addConnector(const std::string &name,
- Args &&...args) {
- connectors_.emplace(name, std::forward<Args>(args)...);
- return *this;
- }
-
- template <typename... Args>
- ForwarderConfiguration &addRoute(Args &&...args) {
- routes_.emplace_back(std::forward<Args>(args)...);
- return *this;
- }
-
- std::vector<ListenerConfig> &getListeners() { return listeners_; }
-
- std::unordered_map<std::string, ConnectorConfig> &getConnectors() {
- return connectors_;
- }
-
- std::vector<RouteConfig> &getRoutes() { return routes_; }
-
- private:
- std::vector<ListenerConfig> listeners_;
- std::unordered_map<std::string, ConnectorConfig> connectors_;
- std::vector<RouteConfig> routes_;
- std::size_t n_threads_;
-};
-
-} \ No newline at end of file
diff --git a/apps/hiperf/src/forwarder_interface.cc b/apps/hiperf/src/forwarder_interface.cc
deleted file mode 100644
index 864208239..000000000
--- a/apps/hiperf/src/forwarder_interface.cc
+++ /dev/null
@@ -1,676 +0,0 @@
-/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <arpa/inet.h>
-#include <forwarder_interface.h>
-#include <hicn/transport/utils/log.h>
-
-#include <chrono>
-#include <iostream>
-#include <thread>
-#include <unordered_set>
-
-extern "C" {
-#include <hicn/error.h>
-#include <hicn/util/ip_address.h>
-}
-
-// XXX the main listener should be retrieve in this class at initialization, aka
-// when hICN becomes avialable
-//
-// XXX the main listener port will be retrieved in the forwarder
-// interface... everything else will be delayed until we have this
-// information
-
-namespace hiperf {
-
-ForwarderInterface::ForwarderInterface(asio::io_service &io_service,
- ICallback *callback)
- : external_ioservice_(io_service),
- forwarder_interface_callback_(callback),
- work_(std::make_unique<asio::io_service::work>(internal_ioservice_)),
- sock_(nullptr),
- thread_(std::make_unique<std::thread>([this]() {
- std::cout << "Starting Forwarder Interface thread" << std::endl;
- internal_ioservice_.run();
- std::cout << "Stopping Forwarder Interface thread" << std::endl;
- })),
- // set_route_callback_(std::forward<Callback &&>(setRouteCallback)),
- check_routes_timer_(nullptr),
- pending_add_route_counter_(0),
- hicn_listen_port_(9695),
- /* We start in disabled state even when a forwarder is always available */
- state_(State::Disabled),
- timer_(io_service),
- num_reattempts(0) {
- std::cout << "Forwarder interface created... connecting to forwarder...\n";
- internal_ioservice_.post([this]() { onHicnServiceAvailable(true); });
-}
-
-ForwarderInterface::~ForwarderInterface() {
- if (thread_ && thread_->joinable()) {
- internal_ioservice_.dispatch([this]() {
- if (sock_) {
- hc_sock_free(sock_);
- sock_ = nullptr;
- }
-
- work_.reset();
- });
-
- thread_->join();
- }
-
- std::cout << "ForwarderInterface::~ForwarderInterface" << std::endl;
-}
-
-void ForwarderInterface::onHicnServiceAvailable(bool flag) {
- if (flag) {
- switch (state_) {
- case State::Disabled:
- case State::Requested:
- state_ = State::Available;
- case State::Available:
- connectToForwarder();
- /* Synchronous */
- if (state_ != State::Connected) {
- std::cout << "ConnectToForwarder failed" << std::endl;
- goto REATTEMPT;
- }
- state_ = State::Ready;
-
- std::cout << "Connected to forwarder... cancelling reconnection timer"
- << std::endl;
- timer_.cancel();
- num_reattempts = 0;
-
- // case State::Connected:
- // checkListener();
-
- // if (state_ != State::Ready) {
- // std::cout << "Listener not found" << std::endl;
- // goto REATTEMPT;
- // }
- // state_ = State::Ready;
-
- // timer_.cancel();
- // num_reattempts = 0;
-
- std::cout << "Forwarder interface is ready... communicate to controller"
- << std::endl;
-
- forwarder_interface_callback_->onHicnServiceReady();
-
- case State::Ready:
- break;
- }
- } else {
- if (sock_) {
- hc_sock_free(sock_);
- sock_ = nullptr;
- }
- state_ = State::Disabled; // XXX to be checked upon callback to prevent the
- // state from going forward (used to manage
- // concurrency)
- }
- return;
-
-REATTEMPT:
- /* Schedule reattempt */
- std::cout << "Failed to connect, scheduling reattempt" << std::endl;
- num_reattempts++;
-
- timer_.expires_from_now(
- std::chrono::milliseconds(ForwarderInterface::REATTEMPT_DELAY_MS));
- // timer_.async_wait(std::bind(&ForwarderInterface::onHicnServiceAvailable,
- // this, flag, std::placeholders::_1));
- timer_.async_wait([this, flag](std::error_code ec) {
- if (ec) return;
- onHicnServiceAvailable(flag);
- });
-}
-
-int ForwarderInterface::connectToForwarder() {
- sock_ = hc_sock_create();
- if (!sock_) {
- std::cout << "Could not create socket" << std::endl;
- goto ERR_SOCK;
- }
-
- if (hc_sock_connect(sock_) < 0) {
- std::cout << "Could not connect to forwarder" << std::endl;
- goto ERR;
- }
-
- std::cout << "Forwarder interface connected" << std::endl;
- state_ = State::Connected;
- return 0;
-
-ERR:
- hc_sock_free(sock_);
- sock_ = nullptr;
-ERR_SOCK:
- return -1;
-}
-
-int ForwarderInterface::checkListener() {
- if (!sock_) return -1;
-
- hc_data_t *data;
- if (hc_listener_list(sock_, &data) < 0) return -1;
-
- int ret = -1;
- foreach_listener(l, data) {
- std::string interface = std::string(l->interface_name);
- if (interface.compare("lo") != 0) {
- hicn_listen_port_ = l->local_port;
- state_ = State::Ready;
- ret = 0;
- std::cout << "Got listener port" << std::endl;
- break;
- }
- }
-
- hc_data_free(data);
- return ret;
-}
-
-void ForwarderInterface::close() {
- std::cout << "ForwarderInterface::close" << std::endl;
-
- state_ = State::Disabled;
- /* Cancelling eventual reattempts */
- timer_.cancel();
-
- if (sock_) {
- hc_sock_free(sock_);
- sock_ = nullptr;
- }
-
- internal_ioservice_.post([this]() { work_.reset(); });
-
- if (thread_->joinable()) {
- thread_->join();
- }
-}
-
-#if 0
-void ForwarderInterface::enableCheckRoutesTimer() {
- if (check_routes_timer_ != nullptr) return;
-
- check_routes_timer_ =
- std::make_unique<asio::steady_timer>(internal_ioservice_);
- checkRoutesLoop();
-}
-
-void ForwarderInterface::removeConnectedUserNow(ProtocolPtr protocol) {
- internalRemoveConnectedUser(protocol);
-}
-
-void ForwarderInterface::scheduleRemoveConnectedUser(ProtocolPtr protocol) {
- internal_ioservice_.post(
- [this, protocol]() { internalRemoveConnectedUser(protocol); });
-}
-#endif
-
-void ForwarderInterface::createFaceAndRoute(const RouteInfoPtr &route_info) {
- std::vector<RouteInfoPtr> routes;
- routes.push_back(std::move(route_info));
- createFaceAndRoutes(routes);
-}
-
-void ForwarderInterface::createFaceAndRoutes(
- const std::vector<RouteInfoPtr> &routes_info) {
- pending_add_route_counter_++;
- auto timer = new asio::steady_timer(internal_ioservice_);
- internal_ioservice_.post([this, routes_info, timer]() {
- internalCreateFaceAndRoutes(routes_info, ForwarderInterface::MAX_REATTEMPT,
- timer);
- });
-}
-
-void ForwarderInterface::deleteFaceAndRoute(const RouteInfoPtr &route_info) {
- std::vector<RouteInfoPtr> routes;
- routes.push_back(std::move(route_info));
- deleteFaceAndRoutes(routes);
-}
-
-void ForwarderInterface::deleteFaceAndRoutes(
- const std::vector<RouteInfoPtr> &routes_info) {
- internal_ioservice_.post([this, routes_info]() {
- for (auto &route : routes_info) {
- internalDeleteFaceAndRoute(route);
- }
- });
-}
-
-void ForwarderInterface::internalDeleteFaceAndRoute(
- const RouteInfoPtr &route_info) {
- if (!sock_) return;
-
- hc_data_t *data;
- if (hc_route_list(sock_, &data) < 0) return;
-
- std::vector<hc_route_t *> routes_to_remove;
- foreach_route(r, data) {
- char remote_addr[INET6_ADDRSTRLEN];
- int ret = ip_address_ntop(&r->remote_addr, remote_addr, r->len, r->family);
- if (ret < 0) continue;
-
- std::string route_addr(remote_addr);
- if (route_addr.compare(route_info->route_addr) == 0 &&
- r->len == route_info->route_len) {
- // route found
- routes_to_remove.push_back(r);
- }
- }
-
- if (routes_to_remove.size() == 0) {
- // nothing to do here
- hc_data_free(data);
- return;
- }
-
- std::unordered_set<uint32_t> connids_to_remove;
- for (unsigned i = 0; i < routes_to_remove.size(); i++) {
- connids_to_remove.insert(routes_to_remove[i]->face_id);
- if (hc_route_delete(sock_, routes_to_remove[i]) < 0) {
- std::cout << "Error removing route from forwarder." << std::endl;
- }
- }
-
- // remove connection
- if (hc_connection_list(sock_, &data) < 0) {
- hc_data_free(data);
- return;
- }
-
- // collects pointerst to the connections using the conn IDs
- std::vector<hc_connection_t *> conns_to_remove;
- foreach_connection(c, data) {
- if (connids_to_remove.find(c->id) != connids_to_remove.end()) {
- // conn found
- conns_to_remove.push_back(c);
- }
- }
-
- if (conns_to_remove.size() == 0) {
- // nothing else to do here
- hc_data_free(data);
- return;
- }
-
- for (unsigned i = 0; i < conns_to_remove.size(); i++) {
- if (hc_connection_delete(sock_, conns_to_remove[i]) < 0) {
- std::cout << "Error removing connection from forwarder." << std::endl;
- }
- }
-
- hc_data_free(data);
-}
-
-void ForwarderInterface::internalCreateFaceAndRoutes(
- const std::vector<RouteInfoPtr> &route_info, uint8_t max_try,
- asio::steady_timer *timer) {
- uint32_t face_id;
-
- std::vector<RouteInfoPtr> failed;
- for (auto &route : route_info) {
- int ret = tryToCreateFace(route.get(), &face_id);
- if (ret >= 0) {
- auto ret = tryToCreateRoute(route.get(), face_id);
- if (ret < 0) {
- failed.push_back(route);
- std::cerr << "Error creating route and face" << std::endl;
- continue;
- }
- }
- }
-
- if (failed.size() > 0) {
- if (max_try == 0) {
- /* All attempts failed */
- goto RESULT;
- }
- max_try--;
- timer->expires_from_now(std::chrono::milliseconds(500));
- timer->async_wait([this, failed, max_try, timer](std::error_code ec) {
- if (ec) return;
- internalCreateFaceAndRoutes(failed, max_try, timer);
- });
- return;
- }
-
-#if 0
- // route_status_[protocol] = std::move(route_info);
- for (size_t i = 0; i < route_info.size(); i++) {
- route_status_.insert(
- std::pair<ClientId, RouteInfoPtr>(protocol, std::move(route_info[i])));
- }
-#endif
-
-RESULT:
- std::cout << "Face / Route create ok, now calling back protocol" << std::endl;
- pending_add_route_counter_--;
- external_ioservice_.post([this, r = std::move(route_info)]() mutable {
- forwarder_interface_callback_->onRouteConfigured(r);
- });
- delete timer;
-}
-
-int ForwarderInterface::tryToCreateFace(RouteInfo *route_info,
- uint32_t *face_id) {
- bool found = false;
-
- // check connection with the forwarder
- if (!sock_) {
- std::cout << "[ForwarderInterface::tryToCreateFace] socket error"
- << std::endl;
- goto ERR_SOCK;
- }
-
- // get listeners list
- hc_data_t *data;
- if (hc_listener_list(sock_, &data) < 0) {
- std::cout << "[ForwarderInterface::tryToCreateFace] cannot list listeners";
- goto ERR_LIST;
- }
-
- char _local_address[128];
- foreach_listener(l, data) {
- std::cout << "Processing " << l->interface_name << std::endl;
- std::string interface = std::string(l->interface_name);
- int ret = ip_address_ntop(&l->local_addr, _local_address, 128, AF_INET);
- if (ret < 0) {
- std::cerr << "Error in ip_address_ntop" << std::endl;
- goto ERR;
- }
-
- std::string local_address = std::string(_local_address);
- uint16_t local_port = l->local_port;
-
- if (interface.compare(route_info->interface) == 0 &&
- local_address.compare(route_info->local_addr) == 0 &&
- local_port == route_info->local_port) {
- found = true;
- break;
- }
- }
-
- std::cout << route_info->remote_addr << std::endl;
-
- ip_address_t local_address, remote_address;
- ip_address_pton(route_info->local_addr.c_str(), &local_address);
- ip_address_pton(route_info->remote_addr.c_str(), &remote_address);
-
- if (!found) {
- // Create listener
- hc_listener_t listener;
- memset(&listener, 0, sizeof(hc_listener_t));
-
- std::string name = "l_" + route_info->name;
- listener.local_addr = local_address;
- listener.type = CONNECTION_TYPE_UDP;
- listener.family = AF_INET;
- listener.local_port = route_info->local_port;
- strncpy(listener.name, name.c_str(), sizeof(listener.name));
- strncpy(listener.interface_name, route_info->interface.c_str(),
- sizeof(listener.interface_name));
-
- std::cout << "------------> " << route_info->interface << std::endl;
-
- int ret = hc_listener_create(sock_, &listener);
-
- if (ret < 0) {
- std::cerr << "Error creating listener." << std::endl;
- return -1;
- } else {
- std::cout << "Listener " << listener.id << " created." << std::endl;
- }
- }
-
- // Create face
- hc_face_t face;
- memset(&face, 0, sizeof(hc_face_t));
-
- // crate face with the local interest
- face.face.type = FACE_TYPE_UDP;
- face.face.family = route_info->family;
- face.face.local_addr = local_address;
- face.face.remote_addr = remote_address;
- face.face.local_port = route_info->local_port;
- face.face.remote_port = route_info->remote_port;
-
- if (netdevice_set_name(&face.face.netdevice, route_info->interface.c_str()) <
- 0) {
- std::cout << "[ForwarderInterface::tryToCreateFaceAndRoute] "
- "netdevice_set_name "
- "("
- << face.face.netdevice.name << ", "
- << route_info->interface << ") error" << std::endl;
- goto ERR;
- }
-
- // create face
- if (hc_face_create(sock_, &face) < 0) {
- std::cout << "[ForwarderInterface::tryToCreateFace] error creating face";
- goto ERR;
- }
-
- std::cout << "Face created successfully" << std::endl;
-
- // assing face to the return value
- *face_id = face.id;
-
- hc_data_free(data);
- return 0;
-
-ERR:
- hc_data_free(data);
-ERR_LIST:
-ERR_SOCK:
- return -1;
-}
-
-int ForwarderInterface::tryToCreateRoute(RouteInfo *route_info,
- uint32_t face_id) {
- std::cout << "Trying to create route" << std::endl;
-
- // check connection with the forwarder
- if (!sock_) {
- std::cout << "[ForwarderInterface::tryToCreateRoute] socket error";
- return -1;
- }
-
- ip_address_t route_ip;
- hc_route_t route;
-
- if (ip_address_pton(route_info->route_addr.c_str(), &route_ip) < 0) {
- std::cout << "[ForwarderInterface::tryToCreateRoute] ip_address_pton error";
- return -1;
- }
-
- route.face_id = face_id;
- route.family = AF_INET6;
- route.remote_addr = route_ip;
- route.len = route_info->route_len;
- route.cost = 1;
-
- if (hc_route_create(sock_, &route) < 0) {
- std::cout << "[ForwarderInterface::tryToCreateRoute] error creating route";
- return -1;
- }
-
- std::cout << "[ForwarderInterface::tryToCreateRoute] OK" << std::endl;
- return 0;
-}
-
-#if 0 // not used
-void ForwarderInterface::checkRoutesLoop() {
- check_routes_timer_->expires_from_now(std::chrono::milliseconds(1000));
- check_routes_timer_->async_wait([this](std::error_code ec) {
- if (ec) return;
- if (pending_add_route_counter_ == 0) checkRoutes();
- });
-}
-
-void ForwarderInterface::checkRoutes() {
- std::cout << "someone called the checkRoutes function" << std::endl;
- if (!sock_) return;
-
- hc_data_t *data;
- if (hc_route_list(sock_, &data) < 0) {
- return;
- }
-
- std::unordered_set<std::string> routes_set;
- foreach_route(r, data) {
- char remote_addr[INET6_ADDRSTRLEN];
- int ret = ip_address_ntop(&r->remote_addr, remote_addr, r->len, r->family);
- if (ret < 0) continue;
- std::string route(std::string(remote_addr) + "/" + std::to_string(r->len));
- routes_set.insert(route);
- }
-
- for (auto it = route_status_.begin(); it != route_status_.end(); it++) {
- std::string route(it->second->route_addr + "/" +
- std::to_string(it->second->route_len));
- if (routes_set.find(route) == routes_set.end()) {
- // the route is missing
- createFaceAndRoute(it->second, it->first);
- break;
- }
- }
-
- hc_data_free(data);
-}
-#endif
-
-#if 0
- using ListenerRetrievedCallback =
- std::function<void(std::error_code, uint32_t)>;
-
- ListenerRetrievedCallback listener_retrieved_callback_;
-
-#ifdef __ANDROID__
- hicn_listen_port_(9695),
-#else
- hicn_listen_port_(0),
-#endif
- timer_(forward_engine_.getIoService()),
-
- void initConfigurationProtocol(void)
- {
- // We need the configuration, which is different for every protocol...
- // so we move this step down towards the protocol implementation itself.
- if (!permanent_hicn) {
- doInitConfigurationProtocol();
- } else {
- // XXX This should be moved somewhere else
- getMainListener(
- [this](std::error_code ec, uint32_t hicn_listen_port) {
- if (!ec)
- {
- hicn_listen_port_ = hicn_listen_port;
- doInitConfigurationProtocol();
- }
- });
- }
- }
-
- template <typename Callback>
- void getMainListener(Callback &&callback)
- {
- listener_retrieved_callback_ = std::forward<Callback &&>(callback);
- tryToConnectToForwarder();
- }
- private:
- void doGetMainListener(std::error_code ec)
- {
- if (!ec)
- {
- // ec == 0 --> timer expired
- int ret = forwarder_interface_.getMainListenerPort();
- if (ret <= 0)
- {
- // Since without the main listener of the forwarder the proxy cannot
- // work, we can stop the program here until we get the listener port.
- std::cout <<
- "Could not retrieve main listener port from the forwarder. "
- "Retrying.";
-
- timer_.expires_from_now(std::chrono::milliseconds(RETRY_INTERVAL));
- timer_.async_wait(std::bind(&Protocol::doGetMainListener, this,
- std::placeholders::_1));
- }
- else
- {
- timer_.cancel();
- retx_count_ = 0;
- hicn_listen_port_ = uint16_t(ret);
- listener_retrieved_callback_(
- make_error_code(configuration_error::success), hicn_listen_port_);
- }
- }
- else
- {
- std::cout << "Timer for retrieving main hicn listener canceled." << std::endl;
- }
- }
-
- void tryToConnectToForwarder()
- {
- doTryToConnectToForwarder(std::make_error_code(std::errc(0)));
- }
-
- void doTryToConnectToForwarder(std::error_code ec)
- {
- if (!ec)
- {
- // ec == 0 --> timer expired
- int ret = forwarder_interface_.connect();
- if (ret < 0)
- {
- // We were not able to connect to the local forwarder. Do not give up
- // and retry.
- std::cout << "Could not connect to local forwarder. Retrying." << std::endl;
-
- timer_.expires_from_now(std::chrono::milliseconds(RETRY_INTERVAL));
- timer_.async_wait(std::bind(&Protocol::doTryToConnectToForwarder, this,
- std::placeholders::_1));
- }
- else
- {
- timer_.cancel();
- retx_count_ = 0;
- doGetMainListener(std::make_error_code(std::errc(0)));
- }
- }
- else
- {
- std::cout << "Timer for re-trying forwarder connection canceled." << std::endl;
- }
- }
-
-
- template <typename ProtocolImplementation>
- constexpr uint32_t Protocol<ProtocolImplementation>::RETRY_INTERVAL;
-
-#endif
-
-constexpr uint32_t ForwarderInterface::REATTEMPT_DELAY_MS;
-constexpr uint32_t ForwarderInterface::MAX_REATTEMPT;
-
-} // namespace hiperf \ No newline at end of file
diff --git a/apps/hiperf/src/forwarder_interface.h b/apps/hiperf/src/forwarder_interface.h
deleted file mode 100644
index 7591ea257..000000000
--- a/apps/hiperf/src/forwarder_interface.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-extern "C" {
-#ifndef WITH_POLICY
-#define WITH_POLICY
-#endif
-#include <hicn/ctrl/api.h>
-#include <hicn/util/ip_address.h>
-}
-
-#ifndef ASIO_STANDALONE
-#define ASIO_STANDALONE
-#endif
-#include <asio.hpp>
-
-#include <functional>
-#include <thread>
-#include <unordered_map>
-
-namespace hiperf {
-
-class ForwarderInterface {
- static const uint32_t REATTEMPT_DELAY_MS = 500;
- static const uint32_t MAX_REATTEMPT = 10;
-
- public:
- struct RouteInfo {
- int family;
- std::string local_addr;
- uint16_t local_port;
- std::string remote_addr;
- uint16_t remote_port;
- std::string route_addr;
- uint8_t route_len;
- std::string interface;
- std::string name;
- };
-
- using RouteInfoPtr = std::shared_ptr<RouteInfo>;
-
- class ICallback {
- public:
- virtual void onHicnServiceReady() = 0;
- virtual void onRouteConfigured(std::vector<RouteInfoPtr> &route_info) = 0;
- };
-
- enum class State {
- Disabled, /* Stack is stopped */
- Requested, /* Stack is starting */
- Available, /* Forwarder is running */
- Connected, /* Control socket connected */
- Ready, /* Listener present */
- };
-
- public:
- ForwarderInterface(asio::io_service &io_service, ICallback *callback);
-
- ~ForwarderInterface();
-
- State getState();
-
- void setState(State state);
-
- void onHicnServiceAvailable(bool flag);
-
- void enableCheckRoutesTimer();
-
- void createFaceAndRoutes(const std::vector<RouteInfoPtr> &routes_info);
-
- void createFaceAndRoute(const RouteInfoPtr &route_info);
-
- void deleteFaceAndRoutes(const std::vector<RouteInfoPtr> &routes_info);
-
- void deleteFaceAndRoute(const RouteInfoPtr &route_info);
-
- void close();
-
- uint16_t getHicnListenerPort() { return hicn_listen_port_; }
-
- private:
- int connectToForwarder();
-
- int checkListener();
-
- void internalCreateFaceAndRoutes(const std::vector<RouteInfoPtr> &route_info,
- uint8_t max_try, asio::steady_timer *timer);
-
- void internalDeleteFaceAndRoute(const RouteInfoPtr &routes_info);
-
- int tryToCreateFace(RouteInfo *RouteInfo, uint32_t *face_id);
- int tryToCreateRoute(RouteInfo *RouteInfo, uint32_t face_id);
-
- void checkRoutesLoop();
-
- void checkRoutes();
-
- asio::io_service &external_ioservice_;
- asio::io_service internal_ioservice_;
- ICallback *forwarder_interface_callback_;
- std::unique_ptr<asio::io_service::work> work_;
- hc_sock_t *sock_;
- std::unique_ptr<std::thread> thread_;
- // SetRouteCallback set_route_callback_;
- // std::unordered_multimap<ProtocolPtr, RouteInfoPtr> route_status_;
- std::unique_ptr<asio::steady_timer> check_routes_timer_;
- uint32_t pending_add_route_counter_;
- uint16_t hicn_listen_port_;
-
- State state_;
-
- /* Reattempt timer */
- asio::steady_timer timer_;
- unsigned num_reattempts;
-};
-
-} // namespace hiperf
diff --git a/apps/hiperf/src/main.cc b/apps/hiperf/src/main.cc
index b2d99c4a4..25c1a288c 100644
--- a/apps/hiperf/src/main.cc
+++ b/apps/hiperf/src/main.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,133 +14,184 @@
*/
#include <client.h>
+#include <hicn/apps/utils/logger.h>
#include <server.h>
-#include <forwarder_interface.h>
namespace hiperf {
+using transport::auth::CryptoHashType;
+
+static std::unordered_map<std::string, hicn_packet_format_t> const
+ packet_format_map = {{"ipv4_tcp", HICN_PACKET_FORMAT_IPV4_TCP},
+ {"ipv6_tcp", HICN_PACKET_FORMAT_IPV6_TCP},
+ {"new", HICN_PACKET_FORMAT_NEW}};
+
+std::string str_tolower(std::string s) {
+ std::transform(s.begin(), s.end(), s.begin(),
+ [](unsigned char c) { return std::tolower(c); });
+ return s;
+}
+
void usage() {
- std::cerr << "HIPERF - A tool for performing network throughput "
- "measurements with hICN"
- << std::endl;
- std::cerr << "usage: hiperf [-S|-C] [options] [prefix|name]" << std::endl;
- std::cerr << std::endl;
- std::cerr << "SERVER OR CLIENT:" << std::endl;
+ LoggerInfo() << "HIPERF - Instrumentation tool for performing active network"
+ "measurements with hICN";
+ LoggerInfo() << "usage: hiperf [-S|-C] [options] [prefix|name]";
+ LoggerInfo();
+ LoggerInfo() << "SERVER OR CLIENT:";
#ifndef _WIN32
- std::cerr << "-D\t\t\t\t\t"
- << "Run as a daemon" << std::endl;
- std::cerr << "-R\t\t\t\t\t"
- << "Run RTC protocol (client or server)" << std::endl;
- std::cerr << "-f\t<filename>\t\t\t"
- << "Log file" << std::endl;
- std::cerr << "-z\t<io_module>\t\t\t"
- << "IO module to use. Default: hicnlight_module" << std::endl;
+ LoggerInfo() << "-D\t\t\t\t\t"
+ << "Run as a daemon";
+ LoggerInfo() << "-R\t\t\t\t\t"
+ << "Run RTC protocol (client or server)";
+ LoggerInfo() << "-f\t<filename>\t\t\t"
+ << "Log file";
+ LoggerInfo() << "-z\t<io_module>\t\t\t"
+ << "IO module to use. Default: hicnlight_module";
+ LoggerInfo() << "-F\t<conf_file>\t\t\t"
+ << "Path to optional configuration file for libtransport";
+ LoggerInfo() << "-a\t\t\t\t\t"
+ << "Enables data packet aggregation. "
+ << "Works only in RTC mode";
+ LoggerInfo() << "-X\t<param>\t\t\t\t"
+ << "Set FEC params. Options are Rely_K#_N# or RS_K#_N#";
+ LoggerInfo()
+ << "-J\t<passphrase>\t\t\t"
+ << "Set the passphrase used to sign/verify aggregated interests. "
+ "If set on the client, aggregated interests are enable automatically.";
#endif
- std::cerr << std::endl;
- std::cerr << "SERVER SPECIFIC:" << std::endl;
- std::cerr << "-A\t<content_size>\t\t\t"
- "Size of the content to publish. This "
- "is not the size of the packet (see -s for it)."
- << std::endl;
- std::cerr << "-s\t<packet_size>\t\t\tSize of the payload of each data packet."
- << std::endl;
- std::cerr << "-r\t\t\t\t\t"
- << "Produce real content of <content_size> bytes" << std::endl;
- std::cerr << "-m\t\t\t\t\t"
- << "Produce transport manifest" << std::endl;
- std::cerr << "-l\t\t\t\t\t"
- << "Start producing content upon the reception of the "
- "first interest"
- << std::endl;
- std::cerr << "-K\t<keystore_path>\t\t\t"
- << "Path of p12 file containing the "
- "crypto material used for signing packets"
- << std::endl;
- std::cerr << "-k\t<passphrase>\t\t\t"
- << "String from which a 128-bit symmetric key will be "
- "derived for signing packets"
- << std::endl;
- std::cerr << "-y\t<hash_algorithm>\t\t"
- << "Use the selected hash algorithm for "
- "calculating manifest digests"
- << std::endl;
- std::cerr << "-p\t<password>\t\t\t"
- << "Password for p12 keystore" << std::endl;
- std::cerr << "-x\t\t\t\t\t"
- << "Produce a content of <content_size>, then after downloading "
- "it produce a new content of"
- << "\n\t\t\t\t\t<content_size> without resetting "
- "the suffix to 0."
- << std::endl;
- std::cerr << "-B\t<bitrate>\t\t\t"
- << "Bitrate for RTC producer, to be used with the -R option."
- << std::endl;
+ LoggerInfo();
+ LoggerInfo() << "SERVER SPECIFIC:";
+ LoggerInfo()
+ << "-A\t<content_size>\t\t\t"
+ "Sends an application data unit in bytes that is published once "
+ "before exit";
+ LoggerInfo() << "-E\t<expiry_time>\t\t\t"
+ "Expiration time for data packets generated by the producer "
+ "socket";
+ LoggerInfo() << "-s\t<packet_size>\t\t\tData packet payload size.";
+ LoggerInfo() << "-r\t\t\t\t\t"
+ << "Produce real content of <content_size> bytes";
+ LoggerInfo()
+ << "-m\t<manifest_max_capacity>\t\t"
+ << "The maximum number of entries a manifest can contain. Set it "
+ "to 0 to disable manifests. Default is 30, max is 255.";
+ LoggerInfo() << "-l\t\t\t\t\t"
+ << "Start producing content upon the reception of the "
+ "first interest";
+ LoggerInfo() << "-K\t<keystore_path>\t\t\t"
+ << "Path of p12 file containing the "
+ "crypto material used for signing packets";
+ LoggerInfo() << "-k\t<passphrase>\t\t\t"
+ << "String from which a 128-bit symmetric key will be "
+ "derived for signing packets";
+ LoggerInfo() << "-p\t<password>\t\t\t"
+ << "Password for p12 keystore";
+ LoggerInfo() << "-y\t<hash_algorithm>\t\t"
+ << "Use the selected hash algorithm for "
+ "computing manifest digests (default: SHA256)";
+ LoggerInfo() << "-x\t\t\t\t\t"
+ << "Produces application data units of size <content_size> "
+ << "without resetting the name suffix to 0.";
+ LoggerInfo() << "-B\t<bitrate>\t\t\t"
+ << "RTC producer data bitrate, to be used with the -R option.";
#ifndef _WIN32
- std::cerr << "-I\t\t\t\t\t"
- "Interactive mode, start/stop real time content production "
- "by pressing return. To be used with the -R option"
- << std::endl;
- std::cerr
+ LoggerInfo() << "-I\t\t\t\t\t"
+ "Interactive mode, start/stop real time content production "
+ "by pressing return. To be used with the -R option";
+ LoggerInfo()
<< "-T\t<filename>\t\t\t"
"Trace based mode, hiperf takes as input a file with a trace. "
"Each line of the file indicates the timestamp and the size of "
"the packet to generate. To be used with the -R option. -B and -I "
- "will be ignored."
- << std::endl;
- std::cerr << "-E\t\t\t\t\t"
- << "Enable encrypted communication. Requires the path to a p12 "
- "file containing the "
- "crypto material used for the TLS handshake"
- << std::endl;
- std::cerr << "-G\t<port>\t\t\t"
- << "input stream from localhost at the specified port" << std::endl;
+ "will be ignored.";
+ LoggerInfo() << "-G\t<port>\t\t\t\t"
+ << "Input stream from localhost at the specified port";
#endif
- std::cerr << std::endl;
- std::cerr << "CLIENT SPECIFIC:" << std::endl;
- std::cerr << "-b\t<beta_parameter>\t\t"
- << "RAAQM beta parameter" << std::endl;
- std::cerr << "-d\t<drop_factor_parameter>\t\t"
- << "RAAQM drop factor "
- "parameter"
- << std::endl;
- std::cerr << "-L\t<interest lifetime>\t\t"
- << "Set interest lifetime." << std::endl;
- std::cerr << "-M\t<input_buffer_size>\t\t"
- << "Size of consumer input buffer. If 0, reassembly of packets "
- "will be disabled."
- << std::endl;
- std::cerr << "-W\t<window_size>\t\t\t"
- << "Use a fixed congestion window "
- "for retrieving the data."
- << std::endl;
- std::cerr << "-i\t<stats_interval>\t\t"
- << "Show the statistics every <stats_interval> milliseconds."
- << std::endl;
- std::cerr << "-c\t<certificate_path>\t\t"
- << "Path of the producer certificate to be used for verifying the "
- "origin of the packets received."
- << std::endl;
- std::cerr << "-k\t<passphrase>\t\t\t"
- << "String from which is derived the symmetric key used by the "
- "producer to sign packets and by the consumer to verify them."
- << std::endl;
- std::cerr << "-t\t\t\t\t\t"
- "Test mode, check if the client is receiving the "
- "correct data. This is an RTC specific option, to be "
- "used with the -R (default false)"
- << std::endl;
- std::cerr << "-P\t\t\t\t\t"
- << "Prefix of the producer where to do the handshake" << std::endl;
- std::cerr << "-j\t<relay_name>\t\t\t"
- << "Publish the received content under the name relay_name."
- "This is an RTC specific option, to be "
- "used with the -R (default false)"
- << std::endl;
- std::cerr << "-g\t<port>\t\t\t"
- << "output stream to localhost at the specified port" << std::endl;
+ LoggerInfo();
+ LoggerInfo() << "CLIENT SPECIFIC:";
+ LoggerInfo() << "-b\t<beta_parameter>\t\t"
+ << "RAAQM beta parameter";
+ LoggerInfo() << "-d\t<drop_factor_parameter>\t\t"
+ << "RAAQM drop factor "
+ "parameter";
+ LoggerInfo() << "-L\t<interest lifetime>\t\t"
+ << "Set interest lifetime.";
+ LoggerInfo() << "-U\t<factor>\t\t\t"
+ << "Update the relevance threshold: if an unverified packet has "
+ "been received before the last U * manifest_max_capacity_ "
+ "packets received (verified or not), it will be flushed out. "
+ "Should be > 1, default is 100.";
+ LoggerInfo()
+ << "-u\t<factor>\t\t\t"
+ << "Update the alert threshold: if the "
+ "number of unverified packet is > u * manifest_max_capacity_, "
+ "an alert is raised. Should be set such that U > u >= 1, "
+ "default is 20. If u >= U, no alert will ever be raised.";
+ LoggerInfo() << "-M\t<input_buffer_size>\t\t"
+ << "Size of consumer input buffer. If 0, reassembly of packets "
+ "will be disabled.";
+ LoggerInfo()
+ << "-N\t\t\t\t\t"
+ << "Enable aggregated interests; the number of suffixes (including "
+ "the one in the header) can be set through the env variable "
+ "`MAX_AGGREGATED_INTERESTS`.";
+ LoggerInfo() << "-W\t<window_size>\t\t\t"
+ << "Use a fixed congestion window "
+ "for retrieving the data.";
+ LoggerInfo() << "-i\t<stats_interval>\t\t"
+ << "Show the statistics every <stats_interval> milliseconds.";
+ LoggerInfo()
+ << "-c\t<certificate_path>\t\t"
+ << "Path of the producer certificate to be used for verifying the "
+ "origin of the packets received.";
+ LoggerInfo()
+ << "-k\t<passphrase>\t\t\t"
+ << "String from which is derived the symmetric key used by the "
+ "producer to sign packets and by the consumer to verify them.";
+ LoggerInfo() << "-t\t\t\t\t\t"
+ "Test mode, check if the client is receiving the "
+ "correct data. This is an RTC specific option, to be "
+ "used with the -R (default: false)";
+ LoggerInfo()
+ << "-P\t\t\t\t\t"
+ << "Number of parallel streams. For hiperf client, this is the "
+ "number of consumer to create, while for hiperf server this is "
+ "the number of producers to create.";
+ LoggerInfo() << "-j\t<relay_name>\t\t\t"
+ << "Publish received content under the name relay_name."
+ "This is an RTC specific option, to be "
+ "used with the -R (default: false)";
+ LoggerInfo() << "-g\t<port>\t\t\t\t"
+ << "Output stream to localhost at the specified port";
+ LoggerInfo()
+ << "-o\t\t\t\t\t"
+ << "Content sharing mode: if set the socket work in content sharing"
+ << "mode. It works only in RTC mode";
+ LoggerInfo() << "-e\t<strategy>\t\t\t"
+ << "Enhance the network with a reliability strategy. Options";
+ LoggerInfo() << "\t\t\t\t\t\t1: unreliable ";
+ LoggerInfo() << "\t\t\t\t\t\t2: rtx only ";
+ LoggerInfo() << "\t\t\t\t\t\t3: fec only ";
+ LoggerInfo() << "\t\t\t\t\t\t4: delay based ";
+ LoggerInfo() << "\t\t\t\t\t\t5: low rate ";
+ LoggerInfo() << "\t\t\t\t\t\t6: low rate and best path ";
+ LoggerInfo() << "\t\t\t\t\t\t7: low rate and replication";
+ LoggerInfo() << "\t\t\t\t\t\t8: low rate and best path/replication ";
+ LoggerInfo() << "\t\t\t\t\t\t9: only fec low residual losses ";
+ LoggerInfo() << "\t\t\t\t\t\t10: delay and best path ";
+ LoggerInfo() << "\t\t\t\t\t\t11: delay and replication ";
+ LoggerInfo() << "\t\t\t\t\t\t(default: 2 = rtx only) ";
+ LoggerInfo() << "-H\t\t\t\t\t"
+ << "Disable periodic print headers in stats report.";
+ LoggerInfo() << "-n\t<nb_iterations>\t\t\t"
+ << "Print the stats report <nb_iterations> times and exit.\n"
+ << "\t\t\t\t\tThis option limits the duration of the run to "
+ "<nb_iterations> * <stats_interval> milliseconds.";
+ LoggerInfo() << "-w <packet_format> Packet format (without signature, "
+ "defaults to IPV6_TCP)";
}
-int main(int argc, char *argv[]) {
+int hiperf_main(int argc, char *argv[]) {
#ifndef _WIN32
// Common
bool daemon = false;
@@ -149,11 +200,13 @@ int main(int argc, char *argv[]) {
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
+ transport::interface::global_config::GlobalConfigInterface global_conf;
+
// -1 server, 0 undefined, 1 client
int role = 0;
int options = 0;
- char *log_file = nullptr;
+ const char *log_file = nullptr;
transport::interface::global_config::IoModuleConfiguration config;
std::string conf_file;
config.name = "hicnlight_module";
@@ -166,10 +219,11 @@ int main(int argc, char *argv[]) {
int opt;
#ifndef _WIN32
- while ((opt = getopt(
- argc, argv,
- "DSCf:b:d:W:RM:c:vA:s:rmlK:k:y:p:hi:xE:P:B:ItL:z:T:F:j:g:G:")) !=
- -1) {
+ // Please keep in alphabetical order.
+ while (
+ (opt = getopt(argc, argv,
+ "A:B:CDE:F:G:HIJ:K:L:M:NP:RST:U:W:X:ab:c:d:e:f:g:hi:j:k:lm:"
+ "n:op:qrs:tu:vw:xy:z:")) != -1) {
switch (opt) {
// Common
case 'D': {
@@ -202,11 +256,16 @@ int main(int argc, char *argv[]) {
break;
}
#else
+ // Please keep in alphabetical order.
while ((opt = getopt(argc, argv,
- "SCf:b:d:W:RM:c:vA:s:rmlK:k:y:p:hi:xB:E:P:tL:z:F:j:")) !=
- -1) {
+ "A:B:CE:F:HK:L:M:P:RSU:W:X:ab:c:d:e:f:hi:j:k:lm:n:op:rs:"
+ "tu:vwxy:z:")) != -1) {
switch (opt) {
#endif
+ case 'E': {
+ server_configuration.content_lifetime_ = std::stoul(optarg);
+ break;
+ }
case 'f': {
log_file = optarg;
break;
@@ -216,6 +275,30 @@ int main(int argc, char *argv[]) {
server_configuration.rtc_ = true;
break;
}
+ case 'a': {
+ client_configuration.aggregated_data_ = true;
+ server_configuration.aggregated_data_ = true;
+ break;
+ }
+ case 'o': {
+ client_configuration.content_sharing_mode_ = true;
+ break;
+ }
+ case 'w': {
+ std::string packet_format_s = std::string(optarg);
+ packet_format_s = str_tolower(packet_format_s);
+ auto it = packet_format_map.find(std::string(optarg));
+ if (it == packet_format_map.end())
+ throw std::runtime_error("Bad packet format");
+ client_configuration.packet_format_ = it->second;
+ server_configuration.packet_format_ = it->second;
+ break;
+ }
+ case 'k': {
+ server_configuration.passphrase_ = std::string(optarg);
+ client_configuration.passphrase_ = std::string(optarg);
+ break;
+ }
case 'z': {
config.name = optarg;
break;
@@ -234,25 +317,31 @@ int main(int argc, char *argv[]) {
role += 1;
break;
}
- case 'k': {
- server_configuration.passphrase = std::string(optarg);
- client_configuration.passphrase = std::string(optarg);
+ case 'q': {
+ client_configuration.colored_ = server_configuration.colored_ = false;
+ break;
+ }
+ case 'J': {
+ client_configuration.aggr_interest_passphrase_ = optarg;
+ server_configuration.aggr_interest_passphrase_ = optarg;
+ // Consumer signature is only used with aggregated interests,
+ // hence enabling it also forces usage of aggregated interests
+ client_configuration.aggregated_interests_ = true;
break;
}
-
// Client specifc
case 'b': {
- client_configuration.beta = std::stod(optarg);
+ client_configuration.beta_ = std::stod(optarg);
options = 1;
break;
}
case 'd': {
- client_configuration.drop_factor = std::stod(optarg);
+ client_configuration.drop_factor_ = std::stod(optarg);
options = 1;
break;
}
case 'W': {
- client_configuration.window = std::stod(optarg);
+ client_configuration.window_ = std::stod(optarg);
options = 1;
break;
}
@@ -261,13 +350,17 @@ int main(int argc, char *argv[]) {
options = 1;
break;
}
+ case 'N': {
+ client_configuration.aggregated_interests_ = true;
+ break;
+ }
case 'P': {
- client_configuration.producer_prefix_ = Prefix(optarg);
- client_configuration.secure_ = true;
+ client_configuration.parallel_flows_ =
+ server_configuration.parallel_flows_ = std::stoull(optarg);
break;
}
case 'c': {
- client_configuration.producer_certificate = std::string(optarg);
+ client_configuration.producer_certificate_ = std::string(optarg);
options = 1;
break;
}
@@ -286,15 +379,35 @@ int main(int argc, char *argv[]) {
options = 1;
break;
}
+ case 'U': {
+ client_configuration.manifest_factor_relevant_ = std::stoul(optarg);
+ options = 1;
+ break;
+ }
+ case 'u': {
+ client_configuration.manifest_factor_alert_ = std::stoul(optarg);
+ options = 1;
+ break;
+ }
case 'j': {
client_configuration.relay_ = true;
client_configuration.relay_name_ = Prefix(optarg);
options = 1;
break;
}
+ case 'H': {
+ client_configuration.print_headers_ = false;
+ options = 1;
+ break;
+ }
+ case 'n': {
+ client_configuration.nb_iterations_ = std::stoul(optarg);
+ options = 1;
+ break;
+ }
// Server specific
case 'A': {
- server_configuration.download_size = std::stoul(optarg);
+ server_configuration.download_size_ = std::stoul(optarg);
options = -1;
break;
}
@@ -304,43 +417,44 @@ int main(int argc, char *argv[]) {
break;
}
case 'r': {
- server_configuration.virtual_producer = false;
+ server_configuration.virtual_producer_ = false;
options = -1;
break;
}
case 'm': {
- server_configuration.manifest = true;
+ server_configuration.manifest_max_capacity_ = std::stoul(optarg);
options = -1;
break;
}
case 'l': {
- server_configuration.live_production = true;
+ server_configuration.live_production_ = true;
options = -1;
break;
}
case 'K': {
- server_configuration.keystore_name = std::string(optarg);
+ server_configuration.keystore_name_ = std::string(optarg);
options = -1;
break;
}
case 'y': {
+ CryptoHashType hash_algorithm = CryptoHashType::SHA256;
if (strncasecmp(optarg, "sha256", 6) == 0) {
- server_configuration.hash_algorithm = CryptoHashType::SHA256;
+ hash_algorithm = CryptoHashType::SHA256;
} else if (strncasecmp(optarg, "sha512", 6) == 0) {
- server_configuration.hash_algorithm = CryptoHashType::SHA512;
+ hash_algorithm = CryptoHashType::SHA512;
} else if (strncasecmp(optarg, "blake2b512", 10) == 0) {
- server_configuration.hash_algorithm = CryptoHashType::BLAKE2B512;
+ hash_algorithm = CryptoHashType::BLAKE2B512;
} else if (strncasecmp(optarg, "blake2s256", 10) == 0) {
- server_configuration.hash_algorithm = CryptoHashType::BLAKE2S256;
+ hash_algorithm = CryptoHashType::BLAKE2S256;
} else {
- std::cerr << "Ignored unknown hash algorithm. Using SHA 256."
- << std::endl;
+ LoggerWarn() << "Unknown hash algorithm. Using SHA 256.";
}
+ server_configuration.hash_algorithm_ = hash_algorithm;
options = -1;
break;
}
case 'p': {
- server_configuration.keystore_password = std::string(optarg);
+ server_configuration.keystore_password_ = std::string(optarg);
options = -1;
break;
}
@@ -356,12 +470,16 @@ int main(int argc, char *argv[]) {
options = -1;
break;
}
- case 'E': {
- server_configuration.keystore_name = std::string(optarg);
- server_configuration.secure_ = true;
+ case 'e': {
+ client_configuration.recovery_strategy_ = std::stoul(optarg);
+ options = 1;
+ break;
+ }
+ case 'X': {
+ server_configuration.fec_type_ = std::string(optarg);
+ options = -1;
break;
}
- case 'h':
default:
usage();
return EXIT_FAILURE;
@@ -369,34 +487,31 @@ int main(int argc, char *argv[]) {
}
if (options > 0 && role < 0) {
- std::cerr << "Client options cannot be used when using the "
- "software in server mode"
- << std::endl;
+ LoggerErr() << "Client options cannot be used when using the "
+ "software in server mode";
usage();
return EXIT_FAILURE;
} else if (options < 0 && role > 0) {
- std::cerr << "Server options cannot be used when using the "
- "software in client mode"
- << std::endl;
+ LoggerErr() << "Server options cannot be used when using the "
+ "software in client mode";
usage();
return EXIT_FAILURE;
} else if (!role) {
- std::cerr << "Please specify if running hiperf as client "
- "or server."
- << std::endl;
+ LoggerErr() << "Please specify if running hiperf as client "
+ "or server.";
usage();
return EXIT_FAILURE;
}
if (argv[optind] == 0) {
- std::cerr << "Please specify the name/prefix to use." << std::endl;
+ LoggerErr() << "Please specify the name/prefix to use.";
usage();
return EXIT_FAILURE;
} else {
if (role > 0) {
- client_configuration.name = Name(argv[optind]);
+ client_configuration.name_ = Prefix(argv[optind]);
} else {
- server_configuration.name = Prefix(argv[optind]);
+ server_configuration.name_ = Prefix(argv[optind]);
}
}
@@ -427,7 +542,7 @@ int main(int argc, char *argv[]) {
config.set();
// Parse config file
- transport::interface::global_config::parseConfigurationFile(conf_file);
+ global_conf.parseConfigurationFile(conf_file);
if (role > 0) {
HIperfClient c(client_configuration);
@@ -453,4 +568,4 @@ int main(int argc, char *argv[]) {
} // namespace hiperf
-int main(int argc, char *argv[]) { return hiperf::main(argc, argv); }
+int main(int argc, char *argv[]) { return hiperf::hiperf_main(argc, argv); }
diff --git a/apps/hiperf/src/server.cc b/apps/hiperf/src/server.cc
index 968d42e2c..3f6c335f9 100644
--- a/apps/hiperf/src/server.cc
+++ b/apps/hiperf/src/server.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,167 +17,92 @@
namespace hiperf {
+using transport::core::ContentObject;
+using transport::core::Interest;
+using transport::core::Name;
+using transport::interface::GeneralTransportOptions;
+using transport::interface::ProducerCallbacksOptions;
+using transport::interface::ProducerInterestCallback;
+using transport::interface::ProducerSocket;
+using transport::interface::ProductionProtocolAlgorithms;
+
/**
* Hiperf server class: configure and setup an hicn producer following the
* ServerConfiguration.
*/
class HIperfServer::Impl {
- const std::size_t log2_content_object_buffer_size = 8;
-
- public:
- Impl(const hiperf::ServerConfiguration &conf)
- : configuration_(conf),
- signals_(io_service_),
- rtc_timer_(io_service_),
- unsatisfied_interests_(),
- content_objects_((std::uint16_t)(1 << log2_content_object_buffer_size)),
- content_objects_index_(0),
- mask_((std::uint16_t)(1 << log2_content_object_buffer_size) - 1),
- last_segment_(0),
-#ifndef _WIN32
- ptr_last_segment_(&last_segment_),
- input_(io_service_),
- rtc_running_(false),
-#else
- ptr_last_segment_(&last_segment_),
-#endif
- flow_name_(configuration_.name.getName()),
- socket_(io_service_),
- recv_buffer_(nullptr, 0) {
- std::string buffer(configuration_.payload_size_, 'X');
- std::cout << "Producing contents under name " << conf.name.getName()
- << std::endl;
-#ifndef _WIN32
- if (configuration_.interactive_) {
- input_.assign(::dup(STDIN_FILENO));
- }
-#endif
-
- for (int i = 0; i < (1 << log2_content_object_buffer_size); i++) {
- content_objects_[i] = ContentObject::Ptr(
- new ContentObject(conf.name.getName(), HF_INET6_TCP, 0,
- (const uint8_t *)buffer.data(), buffer.size()));
- content_objects_[i]->setLifetime(
- default_values::content_object_expiry_time);
- }
- }
-
- void virtualProcessInterest(ProducerSocket &p, const Interest &interest) {
- content_objects_[content_objects_index_ & mask_]->setName(
- interest.getName());
- producer_socket_->produce(
- *content_objects_[content_objects_index_++ & mask_]);
+ static constexpr std::size_t klog2_content_object_buffer_size() { return 8; }
+ static constexpr std::size_t kcontent_object_buffer_size() {
+ return (1 << klog2_content_object_buffer_size());
}
-
- void processInterest(ProducerSocket &p, const Interest &interest) {
- p.setSocketOption(ProducerCallbacksOptions::CACHE_MISS,
- (ProducerInterestCallback)VOID_HANDLER);
- p.setSocketOption(GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
- 5000000_U32);
-
- produceContent(p, interest.getName(), interest.getName().getSuffix());
- std::cout << "Received interest " << interest.getName().getSuffix()
- << std::endl;
+ static constexpr std::size_t kmask() {
+ return (kcontent_object_buffer_size() - 1);
}
- void asyncProcessInterest(ProducerSocket &p, const Interest &interest) {
- p.setSocketOption(ProducerCallbacksOptions::CACHE_MISS,
- (ProducerInterestCallback)bind(&Impl::cacheMiss, this,
- std::placeholders::_1,
- std::placeholders::_2));
- p.setSocketOption(GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
- 5000000_U32);
- uint32_t suffix = interest.getName().getSuffix();
-
- if (suffix == 0) {
- last_segment_ = 0;
- ptr_last_segment_ = &last_segment_;
- unsatisfied_interests_.clear();
- }
-
- // The suffix will either be the one from the received interest or the
- // smallest suffix of a previous interest not satisfed
- if (!unsatisfied_interests_.empty()) {
- auto it =
- std::lower_bound(unsatisfied_interests_.begin(),
- unsatisfied_interests_.end(), *ptr_last_segment_);
- if (it != unsatisfied_interests_.end()) {
- suffix = *it;
+ /**
+ * @brief As we can (potentially) setup many producer sockets, we need to keep
+ * a separate context for each one of them. The context contains parameters
+ * and variable that are specific to a single producer socket.
+ */
+ class ProducerContext
+ : public Base<ProducerContext, ServerConfiguration, Impl>,
+ public ProducerSocket::Callback {
+ public:
+ using ConfType = ServerConfiguration;
+ using ParentType = typename HIperfServer::Impl;
+ static inline const auto getContextType() { return "ProducerContext"; }
+
+ ProducerContext(HIperfServer::Impl &server, int producer_identifier)
+ : Base(server, server.io_service_, producer_identifier) {
+ // Allocate buffer to copy as content objects payload
+ std::string buffer(configuration_.payload_size_, 'X');
+
+ // Allocate array of content objects. They are share_ptr so that the
+ // transport will only capture a reference to them instead of performing
+ // an hard copy.
+ for (std::size_t i = 0; i < kcontent_object_buffer_size(); i++) {
+ const auto &element =
+ content_objects_.emplace_back(std::make_shared<ContentObject>(
+ configuration_.name_.makeName(), configuration_.packet_format_,
+ 0, (const uint8_t *)buffer.data(), buffer.size()));
+ element->setLifetime(
+ transport::interface::default_values::content_object_expiry_time);
}
- unsatisfied_interests_.erase(unsatisfied_interests_.begin(), it);
}
- std::cout << "Received interest " << interest.getName().getSuffix()
- << ", starting production at " << suffix << std::endl;
- std::cout << unsatisfied_interests_.size() << " interests still unsatisfied"
- << std::endl;
- produceContentAsync(p, interest.getName(), suffix);
- }
-
- void produceContent(ProducerSocket &p, const Name &content_name,
- uint32_t suffix) {
- auto b = utils::MemBuf::create(configuration_.download_size);
- std::memset(b->writableData(), '?', configuration_.download_size);
- b->append(configuration_.download_size);
- uint32_t total;
-
- utils::TimePoint t0 = utils::SteadyClock::now();
- total = p.produceStream(content_name, std::move(b),
- !configuration_.multiphase_produce_, suffix);
- utils::TimePoint t1 = utils::SteadyClock::now();
-
- std::cout
- << "Written " << total
- << " data packets in output buffer (Segmentation time: "
- << std::chrono::duration_cast<utils::Microseconds>(t1 - t0).count()
- << " us)" << std::endl;
- }
-
- void produceContentAsync(ProducerSocket &p, Name content_name,
- uint32_t suffix) {
- auto b = utils::MemBuf::create(configuration_.download_size);
- std::memset(b->writableData(), '?', configuration_.download_size);
- b->append(configuration_.download_size);
+ // To make vector happy (move or copy constructor is needed when vector
+ // resizes)
+ ProducerContext(ProducerContext &&other) noexcept
+ : Base(std::move(other)),
+ content_objects_(std::move(other.content_objects_)),
+ unsatisfied_interests_(std::move(other.unsatisfied_interests_)),
+ last_segment_(other.last_segment_),
+ producer_socket_(std::move(other.producer_socket_)),
+ content_objects_index_(other.content_objects_index_),
+ payload_size_max_(other.payload_size_max_) {}
- p.asyncProduce(content_name, std::move(b),
- !configuration_.multiphase_produce_, suffix,
- &ptr_last_segment_);
- }
+ virtual ~ProducerContext() = default;
- void cacheMiss(ProducerSocket &p, const Interest &interest) {
- unsatisfied_interests_.push_back(interest.getName().getSuffix());
- }
+ /**
+ * @brief Produce datagram
+ */
+ void produceDatagram(const uint8_t *buffer, std::size_t buffer_size) const {
+ assert(producer_socket_);
- void onContentProduced(ProducerSocket &p, const std::error_code &err,
- uint64_t bytes_written) {
- p.setSocketOption(ProducerCallbacksOptions::CACHE_MISS,
- (ProducerInterestCallback)bind(
- &Impl::asyncProcessInterest, this,
- std::placeholders::_1, std::placeholders::_2));
- }
+ auto size = std::min(buffer_size, payload_size_max_);
- std::shared_ptr<Identity> getProducerIdentity(std::string &keystore_path,
- std::string &keystore_pwd,
- CryptoHashType &hash_type) {
- if (access(keystore_path.c_str(), F_OK) != -1) {
- return std::make_shared<Identity>(keystore_path, keystore_pwd, hash_type);
+ producer_socket_->produceDatagram(flow_name_, buffer, size);
}
- return std::make_shared<Identity>(keystore_path, keystore_pwd,
- CryptoSuite::RSA_SHA256, 1024, 365,
- "producer-test");
- }
- int setup() {
- int ret;
- int production_protocol;
-
- if (configuration_.secure_) {
- auto identity = getProducerIdentity(configuration_.keystore_name,
- configuration_.keystore_password,
- configuration_.hash_algorithm);
- producer_socket_ = std::make_unique<P2PSecureProducerSocket>(
- configuration_.rtc_, identity);
- } else {
+ /**
+ * @brief Create and setup the producer socket
+ */
+ int setup() {
+ int ret;
+ int production_protocol;
+ std::shared_ptr<transport::auth::Signer> signer =
+ std::make_shared<transport::auth::VoidSigner>();
+
if (!configuration_.rtc_) {
production_protocol = ProductionProtocolAlgorithms::BYTE_STREAM;
} else {
@@ -185,210 +110,470 @@ class HIperfServer::Impl {
}
producer_socket_ = std::make_unique<ProducerSocket>(production_protocol);
- }
- if (producer_socket_->setSocketOption(
- GeneralTransportOptions::MAKE_MANIFEST, configuration_.manifest) ==
- SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
- }
+ if (producer_socket_->setSocketOption(
+ ProducerCallbacksOptions::PRODUCER_CALLBACK, this) ==
+ SOCKET_OPTION_NOT_SET) {
+ getOutputStream() << "Failed to set producer callback." << std::endl;
+ return ERROR_SETUP;
+ }
- if (!configuration_.passphrase.empty()) {
- std::shared_ptr<Signer> signer = std::make_shared<SymmetricSigner>(
- CryptoSuite::HMAC_SHA256, configuration_.passphrase);
- producer_socket_->setSocketOption(GeneralTransportOptions::SIGNER,
- signer);
- }
+ if (producer_socket_->setSocketOption(
+ GeneralTransportOptions::HASH_ALGORITHM,
+ configuration_.hash_algorithm_) == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+
+ if (producer_socket_->setSocketOption(
+ GeneralTransportOptions::MANIFEST_MAX_CAPACITY,
+ configuration_.manifest_max_capacity_) == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+
+ if (producer_socket_->setSocketOption(transport::interface::PACKET_FORMAT,
+ configuration_.packet_format_) ==
+ SOCKET_OPTION_NOT_SET) {
+ getOutputStream() << "ERROR -- Impossible to set the packet format."
+ << std::endl;
+ return ERROR_SETUP;
+ }
+
+ if (!configuration_.passphrase_.empty()) {
+ signer = std::make_shared<transport::auth::SymmetricSigner>(
+ transport::auth::CryptoSuite::HMAC_SHA256,
+ configuration_.passphrase_);
+ }
+
+ if (!configuration_.keystore_name_.empty()) {
+ signer = std::make_shared<transport::auth::AsymmetricSigner>(
+ configuration_.keystore_name_, configuration_.keystore_password_);
+ }
- if (!configuration_.keystore_name.empty()) {
- auto identity = getProducerIdentity(configuration_.keystore_name,
- configuration_.keystore_password,
- configuration_.hash_algorithm);
- std::shared_ptr<Signer> signer = identity->getSigner();
producer_socket_->setSocketOption(GeneralTransportOptions::SIGNER,
signer);
- }
- uint32_t rtc_header_size = 0;
- if (configuration_.rtc_) rtc_header_size = 12;
- producer_socket_->setSocketOption(
- GeneralTransportOptions::DATA_PACKET_SIZE,
- (uint32_t)(
- configuration_.payload_size_ + rtc_header_size +
- (configuration_.name.getAddressFamily() == AF_INET ? 40 : 60)));
- producer_socket_->registerPrefix(configuration_.name);
- producer_socket_->connect();
-
- if (configuration_.rtc_) {
- std::cout << "Running RTC producer: the prefix length will be ignored."
- " Use /128 by default in RTC mode"
- << std::endl;
- return ERROR_SUCCESS;
- }
+ // Compute maximum payload size
+ Packet::Format format = configuration_.packet_format_;
+ if (!configuration_.manifest_max_capacity_)
+ format = Packet::toAHFormat(format);
+ payload_size_max_ = PayloadSize(format).getPayloadSizeMax(
+ configuration_.rtc_ ? RTC_HEADER_SIZE : 0,
+ configuration_.fec_type_.empty() ? 0 : FEC_HEADER_MAX_SIZE,
+ !configuration_.manifest_max_capacity_
+ ? signer->getSignatureFieldSize()
+ : 0);
+
+ if (configuration_.payload_size_ > payload_size_max_) {
+ getOutputStream() << "WARNING: Payload has size "
+ << configuration_.payload_size_ << ", maximum is "
+ << payload_size_max_
+ << ". Payload will be truncated to fit." << std::endl;
+ }
+
+ // Verifier for aggregated interests
+ std::shared_ptr<transport::auth::Verifier> verifier =
+ std::make_shared<transport::auth::VoidVerifier>();
+ if (!configuration_.aggr_interest_passphrase_.empty()) {
+ verifier = std::make_unique<transport::auth::SymmetricVerifier>(
+ configuration_.aggr_interest_passphrase_);
+ }
+ ret = producer_socket_->setSocketOption(GeneralTransportOptions::VERIFIER,
+ verifier);
+ if (ret == SOCKET_OPTION_NOT_SET) return ERROR_SETUP;
+
+ if (configuration_.rtc_) {
+ ret = producer_socket_->setSocketOption(
+ transport::interface::RtcTransportOptions::AGGREGATED_DATA,
+ configuration_.aggregated_data_);
+
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+
+ ret = producer_socket_->setSocketOption(
+ GeneralTransportOptions::FEC_TYPE, configuration_.fec_type_);
+
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+ }
- if (!configuration_.virtual_producer) {
if (producer_socket_->setSocketOption(
GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
- configuration_.content_lifetime) == SOCKET_OPTION_NOT_SET) {
+ configuration_.content_lifetime_) == SOCKET_OPTION_NOT_SET) {
return ERROR_SETUP;
}
- if (producer_socket_->setSocketOption(
- GeneralTransportOptions::OUTPUT_BUFFER_SIZE, 200000U) ==
- SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
+ producer_socket_->registerPrefix(Prefix(flow_name_, 128));
+ producer_socket_->connect();
+ producer_socket_->start();
+
+ if (configuration_.rtc_) {
+ return ERROR_SUCCESS;
}
- if (!configuration_.live_production) {
- produceContent(*producer_socket_, configuration_.name.getName(), 0);
+ if (!configuration_.virtual_producer_) {
+ if (producer_socket_->setSocketOption(
+ GeneralTransportOptions::OUTPUT_BUFFER_SIZE, 200000U) ==
+ SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+
+ if (producer_socket_->setSocketOption(
+ GeneralTransportOptions::MAX_SEGMENT_SIZE,
+ static_cast<uint32_t>(configuration_.payload_size_)) ==
+ SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+
+ if (!configuration_.live_production_) {
+ produceContent(*producer_socket_, configuration_.name_.makeName(), 0);
+ } else {
+ ret = producer_socket_->setSocketOption(
+ ProducerCallbacksOptions::CACHE_MISS,
+ (ProducerInterestCallback)bind(
+ &ProducerContext::asyncProcessInterest, this,
+ std::placeholders::_1, std::placeholders::_2));
+
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+ }
} else {
ret = producer_socket_->setSocketOption(
+ GeneralTransportOptions::OUTPUT_BUFFER_SIZE, 0U);
+
+ if (ret == SOCKET_OPTION_NOT_SET) {
+ return ERROR_SETUP;
+ }
+
+ ret = producer_socket_->setSocketOption(
ProducerCallbacksOptions::CACHE_MISS,
- (ProducerInterestCallback)bind(&Impl::asyncProcessInterest, this,
- std::placeholders::_1,
- std::placeholders::_2));
+ (ProducerInterestCallback)bind(
+ &ProducerContext::virtualProcessInterest, this,
+ std::placeholders::_1, std::placeholders::_2));
if (ret == SOCKET_OPTION_NOT_SET) {
return ERROR_SETUP;
}
}
- } else {
- ret = producer_socket_->setSocketOption(
- GeneralTransportOptions::OUTPUT_BUFFER_SIZE, 0U);
+ ret = producer_socket_->setSocketOption(
+ ProducerCallbacksOptions::CONTENT_PRODUCED,
+ (transport::interface::ProducerContentCallback)bind(
+ &ProducerContext::onContentProduced, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3));
if (ret == SOCKET_OPTION_NOT_SET) {
return ERROR_SETUP;
}
- ret = producer_socket_->setSocketOption(
+ return ERROR_SUCCESS;
+ }
+
+ int run() {
+ getOutputStream() << "started to serve consumers with name " << flow_name_
+ << std::endl;
+ return ERROR_SUCCESS;
+ }
+
+ void stop() {
+ getOutputStream() << "stopped to serve consumers" << std::endl;
+ producer_socket_->stop();
+ }
+
+ private:
+ /**
+ * @brief Produce an existing content object. Set the name as the
+ * interest.
+ */
+ void virtualProcessInterest(ProducerSocket &p, const Interest &interest) {
+ content_objects_[content_objects_index_ & kmask()]->setName(
+ interest.getName());
+ p.produce(*content_objects_[content_objects_index_++ & kmask()]);
+ }
+
+ /**
+ * @brief Create and produce a buffer of configuration_.download_size_
+ * length.
+ */
+ void produceContent(ProducerSocket &p, const Name &content_name,
+ uint32_t suffix) const {
+ uint32_t total;
+
+ auto b = utils::MemBuf::create(configuration_.download_size_);
+ std::memset(b->writableData(), '?', configuration_.download_size_);
+ b->append(configuration_.download_size_);
+
+ utils::SteadyTime::TimePoint t0 = utils::SteadyTime::Clock::now();
+ total = p.produceStream(content_name, std::move(b),
+ !configuration_.multiphase_produce_, suffix);
+ utils::SteadyTime::TimePoint t1 = utils::SteadyTime::Clock::now();
+
+ LoggerInfo() << "Written " << total
+ << " data packets in output buffer (Segmentation time: "
+ << utils::SteadyTime::getDurationUs(t0, t1).count() << " us)"
+ << std::endl;
+ }
+
+ /**
+ * @brief Synchronously produce content upon reception of one interest
+ */
+ void processInterest(ProducerSocket &p, const Interest &interest) const {
+ p.setSocketOption(
ProducerCallbacksOptions::CACHE_MISS,
- (ProducerInterestCallback)bind(&Impl::virtualProcessInterest, this,
- std::placeholders::_1,
- std::placeholders::_2));
+ (ProducerInterestCallback)transport::interface::VOID_HANDLER);
+ p.setSocketOption(GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
+ configuration_.content_lifetime_);
- if (ret == SOCKET_OPTION_NOT_SET) {
- return ERROR_SETUP;
+ produceContent(p, interest.getName(), interest.getName().getSuffix());
+ LoggerInfo() << "Received interest " << interest.getName().getSuffix()
+ << std::endl;
+ }
+
+ /**
+ * @brief Async create and produce a buffer of
+ * configuration_.download_size_ length.
+ */
+ void produceContentAsync(ProducerSocket &p, Name content_name,
+ uint32_t suffix) {
+ parent_.produce_thread_.add([this, suffix, content_name, &p]() {
+ auto b = utils::MemBuf::create(configuration_.download_size_);
+ std::memset(b->writableData(), '?', configuration_.download_size_);
+ b->append(configuration_.download_size_);
+
+ last_segment_ =
+ suffix + p.produceStream(content_name, std::move(b),
+ !configuration_.multiphase_produce_,
+ suffix);
+ });
+ }
+
+ /**
+ * @brief Asynchronously produce content upon reception of one interest
+ */
+ void asyncProcessInterest(ProducerSocket &p, const Interest &interest) {
+ p.setSocketOption(ProducerCallbacksOptions::CACHE_MISS,
+ (ProducerInterestCallback)bind(
+ &ProducerContext::cacheMiss, this,
+ std::placeholders::_1, std::placeholders::_2));
+ p.setSocketOption(GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
+ configuration_.content_lifetime_);
+ uint32_t suffix = interest.getName().getSuffix();
+
+ if (suffix == 0) {
+ last_segment_ = 0;
+ unsatisfied_interests_.clear();
+ }
+
+ // The suffix will either come from the received interest or will be set
+ // to the smallest suffix of a previous interest not satisfied
+ if (!unsatisfied_interests_.empty()) {
+ auto it = std::lower_bound(unsatisfied_interests_.begin(),
+ unsatisfied_interests_.end(), last_segment_);
+ if (it != unsatisfied_interests_.end()) {
+ suffix = *it;
+ }
+ unsatisfied_interests_.erase(unsatisfied_interests_.begin(), it);
}
+
+ getOutputStream() << " Received interest "
+ << interest.getName().getSuffix()
+ << ", starting production at " << suffix << end_mod_
+ << std::endl;
+ getOutputStream() << unsatisfied_interests_.size()
+ << " interests still unsatisfied" << end_mod_
+ << std::endl;
+ produceContentAsync(p, interest.getName(), suffix);
+ }
+
+ /**
+ * @brief Register cache miss events
+ */
+ void cacheMiss([[maybe_unused]] const ProducerSocket &p,
+ const Interest &interest) {
+ unsatisfied_interests_.push_back(interest.getName().getSuffix());
}
- ret = producer_socket_->setSocketOption(
- ProducerCallbacksOptions::CONTENT_PRODUCED,
- (ProducerContentCallback)bind(
- &Impl::onContentProduced, this, std::placeholders::_1,
- std::placeholders::_2, std::placeholders::_3));
+ /**
+ * @brief When content is produced, set cache miss callback so that we can
+ * register any cache miss happening after the production.
+ */
+ void onContentProduced(ProducerSocket &p,
+ [[maybe_unused]] const std::error_code &err,
+ [[maybe_unused]] uint64_t bytes_written) {
+ p.setSocketOption(ProducerCallbacksOptions::CACHE_MISS,
+ (ProducerInterestCallback)bind(
+ &ProducerContext::asyncProcessInterest, this,
+ std::placeholders::_1, std::placeholders::_2));
+ }
- return ERROR_SUCCESS;
+ /**
+ * @brief Internal producer error. When this callback is triggered
+ * something important happened. Here we stop the program.
+ */
+ void produceError(const std::error_code &err) noexcept override {
+ getOutputStream() << "Error from producer transport: " << err.message()
+ << std::endl;
+ parent_.stop();
+ }
+
+ // Members initialized in constructor
+ std::vector<ContentObject::Ptr> content_objects_;
+
+ // Members initialized by in-class initializer
+ std::vector<uint32_t> unsatisfied_interests_;
+ std::uint32_t last_segment_{0};
+ std::unique_ptr<ProducerSocket> producer_socket_{nullptr};
+ std::uint16_t content_objects_index_{0};
+ std::size_t payload_size_max_{0};
+ };
+
+ public:
+ explicit Impl(const hiperf::ServerConfiguration &conf) : config_(conf) {
+#ifndef _WIN32
+ if (config_.interactive_) {
+ input_.assign(::dup(STDIN_FILENO));
+ }
+#endif
+
+ std::memset(rtc_payload_.data(), 'X', rtc_payload_.size());
+ }
+
+ ~Impl() = default;
+
+ int setup() {
+ int ret = ensureFlows(config_.name_, config_.parallel_flows_);
+ if (ret != ERROR_SUCCESS) {
+ return ret;
+ }
+
+ producer_contexts_.reserve(config_.parallel_flows_);
+ for (uint32_t i = 0; i < config_.parallel_flows_; i++) {
+ auto &ctx = producer_contexts_.emplace_back(*this, i);
+ ret = ctx.setup();
+
+ if (ret) {
+ break;
+ }
+ }
+
+ return ret;
}
void receiveStream() {
socket_.async_receive_from(
- asio::buffer(recv_buffer_.first, recv_buffer_.second), remote_,
- [this](std::error_code ec, std::size_t length) {
+ asio::buffer(recv_buffer_.writableData(), recv_buffer_.capacity()),
+ remote_, [this](const std::error_code &ec, std::size_t length) {
if (ec) return;
- sendRTCContentFromStream(recv_buffer_.first, length);
+ sendRTCContentFromStream(recv_buffer_.writableData(), length);
receiveStream();
});
}
- void sendRTCContentFromStream(uint8_t *buff, std::size_t len) {
- auto payload =
- content_objects_[content_objects_index_++ & mask_]->getPayload();
+ void sendRTCContentFromStream(const uint8_t *buff, std::size_t len) {
// this is used to compute the data packet delay
// Used only for performance evaluation
// It requires clock synchronization between producer and consumer
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch())
- .count();
- uint8_t *start = (uint8_t *)payload->writableData();
+ auto now = utils::SystemTime::nowMs().count();
+
+ auto start = rtc_payload_.data();
std::memcpy(start, &now, sizeof(uint64_t));
std::memcpy(start + sizeof(uint64_t), buff, len);
- producer_socket_->produceDatagram(flow_name_, start,
- len + sizeof(uint64_t));
+
+ for (const auto &producer_context : producer_contexts_) {
+ producer_context.produceDatagram(start, len + sizeof(uint64_t));
+ }
}
- void sendRTCContentObjectCallback(std::error_code ec) {
+ void sendRTCContentObjectCallback(const std::error_code &ec) {
if (ec) return;
rtc_timer_.expires_from_now(
- configuration_.production_rate_.getMicrosecondsForPacket(
- configuration_.payload_size_));
+ config_.production_rate_.getMicrosecondsForPacket(
+ config_.payload_size_));
rtc_timer_.async_wait(std::bind(&Impl::sendRTCContentObjectCallback, this,
std::placeholders::_1));
- auto payload =
- content_objects_[content_objects_index_++ & mask_]->getPayload();
+
+ auto start = rtc_payload_.data();
// this is used to compute the data packet delay
// Used only for performance evaluation
// It requires clock synchronization between producer and consumer
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch())
- .count();
-
- std::memcpy(payload->writableData(), &now, sizeof(uint64_t));
+ auto now = utils::SystemTime::nowMs().count();
+ std::memcpy(start, &now, sizeof(uint64_t));
- producer_socket_->produceDatagram(
- flow_name_, payload->data(),
- payload->length() < 1400 ? payload->length() : 1400);
+ for (const auto &producer_context : producer_contexts_) {
+ producer_context.produceDatagram(start, config_.payload_size_);
+ }
}
- void sendRTCContentObjectCallbackWithTrace(std::error_code ec) {
+ void sendRTCContentObjectCallbackWithTrace(const std::error_code &ec) {
if (ec) return;
- auto payload =
- content_objects_[content_objects_index_++ & mask_]->getPayload();
-
- uint32_t packet_len =
- configuration_.trace_[configuration_.trace_index_].size;
+ std::size_t packet_len = config_.trace_[config_.trace_index_].size;
// this is used to compute the data packet delay
// used only for performance evaluation
// it requires clock synchronization between producer and consumer
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch())
- .count();
-
- std::memcpy(payload->writableData(), &now, sizeof(uint64_t));
+ auto now = utils::SystemTime::nowMs().count();
+ auto start = rtc_payload_.data();
+ std::memcpy(start, &now, sizeof(uint64_t));
- if (packet_len > payload->length()) packet_len = payload->length();
- if (packet_len > 1400) packet_len = 1400;
+ if (packet_len > config_.payload_size_) {
+ packet_len = config_.payload_size_;
+ }
- producer_socket_->produceDatagram(flow_name_, payload->data(), packet_len);
+ for (const auto &producer_context : producer_contexts_) {
+ producer_context.produceDatagram(start, packet_len);
+ }
- uint32_t next_index = configuration_.trace_index_ + 1;
+ uint32_t next_index = config_.trace_index_ + 1;
uint64_t schedule_next;
- if (next_index < configuration_.trace_.size()) {
- schedule_next =
- configuration_.trace_[next_index].timestamp -
- configuration_.trace_[configuration_.trace_index_].timestamp;
+ if (next_index < config_.trace_.size()) {
+ schedule_next = config_.trace_[next_index].timestamp -
+ config_.trace_[config_.trace_index_].timestamp;
} else {
// here we need to loop, schedule in a random time
schedule_next = 1000;
}
- configuration_.trace_index_ =
- (configuration_.trace_index_ + 1) % configuration_.trace_.size();
+ config_.trace_index_ = (config_.trace_index_ + 1) % config_.trace_.size();
rtc_timer_.expires_from_now(std::chrono::microseconds(schedule_next));
rtc_timer_.async_wait(
std::bind(&Impl::sendRTCContentObjectCallbackWithTrace, this,
std::placeholders::_1));
}
+ int parseTraceFile() {
+ std::ifstream trace(config_.trace_file_);
+ if (trace.fail()) {
+ return -1;
+ }
+ std::string line;
+ while (std::getline(trace, line)) {
+ std::istringstream iss(line);
+ hiperf::packet_t packet;
+ iss >> packet.timestamp >> packet.size;
+ config_.trace_.push_back(packet);
+ }
+ return 0;
+ }
+
#ifndef _WIN32
void handleInput(const std::error_code &error, std::size_t length) {
if (error) {
- producer_socket_->stop();
- io_service_.stop();
+ stop();
}
if (rtc_running_) {
- std::cout << "stop real time content production" << std::endl;
+ LoggerInfo() << "stop real time content production" << std::endl;
rtc_running_ = false;
rtc_timer_.cancel();
} else {
- std::cout << "start real time content production" << std::endl;
+ LoggerInfo() << "start real time content production" << std::endl;
rtc_running_ = true;
rtc_timer_.expires_from_now(
- configuration_.production_rate_.getMicrosecondsForPacket(
- configuration_.payload_size_));
+ config_.production_rate_.getMicrosecondsForPacket(
+ config_.payload_size_));
rtc_timer_.async_wait(std::bind(&Impl::sendRTCContentObjectCallback, this,
std::placeholders::_1));
}
@@ -401,46 +586,33 @@ class HIperfServer::Impl {
}
#endif
- int parseTraceFile() {
- std::ifstream trace(configuration_.trace_file_);
- if (trace.fail()) {
- return -1;
- }
- std::string line;
- while (std::getline(trace, line)) {
- std::istringstream iss(line);
- hiperf::packet_t packet;
- iss >> packet.timestamp >> packet.size;
- configuration_.trace_.push_back(packet);
+ void stop() {
+ for (auto &producer_context : producer_contexts_) {
+ producer_context.stop();
}
- return 0;
+
+ io_service_.stop();
}
int run() {
- std::cerr << "Starting to serve consumers" << std::endl;
-
signals_.add(SIGINT);
- signals_.async_wait([this](const std::error_code &, const int &) {
- std::cout << "STOPPING!!" << std::endl;
- producer_socket_->stop();
- io_service_.stop();
- });
+ signals_.async_wait(
+ [this](const std::error_code &, const int &) { stop(); });
- if (configuration_.rtc_) {
-#ifndef _WIN32
- if (configuration_.interactive_) {
+ if (config_.rtc_) {
+ if (config_.interactive_) {
asio::async_read_until(
input_, input_buffer_, '\n',
std::bind(&Impl::handleInput, this, std::placeholders::_1,
std::placeholders::_2));
- } else if (configuration_.trace_based_) {
- std::cout << "trace-based mode enabled" << std::endl;
- if (configuration_.trace_file_ == nullptr) {
- std::cout << "cannot find the trace file" << std::endl;
+ } else if (config_.trace_based_) {
+ LoggerInfo() << "trace-based mode enabled" << std::endl;
+ if (config_.trace_file_ == nullptr) {
+ LoggerErr() << "cannot find the trace file" << std::endl;
return ERROR_SETUP;
}
if (parseTraceFile() < 0) {
- std::cout << "cannot parse the trace file" << std::endl;
+ LoggerErr() << "cannot parse the trace file" << std::endl;
return ERROR_SETUP;
}
rtc_running_ = true;
@@ -448,31 +620,26 @@ class HIperfServer::Impl {
rtc_timer_.async_wait(
std::bind(&Impl::sendRTCContentObjectCallbackWithTrace, this,
std::placeholders::_1));
- } else if (configuration_.input_stream_mode_) {
+ } else if (config_.input_stream_mode_) {
rtc_running_ = true;
- // crate socket
+ // create socket
remote_ = asio::ip::udp::endpoint(
- asio::ip::address::from_string("127.0.0.1"), configuration_.port_);
+ asio::ip::address::from_string("127.0.0.1"), config_.port_);
socket_.open(asio::ip::udp::v4());
socket_.bind(remote_);
- recv_buffer_.first = (uint8_t *)malloc(1500);
- recv_buffer_.second = 1500;
receiveStream();
} else {
rtc_running_ = true;
rtc_timer_.expires_from_now(
- configuration_.production_rate_.getMicrosecondsForPacket(
- configuration_.payload_size_));
+ config_.production_rate_.getMicrosecondsForPacket(
+ config_.payload_size_));
rtc_timer_.async_wait(std::bind(&Impl::sendRTCContentObjectCallback,
this, std::placeholders::_1));
}
-#else
- rtc_timer_.expires_from_now(
- configuration_.production_rate_.getMicrosecondsForPacket(
- configuration_.payload_size_));
- rtc_timer_.async_wait(std::bind(&Impl::sendRTCContentObjectCallback, this,
- std::placeholders::_1));
-#endif
+ }
+
+ for (auto &producer_context : producer_contexts_) {
+ producer_context.run();
}
io_service_.run();
@@ -480,34 +647,31 @@ class HIperfServer::Impl {
return ERROR_SUCCESS;
}
+ ServerConfiguration &getConfig() { return config_; }
+
private:
- hiperf::ServerConfiguration configuration_;
+ // Variables initialized by the constructor.
+ ServerConfiguration config_;
+
+ // Variable initialized in the in-class initializer list.
asio::io_service io_service_;
- asio::signal_set signals_;
- asio::steady_timer rtc_timer_;
- std::vector<uint32_t> unsatisfied_interests_;
- std::vector<std::shared_ptr<ContentObject>> content_objects_;
- std::uint16_t content_objects_index_;
- std::uint16_t mask_;
- std::uint32_t last_segment_;
- std::uint32_t *ptr_last_segment_;
- std::unique_ptr<ProducerSocket> producer_socket_;
-#ifndef _WIN32
- asio::posix::stream_descriptor input_;
+ asio::signal_set signals_{io_service_};
+ asio::steady_timer rtc_timer_{io_service_};
+ asio::posix::stream_descriptor input_{io_service_};
+ asio::ip::udp::socket socket_{io_service_};
+ std::vector<ProducerContext> producer_contexts_;
+ ::utils::EventThread produce_thread_;
asio::streambuf input_buffer_;
- bool rtc_running_;
- Name flow_name_;
- asio::ip::udp::socket socket_;
+ bool rtc_running_{false};
asio::ip::udp::endpoint remote_;
- std::pair<uint8_t *, std::size_t> recv_buffer_;
-#endif
+ utils::MemBuf recv_buffer_{utils::MemBuf::CREATE, HIPERF_MTU};
+ std::array<uint8_t, HIPERF_MTU> rtc_payload_;
};
-HIperfServer::HIperfServer(const ServerConfiguration &conf) {
- impl_ = new Impl(conf);
-}
+HIperfServer::HIperfServer(const ServerConfiguration &conf)
+ : impl_(std::make_unique<Impl>(conf)) {}
-HIperfServer::~HIperfServer() { delete impl_; }
+HIperfServer::~HIperfServer() = default;
int HIperfServer::setup() { return impl_->setup(); }
diff --git a/apps/hiperf/src/server.h b/apps/hiperf/src/server.h
index 05407a807..d7420da48 100644
--- a/apps/hiperf/src/server.h
+++ b/apps/hiperf/src/server.h
@@ -21,14 +21,15 @@ namespace hiperf {
class HIperfServer {
public:
- HIperfServer(const ServerConfiguration &conf);
+ explicit HIperfServer(const ServerConfiguration &conf);
+
~HIperfServer();
int setup();
void run();
private:
class Impl;
- Impl *impl_;
+ std::unique_ptr<Impl> impl_;
};
} // namespace hiperf \ No newline at end of file
diff --git a/apps/http-proxy/CMakeLists.txt b/apps/http-proxy/CMakeLists.txt
index 66b9c1bab..80f671567 100644
--- a/apps/http-proxy/CMakeLists.txt
+++ b/apps/http-proxy/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,8 +11,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-set(CMAKE_CXX_STANDARD 14)
+##############################################################
+# Compiler options
+##############################################################
+set(COMPILER_OPTIONS
+ PRIVATE ${DEFAULT_COMPILER_OPTIONS}
+)
# -Wno-c99-designator issue
#
@@ -22,20 +26,22 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
EXECUTE_PROCESS( COMMAND ${CMAKE_CXX_COMPILER} --version OUTPUT_VARIABLE clang_full_version_string )
string (REGEX REPLACE ".*clang version ([0-9]+\\.[0-9]+).*" "\\1" CLANG_VERSION_STRING ${clang_full_version_string})
if (CLANG_VERSION_STRING VERSION_GREATER_EQUAL 11)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c99-designator")
+ list(APPEND COMPILER_OPTIONS
+ "-Wno-c99-designator"
+ )
endif()
endif()
-set(CMAKE_MODULE_PATH
- ${CMAKE_MODULE_PATH}
- "${CMAKE_SOURCE_DIR}/cmake/Modules/"
-)
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
-endif ()
+##############################################################
+# Includes subdirectory
+##############################################################
+add_subdirectory(includes/hicn/http-proxy)
+
+##############################################################
+# Source files
+##############################################################
set(LIB_SOURCE_FILES
src/http_session.cc
src/http_proxy.cc
@@ -48,41 +54,50 @@ set(APP_SOURCE_FILES
main.cc
)
-add_subdirectory(includes/hicn/http-proxy)
-set(LIBHTTP_PROXY hicnhttpproxy)
-set(LIBHTTP_PROXY_STATIC ${LIBHTTP_PROXY}.static)
-
-list(APPEND COMPILER_DEFINITIONS
- -DWITH_POLICY
-)
-
+##############################################################
+# Libraries to link
+##############################################################
list(APPEND HTTP_PROXY_LIBRARIES
- ${LIBTRANSPORT_LIBRARIES}
- ${LIBHICNCTRL_LIBRARIES}
- ${LIBHICN_LIBRARIES}
- ${OPENSSL_LIBRARIES}
- ${CMAKE_THREAD_LIBS_INIT}
+ PUBLIC ${LIBTRANSPORT_LIBRARIES}
+ PUBLIC ${LIBHICNCTRL_LIBRARIES}
+ PUBLIC ${LIBHICN_LIBRARIES}
+ PRIVATE ${CMAKE_THREAD_LIBS_INIT}
)
+
+##############################################################
+# Build http proxy library
+##############################################################
build_library(${LIBHTTP_PROXY}
STATIC
SOURCES ${LIB_SOURCE_FILES}
LINK_LIBRARIES ${HTTP_PROXY_LIBRARIES}
+ INCLUDE_DIRS
+ PRIVATE ${THIRD_PARTY_INCLUDE_DIRS} ${COMMON_INCLUDE_DIRS}
DEPENDS ${DEPENDENCIES}
INSTALL_HEADERS ${LIBPROXY_TO_INSTALL_HEADER_FILES}
- INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIRS} ${LIBHICNCTRL_INCLUDE_DIRS} ${LIBPROXY_INCLUDE_DIRS}
+ INCLUDE_DIRS
+ PUBLIC
+ $<BUILD_INTERFACE:${LIBPROXY_INCLUDE_DIRS}>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
COMPONENT ${HICN_APPS}
LINK_FLAGS ${LINK_FLAGS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
+
+##############################################################
+# Build http proxy executable
+##############################################################
if (NOT DISABLE_EXECUTABLES)
build_executable(${HTTP_PROXY}
SOURCES ${APP_SOURCE_FILES}
LINK_LIBRARIES ${LIBHTTP_PROXY_STATIC}
- DEPENDS ${LIBHTTP_PROXY_STATIC}
+ INCLUDE_DIRS
+ PRIVATE ${THIRD_PARTY_INCLUDE_DIRS} ${COMMON_INCLUDE_DIRS}
+ DEPENDS ${LIBHTTP_PROXY_STATIC} ${THIRD_PARTY_DEPENDENCIES}
COMPONENT ${HICN_APPS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
endif ()
diff --git a/apps/http-proxy/includes/hicn/http-proxy/CMakeLists.txt b/apps/http-proxy/includes/hicn/http-proxy/CMakeLists.txt
index 5cc80a168..18f5704d1 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/CMakeLists.txt
+++ b/apps/http-proxy/includes/hicn/http-proxy/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -24,7 +24,7 @@ list(APPEND HEADER_FILES
set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
set(LIBPROXY_INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR}/../.. ""
+ ${CMAKE_CURRENT_SOURCE_DIR}/../..
CACHE INTERNAL
"" FORCE
)
@@ -34,4 +34,3 @@ set(LIBPROXY_TO_INSTALL_HEADER_FILES
CACHE INTERNAL
"" FORCE
)
-
diff --git a/apps/http-proxy/includes/hicn/http-proxy/forwarder_config.h b/apps/http-proxy/includes/hicn/http-proxy/forwarder_config.h
index e02b9d9a7..14e0068ed 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/forwarder_config.h
+++ b/apps/http-proxy/includes/hicn/http-proxy/forwarder_config.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,9 +15,9 @@
#pragma once
+#include <hicn/apps/utils/logger.h>
#include <hicn/transport/portability/c_portability.h>
#include <hicn/transport/utils/branch_prediction.h>
-#include <hicn/transport/utils/log.h>
#include <hicn/transport/utils/string_utils.h>
#include <asio.hpp>
@@ -60,15 +60,14 @@ class ForwarderConfig {
doTryToConnectToForwarder(std::make_error_code(std::errc(0)));
}
- void doTryToConnectToForwarder(std::error_code ec) {
+ void doTryToConnectToForwarder(const std::error_code& ec) {
if (!ec) {
// ec == 0 --> timer expired
int ret = forwarder_interface_.connectToForwarder();
if (ret < 0) {
// We were not able to connect to the local forwarder. Do not give up
// and retry.
- TRANSPORT_LOG_ERROR
- << "Could not connect to local forwarder. Retrying.";
+ LoggerErr() << "Could not connect to local forwarder. Retrying.";
timer_.expires_from_now(std::chrono::milliseconds(RETRY_INTERVAL));
timer_.async_wait(std::bind(&ForwarderConfig::doTryToConnectToForwarder,
@@ -79,19 +78,18 @@ class ForwarderConfig {
doGetMainListener(std::make_error_code(std::errc(0)));
}
} else {
- TRANSPORT_LOG_ERROR
- << "Timer for re-trying forwarder connection canceled.";
+ LoggerErr() << "Timer for re-trying forwarder connection canceled.";
}
}
- void doGetMainListener(std::error_code ec) {
+ void doGetMainListener(const std::error_code& ec) {
if (!ec) {
// ec == 0 --> timer expired
int ret = forwarder_interface_.getMainListenerPort();
if (ret <= 0) {
// Since without the main listener of the forwarder the proxy cannot
// work, we can stop the program here until we get the listener port.
- TRANSPORT_LOG_ERROR
+ LoggerErr()
<< "Could not retrieve main listener port from the forwarder. "
"Retrying.";
@@ -105,8 +103,7 @@ class ForwarderConfig {
listener_retrieved_callback_(std::make_error_code(std::errc(0)));
}
} else {
- TRANSPORT_LOG_ERROR
- << "Timer for retrieving main hicn listener canceled.";
+ LoggerErr() << "Timer for retrieving main hicn listener canceled.";
}
}
@@ -114,7 +111,7 @@ class ForwarderConfig {
TRANSPORT_ALWAYS_INLINE bool parseHicnHeader(std::string& header,
Callback&& callback) {
std::stringstream ss(header);
- route_info_t* ret = new route_info_t();
+ RouteInfoPtr ret = std::make_shared<route_info_t>();
std::string port_string;
while (ss.good()) {
@@ -174,9 +171,9 @@ class ForwarderConfig {
ret->family = AF_INET;
std::string _prefix = ret->route_addr;
forwarder_interface_.createFaceAndRoute(
- RouteInfoPtr(ret), [callback = std::forward<Callback>(callback),
- configured_prefix = std::move(_prefix)](
- uint32_t route_id, bool result) {
+ std::move(ret), [callback = std::forward<Callback>(callback),
+ configured_prefix = std::move(_prefix)](
+ uint32_t route_id, bool result) {
callback(result, configured_prefix);
});
diff --git a/apps/http-proxy/includes/hicn/http-proxy/forwarder_interface.h b/apps/http-proxy/includes/hicn/http-proxy/forwarder_interface.h
index 54941a4ba..ae9562a12 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/forwarder_interface.h
+++ b/apps/http-proxy/includes/hicn/http-proxy/forwarder_interface.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,8 +23,15 @@ extern "C" {
#ifndef ASIO_STANDALONE
#define ASIO_STANDALONE 1
#endif
-#include <asio.hpp>
-#include <asio/steady_timer.hpp>
+
+#ifdef __APPLE__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wshorten-64-to-32"
+#endif
+#include <hicn/transport/core/asio_wrapper.h>
+#ifdef __APPLE__
+#pragma clang diagnostic pop
+#endif
#include <functional>
#include <thread>
#include <unordered_map>
@@ -45,16 +52,11 @@ using RouteInfoPtr = std::shared_ptr<route_info_t>;
class ForwarderInterface {
public:
- ForwarderInterface(asio::io_service &io_service)
+ explicit ForwarderInterface(asio::io_service &io_service)
: external_ioservice_(io_service),
work_(std::make_unique<asio::io_service::work>(internal_ioservice_)),
- sock_(nullptr),
thread_(std::make_unique<std::thread>(
- [this]() { internal_ioservice_.run(); })),
- check_routes_timer_(nullptr),
- pending_add_route_counter_(0),
- route_id_(0),
- closed_(false) {}
+ [this]() { internal_ioservice_.run(); })) {}
~ForwarderInterface();
@@ -88,20 +90,20 @@ class ForwarderInterface {
void internalCreateFaceAndRoute(RouteInfoPtr route_info, uint8_t max_try,
asio::steady_timer *timer,
- SetRouteCallback callback);
+ const SetRouteCallback &callback);
- int tryToCreateFaceAndRoute(route_info_t *route_info);
+ int tryToCreateFaceAndRoute(const route_info_t *route_info);
asio::io_service &external_ioservice_;
asio::io_service internal_ioservice_;
std::unique_ptr<asio::io_service::work> work_;
- hc_sock_t *sock_;
+ hc_sock_t *sock_ = nullptr;
std::unique_ptr<std::thread> thread_;
std::unordered_map<uint32_t, RouteInfoPtr> route_status_;
- std::unique_ptr<asio::steady_timer> check_routes_timer_;
- uint32_t pending_add_route_counter_;
- uint32_t route_id_;
- bool closed_;
+ std::unique_ptr<asio::steady_timer> check_routes_timer_ = nullptr;
+ uint32_t pending_add_route_counter_ = 0;
+ uint32_t route_id_ = 0;
+ bool closed_ = false;
};
} // namespace transport
diff --git a/apps/http-proxy/includes/hicn/http-proxy/http_1x_message_fast_parser.h b/apps/http-proxy/includes/hicn/http-proxy/http_1x_message_fast_parser.h
index 7c035c83b..87a5c7d4e 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/http_1x_message_fast_parser.h
+++ b/apps/http-proxy/includes/hicn/http-proxy/http_1x_message_fast_parser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/apps/http-proxy/includes/hicn/http-proxy/http_proxy.h b/apps/http-proxy/includes/hicn/http-proxy/http_proxy.h
index a4139a620..567ab4540 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/http_proxy.h
+++ b/apps/http-proxy/includes/hicn/http-proxy/http_proxy.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#pragma once
+#include <hicn/apps/utils/logger.h>
#include <hicn/transport/interfaces/socket_consumer.h>
#include <hicn/transport/utils/event_thread.h>
@@ -22,7 +23,9 @@
#include "http_session.h"
#include "icn_receiver.h"
+#ifndef ASIO_STANDALONE
#define ASIO_STANDALONE
+#endif
#include <asio.hpp>
#include <asio/version.hpp>
#include <unordered_set>
@@ -31,7 +34,8 @@ class TcpListener {
public:
using AcceptCallback = std::function<void(asio::ip::tcp::socket&&)>;
- TcpListener(asio::io_service& io_service, short port, AcceptCallback callback)
+ TcpListener(asio::io_service& io_service, short port,
+ const AcceptCallback& callback)
: acceptor_(io_service),
#if ((ASIO_VERSION / 100 % 1000) < 12)
socket_(io_service),
@@ -46,13 +50,12 @@ class TcpListener {
acceptor_.listen();
}
- public:
void doAccept() {
#if ((ASIO_VERSION / 100 % 1000) >= 12)
acceptor_.async_accept(
- [this](std::error_code ec, asio::ip::tcp::socket socket) {
+ [this](const std::error_code& ec, asio::ip::tcp::socket socket) {
#else
- acceptor_.async_accept(socket_, [this](std::error_code ec) {
+ acceptor_.async_accept(socket_, [this](const std::error_code& ec) {
auto socket = std::move(socket_);
#endif
if (!ec) {
@@ -77,7 +80,7 @@ class HTTPClientConnectionCallback;
class Receiver {
public:
- Receiver() : thread_() {}
+ Receiver() {}
virtual ~Receiver() = default;
void stopAndJoinThread() { thread_.stop(); }
virtual void stop() = 0;
@@ -112,13 +115,13 @@ class TcpReceiver : public Receiver {
std::deque<HTTPClientConnectionCallback*> http_clients_;
std::unordered_set<HTTPClientConnectionCallback*> used_http_clients_;
ForwarderConfig forwarder_config_;
- bool stopped_;
+ bool stopped_ = false;
};
class IcnReceiver : public Receiver {
public:
template <typename... Args>
- IcnReceiver(Args&&... args)
+ explicit IcnReceiver(Args&&... args)
: Receiver(),
icn_consum_producer_(thread_.getIoService(),
std::forward<Args>(args)...) {
@@ -145,20 +148,18 @@ class HTTPProxy {
std::string prefix;
std::string first_ipv6_word;
- virtual void printParams() { std::cout << "Parameters: " << std::endl; };
+ virtual ~CommonParams() {}
+ virtual void printParams() { LoggerInfo() << "Parameters: "; };
};
struct ClientParams : virtual CommonParams {
short tcp_listen_port;
void printParams() override {
- std::cout << "Running HTTP/TCP -> HTTP/hICN proxy." << std::endl;
+ LoggerInfo() << "Running HTTP/TCP -> HTTP/hICN proxy.";
CommonParams::printParams();
- std::cout << "\t"
- << "HTTP listen port: " << tcp_listen_port << std::endl;
- std::cout << "\t"
- << "Consumer Prefix: " << prefix << std::endl;
- std::cout << "\t"
- << "Prefix first word: " << first_ipv6_word << std::endl;
+ LoggerInfo() << "\tHTTP listen port: " << tcp_listen_port;
+ LoggerInfo() << "\tConsumer Prefix: " << prefix;
+ LoggerInfo() << "\tPrefix first word: " << first_ipv6_word;
}
};
@@ -171,25 +172,24 @@ class HTTPProxy {
bool manifest;
void printParams() override {
- std::cout << "Running HTTP/hICN -> HTTP/TCP proxy." << std::endl;
+ LoggerInfo() << "Running HTTP/hICN -> HTTP/TCP proxy.";
CommonParams::printParams();
- std::cout << "\t"
- << "Origin address: " << origin_address << std::endl;
- std::cout << "\t"
- << "Origin port: " << origin_port << std::endl;
- std::cout << "\t"
- << "Producer cache size: " << cache_size << std::endl;
- std::cout << "\t"
- << "hICN MTU: " << mtu << std::endl;
- std::cout << "\t"
- << "Default content lifetime: " << content_lifetime
- << std::endl;
- std::cout << "\t"
- << "Producer Prefix: " << prefix << std::endl;
- std::cout << "\t"
- << "Prefix first word: " << first_ipv6_word << std::endl;
- std::cout << "\t"
- << "Use manifest: " << manifest << std::endl;
+ LoggerInfo() << "\t"
+ << "Origin address: " << origin_address;
+ LoggerInfo() << "\t"
+ << "Origin port: " << origin_port;
+ LoggerInfo() << "\t"
+ << "Producer cache size: " << cache_size;
+ LoggerInfo() << "\t"
+ << "hICN MTU: " << mtu;
+ LoggerInfo() << "\t"
+ << "Default content lifetime: " << content_lifetime;
+ LoggerInfo() << "\t"
+ << "Producer Prefix: " << prefix;
+ LoggerInfo() << "\t"
+ << "Prefix first word: " << first_ipv6_word;
+ LoggerInfo() << "\t"
+ << "Use manifest: " << manifest;
}
};
@@ -207,4 +207,4 @@ class HTTPProxy {
asio::signal_set signals_;
};
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/apps/http-proxy/includes/hicn/http-proxy/http_session.h b/apps/http-proxy/includes/hicn/http-proxy/http_session.h
index f4a3dbdee..1b7df96a6 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/http_session.h
+++ b/apps/http-proxy/includes/hicn/http-proxy/http_session.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,13 +17,19 @@
#include <hicn/transport/core/packet.h>
-#include "http_1x_message_fast_parser.h"
-
-#define ASIO_STANDALONE
-#include <asio.hpp>
+#ifdef __APPLE__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wshorten-64-to-32"
+#endif
+#include <hicn/transport/core/asio_wrapper.h>
+#ifdef __APPLE__
+#pragma clang diagnostic pop
+#endif
#include <deque>
#include <functional>
+#include "http_1x_message_fast_parser.h"
+
namespace transport {
using asio::ip::tcp;
@@ -67,13 +73,16 @@ class HTTPSession {
};
public:
- HTTPSession(asio::io_service &io_service, std::string &ip_address,
- std::string &port, ContentReceivedCallback receive_callback,
- OnConnectionClosed on_reconnect_callback, bool client = false);
+ HTTPSession(asio::io_service &io_service, const std::string &ip_address,
+ const std::string &port,
+ const ContentReceivedCallback &receive_callback,
+ const OnConnectionClosed &on_reconnect_callback,
+ bool client = false);
HTTPSession(asio::ip::tcp::socket socket,
- ContentReceivedCallback receive_callback,
- OnConnectionClosed on_reconnect_callback, bool client = true);
+ const ContentReceivedCallback &receive_callback,
+ const OnConnectionClosed &on_reconnect_callback,
+ bool client = true);
~HTTPSession();
@@ -97,8 +106,7 @@ class HTTPSession {
bool checkConnected();
- private:
- void handleRead(std::error_code ec, std::size_t length);
+ void handleRead(const std::error_code &ec, std::size_t length);
void tryReconnection();
void startConnectionTimer();
void handleDeadline(const std::error_code &ec);
@@ -114,14 +122,14 @@ class HTTPSession {
asio::streambuf input_buffer_;
bool reverse_;
- bool is_reconnection_;
- bool data_available_;
+ bool is_reconnection_ = false;
+ bool data_available_ = false;
- std::size_t content_length_;
+ std::size_t content_length_ = 0;
// Chunked encoding
- bool is_last_chunk_;
- bool chunked_;
+ bool is_last_chunk_ = false;
+ bool chunked_ = false;
ContentReceivedCallback receive_callback_;
OnConnectionClosed on_connection_closed_callback_;
diff --git a/apps/http-proxy/includes/hicn/http-proxy/icn_receiver.h b/apps/http-proxy/includes/hicn/http-proxy/icn_receiver.h
index 780037665..e3ab97fdd 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/icn_receiver.h
+++ b/apps/http-proxy/includes/hicn/http-proxy/icn_receiver.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,20 +13,18 @@
* limitations under the License.
*/
+#include <hicn/http-proxy/http_session.h>
+#include <hicn/transport/core/asio_wrapper.h>
#include <hicn/transport/core/prefix.h>
#include <hicn/transport/interfaces/publication_options.h>
#include <hicn/transport/interfaces/socket_producer.h>
#include <hicn/transport/utils/spinlock.h>
-#include <asio.hpp>
#include <cassert>
#include <cstring>
#include <queue>
#include <utility>
-#include <hicn/http-proxy/http_session.h>
-//#include "http_session.h"
-
namespace transport {
class AsyncConsumerProducer {
@@ -49,9 +47,7 @@ class AsyncConsumerProducer {
const std::string& content_lifetime, bool manifest)
: AsyncConsumerProducer(internal_io_service_, prefix, first_ipv6_word,
origin_address, origin_port, cache_size, mtu,
- content_lifetime, manifest) {
- external_io_service_ = false;
- }
+ content_lifetime, manifest) {}
void run();
@@ -73,7 +69,7 @@ class AsyncConsumerProducer {
core::Prefix prefix_;
asio::io_service& io_service_;
asio::io_service internal_io_service_;
- bool external_io_service_;
+ bool external_io_service_ = false;
interface::ProducerSocket producer_socket_;
std::string ip_address_;
@@ -81,9 +77,8 @@ class AsyncConsumerProducer {
uint32_t cache_size_;
uint32_t mtu_;
- uint64_t request_counter_;
+ uint64_t request_counter_ = 0;
- // std::unordered_map<core::Name, std::shared_ptr<ATSConnector>>
// connection_map_;
HTTPSession connector_;
diff --git a/apps/http-proxy/includes/hicn/http-proxy/utils.h b/apps/http-proxy/includes/hicn/http-proxy/utils.h
index d87c796d0..9865d8e4c 100644
--- a/apps/http-proxy/includes/hicn/http-proxy/utils.h
+++ b/apps/http-proxy/includes/hicn/http-proxy/utils.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -35,17 +35,16 @@ TRANSPORT_ALWAYS_INLINE std::string generatePrefix(
str += pos;
uint32_t locator_hash = utils::hash::fnv32_buf(str, strlen(str));
+ const uint16_t* word = (const uint16_t*)&locator_hash;
std::stringstream stream;
stream << first_ipv6_word << ":0";
- 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;
+ for (std::size_t i = 0; i < sizeof(locator_hash) / 2; i++) {
+ stream << ":" << std::hex << word[i];
}
stream << "::";
return stream.str();
-} \ No newline at end of file
+}
diff --git a/apps/http-proxy/main.cc b/apps/http-proxy/main.cc
index d9c29ecde..832ec23e6 100644
--- a/apps/http-proxy/main.cc
+++ b/apps/http-proxy/main.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,32 +13,31 @@
* limitations under the License.
*/
+#include <hicn/apps/utils/logger.h>
#include <hicn/http-proxy/http_proxy.h>
using namespace transport;
-int usage(char* program) {
- std::cerr << "USAGE: " << program << "[-C|-S] [options] <http_prefix>\n"
- << "Server or Client: \n"
- << " -P [FIRST_IPv6_WORD_HEX]\n"
- << " -t [number of threads]\n"
- << "Client Options: \n"
- << " -L [PROXY_LISTEN_PORT]\n"
- << "Server Options: \n"
- << " -a [ORIGIN_IP_ADDRESS]\n"
- << " -p [ORIGIN_PORT]\n"
- << " -c [CACHE_SIZE]\n"
- << " -m [MTU]"
- << " -l [DEFAULT_CONTENT_LIFETIME] (seconds)\n"
- << " -M (enable manifest)\n"
- << std::endl
- << "Example Server:\n"
- << " " << program
- << " -S -a example.com -p 80 -c 10000 -m 1300 -l 7200 -M -t 1 "
- "http://httpserver\n"
- << "Example Client:\n"
- << " " << program << " -C -L 9091 http://httpserver\n"
- << std::endl;
+int usage(const char* program) {
+ LoggerInfo() << "USAGE: " << program << "[-C|-S] [options] <http_prefix>\n"
+ << "Server or Client: \n"
+ << " -P [FIRST_IPv6_WORD_HEX]\n"
+ << " -t [number of threads]\n"
+ << "Client Options: \n"
+ << " -L [PROXY_LISTEN_PORT]\n"
+ << "Server Options: \n"
+ << " -a [ORIGIN_IP_ADDRESS]\n"
+ << " -p [ORIGIN_PORT]\n"
+ << " -c [CACHE_SIZE]\n"
+ << " -m [MTU]"
+ << " -l [DEFAULT_CONTENT_LIFETIME] (seconds)\n"
+ << " -M (enable manifest)\n";
+ LoggerInfo() << "Example Server:\n"
+ << " " << program
+ << " -S -a example.com -p 80 -c 10000 -m 1300 -l 7200 -M -t 1 "
+ "http://httpserver\n"
+ << "Example Client:\n"
+ << " " << program << " -C -L 9091 http://httpserver\n";
return -1;
}
@@ -53,8 +52,7 @@ struct Params : HTTPProxy::ClientParams, HTTPProxy::ServerParams {
"Proxy configured as client and server at the same time.");
}
- std::cout << "\t"
- << "N Threads: " << n_thread << std::endl;
+ LoggerInfo() << "\tN Threads: " << n_thread;
}
HTTPProxy* instantiateProxyAsValue() {
@@ -93,18 +91,16 @@ int main(int argc, char** argv) {
switch (opt) {
case 'C':
if (params.server) {
- std::cerr << "Cannot be both client and server (both -C anc -S "
- "options specified.)."
- << std::endl;
+ LoggerErr() << "Cannot be both client and server (both -C anc -S "
+ "options specified.).";
return usage(argv[0]);
}
params.client = true;
break;
case 'S':
if (params.client) {
- std::cerr << "Cannot be both client and server (both -C anc -S "
- "options specified.)."
- << std::endl;
+ LoggerErr() << "Cannot be both client and server (both -C anc -S "
+ "options specified.).";
return usage(argv[0]);
}
params.server = true;
@@ -136,15 +132,13 @@ int main(int argc, char** argv) {
case 't':
params.n_thread = std::stoul(optarg);
break;
- case 'h':
default:
return usage(argv[0]);
- break;
}
}
if (argv[optind] == 0) {
- std::cerr << "Using default prefix " << params.prefix << std::endl;
+ LoggerInfo() << "Using default prefix " << params.prefix;
} else {
params.prefix = argv[optind];
}
@@ -155,4 +149,4 @@ int main(int argc, char** argv) {
delete proxy;
return 0;
-} \ No newline at end of file
+}
diff --git a/apps/http-proxy/src/forwarder_interface.cc b/apps/http-proxy/src/forwarder_interface.cc
index c2448de9a..717679e09 100644
--- a/apps/http-proxy/src/forwarder_interface.cc
+++ b/apps/http-proxy/src/forwarder_interface.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,8 +14,8 @@
*/
#include <arpa/inet.h>
+#include <hicn/apps/utils/logger.h>
#include <hicn/http-proxy/forwarder_interface.h>
-#include <hicn/transport/utils/log.h>
#include <chrono>
#include <iostream>
@@ -27,7 +27,7 @@ namespace transport {
ForwarderInterface::~ForwarderInterface() {}
int ForwarderInterface::connectToForwarder() {
- sock_ = hc_sock_create();
+ sock_ = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, NULL);
if (!sock_) return -1;
if (hc_sock_connect(sock_) < 0) {
@@ -96,7 +96,8 @@ void ForwarderInterface::internalRemoveConnectedUser(uint32_t route_id) {
std::vector<hc_route_t *> routes_to_remove;
foreach_route(r, data) {
char remote_addr[INET6_ADDRSTRLEN];
- int ret = ip_address_ntop(&r->remote_addr, remote_addr, r->len, r->family);
+ int ret =
+ hicn_ip_address_ntop(&r->remote_addr, remote_addr, r->len, r->family);
if (ret < 0) continue;
std::string route_addr(remote_addr);
@@ -119,7 +120,7 @@ void ForwarderInterface::internalRemoveConnectedUser(uint32_t route_id) {
for (unsigned i = 0; i < routes_to_remove.size(); i++) {
connids_to_remove.insert(routes_to_remove[i]->face_id);
if (hc_route_delete(sock_, routes_to_remove[i]) < 0) {
- TRANSPORT_LOG_ERROR << "Error removing route from forwarder.";
+ LoggerErr() << "Error removing route from forwarder.";
}
}
@@ -146,24 +147,23 @@ void ForwarderInterface::internalRemoveConnectedUser(uint32_t route_id) {
for (unsigned i = 0; i < conns_to_remove.size(); i++) {
if (hc_connection_delete(sock_, conns_to_remove[i]) < 0) {
- TRANSPORT_LOG_ERROR << "Error removing connection from forwarder.";
+ LoggerErr() << "Error removing connection from forwarder.";
}
}
hc_data_free(data);
}
-void ForwarderInterface::internalCreateFaceAndRoute(RouteInfoPtr route_info,
- uint8_t max_try,
- asio::steady_timer *timer,
- SetRouteCallback callback) {
+void ForwarderInterface::internalCreateFaceAndRoute(
+ RouteInfoPtr route_info, uint8_t max_try, asio::steady_timer *timer,
+ const SetRouteCallback &callback) {
int ret = tryToCreateFaceAndRoute(route_info.get());
if (ret < 0 && max_try > 0) {
max_try--;
timer->expires_from_now(std::chrono::milliseconds(500));
timer->async_wait([this, _route_info = std::move(route_info), max_try,
- timer, callback](std::error_code ec) {
+ timer, callback](const std::error_code &ec) {
if (ec) return;
internalCreateFaceAndRoute(std::move(_route_info), max_try, timer,
std::move(callback));
@@ -185,7 +185,8 @@ void ForwarderInterface::internalCreateFaceAndRoute(RouteInfoPtr route_info,
delete timer;
}
-int ForwarderInterface::tryToCreateFaceAndRoute(route_info_t *route_info) {
+int ForwarderInterface::tryToCreateFaceAndRoute(
+ const route_info_t *route_info) {
if (!sock_) return -1;
hc_data_t *data;
@@ -201,8 +202,9 @@ int ForwarderInterface::tryToCreateFaceAndRoute(route_info_t *route_info) {
if (interface.compare("lo") != 0) {
found = true;
- ip_address_t remote_ip;
- if (ip_address_pton(route_info->remote_addr.c_str(), &remote_ip) < 0) {
+ hicn_ip_address_t remote_ip;
+ if (hicn_ip_address_pton(route_info->remote_addr.c_str(), &remote_ip) <
+ 0) {
hc_data_free(data);
return -1;
}
@@ -210,14 +212,14 @@ int ForwarderInterface::tryToCreateFaceAndRoute(route_info_t *route_info) {
hc_face_t face;
memset(&face, 0, sizeof(hc_face_t));
- face.face.type = FACE_TYPE_UDP;
- face.face.family = route_info->family;
- face.face.local_addr = l->local_addr;
- face.face.remote_addr = remote_ip;
- face.face.local_port = l->local_port;
- face.face.remote_port = route_info->remote_port;
+ face.type = FACE_TYPE_UDP;
+ face.family = route_info->family;
+ face.local_addr = l->local_addr;
+ face.remote_addr = remote_ip;
+ face.local_port = l->local_port;
+ face.remote_port = route_info->remote_port;
- if (netdevice_set_name(&face.face.netdevice, l->interface_name) < 0) {
+ if (netdevice_set_name(&face.netdevice, l->interface_name) < 0) {
hc_data_free(data);
return -1;
}
@@ -237,10 +239,10 @@ int ForwarderInterface::tryToCreateFaceAndRoute(route_info_t *route_info) {
return -1;
}
- ip_address_t route_ip;
+ hicn_ip_address_t route_ip;
hc_route_t route;
- if (ip_address_pton(route_info->route_addr.c_str(), &route_ip) < 0) {
+ if (hicn_ip_address_pton(route_info->route_addr.c_str(), &route_ip) < 0) {
hc_data_free(data);
return -1;
}
diff --git a/apps/http-proxy/src/http_1x_message_fast_parser.cc b/apps/http-proxy/src/http_1x_message_fast_parser.cc
index 4b6b78d55..ffae2368b 100644
--- a/apps/http-proxy/src/http_1x_message_fast_parser.cc
+++ b/apps/http-proxy/src/http_1x_message_fast_parser.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -99,7 +99,8 @@ bool HTTPMessageFastParser::isMpdRequest(const uint8_t *headers,
return false;
}
-uint32_t HTTPMessageFastParser::parseCacheControl(const uint8_t *headers,
- std::size_t length) {
+uint32_t HTTPMessageFastParser::parseCacheControl(
+ [[maybe_unused]] const uint8_t *headers,
+ [[maybe_unused]] std::size_t length) {
return 0;
}
diff --git a/apps/http-proxy/src/http_proxy.cc b/apps/http-proxy/src/http_proxy.cc
index 2040f7cfa..7419c7f7f 100644
--- a/apps/http-proxy/src/http_proxy.cc
+++ b/apps/http-proxy/src/http_proxy.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,11 +13,11 @@
* limitations under the License.
*/
+#include <hicn/apps/utils/logger.h>
#include <hicn/http-proxy/http_proxy.h>
#include <hicn/http-proxy/http_session.h>
#include <hicn/http-proxy/utils.h>
#include <hicn/transport/core/interest.h>
-#include <hicn/transport/utils/log.h>
#include <hicn/transport/utils/string_utils.h>
namespace transport {
@@ -29,16 +29,15 @@ using interface::ConsumerInterestCallback;
using interface::ConsumerSocket;
using interface::TransportProtocolAlgorithms;
-class HTTPClientConnectionCallback : interface::ConsumerSocket::ReadCallback {
+class HTTPClientConnectionCallback
+ : public interface::ConsumerSocket::ReadCallback {
public:
HTTPClientConnectionCallback(TcpReceiver& tcp_receiver,
utils::EventThread& thread)
: tcp_receiver_(tcp_receiver),
thread_(thread),
prefix_hash_(tcp_receiver_.prefix_hash_),
- consumer_(TransportProtocolAlgorithms::RAAQM, thread_.getIoService()),
- session_(nullptr),
- current_size_(0) {
+ consumer_(TransportProtocolAlgorithms::RAAQM, thread_) {
consumer_.setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK, this);
consumer_.setSocketOption(
ConsumerCallbacksOptions::INTEREST_OUTPUT,
@@ -62,15 +61,15 @@ class HTTPClientConnectionCallback : interface::ConsumerSocket::ReadCallback {
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4,
std::placeholders::_5),
- [this](asio::ip::tcp::socket& socket) -> bool {
+ [this](const asio::ip::tcp::socket& socket) {
try {
std::string remote_address =
socket.remote_endpoint().address().to_string();
std::uint16_t remote_port = socket.remote_endpoint().port();
- TRANSPORT_LOG_INFO << "Client " << remote_address << ":"
- << remote_port << "disconnected.";
- } catch (std::system_error& e) {
- // Do nothing
+ LoggerInfo() << "Client " << remote_address << ":" << remote_port
+ << "disconnected.";
+ } catch (asio::system_error& e) {
+ LoggerInfo() << "Client disconnected.";
}
consumer_.stop();
@@ -136,24 +135,19 @@ class HTTPClientConnectionCallback : interface::ConsumerSocket::ReadCallback {
current_size_ += size;
if (is_last) {
- // TRANSPORT_LOGD("Request received: %s",
- // std::string((const char*)tmp_buffer_.first->data(),
- // tmp_buffer_.first->length())
- // .c_str());
if (current_size_ < 1400) {
request_buffer_queue_.emplace_back(std::move(tmp_buffer_));
} else {
- TRANSPORT_LOG_ERROR << "Ignoring client request due to size ("
- << current_size_ << ") > 1400.";
+ LoggerErr() << "Ignoring client request due to size (" << current_size_
+ << ") > 1400.";
session_->close();
current_size_ = 0;
return;
}
if (!consumer_.isRunning()) {
- TRANSPORT_LOG_INFO
- << "Consumer stopped, triggering consume from TCP session "
- "handler..";
+ LoggerInfo() << "Consumer stopped, triggering consume from TCP session "
+ "handler..";
consumeNextRequest();
}
@@ -163,15 +157,16 @@ class HTTPClientConnectionCallback : interface::ConsumerSocket::ReadCallback {
// hicn callbacks
- void processLeavingInterest(interface::ConsumerSocket& c,
- const core::Interest& interest) {
+ void processLeavingInterest(
+ [[maybe_unused]] const interface::ConsumerSocket& c,
+ const core::Interest& interest) {
if (interest.getName().getSuffix() == 0 && interest.payloadSize() == 0) {
Interest& int2 = const_cast<Interest&>(interest);
int2.appendPayload(request_buffer_queue_.front().first->clone());
}
}
- void processInterestRetx(interface::ConsumerSocket& c,
+ void processInterestRetx([[maybe_unused]] const interface::ConsumerSocket& c,
const core::Interest& interest) {
if (interest.payloadSize() == 0) {
Interest& int2 = const_cast<Interest&>(interest);
@@ -180,20 +175,22 @@ class HTTPClientConnectionCallback : interface::ConsumerSocket::ReadCallback {
}
bool isBufferMovable() noexcept { return true; }
- void getReadBuffer(uint8_t** application_buffer, size_t* max_length) {}
- void readDataAvailable(size_t length) noexcept {}
+ void getReadBuffer(uint8_t** application_buffer,
+ size_t* max_length) { /*nothing to do*/
+ }
+ void readDataAvailable(size_t length) noexcept { /*nothing to do*/
+ }
size_t maxBufferSize() const { return 64 * 1024; }
void readBufferAvailable(std::unique_ptr<utils::MemBuf>&& buffer) noexcept {
// Response received. Send it back to client
auto _buffer = buffer.release();
// TRANSPORT_LOGD("From hicn: %zu bytes.", _buffer->length());
- session_->send(_buffer, []() {});
+ session_->send(_buffer, []() { /*nothing to do*/ });
}
- void readError(const std::error_code ec) noexcept {
- TRANSPORT_LOG_ERROR
- << "Error reading from hicn consumer socket. Closing session.";
+ void readError(const std::error_code& ec) noexcept {
+ LoggerErr() << "Error reading from hicn consumer socket. Closing session.";
session_->close();
}
@@ -213,15 +210,16 @@ class HTTPClientConnectionCallback : interface::ConsumerSocket::ReadCallback {
session_->send((const uint8_t*)HTTPMessageFastParser::http_cors,
std::strlen(HTTPMessageFastParser::http_cors), [this]() {
auto& socket = session_->socket_;
- TRANSPORT_LOG_INFO
- << "Sent OPTIONS to client "
- << socket.remote_endpoint().address() << ":"
- << socket.remote_endpoint().port();
+ LoggerInfo() << "Sent OPTIONS to client "
+ << socket.remote_endpoint().address()
+ << ":" << socket.remote_endpoint().port();
});
}
} else {
tcp_receiver_.parseHicnHeader(
- it->second, [this](bool result, std::string configured_prefix) {
+ it->second,
+ [this](bool result,
+ [[maybe_unused]] const std::string& configured_prefix) {
const char* reply = nullptr;
if (result) {
reply = HTTPMessageFastParser::http_ok;
@@ -230,28 +228,26 @@ class HTTPClientConnectionCallback : interface::ConsumerSocket::ReadCallback {
}
/* Route created. Send back a 200 OK to client */
- session_->send((const uint8_t*)reply, std::strlen(reply),
- [this, result]() {
- auto& socket = session_->socket_;
- TRANSPORT_LOG_INFO
- << "Sent " << result << " response to client "
- << socket.remote_endpoint().address() << ":"
- << socket.remote_endpoint().port();
- });
+ session_->send(
+ (const uint8_t*)reply, std::strlen(reply), [this, result]() {
+ auto& socket = session_->socket_;
+ LoggerInfo() << "Sent " << result << " response to client "
+ << socket.remote_endpoint().address() << ":"
+ << socket.remote_endpoint().port();
+ });
});
}
}
- private:
TcpReceiver& tcp_receiver_;
utils::EventThread& thread_;
std::string& prefix_hash_;
ConsumerSocket consumer_;
- std::unique_ptr<HTTPSession> session_;
+ std::unique_ptr<HTTPSession> session_ = nullptr;
std::deque<std::pair<std::unique_ptr<utils::MemBuf>, std::string>>
request_buffer_queue_;
std::pair<std::unique_ptr<utils::MemBuf>, std::string> tmp_buffer_;
- std::size_t current_size_;
+ std::size_t current_size_ = 0;
};
TcpReceiver::TcpReceiver(std::uint16_t port, const std::string& prefix,
@@ -264,8 +260,7 @@ TcpReceiver::TcpReceiver(std::uint16_t port, const std::string& prefix,
ipv6_first_word_(ipv6_first_word),
prefix_hash_(generatePrefix(prefix_, ipv6_first_word_)),
forwarder_config_(
- thread_.getIoService(),
- [this](std::error_code ec) {
+ thread_.getIoService(), [this](const std::error_code& ec) {
if (!ec) {
listener_.doAccept();
for (int i = 0; i < 10; i++) {
@@ -273,8 +268,7 @@ TcpReceiver::TcpReceiver(std::uint16_t port, const std::string& prefix,
new HTTPClientConnectionCallback(*this, thread_));
}
}
- }),
- stopped_(false) {
+ }) {
forwarder_config_.tryToConnectToForwarder();
}
@@ -331,8 +325,8 @@ void TcpReceiver::onNewConnection(asio::ip::tcp::socket&& socket) {
void HTTPProxy::setupSignalHandler() {
signals_.async_wait([this](const std::error_code& ec, int signal_number) {
if (!ec) {
- TRANSPORT_LOG_INFO << "Received signal " << signal_number
- << ". Stopping gracefully.";
+ LoggerInfo() << "Received signal " << signal_number
+ << ". Stopping gracefully.";
stop();
}
});
@@ -353,7 +347,6 @@ void HTTPProxy::stop() {
HTTPProxy::HTTPProxy(ClientParams& params, std::size_t n_thread)
: signals_(main_io_context_, SIGINT, SIGQUIT) {
for (uint16_t i = 0; i < n_thread; i++) {
- // icn_receivers_.emplace_back(std::make_unique<IcnReceiver>(icn_params));
receivers_.emplace_back(std::make_unique<TcpReceiver>(
params.tcp_listen_port, params.prefix, params.first_ipv6_word));
}
diff --git a/apps/http-proxy/src/http_session.cc b/apps/http-proxy/src/http_session.cc
index 84c814cbd..06a81dc27 100644
--- a/apps/http-proxy/src/http_session.cc
+++ b/apps/http-proxy/src/http_session.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,30 +13,24 @@
* limitations under the License.
*/
+#include <hicn/apps/utils/logger.h>
#include <hicn/http-proxy/http_proxy.h>
#include <hicn/transport/utils/branch_prediction.h>
-#include <hicn/transport/utils/log.h>
#include <iostream>
namespace transport {
-HTTPSession::HTTPSession(asio::io_service &io_service, std::string &ip_address,
- std::string &port,
- ContentReceivedCallback receive_callback,
- OnConnectionClosed on_connection_closed_callback,
- bool client)
+HTTPSession::HTTPSession(
+ asio::io_service &io_service, const std::string &ip_address,
+ const std::string &port, const ContentReceivedCallback &receive_callback,
+ const OnConnectionClosed &on_connection_closed_callback, bool client)
: io_service_(io_service),
socket_(io_service_),
resolver_(io_service_),
endpoint_iterator_(resolver_.resolve({ip_address, port})),
timer_(io_service),
reverse_(client),
- is_reconnection_(false),
- data_available_(false),
- content_length_(0),
- is_last_chunk_(false),
- chunked_(false),
receive_callback_(receive_callback),
on_connection_closed_callback_(on_connection_closed_callback) {
input_buffer_.prepare(buffer_size + 2048);
@@ -51,10 +45,10 @@ HTTPSession::HTTPSession(asio::io_service &io_service, std::string &ip_address,
doConnect();
}
-HTTPSession::HTTPSession(asio::ip::tcp::socket socket,
- ContentReceivedCallback receive_callback,
- OnConnectionClosed on_connection_closed_callback,
- bool client)
+HTTPSession::HTTPSession(
+ asio::ip::tcp::socket socket,
+ const ContentReceivedCallback &receive_callback,
+ const OnConnectionClosed &on_connection_closed_callback, bool client)
:
#if ((ASIO_VERSION / 100 % 1000) < 12)
io_service_(socket.get_io_service()),
@@ -92,7 +86,7 @@ void HTTPSession::send(const uint8_t *packet, std::size_t len,
io_service_.dispatch([this, packet, len, content_sent]() {
asio::async_write(socket_, asio::buffer(packet, len),
[content_sent = std::move(content_sent)](
- std::error_code ec, std::size_t /*length*/) {
+ const std::error_code &ec, std::size_t /*length*/) {
if (!ec) {
content_sent();
}
@@ -120,9 +114,7 @@ void HTTPSession::close() {
if (state_ != ConnectorState::CLOSED) {
state_ = ConnectorState::CLOSED;
if (socket_.is_open()) {
- // socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both);
socket_.close();
- // on_disconnect_callback_();
}
}
}
@@ -130,25 +122,26 @@ void HTTPSession::close() {
void HTTPSession::doWrite() {
auto &buffer = write_msgs_.front().first;
- asio::async_write(socket_, asio::buffer(buffer->data(), buffer->length()),
- [this](std::error_code ec, std::size_t length) {
- if (TRANSPORT_EXPECT_FALSE(!ec)) {
- write_msgs_.front().second();
- write_msgs_.pop_front();
- if (!write_msgs_.empty()) {
- doWrite();
- }
- }
- });
+ asio::async_write(
+ socket_, asio::buffer(buffer->data(), buffer->length()),
+ [this](const std::error_code &ec, [[maybe_unused]] std::size_t length) {
+ if (TRANSPORT_EXPECT_FALSE(!ec)) {
+ write_msgs_.front().second();
+ write_msgs_.pop_front();
+ if (!write_msgs_.empty()) {
+ doWrite();
+ }
+ }
+ });
} // namespace transport
-void HTTPSession::handleRead(std::error_code ec, std::size_t length) {
+void HTTPSession::handleRead(const std::error_code &ec, std::size_t length) {
if (TRANSPORT_EXPECT_TRUE(!ec)) {
content_length_ -= length;
const uint8_t *buffer =
asio::buffer_cast<const uint8_t *>(input_buffer_.data());
- bool is_last = chunked_ ? (is_last_chunk_ ? !content_length_ : false)
- : !content_length_;
+ bool check = is_last_chunk_ ? !content_length_ : false;
+ bool is_last = chunked_ ? check : !content_length_;
receive_callback_(buffer, input_buffer_.size(), is_last, false, nullptr);
input_buffer_.consume(input_buffer_.size());
@@ -207,7 +200,7 @@ void HTTPSession::doReadBody(std::size_t body_size,
void HTTPSession::doReadChunkedHeader() {
asio::async_read_until(
socket_, input_buffer_, "\r\n",
- [this](std::error_code ec, std::size_t length) {
+ [this](const std::error_code &ec, std::size_t length) {
if (TRANSPORT_EXPECT_TRUE(!ec)) {
const uint8_t *buffer =
asio::buffer_cast<const uint8_t *>(input_buffer_.data());
@@ -226,7 +219,7 @@ void HTTPSession::doReadChunkedHeader() {
void HTTPSession::doReadHeader() {
asio::async_read_until(
socket_, input_buffer_, "\r\n\r\n",
- [this](std::error_code ec, std::size_t length) {
+ [this](const std::error_code &ec, std::size_t length) {
if (TRANSPORT_EXPECT_TRUE(!ec)) {
const uint8_t *buffer =
asio::buffer_cast<const uint8_t *>(input_buffer_.data());
@@ -269,12 +262,11 @@ void HTTPSession::doReadHeader() {
void HTTPSession::tryReconnection() {
if (on_connection_closed_callback_(socket_)) {
if (state_ == ConnectorState::CONNECTED) {
- TRANSPORT_LOG_ERROR << "Connection lost. Trying to reconnect...";
+ LoggerErr() << "Connection lost. Trying to reconnect...";
state_ = ConnectorState::CONNECTING;
is_reconnection_ = true;
io_service_.post([this]() {
if (socket_.is_open()) {
- // socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both);
socket_.close();
}
startConnectionTimer();
@@ -287,7 +279,7 @@ void HTTPSession::tryReconnection() {
void HTTPSession::doConnect() {
asio::async_connect(
socket_, endpoint_iterator_,
- [this](std::error_code ec, tcp::resolver::iterator) {
+ [this](const std::error_code &ec, tcp::resolver::iterator) {
if (!ec) {
timer_.cancel();
state_ = ConnectorState::CONNECTED;
@@ -295,8 +287,6 @@ void HTTPSession::doConnect() {
asio::ip::tcp::no_delay noDelayOption(true);
socket_.set_option(noDelayOption);
- // on_reconnect_callback_();
-
doReadHeader();
if (data_available_ && !write_msgs_.empty()) {
@@ -306,11 +296,11 @@ void HTTPSession::doConnect() {
if (is_reconnection_) {
is_reconnection_ = false;
- TRANSPORT_LOG_INFO << "Connection recovered!";
+ LoggerInfo() << "Connection recovered!";
}
} else {
- TRANSPORT_LOG_ERROR << "Impossible to reconnect: " << ec.message();
+ LoggerErr() << "Impossible to reconnect: " << ec.message();
close();
}
});
@@ -330,7 +320,7 @@ void HTTPSession::handleDeadline(const std::error_code &ec) {
if (!ec) {
io_service_.post([this]() {
socket_.close();
- TRANSPORT_LOG_ERROR << "Error connecting. Is the server running?";
+ LoggerErr() << "Error connecting. Is the server running?";
io_service_.stop();
});
}
diff --git a/apps/http-proxy/src/icn_receiver.cc b/apps/http-proxy/src/icn_receiver.cc
index ea8ac7191..c8904aa95 100644
--- a/apps/http-proxy/src/icn_receiver.cc
+++ b/apps/http-proxy/src/icn_receiver.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,13 +13,13 @@
* limitations under the License.
*/
+#include <hicn/apps/utils/logger.h>
#include <hicn/http-proxy/http_1x_message_fast_parser.h>
#include <hicn/http-proxy/icn_receiver.h>
#include <hicn/http-proxy/utils.h>
#include <hicn/transport/core/interest.h>
#include <hicn/transport/http/default_values.h>
#include <hicn/transport/utils/hash.h>
-#include <hicn/transport/utils/log.h>
#include <functional>
#include <memory>
@@ -33,18 +33,15 @@ AsyncConsumerProducer::AsyncConsumerProducer(
const std::string& mtu, const std::string& content_lifetime, bool manifest)
: prefix_(core::Prefix(generatePrefix(prefix, first_ipv6_word), 64)),
io_service_(io_service),
- external_io_service_(true),
- producer_socket_(),
ip_address_(origin_address),
port_(origin_port),
- cache_size_(std::stoul(cache_size)),
- mtu_(std::stoul(mtu)),
- request_counter_(0),
+ cache_size_((uint32_t)std::stoul(cache_size)),
+ mtu_((uint32_t)std::stoul(mtu)),
connector_(io_service_, ip_address_, port_,
std::bind(&AsyncConsumerProducer::publishContent, this,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4),
- [this](asio::ip::tcp::socket& socket) -> bool {
+ [this]([[maybe_unused]] const asio::ip::tcp::socket& socket) {
std::queue<interface::PublicationOptions> empty;
std::swap(response_name_queue_, empty);
@@ -55,28 +52,28 @@ AsyncConsumerProducer::AsyncConsumerProducer(
interface::GeneralTransportOptions::OUTPUT_BUFFER_SIZE, cache_size_);
if (ret != SOCKET_OPTION_SET) {
- TRANSPORT_LOG_WARNING << "Warning: output buffer size has not been set.";
+ LoggerWarn() << "Warning: output buffer size has not been set.";
}
ret = producer_socket_.setSocketOption(
- interface::GeneralTransportOptions::MAKE_MANIFEST, manifest);
+ interface::GeneralTransportOptions::MANIFEST_MAX_CAPACITY, manifest);
if (ret != SOCKET_OPTION_SET) {
- TRANSPORT_LOG_WARNING << "Warning: impossible to enable signatures.";
+ LoggerWarn() << "Warning: impossible to enable signatures.";
}
ret = producer_socket_.setSocketOption(
interface::GeneralTransportOptions::DATA_PACKET_SIZE, mtu_);
if (ret != SOCKET_OPTION_SET) {
- TRANSPORT_LOG_WARNING << "Warning: mtu has not been set.";
+ LoggerWarn() << "Warning: mtu has not been set.";
}
producer_socket_.registerPrefix(prefix_);
}
void AsyncConsumerProducer::start() {
- TRANSPORT_LOG_INFO << "Starting listening";
+ LoggerInfo() << "Starting listening";
doReceive();
}
@@ -90,8 +87,8 @@ void AsyncConsumerProducer::run() {
void AsyncConsumerProducer::stop() {
io_service_.post([this]() {
- TRANSPORT_LOG_INFO << "Number of requests processed by plugin: "
- << request_counter_;
+ LoggerInfo() << "Number of requests processed by plugin: "
+ << request_counter_;
producer_socket_.stop();
connector_.close();
});
@@ -100,7 +97,7 @@ void AsyncConsumerProducer::stop() {
void AsyncConsumerProducer::doReceive() {
producer_socket_.setSocketOption(
interface::ProducerCallbacksOptions::CACHE_MISS,
- [this](interface::ProducerSocket& producer,
+ [this]([[maybe_unused]] const interface::ProducerSocket& producer,
interface::Interest& interest) {
if (interest.payloadSize() > 0) {
// Interest may contain http request
@@ -112,6 +109,7 @@ void AsyncConsumerProducer::doReceive() {
});
producer_socket_.connect();
+ producer_socket_.start();
}
void AsyncConsumerProducer::manageIncomingInterest(
@@ -128,9 +126,9 @@ void AsyncConsumerProducer::manageIncomingInterest(
if (seg >= _it->second.first) {
// TRANSPORT_LOGD(
- // "Ignoring interest with name %s for a content object which does not "
- // "exist. (Request: %u, max: %u)",
- // name.toString().c_str(), (uint32_t)seg, (uint32_t)_it->second.first);
+ // "Ignoring interest with name %s for a content object which does not
+ // " "exist. (Request: %u, max: %u)", name.toString().c_str(),
+ // (uint32_t)seg, (uint32_t)_it->second.first);
return;
}
}
@@ -148,7 +146,8 @@ void AsyncConsumerProducer::manageIncomingInterest(
response_name_queue_.emplace(std::move(name),
is_mpd ? 1000 : default_content_lifetime_);
- connector_.send(payload, [packet = std::move(packet)]() {});
+ connector_.send(payload,
+ [packet = std::move(packet)]() { /*nothing to do*/ });
}
void AsyncConsumerProducer::publishContent(const uint8_t* data,
@@ -157,26 +156,25 @@ void AsyncConsumerProducer::publishContent(const uint8_t* data,
uint32_t start_suffix = 0;
if (response_name_queue_.empty()) {
- std::cerr << "Aborting due tue empty request queue" << std::endl;
+ LoggerErr() << "Aborting due tue empty request queue";
abort();
}
- interface::PublicationOptions& options = response_name_queue_.front();
+ const interface::PublicationOptions& options = response_name_queue_.front();
int ret = producer_socket_.setSocketOption(
interface::GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
options.getLifetime());
if (TRANSPORT_EXPECT_FALSE(ret != SOCKET_OPTION_SET)) {
- TRANSPORT_LOG_WARNING << "Warning: content object lifetime has not been set.";
+ LoggerWarn() << "Warning: content object lifetime has not been set.";
}
const interface::Name& name = options.getName();
auto it = chunk_number_map_.find(name);
if (it == chunk_number_map_.end()) {
- std::cerr << "Aborting due to response not found in ResposeInfo map."
- << std::endl;
+ LoggerErr() << "Aborting due to response not found in ResposeInfo map.";
abort();
}
diff --git a/apps/ping/.clang-format b/apps/ping/.clang-format
index cd21e2017..adc73c6fd 100644
--- a/apps/ping/.clang-format
+++ b/apps/ping/.clang-format
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2021 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/apps/ping/CMakeLists.txt b/apps/ping/CMakeLists.txt
index 42f7f98c1..ab3fdf56d 100644
--- a/apps/ping/CMakeLists.txt
+++ b/apps/ping/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -12,28 +12,49 @@
# limitations under the License.
if (NOT DISABLE_EXECUTABLES)
+##############################################################
+# Compiler options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+)
+
+##############################################################
+# Libraries to link
+##############################################################
list (APPEND PING_LIBRARIES
- ${LIBTRANSPORT_LIBRARIES}
- ${CMAKE_THREAD_LIBS_INIT}
- ${WSOCK32_LIBRARY}
- ${WS2_32_LIBRARY}
+ PRIVATE ${LIBHICN_LIBRARIES}
+ PRIVATE ${LIBTRANSPORT_LIBRARIES}
+ PRIVATE ${CMAKE_THREAD_LIBS_INIT}
+ PRIVATE ${WSOCK32_LIBRARY}
+ PRIVATE ${WS2_32_LIBRARY}
)
+##############################################################
+# Build ping server
+##############################################################
build_executable(hicn-ping-server
SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/ping_server.cc
LINK_LIBRARIES ${PING_LIBRARIES}
- INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIRS}
- DEPENDS ${DEPENDENCIES}
+ INCLUDE_DIRS
+ PRIVATE ${THIRD_PARTY_INCLUDE_DIRS} ${COMMON_INCLUDE_DIRS}
+ DEPENDS ${DEPENDENCIES} ${THIRD_PARTY_DEPENDENCIES}
COMPONENT ${HICN_APPS}
LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
+##############################################################
+# Build ping client
+##############################################################
build_executable(hicn-ping-client
SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/ping_client.cc
LINK_LIBRARIES ${PING_LIBRARIES}
- INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIRS}
- DEPENDS ${DEPENDENCIES}
+ INCLUDE_DIRS
+ PRIVATE ${THIRD_PARTY_INCLUDE_DIRS} ${COMMON_INCLUDE_DIRS}
+ DEPENDS ${DEPENDENCIES} ${THIRD_PARTY_DEPENDENCIES}
COMPONENT ${HICN_APPS}
LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
endif () \ No newline at end of file
diff --git a/apps/ping/src/ping_client.cc b/apps/ping/src/ping_client.cc
index 24e0bf3ed..08938734b 100644
--- a/apps/ping/src/ping_client.cc
+++ b/apps/ping/src/ping_client.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,18 +13,22 @@
* limitations under the License.
*/
+#include <hicn/apps/utils/logger.h>
+#include <hicn/transport/auth/signer.h>
#include <hicn/transport/auth/verifier.h>
#include <hicn/transport/core/global_object_pool.h>
#include <hicn/transport/core/interest.h>
+#include <hicn/transport/interfaces/global_conf_interface.h>
#include <hicn/transport/interfaces/portal.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
+#include <hicn/transport/utils/traffic_generator.h>
#include <asio/signal_set.hpp>
#include <asio/steady_timer.hpp>
#include <chrono>
#include <map>
-#define SYN_STATE 1
-#define ACK_STATE 2
+static constexpr uint32_t SYN_STATE = 1;
namespace transport {
@@ -32,147 +36,131 @@ namespace core {
namespace ping {
-typedef std::map<uint64_t, uint64_t> SendTimeMap;
-typedef auth::AsymmetricVerifier Verifier;
+using SendTimeMap = std::map<uint64_t, utils::SteadyTime::TimePoint>;
+using Verifier = auth::AsymmetricVerifier;
class Configuration {
public:
- uint64_t interestLifetime_;
- uint64_t pingInterval_;
- uint64_t maxPing_;
- uint64_t first_suffix_;
- std::string name_;
+ static constexpr char TRAFFIC_GENERATOR_RAND[] = "RANDOM";
+
+ uint32_t num_int_manifest_suffixes_ =
+ 0; // Number of suffixes in interest manifest (suffix in the header
+ // is not included in the count)
+ uint64_t interestLifetime_ = 500; // ms
+ uint64_t pingInterval_ = 1000000; // us
+ uint32_t maxPing_ = 10; // number of interests
+ uint32_t first_suffix_ = 0;
+ std::string name_ = "b001::1";
std::string certificate_;
- uint16_t srcPort_;
- uint16_t dstPort_;
- bool verbose_;
- bool dump_;
- bool jump_;
- bool open_;
- bool always_syn_;
- bool always_ack_;
- bool quiet_;
- uint32_t jump_freq_;
- uint32_t jump_size_;
- uint8_t ttl_;
-
- Configuration() {
- interestLifetime_ = 500; // ms
- pingInterval_ = 1000000; // us
- maxPing_ = 10; // number of interests
- first_suffix_ = 0;
- name_ = "b001::1"; // string
- srcPort_ = 9695;
- dstPort_ = 8080;
- verbose_ = false;
- dump_ = false;
- jump_ = false;
- open_ = false;
- always_syn_ = false;
- always_ack_ = false;
- quiet_ = false;
- jump_freq_ = 0;
- jump_size_ = 0;
- ttl_ = 64;
- }
+ std::string passphrase_;
+ std::string traffic_generator_type_;
+ bool jump_ = false;
+ uint32_t jump_freq_ = 0;
+ uint32_t jump_size_ = 0;
+ hicn_packet_format_t packet_format_ = HICN_PACKET_FORMAT_DEFAULT;
+
+ Configuration() = default;
};
-class Client : interface::Portal::ConsumerCallback {
+class Client : public interface::Portal::TransportCallback {
public:
- Client(Configuration *c)
- : portal_(), signals_(portal_.getIoService(), SIGINT) {
+ explicit Client(Configuration *c)
+ : signals_(io_service_, SIGINT),
+ config_(c),
+ timer_(std::make_unique<asio::steady_timer>(
+ portal_.getThread().getIoService())) {
// Let the main thread to catch SIGINT
- portal_.connect();
- portal_.setConsumerCallback(this);
-
signals_.async_wait(std::bind(&Client::afterSignal, this));
- timer_.reset(new asio::steady_timer(portal_.getIoService()));
- config_ = c;
- sequence_number_ = config_->first_suffix_;
- last_jump_ = 0;
- processed_ = 0;
- state_ = SYN_STATE;
- sent_ = 0;
- received_ = 0;
- timedout_ = 0;
if (!c->certificate_.empty()) {
verifier_.useCertificate(c->certificate_);
}
+
+ // If interst manifest, sign it
+ if (c->num_int_manifest_suffixes_ != 0) {
+ assert(!c->passphrase_.empty());
+ signer_ = std::make_unique<auth::SymmetricSigner>(
+ auth::CryptoSuite::HMAC_SHA256, c->passphrase_);
+ }
+
+ if (c->traffic_generator_type_ ==
+ std::string(Configuration::TRAFFIC_GENERATOR_RAND)) {
+ traffic_generator_ =
+ std::make_unique<RandomTrafficGenerator>(config_->maxPing_);
+ } else {
+ traffic_generator_ = std::make_unique<IncrSuffixTrafficGenerator>(
+ config_->name_, config_->first_suffix_, config_->maxPing_);
+ }
}
- virtual ~Client() {}
+ virtual ~Client() = default;
void ping() {
- std::cout << "start ping" << std::endl;
- doPing();
- portal_.runEventsLoop();
+ LoggerInfo() << "Starting ping...";
+
+ portal_.getThread().add([this]() {
+ portal_.connect();
+ portal_.registerTransportCallback(this);
+ doPing();
+ });
+
+ io_service_.run();
+ }
+
+ void onInterest(Interest &interest) override {
+ LoggerInfo() << "Unexpected interest received.";
}
void onContentObject(Interest &interest, ContentObject &object) override {
uint64_t rtt = 0;
if (!config_->certificate_.empty()) {
- auto t0 = std::chrono::steady_clock::now();
+ auto t0 = utils::SteadyTime::now();
if (verifier_.verifyPacket(&object)) {
- auto t1 = std::chrono::steady_clock::now();
- auto dt =
- std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0);
- std::cout << "Verification time: " << dt.count() << std::endl;
- std::cout << "<<< Signature Ok." << std::endl;
+ auto t1 = utils::SteadyTime::now();
+ auto dt = utils::SteadyTime::getDurationUs(t0, t1);
+ LoggerInfo() << "Verification time: " << dt.count();
+ LoggerInfo() << "<<< Signature Ok.";
} else {
- std::cout << "<<< Signature verification failed!" << std::endl;
+ LoggerErr() << "<<< Signature verification failed!";
}
}
- auto it = send_timestamps_.find(interest.getName().getSuffix());
- if (it != send_timestamps_.end()) {
- rtt = std::chrono::duration_cast<std::chrono::microseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count() -
- it->second;
+ if (auto it = send_timestamps_.find(interest.getName().getSuffix());
+ it != send_timestamps_.end()) {
+ rtt =
+ utils::SteadyTime::getDurationUs(it->second, utils::SteadyTime::now())
+ .count();
send_timestamps_.erase(it);
}
- if (config_->verbose_) {
- std::cout << "<<< recevied object. " << std::endl;
- std::cout << "<<< interest name: " << interest.getName()
- << " src port: " << interest.getSrcPort()
- << " dst port: " << interest.getDstPort()
- << " flags: " << interest.printFlags() << std::endl;
- std::cout << "<<< object name: " << object.getName()
- << " src port: " << object.getSrcPort()
- << " dst port: " << object.getDstPort()
- << " flags: " << object.printFlags() << " path label "
- << object.getPathLabel() << " ("
- << (object.getPathLabel() >> 24) << ")"
- << " TTL: " << (int)object.getTTL() << std::endl;
- } else if (!config_->quiet_) {
- std::cout << "<<< received object. " << std::endl;
- std::cout << "<<< round trip: " << rtt << " [us]" << std::endl;
- std::cout << "<<< interest name: " << interest.getName() << std::endl;
- std::cout << "<<< object name: " << object.getName() << std::endl;
- std::cout << "<<< content object size: "
- << object.payloadSize() + object.headerSize() << " [bytes]"
- << std::endl;
+ if (LoggerIsOn(2)) {
+ LoggerInfo() << "<<< recevied object. ";
+ LoggerInfo() << "<<< interest name: " << interest.getName().getPrefix()
+ << " (n_suffixes=" << config_->num_int_manifest_suffixes_
+ << ")";
+ LoggerInfo() << "<<< object name: " << object.getName() << " path label "
+ << object.getPathLabel() << " ("
+ << (object.getPathLabel() >> 24) << ")";
+ } else if (LoggerIsOn(1)) {
+ LoggerInfo() << "<<< received object. ";
+ LoggerInfo() << "<<< round trip: " << rtt << " [us]";
+ LoggerInfo() << "<<< interest name: " << interest.getName().getPrefix();
+
+ LoggerInfo() << "<<< object name: " << object.getName();
+ LoggerInfo() << "<<< content object size: "
+ << object.payloadSize() + object.headerSize() << " [bytes]";
}
- if (config_->dump_) {
- std::cout << "----- interest dump -----" << std::endl;
+ if (LoggerIsOn(3)) {
+ LoggerInfo() << "----- interest dump -----";
interest.dump();
- std::cout << "-------------------------" << std::endl;
- std::cout << "----- object dump -------" << std::endl;
+ LoggerInfo() << "-------------------------";
+ LoggerInfo() << "----- object dump -------";
object.dump();
- std::cout << "-------------------------" << std::endl;
- }
-
- if (!config_->quiet_) std::cout << std::endl;
-
- if (!config_->always_syn_) {
- if (object.testSyn() && object.testAck() && state_ == SYN_STATE) {
- state_ = ACK_STATE;
- }
+ LoggerInfo() << "-------------------------";
}
+ LoggerVerbose(1) << "\n";
received_++;
processed_++;
@@ -182,178 +170,221 @@ class Client : interface::Portal::ConsumerCallback {
}
void onTimeout(Interest::Ptr &interest, const Name &name) override {
- if (config_->verbose_) {
- std::cout << "### timeout for " << name
- << " src port: " << interest->getSrcPort()
- << " dst port: " << interest->getDstPort()
- << " flags: " << interest->printFlags() << std::endl;
- } else if (!config_->quiet_) {
- std::cout << "### timeout for " << name << std::endl;
+ if (LoggerIsOn(2)) {
+ LoggerInfo() << "### timeout for " << name;
+ } else if (LoggerIsOn(1)) {
+ LoggerInfo() << "### timeout for " << name;
}
- if (config_->dump_) {
- std::cout << "----- interest dump -----" << std::endl;
+ if (LoggerIsOn(3)) {
+ LoggerInfo() << "----- interest dump -----";
interest->dump();
- std::cout << "-------------------------" << std::endl;
+ LoggerInfo() << "-------------------------";
}
-
- if (!config_->quiet_) std::cout << std::endl;
+ LoggerVerbose(1) << "\n";
timedout_++;
processed_++;
- if (processed_ >= config_->maxPing_) {
- afterSignal();
- }
+ if (processed_ >= config_->maxPing_) afterSignal();
}
- void onError(std::error_code ec) override {}
+ void onError(const std::error_code &ec) override {
+ LoggerErr() << "Aborting ping due to internal error: " << ec.message();
+ afterSignal();
+ }
+
+ void checkFamily(hicn_packet_format_t format, int family) {
+ switch (HICN_PACKET_FORMAT_GET(format, 0)) {
+ case IPPROTO_IP:
+ if (family != AF_INET) throw std::runtime_error("Bad packet format");
+ break;
+ case IPPROTO_IPV6:
+ if (family != AF_INET6) throw std::runtime_error("Bad packet format");
+ break;
+ default:
+ throw std::runtime_error("Bad packet format");
+ }
+ }
void doPing() {
- const Name interest_name(config_->name_, (uint32_t)sequence_number_);
- hicn_format_t format;
- if (interest_name.getAddressFamily() == AF_INET) {
- format = HF_INET_TCP;
+ std::string name = traffic_generator_->getPrefix();
+ uint32_t sequence_number = traffic_generator_->getSuffix();
+ const Name interest_name(name, sequence_number);
+
+ hicn_packet_format_t format = config_->packet_format_;
+
+ switch (format) {
+ case HICN_PACKET_FORMAT_NEW:
+ /* Nothing to do */
+ break;
+ case HICN_PACKET_FORMAT_IPV4_TCP:
+ case HICN_PACKET_FORMAT_IPV6_TCP:
+ checkFamily(format, interest_name.getAddressFamily());
+ break;
+ default:
+ throw std::runtime_error("Bad packet format");
+ }
+
+ /*
+ * Eventually add the AH header if a signer is defined. Raise an error
+ * if format include the AH header but no signer is defined.
+ */
+ if (HICN_PACKET_FORMAT_IS_AH(format)) {
+ if (!signer_) throw std::runtime_error("Bad packet format");
} else {
- format = HF_INET6_TCP;
+ if (signer_) format = Packet::toAHFormat(format);
}
- auto interest = std::make_shared<Interest>(interest_name, format);
+ auto interest = core::PacketManager<>::getInstance().getPacket<Interest>(
+ format, signer_ ? signer_->getSignatureFieldSize() : 0);
+ interest->setName(interest_name);
interest->setLifetime(uint32_t(config_->interestLifetime_));
- interest->resetFlags();
- if (config_->open_ || config_->always_syn_) {
- if (state_ == SYN_STATE) {
- interest->setSyn();
- } else if (state_ == ACK_STATE) {
- interest->setAck();
- }
- } else if (config_->always_ack_) {
- interest->setAck();
+ if (LoggerIsOn(2)) {
+ LoggerInfo() << ">>> send interest " << interest->getName()
+ << " suffixes in manifest: "
+ << config_->num_int_manifest_suffixes_;
+ } else if (LoggerIsOn(1)) {
+ LoggerInfo() << ">>> send interest " << interest->getName();
}
+ LoggerVerbose(1) << "\n";
+
+ send_timestamps_[sequence_number] = utils::SteadyTime::now();
+ for (uint32_t i = 0; i < config_->num_int_manifest_suffixes_ &&
+ !traffic_generator_->hasFinished();
+ i++) {
+ uint32_t sequence_number = traffic_generator_->getSuffix();
- interest->setSrcPort(config_->srcPort_);
- interest->setDstPort(config_->dstPort_);
- interest->setTTL(config_->ttl_);
-
- if (config_->verbose_) {
- std::cout << ">>> send interest " << interest->getName()
- << " src port: " << interest->getSrcPort()
- << " dst port: " << interest->getDstPort()
- << " flags: " << interest->printFlags()
- << " TTL: " << (int)interest->getTTL() << std::endl;
- } else if (!config_->quiet_) {
- std::cout << ">>> send interest " << interest->getName() << std::endl;
+ interest->appendSuffix(sequence_number);
+ send_timestamps_[sequence_number] = utils::SteadyTime::now();
}
- if (config_->dump_) {
- std::cout << "----- interest dump -----" << std::endl;
+ if (LoggerIsOn(3)) {
+ LoggerInfo() << "----- interest dump -----";
interest->dump();
- std::cout << "-------------------------" << std::endl;
+ LoggerInfo() << "-------------------------";
}
- if (!config_->quiet_) std::cout << std::endl;
+ interest->encodeSuffixes();
+ if (signer_) signer_->signPacket(interest.get());
+ portal_.sendInterest(interest, interest->getLifetime());
- send_timestamps_[sequence_number_] =
- std::chrono::duration_cast<std::chrono::microseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
-
- portal_.sendInterest(std::move(interest));
-
- sequence_number_++;
- sent_++;
-
- if (sent_ < config_->maxPing_) {
+ if (!traffic_generator_->hasFinished()) {
this->timer_->expires_from_now(
std::chrono::microseconds(config_->pingInterval_));
- this->timer_->async_wait([this](const std::error_code e) { doPing(); });
+ this->timer_->async_wait([this](const std::error_code e) {
+ if (!e) {
+ doPing();
+ }
+ });
}
}
void afterSignal() {
- std::cout << "Stop ping" << std::endl;
- std::cout << "Sent: " << sent_ << " Received: " << received_
- << " Timeouts: " << timedout_ << std::endl;
- portal_.stopEventsLoop();
+ LoggerInfo() << "Stopping ping...";
+ LoggerInfo() << "Sent: " << traffic_generator_->getSentCount()
+ << " Received: " << received_ << " Timeouts: " << timedout_;
+ io_service_.stop();
}
void reset() {
- timer_.reset(new asio::steady_timer(portal_.getIoService()));
- sequence_number_ = config_->first_suffix_;
+ timer_.reset(new asio::steady_timer(portal_.getThread().getIoService()));
+ traffic_generator_->reset();
last_jump_ = 0;
processed_ = 0;
state_ = SYN_STATE;
- sent_ = 0;
received_ = 0;
timedout_ = 0;
}
private:
SendTimeMap send_timestamps_;
+ asio::io_service io_service_;
interface::Portal portal_;
asio::signal_set signals_;
- uint64_t sequence_number_;
- uint64_t last_jump_;
- uint64_t processed_;
- uint32_t state_;
- uint32_t sent_;
- uint32_t received_;
- uint32_t timedout_;
- std::unique_ptr<asio::steady_timer> timer_;
Configuration *config_;
+ std::unique_ptr<asio::steady_timer> timer_;
+ uint64_t last_jump_ = 0;
+ uint64_t processed_ = 0;
+ uint32_t state_ = SYN_STATE;
+ uint32_t received_ = 0;
+ uint32_t timedout_ = 0;
Verifier verifier_;
+ std::unique_ptr<auth::Signer> signer_;
+ std::unique_ptr<TrafficGenerator> traffic_generator_;
};
+static std::unordered_map<std::string, hicn_packet_format_t> const
+ packet_format_map = {{"ipv4_tcp", HICN_PACKET_FORMAT_IPV4_TCP},
+ {"ipv6_tcp", HICN_PACKET_FORMAT_IPV6_TCP},
+ {"new", HICN_PACKET_FORMAT_NEW}};
+
+std::string str_tolower(std::string s) {
+ std::transform(s.begin(), s.end(), s.begin(),
+ [](unsigned char c) { return std::tolower(c); });
+ return s;
+}
+
void help() {
- std::cout << "usage: hicn-consumer-ping [options]" << std::endl;
- std::cout << "PING options" << std::endl;
- std::cout
- << "-i <val> ping interval in microseconds (default 1000000ms)"
- << std::endl;
- std::cout << "-m <val> maximum number of pings to send (default 10)"
- << std::endl;
- std::cout << "-s <val> sorce port (default 9695)" << std::endl;
- std::cout << "-d <val> destination port (default 8080)" << std::endl;
- std::cout << "-t <val> set packet ttl (default 64)" << std::endl;
- std::cout << "-O open tcp connection (three way handshake) "
- "(default false)"
- << std::endl;
- std::cout << "-S send always syn messages (default false)"
- << std::endl;
- std::cout << "-A send always ack messages (default false)"
- << std::endl;
- std::cout << "HICN options" << std::endl;
- std::cout << "-n <val> hicn name (default b001::1)" << std::endl;
- std::cout
- << "-l <val> interest lifetime in milliseconds (default 500ms)"
- << std::endl;
- std::cout << "OUTPUT options" << std::endl;
- std::cout << "-V verbose, prints statistics about the "
- "messagges sent and received (default false)"
- << std::endl;
- std::cout << "-D dump, dumps sent and received packets "
- "(default false)"
- << std::endl;
- std::cout << "-q quiet, not prints (default false)"
- << std::endl;
- std::cout << "-H prints this message" << std::endl;
+ LoggerInfo() << "usage: hicn-consumer-ping [options]";
+ LoggerInfo() << "PING options";
+ LoggerInfo() << "-i <val> ping interval in microseconds (default "
+ "1000000ms)";
+ LoggerInfo()
+ << "-m <val> maximum number of pings to send (default 10)";
+ LoggerInfo() << "-a <val> <pass> set the passphrase and the number of "
+ "suffixes in interest manifest (default 0);";
+ LoggerInfo()
+ << " e.g. '-m 6 -a -2' sends two interest (0 and "
+ "3) with 2 suffixes each (1,2 and 4,5 respectively)";
+ LoggerInfo() << "HICN options";
+ LoggerInfo() << "-n <val> hicn name (default b001::1)";
+ LoggerInfo()
+ << "-l <val> interest lifetime in milliseconds (default "
+ "500ms)";
+ LoggerInfo() << "OUTPUT options";
+ LoggerInfo() << "-V verbose, prints statistics about the "
+ "messagges sent and received (default false)";
+ LoggerInfo() << "-D dump, dumps sent and received packets "
+ "(default false)";
+ LoggerInfo() << "-q quiet, not prints (default false)";
+ LoggerInfo()
+ << "-z <io_module> IO module to use. Default: hicnlight_module";
+ LoggerInfo() << "-F <conf_file> Path to optional configuration file for "
+ "libtransport";
+ LoggerInfo() << "-b <type> Traffic generator type. Use 'RANDOM' for "
+ "random prefixes and suffixes. Default: sequential suffixes.";
+ LoggerInfo()
+ << "-w <packet_format> Packet format (without signature, defaults "
+ "to IPV6_TCP)";
+ LoggerInfo() << "-H prints this message";
}
-int main(int argc, char *argv[]) {
+int start(int argc, char *argv[]) {
#ifdef _WIN32
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
- Configuration *c = new Configuration();
+ transport::interface::global_config::GlobalConfigInterface global_conf;
+
+ auto c = std::make_unique<Configuration>();
int opt;
std::string producer_certificate = "";
- while ((opt = getopt(argc, argv, "j::t:i:m:s:d:n:l:f:c:SAOqVDH")) != -1) {
+ std::string conf_file;
+ transport::interface::global_config::IoModuleConfiguration io_config;
+ io_config.name = "hicnlight_module";
+
+ while ((opt = getopt(argc, argv, "a:b:i:m:f:n:l:c:z:F:w:H")) != -1) {
switch (opt) {
- case 't':
- c->ttl_ = (uint8_t)std::stoi(optarg);
+ case 'a':
+ c->num_int_manifest_suffixes_ = std::stoi(optarg);
+ c->passphrase_ = argv[optind];
+ break;
+ case 'b':
+ c->traffic_generator_type_ = optarg;
break;
case 'i':
c->pingInterval_ = std::stoi(optarg);
@@ -362,13 +393,7 @@ int main(int argc, char *argv[]) {
c->maxPing_ = std::stoi(optarg);
break;
case 'f':
- c->first_suffix_ = std::stoul(optarg);
- break;
- case 's':
- c->srcPort_ = std::stoi(optarg);
- break;
- case 'd':
- c->dstPort_ = std::stoi(optarg);
+ c->first_suffix_ = uint32_t(std::stoul(optarg));
break;
case 'n':
c->name_ = optarg;
@@ -376,53 +401,48 @@ int main(int argc, char *argv[]) {
case 'l':
c->interestLifetime_ = std::stoi(optarg);
break;
- case 'V':
- c->verbose_ = true;
- ;
- break;
- case 'D':
- c->dump_ = true;
- break;
- case 'O':
- c->always_syn_ = false;
- c->always_ack_ = false;
- c->open_ = true;
- break;
- case 'S':
- c->always_syn_ = true;
- c->always_ack_ = false;
- c->open_ = false;
+ case 'c':
+ c->certificate_ = std::string(optarg);
break;
- case 'A':
- c->always_syn_ = false;
- c->always_ack_ = true;
- c->open_ = false;
+ case 'z':
+ io_config.name = optarg;
break;
- case 'q':
- c->quiet_ = true;
- c->verbose_ = false;
- c->dump_ = false;
+ case 'F':
+ conf_file = optarg;
break;
- case 'c':
- c->certificate_ = std::string(optarg);
+ case 'w': {
+ std::string packet_format_s = std::string(optarg);
+ packet_format_s = str_tolower(packet_format_s);
+ auto it = packet_format_map.find(std::string(optarg));
+ if (it == packet_format_map.end())
+ throw std::runtime_error("Bad packet format");
+ c->packet_format_ = it->second;
break;
- case 'H':
+ }
default:
help();
exit(EXIT_FAILURE);
}
}
- auto ping = std::make_unique<Client>(c);
+ /**
+ * IO module configuration
+ */
+ io_config.set();
+
+ /**
+ * Parse config file
+ */
+ global_conf.parseConfigurationFile(conf_file);
+
+ auto ping = std::make_unique<Client>(c.get());
auto t0 = std::chrono::steady_clock::now();
ping->ping();
auto t1 = std::chrono::steady_clock::now();
- std::cout
- << "Elapsed time: "
- << std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count()
- << std::endl;
+ LoggerInfo() << "Elapsed time: "
+ << utils::SteadyTime::getDurationMs(t0, t1).count() << "ms";
#ifdef _WIN32
WSACleanup();
@@ -437,5 +457,5 @@ int main(int argc, char *argv[]) {
} // namespace transport
int main(int argc, char *argv[]) {
- return transport::core::ping::main(argc, argv);
+ return transport::core::ping::start(argc, argv);
}
diff --git a/apps/ping/src/ping_server.cc b/apps/ping/src/ping_server.cc
index baf9c6698..900da18ca 100644
--- a/apps/ping/src/ping_server.cc
+++ b/apps/ping/src/ping_server.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,10 +21,13 @@
#include <openssl/applink.c>
#endif
-#include <hicn/transport/auth/identity.h>
+#include <hicn/apps/utils/logger.h>
#include <hicn/transport/auth/signer.h>
+#include <hicn/transport/auth/verifier.h>
#include <hicn/transport/core/content_object.h>
+#include <hicn/transport/core/global_object_pool.h>
#include <hicn/transport/core/interest.h>
+#include <hicn/transport/interfaces/global_conf_interface.h>
#include <hicn/transport/utils/string_tokenizer.h>
#include <asio.hpp>
@@ -36,170 +39,128 @@ namespace interface {
using HashAlgorithm = core::HashAlgorithm;
using CryptoSuite = auth::CryptoSuite;
-auth::Identity setProducerIdentity(std::string keystore_name,
- std::string keystore_password,
- auth::CryptoHashType hash_algorithm) {
- if (access(keystore_name.c_str(), F_OK) != -1) {
- return auth::Identity(keystore_name, keystore_password, hash_algorithm);
- } else {
- return auth::Identity(keystore_name, keystore_password,
- CryptoSuite::RSA_SHA256, 1024, 365, "producer-test");
- }
-}
-
class CallbackContainer {
- const std::size_t log2_content_object_buffer_size = 12;
-
- public:
- CallbackContainer(const Name &prefix, uint32_t object_size, bool verbose,
- bool dump, bool quite, bool flags, bool reset, uint8_t ttl,
- auth::Identity *identity, bool sign, uint32_t lifetime)
- : buffer_(object_size, 'X'),
- content_objects_((std::uint32_t)(1 << log2_content_object_buffer_size)),
- mask_((std::uint16_t)(1 << log2_content_object_buffer_size) - 1),
- content_objects_index_(0),
- verbose_(verbose),
- dump_(dump),
- quite_(quite),
- flags_(flags),
- reset_(reset),
- ttl_(ttl),
- identity_(identity),
- sign_(sign) {
- core::Packet::Format format;
-
- if (prefix.getAddressFamily() == AF_INET) {
- format = core::Packet::Format::HF_INET_TCP;
- if (sign_) {
- format = core::Packet::Format::HF_INET_TCP_AH;
- }
- } else {
- format = core::Packet::Format::HF_INET6_TCP;
- if (sign_) {
- format = core::Packet::Format::HF_INET6_TCP_AH;
- }
+ private:
+ std::shared_ptr<ContentObject> createContentObject(const Name &name,
+ uint32_t lifetime,
+ const Interest &interest) {
+ auto content_object =
+ core::PacketManager<>::getInstance().getPacket<ContentObject>(
+ interest.getFormat(),
+ (sign_ && signer_) ? signer_->getSignatureFieldSize() : 0);
+
+ content_object->setName(name);
+ content_object->setLifetime(lifetime);
+ content_object->setLocator(interest.getLocator());
+
+ if (LoggerIsOn(2)) {
+ LoggerInfo() << ">>> send object " << content_object->getName();
+ } else if (LoggerIsOn(1)) {
+ LoggerInfo() << ">>> send object " << content_object->getName();
}
- for (int i = 0; i < (1 << log2_content_object_buffer_size); i++) {
- content_objects_[i] = std::make_shared<ContentObject>(
- prefix, format, 0, (const uint8_t *)buffer_.data(), buffer_.size());
- content_objects_[i]->setLifetime(lifetime);
+ if (LoggerIsOn(3)) {
+ LoggerInfo() << "----- object dump -----";
+ content_object->dump();
+ LoggerInfo() << "-----------------------";
}
+
+ if (sign_ && signer_) signer_->signPacket(content_object.get());
+ return content_object;
}
- void processInterest(ProducerSocket &p, const Interest &interest,
+ public:
+ CallbackContainer([[maybe_unused]] const Name &prefix, uint32_t object_size,
+ auth::Signer *signer, bool sign, std::string passphrase,
+ [[maybe_unused]] uint32_t lifetime)
+ : buffer_(object_size, 'X'), signer_(signer), sign_(sign) {
+ // Verifier for interest manifests
+ if (!passphrase.empty())
+ verifier_ = std::make_unique<auth::SymmetricVerifier>(passphrase);
+ }
+
+ void processInterest(ProducerSocket &p, Interest &interest,
uint32_t lifetime) {
- if (verbose_) {
- std::cout << "<<< received interest " << interest.getName()
- << " src port: " << interest.getSrcPort()
- << " dst port: " << interest.getDstPort()
- << " flags: " << interest.printFlags()
- << "TTL: " << (int)interest.getTTL() << std::endl;
- } else if (!quite_) {
- std::cout << "<<< received interest " << interest.getName() << std::endl;
+ if (verifier_ && interest.hasManifest()) {
+ auto t0 = utils::SteadyTime::now();
+ if (verifier_->verifyPacket(&interest)) {
+ auto t1 = utils::SteadyTime::now();
+ auto dt = utils::SteadyTime::getDurationUs(t0, t1);
+ LoggerInfo() << "Verification time: " << dt.count();
+ LoggerInfo() << "<<< Signature Ok.";
+ } else {
+ LoggerErr() << "<<< Signature verification failed!";
+ }
}
- if (dump_) {
- std::cout << "----- interest dump -----" << std::endl;
- interest.dump();
- std::cout << "-------------------------" << std::endl;
+ if (LoggerIsOn(2)) {
+ LoggerInfo() << "<<< received interest " << interest.getName()
+ << " suffixes in manifest: " << interest.numberOfSuffixes();
+ } else if (LoggerIsOn(1)) {
+ LoggerInfo() << "<<< received interest " << interest.getName();
}
- if (interest.testRst()) {
- std::cout << "!!!got a reset, I don't reply" << std::endl;
- } else {
- auto &content_object = content_objects_[content_objects_index_++ & mask_];
-
- content_object->setName(interest.getName());
- content_object->setLifetime(lifetime);
- content_object->setLocator(interest.getLocator());
- content_object->setSrcPort(interest.getDstPort());
- content_object->setDstPort(interest.getSrcPort());
- content_object->setTTL(ttl_);
-
- if (!sign_) {
- content_object->resetFlags();
- }
-
- if (flags_) {
- if (interest.testSyn()) {
- content_object->setSyn();
- content_object->setAck();
- } else if (interest.testAck()) {
- content_object->setAck();
- } // here I may need to handle the FIN flag;
- } else if (reset_) {
- content_object->setRst();
- }
+ if (LoggerIsOn(3)) {
+ LoggerInfo() << "----- interest dump -----";
+ interest.dump();
+ LoggerInfo() << "-------------------------";
+ }
- if (verbose_) {
- std::cout << ">>> send object " << content_object->getName()
- << " src port: " << content_object->getSrcPort()
- << " dst port: " << content_object->getDstPort()
- << " flags: " << content_object->printFlags()
- << " TTL: " << (int)content_object->getTTL() << std::endl;
- } else if (!quite_) {
- std::cout << ">>> send object " << content_object->getName()
- << std::endl;
- }
+ if (!interest.isValid()) throw std::runtime_error("Bad interest format");
+ Name name = interest.getName();
- if (dump_) {
- std::cout << "----- object dump -----" << std::endl;
- content_object->dump();
- std::cout << "-----------------------" << std::endl;
- }
+ if (!interest.hasManifest()) { // Single interest
+ auto content_object = createContentObject(name, lifetime, interest);
+ p.produce(*content_object);
+ } else { // Interest manifest
+ uint32_t _;
+ const uint32_t *suffix = NULL;
+ UNUSED(_);
- if (!quite_) std::cout << std::endl;
+ interest_manifest_foreach_suffix(interest.getIntManifestHeader(), suffix,
+ _) {
+ name.setSuffix(*suffix);
- if (sign_) {
- identity_->getSigner()->signPacket(content_object.get());
+ auto content_object = createContentObject(name, lifetime, interest);
+ p.produce(*content_object);
}
-
- p.produce(*content_object);
}
+
+ LoggerVerbose(1) << "\n";
}
private:
std::string buffer_;
- std::vector<std::shared_ptr<ContentObject>> content_objects_;
- std::uint16_t mask_;
- std::uint16_t content_objects_index_;
- bool verbose_;
- bool dump_;
- bool quite_;
- bool flags_;
- bool reset_;
- uint8_t ttl_;
- auth::Identity *identity_;
+ auth::Signer *signer_;
bool sign_;
+ std::unique_ptr<auth::Verifier> verifier_;
};
void help() {
- std::cout << "usage: hicn-preoducer-ping [options]" << std::endl;
- std::cout << "PING options" << std::endl;
- std::cout << "-s <val> object content size (default 1350B)" << std::endl;
- std::cout << "-n <val> hicn name (default b001::/64)" << std::endl;
- std::cout << "-f set tcp flags according to the flag received "
- "(default false)"
- << std::endl;
- std::cout << "-l data lifetime" << std::endl;
- std::cout << "-r always reply with a reset flag (default false)"
- << std::endl;
- std::cout << "-t set ttl (default 64)" << std::endl;
- std::cout << "OUTPUT options" << std::endl;
- std::cout << "-V verbose, prints statistics about the messagges sent "
- "and received (default false)"
- << std::endl;
- std::cout << "-D dump, dumps sent and received packets (default false)"
- << std::endl;
- std::cout << "-q quite, not prints (default false)" << std::endl;
+ LoggerInfo() << "usage: hicn-preoducer-ping [options]";
+ LoggerInfo() << "PING options";
+ LoggerInfo() << "-s <val> object content size (default 1350B)";
+ LoggerInfo() << "-n <val> hicn name (default b001::/64)";
+ LoggerInfo() << "-l data lifetime";
+ LoggerInfo() << "OUTPUT options";
+ LoggerInfo() << "-V verbose, prints statistics about the "
+ "messagges sent "
+ " and received (default false)";
+ LoggerInfo() << "-D dump, dumps sent and received packets "
+ "(default false)";
+ LoggerInfo() << "-q quiet, not prints (default false)";
+ LoggerInfo()
+ << "-z <io_module> IO module to use. Default: hicnlight_module";
+ LoggerInfo() << "-F <conf_file> Path to optional configuration file for "
+ "libtransport";
#ifndef _WIN32
- std::cout << "-d daemon mode" << std::endl;
+ LoggerInfo() << "-d daemon mode";
#endif
- std::cout << "-H prints this message" << std::endl;
+ LoggerInfo() << "-H prints this message";
}
-int main(int argc, char **argv) {
+int ping_main(int argc, char **argv) {
+ transport::interface::global_config::GlobalConfigInterface global_conf;
#ifdef _WIN32
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
@@ -208,59 +169,41 @@ int main(int argc, char **argv) {
#endif
std::string name_prefix = "b001::0/64";
std::string delimiter = "/";
- bool verbose = false;
- bool dump = false;
- bool quite = false;
- bool flags = false;
- bool reset = false;
uint32_t object_size = 1250;
- uint8_t ttl = 64;
std::string keystore_path = "./rsa_crypto_material.p12";
std::string keystore_password = "cisco";
+ std::string passphrase = "";
bool sign = false;
uint32_t data_lifetime = default_values::content_object_expiry_time;
+ std::string conf_file;
+ transport::interface::global_config::IoModuleConfiguration io_config;
+ io_config.name = "hicnlight_module";
+
int opt;
#ifndef _WIN32
- while ((opt = getopt(argc, argv, "s:n:t:l:qfrVDdHk:p:")) != -1) {
+ while ((opt = getopt(argc, argv, "a:s:n:t:l:frdHk:p:z:F:")) != -1) {
#else
- while ((opt = getopt(argc, argv, "s:n:t:l:qfrVDHk:p:")) != -1) {
+ while ((opt = getopt(argc, argv, "s:n:t:l:frHk:p:z:F:")) != -1) {
#endif
switch (opt) {
+ case 'a':
+ passphrase = optarg;
+ break;
case 's':
object_size = std::stoi(optarg);
break;
case 'n':
name_prefix = optarg;
break;
- case 't':
- ttl = (uint8_t)std::stoi(optarg);
- break;
case 'l':
data_lifetime = std::stoi(optarg);
break;
- case 'V':
- verbose = true;
- break;
- case 'D':
- dump = true;
- break;
- case 'q':
- verbose = false;
- dump = false;
- quite = true;
- break;
#ifndef _WIN32
case 'd':
daemon = true;
break;
#endif
- case 'f':
- flags = true;
- break;
- case 'r':
- reset = true;
- break;
case 'k':
keystore_path = optarg;
sign = true;
@@ -268,7 +211,12 @@ int main(int argc, char **argv) {
case 'p':
keystore_password = optarg;
break;
- case 'H':
+ case 'z':
+ io_config.name = optarg;
+ break;
+ case 'F':
+ conf_file = optarg;
+ break;
default:
help();
exit(EXIT_FAILURE);
@@ -281,6 +229,16 @@ int main(int argc, char **argv) {
}
#endif
+ /**
+ * IO module configuration
+ */
+ io_config.set();
+
+ /**
+ * Parse config file
+ */
+ global_conf.parseConfigurationFile(conf_file);
+
core::Prefix producer_namespace(name_prefix);
utils::StringTokenizer tokenizer(name_prefix, delimiter);
@@ -290,21 +248,23 @@ int main(int argc, char **argv) {
if (object_size > 1350) object_size = 1350;
CallbackContainer *stubs;
- auth::Identity identity = setProducerIdentity(
- keystore_path, keystore_password, auth::CryptoHashType::SHA256);
+ std::unique_ptr<auth::Signer> signer;
if (sign) {
- stubs = new CallbackContainer(n, object_size, verbose, dump, quite, flags,
- reset, ttl, &identity, sign, data_lifetime);
+ signer = std::make_unique<auth::AsymmetricSigner>(keystore_path,
+ keystore_password);
+ stubs = new CallbackContainer(n, object_size, signer.get(), sign,
+ passphrase, data_lifetime);
} else {
- auth::Identity *identity = nullptr;
- stubs = new CallbackContainer(n, object_size, verbose, dump, quite, flags,
- reset, ttl, identity, sign, data_lifetime);
+ auth::Signer *signer = nullptr;
+ stubs = new CallbackContainer(n, object_size, signer, sign, passphrase,
+ data_lifetime);
}
ProducerSocket p;
p.registerPrefix(producer_namespace);
+ p.setSocketOption(GeneralTransportOptions::MANIFEST_MAX_CAPACITY, 0U);
p.setSocketOption(GeneralTransportOptions::OUTPUT_BUFFER_SIZE, 0U);
p.setSocketOption(
ProducerCallbacksOptions::CACHE_MISS,
@@ -313,12 +273,13 @@ int main(int argc, char **argv) {
std::placeholders::_2, data_lifetime));
p.connect();
+ p.start();
asio::io_service io_service;
asio::signal_set signal_set(io_service, SIGINT);
signal_set.async_wait(
[&p, &io_service](const std::error_code &, const int &) {
- std::cout << "STOPPING!!" << std::endl;
+ LoggerInfo() << "STOPPING!!";
p.stop();
io_service.stop();
});
@@ -336,5 +297,5 @@ int main(int argc, char **argv) {
} // end namespace transport
int main(int argc, char **argv) {
- return transport::interface::main(argc, argv);
+ return transport::interface::ping_main(argc, argv);
}
diff --git a/cmake b/cmake
new file mode 160000
+Subproject a7b8a8e60fb4b4d35df628003f1d80438736603
diff --git a/cmake/Modules/BuildMacros.cmake b/cmake/Modules/BuildMacros.cmake
deleted file mode 100644
index 15e2ff1a8..000000000
--- a/cmake/Modules/BuildMacros.cmake
+++ /dev/null
@@ -1,300 +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.
-
-##############################
-# Utils for building libraries and executables
-#
-
-include(GNUInstallDirs)
-
-macro(remove_flag_from_target target flag)
- get_target_property(target_cxx_flags ${target} COMPILE_OPTIONS)
- if(target_cxx_flags)
- list(REMOVE_ITEM target_cxx_flags ${flag})
- set_target_properties(${target} PROPERTIES COMPILE_OPTIONS "${target_cxx_flags}")
- endif()
-endmacro()
-
-macro(build_executable exec)
- cmake_parse_arguments(ARG
- "NO_INSTALL"
- "COMPONENT"
- "SOURCES;LINK_LIBRARIES;DEPENDS;INCLUDE_DIRS;DEFINITIONS;COMPILE_OPTIONS;LINK_FLAGS"
- ${ARGN}
- )
-
- add_executable(${exec}-bin ${ARG_SOURCES})
-
- set(BUILD_ROOT ${CMAKE_BINARY_DIR}/build-root)
-
- set_target_properties(${exec}-bin
- PROPERTIES
- OUTPUT_NAME ${exec}
- INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}"
- BUILD_RPATH "${BUILD_ROOT}/lib"
- INSTALL_RPATH_USE_LINK_PATH TRUE
- ARCHIVE_OUTPUT_DIRECTORY "${BUILD_ROOT}/lib"
- LIBRARY_OUTPUT_DIRECTORY "${BUILD_ROOT}/lib"
- RUNTIME_OUTPUT_DIRECTORY "${BUILD_ROOT}/bin"
- LINK_FLAGS "${ARG_LINK_FLAGS}"
- )
-
- if(ARG_LINK_LIBRARIES)
- target_link_libraries(${exec}-bin ${ARG_LINK_LIBRARIES})
- endif()
-
- if(ARG_DEPENDS)
- add_dependencies(${exec}-bin ${ARG_DEPENDS})
- endif()
-
- if (ARG_COMPILE_OPTIONS)
- target_compile_options(${exec}-bin PRIVATE -Wall -Werror ${ARG_COMPILE_OPTIONS})
- endif()
-
- if(ARG_DEFINITIONS)
- target_compile_definitions(${exec}-bin PRIVATE ${ARG_DEFINITIONS})
- endif()
-
- if(ARG_INCLUDE_DIRS)
- target_include_directories(${exec}-bin BEFORE PUBLIC
- ${ARG_INCLUDE_DIRS}
- ${PROJECT_BINARY_DIR}
- )
- endif()
-
- if(NOT ARG_NO_INSTALL)
- install(
- TARGETS ${exec}-bin
- RUNTIME
- DESTINATION ${CMAKE_INSTALL_BINDIR}
- COMPONENT ${ARG_COMPONENT}
- )
- endif()
-endmacro()
-
-macro(build_library lib)
- cmake_parse_arguments(ARG
- "SHARED;STATIC;NO_DEV"
- "COMPONENT;"
- "SOURCES;LINK_LIBRARIES;OBJECT_LIBRARIES;LINK_FLAGS;INSTALL_HEADERS;DEPENDS;INCLUDE_DIRS;DEFINITIONS;HEADER_ROOT_DIR;LIBRARY_ROOT_DIR;INSTALL_FULL_PATH_DIR;EMPTY_PREFIX;COMPILE_OPTIONS;VERSION"
- ${ARGN}
- )
-
- message(STATUS "Building library ${lib}")
-
- # Clear target_libs
- unset(TARGET_LIBS)
-
- if (ARG_SHARED)
- list(APPEND TARGET_LIBS
- ${lib}.shared
- )
- add_library(${lib}.shared SHARED ${ARG_SOURCES} ${ARG_OBJECT_LIBRARIES})
- endif()
-
- if(ARG_STATIC)
- list(APPEND TARGET_LIBS
- ${lib}.static
- )
- add_library(${lib}.static STATIC ${ARG_SOURCES} ${ARG_OBJECT_LIBRARIES})
- endif()
-
- if(NOT ARG_COMPONENT)
- set(ARG_COMPONENT hicn)
- endif()
-
- set(BUILD_ROOT ${CMAKE_BINARY_DIR}/build-root)
-
- foreach(library ${TARGET_LIBS})
-
- if(HICN_VERSION)
- set_target_properties(${library}
- PROPERTIES
- SOVERSION ${HICN_VERSION}
- )
- endif()
-
- if (${ARG_EMPTY_PREFIX})
- set_target_properties(${library}
- PROPERTIES
- INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}"
- BUILD_RPATH "${BUILD_ROOT}/lib"
- INSTALL_RPATH_USE_LINK_PATH TRUE
- PREFIX ""
- ARCHIVE_OUTPUT_DIRECTORY "${BUILD_ROOT}/lib"
- LIBRARY_OUTPUT_DIRECTORY "${BUILD_ROOT}/lib"
- RUNTIME_OUTPUT_DIRECTORY "${BUILD_ROOT}/bin"
- LINK_FLAGS "${ARG_LINK_FLAGS}"
- )
- else ()
- set_target_properties(${library}
- PROPERTIES
- INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}"
- BUILD_RPATH "${BUILD_ROOT}/lib"
- INSTALL_RPATH_USE_LINK_PATH TRUE
- ARCHIVE_OUTPUT_DIRECTORY "${BUILD_ROOT}/lib"
- LIBRARY_OUTPUT_DIRECTORY "${BUILD_ROOT}/lib"
- RUNTIME_OUTPUT_DIRECTORY "${BUILD_ROOT}/bin"
- LINK_FLAGS "${ARG_LINK_FLAGS}"
- )
- endif()
-
- if (WIN32)
- target_compile_options(${library} PRIVATE ${ARG_COMPILE_OPTIONS})
- set_target_properties(${library}
- PROPERTIES
- WINDOWS_EXPORT_ALL_SYMBOLS TRUE
- )
- else ()
- target_compile_options(${library}
- PRIVATE -Wall -Werror ${ARG_COMPILE_OPTIONS}
- )
- set_target_properties(${library}
- PROPERTIES
- OUTPUT_NAME ${lib}
- )
- endif ()
-
- # library deps
- if(ARG_LINK_LIBRARIES)
- target_link_libraries(${library} PUBLIC ${ARG_LINK_LIBRARIES})
- endif()
-
- if(ARG_DEFINITIONS)
- target_compile_definitions(${library} PRIVATE ${ARG_DEFINITIONS})
- endif()
-
- if(ARG_INCLUDE_DIRS)
- target_include_directories(${library} BEFORE PUBLIC
- ${ARG_INCLUDE_DIRS}
- ${PROJECT_BINARY_DIR}
- )
- endif()
-
- if(ARG_VERSION)
- set_target_properties(${library}
- PROPERTIES
- VERSION ${ARG_VERSION}
- )
- endif()
-
- set(INSTALL_LIB_PATH "${CMAKE_INSTALL_LIBDIR}/${ARG_LIBRARY_ROOT_DIR}")
-
- if (ARG_INSTALL_FULL_PATH_DIR)
- set(INSTALL_LIB_PATH ${ARG_INSTALL_FULL_PATH_DIR})
- endif()
-
- install(
- TARGETS ${library}
- COMPONENT ${ARG_COMPONENT}
- RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- LIBRARY DESTINATION ${INSTALL_LIB_PATH}
- )
-
- if(ARG_DEPENDS)
- add_dependencies(${library} ${ARG_DEPENDS})
- endif()
- endforeach()
-
- # install headers
- if(ARG_INSTALL_HEADERS)
- if (NOT ARG_HEADER_ROOT_DIR)
- set(ARG_HEADER_ROOT_DIR "hicn")
- endif()
-
- list(APPEND local_comps
- ${ARG_COMPONENT}-dev
- )
-
- foreach(file ${ARG_INSTALL_HEADERS})
- get_filename_component(_dir ${file} DIRECTORY)
-
- if (_dir)
- get_filename_component(dir ${_dir} NAME)
- if ("${dir}" STREQUAL src)
- set(dir "")
- endif()
- if ("${dir}" STREQUAL includes)
- set(dir "")
- endif()
- if ("${dir}" STREQUAL ${ARG_HEADER_ROOT_DIR})
- set(dir "")
- endif()
- else()
- set(dir "")
- endif()
-
- set(COMPONENT ${ARG_COMPONENT})
- if (NOT ARG_NO_DEV)
- set(COMPONENT ${COMPONENT}-dev)
- endif()
- install(
- FILES ${file}
- DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${ARG_HEADER_ROOT_DIR}/${dir}
- COMPONENT ${COMPONENT}
- )
- endforeach()
- endif()
-endmacro()
-
-macro (build_module module)
- cmake_parse_arguments(ARG
- "SHARED;STATIC;NO_DEV"
- "COMPONENT;"
- "SOURCES;LINK_LIBRARIES;INSTALL_HEADERS;DEPENDS;INCLUDE_DIRS;DEFINITIONS;HEADER_ROOT_DIR;LIBRARY_ROOT_DIR;INSTALL_FULL_PATH_DIR;EMPTY_PREFIX;COMPILE_OPTIONS;VERSION"
- ${ARGN}
- )
-
- message(STATUS "Building module ${module}")
-
- build_library(${module}
- SHARED
- SOURCES ${ARG_SOURCES}
- LINK_LIBRARIES ${ARG_LINK_LIBRARIES}
- INSTALL_HEADERS ${ARG_INSTALL_HEADERS}
- DEPENDS ${ARG_DEPENDS}
- COMPONENT ${ARG_COMPONENT}
- INCLUDE_DIRS ${ARG_INCLUDE_DIRS}
- HEADER_ROOT_DIR ${ARG_HEADER_ROOT_DIR}
- LIBRARY_ROOT_DIR ${ARG_LIBRARY_ROOT_DIR}
- INSTALL_FULL_PATH_DIR ${ARG_INSTALL_FULL_PATH_DIR}
- DEFINITIONS ${ARG_DEFINITIONS}
- EMPTY_PREFIX ${ARG_EMPTY_PREFIX}
- COMPILE_OPTIONS ${ARG_COMPILE_OPTIONS}
- VERSION ${ARG_VERSION}
- )
-
- if (${CMAKE_SYSTEM_NAME} MATCHES Darwin)
- set(LINK_FLAGS "-Wl,-undefined,dynamic_lookup")
- elseif(${CMAKE_SYSTEM_NAME} MATCHES iOS)
- set(LINK_FLAGS "-Wl,-undefined,dynamic_lookup")
- elseif(${CMAKE_SYSTEM_NAME} MATCHES Linux)
- set(LINK_FLAGS "-Wl,-unresolved-symbols=ignore-all")
- elseif(${CMAKE_SYSTEM_NAME} MATCHES Windows)
- set(LINK_FLAGS "/wd4275")
- else()
- message(FATAL_ERROR "Trying to build module on a not supportd platform. Aborting.")
- endif()
-
- set_target_properties(${module}.shared
- PROPERTIES
- LINKER_LANGUAGE C
- PREFIX ""
- LINK_FLAGS ${LINK_FLAGS}
- )
-
-endmacro(build_module)
-
-include(IosMacros)
-include(WindowsMacros)
diff --git a/cmake/Modules/FindAsio.cmake b/cmake/Modules/FindAsio.cmake
deleted file mode 100644
index 73888e519..000000000
--- a/cmake/Modules/FindAsio.cmake
+++ /dev/null
@@ -1,41 +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.
-
-########################################
-#
-# Find the hcin libraries and includes
-# This module sets:
-# ASIO_FOUND: True if asio was found
-# ASIO_INCLUDE_DIR: The asio include dir
-#
-
-set(ASIO_SEARCH_PATH_LIST
- ${ASIO_HOME}
- $ENV{ASIO_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(ASIO_INCLUDE_DIR asio.hpp
- HINTS ${ASIO_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the asio includes"
-)
-
-set(ASIO_INCLUDE_DIRS ${ASIO_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Asio
- REQUIRED_VARS ASIO_INCLUDE_DIRS
-) \ No newline at end of file
diff --git a/cmake/Modules/FindCURL.cmake b/cmake/Modules/FindCURL.cmake
deleted file mode 100644
index 239b0e505..000000000
--- a/cmake/Modules/FindCURL.cmake
+++ /dev/null
@@ -1,69 +0,0 @@
-#.rst:
-# FindCURL
-# --------
-#
-# Find curl
-#
-# Find the native CURL headers and libraries.
-#
-# ::
-#
-# CURL_INCLUDE_DIRS - where to find curl_/curl_.h, etc.
-# CURL_LIBRARIES - List of libraries when using curl.
-# CURL_FOUND - True if curl found.
-# CURL_VERSION_STRING - the version of curl found (since CMake 2.8.8)
-
-#=============================================================================
-# Copyright 2006-2009 Kitware, Inc.
-# Copyright 2012 Rolf Eike Beer <eike@sf-mail.de>
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-# License text for the above reference.)
-
-# Look for the header file.
-find_path(CURL_INCLUDE_DIR NAMES curl/curl.h)
-mark_as_advanced(CURL_INCLUDE_DIR)
-
-# Look for the library (sorted from most current/relevant entry to least).
-find_library(CURL_LIBRARY NAMES
- curl
- # Windows MSVC prebuilts:
- curllib
- libcurl_imp
- curllib_static
- # Windows older "Win32 - MSVC" prebuilts (libcurl.lib, e.g. libcurl-7.15.5-win32-msvc.zip):
- libcurl
- )
-mark_as_advanced(CURL_LIBRARY)
-
-if(CURL_INCLUDE_DIR)
- foreach(_curl_version_header curlver.h curl.h)
- if(EXISTS "${CURL_INCLUDE_DIR}/curl/${_curl_version_header}")
- file(STRINGS "${CURL_INCLUDE_DIR}/curl/${_curl_version_header}" curl_version_str REGEX "^#define[\t ]+LIBCURL_VERSION[\t ]+\".*\"")
-
- string(REGEX REPLACE "^#define[\t ]+LIBCURL_VERSION[\t ]+\"([^\"]*)\".*" "\\1" CURL_VERSION_STRING "${curl_version_str}")
- unset(curl_version_str)
- break()
- endif()
- endforeach()
-endif()
-
-# handle the QUIETLY and REQUIRED arguments and set CURL_FOUND to TRUE if
-# all listed variables are TRUE
-include(FindPackageHandleStandardArgs)
-
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(CURL
- REQUIRED_VARS CURL_LIBRARY CURL_INCLUDE_DIR
- VERSION_VAR CURL_VERSION_STRING)
-
-if(CURL_FOUND)
- set(CURL_LIBRARIES ${CURL_LIBRARY})
- set(CURL_INCLUDE_DIRS ${CURL_INCLUDE_DIR})
-endif()
diff --git a/cmake/Modules/FindCollectd.cmake b/cmake/Modules/FindCollectd.cmake
deleted file mode 100644
index 244fd14e5..000000000
--- a/cmake/Modules/FindCollectd.cmake
+++ /dev/null
@@ -1,41 +0,0 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-set(COLLECTD_SEARCH_PATH_LIST
- ${COLLECTD_HOME}
- $ENV{COLLECTD_HOME}
- /usr/local
- /opt
- /usr
- )
-
-find_path(COLLECTD_INCLUDE_DIR collectd.h
- HINTS ${COLLECTD_SEARCH_PATH_LIST}
- PATH_SUFFIXES include/collectd/core/daemon/ daemon/
- DOC "Find the collectd includes"
-)
-
-find_path(COLLECTD_CONFIG_INCLUDE_DIR config.h
- HINTS ${COLLECTD_SEARCH_PATH_LIST}
- PATH_SUFFIXES include/collectd/core/
- DOC "Find the collectd includes"
-)
-
-message(STATUS ${COLLECTD_INCLUDE_DIR} ${COLLECTD_CONFIG_INCLUDE_DIR})
-
-set(COLLECTD_INCLUDE_DIRS ${COLLECTD_INCLUDE_DIR} ${COLLECTD_CONFIG_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Collectd DEFAULT_MSG COLLECTD_INCLUDE_DIRS)
-
-mark_as_advanced(COLLECTD_INCLUDE_DIRS)
diff --git a/cmake/Modules/FindGFlags.cmake b/cmake/Modules/FindGFlags.cmake
deleted file mode 100644
index 804bfebdc..000000000
--- a/cmake/Modules/FindGFlags.cmake
+++ /dev/null
@@ -1,36 +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.
-
-#
-# Find libgflags
-#
-# LIBGFLAGS_INCLUDE_DIR - where to find gflags/gflags.h, etc.
-# LIBGFLAGS_LIBRARY - List of libraries when using libgflags.
-# LIBGFLAGS_FOUND - True if libgflags found.
-
-
-IF (LIBGFLAGS_INCLUDE_DIR)
- # Already in cache, be silent
- SET(LIBGFLAGS_FIND_QUIETLY TRUE)
-ENDIF ()
-
-FIND_PATH(LIBGFLAGS_INCLUDE_DIR gflags/gflags.h)
-
-FIND_LIBRARY(LIBGFLAGS_LIBRARY NAMES gflags gflags_static)
-
-# handle the QUIETLY and REQUIRED arguments and set LIBGFLAGS_FOUND to TRUE if
-# all listed variables are TRUE
-INCLUDE(FindPackageHandleStandardArgs)
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBGFLAGS DEFAULT_MSG LIBGFLAGS_LIBRARY LIBGFLAGS_INCLUDE_DIR)
-
-MARK_AS_ADVANCED(LIBGFLAGS_LIBRARY LIBGFLAGS_INCLUDE_DIR) \ No newline at end of file
diff --git a/cmake/Modules/FindGlog.cmake b/cmake/Modules/FindGlog.cmake
deleted file mode 100644
index 10023a187..000000000
--- a/cmake/Modules/FindGlog.cmake
+++ /dev/null
@@ -1,36 +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.
-
-#
-# Find libglog
-#
-# LIBGLOG_INCLUDE_DIR - where to find glog/logging.h, etc.
-# LIBGLOG_LIBRARY - List of libraries when using libglog.
-# LIBGLOG_FOUND - True if libglog found.
-
-
-IF (LIBGLOG_INCLUDE_DIR)
- # Already in cache, be silent
- SET(LIBGLOG_FIND_QUIETLY TRUE)
-ENDIF ()
-
-FIND_PATH(LIBGLOG_INCLUDE_DIR glog/logging.h)
-
-FIND_LIBRARY(LIBGLOG_LIBRARY glog)
-
-# handle the QUIETLY and REQUIRED arguments and set LIBGLOG_FOUND to TRUE if
-# all listed variables are TRUE
-INCLUDE(FindPackageHandleStandardArgs)
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBGLOG DEFAULT_MSG LIBGLOG_LIBRARY LIBGLOG_INCLUDE_DIR)
-
-MARK_AS_ADVANCED(LIBGLOG_LIBRARY LIBGLOG_INCLUDE_DIR) \ No newline at end of file
diff --git a/cmake/Modules/FindHicnLight.cmake b/cmake/Modules/FindHicnLight.cmake
deleted file mode 100644
index 6894415e7..000000000
--- a/cmake/Modules/FindHicnLight.cmake
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright (c) 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.
-
-set(HICNLIGHT_SEARCH_PATH_LIST
- ${HICNLIGHT_HOME}
- $ENV{HICNLIGHT_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(HICNLIGHT_INCLUDE_DIR hicn/ctrl/api.h
- HINTS ${HICNLIGHT_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the hicn plugin includes"
-)
-
-find_library(HICNLIGHT_LIBRARY NAMES libhicnctrl.so
- HINTS ${HICNLIGHT_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x86_64-linux-gnu/
- DOC "Find the hicn light lib"
-)
-
-set(HICNLIGHT_LIBRARIES ${HICNLIGHT_LIBRARY})
-set(HICNLIGHT_INCLUDE_DIRS ${HICNLIGHT_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Hicnlight HICNLIGHT_LIBRARIES HICNLIGHT_INCLUDE_DIRS)
-
-mark_as_advanced(HICNLIGHT_LIBRARY HICNLIGHT_INCLUDE_DIR)
diff --git a/cmake/Modules/FindHicnPlugin.cmake b/cmake/Modules/FindHicnPlugin.cmake
deleted file mode 100644
index 07e5f9a8c..000000000
--- a/cmake/Modules/FindHicnPlugin.cmake
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (c) 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.
-
-set(HICNPLUGIN_SEARCH_PATH_LIST
- ${VPP_SEARCH_PATH_LIST}
- ${HICNPLUGIN_HOME}
- $ENV{HICNPLUGIN_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(HICNPLUGIN_INCLUDE_DIR vapi/hicn.api.vapi.h
- HINTS ${HICNPLUGIN_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the hicn plugin includes"
-)
-
-
-set(HICNPLUGIN_INCLUDE_DIRS ${HICNPLUGIN_INCLUDE_DIR} ${HICNPLUGIN_INCLUDE_DIR}/vpp_plugins)
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(HicnPlugin DEFAULT_MSG HICNPLUGIN_INCLUDE_DIR)
-
-mark_as_advanced(HICNPLUGIN_INCLUDE_DIR) \ No newline at end of file
diff --git a/cmake/Modules/FindJsoncpp.cmake b/cmake/Modules/FindJsoncpp.cmake
deleted file mode 100644
index acde7b95b..000000000
--- a/cmake/Modules/FindJsoncpp.cmake
+++ /dev/null
@@ -1,47 +0,0 @@
-# Find jsoncpp
-#
-# Find the jsoncpp includes and library
-#
-# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
-#
-# This module defines
-# JSONCPP_INCLUDE_DIRS, where to find header, etc.
-# JSONCPP_LIBRARIES, the libraries needed to use jsoncpp.
-# JSONCPP_FOUND, If false, do not try to use jsoncpp.
-# JSONCPP_INCLUDE_PREFIX, include prefix for jsoncpp
-
-# only look in default directories
-find_path(
- JSONCPP_INCLUDE_DIR
- NAMES jsoncpp/json/json.h json/json.h
- DOC "jsoncpp include dir"
-)
-
-find_library(
- JSONCPP_LIBRARY
- NAMES jsoncpp
- DOC "jsoncpp library"
-)
-
-set(JSONCPP_INCLUDE_DIRS ${JSONCPP_INCLUDE_DIR})
-set(JSONCPP_LIBRARIES ${JSONCPP_LIBRARY})
-
-# find JSONCPP_INCLUDE_PREFIX
-find_path(
- JSONCPP_INCLUDE_PREFIX
- NAMES json.h
- PATH_SUFFIXES jsoncpp/json json
-)
-
-if (${JSONCPP_INCLUDE_PREFIX} MATCHES "jsoncpp")
- set(JSONCPP_INCLUDE_PREFIX "jsoncpp/json")
-else()
- set(JSONCPP_INCLUDE_PREFIX "json")
-endif()
-
-# handle the QUIETLY and REQUIRED arguments and set JSONCPP_FOUND to TRUE
-# if all listed variables are TRUE, hide their existence from configuration view
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(jsoncpp DEFAULT_MSG
- JSONCPP_INCLUDE_DIR JSONCPP_LIBRARY)
-mark_as_advanced (JSONCPP_INCLUDE_DIR JSONCPP_LIBRARY) \ No newline at end of file
diff --git a/cmake/Modules/FindLibEvent.cmake b/cmake/Modules/FindLibEvent.cmake
deleted file mode 100644
index 5e4113716..000000000
--- a/cmake/Modules/FindLibEvent.cmake
+++ /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.
-
-########################################
-#
-# Find the LibEvent libraries and includes
-# This module sets:
-# LIBEVENT_FOUND: True if LibEvent was found
-# LIBEVENT_LIBRARY: The LibEvent library
-# LIBEVENT_LIBRARIES: The LibEvent library and dependencies
-# LIBEVENT_INCLUDE_DIR: The LibEvent include dir
-#
-# This module will look for the libraries in various locations
-# See the LIBEVENT_SEARCH_PATH_LIST for a full list.
-#
-# The caller can hint at locations using the following variables:
-#
-# LIBEVENT_HOME (passed as -D to cmake)
-# LIBEVENT_HOME (in environment)
-#
-
-set(LIBEVENT_SEARCH_PATH_LIST
- ${LIBEVENT_HOME}
- $ENV{DEPENDENCIES}
- $ENV{LIBEVENT_HOME}
- /usr/local
- /opt
- /usr
- )
-
-find_path(LIBEVENT_INCLUDE_DIR event2/event.h
- HINTS ${LIBEVENT_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the LibEvent includes" )
-
-find_library(LIBEVENT_LIBRARY NAMES event
- HINTS ${LIBEVENT_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the LibEvent libraries" )
-
-set(LIBEVENT_LIBRARIES ${LIBEVENT_LIBRARY})
-set(LIBEVENT_INCLUDE_DIRS ${LIBEVENT_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(LibEvent DEFAULT_MSG LIBEVENT_LIBRARY LIBEVENT_INCLUDE_DIR)
diff --git a/cmake/Modules/FindLibconfig++.cmake b/cmake/Modules/FindLibconfig++.cmake
deleted file mode 100644
index 1636ae96a..000000000
--- a/cmake/Modules/FindLibconfig++.cmake
+++ /dev/null
@@ -1,43 +0,0 @@
-set(LIBCONFIG_SEARCH_PATH_LIST
- ${LIBCONFIG_HOME}
- $ENV{LIBCONFIG_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(LIBCONFIG_INCLUDE_DIR libconfig.h++
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the libconfig include"
-)
-
-if (WIN32)
- if(CMAKE_SIZEOF_VOID_P EQUAL 8)
- find_library(LIBCONFIG_CPP_LIBRARIES NAMES libconfig++.lib
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x64
- DOC "Find the libconfig libraries"
- )
- elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
- find_library(LIBCONFIG_CPP_LIBRARIES NAMES libconfig++.lib
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x32
- DOC "Find the libconfig libraries"
- )
- endif()
-else()
- find_library(LIBCONFIG_CPP_LIBRARY NAMES config++
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the libconfig++ libraries"
- )
-endif()
-
-set(LIBCONFIG_CPP_LIBRARIES ${LIBCONFIG_CPP_LIBRARY})
-set(LIBCONFIG_INCLUDE_DIRS ${LIBCONFIG_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Libconfig++ LIBCONFIG_CPP_LIBRARIES LIBCONFIG_INCLUDE_DIRS)
-
-mark_as_advanced(LIBCONFIG_CPP_LIBRARIES LIBCONFIG_INCLUDE_DIRS)
diff --git a/cmake/Modules/FindLibconfig.cmake b/cmake/Modules/FindLibconfig.cmake
deleted file mode 100644
index 55d2a0fad..000000000
--- a/cmake/Modules/FindLibconfig.cmake
+++ /dev/null
@@ -1,43 +0,0 @@
-set(LIBCONFIG_SEARCH_PATH_LIST
- ${LIBCONFIG_HOME}
- $ENV{LIBCONFIG_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(LIBCONFIG_INCLUDE_DIR libconfig.h
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the libconfig include"
-)
-
-if (WIN32)
- if(CMAKE_SIZEOF_VOID_P EQUAL 8)
- find_library(LIBCONFIG_LIBRARY NAMES libconfig.lib
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x64
- DOC "Find the libconfig libraries"
- )
- elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
- find_library(LIBCONFIG_LIBRARY NAMES libconfig.lib
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x32
- DOC "Find the libconfig libraries"
- )
- endif()
-else()
- find_library(LIBCONFIG_LIBRARY NAMES config
- HINTS ${LIBCONFIG_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the libconfig libraries"
- )
-endif()
-
-set(LIBCONFIG_LIBRARIES ${LIBCONFIG_LIBRARY})
-set(LIBCONFIG_INCLUDE_DIRS ${LIBCONFIG_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Libconfig LIBCONFIG_LIBRARIES LIBCONFIG_INCLUDE_DIRS)
-
-mark_as_advanced(LIBCONFIG_LIBRARIES LIBCONFIG_INCLUDE_DIRS)
diff --git a/cmake/Modules/FindLibhicn.cmake b/cmake/Modules/FindLibhicn.cmake
deleted file mode 100644
index 5f241a6cd..000000000
--- a/cmake/Modules/FindLibhicn.cmake
+++ /dev/null
@@ -1,52 +0,0 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-########################################
-#
-# Find the hcin libraries and includes
-# This module sets:
-# HICN_FOUND: True if hicn was found
-# HICN_LIBRARY: The hicn library
-# HICN_LIBRARIES: The hicn library and dependencies
-# HCIN_INCLUDE_DIR: The hicn include dir
-#
-
-set(HICN_SEARCH_PATH_LIST
- ${HICN_HOME}
- $ENV{HICN_HOME}
- $ENV{FOUNDATION_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(HICN_INCLUDE_DIR hicn/hicn.h
- HINTS ${HICN_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the hicn includes"
-)
-
-find_library(HICN_LIBRARY NAMES hicn
- HINTS ${HICN_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the hicn libraries"
-)
-
-set(HICN_LIBRARIES ${HICN_LIBRARY})
-if (${CMAKE_SYSTEM_NAME} STREQUAL "Android")
- set(HICN_LIBRARIES ${HICN_LIBRARIES} log)
-endif()
-set(HICN_INCLUDE_DIRS ${HICN_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(hicn DEFAULT_MSG HICN_LIBRARY HICN_INCLUDE_DIR)
diff --git a/cmake/Modules/FindLibhicnctrl.cmake b/cmake/Modules/FindLibhicnctrl.cmake
deleted file mode 100755
index 7c20420b4..000000000
--- a/cmake/Modules/FindLibhicnctrl.cmake
+++ /dev/null
@@ -1,45 +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.
-
-########################################
-#
-# Find the hICN control library and include files
-#
-
-set(HICN_SEARCH_PATH_LIST
- ${HICN_HOME}
- $ENV{HICN_HOME}
- $ENV{FOUNDATION_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(LIBHICNCTRL_INCLUDE_DIR hicn/ctrl.h
- HINTS ${HICN_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the hICN control include"
-)
-
-find_library(LIBHICNCTRL_LIBRARY NAMES hicnctrl
- HINTS ${HICN_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the hicn control library"
-)
-
-set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_LIBRARY})
-set(LIBHICNCTRL_INCLUDE_DIRS ${LIBHICNCTRL_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(hicnctrl DEFAULT_MSG
- LIBHICNCTRL_LIBRARY LIBHICNCTRL_INCLUDE_DIR)
diff --git a/cmake/Modules/FindLibmemif.cmake b/cmake/Modules/FindLibmemif.cmake
deleted file mode 100644
index 48460eecd..000000000
--- a/cmake/Modules/FindLibmemif.cmake
+++ /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.
-
-########################################
-#
-# Find the hcin libraries and includes
-# This module sets:
-# LIBMEMIF_FOUND: True if core was found
-# LIBMEMIF_LIBRARY: The core library
-# LIBMEMIF_INCLUDE_DIR: The core include dir
-#
-
-set(LIBMEMIF_SEARCH_PATH_LIST
- ${LIBMEMIF_HOME}
- $ENV{LIBMEMIF_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(LIBMEMIF_INCLUDE_DIR memif/libmemif.h
- HINTS ${LIBMEMIF_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the libmemif includes"
-)
-
-find_library(LIBMEMIF_LIBRARY NAMES memif
- HINTS ${LIBMEMIF_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the libmemif libraries"
-)
-
-set(LIBMEMIF_LIBRARIES ${LIBMEMIF_LIBRARY})
-set(LIBMEMIF_INCLUDE_DIRS ${LIBMEMIF_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Libmemif DEFAULT_MSG LIBMEMIF_LIBRARY LIBMEMIF_INCLUDE_DIR)
diff --git a/cmake/Modules/FindLibparc.cmake b/cmake/Modules/FindLibparc.cmake
deleted file mode 100644
index c5c99af15..000000000
--- a/cmake/Modules/FindLibparc.cmake
+++ /dev/null
@@ -1,50 +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.
-
-########################################
-#
-# Find the Libparc libraries and includes
-# This module sets:
-# LIBPARC_FOUND: True if Libparc was found
-# LIBPARC_LIBRARY: The Libparc library
-# LIBPARC_LIBRARIES: The Libparc library and dependencies
-# LIBPARC_INCLUDE_DIR: The Libparc include dir
-#
-
-set(LIBPARC_SEARCH_PATH_LIST
- ${LIBPARC_HOME}
- $ENV{LIBPARC_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(LIBPARC_INCLUDE_DIR parc/libparc_About.h
- HINTS ${LIBPARC_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the Libparc includes"
-)
-
-find_library(LIBPARC_LIBRARY NAMES parc
- HINTS ${LIBPARC_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the Libparc libraries"
-)
-
-set(LIBPARC_LIBRARIES ${LIBPARC_LIBRARY})
-set(LIBPARC_INCLUDE_DIRS ${LIBPARC_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Libparc DEFAULT_MSG LIBPARC_LIBRARY LIBPARC_INCLUDE_DIR)
-
-mark_as_advanced(LIBPARC_LIBRARY LIBPARC_INCLUDE_DIR)
diff --git a/cmake/Modules/FindLibtransport.cmake b/cmake/Modules/FindLibtransport.cmake
deleted file mode 100644
index 8a650b98c..000000000
--- a/cmake/Modules/FindLibtransport.cmake
+++ /dev/null
@@ -1,49 +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.
-
-########################################
-#
-# Find the LibTRANSPORT libraries and includes
-# This module sets:
-# LIBTRANSPORT_FOUND: True if Libconsumer-producer was found
-# LIBTRANSPORTR_LIBRARY: The Libconsumer-producer library
-# LIBTRANSPORT_LIBRARIES: The Libconsumer-producer library and dependencies
-# LIBTRANSPORT_INCLUDE_DIR: The Libconsumer-producer include dir
-#
-
-set(LIBTRANSPORT_SEARCH_PATH_LIST
- ${LIBTRANSPORT_HOME}
- $ENV{LIBTRANSPORTHOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(LIBTRANSPORT_INCLUDE_DIR hicn/transport/config.h
- HINTS ${LIBTRANSPORT_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the libtransport includes"
-)
-
-find_library(LIBTRANSPORT_LIBRARY
- NAMES hicntransport hicntransport-memif
- HINTS ${LIBTRANSPORT_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the libtransport libraries"
-)
-
-set(LIBTRANSPORT_LIBRARIES ${LIBTRANSPORT_LIBRARY})
-set(LIBTRANSPORT_INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Libtransport DEFAULT_MSG LIBTRANSPORT_LIBRARIES LIBTRANSPORT_INCLUDE_DIRS) \ No newline at end of file
diff --git a/cmake/Modules/FindLongBow.cmake b/cmake/Modules/FindLongBow.cmake
deleted file mode 100644
index 4a05d7fdf..000000000
--- a/cmake/Modules/FindLongBow.cmake
+++ /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.
-
-########################################
-#
-# Find the LongBow libraries and includes
-# This module sets:
-# LONGBOW_FOUND: True if LongBow was found
-# LONGBOW_LIBRARY: The LongBow library
-# LONGBOW_LIBRARIES: The LongBow library and dependencies
-# LONGBOW_INCLUDE_DIR: The LongBow include dir
-#
-
-set(LONGBOW_SEARCH_PATH_LIST
- ${LONGBOW_HOME}
- $ENV{LONGBOW_HOME}
- $ENV{PARC_HOME}
- $ENV{FOUNDATION_HOME}
- /usr/local/parc
- /usr/local/ccn
- /usr/local
- /opt
- /usr
- )
-
-find_path(LONGBOW_INCLUDE_DIR LongBow/longBow_About.h
- HINTS ${LONGBOW_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the LongBow includes" )
-
-find_library(LONGBOW_LIBRARY NAMES longbow
- HINTS ${LONGBOW_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the LongBow libraries" )
-
-find_library(LONGBOW_REPORT_LIBRARY NAMES longbow-textplain longbow-ansiterm
- HINTS ${LONGBOW_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the LongBow report libraries" )
-
-set(LONGBOW_LIBRARIES ${LONGBOW_LIBRARY} ${LONGBOW_REPORT_LIBRARY})
-set(LONGBOW_INCLUDE_DIRS ${LONGBOW_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(LongBow DEFAULT_MSG LONGBOW_LIBRARY LONGBOW_INCLUDE_DIR)
diff --git a/cmake/Modules/FindPThread.cmake b/cmake/Modules/FindPThread.cmake
deleted file mode 100644
index 6f0eeb7c0..000000000
--- a/cmake/Modules/FindPThread.cmake
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright (c) 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.
-
-########################################
-#
-# Find the PThread libraries and includes
-# This module sets:
-# PTHREAD_FOUND: True if pthread was found
-# PTHREADR_LIBRARY: The pthread library
-# PTHREAD_LIBRARIES: The pthread library and dependencies
-# PTHREAD_INCLUDE_DIR: The pthread include dir
-#
-
-
-set(PTHREAD_SEARCH_PATH_LIST
- ${PTHREAD_HOME}
- $ENV{PTHREAD_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(PTHREAD_INCLUDE_DIR pthread.h
- HINTS ${PTHREAD_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the pthreadincludes"
-)
-
-if(CMAKE_SIZEOF_VOID_P EQUAL 8)
- find_library(PTHREAD_LIBRARY NAMES pthreadVC2.lib
- HINTS ${PTHREAD_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x64
- DOC "Find the pthread libraries"
- )
-elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
- find_library(PTHREAD_LIBRARY NAMES pthreadVC2.lib
- HINTS ${PTHREAD_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x32
- DOC "Find the pthread libraries"
- )
-endif()
-
-
-set(PTHREAD_LIBRARIES ${PTHREAD_LIBRARY})
-set(PTHREAD_INCLUDE_DIRS ${PTHREAD_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Pthread DEFAULT_MSG PTHREAD_LIBRARIES PTHREAD_INCLUDE_DIRS) \ No newline at end of file
diff --git a/cmake/Modules/FindSafeVapi.cmake b/cmake/Modules/FindSafeVapi.cmake
deleted file mode 100644
index a9077ae14..000000000
--- a/cmake/Modules/FindSafeVapi.cmake
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright (c) 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.
-
-set(SAFE_VAPI_SEARCH_PATH_LIST
- ${SAFE_VAPI_HOME}
- $ENV{SAFE_VAPI_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(SAFE_VAPI_INCLUDE_DIR vapi/vapi_safe.h
- HINTS ${SAFE_VAPI_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the vapi_safe includes"
-)
-
-find_library(SAFE_VAPI_LIBRARY NAMES libsafe_vapi.so
- HINTS ${SAFE_VAPI_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x86_64-linux-gnu/
- DOC "Find the vapi safe lib"
-)
-
-set(SAFE_VAPI_LIBRARIES ${SAFE_VAPI_LIBRARY})
-set(SAFE_VAPI_INCLUDE_DIRS ${SAFE_VAPI_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Hicnlight SAFE_VAPI_LIBRARIES SAFE_VAPI_INCLUDE_DIRS)
-
-mark_as_advanced(SAFE_VAPI_LIBRARY SAFE_VAPI_INCLUDE_DIR)
diff --git a/cmake/Modules/FindSysrepo.cmake b/cmake/Modules/FindSysrepo.cmake
deleted file mode 100644
index 1c389e480..000000000
--- a/cmake/Modules/FindSysrepo.cmake
+++ /dev/null
@@ -1,46 +0,0 @@
-# Copyright (c) 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.
-
-set(SYSREPO_SEARCH_PATH_LIST
- ${SYSREPO_HOME}
- $ENV{SYSREPO_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(SYSREPO_INCLUDE_DIR sysrepo/values.h
- HINTS ${SYSREPO_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the sysrepo includes"
-)
-
-find_path(SYSREPO_INCLUDE_MAIN_DIR sysrepo.h
- HINTS ${SYSREPO_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the sysrepo includes"
-)
-
-find_library(SYSREPO_LIBRARY NAMES libsysrepo.so
- HINTS ${SYSREPO_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib
- DOC "Find the sysrepo library"
-)
-
-set(SYSREPO_LIBRARIES ${SYSREPO_LIBRARY})
-set(SYSREPO_INCLUDE_DIRS ${SYSREPO_INCLUDE_DIR} ${SYSREPO_INCLUDE_MAIN_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Sysrepo DEFAULT_MSG SYSREPO_LIBRARIES SYSREPO_INCLUDE_DIRS)
-
-mark_as_advanced(SYSREPO_LIBRARY SYSREPO_INCLUDE_DIR SYSREPO_INCLUDE_MAIN_DIR)
diff --git a/cmake/Modules/FindVapiSafe.cmake b/cmake/Modules/FindVapiSafe.cmake
deleted file mode 100644
index c2c9fd762..000000000
--- a/cmake/Modules/FindVapiSafe.cmake
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-set(SAFE_VAPI_SEARCH_PATH_LIST
- ${SAFE_VAPI_HOME}
- $ENV{SAFE_VAPI_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(SAFE_VAPI_INCLUDE_DIR vapi/vapi_safe.h
- HINTS ${SAFE_VAPI_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the vapi_safe includes"
-)
-
-find_library(SAFE_VAPI_LIBRARY NAMES libsafe_vapi.so
- HINTS ${SAFE_VAPI_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib/x86_64-linux-gnu/
- DOC "Find the vapi safe lib"
-)
-
-set(SAFE_VAPI_LIBRARIES ${SAFE_VAPI_LIBRARY})
-set(SAFE_VAPI_INCLUDE_DIRS ${SAFE_VAPI_INCLUDE_DIR})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(VapiSafe DEFAULT_MSG SAFE_VAPI_LIBRARIES SAFE_VAPI_INCLUDE_DIRS)
-
-mark_as_advanced(SAFE_VAPI_LIBRARY SAFE_VAPI_INCLUDE_DIR)
diff --git a/cmake/Modules/FindVpp.cmake b/cmake/Modules/FindVpp.cmake
deleted file mode 100644
index 4f8dba17a..000000000
--- a/cmake/Modules/FindVpp.cmake
+++ /dev/null
@@ -1,95 +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.
-
-set(VPP_SEARCH_PATH_LIST
- ${VPP_HOME}
- $ENV{VPP_HOME}
- /usr/local
- /opt
- /usr
-)
-
-find_path(VPP_INCLUDE_DIR vnet/vnet.h
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES include
- DOC "Find the VPP includes"
-)
-
-find_library(VPP_LIBRARY_MEMORYCLIENT
- NAMES vlibmemoryclient
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp Memoryclient library"
-)
-
-find_library(VPP_LIBRARY_SVM
- NAMES svm
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp svm library"
-)
-
-find_library(VPP_LIBRARY_INFRA
- NAMES vppinfra
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp infra library"
-)
-
-find_library(VPP_LIBRARY_VNET
- NAMES vnet
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp vnet library"
-)
-
-find_library(VPP_LIBRARY_VATPLUGIN
- NAMES vatplugin
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp vatplugin library"
-)
-
-find_library(VPP_LIBRARY_VLIB
- NAMES vlib
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp vlib library"
-)
-
-find_library(VPP_LIBRARY_VPPAPICLIENT
- NAMES vppapiclient
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp api library"
-)
-
-find_library(VPP_LIBRARY_VAPICLIENT
- NAMES vapiclient
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp vapi library"
-)
-
-find_library(VPP_LIBRARY_VLIBMEMORY
- NAMES vlibmemory
- HINTS ${VPP_SEARCH_PATH_LIST}
- PATH_SUFFIXES lib lib64
- DOC "Find the Vpp vlibmemory library"
-)
-
-set(VPP_LIBRARIES ${VPP_LIBRARY_MEMORYCLIENT} ${VPP_LIBRARY_SVM} ${VPP_LIBRARY_INFRA} ${VPP_LIBRARY_VATPLUGIN} ${VPP_LIBRARY_VLIB} ${VPP_LIBRARY_VNET} ${VPP_LIBRARY_VAPICLIENT} ${VPP_LIBRARY_VLIBMEMORY})
-set(VPP_INCLUDE_DIRS ${VPP_INCLUDE_DIR} ${VPP_INCLUDE_DIR}/vpp_plugins)
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Vpp DEFAULT_MSG VPP_LIBRARIES VPP_INCLUDE_DIRS)
diff --git a/cmake/Modules/GTestImport.cmake b/cmake/Modules/GTestImport.cmake
deleted file mode 100644
index d9d182578..000000000
--- a/cmake/Modules/GTestImport.cmake
+++ /dev/null
@@ -1,45 +0,0 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-##################################
-# Download and install GoogleTest
-
-include(ExternalProject)
-ExternalProject_Add(gtest
- URL https://github.com/google/googletest/archive/v1.10.x.zip
- PREFIX ${CMAKE_BINARY_DIR}/gtest
- BUILD_BYPRODUCTS
- ${CMAKE_BINARY_DIR}/gtest/src/gtest-build/lib/libgmock_main.a
- ${CMAKE_BINARY_DIR}/gtest/src/gtest-build/lib/libgmock.a
- ${CMAKE_BINARY_DIR}/gtest/src/gtest-build/lib/libgtest_main.a
- ${CMAKE_BINARY_DIR}/gtest/src/gtest-build/lib/libgtest.a
- INSTALL_COMMAND ""
-)
-
-ExternalProject_Get_Property(gtest source_dir binary_dir)
-
-message (STATUS "GTest include dir: ${source_dir}/googlemock/include ${source_dir}/googletest/include)")
-message (STATUS "GTest libs: ${binary_dir}/lib/libgmock_main.a ${binary_dir}/lib/libgmock.a ${binary_dir}/lib/libgtest_main.a ${binary_dir}/lib/libgtest.a")
-
-set(GTEST_INCLUDE_DIRS ${source_dir}/googlemock/include ${source_dir}/googletest/include)
-set(GTEST_LIBRARIES ${binary_dir}/lib/libgmock_main.a ${binary_dir}/lib/libgmock.a ${binary_dir}/lib/libgtest_main.a ${binary_dir}/lib/libgtest.a)
-
-macro(add_test_internal test)
- if(${CMAKE_VERSION} VERSION_GREATER "3.10.0")
- gtest_discover_tests(${test}-bin TEST_PREFIX new:)
- else()
- add_test(NAME ${test}-bin COMMAND ${test})
- endif()
-endmacro(add_test_internal)
-
-enable_testing()
diff --git a/cmake/Modules/License.txt b/cmake/Modules/License.txt
deleted file mode 100644
index 4d84c0dc7..000000000
--- a/cmake/Modules/License.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-Copyright (c) 2017-2021 Cisco and/or its affiliates.
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at:
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License. \ No newline at end of file
diff --git a/cmake/Modules/Packager.cmake b/cmake/Modules/Packager.cmake
deleted file mode 100644
index 105952662..000000000
--- a/cmake/Modules/Packager.cmake
+++ /dev/null
@@ -1,344 +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.
-
-#############
-# RPM/DEB/TGZ Packaging utils
-#
-
-set(CONTACT "hicn-dev@lists.fd.io" CACHE STRING "Contact")
-set(PACKAGE_MAINTAINER "ICN Team" CACHE STRING "Maintainer")
-set(PACKAGE_VENDOR "fd.io" CACHE STRING "Vendor")
-
-function(get_next_version VERSION NEXT_VERSION)
- string(REGEX REPLACE "([0-9]+).([0-9]+)" "\\1;\\2" VER_NUMBERS ${VERSION})
-
- # Increment version for getting next version value
- list(GET VER_NUMBERS 0 major)
- list(GET VER_NUMBERS 1 minor)
-
- math(EXPR minor "${minor} + 4")
-
- if (minor GREATER 12)
- math(EXPR minor "${minor} % 12")
- math(EXPR major "${major} + 1")
- endif()
-
- if (minor LESS 10)
- set(minor "0${minor}")
- endif()
-
- set(${NEXT_VERSION} "${major}.${minor}" PARENT_SCOPE)
-endfunction()
-
-macro(extract_version)
- # Extract version from git
- execute_process(
- COMMAND git describe --long --match v*
- WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
- OUTPUT_VARIABLE VER
- OUTPUT_STRIP_TRAILING_WHITESPACE
- )
-
- if (NOT VER)
- set(VER "v1.2-0-gcafe")
- endif()
- message(STATUS "Git describe output: ${VER}")
-
- string(REGEX REPLACE "v([0-9]+).([0-9]+)-?(.*)?-([0-9]+)-(g[0-9a-f]+)" "\\1;\\2;\\3;\\4;\\5;" VER ${VER})
- list(GET VER 0 VERSION_MAJOR)
- list(GET VER 1 VERSION_MINOR)
- list(GET VER 2 RELEASE_CANDIDATE)
- list(GET VER 3 VERSION_REVISION)
- list(GET VER 4 COMMIT_NAME)
-endmacro(extract_version)
-
-function(make_packages)
- if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
- # parse /etc/os-release
- file(READ "/etc/os-release" os_version)
- string(REPLACE "\n" ";" os_version ${os_version})
- foreach(_ver ${os_version})
- string(REPLACE "=" ";" _ver ${_ver})
- list(GET _ver 0 _name)
- list(GET _ver 1 _value)
- set(OS_${_name} ${_value})
- endforeach()
-
- extract_version()
-
- message(STATUS "Version major: ${VERSION_MAJOR}")
- message(STATUS "Version minor: ${VERSION_MINOR}")
- message(STATUS "Release: ${RELEASE_CANDIDATE}")
- message(STATUS "Revision: ${VERSION_REVISION}")
- message(STATUS "Commit hash: ${COMMIT_NAME}")
-
- set(tag "${VERSION_MAJOR}.${VERSION_MINOR}")
- string(REPLACE "-" "~" tag ${tag})
- set(commit_num ${VERSION_REVISION})
- set(commit_name ${COMMIT_NAME})
-
- if (NOT DEFINED ENV{BUILD_NUMBER})
- set(bld "b1")
- else()
- set(bld "b$ENV{BUILD_NUMBER}")
- endif()
- message(STATUS "Build number is: ${bld}")
-
- #define DEB and RPM version numbers
- if(NOT RELEASE_CANDIDATE)
- if (commit_num)
- set(deb_ver "${tag}.${commit_num}-release")
- set(rpm_ver "${tag}.${commit_num}")
- else()
- set(deb_ver "${tag}-release")
- set(rpm_ver "${tag}")
- endif()
- set(rpm_release "release")
- else()
- # TODO To be changed for next release with
- # set(deb_ver "${tag}${RELEASE_CANDIDATE}~${commit_num}")
- # set(rpm_ver "${tag}")
- # set(rpm_release "${RELEASE_CANDIDATE}~${commit_num}")
- set(deb_ver "${tag}-${commit_num}")
- set(rpm_ver "${tag}-${commit_num}")
- set(rpm_release "1")
- endif()
-
- message(STATUS "Version: ${deb_ver}")
-
- get_next_version(${tag} next_version)
- message(STATUS "Next version: ${next_version}")
-
- get_cmake_property(components COMPONENTS)
- list(REMOVE_ITEM components "Unspecified")
- set(CPACK_COMPONENTS_ALL ${components})
-
- list(LENGTH components N_COMPONENTS)
-
- if (NOT N_COMPONENTS)
- return()
- endif()
-
- if(OS_ID MATCHES "debian" OR OS_ID_LIKE MATCHES "debian")
- set(CPACK_GENERATOR "DEB")
- set(type "DEBIAN")
-
- execute_process(
- COMMAND dpkg --print-architecture
- OUTPUT_VARIABLE arch
- OUTPUT_STRIP_TRAILING_WHITESPACE
- )
-
- set(CPACK_${type}_PACKAGE_VERSION "${deb_ver}")
- foreach(lc ${components})
- if (${lc} MATCHES ".*Unspecified.*")
- continue()
- endif()
-
- string(TOUPPER ${lc} uc)
- set(CPACK_${type}_${uc}_FILE_NAME "${lc}_${deb_ver}_${arch}.deb")
-
- set(DEB_DEPS)
- if (NOT ${${lc}_DEB_DEPENDENCIES} STREQUAL "")
- string(REPLACE "stable_version" ${tag} DEB_DEPS ${${lc}_DEB_DEPENDENCIES})
- string(REPLACE "next_version" ${next_version} DEB_DEPS ${DEB_DEPS})
- endif()
-
- set(CPACK_${type}_${uc}_PACKAGE_DEPENDS "${DEB_DEPS}")
- set(CPACK_${type}_${uc}_PACKAGE_NAME "${lc}")
- set(CPACK_COMPONENT_${uc}_DESCRIPTION "${${lc}_DESCRIPTION}")
-
- if (${lc}_DEB_PACKAGE_CONTROL_EXTRA)
- set(CPACK_DEBIAN_${uc}_PACKAGE_CONTROL_EXTRA "${${lc}_DEB_PACKAGE_CONTROL_EXTRA}")
- endif()
- endforeach()
- elseif(OS_ID_LIKE MATCHES "rhel")
- set(CPACK_GENERATOR "RPM")
- set(type "RPM")
-
- execute_process(
- COMMAND uname -m
- OUTPUT_VARIABLE arch
- OUTPUT_STRIP_TRAILING_WHITESPACE
- )
-
- set(CPACK_${type}_PACKAGE_VERSION "${rpm_ver}")
- set(CPACK_${type}_PACKAGE_RELEASE "${rpm_release}")
- foreach(lc ${components})
- if (${lc} MATCHES ".*Unspecified.*")
- continue()
- endif()
-
- string(TOUPPER ${lc} uc)
- set(CPACK_${type}_${uc}_DESCRIPTION "${${lc}_DESCRIPTION}")
-
- set(RPM_DEPS)
- if (NOT ${${lc}_RPM_DEPENDENCIES} STREQUAL "")
- string(REPLACE "stable_version" ${tag} RPM_DEPS ${${lc}_RPM_DEPENDENCIES})
- string(REPLACE "next_version" ${next_version} RPM_DEPS ${RPM_DEPS})
- endif()
-
- set(CPACK_${type}_${uc}_PACKAGE_REQUIRES "${RPM_DEPS}")
-
- if(${lc} MATCHES ".*-dev")
- set(package_name ${lc}el)
- else()
- set(package_name ${lc})
- endif()
-
- set(CPACK_RPM_${uc}_PACKAGE_NAME "${package_name}")
- set(CPACK_${type}_${uc}_FILE_NAME "${package_name}-${rpm_ver}-${rpm_release}.${arch}.rpm")
-
- if (NOT ${${lc}_RPM_POST_INSTALL_SCRIPT_FILE} STREQUAL "")
- set(CPACK_RPM_${uc}_POST_INSTALL_SCRIPT_FILE "${${lc}_RPM_POST_INSTALL_SCRIPT_FILE}")
- endif()
-
- if (NOT ${${lc}_RPM_POST_UNINSTALL_SCRIPT_FILE} STREQUAL "")
- set(CPACK_RPM_${uc}_POST_UNINSTALL_SCRIPT_FILE "${${lc}_RPM_POST_UNINSTALL_SCRIPT_FILE}")
- endif()
-
- if (NOT ${${lc}_RPM_PRE_UNINSTALL_SCRIPT_FILE} STREQUAL "")
- set(CPACK_RPM_${uc}_PRE_UNINSTALL_SCRIPT_FILE "${${lc}_RPM_PRE_UNINSTALL_SCRIPT_FILE}")
- endif()
- endforeach()
- endif()
-
- if(CPACK_GENERATOR)
- set(CPACK_PACKAGE_NAME ${ARG_NAME})
- set(CPACK_STRIP_FILES OFF)
- set(CPACK_PACKAGE_VENDOR "${PACKAGE_VENDOR}")
- set(CPACK_COMPONENTS_IGNORE_GROUPS 1)
- set(CPACK_${CPACK_GENERATOR}_COMPONENT_INSTALL ON)
- set(CPACK_${type}_PACKAGE_MAINTAINER "HICN Team")
- set(CPACK_PACKAGE_CONTACT ${CONTACT})
- include(CPack)
- endif()
- elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR ${CMAKE_SYSTEM_NAME} MATCHES "Windows")
- set(CMAKE_SKIP_BUILD_RPATH FALSE)
- set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
- set(CMAKE_INSTALL_RPATH /opt/hicn)
-
- set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
-
- set(CPACK_SET_DESTDIR true)
-
- set(CMAKE_INSTALL_RPATH "\${CPACK_INSTALL_PREFIX}")
- set(CMAKE_SKIP_INSTALL_RPATH FALSE)
- set(HICN_DEPENDECIES_INSTALLER "${LIBTRANSPORT_LIBRARIES_LIST};${FACEMGR_LIBRARY_LIST};${APPS_LIBRARY_LIST}")
- separate_arguments(HICN_DEPENDECIES_INSTALLER)
- foreach (HICN_DEPENDECY ${HICN_DEPENDECIES_INSTALLER})
- get_filename_component(DEPENDENCY_NAME "${HICN_DEPENDECY}" NAME)
- get_filename_component(DEPENDENCY "${HICN_DEPENDECY}" REALPATH)
- get_filename_component(DEPENDENCY_PATH "${DEPENDENCY}" DIRECTORY)
- install(FILES ${DEPENDENCY} DESTINATION lib COMPONENT dependencies)
- endforeach()
- set(CPACK_PACKAGE_NAME "hicn")
- extract_version()
- set(CPACK_PACKAGE_VENDOR "${PACKAGE_VENDOR}")
- set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "hICN")
- set(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_REVISION}")
- set(CPACK_PACKAGE_VERSION_MAJOR "${VERSION_MAJOR}")
- set(CPACK_PACKAGE_VERSION_MINOR "${VERSION_MINOR}")
- set(CPACK_PACKAGE_VERSION_PATCH "${VERSION_REVISION}")
- set(CPACK_PACKAGE_INSTALL_DIRECTORY "hICN Components")
-
- set(CPACK_COMPONENTS_ALL dependencies ${HICN_UTILS} ${HICN_LIGHT} ${HICN_APPS} ${FACEMGR} lib${LIBTRANSPORT} ${LIBTRANSPORT}-dev lib${LIBHICN} ${LIBHICN}-dev ${HICN_UTILS}-dev ${HICN_LIGHT}-dev ${HICN_APPS}-dev ${FACEMGR}-dev)
- set(CPACK_COMPONENT_DEPENDENCIES_DISPLAY_NAME "Dependencies")
- if (NOT "${HICN_UTILS}" STREQUAL "")
- string(TOUPPER ${HICN_UTILS} HICN_UTILS_UPPERCASE)
- string(TOUPPER ${HICN_UTILS}-dev HICN_UTILS_DEV_UPPERCASE)
- set(CPACK_COMPONENT_${HICN_UTILS_UPPERCASE}_DISPLAY_NAME "hICN utils")
- set(CPACK_COMPONENT_${HICN_UTILS_DEV_UPPERCASE}_DISPLAY_NAME "hicn utils headers")
- set(CPACK_COMPONENT_${HICN_UTILS_UPPERCASE}_GROUP "Executables")
- set(CPACK_COMPONENT_${HICN_UTILS_DEV_UPPERCASE}_GROUP "Headers")
- set(CPACK_COMPONENT_${HICN_UTILS_UPPERCASE}_INSTALL_TYPES Full)
- set(CPACK_COMPONENT_${HICN_UTILS_DEV_UPPERCASE}_INSTALL_TYPES Full)
- endif ()
-
- if (NOT "${HICN_LIGHT}" STREQUAL "")
- string(TOUPPER ${HICN_LIGHT} HICN_LIGHT_UPPERCASE)
- string(TOUPPER ${HICN_LIGHT}-dev HICN_LIGHT_DEV_UPPERCASE)
- set(CPACK_COMPONENT_${HICN_LIGHT_UPPERCASE}_DISPLAY_NAME "hICN light apps")
- set(CPACK_COMPONENT_${HICN_LIGHT_DEV_UPPERCASE}_DISPLAY_NAME "hicn-light headers")
- set(CPACK_COMPONENT_${HICN_LIGHT_UPPERCASE}_GROUP "Executables")
- set(CPACK_COMPONENT_${HICN_LIGHT_DEV_UPPERCASE}_GROUP "Headers")
- set(CPACK_COMPONENT_${HICN_LIGHT_UPPERCASE}_INSTALL_TYPES Full)
- set(CPACK_COMPONENT_${HICN_LIGHT_DEV_UPPERCASE}_INSTALL_TYPES Full)
- endif ()
-
- if (NOT "${HICN_APPS}" STREQUAL "")
- string(TOUPPER ${HICN_APPS} HICN_APPS_UPPERCASE)
- string(TOUPPER ${HICN_APPS}-dev HICN_APPS_DEV_UPPERCASE)
- set(CPACK_COMPONENT_${HICN_APPS_UPPERCASE}_DISPLAY_NAME "hICN apps")
- set(CPACK_COMPONENT_${HICN_APPS_DEV_UPPERCASE}_DISPLAY_NAME "hicn-apps headers")
- set(CPACK_COMPONENT_${HICN_APPS_UPPERCASE}_GROUP "Executables")
- set(CPACK_COMPONENT_${HICN_APPS_DEV_UPPERCASE}_GROUP "Headers")
- set(CPACK_COMPONENT_${HICN_APPS_UPPERCASE}_INSTALL_TYPES Full)
- set(CPACK_COMPONENT_${HICN_APPS_DEV_UPPERCASE}_INSTALL_TYPES Full)
- endif ()
-
- if (NOT "${FACEMGR}" STREQUAL "")
- string(TOUPPER ${FACEMGR} FACEMGR_UPPERCASE)
- string(TOUPPER ${FACEMGR}-dev FACEMGR_DEV_UPPERCASE)
- set(CPACK_COMPONENT_${FACEMGR_UPPERCASE}_DISPLAY_NAME "facemgr")
- set(CPACK_COMPONENT_${FACEMGR_DEV_UPPERCASE}_DISPLAY_NAME "facemgr headers")
- set(CPACK_COMPONENT_${FACEMGR_UPPERCASE}_GROUP "Executables")
- set(CPACK_COMPONENT_${FACEMGR_DEV_UPPERCASE}_GROUP "Headers")
- set(CPACK_COMPONENT_${FACEMGR_UPPERCASE}_INSTALL_TYPES Full)
- set(CPACK_COMPONENT_${FACEMGR_DEV_UPPERCASE}_INSTALL_TYPES Full)
- endif ()
-
- if (NOT "${LIBTRANSPORT}" STREQUAL "")
- string(TOUPPER lib${LIBTRANSPORT} LIBTRANSPORT_UPPERCASE)
- string(TOUPPER ${LIBTRANSPORT}-dev LIBTRANSPORT_DEV_UPPERCASE)
- set(CPACK_COMPONENT_${LIBTRANSPORT_UPPERCASE}_DISPLAY_NAME "libtransport libs")
- set(CPACK_COMPONENT_${LIBTRANSPORT_DEV_UPPERCASE}_DISPLAY_NAME "libtransport headers")
- set(CPACK_COMPONENT_${LIBTRANSPORT_UPPERCASE}_GROUP "Libraries")
- set(CPACK_COMPONENT_${LIBTRANSPORT_DEV_UPPERCASE}_GROUP "Headers")
- set(CPACK_COMPONENT_${LIBTRANSPORT_UPPERCASE}_INSTALL_TYPES Full)
- set(CPACK_COMPONENT_${LIBTRANSPORT_DEV_UPPERCASE}_INSTALL_TYPES Full)
- endif ()
-
- if (NOT "${LIBHICN}" STREQUAL "")
- string(TOUPPER lib${LIBHICN} LIBHICN_UPPERCASE)
- string(TOUPPER ${LIBHICN}-dev LIBHICN_DEV_UPPERCASE)
- set(CPACK_COMPONENT_${LIBHICN_UPPERCASE}_DISPLAY_NAME "hicn libs")
- set(CPACK_COMPONENT_${LIBHICN_DEV_UPPERCASE}_DISPLAY_NAME "hicn headers")
- set(CPACK_COMPONENT_${LIBHICN_UPPERCASE}_GROUP "Libraries")
- set(CPACK_COMPONENT_${LIBHICN_DEV_UPPERCASE}_GROUP "Headers")
- set(CPACK_COMPONENT_${LIBHICN_UPPERCASE}_INSTALL_TYPES Full)
- set(CPACK_COMPONENT_${LIBHICN_DEV_UPPERCASE}_INSTALL_TYPES Full)
- endif ()
-
- set (CPACK_RESOURCE_FILE_LICENSE
- "${PROJECT_SOURCE_DIR}/cmake/Modules/License.txt")
- set(CPACK_COMPONENT_DEPENDENCIES_DESCRIPTION
- "All dependency libreries")
- set(CPACK_COMPONENT_DEPENDENCIES_GROUP "Dependencies")
- set(CPACK_COMPONENT_GROUP_DEVELOPMENT_EXPANDED ON)
- set(CPACK_COMPONENT_GROUP_DEPENDENCIES_DESCRIPTION
- "All dependency libreries")
- set(CPACK_ALL_INSTALL_TYPES Full Developer)
- set(CPACK_INSTALL_TYPE_FULL_DISPLAY_NAME "Everything")
- if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
- set(CMAKE_INSTALL_RPATH /opt/hicn)
-
- set(CPACK_INSTALL_PREFIX "/opt/hicn")
- set(CPACK_GENERATOR productbuild)
- set( CPACK_PRE_BUILD_SCRIPTS "${PROJECT_SOURCE_DIR}/cmake/Modules/PostInstall.cmake")
- else()
- set(CPACK_INSTALL_PREFIX "c:/Program Files/hicn")
- endif()
- include(CPack)
- endif()
-endfunction()
diff --git a/cmake/Modules/PostInstall.cmake b/cmake/Modules/PostInstall.cmake
deleted file mode 100644
index 89c7b9f68..000000000
--- a/cmake/Modules/PostInstall.cmake
+++ /dev/null
@@ -1,83 +0,0 @@
-function(change_rpath LIB_PATH TYPE)
- execute_process (
- COMMAND bash -c "ls ${LIB_PATH}"
- OUTPUT_VARIABLE ITEMS
- )
- string(REPLACE "\n" ";" ITEMS ${ITEMS})
-
- separate_arguments(ITEMS)
- foreach (ITEM ${ITEMS})
- if (NOT ITEM MATCHES ".a$")
- if (TYPE STREQUAL "LIB")
- execute_process (
- COMMAND bash -c "otool -L ${LIB_PATH}/${ITEM} | head -2 | tail -1| sed -e 's/^[[:space:]]*//'|awk '{print $1;}'"
- OUTPUT_VARIABLE OTOOL_OUTPUT
- )
- string(REPLACE "\n" "" OTOOL_OUTPUT ${OTOOL_OUTPUT})
-
- execute_process (
- COMMAND bash -c "basename ${OTOOL_OUTPUT}| sed -e 's/^[[:space:]]*//'"
- OUTPUT_VARIABLE BASENAME
- )
- string(REPLACE "\n" "" BASENAME ${BASENAME})
- execute_process (
- COMMAND bash -c "install_name_tool -id ${CPACK_INSTALL_PREFIX}/${BASENAME} ${LIB_PATH}/${ITEM}"
- OUTPUT_VARIABLE OUTPUT_INSTALL_NAME_TOOL
- )
- #change rpath
- execute_process (
- COMMAND bash -c "otool -L ${LIB_PATH}/${ITEM} | tail -n +3| sed -e 's/^[[:space:]]*//'|awk '{print $1;}'"
- OUTPUT_VARIABLE OTOOL_OUTPUTS
- )
- else ()
- #change rpath
- execute_process (
- COMMAND bash -c "otool -L ${LIB_PATH}/${ITEM} | tail -n +2| sed -e 's/^[[:space:]]*//'|awk '{print $1;}'"
- OUTPUT_VARIABLE OTOOL_OUTPUTS
- )
- endif ()
- string(REPLACE "\n" ";" OTOOL_OUTPUTS ${OTOOL_OUTPUTS})
- separate_arguments(OTOOL_OUTPUTS)
- foreach (OTOOL_OUTPUT ${OTOOL_OUTPUTS})
- execute_process (
- COMMAND bash -c "basename ${OTOOL_OUTPUT}| sed -e 's/^[[:space:]]*//'"
- OUTPUT_VARIABLE BASENAME
- )
- string(REPLACE "\n" "" BASENAME ${BASENAME})
- execute_process (
- COMMAND bash -c "dirname ${OTOOL_OUTPUT}| sed -e 's/^[[:space:]]*//'"
- OUTPUT_VARIABLE DIRNAME
- )
- string(REPLACE "\n" "" DIRNAME ${DIRNAME})
- if(NOT DIRNAME MATCHES "/usr/lib")
- execute_process (
- COMMAND bash -c "install_name_tool -change ${OTOOL_OUTPUT} ${CPACK_INSTALL_PREFIX}/${BASENAME} ${LIB_PATH}/${ITEM}"
- OUTPUT_VARIABLE OUTPUT_INSTALL_NAME_TOOL
- )
- endif()
-
- endforeach()
- endif()
- endforeach()
-endfunction()
-string(TOLOWER ${CPACK_COMPONENT_DEPENDENCIES_GROUP} CPACK_COMPONENT_DEPENDENCIES_GROUP )
-set(LIB_PATH "${CPACK_TEMPORARY_DIRECTORY}/${CPACK_COMPONENT_DEPENDENCIES_GROUP}${CPACK_INSTALL_PREFIX}/lib")
-change_rpath(${LIB_PATH} LIB)
-
-set(LIB_PATH "${CPACK_TEMPORARY_DIRECTORY}/facemgr${CPACK_INSTALL_PREFIX}/lib")
-change_rpath(${LIB_PATH} LIB)
-set(LIB_PATH "${CPACK_TEMPORARY_DIRECTORY}/libhicntransport${CPACK_INSTALL_PREFIX}/lib")
-change_rpath(${LIB_PATH} LIB)
-set(LIB_PATH "${CPACK_TEMPORARY_DIRECTORY}/libhicn${CPACK_INSTALL_PREFIX}/lib")
-change_rpath(${LIB_PATH} LIB)
-
-set(EXE_PATH "${CPACK_TEMPORARY_DIRECTORY}/hicn-utils${CPACK_INSTALL_PREFIX}/bin")
-change_rpath(${EXE_PATH} EXE)
-set(EXE_PATH "${CPACK_TEMPORARY_DIRECTORY}/hicn-light${CPACK_INSTALL_PREFIX}/bin")
-change_rpath(${EXE_PATH} EXE)
-set(EXE_PATH "${CPACK_TEMPORARY_DIRECTORY}/hicn-apps${CPACK_INSTALL_PREFIX}/bin")
-change_rpath(${EXE_PATH} EXE)
-set(EXE_PATH "${CPACK_TEMPORARY_DIRECTORY}/facemgr${CPACK_INSTALL_PREFIX}/bin")
-change_rpath(${EXE_PATH} EXE)
-#set(EXE_PATH "${CPACK_TEMPORARY_DIRECTORY}/hicnctrl${CPACK_INSTALL_PREFIX}/bin")
-#change_rpath(${EXE_PATH} EXE)
diff --git a/cmake/Modules/ServiceScript.cmake b/cmake/Modules/ServiceScript.cmake
deleted file mode 100644
index 8e7056a5a..000000000
--- a/cmake/Modules/ServiceScript.cmake
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright (c) 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.
-
-########################################
-#
-# Find the LongBow libraries and includes
-# This module sets:
-# SYSTEMD_FOUND: True if Systemd was found
-# SYSTEMD_SERVICES_INSTALL_DIR: The Systemd install directory
-
-set(SYSTEMD_SERVICE_FOLDER "/lib/systemd/system")
-
-macro(install_service_script script)
-cmake_parse_arguments(ARG
- ""
- "COMPONENT"
- ""
- ${ARGN}
-)
-
- # Install service file only if
- # 1) We are on a linux system
- # 2) The installation prefix is /usr
-
- if (NOT ARG_COMPONENT)
- set(ARG_COMPONENT hicn)
- endif()
-
- if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" AND ${CMAKE_INSTALL_PREFIX} STREQUAL "/usr")
- install (FILES ${script} DESTINATION ${SYSTEMD_SERVICE_FOLDER} COMPONENT ${ARG_COMPONENT})
- endif()
-endmacro(install_service_script)
diff --git a/cmake/Modules/WindowsMacros.cmake b/cmake/Modules/WindowsMacros.cmake
deleted file mode 100644
index 0b34cde19..000000000
--- a/cmake/Modules/WindowsMacros.cmake
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-if(WIN32)
- find_package(LibEvent REQUIRED)
- find_package(OpenSSL REQUIRED)
- find_package(PThread REQUIRED)
- find_library(WSOCK32_LIBRARY wsock32 required)
- find_library(WS2_32_LIBRARY ws2_32 required)
- list(APPEND WINDOWS_LIBRARIES
- ${LIBEVENT_LIBRARIES}
- ${OPENSSL_LIBRARIES}
- ${PTHREAD_LIBRARIES}
- ${WSOCK32_LIBRARY}
- ${WS2_32_LIBRARY}
- )
-
- list(APPEND WINDOWS_INCLUDE_DIRS
- ${LIBEVENT_INCLUDE_DIRS}
- ${OPENSSL_INCLUDE_DIR}
- ${PTHREAD_INCLUDE_DIRS}
- )
-endif() \ No newline at end of file
diff --git a/cmake/Modules/detectCacheSize.cmake b/cmake/Modules/detectCacheSize.cmake
deleted file mode 100644
index a8209bb27..000000000
--- a/cmake/Modules/detectCacheSize.cmake
+++ /dev/null
@@ -1,21 +0,0 @@
-# Detect the cache size
-#
-# XXX: TODO: This is a bug when cross compiling. We are detecting the local
-# Cache Line size and not the target cache line size. We should provide some
-# way to define this
-
-set(LEVEL1_DCACHE_LINESIZE 32)
-
-if( APPLE )
- execute_process(COMMAND sysctl -n hw.cachelinesize
- OUTPUT_VARIABLE LEVEL1_DCACHE_LINESIZE
- OUTPUT_STRIP_TRAILING_WHITESPACE)
-endif( APPLE )
-
-if( ${CMAKE_SYSTEM_NAME} STREQUAL "Linux" )
- execute_process(COMMAND getconf LEVEL1_DCACHE_LINESIZE
- OUTPUT_VARIABLE LEVEL1_DCACHE_LINESIZE
- OUTPUT_STRIP_TRAILING_WHITESPACE)
-endif()
-
-message(STATUS "Cache line size: ${LEVEL1_DCACHE_LINESIZE}")
diff --git a/libtransport/cmake/Modules/TestMacros.cmake b/ctrl/.clang-format
index 680b5585f..2f629734d 100644
--- a/libtransport/cmake/Modules/TestMacros.cmake
+++ b/ctrl/.clang-format
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,5 +11,5 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-include(CTest)
-
+BasedOnStyle: Google
+SortIncludes: false
diff --git a/ctrl/CMakeLists.txt b/ctrl/CMakeLists.txt
index 331ae9078..e601d9509 100644
--- a/ctrl/CMakeLists.txt
+++ b/ctrl/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -10,13 +10,17 @@
# 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.
-
+##############################################################
+# Project and cmake version
+##############################################################
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-
project(ctrl)
-add_subdirectory(libhicnctrl)
-if (NOT (BUILD_HICNPLUGIN AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux"))
- add_subdirectory(facemgr)
-endif () \ No newline at end of file
+##############################################################
+# Subdirectories
+##############################################################
+add_subdirectory(libhicnctrl)
+if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux" OR "${CMAKE_SYSTEM_NAME}" STREQUAL "Android" OR "${CMAKE_SYSTEM_NAME}" STREQUAL "iOS")
+ add_subdirectory(facemgr)
+endif ()
diff --git a/ctrl/facemgr/CMakeLists.txt b/ctrl/facemgr/CMakeLists.txt
index 2fad5d839..9d549bddf 100644
--- a/ctrl/facemgr/CMakeLists.txt
+++ b/ctrl/facemgr/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,62 +11,98 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Project and cmake version
+##############################################################
+project(facemgr)
+
if (APPLE)
- # >= 3.13 - CMP0079 (only needed on Apple platform for conditionally linking Network.framwork to libfacemgr)
- cmake_minimum_required(VERSION 3.13 FATAL_ERROR)
+ # >= 3.13 - CMP0079 (only needed on Apple platform for conditionally linking Network.framwork to libfacemgr)
+ cmake_minimum_required(VERSION 3.13 FATAL_ERROR)
else()
- cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
+ cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
endif()
-project(facemgr)
+##############################################################
+# C Standard
+##############################################################
+set(CMAKE_C_STANDARD 11)
+set(CMAKE_C_STANDARD_REQUIRED ON)
+
+##############################################################
+# CMAKE Options
+##############################################################
option(WITH_THREAD "Run library as thread" OFF)
option(WITH_EXAMPLE_DUMMY "Compile dummy example interface" OFF)
option(WITH_EXAMPLE_UPDOWN "Compile updown example interface" OFF)
if(WITH_THREAD)
- message("Building with thread support")
+ message(STATUS "Building with thread support")
endif()
if(WITH_EXAMPLE_DUMMY)
- message("Building with 'dummy' example interface")
+ message(STATUS "Building with 'dummy' example interface")
endif()
if(WITH_EXAMPLE_UPDOWN)
- message("Building with 'updown' example interface")
-endif()
-
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
+ message(STATUS "Building with 'updown' example interface")
endif()
if(CMAKE_BUILD_TYPE MATCHES Debug)
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -ggdb3")
endif()
+
+##############################################################
+# Cmake modules
+##############################################################
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
"${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/Modules"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
)
-include(BuildMacros)
-set(CMAKE_C_STANDARD 11)
-set(CMAKE_C_STANDARD_REQUIRED ON)
+##############################################################
+# Libs and Bins names
+##############################################################
+set(FACEMGR facemgr CACHE INTERNAL "" FORCE)
+set(LIBFACEMGR facemgr CACHE INTERNAL "" FORCE)
+
+
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../versions.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH ON)
-find_package_wrapper(Libconfig REQUIRED)
-find_package_wrapper(LibEvent REQUIRED)
-set(FACEMGR facemgr CACHE INTERNAL "" FORCE)
-set(LIBFACEMGR facemgr CACHE INTERNAL "" FORCE)
+##############################################################
+# Dependencies and third party libs
+##############################################################
+find_package(Libconfig ${LIBCONFIG_DEFAULT_VERSION} REQUIRED)
+find_package(LibEvent ${LIBEVENT_DEFAULT_VERSION} REQUIRED)
+
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- find_package_wrapper(Libhicn REQUIRED)
- find_package_wrapper(Libhicnctrl REQUIRED)
+ include(CommonSetup)
+
+ find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
+ find_package(Libhicnctrl ${CURRENT_VERSION} REQUIRED NO_MODULE)
+
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
+
+ list(APPEND HICN_LIBRARIES hicn::hicn.${LIBTYPE})
+ list(APPEND LIBHICNCTRL_LIBRARIES hicn::hicnctrl.${LIBTYPE})
else()
if (DISABLE_SHARED_LIBRARIES)
if (WIN32)
@@ -89,11 +125,18 @@ else()
endif ()
endif()
+
+##############################################################
+# Subdirectories
+##############################################################
add_subdirectory(includes)
add_subdirectory(src)
-include(Packaging)
+
+##############################################################
+# Service file
+##############################################################
# Install service file in linux systems
include(ServiceScript)
install_service_script(
@@ -101,14 +144,23 @@ install_service_script(
COMPONENT ${FACEMGR}
)
+
+##############################################################
# Configuration file
+##############################################################
set(FACEMGR_CONF_FILE ${CMAKE_CURRENT_SOURCE_DIR}/config/facemgr.conf)
-set(FACEMGR_CONF_FOLDER "/etc/facemgr")
-if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
- install (FILES ${FACEMGR_CONF_FILE} DESTINATION ${FACEMGR_CONF_FOLDER} COMPONENT ${FACEMGR})
+if (${CMAKE_SYSTEM_NAME} MATCHES Darwin OR ${CMAKE_SYSTEM_NAME} MATCHES Linux)
+ set(FACEMGR_CONF_FOLDER "${CMAKE_INSTALL_FULL_SYSCONFDIR}/facemgr")
+else ()
+ set(FACEMGR_CONF_FOLDER "${CMAKE_INSTALL_PREFIX}/etc/hicn")
endif()
+install (FILES
+ ${FACEMGR_CONF_FILE}
+ DESTINATION ${FACEMGR_CONF_FOLDER}
+ COMPONENT ${FACEMGR}
+)
+
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
+ make_packages()
endif()
diff --git a/ctrl/facemgr/cmake/Modules/Packaging.cmake b/ctrl/facemgr/cmake/packaging.cmake
index bb4fa42fa..62b14b202 100644
--- a/ctrl/facemgr/cmake/Modules/Packaging.cmake
+++ b/ctrl/facemgr/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -20,27 +20,37 @@ set(${FACEMGR}_DESCRIPTION
CACHE STRING "Description for deb/rpm package."
)
+set(${FACEMGR}-dev_DEB_DEPENDENCIES
+ "libconfig9, libevent-dev, lib${LIBHICNCTRL}-dev (= stable_version)"
+ CACHE STRING "Dependencies for deb/rpm package."
+)
+
set(${FACEMGR}_DEB_DEPENDENCIES
- "libconfig9, libevent-dev, lib${LIBHICNCTRL} (>= stable_version)"
+ "libconfig9, libevent-2.1-7, lib${LIBHICNCTRL} (= stable_version)"
CACHE STRING "Dependencies for deb/rpm package."
)
-set(${HICN_LIGHT}_DEB_PACKAGE_CONTROL_EXTRA
+set(${FACEMGR}_DEB_PACKAGE_CONTROL_EXTRA
"${CMAKE_CURRENT_SOURCE_DIR}/config/postinst;${CMAKE_CURRENT_SOURCE_DIR}/config/prerm"
CACHE STRING "Control scripts conffiles, postinst, postrm, prerm."
)
set(${FACEMGR}_RPM_DEPENDENCIES
- "libconfig, libevent-devel, lib${LIBHICNCTRL} >= stable_version"
+ "libconfig, libevent, lib${LIBHICNCTRL} = stable_version"
+ CACHE STRING "Dependencies for deb/rpm package."
+)
+
+set(${FACEMGR}-dev_RPM_DEPENDENCIES
+ "libconfig, libevent-devel, lib${LIBHICNCTRL}-dev = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
)
-set(${HICN_LIGHT}_RPM_POST_INSTALL_SCRIPT_FILE
+set(${FACEMGR}_RPM_POST_INSTALL_SCRIPT_FILE
"${CMAKE_CURRENT_SOURCE_DIR}/config/post"
CACHE STRING "Install script that will be copied in the %post section"
)
-set(${HICN_LIGHT}_RPM_PRE_UNINSTALL_SCRIPT_FILE
+set(${FACEMGR}_RPM_PRE_UNINSTALL_SCRIPT_FILE
"${CMAKE_CURRENT_SOURCE_DIR}/config/preun"
CACHE STRING "Install script that will be copied in the %post section"
)
diff --git a/ctrl/facemgr/config/facemgr.service b/ctrl/facemgr/config/facemgr.service
index 0f9e818ea..89d4f9283 100644
--- a/ctrl/facemgr/config/facemgr.service
+++ b/ctrl/facemgr/config/facemgr.service
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/config/postinst b/ctrl/facemgr/config/postinst
index 4113b0eca..7b2fd57fe 100755
--- a/ctrl/facemgr/config/postinst
+++ b/ctrl/facemgr/config/postinst
@@ -1,3 +1,5 @@
#!/bin/bash
-systemctl enable facemgr
+if pidof systemd; then
+ systemctl enable facemgr
+fi
diff --git a/ctrl/facemgr/config/prerm b/ctrl/facemgr/config/prerm
index b5c486ea5..8c0eadf0d 100755
--- a/ctrl/facemgr/config/prerm
+++ b/ctrl/facemgr/config/prerm
@@ -1,3 +1,5 @@
#!/bin/bash
-systemctl disable facemgr
+if pidof systemd; then
+ systemctl disable facemgr
+fi
diff --git a/ctrl/facemgr/config/preun b/ctrl/facemgr/config/preun
index b5c486ea5..8c0eadf0d 100755
--- a/ctrl/facemgr/config/preun
+++ b/ctrl/facemgr/config/preun
@@ -1,3 +1,5 @@
#!/bin/bash
-systemctl disable facemgr
+if pidof systemd; then
+ systemctl disable facemgr
+fi
diff --git a/ctrl/facemgr/examples/mobility/mobility.c b/ctrl/facemgr/examples/mobility/mobility.c
index 528951446..ae1d6dee3 100644
--- a/ctrl/facemgr/examples/mobility/mobility.c
+++ b/ctrl/facemgr/examples/mobility/mobility.c
@@ -7,82 +7,81 @@
* Test server using nc: nc -4kvul localhost 9533
*/
-#include <arpa/inet.h> // inet_ntop
-#include <errno.h> // EINTR,. ..
-#include <netinet/in.h> // INET_ADDRSTRLEN, INET6_ADDRSTRLEN
+#include <arpa/inet.h> // inet_ntop
+#include <errno.h> // EINTR,. ..
+#include <netinet/in.h> // INET_ADDRSTRLEN, INET6_ADDRSTRLEN
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
-#include <sys/un.h> // sockaddr_un
-#include <unistd.h> // fcntl
-#include <fcntl.h> // fcntl
+#include <sys/un.h> // sockaddr_un
+#include <unistd.h> // fcntl
+#include <fcntl.h> // fcntl
#define MS2US(x) (x * 1000)
/**
* \brief Main function
*/
-int main(int argc, char **argv)
-{
- int rc;
+int main(int argc, char **argv) {
+ int rc;
- if (argc != 4) {
- fprintf(stderr, "Usage: %s IP PORT INTERVAL\n", argv[0]);
- fprintf(stderr, "\n");
- fprintf(stderr, " IP Target hostname\n");
- fprintf(stderr, " PORT Target port\n");
- fprintf(stderr, " INTERVAL Interval between mobility events (in ms)\n");
- fprintf(stderr, "\n");
- exit(EXIT_FAILURE);
- }
+ if (argc != 4) {
+ fprintf(stderr, "Usage: %s IP PORT INTERVAL\n", argv[0]);
+ fprintf(stderr, "\n");
+ fprintf(stderr, " IP Target hostname\n");
+ fprintf(stderr, " PORT Target port\n");
+ fprintf(stderr, " INTERVAL Interval between mobility events (in ms)\n");
+ fprintf(stderr, "\n");
+ exit(EXIT_FAILURE);
+ }
- int interval = atoi(argv[3]);
+ int interval = atoi(argv[3]);
- int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if (fd < 0) {
- perror("socket");
- goto ERR_SOCKET;
- }
+ int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (fd < 0) {
+ perror("socket");
+ goto ERR_SOCKET;
+ }
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = inet_addr(argv[1]);
- addr.sin_port = htons(atoi(argv[2]));
+ struct sockaddr_in addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = inet_addr(argv[1]);
+ addr.sin_port = htons(atoi(argv[2]));
- if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
- perror("connect");
- goto ERR_CONNECT;
- }
+ if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+ perror("connect");
+ goto ERR_CONNECT;
+ }
- unsigned state = 0;
- char buf[1];
- for(;;) {
- usleep(MS2US(interval));
+ unsigned state = 0;
+ char buf[1];
+ for (;;) {
+ usleep(MS2US(interval));
- buf[0] = state;
- rc = send(fd, buf, 1, 0);
- if (rc < 0) {
- if (errno == ECONNREFUSED) {
- continue;
- }
- perror("send");
- goto ERR_SEND;
- }
-
- state = 1 - state;
+ buf[0] = state;
+ rc = send(fd, buf, 1, 0);
+ if (rc < 0) {
+ if (errno == ECONNREFUSED) {
+ continue;
+ }
+ perror("send");
+ goto ERR_SEND;
}
- close(fd);
+ state = 1 - state;
+ }
+
+ close(fd);
- exit(EXIT_SUCCESS);
+ exit(EXIT_SUCCESS);
ERR_SEND:
ERR_CONNECT:
- close(fd);
+ close(fd);
ERR_SOCKET:
- exit(EXIT_FAILURE);
+ exit(EXIT_FAILURE);
}
diff --git a/ctrl/facemgr/examples/updowncli/updowncli.c b/ctrl/facemgr/examples/updowncli/updowncli.c
index 4f5a14165..34ec3fb97 100644
--- a/ctrl/facemgr/examples/updowncli/updowncli.c
+++ b/ctrl/facemgr/examples/updowncli/updowncli.c
@@ -5,6 +5,8 @@
#include <stdlib.h>
#include <unistd.h>
+#include <hicn/util/sstrncpy.h>
+
/**
* \brief Default unix socket path (the leading \0 means using the abstract
* namespace instead of the filesystem).
@@ -12,46 +14,46 @@
#define UNIX_PATH "\0updownsrv"
int main() {
- struct sockaddr_un addr;
- char buf[100];
- int fd,rc;
-
- char * socket_path = UNIX_PATH;
-
- if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
- perror("socket error");
- exit(-1);
- }
-
- memset(&addr, 0, sizeof(addr));
- addr.sun_family = AF_UNIX;
- if (*socket_path == '\0') {
- *addr.sun_path = '\0';
- strncpy(addr.sun_path+1, socket_path+1, sizeof(addr.sun_path)-2);
- } else {
- strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1);
- }
-
- if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
- perror("connect error");
- exit(-1);
- }
-
- printf("Waiting for server data...\n");
- while( (rc=read(fd, buf, sizeof(buf))) > 0) {
- assert(rc == 1);
- switch(buf[0]) {
- case '\0':
- printf("WiFi\n");
- break;
- case '\1':
- printf("LTE\n");
- break;
- default:
- printf("Unknown\n");
- break;
- }
+ struct sockaddr_un addr;
+ char buf[100];
+ int fd, rc;
+
+ char* socket_path = UNIX_PATH;
+
+ if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
+ perror("socket error");
+ exit(-1);
+ }
+
+ memset(&addr, 0, sizeof(addr));
+ addr.sun_family = AF_UNIX;
+ if (*socket_path == '\0') {
+ *addr.sun_path = '\0';
+ strcpy_s(addr.sun_path + 1, sizeof(addr.sun_path) - 2, socket_path + 1);
+ } else {
+ strcpy_s(addr.sun_path, sizeof(addr.sun_path) - 1, socket_path);
+ }
+
+ if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
+ perror("connect error");
+ exit(-1);
+ }
+
+ printf("Waiting for server data...\n");
+ while ((rc = read(fd, buf, sizeof(buf))) > 0) {
+ assert(rc == 1);
+ switch (buf[0]) {
+ case '\0':
+ printf("WiFi\n");
+ break;
+ case '\1':
+ printf("LTE\n");
+ break;
+ default:
+ printf("Unknown\n");
+ break;
}
+ }
- return 0;
+ return 0;
}
diff --git a/ctrl/facemgr/examples/updownsrv/updownsrv.c b/ctrl/facemgr/examples/updownsrv/updownsrv.c
index 3aba3cfd0..57661d427 100644
--- a/ctrl/facemgr/examples/updownsrv/updownsrv.c
+++ b/ctrl/facemgr/examples/updownsrv/updownsrv.c
@@ -5,19 +5,20 @@
* using unix domains that sets a face up and down.
*/
-#include <arpa/inet.h> // inet_ntop
-#include <errno.h> // EINTR,. ..
-#include <netinet/in.h> // INET_ADDRSTRLEN, INET6_ADDRSTRLEN
+#include <arpa/inet.h> // inet_ntop
+#include <errno.h> // EINTR,. ..
+#include <netinet/in.h> // INET_ADDRSTRLEN, INET6_ADDRSTRLEN
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
-#include <sys/un.h> // sockaddr_un
-#include <unistd.h> // fcntl
-#include <fcntl.h> // fcntl
+#include <sys/un.h> // sockaddr_un
+#include <unistd.h> // fcntl
+#include <fcntl.h> // fcntl
+#include <hicn/util/sstrncpy.h>
/**
* \brief Default unix socket path (the leading \0 means using the abstract
@@ -40,199 +41,190 @@
*/
#define LISTEN_BACKLOG MAX_CLIENTS
-
/**
* \brief Creates a unix server socket
* \param [in] path - string representing the path on which to listen for
* connections
* \return int - fd associated to the socket
*/
-int
-create_unix_server(char * path)
-{
- struct sockaddr_un addr;
- int fd;
-
- fd = socket(AF_UNIX, SOCK_STREAM, 0);
- if (fd == -1) {
- perror("socket error");
- return -1;
- }
-
- if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
- perror("fcntl");
- return -1;
- }
-
- memset(&addr, 0, sizeof(addr));
- addr.sun_family = AF_UNIX;
- if (*path == '\0') {
- *addr.sun_path = '\0';
- strncpy(addr.sun_path+1, path+1, sizeof(addr.sun_path)-2);
- } else {
- strncpy(addr.sun_path, path, sizeof(addr.sun_path)-1);
- unlink(path);
- }
-
- if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
- perror("bind error");
- return -1;
- }
-
- if (listen(fd, LISTEN_BACKLOG) == -1) {
- perror("listen error");
- return -1;
- }
-
- return fd;
+int create_unix_server(char* path) {
+ struct sockaddr_un addr;
+ int fd;
+
+ fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (fd == -1) {
+ perror("socket error");
+ return -1;
+ }
+
+ if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
+ perror("fcntl");
+ return -1;
+ }
+
+ memset(&addr, 0, sizeof(addr));
+ addr.sun_family = AF_UNIX;
+ if (*path == '\0') {
+ *addr.sun_path = '\0';
+ strcpy_s(addr.sun_path + 1, sizeof(addr.sun_path) - 2, path + 1);
+ } else {
+ strcpy_s(addr.sun_path, sizeof(addr.sun_path) - 1, path);
+ unlink(path);
+ }
+
+ if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
+ perror("bind error");
+ return -1;
+ }
+
+ if (listen(fd, LISTEN_BACKLOG) == -1) {
+ perror("listen error");
+ return -1;
+ }
+
+ return fd;
}
-
/**
* \brief Main function
*/
int main() {
- int fd, tfd;
- int rc;
-
- /* Alternating state of the server : 0 / 1 */
- unsigned state = 0;
-
- /*
- * This server has to send a signal to all connected clients at periodic
- * intervals. Since we don't expect a large number of connected clients for
- * such a simple program, we simply use a statically allocated array.
- */
- int clients[MAX_CLIENTS];
- size_t num_clients = 0;
-
- fd_set active_fd_set, read_fd_set;
- FD_ZERO (&active_fd_set);
-
- /* Create listening unix socket */
- fd = create_unix_server(UNIX_PATH);
- if (fd < 0)
- exit(EXIT_FAILURE);
-
- if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
- perror("fcntl");
- exit(EXIT_FAILURE);
- }
-
- FD_SET (fd, &active_fd_set);
-
- /* Create timer */
- tfd = timerfd_create(CLOCK_MONOTONIC, 0);
- if (tfd == -1) {
- perror("timer error");
- exit(EXIT_FAILURE);
+ int fd, tfd;
+ int rc;
+
+ /* Alternating state of the server : 0 / 1 */
+ unsigned state = 0;
+
+ /*
+ * This server has to send a signal to all connected clients at periodic
+ * intervals. Since we don't expect a large number of connected clients for
+ * such a simple program, we simply use a statically allocated array.
+ */
+ int clients[MAX_CLIENTS];
+ size_t num_clients = 0;
+
+ fd_set active_fd_set, read_fd_set;
+ FD_ZERO(&active_fd_set);
+
+ /* Create listening unix socket */
+ fd = create_unix_server(UNIX_PATH);
+ if (fd < 0) exit(EXIT_FAILURE);
+
+ if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
+ perror("fcntl");
+ exit(EXIT_FAILURE);
+ }
+
+ FD_SET(fd, &active_fd_set);
+
+ /* Create timer */
+ tfd = timerfd_create(CLOCK_MONOTONIC, 0);
+ if (tfd == -1) {
+ perror("timer error");
+ exit(EXIT_FAILURE);
+ }
+
+ if (fcntl(tfd, F_SETFL, O_NONBLOCK) < 0) {
+ perror("fcntl");
+ exit(EXIT_FAILURE);
+ }
+
+ FD_SET(tfd, &active_fd_set);
+
+ struct itimerspec ts = {.it_interval =
+ {
+ .tv_sec = DEFAULT_INTERVAL_SEC,
+ .tv_nsec = DEFAULT_INTERVAL_NSEC,
+ },
+ .it_value = {
+ .tv_sec = DEFAULT_INTERVAL_SEC,
+ .tv_nsec = DEFAULT_INTERVAL_NSEC,
+ }};
+ rc = timerfd_settime(tfd, 0, &ts, NULL);
+ if (rc == -1) {
+ perror("timerfd_settime");
+ exit(EXIT_FAILURE);
+ }
+
+ printf("Waiting for clients...\n");
+
+ for (;;) {
+ /* Block until input arrives on one or more active sockets. */
+ read_fd_set = active_fd_set;
+ rc = select(FD_SETSIZE, &read_fd_set, NULL, NULL, NULL);
+ if (rc < 0) {
+ if (rc == EINTR) break;
+ perror("select");
+ exit(EXIT_FAILURE);
}
- if (fcntl(tfd, F_SETFL, O_NONBLOCK) < 0) {
- perror("fcntl");
- exit(EXIT_FAILURE);
- }
-
- FD_SET (tfd, &active_fd_set);
-
- struct itimerspec ts = {
- .it_interval = {
- .tv_sec = DEFAULT_INTERVAL_SEC,
- .tv_nsec = DEFAULT_INTERVAL_NSEC,
- },
- .it_value = {
- .tv_sec = DEFAULT_INTERVAL_SEC,
- .tv_nsec = DEFAULT_INTERVAL_NSEC,
- }
- };
- rc = timerfd_settime(tfd, 0, &ts, NULL);
- if (rc == -1) {
- perror("timerfd_settime");
- exit(EXIT_FAILURE);
- }
-
- printf("Waiting for clients...\n");
-
- for(;;) {
- /* Block until input arrives on one or more active sockets. */
- read_fd_set = active_fd_set;
- rc = select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL);
- if (rc < 0) {
- if (rc == EINTR)
- break;
- perror("select");
- exit (EXIT_FAILURE);
+ /* Service all the sockets with input pending. */
+ for (int i = 0; i < FD_SETSIZE; ++i) {
+ if (!FD_ISSET(i, &read_fd_set)) continue;
+ if (i == fd) {
+ /* Connection request on original socket. */
+ int client_fd = accept(fd, NULL, NULL);
+ if (client_fd < 0) {
+ perror("accept");
+ continue;
}
- /* Service all the sockets with input pending. */
- for (int i = 0; i < FD_SETSIZE; ++i) {
- if (!FD_ISSET (i, &read_fd_set))
- continue;
- if (i == fd) {
- /* Connection request on original socket. */
- int client_fd = accept(fd, NULL, NULL);
- if (client_fd < 0) {
- perror("accept");
- continue;
- }
-
- fprintf(stderr, "Server: connect from new client\n");
- clients[num_clients++] = client_fd;
- FD_SET(client_fd, &active_fd_set);
- } else if (i == tfd) {
- /* Timer event */
- uint64_t res;
-
- read(tfd, &res, sizeof(res));
-// while (read(fd, &missed, sizeof(missed)) > 0)
-// ;
- for (unsigned j = 0; j < num_clients; j++) {
- write(clients[j], state ? "\1" : "\0", 1);
- }
- printf("STATE=%d\n", state);
- state = 1 - state;
- } else {
- char buf[1024];
- rc = read(i, buf, sizeof(buf));
- /* Client event : we close the connection on any event... */
- for (unsigned j = 0; j < num_clients; j++) {
- if (i == clients[j]) {
- clients[j] = clients[num_clients--];
- break;
- }
- }
- close(i);
- FD_CLR(i, &active_fd_set);
- }
+ fprintf(stderr, "Server: connect from new client\n");
+ clients[num_clients++] = client_fd;
+ FD_SET(client_fd, &active_fd_set);
+ } else if (i == tfd) {
+ /* Timer event */
+ uint64_t res;
+
+ read(tfd, &res, sizeof(res));
+ // while (read(fd, &missed, sizeof(missed)) > 0)
+ // ;
+ for (unsigned j = 0; j < num_clients; j++) {
+ write(clients[j], state ? "\1" : "\0", 1);
}
-
- }
-
- int ret = EXIT_SUCCESS;
-
- /* Close all active client connections */
- for (unsigned i = 0; i < num_clients; i++) {
- rc = close(clients[i]);
- if (rc == -1) {
- perror("close");
- ret = EXIT_FAILURE;
+ printf("STATE=%d\n", state);
+ state = 1 - state;
+ } else {
+ char buf[1024];
+ rc = read(i, buf, sizeof(buf));
+ /* Client event : we close the connection on any event... */
+ for (unsigned j = 0; j < num_clients; j++) {
+ if (i == clients[j]) {
+ clients[j] = clients[num_clients--];
+ break;
+ }
}
+ close(i);
+ FD_CLR(i, &active_fd_set);
+ }
}
+ }
- /* Close server */
- rc = close(fd);
- if (rc == -1) {
- perror("close");
- ret = EXIT_FAILURE;
- }
+ int ret = EXIT_SUCCESS;
- /* Terminate timer */
- ts.it_value.tv_sec = 0;
- rc = timerfd_settime(tfd, 0, &ts, NULL);
+ /* Close all active client connections */
+ for (unsigned i = 0; i < num_clients; i++) {
+ rc = close(clients[i]);
if (rc == -1) {
- perror("timerfd_settime");
- exit(EXIT_FAILURE);
+ perror("close");
+ ret = EXIT_FAILURE;
}
-
- exit(ret);
+ }
+
+ /* Close server */
+ rc = close(fd);
+ if (rc == -1) {
+ perror("close");
+ ret = EXIT_FAILURE;
+ }
+
+ /* Terminate timer */
+ ts.it_value.tv_sec = 0;
+ rc = timerfd_settime(tfd, 0, &ts, NULL);
+ if (rc == -1) {
+ perror("timerfd_settime");
+ exit(EXIT_FAILURE);
+ }
+
+ exit(ret);
}
diff --git a/ctrl/facemgr/includes/CMakeLists.txt b/ctrl/facemgr/includes/CMakeLists.txt
index 065a9022f..bfbf65717 100644
--- a/ctrl/facemgr/includes/CMakeLists.txt
+++ b/ctrl/facemgr/includes/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,15 +11,20 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# XXX
-
+##############################################################
+# Public headers directory
+##############################################################
set(LIBFACEMGR_INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR} ""
+ ${CMAKE_CURRENT_SOURCE_DIR}
CACHE INTERNAL
"" FORCE
)
-if (${CMAKE_SYSTEM_NAME} STREQUAL "Android")
+
+##############################################################
+# To install header files
+##############################################################
+if (${CMAKE_SYSTEM_NAME} STREQUAL "Android")
set(TO_INSTALL_HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/facemgr.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/facemgr/api.h
@@ -28,9 +33,7 @@ if (${CMAKE_SYSTEM_NAME} STREQUAL "Android")
${CMAKE_CURRENT_SOURCE_DIR}/hicn/facemgr/loop.h
PARENT_SCOPE
)
-
else ()
-
set(TO_INSTALL_HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/facemgr.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/facemgr/api.h
@@ -39,7 +42,4 @@ else ()
${CMAKE_CURRENT_SOURCE_DIR}/hicn/facemgr/loop.h
PARENT_SCOPE
)
-
endif ()
-
-
diff --git a/ctrl/facemgr/includes/facemgr.h b/ctrl/facemgr/includes/facemgr.h
index b3b482ccc..b62bb88ce 100644
--- a/ctrl/facemgr/includes/facemgr.h
+++ b/ctrl/facemgr/includes/facemgr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,4 +26,3 @@
#include <hicn/facemgr/loop.h>
#endif /* HICN_FACEMGR_H */
-
diff --git a/ctrl/facemgr/includes/hicn/facemgr.h b/ctrl/facemgr/includes/hicn/facemgr.h
index 4165a8fc4..83a76cc08 100644
--- a/ctrl/facemgr/includes/hicn/facemgr.h
+++ b/ctrl/facemgr/includes/hicn/facemgr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,4 +24,3 @@
#include <hicn/facemgr/api.h>
#endif /* HICN_FACEMGR_H */
-
diff --git a/ctrl/facemgr/includes/hicn/facemgr/api.h b/ctrl/facemgr/includes/hicn/facemgr/api.h
index e9d25f132..582be0e78 100644
--- a/ctrl/facemgr/includes/hicn/facemgr/api.h
+++ b/ctrl/facemgr/includes/hicn/facemgr/api.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -30,40 +30,38 @@
/* facemgr callbacks */
typedef enum {
- FACEMGR_CB_TYPE_REGISTER_FD,
- FACEMGR_CB_TYPE_UNREGISTER_FD,
- FACEMGR_CB_TYPE_REGISTER_TIMER,
- FACEMGR_CB_TYPE_UNREGISTER_TIMER,
+ FACEMGR_CB_TYPE_REGISTER_FD,
+ FACEMGR_CB_TYPE_UNREGISTER_FD,
+ FACEMGR_CB_TYPE_REGISTER_TIMER,
+ FACEMGR_CB_TYPE_UNREGISTER_TIMER,
} facemgr_cb_type_t;
-typedef int (*facemgr_cb_t)(void * loop, facemgr_cb_type_t type, void * data);
-
+typedef int (*facemgr_cb_t)(void *loop, facemgr_cb_type_t type, void *data);
/*
* \brief Manual overlay settings (alternative to service discovery)
*/
typedef struct {
- uint16_t local_port;
- ip_address_t remote_addr;
- uint16_t remote_port;
+ uint16_t local_port;
+ hicn_ip_address_t remote_addr;
+ uint16_t remote_port;
} facemgr_overlay_setting_t;
-#define FACEMGR_OVERLAY_SETTING_EMPTY (facemgr_overlay_setting_t) { \
- .local_port = 0, \
- .remote_addr = IP_ADDRESS_EMPTY, \
- .remote_port = 0, \
-}
+#define FACEMGR_OVERLAY_SETTING_EMPTY \
+ (facemgr_overlay_setting_t) { \
+ .local_port = 0, .remote_addr = IP_ADDRESS_EMPTY, .remote_port = 0, \
+ }
typedef struct {
- facemgr_overlay_setting_t v4;
- facemgr_overlay_setting_t v6;
+ facemgr_overlay_setting_t v4;
+ facemgr_overlay_setting_t v6;
} facemgr_overlay_t;
-#define FACEMGR_OVERLAY_EMPTY (facemgr_overlay_t) { \
- .v4 = FACEMGR_OVERLAY_SETTING_EMPTY, \
- .v6 = FACEMGR_OVERLAY_SETTING_EMPTY, \
-}
+#define FACEMGR_OVERLAY_EMPTY \
+ (facemgr_overlay_t) { \
+ .v4 = FACEMGR_OVERLAY_SETTING_EMPTY, .v6 = FACEMGR_OVERLAY_SETTING_EMPTY, \
+ }
/*
* \brief Face manager context
@@ -72,24 +70,30 @@ typedef struct facemgr_s facemgr_t;
int facemgr_initialize(facemgr_t *);
int facemgr_finalize(facemgr_t *);
-facemgr_t * facemgr_create();
-facemgr_t * facemgr_create_with_config(facemgr_cfg_t * cfg);
+facemgr_t *facemgr_create();
+facemgr_t *facemgr_create_with_config(facemgr_cfg_t *cfg);
void facemgr_stop(facemgr_t *);
void facemgr_free(facemgr_t *);
+void facemgr_set_callback(facemgr_t *facemgr, void *callback_owner,
+ facemgr_cb_t callback);
-void facemgr_set_callback(facemgr_t * facemgr, void * callback_owner, facemgr_cb_t callback);
-
-int facemgr_set_config(facemgr_t * facemgr, facemgr_cfg_t * cfg);
-int facemgr_reset_config(facemgr_t * facemgr);
-int facemgr_bootstrap(facemgr_t * facemgr);
+int facemgr_set_config(facemgr_t *facemgr, facemgr_cfg_t *cfg);
+int facemgr_reset_config(facemgr_t *facemgr);
+int facemgr_bootstrap(facemgr_t *facemgr);
#ifdef __ANDROID__
-void facemgr_set_jvm(facemgr_t * facemgr, JavaVM *jvm);
+void facemgr_set_jvm(facemgr_t *facemgr, JavaVM *jvm);
+void facemgr_on_android_callback(facemgr_t *facemgr, const char *interface_name,
+ netdevice_type_t netdevice_type, bool up,
+ int family, const char *ip_address);
#endif /* __ANDROID__ */
-typedef int (*facemgr_list_facelets_cb_t)(const facemgr_t * facemgr, const facelet_t * facelet, void * user_data);
+typedef int (*facemgr_list_facelets_cb_t)(const facemgr_t *facemgr,
+ const facelet_t *facelet,
+ void *user_data);
-void facemgr_list_facelets(const facemgr_t * facemgr, facemgr_list_facelets_cb_t cb, void * user_data);
-int facemgr_list_facelets_json(const facemgr_t * facemgr, char ** buffer);
+void facemgr_list_facelets(const facemgr_t *facemgr,
+ facemgr_list_facelets_cb_t cb, void *user_data);
+int facemgr_list_facelets_json(const facemgr_t *facemgr, char **buffer);
#endif /* FACEMGR_H */
diff --git a/ctrl/facemgr/includes/hicn/facemgr/cfg.h b/ctrl/facemgr/includes/hicn/facemgr/cfg.h
index 84d63fe73..57d8f35bc 100644
--- a/ctrl/facemgr/includes/hicn/facemgr/cfg.h
+++ b/ctrl/facemgr/includes/hicn/facemgr/cfg.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,7 +20,7 @@
#ifndef FACEMGR_CFG_H
#define FACEMGR_CFG_H
-#include <hicn/ctrl/face.h>
+#include <hicn/face.h>
#include <hicn/facemgr/facelet.h>
#include <hicn/util/log.h>
@@ -38,68 +38,72 @@
#define FACEMGR_CFG_DEFAULT_IPV4 true
#define FACEMGR_CFG_DEFAULT_IPV6 false
-
-
typedef struct facemgr_cfg_s facemgr_cfg_t;
-facemgr_cfg_t * facemgr_cfg_create();
-void facemgr_cfg_free(facemgr_cfg_t * cfg);
-int facemgr_cfg_initialize(facemgr_cfg_t * cfg);
-int facemgr_cfg_finalize(facemgr_cfg_t * cfg);
-void facemgr_cfg_dump(facemgr_cfg_t * cfg);
+facemgr_cfg_t* facemgr_cfg_create();
+void facemgr_cfg_free(facemgr_cfg_t* cfg);
+int facemgr_cfg_initialize(facemgr_cfg_t* cfg);
+int facemgr_cfg_finalize(facemgr_cfg_t* cfg);
+void facemgr_cfg_dump(facemgr_cfg_t* cfg);
/* Rules */
typedef struct facemgr_cfg_rule_s facemgr_cfg_rule_t;
-facemgr_cfg_rule_t * facemgr_cfg_rule_create();
-void facemgr_cfg_rule_free(facemgr_cfg_rule_t * rule);
-int facemgr_cfg_rule_initialize(facemgr_cfg_rule_t * rule);
-int facemgr_cfg_rule_finalize(facemgr_cfg_rule_t * rule);
+facemgr_cfg_rule_t* facemgr_cfg_rule_create();
+void facemgr_cfg_rule_free(facemgr_cfg_rule_t* rule);
+int facemgr_cfg_rule_initialize(facemgr_cfg_rule_t* rule);
+int facemgr_cfg_rule_finalize(facemgr_cfg_rule_t* rule);
-int facemgr_cfg_rule_set_match(facemgr_cfg_rule_t * rule,
- const char * interface_name, netdevice_type_t interface_type);
+int facemgr_cfg_rule_set_match(facemgr_cfg_rule_t* rule,
+ const char* interface_name,
+ netdevice_type_t interface_type);
-int facemgr_cfg_rule_set_face_type(facemgr_cfg_rule_t * cfg_rule, facemgr_face_type_t * face_type);
-int facemgr_cfg_rule_unset_face_type(facemgr_cfg_rule_t * cfg_rule);
+int facemgr_cfg_rule_set_face_type(facemgr_cfg_rule_t* cfg_rule,
+ facemgr_face_type_t* face_type);
+int facemgr_cfg_rule_unset_face_type(facemgr_cfg_rule_t* cfg_rule);
-int facemgr_cfg_rule_set_discovery(facemgr_cfg_rule_t * cfg_rule, bool status);
-int facemgr_cfg_rule_unset_discovery(facemgr_cfg_rule_t * cfg_rule);
+int facemgr_cfg_rule_set_discovery(facemgr_cfg_rule_t* cfg_rule, bool status);
+int facemgr_cfg_rule_unset_discovery(facemgr_cfg_rule_t* cfg_rule);
-int facemgr_cfg_rule_set_ignore(facemgr_cfg_rule_t * cfg_rule, bool status);
-int facemgr_cfg_rule_unset_ignore(facemgr_cfg_rule_t * cfg_rule);
+int facemgr_cfg_rule_set_ignore(facemgr_cfg_rule_t* cfg_rule, bool status);
+int facemgr_cfg_rule_unset_ignore(facemgr_cfg_rule_t* cfg_rule);
-int facemgr_cfg_rule_set_ipv4(facemgr_cfg_rule_t * cfg_rule, bool status);
-int facemgr_cfg_rule_unset_ipv4(facemgr_cfg_rule_t * cfg_rule);
+int facemgr_cfg_rule_set_ipv4(facemgr_cfg_rule_t* cfg_rule, bool status);
+int facemgr_cfg_rule_unset_ipv4(facemgr_cfg_rule_t* cfg_rule);
-int facemgr_cfg_rule_set_ipv6(facemgr_cfg_rule_t * cfg_rule, bool status);
-int facemgr_cfg_rule_unset_ipv6(facemgr_cfg_rule_t * cfg_rule);
+int facemgr_cfg_rule_set_ipv6(facemgr_cfg_rule_t* cfg_rule, bool status);
+int facemgr_cfg_rule_unset_ipv6(facemgr_cfg_rule_t* cfg_rule);
-int facemgr_cfg_rule_set_overlay(facemgr_cfg_rule_t * rule, int family,
- ip_address_t * local_addr, uint16_t local_port,
- ip_address_t * remote_addr, uint16_t remote_port);
-int facemgr_rule_unset_overlay(facemgr_cfg_rule_t * rule, int family);
+int facemgr_cfg_rule_set_overlay(facemgr_cfg_rule_t* rule, int family,
+ hicn_ip_address_t* local_addr,
+ uint16_t local_port,
+ hicn_ip_address_t* remote_addr,
+ uint16_t remote_port);
+int facemgr_rule_unset_overlay(facemgr_cfg_rule_t* rule, int family);
/* General */
-int facemgr_cfg_set_face_type(facemgr_cfg_t * cfg, facemgr_face_type_t * face_type);
-int facemgr_cfg_unset_face_type(facemgr_cfg_t * cfg);
-int facemgr_cfg_set_discovery(facemgr_cfg_t * cfg, bool status);
-int facemgr_cfg_unset_discovery(facemgr_cfg_t * cfg);
-int facemgr_cfg_set_ipv4(facemgr_cfg_t * cfg, bool status);
-int facemgr_cfg_unset_ipv4(facemgr_cfg_t * cfg);
-int facemgr_cfg_set_ipv6(facemgr_cfg_t * cfg, bool status);
-int facemgr_cfg_unset_ipv6(facemgr_cfg_t * cfg);
-
-int facemgr_cfg_set_overlay(facemgr_cfg_t * cfg, int family,
- ip_address_t * local_addr, uint16_t local_port,
- ip_address_t * remote_addr, uint16_t remote_port);
-int facemgr_cfg_unset_overlay(facemgr_cfg_t * cfg, int family);
-
-
-int facemgr_cfg_add_rule(facemgr_cfg_t * cfg, facemgr_cfg_rule_t * rule);
-int facemgr_cfg_del_rule(facemgr_cfg_t * cfg, facemgr_cfg_rule_t * rule);
-int facemgr_cfg_get_rule(const facemgr_cfg_t * cfg, const char * interface_name,
- netdevice_type_t interface_type, facemgr_cfg_rule_t ** rule);
+int facemgr_cfg_set_face_type(facemgr_cfg_t* cfg,
+ facemgr_face_type_t* face_type);
+int facemgr_cfg_unset_face_type(facemgr_cfg_t* cfg);
+int facemgr_cfg_set_discovery(facemgr_cfg_t* cfg, bool status);
+int facemgr_cfg_unset_discovery(facemgr_cfg_t* cfg);
+int facemgr_cfg_set_ipv4(facemgr_cfg_t* cfg, bool status);
+int facemgr_cfg_unset_ipv4(facemgr_cfg_t* cfg);
+int facemgr_cfg_set_ipv6(facemgr_cfg_t* cfg, bool status);
+int facemgr_cfg_unset_ipv6(facemgr_cfg_t* cfg);
+
+int facemgr_cfg_set_overlay(facemgr_cfg_t* cfg, int family,
+ hicn_ip_address_t* local_addr, uint16_t local_port,
+ hicn_ip_address_t* remote_addr,
+ uint16_t remote_port);
+int facemgr_cfg_unset_overlay(facemgr_cfg_t* cfg, int family);
+
+int facemgr_cfg_add_rule(facemgr_cfg_t* cfg, facemgr_cfg_rule_t* rule);
+int facemgr_cfg_del_rule(facemgr_cfg_t* cfg, facemgr_cfg_rule_t* rule);
+int facemgr_cfg_get_rule(const facemgr_cfg_t* cfg, const char* interface_name,
+ netdevice_type_t interface_type,
+ facemgr_cfg_rule_t** rule);
/* Log */
@@ -107,57 +111,63 @@ int facemgr_cfg_get_rule(const facemgr_cfg_t * cfg, const char * interface_name,
* Query API
*
* Takes the overrides into account
- *
- * TODO : interface_types are currently not taken into account by this API
*/
-int facemgr_cfg_get_face_type(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- facemgr_face_type_t * face_type);
-int facemgr_cfg_get_discovery(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * discovery);
-int facemgr_cfg_get_ignore(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * ignore);
-int facemgr_cfg_get_ipv4(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * ipv4);
-int facemgr_cfg_get_ipv6(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * ipv6);
-int facemgr_cfg_get_overlay_local_addr(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, ip_address_t * addr);
-int facemgr_cfg_get_overlay_local_port(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, u16 * port);
-int facemgr_cfg_get_overlay_remote_addr(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, ip_address_t * addr);
-int facemgr_cfg_get_overlay_remote_port(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, u16 * port);
-
-int facemgr_cfg_rule_get(const facemgr_cfg_t * cfg, const netdevice_t netdevice,
- netdevice_type_t netdevice_type, facemgr_cfg_rule_t ** rule);
-int facemgr_cfg_rule_get_face_type(const facemgr_cfg_rule_t * cfg_rule, facemgr_face_type_t * face_type);
-int facemgr_cfg_rule_get_discovery(const facemgr_cfg_rule_t * cfg_rule, bool * status);
-int facemgr_cfg_rule_get_ignore(const facemgr_cfg_rule_t * cfg_rule, bool * status);
-int facemgr_cfg_rule_get_ipv4(const facemgr_cfg_rule_t * cfg_rule, bool * status);
-int facemgr_cfg_rule_get_ipv6(const facemgr_cfg_rule_t * cfg_rule, bool * status);
-int facemgr_cfg_rule_get_overlay_local_addr(const facemgr_cfg_rule_t * rule, int family,
- ip_address_t * addr);
-int facemgr_cfg_rule_get_overlay_local_port(const facemgr_cfg_rule_t * rule, int family,
- uint16_t * port);
-int facemgr_cfg_rule_get_overlay_remote_addr(const facemgr_cfg_rule_t * rule, int family,
- ip_address_t * addr);
-int facemgr_cfg_rule_get_overlay_remote_port(const facemgr_cfg_rule_t * rule, int family,
- uint16_t * port);
-
-int facemgr_cfg_add_static_facelet(facemgr_cfg_t * cfg, facelet_t * facelet);
-int facemgr_cfg_remove_static_facelet(facemgr_cfg_t * cfg, facelet_t * facelet,
- facelet_t ** removed_facelet);
-int facemgr_cfg_get_static_facelet_array(const facemgr_cfg_t * cfg, facelet_t *** array);
+int facemgr_cfg_get_face_type(const facemgr_cfg_t* cfg,
+ const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type,
+ facemgr_face_type_t* face_type);
+int facemgr_cfg_get_discovery(const facemgr_cfg_t* cfg,
+ const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type, bool* discovery);
+int facemgr_cfg_get_ignore(const facemgr_cfg_t* cfg,
+ const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type, bool* ignore);
+int facemgr_cfg_get_ipv4(const facemgr_cfg_t* cfg, const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type, bool* ipv4);
+int facemgr_cfg_get_ipv6(const facemgr_cfg_t* cfg, const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type, bool* ipv6);
+int facemgr_cfg_get_overlay_local_addr(const facemgr_cfg_t* cfg,
+ const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type,
+ int family, hicn_ip_address_t* addr);
+int facemgr_cfg_get_overlay_local_port(const facemgr_cfg_t* cfg,
+ const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type,
+ int family, u16* port);
+int facemgr_cfg_get_overlay_remote_addr(const facemgr_cfg_t* cfg,
+ const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type,
+ int family, hicn_ip_address_t* addr);
+int facemgr_cfg_get_overlay_remote_port(const facemgr_cfg_t* cfg,
+ const netdevice_t* netdevice,
+ netdevice_type_t netdevice_type,
+ int family, u16* port);
+
+int facemgr_cfg_rule_get(const facemgr_cfg_t* cfg, const netdevice_t netdevice,
+ netdevice_type_t netdevice_type,
+ facemgr_cfg_rule_t** rule);
+int facemgr_cfg_rule_get_face_type(const facemgr_cfg_rule_t* cfg_rule,
+ facemgr_face_type_t* face_type);
+int facemgr_cfg_rule_get_discovery(const facemgr_cfg_rule_t* cfg_rule,
+ bool* status);
+int facemgr_cfg_rule_get_ignore(const facemgr_cfg_rule_t* cfg_rule,
+ bool* status);
+int facemgr_cfg_rule_get_ipv4(const facemgr_cfg_rule_t* cfg_rule, bool* status);
+int facemgr_cfg_rule_get_ipv6(const facemgr_cfg_rule_t* cfg_rule, bool* status);
+int facemgr_cfg_rule_get_overlay_local_addr(const facemgr_cfg_rule_t* rule,
+ int family,
+ hicn_ip_address_t* addr);
+int facemgr_cfg_rule_get_overlay_local_port(const facemgr_cfg_rule_t* rule,
+ int family, uint16_t* port);
+int facemgr_cfg_rule_get_overlay_remote_addr(const facemgr_cfg_rule_t* rule,
+ int family,
+ hicn_ip_address_t* addr);
+int facemgr_cfg_rule_get_overlay_remote_port(const facemgr_cfg_rule_t* rule,
+ int family, uint16_t* port);
+
+int facemgr_cfg_add_static_facelet(facemgr_cfg_t* cfg, facelet_t* facelet);
+int facemgr_cfg_get_static_facelet_array(const facemgr_cfg_t* cfg,
+ facelet_t*** array);
#endif /* FACEMGR_CFG_H */
diff --git a/ctrl/facemgr/includes/hicn/facemgr/facelet.h b/ctrl/facemgr/includes/hicn/facemgr/facelet.h
index cfdc5540e..9b04832b3 100644
--- a/ctrl/facemgr/includes/hicn/facemgr/facelet.h
+++ b/ctrl/facemgr/includes/hicn/facemgr/facelet.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,7 +28,7 @@
#include <stdbool.h>
-#include <hicn/ctrl/face.h>
+#include <hicn/face.h>
#include <hicn/ctrl/route.h>
#define MAXSZ_FACELET 1024
@@ -36,111 +36,111 @@
#define FACELET_MAX_ERRORS 10
/* NOTE: Any test should be sufficient */
-#define IS_VALID_NETDEVICE(netdevice) ((netdevice.index != 0) && (netdevice.name[0] != '\0'))
+#define IS_VALID_NETDEVICE(netdevice) \
+ ((netdevice.index != 0) && (netdevice.name[0] != '\0'))
typedef struct facelet_s facelet_t;
/* Face type */
#define foreach_face_type_layer \
- _(UNDEFINED) \
- _(3) \
- _(4) \
- _(N)
+ _(UNDEFINED) \
+ _(3) \
+ _(4) \
+ _(N)
typedef enum {
-#define _(x) FACE_TYPE_LAYER_ ## x,
- foreach_face_type_layer
+#define _(x) FACE_TYPE_LAYER_##x,
+ foreach_face_type_layer
#undef _
} face_type_layer_t;
#define foreach_face_type_encap \
- _(UNDEFINED) \
- _(TCP) \
- _(UDP) \
- _(N)
+ _(UNDEFINED) \
+ _(TCP) \
+ _(UDP) \
+ _(N)
typedef enum {
-#define _(x) FACE_TYPE_ENCAP_ ## x,
- foreach_face_type_encap
+#define _(x) FACE_TYPE_ENCAP_##x,
+ foreach_face_type_encap
#undef _
} face_type_encap_t;
typedef struct {
- face_type_layer_t layer;
- face_type_encap_t encap;
+ face_type_layer_t layer;
+ face_type_encap_t encap;
} facemgr_face_type_t;
+extern const char* face_type_layer_str[];
+extern const char* face_type_encap_str[];
-extern const char * face_type_layer_str[];
-extern const char * face_type_encap_str[];
+#define FACEMGR_FACE_TYPE_STR(x) \
+ face_type_layer_str[x.layer], face_type_encap_str[x.encap]
-#define FACEMGR_FACE_TYPE_STR(x) \
- face_type_layer_str[x.layer], face_type_encap_str[x.encap]
+#define FACEMGR_FACE_TYPE_UNDEFINED \
+ (facemgr_face_type_t) { \
+ .layer = FACE_TYPE_LAYER_UNDEFINED, .encap = FACE_TYPE_ENCAP_UNDEFINED, \
+ }
-#define FACEMGR_FACE_TYPE_UNDEFINED (facemgr_face_type_t) { \
- .layer = FACE_TYPE_LAYER_UNDEFINED, \
- .encap = FACE_TYPE_ENCAP_UNDEFINED, \
-}
+#define FACEMGR_FACE_TYPE_NATIVE_UDP \
+ (facemgr_face_type_t) { \
+ .layer = FACE_TYPE_LAYER_3, .encap = FACE_TYPE_ENCAP_UDP, \
+ }
-#define FACEMGR_FACE_TYPE_NATIVE_UDP (facemgr_face_type_t) { \
- .layer = FACE_TYPE_LAYER_3, \
- .encap = FACE_TYPE_ENCAP_UDP, \
-}
+#define FACEMGR_FACE_TYPE_NATIVE_TCP \
+ (facemgr_face_type_t) { \
+ .layer = FACE_TYPE_LAYER_3, .encap = FACE_TYPE_ENCAP_TCP, \
+ }
-#define FACEMGR_FACE_TYPE_NATIVE_TCP (facemgr_face_type_t) { \
- .layer = FACE_TYPE_LAYER_3, \
- .encap = FACE_TYPE_ENCAP_TCP, \
-}
+#define FACEMGR_FACE_TYPE_OVERLAY_UDP \
+ (facemgr_face_type_t) { \
+ .layer = FACE_TYPE_LAYER_4, .encap = FACE_TYPE_ENCAP_UDP, \
+ }
-#define FACEMGR_FACE_TYPE_OVERLAY_UDP (facemgr_face_type_t) { \
- .layer = FACE_TYPE_LAYER_4, \
- .encap = FACE_TYPE_ENCAP_UDP, \
-}
-
-#define FACEMGR_FACE_TYPE_OVERLAY_TCP (facemgr_face_type_t) { \
- .layer = FACE_TYPE_LAYER_4, \
- .encap = FACE_TYPE_ENCAP_TCP, \
-}
+#define FACEMGR_FACE_TYPE_OVERLAY_TCP \
+ (facemgr_face_type_t) { \
+ .layer = FACE_TYPE_LAYER_4, .encap = FACE_TYPE_ENCAP_TCP, \
+ }
/* Facelet status */
-#define foreach_facelet_status \
- _(UNDEFINED) \
- _(DOWN) \
- _(UNCERTAIN) \
- _(INCOMPLETE) \
- _(CREATE) \
- _(CLEAN) \
- _(IGNORED) \
- _(UPDATE) \
- _(DELETE) \
- _(DELETED) \
- _(N)
+#define foreach_facelet_status \
+ _(UNDEFINED) \
+ _(DOWN) \
+ _(UNCERTAIN) \
+ _(INCOMPLETE) \
+ _(CREATE) \
+ _(CLEAN) \
+ _(IGNORED) \
+ _(UPDATE) \
+ _(DELETE) \
+ _(DELETED) \
+ _(N)
typedef enum {
-#define _(x) FACELET_STATUS_ ## x,
- foreach_facelet_status
+#define _(x) FACELET_STATUS_##x,
+ foreach_facelet_status
#undef _
} facelet_status_t;
-extern const char * facelet_status_str[];
+extern const char* facelet_status_str[];
/* Facelet error reason */
-#define foreach_facelet_error_reason \
- _(UNDEFINED) \
- _(UNSPECIFIED_ERROR) \
- _(FORWARDER_OFFLINE) \
- _(PERMISSION_DENIED) \
- _(INTERNAL_ERROR) \
- _(N)
+#define foreach_facelet_error_reason \
+ _(UNDEFINED) \
+ _(UNSPECIFIED_ERROR) \
+ _(FORWARDER_OFFLINE) \
+ _(PERMISSION_DENIED) \
+ _(INTERNAL_ERROR) \
+ _(N)
typedef enum {
-#define _(x) FACELET_ERROR_REASON_ ## x,
- foreach_facelet_error_reason
+#define _(x) FACELET_ERROR_REASON_##x,
+ foreach_facelet_error_reason
#undef _
} facelet_error_reason_t;
-extern const char * facelet_error_reason_str[];
+extern const char* facelet_error_reason_str[];
/* Facelet attribute status */
@@ -148,62 +148,48 @@ extern const char * facelet_error_reason_str[];
* We expect an attribute in the cache to be able to take any value but
* UNDEFINED and N, which facelet events should either be UNSET or CLEAN
*/
-#define foreach_facelet_attr_status \
- _(UNDEFINED, '?') \
- _(UNSET, 'X') \
- _(CLEAN, ' ') \
- _(DIRTY, '*') \
- _(PENDING, 'P') \
- _(CONFLICT, '!') \
- _(N, '-')
+#define foreach_facelet_attr_status \
+ _(UNDEFINED, '?') \
+ _(UNSET, 'X') \
+ _(CLEAN, ' ') \
+ _(DIRTY, '*') \
+ _(PENDING, 'P') \
+ _(CONFLICT, '!') \
+ _(N, '-')
typedef enum {
-#define _(x, y) FACELET_ATTR_STATUS_ ## x,
- foreach_facelet_attr_status
+#define _(x, y) FACELET_ATTR_STATUS_##x,
+ foreach_facelet_attr_status
#undef _
} facelet_attr_status_t;
-extern const char * facelet_attr_status_str[];
-extern const char * facelet_attr_status_str_short[];
+extern const char* facelet_attr_status_str[];
+extern const char* facelet_attr_status_str_short[];
/* Facelet attribute */
-#ifdef WITH_POLICY
-#define foreach_facelet_attr \
- _(netdevice_type_t, netdevice_type) \
- _(netdevice_t, netdevice) \
- _(int, family) \
- _(ip_address_t, local_addr) \
- _(u16, local_port) \
- _(ip_address_t, remote_addr) \
- _(u16, remote_port) \
- _(face_state_t, admin_state) \
- _(face_state_t, state) \
- _(u32, priority) \
- _(facemgr_face_type_t, face_type)
-#else
-#define foreach_facelet_attr \
- _(netdevice_type_t, netdevice_type) \
- _(netdevice_t, netdevice) \
- _(int, family) \
- _(ip_address_t, local_addr) \
- _(u16, local_port) \
- _(ip_address_t, remote_addr) \
- _(u16, remote_port) \
- _(face_state_t, admin_state) \
- _(face_state_t, state) \
- _(facemgr_face_type_t, face_type)
-#endif /* WITH_POLICY */
-
-#define foreach_facelet_event \
- _(UNDEFINED) \
- _(GET) \
- _(CREATE) \
- _(UPDATE) \
- _(DELETE) \
- _(SET_UP) \
- _(SET_DOWN) \
- _(N)
+#define foreach_facelet_attr \
+ _(netdevice_type_t, netdevice_type) \
+ _(netdevice_t, netdevice) \
+ _(int, family) \
+ _(hicn_ip_address_t, local_addr) \
+ _(u16, local_port) \
+ _(hicn_ip_address_t, remote_addr) \
+ _(u16, remote_port) \
+ _(face_state_t, admin_state) \
+ _(face_state_t, state) \
+ _(u32, priority) \
+ _(facemgr_face_type_t, face_type)
+
+#define foreach_facelet_event \
+ _(UNDEFINED) \
+ _(GET) \
+ _(CREATE) \
+ _(UPDATE) \
+ _(DELETE) \
+ _(SET_UP) \
+ _(SET_DOWN) \
+ _(N)
#define MAXSZ_EVENT__ 10
#define MAXSZ_EVENT_ MAXSZ_EVENT_ + 1
@@ -212,37 +198,37 @@ extern const char * facelet_attr_status_str_short[];
* \brief Enumeration of the possible types of event
*/
typedef enum {
-#define _(x) FACELET_EVENT_ ## x,
-foreach_facelet_event
+#define _(x) FACELET_EVENT_##x,
+ foreach_facelet_event
#undef _
} facelet_event_t;
-extern const char * facelet_event_str[];
+extern const char* facelet_event_str[];
/**
* \brief Create a facelet.
*/
-facelet_t * facelet_create();
+facelet_t* facelet_create();
-facelet_t * facelet_create_from_netdevice(netdevice_t * netdevice);
+facelet_t* facelet_create_from_netdevice(netdevice_t* netdevice);
-unsigned facelet_get_id(facelet_t * facelet);
-void facelet_set_id(facelet_t * facelet, unsigned id);
+unsigned facelet_get_id(facelet_t* facelet);
+void facelet_set_id(facelet_t* facelet, unsigned id);
-int facelet_validate_face(const facelet_t * facelet);
+int facelet_validate_face(const facelet_t* facelet);
-facelet_t * facelet_create_from_face(face_t * face);
+facelet_t* facelet_create_from_face(face_t* face);
-void facelet_free(facelet_t * facelet);
+void facelet_free(facelet_t* facelet);
-facelet_t * facelet_dup(const facelet_t * current_facelet);
+facelet_t* facelet_dup(const facelet_t* current_facelet);
-int facelet_cmp(const facelet_t * f1, const facelet_t * f2);
+int facelet_cmp(const facelet_t* f1, const facelet_t* f2);
-bool facelet_equals(const facelet_t * facelet1, const facelet_t * facelet2);
+bool facelet_equals(const facelet_t* facelet1, const facelet_t* facelet2);
/* NOTE: only clean attributes are matched */
-bool facelet_match(const facelet_t * facelet, const facelet_t * facelet_match);
+bool facelet_match(const facelet_t* facelet, const facelet_t* facelet_match);
/**
* \brief Returns whether the specified facelet has all key attributes defined.
@@ -251,55 +237,58 @@ bool facelet_match(const facelet_t * facelet, const facelet_t * facelet_match);
* uniquely identify a facelet, otherwise it is a 'wildcard' facelet
* specification and might match several facelets.
*/
-bool facelet_has_key(const facelet_t * facelet);
+bool facelet_has_key(const facelet_t* facelet);
-#define FACELET_ACCESSORS_H(TYPE, NAME) \
-bool facelet_has_ ## NAME(const facelet_t * facelet); \
-facelet_attr_status_t facelet_get_ ## NAME ## _status(const facelet_t * facelet);\
-void facelet_set_ ## NAME ## _status(facelet_t * facelet, \
- facelet_attr_status_t status); \
-int facelet_get_ ## NAME(const facelet_t * facelet, TYPE * NAME); \
-int facelet_set_ ## NAME(facelet_t * facelet, TYPE NAME); \
-int facelet_unset_ ## NAME(facelet_t * facelet);
+#define FACELET_ACCESSORS_H(TYPE, NAME) \
+ bool facelet_has_##NAME(const facelet_t* facelet); \
+ facelet_attr_status_t facelet_get_##NAME##_status(const facelet_t* facelet); \
+ void facelet_set_##NAME##_status(facelet_t* facelet, \
+ facelet_attr_status_t status); \
+ int facelet_get_##NAME(const facelet_t* facelet, TYPE* NAME); \
+ int facelet_set_##NAME(facelet_t* facelet, TYPE NAME); \
+ int facelet_unset_##NAME(facelet_t* facelet);
#define _(TYPE, NAME) FACELET_ACCESSORS_H(TYPE, NAME)
foreach_facelet_attr
#undef _
-int facelet_get_face(const facelet_t * facelet, face_t ** pface);
+ int
+ facelet_get_face(const facelet_t* facelet, face_t** pface);
-int facelet_merge(facelet_t * facelet, facelet_t * facelet_to_merge);
+int facelet_merge(facelet_t* facelet, facelet_t* facelet_to_merge);
-facelet_status_t facelet_get_status(const facelet_t * facelet);
-void facelet_set_status(facelet_t * facelet, facelet_status_t status);
-void facelet_set_attr_clean(facelet_t * facelet);
+facelet_status_t facelet_get_status(const facelet_t* facelet);
+void facelet_set_status(facelet_t* facelet, facelet_status_t status);
+void facelet_set_attr_clean(facelet_t* facelet);
-void facelet_set_error(facelet_t * facelet, facelet_error_reason_t reason);
-void facelet_unset_error(facelet_t * facelet);
-bool facelet_get_error(const facelet_t * facelet);
+void facelet_set_error(facelet_t* facelet, facelet_error_reason_t reason);
+void facelet_unset_error(facelet_t* facelet);
+bool facelet_get_error(const facelet_t* facelet);
-void facelet_set_bj_done(facelet_t * facelet);
-void facelet_unset_bj_done(facelet_t * facelet);
-bool facelet_is_bj_done(const facelet_t * facelet);
-void facelet_set_au_done(facelet_t * facelet);
-bool facelet_is_au_done(const facelet_t * facelet);
+void facelet_set_bj_done(facelet_t* facelet);
+void facelet_unset_bj_done(facelet_t* facelet);
+bool facelet_is_bj_done(const facelet_t* facelet);
-facelet_event_t facelet_get_event(const facelet_t * facelet);
-void facelet_set_event(facelet_t * facelet, facelet_event_t event);
+facelet_event_t facelet_get_event(const facelet_t* facelet);
+void facelet_set_event(facelet_t* facelet, facelet_event_t event);
-int facelet_add_route(facelet_t * facelet, hicn_route_t * route);
-int facelet_remove_route(facelet_t * facelet, hicn_route_t * route, hicn_route_t ** route_removed);
-int facelet_clear_routes(facelet_t * facelet);
-int facelet_get_route_array(const facelet_t * facelet, hicn_route_t *** route_array);
+int facelet_add_route(facelet_t* facelet, hicn_route_t* route);
+int facelet_remove_route(facelet_t* facelet, hicn_route_t* route,
+ hicn_route_t** route_removed);
+int facelet_clear_routes(facelet_t* facelet);
+int facelet_get_route_array(const facelet_t* facelet,
+ hicn_route_t*** route_array);
-int facelet_snprintf(char * buf, size_t size, const facelet_t * facelet);
+int facelet_snprintf(char* buf, size_t size, const facelet_t* facelet);
-#define DUMP_FACELET(msg, facelet) do { \
- char buf[MAXSZ_FACELET]; \
- facelet_snprintf(buf, MAXSZ_FACELET, facelet); \
- DEBUG("%s : %s", msg, buf); \
-} while(0)
+#define DUMP_FACELET(msg, facelet) \
+ do { \
+ char buf[MAXSZ_FACELET]; \
+ facelet_snprintf(buf, MAXSZ_FACELET, facelet); \
+ DEBUG("%s : %s", msg, buf); \
+ } while (0)
-int facelet_snprintf_json(char * buf, size_t size, const facelet_t * facelet, int indent);
+int facelet_snprintf_json(char* buf, size_t size, const facelet_t* facelet,
+ int indent);
#endif /* FACEMGR_FACELET_H */
diff --git a/ctrl/facemgr/includes/hicn/facemgr/loop.h b/ctrl/facemgr/includes/hicn/facemgr/loop.h
index 752a3b365..3965a1f27 100644
--- a/ctrl/facemgr/includes/hicn/facemgr/loop.h
+++ b/ctrl/facemgr/includes/hicn/facemgr/loop.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,23 +25,21 @@
/* fd & timer callbacks */
-typedef int (*fd_callback_t)(void * owner, int fd, void * data);
+typedef int (*fd_callback_t)(void *owner, int fd, void *data);
typedef struct {
- int fd;
- void *owner;
- fd_callback_t callback;
- //int (*callback)(void * owner, int fd, void * data);
- void *data;
+ int fd;
+ void *owner;
+ fd_callback_t callback;
+ void *data;
} fd_callback_data_t;
/* timer callbacks */
typedef struct {
- unsigned delay_ms;
- void *owner;
- fd_callback_t callback;
- //int (*callback)(void * owner, int fd, void * data);
- void *data;
+ unsigned delay_ms;
+ void *owner;
+ fd_callback_t callback;
+ void *data;
} timer_callback_data_t;
/* loop */
@@ -52,33 +50,32 @@ typedef struct loop_s loop_t;
* \brief Creates a main loop
* \return Pointer to the newly created loop, or NULL in case of error
*/
-loop_t * loop_create();
+loop_t *loop_create();
/**
* \brief Releases a loop instance and frees all associated memory
* \param [in] loop - Pointer to the loop instance to free
*/
-void loop_free(loop_t * loop);
+void loop_free(loop_t *loop);
/**
* \brief Runs the loop instance to process events
* \param [in] loop - Pointer to the loop instance
* \return 0 if successful, -1 otherwise
*/
-int loop_dispatch(loop_t * loop);
+int loop_dispatch(loop_t *loop);
/**
* \brief Terminates the dispatching of events
* \param [in] loop - Pointer to the loop instance
*/
-int loop_undispatch(loop_t * loop);
+int loop_undispatch(loop_t *loop);
/**
* \brief Breaks out of the loop
* \param [in] loop - Pointer to the loop instance
*/
-void loop_break(loop_t * loop);
-
+void loop_break(loop_t *loop);
/**
* \brief Callback for loop helpers
@@ -86,6 +83,6 @@ void loop_break(loop_t * loop);
* \param [in] type - Type of service to be requested
* \param [in] data - Service specific data
*/
-int loop_callback(loop_t * loop, facemgr_cb_type_t type, void * data);
+int loop_callback(loop_t *loop, facemgr_cb_type_t type, void *data);
#endif /* FACEMGR_LOOP_H */
diff --git a/ctrl/facemgr/src/CMakeLists.txt b/ctrl/facemgr/src/CMakeLists.txt
index cf5606e04..87938fb57 100644
--- a/ctrl/facemgr/src/CMakeLists.txt
+++ b/ctrl/facemgr/src/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -12,130 +12,157 @@
# limitations under the License.
if(UNIX AND NOT APPLE)
- set(LINUX TRUE)
+ set(LINUX TRUE)
endif()
-set(COMPILER_DEFINITIONS
- "-DWITH_POLICY"
-)
+##############################################################
+# Sources
+##############################################################
set(HEADER_FILES
- common.h
- error.h
- facelet_array.h
- interface.h
- loop.h
+ common.h
+ error.h
+ facelet_array.h
+ interface.h
+ loop.h
)
set(SOURCE_FILES
- api.c
- cfg.c
- cfg_file.c
- error.c
- facelet.c
- facelet_array.c
- interface.c
+ api.c
+ cfg.c
+ cfg_file.c
+ error.c
+ facelet.c
+ facelet_array.c
+ interface.c
)
if(APPLE)
-set(SOURCE_FILES
+ set(SOURCE_FILES
${SOURCE_FILES}
loop_dispatcher.c
-)
+ )
endif()
if (LINUX)
-set(SOURCE_FILES
+ set(SOURCE_FILES
${SOURCE_FILES}
loop_libevent.c
-)
+ )
endif()
+add_subdirectory(interfaces)
+
+
+##############################################################
+# Include directories
+##############################################################
set(INCLUDE_DIRS
- ./
- ../includes/
- ${HICN_INCLUDE_DIRS}
- ${LIBHICNCTRL_INCLUDE_DIRS}
- ${CONFIG_INCLUDE_DIR}
- ${LIBEVENT_INCLUDE_DIR}
+ PRIVATE ./
+ PRIVATE ${CONFIG_INCLUDE_DIR}
+ PRIVATE ${LIBEVENT_INCLUDE_DIR}
+ PUBLIC
+ $<BUILD_INTERFACE:${LIBFACEMGR_INCLUDE_DIRS}>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
+
+##############################################################
+# Libraries to link
+##############################################################
set(LIBRARIES
- m
- ${HICN_LIBRARIES}
- ${LIBHICNCTRL_LIBRARIES}
- ${LIBCONFIG_LIBRARIES}
- ${LIBEVENT_LIBRARY}
+ PUBLIC ${HICN_LIBRARIES}
+ PUBLIC ${LIBHICNCTRL_LIBRARIES}
+ PRIVATE m
+ PRIVATE ${LIBCONFIG_LIBRARIES}
+ PRIVATE ${LIBEVENT_LIBRARY}
)
-set(FACEMGR_LIBRARY_LIST "${LIBCONFIG_LIBRARIES};${LIBEVENT_LIBRARY}" CACHE INTERNAL "FACEMGR_LIBRARY_LIST")
+if(WITH_THREAD)
+ set(LIBRARIES
+ ${LIBRARIES}
+ "pthread"
+ "event_pthreads"
+ )
+ set(COMPILER_DEFINITIONS
+ ${COMPILER_DEFINITIONS}
+ "-DWITH_THREAD"
+ )
+endif()
-add_subdirectory(interfaces)
+##############################################################
+# Compiler definitions
+##############################################################
if(WITH_THREAD)
- set(LIBRARIES
- ${LIBRARIES}
- "pthread"
- "event_pthreads"
- )
- set(COMPILER_DEFINITIONS
- ${COMPILER_DEFINITIONS}
- "-DWITH_THREAD"
- )
+ list(APPEND COMPILER_DEFINITIONS
+ "-DWITH_THREAD"
+ )
endif()
if(WITH_EXAMPLE_DUMMY)
- set(COMPILER_DEFINITIONS
- ${COMPILER_DEFINITIONS}
- "-DWITH_EXAMPLE_DUMMY"
- )
+ list(APPEND COMPILER_DEFINITIONS
+ "-DWITH_EXAMPLE_DUMMY"
+ )
endif()
if(WITH_EXAMPLE_UPDOWN)
- set(COMPILER_DEFINITIONS
- ${COMPILER_DEFINITIONS}
- "-DWITH_EXAMPLE_UPDOWN"
- )
+ list(APPEND COMPILER_DEFINITIONS
+ "-DWITH_EXAMPLE_UPDOWN"
+ )
endif()
+
+##############################################################
+# Compiler options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Build type
+##############################################################
if (DISABLE_SHARED_LIBRARIES)
- build_library(${LIBFACEMGR}
- STATIC
- SOURCES ${SOURCE_FILES}
- INSTALL_HEADERS ${TO_INSTALL_HEADER_FILES}
- DEPENDS ${DEPENDENCIES}
- LINK_LIBRARIES ${LIBRARIES}
- COMPONENT ${FACEMGR}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- HEADER_ROOT_DIR hicn
- DEFINITIONS ${COMPILER_DEFINITIONS}
- )
+ set(LINK_TYPE STATIC)
else ()
- build_library(${LIBFACEMGR}
- SHARED STATIC NO_DEV
- SOURCES ${SOURCE_FILES}
- INSTALL_HEADERS ${TO_INSTALL_HEADER_FILES}
- DEPENDS ${DEPENDENCIES}
- LINK_LIBRARIES ${LIBRARIES}
- COMPONENT ${FACEMGR}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- HEADER_ROOT_DIR hicn
- DEFINITIONS ${COMPILER_DEFINITIONS}
- )
+ set(LINK_TYPE SHARED STATIC)
endif ()
+
+##############################################################
+# Build libfacemgr
+##############################################################
+build_library(${LIBFACEMGR}
+ ${LINK_TYPE}
+ SOURCES ${SOURCE_FILES}
+ INSTALL_HEADERS ${TO_INSTALL_HEADER_FILES}
+ DEPENDS ${DEPENDENCIES}
+ LINK_LIBRARIES ${LIBRARIES}
+ COMPONENT ${FACEMGR}
+ INCLUDE_DIRS PRIVATE ${INCLUDE_DIRS}
+ DEFINITIONS PRIVATE ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Build executable
+##############################################################
if(NOT DISABLE_EXECUTABLES)
- list(APPEND DAEMON_SRC
- main.c
- )
-
- build_executable(${FACEMGR}
- SOURCES ${DAEMON_SRC}
- LINK_LIBRARIES ${LIBFACEMGR}.static ${LIBRARIES}
- DEPENDS ${LIBFACEMGR}.static
- COMPONENT ${FACEMGR}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- )
+ list(APPEND DAEMON_SRC
+ main.c
+ )
+
+ build_executable(${FACEMGR}
+ SOURCES ${DAEMON_SRC}
+ LINK_LIBRARIES PRIVATE ${LIBFACEMGR}.static
+ DEPENDS ${LIBFACEMGR}.static
+ COMPONENT ${FACEMGR}
+ INCLUDE_DIRS ${INCLUDE_DIRS}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ )
endif ()
diff --git a/ctrl/facemgr/src/api.c b/ctrl/facemgr/src/api.c
index dfbd24bcb..f271b24c7 100644
--- a/ctrl/facemgr/src/api.c
+++ b/ctrl/facemgr/src/api.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,22 +21,14 @@
#ifdef __ANDROID__
/*
- * Use FacemgrUtility to determine interface types
- *
- * NOTE: this is currently disabled as SDK APIs do not allow to determine the
- * type of interfaces that are DOWN
- */
-//#define WITH_FACEMGR_UTILITY
-
-/*
* Use priority controller interface
*/
-#define WITH_PRIORITY_CONTROLLER
+//#define WITH_PRIORITY_CONTROLLER
/*
* Dump facelets (debug)
*/
-//#define WITH_DUMP
+#define WITH_DUMP 1
/*
* Allow priority setting before interface is actually created
@@ -62,15 +54,14 @@
#ifdef __linux__
#include "interfaces/bonjour/bonjour.h"
+#ifdef __ANDROID__
+#include "interfaces/android/android.h"
+#endif /* __ANDROID__ */
#endif /* __linux__ */
-#ifdef WITH_FACEMGR_UTILITY
-#include "interfaces/android_utility/android_utility.h"
-#endif /* WITH_FACEMGR_UTILITY */
-
#include "interfaces/priority_controller/priority_controller.h"
-#include <hicn/ctrl/face.h>
+#include <hicn/face.h>
#include <hicn/facemgr/facelet.h>
#include "common.h"
#include "facelet_array.h"
@@ -84,19 +75,21 @@
#define MAX_FDS 10
typedef struct {
- interface_t * interface;
- int fds[MAX_FDS];
- size_t num_fds;
+ interface_t *interface;
+ int fds[MAX_FDS];
+ size_t num_fds;
} interface_map_data_t;
TYPEDEF_SET_H(facelet_set, facelet_t *);
TYPEDEF_SET(facelet_set, facelet_t *, facelet_cmp, facelet_snprintf);
TYPEDEF_MAP_H(interface_map, const char *, interface_map_data_t *);
-TYPEDEF_MAP(interface_map, const char *, interface_map_data_t *, strcmp, string_snprintf, generic_snprintf);
+TYPEDEF_MAP(interface_map, const char *, interface_map_data_t *, strcmp,
+ string_snprintf, generic_snprintf);
TYPEDEF_MAP_H(bonjour_map, netdevice_t *, interface_t *);
-TYPEDEF_MAP(bonjour_map, netdevice_t *, interface_t *, netdevice_cmp, generic_snprintf, generic_snprintf);
+TYPEDEF_MAP(bonjour_map, netdevice_t *, interface_t *, netdevice_cmp,
+ generic_snprintf, generic_snprintf);
/* TODO automatically register interfaces */
@@ -104,12 +97,13 @@ TYPEDEF_MAP(bonjour_map, netdevice_t *, interface_t *, netdevice_cmp, generic_sn
extern interface_ops_t network_framework_ops;
#endif
#ifdef __linux__
+#ifdef __ANDROID__
+extern interface_ops_t android_ops;
+#else
extern interface_ops_t netlink_ops;
+#endif /* __ANDROID__ */
extern interface_ops_t bonjour_ops;
#endif
-#ifdef WITH_FACEMGR_UTILITY
-extern interface_ops_t android_utility_ops;
-#endif /* WITH_FACEMGR_UTILITY */
#ifdef WITH_PRIORITY_CONTROLLER
extern interface_ops_t priority_controller_ops;
#endif
@@ -121,458 +115,424 @@ extern interface_ops_t updown_ops;
#endif
extern interface_ops_t hicn_light_ops;
-int facemgr_on_event(facemgr_t * facemgr, facelet_t * facelet);
+int facemgr_on_event(facemgr_t *facemgr, facelet_t *facelet);
-int
-facemgr_overlay_snprintf(char * s, size_t size, const facemgr_overlay_t * overlay)
-{
- return -1;
+int facemgr_overlay_snprintf(char *s, size_t size,
+ const facemgr_overlay_t *overlay) {
+ return -1;
}
struct facemgr_s {
- /**************************************************/
- /* Configuration parameters (exposed through API) */
+ /**************************************************/
+ /* Configuration parameters (exposed through API) */
- facemgr_cfg_t * cfg;
+ facemgr_cfg_t *cfg;
#ifdef __ANDROID__
- /*
- * Those two pointers are needed to call java functions from the face
- * manager.
- */
- JavaVM *jvm;
+ /*
+ * Those two pointers are needed to call java functions from the face
+ * manager.
+ */
+ JavaVM *jvm;
#endif /* __ANDROID__ */
- /* Callback */
- facemgr_cb_t callback;
- void * callback_owner;
+ /* Callback */
+ facemgr_cb_t callback;
+ void *callback_owner;
- /****************************/
- /* Internal data structures */
+ /****************************/
+ /* Internal data structures */
- /* Map of interfaces index by name */
- interface_map_t * interface_map;
+ /* Map of interfaces index by name */
+ interface_map_t *interface_map;
- /* Faces under construction */
- facelet_set_t * facelet_cache;
+ /* Faces under construction */
+ facelet_set_t *facelet_cache;
- /* Static facelets */
- facelet_array_t * static_facelets;
+ /* Static facelets */
+ facelet_array_t *static_facelets;
#ifdef WITH_DEFAULT_PRIORITIES
- /* Default priorities */
- u32 default_priority[NETDEVICE_TYPE_N+1];
+ /* Default priorities */
+ u32 default_priority[NETDEVICE_TYPE_N + 1];
#endif /* WITH_DEFAULT_PRIORITIES */
- /********************************************************/
- /* Interfaces - Those should be fully replaced by a map */
-
- interface_t * hl;
+ /********************************************************/
+ /* Interfaces - Those should be fully replaced by a map */
-#ifdef WITH_FACEMGR_UTILITY
- interface_t * au; /* android_utility */
-#endif /* WITH_FACEMGR_UTILITY */
+ interface_t *hl;
#ifdef WITH_PRIORITY_CONTROLLER
- interface_t * pc;
+ interface_t *pc;
#endif
#ifdef __APPLE__
- interface_t * nf; /* network_framework */
-#endif /* __APPLE__ */
+ interface_t *nf; /* network_framework */
+#endif /* __APPLE__ */
#ifdef __linux__
- interface_t * nl; /* netlink */
- /*
- * We maintain a map of dynamically created bonjour interfaces, one for each
- * found netdevice
- */
- bonjour_map_t * bonjour_map;
+#ifdef __ANDROID__
+ interface_t *android;
+#else
+ interface_t *nl; /* netlink */
+#endif /* __ANDROID__ */
+ /*
+ * We maintain a map of dynamically created bonjour interfaces, one for each
+ * found netdevice
+ */
+ bonjour_map_t *bonjour_map;
#endif /* __linux__ */
#ifdef WITH_EXAMPLE_DUMMY
- interface_t * dummy;
+ interface_t *dummy;
#endif
#ifdef WITH_EXAMPLE_UPDOWN
- interface_t * updown;
+ interface_t *updown;
#endif
- int timer_fd; /* Timer used for reattempts */
+ int timer_fd; /* Timer used for reattempts */
- int cur_static_id; /* Used to distinguish static faces (pre-incremented) */
+ int cur_static_id; /* Used to distinguish static faces (pre-incremented) */
};
-int
-facemgr_initialize(facemgr_t * facemgr)
-{
- facemgr->interface_map = interface_map_create();
- if (!facemgr->interface_map) {
- ERROR("[facemgr_initialize] Error creating interface map");
- goto ERR_INTERFACE_MAP;
- }
-
- facemgr->facelet_cache = facelet_set_create();
- if (!facemgr->facelet_cache) {
- ERROR("[facemgr_initialize] Error creating interface map");
- goto ERR_FACE_CACHE_PENDING;
- }
-
- facemgr->static_facelets = facelet_array_create();
- if (!facemgr->static_facelets) {
- ERROR("[facemgr_initialize] Error creating interface map");
- goto ERR_STATIC;
- }
+int facemgr_initialize(facemgr_t *facemgr) {
+ facemgr->interface_map = interface_map_create();
+ if (!facemgr->interface_map) {
+ ERROR("[facemgr_initialize] Error creating interface map");
+ goto ERR_INTERFACE_MAP;
+ }
+
+ facemgr->facelet_cache = facelet_set_create();
+ if (!facemgr->facelet_cache) {
+ ERROR("[facemgr_initialize] Error creating interface map");
+ goto ERR_FACE_CACHE_PENDING;
+ }
+
+ facemgr->static_facelets = facelet_array_create();
+ if (!facemgr->static_facelets) {
+ ERROR("[facemgr_initialize] Error creating interface map");
+ goto ERR_STATIC;
+ }
#ifdef __linux__
- facemgr->bonjour_map = bonjour_map_create();
- if (!facemgr->bonjour_map) {
- ERROR("[facemgr_initialize] Error creating bonjour map");
- goto ERR_BJ;
- }
+ facemgr->bonjour_map = bonjour_map_create();
+ if (!facemgr->bonjour_map) {
+ ERROR("[facemgr_initialize] Error creating bonjour map");
+ goto ERR_BJ;
+ }
#endif /* __linux */
- facemgr->cfg = facemgr_cfg_create();
- if (!facemgr->cfg) {
- ERROR("[facemgr_initialize] Error creating face manager configuration");
- goto ERR_CFG;
- }
+ facemgr->cfg = facemgr_cfg_create();
+ if (!facemgr->cfg) {
+ ERROR("[facemgr_initialize] Error creating face manager configuration");
+ goto ERR_CFG;
+ }
- facemgr->timer_fd = 0;
- facemgr->cur_static_id = 0;
+ facemgr->timer_fd = 0;
+ facemgr->cur_static_id = 0;
#ifdef WITH_DEFAULT_PRIORITIES
-#define _(x) facemgr->default_priority[NETDEVICE_TYPE_ ## x] = 0;
-foreach_netdevice_type
+#define _(x) facemgr->default_priority[NETDEVICE_TYPE_##x] = 0;
+ foreach_netdevice_type
#undef _
#endif /* WITH_DEFAULT_PRIORITIES */
- return 0;
+ return 0;
ERR_CFG:
#ifdef __linux__
- bonjour_map_free(facemgr->bonjour_map);
+ bonjour_map_free(facemgr->bonjour_map);
ERR_BJ:
#endif /* __linux__ */
- facelet_array_free(facemgr->static_facelets);
+ facelet_array_free(facemgr->static_facelets);
ERR_STATIC:
- facelet_set_free(facemgr->facelet_cache);
+ facelet_set_free(facemgr->facelet_cache);
ERR_FACE_CACHE_PENDING:
- interface_map_free(facemgr->interface_map);
+ interface_map_free(facemgr->interface_map);
ERR_INTERFACE_MAP:
- return -1;
+ return -1;
}
-int
-facemgr_finalize(facemgr_t * facemgr)
-{
- int ret = 0;
- int rc;
+int facemgr_finalize(facemgr_t *facemgr) {
+ int ret = 0;
+ int rc;
- if (facemgr->timer_fd) {
- rc = facemgr->callback(facemgr->callback_owner,
- FACEMGR_CB_TYPE_UNREGISTER_TIMER, &facemgr->timer_fd);
- if (rc < 0) {
- ERROR("[facemgr_finalize] Error unregistering timer");
- ret = -1;
- }
- facemgr->timer_fd = 0;
+ if (facemgr->timer_fd) {
+ rc =
+ facemgr->callback(facemgr->callback_owner,
+ FACEMGR_CB_TYPE_UNREGISTER_TIMER, &facemgr->timer_fd);
+ if (rc < 0) {
+ ERROR("[facemgr_finalize] Error unregistering timer");
+ ret = -1;
}
+ facemgr->timer_fd = 0;
+ }
- interface_map_free(facemgr->interface_map);
+ interface_map_free(facemgr->interface_map);
- /* Free all facelets from cache */
- facelet_t ** facelet_array;
- int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
- if (n < 0) {
- ERROR("[facemgr_finalize] Could not retrieve facelets in cache");
- } else {
- for (unsigned i = 0; i < n; i++) {
- facelet_t * facelet = facelet_array[i];
- if (facelet_set_remove(facemgr->facelet_cache, facelet, NULL)) {
- ERROR("[facemgr_finalize] Could not purge facelet from cache");
- }
- facelet_free(facelet);
- }
- free(facelet_array);
+ /* Free all facelets from cache */
+ facelet_t **facelet_array;
+ int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
+ if (n < 0) {
+ ERROR("[facemgr_finalize] Could not retrieve facelets in cache");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *facelet = facelet_array[i];
+ if (!facelet) continue; /* Should not occur */
+ if (facelet_set_remove(facemgr->facelet_cache, facelet, NULL)) {
+ ERROR("[facemgr_finalize] Could not purge facelet from cache");
+ }
+ facelet_free(facelet);
}
+ free(facelet_array);
+ }
- facelet_set_free(facemgr->facelet_cache);
+ facelet_set_free(facemgr->facelet_cache);
- /* Free all facelets from static array */
- for (unsigned i = 0; i < facelet_array_len(facemgr->static_facelets); i++) {
- facelet_t * facelet;
- if (facelet_array_get_index(facemgr->static_facelets, i, &facelet) < 0) {
- ERROR("[facemgr_cfg_finalize] Error getting facelet in array");
- continue;
- }
- if (facelet_array_remove_index(facemgr->static_facelets, i, NULL) < 0) {
- ERROR("[facemgr_finalize] Could not purge facelet from static array");
- }
- facelet_free(facelet);
+ /* Free all facelets from static array */
+ n = (int)facelet_array_len(facemgr->static_facelets);
+
+ INFO("Removing %d facelets from static array", n);
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *facelet;
+ if (facelet_array_get_index(facemgr->static_facelets, i, &facelet) < 0) {
+ ERROR("[facemgr_cfg_finalize] Error getting facelet in array");
+ continue;
+ }
+ if (facelet_array_remove_index(facemgr->static_facelets, i, NULL) < 0) {
+ ERROR("[facemgr_finalize] Could not purge facelet from static array");
}
+ facelet_free(facelet);
+ }
- facelet_array_free(facemgr->static_facelets);
+ facelet_array_free(facemgr->static_facelets);
#ifdef __linux__
- bonjour_map_free(facemgr->bonjour_map);
+ bonjour_map_free(facemgr->bonjour_map);
#endif /* __linux__ */
- interface_unregister_all();
+ interface_unregister_all();
- return ret;
+ return ret;
}
AUTOGENERATE_CREATE_FREE(facemgr);
-int
-facemgr_set_config(facemgr_t * facemgr, facemgr_cfg_t * cfg)
-{
- if (facemgr->cfg) {
- facemgr_cfg_free(facemgr->cfg);
- }
- facemgr->cfg = cfg;
-
- /* Populate the initial list of static facelets */
- facelet_t ** facelet_array;
- int n = facemgr_cfg_get_static_facelet_array(cfg, &facelet_array);
- if (n < 0) {
- ERROR("[facemgr_finalize] Could not retrieve static facelets from cfg");
- } else {
- for (unsigned i = 0; i < n; i++) {
- facelet_t * facelet = facelet_dup(facelet_array[i]);
- facelet_set_status(facelet, FACELET_STATUS_UNDEFINED);
- facelet_set_attr_clean(facelet);
- if (facelet_array_add(facemgr->static_facelets, facelet)) {
- ERROR("[facemgr_finalize] Could not add static facelet to face manager");
- }
- }
+int facemgr_set_config(facemgr_t *facemgr, facemgr_cfg_t *cfg) {
+ if (facemgr->cfg) {
+ facemgr_cfg_free(facemgr->cfg);
+ }
+ facemgr->cfg = cfg;
+
+ /* Populate the initial list of static facelets */
+ facelet_t **facelet_array;
+ int n = facemgr_cfg_get_static_facelet_array(cfg, &facelet_array);
+ if (n < 0) {
+ ERROR("[facemgr_finalize] Could not retrieve static facelets from cfg");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *facelet = facelet_dup(facelet_array[i]);
+ facelet_set_status(facelet, FACELET_STATUS_UNDEFINED);
+ facelet_set_attr_clean(facelet);
+ if (facelet_array_add(facemgr->static_facelets, facelet)) {
+ ERROR(
+ "[facemgr_finalize] Could not add static facelet to face manager");
+ }
}
+ }
- return 0;
+ return 0;
}
-int facemgr_reset_config(facemgr_t * facemgr)
-{
- assert(facemgr->cfg);
- facemgr_cfg_free(facemgr->cfg);
- facemgr->cfg = facemgr_cfg_create();
- if (!facemgr->cfg)
- return -1;
- return 0;
+int facemgr_reset_config(facemgr_t *facemgr) {
+ assert(facemgr->cfg);
+ facemgr_cfg_free(facemgr->cfg);
+ facemgr->cfg = facemgr_cfg_create();
+ if (!facemgr->cfg) return -1;
+ return 0;
}
-facemgr_t *
-facemgr_create_with_config(facemgr_cfg_t * cfg)
-{
- facemgr_t * facemgr = facemgr_create();
- if (!facemgr)
- return NULL;
- int rc = facemgr_set_config(facemgr, cfg);
- if (rc < 0) {
- free(facemgr);
- return NULL;
- }
- return facemgr;
+facemgr_t *facemgr_create_with_config(facemgr_cfg_t *cfg) {
+ facemgr_t *facemgr = facemgr_create();
+ if (!facemgr) return NULL;
+ int rc = facemgr_set_config(facemgr, cfg);
+ if (rc < 0) {
+ free(facemgr);
+ return NULL;
+ }
+ return facemgr;
}
/*
* \brief Heuristics to determine face type based on name, until a better
* solution is found
*/
-netdevice_type_t
-facemgr_get_netdevice_type(const facemgr_t * facemgr, const char * interface_name)
-{
- if (strncmp(interface_name, "lo", 2) == 0) {
- return NETDEVICE_TYPE_LOOPBACK;
- }
- if ((strncmp(interface_name, "eth", 3) == 0) ||
- (strncmp(interface_name, "en", 2) == 0)) {
- /* eth* en* enx* */
- return NETDEVICE_TYPE_WIRED;
- }
- if (strncmp(interface_name, "wl", 2) == 0) {
- /* wlan* wlp* wlx* */
- return NETDEVICE_TYPE_WIFI;
- }
- if (strncmp(interface_name, "rmnet_ipa", 9) == 0) {
- /* Qualcomm IPA driver */
- return NETDEVICE_TYPE_UNDEFINED;
- }
- if ((strncmp(interface_name, "rmnet", 5) == 0) ||
- (strncmp(interface_name, "rev_rmnet", 9) == 0) ||
- (strncmp(interface_name, "ccmni", 5) == 0)) {
- /*
- * rmnet* (Qualcomm) ccmni* (MediaTek)
- */
- return NETDEVICE_TYPE_CELLULAR;
- }
- /* usb0 might be cellular (eg Zenfone2) */
- /* what about tethering */
- /* tun* dummy* ... */
- /* bnet* pan* hci* for bluetooth */
+netdevice_type_t facemgr_get_netdevice_type(const facemgr_t *facemgr,
+ const char *interface_name) {
+ if (strncmp(interface_name, "lo", 2) == 0) {
+ return NETDEVICE_TYPE_LOOPBACK;
+ }
+ if ((strncmp(interface_name, "eth", 3) == 0) ||
+ (strncmp(interface_name, "en", 2) == 0)) {
+ /* eth* en* enx* */
+ return NETDEVICE_TYPE_WIRED;
+ }
+ if (strncmp(interface_name, "wl", 2) == 0) {
+ /* wlan* wlp* wlx* */
+ return NETDEVICE_TYPE_WIFI;
+ }
+ if (strncmp(interface_name, "rmnet_ipa", 9) == 0) {
+ /* Qualcomm IPA driver */
return NETDEVICE_TYPE_UNDEFINED;
+ }
+ if ((strncmp(interface_name, "rmnet", 5) == 0) ||
+ (strncmp(interface_name, "rev_rmnet", 9) == 0) ||
+ (strncmp(interface_name, "ccmni", 5) == 0)) {
+ /*
+ * rmnet* (Qualcomm) ccmni* (MediaTek)
+ */
+ return NETDEVICE_TYPE_CELLULAR;
+ }
+ /* usb0 might be cellular (eg Zenfone2) */
+ /* what about tethering */
+ /* tun* dummy* ... */
+ /* bnet* pan* hci* for bluetooth */
+ return NETDEVICE_TYPE_UNDEFINED;
}
-int facemgr_callback(facemgr_t * facemgr, interface_cb_type_t type, void * data);
-
-int
-facemgr_create_interface(facemgr_t * facemgr, const char * name, const char * type, void * cfg, interface_t ** pinterface)
-{
- char rand_name[RAND_NAME_LEN+1];
- interface_t * interface;
-
- if (!name) {
- /*
- * We can manipulate the name on the stack as it will be strdup'ed by
- * interface_create
- */
- rand_str(rand_name, RAND_NAME_LEN);
- name = rand_name;
- }
-
- INFO("Creating interface %s [%s]...", name, type);
- interface = interface_create(name, type);
- if (!interface) {
- ERROR("Error creating interface %s [%s]", name, type);
- goto ERR_CREATE;
- }
- interface_set_callback(interface, facemgr, facemgr_callback);
+int facemgr_callback(facemgr_t *facemgr, interface_cb_type_t type, void *data);
- interface_map_data_t * interface_map_data = malloc(sizeof(interface_map_data_t));
- if (!interface_map_data)
- goto ERR_MAP_DATA;
-
- *interface_map_data = (interface_map_data_t) {
- .interface = interface,
- .fds = {0},
- .num_fds = 0,
- };
-
- if (interface_map_add(facemgr->interface_map, interface->name, interface_map_data) < 0)
- goto ERR_MAP_ADD;
+int facemgr_create_interface(facemgr_t *facemgr, const char *name,
+ const char *type, void *cfg,
+ interface_t **pinterface) {
+ char rand_name[RAND_NAME_LEN + 1];
+ interface_t *interface;
+ if (!name) {
/*
- * This should be called _after_ the interface_map is initialized otherwise
- * it will be impossible to register fds from *_initialize
+ * We can manipulate the name on the stack as it will be strdup'ed by
+ * interface_create
*/
- if (interface_initialize(interface, cfg) < 0) {
- ERROR("[facemgr_create_interface] Error initializing interface");
- goto ERR_INIT;
- }
-
- DEBUG("Interface %s created successfully.", name);
- if (pinterface)
- *pinterface = interface;
- return 0;
-
-
- //interface_finalize(interface);
+ rand_str(rand_name, RAND_NAME_LEN);
+ name = rand_name;
+ }
+
+ INFO("Creating interface %s [%s]...", name, type);
+ interface = interface_create(name, type);
+ if (!interface) {
+ ERROR("Error creating interface %s [%s]", name, type);
+ goto ERR_CREATE;
+ }
+ interface_set_callback(interface, facemgr, facemgr_callback);
+
+ interface_map_data_t *interface_map_data =
+ malloc(sizeof(interface_map_data_t));
+ if (!interface_map_data) goto ERR_MAP_DATA;
+
+ *interface_map_data = (interface_map_data_t){
+ .interface = interface,
+ .fds = {0},
+ .num_fds = 0,
+ };
+
+ if (interface_map_add(facemgr->interface_map, interface->name,
+ interface_map_data) < 0)
+ goto ERR_MAP_ADD;
+
+ /*
+ * This should be called _after_ the interface_map is initialized otherwise
+ * it will be impossible to register fds from *_initialize
+ */
+ if (interface_initialize(interface, cfg) < 0) {
+ ERROR("[facemgr_create_interface] Error initializing interface");
+ goto ERR_INIT;
+ }
+
+ DEBUG("Interface %s created successfully.", name);
+ if (pinterface) *pinterface = interface;
+ return 0;
+
+ // interface_finalize(interface);
ERR_INIT:
- interface_map_remove(facemgr->interface_map, interface->name, NULL);
+ interface_map_remove(facemgr->interface_map, interface->name, NULL);
ERR_MAP_ADD:
- free(interface_map_data);
+ free(interface_map_data);
ERR_MAP_DATA:
- interface_free(interface);
+ interface_free(interface);
ERR_CREATE:
- if (pinterface)
- *pinterface = NULL;
- return -1;
+ if (pinterface) *pinterface = NULL;
+ return -1;
}
-int
-facemgr_delete_interface(facemgr_t * facemgr, interface_t * interface)
-{
- int rc;
+int facemgr_delete_interface(facemgr_t *facemgr, interface_t *interface) {
+ int rc;
- interface_map_data_t * interface_map_data = NULL;
+ /*
+ * It is possible that one interface was never initialized, and thus the
+ * facemgr never started, and we still call stop(). This is for instance the
+ * case on Android (sdk 30) when netlink is blocked.
+ */
+ if (!interface) return 0;
- DEBUG("Removing interface %s", interface->name);
- rc = interface_map_remove(facemgr->interface_map, interface->name, &interface_map_data);
- if (rc < 0)
- return -1;
+ interface_map_data_t *interface_map_data = NULL;
- if (!interface_map_data)
- return -1;
-
- for (unsigned i = 0; i < interface_map_data->num_fds; i++) {
- int fd = interface_map_data->fds[i];
- fd_callback_data_t fd_callback_data = {
- .fd = fd,
- .owner = facemgr,
- .callback = NULL,
- .data = NULL,
- };
- facemgr->callback(facemgr->callback_owner, FACEMGR_CB_TYPE_UNREGISTER_FD, &fd_callback_data);
- if (rc < 0)
- WARN("[facemgr_delete_interface] Error unregistering fd %d for interface", fd);
- }
+ DEBUG("Removing interface %s", interface->name);
+ rc = interface_map_remove(facemgr->interface_map, interface->name,
+ &interface_map_data);
+ if (rc < 0) return -1;
- free(interface_map_data);
+ if (!interface_map_data) return -1;
- interface_finalize(interface);
- interface_free(interface);
-
- return 0;
-}
-
-#ifdef __linux__
-int facemgr_query_bonjour(facemgr_t * facemgr, netdevice_t * netdevice)
-{
- interface_t * bj = NULL;
-
- int rc = bonjour_map_get(facemgr->bonjour_map, netdevice, &bj);
+ for (unsigned i = 0; i < interface_map_data->num_fds; i++) {
+ int fd = interface_map_data->fds[i];
+ fd_callback_data_t fd_callback_data = {
+ .fd = fd,
+ .owner = facemgr,
+ .callback = NULL,
+ .data = NULL,
+ };
+ facemgr->callback(facemgr->callback_owner, FACEMGR_CB_TYPE_UNREGISTER_FD,
+ &fd_callback_data);
if (rc < 0)
- return rc;
-
- if (!bj) {
- /* Create a new bonjour interface */
- bonjour_cfg_t bj_cfg = {
- .netdevice = *netdevice,
- };
- rc = facemgr_create_interface(facemgr, NULL, "bonjour", &bj_cfg, &bj);
- if (rc < 0) {
- ERROR("Error creating 'Bonjour' interface for '%s'\n", netdevice->name);
- return -1;
- }
- }
+ WARN("[facemgr_delete_interface] Error unregistering fd %d for interface",
+ fd);
+ }
+
+ free(interface_map_data);
- DEBUG("sending event to bonjour interface");
+ interface_finalize(interface);
+ interface_free(interface);
- /* Send an event to the interface (GET ?) */
- // XXX error handling
- return interface_on_event(bj, NULL);
+ return 0;
}
-#endif /* __linux__ */
-#ifdef WITH_FACEMGR_UTILITY
-int facemgr_query_android_utility(facemgr_t * facemgr, netdevice_t netdevice)
-{
- /* Send an event to the interface */
- facelet_t * facelet = facelet_create();
- if (!facelet)
- goto ERR_MALLOC;
+#ifdef __linux__
+int facemgr_query_bonjour(facemgr_t *facemgr, netdevice_t *netdevice) {
+ interface_t *bj = NULL;
- int rc = facelet_set_netdevice(facelet, netdevice);
- if (rc < 0)
- goto ERR_ND;
+ int rc = bonjour_map_get(facemgr->bonjour_map, netdevice, &bj);
+ if (rc < 0) return rc;
- rc = interface_on_event(facemgr->au, facelet);
+ if (!bj) {
+ /* Create a new bonjour interface */
+ bonjour_cfg_t bj_cfg = {
+ .netdevice = *netdevice,
+ };
+ rc = facemgr_create_interface(facemgr, NULL, "bonjour", &bj_cfg, &bj);
if (rc < 0) {
- // XXX error handling
- goto ERR_EVENT;
+ ERROR("Error creating 'Bonjour' interface for '%s'\n", netdevice->name);
+ return -1;
}
+ }
- return 0;
+ DEBUG("sending event to bonjour interface");
-ERR_EVENT:
-ERR_ND:
- facelet_free(facelet);
-ERR_MALLOC:
- return -1;
+ /* Send an event to the interface (GET ?) */
+ // XXX error handling
+ return interface_on_event(bj, NULL);
}
-#endif /* WITH_FACEMGR_UTILITY */
-
+#endif /* __linux__ */
/**
* \brief Performs a cache lookup to find matching facelets
@@ -583,43 +543,38 @@ ERR_MALLOC:
* \return The number of entries in the array in case of success (positive
* value), or -1 in case of error.
*/
-int
-facelet_cache_lookup(const facelet_set_t * facelet_cache, facelet_t * facelet,
- facelet_t ***cached_facelets)
-{
- assert(facelet);
-
- /* ...otherwise, we iterate over the facelet
- * cache to find matching elements.
- */
- facelet_t ** facelet_array;
- int n = facelet_set_get_array(facelet_cache, &facelet_array);
- if (n < 0) {
- ERROR("[facelet_cache_lookup] Error during cache match");
- return -1;
- }
- if (cached_facelets)
- *cached_facelets = malloc(n * sizeof(facelet_t*));
+int facelet_cache_lookup(const facelet_set_t *facelet_cache, facelet_t *facelet,
+ facelet_t ***cached_facelets) {
+ assert(facelet);
+
+ /* ...otherwise, we iterate over the facelet
+ * cache to find matching elements.
+ */
+ facelet_t **facelet_array;
+ int n = facelet_set_get_array(facelet_cache, &facelet_array);
+ if (n < 0) {
+ ERROR("[facelet_cache_lookup] Error during cache match");
+ return -1;
+ }
+ if (cached_facelets) *cached_facelets = malloc(n * sizeof(facelet_t *));
- int num_match = 0;
- for (unsigned i = 0; i < n; i++) {
+ int num_match = 0;
+ for (unsigned i = 0; i < n; i++) {
#if 0
- char facelet_s[MAXSZ_FACELET];
- facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet_array[i]);
- DEBUG("cache entry #%d/%di = %s", i+1, n, facelet_s);
+ char facelet_s[MAXSZ_FACELET];
+ facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet_array[i]);
+ DEBUG("cache entry #%d/%di = %s", i + 1, n, facelet_s);
#endif
- if (!facelet_match(facelet_array[i], facelet)) {
- continue;
- }
- if (cached_facelets)
- (*cached_facelets)[num_match] = facelet_array[i];
- num_match++;
- }
- free(facelet_array);
- return num_match;
+ facelet_t *f = facelet_array[i];
+ if (!f) continue; /* Should not occur */
+ if (!facelet_match(f, facelet)) continue;
+ if (cached_facelets) (*cached_facelets)[num_match] = f;
+ num_match++;
+ }
+ free(facelet_array);
+ return num_match;
}
-
/**
* \brief Checks whether the facelet satisfies face creation rules
* \param [in] facemgr - Pointer to the face manager instance
@@ -627,129 +582,92 @@ facelet_cache_lookup(const facelet_set_t * facelet_cache, facelet_t * facelet,
* \return 0 in case of success, -2 if we don't have enough information to
* decide, -3 if the face does not satisfy rules, and -1 in case of error
*/
-int
-facemgr_facelet_satisfy_rules(facemgr_t * facemgr, facelet_t * facelet)
-{
- /* As key, netdevice and family should always be present */
- netdevice_t netdevice = NETDEVICE_EMPTY;
- int rc = facelet_get_netdevice(facelet, &netdevice);
- if (rc < 0) {
- ERROR("[facemgr_facelet_satisfy_rules] Error retrieving netdevice from facelet");
+int facemgr_facelet_satisfy_rules(facemgr_t *facemgr, facelet_t *facelet) {
+ /* As key, netdevice and family should always be present */
+ netdevice_t netdevice = NETDEVICE_EMPTY;
+ int rc = facelet_get_netdevice(facelet, &netdevice);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_facelet_satisfy_rules] Error retrieving netdevice from "
+ "facelet");
+ return -1;
+ }
+
+ int family = AF_UNSPEC;
+ if (facelet_has_family(facelet)) {
+ if (facelet_get_family(facelet, &family) < 0) {
+ ERROR(
+ "[facemgr_facelet_satisfy_rules] Error retrieving family from "
+ "facelet");
+ return -1;
+ }
+ }
+
+ netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ /*
+ * In addition to netdevice, netdevice_type should be present to correctly
+ * apply rules
+ */
+ rc = facelet_get_netdevice_type(facelet, &netdevice_type);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_facelet_satisfy_rules] Error retrieving netdevice_type from "
+ "facelet");
+ return -2;
+ }
+
+ /* Default ignore list */
+ if ((netdevice_type == NETDEVICE_TYPE_LOOPBACK) ||
+ (netdevice_type == NETDEVICE_TYPE_UNDEFINED)) {
+ DEBUG("Ignored interface '%s/%s'...", netdevice.name,
+ netdevice_type_str(netdevice_type));
+ return -3;
+ }
+
+ /* Ignore */
+ bool ignore;
+ if (facemgr_cfg_get_ignore(facemgr->cfg, &netdevice, netdevice_type,
+ &ignore) < 0)
+ return -1;
+ if (ignore) {
+ DEBUG("Ignored interface '%s/%s'...", netdevice.name,
+ netdevice_type_str(netdevice_type));
+ return -3;
+ }
+
+ switch (family) {
+ case AF_INET: {
+ bool ipv4;
+ if (facemgr_cfg_get_ipv4(facemgr->cfg, &netdevice, netdevice_type,
+ &ipv4) < 0)
return -1;
- }
-
- int family = AF_UNSPEC;
- if (facelet_has_family(facelet)) {
- if (facelet_get_family(facelet, &family) < 0) {
- ERROR("[facemgr_facelet_satisfy_rules] Error retrieving family from facelet");
- return -1;
- }
- }
-
- netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
-#ifndef WITH_FACEMGR_UTILITY
- /*
- * In addition to netdevice, netdevice_type should be present to correctly
- * apply rules
- */
- rc = facelet_get_netdevice_type(facelet, &netdevice_type);
- if (rc < 0) {
- ERROR("[facemgr_facelet_satisfy_rules] Error retrieving netdevice_type from facelet");
- return -2;
- }
-#endif /* WITH_FACEMGR_UTILITY */
-
- /* Default ignore list */
- if ((netdevice_type == NETDEVICE_TYPE_LOOPBACK) || (netdevice_type == NETDEVICE_TYPE_UNDEFINED)) {
- DEBUG("Ignored interface '%s/%s'...", netdevice.name,
- netdevice_type_str[netdevice_type]);
+ if (!ipv4) {
+ DEBUG("Ignored IPv4 facelet...");
return -3;
+ }
+ break;
}
- /* Ignore */
- bool ignore;
- if (facemgr_cfg_get_ignore(facemgr->cfg, &netdevice, netdevice_type,
- &ignore) < 0)
+ case AF_INET6: {
+ bool ipv6;
+ if (facemgr_cfg_get_ipv6(facemgr->cfg, &netdevice, netdevice_type,
+ &ipv6) < 0)
return -1;
- if (ignore) {
- DEBUG("Ignored interface '%s/%s'...", netdevice.name,
- netdevice_type_str[netdevice_type]);
+ if (!ipv6) {
+ DEBUG("Ignored IPv6 facelet...");
return -3;
+ }
+ break;
}
- switch(family) {
- case AF_INET:
- {
- bool ipv4;
- if (facemgr_cfg_get_ipv4(facemgr->cfg, &netdevice, netdevice_type,
- &ipv4) < 0)
- return -1;
- if (!ipv4) {
- DEBUG("Ignored IPv4 facelet...");
- return -3;
- }
- break;
- }
-
- case AF_INET6:
- {
- bool ipv6;
- if (facemgr_cfg_get_ipv6(facemgr->cfg, &netdevice, netdevice_type,
- &ipv6) < 0)
- return -1;
- if (!ipv6) {
- DEBUG("Ignored IPv6 facelet...");
- return -3;
- }
- break;
- }
-
- default:
- DEBUG("Ignored facelet with unknown family");
- return -2;
- }
+ default:
+ DEBUG("Ignored facelet with unknown family");
+ return -2;
+ }
- return 0;
+ return 0;
}
-#ifdef WITH_FACEMGR_UTILITY
-/**
- * \brief Complements facelet information through Android Utility interface
- * \return 0 if request was successful, -1 in case of error, and -2 if the
- * interface is not applicable
- *
- * This function returnds _after_ completion.
- */
-int
-facemgr_complement_facelet_au(facemgr_t * facemgr, facelet_t * facelet)
-{
-
- if (facelet_has_netdevice_type(facelet))
- return -2;
-
- if (facelet_is_au_done(facelet))
- return -2;
-
- netdevice_t netdevice = NETDEVICE_EMPTY;
-
- int rc = facelet_get_netdevice(facelet, &netdevice);
- if (rc < 0) {
- ERROR("[facemgr_complement_facelet_bj] Error retrieving netdevice from facelet");
- return -1;
- }
-
- DEBUG("Querying android utility...");
-
- /* /!\ Synchronous code here /!\ */
- if (facemgr_query_android_utility(facemgr, netdevice) < 0) {
- return -1;
- }
-
- facelet_set_au_done(facelet);
- return 0;
-}
-#endif /* WITH_FACEMGR_UTILITY */
-
#ifdef __linux__
/**
* \brief Complements facelet information through Bonjour interface.
@@ -759,66 +677,68 @@ facemgr_complement_facelet_au(facemgr_t * facemgr, facelet_t * facelet)
* This function returnds _before_ completion as bonjour querying is
* asynchronous.
*/
-int
-facemgr_complement_facelet_bj(facemgr_t * facemgr, facelet_t * facelet)
-{
- netdevice_t netdevice = NETDEVICE_EMPTY;
- int rc = facelet_get_netdevice(facelet, &netdevice);
- if (rc < 0) {
- ERROR("[facemgr_complement_facelet_bj] Error retrieving netdevice from facelet");
- return -1;
- }
-
- netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
-#ifndef WITH_FACEMGR_UTILITY
- /*
- * In addition to netdevice, netdevice_type should be present to correctly
- * apply rules
- */
- rc = facelet_get_netdevice_type(facelet, &netdevice_type);
- if (rc < 0) {
- ERROR("[facemgr_complement_facelet_bj] Error retrieving netdevice_type from facelet");
- return -2;
- }
-#endif /* WITH_FACEMGR_UTILITY */
-
- bool discovery;
- if (facemgr_cfg_get_discovery(facemgr->cfg, &netdevice, netdevice_type,
- &discovery) < 0)
- return -2;
-
- DEBUG("Discovery: %s", discovery ? "ON" : "OFF");
-
- if (!discovery)
- return -2;
-
- facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
- if (facelet_get_face_type(facelet, &face_type) < 0) {
- ERROR("[facemgr_complement_facelet_bj] Error retrieving face type from facelet");
- return -1;
- }
+int facemgr_complement_facelet_bj(facemgr_t *facemgr, facelet_t *facelet) {
+ netdevice_t netdevice = NETDEVICE_EMPTY;
+ int rc = facelet_get_netdevice(facelet, &netdevice);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_bj] Error retrieving netdevice from "
+ "facelet");
+ return -1;
+ }
+
+ netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ /*
+ * In addition to netdevice, netdevice_type should be present to correctly
+ * apply rules
+ */
+ rc = facelet_get_netdevice_type(facelet, &netdevice_type);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_bj] Error retrieving netdevice_type from "
+ "facelet");
+ return -2;
+ }
+
+ bool discovery;
+ if (facemgr_cfg_get_discovery(facemgr->cfg, &netdevice, netdevice_type,
+ &discovery) < 0)
+ return -2;
+
+ DEBUG("Discovery: %s", discovery ? "ON" : "OFF");
+
+ if (!discovery) return -2;
+
+ facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
+ if (facelet_get_face_type(facelet, &face_type) < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_bj] Error retrieving face type from "
+ "facelet");
+ return -1;
+ }
- bool discovery_needed = (face_type.layer == FACE_TYPE_LAYER_4) &&
- ((!facelet_has_remote_addr(facelet)) || (!facelet_has_remote_port(facelet)));
+ bool discovery_needed = (face_type.layer == FACE_TYPE_LAYER_4) &&
+ ((!facelet_has_remote_addr(facelet)) ||
+ (!facelet_has_remote_port(facelet)));
- DEBUG("Discovery needed: %s", discovery ? "ON" : "OFF");
+ DEBUG("Discovery needed: %s", discovery ? "ON" : "OFF");
- if (!discovery_needed) {
- return -2;
- }
+ if (!discovery_needed) {
+ return -2;
+ }
- if (!facelet_has_local_addr(facelet)) {
- DEBUG("No discovery possible without local address");
- return -2;
- }
+ if (!facelet_has_local_addr(facelet)) {
+ DEBUG("No discovery possible without local address");
+ return -2;
+ }
- if (facelet_is_bj_done(facelet)) {
- DEBUG("Bonjour already queried");
- return -2;
- }
+ if (facelet_is_bj_done(facelet)) {
+ DEBUG("Bonjour already queried");
+ return -2;
+ }
- facelet_set_bj_done(facelet);
- return facemgr_query_bonjour(facemgr, &netdevice);
+ facelet_set_bj_done(facelet);
+ return facemgr_query_bonjour(facemgr, &netdevice);
}
#endif /* __linux__ */
@@ -830,49 +750,52 @@ facemgr_complement_facelet_bj(facemgr_t * facemgr, facelet_t * facelet)
* This function returnds _before_ completion as bonjour querying is
* asynchronous.
*/
-int
-facemgr_complement_facelet_manual(facemgr_t * facemgr, facelet_t * facelet)
-{
-
- netdevice_t netdevice = NETDEVICE_EMPTY;
- int rc = facelet_get_netdevice(facelet, &netdevice);
- if (rc < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error retrieving netdevice from facelet");
- return -1;
- }
-
- netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
-#ifndef WITH_FACEMGR_UTILITY
- /*
- * In addition to netdevice, netdevice_type should be present to correctly
- * apply rules
- */
- rc = facelet_get_netdevice_type(facelet, &netdevice_type);
- if (rc < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error retrieving netdevice_type from facelet");
- return -2;
- }
-#endif /* WITH_FACEMGR_UTILITY */
-
- int family = AF_UNSPEC;
- if (facelet_has_family(facelet)) {
- if (facelet_get_family(facelet, &family) < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error retrieving family from facelet");
- return -1;
- }
- }
-
- /* Do not query manual is there is a change to go through bonjour */
- bool discovery;
- if (facemgr_cfg_get_discovery(facemgr->cfg, &netdevice, netdevice_type,
- &discovery) < 0)
- return -2;
-
- facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
- if (facelet_get_face_type(facelet, &face_type) < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error retrieving face type from facelet");
- return -1;
- }
+int facemgr_complement_facelet_manual(facemgr_t *facemgr, facelet_t *facelet) {
+ netdevice_t netdevice = NETDEVICE_EMPTY;
+ int rc = facelet_get_netdevice(facelet, &netdevice);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error retrieving netdevice from "
+ "facelet");
+ return -1;
+ }
+
+ netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ /*
+ * In addition to netdevice, netdevice_type should be present to correctly
+ * apply rules
+ */
+ rc = facelet_get_netdevice_type(facelet, &netdevice_type);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error retrieving netdevice_type "
+ "from facelet");
+ return -2;
+ }
+
+ int family = AF_UNSPEC;
+ if (facelet_has_family(facelet)) {
+ if (facelet_get_family(facelet, &family) < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error retrieving family from "
+ "facelet");
+ return -1;
+ }
+ }
+
+ /* Do not query manual is there is a change to go through bonjour */
+ bool discovery;
+ if (facemgr_cfg_get_discovery(facemgr->cfg, &netdevice, netdevice_type,
+ &discovery) < 0)
+ return -2;
+
+ facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
+ if (facelet_get_face_type(facelet, &face_type) < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error retrieving face type from "
+ "facelet");
+ return -1;
+ }
#if 0 /* Wrong if we need to complement local addr / port */
bool discovery_needed = (face_type.layer == FACE_TYPE_LAYER_4) &&
@@ -884,91 +807,97 @@ facemgr_complement_facelet_manual(facemgr_t * facemgr, facelet_t * facelet)
}
#endif
- if (discovery && !facelet_is_bj_done(facelet)) {
- DEBUG("manual settings not considered as discovery is enabled and Bonjour has not yet been done");
- return -2;
- }
-
- DEBUG("Applying manual settings...");
- /*
- * Manual overlay specification (remote addr/port)
- * We never override a result we have obtained through bonjour
- */
- if (!facelet_has_remote_addr(facelet)) {
- ip_address_t remote_addr;
- if (facemgr_cfg_get_overlay_remote_addr(facemgr->cfg,
- &netdevice, netdevice_type, family, &remote_addr) < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error getting remote addr information from cfg");
- return -1;
- }
- if (ip_address_empty(&remote_addr)) {
- ERROR("[facemgr_complement_facelet_manual] Got empty remote addr information from cfg");
- } else {
- DEBUG(" - remote address");
- facelet_set_remote_addr(facelet, remote_addr);
- }
- }
-
- if (!facelet_has_remote_port(facelet)) {
- uint16_t remote_port;
- int rc = facemgr_cfg_get_overlay_remote_port(facemgr->cfg,
- &netdevice, netdevice_type, family, &remote_port);
- if (rc < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error getting remote port information from cfg");
- return -1;
- }
- DEBUG(" - remote port");
- facelet_set_remote_port(facelet, remote_port);
- }
-
- /*
- * Complementing local addr/port XXX this should be done somewhere
- * else : manual settings have the lowest priority
- *
- * Local IP address is specific as it allows to override the source
- * address just before creating the face... we would need to check
- * whether this is an address that belong to us... it might be used
- * to arbitrate amongst several IP addresses instead...
- */
- ip_address_t local_addr;
- if (facemgr_cfg_get_overlay_local_addr(facemgr->cfg, &netdevice,
- netdevice_type, family, &local_addr) < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error getting local addr information from cfg");
- return -1;
- }
- if (ip_address_empty(&local_addr)) {
- ERROR("[facemgr_complement_facelet_manual] Got empty local addr information from cfg");
+ if (discovery && !facelet_is_bj_done(facelet)) {
+ DEBUG(
+ "manual settings not considered as discovery is enabled and Bonjour "
+ "has not yet been done");
+ return -2;
+ }
+
+ DEBUG("Applying manual settings...");
+ /*
+ * Manual overlay specification (remote addr/port)
+ * We never override a result we have obtained through bonjour
+ */
+ if (!facelet_has_remote_addr(facelet)) {
+ hicn_ip_address_t remote_addr;
+ if (facemgr_cfg_get_overlay_remote_addr(facemgr->cfg, &netdevice,
+ netdevice_type, family,
+ &remote_addr) < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error getting remote addr "
+ "information from cfg");
+ return -1;
+ }
+ if (hicn_ip_address_empty(&remote_addr)) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Got empty remote addr "
+ "information from cfg");
} else {
- DEBUG(" - local addres");
- facelet_set_local_addr(facelet, local_addr);
+ DEBUG(" - remote address");
+ facelet_set_remote_addr(facelet, remote_addr);
}
+ }
- /* Sets a default local port, so far nobody sets it */
- uint16_t local_port;
- if (facemgr_cfg_get_overlay_local_port(facemgr->cfg,
- &netdevice, netdevice_type, family, &local_port) < 0) {
- ERROR("[facemgr_complement_facelet_manual] Error getting local port information from cfg");
- return -1;
- }
- DEBUG(" - local port");
- facelet_set_local_port(facelet, local_port);
- return 0;
+ if (!facelet_has_remote_port(facelet)) {
+ uint16_t remote_port;
+ int rc = facemgr_cfg_get_overlay_remote_port(
+ facemgr->cfg, &netdevice, netdevice_type, family, &remote_port);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error getting remote port "
+ "information from cfg");
+ return -1;
+ }
+ DEBUG(" - remote port");
+ facelet_set_remote_port(facelet, remote_port);
+ }
+
+ /*
+ * Complementing local addr/port XXX this should be done somewhere
+ * else : manual settings have the lowest priority
+ *
+ * Local IP address is specific as it allows to override the source
+ * address just before creating the face... we would need to check
+ * whether this is an address that belong to us... it might be used
+ * to arbitrate amongst several IP addresses instead...
+ */
+ hicn_ip_address_t local_addr;
+ if (facemgr_cfg_get_overlay_local_addr(
+ facemgr->cfg, &netdevice, netdevice_type, family, &local_addr) < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error getting local addr "
+ "information from cfg");
+ return -1;
+ }
+ if (hicn_ip_address_empty(&local_addr)) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Got empty local addr information "
+ "from cfg");
+ } else {
+ DEBUG(" - local addres");
+ facelet_set_local_addr(facelet, local_addr);
+ }
+
+ /* Sets a default local port, so far nobody sets it */
+ uint16_t local_port;
+ if (facemgr_cfg_get_overlay_local_port(
+ facemgr->cfg, &netdevice, netdevice_type, family, &local_port) < 0) {
+ ERROR(
+ "[facemgr_complement_facelet_manual] Error getting local port "
+ "information from cfg");
+ return -1;
+ }
+ DEBUG(" - local port");
+ facelet_set_local_port(facelet, local_port);
+ return 0;
}
-int
-facemgr_complement_facelet(facemgr_t * facemgr, facelet_t * facelet)
-{
- int rc;
-
- DEBUG("[facemgr_complement_facelet]");
- if (!facelet_has_key(facelet))
- return -2;
+int facemgr_complement_facelet(facemgr_t *facemgr, facelet_t *facelet) {
+ int rc;
-#ifdef WITH_FACEMGR_UTILITY
- rc = facemgr_complement_facelet_au(facemgr, facelet);
- if (rc != -2)
- return rc;
-#endif /* WITH_FACEMGR_UTILITY */
+ DEBUG("[facemgr_complement_facelet]");
+ if (!facelet_has_key(facelet)) return -2;
#if 0
if (!facelet_has_netdevice_type(facelet)) {
@@ -988,51 +917,51 @@ facemgr_complement_facelet(facemgr_t * facemgr, facelet_t * facelet)
*/
#ifdef __linux__
- rc = facemgr_complement_facelet_bj(facemgr, facelet);
- if (rc != -2)
- return rc;
+ rc = facemgr_complement_facelet_bj(facemgr, facelet);
+ if (rc != -2) return rc;
#endif /* __linux__ */
- DEBUG("[facemgr_complement_facelet] Complement manual");
+ DEBUG("[facemgr_complement_facelet] Complement manual");
- rc = facemgr_complement_facelet_manual(facemgr, facelet);
- if (rc != -2)
- return rc;
+ rc = facemgr_complement_facelet_manual(facemgr, facelet);
+ if (rc != -2) return rc;
- INFO("[facemgr_complement_facelet] No more interfaces to query... incomplete face");
- return 0;
+ INFO(
+ "[facemgr_complement_facelet] No more interfaces to query... incomplete "
+ "face");
+ return 0;
}
-int facemgr_assign_face_type(facemgr_t * facemgr, facelet_t * facelet)
-{
- DEBUG("[facemgr_assign_face_type]");
- /* As key, netdevice and family should always be present */
- netdevice_t netdevice = NETDEVICE_EMPTY;
- int rc = facelet_get_netdevice(facelet, &netdevice);
- if (rc < 0) {
- ERROR("[facemgr_assign_face_type] Error retrieving netdevice from facelet");
- return -1;
- }
-
- netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
-#ifndef WITH_FACEMGR_UTILITY
- /*
- * In addition to netdevice, netdevice_type should be present to correctly
- * apply rules
- */
- rc = facelet_get_netdevice_type(facelet, &netdevice_type);
- if (rc < 0) {
- ERROR("[facemgr_assign_face_type] Error retrieving netdevice_type from facelet");
- return -2;
- }
-#endif /* WITH_FACEMGR_UTILITY */
-
- facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
- if (facemgr_cfg_get_face_type(facemgr->cfg, &netdevice, netdevice_type, &face_type) < 0)
- return rc;
- facelet_set_face_type(facelet, face_type);
- DEBUG("[facemgr_assign_face_type] %s", FACEMGR_FACE_TYPE_STR(face_type));
- return 0;
+int facemgr_assign_face_type(facemgr_t *facemgr, facelet_t *facelet) {
+ DEBUG("[facemgr_assign_face_type]");
+ /* As key, netdevice and family should always be present */
+ netdevice_t netdevice = NETDEVICE_EMPTY;
+ int rc = facelet_get_netdevice(facelet, &netdevice);
+ if (rc < 0) {
+ ERROR("[facemgr_assign_face_type] Error retrieving netdevice from facelet");
+ return -1;
+ }
+
+ netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ /*
+ * In addition to netdevice, netdevice_type should be present to correctly
+ * apply rules
+ */
+ rc = facelet_get_netdevice_type(facelet, &netdevice_type);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_assign_face_type] Error retrieving netdevice_type from "
+ "facelet");
+ return -2;
+ }
+
+ facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
+ if (facemgr_cfg_get_face_type(facemgr->cfg, &netdevice, netdevice_type,
+ &face_type) < 0)
+ return rc;
+ facelet_set_face_type(facelet, face_type);
+ DEBUG("[facemgr_assign_face_type] %s", FACEMGR_FACE_TYPE_STR(face_type));
+ return 0;
}
/*
@@ -1041,102 +970,102 @@ int facemgr_assign_face_type(facemgr_t * facemgr, facelet_t * facelet)
*
* We assume the facelet is already present in the cache
*/
-int
-facemgr_process_facelet(facemgr_t * facemgr, facelet_t * facelet)
-{
- int rc;
- facelet_error_reason_t reason = FACELET_ERROR_REASON_INTERNAL_ERROR;
-
- switch(facelet_get_status(facelet)) {
- case FACELET_STATUS_UNCERTAIN:
- /*
- * All new faces are marked UNCERTAIN. We need to check whether we
- * have sufficient information to check rules, if not proceed,
- * otherwise possibly mark the face as IGNORED. Otherwise, we verify
- * the completeness of the information we have, and continue towards
- * being able to mark the face as CREATE.
- */
- rc = facemgr_facelet_satisfy_rules(facemgr, facelet);
- switch(rc) {
- case -3:
- /* Does not satisfy rules */
- DEBUG("[facemgr_process_facelet] Does not satisfy rules");
- facelet_set_status(facelet, FACELET_STATUS_IGNORED);
- return 0;
-
- case -2:
- DEBUG("[facemgr_process_facelet] Complementing facelet is required");
- if (facemgr_complement_facelet(facemgr, facelet) < 0) {
- ERROR("[facemgr_process_facelet] Error while attempting to complement face for fields required by face creation");
- goto ERR;
- }
- return 0;
-
- case 0:
- /* Ok pass rules */
- break;
-
- default:
- /* -1 - Error */
- goto ERR;
- }
-
- if (facemgr_assign_face_type(facemgr, facelet) < 0) {
- ERROR("[facemgr_process_facelet] Could not assign face type");
- goto ERR;
- }
- facelet_set_status(facelet, FACELET_STATUS_INCOMPLETE);
- /* Continue in case facelet satisfies rules */
-
- case FACELET_STATUS_INCOMPLETE:
- if (!facelet_validate_face(facelet)) {
- /* We need additional information */
- if (facemgr_complement_facelet(facemgr, facelet) < 0) {
- ERROR("[facemgr_process_facelet] Error while attempting to complement face for fields required by face creation");
- goto ERR;
- }
- }
- if (!facelet_validate_face(facelet))
- return 0;
-
- facelet_set_status(facelet, FACELET_STATUS_CREATE);
- /* Continue in case we need to proceed to creation */
-
- case FACELET_STATUS_CREATE:
- facelet_set_event(facelet, FACELET_EVENT_CREATE);
- rc = interface_on_event(facemgr->hl, facelet);
- if (rc < 0) {
- ERROR("[facemgr_process_facelet] Failed to create face");
- reason = -rc;
- goto ERR;
- }
-
- /* This works assuming the call to hicn-light is blocking */
- facelet_set_status(facelet, FACELET_STATUS_CLEAN);
- break;
+int facemgr_process_facelet(facemgr_t *facemgr, facelet_t *facelet) {
+ int rc;
+ facelet_error_reason_t reason = FACELET_ERROR_REASON_INTERNAL_ERROR;
+
+ switch (facelet_get_status(facelet)) {
+ case FACELET_STATUS_UNCERTAIN:
+ /*
+ * All new faces are marked UNCERTAIN. We need to check whether we
+ * have sufficient information to check rules, if not proceed,
+ * otherwise possibly mark the face as IGNORED. Otherwise, we verify
+ * the completeness of the information we have, and continue towards
+ * being able to mark the face as CREATE.
+ */
+ rc = facemgr_facelet_satisfy_rules(facemgr, facelet);
+ switch (rc) {
+ case -3:
+ /* Does not satisfy rules */
+ DEBUG("[facemgr_process_facelet] Does not satisfy rules");
+ facelet_set_status(facelet, FACELET_STATUS_IGNORED);
+ return 0;
+
+ case -2:
+ DEBUG("[facemgr_process_facelet] Complementing facelet is required");
+ if (facemgr_complement_facelet(facemgr, facelet) < 0) {
+ ERROR(
+ "[facemgr_process_facelet] Error while attempting to "
+ "complement face for fields required by face creation");
+ goto ERR;
+ }
+ return 0;
+ case 0:
+ /* Ok pass rules */
+ break;
- case FACELET_STATUS_UPDATE:
- facelet_set_event(facelet, FACELET_EVENT_UPDATE);
- rc = interface_on_event(facemgr->hl, facelet);
- if (rc < 0) {
- ERROR("[facemgr_process_facelet] Failed to update face");
- reason = -rc;
- goto ERR;
- }
+ default:
+ /* -1 - Error */
+ goto ERR;
+ }
- /* This works assuming the call to hicn-light is blocking */
- facelet_set_status(facelet, FACELET_STATUS_CLEAN);
- break;
-
- case FACELET_STATUS_DELETE:
- facelet_set_event(facelet, FACELET_EVENT_DELETE);
- rc = interface_on_event(facemgr->hl, facelet);
- if (rc < 0) {
- ERROR("[facemgr_process_facelet] Failed to delete face");
- reason = -rc;
- goto ERR;
- }
+ if (facemgr_assign_face_type(facemgr, facelet) < 0) {
+ ERROR("[facemgr_process_facelet] Could not assign face type");
+ goto ERR;
+ }
+ facelet_set_status(facelet, FACELET_STATUS_INCOMPLETE);
+ /* Continue in case facelet satisfies rules */
+
+ case FACELET_STATUS_INCOMPLETE:
+ if (!facelet_validate_face(facelet)) {
+ /* We need additional information */
+ if (facemgr_complement_facelet(facemgr, facelet) < 0) {
+ ERROR(
+ "[facemgr_process_facelet] Error while attempting to complement "
+ "face for fields required by face creation");
+ goto ERR;
+ }
+ }
+ if (!facelet_validate_face(facelet)) return 0;
+
+ facelet_set_status(facelet, FACELET_STATUS_CREATE);
+ /* Continue in case we need to proceed to creation */
+
+ case FACELET_STATUS_CREATE:
+ facelet_set_event(facelet, FACELET_EVENT_CREATE);
+ rc = interface_on_event(facemgr->hl, facelet);
+ if (rc < 0) {
+ ERROR("[facemgr_process_facelet] Failed to create face");
+ reason = -rc;
+ goto ERR;
+ }
+
+ /* This works assuming the call to hicn-light is blocking */
+ facelet_set_status(facelet, FACELET_STATUS_CLEAN);
+ break;
+
+ case FACELET_STATUS_UPDATE:
+ facelet_set_event(facelet, FACELET_EVENT_UPDATE);
+ rc = interface_on_event(facemgr->hl, facelet);
+ if (rc < 0) {
+ ERROR("[facemgr_process_facelet] Failed to update face");
+ reason = -rc;
+ goto ERR;
+ }
+
+ /* This works assuming the call to hicn-light is blocking */
+ facelet_set_status(facelet, FACELET_STATUS_CLEAN);
+ break;
+
+ case FACELET_STATUS_DELETE:
+ facelet_set_event(facelet, FACELET_EVENT_DELETE);
+ rc = interface_on_event(facemgr->hl, facelet);
+ if (rc < 0) {
+ ERROR("[facemgr_process_facelet] Failed to delete face");
+ reason = -rc;
+ goto ERR;
+ }
#if 0
if (facelet_get_id(facelet) > 0) {
@@ -1147,111 +1076,102 @@ facemgr_process_facelet(facemgr_t * facemgr, facelet_t * facelet)
facelet_free(facelet);
} else {
#endif
- /* This works assuming the call to hicn-light is blocking */
- DEBUG("[facemgr_process_facelet] Cleaning cached data");
- facelet_unset_local_addr(facelet);
- facelet_unset_local_port(facelet);
- if (facelet_get_id(facelet) == 0) {
- facelet_unset_remote_addr(facelet);
- facelet_unset_remote_port(facelet);
- facelet_clear_routes(facelet);
- }
-
- facelet_unset_admin_state(facelet);
- facelet_unset_state(facelet);
- facelet_unset_bj_done(facelet);
-#ifdef WITH_FACEMGR_UTILITY
- facelet_unset_au_done(facelet);
-#endif /* WITH_FACEMGR_UTILITY */
-
- facelet_set_status(facelet, FACELET_STATUS_DELETED);
+ /* This works assuming the call to hicn-light is blocking */
+ DEBUG("[facemgr_process_facelet] Cleaning cached data");
+ facelet_unset_local_addr(facelet);
+ facelet_unset_local_port(facelet);
+ if (facelet_get_id(facelet) == 0) {
+ facelet_unset_remote_addr(facelet);
+ facelet_unset_remote_port(facelet);
+ facelet_clear_routes(facelet);
+ }
+
+ facelet_unset_admin_state(facelet);
+ facelet_unset_state(facelet);
+ facelet_unset_bj_done(facelet);
+
+ facelet_set_status(facelet, FACELET_STATUS_DELETED);
#if 0
}
#endif
- break;
-
- case FACELET_STATUS_CLEAN:
- case FACELET_STATUS_IGNORED:
- case FACELET_STATUS_DOWN:
- case FACELET_STATUS_DELETED:
- /* Nothing to do */
- break;
-
- case FACELET_STATUS_UNDEFINED:
- case FACELET_STATUS_N:
- ERROR("[facemgr_process_facelet] Unexpected facelet status");
- goto ERR;
- }
+ break;
- facelet_unset_error(facelet);
- return 0;
+ case FACELET_STATUS_CLEAN:
+ case FACELET_STATUS_IGNORED:
+ case FACELET_STATUS_DOWN:
+ case FACELET_STATUS_DELETED:
+ /* Nothing to do */
+ break;
+
+ case FACELET_STATUS_UNDEFINED:
+ case FACELET_STATUS_N:
+ ERROR("[facemgr_process_facelet] Unexpected facelet status");
+ goto ERR;
+ }
+
+ facelet_unset_error(facelet);
+ return 0;
ERR:
- facelet_set_error(facelet, reason);
- return -1;
+ facelet_set_error(facelet, reason);
+ return -1;
}
-int
-facemgr_reattempt_timeout(facemgr_t * facemgr, int fd, void * data)
-{
- bool has_error = false;
+int facemgr_reattempt_timeout(facemgr_t *facemgr, int fd, void *data) {
+ bool has_error = false;
- assert(data == NULL);
+ assert(data == NULL);
- /* Free all facelets from cache */
- facelet_t ** facelet_array;
- int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
- if (n < 0) {
- ERROR("[facemgr_reattempt_timeout] Could not retrieve facelets in cache");
+ /* Free all facelets from cache */
+ facelet_t **facelet_array;
+ int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
+ if (n < 0) {
+ ERROR("[facemgr_reattempt_timeout] Could not retrieve facelets in cache");
+ has_error = true;
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *facelet = facelet_array[i];
+ if (!facelet) continue; /* Should not occur */
+ if (!facelet_get_error(facelet)) continue;
+
+ char buf[MAXSZ_FACELET];
+ facelet_snprintf(buf, MAXSZ_FACELET, facelet);
+ DEBUG("Reattempt to process failed facelet %s", buf);
+ if (facemgr_process_facelet(facemgr, facelet) < 0) {
+ ERROR("[facemgr_reattempt_timeout] Error processing facelet");
has_error = true;
- } else {
- for (unsigned i = 0; i < n; i++) {
- facelet_t * facelet = facelet_array[i];
-
- if (!facelet_get_error(facelet))
- continue;
-
- char buf[MAXSZ_FACELET];
- facelet_snprintf(buf, MAXSZ_FACELET, facelet);
- DEBUG("Reattempt to process failed facelet %s", buf);
- if (facemgr_process_facelet(facemgr, facelet) < 0) {
- ERROR("[facemgr_reattempt_timeout] Error processing facelet");
- has_error = true;
- continue;
- }
- facelet_unset_error(facelet);
- }
- free(facelet_array);
+ continue;
+ }
+ facelet_unset_error(facelet);
}
+ free(facelet_array);
+ }
- if (has_error)
- return 0;
+ if (has_error) return 0;
- DEBUG("Cancelling timer");
- if (facemgr->callback(facemgr->callback_owner,
- FACEMGR_CB_TYPE_UNREGISTER_TIMER, &facemgr->timer_fd) < 0) {
- ERROR("[facemgr_reattempt_timeout] Error unregistering reattempt timer");
- return -1;
- }
- facemgr->timer_fd = 0;
- return 0;
+ DEBUG("Cancelling timer");
+ if (facemgr->callback(facemgr->callback_owner,
+ FACEMGR_CB_TYPE_UNREGISTER_TIMER,
+ &facemgr->timer_fd) < 0) {
+ ERROR("[facemgr_reattempt_timeout] Error unregistering reattempt timer");
+ return -1;
+ }
+ facemgr->timer_fd = 0;
+ return 0;
}
-int
-facemgr_start_reattempts(facemgr_t * facemgr)
-{
- if (facemgr->timer_fd > 0)
- return 0;
-
- timer_callback_data_t timer_callback = {
- .delay_ms = DEFAULT_REATTEMPT_DELAY_MS,
- .owner = facemgr,
- .callback = (fd_callback_t)facemgr_reattempt_timeout,
- .data = NULL,
- };
- facemgr->timer_fd = facemgr->callback(facemgr->callback_owner,
- FACEMGR_CB_TYPE_REGISTER_TIMER, &timer_callback);
- return (facemgr->timer_fd > 0);
+int facemgr_start_reattempts(facemgr_t *facemgr) {
+ if (facemgr->timer_fd > 0) return 0;
+
+ timer_callback_data_t timer_callback = {
+ .delay_ms = DEFAULT_REATTEMPT_DELAY_MS,
+ .owner = facemgr,
+ .callback = (fd_callback_t)facemgr_reattempt_timeout,
+ .data = NULL,
+ };
+ facemgr->timer_fd = facemgr->callback(
+ facemgr->callback_owner, FACEMGR_CB_TYPE_REGISTER_TIMER, &timer_callback);
+ return (facemgr->timer_fd > 0);
}
/**
@@ -1261,218 +1181,226 @@ facemgr_start_reattempts(facemgr_t * facemgr)
* \return 0 if everything went correctly, or -1 in case of error.
* -2 means we ignored the face purposedly
*/
-int
-facemgr_process_facelet_create(facemgr_t * facemgr, facelet_t * facelet)
-{
- char facelet_s[MAXSZ_FACELET];
- facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet);
- DEBUG("[facemgr_process_facelet_create] %s", facelet_s);
- switch(facelet_get_status(facelet)) {
- case FACELET_STATUS_UNCERTAIN:
- case FACELET_STATUS_INCOMPLETE:
- case FACELET_STATUS_CREATE:
- /* No change */
- DEBUG("[facemgr_process_facelet_create] UNCHANGED STATUS");
- break;
- case FACELET_STATUS_UPDATE:
- case FACELET_STATUS_DELETE:
- /*
- * Unlikely. The face had been created and is planned to
- * be deleted. Schedule for creation (we should have all
- * needed information), but make sure to handle errors
- * correctly if the face is still present.
- * TODO What if some fields have been updated ?
- */
- DEBUG("[facemgr_process_facelet_create] SET STATUS TO CREATE");
- facelet_set_status(facelet, FACELET_STATUS_CREATE);
- break;
- case FACELET_STATUS_CLEAN:
- case FACELET_STATUS_IGNORED:
- /*
- * We should have nothing to do unless some fields have
- * been updated.
- */
- DEBUG("[facemgr_process_facelet_create] NOTHING TO DO");
- break;
-
- case FACELET_STATUS_DOWN:
- case FACELET_STATUS_DELETED:
- /*
- * Unless rules have changed, we only need to recover
- * missing information, and proceed to face creation.
- * Rule changes should be handled separately.
- */
- DEBUG("[facemgr_process_facelet_create] SET STATUS TO INCOMPLETE");
- facelet_set_status(facelet, FACELET_STATUS_INCOMPLETE);
- break;
- case FACELET_STATUS_UNDEFINED:
- case FACELET_STATUS_N:
- ERROR("[facemgr_process_facelet_create] Unexpected facelet status");
- return -1;
- }
-
-
- DEBUG("[facemgr_process_facelet_create] Processing facelet");
- if (facemgr_process_facelet(facemgr, facelet) < 0) {
- ERROR("[facemgr_process_facelet_create] Error processing facelet");
- return -1;
- }
+int facemgr_process_facelet_create(facemgr_t *facemgr, facelet_t *facelet) {
+ char facelet_s[MAXSZ_FACELET];
+ facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet);
+ DEBUG("[facemgr_process_facelet_create] %s", facelet_s);
+ switch (facelet_get_status(facelet)) {
+ case FACELET_STATUS_UNCERTAIN:
+ case FACELET_STATUS_INCOMPLETE:
+ case FACELET_STATUS_CREATE:
+ /* No change */
+ DEBUG("[facemgr_process_facelet_create] UNCHANGED STATUS");
+ break;
+ case FACELET_STATUS_UPDATE:
+ case FACELET_STATUS_DELETE:
+ /*
+ * Unlikely. The face had been created and is planned to
+ * be deleted. Schedule for creation (we should have all
+ * needed information), but make sure to handle errors
+ * correctly if the face is still present.
+ * TODO What if some fields have been updated ?
+ */
+ DEBUG("[facemgr_process_facelet_create] SET STATUS TO CREATE");
+ facelet_set_status(facelet, FACELET_STATUS_CREATE);
+ break;
+ case FACELET_STATUS_CLEAN:
+ case FACELET_STATUS_IGNORED:
+ /*
+ * We should have nothing to do unless some fields have
+ * been updated.
+ */
+ DEBUG("[facemgr_process_facelet_create] NOTHING TO DO");
+ break;
+
+ case FACELET_STATUS_DOWN:
+ case FACELET_STATUS_DELETED:
+ /*
+ * Unless rules have changed, we only need to recover
+ * missing information, and proceed to face creation.
+ * Rule changes should be handled separately.
+ */
+ DEBUG("[facemgr_process_facelet_create] SET STATUS TO INCOMPLETE");
+ facelet_set_status(facelet, FACELET_STATUS_INCOMPLETE);
+ break;
+ case FACELET_STATUS_UNDEFINED:
+ case FACELET_STATUS_N:
+ ERROR("[facemgr_process_facelet_create] Unexpected facelet status");
+ return -1;
+ }
+
+ DEBUG("[facemgr_process_facelet_create] Processing facelet");
+ if (facemgr_process_facelet(facemgr, facelet) < 0) {
+ ERROR("[facemgr_process_facelet_create] Error processing facelet");
+ return -1;
+ }
- return 0;
+ return 0;
}
/*
* \return 0 in case of success and no static facelet was added, 1 if a static
* facelet was added, and -1 in case of error.
*/
-int
-facemgr_consider_static_facelet(facemgr_t * facemgr, facelet_t * facelet)
-{
- /*
- * We need to analyze the facelet and eventually:
- * - add it in our static list
- * - replicate it on multipath interfaces
- */
- netdevice_type_t netdevice_type;
- if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0)
- return -1;
-
- if ((netdevice_type == NETDEVICE_TYPE_UNDEFINED) ||
- (netdevice_type == NETDEVICE_TYPE_LOOPBACK))
- return 0;
-
- if ((facelet_get_route_array(facelet, NULL) == 0))
- return 0;
-
- /*
- * How to differenciate facelet created by face manager from user
- * created ones ? This cannot be a flag in the facelet as it needs
- * to work across restarts of the face manager...
- * Also we might have two default routes.
- *
- * TODO:
- * - The static one should not be a duplicate of the one we would
- * create by default....
- * - This should anyways be detected...
- *
- * One solution would be to install the default ones as static but
- * this requires to implement a priority scheme between some of the
- * static routes so that the override mechanism continues to work as
- * usual.
- *
- * Current, we recognize the routes created by default by the face
- * maanger thanks to the routing prefixes (a single default route).
- */
-
- facelet_t * static_facelet = facelet_dup(facelet);
- facelet_set_event(static_facelet, FACELET_EVENT_CREATE);
- facelet_unset_netdevice(static_facelet);
- facelet_unset_netdevice_type(static_facelet);
- facelet_unset_local_addr(static_facelet);
- facelet_unset_local_port(static_facelet);
-
- facelet_t * facelet_found = NULL;
- if (facelet_array_get(facemgr->static_facelets, static_facelet, &facelet_found) < 0) {
- ERROR("[facemgr_consider_static_facelet] Error checking whether static facelet already exists or not");
- return -1;
- }
+int facemgr_consider_static_facelet(facemgr_t *facemgr, facelet_t *facelet) {
+ /*
+ * We need to analyze the facelet and eventually:
+ * - add it in our static list
+ * - replicate it on multipath interfaces
+ */
+ netdevice_type_t netdevice_type;
+ if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) return -1;
+
+ if ((netdevice_type == NETDEVICE_TYPE_UNDEFINED) ||
+ (netdevice_type == NETDEVICE_TYPE_LOOPBACK))
+ return 0;
- /* Skip addition if facelet exists */
- if (facelet_found)
- return 0;
+ if ((facelet_get_route_array(facelet, NULL) == 0)) return 0;
+
+ /*
+ * How to differenciate facelet created by face manager from user
+ * created ones ? This cannot be a flag in the facelet as it needs
+ * to work across restarts of the face manager...
+ * Also we might have two default routes.
+ *
+ * TODO:
+ * - The static one should not be a duplicate of the one we would
+ * create by default....
+ * - This should anyways be detected...
+ *
+ * One solution would be to install the default ones as static but
+ * this requires to implement a priority scheme between some of the
+ * static routes so that the override mechanism continues to work as
+ * usual.
+ *
+ * Current, we recognize the routes created by default by the face
+ * maanger thanks to the routing prefixes (a single default route).
+ */
+
+ facelet_t *static_facelet = facelet_dup(facelet);
+ facelet_set_event(static_facelet, FACELET_EVENT_CREATE);
+ facelet_unset_netdevice(static_facelet);
+ facelet_unset_netdevice_type(static_facelet);
+ facelet_unset_local_addr(static_facelet);
+ facelet_unset_local_port(static_facelet);
+
+ facelet_t *facelet_found = NULL;
+ if (facelet_array_get(facemgr->static_facelets, static_facelet,
+ &facelet_found) < 0) {
+ ERROR(
+ "[facemgr_consider_static_facelet] Error checking whether static "
+ "facelet already exists or not");
+ return -1;
+ }
- facemgr->cur_static_id++;
+ /* Skip addition if facelet exists */
+ if (facelet_found) return 0;
- facelet_set_id(static_facelet, facemgr->cur_static_id);
- facelet_set_id(facelet, facemgr->cur_static_id);
+ facemgr->cur_static_id++;
- if (facelet_array_add(facemgr->static_facelets, static_facelet) < 0) {
- ERROR("[facemgr_consider_static_facelet] Could not add facelet to static array");
- facelet_free(static_facelet);
- return -1;
- }
+ facelet_set_id(static_facelet, facemgr->cur_static_id);
+ facelet_set_id(facelet, facemgr->cur_static_id);
- char facelet_s[MAXSZ_FACELET];
- int rc = facelet_snprintf(facelet_s, MAXSZ_FACELET, static_facelet);
- if (rc >= MAXSZ_FACELET)
- ERROR("[facemgr_consider_static_facelet] Unexpected truncation of facelet string");
- if (rc < 0)
- ERROR("[facemgr_consider_static_facelet] Error during facelet string output");
- DEBUG("[facemgr_consider_static_facelet] Successfully added facelet to static array %s", facelet_s);
+ if (facelet_array_add(facemgr->static_facelets, static_facelet) < 0) {
+ ERROR(
+ "[facemgr_consider_static_facelet] Could not add facelet to static "
+ "array");
+ facelet_free(static_facelet);
+ return -1;
+ }
+
+ char facelet_s[MAXSZ_FACELET];
+ int rc = facelet_snprintf(facelet_s, MAXSZ_FACELET, static_facelet);
+ if (rc >= MAXSZ_FACELET)
+ ERROR(
+ "[facemgr_consider_static_facelet] Unexpected truncation of facelet "
+ "string");
+ if (rc < 0)
+ ERROR(
+ "[facemgr_consider_static_facelet] Error during facelet string output");
+ DEBUG(
+ "[facemgr_consider_static_facelet] Successfully added facelet to static "
+ "array %s",
+ facelet_s);
#if 1
- /* Force application of the static face on all existing interfaces */
- facelet_t ** facelet_array;
- int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
- if (n >= 0) {
- for (unsigned i = 0; i < n; i++) {
- facelet_t * cached_facelet = facelet_array[i];
-
- netdevice_type_t netdevice_type;
- if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
- ERROR("[facemgr_consider_static_facelet] Error retrieving netdevice type from cached facelet");
- continue;
- }
- if ((netdevice_type == NETDEVICE_TYPE_LOOPBACK) || (netdevice_type == NETDEVICE_TYPE_UNDEFINED))
- continue;
-
- facelet_t * new_facelet = facelet_dup(cached_facelet);
- facelet_unset_remote_addr(new_facelet);
- facelet_unset_remote_port(new_facelet);
- facelet_unset_admin_state(new_facelet);
- facelet_unset_state(new_facelet);
- facelet_unset_bj_done(new_facelet);
- facelet_clear_routes(new_facelet);
-#ifdef WITH_FACEMGR_UTILITY
- facelet_unset_au_done(new_facelet);
-#endif /* WITH_FACEMGR_UTILITY */
-
- /* We try to apply static_facelet over facelet */
- if (!facelet_match(new_facelet, static_facelet)) {
- facelet_free(new_facelet);
- continue;
- }
-
- if (facelet_merge(new_facelet, static_facelet) < 0) {
- ERROR("[facemgr_consider_static_facelet] Error merging facelets");
- facelet_free(new_facelet);
- continue;
- }
-
- /*
- * We need to set the id before checking for existence as tuple used
- * is (id, netdevice, family)
- */
- facelet_set_id(new_facelet, facemgr->cur_static_id);
-
- facelet_found = NULL;
- if (facelet_set_get(facemgr->facelet_cache, new_facelet, &facelet_found) < 0) {
- ERROR("[facemgr_consider_static_facelet] Error checking whether new static facelet already exists or not");
- continue;
- }
-
-
- /* Skip addition if facelet exists */
- if (facelet_found) {
- facelet_free(new_facelet);
- continue;
- }
-
- facelet_set_attr_clean(new_facelet);
- facelet_set_status(facelet, FACELET_STATUS_UNDEFINED);
-
- if (facemgr_on_event(facemgr, new_facelet) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error creating static facelet for existing face");
- continue;
- }
-
- INFO("Successfully created static facelet for existing face");
- }
- free(facelet_array);
+ /* Force application of the static face on all existing interfaces */
+ facelet_t **facelet_array;
+ int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
+ if (n >= 0) {
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *cached_facelet = facelet_array[i];
+ if (!cached_facelet) continue; /* Should not occur */
+
+ netdevice_type_t netdevice_type;
+ if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
+ ERROR(
+ "[facemgr_consider_static_facelet] Error retrieving netdevice type "
+ "from cached facelet");
+ continue;
+ }
+ if ((netdevice_type == NETDEVICE_TYPE_LOOPBACK) ||
+ (netdevice_type == NETDEVICE_TYPE_UNDEFINED))
+ continue;
+
+ facelet_t *new_facelet = facelet_dup(cached_facelet);
+ facelet_unset_remote_addr(new_facelet);
+ facelet_unset_remote_port(new_facelet);
+ facelet_unset_admin_state(new_facelet);
+ facelet_unset_state(new_facelet);
+ facelet_unset_bj_done(new_facelet);
+ facelet_clear_routes(new_facelet);
+
+ /* We try to apply static_facelet over facelet */
+ if (!facelet_match(new_facelet, static_facelet)) {
+ facelet_free(new_facelet);
+ continue;
+ }
+
+ if (facelet_merge(new_facelet, static_facelet) < 0) {
+ ERROR("[facemgr_consider_static_facelet] Error merging facelets");
+ facelet_free(new_facelet);
+ continue;
+ }
+
+ /*
+ * We need to set the id before checking for existence as tuple used
+ * is (id, netdevice, family)
+ */
+ facelet_set_id(new_facelet, facemgr->cur_static_id);
+
+ facelet_found = NULL;
+ if (facelet_set_get(facemgr->facelet_cache, new_facelet, &facelet_found) <
+ 0) {
+ ERROR(
+ "[facemgr_consider_static_facelet] Error checking whether new "
+ "static facelet already exists or not");
+ continue;
+ }
+
+ /* Skip addition if facelet exists */
+ if (facelet_found) {
+ facelet_free(new_facelet);
+ continue;
+ }
+
+ facelet_set_attr_clean(new_facelet);
+ facelet_set_status(facelet, FACELET_STATUS_UNDEFINED);
+
+ if (facemgr_on_event(facemgr, new_facelet) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error creating static "
+ "facelet for existing face");
+ continue;
+ }
+
+ INFO("Successfully created static facelet for existing face");
}
+ free(facelet_array);
+ }
#endif
- return 1;
+ return 1;
}
/**
@@ -1482,93 +1410,96 @@ facemgr_consider_static_facelet(facemgr_t * facemgr, facelet_t * facelet)
* \return 0 if everything went correctly, or -1 in case of error.
* -2 means we ignored the face purposedly
*/
-int
-facemgr_process_facelet_get(facemgr_t * facemgr, facelet_t * facelet)
-{
- assert(facelet);
+int facemgr_process_facelet_get(facemgr_t *facemgr, facelet_t *facelet) {
+ assert(facelet);
- if (!facelet_has_netdevice(facelet))
- return -2;
+ if (!facelet_has_netdevice(facelet)) return -2;
- netdevice_t netdevice;
- if (facelet_get_netdevice(facelet, &netdevice) < 0)
- return -1;
- if (!IS_VALID_NETDEVICE(netdevice))
- return -2;
+ netdevice_t netdevice;
+ if (facelet_get_netdevice(facelet, &netdevice) < 0) return -1;
+ if (!IS_VALID_NETDEVICE(netdevice)) return -2;
- facelet_set_status(facelet, FACELET_STATUS_CLEAN);
+ facelet_set_status(facelet, FACELET_STATUS_CLEAN);
- /* Skip if face exists */
- int n = facelet_cache_lookup(facemgr->facelet_cache, facelet, NULL);
- if (n < 0) {
- ERROR("[facemgr_process_facelet_get] Error during cache lookup");
- return -1;
- }
- assert (n <= 1);
- if (n > 0)
- return 0;
-
- /* Process untagged faces */
- netdevice_type_t netdevice_type;
+ /* Skip if face exists */
+ int n = facelet_cache_lookup(facemgr->facelet_cache, facelet, NULL);
+ if (n < 0) {
+ ERROR("[facemgr_process_facelet_get] Error during cache lookup");
+ return -1;
+ }
+ assert(n <= 1);
+ if (n > 0) return 0;
+
+ /* Process untagged faces */
+ netdevice_type_t netdevice_type;
+ if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
+ facelet_set_netdevice_type(
+ facelet, facemgr_get_netdevice_type(facemgr, netdevice.name));
if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
- facelet_set_netdevice_type(facelet, facemgr_get_netdevice_type(facemgr, netdevice.name));
- if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
- /* Inspect local address */
- int family;
- ip_address_t local;
- if (facelet_get_family(facelet, &family) < 0) {
- ERROR("[facemgr_process_facelet_get] Error getting facelet family");
- return -1;
- }
- if (facelet_get_local_addr(facelet, &local) < 0) {
- ERROR("[facemgr_process_facelet_get] Error getting facelet local address");
- return -1;
- }
- switch(family) {
- case AF_INET:
- if (ip_address_cmp(&local, &IPV4_LOOPBACK, family) == 0) {
- facelet_set_netdevice_type(facelet, NETDEVICE_TYPE_LOOPBACK);
- } else {
- return -2;
- }
- break;
- case AF_INET6:
- if (ip_address_cmp(&local, &IPV6_LOOPBACK, family) == 0) {
- facelet_set_netdevice_type(facelet, NETDEVICE_TYPE_LOOPBACK);
- } else {
- return -2;
- }
- break;
- default:
- return -2;
- }
- }
-
- if ((netdevice_type == NETDEVICE_TYPE_UNDEFINED) || (netdevice_type == NETDEVICE_TYPE_LOOPBACK))
- return 0;
-
- if (facemgr_process_facelet(facemgr, facelet) < 0) {
- ERROR("[facemgr_process_facelet_get] Error processing facelet");
- return -1;
- }
- }
-
- if ((netdevice_type == NETDEVICE_TYPE_UNDEFINED) || (netdevice_type == NETDEVICE_TYPE_LOOPBACK))
- return 0;
-
- if (facelet_set_add(facemgr->facelet_cache, facelet) < 0) {
- ERROR("[facemgr_process_facelet_get] Error adding received facelet to cache");
+ /* Inspect local address */
+ int family;
+ hicn_ip_address_t local;
+ if (facelet_get_family(facelet, &family) < 0) {
+ ERROR("[facemgr_process_facelet_get] Error getting facelet family");
return -1;
+ }
+ if (facelet_get_local_addr(facelet, &local) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_get] Error getting facelet local "
+ "address");
+ return -1;
+ }
+ switch (family) {
+ case AF_INET:
+ if (hicn_ip_address_cmp(&local, &IPV4_LOOPBACK) == 0) {
+ facelet_set_netdevice_type(facelet, NETDEVICE_TYPE_LOOPBACK);
+ } else {
+ return -2;
+ }
+ break;
+ case AF_INET6:
+ if (hicn_ip_address_cmp(&local, &IPV6_LOOPBACK) == 0) {
+ facelet_set_netdevice_type(facelet, NETDEVICE_TYPE_LOOPBACK);
+ } else {
+ return -2;
+ }
+ break;
+ default:
+ return -2;
+ }
}
- n = facemgr_consider_static_facelet(facemgr, facelet);
- if (n < 0) {
- ERROR("[facemgr_process_facelet_get] Could not add facelet to static array");
- return -1;
+ if ((netdevice_type == NETDEVICE_TYPE_UNDEFINED) ||
+ (netdevice_type == NETDEVICE_TYPE_LOOPBACK))
+ return -2;
+
+ if (facemgr_process_facelet(facemgr, facelet) < 0) {
+ ERROR("[facemgr_process_facelet_get] Error processing facelet");
+ return -1;
}
+ }
+ if ((netdevice_type == NETDEVICE_TYPE_UNDEFINED) ||
+ (netdevice_type == NETDEVICE_TYPE_LOOPBACK))
+ return -2;
- return 0;
+ if (facelet_set_add(facemgr->facelet_cache, facelet) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_get] Error adding received facelet to cache");
+ return -1;
+ }
+
+ /*
+ * From there, don't raise errors otherwise the facelet just added to cache
+ * will be freed
+ */
+ n = facemgr_consider_static_facelet(facemgr, facelet);
+ if (n < 0) {
+ ERROR(
+ "[facemgr_process_facelet_get] Could not add facelet to static array");
+ }
+
+ return 0;
}
/**
@@ -1578,45 +1509,43 @@ facemgr_process_facelet_get(facemgr_t * facemgr, facelet_t * facelet)
* \return 0 if everything went correctly, or -1 in case of error.
* -2 means we ignored the face purposedly
*/
-int
-facemgr_process_facelet_update(facemgr_t * facemgr, facelet_t * facelet)
-{
- char facelet_s[MAXSZ_FACELET];
- facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet);
- DEBUG("[facemgr_process_facelet_update] %s", facelet_s);
- switch(facelet_get_status(facelet)) {
- case FACELET_STATUS_UNCERTAIN:
- case FACELET_STATUS_INCOMPLETE:
- case FACELET_STATUS_CREATE:
- case FACELET_STATUS_UPDATE:
- /* No change */
- DEBUG("[facemgr_process_facelet_update] UNCHANGED STATUS");
- break;
- case FACELET_STATUS_CLEAN:
- DEBUG("[facemgr_process_facelet_update] SET STATUS TO UPDATE");
- facelet_set_status(facelet, FACELET_STATUS_UPDATE);
- break;
- case FACELET_STATUS_DOWN:
- case FACELET_STATUS_DELETE:
- case FACELET_STATUS_DELETED:
- case FACELET_STATUS_IGNORED:
- /* Reconsider face creation in light of new information */
- DEBUG("[facemgr_process_facelet_update] SET STATUS TO UNCERTAIN");
- facelet_set_status(facelet, FACELET_STATUS_UNCERTAIN);
- break;
- case FACELET_STATUS_UNDEFINED:
- case FACELET_STATUS_N:
- ERROR("[facemgr_process_facelet_update] Unexpected facelet status");
- return -1;
- }
-
- DEBUG("[facemgr_process_facelet_update] Processing facelet");
- if (facemgr_process_facelet(facemgr, facelet) < 0) {
- ERROR("[facemgr_process_facelet_update] Error processing facelet");
- return -1;
- }
+int facemgr_process_facelet_update(facemgr_t *facemgr, facelet_t *facelet) {
+ char facelet_s[MAXSZ_FACELET];
+ facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet);
+ DEBUG("[facemgr_process_facelet_update] %s", facelet_s);
+ switch (facelet_get_status(facelet)) {
+ case FACELET_STATUS_UNCERTAIN:
+ case FACELET_STATUS_INCOMPLETE:
+ case FACELET_STATUS_CREATE:
+ case FACELET_STATUS_UPDATE:
+ /* No change */
+ DEBUG("[facemgr_process_facelet_update] UNCHANGED STATUS");
+ break;
+ case FACELET_STATUS_CLEAN:
+ DEBUG("[facemgr_process_facelet_update] SET STATUS TO UPDATE");
+ facelet_set_status(facelet, FACELET_STATUS_UPDATE);
+ break;
+ case FACELET_STATUS_DOWN:
+ case FACELET_STATUS_DELETE:
+ case FACELET_STATUS_DELETED:
+ case FACELET_STATUS_IGNORED:
+ /* Reconsider face creation in light of new information */
+ DEBUG("[facemgr_process_facelet_update] SET STATUS TO UNCERTAIN");
+ facelet_set_status(facelet, FACELET_STATUS_UNCERTAIN);
+ break;
+ case FACELET_STATUS_UNDEFINED:
+ case FACELET_STATUS_N:
+ ERROR("[facemgr_process_facelet_update] Unexpected facelet status");
+ return -1;
+ }
+
+ DEBUG("[facemgr_process_facelet_update] Processing facelet");
+ if (facemgr_process_facelet(facemgr, facelet) < 0) {
+ ERROR("[facemgr_process_facelet_update] Error processing facelet");
+ return -1;
+ }
- return 0;
+ return 0;
}
/**
@@ -1626,15 +1555,13 @@ facemgr_process_facelet_update(facemgr_t * facemgr, facelet_t * facelet)
* \return 0 if everything went correctly, or -1 in case of error.
* -2 means we ignored the face purposedly
*/
-int
-facemgr_process_facelet_delete(facemgr_t * facemgr, facelet_t * facelet)
-{
- switch(facelet_get_status(facelet)) {
- case FACELET_STATUS_UNCERTAIN:
- case FACELET_STATUS_INCOMPLETE:
- case FACELET_STATUS_IGNORED:
- case FACELET_STATUS_DOWN:
- case FACELET_STATUS_CREATE:
+int facemgr_process_facelet_delete(facemgr_t *facemgr, facelet_t *facelet) {
+ switch (facelet_get_status(facelet)) {
+ case FACELET_STATUS_UNCERTAIN:
+ case FACELET_STATUS_INCOMPLETE:
+ case FACELET_STATUS_IGNORED:
+ case FACELET_STATUS_DOWN:
+ case FACELET_STATUS_CREATE:
#if 0
/* Facelets created from static get deleted */
if (facelet_get_id(facelet) > 0) {
@@ -1645,142 +1572,160 @@ facemgr_process_facelet_delete(facemgr_t * facemgr, facelet_t * facelet)
facelet_free(facelet);
} else {
#endif
- /* Face has not been created */
- DEBUG("[facemgr_process_facelet] Cleaning cached data");
- facelet_unset_local_addr(facelet);
- facelet_unset_local_port(facelet);
- if (facelet_get_id(facelet) == 0) {
- facelet_unset_remote_addr(facelet);
- facelet_unset_remote_port(facelet);
- facelet_clear_routes(facelet);
- }
- facelet_unset_admin_state(facelet);
- facelet_unset_state(facelet);
- facelet_unset_bj_done(facelet);
-#ifdef WITH_FACEMGR_UTILITY
- facelet_unset_au_done(facelet);
-#endif /* WITH_FACEMGR_UTILITY */
- facelet_unset_error(facelet);
- facelet_set_status(facelet, FACELET_STATUS_DELETED);
+ /* Face has not been created */
+ DEBUG("[facemgr_process_facelet] Cleaning cached data");
+ facelet_unset_local_addr(facelet);
+ facelet_unset_local_port(facelet);
+ if (facelet_get_id(facelet) == 0) {
+ facelet_unset_remote_addr(facelet);
+ facelet_unset_remote_port(facelet);
+ facelet_clear_routes(facelet);
+ }
+ facelet_unset_admin_state(facelet);
+ facelet_unset_state(facelet);
+ facelet_unset_bj_done(facelet);
+ facelet_unset_error(facelet);
+ facelet_set_status(facelet, FACELET_STATUS_DELETED);
#if 0
}
#endif
- break;
-
- case FACELET_STATUS_UPDATE:
- case FACELET_STATUS_CLEAN:
- facelet_set_status(facelet, FACELET_STATUS_DELETE);
- if (facemgr_process_facelet(facemgr, facelet) < 0) {
- ERROR("[facemgr_process_facelet_delete] Error processing facelet");
- return -1;
- }
- break;
+ break;
- case FACELET_STATUS_DELETE:
- case FACELET_STATUS_DELETED:
- /* Nothing to do */
- break;
+ case FACELET_STATUS_UPDATE:
+ case FACELET_STATUS_CLEAN:
+ facelet_set_status(facelet, FACELET_STATUS_DELETE);
+ if (facemgr_process_facelet(facemgr, facelet) < 0) {
+ ERROR("[facemgr_process_facelet_delete] Error processing facelet");
+ return -1;
+ }
+ break;
- case FACELET_STATUS_UNDEFINED:
- case FACELET_STATUS_N:
- ERROR("[facemgr_process_facelet_delete] Unexpected facelet status");
- return -1;
- }
+ case FACELET_STATUS_DELETE:
+ case FACELET_STATUS_DELETED:
+ /* Nothing to do */
+ break;
- return 0;
-}
+ case FACELET_STATUS_UNDEFINED:
+ case FACELET_STATUS_N:
+ ERROR("[facemgr_process_facelet_delete] Unexpected facelet status");
+ return -1;
+ }
-int
-facemgr_process_facelet_create_no_family(facemgr_t * facemgr, facelet_t * facelet)
-{
+ return 0;
+}
+int facemgr_process_facelet_create_no_family(facemgr_t *facemgr,
+ facelet_t *facelet) {
#ifdef WITH_DEFAULT_PRIORITIES
- /* Assign default priority based on face type */
- netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
- if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error getting netdevice_type: no default priority set.");
- goto ERR_PRIORITY;
- }
- if (facelet_set_priority(facelet, facemgr->default_priority[netdevice_type]) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error setting default priority");
- }
+ /* Assign default priority based on face type */
+ netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error getting "
+ "netdevice_type: no default priority set.");
+ goto ERR_PRIORITY;
+ }
+ if (facelet_set_priority(facelet, facemgr->default_priority[netdevice_type]) <
+ 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error setting default "
+ "priority");
+ }
ERR_PRIORITY:
#endif /* WITH_DEFAULT_PRIORITIES */
- DEBUG("[facemgr_process_facelet_create_no_family] Default v4");
- /* Create default v4 and v6 facelets */
- facelet_t * facelet_v4 = facelet_dup(facelet);
- if (!facelet_v4) {
- ERROR("[facemgr_process_facelet_create_no_family] Error allocating default IPv4 face");
- } else {
- facelet_set_family(facelet_v4, AF_INET);
- facelet_set_attr_clean(facelet_v4);
- if (facemgr_on_event(facemgr, facelet_v4) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error creating default IPv4 face");
- //facelet_free(facelet_v4);
- }
- }
-
- DEBUG("[facemgr_process_facelet_create_no_family] Default v6");
- facelet_t * facelet_v6 = facelet_dup(facelet);
- if (!facelet_v6) {
- ERROR("[facemgr_process_facelet_create_no_family] Error allocating default IPv6 face");
- } else {
- facelet_set_family(facelet_v6, AF_INET6);
- facelet_set_attr_clean(facelet_v6);
- if (facemgr_on_event(facemgr, facelet_v6) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error creating default IPv6 face");
- //facelet_free(facelet_v6);
- }
+ DEBUG("[facemgr_process_facelet_create_no_family] Default v4");
+ /* Create default v4 and v6 facelets */
+ facelet_t *facelet_v4 = facelet_dup(facelet);
+ if (!facelet_v4) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error allocating default "
+ "IPv4 face");
+ } else {
+ facelet_set_family(facelet_v4, AF_INET);
+ facelet_set_attr_clean(facelet_v4);
+ if (facemgr_on_event(facemgr, facelet_v4) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error creating default "
+ "IPv4 face");
+ // facelet_free(facelet_v4);
+ }
+ }
+
+ DEBUG("[facemgr_process_facelet_create_no_family] Default v6");
+ facelet_t *facelet_v6 = facelet_dup(facelet);
+ if (!facelet_v6) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error allocating default "
+ "IPv6 face");
+ } else {
+ facelet_set_family(facelet_v6, AF_INET6);
+ facelet_set_attr_clean(facelet_v6);
+ if (facemgr_on_event(facemgr, facelet_v6) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error creating default "
+ "IPv6 face");
+ // facelet_free(facelet_v6);
+ }
+ }
+
+ /* Create additional connections
+ *
+ * This is where we spawn multiple facelets based on the
+ * configured "static routes" in addition to the default
+ * routes managed by the face manager.
+ */
+ DEBUG("[facemgr_process_facelet_create_no_family] Loop static");
+ int n = (int)facelet_array_len(facemgr->static_facelets);
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *static_facelet;
+ if (facelet_array_get_index(facemgr->static_facelets, i, &static_facelet) <
+ 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error getting static "
+ "facelet");
+ continue;
}
- /* Create additional connections
- *
- * This is where we spawn multiple facelets based on the
- * configured "static routes" in addition to the default
- * routes managed by the face manager.
+ /*
+ * We don't enforce any present or absent fields. A match
+ * operation will be performed deciding whether to create
+ * the facelet (if it bring additional information to the
+ * ingress one) or not.
*/
- DEBUG("[facemgr_process_facelet_create_no_family] Loop static");
- for (unsigned i = 0; i < facelet_array_len(facemgr->static_facelets); i++) {
- facelet_t * static_facelet;
- if (facelet_array_get_index(facemgr->static_facelets, i, &static_facelet) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error getting static facelet");
- continue;
- }
-
- /*
- * We don't enforce any present or absent fields. A match
- * operation will be performed deciding whether to create
- * the facelet (if it bring additional information to the
- * ingress one) or not.
- */
- /* We try to apply static_facelet over facelet */
- if (!facelet_match(facelet, static_facelet)) {
- continue;
- }
-
- facelet_t * facelet_new = facelet_dup(facelet);
- if (!facelet_new) {
- ERROR("[facemgr_process_facelet_create_no_family] Error allocating static facelet");
- continue;
- } else {
- if (facelet_merge(facelet_new, static_facelet) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error merging facelets");
- facelet_free(facelet_new);
- continue;
- }
- facelet_set_id(facelet_new, facelet_get_id(static_facelet));
- facelet_set_attr_clean(facelet_new);
- facelet_set_status(facelet, FACELET_STATUS_UNDEFINED);
-
- if (facemgr_on_event(facemgr, facelet_new) < 0) {
- ERROR("[facemgr_process_facelet_create_no_family] Error creating default IPv6 face");
- //facelet_free(facelet_new);
- }
- }
+ /* We try to apply static_facelet over facelet */
+ if (!facelet_match(facelet, static_facelet)) {
+ continue;
}
- return 0;
+ facelet_t *facelet_new = facelet_dup(facelet);
+ if (!facelet_new) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error allocating static "
+ "facelet");
+ continue;
+ } else {
+ if (facelet_merge(facelet_new, static_facelet) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error merging "
+ "facelets");
+ facelet_free(facelet_new);
+ continue;
+ }
+ facelet_set_id(facelet_new, facelet_get_id(static_facelet));
+ facelet_set_attr_clean(facelet_new);
+ facelet_set_status(facelet, FACELET_STATUS_UNDEFINED);
+
+ if (facemgr_on_event(facemgr, facelet_new) < 0) {
+ ERROR(
+ "[facemgr_process_facelet_create_no_family] Error creating default "
+ "IPv6 face");
+ // facelet_free(facelet_new);
+ }
+ }
+ }
+
+ return 0;
}
/**
@@ -1790,30 +1735,29 @@ ERR_PRIORITY:
* - Any event or timeout due to an interface triggers either a local cache
* update, as well a face operations needed to resync the state.
*/
-int
-facemgr_on_event(facemgr_t * facemgr, facelet_t * facelet_in)
-{
- bool remove_facelet = true;
-#if WITH_DUMP
- bool dump = true;
+int facemgr_on_event(facemgr_t *facemgr, facelet_t *facelet_in) {
+ bool remove_facelet = true;
+#ifdef WITH_DUMP
+ bool dump = true;
#endif /* WITH_DUMP */
- int ret = 0;
- int rc;
- assert(facelet_in);
-
- /* Update Netdevice type */
- if ((facelet_get_event(facelet_in) != FACELET_EVENT_GET) &&
- facelet_has_netdevice(facelet_in) &&
- (!facelet_has_netdevice_type(facelet_in))) {
- netdevice_t netdevice = NETDEVICE_EMPTY;
+ int ret = 0;
+ int rc;
+ assert(facelet_in);
+
+ /* Update Netdevice type */
+ if ((facelet_get_event(facelet_in) != FACELET_EVENT_GET) &&
+ facelet_has_netdevice(facelet_in) &&
+ (!facelet_has_netdevice_type(facelet_in))) {
+ netdevice_t netdevice = NETDEVICE_EMPTY;
- rc = facelet_get_netdevice(facelet_in, &netdevice);
- if (rc < 0) {
- ERROR("[facemgr_on_event] Error retrieving netdevice from facelet");
- return -1;
- }
- facelet_set_netdevice_type(facelet_in, facemgr_get_netdevice_type(facemgr, netdevice.name));
+ rc = facelet_get_netdevice(facelet_in, &netdevice);
+ if (rc < 0) {
+ ERROR("[facemgr_on_event] Error retrieving netdevice from facelet");
+ return -1;
}
+ facelet_set_netdevice_type(
+ facelet_in, facemgr_get_netdevice_type(facemgr, netdevice.name));
+ }
#if 0
netdevice_type_t netdevice_type;
@@ -1826,656 +1770,660 @@ facemgr_on_event(facemgr_t * facemgr, facelet_t * facelet_in)
return 0;
#endif
- char facelet_s[MAXSZ_FACELET];
- facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet_in);
+ char facelet_s[MAXSZ_FACELET];
+ facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet_in);
- facelet_t ** cached_facelets = NULL;
- assert(facelet_in);
+ facelet_t **cached_facelets = NULL;
+ assert(facelet_in);
- if (facelet_get_status(facelet_in) == FACELET_STATUS_UNDEFINED) {
- facelet_set_status(facelet_in, FACELET_STATUS_UNCERTAIN);
- }
+ if (facelet_get_status(facelet_in) == FACELET_STATUS_UNDEFINED) {
+ facelet_set_status(facelet_in, FACELET_STATUS_UNCERTAIN);
+ }
- int n = facelet_cache_lookup(facemgr->facelet_cache, facelet_in, &cached_facelets);
- if (n < 0) {
- ERROR("[facemgr_on_event] Error during cache lookup");
- free(facelet_in);
- return -1;
- }
- if (n == 0) {
- /* This is a new facelet... we expect a CREATE event. */
- switch(facelet_get_event(facelet_in)) {
- case FACELET_EVENT_CREATE:
- {
- /*
- * This is the first time we hear about a facelet, it will
- * likely not have an address family
- *
- * Assumption: we should always see the link before the address
- * assignment
- */
- DEBUG("[facemgr_on_event] CREATE NEW %s", facelet_s);
-
- if (!facelet_has_family(facelet_in)) {
- facemgr_assign_face_type(facemgr, facelet_in);
- if (facemgr_process_facelet_create_no_family(facemgr, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error processing new interface event");
- goto ERR;
- }
- goto DUMP_CACHE;
- }
+ int n = facelet_cache_lookup(facemgr->facelet_cache, facelet_in,
+ &cached_facelets);
+ if (n < 0) {
+ ERROR("[facemgr_on_event] Error during cache lookup");
+ free(facelet_in);
+ return -1;
+ }
+ if (n == 0) {
+ /* This is a new facelet... we expect a CREATE event. */
+ switch (facelet_get_event(facelet_in)) {
+ case FACELET_EVENT_CREATE: {
+ /*
+ * This is the first time we hear about a facelet, it will
+ * likely not have an address family
+ *
+ * Assumption: we should always see the link before the address
+ * assignment
+ */
+ DEBUG("[facemgr_on_event] CREATE NEW %s", facelet_s);
- if (facelet_set_add(facemgr->facelet_cache, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error adding facelet to cache");
- goto ERR;
- }
+ if (!facelet_has_family(facelet_in)) {
+ facemgr_assign_face_type(facemgr, facelet_in);
+ if (facemgr_process_facelet_create_no_family(facemgr, facelet_in) <
+ 0) {
+ ERROR("[facemgr_on_event] Error processing new interface event");
+ goto ERR;
+ }
+ goto DUMP_CACHE;
+ }
- if (facemgr_process_facelet_create(facemgr, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error processing facelet CREATE event");
- ret = -1;
- }
+ if (facelet_set_add(facemgr->facelet_cache, facelet_in) < 0) {
+ ERROR("[facemgr_on_event] Error adding facelet to cache");
+ goto ERR;
+ }
- remove_facelet = false;
+ if (facemgr_process_facelet_create(facemgr, facelet_in) < 0) {
+ ERROR("[facemgr_on_event] Error processing facelet CREATE event");
+ ret = -1;
+ }
- break;
- }
+ remove_facelet = false;
+
+ break;
+ }
- case FACELET_EVENT_GET:
- /* Insert new facelet in cached */
- //DEBUG("[facemgr_on_event] GET NEW %s", facelet_s);
- rc = facemgr_process_facelet_get(facemgr, facelet_in);
- if (rc == 0)
- remove_facelet = false;
-#if WITH_DUMP
- dump = false;
+ case FACELET_EVENT_GET:
+ /* Insert new facelet in cached */
+ // DEBUG("[facemgr_on_event] GET NEW %s", facelet_s);
+ rc = facemgr_process_facelet_get(facemgr, facelet_in);
+ if (rc == 0) remove_facelet = false;
+#ifdef WITH_DUMP
+ dump = false;
#endif
- if (rc == -1) {
- ERROR("[facemgr_on_event] Error processing GET event");
- goto ERR;
- }
- break;
+ if (rc == -1) {
+ ERROR("[facemgr_on_event] Error processing GET event");
+ goto ERR;
+ }
+ break;
- case FACELET_EVENT_UPDATE:
- /* Might be because we previously ignored the facelet... */
- //ERROR("[facemgr_on_event] Unexpected UPDATE... face does not exist");
- //goto ERR;
+ case FACELET_EVENT_UPDATE:
+ /* Might be because we previously ignored the facelet... */
+ // ERROR("[facemgr_on_event] Unexpected UPDATE... face does not exist");
+ // goto ERR;
#ifdef WITH_DEFAULT_PRIORITIES
- if (facelet_has_netdevice_type(facelet_in) && !facelet_has_netdevice(facelet_in) && facelet_has_priority(facelet_in)) {
- /* Remember last priority choice for newly created facelets */
- netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
- u32 priority = 0;
- if (facelet_get_netdevice_type(facelet_in, &netdevice_type) < 0) {
- ERROR("[facelet_on_event] Error getting netdevice_type");
- goto ERR;
- }
- if (facelet_get_priority(facelet_in, &priority) < 0) {
- ERROR("[facelet_on_event] Error getting priority");
- goto ERR;
- }
- facemgr->default_priority[netdevice_type] = priority;
- }
+ if (facelet_has_netdevice_type(facelet_in) &&
+ !facelet_has_netdevice(facelet_in) &&
+ facelet_has_priority(facelet_in)) {
+ /* Remember last priority choice for newly created facelets */
+ netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ u32 priority = 0;
+ if (facelet_get_netdevice_type(facelet_in, &netdevice_type) < 0) {
+ ERROR("[facelet_on_event] Error getting netdevice_type");
+ goto ERR;
+ }
+ if (facelet_get_priority(facelet_in, &priority) < 0) {
+ ERROR("[facelet_on_event] Error getting priority");
+ goto ERR;
+ }
+ facemgr->default_priority[netdevice_type] = priority;
+ }
#endif /* WITH_DEFAULT_PRIORITIES */
- DEBUG("[facemgr_on_event] UPDATE NEW %s", facelet_s);
- INFO("Ignored UPDATE for non-existing face");
- break;
+ DEBUG("[facemgr_on_event] UPDATE NEW %s", facelet_s);
+ INFO("Ignored UPDATE for non-existing face");
+ break;
- case FACELET_EVENT_DELETE:
- DEBUG("[facemgr_on_event] DELETE NEW %s", facelet_s);
- ERROR("[facemgr_on_event] Unexpected DELETE... face does not exist");
- goto ERR;
-
- case FACELET_EVENT_SET_UP:
- case FACELET_EVENT_SET_DOWN:
- ERROR("[facemgr_on_event] Unexpected event on a face that does not exist");
- goto ERR;
+ case FACELET_EVENT_DELETE:
+ DEBUG("[facemgr_on_event] DELETE NEW %s", facelet_s);
+ ERROR("[facemgr_on_event] Unexpected DELETE... face does not exist");
+ goto ERR;
- case FACELET_EVENT_UNDEFINED:
- case FACELET_EVENT_N:
- ERROR("[facemgr_on_event] Unexpected UNDEFINED event.");
- ret = -1;
- goto ERR;
+ case FACELET_EVENT_SET_UP:
+ case FACELET_EVENT_SET_DOWN:
+ ERROR(
+ "[facemgr_on_event] Unexpected event on a face that does not "
+ "exist");
+ goto ERR;
- }
- goto DUMP_CACHE;
+ case FACELET_EVENT_UNDEFINED:
+ case FACELET_EVENT_N:
+ ERROR("[facemgr_on_event] Unexpected UNDEFINED event.");
+ ret = -1;
+ goto ERR;
}
+ goto DUMP_CACHE;
+ }
+ /*
+ * From now on, it should not make any difference whether we have one or
+ * more facelet.
+ */
+ for (unsigned i = 0; i < n; i++) {
/*
- * From now on, it should not make any difference whether we have one or
- * more facelet.
+ * We merge each cached facelet with incoming one, and perform state
+ * reconciliation by sending appropriate updates to the forwarder
*/
- for (unsigned i = 0; i < n; i ++) {
+ facelet_t *facelet = cached_facelets[i];
+
+ char facelet_old_s[MAXSZ_FACELET];
+ facelet_snprintf(facelet_old_s, MAXSZ_FACELET, facelet);
+ // DEBUG("Facelet from cache #%d %s", i, facelet_s);
+
+ switch (facelet_get_event(facelet_in)) {
+ case FACELET_EVENT_CREATE:
/*
- * We merge each cached facelet with incoming one, and perform state
- * reconciliation by sending appropriate updates to the forwarder
+ * This can occur for a facelet already in cache but that has
+ * been previously deleted... we need to be able to consider
+ * static facelets in this situation too...
*/
- facelet_t * facelet = cached_facelets[i];
-
- char facelet_old_s[MAXSZ_FACELET];
- facelet_snprintf(facelet_old_s, MAXSZ_FACELET, facelet);
- //DEBUG("Facelet from cache #%d %s", i, facelet_s);
-
- switch(facelet_get_event(facelet_in)) {
- case FACELET_EVENT_CREATE:
- /*
- * This can occur for a facelet already in cache but that has
- * been previously deleted... we need to be able to consider
- * static facelets in this situation too...
- */
- DEBUG("[facemgr_on_event] CREATE EXISTING %s", facelet_s);
-
- if (!facelet_has_family(facelet_in)) {
- if (facemgr_process_facelet_create_no_family(facemgr, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error processing new interface event");
- goto ERR;
- }
- goto DUMP_CACHE;
- }
+ DEBUG("[facemgr_on_event] CREATE EXISTING %s", facelet_s);
- // This case will occur when we try to re-create existing faces,
- // eg. in the situation of a forwarder restarting.
- // likely this occurs when the interface receives a (potentially new) address
- if (facelet_merge(facelet, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error merging facelets");
- continue;
- }
+ if (!facelet_has_family(facelet_in)) {
+ if (facemgr_process_facelet_create_no_family(facemgr, facelet_in) <
+ 0) {
+ ERROR("[facemgr_on_event] Error processing new interface event");
+ goto ERR;
+ }
+ goto DUMP_CACHE;
+ }
- if (facemgr_process_facelet_create(facemgr, facelet) < 0) {
- ERROR("[facemgr_on_event] Error processing facelet CREATE event");
- ret = -1;
- }
+ // This case will occur when we try to re-create existing faces,
+ // eg. in the situation of a forwarder restarting.
+ // likely this occurs when the interface receives a (potentially new)
+ // address
+ if (facelet_merge(facelet, facelet_in) < 0) {
+ ERROR("[facemgr_on_event] Error merging facelets");
+ continue;
+ }
- continue;
+ if (facemgr_process_facelet_create(facemgr, facelet) < 0) {
+ ERROR("[facemgr_on_event] Error processing facelet CREATE event");
+ ret = -1;
+ }
- case FACELET_EVENT_GET: /* should be an INFORM message */
- /*
- * This happens due to polling of the forwarder (or when it
- * restarts)
- */
- //DEBUG("[facemgr_on_event] GET EXISTING %s", facelet_old_s);
- //DEBUG(" WITH %s", facelet_s);
- //ERROR("[facemgr_on_event] GET event for a face that already exists...");
+ continue;
+
+ case FACELET_EVENT_GET: /* should be an INFORM message */
+ /*
+ * This happens due to polling of the forwarder (or when it
+ * restarts)
+ */
+ // DEBUG("[facemgr_on_event] GET EXISTING %s", facelet_old_s);
+ // DEBUG(" WITH %s", facelet_s);
+ // ERROR("[facemgr_on_event] GET event for a face that already
+ // exists...");
#ifdef WITH_DUMP
- dump = false;
+ // dump = false;
#endif /* WITH_DUMP */
- continue;
+ continue;
- case FACELET_EVENT_UPDATE:
- DEBUG("[facemgr_on_event] UPDATE EXISTING %s", facelet_old_s);
- DEBUG(" WITH %s", facelet_s);
+ case FACELET_EVENT_UPDATE:
+ DEBUG("[facemgr_on_event] UPDATE EXISTING %s", facelet_old_s);
+ DEBUG(" WITH %s", facelet_s);
#ifdef WITH_DEFAULT_PRIORITIES
- if (facelet_has_netdevice_type(facelet_in) && !facelet_has_netdevice(facelet_in) && facelet_has_priority(facelet_in)) {
- /* Remember last priority choice for newly created facelets */
- netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
- u32 priority = 0;
- if (facelet_get_netdevice_type(facelet_in, &netdevice_type) < 0) {
- ERROR("[facelet_on_event] Error getting netdevice_type");
- goto ERR;
- }
- if (facelet_get_priority(facelet_in, &priority) < 0) {
- ERROR("[facelet_on_event] Error getting priority");
- goto ERR;
- }
- facemgr->default_priority[netdevice_type] = priority;
- }
+ if (facelet_has_netdevice_type(facelet_in) &&
+ !facelet_has_netdevice(facelet_in) &&
+ facelet_has_priority(facelet_in)) {
+ /* Remember last priority choice for newly created facelets */
+ netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ u32 priority = 0;
+ if (facelet_get_netdevice_type(facelet_in, &netdevice_type) < 0) {
+ ERROR("[facelet_on_event] Error getting netdevice_type");
+ goto ERR;
+ }
+ if (facelet_get_priority(facelet_in, &priority) < 0) {
+ ERROR("[facelet_on_event] Error getting priority");
+ goto ERR;
+ }
+ facemgr->default_priority[netdevice_type] = priority;
+ }
#endif /* WITH_DEFAULT_PRIORITIES */
- if (facelet_merge(facelet, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error merging facelets");
- continue;
- }
- if (facemgr_process_facelet_update(facemgr, facelet) < 0) {
- ERROR("[facemgr_on_event] Error processing facelet UPDATE event");
- ret = -1;
- }
- continue;
-
- case FACELET_EVENT_DELETE:
- DEBUG("[facemgr_on_event] DELETE EXISTING %s", facelet_old_s);
- DEBUG(" WITH %s", facelet_s);
- if (facelet_merge(facelet, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error merging facelets");
- continue;
- }
- if (facemgr_process_facelet_delete(facemgr, facelet) < 0) {
- ERROR("[facemgr_on_event] Error processing facelet DELETE event");
- ret = -1;
- }
- continue;
-
- case FACELET_EVENT_SET_UP:
- ERROR("[facemgr_on_event] Not implemented\n");
- ret = -1;
- continue;
-
- case FACELET_EVENT_SET_DOWN:
- DEBUG("[facemgr_on_event] SET DOWN EXISTING %s", facelet_old_s);
- DEBUG(" WITH %s", facelet_s);
- /* We don't even need to merge */
- if (facelet_merge(facelet, facelet_in) < 0) {
- ERROR("[facemgr_on_event] Error merging facelets");
- continue;
- }
- if (facemgr_process_facelet_delete(facemgr, facelet) < 0) {
- ERROR("[facemgr_on_event] Error processing facelet DELETE event");
- continue;
- }
- continue;
-
- case FACELET_EVENT_UNDEFINED:
- case FACELET_EVENT_N:
- ERROR("[facemgr_on_event] Unexpected UNDEFINED event.");
- ret = -1;
- goto ERR;
-
+ if (facelet_merge(facelet, facelet_in) < 0) {
+ ERROR("[facemgr_on_event] Error merging facelets");
+ continue;
+ }
+ if (facemgr_process_facelet_update(facemgr, facelet) < 0) {
+ ERROR("[facemgr_on_event] Error processing facelet UPDATE event");
+ ret = -1;
}
+ continue;
+
+ case FACELET_EVENT_DELETE:
+ DEBUG("[facemgr_on_event] DELETE EXISTING %s", facelet_old_s);
+ DEBUG(" WITH %s", facelet_s);
+ if (facelet_merge(facelet, facelet_in) < 0) {
+ ERROR("[facemgr_on_event] Error merging facelets");
+ continue;
+ }
+ if (facemgr_process_facelet_delete(facemgr, facelet) < 0) {
+ ERROR("[facemgr_on_event] Error processing facelet DELETE event");
+ ret = -1;
+ }
+ continue;
+
+ case FACELET_EVENT_SET_UP:
+ ERROR("[facemgr_on_event] Not implemented\n");
+ ret = -1;
+ continue;
+
+ case FACELET_EVENT_SET_DOWN:
+ DEBUG("[facemgr_on_event] SET DOWN EXISTING %s", facelet_old_s);
+ DEBUG(" WITH %s", facelet_s);
+ /* We don't even need to merge */
+ if (facelet_merge(facelet, facelet_in) < 0) {
+ ERROR("[facemgr_on_event] Error merging facelets");
+ continue;
+ }
+ if (facemgr_process_facelet_delete(facemgr, facelet) < 0) {
+ ERROR("[facemgr_on_event] Error processing facelet DELETE event");
+ continue;
+ }
+ continue;
+ case FACELET_EVENT_UNDEFINED:
+ case FACELET_EVENT_N:
+ ERROR("[facemgr_on_event] Unexpected UNDEFINED event.");
+ ret = -1;
+ goto ERR;
}
- goto DUMP_CACHE;
+ }
+ goto DUMP_CACHE;
ERR:
- ret = -1;
+ ret = -1;
DUMP_CACHE:
-#if WITH_DUMP
- if (dump) {
- DEBUG(" <CACHE>");
- facelet_set_dump(facemgr->facelet_cache);
- DEBUG(" </CACHE>");
- DEBUG("</EVENT ret=%d>", ret);
- DEBUG("----------------------------------");
- }
+#ifdef WITH_DUMP
+ if (dump) {
+ DEBUG(" <CACHE>");
+ facelet_set_dump(facemgr->facelet_cache);
+ DEBUG(" </CACHE>");
+ DEBUG("</EVENT ret=%d>", ret);
+ DEBUG("----------------------------------");
+ }
#endif /* WITH_DUMP */
- free(cached_facelets);
+ free(cached_facelets);
- if (remove_facelet)
- facelet_free(facelet_in);
+ if (remove_facelet) facelet_free(facelet_in);
- if (ret == -1) {
- INFO("Error... starting reattempts");
- facemgr_start_reattempts(facemgr);
- }
+ if (ret == -1) {
+ INFO("Error... starting reattempts");
+ facemgr_start_reattempts(facemgr);
+ }
- return ret;
+ return ret;
}
-int facemgr_callback(facemgr_t * facemgr, interface_cb_type_t type, void * data)
-{
- switch(type) {
- case INTERFACE_CB_TYPE_RAISE_EVENT:
- return facemgr_on_event(facemgr, data);
-
- case INTERFACE_CB_TYPE_REGISTER_FD:
- {
- /* Remember fd for further release */
- fd_callback_data_t * fd_callback_data = data;
- interface_t * interface = (interface_t*)(fd_callback_data->owner);
-
- interface_map_data_t * interface_map_data = NULL;
- if (interface_map_get(facemgr->interface_map, interface->name, &interface_map_data) < 0) {
- ERROR("[facemgr_callback] Error getting interface map data");
- return -1;
- }
- if (!interface_map_data) {
- ERROR("[facemgr_callback] No entry in interface map data");
- return -1;
- }
- interface_map_data->fds[interface_map_data->num_fds++] = fd_callback_data->fd;
+int facemgr_callback(facemgr_t *facemgr, interface_cb_type_t type, void *data) {
+ switch (type) {
+ case INTERFACE_CB_TYPE_RAISE_EVENT:
+ return facemgr_on_event(facemgr, data);
- return facemgr->callback(facemgr->callback_owner,
- FACEMGR_CB_TYPE_REGISTER_FD, data);
- }
+ case INTERFACE_CB_TYPE_REGISTER_FD: {
+ /* Remember fd for further release */
+ fd_callback_data_t *fd_callback_data = data;
+ interface_t *interface = (interface_t *)(fd_callback_data->owner);
- case INTERFACE_CB_TYPE_UNREGISTER_FD:
- {
- fd_callback_data_t * fd_callback_data = data;
- interface_t * interface = (interface_t*)(fd_callback_data->owner);
+ interface_map_data_t *interface_map_data = NULL;
+ if (interface_map_get(facemgr->interface_map, interface->name,
+ &interface_map_data) < 0) {
+ ERROR("[facemgr_callback] Error getting interface map data");
+ return -1;
+ }
+ if (!interface_map_data) {
+ ERROR("[facemgr_callback] No entry in interface map data");
+ return -1;
+ }
+ interface_map_data->fds[interface_map_data->num_fds++] =
+ fd_callback_data->fd;
- interface_map_data_t * interface_map_data = NULL;
- if (interface_map_get(facemgr->interface_map, interface->name, &interface_map_data) < 0) {
- ERROR("[facemgr_callback] Error getting interface map data");
- return -1;
- }
- if (!interface_map_data) {
- ERROR("[facemgr_callback] No entry in interface map data");
- return -1;
- }
+ return facemgr->callback(facemgr->callback_owner,
+ FACEMGR_CB_TYPE_REGISTER_FD, data);
+ }
- for (unsigned i = 0; i < interface_map_data->num_fds; i++) {
- if (interface_map_data->fds[i] == fd_callback_data->fd) {
- interface_map_data->fds[i] = interface_map_data->fds[--interface_map_data->num_fds];
- break;
- }
- }
+ case INTERFACE_CB_TYPE_UNREGISTER_FD: {
+ fd_callback_data_t *fd_callback_data = data;
+ interface_t *interface = (interface_t *)(fd_callback_data->owner);
- return facemgr->callback(facemgr->callback_owner,
- FACEMGR_CB_TYPE_UNREGISTER_FD, data);
+ interface_map_data_t *interface_map_data = NULL;
+ if (interface_map_get(facemgr->interface_map, interface->name,
+ &interface_map_data) < 0) {
+ ERROR("[facemgr_callback] Error getting interface map data");
+ return -1;
+ }
+ if (!interface_map_data) {
+ ERROR("[facemgr_callback] No entry in interface map data");
+ return -1;
+ }
+
+ for (unsigned i = 0; i < interface_map_data->num_fds; i++) {
+ if (interface_map_data->fds[i] == fd_callback_data->fd) {
+ interface_map_data->fds[i] =
+ interface_map_data->fds[--interface_map_data->num_fds];
+ break;
}
+ }
- case INTERFACE_CB_TYPE_REGISTER_TIMER:
- return facemgr->callback(facemgr->callback_owner,
- FACEMGR_CB_TYPE_REGISTER_TIMER, data);
+ return facemgr->callback(facemgr->callback_owner,
+ FACEMGR_CB_TYPE_UNREGISTER_FD, data);
+ }
- case INTERFACE_CB_TYPE_UNREGISTER_TIMER:
- return facemgr->callback(facemgr->callback_owner,
- FACEMGR_CB_TYPE_UNREGISTER_TIMER, data);
+ case INTERFACE_CB_TYPE_REGISTER_TIMER:
+ return facemgr->callback(facemgr->callback_owner,
+ FACEMGR_CB_TYPE_REGISTER_TIMER, data);
- }
- return -1;
+ case INTERFACE_CB_TYPE_UNREGISTER_TIMER:
+ return facemgr->callback(facemgr->callback_owner,
+ FACEMGR_CB_TYPE_UNREGISTER_TIMER, data);
+ }
+ return -1;
}
-int
-facemgr_bootstrap(facemgr_t * facemgr)
-{
- int rc;
+int facemgr_bootstrap(facemgr_t *facemgr) {
+ int rc;
- DEBUG("Registering interfaces...");
- rc = interface_register(&hicn_light_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering hicn_light interface");
- goto ERR_REGISTER;
- }
+ DEBUG("Registering interfaces...");
+ rc = interface_register(&hicn_light_ops);
+ if (rc < 0) {
+ ERROR("[facemgr_bootstrap] Error registering hicn_light interface");
+ goto ERR_REGISTER;
+ }
#ifdef __APPLE__
- rc = interface_register(&network_framework_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering network_framework interface");
- goto ERR_REGISTER;
- }
+ rc = interface_register(&network_framework_ops);
+ if (rc < 0) {
+ ERROR("[facemgr_bootstrap] Error registering network_framework interface");
+ goto ERR_REGISTER;
+ }
#endif /* __APPLE__ */
#ifdef __linux__
- rc = interface_register(&netlink_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering netlink interface");
- goto ERR_REGISTER;
- }
+#ifdef __ANDROID__
+ rc = interface_register(&android_ops);
+ if (rc < 0) {
+ ERROR("[facemgr_bootstrap] Error registering android interface");
+ goto ERR_REGISTER;
+ }
+#else
+ rc = interface_register(&netlink_ops);
+ if (rc < 0) {
+ ERROR("[facemgr_bootstrap] Error registering netlink interface");
+ goto ERR_REGISTER;
+ }
+#endif /* __ANDROID__ */
- rc = interface_register(&bonjour_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering bonjour interface");
- goto ERR_REGISTER;
- }
+ rc = interface_register(&bonjour_ops);
+ if (rc < 0) {
+ ERROR("[facemgr_bootstrap] Error registering bonjour interface");
+ goto ERR_REGISTER;
+ }
#endif /* __linux__ */
-#ifdef WITH_FACEMGR_UTILITY
- rc = interface_register(&android_utility_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering android_utility interface");
- goto ERR_REGISTER;
- }
-#endif /* WITH_FACEMGR_UTILITY */
-
#ifdef WITH_PRIORITY_CONTROLLER
- INFO("[facemgr_bootstrap] registering priority_controller interface");
- rc = interface_register(&priority_controller_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering priority_controller interface");
- goto ERR_REGISTER;
- }
+ INFO("[facemgr_bootstrap] registering priority_controller interface");
+ rc = interface_register(&priority_controller_ops);
+ if (rc < 0) {
+ ERROR(
+ "[facemgr_bootstrap] Error registering priority_controller interface");
+ goto ERR_REGISTER;
+ }
#endif
#ifdef WITH_EXAMPLE_DUMMY
- rc = interface_register(&dummy_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering dummy interface");
- goto ERR_REGISTER;
- }
+ rc = interface_register(&dummy_ops);
+ if (rc < 0) {
+ ERROR("[facemgr_bootstrap] Error registering dummy interface");
+ goto ERR_REGISTER;
+ }
#endif
#ifdef WITH_EXAMPLE_UPDOWN
- rc = interface_register(&updown_ops);
- if (rc < 0) {
- ERROR("[facemgr_bootstrap] Error registering updown interface");
- goto ERR_REGISTER;
- }
+ rc = interface_register(&updown_ops);
+ if (rc < 0) {
+ ERROR("[facemgr_bootstrap] Error registering updown interface");
+ goto ERR_REGISTER;
+ }
#endif
- rc = facemgr_create_interface(facemgr, "hl", "hicn_light", NULL, &facemgr->hl);
- if (rc < 0) {
- ERROR("Error creating 'hICN forwarder (hicn-light)' interface\n");
- goto ERR_HL_CREATE;
- }
-
#ifdef __APPLE__
- network_framework_cfg_t nf_cfg = {
- };
- rc = facemgr_create_interface(facemgr, "nf", "network_framework", &nf_cfg, &facemgr->nf);
- if (rc < 0) {
- ERROR("Error creating 'Apple Network Framework' interface\n");
- goto ERR_NF_CREATE;
- }
+ network_framework_cfg_t nf_cfg = {};
+ rc = facemgr_create_interface(facemgr, "nf", "network_framework", &nf_cfg,
+ &facemgr->nf);
+ if (rc < 0) {
+ ERROR("Error creating 'Apple Network Framework' interface\n");
+ goto ERR_NF_CREATE;
+ }
#endif /* __APPLE__ */
#ifdef __linux__
- rc = facemgr_create_interface(facemgr, "nl", "netlink", NULL, &facemgr->nl);
- if (rc < 0) {
- ERROR("Error creating 'Netlink' interface\n");
- goto ERR_NL_CREATE;
- }
+#ifdef __ANDROID__
+ android_cfg_t android_cfg = {
+ .jvm = facemgr->jvm,
+ };
+ rc = facemgr_create_interface(facemgr, "android", "android", &android_cfg,
+ &facemgr->android);
+ if (rc < 0) {
+ ERROR("Error creating 'Android' interface\n");
+ goto ERR_ANDROID_CREATE;
+ }
+#else
+ rc = facemgr_create_interface(facemgr, "nl", "netlink", NULL, &facemgr->nl);
+ if (rc < 0) {
+ ERROR("Error creating 'Netlink' interface\n");
+ goto ERR_NL_CREATE;
+ }
+#endif /* __ANDROID__ */
#endif /* __linux__ */
-#ifdef WITH_FACEMGR_UTILITY
- android_utility_cfg_t au_cfg = {
- .jvm = facemgr->jvm,
- };
- rc = facemgr_create_interface(facemgr, "au", "android_utility", &au_cfg, &facemgr->au);
- if (rc < 0) {
- ERROR("Error creating 'Android Utility' interface\n");
- goto ERR_AU_CREATE;
- }
-#endif /* WITH_FACEMGR_UTILITY */
-
#ifdef WITH_PRIORITY_CONTROLLER
- INFO("[facemgr_bootstrap] creating priority_controller interface");
- priority_controller_cfg_t pc_cfg = {
+ INFO("[facemgr_bootstrap] creating priority_controller interface");
+ priority_controller_cfg_t pc_cfg = {
#ifdef PRIORITY_CONTROLLER_INTERNAL
- .jvm = facemgr->jvm,
+ .jvm = facemgr->jvm,
#endif /* PRIORITY_CONTROLLER_INTERNAL */
- };
- rc = facemgr_create_interface(facemgr, "pc", "priority_controller", &pc_cfg, &facemgr->pc);
- if (rc < 0) {
- ERROR("Error creating 'Priority Controller' interface\n");
- goto ERR_PC_CREATE;
- }
+ };
+ rc = facemgr_create_interface(facemgr, "pc", "priority_controller", &pc_cfg,
+ &facemgr->pc);
+ if (rc < 0) {
+ ERROR("Error creating 'Priority Controller' interface\n");
+ goto ERR_PC_CREATE;
+ }
#endif
#ifdef WITH_EXAMPLE_DUMMY
- rc = facemgr_create_interface(facemgr, "dummy0", "dummy", NULL, &facemgr->dummy);
- if (rc < 0) {
- ERROR("Error creating 'dummy' interface\n");
- goto ERR_DUMMY_CREATE;
- }
+ rc = facemgr_create_interface(facemgr, "dummy0", "dummy", NULL,
+ &facemgr->dummy);
+ if (rc < 0) {
+ ERROR("Error creating 'dummy' interface\n");
+ goto ERR_DUMMY_CREATE;
+ }
#endif
#ifdef WITH_EXAMPLE_UPDOWN
- rc = facemgr_create_interface(facemgr, "updown0", "updown", NULL, &facemgr->updown);
- if (rc < 0) {
- ERROR("Error creating 'updown' interface\n");
- goto ERR_UPDOWN_CREATE;
- }
+ rc = facemgr_create_interface(facemgr, "updown0", "updown", NULL,
+ &facemgr->updown);
+ if (rc < 0) {
+ ERROR("Error creating 'updown' interface\n");
+ goto ERR_UPDOWN_CREATE;
+ }
#endif
- DEBUG("Facemgr successfully initialized...");
+ rc =
+ facemgr_create_interface(facemgr, "hl", "hicn_light", NULL, &facemgr->hl);
+ if (rc < 0) {
+ ERROR("Error creating 'hICN forwarder (hicn-light)' interface\n");
+ goto ERR_HL_CREATE;
+ }
- return 0;
+ DEBUG("Facemgr successfully initialized...");
+
+ return 0;
+ERR_HL_CREATE:
#ifdef WITH_EXAMPLE_UPDOWN
- facemgr_delete_interface(facemgr, facemgr->updown);
+ facemgr_delete_interface(facemgr, facemgr->updown);
ERR_UPDOWN_CREATE:
#endif
+
#ifdef WITH_EXAMPLE_DUMMY
- facemgr_delete_interface(facemgr, facemgr->dummy);
+ facemgr_delete_interface(facemgr, facemgr->dummy);
ERR_DUMMY_CREATE:
#endif
-#ifdef WITH_FACEMGR_UTILITY
- facemgr_delete_interface(facemgr, facemgr->au);
-ERR_AU_CREATE:
-#endif /* WITH_FACEMGR_UTILITY */
+
#ifdef WITH_PRIORITY_CONTROLLER
- facemgr_delete_interface(facemgr, facemgr->pc);
+ facemgr_delete_interface(facemgr, facemgr->pc);
ERR_PC_CREATE:
#endif
+
#ifdef __linux__
- facemgr_delete_interface(facemgr, facemgr->nl);
+#ifdef __ANDROID__
+ facemgr_delete_interface(facemgr, facemgr->android);
+ERR_ANDROID_CREATE:
+#else
+ facemgr_delete_interface(facemgr, facemgr->nl);
ERR_NL_CREATE:
+#endif /* __ANDROID__ */
#endif /* __linux__ */
+
#ifdef __APPLE__
- facemgr_delete_interface(facemgr, facemgr->nf);
+ facemgr_delete_interface(facemgr, facemgr->nf);
ERR_NF_CREATE:
#endif /* __APPLE__ */
- facemgr_delete_interface(facemgr, facemgr->hl);
-ERR_HL_CREATE:
ERR_REGISTER:
- return -1;
+ return -1;
}
-void facemgr_stop(facemgr_t * facemgr)
-{
- // FIXME we should iterate on interface map
+void facemgr_stop(facemgr_t *facemgr) {
+ // FIXME we should iterate on interface map
#ifdef __APPLE__
- facemgr_delete_interface(facemgr, facemgr->nf);
+ facemgr_delete_interface(facemgr, facemgr->nf);
#endif /* __APPLE__ */
-
#ifdef __linux__
- facemgr_delete_interface(facemgr, facemgr->nl);
-
- /* Delete all bonjour interfaces */
- interface_t ** bonjour_array = NULL;
- int n = bonjour_map_get_value_array(facemgr->bonjour_map, &bonjour_array);
- if (n >= 0) {
- netdevice_t ** netdevice_array = NULL;
- int m = bonjour_map_get_key_array(facemgr->bonjour_map, &netdevice_array);
- if (m >= 0) {
- assert(m == n);
- for (int i = 0; i < n; i++) { /* Fail silently */
- DEBUG("Deleting bonjour interface associated to %s (%p)",
- netdevice_array[i]->name, bonjour_array[i]);
- facemgr_delete_interface(facemgr, bonjour_array[i]);
- }
- free(netdevice_array);
- }
- free(bonjour_array);
- }
-#endif /* __linux__ */
+#ifdef __ANDROID__
+ facemgr_delete_interface(facemgr, facemgr->android);
+#else
+ facemgr_delete_interface(facemgr, facemgr->nl);
+#endif /* __ANDROID__ */
-#ifdef WITH_FACEMGR_UTILITY
- facemgr_delete_interface(facemgr, facemgr->au);
-#endif /* WITH_FACEMGR_UTILITY */
+ /* Delete all bonjour interfaces */
+ interface_t **bonjour_array = NULL;
+ int n = bonjour_map_get_value_array(facemgr->bonjour_map, &bonjour_array);
+ if (n >= 0) {
+ netdevice_t **netdevice_array = NULL;
+ int m = bonjour_map_get_key_array(facemgr->bonjour_map, &netdevice_array);
+ if (m >= 0) {
+ assert(m == n);
+ for (int i = 0; i < n; i++) { /* Fail silently */
+ DEBUG("Deleting bonjour interface associated to %s (%p)",
+ netdevice_array[i]->name, bonjour_array[i]);
+ facemgr_delete_interface(facemgr, bonjour_array[i]);
+ }
+ free(netdevice_array);
+ }
+ free(bonjour_array);
+ }
+#endif /* __linux__ */
#ifdef WITH_PRIORITY_CONTROLLER
- facemgr_delete_interface(facemgr, facemgr->pc);
+ facemgr_delete_interface(facemgr, facemgr->pc);
#endif
- facemgr_delete_interface(facemgr, facemgr->hl);
+ facemgr_delete_interface(facemgr, facemgr->hl);
#ifdef WITH_EXAMPLE_DUMMY
- facemgr_delete_interface(facemgr, facemgr->dummy);
+ facemgr_delete_interface(facemgr, facemgr->dummy);
#endif
#ifdef WITH_EXAMPLE_UPDOWN
- facemgr_delete_interface(facemgr, facemgr->updown);
+ facemgr_delete_interface(facemgr, facemgr->updown);
#endif
}
#ifdef __ANDROID__
-void facemgr_set_jvm(facemgr_t * facemgr, JavaVM *jvm)
-{
- facemgr->jvm = jvm;
+void facemgr_set_jvm(facemgr_t *facemgr, JavaVM *jvm) { facemgr->jvm = jvm; }
+
+void facemgr_on_android_callback(facemgr_t *facemgr, const char *interface_name,
+ netdevice_type_t netdevice_type, bool up,
+ int family, const char *ip_address) {
+ android_on_network_event(facemgr->android, interface_name, netdevice_type, up,
+ family, ip_address);
}
#endif /* __ANDROID__ */
-void
-facemgr_set_callback(facemgr_t * facemgr, void * callback_owner, facemgr_cb_t callback)
-{
- facemgr->callback = callback;
- facemgr->callback_owner = callback_owner;
+void facemgr_set_callback(facemgr_t *facemgr, void *callback_owner,
+ facemgr_cb_t callback) {
+ facemgr->callback = callback;
+ facemgr->callback_owner = callback_owner;
}
-void facemgr_list_facelets(const facemgr_t * facemgr, facemgr_list_facelets_cb_t cb, void * user_data)
-{
- facelet_t ** facelet_array;
- if (!cb)
- return;
- int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
- if (n < 0) {
- ERROR("[facemgr_list_facelets] Could not retrieve facelets in cache");
- return;
- }
- for (unsigned i = 0; i < n; i++) {
- facelet_t * facelet = facelet_array[i];
- cb(facemgr, facelet, user_data);
- }
- free(facelet_array);
+void facemgr_list_facelets(const facemgr_t *facemgr,
+ facemgr_list_facelets_cb_t cb, void *user_data) {
+ facelet_t **facelet_array;
+ if (!cb) return;
+ int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
+ if (n < 0) {
+ ERROR("[facemgr_list_facelets] Could not retrieve facelets in cache");
+ return;
+ }
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *facelet = facelet_array[i];
+ if (!facelet) continue; /* Should not occur */
+ cb(facemgr, facelet, user_data);
+ }
+ free(facelet_array);
}
-int
-facemgr_list_facelets_json(const facemgr_t * facemgr, char ** buffer)
-{
- char * cur;
- char * s;
- int rc;
-
- facelet_t ** facelet_array;
- int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
- if (n < 0) {
- ERROR("[facemgr_list_facelets_json] Could not retrieve facelets in cache");
- return -1;
- }
- /* This should be enough for JSON overhead, refine later */
- size_t size = 2 * n * MAXSZ_FACELET;
- *buffer = malloc(size);
- if (!buffer) {
- ERROR("[facemgr_list_facelets_json] Could not allocate JSON s");
- free(facelet_array);
- return -1;
- }
- s = *buffer;
- cur = s;
+int facemgr_list_facelets_json(const facemgr_t *facemgr, char **buffer) {
+ char *cur;
+ char *s;
+ int rc;
- rc = snprintf(cur, s + size - cur, "{\"facelets\": [\n");
- if (rc < 0)
- goto ERR;
- cur += rc;
- if (size != 0 && cur >= s + size)
- goto END;
+ facelet_t **facelet_array;
+ int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
+ if (n < 0) {
+ ERROR("[facemgr_list_facelets_json] Could not retrieve facelets in cache");
+ return -1;
+ }
+ /* This should be enough for JSON overhead, refine later */
+ size_t size = 2 * n * MAXSZ_FACELET;
+ *buffer = malloc(size);
+ if (!buffer) {
+ ERROR("[facemgr_list_facelets_json] Could not allocate JSON s");
+ free(facelet_array);
+ return -1;
+ }
+ s = *buffer;
+ cur = s;
- for (unsigned i = 0; i < n; i++) {
- facelet_t * facelet = facelet_array[i];
+ rc = snprintf(cur, s + size - cur, "{\"facelets\": [\n");
+ if (rc < 0) goto ERR;
+ cur += rc;
+ if (size != 0 && cur >= s + size) goto END;
- rc = facelet_snprintf_json(cur, s + size - cur, facelet, /* indent */ 1);
- if (rc < 0)
- goto ERR;
- cur += rc;
- if (size != 0 && cur >= s + size)
- goto END;
+ for (unsigned i = 0; i < n; i++) {
+ facelet_t *facelet = facelet_array[i];
+ if (!facelet) continue; /* Should not occur */
- rc = snprintf(cur, s + size - cur, (i == n-1) ? "\n" : ",\n");
- if (rc < 0)
- goto ERR;
- cur += rc;
- if (size != 0 && cur >= s + size)
- goto END;
- }
+ rc = facelet_snprintf_json(cur, s + size - cur, facelet, /* indent */ 1);
+ if (rc < 0) goto ERR;
+ cur += rc;
+ if (size != 0 && cur >= s + size) goto END;
- rc = snprintf(cur, s + size - cur, "]}\n");
- if (rc < 0)
- goto ERR;
+ rc = snprintf(cur, s + size - cur, (i == n - 1) ? "\n" : ",\n");
+ if (rc < 0) goto ERR;
cur += rc;
- if (size != 0 && cur >= s + size)
- goto END;
+ if (size != 0 && cur >= s + size) goto END;
+ }
+
+ rc = snprintf(cur, s + size - cur, "]}\n");
+ if (rc < 0) goto ERR;
+ cur += rc;
+ if (size != 0 && cur >= s + size) goto END;
END:
- free(facelet_array);
- return (int)(cur - s);
+ free(facelet_array);
+ return (int)(cur - s);
ERR:
- free(facelet_array);
- return rc;
+ free(facelet_array);
+ return rc;
}
-
diff --git a/ctrl/facemgr/src/cache.c b/ctrl/facemgr/src/cache.c
index f994d7d37..98c68e9b0 100644
--- a/ctrl/facemgr/src/cache.c
+++ b/ctrl/facemgr/src/cache.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,106 +22,86 @@
* search.h).
*/
-#include <math.h> // log2
-#include <string.h> // memmove
+#include <math.h> // log2
+#include <string.h> // memmove
#include "cache.h"
#define FACE_CACHE_MAX_SIZE_LOG_INIT 0
-face_cache_t *
-face_cache_create()
-{
- face_cache_t * face_cache = malloc(sizeof(face_cache_t));
- if (!face_cache)
- goto ERR_MALLOC;
+face_cache_t* face_cache_create() {
+ face_cache_t* face_cache = malloc(sizeof(face_cache_t));
+ if (!face_cache) goto ERR_MALLOC;
- face_cache->max_size_log = FACE_CACHE_MAX_SIZE_LOG_INIT;
-#if(FACE_CACHE_MAX_SIZE_LOG_INIT == 0)
- face_cache->faces = NULL;
+ face_cache->max_size_log = FACE_CACHE_MAX_SIZE_LOG_INIT;
+#if (FACE_CACHE_MAX_SIZE_LOG_INIT == 0)
+ face_cache->faces = NULL;
#else
- face_cache->faces = malloc((1 << face_cache->max_size_log) * sizeof(face_t*));
- if (!face_cache->faces)
- goto ERR_ARRAY:
+ face_cache->faces = malloc((1 << face_cache->max_size_log) * sizeof(face_t*));
+ if (!face_cache->faces)
+ goto ERR_ARRAY :
#endif
- face_cache->size = 0;
+ face_cache->size = 0;
- return face_cache;
+ return face_cache;
-#if(FACE_CACHE_MAX_SIZE_LOG_INIT != 0)
+#if (FACE_CACHE_MAX_SIZE_LOG_INIT != 0)
ERR_ARRAY:
- free(face_cache);
+ free(face_cache);
#endif
ERR_MALLOC:
- return NULL;
+ return NULL;
}
-void
-face_cache_free(face_cache_t * face_cache)
-{
- free(face_cache->faces);
+void face_cache_free(face_cache_t* face_cache) {
+ free(face_cache->faces);
- free(face_cache);
+ free(face_cache);
}
-face_t *
-face_cache_add(face_cache_t * face_cache, face_t * face)
-{
- /* Ensure sufficient space for next addition */
- size_t new_size_log = (face_cache->size > 0) ? log2(face_cache->size) + 1 : 0;
- if (new_size_log > face_cache->max_size_log) {
- face_cache->max_size_log = new_size_log;
- face_cache->faces = realloc(face_cache->faces, (1 << new_size_log) * sizeof(face_t*));
- }
+face_t* face_cache_add(face_cache_t* face_cache, face_t* face) {
+ /* Ensure sufficient space for next addition */
+ size_t new_size_log = (face_cache->size > 0) ? log2(face_cache->size) + 1 : 0;
+ if (new_size_log > face_cache->max_size_log) {
+ face_cache->max_size_log = new_size_log;
+ face_cache->faces =
+ realloc(face_cache->faces, (1 << new_size_log) * sizeof(face_t*));
+ }
- if (!face_cache->faces)
- goto ERR_REALLOC;
+ if (!face_cache->faces) goto ERR_REALLOC;
- face_cache->faces[face_cache->size++] = face;
+ face_cache->faces[face_cache->size++] = face;
- return face;
+ return face;
ERR_REALLOC:
- return NULL;
+ return NULL;
}
-int face_cache_search(face_cache_t * face_cache, face_t * face, face_cmp_t face_cmp)
-{
- for (int i = 0; i < face_cache->size; i++)
- if (face_cmp(face, face_cache->faces[i]))
- return i;
- return -1;
+int face_cache_search(face_cache_t* face_cache, face_t* face,
+ face_cmp_t face_cmp) {
+ for (int i = 0; i < face_cache->size; i++)
+ if (face_cmp(face, face_cache->faces[i])) return i;
+ return -1;
}
/* Remove a single occurrence */
-face_t *
-face_cache_remove(face_cache_t * face_cache, face_t * face)
-{
- int pos = face_cache_search(face_cache, face, face_cmp);
- if (pos < 0)
- return NULL;
+face_t* face_cache_remove(face_cache_t* face_cache, face_t* face) {
+ int pos = face_cache_search(face_cache, face, face_cmp);
+ if (pos < 0) return NULL;
- /* No need to move memory if last item is removed */
- if (pos < face_cache->size)
- memmove(face_cache->faces+pos, face_cache->faces+pos+1, face_cache->size - pos);
+ /* No need to move memory if last item is removed */
+ if (pos < face_cache->size)
+ memmove(face_cache->faces + pos, face_cache->faces + pos + 1,
+ face_cache->size - pos);
- face_cache->size--;
+ face_cache->size--;
- return face;
+ return face;
}
/* TODO : remove by ... */
-face_t *
-face_cache_get_by_id(face_cache_t * face_cache, int id)
-{
- return NULL;
-}
-
-
+face_t* face_cache_get_by_id(face_cache_t* face_cache, int id) { return NULL; }
-void
-face_cache_dump(face_cache_t * face_cache)
-{
-
-}
+void face_cache_dump(face_cache_t* face_cache) {}
diff --git a/ctrl/facemgr/src/cache.h b/ctrl/facemgr/src/cache.h
index 1389ed6ec..ac14fabb8 100644
--- a/ctrl/facemgr/src/cache.h
+++ b/ctrl/facemgr/src/cache.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -32,22 +32,22 @@
* \brief Face cache
*/
typedef struct {
- face_t ** faces; /**< array of _pointers_ to faces */
- size_t max_size_log; /**< log2 of allocated size */
- size_t size; /**< effective array size */
+ face_t** faces; /**< array of _pointers_ to faces */
+ size_t max_size_log; /**< log2 of allocated size */
+ size_t size; /**< effective array size */
} face_cache_t;
-face_cache_t * face_cache_create();
-void face_cache_free(face_cache_t * face_cache);
+face_cache_t* face_cache_create();
+void face_cache_free(face_cache_t* face_cache);
/* a la VPP vector, we never create a face outside of the vector */
/* problem is that face ptr can get invalid if we manipulate the vector */
-face_t * face_cache_get(face_cache_t * cache_cache);
+face_t* face_cache_get(face_cache_t* cache_cache);
-face_t * face_cache_add(face_cache_t * face_cache, face_t * face);
-face_t * face_cache_remove(face_cache_t * face_cache, face_t * face);
-face_t * face_cache_get_by_id(face_cache_t * face_cache, int id);
+face_t* face_cache_add(face_cache_t* face_cache, face_t* face);
+face_t* face_cache_remove(face_cache_t* face_cache, face_t* face);
+face_t* face_cache_get_by_id(face_cache_t* face_cache, int id);
-void face_cache_dump(face_cache_t * face_cache);
+void face_cache_dump(face_cache_t* face_cache);
#endif /* FACEMGR_CACHE_H */
diff --git a/ctrl/facemgr/src/cfg.c b/ctrl/facemgr/src/cfg.c
index df73acd1b..87a6279ca 100644
--- a/ctrl/facemgr/src/cfg.c
+++ b/ctrl/facemgr/src/cfg.c
@@ -4,7 +4,7 @@
*/
#include <assert.h>
-#include <hicn/ctrl.h> // HICN_DEFAULT_PORT
+#include <hicn/ctrl.h> // HICN_DEFAULT_PORT
#include <hicn/facemgr/cfg.h>
#include <hicn/policy.h>
#include <hicn/util/ip_address.h>
@@ -14,691 +14,644 @@
/* Overlay */
typedef struct {
- bool is_local_port;
- uint16_t local_port;
- bool is_local_addr;
- ip_address_t local_addr;
- bool is_remote_port;
- uint16_t remote_port;
- bool is_remote_addr;
- ip_address_t remote_addr;
+ bool is_local_port;
+ uint16_t local_port;
+ bool is_local_addr;
+ hicn_ip_address_t local_addr;
+ bool is_remote_port;
+ uint16_t remote_port;
+ bool is_remote_addr;
+ hicn_ip_address_t remote_addr;
} facemgr_cfg_overlay_t;
-int facemgr_cfg_overlay_initialize(facemgr_cfg_overlay_t * overlay)
-{
- overlay->is_local_port = false;
- overlay->local_port = 0;
- overlay->is_local_addr = false;
- overlay->local_addr = IP_ADDRESS_EMPTY;
+int facemgr_cfg_overlay_initialize(facemgr_cfg_overlay_t *overlay) {
+ overlay->is_local_port = false;
+ overlay->local_port = 0;
+ overlay->is_local_addr = false;
+ overlay->local_addr = IP_ADDRESS_EMPTY;
- overlay->is_remote_port = false;
- overlay->remote_port = 0;
- overlay->is_remote_addr = false;
- overlay->remote_addr = IP_ADDRESS_EMPTY;
+ overlay->is_remote_port = false;
+ overlay->remote_port = 0;
+ overlay->is_remote_addr = false;
+ overlay->remote_addr = IP_ADDRESS_EMPTY;
- return 0;
+ return 0;
}
-int facemgr_cfg_overlay_finalize(facemgr_cfg_overlay_t * overlay)
-{
- return 0;
-}
+int facemgr_cfg_overlay_finalize(facemgr_cfg_overlay_t *overlay) { return 0; }
-facemgr_cfg_overlay_t * facemgr_cfg_overlay_create()
-{
- facemgr_cfg_overlay_t * overlay = malloc(sizeof(facemgr_cfg_overlay_t));
- if (!overlay)
- return NULL;
+facemgr_cfg_overlay_t *facemgr_cfg_overlay_create() {
+ facemgr_cfg_overlay_t *overlay = malloc(sizeof(facemgr_cfg_overlay_t));
+ if (!overlay) return NULL;
- int rc = facemgr_cfg_overlay_initialize(overlay);
- if (rc < 0) {
- free(overlay);
- return NULL;
- }
+ int rc = facemgr_cfg_overlay_initialize(overlay);
+ if (rc < 0) {
+ free(overlay);
+ return NULL;
+ }
- return overlay;
+ return overlay;
}
-void facemgr_cfg_overlay_free(facemgr_cfg_overlay_t * overlay)
-{
- facemgr_cfg_overlay_finalize(overlay);
- free(overlay);
+void facemgr_cfg_overlay_free(facemgr_cfg_overlay_t *overlay) {
+ facemgr_cfg_overlay_finalize(overlay);
+ free(overlay);
}
typedef struct {
- facemgr_cfg_overlay_t * v4;
- facemgr_cfg_overlay_t * v6;
+ facemgr_cfg_overlay_t *v4;
+ facemgr_cfg_overlay_t *v6;
} facemgr_cfg_overlays_t;
typedef struct {
- const char * interface_name;
- netdevice_type_t interface_type;
+ const char *interface_name;
+ netdevice_type_t interface_type;
} facemgr_cfg_match_t;
-
typedef struct {
- /* Interface specific */
- bool is_face_type; // default is auto
- facemgr_face_type_t face_type;
-
- /* This should be defaut for the global settings */
- bool is_ignore;
- bool ignore;
- bool is_discovery;
- bool discovery;
- bool is_ipv4;
- bool ipv4;
- bool is_ipv6;
- bool ipv6;
-
- facemgr_cfg_overlays_t overlays; // fallback unless discovery is disabled
+ /* Interface specific */
+ bool is_face_type; // default is auto
+ facemgr_face_type_t face_type;
+
+ /* This should be defaut for the global settings */
+ bool is_ignore;
+ bool ignore;
+ bool is_discovery;
+ bool discovery;
+ bool is_ipv4;
+ bool ipv4;
+ bool is_ipv6;
+ bool ipv6;
+
+ facemgr_cfg_overlays_t overlays; // fallback unless discovery is disabled
} facemgr_cfg_override_t;
struct facemgr_cfg_rule_s {
- facemgr_cfg_match_t match;
- facemgr_cfg_override_t override;
+ facemgr_cfg_match_t match;
+ facemgr_cfg_override_t override;
};
-int facemgr_cfg_override_initialize(facemgr_cfg_override_t * override)
-{
- override->is_face_type = false;
- override->face_type = FACEMGR_FACE_TYPE_UNDEFINED;
+int facemgr_cfg_override_initialize(facemgr_cfg_override_t *override) {
+ override->is_face_type = false;
+ override->face_type = FACEMGR_FACE_TYPE_UNDEFINED;
- override->is_ignore = false;
- override->ignore = false;
+ override->is_ignore = false;
+ override->ignore = false;
- override->is_discovery = false;
- override->discovery = false;
+ override->is_discovery = false;
+ override->discovery = false;
- override->is_ipv4 = false;
- override->ipv6 = false;
- override->is_ipv6 = false;
- override->ipv6 = false;
+ override->is_ipv4 = false;
+ override->ipv6 = false;
+ override->is_ipv6 = false;
+ override->ipv6 = false;
- override->overlays.v4 = NULL;
- override->overlays.v6 = NULL;
+ override->overlays.v4 = NULL;
+ override->overlays.v6 = NULL;
- return 0;
+ return 0;
}
-int facemgr_cfg_override_finalize(facemgr_cfg_override_t * override)
-{
- if (override->overlays.v4) {
- facemgr_cfg_overlay_free(override->overlays.v4);
- override->overlays.v4 = NULL;
- }
- if (override->overlays.v6) {
- facemgr_cfg_overlay_free(override->overlays.v6);
- override->overlays.v6 = NULL;
- }
+int facemgr_cfg_override_finalize(facemgr_cfg_override_t *override) {
+ if (override->overlays.v4) {
+ facemgr_cfg_overlay_free(override->overlays.v4);
+ override->overlays.v4 = NULL;
+ }
+ if (override->overlays.v6) {
+ facemgr_cfg_overlay_free(override->overlays.v6);
+ override->overlays.v6 = NULL;
+ }
- return 0;
+ return 0;
}
-
/* Rule */
-facemgr_cfg_rule_t * facemgr_cfg_rule_create()
-{
- facemgr_cfg_rule_t * rule = malloc(sizeof(facemgr_cfg_rule_t));
- if (!rule)
- return NULL;
+facemgr_cfg_rule_t *facemgr_cfg_rule_create() {
+ facemgr_cfg_rule_t *rule = malloc(sizeof(facemgr_cfg_rule_t));
+ if (!rule) return NULL;
- int rc = facemgr_cfg_rule_initialize(rule);
- if (rc < 0)
- return NULL;
+ int rc = facemgr_cfg_rule_initialize(rule);
+ if (rc < 0) return NULL;
- return rule;
+ return rule;
}
-void facemgr_cfg_rule_free(facemgr_cfg_rule_t * rule)
-{
- facemgr_cfg_rule_finalize(rule);
- free(rule);
+void facemgr_cfg_rule_free(facemgr_cfg_rule_t *rule) {
+ facemgr_cfg_rule_finalize(rule);
+ free(rule);
}
-int facemgr_cfg_rule_initialize(facemgr_cfg_rule_t * rule)
-{
- rule->match.interface_name = NULL;
- rule->match.interface_type = NETDEVICE_TYPE_UNDEFINED;
+int facemgr_cfg_rule_initialize(facemgr_cfg_rule_t *rule) {
+ rule->match.interface_name = NULL;
+ rule->match.interface_type = NETDEVICE_TYPE_UNDEFINED;
- int rc = facemgr_cfg_override_initialize(&rule->override);
- if (rc < 0)
- return -1;
+ int rc = facemgr_cfg_override_initialize(&rule->override);
+ if (rc < 0) return -1;
- return 0;
+ return 0;
}
-int facemgr_cfg_rule_finalize(facemgr_cfg_rule_t * rule)
-{
- if (rule->match.interface_name) {
- free((void*)rule->match.interface_name);
- rule->match.interface_name = NULL;
+int facemgr_cfg_rule_finalize(facemgr_cfg_rule_t *rule) {
+ if (rule->match.interface_name) {
+ free((void *)rule->match.interface_name);
+ rule->match.interface_name = NULL;
+ }
+ return facemgr_cfg_override_finalize(&rule->override);
+}
+
+void facemgr_cfg_rule_dump(facemgr_cfg_rule_t *rule) {
+ DEBUG(" <rule>");
+ DEBUG(" <match interface_name=%s interface_type=%s>",
+ rule->match.interface_name,
+ netdevice_type_str(rule->match.interface_type));
+ DEBUG(" <override>");
+ if (rule->override.is_face_type) {
+ DEBUG(" <face_type>%d</face_type>", rule->override.face_type);
+ }
+ if (rule->override.is_ignore) {
+ DEBUG(" <ignore>%d</ignore>", rule->override.ignore);
+ }
+ if (rule->override.is_discovery) {
+ DEBUG(" <discovery>%d</discovery>", rule->override.discovery);
+ }
+ if (rule->override.is_ipv4) {
+ DEBUG(" <ipv4>%d</ipv4>", rule->override.ipv4);
+ }
+ if (rule->override.is_ipv6) {
+ DEBUG(" <ipv6>%d</ipv6>", rule->override.ipv6);
+ }
+ DEBUG(" <overlays>");
+ if (rule->override.overlays.v4) {
+ DEBUG(" <ipv4>");
+ if (rule->override.overlays.v4->is_local_addr) {
+ char buf[MAXSZ_IP_ADDRESS];
+ hicn_ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
+ &rule->override.overlays.v4->local_addr);
+ DEBUG(" <local_addr>%s</local_addr>", buf);
}
- return facemgr_cfg_override_finalize(&rule->override);
-}
-
-void facemgr_cfg_rule_dump(facemgr_cfg_rule_t * rule)
-{
- DEBUG(" <rule>");
- DEBUG(" <match interface_name=%s interface_type=%s>",
- rule->match.interface_name,
- netdevice_type_str[rule->match.interface_type]);
- DEBUG(" <override>");
- if (rule->override.is_face_type) {
- DEBUG(" <face_type>%d</face_type>", rule->override.face_type);
+ if (rule->override.overlays.v4->is_local_port) {
+ DEBUG(" <local_port>%d</local_port>",
+ rule->override.overlays.v4->local_port);
}
- if (rule->override.is_ignore) {
- DEBUG(" <ignore>%d</ignore>", rule->override.ignore);
+ if (rule->override.overlays.v4->is_remote_addr) {
+ char buf[MAXSZ_IP_ADDRESS];
+ hicn_ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
+ &rule->override.overlays.v4->remote_addr);
+ DEBUG(" <remote_addr>%s</remote_addr>", buf);
}
- if (rule->override.is_discovery) {
- DEBUG(" <discovery>%d</discovery>", rule->override.discovery);
+ if (rule->override.overlays.v4->is_remote_port) {
+ DEBUG(" <remote_port>%d</remote_port>",
+ rule->override.overlays.v4->remote_port);
}
- if (rule->override.is_ipv4) {
- DEBUG(" <ipv4>%d</ipv4>", rule->override.ipv4);
+ DEBUG(" </ipv4>");
+ }
+ if (rule->override.overlays.v6) {
+ DEBUG(" <ipv6>");
+ if (rule->override.overlays.v6->is_local_addr) {
+ char buf[MAXSZ_IP_ADDRESS];
+ hicn_ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
+ &rule->override.overlays.v6->local_addr);
+ DEBUG(" <local_addr>%s</local_addr>", buf);
}
- if (rule->override.is_ipv6) {
- DEBUG(" <ipv6>%d</ipv6>", rule->override.ipv6);
+ if (rule->override.overlays.v6->is_local_port) {
+ DEBUG(" <local_port>%d</local_port>",
+ rule->override.overlays.v6->local_port);
}
- DEBUG(" <overlays>");
- if (rule->override.overlays.v4) {
- DEBUG(" <ipv4>");
- if (rule->override.overlays.v4->is_local_addr) {
- char buf[MAXSZ_IP_ADDRESS];
- ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
- &rule->override.overlays.v4->local_addr, AF_INET);
- DEBUG(" <local_addr>%s</local_addr>", buf);
- }
- if (rule->override.overlays.v4->is_local_port) {
- DEBUG(" <local_port>%d</local_port>",
- rule->override.overlays.v4->local_port);
- }
- if (rule->override.overlays.v4->is_remote_addr) {
- char buf[MAXSZ_IP_ADDRESS];
- ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
- &rule->override.overlays.v4->remote_addr, AF_INET);
- DEBUG(" <remote_addr>%s</remote_addr>", buf);
- }
- if (rule->override.overlays.v4->is_remote_port) {
- DEBUG(" <remote_port>%d</remote_port>",
- rule->override.overlays.v4->remote_port);
- }
- DEBUG(" </ipv4>");
+ if (rule->override.overlays.v6->is_remote_addr) {
+ char buf[MAXSZ_IP_ADDRESS];
+ hicn_ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
+ &rule->override.overlays.v6->remote_addr);
+ DEBUG(" <remote_addr>%s</remote_addr>", buf);
}
- if (rule->override.overlays.v6) {
- DEBUG(" <ipv6>");
- if (rule->override.overlays.v6->is_local_addr) {
- char buf[MAXSZ_IP_ADDRESS];
- ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
- &rule->override.overlays.v6->local_addr, AF_INET6);
- DEBUG(" <local_addr>%s</local_addr>", buf);
- }
- if (rule->override.overlays.v6->is_local_port) {
- DEBUG(" <local_port>%d</local_port>",
- rule->override.overlays.v6->local_port);
- }
- if (rule->override.overlays.v6->is_remote_addr) {
- char buf[MAXSZ_IP_ADDRESS];
- ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
- &rule->override.overlays.v6->remote_addr, AF_INET6);
- DEBUG(" <remote_addr>%s</remote_addr>", buf);
- }
- if (rule->override.overlays.v6->is_remote_port) {
- DEBUG(" <remote_port>%d</remote_port>",
- rule->override.overlays.v6->remote_port);
- }
- DEBUG(" </ipv6>");
+ if (rule->override.overlays.v6->is_remote_port) {
+ DEBUG(" <remote_port>%d</remote_port>",
+ rule->override.overlays.v6->remote_port);
}
- DEBUG(" </overlays>");
- DEBUG(" </override>");
- DEBUG(" </rule>");
+ DEBUG(" </ipv6>");
+ }
+ DEBUG(" </overlays>");
+ DEBUG(" </override>");
+ DEBUG(" </rule>");
}
-int facemgr_cfg_rule_set_match(facemgr_cfg_rule_t * rule, const char * interface_name,
- netdevice_type_t interface_type)
-{
- rule->match.interface_name = interface_name ? strdup(interface_name) : NULL;
- rule->match.interface_type = interface_type;
- return 0;
+int facemgr_cfg_rule_set_match(facemgr_cfg_rule_t *rule,
+ const char *interface_name,
+ netdevice_type_t interface_type) {
+ rule->match.interface_name = interface_name ? strdup(interface_name) : NULL;
+ rule->match.interface_type = interface_type;
+ return 0;
}
-int facemgr_cfg_rule_set_face_type(facemgr_cfg_rule_t * rule, facemgr_face_type_t * face_type)
-{
- rule->override.is_face_type = true;
- rule->override.face_type = *face_type;
- return 0;
+int facemgr_cfg_rule_set_face_type(facemgr_cfg_rule_t *rule,
+ facemgr_face_type_t *face_type) {
+ rule->override.is_face_type = true;
+ rule->override.face_type = *face_type;
+ return 0;
}
-int facemgr_cfg_rule_unset_face_type(facemgr_cfg_rule_t * rule)
-{
- rule->override.is_face_type = false;
- rule->override.face_type = FACEMGR_FACE_TYPE_UNDEFINED; /* optional */
- return 0;
+int facemgr_cfg_rule_unset_face_type(facemgr_cfg_rule_t *rule) {
+ rule->override.is_face_type = false;
+ rule->override.face_type = FACEMGR_FACE_TYPE_UNDEFINED; /* optional */
+ return 0;
}
-int facemgr_cfg_rule_set_discovery(facemgr_cfg_rule_t * rule, bool status)
-{
- rule->override.is_discovery = true;
- rule->override.discovery = status;
- return 0;
+int facemgr_cfg_rule_set_discovery(facemgr_cfg_rule_t *rule, bool status) {
+ rule->override.is_discovery = true;
+ rule->override.discovery = status;
+ return 0;
}
-int facemgr_cfg_rule_unset_discovery(facemgr_cfg_rule_t * rule)
-{
- rule->override.is_discovery = false;
- return 0;
+int facemgr_cfg_rule_unset_discovery(facemgr_cfg_rule_t *rule) {
+ rule->override.is_discovery = false;
+ return 0;
}
-int facemgr_cfg_rule_set_ignore(facemgr_cfg_rule_t * rule, bool status)
-{
- rule->override.is_ignore = true;
- rule->override.ignore = status;
- return 0;
+int facemgr_cfg_rule_set_ignore(facemgr_cfg_rule_t *rule, bool status) {
+ rule->override.is_ignore = true;
+ rule->override.ignore = status;
+ return 0;
}
-int facemgr_cfg_rule_unset_ignore(facemgr_cfg_rule_t * rule)
-{
- rule->override.is_ignore = false;
- return 0;
+int facemgr_cfg_rule_unset_ignore(facemgr_cfg_rule_t *rule) {
+ rule->override.is_ignore = false;
+ return 0;
}
-int facemgr_cfg_rule_set_ipv4(facemgr_cfg_rule_t * rule, bool status)
-{
- rule->override.is_ipv4 = true;
- rule->override.ipv4 = status;
- return 0;
+int facemgr_cfg_rule_set_ipv4(facemgr_cfg_rule_t *rule, bool status) {
+ rule->override.is_ipv4 = true;
+ rule->override.ipv4 = status;
+ return 0;
}
-int facemgr_cfg_rule_unset_ipv4(facemgr_cfg_rule_t * rule)
-{
- rule->override.is_ipv4 = false;
- return 0;
+int facemgr_cfg_rule_unset_ipv4(facemgr_cfg_rule_t *rule) {
+ rule->override.is_ipv4 = false;
+ return 0;
}
-int facemgr_cfg_rule_set_ipv6(facemgr_cfg_rule_t * rule, bool status)
-{
- rule->override.is_ipv6 = true;
- rule->override.ipv6 = status;
- return 0;
+int facemgr_cfg_rule_set_ipv6(facemgr_cfg_rule_t *rule, bool status) {
+ rule->override.is_ipv6 = true;
+ rule->override.ipv6 = status;
+ return 0;
}
-int facemgr_cfg_rule_unset_ipv6(facemgr_cfg_rule_t * rule)
-{
- rule->override.is_ipv6 = false;
- return 0;
+int facemgr_cfg_rule_unset_ipv6(facemgr_cfg_rule_t *rule) {
+ rule->override.is_ipv6 = false;
+ return 0;
}
-int facemgr_cfg_rule_set_overlay(facemgr_cfg_rule_t * rule, int family,
- ip_address_t * local_addr, uint16_t local_port,
- ip_address_t * remote_addr, uint16_t remote_port) {
- if ((family != AF_INET) && (family != AF_INET6))
- return -1;
+int facemgr_cfg_rule_set_overlay(facemgr_cfg_rule_t *rule, int family,
+ hicn_ip_address_t *local_addr,
+ uint16_t local_port,
+ hicn_ip_address_t *remote_addr,
+ uint16_t remote_port) {
+ if ((family != AF_INET) && (family != AF_INET6)) return -1;
- facemgr_cfg_overlay_t * overlay = facemgr_cfg_overlay_create();
- if (local_addr) {
- overlay->is_local_addr = true;
- overlay->local_addr = *local_addr;
- }
- if (IS_VALID_PORT(local_port)) {
- overlay->is_local_port = true;
- overlay->local_port = local_port;
- }
- if (remote_addr) {
- overlay->is_remote_addr = true;
- overlay->remote_addr = *remote_addr;
- }
- if (IS_VALID_PORT(remote_port)) {
- overlay->is_remote_port = true;
- overlay->remote_port = remote_port;
- }
+ facemgr_cfg_overlay_t *overlay = facemgr_cfg_overlay_create();
+ if (local_addr) {
+ overlay->is_local_addr = true;
+ overlay->local_addr = *local_addr;
+ }
+ if (IS_VALID_PORT(local_port)) {
+ overlay->is_local_port = true;
+ overlay->local_port = local_port;
+ }
+ if (remote_addr) {
+ overlay->is_remote_addr = true;
+ overlay->remote_addr = *remote_addr;
+ }
+ if (IS_VALID_PORT(remote_port)) {
+ overlay->is_remote_port = true;
+ overlay->remote_port = remote_port;
+ }
- switch(family) {
- case AF_INET:
- rule->override.overlays.v4 = overlay;
- break;
+ switch (family) {
+ case AF_INET:
+ rule->override.overlays.v4 = overlay;
+ break;
- case AF_INET6:
- rule->override.overlays.v6 = overlay;
- break;
+ case AF_INET6:
+ rule->override.overlays.v6 = overlay;
+ break;
- default:
- return -1;
- }
+ default:
+ return -1;
+ }
- return 0;
+ return 0;
}
-int facemgr_rule_unset_overlay(facemgr_cfg_rule_t * rule, int family)
-{
- if ((family != AF_INET) && (family != AF_INET6) && (family != AF_UNSPEC))
- return -1;
+int facemgr_rule_unset_overlay(facemgr_cfg_rule_t *rule, int family) {
+ if ((family != AF_INET) && (family != AF_INET6) && (family != AF_UNSPEC))
+ return -1;
- if ((family == AF_UNSPEC) || (family == AF_INET)) {
- if (rule->override.overlays.v4) {
- facemgr_cfg_overlay_free(rule->override.overlays.v4);
- rule->override.overlays.v4 = NULL;
- }
- }
- if ((family == AF_UNSPEC) || (family == AF_INET6)) {
- if (rule->override.overlays.v6) {
- facemgr_cfg_overlay_free(rule->override.overlays.v6);
- rule->override.overlays.v6 = NULL;
- }
+ if ((family == AF_UNSPEC) || (family == AF_INET)) {
+ if (rule->override.overlays.v4) {
+ facemgr_cfg_overlay_free(rule->override.overlays.v4);
+ rule->override.overlays.v4 = NULL;
}
- return 0;
-}
-
-int facemgr_cfg_rule_cmp(const facemgr_cfg_rule_t * r1, const facemgr_cfg_rule_t * r2)
-{
- /*
- * We implement a lexicographic order on the tuple (interface_name,
- * interface_type)
- */
-
- /* We need to handle NULL cases out of strcmp */
- if (!r1->match.interface_name) {
- if (r2->match.interface_name)
- return 1;
- else
- goto BOTH_NULL;
- } else {
- if (!r2->match.interface_name)
- return -1;
+ }
+ if ((family == AF_UNSPEC) || (family == AF_INET6)) {
+ if (rule->override.overlays.v6) {
+ facemgr_cfg_overlay_free(rule->override.overlays.v6);
+ rule->override.overlays.v6 = NULL;
}
-
-
- /* Only if both are non-NULL, we proceed to strcmp */
- int rc = strcmp(r1->match.interface_name, r2->match.interface_name);
- if (rc != 0)
- return rc;
+ }
+ return 0;
+}
+
+int facemgr_cfg_rule_cmp(const facemgr_cfg_rule_t *r1,
+ const facemgr_cfg_rule_t *r2) {
+ /*
+ * We implement a lexicographic order on the tuple (interface_name,
+ * interface_type)
+ */
+
+ /* We need to handle NULL cases out of strcmp */
+ if (!r1->match.interface_name) {
+ if (r2->match.interface_name)
+ return 1;
+ else
+ goto BOTH_NULL;
+ } else {
+ if (!r2->match.interface_name) return -1;
+ }
+
+ /* Only if both are non-NULL, we proceed to strcmp */
+ int rc = strcmp(r1->match.interface_name, r2->match.interface_name);
+ if (rc != 0) return rc;
BOTH_NULL:
- return r1->match.interface_type - r2->match.interface_type;
+ return r1->match.interface_type - r2->match.interface_type;
}
/* General */
TYPEDEF_SET_H(facemgr_cfg_rule_set, facemgr_cfg_rule_t *);
-TYPEDEF_SET(facemgr_cfg_rule_set, facemgr_cfg_rule_t *, facemgr_cfg_rule_cmp, generic_snprintf);
+TYPEDEF_SET(facemgr_cfg_rule_set, facemgr_cfg_rule_t *, facemgr_cfg_rule_cmp,
+ generic_snprintf);
struct facemgr_cfg_s {
- facemgr_cfg_override_t global;
- facemgr_cfg_rule_set_t * rule_set;
- facelet_array_t * static_facelets;
- //log_cfg_t log;
+ facemgr_cfg_override_t global;
+ facemgr_cfg_rule_set_t *rule_set;
+ facelet_array_t *static_facelets;
+ // log_cfg_t log;
};
-facemgr_cfg_t * facemgr_cfg_create()
-{
- facemgr_cfg_t * cfg = malloc(sizeof(facemgr_cfg_t));
- if (!cfg) {
- ERROR("[facemgr_cfg_create] Error allocating face manager configuration");
- goto ERR_MALLOC;
- }
+facemgr_cfg_t *facemgr_cfg_create() {
+ facemgr_cfg_t *cfg = malloc(sizeof(facemgr_cfg_t));
+ if (!cfg) {
+ ERROR("[facemgr_cfg_create] Error allocating face manager configuration");
+ goto ERR_MALLOC;
+ }
- int rc = facemgr_cfg_initialize(cfg);
- if (rc < 0) {
- ERROR("[facemgr_cfg_create] Error initializing face manager configuration");
- goto ERR_INIT;
- }
+ int rc = facemgr_cfg_initialize(cfg);
+ if (rc < 0) {
+ ERROR("[facemgr_cfg_create] Error initializing face manager configuration");
+ goto ERR_INIT;
+ }
- return cfg;
+ return cfg;
ERR_INIT:
- free(cfg);
+ free(cfg);
ERR_MALLOC:
- return NULL;
+ return NULL;
}
-void facemgr_cfg_free(facemgr_cfg_t * cfg)
-{
- facemgr_cfg_finalize(cfg);
- free(cfg);
+void facemgr_cfg_free(facemgr_cfg_t *cfg) {
+ facemgr_cfg_finalize(cfg);
+ free(cfg);
}
-int facemgr_cfg_initialize(facemgr_cfg_t * cfg)
-{
- int rc = facemgr_cfg_override_initialize(&cfg->global);
- if (rc < 0) {
- ERROR("[facemgr_cfg_initialize] Error initializing global values");
- goto ERR_OVERRIDE;
- }
+int facemgr_cfg_initialize(facemgr_cfg_t *cfg) {
+ int rc = facemgr_cfg_override_initialize(&cfg->global);
+ if (rc < 0) {
+ ERROR("[facemgr_cfg_initialize] Error initializing global values");
+ goto ERR_OVERRIDE;
+ }
- cfg->rule_set = facemgr_cfg_rule_set_create();
- if (!cfg->rule_set) {
- ERROR("[facemgr_cfg_initialize] Error creating rule set");
- goto ERR_RULE_SET;
- }
+ cfg->rule_set = facemgr_cfg_rule_set_create();
+ if (!cfg->rule_set) {
+ ERROR("[facemgr_cfg_initialize] Error creating rule set");
+ goto ERR_RULE_SET;
+ }
- cfg->static_facelets = facelet_array_create(cfg->static_facelets);
- if (!cfg->static_facelets) {
- ERROR("[facemgr_cfg_initialize] Error creating static facelet set");
- goto ERR_STATIC;
- }
+ cfg->static_facelets = facelet_array_create();
+ if (!cfg->static_facelets) {
+ ERROR("[facemgr_cfg_initialize] Error creating static facelet set");
+ goto ERR_STATIC;
+ }
- return 0;
+ return 0;
ERR_STATIC:
- facemgr_cfg_rule_set_free(cfg->rule_set);
+ facemgr_cfg_rule_set_free(cfg->rule_set);
ERR_RULE_SET:
- facemgr_cfg_override_finalize(&cfg->global);
+ facemgr_cfg_override_finalize(&cfg->global);
ERR_OVERRIDE:
- return -1;
-}
-
-int facemgr_cfg_finalize(facemgr_cfg_t * cfg)
-{
- /* TODO Free all rules */
- facemgr_cfg_rule_t ** rule_array;
- int n = facemgr_cfg_rule_set_get_array(cfg->rule_set, &rule_array);
- if (n < 0) {
- ERROR("[facemgr_cfg_finalize] Could not retrieve rule set array from configuration");
- } else {
- for (unsigned i = 0; i < n; i++) {
- facemgr_cfg_rule_t * rule = rule_array[i];
- if (facemgr_cfg_rule_set_remove(cfg->rule_set, rule, NULL) < 0) {
- ERROR("[facemgr_cfg_finalize] Could not remove rule from set");
- }
- facemgr_cfg_rule_free(rule);
- }
- free(rule_array);
+ return -1;
+}
+
+int facemgr_cfg_finalize(facemgr_cfg_t *cfg) {
+ /* TODO Free all rules */
+ facemgr_cfg_rule_t **rule_array;
+ int n = facemgr_cfg_rule_set_get_array(cfg->rule_set, &rule_array);
+ if (n < 0) {
+ ERROR(
+ "[facemgr_cfg_finalize] Could not retrieve rule set array from "
+ "configuration");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ facemgr_cfg_rule_t *rule = rule_array[i];
+ if (!rule) continue; /* Should not occur */
+ if (facemgr_cfg_rule_set_remove(cfg->rule_set, rule, NULL) < 0) {
+ ERROR("[facemgr_cfg_finalize] Could not remove rule from set");
+ }
+ facemgr_cfg_rule_free(rule);
+ }
+ free(rule_array);
+ }
+ facemgr_cfg_rule_set_free(cfg->rule_set);
+
+ /* Free all facelets from static array */
+ for (unsigned i = 0; i < facelet_array_len(cfg->static_facelets); i++) {
+ facelet_t *facelet;
+ if (facelet_array_get_index(cfg->static_facelets, i, &facelet) < 0) {
+ ERROR("[facemgr_cfg_finalize] Error getting facelet in array");
+ continue;
}
- facemgr_cfg_rule_set_free(cfg->rule_set);
-
- /* Free all facelets from static array */
- for (unsigned i = 0; i < facelet_array_len(cfg->static_facelets); i++) {
- facelet_t * facelet;
- if (facelet_array_get_index(cfg->static_facelets, i, &facelet) < 0) {
- ERROR("[facemgr_cfg_finalize] Error getting facelet in array");
- continue;
- }
- if (facelet_array_remove_index(cfg->static_facelets, i, NULL)) {
- ERROR("[facemgr_cfg_finalize] Could not purge facelet from static set");
- }
- facelet_free(facelet);
+ if (facelet_array_remove_index(cfg->static_facelets, i, NULL)) {
+ ERROR("[facemgr_cfg_finalize] Could not purge facelet from static set");
}
+ facelet_free(facelet);
+ }
- facelet_array_free(cfg->static_facelets);
+ facelet_array_free(cfg->static_facelets);
- return facemgr_cfg_override_finalize(&cfg->global);
+ return facemgr_cfg_override_finalize(&cfg->global);
}
-void facemgr_cfg_dump(facemgr_cfg_t * cfg)
-{
- return; /* NOT IMPLEMENTED */
-}
+void facemgr_cfg_dump(facemgr_cfg_t *cfg) { return; /* NOT IMPLEMENTED */ }
/* General */
-int facemgr_cfg_set_face_type(facemgr_cfg_t * cfg, facemgr_face_type_t * face_type)
-{
- cfg->global.is_face_type = true;
- cfg->global.face_type = *face_type;
- return 0;
-}
-
-int facemgr_cfg_unset_face_type(facemgr_cfg_t * cfg)
-{
- cfg->global.is_face_type = false;
- cfg->global.face_type = FACEMGR_FACE_TYPE_UNDEFINED; /* optional */
- return 0;
-}
-
-int facemgr_cfg_set_discovery(facemgr_cfg_t * cfg, bool status)
-{
- cfg->global.is_discovery = true;
- cfg->global.discovery = status;
- return 0;
-}
-
-int facemgr_cfg_unset_discovery(facemgr_cfg_t * cfg)
-{
- cfg->global.is_discovery = false;
- return 0;
-}
-
-int facemgr_cfg_set_ipv4(facemgr_cfg_t * cfg, bool status)
-{
- cfg->global.is_ipv4 = true;
- cfg->global.ipv4 = status;
- DEBUG("<global>");
- DEBUG(" <ipv4>%d</ipv4>", cfg->global.ipv4);
- DEBUG("</global>");
- return 0;
-}
-
-int facemgr_cfg_unset_ipv4(facemgr_cfg_t * cfg)
-{
- cfg->global.is_ipv4 = false;
- return 0;
-}
-
-int facemgr_cfg_set_ipv6(facemgr_cfg_t * cfg, bool status)
-{
- cfg->global.is_ipv6 = true;
- cfg->global.ipv6 = status;
- DEBUG("<global>");
- DEBUG(" <ipv6>%d</ipv6>", cfg->global.ipv6);
- DEBUG("</global>");
- return 0;
-}
-
-int facemgr_cfg_unset_ipv6(facemgr_cfg_t * cfg)
-{
- cfg->global.is_ipv6 = false;
- return 0;
-}
-
-int facemgr_cfg_set_overlay(facemgr_cfg_t * cfg, int family,
- ip_address_t * local_addr, uint16_t local_port,
- ip_address_t * remote_addr, uint16_t remote_port)
-{
- if ((family != AF_INET) && (family != AF_INET6))
- return -1;
-
- facemgr_cfg_overlay_t * overlay = facemgr_cfg_overlay_create();
- if (local_addr) {
- overlay->is_local_addr = true;
- overlay->local_addr = *local_addr;
- }
- if (IS_VALID_PORT(local_port)) {
- overlay->is_local_port = true;
- overlay->local_port = local_port;
- }
- if (remote_addr) {
- overlay->is_remote_addr = true;
- overlay->remote_addr = *remote_addr;
+int facemgr_cfg_set_face_type(facemgr_cfg_t *cfg,
+ facemgr_face_type_t *face_type) {
+ cfg->global.is_face_type = true;
+ cfg->global.face_type = *face_type;
+ return 0;
+}
+
+int facemgr_cfg_unset_face_type(facemgr_cfg_t *cfg) {
+ cfg->global.is_face_type = false;
+ cfg->global.face_type = FACEMGR_FACE_TYPE_UNDEFINED; /* optional */
+ return 0;
+}
+
+int facemgr_cfg_set_discovery(facemgr_cfg_t *cfg, bool status) {
+ cfg->global.is_discovery = true;
+ cfg->global.discovery = status;
+ return 0;
+}
+
+int facemgr_cfg_unset_discovery(facemgr_cfg_t *cfg) {
+ cfg->global.is_discovery = false;
+ return 0;
+}
+
+int facemgr_cfg_set_ipv4(facemgr_cfg_t *cfg, bool status) {
+ cfg->global.is_ipv4 = true;
+ cfg->global.ipv4 = status;
+ DEBUG("<global>");
+ DEBUG(" <ipv4>%d</ipv4>", cfg->global.ipv4);
+ DEBUG("</global>");
+ return 0;
+}
+
+int facemgr_cfg_unset_ipv4(facemgr_cfg_t *cfg) {
+ cfg->global.is_ipv4 = false;
+ return 0;
+}
+
+int facemgr_cfg_set_ipv6(facemgr_cfg_t *cfg, bool status) {
+ cfg->global.is_ipv6 = true;
+ cfg->global.ipv6 = status;
+ DEBUG("<global>");
+ DEBUG(" <ipv6>%d</ipv6>", cfg->global.ipv6);
+ DEBUG("</global>");
+ return 0;
+}
+
+int facemgr_cfg_unset_ipv6(facemgr_cfg_t *cfg) {
+ cfg->global.is_ipv6 = false;
+ return 0;
+}
+
+int facemgr_cfg_set_overlay(facemgr_cfg_t *cfg, int family,
+ hicn_ip_address_t *local_addr, uint16_t local_port,
+ hicn_ip_address_t *remote_addr,
+ uint16_t remote_port) {
+ if ((family != AF_INET) && (family != AF_INET6)) return -1;
+
+ facemgr_cfg_overlay_t *overlay = facemgr_cfg_overlay_create();
+ if (local_addr) {
+ overlay->is_local_addr = true;
+ overlay->local_addr = *local_addr;
+ }
+ if (IS_VALID_PORT(local_port)) {
+ overlay->is_local_port = true;
+ overlay->local_port = local_port;
+ }
+ if (remote_addr) {
+ overlay->is_remote_addr = true;
+ overlay->remote_addr = *remote_addr;
+ }
+ if (IS_VALID_PORT(remote_port)) {
+ overlay->is_remote_port = true;
+ overlay->remote_port = remote_port;
+ }
+
+ DEBUG("facemgr_cfg_set_overlay");
+
+ switch (family) {
+ case AF_INET:
+ cfg->global.overlays.v4 = overlay;
+ break;
+
+ case AF_INET6:
+ cfg->global.overlays.v6 = overlay;
+ break;
+
+ default:
+ return -1;
+ }
+
+ DEBUG("<global>");
+ DEBUG(" <overlay>");
+ if (overlay) {
+ DEBUG(" <ipv4>");
+ if (overlay->is_local_addr) {
+ char buf[MAXSZ_IP_ADDRESS];
+ hicn_ip_address_snprintf(buf, MAXSZ_IP_ADDRESS, &overlay->local_addr);
+ DEBUG(" <local_addr>%s</local_addr>", buf);
}
- if (IS_VALID_PORT(remote_port)) {
- overlay->is_remote_port = true;
- overlay->remote_port = remote_port;
+ if (overlay->is_local_port) {
+ DEBUG(" <local_port>%d</local_port>", overlay->local_port);
}
-
- DEBUG("facemgr_cfg_set_overlay");
-
- switch(family) {
- case AF_INET:
- cfg->global.overlays.v4 = overlay;
- break;
-
- case AF_INET6:
- cfg->global.overlays.v6 = overlay;
- break;
-
- default:
- return -1;
+ if (overlay->is_remote_addr) {
+ char buf[MAXSZ_IP_ADDRESS];
+ hicn_ip_address_snprintf(buf, MAXSZ_IP_ADDRESS, &overlay->remote_addr);
+ DEBUG(" <remote_addr>%s</remote_addr>", buf);
}
-
- DEBUG("<global>");
- DEBUG(" <overlay>");
- if (overlay) {
- DEBUG(" <ipv4>");
- if (overlay->is_local_addr) {
- char buf[MAXSZ_IP_ADDRESS];
- ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
- &overlay->local_addr, AF_INET);
- DEBUG(" <local_addr>%s</local_addr>", buf);
- }
- if (overlay->is_local_port) {
- DEBUG(" <local_port>%d</local_port>",
- overlay->local_port);
- }
- if (overlay->is_remote_addr) {
- char buf[MAXSZ_IP_ADDRESS];
- ip_address_snprintf(buf, MAXSZ_IP_ADDRESS,
- &overlay->remote_addr, AF_INET);
- DEBUG(" <remote_addr>%s</remote_addr>", buf);
- }
- if (overlay->is_remote_port) {
- DEBUG(" <remote_port>%d</remote_port>",
- overlay->remote_port);
- }
- DEBUG(" </ipv4>");
+ if (overlay->is_remote_port) {
+ DEBUG(" <remote_port>%d</remote_port>", overlay->remote_port);
}
- DEBUG(" </overlay>");
- DEBUG("</global>");
+ DEBUG(" </ipv4>");
+ }
+ DEBUG(" </overlay>");
+ DEBUG("</global>");
- return 0;
+ return 0;
}
-int facemgr_cfg_unset_overlay(facemgr_cfg_t * cfg, int family)
-{
- if ((family != AF_INET) && (family != AF_INET6) && (family != AF_UNSPEC))
- return -1;
+int facemgr_cfg_unset_overlay(facemgr_cfg_t *cfg, int family) {
+ if ((family != AF_INET) && (family != AF_INET6) && (family != AF_UNSPEC))
+ return -1;
- if ((family == AF_UNSPEC) || (family == AF_INET)) {
- if (cfg->global.overlays.v4) {
- facemgr_cfg_overlay_free(cfg->global.overlays.v4);
- cfg->global.overlays.v4 = NULL;
- }
+ if ((family == AF_UNSPEC) || (family == AF_INET)) {
+ if (cfg->global.overlays.v4) {
+ facemgr_cfg_overlay_free(cfg->global.overlays.v4);
+ cfg->global.overlays.v4 = NULL;
}
- if ((family == AF_UNSPEC) || (family == AF_INET6)) {
- if (cfg->global.overlays.v6) {
- facemgr_cfg_overlay_free(cfg->global.overlays.v6);
- cfg->global.overlays.v6 = NULL;
- }
+ }
+ if ((family == AF_UNSPEC) || (family == AF_INET6)) {
+ if (cfg->global.overlays.v6) {
+ facemgr_cfg_overlay_free(cfg->global.overlays.v6);
+ cfg->global.overlays.v6 = NULL;
}
- return 0;
+ }
+ return 0;
}
-int facemgr_cfg_add_rule(facemgr_cfg_t * cfg, facemgr_cfg_rule_t * rule)
-{
- facemgr_cfg_rule_dump(rule);
- return facemgr_cfg_rule_set_add(cfg->rule_set, rule);
+int facemgr_cfg_add_rule(facemgr_cfg_t *cfg, facemgr_cfg_rule_t *rule) {
+ facemgr_cfg_rule_dump(rule);
+ return facemgr_cfg_rule_set_add(cfg->rule_set, rule);
}
-int facemgr_cfg_del_rule(facemgr_cfg_t * cfg, facemgr_cfg_rule_t * rule)
-{
- return facemgr_cfg_rule_set_remove(cfg->rule_set, rule, NULL);
+int facemgr_cfg_del_rule(facemgr_cfg_t *cfg, facemgr_cfg_rule_t *rule) {
+ return facemgr_cfg_rule_set_remove(cfg->rule_set, rule, NULL);
}
-int facemgr_cfg_get_rule(const facemgr_cfg_t * cfg, const char * interface_name,
- netdevice_type_t interface_type, facemgr_cfg_rule_t ** rule) {
- facemgr_cfg_rule_t rule_search = {
- .match = {
- .interface_name = interface_name,
- .interface_type = interface_type,
- },
- };
- return facemgr_cfg_rule_set_get(cfg->rule_set, &rule_search, rule);
+int facemgr_cfg_get_rule(const facemgr_cfg_t *cfg, const char *interface_name,
+ netdevice_type_t interface_type,
+ facemgr_cfg_rule_t **rule) {
+ facemgr_cfg_rule_t rule_search = {
+ .match =
+ {
+ .interface_name = interface_name,
+ .interface_type = interface_type,
+ },
+ };
+ return facemgr_cfg_rule_set_get(cfg->rule_set, &rule_search, rule);
}
/* Query API */
@@ -709,506 +662,473 @@ int facemgr_cfg_get_rule(const facemgr_cfg_t * cfg, const char * interface_name,
* TODO:
* - until we have proper indexes we loop through the whole structure
*/
-int facemgr_cfg_get_override(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- facemgr_cfg_override_t ** override)
-{
- if (!netdevice) {
- *override = NULL;
- return 0;
- }
-
- facemgr_cfg_rule_t **rule_array;
- int rc = facemgr_cfg_rule_set_get_array(cfg->rule_set, &rule_array);
- if (rc < 0) {
- ERROR("facemgr_cfg_rule_set_get_array failed");
- return rc;
- }
- for (unsigned i = 0; i < rc; i++) {
- const char * interface_name = rule_array[i]->match.interface_name;
- /* Check match for interface name */
- if (interface_name && (strcmp(interface_name, netdevice->name) != 0))
- continue;
- /* Check match for interface type */
- if (rule_array[i]->match.interface_type != NETDEVICE_TYPE_UNDEFINED) {
-//#ifdef __ANDROID__
- if (netdevice_type != rule_array[i]->match.interface_type)
- continue;
-//#else
-// ERROR("Match on interface type is currently not implemented");
-// goto ERR_ARRAY;
-//#endif /* __ANDROID__ */
- }
- /* Found match... do we have an override for face_type */
- *override = &rule_array[i]->override;
- goto FOUND;
- }
-
+int facemgr_cfg_get_override(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type,
+ facemgr_cfg_override_t **override) {
+ if (!netdevice) {
*override = NULL;
-
-FOUND:
- free(rule_array);
return 0;
-
-//#ifndef __ANDROID__
-//ERR_ARRAY:
-// free(rule_array);
-// return -1;
-//#endif /* __ANDROID__ */
-}
-
-int facemgr_cfg_get_face_type(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- facemgr_face_type_t * face_type)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0) {
- ERROR("get override failed");
- return rc;
- }
-
- if ((override) && (override->is_face_type)) {
- *face_type = override->face_type;
- return 0;
+ }
+
+ facemgr_cfg_rule_t **rule_array;
+ int rc = facemgr_cfg_rule_set_get_array(cfg->rule_set, &rule_array);
+ if (rc < 0) {
+ ERROR("facemgr_cfg_rule_set_get_array failed");
+ return rc;
+ }
+ for (unsigned i = 0; i < rc; i++) {
+ facemgr_cfg_rule_t *rule = rule_array[i];
+ if (!rule) continue; /* Should not occur */
+ const char *interface_name = rule->match.interface_name;
+ /* Check match for interface name */
+ if (interface_name && (strcmp(interface_name, netdevice->name) != 0))
+ continue;
+ /* Check match for interface type */
+ if (rule->match.interface_type != NETDEVICE_TYPE_UNDEFINED) {
+ //#ifdef __ANDROID__
+ if (netdevice_type != rule->match.interface_type) continue;
+ //#else
+ // ERROR("Match on interface type is currently not
+ // implemented"); goto ERR_ARRAY;
+ //#endif /* __ANDROID__ */
}
+ /* Found match... do we have an override for face_type */
+ *override = &rule->override;
+ goto FOUND;
+ }
- *face_type = cfg->global.is_face_type
- ? cfg->global.face_type
- : FACEMGR_FACE_TYPE_DEFAULT;
+ *override = NULL;
+FOUND:
+ free(rule_array);
+ return 0;
+
+ //#ifndef __ANDROID__
+ // ERR_ARRAY:
+ // free(rule_array);
+ // return -1;
+ //#endif /* __ANDROID__ */
+}
+
+int facemgr_cfg_get_face_type(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type,
+ facemgr_face_type_t *face_type) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) {
+ ERROR("get override failed");
+ return rc;
+ }
+
+ if ((override) && (override->is_face_type)) {
+ *face_type = override->face_type;
return 0;
-}
+ }
-int facemgr_cfg_get_discovery(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * discovery)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- if ((override) && (override->is_discovery)) {
- *discovery = override->discovery;
- return 0;
- }
+ *face_type = cfg->global.is_face_type ? cfg->global.face_type
+ : FACEMGR_FACE_TYPE_DEFAULT;
- *discovery = cfg->global.is_discovery
- ? cfg->global.discovery
- : FACEMGR_CFG_DEFAULT_DISCOVERY;
- return 0;
+ return 0;
}
-int facemgr_cfg_get_ipv4(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * ipv4)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- if ((override) && (override->is_ipv4)) {
- *ipv4 = override->ipv4;
- return 0;
- }
+int facemgr_cfg_get_discovery(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type,
+ bool *discovery) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
- *ipv4 = cfg->global.is_ipv4
- ? cfg->global.ipv4
- : FACEMGR_CFG_DEFAULT_IPV4;
+ if ((override) && (override->is_discovery)) {
+ *discovery = override->discovery;
return 0;
-}
+ }
-int facemgr_cfg_get_ipv6(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * ipv6)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- if ((override) && (override->is_ipv6)) {
- *ipv6 = override->ipv6;
- return 0;
- }
-
- *ipv6 = cfg->global.is_ipv6
- ? cfg->global.ipv6
- : FACEMGR_CFG_DEFAULT_IPV6;
- return 0;
+ *discovery = cfg->global.is_discovery ? cfg->global.discovery
+ : FACEMGR_CFG_DEFAULT_DISCOVERY;
+ return 0;
}
-int facemgr_cfg_get_ignore(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- bool * ignore)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- if ((override) && (override->is_ignore)) {
- *ignore = override->ignore;
- return 0;
- }
-
- assert (!cfg->global.is_ignore);
-
- *ignore = (netdevice && (netdevice->name[0] != '\0') && strcmp(netdevice->name, "lo") == 0);
+int facemgr_cfg_get_ipv4(const facemgr_cfg_t *cfg, const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type, bool *ipv4) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
+ if ((override) && (override->is_ipv4)) {
+ *ipv4 = override->ipv4;
return 0;
-}
+ }
-int facemgr_cfg_get_overlay_local_addr(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, ip_address_t * addr)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- switch (family) {
- case AF_INET:
- if ((override) && (override->overlays.v4) && (override->overlays.v4->is_local_addr)) {
- *addr = override->overlays.v4->local_addr;
- return 0;
- }
- if ((cfg->global.overlays.v4) && (cfg->global.overlays.v4->is_local_addr)) {
- *addr = cfg->global.overlays.v4->local_addr;
- return 0;
- }
- break;
- case AF_INET6:
- if ((override) && (override->overlays.v6) && (override->overlays.v6->is_local_addr)) {
- *addr = override->overlays.v6->local_addr;
- return 0;
- }
- if ((cfg->global.overlays.v6) && (cfg->global.overlays.v6->is_local_addr)) {
- *addr = cfg->global.overlays.v6->local_addr;
- return 0;
- }
- break;
- case AF_UNSPEC:
- break;
- default:
- return -1;
- }
-
- *addr = IP_ADDRESS_EMPTY;
- return 0;
+ *ipv4 = cfg->global.is_ipv4 ? cfg->global.ipv4 : FACEMGR_CFG_DEFAULT_IPV4;
+ return 0;
}
-int facemgr_cfg_get_overlay_local_port(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, u16 * port)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- switch (family) {
- case AF_INET:
- if ((override) && (override->overlays.v4) && (override->overlays.v4->is_local_port)) {
- *port = override->overlays.v4->local_port;
- return 0;
- }
- if ((cfg->global.overlays.v4) && (cfg->global.overlays.v4->is_local_port)) {
- *port = cfg->global.overlays.v4->local_port;
- return 0;
- }
- break;
- case AF_INET6:
- if ((override) && (override->overlays.v6) && (override->overlays.v6->is_local_port)) {
- *port = override->overlays.v6->local_port;
- return 0;
- }
- if ((cfg->global.overlays.v6) && (cfg->global.overlays.v6->is_local_port)) {
- *port = cfg->global.overlays.v6->local_port;
- return 0;
- }
- break;
- case AF_UNSPEC:
- break;
- default:
- return -1;
- }
+int facemgr_cfg_get_ipv6(const facemgr_cfg_t *cfg, const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type, bool *ipv6) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
- *port = HICN_DEFAULT_PORT;
+ if ((override) && (override->is_ipv6)) {
+ *ipv6 = override->ipv6;
return 0;
-}
-
-int facemgr_cfg_get_overlay_remote_addr(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, ip_address_t * addr)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- switch (family) {
- case AF_INET:
- if ((override) && (override->overlays.v4) && (override->overlays.v4->is_remote_addr)) {
- DEBUG("remote addr v4 from override");
- *addr = override->overlays.v4->remote_addr;
- return 0;
- }
- if ((cfg->global.overlays.v4) && (cfg->global.overlays.v4->is_remote_addr)) {
- DEBUG("remote addr v4 from global");
- *addr = cfg->global.overlays.v4->remote_addr;
- return 0;
- }
- break;
- case AF_INET6:
- if ((override) && (override->overlays.v6) && (override->overlays.v6->is_remote_addr)) {
- DEBUG("remote addr v6 from override");
- *addr = override->overlays.v6->remote_addr;
- return 0;
- }
- if ((cfg->global.overlays.v6) && (cfg->global.overlays.v6->is_remote_addr)) {
- DEBUG("remote addr v6 from global");
- *addr = cfg->global.overlays.v6->remote_addr;
- return 0;
- }
- break;
- case AF_UNSPEC:
- break;
- default:
- return -1;
- }
+ }
- DEBUG("remote addr empty");
- *addr = IP_ADDRESS_EMPTY;
- return 0;
+ *ipv6 = cfg->global.is_ipv6 ? cfg->global.ipv6 : FACEMGR_CFG_DEFAULT_IPV6;
+ return 0;
}
-int facemgr_cfg_get_overlay_remote_port(const facemgr_cfg_t * cfg,
- const netdevice_t * netdevice, netdevice_type_t netdevice_type,
- int family, u16 * port)
-{
- facemgr_cfg_override_t * override;
- int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type,
- &override);
- if (rc < 0)
- return rc;
-
- switch (family) {
- case AF_INET:
- if ((override) && (override->overlays.v4) && (override->overlays.v4->is_remote_port)) {
- *port = override->overlays.v4->remote_port;
- return 0;
- }
- if ((cfg->global.overlays.v4) && (cfg->global.overlays.v4->is_remote_port)) {
- *port = cfg->global.overlays.v4->remote_port;
- return 0;
- }
- break;
- case AF_INET6:
- if ((override) && (override->overlays.v6) && (override->overlays.v6->is_remote_port)) {
- *port = override->overlays.v6->remote_port;
- return 0;
- }
- if ((cfg->global.overlays.v6) && (cfg->global.overlays.v6->is_remote_port)) {
- *port = cfg->global.overlays.v6->remote_port;
- return 0;
- }
- break;
- case AF_UNSPEC:
- break;
- default:
- return -1;
- }
+int facemgr_cfg_get_ignore(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type, bool *ignore) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
- *port = HICN_DEFAULT_PORT;
+ if ((override) && (override->is_ignore)) {
+ *ignore = override->ignore;
return 0;
-}
+ }
-int facemgr_cfg_rule_get(const facemgr_cfg_t * cfg, const netdevice_t netdevice, netdevice_type_t
- netdevice_type, facemgr_cfg_rule_t ** rule)
-{
- facemgr_cfg_rule_t **rule_array;
- *rule = NULL;
- int n = facemgr_cfg_rule_set_get_array(cfg->rule_set, &rule_array);
- if (n < 0) {
- ERROR("facemgr_cfg_rule_set_get_array failed");
- return n;
- }
- for (unsigned i = 0; i < n; i++) {
- const char * interface_name = rule_array[i]->match.interface_name;
- /* Check match for interface name */
- if (netdevice.name[0] != '\0') {
- if (!interface_name)
- continue;
- if (strcmp(netdevice.name, interface_name) != 0)
- continue;
- } else {
- if (interface_name && interface_name[0] != '\0')
- continue;
- }
-
- /* Check match for netdevice_type */
- if (netdevice_type != rule_array[i]->match.interface_type)
- continue;
-
- /* Found */
- *rule = rule_array[i];
- break;
- }
- return 0;
-}
+ assert(!cfg->global.is_ignore);
-int facemgr_cfg_rule_get_face_type(const facemgr_cfg_rule_t * rule,
- facemgr_face_type_t * face_type)
-{
- if (!rule->override.is_face_type)
- return -1;
- *face_type = rule->override.face_type;
- return 0;
-}
-
-int facemgr_cfg_rule_get_discovery(const facemgr_cfg_rule_t * rule, bool * discovery)
-{
- if (!rule->override.is_discovery)
- return -1;
- *discovery = rule->override.discovery;
- return 0;
-}
-
-int facemgr_cfg_rule_get_ignore(const facemgr_cfg_rule_t * rule, bool * ignore)
-{
- if (!rule->override.is_ignore)
- return -1;
- *ignore = rule->override.ignore;
- return 0;
-}
-
-int facemgr_cfg_rule_get_ipv4(const facemgr_cfg_rule_t * rule, bool * ipv4)
-{
- if (!rule->override.is_ipv4)
- return -1;
- *ipv4 = rule->override.ipv4;
- return 0;
-}
-
-int facemgr_cfg_rule_get_ipv6(const facemgr_cfg_rule_t * rule, bool * ipv6)
-{
- if (!rule->override.is_ipv6)
- return -1;
- *ipv6 = rule->override.ipv6;
- return 0;
-}
-
-int facemgr_cfg_rule_get_overlay_local_addr(const facemgr_cfg_rule_t * rule, int family,
- ip_address_t * addr)
-{
- facemgr_cfg_overlay_t * overlay = NULL;
- switch(family) {
- case AF_INET:
- overlay = rule->override.overlays.v4;
- break;
- case AF_INET6:
- overlay = rule->override.overlays.v6;
- break;
- default:
- return -1;
- }
- if (!overlay->is_local_addr)
- return -1;
- *addr = overlay->local_addr;
- return 0;
-}
+ *ignore = (netdevice && (netdevice->name[0] != '\0') &&
+ strcmp(netdevice->name, "lo") == 0);
-int facemgr_cfg_rule_get_overlay_local_port(const facemgr_cfg_rule_t * rule, int family,
- uint16_t * port)
-{
- facemgr_cfg_overlay_t * overlay = NULL;
- switch(family) {
- case AF_INET:
- overlay = rule->override.overlays.v4;
- break;
- case AF_INET6:
- overlay = rule->override.overlays.v6;
- break;
- default:
- return -1;
- }
- if (!overlay->is_local_port)
- return -1;
- *port = overlay->local_port;
- return 0;
+ return 0;
}
-int facemgr_cfg_rule_get_overlay_remote_addr(const facemgr_cfg_rule_t * rule, int family,
- ip_address_t * addr)
-{
- facemgr_cfg_overlay_t * overlay = NULL;
- switch(family) {
- case AF_INET:
- overlay = rule->override.overlays.v4;
- break;
- case AF_INET6:
- overlay = rule->override.overlays.v6;
- break;
- default:
- return -1;
- }
- if (!overlay->is_remote_addr)
- return -1;
- *addr = overlay->remote_addr;
- return 0;
-}
+int facemgr_cfg_get_overlay_local_addr(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type,
+ int family, hicn_ip_address_t *addr) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
-int facemgr_cfg_rule_get_overlay_remote_port(const facemgr_cfg_rule_t * rule, int family,
- uint16_t * port)
-{
- facemgr_cfg_overlay_t * overlay = NULL;
- switch(family) {
- case AF_INET:
- overlay = rule->override.overlays.v4;
- break;
- case AF_INET6:
- overlay = rule->override.overlays.v6;
- break;
- default:
- return -1;
+ switch (family) {
+ case AF_INET:
+ if ((override) && (override->overlays.v4) &&
+ (override->overlays.v4->is_local_addr)) {
+ *addr = override->overlays.v4->local_addr;
+ return 0;
+ }
+ if ((cfg->global.overlays.v4) &&
+ (cfg->global.overlays.v4->is_local_addr)) {
+ *addr = cfg->global.overlays.v4->local_addr;
+ return 0;
+ }
+ break;
+ case AF_INET6:
+ if ((override) && (override->overlays.v6) &&
+ (override->overlays.v6->is_local_addr)) {
+ *addr = override->overlays.v6->local_addr;
+ return 0;
+ }
+ if ((cfg->global.overlays.v6) &&
+ (cfg->global.overlays.v6->is_local_addr)) {
+ *addr = cfg->global.overlays.v6->local_addr;
+ return 0;
+ }
+ break;
+ case AF_UNSPEC:
+ break;
+ default:
+ return -1;
+ }
+
+ *addr = IP_ADDRESS_EMPTY;
+ return 0;
+}
+
+int facemgr_cfg_get_overlay_local_port(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type,
+ int family, u16 *port) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
+
+ switch (family) {
+ case AF_INET:
+ if ((override) && (override->overlays.v4) &&
+ (override->overlays.v4->is_local_port)) {
+ *port = override->overlays.v4->local_port;
+ return 0;
+ }
+ if ((cfg->global.overlays.v4) &&
+ (cfg->global.overlays.v4->is_local_port)) {
+ *port = cfg->global.overlays.v4->local_port;
+ return 0;
+ }
+ break;
+ case AF_INET6:
+ if ((override) && (override->overlays.v6) &&
+ (override->overlays.v6->is_local_port)) {
+ *port = override->overlays.v6->local_port;
+ return 0;
+ }
+ if ((cfg->global.overlays.v6) &&
+ (cfg->global.overlays.v6->is_local_port)) {
+ *port = cfg->global.overlays.v6->local_port;
+ return 0;
+ }
+ break;
+ case AF_UNSPEC:
+ break;
+ default:
+ return -1;
+ }
+
+ *port = HICN_DEFAULT_PORT;
+ return 0;
+}
+
+int facemgr_cfg_get_overlay_remote_addr(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type,
+ int family, hicn_ip_address_t *addr) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
+
+ switch (family) {
+ case AF_INET:
+ if ((override) && (override->overlays.v4) &&
+ (override->overlays.v4->is_remote_addr)) {
+ DEBUG("remote addr v4 from override");
+ *addr = override->overlays.v4->remote_addr;
+ return 0;
+ }
+ if ((cfg->global.overlays.v4) &&
+ (cfg->global.overlays.v4->is_remote_addr)) {
+ DEBUG("remote addr v4 from global");
+ *addr = cfg->global.overlays.v4->remote_addr;
+ return 0;
+ }
+ break;
+ case AF_INET6:
+ if ((override) && (override->overlays.v6) &&
+ (override->overlays.v6->is_remote_addr)) {
+ DEBUG("remote addr v6 from override");
+ *addr = override->overlays.v6->remote_addr;
+ return 0;
+ }
+ if ((cfg->global.overlays.v6) &&
+ (cfg->global.overlays.v6->is_remote_addr)) {
+ DEBUG("remote addr v6 from global");
+ *addr = cfg->global.overlays.v6->remote_addr;
+ return 0;
+ }
+ break;
+ case AF_UNSPEC:
+ break;
+ default:
+ return -1;
+ }
+
+ DEBUG("remote addr empty");
+ *addr = IP_ADDRESS_EMPTY;
+ return 0;
+}
+
+int facemgr_cfg_get_overlay_remote_port(const facemgr_cfg_t *cfg,
+ const netdevice_t *netdevice,
+ netdevice_type_t netdevice_type,
+ int family, u16 *port) {
+ facemgr_cfg_override_t *override;
+ int rc = facemgr_cfg_get_override(cfg, netdevice, netdevice_type, &override);
+ if (rc < 0) return rc;
+
+ switch (family) {
+ case AF_INET:
+ if ((override) && (override->overlays.v4) &&
+ (override->overlays.v4->is_remote_port)) {
+ *port = override->overlays.v4->remote_port;
+ return 0;
+ }
+ if ((cfg->global.overlays.v4) &&
+ (cfg->global.overlays.v4->is_remote_port)) {
+ *port = cfg->global.overlays.v4->remote_port;
+ return 0;
+ }
+ break;
+ case AF_INET6:
+ if ((override) && (override->overlays.v6) &&
+ (override->overlays.v6->is_remote_port)) {
+ *port = override->overlays.v6->remote_port;
+ return 0;
+ }
+ if ((cfg->global.overlays.v6) &&
+ (cfg->global.overlays.v6->is_remote_port)) {
+ *port = cfg->global.overlays.v6->remote_port;
+ return 0;
+ }
+ break;
+ case AF_UNSPEC:
+ break;
+ default:
+ return -1;
+ }
+
+ *port = HICN_DEFAULT_PORT;
+ return 0;
+}
+
+int facemgr_cfg_rule_get(const facemgr_cfg_t *cfg, const netdevice_t netdevice,
+ netdevice_type_t netdevice_type,
+ facemgr_cfg_rule_t **rule_p) {
+ facemgr_cfg_rule_t **rule_array;
+ *rule_p = NULL;
+ int n = facemgr_cfg_rule_set_get_array(cfg->rule_set, &rule_array);
+ if (n < 0) {
+ ERROR("facemgr_cfg_rule_set_get_array failed");
+ return n;
+ }
+ for (unsigned i = 0; i < n; i++) {
+ facemgr_cfg_rule_t *rule = rule_array[i];
+ if (!rule) continue; /* Should not occur */
+ const char *interface_name = rule->match.interface_name;
+ /* Check match for interface name */
+ if (netdevice.name[0] != '\0') {
+ if (!interface_name) continue;
+ if (strcmp(netdevice.name, interface_name) != 0) continue;
+ } else {
+ if (interface_name && interface_name[0] != '\0') continue;
}
- if (!overlay->is_remote_port)
- return -1;
- *port = overlay->remote_port;
- return 0;
-}
-int facemgr_cfg_add_static_facelet(facemgr_cfg_t * cfg, facelet_t * facelet)
-{
- char buf[MAXSZ_FACELET];
- facelet_snprintf(buf, MAXSZ_FACELET, facelet);
- DEBUG("STATIC FACELET: %s", buf);
- return facelet_array_add(cfg->static_facelets, facelet);
-}
-
-int facemgr_cfg_remove_static_facelet(facemgr_cfg_t * cfg, facelet_t * facelet,
- facelet_t ** removed_facelet)
-{
- return facelet_array_remove(cfg->static_facelets, facelet, removed_facelet);
-}
-
-int facemgr_cfg_get_static_facelet_array(const facemgr_cfg_t * cfg, facelet_t *** array)
-{
- if (facelet_array_get_elements(cfg->static_facelets, array) < 0) {
- ERROR("[facemgr_cfg_get_static_facelet_array] Error getting array elements");
- return -1;
- }
- return (int)facelet_array_len(cfg->static_facelets);
+ /* Check match for netdevice_type */
+ if (netdevice_type != rule->match.interface_type) continue;
+
+ /* Found */
+ *rule_p = rule;
+ break;
+ }
+ return 0;
+}
+
+int facemgr_cfg_rule_get_face_type(const facemgr_cfg_rule_t *rule,
+ facemgr_face_type_t *face_type) {
+ if (!rule->override.is_face_type) return -1;
+ *face_type = rule->override.face_type;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_discovery(const facemgr_cfg_rule_t *rule,
+ bool *discovery) {
+ if (!rule->override.is_discovery) return -1;
+ *discovery = rule->override.discovery;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_ignore(const facemgr_cfg_rule_t *rule, bool *ignore) {
+ if (!rule->override.is_ignore) return -1;
+ *ignore = rule->override.ignore;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_ipv4(const facemgr_cfg_rule_t *rule, bool *ipv4) {
+ if (!rule->override.is_ipv4) return -1;
+ *ipv4 = rule->override.ipv4;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_ipv6(const facemgr_cfg_rule_t *rule, bool *ipv6) {
+ if (!rule->override.is_ipv6) return -1;
+ *ipv6 = rule->override.ipv6;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_overlay_local_addr(const facemgr_cfg_rule_t *rule,
+ int family,
+ hicn_ip_address_t *addr) {
+ facemgr_cfg_overlay_t *overlay = NULL;
+ switch (family) {
+ case AF_INET:
+ overlay = rule->override.overlays.v4;
+ break;
+ case AF_INET6:
+ overlay = rule->override.overlays.v6;
+ break;
+ default:
+ return -1;
+ }
+ if (!overlay->is_local_addr) return -1;
+ *addr = overlay->local_addr;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_overlay_local_port(const facemgr_cfg_rule_t *rule,
+ int family, uint16_t *port) {
+ facemgr_cfg_overlay_t *overlay = NULL;
+ switch (family) {
+ case AF_INET:
+ overlay = rule->override.overlays.v4;
+ break;
+ case AF_INET6:
+ overlay = rule->override.overlays.v6;
+ break;
+ default:
+ return -1;
+ }
+ if (!overlay->is_local_port) return -1;
+ *port = overlay->local_port;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_overlay_remote_addr(const facemgr_cfg_rule_t *rule,
+ int family,
+ hicn_ip_address_t *addr) {
+ facemgr_cfg_overlay_t *overlay = NULL;
+ switch (family) {
+ case AF_INET:
+ overlay = rule->override.overlays.v4;
+ break;
+ case AF_INET6:
+ overlay = rule->override.overlays.v6;
+ break;
+ default:
+ return -1;
+ }
+ if (!overlay->is_remote_addr) return -1;
+ *addr = overlay->remote_addr;
+ return 0;
+}
+
+int facemgr_cfg_rule_get_overlay_remote_port(const facemgr_cfg_rule_t *rule,
+ int family, uint16_t *port) {
+ facemgr_cfg_overlay_t *overlay = NULL;
+ switch (family) {
+ case AF_INET:
+ overlay = rule->override.overlays.v4;
+ break;
+ case AF_INET6:
+ overlay = rule->override.overlays.v6;
+ break;
+ default:
+ return -1;
+ }
+ if (!overlay->is_remote_port) return -1;
+ *port = overlay->remote_port;
+ return 0;
+}
+
+int facemgr_cfg_add_static_facelet(facemgr_cfg_t *cfg, facelet_t *facelet) {
+ char buf[MAXSZ_FACELET];
+ facelet_snprintf(buf, MAXSZ_FACELET, facelet);
+ DEBUG("STATIC FACELET: %s", buf);
+ return facelet_array_add(cfg->static_facelets, facelet);
+}
+
+int facemgr_cfg_get_static_facelet_array(const facemgr_cfg_t *cfg,
+ facelet_t ***array) {
+ if (facelet_array_get_elements(cfg->static_facelets, array) < 0) {
+ ERROR(
+ "[facemgr_cfg_get_static_facelet_array] Error getting array elements");
+ return -1;
+ }
+ return (int)facelet_array_len(cfg->static_facelets);
}
diff --git a/ctrl/facemgr/src/cfg_file.c b/ctrl/facemgr/src/cfg_file.c
index cb1ded1c9..9b5f592dd 100644
--- a/ctrl/facemgr/src/cfg_file.c
+++ b/ctrl/facemgr/src/cfg_file.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,338 +18,311 @@
* \brief Implementation of configuration file parsing
*/
-#include <unistd.h> // access
+#include <unistd.h> // access
#include <libconfig.h>
#include <hicn/ctrl/route.h>
#include "cfg_file.h"
-#define ARRAYSIZE(x) (sizeof(x)/sizeof(*x))
+#define ARRAYSIZE(x) (sizeof(x) / sizeof(*x))
-static const char * DEFAULT_CFGFILES[] = {
+static const char *DEFAULT_CFGFILES[] = {
"/etc/facemgr.conf",
"~/facemgr.conf",
};
-int
-probe_cfgfile(char * f)
-{
- for (unsigned i = 0; i < ARRAYSIZE(DEFAULT_CFGFILES); i++) {
- if (access(DEFAULT_CFGFILES[i], F_OK ) != -1) {
- if (!realpath(DEFAULT_CFGFILES[i], f))
- continue;
- return 0;
- }
+int probe_cfgfile(char *f) {
+ for (unsigned i = 0; i < ARRAYSIZE(DEFAULT_CFGFILES); i++) {
+ if (access(DEFAULT_CFGFILES[i], F_OK) != -1) {
+ if (!realpath(DEFAULT_CFGFILES[i], f)) continue;
+ return 0;
}
- return -1;
+ }
+ return -1;
}
-int
-parse_config_global(facemgr_cfg_t * cfg, config_setting_t * setting)
-{
- /* - face_type */
-
- const char *face_type_str;
- facemgr_face_type_t face_type;
- if (config_setting_lookup_string(setting, "face_type", &face_type_str)) {
- if (strcasecmp(face_type_str, "auto") == 0) {
- face_type = FACEMGR_FACE_TYPE_DEFAULT;
- } else
- if (strcasecmp(face_type_str, "native-udp") == 0) {
- face_type = FACEMGR_FACE_TYPE_NATIVE_UDP;
- } else
- if (strcasecmp(face_type_str, "native-tcp") == 0) {
- face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
- } else
- if (strcasecmp(face_type_str, "overlay-udp") == 0) {
- face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
- } else
- if (strcasecmp(face_type_str, "overlay-tcp") == 0) {
- face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
- } else {
- ERROR("Invalid face type in section 'global'");
- return -1;
- }
-
- int rc = facemgr_cfg_set_face_type(cfg, &face_type);
- if (rc < 0)
- goto ERR;
+int parse_config_global(facemgr_cfg_t *cfg, config_setting_t *setting) {
+ /* - face_type */
+
+ const char *face_type_str;
+ facemgr_face_type_t face_type;
+ if (config_setting_lookup_string(setting, "face_type", &face_type_str)) {
+ if (strcasecmp(face_type_str, "auto") == 0) {
+ face_type = FACEMGR_FACE_TYPE_DEFAULT;
+ } else if (strcasecmp(face_type_str, "native-udp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_NATIVE_UDP;
+ } else if (strcasecmp(face_type_str, "native-tcp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
+ } else if (strcasecmp(face_type_str, "overlay-udp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
+ } else if (strcasecmp(face_type_str, "overlay-tcp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
+ } else {
+ ERROR("Invalid face type in section 'global'");
+ return -1;
}
- /* - disable_discovery */
-
- int disable_discovery;
- if (config_setting_lookup_bool(setting, "disable_discovery",
- &disable_discovery)) {
- int rc = facemgr_cfg_set_discovery(cfg, !disable_discovery);
- if (rc < 0)
- goto ERR;
- }
-
- /* - disable_ipv4 */
-
- int disable_ipv4;
- if (config_setting_lookup_bool(setting, "disable_ipv4",
- &disable_ipv4)) {
- int rc = facemgr_cfg_set_ipv4(cfg, !disable_ipv4);
- if (rc < 0)
- goto ERR;
- }
-
- /* - disable ipv6 */
-
- int disable_ipv6;
- if (config_setting_lookup_bool(setting, "disable_ipv6",
- &disable_ipv6)) {
- int rc = facemgr_cfg_set_ipv6(cfg, !disable_ipv6);
- if (rc < 0)
- goto ERR;
+ int rc = facemgr_cfg_set_face_type(cfg, &face_type);
+ if (rc < 0) goto ERR;
+ }
+
+ /* - disable_discovery */
+
+ int disable_discovery;
+ if (config_setting_lookup_bool(setting, "disable_discovery",
+ &disable_discovery)) {
+ int rc = facemgr_cfg_set_discovery(cfg, !disable_discovery);
+ if (rc < 0) goto ERR;
+ }
+
+ /* - disable_ipv4 */
+
+ int disable_ipv4;
+ if (config_setting_lookup_bool(setting, "disable_ipv4", &disable_ipv4)) {
+ int rc = facemgr_cfg_set_ipv4(cfg, !disable_ipv4);
+ if (rc < 0) goto ERR;
+ }
+
+ /* - disable ipv6 */
+
+ int disable_ipv6;
+ if (config_setting_lookup_bool(setting, "disable_ipv6", &disable_ipv6)) {
+ int rc = facemgr_cfg_set_ipv6(cfg, !disable_ipv6);
+ if (rc < 0) goto ERR;
+ }
+
+ /* - overlay */
+ config_setting_t *overlay = config_setting_get_member(setting, "overlay");
+ if (overlay) {
+ /* ipv4 */
+ config_setting_t *overlay_v4 = config_setting_get_member(overlay, "ipv4");
+ if (overlay_v4) {
+ const char *local_addr_str, *remote_addr_str;
+ hicn_ip_address_t local_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t remote_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t *local_addr_p = NULL;
+ hicn_ip_address_t *remote_addr_p = NULL;
+ int local_port = 0;
+ int remote_port = 0;
+
+ if (config_setting_lookup_string(overlay_v4, "local_addr",
+ &local_addr_str)) {
+ if (hicn_ip_address_pton(local_addr_str, &local_addr) < 0) {
+ ERROR("Error parsing v4 local addr");
+ goto ERR;
+ }
+ local_addr_p = &local_addr;
+ }
+
+ if (config_setting_lookup_int(overlay_v4, "local_port", &local_port)) {
+ if (!IS_VALID_PORT(local_port)) goto ERR;
+ }
+
+ if (config_setting_lookup_string(overlay_v4, "remote_addr",
+ &remote_addr_str)) {
+ if (hicn_ip_address_pton(remote_addr_str, &remote_addr) < 0) {
+ ERROR("Error parsing v4 remote addr");
+ goto ERR;
+ }
+ remote_addr_p = &remote_addr;
+ }
+
+ if (config_setting_lookup_int(overlay_v4, "remote_port", &remote_port)) {
+ if (!IS_VALID_PORT(remote_port)) goto ERR;
+ }
+ int rc = facemgr_cfg_set_overlay(cfg, AF_INET, local_addr_p, local_port,
+ remote_addr_p, remote_port);
+ if (rc < 0) goto ERR;
}
- /* - overlay */
- config_setting_t *overlay = config_setting_get_member(setting, "overlay");
- if (overlay) {
-
- /* ipv4 */
- config_setting_t *overlay_v4 = config_setting_get_member(overlay, "ipv4");
- if (overlay_v4) {
- const char * local_addr_str, * remote_addr_str;
- ip_address_t local_addr = IP_ADDRESS_EMPTY;
- ip_address_t remote_addr = IP_ADDRESS_EMPTY;
- ip_address_t * local_addr_p = NULL;
- ip_address_t * remote_addr_p = NULL;
- int local_port = 0;
- int remote_port = 0;
-
- if (config_setting_lookup_string(overlay_v4, "local_addr", &local_addr_str)) {
- if (ip_address_pton(local_addr_str, &local_addr) < 0) {
- ERROR("Error parsing v4 local addr");
- goto ERR;
- }
- local_addr_p = &local_addr;
- }
-
- if (config_setting_lookup_int(overlay_v4, "local_port", &local_port)) {
- if (!IS_VALID_PORT(local_port))
- goto ERR;
- }
-
- if (config_setting_lookup_string(overlay_v4, "remote_addr", &remote_addr_str)) {
- if (ip_address_pton(remote_addr_str, &remote_addr) < 0) {
- ERROR("Error parsing v4 remote addr");
- goto ERR;
- }
- remote_addr_p = &remote_addr;
- }
-
- if (config_setting_lookup_int(overlay_v4, "remote_port", &remote_port)) {
- if (!IS_VALID_PORT(remote_port))
- goto ERR;
- }
- int rc = facemgr_cfg_set_overlay(cfg, AF_INET,
- local_addr_p, local_port,
- remote_addr_p, remote_port);
- if (rc < 0)
- goto ERR;
+ /* ipv6 */
+ config_setting_t *overlay_v6 = config_setting_get_member(overlay, "ipv6");
+ if (overlay_v6) {
+ const char *local_addr_str, *remote_addr_str;
+ hicn_ip_address_t local_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t remote_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t *local_addr_p = NULL;
+ hicn_ip_address_t *remote_addr_p = NULL;
+ int local_port = 0;
+ int remote_port = 0;
+
+ if (config_setting_lookup_string(overlay_v6, "local_addr",
+ &local_addr_str)) {
+ if (hicn_ip_address_pton(local_addr_str, &local_addr) < 0) {
+ ERROR("Error parsing v6 local addr");
+ goto ERR;
}
-
- /* ipv6 */
- config_setting_t *overlay_v6 = config_setting_get_member(overlay, "ipv6");
- if (overlay_v6) {
- const char * local_addr_str, * remote_addr_str;
- ip_address_t local_addr = IP_ADDRESS_EMPTY;
- ip_address_t remote_addr = IP_ADDRESS_EMPTY;
- ip_address_t * local_addr_p = NULL;
- ip_address_t * remote_addr_p = NULL;
- int local_port = 0;
- int remote_port = 0;
-
- if (config_setting_lookup_string(overlay_v6, "local_addr", &local_addr_str)) {
- if (ip_address_pton(local_addr_str, &local_addr) < 0) {
- ERROR("Error parsing v6 local addr");
- goto ERR;
- }
- local_addr_p = &local_addr;
- }
-
- if (config_setting_lookup_int(overlay_v6, "local_port", &local_port)) {
- if (!IS_VALID_PORT(local_port))
- goto ERR;
- }
-
- if (config_setting_lookup_string(overlay_v6, "remote_addr", &remote_addr_str)) {
- if (ip_address_pton(remote_addr_str, &remote_addr) < 0) {
- ERROR("Error parsing v6 remote addr");
- goto ERR;
- }
- remote_addr_p = &remote_addr;
- }
-
- if (config_setting_lookup_int(overlay_v6, "remote_port", &remote_port)) {
- if (!IS_VALID_PORT(remote_port))
- goto ERR;
- }
- int rc = facemgr_cfg_set_overlay(cfg, AF_INET6,
- local_addr_p, local_port,
- remote_addr_p, remote_port);
- if (rc < 0)
- goto ERR;
+ local_addr_p = &local_addr;
+ }
+
+ if (config_setting_lookup_int(overlay_v6, "local_port", &local_port)) {
+ if (!IS_VALID_PORT(local_port)) goto ERR;
+ }
+
+ if (config_setting_lookup_string(overlay_v6, "remote_addr",
+ &remote_addr_str)) {
+ if (hicn_ip_address_pton(remote_addr_str, &remote_addr) < 0) {
+ ERROR("Error parsing v6 remote addr");
+ goto ERR;
}
+ remote_addr_p = &remote_addr;
+ }
+
+ if (config_setting_lookup_int(overlay_v6, "remote_port", &remote_port)) {
+ if (!IS_VALID_PORT(remote_port)) goto ERR;
+ }
+ int rc = facemgr_cfg_set_overlay(cfg, AF_INET6, local_addr_p, local_port,
+ remote_addr_p, remote_port);
+ if (rc < 0) goto ERR;
+ }
- } /* overlay */
+ } /* overlay */
- return 0;
+ return 0;
ERR:
- return -1;
+ return -1;
}
-int
-parse_config_rules(facemgr_cfg_t * cfg, config_setting_t * setting)
-{
- /* List of match-override tuples */
- facemgr_cfg_rule_t * rule;
+int parse_config_rules(facemgr_cfg_t *cfg, config_setting_t *setting) {
+ /* List of match-override tuples */
+ facemgr_cfg_rule_t *rule;
- int count = config_setting_length(setting);
- for (unsigned i = 0; i < count; ++i) {
- config_setting_t * rule_setting = config_setting_get_elem(setting, i);
+ int count = config_setting_length(setting);
+ for (unsigned i = 0; i < count; ++i) {
+ config_setting_t *rule_setting = config_setting_get_elem(setting, i);
- /* Sanity check */
+ /* Sanity check */
- config_setting_t * match_setting = config_setting_get_member(rule_setting, "match");
- if (!match_setting) {
- ERROR("Missing match section in rule #%d", i);
- goto ERR_CHECK;
- }
+ config_setting_t *match_setting =
+ config_setting_get_member(rule_setting, "match");
+ if (!match_setting) {
+ ERROR("Missing match section in rule #%d", i);
+ goto ERR_CHECK;
+ }
- config_setting_t * override_setting = config_setting_get_member(rule_setting, "override");
- if (!override_setting) {
- ERROR("Missing override section in rule #%d", i);
- goto ERR_CHECK;
- }
+ config_setting_t *override_setting =
+ config_setting_get_member(rule_setting, "override");
+ if (!override_setting) {
+ ERROR("Missing override section in rule #%d", i);
+ goto ERR_CHECK;
+ }
- rule = facemgr_cfg_rule_create();
- if (!rule)
- goto ERR_RULE;
-
- /* Parse match */
-
- const char * interface_name = NULL;
- config_setting_lookup_string(match_setting, "interface_name", &interface_name);
-
- const char * interface_type_str;
- netdevice_type_t interface_type = NETDEVICE_TYPE_UNDEFINED;
- if (config_setting_lookup_string(match_setting, "interface_type", &interface_type_str)) {
- if (strcasecmp(interface_type_str, "wired") == 0) {
- interface_type = NETDEVICE_TYPE_WIRED;
- } else
- if (strcasecmp(interface_type_str, "wifi") == 0) {
- interface_type = NETDEVICE_TYPE_WIFI;
- } else
- if (strcasecmp(interface_type_str, "cellular") == 0) {
- interface_type = NETDEVICE_TYPE_CELLULAR;
- } else {
- ERROR("Unknown interface type in rule #%d", i);
- goto ERR;
- }
- }
+ rule = facemgr_cfg_rule_create();
+ if (!rule) goto ERR_RULE;
+
+ /* Parse match */
+
+ const char *interface_name = NULL;
+ config_setting_lookup_string(match_setting, "interface_name",
+ &interface_name);
+
+ const char *interface_type_str;
+ netdevice_type_t interface_type = NETDEVICE_TYPE_UNDEFINED;
+ if (config_setting_lookup_string(match_setting, "interface_type",
+ &interface_type_str)) {
+ if (strcasecmp(interface_type_str, "wired") == 0) {
+ interface_type = NETDEVICE_TYPE_WIRED;
+ } else if (strcasecmp(interface_type_str, "wifi") == 0) {
+ interface_type = NETDEVICE_TYPE_WIFI;
+ } else if (strcasecmp(interface_type_str, "cellular") == 0) {
+ interface_type = NETDEVICE_TYPE_CELLULAR;
+ } else {
+ ERROR("Unknown interface type in rule #%d", i);
+ goto ERR;
+ }
+ }
- if ((!interface_name) && (interface_type == NETDEVICE_TYPE_UNDEFINED)) {
- ERROR("Empty match section in rule #%d", i);
- goto ERR;
- }
+ if ((!interface_name) && (interface_type == NETDEVICE_TYPE_UNDEFINED)) {
+ ERROR("Empty match section in rule #%d", i);
+ goto ERR;
+ }
- /* Associate match to rule */
+ /* Associate match to rule */
- int rc = facemgr_cfg_rule_set_match(rule, interface_name, interface_type);
- if (rc < 0)
- goto ERR;
+ int rc = facemgr_cfg_rule_set_match(rule, interface_name, interface_type);
+ if (rc < 0) goto ERR;
- /* Parse override */
+ /* Parse override */
- /* - face_type */
+ /* - face_type */
- const char *face_type_str;
- facemgr_face_type_t face_type;
- if (config_setting_lookup_string(override_setting, "face_type", &face_type_str)) {
- if (strcasecmp(face_type_str, "auto")) {
- /* We currently hardcode different behaviours based on the OS */
+ const char *face_type_str;
+ facemgr_face_type_t face_type;
+ if (config_setting_lookup_string(override_setting, "face_type",
+ &face_type_str)) {
+ if (strcasecmp(face_type_str, "auto")) {
+ /* We currently hardcode different behaviours based on the OS */
#ifdef __ANDROID__
- face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
+ face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
#else
- face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
+ face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
#endif
- } else
- if (strcasecmp(face_type_str, "native-udp") == 0) {
- face_type = FACEMGR_FACE_TYPE_NATIVE_UDP;
- } else
- if (strcasecmp(face_type_str, "native-tcp") == 0) {
- face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
- } else
- if (strcasecmp(face_type_str, "overlay-udp") == 0) {
- face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
- } else
- if (strcasecmp(face_type_str, "overlay-tcp") == 0) {
- face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
- } else {
- ERROR("Invalid face type in section 'global'");
- return -1;
- }
+ } else if (strcasecmp(face_type_str, "native-udp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_NATIVE_UDP;
+ } else if (strcasecmp(face_type_str, "native-tcp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
+ } else if (strcasecmp(face_type_str, "overlay-udp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
+ } else if (strcasecmp(face_type_str, "overlay-tcp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
+ } else {
+ ERROR("Invalid face type in section 'global'");
+ return -1;
+ }
- int rc = facemgr_cfg_rule_set_face_type(rule, &face_type);
- if (rc < 0)
- goto ERR;
- }
+ int rc = facemgr_cfg_rule_set_face_type(rule, &face_type);
+ if (rc < 0) goto ERR;
+ }
- /* - disable_discovery */
+ /* - disable_discovery */
- int disable_discovery;
- if (config_setting_lookup_bool(override_setting, "disable_discovery",
- &disable_discovery)) {
- int rc = facemgr_cfg_rule_set_discovery(rule, !disable_discovery);
- if (rc < 0)
- goto ERR;
- }
+ int disable_discovery;
+ if (config_setting_lookup_bool(override_setting, "disable_discovery",
+ &disable_discovery)) {
+ int rc = facemgr_cfg_rule_set_discovery(rule, !disable_discovery);
+ if (rc < 0) goto ERR;
+ }
- /* - disable_ipv4 */
+ /* - disable_ipv4 */
- int disable_ipv4;
- if (config_setting_lookup_bool(override_setting, "disable_ipv4",
- &disable_ipv4)) {
- INFO("Ignored setting 'disable_ipv4' in rule #%d (not implemented).", i);
+ int disable_ipv4;
+ if (config_setting_lookup_bool(override_setting, "disable_ipv4",
+ &disable_ipv4)) {
+ INFO("Ignored setting 'disable_ipv4' in rule #%d (not implemented).", i);
#if 0
int rc = facemgr_cfg_rule_set_ipv4(rule, !disable_ipv4);
if (rc < 0)
goto ERR;
#endif
- }
+ }
- /* - disable ipv6 */
+ /* - disable ipv6 */
- int disable_ipv6;
- if (config_setting_lookup_bool(override_setting, "disable_ipv6",
- &disable_ipv6)) {
- INFO("Ignored setting 'disable_ipv6' in rule #%d (not implemented).", i);
+ int disable_ipv6;
+ if (config_setting_lookup_bool(override_setting, "disable_ipv6",
+ &disable_ipv6)) {
+ INFO("Ignored setting 'disable_ipv6' in rule #%d (not implemented).", i);
#if 0
int rc = facemgr_cfg_rule_set_ipv6(rule, !disable_ipv6);
if (rc < 0)
goto ERR;
#endif
- }
+ }
- /* - ignore */
- int ignore;
- if (config_setting_lookup_bool(override_setting, "ignore", &ignore)) {
- int rc = facemgr_cfg_rule_set_ignore(rule, !!ignore);
- if (rc < 0)
- goto ERR;
- }
+ /* - ignore */
+ int ignore;
+ if (config_setting_lookup_bool(override_setting, "ignore", &ignore)) {
+ int rc = facemgr_cfg_rule_set_ignore(rule, !!ignore);
+ if (rc < 0) goto ERR;
+ }
- /* - tags */
- config_setting_t *tag_settings = config_setting_get_member(override_setting, "tags");
- if (tag_settings) {
- INFO("Ignored setting 'tags' in rule #%d (not implemented).", i);
+ /* - tags */
+ config_setting_t *tag_settings =
+ config_setting_get_member(override_setting, "tags");
+ if (tag_settings) {
+ INFO("Ignored setting 'tags' in rule #%d (not implemented).", i);
#if 0
policy_tags_t tags = POLICY_TAGS_EMPTY;
for (unsigned j = 0; j < config_setting_length(tag_settings); j++) {
@@ -370,361 +343,337 @@ parse_config_rules(facemgr_cfg_t * cfg, config_setting_t * setting)
DEBUG("Added tags tags=%s", tags_str);
#endif
#endif
+ }
+
+ /* - overlay */
+ config_setting_t *overlay =
+ config_setting_get_member(override_setting, "overlay");
+ if (overlay) {
+ /* ipv4 */
+ config_setting_t *overlay_v4 = config_setting_get_member(overlay, "ipv4");
+ if (overlay_v4) {
+ const char *local_addr_str, *remote_addr_str;
+ hicn_ip_address_t local_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t remote_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t *local_addr_p = NULL;
+ hicn_ip_address_t *remote_addr_p = NULL;
+ int local_port = 0;
+ int remote_port = 0;
+
+ if (config_setting_lookup_string(overlay_v4, "local_addr",
+ &local_addr_str)) {
+ hicn_ip_address_pton(local_addr_str, &local_addr);
+ local_addr_p = &local_addr;
}
- /* - overlay */
- config_setting_t *overlay = config_setting_get_member(override_setting, "overlay");
- if (overlay) {
-
- /* ipv4 */
- config_setting_t *overlay_v4 = config_setting_get_member(overlay, "ipv4");
- if (overlay_v4) {
- const char * local_addr_str, * remote_addr_str;
- ip_address_t local_addr = IP_ADDRESS_EMPTY;
- ip_address_t remote_addr = IP_ADDRESS_EMPTY;
- ip_address_t * local_addr_p = NULL;
- ip_address_t * remote_addr_p = NULL;
- int local_port = 0;
- int remote_port = 0;
-
- if (config_setting_lookup_string(overlay_v4, "local_addr", &local_addr_str)) {
- ip_address_pton(local_addr_str, &local_addr);
- local_addr_p = &local_addr;
- }
-
- if (config_setting_lookup_int(overlay_v4, "local_port", &local_port)) {
- if (!IS_VALID_PORT(local_port))
- goto ERR;
- }
-
- if (config_setting_lookup_string(overlay_v4, "remote_addr", &remote_addr_str)) {
- ip_address_pton(remote_addr_str, &remote_addr);
- remote_addr_p = &remote_addr;
- }
-
- if (config_setting_lookup_int(overlay_v4, "remote_port", &remote_port)) {
- if (!IS_VALID_PORT(remote_port))
- goto ERR;
- }
- int rc = facemgr_cfg_rule_set_overlay(rule, AF_INET,
- local_addr_p, local_port,
- remote_addr_p, remote_port);
- if (rc < 0)
- goto ERR;
- }
+ if (config_setting_lookup_int(overlay_v4, "local_port", &local_port)) {
+ if (!IS_VALID_PORT(local_port)) goto ERR;
+ }
- /* ipv6 */
- config_setting_t *overlay_v6 = config_setting_get_member(overlay, "ipv6");
- if (overlay_v6) {
- const char * local_addr_str, * remote_addr_str;
- ip_address_t local_addr = IP_ADDRESS_EMPTY;
- ip_address_t remote_addr = IP_ADDRESS_EMPTY;
- ip_address_t * local_addr_p = NULL;
- ip_address_t * remote_addr_p = NULL;
- int local_port = 0;
- int remote_port = 0;
-
- if (config_setting_lookup_string(overlay_v6, "local_addr", &local_addr_str)) {
- ip_address_pton(local_addr_str, &local_addr);
- local_addr_p = &local_addr;
- }
-
- if (config_setting_lookup_int(overlay_v6, "local_port", &local_port)) {
- if (!IS_VALID_PORT(local_port))
- goto ERR;
- }
-
- if (config_setting_lookup_string(overlay_v6, "remote_addr", &remote_addr_str)) {
- ip_address_pton(remote_addr_str, &remote_addr);
- remote_addr_p = &remote_addr;
- }
-
- if (config_setting_lookup_int(overlay_v6, "remote_port", &remote_port)) {
- if (!IS_VALID_PORT(remote_port))
- goto ERR;
- }
- int rc = facemgr_cfg_rule_set_overlay(rule, AF_INET6,
- local_addr_p, local_port,
- remote_addr_p, remote_port);
- if (rc < 0)
- goto ERR;
- }
+ if (config_setting_lookup_string(overlay_v4, "remote_addr",
+ &remote_addr_str)) {
+ hicn_ip_address_pton(remote_addr_str, &remote_addr);
+ remote_addr_p = &remote_addr;
+ }
+
+ if (config_setting_lookup_int(overlay_v4, "remote_port",
+ &remote_port)) {
+ if (!IS_VALID_PORT(remote_port)) goto ERR;
+ }
+ int rc = facemgr_cfg_rule_set_overlay(rule, AF_INET, local_addr_p,
+ local_port, remote_addr_p,
+ remote_port);
+ if (rc < 0) goto ERR;
+ }
+
+ /* ipv6 */
+ config_setting_t *overlay_v6 = config_setting_get_member(overlay, "ipv6");
+ if (overlay_v6) {
+ const char *local_addr_str, *remote_addr_str;
+ hicn_ip_address_t local_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t remote_addr = IP_ADDRESS_EMPTY;
+ hicn_ip_address_t *local_addr_p = NULL;
+ hicn_ip_address_t *remote_addr_p = NULL;
+ int local_port = 0;
+ int remote_port = 0;
- } /* overlay */
+ if (config_setting_lookup_string(overlay_v6, "local_addr",
+ &local_addr_str)) {
+ hicn_ip_address_pton(local_addr_str, &local_addr);
+ local_addr_p = &local_addr;
+ }
- /* Add newly created rule */
+ if (config_setting_lookup_int(overlay_v6, "local_port", &local_port)) {
+ if (!IS_VALID_PORT(local_port)) goto ERR;
+ }
- rc = facemgr_cfg_add_rule(cfg, rule);
- if (rc < 0)
- goto ERR;
- }
- return 0;
+ if (config_setting_lookup_string(overlay_v6, "remote_addr",
+ &remote_addr_str)) {
+ hicn_ip_address_pton(remote_addr_str, &remote_addr);
+ remote_addr_p = &remote_addr;
+ }
+
+ if (config_setting_lookup_int(overlay_v6, "remote_port",
+ &remote_port)) {
+ if (!IS_VALID_PORT(remote_port)) goto ERR;
+ }
+ int rc = facemgr_cfg_rule_set_overlay(rule, AF_INET6, local_addr_p,
+ local_port, remote_addr_p,
+ remote_port);
+ if (rc < 0) goto ERR;
+ }
+
+ } /* overlay */
+
+ /* Add newly created rule */
+
+ rc = facemgr_cfg_add_rule(cfg, rule);
+ if (rc < 0) goto ERR;
+ }
+ return 0;
ERR:
- facemgr_cfg_rule_free(rule);
+ facemgr_cfg_rule_free(rule);
ERR_RULE:
ERR_CHECK:
- return -1;
+ return -1;
}
-int parse_config_static_facelets(facemgr_cfg_t * cfg, config_setting_t * setting)
-{
- int count = config_setting_length(setting);
- for (unsigned i = 0; i < count; ++i) {
- config_setting_t * static_setting = config_setting_get_elem(setting, i);
-
- const char *face_type_str;
- facemgr_face_type_t face_type;
- const char * family_str;
- int family;
- const char * remote_addr_str;
- ip_address_t remote_addr = IP_ADDRESS_EMPTY;
- int remote_port = 0;
- const char * interface_name;
- const char * interface_type_str;
-
- facelet_t * facelet = facelet_create();
-
- /* Face type */
- if (config_setting_lookup_string(static_setting, "face_type", &face_type_str)) {
- if (strcasecmp(face_type_str, "auto") == 0) {
- face_type = FACEMGR_FACE_TYPE_DEFAULT;
- } else
- if (strcasecmp(face_type_str, "native-udp") == 0) {
- face_type = FACEMGR_FACE_TYPE_NATIVE_UDP;
- } else
- if (strcasecmp(face_type_str, "native-tcp") == 0) {
- face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
- } else
- if (strcasecmp(face_type_str, "overlay-udp") == 0) {
- face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
- } else
- if (strcasecmp(face_type_str, "overlay-tcp") == 0) {
- face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
- } else {
- ERROR("Invalid face type in section 'global'");
- goto ERR_FACELET;
- }
+int parse_config_static_facelets(facemgr_cfg_t *cfg,
+ config_setting_t *setting) {
+ int count = config_setting_length(setting);
+ for (unsigned i = 0; i < count; ++i) {
+ config_setting_t *static_setting = config_setting_get_elem(setting, i);
- int rc = facelet_set_face_type(facelet, face_type);
- if (rc < 0)
- goto ERR_FACELET;
- }
+ const char *face_type_str;
+ facemgr_face_type_t face_type;
+ const char *family_str;
+ int family;
+ const char *remote_addr_str;
+ hicn_ip_address_t remote_addr = IP_ADDRESS_EMPTY;
+ int remote_port = 0;
+ const char *interface_name;
+ const char *interface_type_str;
+
+ facelet_t *facelet = facelet_create();
+
+ /* Face type */
+ if (config_setting_lookup_string(static_setting, "face_type",
+ &face_type_str)) {
+ if (strcasecmp(face_type_str, "auto") == 0) {
+ face_type = FACEMGR_FACE_TYPE_DEFAULT;
+ } else if (strcasecmp(face_type_str, "native-udp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_NATIVE_UDP;
+ } else if (strcasecmp(face_type_str, "native-tcp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
+ } else if (strcasecmp(face_type_str, "overlay-udp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
+ } else if (strcasecmp(face_type_str, "overlay-tcp") == 0) {
+ face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
+ } else {
+ ERROR("Invalid face type in section 'global'");
+ goto ERR_FACELET;
+ }
+
+ int rc = facelet_set_face_type(facelet, face_type);
+ if (rc < 0) goto ERR_FACELET;
+ }
- /* Family */
- if (config_setting_lookup_string(static_setting, "family", &family_str)) {
- if (strcasecmp(family_str, "AF_INET") == 0) {
- family = AF_INET;
- } else
- if (strcasecmp(family_str, "AF_INET6") == 0) {
- family = AF_INET6;
- } else {
- ERROR("Invalid family in section 'static', items #%d", i+1);
- goto ERR_FACELET;
- }
- int rc = facelet_set_family(facelet, family);
- if (rc < 0)
- goto ERR_FACELET;
- }
+ /* Family */
+ if (config_setting_lookup_string(static_setting, "family", &family_str)) {
+ if (strcasecmp(family_str, "AF_INET") == 0) {
+ family = AF_INET;
+ } else if (strcasecmp(family_str, "AF_INET6") == 0) {
+ family = AF_INET6;
+ } else {
+ ERROR("Invalid family in section 'static', items #%d", i + 1);
+ goto ERR_FACELET;
+ }
+ int rc = facelet_set_family(facelet, family);
+ if (rc < 0) goto ERR_FACELET;
+ }
- /* Remote address */
- if (config_setting_lookup_string(static_setting, "remote_addr", &remote_addr_str)) {
- if (ip_address_pton(remote_addr_str, &remote_addr) < 0) {
- ERROR("Error parsing v4 remote addr");
- goto ERR_FACELET;
- }
+ /* Remote address */
+ if (config_setting_lookup_string(static_setting, "remote_addr",
+ &remote_addr_str)) {
+ if (hicn_ip_address_pton(remote_addr_str, &remote_addr) < 0) {
+ ERROR("Error parsing v4 remote addr");
+ goto ERR_FACELET;
+ }
- int rc = facelet_set_remote_addr(facelet, remote_addr);
- if (rc < 0)
- goto ERR_FACELET;
- }
+ int rc = facelet_set_remote_addr(facelet, remote_addr);
+ if (rc < 0) goto ERR_FACELET;
+ }
- /* Remote port */
- if (config_setting_lookup_int(static_setting, "remote_port", &remote_port)) {
- if (!IS_VALID_PORT(remote_port))
- goto ERR_FACELET;
- int rc = facelet_set_remote_port(facelet, remote_port);
- if (rc < 0)
- goto ERR_FACELET;
- }
+ /* Remote port */
+ if (config_setting_lookup_int(static_setting, "remote_port",
+ &remote_port)) {
+ if (!IS_VALID_PORT(remote_port)) goto ERR_FACELET;
+ int rc = facelet_set_remote_port(facelet, remote_port);
+ if (rc < 0) goto ERR_FACELET;
+ }
- /* Interface name */
- if (config_setting_lookup_string(static_setting, "interface_name", &interface_name)) {
- netdevice_t netdevice;
- /* Warning: interface might not exist when we create the facelet */
- snprintf(netdevice.name, IFNAMSIZ, "%s", interface_name);
- netdevice.index = 0;
- int rc = facelet_set_netdevice(facelet, netdevice);
- if (rc < 0)
- goto ERR_FACELET;
- }
+ /* Interface name */
+ if (config_setting_lookup_string(static_setting, "interface_name",
+ &interface_name)) {
+ netdevice_t netdevice;
+ /* Warning: interface might not exist when we create the facelet */
+ snprintf(netdevice.name, IFNAMSIZ, "%s", interface_name);
+ netdevice.index = 0;
+ int rc = facelet_set_netdevice(facelet, netdevice);
+ if (rc < 0) goto ERR_FACELET;
+ }
- /* Interface type */
- netdevice_type_t interface_type = NETDEVICE_TYPE_UNDEFINED;
- if (config_setting_lookup_string(static_setting, "interface_type", &interface_type_str)) {
- if (strcasecmp(interface_type_str, "wired") == 0) {
- interface_type = NETDEVICE_TYPE_WIRED;
- } else
- if (strcasecmp(interface_type_str, "wifi") == 0) {
- interface_type = NETDEVICE_TYPE_WIFI;
- } else
- if (strcasecmp(interface_type_str, "cellular") == 0) {
- interface_type = NETDEVICE_TYPE_CELLULAR;
- } else {
- ERROR("Unknown interface type in rule #%d", i);
- goto ERR_FACELET;
- }
+ /* Interface type */
+ netdevice_type_t interface_type = NETDEVICE_TYPE_UNDEFINED;
+ if (config_setting_lookup_string(static_setting, "interface_type",
+ &interface_type_str)) {
+ if (strcasecmp(interface_type_str, "wired") == 0) {
+ interface_type = NETDEVICE_TYPE_WIRED;
+ } else if (strcasecmp(interface_type_str, "wifi") == 0) {
+ interface_type = NETDEVICE_TYPE_WIFI;
+ } else if (strcasecmp(interface_type_str, "cellular") == 0) {
+ interface_type = NETDEVICE_TYPE_CELLULAR;
+ } else {
+ ERROR("Unknown interface type in rule #%d", i);
+ goto ERR_FACELET;
+ }
+
+ int rc = facelet_set_netdevice_type(facelet, interface_type);
+ if (rc < 0) goto ERR_FACELET;
+ }
- int rc = facelet_set_netdevice_type(facelet, interface_type);
- if (rc < 0)
- goto ERR_FACELET;
+ /* Routes */
+ config_setting_t *routes_static_setting =
+ config_setting_get_member(static_setting, "routes");
+ if (routes_static_setting) {
+ /* ... */
+ int count_routes = config_setting_length(routes_static_setting);
+ for (unsigned j = 0; j < count_routes; ++j) {
+ config_setting_t *route_static_setting =
+ config_setting_get_elem(routes_static_setting, j);
+
+ const char *prefix_str;
+ hicn_ip_prefix_t prefix;
+ int cost = 0; /* default */
+
+ if (config_setting_lookup_string(route_static_setting, "prefix",
+ &prefix_str)) {
+ if (hicn_ip_prefix_pton(prefix_str, &prefix) < 0) {
+ ERROR("Error parsing prefix in route #%d, rule #%d", j, i);
+ goto ERR_FACELET;
+ }
+ } else {
+ ERROR("Cannot add route without prefix");
+ goto ERR_FACELET;
}
- /* Routes */
- config_setting_t * routes_static_setting = config_setting_get_member(static_setting, "routes");
- if (routes_static_setting) {
- /* ... */
- int count_routes = config_setting_length(routes_static_setting);
- for (unsigned j = 0; j < count_routes; ++j) {
- config_setting_t * route_static_setting = config_setting_get_elem(routes_static_setting, j);
-
- const char * prefix_str;
- ip_prefix_t prefix;
- int cost = 0; /* default */
-
- if (config_setting_lookup_string(route_static_setting, "prefix", &prefix_str)) {
- if (ip_prefix_pton(prefix_str, &prefix) < 0) {
- ERROR("Error parsing prefix in route #%d, rule #%d", j, i);
- goto ERR_FACELET;
- }
- } else {
- ERROR("Cannot add route without prefix");
- goto ERR_FACELET;
- }
-
- config_setting_lookup_int(static_setting, "cost", &cost);
-
- hicn_route_t * route = hicn_route_create(&prefix, 0, cost);
- if (!route) {
- ERROR("Could not create hICN route");
- goto ERR_FACELET;
- }
-
- int rc = facelet_add_route(facelet, route);
- if (rc < 0) {
- ERROR("Could not add route to facelet");
- goto ERR_ROUTE;
- }
-
- continue;
-
-ERR_ROUTE:
- hicn_route_free(route);
- goto ERR_FACELET;
- }
+ config_setting_lookup_int(static_setting, "cost", &cost);
+
+ hicn_route_t *route = hicn_route_create(&prefix, 0, cost);
+ if (!route) {
+ ERROR("Could not create hICN route");
+ goto ERR_FACELET;
}
- if (facemgr_cfg_add_static_facelet(cfg, facelet) < 0) {
- ERROR("Could not add static facelet to configuration");
- goto ERR_FACELET;
+ int rc = facelet_add_route(facelet, route);
+ if (rc < 0) {
+ ERROR("Could not add route to facelet");
+ goto ERR_ROUTE;
}
continue;
-ERR_FACELET:
- facelet_free(facelet);
- return -1;
+ ERR_ROUTE:
+ hicn_route_free(route);
+ goto ERR_FACELET;
+ }
+ }
- }
- return 0;
+ if (facemgr_cfg_add_static_facelet(cfg, facelet) < 0) {
+ ERROR("Could not add static facelet to configuration");
+ goto ERR_FACELET;
+ }
+
+ continue;
+
+ ERR_FACELET:
+ facelet_free(facelet);
+ return -1;
+ }
+ return 0;
}
/* Currently not using facemgr_cfg_t */
-int
-parse_config_log(facemgr_cfg_t * cfg, config_setting_t * setting)
-{
- const char *log_level_str;
- if (config_setting_lookup_string(setting, "log_level", &log_level_str)) {
- if (strcasecmp(log_level_str, "FATAL") == 0) {
- log_conf.log_level = LOG_FATAL;
- } else
- if (strcasecmp(log_level_str, "ERROR") == 0) {
- log_conf.log_level = LOG_ERROR;
- } else
- if (strcasecmp(log_level_str, "WARN") == 0) {
- log_conf.log_level = LOG_WARN;
- } else
- if (strcasecmp(log_level_str, "INFO") == 0) {
- log_conf.log_level = LOG_INFO;
- } else
- if (strcasecmp(log_level_str, "DEBUG") == 0) {
- log_conf.log_level = LOG_DEBUG;
- } else
- if (strcasecmp(log_level_str, "TRACE") == 0) {
- log_conf.log_level = LOG_TRACE;
- } else {
- ERROR("Invalid log level in section 'log'");
- return -1;
- }
+int parse_config_log(facemgr_cfg_t *cfg, config_setting_t *setting) {
+ const char *log_level_str;
+ if (config_setting_lookup_string(setting, "log_level", &log_level_str)) {
+ if (strcasecmp(log_level_str, "FATAL") == 0) {
+ log_conf.log_level = LOG_FATAL;
+ } else if (strcasecmp(log_level_str, "ERROR") == 0) {
+ log_conf.log_level = LOG_ERROR;
+ } else if (strcasecmp(log_level_str, "WARN") == 0) {
+ log_conf.log_level = LOG_WARN;
+ } else if (strcasecmp(log_level_str, "INFO") == 0) {
+ log_conf.log_level = LOG_INFO;
+ } else if (strcasecmp(log_level_str, "DEBUG") == 0) {
+ log_conf.log_level = LOG_DEBUG;
+ } else if (strcasecmp(log_level_str, "TRACE") == 0) {
+ log_conf.log_level = LOG_TRACE;
+ } else {
+ ERROR("Invalid log level in section 'log'");
+ return -1;
}
- return 0;
+ }
+ return 0;
}
-int
-parse_config_file(const char * cfgpath, facemgr_cfg_t * cfg)
-{
- /* Reading configuration file */
- config_t cfgfile;
- config_setting_t *setting;
+int parse_config_file(const char *cfgpath, facemgr_cfg_t *cfg) {
+ /* Reading configuration file */
+ config_t cfgfile;
+ config_setting_t *setting;
- config_init(&cfgfile);
+ config_init(&cfgfile);
- /* Read the file. If there is an error, report it and exit. */
- if(!config_read_file(&cfgfile, cfgpath))
- goto ERR_FILE;
+ /* Read the file. If there is an error, report it and exit. */
+ if (!config_read_file(&cfgfile, cfgpath)) goto ERR_FILE;
- setting = config_lookup(&cfgfile, "global");
- if (setting) {
- int rc = parse_config_global(cfg, setting);
- if (rc < 0)
- goto ERR_PARSE;
- }
+ setting = config_lookup(&cfgfile, "global");
+ if (setting) {
+ int rc = parse_config_global(cfg, setting);
+ if (rc < 0) goto ERR_PARSE;
+ }
- setting = config_lookup(&cfgfile, "rules");
- if (setting) {
- int rc = parse_config_rules(cfg, setting);
- if (rc < 0)
- goto ERR_PARSE;
- }
+ setting = config_lookup(&cfgfile, "rules");
+ if (setting) {
+ int rc = parse_config_rules(cfg, setting);
+ if (rc < 0) goto ERR_PARSE;
+ }
- setting = config_lookup(&cfgfile, "static");
- if (setting) {
- int rc = parse_config_static_facelets(cfg, setting);
- if (rc < 0)
- goto ERR_PARSE;
- }
+ setting = config_lookup(&cfgfile, "static");
+ if (setting) {
+ int rc = parse_config_static_facelets(cfg, setting);
+ if (rc < 0) goto ERR_PARSE;
+ }
- setting = config_lookup(&cfgfile, "log");
- if (setting) {
- int rc = parse_config_log(cfg, setting);
- if (rc < 0)
- goto ERR_PARSE;
- }
+ setting = config_lookup(&cfgfile, "log");
+ if (setting) {
+ int rc = parse_config_log(cfg, setting);
+ if (rc < 0) goto ERR_PARSE;
+ }
- config_destroy(&cfgfile);
- return 0;
+ config_destroy(&cfgfile);
+ return 0;
ERR_FILE:
- ERROR("Could not read configuration file %s", cfgpath);
- fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfgfile),
- config_error_line(&cfgfile), config_error_text(&cfgfile));
- config_destroy(&cfgfile);
- exit(EXIT_FAILURE);
- return -1;
+ ERROR("Could not read configuration file %s", cfgpath);
+ fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfgfile),
+ config_error_line(&cfgfile), config_error_text(&cfgfile));
+ config_destroy(&cfgfile);
+ return -1;
ERR_PARSE:
- fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfgfile),
- config_error_line(&cfgfile), config_error_text(&cfgfile));
- config_destroy(&cfgfile);
- return -1;
+ fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfgfile),
+ config_error_line(&cfgfile), config_error_text(&cfgfile));
+ config_destroy(&cfgfile);
+ return -1;
}
-
diff --git a/ctrl/facemgr/src/cfg_file.h b/ctrl/facemgr/src/cfg_file.h
index dfce041d8..fea6a84a6 100644
--- a/ctrl/facemgr/src/cfg_file.h
+++ b/ctrl/facemgr/src/cfg_file.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,7 +28,7 @@
* \param [in] f - File name
* \return 0 in case of success, -1 otherwise.
*/
-int probe_cfgfile(char * f);
+int probe_cfgfile(char* f);
/**
* \brief Parses the provided configuration file into the facemgr configuration
@@ -37,6 +37,6 @@ int probe_cfgfile(char * f);
* \param [out] cfg - Pre-allocated configuration data structure
* \return 0 in case of success, -1 otherwise.
*/
-int parse_config_file(const char * cfgpath, facemgr_cfg_t * cfg);
+int parse_config_file(const char* cfgpath, facemgr_cfg_t* cfg);
#endif /* FACEMGR_CFG_FILE_H */
diff --git a/ctrl/facemgr/src/common.h b/ctrl/facemgr/src/common.h
index 56bd706f1..2adbc9a23 100644
--- a/ctrl/facemgr/src/common.h
+++ b/ctrl/facemgr/src/common.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -32,71 +32,56 @@
/* Dump with indent */
#define INDENT(n, fmt) "%*s" fmt, n, ""
-#define printfi(n, fmt, ...) printf(INDENT(n*4, fmt), ##__VA_ARGS__)
-
-#define _unused(x) ((void)(x))
+#define printfi(n, fmt, ...) printf(INDENT(n * 4, fmt), ##__VA_ARGS__)
/* Random strings */
-static inline
-void rand_str(char *dest, size_t length) {
- char charset[] = "0123456789"
- "abcdefghijklmnopqrstuvwxyz"
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
- while (length-- > 0) {
- size_t index = (double) rand() / RAND_MAX * (sizeof charset - 1);
- *dest++ = charset[index];
- }
- *dest = '\0';
+static inline void rand_str(char *dest, size_t length) {
+ char charset[] =
+ "0123456789"
+ "abcdefghijklmnopqrstuvwxyz"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+
+ while (length-- > 0) {
+ size_t index = (double)rand() / RAND_MAX * (sizeof charset - 1);
+ *dest++ = charset[index];
+ }
+ *dest = '\0';
}
/* Boilerplate code */
-#define NO_INITIALIZE(NAME) \
-int \
-NAME ## _initialize(NAME ## _t * obj) { \
- return 0; \
-}
-
-#define NO_FINALIZE(NAME) \
-int \
-NAME ## _finalize(NAME ## _t * obj) { \
- return 0; \
-}
-
-#define AUTOGENERATE_CREATE_FREE(NAME) \
- \
-NAME ## _t * \
-NAME ## _create() \
-{ \
- NAME ## _t * obj = malloc(sizeof(NAME ## _t)); \
- if (!obj) \
- goto ERR_MALLOC; \
- \
- if (NAME ## _initialize(obj) < 0) \
- goto ERR_INIT; \
- \
- return obj; \
- \
-ERR_INIT: \
- free(obj); \
-ERR_MALLOC: \
- return NULL; \
-} \
- \
-void \
-NAME ## _free(NAME ## _t * obj) \
-{ \
- if (NAME ## _finalize(obj) < 0) \
- (void)0; /* XXX */ \
- free(obj); \
-} \
-
-#define AUTOGENERATE_DEFS(NAME) \
-int NAME ## _initialize(NAME ## _t *); \
-int NAME ## _finalize(NAME ## _t *); \
-NAME ## _t * NAME ## _create(); \
-void NAME ## _free(NAME ## _t *); \
+#define NO_INITIALIZE(NAME) \
+ int NAME##_initialize(NAME##_t *obj) { return 0; }
+
+#define NO_FINALIZE(NAME) \
+ int NAME##_finalize(NAME##_t *obj) { return 0; }
+
+#define AUTOGENERATE_CREATE_FREE(NAME) \
+ \
+ NAME##_t *NAME##_create() { \
+ NAME##_t *obj = malloc(sizeof(NAME##_t)); \
+ if (!obj) goto ERR_MALLOC; \
+ \
+ if (NAME##_initialize(obj) < 0) goto ERR_INIT; \
+ \
+ return obj; \
+ \
+ ERR_INIT: \
+ free(obj); \
+ ERR_MALLOC: \
+ return NULL; \
+ } \
+ \
+ void NAME##_free(NAME##_t *obj) { \
+ if (NAME##_finalize(obj) < 0) (void)0; /* XXX */ \
+ free(obj); \
+ }
+
+#define AUTOGENERATE_DEFS(NAME) \
+ int NAME##_initialize(NAME##_t *); \
+ int NAME##_finalize(NAME##_t *); \
+ NAME##_t *NAME##_create(); \
+ void NAME##_free(NAME##_t *);
#endif /* FACEMGR_COMMON_H */
diff --git a/ctrl/facemgr/src/error.c b/ctrl/facemgr/src/error.c
index 4dcea6e1f..36ce5f561 100644
--- a/ctrl/facemgr/src/error.c
+++ b/ctrl/facemgr/src/error.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,8 +21,7 @@
#include "error.h"
const char *FACEMGR_ERROR_STRING[] = {
-#define _(a,b,c) [b] = c,
- foreach_facemgr_error
+#define _(a, b, c) [b] = c,
+ foreach_facemgr_error
#undef _
};
-
diff --git a/ctrl/facemgr/src/error.h b/ctrl/facemgr/src/error.h
index a0d76b3e5..7fadea49f 100644
--- a/ctrl/facemgr/src/error.h
+++ b/ctrl/facemgr/src/error.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,15 +16,13 @@
#ifndef FACEMGR_ERROR_H
#define FACEMGR_ERROR_H
-#define foreach_facemgr_error \
-_(NONE, 0, "OK") \
-
+#define foreach_facemgr_error _(NONE, 0, "OK")
typedef enum {
-#define _(a,b,c) FACEMGR_ERROR_##a = (-b),
- foreach_facemgr_error
+#define _(a, b, c) FACEMGR_ERROR_##a = (-b),
+ foreach_facemgr_error
#undef _
- FACEMGR_ERROR_N,
+ FACEMGR_ERROR_N,
} facemgr_error_t;
extern const char *HICN_LIB_ERROR_STRING[];
diff --git a/ctrl/facemgr/src/facelet.c b/ctrl/facemgr/src/facelet.c
index 9e9f3f67f..4723b8940 100644
--- a/ctrl/facemgr/src/facelet.c
+++ b/ctrl/facemgr/src/facelet.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,7 +20,7 @@
#include <assert.h>
#include <stdbool.h>
-#include <hicn/ctrl/face.h>
+#include <hicn/face.h>
#include <hicn/ctrl/route.h>
#include <hicn/facemgr/cfg.h>
#include <hicn/facemgr/facelet.h>
@@ -32,152 +32,130 @@
TYPEDEF_SET_H(route_set, hicn_route_t *);
TYPEDEF_SET(route_set, hicn_route_t *, hicn_route_cmp, generic_snprintf);
-const char * face_type_layer_str[] = {
-#define _(x) [FACE_TYPE_LAYER_ ## x] = STRINGIZE(x),
+const char *face_type_layer_str[] = {
+#define _(x) [FACE_TYPE_LAYER_##x] = STRINGIZE(x),
foreach_face_type_layer
#undef _
};
-const char * face_type_encap_str[] = {
-#define _(x) [FACE_TYPE_ENCAP_ ## x] = STRINGIZE(x),
+const char *face_type_encap_str[] = {
+#define _(x) [FACE_TYPE_ENCAP_##x] = STRINGIZE(x),
foreach_face_type_encap
#undef _
};
-const char * facelet_status_str[] = {
-#define _(x) [FACELET_STATUS_ ## x] = STRINGIZE(x),
+const char *facelet_status_str[] = {
+#define _(x) [FACELET_STATUS_##x] = STRINGIZE(x),
foreach_facelet_status
#undef _
};
-const char * facelet_error_reason_str[] = {
-#define _(x) [FACELET_ERROR_REASON_ ## x] = STRINGIZE(x),
+const char *facelet_error_reason_str[] = {
+#define _(x) [FACELET_ERROR_REASON_##x] = STRINGIZE(x),
foreach_facelet_error_reason
#undef _
};
/* Facelet attribute status */
-const char * facelet_attr_status_str[] = {
-#define _(x, str) [FACELET_ATTR_STATUS_ ## x] = STRINGIZE(x),
+const char *facelet_attr_status_str[] = {
+#define _(x, str) [FACELET_ATTR_STATUS_##x] = STRINGIZE(x),
foreach_facelet_attr_status
#undef _
};
-const char * facelet_attr_status_str_short[] = {
-#define _(x, str) [FACELET_ATTR_STATUS_ ## x] = STRINGIZE(str),
+const char *facelet_attr_status_str_short[] = {
+#define _(x, str) [FACELET_ATTR_STATUS_##x] = STRINGIZE(str),
foreach_facelet_attr_status
#undef _
};
-
/* Facelet */
struct facelet_s {
- unsigned id;
+ unsigned id;
#define _(TYPE, NAME) TYPE NAME;
- foreach_facelet_attr
+ foreach_facelet_attr
#undef _
-#define _(TYPE, NAME) facelet_attr_status_t NAME ## _status;
- foreach_facelet_attr
+#define _(TYPE, NAME) facelet_attr_status_t NAME##_status;
+ foreach_facelet_attr
#undef _
+ facelet_status_t status;
+ int error;
+ facelet_event_t event;
- facelet_status_t status;
- int error;
-
- facelet_event_t event;
-
- route_set_t * routes;
- bool routes_done;
+ route_set_t *routes;
+ bool routes_done;
- bool bj_done;
- bool au_done;
+ bool bj_done;
};
-const char * facelet_event_str[] = {
-#define _(x) [FACELET_EVENT_ ## x] = STRINGIZE(x),
-foreach_facelet_event
+const char *facelet_event_str[] = {
+#define _(x) [FACELET_EVENT_##x] = STRINGIZE(x),
+ foreach_facelet_event
#undef _
};
-facelet_t *
-facelet_create()
-{
- facelet_t * facelet = calloc(1, sizeof(facelet_t));
- if (!facelet)
- goto ERR_MALLOC;
+facelet_t *facelet_create() {
+ facelet_t *facelet = calloc(1, sizeof(facelet_t));
+ if (!facelet) goto ERR_MALLOC;
- facelet->id = 0;
+ facelet->id = 0;
- facelet->netdevice_status = FACELET_ATTR_STATUS_UNSET;
- facelet->netdevice_type_status = FACELET_ATTR_STATUS_UNSET;
- facelet->family_status = FACELET_ATTR_STATUS_UNSET;
- facelet->local_addr_status = FACELET_ATTR_STATUS_UNSET;
- facelet->local_port_status = FACELET_ATTR_STATUS_UNSET;
- facelet->remote_addr_status = FACELET_ATTR_STATUS_UNSET;
- facelet->remote_port_status = FACELET_ATTR_STATUS_UNSET;
- facelet->admin_state_status = FACELET_ATTR_STATUS_UNSET;
- facelet->state_status = FACELET_ATTR_STATUS_UNSET;
-#ifdef WITH_POLICY
- facelet->priority_status = FACELET_ATTR_STATUS_UNSET;
-#endif /* WITH_POLICY */
- facelet->face_type_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->netdevice_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->netdevice_type_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->family_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->local_addr_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->local_port_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->remote_addr_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->remote_port_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->admin_state_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->state_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->priority_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->face_type_status = FACELET_ATTR_STATUS_UNSET;
- facelet->status = FACELET_STATUS_UNDEFINED;
- facelet->error = 0;
+ facelet->status = FACELET_STATUS_UNDEFINED;
+ facelet->error = 0;
- facelet->bj_done = false;
- facelet->au_done = false;
+ facelet->bj_done = false;
- facelet->event = FACELET_EVENT_UNDEFINED;
+ facelet->event = FACELET_EVENT_UNDEFINED;
- facelet->routes = route_set_create();
- if (!facelet->routes) {
- ERROR("[facelet_create] Cannot create route set");
- goto ERR_ROUTE_SET;
- }
- facelet->routes_done = false;
+ facelet->routes = route_set_create();
+ if (!facelet->routes) {
+ ERROR("[facelet_create] Cannot create route set");
+ goto ERR_ROUTE_SET;
+ }
+ facelet->routes_done = false;
- return facelet;
+ return facelet;
ERR_ROUTE_SET:
- free(facelet);
+ free(facelet);
ERR_MALLOC:
- return NULL;
+ return NULL;
}
-unsigned
-facelet_get_id(facelet_t * facelet)
-{
- return facelet->id;
-}
+unsigned facelet_get_id(facelet_t *facelet) { return facelet->id; }
-void
-facelet_set_id(facelet_t * facelet, unsigned id)
-{
- facelet->id = id;
-}
+void facelet_set_id(facelet_t *facelet, unsigned id) { facelet->id = id; }
-facelet_t *
-facelet_create_from_netdevice(netdevice_t * netdevice)
-{
- facelet_t * facelet = facelet_create();
- if (!facelet)
- goto ERR_FACELET;
+facelet_t *facelet_create_from_netdevice(netdevice_t *netdevice) {
+ facelet_t *facelet = facelet_create();
+ if (!facelet) goto ERR_FACELET;
- int rc = facelet_set_netdevice(facelet, *netdevice);
- if (rc < 0)
- goto ERR_NETDEV;
+ int rc = facelet_set_netdevice(facelet, *netdevice);
+ if (rc < 0) goto ERR_NETDEV;
- return facelet;
+ return facelet;
ERR_NETDEV:
- facelet_free(facelet);
+ facelet_free(facelet);
ERR_FACELET:
- return NULL;
+ return NULL;
}
/**
@@ -186,368 +164,334 @@ ERR_FACELET:
* \param [in] facelet - Pointer to the facelet to verify
* \return 0 in case of success, -1 otherwise
*/
-int
-facelet_validate_face(const facelet_t * facelet)
-{
- if (!facelet_has_face_type(facelet))
- return false;
- switch(facelet->face_type.layer) {
- case FACE_TYPE_LAYER_4:
- if (!facelet_has_remote_port(facelet))
- return false;
- if (!facelet_has_remote_addr(facelet))
- return false;
- case FACE_TYPE_LAYER_3:
- if (!facelet_has_local_port(facelet))
- return false;
- if (!facelet_has_local_addr(facelet))
- return false;
- if (!facelet_has_netdevice(facelet))
- return false;
- return true;
-
- default:
- return false; /* Error */
- }
- // FIXME Not implemented
- return 0;
+int facelet_validate_face(const facelet_t *facelet) {
+ if (!facelet_has_face_type(facelet)) return false;
+
+ switch (facelet->face_type.layer) {
+ case FACE_TYPE_LAYER_4:
+ if (!facelet_has_remote_port(facelet)) return false;
+ if (!facelet_has_remote_addr(facelet)) return false;
+ case FACE_TYPE_LAYER_3:
+ if (!facelet_has_local_port(facelet)) return false;
+ if (!facelet_has_local_addr(facelet)) return false;
+ if (!facelet_has_netdevice(facelet)) return false;
+ break;
+
+ default:
+ return false;
+ }
+
+ return true;
}
-
-netdevice_type_t
-netdevice_type_from_face_tags(const face_t * face)
-{
- policy_tags_t tags = face->tags;
- if (policy_tags_has(tags, POLICY_TAG_WIRED))
- return NETDEVICE_TYPE_WIRED;
- else if (policy_tags_has(tags, POLICY_TAG_WIFI))
- return NETDEVICE_TYPE_WIFI;
- else if (policy_tags_has(tags, POLICY_TAG_CELLULAR))
- return NETDEVICE_TYPE_CELLULAR;
- return NETDEVICE_TYPE_UNDEFINED;
+netdevice_type_t netdevice_type_from_face_tags(const face_t *face) {
+ policy_tags_t tags = face->tags;
+ if (policy_tags_has(tags, POLICY_TAG_WIRED))
+ return NETDEVICE_TYPE_WIRED;
+ else if (policy_tags_has(tags, POLICY_TAG_WIFI))
+ return NETDEVICE_TYPE_WIFI;
+ else if (policy_tags_has(tags, POLICY_TAG_CELLULAR))
+ return NETDEVICE_TYPE_CELLULAR;
+ return NETDEVICE_TYPE_UNDEFINED;
}
-facelet_t *
-facelet_create_from_face(face_t * face)
-{
- facelet_t * facelet = malloc(sizeof(facelet_t));
- if (!facelet)
- goto ERR_MALLOC;
+facelet_t *facelet_create_from_face(face_t *face) {
+ facelet_t *facelet = malloc(sizeof(facelet_t));
+ if (!facelet) goto ERR_MALLOC;
- facelet->id = 0;
+ facelet->id = 0;
- /* Go through the face attributes to update the local representation */
+ /* Go through the face attributes to update the local representation */
- /* Attribute : netdevice */
- /* NOTE index is not set */
- if (IS_VALID_NETDEVICE(face->netdevice)) {
- /* /!\ A face has only the netdevice name */
- netdevice_set_name(&facelet->netdevice, face->netdevice.name);
- facelet->netdevice_status = FACELET_ATTR_STATUS_CLEAN;
- } else {
- facelet->netdevice_status = FACELET_ATTR_STATUS_UNSET;
- }
-
- /* Attribute : netdevice_type */
- facelet->netdevice_type = netdevice_type_from_face_tags(face);
- if (facelet->netdevice_type != NETDEVICE_TYPE_UNDEFINED) {
- facelet->netdevice_type_status = FACELET_ATTR_STATUS_CLEAN;
- } else {
- facelet->netdevice_type = NETDEVICE_TYPE_UNDEFINED;
- facelet->netdevice_type_status = FACELET_ATTR_STATUS_UNSET;
- }
+ /* Attribute : netdevice */
+ /* NOTE index is not set */
+ if (IS_VALID_NETDEVICE(face->netdevice)) {
+ /* /!\ A face has only the netdevice name */
+ netdevice_set_name(&facelet->netdevice, face->netdevice.name);
+ facelet->netdevice_status = FACELET_ATTR_STATUS_CLEAN;
+ } else {
+ facelet->netdevice_status = FACELET_ATTR_STATUS_UNSET;
+ }
+
+ /* Attribute : netdevice_type */
+ facelet->netdevice_type = netdevice_type_from_face_tags(face);
+ if (facelet->netdevice_type != NETDEVICE_TYPE_UNDEFINED) {
+ facelet->netdevice_type_status = FACELET_ATTR_STATUS_CLEAN;
+ } else {
+ facelet->netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ facelet->netdevice_type_status = FACELET_ATTR_STATUS_UNSET;
+ }
- /* Attribute : family */
- if (IS_VALID_FAMILY(face->family)) {
- facelet->family = face->family;
- facelet->family_status = FACELET_ATTR_STATUS_CLEAN;
-
- /* Attribute : local_addr */
- if (ip_address_cmp(&face->local_addr, &IP_ADDRESS_EMPTY, face->family) != 0) {
- facelet->local_addr = face->local_addr;
- facelet->local_addr_status = FACELET_ATTR_STATUS_CLEAN;
- } else {
- facelet->local_addr_status = FACELET_ATTR_STATUS_UNSET;
- }
-
- /* Attribute : local_port */
- if (IS_VALID_PORT(face->local_port)) {
- facelet->local_port = face->local_port;
- facelet->local_port_status = FACELET_ATTR_STATUS_CLEAN;
- } else {
- facelet->local_port_status = FACELET_ATTR_STATUS_UNSET;
- }
-
- /* Attribute : remote_addr */
- if (ip_address_cmp(&face->remote_addr, &IP_ADDRESS_EMPTY, face->family) != 0) {
- facelet->remote_addr = face->remote_addr;
- facelet->remote_addr_status = FACELET_ATTR_STATUS_CLEAN;
- } else {
- facelet->remote_addr_status = FACELET_ATTR_STATUS_UNSET;
- }
-
- /* Attribute : remote_port */
- if (IS_VALID_PORT(face->remote_port)) {
- facelet->remote_port = face->remote_port;
- facelet->remote_port_status = FACELET_ATTR_STATUS_CLEAN;
- } else {
- facelet->remote_port_status = FACELET_ATTR_STATUS_UNSET;
- }
+ /* Attribute : family */
+ if (IS_VALID_FAMILY(face->family)) {
+ facelet->family = face->family;
+ facelet->family_status = FACELET_ATTR_STATUS_CLEAN;
+ /* Attribute : local_addr */
+ if (hicn_ip_address_cmp(&face->local_addr, &IP_ADDRESS_EMPTY) != 0) {
+ facelet->local_addr = face->local_addr;
+ facelet->local_addr_status = FACELET_ATTR_STATUS_CLEAN;
} else {
- facelet->family_status = FACELET_ATTR_STATUS_UNSET;
- facelet->local_addr_status = FACELET_ATTR_STATUS_UNSET;
- facelet->local_port_status = FACELET_ATTR_STATUS_UNSET;
- facelet->remote_addr_status = FACELET_ATTR_STATUS_UNSET;
- facelet->remote_port_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->local_addr_status = FACELET_ATTR_STATUS_UNSET;
}
- /* Attribute : admin_state */
- if ((face->admin_state == FACE_STATE_UP) ||
- (face->admin_state == FACE_STATE_DOWN)) {
- facelet->admin_state = face->admin_state;
- facelet->admin_state_status = FACELET_ATTR_STATUS_CLEAN;
+ /* Attribute : local_port */
+ if (IS_VALID_PORT(face->local_port)) {
+ facelet->local_port = face->local_port;
+ facelet->local_port_status = FACELET_ATTR_STATUS_CLEAN;
} else {
- facelet->admin_state_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->local_port_status = FACELET_ATTR_STATUS_UNSET;
}
- /* Attribute : state */
- if ((face->state == FACE_STATE_UP) ||
- (face->state == FACE_STATE_DOWN)) {
- facelet->state = face->state;
- facelet->state_status = FACELET_ATTR_STATUS_CLEAN;
+ /* Attribute : remote_addr */
+ if (hicn_ip_address_cmp(&face->remote_addr, &IP_ADDRESS_EMPTY) != 0) {
+ facelet->remote_addr = face->remote_addr;
+ facelet->remote_addr_status = FACELET_ATTR_STATUS_CLEAN;
} else {
- facelet->state_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->remote_addr_status = FACELET_ATTR_STATUS_UNSET;
}
-#ifdef WITH_POLICY
- /* Attribute : priority */
- if (face->priority > 0) {
- facelet->priority = face->priority;
- facelet->priority_status = FACELET_ATTR_STATUS_CLEAN;
- } else {
- facelet->priority_status = FACELET_ATTR_STATUS_UNSET;
- }
-#endif /* WITH_POLICY */
-
- /* Attribute : face_type */
- if ((face->type != FACE_TYPE_UNDEFINED) && (face->type != FACE_TYPE_N)) {
- switch(face->type) {
- case FACE_TYPE_UDP:
- facelet->face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
- break;
- case FACE_TYPE_TCP:
- facelet->face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
- break;
- case FACE_TYPE_HICN:
- facelet->face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
- break;
- default:
- ERROR("[facelet_create_from_face] Face type not (yet) implemented");
- goto ERR_FACE;
- }
- facelet->face_type_status = FACELET_ATTR_STATUS_CLEAN;
+ /* Attribute : remote_port */
+ if (IS_VALID_PORT(face->remote_port)) {
+ facelet->remote_port = face->remote_port;
+ facelet->remote_port_status = FACELET_ATTR_STATUS_CLEAN;
} else {
- facelet->face_type_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->remote_port_status = FACELET_ATTR_STATUS_UNSET;
}
- /* Status */
- facelet->status = FACELET_STATUS_CLEAN;
- facelet->error = 0;
+ } else {
+ facelet->family_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->local_addr_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->local_port_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->remote_addr_status = FACELET_ATTR_STATUS_UNSET;
+ facelet->remote_port_status = FACELET_ATTR_STATUS_UNSET;
+ }
+
+ /* Attribute : admin_state */
+ if ((face->admin_state == FACE_STATE_UP) ||
+ (face->admin_state == FACE_STATE_DOWN)) {
+ facelet->admin_state = face->admin_state;
+ facelet->admin_state_status = FACELET_ATTR_STATUS_CLEAN;
+ } else {
+ facelet->admin_state_status = FACELET_ATTR_STATUS_UNSET;
+ }
+
+ /* Attribute : state */
+ if ((face->state == FACE_STATE_UP) || (face->state == FACE_STATE_DOWN)) {
+ facelet->state = face->state;
+ facelet->state_status = FACELET_ATTR_STATUS_CLEAN;
+ } else {
+ facelet->state_status = FACELET_ATTR_STATUS_UNSET;
+ }
- /* TODO Consistency check between face type and found attributes */
- if (facelet_validate_face(facelet) < 0) {
- ERROR("[facelet_create_from_face] Cannot validate face");
+ /* Attribute : priority */
+ if (face->priority > 0) {
+ facelet->priority = face->priority;
+ facelet->priority_status = FACELET_ATTR_STATUS_CLEAN;
+ } else {
+ facelet->priority_status = FACELET_ATTR_STATUS_UNSET;
+ }
+
+ /* Attribute : face_type */
+ if ((face->type != FACE_TYPE_UNDEFINED) && (face->type != FACE_TYPE_N)) {
+ switch (face->type) {
+ case FACE_TYPE_UDP:
+ facelet->face_type = FACEMGR_FACE_TYPE_OVERLAY_UDP;
+ break;
+ case FACE_TYPE_TCP:
+ facelet->face_type = FACEMGR_FACE_TYPE_OVERLAY_TCP;
+ break;
+ case FACE_TYPE_HICN:
+ facelet->face_type = FACEMGR_FACE_TYPE_NATIVE_TCP;
+ break;
+ default:
+ ERROR("[facelet_create_from_face] Face type not (yet) implemented");
goto ERR_FACE;
}
+ facelet->face_type_status = FACELET_ATTR_STATUS_CLEAN;
+ } else {
+ facelet->face_type_status = FACELET_ATTR_STATUS_UNSET;
+ }
- facelet->bj_done = false;
- facelet->au_done = false;
+ /* Status */
+ facelet->status = FACELET_STATUS_CLEAN;
+ facelet->error = 0;
- facelet->event = FACELET_EVENT_UNDEFINED;
+ /* TODO Consistency check between face type and found attributes */
+ if (facelet_validate_face(facelet) < 0) {
+ ERROR("[facelet_create_from_face] Cannot validate face");
+ goto ERR_FACE;
+ }
- /* We need to get route set */
- facelet->routes = route_set_create();
- if (!facelet->routes) {
- ERROR("[facelet_create_from_face] Cannot create route set");
- goto ERR_ROUTE_SET;
- }
- facelet->routes_done = false;
+ facelet->bj_done = false;
+
+ facelet->event = FACELET_EVENT_UNDEFINED;
- return facelet;
+ /* We need to get route set */
+ facelet->routes = route_set_create();
+ if (!facelet->routes) {
+ ERROR("[facelet_create_from_face] Cannot create route set");
+ goto ERR_ROUTE_SET;
+ }
+ facelet->routes_done = false;
+
+ return facelet;
ERR_ROUTE_SET:
ERR_FACE:
- free(facelet);
+ free(facelet);
ERR_MALLOC:
- return NULL;
+ return NULL;
}
+void facelet_free(facelet_t *facelet) {
+ /* Workaround: investigate how routes could be NULL */
+ if (!facelet->routes) return;
-void
-facelet_free(facelet_t * facelet)
-{
- /* Free up routes */
- route_set_clear(facelet->routes);
- route_set_free(facelet->routes);
- free(facelet);
+ /* Free up routes */
+ route_set_clear(facelet->routes);
+ route_set_free(facelet->routes);
+ free(facelet);
}
-facelet_t *
-facelet_dup(const facelet_t * current_facelet)
-{
- facelet_t * facelet = facelet_create();
- if (!facelet)
- goto ERR_CREATE;
+facelet_t *facelet_dup(const facelet_t *current_facelet) {
+ facelet_t *facelet = facelet_create();
+ if (!facelet) goto ERR_CREATE;
-#define _(TYPE, NAME) facelet-> NAME = current_facelet-> NAME;
- foreach_facelet_attr
+#define _(TYPE, NAME) facelet->NAME = current_facelet->NAME;
+ foreach_facelet_attr
#undef _
-#define _(TYPE, NAME) facelet-> NAME ## _status = current_facelet-> NAME ## _status;
- foreach_facelet_attr
+#define _(TYPE, NAME) facelet->NAME##_status = current_facelet->NAME##_status;
+ foreach_facelet_attr
#undef _
- facelet->status = current_facelet->status;
- facelet->event = current_facelet->event;
-
- facelet->bj_done = current_facelet->bj_done;
- facelet->au_done = current_facelet->au_done;
-
- /* Routes */
- hicn_route_t ** route_array;
- int n = route_set_get_array(current_facelet->routes, &route_array);
- if (n < 0) {
- ERROR("[facelet_free] Error getting route set associated to facelet");
- } else {
- for (unsigned i = 0; i < n; i++) {
- hicn_route_t * route = route_array[i];
- hicn_route_t * new_route = hicn_route_dup(route);
- if (!new_route)
- goto ERR_ROUTE;
- route_set_add(facelet->routes, new_route);
- }
+ facelet->status = current_facelet->status;
+ facelet->event = current_facelet->event;
+
+ facelet->bj_done = current_facelet->bj_done;
+
+ /* Routes */
+ hicn_route_t **route_array;
+ int n = route_set_get_array(current_facelet->routes, &route_array);
+ if (n < 0) {
+ ERROR("[facelet_free] Error getting route set associated to facelet %p",
+ current_facelet);
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ hicn_route_t *route = route_array[i];
+ if (!route) continue; /* Should not occur */
+ hicn_route_t *new_route = hicn_route_dup(route);
+ if (!new_route) goto ERR_ROUTE;
+ route_set_add(facelet->routes, new_route);
}
- free(route_array);
+ }
+ free(route_array);
- return facelet;
+ return facelet;
ERR_ROUTE:
- /* This will free all routes */
- facelet_free(facelet);
+ /* This will free all routes */
+ facelet_free(facelet);
ERR_CREATE:
- return NULL;
+ return NULL;
}
-int
-facelet_cmp(const facelet_t * f1, const facelet_t * f2)
-{
- /*
- * Under the assumption we only create a face per physical interface, a
- * facelet is uniquely identified by its netdevice attribute, and address
- * family if any.
- *
- * Because of additional static faces, we introduce a unique facelet id
- *
- * This function is mostly used for lookups into the cache, and the face
- * thus needs to have a netdevice associated, and optionally, an address
- * family.
- *
- * For other situations, the `facelet_match` function is more appropriate.
+int facelet_cmp(const facelet_t *f1, const facelet_t *f2) {
+ /*
+ * Under the assumption we only create a face per physical interface, a
+ * facelet is uniquely identified by its netdevice attribute, and address
+ * family if any.
+ *
+ * Because of additional static faces, we introduce a unique facelet id
+ *
+ * This function is mostly used for lookups into the cache, and the face
+ * thus needs to have a netdevice associated, and optionally, an address
+ * family.
+ *
+ * For other situations, the `facelet_match` function is more appropriate.
+ */
+
+ if (f1->id != f2->id) return f1->id > f2->id ? 1 : -1;
+
+ if ((f1->netdevice_status != FACELET_ATTR_STATUS_UNSET) &&
+ (f2->netdevice_status != FACELET_ATTR_STATUS_UNSET)) {
+ int rc = netdevice_cmp(&f1->netdevice, &f2->netdevice);
+ if (rc != 0) return rc;
+
+ } else {
+ /* Both unset : we might have the face without netdevice due to hicn
+ * light not returning it currently, but we cannot skip it in the match
+ * otherwise we cannot distinguish with other faces except matching on
+ * other fields which might unfortunately not be determined yet...
*/
+ return (f1->netdevice_status == FACELET_ATTR_STATUS_UNSET) ? -1 : 1;
+ }
- if (f1->id != f2->id)
- return f1->id > f2->id ? 1 : -1;
-
- if ((f1->netdevice_status != FACELET_ATTR_STATUS_UNSET) &&
- (f2->netdevice_status != FACELET_ATTR_STATUS_UNSET)) {
- int rc = netdevice_cmp(&f1->netdevice, &f2->netdevice);
- if (rc != 0)
- return rc;
-
- } else {
- /* Both unset : we might have the face without netdevice due to hicn
- * light not returning it currently, but we cannot skip it in the match
- * otherwise we cannot distinguish with other faces except matching on
- * other fields which might unfortunately not be determined yet...
- */
- return (f1->netdevice_status == FACELET_ATTR_STATUS_UNSET) ? -1 : 1;
- }
+ assert(f1->family_status != FACELET_ATTR_STATUS_UNSET);
+ assert(f2->family_status != FACELET_ATTR_STATUS_UNSET);
- assert(f1->family_status != FACELET_ATTR_STATUS_UNSET);
- assert(f2->family_status != FACELET_ATTR_STATUS_UNSET);
-
- if ((f1->family == AF_UNSPEC) || (f2->family == AF_UNSPEC))
- return 0;
- int diff = f1->family - f2->family;
- return (diff > 0) ? 1 :
- (diff < 0) ? -1 : 0;
+ if ((f1->family == AF_UNSPEC) || (f2->family == AF_UNSPEC)) return 0;
+ int diff = f1->family - f2->family;
+ return (diff > 0) ? 1 : (diff < 0) ? -1 : 0;
}
/*
* If the match has a field set, then the facelet only matches iif it has the
* same field set, and both values are equal
*/
-#define EQUALS_ATTRIBUTE(TYPE, NAME) \
-do { \
- if (facelet_has_ ## NAME(facelet1)) { \
- if (facelet_has_ ## NAME(facelet2)) { \
- TYPE NAME ## 1; \
- TYPE NAME ## 2; \
- if (facelet_get_ ## NAME (facelet1, & NAME ## 1) < 0) \
- return false; \
- if (facelet_get_ ## NAME (facelet2, & NAME ## 2) < 0) \
- return false; \
- if (memcmp(& NAME ## 1, & NAME ## 2, sizeof(TYPE)) != 0) \
- return false; \
- } else { \
- return false; \
- } \
- } else { \
- if (facelet_has_ ## NAME(facelet2)) { \
- return false; \
- } \
- } \
-} while(0)
-
-bool
-facelet_equals(const facelet_t * facelet1, const facelet_t * facelet2)
-{
+#define EQUALS_ATTRIBUTE(TYPE, NAME) \
+ do { \
+ if (facelet_has_##NAME(facelet1)) { \
+ if (facelet_has_##NAME(facelet2)) { \
+ TYPE NAME##1; \
+ TYPE NAME##2; \
+ if (facelet_get_##NAME(facelet1, &NAME##1) < 0) return false; \
+ if (facelet_get_##NAME(facelet2, &NAME##2) < 0) return false; \
+ if (memcmp(&NAME##1, &NAME##2, sizeof(TYPE)) != 0) return false; \
+ } else { \
+ return false; \
+ } \
+ } else { \
+ if (facelet_has_##NAME(facelet2)) { \
+ return false; \
+ } \
+ } \
+ } while (0)
+
+bool facelet_equals(const facelet_t *facelet1, const facelet_t *facelet2) {
#define _(TYPE, NAME) EQUALS_ATTRIBUTE(TYPE, NAME);
- foreach_facelet_attr
+ foreach_facelet_attr
#undef _
- return true;
+ return true;
}
/*
* If the match has a field set, then the facelet only matches iif it has the
* same field set, and both values are equal
*/
-#define MATCH_ATTRIBUTE(TYPE, NAME) \
-do { \
- if (facelet_match->NAME ## _status == FACELET_ATTR_STATUS_CLEAN) { \
- if (facelet_has_ ## NAME(facelet_match)) { \
- TYPE NAME; \
- TYPE NAME ## _match; \
- if (!facelet_has_ ## NAME(facelet)) { \
- continue; /* return false; */ \
- } \
- if (facelet_get_ ## NAME (facelet, & NAME) < 0) \
- return false; \
- if (facelet_get_ ## NAME (facelet_match, & NAME ## _match) < 0) \
- return false; \
- if (memcmp(& NAME, & NAME ## _match, sizeof(NAME)) != 0) { \
- return false; \
- } \
- } \
- } \
-} while(0)
+#define MATCH_ATTRIBUTE(TYPE, NAME) \
+ do { \
+ if (facelet_match->NAME##_status == FACELET_ATTR_STATUS_CLEAN) { \
+ if (facelet_has_##NAME(facelet_match)) { \
+ TYPE NAME; \
+ TYPE NAME##_match; \
+ if (!facelet_has_##NAME(facelet)) { \
+ continue; /* return false; */ \
+ } \
+ if (facelet_get_##NAME(facelet, &NAME) < 0) return false; \
+ if (facelet_get_##NAME(facelet_match, &NAME##_match) < 0) \
+ return false; \
+ if (memcmp(&NAME, &NAME##_match, sizeof(NAME)) != 0) { \
+ return false; \
+ } \
+ } \
+ } \
+ } while (0)
/* facelet_match is the incoming one */
-bool
-facelet_match(const facelet_t * facelet, const facelet_t * facelet_match)
-{
+bool facelet_match(const facelet_t *facelet, const facelet_t *facelet_match) {
#define _(TYPE, NAME) MATCH_ATTRIBUTE(TYPE, NAME);
- foreach_facelet_attr
+ foreach_facelet_attr
#undef _
#if 0
@@ -557,117 +501,101 @@ facelet_match(const facelet_t * facelet, const facelet_t * facelet_match)
facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet);
DEBUG(" WITH %s", facelet_s);
#endif
- return true;
+ return true;
}
-bool facelet_has_key(const facelet_t * facelet) {
- return (facelet_has_netdevice(facelet) && facelet_has_family(facelet));
+bool facelet_has_key(const facelet_t *facelet) {
+ return (facelet_has_netdevice(facelet) && facelet_has_family(facelet));
}
/*
* Implementation note:
* - facelet_set_* is equivalent to merge with a CLEAN remote attribute
*/
-#define FACELET_ACCESSORS(TYPE, NAME) \
-bool \
-facelet_has_ ## NAME(const facelet_t * facelet) \
-{ \
- assert(facelet); \
- assert(facelet->NAME ## _status != FACELET_ATTR_STATUS_UNDEFINED); \
- assert(facelet->NAME ## _status != FACELET_ATTR_STATUS_N); \
- return ((facelet-> NAME ## _status != FACELET_ATTR_STATUS_UNSET)); \
-} \
- \
-facelet_attr_status_t \
-facelet_get_ ## NAME ## _status(const facelet_t * facelet) \
-{ \
- return (facelet->NAME ## _status); \
-} \
- \
-void \
-facelet_set_ ## NAME ## _status(facelet_t * facelet, \
- facelet_attr_status_t status) \
-{ \
- facelet->NAME ## _status = status; \
-} \
- \
-int \
-facelet_get_ ## NAME(const facelet_t * facelet, TYPE * NAME) \
-{ \
- assert(facelet); \
- if (!facelet_has_ ## NAME(facelet)) \
- return -1; \
- *NAME = facelet-> NAME; \
- return 0; \
-} \
- \
-int \
-facelet_set_local_ ## NAME(facelet_t * facelet, TYPE NAME) \
-{ \
- assert(facelet); \
- switch(facelet->NAME ## _status) { \
- case FACELET_ATTR_STATUS_UNSET: \
- case FACELET_ATTR_STATUS_CLEAN: \
- case FACELET_ATTR_STATUS_DIRTY: \
- case FACELET_ATTR_STATUS_PENDING: \
- facelet-> NAME = NAME; \
- facelet->NAME ## _status = FACELET_ATTR_STATUS_DIRTY; \
- if (facelet->status == FACELET_STATUS_CLEAN) \
- facelet->status = FACELET_STATUS_UPDATE; \
- break; \
- case FACELET_ATTR_STATUS_CONFLICT: \
- break; \
- case FACELET_ATTR_STATUS_UNDEFINED: \
- case FACELET_ATTR_STATUS_N: \
- ERROR("Unexpected attribute status value"); \
- return -1; \
- } \
- return 0; \
-} \
- \
-int \
-facelet_set_remote_ ## NAME(facelet_t * facelet, TYPE NAME) \
-{ \
- assert(facelet); \
- switch(facelet->NAME ## _status) { \
- case FACELET_ATTR_STATUS_UNSET: \
- facelet-> NAME = NAME; \
- facelet->NAME ## _status = FACELET_ATTR_STATUS_CLEAN; \
- break; \
- case FACELET_ATTR_STATUS_CLEAN: \
- facelet->NAME = NAME; \
- break; \
- case FACELET_ATTR_STATUS_DIRTY: \
- ERROR("Discarded remote value for status reasons"); \
- break; \
- case FACELET_ATTR_STATUS_PENDING: \
- ERROR("Received remote value on pending attribute"); \
- facelet->NAME ## _status = FACELET_ATTR_STATUS_CONFLICT; \
- /* We need to proceed to an update of the face */ \
- if (facelet->status != FACELET_STATUS_UPDATE) \
- facelet->status = FACELET_STATUS_UPDATE; \
- break; \
- case FACELET_ATTR_STATUS_CONFLICT: \
- return -1; \
- case FACELET_ATTR_STATUS_UNDEFINED: \
- case FACELET_ATTR_STATUS_N: \
- ERROR("Unexpected attribute status value"); \
- return -1; \
- } \
- return 0; \
-} \
- \
-int \
-facelet_set_ ## NAME(facelet_t * facelet, TYPE NAME) \
-{ \
- return facelet_set_local_ ## NAME(facelet, NAME); \
-} \
- \
-int \
-facelet_unset_ ## NAME(facelet_t * facelet) \
-{ \
- return facelet->NAME ## _status = FACELET_ATTR_STATUS_UNSET; \
-}
+#define FACELET_ACCESSORS(TYPE, NAME) \
+ bool facelet_has_##NAME(const facelet_t *facelet) { \
+ assert(facelet); \
+ assert(facelet->NAME##_status != FACELET_ATTR_STATUS_UNDEFINED); \
+ assert(facelet->NAME##_status != FACELET_ATTR_STATUS_N); \
+ return ((facelet->NAME##_status != FACELET_ATTR_STATUS_UNSET)); \
+ } \
+ \
+ facelet_attr_status_t facelet_get_##NAME##_status( \
+ const facelet_t *facelet) { \
+ return (facelet->NAME##_status); \
+ } \
+ \
+ void facelet_set_##NAME##_status(facelet_t *facelet, \
+ facelet_attr_status_t status) { \
+ facelet->NAME##_status = status; \
+ } \
+ \
+ int facelet_get_##NAME(const facelet_t *facelet, TYPE *NAME) { \
+ assert(facelet); \
+ if (!facelet_has_##NAME(facelet)) return -1; \
+ *NAME = facelet->NAME; \
+ return 0; \
+ } \
+ \
+ int facelet_set_local_##NAME(facelet_t *facelet, TYPE NAME) { \
+ assert(facelet); \
+ switch (facelet->NAME##_status) { \
+ case FACELET_ATTR_STATUS_UNSET: \
+ case FACELET_ATTR_STATUS_CLEAN: \
+ case FACELET_ATTR_STATUS_DIRTY: \
+ case FACELET_ATTR_STATUS_PENDING: \
+ facelet->NAME = NAME; \
+ facelet->NAME##_status = FACELET_ATTR_STATUS_DIRTY; \
+ if (facelet->status == FACELET_STATUS_CLEAN) \
+ facelet->status = FACELET_STATUS_UPDATE; \
+ break; \
+ case FACELET_ATTR_STATUS_CONFLICT: \
+ break; \
+ case FACELET_ATTR_STATUS_UNDEFINED: \
+ case FACELET_ATTR_STATUS_N: \
+ ERROR("Unexpected attribute status value"); \
+ return -1; \
+ } \
+ return 0; \
+ } \
+ \
+ int facelet_set_remote_##NAME(facelet_t *facelet, TYPE NAME) { \
+ assert(facelet); \
+ switch (facelet->NAME##_status) { \
+ case FACELET_ATTR_STATUS_UNSET: \
+ facelet->NAME = NAME; \
+ facelet->NAME##_status = FACELET_ATTR_STATUS_CLEAN; \
+ break; \
+ case FACELET_ATTR_STATUS_CLEAN: \
+ facelet->NAME = NAME; \
+ break; \
+ case FACELET_ATTR_STATUS_DIRTY: \
+ ERROR("Discarded remote value for status reasons"); \
+ break; \
+ case FACELET_ATTR_STATUS_PENDING: \
+ ERROR("Received remote value on pending attribute"); \
+ facelet->NAME##_status = FACELET_ATTR_STATUS_CONFLICT; \
+ /* We need to proceed to an update of the face */ \
+ if (facelet->status != FACELET_STATUS_UPDATE) \
+ facelet->status = FACELET_STATUS_UPDATE; \
+ break; \
+ case FACELET_ATTR_STATUS_CONFLICT: \
+ return -1; \
+ case FACELET_ATTR_STATUS_UNDEFINED: \
+ case FACELET_ATTR_STATUS_N: \
+ ERROR("Unexpected attribute status value"); \
+ return -1; \
+ } \
+ return 0; \
+ } \
+ \
+ int facelet_set_##NAME(facelet_t *facelet, TYPE NAME) { \
+ return facelet_set_local_##NAME(facelet, NAME); \
+ } \
+ \
+ int facelet_unset_##NAME(facelet_t *facelet) { \
+ return facelet->NAME##_status = FACELET_ATTR_STATUS_UNSET; \
+ }
#define _(TYPE, NAME) FACELET_ACCESSORS(TYPE, NAME)
foreach_facelet_attr
@@ -681,773 +609,616 @@ foreach_facelet_attr
// FIXME CLEAN for key fields, dirty for fields to update.
-#define MERGE_ATTRIBUTE(TYPE, NAME) \
-do { \
- switch(facelet_to_merge->NAME ## _status) { \
- case FACELET_ATTR_STATUS_UNDEFINED: \
- case FACELET_ATTR_STATUS_N: \
- case FACELET_ATTR_STATUS_PENDING: \
- case FACELET_ATTR_STATUS_CONFLICT: \
- ERROR("Unexpected facelet attribute status"); \
- return -1; \
- case FACELET_ATTR_STATUS_UNSET: \
- break; \
- case FACELET_ATTR_STATUS_CLEAN: \
- case FACELET_ATTR_STATUS_DIRTY: \
- facelet_set_ ## NAME(facelet, facelet_to_merge-> NAME); \
- break; \
- } \
-} while (0)
-
-int facelet_merge(facelet_t * facelet, facelet_t * facelet_to_merge)
-{
- assert(facelet && facelet_to_merge);
+#define MERGE_ATTRIBUTE(TYPE, NAME) \
+ do { \
+ switch (facelet_to_merge->NAME##_status) { \
+ case FACELET_ATTR_STATUS_UNDEFINED: \
+ case FACELET_ATTR_STATUS_N: \
+ case FACELET_ATTR_STATUS_PENDING: \
+ case FACELET_ATTR_STATUS_CONFLICT: \
+ ERROR("Unexpected facelet attribute status"); \
+ return -1; \
+ case FACELET_ATTR_STATUS_UNSET: \
+ break; \
+ case FACELET_ATTR_STATUS_CLEAN: \
+ case FACELET_ATTR_STATUS_DIRTY: \
+ facelet_set_##NAME(facelet, facelet_to_merge->NAME); \
+ break; \
+ } \
+ } while (0)
+
+ int
+ facelet_merge(facelet_t *facelet, facelet_t *facelet_to_merge) {
+ assert(facelet && facelet_to_merge);
#define _(TYPE, NAME) MERGE_ATTRIBUTE(TYPE, NAME);
- foreach_facelet_attr
+ foreach_facelet_attr
#undef _
- facelet->event = facelet_to_merge->event;
-
- /* Routes */
- hicn_route_t ** route_array;
- int n = route_set_get_array(facelet_to_merge->routes, &route_array);
- if (n < 0) {
- ERROR("[facelet_free] Error getting route set associated to facelet");
- } else {
- for (unsigned i = 0; i < n; i++) {
- hicn_route_t * route = route_array[i];
- hicn_route_t * route_found = NULL;
- if (route_set_get(facelet->routes, route, &route_found) < 0) {
- ERROR("Error searching for route");
- continue;
- }
- if (route_found)
- continue;
- route_set_add(facelet->routes, hicn_route_dup(route));
- }
+ facelet->event = facelet_to_merge->event;
+
+ /* Routes */
+ hicn_route_t **route_array;
+ int n = route_set_get_array(facelet_to_merge->routes, &route_array);
+ if (n < 0) {
+ ERROR("[facelet_free] Error getting route set associated to facelet");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ hicn_route_t *route = route_array[i];
+ if (!route) continue; /* Should not occur */
+ hicn_route_t *route_found = NULL;
+ if (route_set_get(facelet->routes, route, &route_found) < 0) {
+ ERROR("Error searching for route");
+ continue;
+ }
+ if (route_found) continue;
+ route_set_add(facelet->routes, hicn_route_dup(route));
}
- free(route_array);
+ }
+ free(route_array);
- return 0;
+ return 0;
}
-#define MERGE_ATTRIBUTE_REMOTE(TYPE, NAME) \
-do { \
- switch(facelet_to_merge->NAME ## _status) { \
- case FACELET_ATTR_STATUS_UNDEFINED: \
- case FACELET_ATTR_STATUS_N: \
- case FACELET_ATTR_STATUS_DIRTY: \
- case FACELET_ATTR_STATUS_PENDING: \
- case FACELET_ATTR_STATUS_CONFLICT: \
- ERROR("Unexpected facelet attribute status"); \
- return -1; \
- case FACELET_ATTR_STATUS_UNSET: \
- break; \
- case FACELET_ATTR_STATUS_CLEAN: \
- facelet_set_ ## NAME(facelet, facelet_to_merge-> NAME); \
- break; \
- \
- } \
-} while (0)
-
-int facelet_merge_remote(facelet_t * facelet, const facelet_t * facelet_to_merge)
-{
- assert(facelet && facelet_to_merge);
+#define MERGE_ATTRIBUTE_REMOTE(TYPE, NAME) \
+ do { \
+ switch (facelet_to_merge->NAME##_status) { \
+ case FACELET_ATTR_STATUS_UNDEFINED: \
+ case FACELET_ATTR_STATUS_N: \
+ case FACELET_ATTR_STATUS_DIRTY: \
+ case FACELET_ATTR_STATUS_PENDING: \
+ case FACELET_ATTR_STATUS_CONFLICT: \
+ ERROR("Unexpected facelet attribute status"); \
+ return -1; \
+ case FACELET_ATTR_STATUS_UNSET: \
+ break; \
+ case FACELET_ATTR_STATUS_CLEAN: \
+ facelet_set_##NAME(facelet, facelet_to_merge->NAME); \
+ break; \
+ } \
+ } while (0)
+
+int facelet_merge_remote(facelet_t *facelet,
+ const facelet_t *facelet_to_merge) {
+ assert(facelet && facelet_to_merge);
#define _(TYPE, NAME) MERGE_ATTRIBUTE_REMOTE(TYPE, NAME);
- foreach_facelet_attr
+ foreach_facelet_attr
#undef _
- facelet->event = facelet_to_merge->event;
- return 0;
+ facelet->event = facelet_to_merge->event;
+ return 0;
}
-int
-facelet_get_face(const facelet_t * facelet, face_t ** pface)
-{
- assert(pface);
+int facelet_get_face(const facelet_t *facelet, face_t **pface) {
+ assert(pface);
- /* Facelet has all the required information to create a face */
- if (facelet_validate_face(facelet) < 0) {
- ERROR("[facelet_get_face] Face does not validate");
- return 0;
- }
-
- face_t * face = face_create();
- if (!face)
- goto ERR_CREATE;
-
- assert(facelet_has_netdevice(facelet));
- face->netdevice = facelet->netdevice;
-
- /* Face type */
- switch(facelet->face_type.layer) {
- case FACE_TYPE_LAYER_4:
- switch(facelet->face_type.encap) {
- case FACE_TYPE_ENCAP_UDP:
- face->type = FACE_TYPE_UDP;
- break;
- case FACE_TYPE_ENCAP_TCP:
- face->type = FACE_TYPE_TCP;
- break;
- case FACE_TYPE_ENCAP_UNDEFINED:
- case FACE_TYPE_ENCAP_N:
- ERROR("[facelet_get_face] Unsupported face encapsulation");
- goto ERR;
- }
-
- if (facelet_get_family(facelet, &face->family) < 0) {
- ERROR("[facelet_get_face] Error retrieving face family");
- goto ERR;
- }
- if (facelet_get_local_addr(facelet, &face->local_addr) < 0) {
- ERROR("[facelet_get_face] Error retrieving face local address");
- goto ERR;
- }
- if (facelet_get_local_port(facelet, &face->local_port) < 0) {
- ERROR("[facelet_get_face] Error retrieving face local port");
- goto ERR;
- }
- if (facelet_get_remote_addr(facelet, &face->remote_addr) < 0) {
- ERROR("[facelet_get_face] Error retrieving face remote address");
- goto ERR;
- }
- if (facelet_get_remote_port(facelet, &face->remote_port) < 0) {
- ERROR("[facelet_get_face] Error retrieving face remote port");
- goto ERR;
- }
- break;
-
- case FACE_TYPE_LAYER_3:
- ERROR("{facelet_get_face] hICN face not (yet) implemented");
- goto ERR;
-
- case FACE_TYPE_LAYER_UNDEFINED:
- case FACE_TYPE_LAYER_N:
- ERROR("[facelet_get_face] Unsupported face type");
- goto ERR;
+ /* Facelet has all the required information to create a face */
+ if (facelet_validate_face(facelet) < 0) {
+ ERROR("[facelet_get_face] Face does not validate");
+ return 0;
+ }
+
+ face_t *face = face_create();
+ if (!face) goto ERR_CREATE;
+
+ assert(facelet_has_netdevice(facelet));
+ face->netdevice = facelet->netdevice;
+
+ /* Face type */
+ switch (facelet->face_type.layer) {
+ case FACE_TYPE_LAYER_4:
+ switch (facelet->face_type.encap) {
+ case FACE_TYPE_ENCAP_UDP:
+ face->type = FACE_TYPE_UDP;
+ break;
+ case FACE_TYPE_ENCAP_TCP:
+ face->type = FACE_TYPE_TCP;
+ break;
+ case FACE_TYPE_ENCAP_UNDEFINED:
+ case FACE_TYPE_ENCAP_N:
+ ERROR("[facelet_get_face] Unsupported face encapsulation");
+ goto ERR;
+ }
+
+ if (facelet_get_family(facelet, &face->family) < 0) {
+ ERROR("[facelet_get_face] Error retrieving face family");
+ goto ERR;
+ }
+ if (facelet_get_local_addr(facelet, &face->local_addr) < 0) {
+ ERROR("[facelet_get_face] Error retrieving face local address");
+ goto ERR;
+ }
+ if (facelet_get_local_port(facelet, &face->local_port) < 0) {
+ ERROR("[facelet_get_face] Error retrieving face local port");
+ goto ERR;
+ }
+ if (facelet_get_remote_addr(facelet, &face->remote_addr) < 0) {
+ ERROR("[facelet_get_face] Error retrieving face remote address");
+ goto ERR;
+ }
+ if (facelet_get_remote_port(facelet, &face->remote_port) < 0) {
+ ERROR("[facelet_get_face] Error retrieving face remote port");
+ goto ERR;
+ }
+ break;
+
+ case FACE_TYPE_LAYER_3:
+ ERROR("{facelet_get_face] hICN face not (yet) implemented");
+ goto ERR;
+
+ case FACE_TYPE_LAYER_UNDEFINED:
+ case FACE_TYPE_LAYER_N:
+ ERROR("[facelet_get_face] Unsupported face type");
+ goto ERR;
+ }
+
+ if (facelet_has_admin_state(facelet)) {
+ if (facelet_get_admin_state(facelet, &face->admin_state) < 0) {
+ ERROR("[facelet_get_face] Error getting face admin state");
+ goto ERR;
}
-
- if (facelet_has_admin_state(facelet)) {
- if (facelet_get_admin_state(facelet, &face->admin_state) < 0) {
- ERROR("[facelet_get_face] Error getting face admin state");
- goto ERR;
- }
- } else {
- face->admin_state = FACE_STATE_UP;
+ } else {
+ face->admin_state = FACE_STATE_UP;
+ }
+
+ if (facelet_has_state(facelet)) {
+ if (facelet_get_state(facelet, &face->state) < 0) {
+ ERROR("[facelet_get_face] Error getting face state");
+ goto ERR;
}
-
- if (facelet_has_state(facelet)) {
- if (facelet_get_state(facelet, &face->state) < 0) {
- ERROR("[facelet_get_face] Error getting face state");
- goto ERR;
- }
- } else {
- face->state = FACE_STATE_UP;
+ } else {
+ face->state = FACE_STATE_UP;
+ }
+
+ /* Priority */
+ if (facelet_has_priority(facelet)) {
+ if (facelet_get_priority(facelet, &face->priority) < 0) {
+ ERROR("[facelet_get_face] Error getting face priority");
+ goto ERR;
}
-
-#ifdef WITH_POLICY
- /* Priority */
- if (facelet_has_priority(facelet)) {
- if (facelet_get_priority(facelet, &face->priority) < 0) {
- ERROR("[facelet_get_face] Error getting face priority");
- goto ERR;
- }
- } else {
- face->priority = 0;
+ } else {
+ face->priority = 0;
+ }
+
+ /* Tags */
+
+ /* - based on netdevice type */
+ policy_tags_t tags = POLICY_TAGS_EMPTY;
+ if (facelet_has_netdevice_type(facelet)) {
+ netdevice_type_t netdevice_type;
+ if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
+ ERROR("error getting netdevice_type");
+ goto ERR;
}
- /* Tags */
-
- /* - based on netdevice type */
- policy_tags_t tags = POLICY_TAGS_EMPTY;
- if (facelet_has_netdevice_type(facelet)) {
- netdevice_type_t netdevice_type;
- if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
- ERROR("error getting netdevice_type");
- goto ERR;
- }
-
-
- switch(netdevice_type) {
- case NETDEVICE_TYPE_UNDEFINED:
- case NETDEVICE_TYPE_LOOPBACK:
- break;
- case NETDEVICE_TYPE_WIRED:
- policy_tags_add(&tags, POLICY_TAG_WIRED);
- break;
- case NETDEVICE_TYPE_WIFI:
- policy_tags_add(&tags, POLICY_TAG_WIFI);
- break;
- case NETDEVICE_TYPE_CELLULAR:
- policy_tags_add(&tags, POLICY_TAG_CELLULAR);
- break;
- default:
- goto ERR;
- }
+ switch (netdevice_type) {
+ case NETDEVICE_TYPE_UNDEFINED:
+ case NETDEVICE_TYPE_LOOPBACK:
+ break;
+ case NETDEVICE_TYPE_WIRED:
+ policy_tags_add(&tags, POLICY_TAG_WIRED);
+ break;
+ case NETDEVICE_TYPE_WIFI:
+ policy_tags_add(&tags, POLICY_TAG_WIFI);
+ break;
+ case NETDEVICE_TYPE_CELLULAR:
+ policy_tags_add(&tags, POLICY_TAG_CELLULAR);
+ break;
+ default:
+ goto ERR;
}
- face->tags = tags;
-#endif /* WITH_POLICY */
+ }
+ face->tags = tags;
- *pface = face;
+ *pface = face;
- return 0;
+ return 0;
ERR:
- free(face);
+ free(face);
ERR_CREATE:
- *pface = NULL;
- return -1;
+ *pface = NULL;
+ return -1;
}
-facelet_status_t
-facelet_get_status(const facelet_t * facelet)
-{
- return facelet->status;
+facelet_status_t facelet_get_status(const facelet_t *facelet) {
+ return facelet->status;
}
-void
-facelet_set_status(facelet_t * facelet, facelet_status_t status)
-{
- facelet->status = status;
+void facelet_set_status(facelet_t *facelet, facelet_status_t status) {
+ facelet->status = status;
}
-#define SET_ATTR_STATUS_CLEAN(TYPE, NAME) \
-do { \
- if (facelet->NAME ## _status == FACELET_ATTR_STATUS_DIRTY) \
- facelet->NAME ## _status = FACELET_ATTR_STATUS_CLEAN; \
-} while (0)
+#define SET_ATTR_STATUS_CLEAN(TYPE, NAME) \
+ do { \
+ if (facelet->NAME##_status == FACELET_ATTR_STATUS_DIRTY) \
+ facelet->NAME##_status = FACELET_ATTR_STATUS_CLEAN; \
+ } while (0)
-void
-facelet_set_attr_clean(facelet_t * facelet)
-{
+void facelet_set_attr_clean(facelet_t *facelet) {
#define _(TYPE, NAME) SET_ATTR_STATUS_CLEAN(TYPE, NAME);
- foreach_facelet_attr
+ foreach_facelet_attr
#undef _
}
-void
-facelet_set_error(facelet_t * facelet, facelet_error_reason_t reason)
-{
- facelet->error++;
- switch(reason) {
- case FACELET_ERROR_REASON_UNSPECIFIED_ERROR:
- case FACELET_ERROR_REASON_INTERNAL_ERROR:
- case FACELET_ERROR_REASON_PERMISSION_DENIED:
- if (facelet->error >= FACELET_MAX_ERRORS)
- facelet_set_status(facelet, FACELET_STATUS_IGNORED);
- break;
- case FACELET_ERROR_REASON_FORWARDER_OFFLINE:
- break;
- case FACELET_ERROR_REASON_UNDEFINED:
- case FACELET_ERROR_REASON_N:
- ERROR("facelet_set_error] Unexpected error reason");
- break;
- }
+void facelet_set_error(facelet_t *facelet, facelet_error_reason_t reason) {
+ facelet->error++;
+ switch (reason) {
+ case FACELET_ERROR_REASON_UNSPECIFIED_ERROR:
+ case FACELET_ERROR_REASON_INTERNAL_ERROR:
+ case FACELET_ERROR_REASON_PERMISSION_DENIED:
+ if (facelet->error >= FACELET_MAX_ERRORS)
+ facelet_set_status(facelet, FACELET_STATUS_IGNORED);
+ break;
+ case FACELET_ERROR_REASON_FORWARDER_OFFLINE:
+ break;
+ case FACELET_ERROR_REASON_UNDEFINED:
+ case FACELET_ERROR_REASON_N:
+ ERROR("facelet_set_error] Unexpected error reason");
+ break;
+ }
}
-void
-facelet_unset_error(facelet_t * facelet)
-{
- facelet->error = 0;
-}
+void facelet_unset_error(facelet_t *facelet) { facelet->error = 0; }
-bool
-facelet_get_error(const facelet_t * facelet)
-{
- return facelet->error;
-}
+bool facelet_get_error(const facelet_t *facelet) { return facelet->error; }
-void
-facelet_set_bj_done(facelet_t * facelet)
-{
- facelet->bj_done = true;
-}
+void facelet_set_bj_done(facelet_t *facelet) { facelet->bj_done = true; }
-void
-facelet_unset_bj_done(facelet_t * facelet)
-{
- facelet->bj_done = false;
-}
+void facelet_unset_bj_done(facelet_t *facelet) { facelet->bj_done = false; }
-bool
-facelet_is_bj_done(const facelet_t * facelet)
-{
- return facelet->bj_done;
-}
+bool facelet_is_bj_done(const facelet_t *facelet) { return facelet->bj_done; }
-void
-facelet_set_au_done(facelet_t * facelet)
-{
- facelet->au_done = true;
+facelet_event_t facelet_get_event(const facelet_t *facelet) {
+ return facelet->event;
}
-bool
-facelet_is_au_done(const facelet_t * facelet)
-{
- return facelet->au_done;
+void facelet_set_event(facelet_t *facelet, facelet_event_t event) {
+ facelet->event = event;
}
-facelet_event_t
-facelet_get_event(const facelet_t * facelet)
-{
- return facelet->event;
+int facelet_add_route(facelet_t *facelet, hicn_route_t *route) {
+ return route_set_add(facelet->routes, route);
}
-void
-facelet_set_event(facelet_t * facelet, facelet_event_t event)
-{
- facelet->event = event;
+int facelet_remove_route(facelet_t *facelet, hicn_route_t *route,
+ hicn_route_t **route_removed) {
+ return route_set_remove(facelet->routes, route, route_removed);
}
-int
-facelet_add_route(facelet_t * facelet, hicn_route_t * route)
-{
- return route_set_add(facelet->routes, route);
+int facelet_clear_routes(facelet_t *facelet) {
+ return route_set_clear(facelet->routes);
}
-int
-facelet_remove_route(facelet_t * facelet, hicn_route_t * route, hicn_route_t ** route_removed)
-{
- return route_set_remove(facelet->routes, route, route_removed);
+int facelet_get_route_array(const facelet_t *facelet,
+ hicn_route_t ***route_array) {
+ return route_set_get_array(facelet->routes, route_array);
}
-int
-facelet_clear_routes(facelet_t * facelet)
-{
- return route_set_clear(facelet->routes);
-}
-
-int
-facelet_get_route_array(const facelet_t * facelet, hicn_route_t *** route_array)
-{
- return route_set_get_array(facelet->routes, route_array);
-}
+int facelet_snprintf(char *s, size_t size, const facelet_t *facelet) {
+ char *cur = s;
+ int rc;
+
+ assert(facelet);
+
+ /* Header + key attributes (netdevice + family) */
+ rc = snprintf(cur, s + size - cur, "<Facelet [%d] %s %s (%s)", facelet->id,
+ facelet_status_str[facelet->status],
+ facelet_get_error(facelet) ? "/!\\" : "",
+ (facelet->family == AF_INET) ? "AF_INET"
+ : (facelet->family == AF_INET6) ? "AF_INET6"
+ : (facelet->family == AF_UNSPEC) ? "AF_UNSPEC"
+ : "unknown");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ /* Netdevice */
+ if (facelet_has_netdevice(facelet)) {
+ rc = snprintf(cur, s + size - cur, " netdevice=%s",
+ facelet->netdevice.name[0] ? facelet->netdevice.name : "*");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
-int
-facelet_snprintf(char * s, size_t size, const facelet_t * facelet)
-{
- char * cur = s;
- int rc;
-
- assert(facelet);
-
- /* Header + key attributes (netdevice + family) */
- rc = snprintf(cur, s + size - cur, "<Facelet [%d] %s %s (%s)",
- facelet->id,
- facelet_status_str[facelet->status],
- facelet_get_error(facelet) ? "/!\\" : "",
- (facelet->family == AF_INET) ? "AF_INET" :
- (facelet->family == AF_INET6) ? "AF_INET6" :
- (facelet->family == AF_UNSPEC) ? "AF_UNSPEC" :
- "unknown");
- if (rc < 0)
- return rc;
+ rc = snprintf(cur, s + size - cur, "/%d", facelet->netdevice.index);
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- /* Netdevice */
- if (facelet_has_netdevice(facelet)) {
- rc = snprintf(cur, s + size - cur, " netdevice=%s",
- facelet->netdevice.name[0] ? facelet->netdevice.name : "*");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = snprintf(cur, s + size - cur, "/%d", facelet->netdevice.index);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
+ if (cur >= s + size) return (int)(cur - s);
- } else {
- rc = snprintf(cur, s + size - cur, " netdevice=*/*");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ } else {
+ rc = snprintf(cur, s + size - cur, " netdevice=*/*");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Netdevice type */
+ if (facelet_has_netdevice_type(facelet)) {
+ rc = snprintf(cur, s + size - cur, " type=%s",
+ netdevice_type_str(facelet->netdevice_type));
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
- /* Netdevice type */
- if (facelet_has_netdevice_type(facelet)) {
- rc = snprintf(cur, s + size - cur, " type=%s",
- netdevice_type_str[facelet->netdevice_type]);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ /* Local ip address */
+ if (facelet_has_local_addr(facelet)) {
+ rc = snprintf(cur, s + size - cur, " local_addr=");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
- /* Local ip address */
- if (facelet_has_local_addr(facelet)) {
- rc = snprintf(cur, s + size - cur, " local_addr=");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = ip_address_snprintf(cur, s + size - cur, &facelet->local_addr,
- facelet->family);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ rc = hicn_ip_address_snprintf(cur, s + size - cur, &facelet->local_addr);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
- /* Local port */
- if (facelet_has_local_port(facelet)) {
- rc = snprintf(cur, s + size - cur, " local_port=%d",
- facelet->local_port);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ /* Local port */
+ if (facelet_has_local_port(facelet)) {
+ rc = snprintf(cur, s + size - cur, " local_port=%d", facelet->local_port);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
- /* Remote ip address */
- if (facelet_has_remote_addr(facelet)) {
- rc = snprintf(cur, s + size - cur, " remote_addr=");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = ip_address_snprintf(cur, s + size - cur, &facelet->remote_addr,
- facelet->family);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ /* Remote ip address */
+ if (facelet_has_remote_addr(facelet)) {
+ rc = snprintf(cur, s + size - cur, " remote_addr=");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
- /* Remote port */
- if (facelet_has_remote_port(facelet)) {
- rc = snprintf(cur, s + size - cur, " remote_port=%d",
- facelet->remote_port);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ rc = hicn_ip_address_snprintf(cur, s + size - cur, &facelet->remote_addr);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
- /* Admin state */
- if (facelet_has_admin_state(facelet)) {
- rc = snprintf(cur, s + size - cur, " admin_state=%s",
- face_state_str[facelet->admin_state]);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ /* Remote port */
+ if (facelet_has_remote_port(facelet)) {
+ rc = snprintf(cur, s + size - cur, " remote_port=%d", facelet->remote_port);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Admin state */
+ if (facelet_has_admin_state(facelet)) {
+ rc = snprintf(cur, s + size - cur, " admin_state=%s",
+ face_state_str(facelet->admin_state));
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* State */
+ if (facelet_has_state(facelet)) {
+ rc = snprintf(cur, s + size - cur, " state=%s",
+ face_state_str(facelet->state));
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
- /* State */
- if (facelet_has_state(facelet)) {
- rc = snprintf(cur, s + size - cur, " state=%s",
- face_state_str[facelet->state]);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
+ /* Priority */
+ if (facelet_has_priority(facelet)) {
+ rc = snprintf(cur, s + size - cur, " priority=%d", facelet->priority);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Face type */
+ if (facelet_has_face_type(facelet)) {
+ rc = snprintf(cur, s + size - cur, " face_type=LAYER%s/%s",
+ FACEMGR_FACE_TYPE_STR(facelet->face_type));
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Routes */
+ rc = snprintf(cur, s + size - cur, " routes={ ");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ hicn_route_t **route_array;
+ int n = route_set_get_array(facelet->routes, &route_array);
+ if (n < 0) {
+ ERROR("[facelet_free] Error getting route set associated to facelet");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ hicn_route_t *route = route_array[i];
+ if (!route) continue; /* Should not occur */
+ rc = (int)hicn_route_snprintf(cur, s + size - cur, route);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ rc = snprintf(cur, s + size - cur, ", ");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
}
+ }
+ free(route_array);
-#ifdef WITH_POLICY
- /* Priority */
- if (facelet_has_priority(facelet)) {
- rc = snprintf(cur, s + size - cur, " priority=%d", facelet->priority);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-#endif /* WITH_POLICY */
-
- /* Face type */
- if (facelet_has_face_type(facelet)) {
- rc = snprintf(cur, s + size - cur, " face_type=LAYER%s/%s",
- FACEMGR_FACE_TYPE_STR(facelet->face_type));
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
+ rc = snprintf(cur, s + size - cur, "}>");
+ if (rc < 0) return rc;
+ cur += rc;
+ return (int)(cur - s);
+}
- /* Routes */
- rc = snprintf(cur, s + size - cur, " routes={ ");
- if (rc < 0)
- return rc;
+int facelet_snprintf_json(char *s, size_t size, const facelet_t *facelet,
+ int indent) {
+ char *cur = s;
+ int rc;
+
+ assert(facelet);
+
+ /* Header + key attributes (netdevice + family) */
+ rc = snprintf(cur, s + size - cur, "%*s%s", 4 * indent, "", "{\n");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ /* id */
+ rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent + 1), "",
+ "\"id\"", facelet->id);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ /* Status */
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent + 1), "",
+ "\"status\"", facelet_status_str[facelet->status]);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ /* Family */
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent + 1), "",
+ "\"family\"",
+ (facelet->family == AF_INET) ? "AF_INET"
+ : (facelet->family == AF_INET6) ? "AF_INET6"
+ : (facelet->family == AF_UNSPEC) ? "AF_UNSPEC"
+ : "unknown");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ /* Netdevice */
+ if (facelet_has_netdevice(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent + 1), "",
+ "\"netdevice\"",
+ facelet->netdevice.name[0] ? facelet->netdevice.name : "*");
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- hicn_route_t ** route_array;
- int n = route_set_get_array(facelet->routes, &route_array);
- if (n < 0) {
- ERROR("[facelet_free] Error getting route set associated to facelet");
- } else {
- for (unsigned i = 0; i < n; i++) {
- hicn_route_t * route = route_array[i];
- rc = (int)hicn_route_snprintf(cur, s + size - cur, route);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = snprintf(cur, s + size - cur, ", ");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
- }
- free(route_array);
+ if (cur >= s + size) return (int)(cur - s);
- rc = snprintf(cur, s + size - cur, "}>");
- if (rc < 0)
- return rc;
+ } else {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent + 1), "",
+ "\"netdevice\"", "*");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Netdevice type */
+ if (facelet_has_netdevice_type(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent + 1), "",
+ "\"netdevice_type\"",
+ netdevice_type_str(facelet->netdevice_type));
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Local ip address */
+ if (facelet_has_local_addr(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"", 4 * (indent + 1), "",
+ "\"local_addr\"");
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
+ if (cur >= s + size) return (int)(cur - s);
- return (int)(cur - s);
-}
+ rc = hicn_ip_address_snprintf(cur, s + size - cur, &facelet->local_addr);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
-int facelet_snprintf_json(char * s, size_t size, const facelet_t * facelet, int indent)
-{
- char * cur = s;
- int rc;
+ rc = snprintf(cur, s + size - cur, "\",\n");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Local port */
+ if (facelet_has_local_port(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent + 1), "",
+ "\"local_port\"", facelet->local_port);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Remote ip address */
+ if (facelet_has_remote_addr(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"", 4 * (indent + 1), "",
+ "\"remote_addr\"");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
- assert(facelet);
+ rc = hicn_ip_address_snprintf(cur, s + size - cur, &facelet->remote_addr);
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
- /* Header + key attributes (netdevice + family) */
- rc = snprintf(cur, s + size - cur, "%*s%s", 4 * indent, "", "{\n");
- if (rc < 0)
- return rc;
+ rc = snprintf(cur, s + size - cur, "\",\n");
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- /* id */
- rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent+1), "", "\"id\"",
- facelet->id);
- if (rc < 0)
- return rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Remote port */
+ if (facelet_has_remote_port(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent + 1), "",
+ "\"remote_port\"", facelet->remote_port);
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- /* Status */
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent+1), "", "\"status\"",
- facelet_status_str[facelet->status]);
- if (rc < 0)
- return rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Admin state */
+ if (facelet_has_admin_state(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent + 1), "",
+ "\"admin_state\"", face_state_str(facelet->admin_state));
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- /* Family */
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent+1), "", "\"family\"",
- (facelet->family == AF_INET) ? "AF_INET" :
- (facelet->family == AF_INET6) ? "AF_INET6" :
- (facelet->family == AF_UNSPEC) ? "AF_UNSPEC" :
- "unknown");
- if (rc < 0)
- return rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* State */
+ if (facelet_has_state(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent + 1), "",
+ "\"state\"", face_state_str(facelet->state));
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- /* Netdevice */
- if (facelet_has_netdevice(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent+1), "",
- "\"netdevice\"",
- facelet->netdevice.name[0] ? facelet->netdevice.name : "*");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- } else {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent+1), "",
- "\"netdevice\"", "*");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* Netdevice type */
- if (facelet_has_netdevice_type(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent+1), "",
- "\"netdevice_type\"",
- netdevice_type_str[facelet->netdevice_type]);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* Local ip address */
- if (facelet_has_local_addr(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"", 4 * (indent+1), "",
- "\"local_addr\"");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = ip_address_snprintf(cur, s + size - cur, &facelet->local_addr,
- facelet->family);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = snprintf(cur, s + size - cur, "\",\n");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* Local port */
- if (facelet_has_local_port(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent+1), "",
- "\"local_port\"",
- facelet->local_port);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* Remote ip address */
- if (facelet_has_remote_addr(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"", 4 * (indent+1), "",
- "\"remote_addr\"");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = ip_address_snprintf(cur, s + size - cur, &facelet->remote_addr,
- facelet->family);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- rc = snprintf(cur, s + size - cur, "\",\n");
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* Remote port */
- if (facelet_has_remote_port(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent+1), "",
- "\"remote_port\"",
- facelet->remote_port);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* Admin state */
- if (facelet_has_admin_state(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent+1), "",
- "\"admin_state\"",
- face_state_str[facelet->admin_state]);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* State */
- if (facelet_has_state(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\",\n", 4 * (indent+1), "",
- "\"state\"",
- face_state_str[facelet->state]);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
-#ifdef WITH_POLICY
- /* Priority */
- if (facelet_has_priority(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent+1), "",
- "\"priority\"", facelet->priority);
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-#endif /* WITH_POLICY */
-
- if (facelet_has_face_type(facelet)) {
- rc = snprintf(cur, s + size - cur, "%*s%s: \"LAYER%s/%s\",\n", 4 * (indent+1), "",
- "\"face_type\"",
- FACEMGR_FACE_TYPE_STR(facelet->face_type));
- if (rc < 0)
- return rc;
- cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
- }
-
- /* Status error */
- rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\"\n", 4 * (indent+1), "",
- "\"error\"",
- facelet_get_error(facelet) ? "true" : "false");
- if (rc < 0)
- return rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Priority */
+ if (facelet_has_priority(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: %d,\n", 4 * (indent + 1), "",
+ "\"priority\"", facelet->priority);
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- /* Routes */
- // TODO
-
- rc = snprintf(cur, s + size - cur, "%*s%s", 4 * indent, "", "}");
- if (rc < 0)
- return rc;
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ if (facelet_has_face_type(facelet)) {
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"LAYER%s/%s\",\n",
+ 4 * (indent + 1), "", "\"face_type\"",
+ FACEMGR_FACE_TYPE_STR(facelet->face_type));
+ if (rc < 0) return rc;
cur += rc;
- if (cur >= s + size)
- return (int)(cur - s);
-
- return (int)(cur - s);
+ if (cur >= s + size) return (int)(cur - s);
+ }
+
+ /* Status error */
+ rc = snprintf(cur, s + size - cur, "%*s%s: \"%s\"\n", 4 * (indent + 1), "",
+ "\"error\"", facelet_get_error(facelet) ? "true" : "false");
+ if (rc < 0) return rc;
+ cur += rc;
+ if (cur >= s + size) return (int)(cur - s);
+
+ /* Routes */
+ // TODO
+
+ rc = snprintf(cur, s + size - cur, "%*s%s", 4 * indent, "", "}");
+ if (rc < 0) return rc;
+ cur += rc;
+ return (int)(cur - s);
}
diff --git a/ctrl/facemgr/src/facelet_array.c b/ctrl/facemgr/src/facelet_array.c
index 3ee110b8e..d48625979 100644
--- a/ctrl/facemgr/src/facelet_array.c
+++ b/ctrl/facemgr/src/facelet_array.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,4 +23,3 @@
#include "facelet_array.h"
TYPEDEF_ARRAY(facelet_array, facelet_t *, facelet_equals, facelet_snprintf);
-
diff --git a/ctrl/facemgr/src/facelet_array.h b/ctrl/facemgr/src/facelet_array.h
index 099774691..b3b17e88b 100644
--- a/ctrl/facemgr/src/facelet_array.h
+++ b/ctrl/facemgr/src/facelet_array.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/src/interface.c b/ctrl/facemgr/src/interface.c
index 7f95be4ce..a9aeeaf33 100644
--- a/ctrl/facemgr/src/interface.c
+++ b/ctrl/facemgr/src/interface.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,170 +29,144 @@
#include "interface.h"
TYPEDEF_MAP_H(interface_ops_map, const char *, const interface_ops_t *);
-TYPEDEF_MAP(interface_ops_map, const char *, const interface_ops_t *, strcmp, string_snprintf, generic_snprintf);
-
-static interface_ops_map_t * interface_ops_map = NULL;
-
-int
-interface_register(const interface_ops_t * ops)
-{
- if (!interface_ops_map) {
- interface_ops_map = interface_ops_map_create();
- if (!interface_ops_map)
- return -1;
- }
- interface_ops_map_add(interface_ops_map, ops->type, ops);
- return 0;
+TYPEDEF_MAP(interface_ops_map, const char *, const interface_ops_t *, strcmp,
+ string_snprintf, generic_snprintf);
+
+static interface_ops_map_t *interface_ops_map = NULL;
+
+int interface_register(const interface_ops_t *ops) {
+ if (!interface_ops_map) {
+ interface_ops_map = interface_ops_map_create();
+ if (!interface_ops_map) return -1;
+ }
+ interface_ops_map_add(interface_ops_map, ops->type, ops);
+ return 0;
}
-int
-interface_unregister_all()
-{
- int ret = 0;
- const char ** ops_name_array = NULL;
- int n = interface_ops_map_get_key_array(interface_ops_map, &ops_name_array);
- if (n < 0) {
- ERROR("[interface_unregister_all] Could not get interface ops array");
- return -1;
- }
-
- for (unsigned i = 0; i < n; i++) {
- const char * ops_name = ops_name_array[i];
- if (interface_ops_map_remove(interface_ops_map, ops_name, NULL) < 0) {
- ERROR("[interface_unregister_all] Could not remove %s from interface ops map", ops_name);
- ret = -1;
- }
+int interface_unregister_all() {
+ int ret = 0;
+ const char **ops_name_array = NULL;
+ int n = interface_ops_map_get_key_array(interface_ops_map, &ops_name_array);
+ if (n < 0) {
+ ERROR("[interface_unregister_all] Could not get interface ops array");
+ return -1;
+ }
+
+ for (unsigned i = 0; i < n; i++) {
+ const char *ops_name = ops_name_array[i];
+ if (interface_ops_map_remove(interface_ops_map, ops_name, NULL) < 0) {
+ ERROR(
+ "[interface_unregister_all] Could not remove %s from interface ops "
+ "map",
+ ops_name);
+ ret = -1;
}
- free(ops_name_array);
+ }
+ free(ops_name_array);
- interface_ops_map_free(interface_ops_map);
- interface_ops_map = NULL;
+ interface_ops_map_free(interface_ops_map);
+ interface_ops_map = NULL;
- return ret;
+ return ret;
}
-interface_t *
-interface_create(const char * name, const char * type)
-{
-
- const interface_ops_t * ops = NULL;
- int rc = interface_ops_map_get(interface_ops_map, type, &ops);
- if (rc < 0) {
- printf("Interface type not found %s\n", type);
- return NULL;
- }
-
- interface_t * interface = malloc(sizeof(interface_t));
- if (!interface)
- return NULL;
-
- interface->name = strdup(name);
- /* this should use type */
- interface->ops = ops;
- interface->callback = NULL;
- interface->callback_owner = NULL;
- interface->data = NULL;
-
- return interface;
+interface_t *interface_create(const char *name, const char *type) {
+ const interface_ops_t *ops = NULL;
+ int rc = interface_ops_map_get(interface_ops_map, type, &ops);
+ if (rc < 0) {
+ printf("Interface type not found %s\n", type);
+ return NULL;
+ }
+
+ interface_t *interface = malloc(sizeof(interface_t));
+ if (!interface) return NULL;
+
+ interface->name = strdup(name);
+ /* this should use type */
+ interface->ops = ops;
+ interface->callback = NULL;
+ interface->callback_owner = NULL;
+ interface->data = NULL;
+
+ return interface;
}
-void
-interface_free(interface_t * interface)
-{
- free(interface->name);
- free(interface);
+void interface_free(interface_t *interface) {
+ free(interface->name);
+ free(interface);
}
-void
-interface_set_callback(interface_t * interface, void * callback_owner,
- interface_cb_t callback)
-{
- interface->callback = callback;
- interface->callback_owner = callback_owner;
+void interface_set_callback(interface_t *interface, void *callback_owner,
+ interface_cb_t callback) {
+ interface->callback = callback;
+ interface->callback_owner = callback_owner;
}
-int
-interface_initialize(interface_t * interface, void * cfg)
-{
- if (!interface->ops->initialize)
- return -1;
- return interface->ops->initialize(interface, cfg);
+int interface_initialize(interface_t *interface, void *cfg) {
+ if (!interface->ops->initialize) return -1;
+ return interface->ops->initialize(interface, cfg);
}
-int
-interface_finalize(interface_t * interface)
-{
- if (!interface->ops->finalize)
- return -1;
- return interface->ops->finalize(interface);
+int interface_finalize(interface_t *interface) {
+ if (!interface->ops->finalize) return -1;
+ return interface->ops->finalize(interface);
}
-int
-interface_on_event(interface_t * interface, facelet_t * facelet)
-{
- if (!interface->ops->on_event)
- return -1;
- return interface->ops->on_event(interface, facelet);
+int interface_on_event(interface_t *interface, facelet_t *facelet) {
+ if (!interface->ops->on_event) return -1;
+ return interface->ops->on_event(interface, facelet);
}
-int
-interface_raise_event(interface_t * interface, facelet_t * facelet)
-{
- assert(interface->callback);
- return interface->callback(interface->callback_owner,
- INTERFACE_CB_TYPE_RAISE_EVENT, facelet);
+int interface_raise_event(interface_t *interface, facelet_t *facelet) {
+ assert(interface->callback);
+ return interface->callback(interface->callback_owner,
+ INTERFACE_CB_TYPE_RAISE_EVENT, facelet);
}
-int
-interface_register_fd(interface_t * interface, int fd, void * data)
-{
- assert(interface->callback);
- fd_callback_data_t fd_callback = {
- .fd = fd,
- .owner = interface,
- .callback = (fd_callback_t)interface->ops->callback,
- .data = data,
- };
- return interface->callback(interface->callback_owner,
- INTERFACE_CB_TYPE_REGISTER_FD, &fd_callback);
+int interface_register_fd(interface_t *interface, int fd, void *data) {
+ assert(interface->callback);
+ fd_callback_data_t fd_callback = {
+ .fd = fd,
+ .owner = interface,
+ .callback = (fd_callback_t)interface->ops->callback,
+ .data = data,
+ };
+ return interface->callback(interface->callback_owner,
+ INTERFACE_CB_TYPE_REGISTER_FD, &fd_callback);
}
-int
-interface_unregister_fd(interface_t * interface, int fd)
-{
- assert(interface->callback);
- fd_callback_data_t fd_callback = {
- .fd = fd,
- .owner = interface,
- .callback = NULL,
- .data = NULL,
- };
- return interface->callback(interface->callback_owner,
- INTERFACE_CB_TYPE_UNREGISTER_FD, &fd_callback);
+int interface_unregister_fd(interface_t *interface, int fd) {
+ assert(interface->callback);
+ fd_callback_data_t fd_callback = {
+ .fd = fd,
+ .owner = interface,
+ .callback = NULL,
+ .data = NULL,
+ };
+ return interface->callback(interface->callback_owner,
+ INTERFACE_CB_TYPE_UNREGISTER_FD, &fd_callback);
}
-typedef int (*interface_fd_callback_t)(interface_t * interface, int fd, void * unused);
-
-int
-interface_register_timer(interface_t * interface, unsigned delay_ms,
- interface_fd_callback_t callback, void * data)
-{
- assert(interface->callback);
- timer_callback_data_t timer_callback = {
- .delay_ms = delay_ms,
- .owner = interface,
- .callback = (fd_callback_t)callback,
- .data = data,
- };
- int rc = interface->callback(interface->callback_owner,
- INTERFACE_CB_TYPE_REGISTER_TIMER, &timer_callback);
- return rc;
+typedef int (*interface_fd_callback_t)(interface_t *interface, int fd,
+ void *unused);
+
+int interface_register_timer(interface_t *interface, unsigned delay_ms,
+ interface_fd_callback_t callback, void *data) {
+ assert(interface->callback);
+ timer_callback_data_t timer_callback = {
+ .delay_ms = delay_ms,
+ .owner = interface,
+ .callback = (fd_callback_t)callback,
+ .data = data,
+ };
+ int rc =
+ interface->callback(interface->callback_owner,
+ INTERFACE_CB_TYPE_REGISTER_TIMER, &timer_callback);
+ return rc;
}
-int
-interface_unregister_timer(interface_t * interface, int fd)
-{
- assert(interface->callback);
- return interface->callback(interface->callback_owner,
- INTERFACE_CB_TYPE_UNREGISTER_TIMER, &fd);
+int interface_unregister_timer(interface_t *interface, int fd) {
+ assert(interface->callback);
+ return interface->callback(interface->callback_owner,
+ INTERFACE_CB_TYPE_UNREGISTER_TIMER, &fd);
}
diff --git a/ctrl/facemgr/src/interface.h b/ctrl/facemgr/src/interface.h
index a4fbda1fb..a999036d5 100644
--- a/ctrl/facemgr/src/interface.h
+++ b/ctrl/facemgr/src/interface.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -32,40 +32,41 @@
#include <hicn/facemgr/loop.h>
typedef enum {
- INTERFACE_CB_TYPE_REGISTER_FD,
- INTERFACE_CB_TYPE_UNREGISTER_FD,
- INTERFACE_CB_TYPE_RAISE_EVENT,
- INTERFACE_CB_TYPE_REGISTER_TIMER,
- INTERFACE_CB_TYPE_UNREGISTER_TIMER,
+ INTERFACE_CB_TYPE_REGISTER_FD,
+ INTERFACE_CB_TYPE_UNREGISTER_FD,
+ INTERFACE_CB_TYPE_RAISE_EVENT,
+ INTERFACE_CB_TYPE_REGISTER_TIMER,
+ INTERFACE_CB_TYPE_UNREGISTER_TIMER,
} interface_cb_type_t;
-typedef int (*interface_cb_t)(facemgr_t * facemgr, interface_cb_type_t type, void * data);
+typedef int (*interface_cb_t)(facemgr_t* facemgr, interface_cb_type_t type,
+ void* data);
/**
* \brief Interface operations
*/
struct interface_s;
typedef struct {
- /** The type given to the interfaces */
- char * type;
- /* Constructor */
- int (*initialize)(struct interface_s * interface, void * cfg);
- /* Destructor */
- int (*finalize)(struct interface_s * interface);
- /* Callback upon file descriptor event (iif previously registered) */
- int (*callback)(struct interface_s * interface, int fd, void * data);
- /* Callback upon face events coming from the face manager */
- int (*on_event)(struct interface_s * interface, struct facelet_s * facelet);
+ /** The type given to the interfaces */
+ char* type;
+ /* Constructor */
+ int (*initialize)(struct interface_s* interface, void* cfg);
+ /* Destructor */
+ int (*finalize)(struct interface_s* interface);
+ /* Callback upon file descriptor event (iif previously registered) */
+ int (*callback)(struct interface_s* interface, int fd, void* data);
+ /* Callback upon face events coming from the face manager */
+ int (*on_event)(struct interface_s* interface, struct facelet_s* facelet);
} interface_ops_t;
typedef struct interface_s {
- char * name;
- const interface_ops_t * ops;
+ char* name;
+ const interface_ops_t* ops;
- interface_cb_t callback;
- void * callback_owner;
+ interface_cb_t callback;
+ void* callback_owner;
- void * data;
+ void* data;
} interface_t;
/**
@@ -75,7 +76,7 @@ typedef struct interface_s {
* \return Flag indicating the success (FACEMGR_SUCCESS=0), or failure (any
* other value) of the operation.
*/
-int interface_register(const interface_ops_t * ops);
+int interface_register(const interface_ops_t* ops);
int interface_unregister_all();
@@ -91,22 +92,22 @@ int interface_unregister_all();
* \return A a pointer to the newly created instance of the requested type, or
* NULL in case of failure.
*/
-interface_t * interface_create(const char * name, const char * type);
+interface_t* interface_create(const char* name, const char* type);
/**
* \brief Free an interface instance.
* \param [in] interface - Pointer to the instance to free.
*/
-void interface_free(interface_t * interface);
+void interface_free(interface_t* interface);
+void interface_set_callback(interface_t* interface, void* callback_owner,
+ interface_cb_t callback);
-void interface_set_callback(interface_t * interface, void * callback_owner, interface_cb_t callback);
+int interface_initialize(interface_t* interface, void* cfg);
-int interface_initialize(interface_t * interface, void * cfg);
+int interface_finalize(interface_t* interface);
-int interface_finalize(interface_t * interface);
-
-int interface_on_event(interface_t * interface, struct facelet_s * facelet);
+int interface_on_event(interface_t* interface, struct facelet_s* facelet);
/**
* \brief Raises a facelet event to the face manager
@@ -115,15 +116,17 @@ int interface_on_event(interface_t * interface, struct facelet_s * facelet);
* \param [in] facelet - Facelet to communicate with the event
* \return Error code
*/
-int interface_callback(interface_t * interface, interface_cb_type_t type, void * data);
+int interface_callback(interface_t* interface, interface_cb_type_t type,
+ void* data);
-int interface_raise_event(interface_t * interface, facelet_t * facelet);
+int interface_raise_event(interface_t* interface, facelet_t* facelet);
-int interface_register_fd(interface_t * interface, int fd, void * data);
+int interface_register_fd(interface_t* interface, int fd, void* data);
-int interface_unregister_fd(interface_t * interface, int fd);
+int interface_unregister_fd(interface_t* interface, int fd);
-typedef int (*interface_fd_callback_t)(interface_t * interface, int fd, void * unused);
+typedef int (*interface_fd_callback_t)(interface_t* interface, int fd,
+ void* unused);
/**
* \brief Registers a timer event
@@ -135,8 +138,8 @@ typedef int (*interface_fd_callback_t)(interface_t * interface, int fd, void * u
* \return A positive value uniquely identifying the timer, or -1 in case of
* error
*/
-int interface_register_timer(interface_t * interface, unsigned delay_ms,
- interface_fd_callback_t callback, void * data);
+int interface_register_timer(interface_t* interface, unsigned delay_ms,
+ interface_fd_callback_t callback, void* data);
/**
* \brief Unregisters a timer event
@@ -144,6 +147,6 @@ int interface_register_timer(interface_t * interface, unsigned delay_ms,
* \param [in] fd - Timer identifier
* \return 0 in case of success, -1 otherwise
*/
-int interface_unregister_timer(interface_t * interface, int fd);
+int interface_unregister_timer(interface_t* interface, int fd);
#endif /* FACEMGR_INTERFACE_H */
diff --git a/ctrl/facemgr/src/interfaces/CMakeLists.txt b/ctrl/facemgr/src/interfaces/CMakeLists.txt
index e4d4423e9..02fb0eb48 100644
--- a/ctrl/facemgr/src/interfaces/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -16,28 +16,33 @@ list(APPEND SOURCE_FILES)
list(APPEND INCLUDE_DIRS)
list(APPEND LIBRARIES)
+
+##############################################################
+# Add components
+##############################################################
add_subdirectory(hicn_light)
if(APPLE)
-add_subdirectory(network_framework)
+ add_subdirectory(network_framework)
endif()
if(LINUX)
-add_subdirectory(netlink)
-add_subdirectory(bonjour)
-endif()
-
-if(ANDROID)
-add_subdirectory(android_utility)
-add_subdirectory(priority_controller)
+ if(ANDROID)
+ add_subdirectory(android)
+ add_subdirectory(priority_controller)
+ else()
+ add_subdirectory(netlink)
+ endif()
+
+ add_subdirectory(bonjour)
endif()
if(WITH_EXAMPLE_DUMMY)
-add_subdirectory(dummy)
+ add_subdirectory(dummy)
endif()
if(WITH_EXAMPLE_UPDOWN)
-add_subdirectory(updown)
+ add_subdirectory(updown)
endif()
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
diff --git a/ctrl/facemgr/src/interfaces/android_utility/CMakeLists.txt b/ctrl/facemgr/src/interfaces/android/CMakeLists.txt
index 0ebe87745..beabc1280 100644
--- a/ctrl/facemgr/src/interfaces/android_utility/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/android/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,16 +11,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/android_utility.c
+list(APPEND HEADER_FILES
)
-list(APPEND INCLUDE_DIRS
+list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/android.c
)
list(APPEND LIBRARIES
)
+list(APPEND INCLUDE_DIRS
+)
+
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
set(INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE)
diff --git a/ctrl/facemgr/src/interfaces/android/android.c b/ctrl/facemgr/src/interfaces/android/android.c
new file mode 100644
index 000000000..578e7472a
--- /dev/null
+++ b/ctrl/facemgr/src/interfaces/android/android.c
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file interfaces/android/android.c
+ * \brief Netlink interface
+ */
+
+#include <assert.h>
+#include <pthread.h>
+#include <sys/eventfd.h>
+#include <unistd.h> // close
+
+#include <hicn/facemgr.h>
+#include <hicn/util/ip_address.h>
+#include <hicn/util/log.h>
+
+#include "../../common.h"
+#include "../../interface.h"
+#include "../../facelet_array.h"
+
+#include "android.h"
+
+/*
+ * aar_modules/FaceMgrLibrary/facemgrLibrary/src/main/java/com/cisco/hicn/facemgrlibrary/supportlibrary/FacemgrUtility.java
+ */
+#define FACEMGR_ANDROID_CLASS \
+ "com/cisco/hicn/facemgrlibrary/supportlibrary/FacemgrUtility"
+
+/* Internal data storage */
+typedef struct {
+ int fd;
+ android_cfg_t cfg;
+ JNIEnv *env;
+ jclass cls;
+ bool attached_to_vm;
+ facelet_array_t *facelets;
+ pthread_mutex_t mutex;
+} android_data_t;
+
+// might replace android utility
+
+jclass find_class_global(JNIEnv *env, const char *name) {
+ jclass c = (*env)->FindClass(env, name);
+ jclass c_global = 0;
+ if (c) {
+ c_global = (jclass)(*env)->NewGlobalRef(env, c);
+ (*env)->DeleteLocalRef(env, c);
+ }
+ return c_global;
+}
+
+int android_on_network_event(interface_t *interface, const char *interface_name,
+ netdevice_type_t netdevice_type, bool up,
+ int family, const char *ip_address) {
+ android_data_t *data = (android_data_t *)interface->data;
+
+ netdevice_t *netdevice = netdevice_create_from_name(interface_name);
+ if (!netdevice) {
+ ERROR("[android_on_network_event] error creating netdevice '%s'",
+ interface_name);
+ goto ERR_ND;
+ }
+
+ hicn_ip_address_t local_addr = IP_ADDRESS_EMPTY;
+ if (ip_address) {
+ if (hicn_ip_address_pton(ip_address, &local_addr) < 0) {
+ ERROR("[android_on_network_event] error processing IP address");
+ goto ERR_IP_ADDRESS;
+ }
+ }
+
+ facelet_t *facelet = facelet_create();
+ if (!facelet) {
+ ERROR("[android_on_network_event] error creating facelet");
+ goto ERR_FACELET;
+ }
+
+ if (facelet_set_netdevice(facelet, *netdevice) < 0) {
+ ERROR("[android_on_network_event] error setting netdevice");
+ goto ERR;
+ }
+
+ if (netdevice_type != NETDEVICE_TYPE_UNDEFINED) {
+ if (facelet_set_netdevice_type(facelet, netdevice_type) < 0) {
+ ERROR("[android_on_network_event] error setting netdevice type");
+ goto ERR;
+ }
+ }
+
+ if (facelet_set_family(facelet, family) < 0) {
+ ERROR("[android_on_network_event] error setting family");
+ goto ERR;
+ }
+
+ if (ip_address) {
+ if (facelet_set_local_addr(facelet, local_addr) < 0) {
+ ERROR("[android_on_network_event] error setting local address");
+ goto ERR;
+ }
+ }
+ netdevice_free(netdevice);
+
+ facelet_set_event(facelet, up ? FACELET_EVENT_CREATE : FACELET_EVENT_DELETE);
+ // FACELET_EVENT_UPDATE, FACELET_EVENT_SET_DOWN
+ facelet_set_attr_clean(facelet);
+
+ pthread_mutex_lock(&data->mutex);
+ if (facelet_array_add(data->facelets, facelet)) {
+ ERROR("[android_on_network_event] Could not add facelet to buffer");
+ goto ERR_ADD;
+ }
+
+ pthread_mutex_unlock(&data->mutex);
+
+ eventfd_write(data->fd, 1);
+ return 0;
+
+ERR_ADD:
+ pthread_mutex_unlock(&data->mutex);
+ERR:
+ facelet_free(facelet);
+ERR_FACELET:
+ERR_IP_ADDRESS:
+ netdevice_free(netdevice);
+ERR_ND:
+ return -1;
+}
+
+bool get_jni_env(JavaVM *jvm, JNIEnv **env) {
+ bool did_attach_thread = false;
+ INFO("initialize: get_jni_env");
+ *env = NULL;
+ // Check if the current thread is attached to the VM
+ int get_env_result = (*jvm)->GetEnv(jvm, (void **)env, JNI_VERSION_1_6);
+ if (get_env_result == JNI_EDETACHED) {
+ INFO("initialize: detached!");
+ if ((*jvm)->AttachCurrentThread(jvm, env, NULL) == JNI_OK) {
+ INFO("initialize: attached...");
+ did_attach_thread = true;
+ } else {
+ INFO("initialize: failed to attach");
+ // Failed to attach thread. Throw an exception if you want to.
+ }
+ } else if (get_env_result == JNI_EVERSION) {
+ // Unsupported JNI version. Throw an exception if you want to.
+ INFO("initialize: unsupported");
+ }
+ return did_attach_thread;
+}
+
+int android_initialize(interface_t *interface, void *cfg) {
+ android_data_t *data = malloc(sizeof(android_data_t));
+ if (!data) goto ERR_MALLOC;
+ interface->data = data;
+
+ if (!cfg) goto ERR_CFG;
+ data->cfg = *(android_cfg_t *)cfg;
+
+ JavaVM *jvm = data->cfg.jvm;
+ if (!jvm) goto ERR_JVM;
+
+ data->facelets = facelet_array_create();
+ if (!data->facelets) goto ERR_FACELETS;
+
+ if ((data->fd = eventfd(0, EFD_SEMAPHORE)) == -1) goto ERR_EVENTFD;
+
+ if (interface_register_fd(interface, data->fd, NULL) < 0) {
+ ERROR("[android_initialize] Error registering fd");
+ goto ERR_REGISTER_FD;
+ }
+
+ pthread_mutex_init(&data->mutex, NULL);
+
+ data->attached_to_vm = get_jni_env(jvm, &data->env);
+
+ if (!data->env) goto ERR_ENV;
+
+ data->cls = find_class_global(data->env, FACEMGR_ANDROID_CLASS);
+ if (data->cls == 0) goto ERR_CLS;
+
+ jmethodID mid_initialize =
+ (*data->env)
+ ->GetStaticMethodID(data->env, data->cls, "initialize", "()I");
+ if (!mid_initialize) goto ERR_MID;
+
+ (*data->env)
+ ->CallStaticIntMethod(data->env, data->cls, mid_initialize,
+ &android_on_network_event, interface);
+
+ return 0;
+
+ERR_MID:
+ (*data->env)->DeleteGlobalRef(data->env, data->cls);
+ERR_CLS:
+ if (data->attached_to_vm) {
+ (*jvm)->DetachCurrentThread(jvm);
+ data->attached_to_vm = false;
+ }
+ data->env = NULL;
+ERR_ENV:
+ interface_unregister_fd(interface, data->fd);
+ERR_REGISTER_FD:
+ close(data->fd);
+ERR_EVENTFD:
+ facelet_array_free(data->facelets);
+ERR_FACELETS:
+ERR_JVM:
+ERR_CFG:
+ free(data);
+ERR_MALLOC:
+ return -1;
+}
+
+int android_finalize(interface_t *interface) {
+ android_data_t *data = (android_data_t *)interface->data;
+
+ jmethodID mid_terminate =
+ (*data->env)->GetStaticMethodID(data->env, data->cls, "terminate", "()I");
+ if (mid_terminate) {
+ (*data->env)
+ ->CallStaticIntMethod(data->env, data->cls, mid_terminate,
+ &android_on_network_event, interface);
+ }
+
+ (*data->env)->DeleteGlobalRef(data->env, data->cls);
+
+ JavaVM *jvm = data->cfg.jvm;
+ if (data->attached_to_vm) {
+ (*jvm)->DetachCurrentThread(jvm);
+ data->attached_to_vm = false;
+ }
+ data->env = NULL;
+
+ pthread_mutex_destroy(&data->mutex);
+
+ // interface_unregister_fd(interface, data->fd); // XXX done in
+ // facemgr_delete_interface...
+ close(data->fd);
+ facelet_array_free(data->facelets);
+
+ free(data);
+
+ return 0;
+}
+
+int android_callback(interface_t *interface, int fd, void *unused) {
+ android_data_t *data = (android_data_t *)interface->data;
+
+ uint64_t ret;
+ if (read(data->fd, &ret, sizeof(ret)) < 0) return -1;
+ if (ret == 0) // EOF
+ return 0;
+
+ pthread_mutex_lock(&data->mutex);
+ for (unsigned i = 0; i < facelet_array_len(data->facelets); i++) {
+ facelet_t *facelet;
+ if (facelet_array_get_index(data->facelets, i, &facelet) < 0) {
+ ERROR("[android_callback] Error getting facelet in array");
+ continue;
+ }
+
+ interface_raise_event(interface, facelet);
+ }
+
+ for (unsigned i = 0; i < facelet_array_len(data->facelets); i++) {
+ if (facelet_array_remove_index(data->facelets, i, NULL) < 0) {
+ ERROR("[android_callback] Could not purge facelet from array");
+ }
+ }
+ pthread_mutex_unlock(&data->mutex);
+
+ return 0;
+}
+
+const interface_ops_t android_ops = {
+ .type = "android",
+ .initialize = android_initialize,
+ .callback = android_callback,
+ .finalize = android_finalize,
+ .on_event = NULL,
+};
diff --git a/ctrl/facemgr/src/interfaces/android/android.h b/ctrl/facemgr/src/interfaces/android/android.h
new file mode 100644
index 000000000..319bfe10a
--- /dev/null
+++ b/ctrl/facemgr/src/interfaces/android/android.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file android/android.h
+ * \brief Android utility.
+ */
+
+#ifndef FACEMGR_INTERFACE_ANDROID_H
+#define FACEMGR_INTERFACE_ANDROID_H
+
+#ifdef __ANDROID__
+
+#include <jni.h>
+#include "../../interface.h"
+
+typedef struct {
+ JavaVM *jvm;
+} android_cfg_t;
+
+int android_on_network_event(interface_t *interface, const char *interface_name,
+ netdevice_type_t netdevice_type, bool up,
+ int family, const char *ip_address);
+
+#endif /* __ANDROID__ */
+
+#endif /* FACEMGR_INTERFACE_ANDROID_H */
diff --git a/ctrl/facemgr/src/interfaces/android_utility/android_utility.c b/ctrl/facemgr/src/interfaces/android_utility/android_utility.c
deleted file mode 100644
index d8e20659a..000000000
--- a/ctrl/facemgr/src/interfaces/android_utility/android_utility.c
+++ /dev/null
@@ -1,138 +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.
- */
-
-/**
- * \file interfaces/android_utility/android_utility.c
- * \brief Implementation of Android utility.
- */
-
-#include <assert.h>
-
-#include <hicn/facemgr.h>
-#include <hicn/ctrl/face.h>
-#include <hicn/util/log.h>
-#include "../../common.h"
-#include "../../interface.h"
-
-#include "android_utility.h"
-
-#define FACEMGR_UTILITY_CLASS "com/cisco/hicn/facemgrlibrary/supportlibrary/FacemgrUtility"
-
-
-#define AU_INTERFACE_TYPE_UNDEFINED 0
-#define AU_INTERFACE_TYPE_WIRED 1
-#define AU_INTERFACE_TYPE_WIFI 2
-#define AU_INTERFACE_TYPE_CELLULAR 3
-#define AU_INTERFACE_TYPE_LOOPBACK 4
-#define AU_INTERFACE_TYPE_UNAVAILABLE 5
-
-#define ERR_STR_JAVA "Java VM parameters are required in the interface configuration."
-
-typedef struct {
- android_utility_cfg_t cfg;
-} au_data_t;
-
-int au_initialize(interface_t * interface, void * cfg)
-{
- au_data_t * data = malloc(sizeof(au_data_t));
- if (!data)
- return -1;
- interface->data = data;
-
- if (!cfg)
- goto ERR_CFG;
-
- data->cfg = * (android_utility_cfg_t *) cfg;
-
- if (!data->cfg.jvm)
- goto ERR_CFG;
-
- return 0;
-
-ERR_CFG:
- fprintf(stderr, ERR_STR_JAVA);
- return -1;
-}
-
-int au_finalize(interface_t * interface)
-{
- /* Nothing to do */
- return 0;
-}
-
-int au_on_event(interface_t * interface, facelet_t * facelet)
-{
- /*
- * This function is responsible to annotate every face we receive with the
- * correct interface type, based on the value returned by the Android
- * utility shipped with the Android forwarder.
- */
- au_data_t * data = (au_data_t*)interface->data;
-
- netdevice_t netdevice = NETDEVICE_EMPTY;
- int rc = facelet_get_netdevice(facelet, &netdevice);
- if (rc < 0)
- return -1;
-
- JNIEnv *env;
- JavaVM *jvm = data->cfg.jvm;
- (*jvm)->AttachCurrentThread(jvm, &env, NULL);
- jclass cls = (*env)->FindClass(env, FACEMGR_UTILITY_CLASS);
- jmethodID getNetworkType = (*env)->GetStaticMethodID(env, cls,
- "getNetworkType", "(Ljava/lang/String;)I");
- jint interface_type = (*env)->CallStaticIntMethod(env, cls, getNetworkType,
- (*env)->NewStringUTF(env, netdevice.name));
-
- netdevice_type_t netdevice_type = AU_INTERFACE_TYPE_UNDEFINED;
- switch(interface_type) {
- case AU_INTERFACE_TYPE_UNDEFINED:
- break;
- case AU_INTERFACE_TYPE_WIRED:
- netdevice_type = NETDEVICE_TYPE_WIRED;
- break;
- case AU_INTERFACE_TYPE_WIFI:
- netdevice_type = NETDEVICE_TYPE_WIFI;
- break;
- case AU_INTERFACE_TYPE_CELLULAR:
- netdevice_type = NETDEVICE_TYPE_CELLULAR;
- break;
- case AU_INTERFACE_TYPE_LOOPBACK:
- netdevice_type = NETDEVICE_TYPE_LOOPBACK;
- break;
- default:
- DEBUG("AU RETURNED ERROR");
- return -1;
- }
-
- DEBUG("AU RETURNED %s : %s", netdevice.name, netdevice_type_str[netdevice_type]);
-
- facelet_t * facelet_new = facelet_create();
- facelet_set_netdevice(facelet_new, netdevice);
- facelet_set_attr_clean(facelet_new);
- facelet_set_netdevice_type(facelet_new, netdevice_type);
-
- facelet_set_event(facelet_new, FACELET_EVENT_UPDATE);
- interface_raise_event(interface, facelet_new);
-
- return 0;
-}
-
-const interface_ops_t android_utility_ops = {
- .type = "android_utility",
- .initialize = au_initialize,
- .finalize = au_finalize,
- .callback = NULL,
- .on_event = au_on_event,
-};
diff --git a/ctrl/facemgr/src/interfaces/android_utility/android_utility.h b/ctrl/facemgr/src/interfaces/android_utility/android_utility.h
deleted file mode 100644
index 53adfedf6..000000000
--- a/ctrl/facemgr/src/interfaces/android_utility/android_utility.h
+++ /dev/null
@@ -1,48 +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.
- */
-
-/**
- * \file android_utility/android_utility.h
- * \brief Android utility.
- *
- * This class relies on a small utility wrapper shipped with the Android
- * application to access to Java SDK APIs for information not available to
- * native code.
- *
- * For instance, we currently don't have on Linux any mean to get the type
- * associated to an interface, especially for cellular interfaces. WiFi and
- * Bluetooth information is for instance available through specific netlink
- * subsystems, or by means of a support library, but cellular detection mostly
- * relies on heuristics based on interface names (eg. in network manager).
- *
- * Android ship a Radio Interface Layer (RIL) daemon that exposes a control
- * socket to the Java API to control the radio layer, but there is no working
- * code exploiting it and no proper documentation.
- */
-
-#ifndef FACEMGR_INTERFACE_ANDROID_UTILITY_H
-#define FACEMGR_INTERFACE_ANDROID_UTILITY_H
-
-#ifdef __ANDROID__
-
-#include <jni.h>
-
-typedef struct {
- JavaVM *jvm;
-} android_utility_cfg_t;
-
-#endif /* __ANDROID__ */
-
-#endif /* FACEMGR_INTERFACE_ANDROID_UTILITY_H */
diff --git a/ctrl/facemgr/src/interfaces/bonjour/CMakeLists.txt b/ctrl/facemgr/src/interfaces/bonjour/CMakeLists.txt
index 8a0ddc888..90ca0e47f 100644
--- a/ctrl/facemgr/src/interfaces/bonjour/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/bonjour/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/src/interfaces/bonjour/bonjour.c b/ctrl/facemgr/src/interfaces/bonjour/bonjour.c
index 40b7f5f90..e7de5d648 100644
--- a/ctrl/facemgr/src/interfaces/bonjour/bonjour.c
+++ b/ctrl/facemgr/src/interfaces/bonjour/bonjour.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,6 +25,7 @@
#include <hicn/facemgr.h>
#include <hicn/util/log.h>
#include <hicn/util/map.h>
+#include <hicn/util/sstrncpy.h>
#include "../../common.h"
#include "../../interface.h"
@@ -40,368 +41,358 @@
#define DEFAULT_SERVICE_DOMAIN "local"
typedef struct {
- bonjour_cfg_t cfg;
- int sock;
- size_t buffer_size;
- void* buffer;
+ bonjour_cfg_t cfg;
+ int sock;
+ size_t buffer_size;
+ void* buffer;
- /* The face being resolved, non-NULL values indicate interface is busy... */
- face_t * face;
+ /* The face being resolved, non-NULL values indicate interface is busy... */
+ face_t* face;
} bj_data_t;
-int bj_initialize(interface_t * interface, void * cfg)
-{
- bj_data_t * data = malloc(sizeof(bj_data_t));
- if (!data)
- goto ERR_MALLOC;
- interface->data = data;
+int bj_initialize(interface_t* interface, void* cfg) {
+ bj_data_t* data = malloc(sizeof(bj_data_t));
+ if (!data) goto ERR_MALLOC;
+ interface->data = data;
- if (cfg) {
+ if (cfg) {
#ifndef __linux__
- if (cfg->netdevice)
- WARN("Binding to interface is (currently) only supported on Linux");
+ if (cfg->netdevice)
+ WARN("Binding to interface is (currently) only supported on Linux");
#endif /* ! __linux__ */
- data->cfg = * (bonjour_cfg_t *) cfg;
- } else {
- memset(&data->cfg, 0, sizeof(bonjour_cfg_t));
- }
+ data->cfg = *(bonjour_cfg_t*)cfg;
+ } else {
+ memset(&data->cfg, 0, sizeof(bonjour_cfg_t));
+ }
- if (!data->cfg.service_name)
- data->cfg.service_name = DEFAULT_SERVICE_NAME;
+ if (!data->cfg.service_name) data->cfg.service_name = DEFAULT_SERVICE_NAME;
- if (!data->cfg.service_protocol)
- data->cfg.service_protocol = DEFAULT_SERVICE_PROTOCOL;
+ if (!data->cfg.service_protocol)
+ data->cfg.service_protocol = DEFAULT_SERVICE_PROTOCOL;
- if (!data->cfg.service_domain)
- data->cfg.service_domain = DEFAULT_SERVICE_DOMAIN;
+ if (!data->cfg.service_domain)
+ data->cfg.service_domain = DEFAULT_SERVICE_DOMAIN;
- data->sock = mdns_socket_open_ipv4();
- if (data->sock < 0) {
- printf("Failed to open socket: %s\n", strerror(errno));
- goto ERR_SOCK;
- }
+ data->sock = mdns_socket_open_ipv4();
+ if (data->sock < 0) {
+ printf("Failed to open socket: %s\n", strerror(errno));
+ goto ERR_SOCK;
+ }
- /* Netdevice configuration */
+ /* Netdevice configuration */
#ifdef __linux__
#ifndef __ANDROID__
- if (IS_VALID_NETDEVICE(data->cfg.netdevice)) {
- int rc = setsockopt(data->sock, SOL_SOCKET, SO_BINDTODEVICE,
- &data->cfg.netdevice.name, strlen(data->cfg.netdevice.name) + 1);
- if (rc == -1) {
- ERROR("setsockopt");
- goto ERR_SOCK_OPT;
- }
+ if (IS_VALID_NETDEVICE(data->cfg.netdevice)) {
+ int rc = setsockopt(data->sock, SOL_SOCKET, SO_BINDTODEVICE,
+ &data->cfg.netdevice.name,
+ strnlen_s(data->cfg.netdevice.name, IFNAMSIZ));
+ if (rc == -1) {
+ ERROR("setsockopt");
+ goto ERR_SOCK_OPT;
}
+ }
#endif
#endif /* __linux__ */
- data->buffer_size = DEFAULT_BUFFER_SIZE;
- data->buffer = malloc(data->buffer_size);
- if (!data->buffer)
- goto ERR_BUFFER;
+ data->buffer_size = DEFAULT_BUFFER_SIZE;
+ data->buffer = malloc(data->buffer_size);
+ if (!data->buffer) goto ERR_BUFFER;
#ifdef _WIN32
- WORD versionWanted = MAKEWORD(1, 1);
- WSADATA wsaData;
- WSAStartup(versionWanted, &wsaData);
+ WORD versionWanted = MAKEWORD(1, 1);
+ WSADATA wsaData;
+ WSAStartup(versionWanted, &wsaData);
#endif
- if (interface_register_fd(interface, data->sock, NULL) < 0) {
- ERROR("[bj_initialize] Error registering fd");
- goto ERR_FD;
- }
+ if (interface_register_fd(interface, data->sock, NULL) < 0) {
+ ERROR("[bj_initialize] Error registering fd");
+ goto ERR_FD;
+ }
- return 0;
+ return 0;
ERR_FD:
- free(data->buffer);
+ free(data->buffer);
ERR_BUFFER:
#ifndef __ANDROID__
ERR_SOCK_OPT:
#endif
- mdns_socket_close(data->sock);
+ mdns_socket_close(data->sock);
#ifdef _WIN32
- WSACleanup();
+ WSACleanup();
#endif
ERR_SOCK:
- free(data);
+ free(data);
ERR_MALLOC:
- return -1;
+ return -1;
}
/*
* We reuse the callback to be triggered upon external events
* TODO: move to a cleaner interface architecture later...
*/
-int bj_on_event(interface_t * interface, facelet_t * facelet)
-{
- bj_data_t * data = (bj_data_t*)interface->data;
-
- /*
- printf("Sending DNS-SD discovery\n");
- if (mdns_discovery_send(sock)) {
- printf("Failed to send DNS-DS discovery: %s\n", strerror(errno));
- goto quit;
- }
-
- printf("Reading DNS-SD replies\n");
- for (int i = 0; i < 10; ++i) {
- records = mdns_discovery_recv(sock, buffer, capacity, callback,
- user_data);
- sleep(1);
- }
- */
-
- DEBUG("Sending mDNS query");
- char service_string[SERVICE_STRING_SIZE];
-
- int rc = snprintf(service_string, SERVICE_STRING_SIZE, "_%s._%s.%s.",
- data->cfg.service_name, data->cfg.service_protocol,
- data->cfg.service_domain);
- if (rc < 0)
- ; // error
- else if (rc >= SERVICE_STRING_SIZE)
- ; //truncated
-
- if (mdns_query_send(data->sock, MDNS_RECORDTYPE_PTR,
- service_string,
- strlen(service_string),
- data->buffer, data->buffer_size)) {
- printf("Failed to send mDNS query: %s\n", strerror(errno));
- return -1;
- }
- return 0;
+int bj_on_event(interface_t* interface, facelet_t* facelet) {
+ bj_data_t* data = (bj_data_t*)interface->data;
+
+ /*
+ printf("Sending DNS-SD discovery\n");
+ if (mdns_discovery_send(sock)) {
+ printf("Failed to send DNS-DS discovery: %s\n", strerror(errno));
+ goto quit;
+ }
+
+ printf("Reading DNS-SD replies\n");
+ for (int i = 0; i < 10; ++i) {
+ records = mdns_discovery_recv(sock, buffer, capacity, callback,
+ user_data);
+ sleep(1);
+ }
+ */
+
+ DEBUG("Sending mDNS query");
+ char service_string[SERVICE_STRING_SIZE];
+
+ int rc = snprintf(service_string, SERVICE_STRING_SIZE, "_%s._%s.%s.",
+ data->cfg.service_name, data->cfg.service_protocol,
+ data->cfg.service_domain);
+ if (rc < 0)
+ ; // error
+ else if (rc >= SERVICE_STRING_SIZE)
+ ; // truncated
+
+ if (mdns_query_send(data->sock, MDNS_RECORDTYPE_PTR, service_string,
+ strnlen_s(service_string, SERVICE_STRING_SIZE),
+ data->buffer, data->buffer_size)) {
+ printf("Failed to send mDNS query: %s\n", strerror(errno));
+ return -1;
+ }
+ return 0;
}
static char addrbuffer[64];
static char namebuffer[256];
static mdns_record_txt_t txtbuffer[128];
-static mdns_string_t
-ipv4_address_to_string(char* buffer, size_t capacity, const struct sockaddr_in* addr) {
- char host[NI_MAXHOST] = {0};
- char service[NI_MAXSERV] = {0};
- int ret = getnameinfo((const struct sockaddr*)addr, sizeof(struct sockaddr_in),
- host, NI_MAXHOST, service, NI_MAXSERV,
- NI_NUMERICSERV | NI_NUMERICHOST);
- int len = 0;
- if (ret == 0) {
- if (addr->sin_port != 0)
- len = snprintf(buffer, capacity, "%s:%s", host, service);
- else
- len = snprintf(buffer, capacity, "%s", host);
- }
- if (len >= (int)capacity)
- len = (int)capacity - 1;
- mdns_string_t str = {buffer, len};
- return str;
+static mdns_string_t ipv4_address_to_string(char* buffer, size_t capacity,
+ const struct sockaddr_in* addr) {
+ char host[NI_MAXHOST] = {0};
+ char service[NI_MAXSERV] = {0};
+ int ret = getnameinfo((const struct sockaddr*)addr,
+ sizeof(struct sockaddr_in), host, NI_MAXHOST, service,
+ NI_MAXSERV, NI_NUMERICSERV | NI_NUMERICHOST);
+ int len = 0;
+ if (ret == 0) {
+ if (addr->sin_port != 0)
+ len = snprintf(buffer, capacity, "%s:%s", host, service);
+ else
+ len = snprintf(buffer, capacity, "%s", host);
+ }
+ if (len >= (int)capacity) len = (int)capacity - 1;
+ mdns_string_t str = {buffer, len};
+ return str;
}
-static mdns_string_t
-ipv6_address_to_string(char* buffer, size_t capacity, const struct sockaddr_in6* addr) {
- char host[NI_MAXHOST] = {0};
- char service[NI_MAXSERV] = {0};
- int ret = getnameinfo((const struct sockaddr*)addr, sizeof(struct sockaddr_in6),
- host, NI_MAXHOST, service, NI_MAXSERV,
- NI_NUMERICSERV | NI_NUMERICHOST);
- int len = 0;
- if (ret == 0) {
- if (addr->sin6_port != 0)
- len = snprintf(buffer, capacity, "[%s]:%s", host, service);
- else
- len = snprintf(buffer, capacity, "%s", host);
- }
- if (len >= (int)capacity)
- len = (int)capacity - 1;
- mdns_string_t str = {buffer, len};
- return str;
+static mdns_string_t ipv6_address_to_string(char* buffer, size_t capacity,
+ const struct sockaddr_in6* addr) {
+ char host[NI_MAXHOST] = {0};
+ char service[NI_MAXSERV] = {0};
+ int ret = getnameinfo((const struct sockaddr*)addr,
+ sizeof(struct sockaddr_in6), host, NI_MAXHOST, service,
+ NI_MAXSERV, NI_NUMERICSERV | NI_NUMERICHOST);
+ int len = 0;
+ if (ret == 0) {
+ if (addr->sin6_port != 0)
+ len = snprintf(buffer, capacity, "[%s]:%s", host, service);
+ else
+ len = snprintf(buffer, capacity, "%s", host);
+ }
+ if (len >= (int)capacity) len = (int)capacity - 1;
+ mdns_string_t str = {buffer, len};
+ return str;
}
-static mdns_string_t
-ip_address_to_string(char* buffer, size_t capacity, const struct sockaddr* addr) {
- if (addr->sa_family == AF_INET6)
- return ipv6_address_to_string(buffer, capacity, (const struct sockaddr_in6*)addr);
- return ipv4_address_to_string(buffer, capacity, (const struct sockaddr_in*)addr);
+static mdns_string_t hicn_ip_address_to_string(char* buffer, size_t capacity,
+ const struct sockaddr* addr) {
+ if (addr->sa_family == AF_INET6)
+ return ipv6_address_to_string(buffer, capacity,
+ (const struct sockaddr_in6*)addr);
+ return ipv4_address_to_string(buffer, capacity,
+ (const struct sockaddr_in*)addr);
}
-int
-ip_address_set_sockaddr(ip_address_t * ip_address, struct sockaddr * sa)
-{
- switch(sa->sa_family) {
- case AF_INET:
- ip_address->v4.as_inaddr = ((struct sockaddr_in *)sa)->sin_addr;
- break;
- case AF_INET6:
- ip_address->v6.as_in6addr = ((struct sockaddr_in6 *)sa)->sin6_addr;
- break;
- default:
- return -1;
- }
-
- return 0;
+int hicn_ip_address_set_sockaddr(hicn_ip_address_t* ip_address,
+ struct sockaddr* sa) {
+ switch (sa->sa_family) {
+ case AF_INET:
+ ip_address->v4.as_inaddr = ((struct sockaddr_in*)sa)->sin_addr;
+ break;
+ case AF_INET6:
+ ip_address->v6.as_in6addr = ((struct sockaddr_in6*)sa)->sin6_addr;
+ break;
+ default:
+ return -1;
+ }
+
+ return 0;
}
-static int
-callback(const struct sockaddr* from, mdns_entry_type_t entry, uint16_t type,
- uint16_t rclass, uint32_t ttl, const void* data, size_t size, size_t
- offset, size_t length, void* user_data)
-{
- interface_t * interface = (interface_t*)user_data;
- bj_data_t * bj_data = (bj_data_t *)interface->data;
-
- struct sockaddr_storage addr;
-
- mdns_string_t fromaddrstr = ip_address_to_string(addrbuffer, sizeof(addrbuffer), from);
- const char* entrytype = (entry == MDNS_ENTRYTYPE_ANSWER) ? "answer" :
- ((entry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional");
-
- switch(type) {
- case MDNS_RECORDTYPE_A:
- {
- ip_address_t ip_address;
- mdns_record_parse_a(data, size, offset, length, (struct sockaddr_in*)&addr);
- ip_address_set_sockaddr(&ip_address, (struct sockaddr *)&addr);
-
- mdns_string_t addrstr = ipv4_address_to_string(namebuffer, sizeof(namebuffer), (struct sockaddr_in *)&addr);
- DEBUG("%.*s : %s A %.*s",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(addrstr));
-
- facelet_t * facelet = facelet_create();
- facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
- facelet_set_family(facelet, AF_INET);
- facelet_set_remote_addr(facelet, ip_address);
- //facelet_set_remote_port(facelet, ((struct sockaddr_in*)&addr)->sin_port);
-
- facelet_set_event(facelet, FACELET_EVENT_UPDATE);
- interface_raise_event(interface, facelet);
- break;
- }
+static int callback(const struct sockaddr* from, mdns_entry_type_t entry,
+ uint16_t type, uint16_t rclass, uint32_t ttl,
+ const void* data, size_t size, size_t offset, size_t length,
+ void* user_data) {
+ interface_t* interface = (interface_t*)user_data;
+ bj_data_t* bj_data = (bj_data_t*)interface->data;
+
+ struct sockaddr_storage addr;
+
+ mdns_string_t fromaddrstr =
+ hicn_ip_address_to_string(addrbuffer, sizeof(addrbuffer), from);
+ const char* entrytype =
+ (entry == MDNS_ENTRYTYPE_ANSWER)
+ ? "answer"
+ : ((entry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional");
+
+ switch (type) {
+ case MDNS_RECORDTYPE_A: {
+ hicn_ip_address_t ip_address;
+ mdns_record_parse_a(data, size, offset, length,
+ (struct sockaddr_in*)&addr);
+ hicn_ip_address_set_sockaddr(&ip_address, (struct sockaddr*)&addr);
+
+ mdns_string_t addrstr = ipv4_address_to_string(
+ namebuffer, sizeof(namebuffer), (struct sockaddr_in*)&addr);
+ DEBUG("%.*s : %s A %.*s", MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(addrstr));
+
+ facelet_t* facelet = facelet_create();
+ facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
+ facelet_set_family(facelet, AF_INET);
+ facelet_set_remote_addr(facelet, ip_address);
+ // facelet_set_remote_port(facelet, ((struct
+ // sockaddr_in*)&addr)->sin_port);
+
+ facelet_set_event(facelet, FACELET_EVENT_UPDATE);
+ interface_raise_event(interface, facelet);
+ break;
+ }
- case MDNS_RECORDTYPE_AAAA:
- {
- ip_address_t ip_address;
- mdns_record_parse_aaaa(data, size, offset, length, (struct sockaddr_in6*)&addr);
- ip_address_set_sockaddr(&ip_address, (struct sockaddr *)&addr);
-
- mdns_string_t addrstr = ipv6_address_to_string(namebuffer,
- sizeof(namebuffer), (struct sockaddr_in6*)&addr);
- DEBUG("%.*s : %s AAAA %.*s",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(addrstr));
-
- facelet_t * facelet = facelet_create();
- facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
- facelet_set_family(facelet, AF_INET6);
- facelet_set_remote_addr(facelet, ip_address);
- //facelet_set_remote_port(facelet, ((struct sockaddr_in6*)&addr)->sin6_port);
-
- facelet_set_event(facelet, FACELET_EVENT_UPDATE);
- interface_raise_event(interface, facelet);
- break;
- }
+ case MDNS_RECORDTYPE_AAAA: {
+ hicn_ip_address_t ip_address;
+ mdns_record_parse_aaaa(data, size, offset, length,
+ (struct sockaddr_in6*)&addr);
+ hicn_ip_address_set_sockaddr(&ip_address, (struct sockaddr*)&addr);
+
+ mdns_string_t addrstr = ipv6_address_to_string(
+ namebuffer, sizeof(namebuffer), (struct sockaddr_in6*)&addr);
+ DEBUG("%.*s : %s AAAA %.*s", MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(addrstr));
+
+ facelet_t* facelet = facelet_create();
+ facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
+ facelet_set_family(facelet, AF_INET6);
+ facelet_set_remote_addr(facelet, ip_address);
+ // facelet_set_remote_port(facelet, ((struct
+ // sockaddr_in6*)&addr)->sin6_port);
+
+ facelet_set_event(facelet, FACELET_EVENT_UPDATE);
+ interface_raise_event(interface, facelet);
+ break;
+ }
- case MDNS_RECORDTYPE_SRV: /* same port for both v4 and v6 */
- {
- mdns_record_srv_t srv = mdns_record_parse_srv(data, size, offset, length,
- namebuffer, sizeof(namebuffer));
-
- DEBUG("%.*s : %s SRV %.*s priority %d weight %d port %d",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(srv.name), srv.priority, srv.weight, srv.port);
-
- /* We raise both v4 and v6
- *
- * Unless we choose whether we query A and/or AAAA, this might leave
- * us with an unused pending facelet, eg. we might not have an IPv6
- * but we raise an IPv6 bonjour event...
- */
-
- facelet_t * facelet = facelet_create();
- facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
- facelet_set_family(facelet, AF_INET);
- facelet_set_remote_port(facelet, srv.port);
-
- facelet_set_event(facelet, FACELET_EVENT_UPDATE);
- interface_raise_event(interface, facelet);
-
- facelet = facelet_create();
- facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
- facelet_set_family(facelet, AF_INET6);
- facelet_set_remote_port(facelet, srv.port);
-
- facelet_set_event(facelet, FACELET_EVENT_UPDATE);
- interface_raise_event(interface, facelet);
- break;
- }
+ case MDNS_RECORDTYPE_SRV: /* same port for both v4 and v6 */
+ {
+ mdns_record_srv_t srv = mdns_record_parse_srv(
+ data, size, offset, length, namebuffer, sizeof(namebuffer));
+
+ DEBUG("%.*s : %s SRV %.*s priority %d weight %d port %d",
+ MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(srv.name), srv.priority, srv.weight, srv.port);
+
+ /* We raise both v4 and v6
+ *
+ * Unless we choose whether we query A and/or AAAA, this might leave
+ * us with an unused pending facelet, eg. we might not have an IPv6
+ * but we raise an IPv6 bonjour event...
+ */
+
+ facelet_t* facelet = facelet_create();
+ facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
+ facelet_set_family(facelet, AF_INET);
+ facelet_set_remote_port(facelet, srv.port);
+
+ facelet_set_event(facelet, FACELET_EVENT_UPDATE);
+ interface_raise_event(interface, facelet);
+
+ facelet = facelet_create();
+ facelet_set_netdevice(facelet, bj_data->cfg.netdevice);
+ facelet_set_family(facelet, AF_INET6);
+ facelet_set_remote_port(facelet, srv.port);
+
+ facelet_set_event(facelet, FACELET_EVENT_UPDATE);
+ interface_raise_event(interface, facelet);
+ break;
+ }
- case MDNS_RECORDTYPE_PTR:
- {
- mdns_string_t namestr = mdns_record_parse_ptr(data, size, offset, length,
- namebuffer, sizeof(namebuffer));
- DEBUG("%.*s : %s PTR %.*s type %u rclass 0x%x ttl %u length %d",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(namestr), type, rclass, ttl, (int)length);
- break;
- }
+ case MDNS_RECORDTYPE_PTR: {
+ mdns_string_t namestr = mdns_record_parse_ptr(
+ data, size, offset, length, namebuffer, sizeof(namebuffer));
+ DEBUG("%.*s : %s PTR %.*s type %u rclass 0x%x ttl %u length %d",
+ MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(namestr), type, rclass, ttl, (int)length);
+ break;
+ }
- case MDNS_RECORDTYPE_TXT:
- {
- size_t parsed = mdns_record_parse_txt(data, size, offset, length,
- txtbuffer, sizeof(txtbuffer) / sizeof(mdns_record_txt_t));
- for (size_t itxt = 0; itxt < parsed; ++itxt) {
- if (txtbuffer[itxt].value.length) {
- DEBUG("%.*s : %s TXT %.*s = %.*s",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(txtbuffer[itxt].key),
- MDNS_STRING_FORMAT(txtbuffer[itxt].value));
- }
- else {
- DEBUG("%.*s : %s TXT %.*s",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(txtbuffer[itxt].key));
- }
- }
- break;
+ case MDNS_RECORDTYPE_TXT: {
+ size_t parsed =
+ mdns_record_parse_txt(data, size, offset, length, txtbuffer,
+ sizeof(txtbuffer) / sizeof(mdns_record_txt_t));
+ for (size_t itxt = 0; itxt < parsed; ++itxt) {
+ if (txtbuffer[itxt].value.length) {
+ DEBUG("%.*s : %s TXT %.*s = %.*s", MDNS_STRING_FORMAT(fromaddrstr),
+ entrytype, MDNS_STRING_FORMAT(txtbuffer[itxt].key),
+ MDNS_STRING_FORMAT(txtbuffer[itxt].value));
+ } else {
+ DEBUG("%.*s : %s TXT %.*s", MDNS_STRING_FORMAT(fromaddrstr),
+ entrytype, MDNS_STRING_FORMAT(txtbuffer[itxt].key));
}
-
- default:
- /* Silently ignore the received record */
- DEBUG("%.*s : %s type %u rclass 0x%x ttl %u length %d",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- type, rclass, ttl, (int)length);
- return 0;
+ }
+ break;
}
- return 0;
+ default:
+ /* Silently ignore the received record */
+ DEBUG("%.*s : %s type %u rclass 0x%x ttl %u length %d",
+ MDNS_STRING_FORMAT(fromaddrstr), entrytype, type, rclass, ttl,
+ (int)length);
+ return 0;
+ }
+ return 0;
}
/*
* The fact we use a single fd does not allow us to get user_data associated to
* the query.
*/
-int bj_callback(interface_t * interface, int fd, void * unused)
-{
- bj_data_t * data = (bj_data_t*)interface->data;
- DEBUG("Got an mDNS reply");
- /* size_t records = */ mdns_query_recv(data->sock, data->buffer, data->buffer_size, callback, interface, 1);
+int bj_callback(interface_t* interface, int fd, void* unused) {
+ bj_data_t* data = (bj_data_t*)interface->data;
+ DEBUG("Got an mDNS reply");
+ /* size_t records = */ mdns_query_recv(
+ data->sock, data->buffer, data->buffer_size, callback, interface, 1);
- return 0;
+ return 0;
}
-int bj_finalize(interface_t * interface)
-{
- bj_data_t * data = (bj_data_t*)interface->data;
+int bj_finalize(interface_t* interface) {
+ bj_data_t* data = (bj_data_t*)interface->data;
- free(data->buffer);
- mdns_socket_close(data->sock);
+ free(data->buffer);
+ mdns_socket_close(data->sock);
#ifdef _WIN32
- WSACleanup();
+ WSACleanup();
#endif
- return 0;
-
+ return 0;
}
const interface_ops_t bonjour_ops = {
@@ -410,5 +401,5 @@ const interface_ops_t bonjour_ops = {
.on_event = bj_on_event,
.callback = bj_callback,
.finalize = bj_finalize,
- // .on_event = NULL,
+ // .on_event = NULL,
};
diff --git a/ctrl/facemgr/src/interfaces/bonjour/bonjour.h b/ctrl/facemgr/src/interfaces/bonjour/bonjour.h
index fe053079d..6458423ea 100644
--- a/ctrl/facemgr/src/interfaces/bonjour/bonjour.h
+++ b/ctrl/facemgr/src/interfaces/bonjour/bonjour.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,11 +25,11 @@
* queries...
*/
-#include <hicn/ctrl/face.h> /* netdevice_t */
+#include <hicn/face.h> /* netdevice_t */
typedef struct {
- netdevice_t netdevice;
- char * service_name;
- char * service_protocol;
- char * service_domain;
+ netdevice_t netdevice;
+ char* service_name;
+ char* service_protocol;
+ char* service_domain;
} bonjour_cfg_t;
diff --git a/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.c b/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.c
index a8e97e8e0..e2bb4f432 100644
--- a/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.c
+++ b/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.c
@@ -1,6 +1,6 @@
#ifdef _WIN32
-# define _CRT_SECURE_NO_WARNINGS 1
+#define _CRT_SECURE_NO_WARNINGS 1
#endif
#include "mdns.h"
@@ -9,184 +9,176 @@
#include <errno.h>
#ifdef _WIN32
-# define sleep(x) Sleep(x * 1000)
+#define sleep(x) Sleep(x * 1000)
#else
-# include <netdb.h>
+#include <netdb.h>
#endif
static char addrbuffer[64];
static char namebuffer[256];
static mdns_record_txt_t txtbuffer[128];
-static mdns_string_t
-ipv4_address_to_string(char* buffer, size_t capacity, const struct sockaddr_in* addr) {
- char host[NI_MAXHOST] = {0};
- char service[NI_MAXSERV] = {0};
- int ret = getnameinfo((const struct sockaddr*)addr, sizeof(struct sockaddr_in),
- host, NI_MAXHOST, service, NI_MAXSERV,
- NI_NUMERICSERV | NI_NUMERICHOST);
- int len = 0;
- if (ret == 0) {
- if (addr->sin_port != 0)
- len = snprintf(buffer, capacity, "%s:%s", host, service);
- else
- len = snprintf(buffer, capacity, "%s", host);
- }
- if (len >= (int)capacity)
- len = (int)capacity - 1;
- mdns_string_t str = {buffer, len};
- return str;
+static mdns_string_t ipv4_address_to_string(char* buffer, size_t capacity,
+ const struct sockaddr_in* addr) {
+ char host[NI_MAXHOST] = {0};
+ char service[NI_MAXSERV] = {0};
+ int ret = getnameinfo((const struct sockaddr*)addr,
+ sizeof(struct sockaddr_in), host, NI_MAXHOST, service,
+ NI_MAXSERV, NI_NUMERICSERV | NI_NUMERICHOST);
+ int len = 0;
+ if (ret == 0) {
+ if (addr->sin_port != 0)
+ len = snprintf(buffer, capacity, "%s:%s", host, service);
+ else
+ len = snprintf(buffer, capacity, "%s", host);
+ }
+ if (len >= (int)capacity) len = (int)capacity - 1;
+ mdns_string_t str = {buffer, len};
+ return str;
}
-static mdns_string_t
-ipv6_address_to_string(char* buffer, size_t capacity, const struct sockaddr_in6* addr) {
- char host[NI_MAXHOST] = {0};
- char service[NI_MAXSERV] = {0};
- int ret = getnameinfo((const struct sockaddr*)addr, sizeof(struct sockaddr_in6),
- host, NI_MAXHOST, service, NI_MAXSERV,
- NI_NUMERICSERV | NI_NUMERICHOST);
- int len = 0;
- if (ret == 0) {
- if (addr->sin6_port != 0)
- len = snprintf(buffer, capacity, "[%s]:%s", host, service);
- else
- len = snprintf(buffer, capacity, "%s", host);
- }
- if (len >= (int)capacity)
- len = (int)capacity - 1;
- mdns_string_t str = {buffer, len};
- return str;
+static mdns_string_t ipv6_address_to_string(char* buffer, size_t capacity,
+ const struct sockaddr_in6* addr) {
+ char host[NI_MAXHOST] = {0};
+ char service[NI_MAXSERV] = {0};
+ int ret = getnameinfo((const struct sockaddr*)addr,
+ sizeof(struct sockaddr_in6), host, NI_MAXHOST, service,
+ NI_MAXSERV, NI_NUMERICSERV | NI_NUMERICHOST);
+ int len = 0;
+ if (ret == 0) {
+ if (addr->sin6_port != 0)
+ len = snprintf(buffer, capacity, "[%s]:%s", host, service);
+ else
+ len = snprintf(buffer, capacity, "%s", host);
+ }
+ if (len >= (int)capacity) len = (int)capacity - 1;
+ mdns_string_t str = {buffer, len};
+ return str;
}
-static mdns_string_t
-ip_address_to_string(char* buffer, size_t capacity, const struct sockaddr* addr) {
- if (addr->sa_family == AF_INET6)
- return ipv6_address_to_string(buffer, capacity, (const struct sockaddr_in6*)addr);
- return ipv4_address_to_string(buffer, capacity, (const struct sockaddr_in*)addr);
+static mdns_string_t ip_address_to_string(char* buffer, size_t capacity,
+ const struct sockaddr* addr) {
+ if (addr->sa_family == AF_INET6)
+ return ipv6_address_to_string(buffer, capacity,
+ (const struct sockaddr_in6*)addr);
+ return ipv4_address_to_string(buffer, capacity,
+ (const struct sockaddr_in*)addr);
}
-static int
-callback(const struct sockaddr* from,
- mdns_entry_type_t entry, uint16_t type,
- uint16_t rclass, uint32_t ttl,
- const void* data, size_t size, size_t offset, size_t length,
- void* user_data) {
- mdns_string_t fromaddrstr = ip_address_to_string(addrbuffer, sizeof(addrbuffer), from);
- const char* entrytype = (entry == MDNS_ENTRYTYPE_ANSWER) ? "answer" :
- ((entry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional");
- if (type == MDNS_RECORDTYPE_PTR) {
- mdns_string_t namestr = mdns_record_parse_ptr(data, size, offset, length,
- namebuffer, sizeof(namebuffer));
- INFO("%.*s : %s PTR %.*s type %u rclass 0x%x ttl %u length %d\n",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(namestr), type, rclass, ttl, (int)length);
- }
- else if (type == MDNS_RECORDTYPE_SRV) {
- mdns_record_srv_t srv = mdns_record_parse_srv(data, size, offset, length,
- namebuffer, sizeof(namebuffer));
- INFO("%.*s : %s SRV %.*s priority %d weight %d port %d\n",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(srv.name), srv.priority, srv.weight, srv.port);
- }
- else if (type == MDNS_RECORDTYPE_A) {
- struct sockaddr_in addr;
- mdns_record_parse_a(data, size, offset, length, &addr);
- mdns_string_t addrstr = ipv4_address_to_string(namebuffer, sizeof(namebuffer), &addr);
- INFO("%.*s : %s A %.*s\n",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(addrstr));
- }
- else if (type == MDNS_RECORDTYPE_AAAA) {
- struct sockaddr_in6 addr;
- mdns_record_parse_aaaa(data, size, offset, length, &addr);
- mdns_string_t addrstr = ipv6_address_to_string(namebuffer, sizeof(namebuffer), &addr);
- INFO("%.*s : %s AAAA %.*s\n",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(addrstr));
- }
- else if (type == MDNS_RECORDTYPE_TXT) {
- size_t parsed = mdns_record_parse_txt(data, size, offset, length,
- txtbuffer, sizeof(txtbuffer) / sizeof(mdns_record_txt_t));
- for (size_t itxt = 0; itxt < parsed; ++itxt) {
- if (txtbuffer[itxt].value.length) {
- INFO("%.*s : %s TXT %.*s = %.*s\n",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(txtbuffer[itxt].key),
- MDNS_STRING_FORMAT(txtbuffer[itxt].value));
- }
- else {
- INFO("%.*s : %s TXT %.*s\n",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- MDNS_STRING_FORMAT(txtbuffer[itxt].key));
- }
- }
- }
- else {
- INFO("%.*s : %s type %u rclass 0x%x ttl %u length %d\n",
- MDNS_STRING_FORMAT(fromaddrstr), entrytype,
- type, rclass, ttl, (int)length);
- }
- return 0;
+static int callback(const struct sockaddr* from, mdns_entry_type_t entry,
+ uint16_t type, uint16_t rclass, uint32_t ttl,
+ const void* data, size_t size, size_t offset, size_t length,
+ void* user_data) {
+ mdns_string_t fromaddrstr =
+ ip_address_to_string(addrbuffer, sizeof(addrbuffer), from);
+ const char* entrytype =
+ (entry == MDNS_ENTRYTYPE_ANSWER)
+ ? "answer"
+ : ((entry == MDNS_ENTRYTYPE_AUTHORITY) ? "authority" : "additional");
+ if (type == MDNS_RECORDTYPE_PTR) {
+ mdns_string_t namestr = mdns_record_parse_ptr(
+ data, size, offset, length, namebuffer, sizeof(namebuffer));
+ INFO("%.*s : %s PTR %.*s type %u rclass 0x%x ttl %u length %d\n",
+ MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(namestr), type, rclass, ttl, (int)length);
+ } else if (type == MDNS_RECORDTYPE_SRV) {
+ mdns_record_srv_t srv = mdns_record_parse_srv(
+ data, size, offset, length, namebuffer, sizeof(namebuffer));
+ INFO("%.*s : %s SRV %.*s priority %d weight %d port %d\n",
+ MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(srv.name), srv.priority, srv.weight, srv.port);
+ } else if (type == MDNS_RECORDTYPE_A) {
+ struct sockaddr_in addr;
+ mdns_record_parse_a(data, size, offset, length, &addr);
+ mdns_string_t addrstr =
+ ipv4_address_to_string(namebuffer, sizeof(namebuffer), &addr);
+ INFO("%.*s : %s A %.*s\n", MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(addrstr));
+ } else if (type == MDNS_RECORDTYPE_AAAA) {
+ struct sockaddr_in6 addr;
+ mdns_record_parse_aaaa(data, size, offset, length, &addr);
+ mdns_string_t addrstr =
+ ipv6_address_to_string(namebuffer, sizeof(namebuffer), &addr);
+ INFO("%.*s : %s AAAA %.*s\n", MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(addrstr));
+ } else if (type == MDNS_RECORDTYPE_TXT) {
+ size_t parsed =
+ mdns_record_parse_txt(data, size, offset, length, txtbuffer,
+ sizeof(txtbuffer) / sizeof(mdns_record_txt_t));
+ for (size_t itxt = 0; itxt < parsed; ++itxt) {
+ if (txtbuffer[itxt].value.length) {
+ INFO("%.*s : %s TXT %.*s = %.*s\n", MDNS_STRING_FORMAT(fromaddrstr),
+ entrytype, MDNS_STRING_FORMAT(txtbuffer[itxt].key),
+ MDNS_STRING_FORMAT(txtbuffer[itxt].value));
+ } else {
+ INFO("%.*s : %s TXT %.*s\n", MDNS_STRING_FORMAT(fromaddrstr), entrytype,
+ MDNS_STRING_FORMAT(txtbuffer[itxt].key));
+ }
+ }
+ } else {
+ INFO("%.*s : %s type %u rclass 0x%x ttl %u length %d\n",
+ MDNS_STRING_FORMAT(fromaddrstr), entrytype, type, rclass, ttl,
+ (int)length);
+ }
+ return 0;
}
-int
-main() {
- size_t capacity = 2048;
- void* buffer = 0;
- void* user_data = 0;
- size_t records;
+int main() {
+ size_t capacity = 2048;
+ void* buffer = 0;
+ void* user_data = 0;
+ size_t records;
#ifdef _WIN32
- WORD versionWanted = MAKEWORD(1, 1);
- WSADATA wsaData;
- WSAStartup(versionWanted, &wsaData);
+ WORD versionWanted = MAKEWORD(1, 1);
+ WSADATA wsaData;
+ WSAStartup(versionWanted, &wsaData);
#endif
- int sock = mdns_socket_open_ipv4();
- if (sock < 0) {
- INFO("Failed to open socket: %s\n", strerror(errno));
- return -1;
- }
- INFO("Opened IPv4 socket for mDNS/DNS-SD\n");
- buffer = malloc(capacity);
-/*
- INFO("Sending DNS-SD discovery\n");
- if (mdns_discovery_send(sock)) {
- INFO("Failed to send DNS-DS discovery: %s\n", strerror(errno));
- goto quit;
- }
-
- INFO("Reading DNS-SD replies\n");
- for (int i = 0; i < 10; ++i) {
- records = mdns_discovery_recv(sock, buffer, capacity, callback,
- user_data);
- sleep(1);
- }
- */
-
- INFO("Sending mDNS query\n");
- if (mdns_query_send(sock, MDNS_RECORDTYPE_PTR,
- MDNS_STRING_CONST("_hicn._udp.local."),
- buffer, capacity)) {
- INFO("Failed to send mDNS query: %s\n", strerror(errno));
- goto quit;
- }
-
- INFO("Reading mDNS replies\n");
- for (int i = 0; i < 10; ++i) {
- records = mdns_query_recv(sock, buffer, capacity, callback, user_data, 1);
- sleep(1);
- }
+ int sock = mdns_socket_open_ipv4();
+ if (sock < 0) {
+ INFO("Failed to open socket: %s\n", strerror(errno));
+ return -1;
+ }
+ INFO("Opened IPv4 socket for mDNS/DNS-SD\n");
+ buffer = malloc(capacity);
+ /*
+ INFO("Sending DNS-SD discovery\n");
+ if (mdns_discovery_send(sock)) {
+ INFO("Failed to send DNS-DS discovery: %s\n",
+ strerror(errno)); goto quit;
+ }
+
+ INFO("Reading DNS-SD replies\n");
+ for (int i = 0; i < 10; ++i) {
+ records = mdns_discovery_recv(sock, buffer, capacity,
+ callback, user_data); sleep(1);
+ }
+ */
+
+ INFO("Sending mDNS query\n");
+ if (mdns_query_send(sock, MDNS_RECORDTYPE_PTR,
+ MDNS_STRING_CONST("_hicn._udp.local."), buffer,
+ capacity)) {
+ INFO("Failed to send mDNS query: %s\n", strerror(errno));
+ goto quit;
+ }
+
+ INFO("Reading mDNS replies\n");
+ for (int i = 0; i < 10; ++i) {
+ records = mdns_query_recv(sock, buffer, capacity, callback, user_data, 1);
+ sleep(1);
+ }
quit:
- free(buffer);
+ free(buffer);
- mdns_socket_close(sock);
- INFO("Closed socket\n");
+ mdns_socket_close(sock);
+ INFO("Closed socket\n");
#ifdef _WIN32
- WSACleanup();
+ WSACleanup();
#endif
- return 0;
+ return 0;
}
diff --git a/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.h b/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.h
index ff04b5d72..4b8e7a7f4 100644
--- a/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.h
+++ b/ctrl/facemgr/src/interfaces/bonjour/mdns/mdns.h
@@ -7,7 +7,8 @@
*
* https://github.com/mjansson/mdns
*
- * This library is put in the public domain; you can redistribute it and/or modify it without any restrictions.
+ * This library is put in the public domain; you can redistribute it and/or
+ * modify it without any restrictions.
*
*/
@@ -31,76 +32,73 @@
#define MDNS_INVALID_POS ((size_t)-1)
-#define MDNS_STRING_CONST(s) (s), (sizeof((s))-1)
+#define MDNS_STRING_CONST(s) (s), (sizeof((s)) - 1)
#define MDNS_STRING_FORMAT(s) (int)((s).length), s.str
enum mdns_record_type {
- MDNS_RECORDTYPE_IGNORE = 0,
- //Address
- MDNS_RECORDTYPE_A = 1,
- //Domain Name pointer
- MDNS_RECORDTYPE_PTR = 12,
- //Arbitrary text string
- MDNS_RECORDTYPE_TXT = 16,
- //IP6 Address [Thomson]
- MDNS_RECORDTYPE_AAAA = 28,
- //Server Selection [RFC2782]
- MDNS_RECORDTYPE_SRV = 33
+ MDNS_RECORDTYPE_IGNORE = 0,
+ // Address
+ MDNS_RECORDTYPE_A = 1,
+ // Domain Name pointer
+ MDNS_RECORDTYPE_PTR = 12,
+ // Arbitrary text string
+ MDNS_RECORDTYPE_TXT = 16,
+ // IP6 Address [Thomson]
+ MDNS_RECORDTYPE_AAAA = 28,
+ // Server Selection [RFC2782]
+ MDNS_RECORDTYPE_SRV = 33
};
enum mdns_entry_type {
- MDNS_ENTRYTYPE_ANSWER = 1,
- MDNS_ENTRYTYPE_AUTHORITY = 2,
- MDNS_ENTRYTYPE_ADDITIONAL = 3
+ MDNS_ENTRYTYPE_ANSWER = 1,
+ MDNS_ENTRYTYPE_AUTHORITY = 2,
+ MDNS_ENTRYTYPE_ADDITIONAL = 3
};
-enum mdns_class {
- MDNS_CLASS_IN = 1
-};
+enum mdns_class { MDNS_CLASS_IN = 1 };
-typedef enum mdns_record_type mdns_record_type_t;
-typedef enum mdns_entry_type mdns_entry_type_t;
-typedef enum mdns_class mdns_class_t;
+typedef enum mdns_record_type mdns_record_type_t;
+typedef enum mdns_entry_type mdns_entry_type_t;
+typedef enum mdns_class mdns_class_t;
-typedef int (* mdns_record_callback_fn)(const struct sockaddr* from,
- mdns_entry_type_t entry, uint16_t type,
- uint16_t rclass, uint32_t ttl,
- const void* data, size_t size, size_t offset, size_t length,
- void* user_data);
+typedef int (*mdns_record_callback_fn)(const struct sockaddr* from,
+ mdns_entry_type_t entry, uint16_t type,
+ uint16_t rclass, uint32_t ttl,
+ const void* data, size_t size,
+ size_t offset, size_t length,
+ void* user_data);
-typedef struct mdns_string_t mdns_string_t;
-typedef struct mdns_string_pair_t mdns_string_pair_t;
-typedef struct mdns_record_srv_t mdns_record_srv_t;
-typedef struct mdns_record_txt_t mdns_record_txt_t;
+typedef struct mdns_string_t mdns_string_t;
+typedef struct mdns_string_pair_t mdns_string_pair_t;
+typedef struct mdns_record_srv_t mdns_record_srv_t;
+typedef struct mdns_record_txt_t mdns_record_txt_t;
struct mdns_string_t {
- const char* str;
- size_t length;
+ const char* str;
+ size_t length;
};
struct mdns_string_pair_t {
- size_t offset;
- size_t length;
- int ref;
+ size_t offset;
+ size_t length;
+ int ref;
};
struct mdns_record_srv_t {
- uint16_t priority;
- uint16_t weight;
- uint16_t port;
- mdns_string_t name;
+ uint16_t priority;
+ uint16_t weight;
+ uint16_t port;
+ mdns_string_t name;
};
struct mdns_record_txt_t {
- mdns_string_t key;
- mdns_string_t value;
+ mdns_string_t key;
+ mdns_string_t value;
};
-static int
-mdns_socket_open_ipv4(void);
+static int mdns_socket_open_ipv4(void);
-static int
-mdns_socket_setup_ipv4(int sock);
+static int mdns_socket_setup_ipv4(int sock);
#if 0
static int
@@ -112,8 +110,7 @@ static int
mdns_socket_setup_ipv6(int sock);
#endif
-static void
-mdns_socket_close(int sock);
+static void mdns_socket_close(int sock);
#if 0
static int
@@ -125,21 +122,18 @@ mdns_discovery_recv(int sock, void* buffer, size_t capacity,
mdns_record_callback_fn callback, void* user_data);
#endif
-static int
-mdns_query_send(int sock, mdns_record_type_t type, const char* name, size_t length,
- void* buffer, size_t capacity);
+static int mdns_query_send(int sock, mdns_record_type_t type, const char* name,
+ size_t length, void* buffer, size_t capacity);
-static size_t
-mdns_query_recv(int sock, void* buffer, size_t capacity,
- mdns_record_callback_fn callback, void* user_data,
- uint8_t one_shot);
+static size_t mdns_query_recv(int sock, void* buffer, size_t capacity,
+ mdns_record_callback_fn callback, void* user_data,
+ uint8_t one_shot);
-static mdns_string_t
-mdns_string_extract(const void* buffer, size_t size, size_t* offset,
- char* str, size_t capacity);
+static mdns_string_t mdns_string_extract(const void* buffer, size_t size,
+ size_t* offset, char* str,
+ size_t capacity);
-static int
-mdns_string_skip(const void* buffer, size_t size, size_t* offset);
+static int mdns_string_skip(const void* buffer, size_t size, size_t* offset);
#if 0
static int
@@ -147,78 +141,80 @@ mdns_string_equal(const void* buffer_lhs, size_t size_lhs, size_t* ofs_lhs,
const void* buffer_rhs, size_t size_rhs, size_t* ofs_rhs);
#endif
-static void*
-mdns_string_make(void* data, size_t capacity, const char* name, size_t length);
+static void* mdns_string_make(void* data, size_t capacity, const char* name,
+ size_t length);
-static mdns_string_t
-mdns_record_parse_ptr(const void* buffer, size_t size, size_t offset, size_t length,
- char* strbuffer, size_t capacity);
+static mdns_string_t mdns_record_parse_ptr(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ char* strbuffer, size_t capacity);
-static mdns_record_srv_t
-mdns_record_parse_srv(const void* buffer, size_t size, size_t offset, size_t length,
- char* strbuffer, size_t capacity);
+static mdns_record_srv_t mdns_record_parse_srv(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ char* strbuffer,
+ size_t capacity);
-static struct sockaddr_in*
-mdns_record_parse_a(const void* buffer, size_t size, size_t offset, size_t length,
- struct sockaddr_in* addr);
+static struct sockaddr_in* mdns_record_parse_a(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ struct sockaddr_in* addr);
-static struct sockaddr_in6*
-mdns_record_parse_aaaa(const void* buffer, size_t size, size_t offset, size_t length,
- struct sockaddr_in6* addr);
+static struct sockaddr_in6* mdns_record_parse_aaaa(const void* buffer,
+ size_t size, size_t offset,
+ size_t length,
+ struct sockaddr_in6* addr);
-static size_t
-mdns_record_parse_txt(const void* buffer, size_t size, size_t offset, size_t length,
- mdns_record_txt_t* records, size_t capacity);
+static size_t mdns_record_parse_txt(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ mdns_record_txt_t* records,
+ size_t capacity);
// Implementations
-static int
-mdns_socket_open_ipv4(void) {
- int sock = (int)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if (sock < 0)
- return -1;
- if (mdns_socket_setup_ipv4(sock)) {
- mdns_socket_close(sock);
- return -1;
- }
- return sock;
+static int mdns_socket_open_ipv4(void) {
+ int sock = (int)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (sock < 0) return -1;
+ if (mdns_socket_setup_ipv4(sock)) {
+ mdns_socket_close(sock);
+ return -1;
+ }
+ return sock;
}
-static int
-mdns_socket_setup_ipv4(int sock) {
- struct sockaddr_in saddr;
- memset(&saddr, 0, sizeof(saddr));
- saddr.sin_family = AF_INET;
- saddr.sin_addr.s_addr = INADDR_ANY;
+static int mdns_socket_setup_ipv4(int sock) {
+ struct sockaddr_in saddr;
+ memset(&saddr, 0, sizeof(saddr));
+ saddr.sin_family = AF_INET;
+ saddr.sin_addr.s_addr = INADDR_ANY;
#ifdef __APPLE__
- saddr.sin_len = sizeof(saddr);
+ saddr.sin_len = sizeof(saddr);
#endif
- if (bind(sock, (struct sockaddr*)&saddr, sizeof(saddr)))
- return -1;
+ if (bind(sock, (struct sockaddr*)&saddr, sizeof(saddr))) return -1;
#ifdef _WIN32
- unsigned long param = 1;
- ioctlsocket(sock, FIONBIO, &param);
+ unsigned long param = 1;
+ ioctlsocket(sock, FIONBIO, &param);
#else
- const int flags = fcntl(sock, F_GETFL, 0);
- fcntl(sock, F_SETFL, flags | O_NONBLOCK);
+ const int flags = fcntl(sock, F_GETFL, 0);
+ fcntl(sock, F_SETFL, flags | O_NONBLOCK);
#endif
- unsigned char ttl = 1;
- unsigned char loopback = 1;
- struct ip_mreq req;
+ unsigned char ttl = 1;
+ unsigned char loopback = 1;
+ struct ip_mreq req;
- setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char*)&ttl, sizeof(ttl));
- setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, (const char*)&loopback, sizeof(loopback));
+ setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char*)&ttl,
+ sizeof(ttl));
+ setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, (const char*)&loopback,
+ sizeof(loopback));
- memset(&req, 0, sizeof(req));
- req.imr_multiaddr.s_addr = htonl((((uint32_t)224U) << 24U) | ((uint32_t)251U));
- req.imr_interface.s_addr = INADDR_ANY;
- if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&req, sizeof(req)))
- return -1;
+ memset(&req, 0, sizeof(req));
+ req.imr_multiaddr.s_addr =
+ htonl((((uint32_t)224U) << 24U) | ((uint32_t)251U));
+ req.imr_interface.s_addr = INADDR_ANY;
+ if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&req, sizeof(req)))
+ return -1;
- return 0;
+ return 0;
}
#if 0
@@ -274,67 +270,58 @@ mdns_socket_setup_ipv6(int sock) {
}
#endif
-static void
-mdns_socket_close(int sock) {
+static void mdns_socket_close(int sock) {
#ifdef _WIN32
- closesocket(sock);
+ closesocket(sock);
#else
- close(sock);
+ close(sock);
#endif
}
-static int
-mdns_is_string_ref(uint8_t val) {
- return (0xC0 == (val & 0xC0));
-}
+static int mdns_is_string_ref(uint8_t val) { return (0xC0 == (val & 0xC0)); }
-static mdns_string_pair_t
-mdns_get_next_substring(const void* rawdata, size_t size, size_t offset) {
- const uint8_t* buffer = rawdata;
- mdns_string_pair_t pair = {MDNS_INVALID_POS, 0, 0};
- if (!buffer[offset]) {
- pair.offset = offset;
- return pair;
- }
- if (mdns_is_string_ref(buffer[offset])) {
- if (size < offset + 2)
- return pair;
+static mdns_string_pair_t mdns_get_next_substring(const void* rawdata,
+ size_t size, size_t offset) {
+ const uint8_t* buffer = rawdata;
+ mdns_string_pair_t pair = {MDNS_INVALID_POS, 0, 0};
+ if (!buffer[offset]) {
+ pair.offset = offset;
+ return pair;
+ }
+ if (mdns_is_string_ref(buffer[offset])) {
+ if (size < offset + 2) return pair;
- offset = (((size_t)(0x3f & buffer[offset]) << 8) | (size_t)buffer[offset + 1]);
- if (offset >= size)
- return pair;
+ offset =
+ (((size_t)(0x3f & buffer[offset]) << 8) | (size_t)buffer[offset + 1]);
+ if (offset >= size) return pair;
- pair.ref = 1;
- }
+ pair.ref = 1;
+ }
- size_t length = (size_t)buffer[offset++];
- if (size < offset + length)
- return pair;
+ size_t length = (size_t)buffer[offset++];
+ if (size < offset + length) return pair;
- pair.offset = offset;
- pair.length = length;
+ pair.offset = offset;
+ pair.length = length;
- return pair;
+ return pair;
}
-static int
-mdns_string_skip(const void* buffer, size_t size, size_t* offset) {
- size_t cur = *offset;
- mdns_string_pair_t substr;
- do {
- substr = mdns_get_next_substring(buffer, size, cur);
- if (substr.offset == MDNS_INVALID_POS)
- return 0;
- if (substr.ref) {
- *offset = cur + 2;
- return 1;
- }
- cur = substr.offset + substr.length;
- }
- while (substr.length);
-
- *offset = cur + 1;
- return 1;
+static int mdns_string_skip(const void* buffer, size_t size, size_t* offset) {
+ size_t cur = *offset;
+ mdns_string_pair_t substr;
+ do {
+ substr = mdns_get_next_substring(buffer, size, cur);
+ if (substr.offset == MDNS_INVALID_POS) return 0;
+ if (substr.ref) {
+ *offset = cur + 2;
+ return 1;
+ }
+ cur = substr.offset + substr.length;
+ } while (substr.length);
+
+ *offset = cur + 1;
+ return 1;
}
#if 0
@@ -378,142 +365,133 @@ mdns_string_equal(const void* buffer_lhs, size_t size_lhs, size_t* ofs_lhs,
}
#endif
-static mdns_string_t
-mdns_string_extract(const void* buffer, size_t size, size_t* offset,
- char* str, size_t capacity) {
- size_t cur = *offset;
- size_t end = MDNS_INVALID_POS;
- mdns_string_pair_t substr;
- mdns_string_t result = {str, 0};
- char* dst = str;
- size_t remain = capacity;
- do {
- substr = mdns_get_next_substring(buffer, size, cur);
- if (substr.offset == MDNS_INVALID_POS)
- return result;
- if (substr.ref && (end == MDNS_INVALID_POS))
- end = cur + 2;
- if (substr.length) {
- size_t to_copy = (substr.length < remain) ? substr.length : remain;
- memcpy(dst, (const char*)buffer + substr.offset, to_copy);
- dst += to_copy;
- remain -= to_copy;
- if (remain) {
- *dst++ = '.';
- --remain;
- }
- }
- cur = substr.offset + substr.length;
- }
- while (substr.length);
-
- if (end == MDNS_INVALID_POS)
- end = cur + 1;
- *offset = end;
-
- result.length = capacity - remain;
- return result;
+static mdns_string_t mdns_string_extract(const void* buffer, size_t size,
+ size_t* offset, char* str,
+ size_t capacity) {
+ size_t cur = *offset;
+ size_t end = MDNS_INVALID_POS;
+ mdns_string_pair_t substr;
+ mdns_string_t result = {str, 0};
+ char* dst = str;
+ size_t remain = capacity;
+ do {
+ substr = mdns_get_next_substring(buffer, size, cur);
+ if (substr.offset == MDNS_INVALID_POS) return result;
+ if (substr.ref && (end == MDNS_INVALID_POS)) end = cur + 2;
+ if (substr.length) {
+ size_t to_copy = (substr.length < remain) ? substr.length : remain;
+ memcpy(dst, (const char*)buffer + substr.offset, to_copy);
+ dst += to_copy;
+ remain -= to_copy;
+ if (remain) {
+ *dst++ = '.';
+ --remain;
+ }
+ }
+ cur = substr.offset + substr.length;
+ } while (substr.length);
+
+ if (end == MDNS_INVALID_POS) end = cur + 1;
+ *offset = end;
+
+ result.length = capacity - remain;
+ return result;
}
-static size_t
-mdns_string_find(const char* str, size_t length, char c, size_t offset) {
- const void* found;
- if (offset >= length)
- return MDNS_INVALID_POS;
- found = memchr(str + offset, c, length - offset);
- if (found)
- return (size_t)((const char*)found - str);
- return MDNS_INVALID_POS;
+static size_t mdns_string_find(const char* str, size_t length, char c,
+ size_t offset) {
+ const void* found;
+ if (offset >= length) return MDNS_INVALID_POS;
+ found = memchr(str + offset, c, length - offset);
+ if (found) return (size_t)((const char*)found - str);
+ return MDNS_INVALID_POS;
}
-static void*
-mdns_string_make(void* data, size_t capacity, const char* name, size_t length) {
- size_t pos = 0;
- size_t last_pos = 0;
- size_t remain = capacity;
- unsigned char* dest = data;
- while ((last_pos < length) && ((pos = mdns_string_find(name, length, '.', last_pos)) != MDNS_INVALID_POS)) {
- size_t sublength = pos - last_pos;
- if (sublength < remain) {
- *dest = (unsigned char)sublength;
- memcpy(dest + 1, name + last_pos, sublength);
- dest += sublength + 1;
- remain -= sublength + 1;
- }
- else {
- return 0;
- }
- last_pos = pos + 1;
- }
- if (last_pos < length) {
- size_t sublength = length - last_pos;
- if (sublength < capacity) {
- *dest = (unsigned char)sublength;
- memcpy(dest + 1, name + last_pos, sublength);
- dest += sublength + 1;
- remain -= sublength + 1;
- }
- else {
- return 0;
- }
- }
- if (!remain)
- return 0;
- *dest++ = 0;
- return dest;
+static void* mdns_string_make(void* data, size_t capacity, const char* name,
+ size_t length) {
+ size_t pos = 0;
+ size_t last_pos = 0;
+ size_t remain = capacity;
+ unsigned char* dest = data;
+ while ((last_pos < length) &&
+ ((pos = mdns_string_find(name, length, '.', last_pos)) !=
+ MDNS_INVALID_POS)) {
+ size_t sublength = pos - last_pos;
+ if (sublength < remain) {
+ *dest = (unsigned char)sublength;
+ memcpy(dest + 1, name + last_pos, sublength);
+ dest += sublength + 1;
+ remain -= sublength + 1;
+ } else {
+ return 0;
+ }
+ last_pos = pos + 1;
+ }
+ if (last_pos < length) {
+ size_t sublength = length - last_pos;
+ if (sublength < capacity) {
+ *dest = (unsigned char)sublength;
+ memcpy(dest + 1, name + last_pos, sublength);
+ dest += sublength + 1;
+ remain -= sublength + 1;
+ } else {
+ return 0;
+ }
+ }
+ if (!remain) return 0;
+ *dest++ = 0;
+ return dest;
}
-static size_t
-mdns_records_parse(const struct sockaddr* from, const void* buffer, size_t size, size_t* offset,
- mdns_entry_type_t type, size_t records, mdns_record_callback_fn callback,
- void* user_data) {
- size_t parsed = 0;
- int do_callback = 1;
- for (size_t i = 0; i < records; ++i) {
- mdns_string_skip(buffer, size, offset);
- const uint16_t* data = (const uint16_t*)((const char*)buffer + (*offset));
-
- uint16_t rtype = ntohs(*data++);
- uint16_t rclass = ntohs(*data++);
- uint32_t ttl = ntohs(*(const uint32_t*)(const void*)data); data += 2;
- uint16_t length = ntohs(*data++);
-
- *offset += 10;
-
- if (do_callback) {
- ++parsed;
- if (callback(from, type, rtype, rclass, ttl, buffer, size, *offset, length,
- user_data))
- do_callback = 0;
- }
-
- *offset += length;
- }
- return parsed;
+static size_t mdns_records_parse(const struct sockaddr* from,
+ const void* buffer, size_t size,
+ size_t* offset, mdns_entry_type_t type,
+ size_t records,
+ mdns_record_callback_fn callback,
+ void* user_data) {
+ size_t parsed = 0;
+ int do_callback = 1;
+ for (size_t i = 0; i < records; ++i) {
+ mdns_string_skip(buffer, size, offset);
+ const uint16_t* data = (const uint16_t*)((const char*)buffer + (*offset));
+
+ uint16_t rtype = ntohs(*data++);
+ uint16_t rclass = ntohs(*data++);
+ uint32_t ttl = ntohs(*(const uint32_t*)(const void*)data);
+ data += 2;
+ uint16_t length = ntohs(*data++);
+
+ *offset += 10;
+
+ if (do_callback) {
+ ++parsed;
+ if (callback(from, type, rtype, rclass, ttl, buffer, size, *offset,
+ length, user_data))
+ do_callback = 0;
+ }
+
+ *offset += length;
+ }
+ return parsed;
}
static const uint8_t mdns_services_query[] = {
- // Transaction ID
- 0x00, 0x00,
- // Flags
- 0x00, 0x00,
- // 1 question
- 0x00, 0x01,
- // No answer, authority or additional RRs
- 0x00, 0x00,
- 0x00, 0x00,
- 0x00, 0x00,
- // _services._dns-sd._udp.local.
- 0x09, '_', 's', 'e', 'r', 'v', 'i', 'c', 'e', 's',
- 0x07, '_', 'd', 'n', 's', '-', 's', 'd',
- 0x04, '_', 'u', 'd', 'p',
- 0x05, 'l', 'o', 'c', 'a', 'l',
- 0x00,
- // PTR record
- 0x00, MDNS_RECORDTYPE_PTR,
- // QU (unicast response) and class IN
- 0x80, MDNS_CLASS_IN
-};
+ // Transaction ID
+ 0x00, 0x00,
+ // Flags
+ 0x00, 0x00,
+ // 1 question
+ 0x00, 0x01,
+ // No answer, authority or additional RRs
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ // _services._dns-sd._udp.local.
+ 0x09, '_', 's', 'e', 'r', 'v', 'i', 'c', 'e', 's', 0x07, '_', 'd', 'n', 's',
+ '-', 's', 'd', 0x04, '_', 'u', 'd', 'p', 0x05, 'l', 'o', 'c', 'a', 'l',
+ 0x00,
+ // PTR record
+ 0x00, MDNS_RECORDTYPE_PTR,
+ // QU (unicast response) and class IN
+ 0x80, MDNS_CLASS_IN};
#if 0
static int
@@ -645,233 +623,223 @@ mdns_discovery_recv(int sock, void* buffer, size_t capacity,
static uint16_t mdns_transaction_id = 0;
-static int
-mdns_query_send(int sock, mdns_record_type_t type, const char* name, size_t length,
- void* buffer, size_t capacity) {
- if (capacity < (17 + length))
- return -1;
-
- uint16_t* data = buffer;
- //Transaction ID
- *data++ = htons(++mdns_transaction_id);
- //Flags
- *data++ = 0;
- //Questions
- *data++ = htons(1);
- //No answer, authority or additional RRs
- *data++ = 0;
- *data++ = 0;
- *data++ = 0;
- //Name string
- data = mdns_string_make(data, capacity - 17, name, length);
- if (!data)
- return -1;
- //Record type
- *data++ = htons(type);
- //! Unicast response, class IN
- *data++ = htons(0x8000U | MDNS_CLASS_IN);
-
- struct sockaddr_storage addr_storage;
- struct sockaddr_in addr;
- struct sockaddr_in6 addr6;
- struct sockaddr* saddr = (struct sockaddr*)&addr_storage;
- socklen_t saddrlen = sizeof(struct sockaddr_storage);
- if (getsockname(sock, saddr, &saddrlen))
- return -1;
- if (saddr->sa_family == AF_INET6) {
- memset(&addr6, 0, sizeof(struct sockaddr_in6));
- addr6.sin6_family = AF_INET6;
+static int mdns_query_send(int sock, mdns_record_type_t type, const char* name,
+ size_t length, void* buffer, size_t capacity) {
+ if (capacity < (17 + length)) return -1;
+
+ uint16_t* data = buffer;
+ // Transaction ID
+ *data++ = htons(++mdns_transaction_id);
+ // Flags
+ *data++ = 0;
+ // Questions
+ *data++ = htons(1);
+ // No answer, authority or additional RRs
+ *data++ = 0;
+ *data++ = 0;
+ *data++ = 0;
+ // Name string
+ data = mdns_string_make(data, capacity - 17, name, length);
+ if (!data) return -1;
+ // Record type
+ *data++ = htons(type);
+ //! Unicast response, class IN
+ *data++ = htons(0x8000U | MDNS_CLASS_IN);
+
+ struct sockaddr_storage addr_storage;
+ struct sockaddr_in addr;
+ struct sockaddr_in6 addr6;
+ struct sockaddr* saddr = (struct sockaddr*)&addr_storage;
+ socklen_t saddrlen = sizeof(struct sockaddr_storage);
+ if (getsockname(sock, saddr, &saddrlen)) return -1;
+ if (saddr->sa_family == AF_INET6) {
+ memset(&addr6, 0, sizeof(struct sockaddr_in6));
+ addr6.sin6_family = AF_INET6;
#ifdef __APPLE__
- addr6.sin6_len = sizeof(struct sockaddr_in6);
+ addr6.sin6_len = sizeof(struct sockaddr_in6);
#endif
- addr6.sin6_addr.s6_addr[0] = 0xFF;
- addr6.sin6_addr.s6_addr[1] = 0x02;
- addr6.sin6_addr.s6_addr[15] = 0xFB;
- addr6.sin6_port = htons((unsigned short)5353);
- saddr = (struct sockaddr*)&addr6;
- saddrlen = sizeof(struct sockaddr_in6);
- }
- else {
- memset(&addr, 0, sizeof(struct sockaddr_in));
- addr.sin_family = AF_INET;
+ addr6.sin6_addr.s6_addr[0] = 0xFF;
+ addr6.sin6_addr.s6_addr[1] = 0x02;
+ addr6.sin6_addr.s6_addr[15] = 0xFB;
+ addr6.sin6_port = htons((unsigned short)5353);
+ saddr = (struct sockaddr*)&addr6;
+ saddrlen = sizeof(struct sockaddr_in6);
+ } else {
+ memset(&addr, 0, sizeof(struct sockaddr_in));
+ addr.sin_family = AF_INET;
#ifdef __APPLE__
- addr.sin_len = sizeof(struct sockaddr_in);
+ addr.sin_len = sizeof(struct sockaddr_in);
#endif
- addr.sin_addr.s_addr = htonl((((uint32_t)224U) << 24U) | ((uint32_t)251U));
- addr.sin_port = htons((unsigned short)5353);
- saddr = (struct sockaddr*)&addr;
- saddrlen = sizeof(struct sockaddr_in);
- }
-
- if (sendto(sock, buffer, (char*)data - (char*)buffer, 0,
- saddr, saddrlen) < 0)
- return -1;
- return 0;
+ addr.sin_addr.s_addr = htonl((((uint32_t)224U) << 24U) | ((uint32_t)251U));
+ addr.sin_port = htons((unsigned short)5353);
+ saddr = (struct sockaddr*)&addr;
+ saddrlen = sizeof(struct sockaddr_in);
+ }
+
+ if (sendto(sock, buffer, (char*)data - (char*)buffer, 0, saddr, saddrlen) < 0)
+ return -1;
+ return 0;
}
-static size_t
-mdns_query_recv(int sock, void* buffer, size_t capacity,
- mdns_record_callback_fn callback, void* user_data,
- uint8_t one_shot) {
- struct sockaddr_in6 addr;
- struct sockaddr* saddr = (struct sockaddr*)&addr;
- memset(&addr, 0, sizeof(addr));
- saddr->sa_family = AF_INET;
+static size_t mdns_query_recv(int sock, void* buffer, size_t capacity,
+ mdns_record_callback_fn callback, void* user_data,
+ uint8_t one_shot) {
+ struct sockaddr_in6 addr;
+ struct sockaddr* saddr = (struct sockaddr*)&addr;
+ memset(&addr, 0, sizeof(addr));
+ saddr->sa_family = AF_INET;
#ifdef __APPLE__
- saddr->sa_len = sizeof(addr);
+ saddr->sa_len = sizeof(addr);
#endif
- socklen_t addrlen = sizeof(addr);
- int ret = recvfrom(sock, buffer, capacity, 0,
- saddr, &addrlen);
- if (ret <= 0)
- return 0;
-
- size_t data_size = (size_t)ret;
- uint16_t* data = (uint16_t*)buffer;
-
- uint16_t transaction_id = ntohs(*data++);
- ++data;// uint16_t flags = ntohs(*data++);
- uint16_t questions = ntohs(*data++);
- uint16_t answer_rrs = ntohs(*data++);
- uint16_t authority_rrs = ntohs(*data++);
- uint16_t additional_rrs = ntohs(*data++);
-
- if (one_shot && transaction_id != mdns_transaction_id)// || (flags != 0x8400))
- return 0; //Not a reply to our last question
-
- if (questions > 1)
- return 0;
-
- //Skip questions part
- int i;
- for (i = 0; i < questions; ++i) {
- size_t ofs = (size_t)((char*)data - (char*)buffer);
- if (!mdns_string_skip(buffer, data_size, &ofs))
- return 0;
- data = (void*)((char*)buffer + ofs);
- ++data;
- ++data;
- }
-
- size_t records = 0;
- size_t offset = (size_t)((char*)data - (char*)buffer);
- records += mdns_records_parse(saddr, buffer, data_size, &offset,
- MDNS_ENTRYTYPE_ANSWER, answer_rrs,
- callback, user_data);
- records += mdns_records_parse(saddr, buffer, data_size, &offset,
- MDNS_ENTRYTYPE_AUTHORITY, authority_rrs,
- callback, user_data);
- records += mdns_records_parse(saddr, buffer, data_size, &offset,
- MDNS_ENTRYTYPE_ADDITIONAL, additional_rrs,
- callback, user_data);
- return records;
+ socklen_t addrlen = sizeof(addr);
+ int ret = recvfrom(sock, buffer, capacity, 0, saddr, &addrlen);
+ if (ret <= 0) return 0;
+
+ size_t data_size = (size_t)ret;
+ uint16_t* data = (uint16_t*)buffer;
+
+ uint16_t transaction_id = ntohs(*data++);
+ ++data; // uint16_t flags = ntohs(*data++);
+ uint16_t questions = ntohs(*data++);
+ uint16_t answer_rrs = ntohs(*data++);
+ uint16_t authority_rrs = ntohs(*data++);
+ uint16_t additional_rrs = ntohs(*data++);
+
+ if (one_shot &&
+ transaction_id != mdns_transaction_id) // || (flags != 0x8400))
+ return 0; // Not a reply to our last question
+
+ if (questions > 1) return 0;
+
+ // Skip questions part
+ int i;
+ for (i = 0; i < questions; ++i) {
+ size_t ofs = (size_t)((char*)data - (char*)buffer);
+ if (!mdns_string_skip(buffer, data_size, &ofs)) return 0;
+ data = (void*)((char*)buffer + ofs);
+ ++data;
+ ++data;
+ }
+
+ size_t records = 0;
+ size_t offset = (size_t)((char*)data - (char*)buffer);
+ records += mdns_records_parse(saddr, buffer, data_size, &offset,
+ MDNS_ENTRYTYPE_ANSWER, answer_rrs, callback,
+ user_data);
+ records += mdns_records_parse(saddr, buffer, data_size, &offset,
+ MDNS_ENTRYTYPE_AUTHORITY, authority_rrs,
+ callback, user_data);
+ records += mdns_records_parse(saddr, buffer, data_size, &offset,
+ MDNS_ENTRYTYPE_ADDITIONAL, additional_rrs,
+ callback, user_data);
+ return records;
}
-static mdns_string_t
-mdns_record_parse_ptr(const void* buffer, size_t size, size_t offset, size_t length,
- char* strbuffer, size_t capacity) {
- //PTR record is just a string
- if ((size >= offset + length) && (length >= 2))
- return mdns_string_extract(buffer, size, &offset, strbuffer, capacity);
- mdns_string_t empty = {0, 0};
- return empty;
+static mdns_string_t mdns_record_parse_ptr(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ char* strbuffer, size_t capacity) {
+ // PTR record is just a string
+ if ((size >= offset + length) && (length >= 2))
+ return mdns_string_extract(buffer, size, &offset, strbuffer, capacity);
+ mdns_string_t empty = {0, 0};
+ return empty;
}
-static mdns_record_srv_t
-mdns_record_parse_srv(const void* buffer, size_t size, size_t offset, size_t length,
- char* strbuffer, size_t capacity) {
- mdns_record_srv_t srv;
- memset(&srv, 0, sizeof(mdns_record_srv_t));
- // Read the priority, weight, port number and the discovery name
- // SRV record format (http://www.ietf.org/rfc/rfc2782.txt):
- // 2 bytes network-order unsigned priority
- // 2 bytes network-order unsigned weight
- // 2 bytes network-order unsigned port
- // string: discovery (domain) name, minimum 2 bytes when compressed
- if ((size >= offset + length) && (length >= 8)) {
- const uint16_t* recorddata = (const uint16_t*)((const char*)buffer + offset);
- srv.priority = ntohs(*recorddata++);
- srv.weight = ntohs(*recorddata++);
- srv.port = ntohs(*recorddata++);
- offset += 6;
- srv.name = mdns_string_extract(buffer, size, &offset, strbuffer, capacity);
- }
- return srv;
+static mdns_record_srv_t mdns_record_parse_srv(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ char* strbuffer,
+ size_t capacity) {
+ mdns_record_srv_t srv;
+ memset(&srv, 0, sizeof(mdns_record_srv_t));
+ // Read the priority, weight, port number and the discovery name
+ // SRV record format (http://www.ietf.org/rfc/rfc2782.txt):
+ // 2 bytes network-order unsigned priority
+ // 2 bytes network-order unsigned weight
+ // 2 bytes network-order unsigned port
+ // string: discovery (domain) name, minimum 2 bytes when compressed
+ if ((size >= offset + length) && (length >= 8)) {
+ const uint16_t* recorddata =
+ (const uint16_t*)((const char*)buffer + offset);
+ srv.priority = ntohs(*recorddata++);
+ srv.weight = ntohs(*recorddata++);
+ srv.port = ntohs(*recorddata++);
+ offset += 6;
+ srv.name = mdns_string_extract(buffer, size, &offset, strbuffer, capacity);
+ }
+ return srv;
}
-static struct sockaddr_in*
-mdns_record_parse_a(const void* buffer, size_t size, size_t offset, size_t length,
- struct sockaddr_in* addr) {
- memset(addr, 0, sizeof(struct sockaddr_in));
- addr->sin_family = AF_INET;
+static struct sockaddr_in* mdns_record_parse_a(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ struct sockaddr_in* addr) {
+ memset(addr, 0, sizeof(struct sockaddr_in));
+ addr->sin_family = AF_INET;
#ifdef __APPLE__
- addr->sin_len = sizeof(struct sockaddr_in);
+ addr->sin_len = sizeof(struct sockaddr_in);
#endif
- if ((size >= offset + length) && (length == 4))
- addr->sin_addr.s_addr = *(const uint32_t*)((const char*)buffer + offset);
- return addr;
+ if ((size >= offset + length) && (length == 4))
+ addr->sin_addr.s_addr = *(const uint32_t*)((const char*)buffer + offset);
+ return addr;
}
-static struct sockaddr_in6*
-mdns_record_parse_aaaa(const void* buffer, size_t size, size_t offset, size_t length,
- struct sockaddr_in6* addr) {
- memset(addr, 0, sizeof(struct sockaddr_in6));
- addr->sin6_family = AF_INET6;
+static struct sockaddr_in6* mdns_record_parse_aaaa(const void* buffer,
+ size_t size, size_t offset,
+ size_t length,
+ struct sockaddr_in6* addr) {
+ memset(addr, 0, sizeof(struct sockaddr_in6));
+ addr->sin6_family = AF_INET6;
#ifdef __APPLE__
- addr->sin6_len = sizeof(struct sockaddr_in6);
+ addr->sin6_len = sizeof(struct sockaddr_in6);
#endif
- if ((size >= offset + length) && (length == 16))
- addr->sin6_addr = *(const struct in6_addr*)((const char*)buffer + offset);
- return addr;
+ if ((size >= offset + length) && (length == 16))
+ addr->sin6_addr = *(const struct in6_addr*)((const char*)buffer + offset);
+ return addr;
}
-static size_t
-mdns_record_parse_txt(const void* buffer, size_t size, size_t offset, size_t length,
- mdns_record_txt_t* records, size_t capacity) {
- size_t parsed = 0;
- const char* strdata;
- size_t separator, sublength;
- size_t end = offset + length;
-
- if (size < end)
- end = size;
-
- while ((offset < end) && (parsed < capacity)) {
- strdata = (const char*)buffer + offset;
- sublength = *(const unsigned char*)strdata;
-
- ++strdata;
- offset += sublength + 1;
-
- separator = 0;
- for (size_t c = 0; c < sublength; ++c) {
- //DNS-SD TXT record keys MUST be printable US-ASCII, [0x20, 0x7E]
- if ((strdata[c] < 0x20) || (strdata[c] > 0x7E))
- break;
- if (strdata[c] == '=') {
- separator = c;
- break;
- }
- }
-
- if (!separator)
- continue;
-
- if (separator < sublength) {
- records[parsed].key.str = strdata;
- records[parsed].key.length = separator;
- records[parsed].value.str = strdata + separator + 1;
- records[parsed].value.length = sublength - (separator + 1);
- }
- else {
- records[parsed].key.str = strdata;
- records[parsed].key.length = sublength;
- }
-
- ++parsed;
- }
-
- return parsed;
+static size_t mdns_record_parse_txt(const void* buffer, size_t size,
+ size_t offset, size_t length,
+ mdns_record_txt_t* records,
+ size_t capacity) {
+ size_t parsed = 0;
+ const char* strdata;
+ size_t separator, sublength;
+ size_t end = offset + length;
+
+ if (size < end) end = size;
+
+ while ((offset < end) && (parsed < capacity)) {
+ strdata = (const char*)buffer + offset;
+ sublength = *(const unsigned char*)strdata;
+
+ ++strdata;
+ offset += sublength + 1;
+
+ separator = 0;
+ for (size_t c = 0; c < sublength; ++c) {
+ // DNS-SD TXT record keys MUST be printable US-ASCII, [0x20, 0x7E]
+ if ((strdata[c] < 0x20) || (strdata[c] > 0x7E)) break;
+ if (strdata[c] == '=') {
+ separator = c;
+ break;
+ }
+ }
+
+ if (!separator) continue;
+
+ if (separator < sublength) {
+ records[parsed].key.str = strdata;
+ records[parsed].key.length = separator;
+ records[parsed].value.str = strdata + separator + 1;
+ records[parsed].value.length = sublength - (separator + 1);
+ } else {
+ records[parsed].key.str = strdata;
+ records[parsed].key.length = sublength;
+ }
+
+ ++parsed;
+ }
+
+ return parsed;
}
#ifdef _WIN32
diff --git a/ctrl/facemgr/src/interfaces/dummy/CMakeLists.txt b/ctrl/facemgr/src/interfaces/dummy/CMakeLists.txt
index 05276bc5a..c68c39273 100644
--- a/ctrl/facemgr/src/interfaces/dummy/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/dummy/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/src/interfaces/dummy/dummy.c b/ctrl/facemgr/src/interfaces/dummy/dummy.c
index 69c336e57..df63eef17 100644
--- a/ctrl/facemgr/src/interfaces/dummy/dummy.c
+++ b/ctrl/facemgr/src/interfaces/dummy/dummy.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,7 +19,7 @@
*/
#include <stdlib.h>
-#include <unistd.h> // close
+#include <unistd.h> // close
#include <hicn/facemgr.h>
@@ -36,34 +36,32 @@
* Internal data
*/
typedef struct {
- /* The configuration data will likely be allocated on the stack (or should
- * be freed) by the caller, we recommend to make a copy of this data.
- * This copy can further be altered with default values.
- */
- dummy_cfg_t cfg;
+ /* The configuration data will likely be allocated on the stack (or should
+ * be freed) by the caller, we recommend to make a copy of this data.
+ * This copy can further be altered with default values.
+ */
+ dummy_cfg_t cfg;
- /* ... */
+ /* ... */
- int fd; /* Sample internal data: file descriptor */
+ int fd; /* Sample internal data: file descriptor */
} dummy_data_t;
-int dummy_initialize(interface_t * interface, void * cfg)
-{
- dummy_data_t * data = malloc(sizeof(dummy_data_t));
- if (!data)
- goto ERR_MALLOC;
- interface->data = data;
-
- /* Use default values for unspecified configuration parameters */
- if (cfg) {
- data->cfg = *(dummy_cfg_t *)cfg;
- } else {
- memset(&data->cfg, 0, sizeof(data->cfg));
- }
+int dummy_initialize(interface_t *interface, void *cfg) {
+ dummy_data_t *data = malloc(sizeof(dummy_data_t));
+ if (!data) goto ERR_MALLOC;
+ interface->data = data;
+
+ /* Use default values for unspecified configuration parameters */
+ if (cfg) {
+ data->cfg = *(dummy_cfg_t *)cfg;
+ } else {
+ memset(&data->cfg, 0, sizeof(data->cfg));
+ }
- /* ... */
+ /* ... */
- data->fd = 0;
+ data->fd = 0;
#if 0
if (interface_register_fd(interface, data->fd, NULL) < 0) {
ERROR("[dummy_initialize] Error registering fd");
@@ -71,49 +69,45 @@ int dummy_initialize(interface_t * interface, void * cfg)
}
#endif
- /* ... */
+ /* ... */
- /*
- * We should return a negative value in case of error, and a positive value
- * otherwise:
- * - a file descriptor (>0) will be added to the event loop; or
- * - 0 if we don't use any file descriptor
- */
- return 0;
+ /*
+ * We should return a negative value in case of error, and a positive value
+ * otherwise:
+ * - a file descriptor (>0) will be added to the event loop; or
+ * - 0 if we don't use any file descriptor
+ */
+ return 0;
ERR_FD:
ERR_MALLOC:
- return -1;
+ return -1;
}
-int dummy_finalize(interface_t * interface)
-{
- dummy_data_t * data = (dummy_data_t*)interface->data;
+int dummy_finalize(interface_t *interface) {
+ dummy_data_t *data = (dummy_data_t *)interface->data;
- if (data->fd > 0)
- close(data->fd);
+ if (data->fd > 0) close(data->fd);
- return 0;
+ return 0;
}
-int dummy_callback(interface_t * interface)
-{
- dummy_data_t * data = (dummy_data_t*)interface->data;
- UNUSED(data);
+int dummy_callback(interface_t *interface) {
+ dummy_data_t *data = (dummy_data_t *)interface->data;
+ UNUSED(data);
- /* ... */
+ /* ... */
- return 0;
+ return 0;
}
-int dummy_on_event(interface_t * interface, facelet_t * facelet)
-{
- dummy_data_t * data = (dummy_data_t*)interface->data;
- UNUSED(data);
+int dummy_on_event(interface_t *interface, facelet_t *facelet) {
+ dummy_data_t *data = (dummy_data_t *)interface->data;
+ UNUSED(data);
- /* ... */
+ /* ... */
- return 0;
+ return 0;
}
interface_ops_t dummy_ops = {
diff --git a/ctrl/facemgr/src/interfaces/dummy/dummy.h b/ctrl/facemgr/src/interfaces/dummy/dummy.h
index 22fe5d1a6..f930ead58 100644
--- a/ctrl/facemgr/src/interfaces/dummy/dummy.h
+++ b/ctrl/facemgr/src/interfaces/dummy/dummy.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,7 +28,7 @@
* Configuration data
*/
typedef struct {
- /* ... */
+ /* ... */
} dummy_cfg_t;
#endif /* FACEMGR_INTERFACE_DUMMY_H */
diff --git a/ctrl/facemgr/src/interfaces/hicn_light/CMakeLists.txt b/ctrl/facemgr/src/interfaces/hicn_light/CMakeLists.txt
index ef839a69c..a0fb3e351 100644
--- a/ctrl/facemgr/src/interfaces/hicn_light/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/hicn_light/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,20 +11,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+
+##############################################################
+# Sources
+##############################################################
list(APPEND HEADER_FILES
)
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light.c
)
list(APPEND LIBRARIES
- ${HICNCTRL_LIBRARIES}
+ ${LIBHICNCTRL_LIBRARIES}
)
-
list(APPEND INCLUDE_DIRS
- ${HICNCTRL_INCLUDE_DIR}
+ ${LIBHICNCTRL_INCLUDE_DIR}
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
diff --git a/ctrl/facemgr/src/interfaces/hicn_light/hicn_light.c b/ctrl/facemgr/src/interfaces/hicn_light/hicn_light.c
index b6e0e605a..25cc44caf 100644
--- a/ctrl/facemgr/src/interfaces/hicn_light/hicn_light.c
+++ b/ctrl/facemgr/src/interfaces/hicn_light/hicn_light.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,10 +19,11 @@
*/
#include <assert.h>
#include <stdbool.h>
-#include <stdio.h> // snprintf
-#include <time.h> // time
+#include <stdio.h> // snprintf
+#include <time.h> // time
#include <hicn/ctrl.h>
+#include <hicn/ctrl/socket.h>
#include <hicn/facemgr.h>
#include <hicn/util/ip_address.h>
#include <hicn/util/log.h>
@@ -38,578 +39,631 @@
#define WITH_POLL
typedef enum {
- HL_STATE_UNDEFINED,
- HL_STATE_IDLE,
- HL_STATE_ROUTES_SENT,
- HL_STATE_ROUTES_RECEIVED,
- HL_STATE_FACES_SENT,
- HL_STATE_FACES_RECEIVED,
- HL_STATE_N
+ HL_STATE_UNDEFINED,
+ HL_STATE_IDLE,
+ HL_STATE_ROUTES_SENT,
+ HL_STATE_ROUTES_RECEIVED,
+ HL_STATE_FACES_SENT,
+ HL_STATE_FACES_RECEIVED,
+ HL_STATE_N
} hl_state_t;
typedef struct {
- hc_sock_t * s; /* NULL means no active socket */
- hl_state_t state;
+ hc_sock_t *s; /* NULL means no active socket */
- /* Timer used for forwarder reconnection */
- int reconnect_timer_fd; /* 0 means no active timer */
+ /* Socket for polling, dependent on s */
+ hc_sock_t *sp; /* NULL means no active socket */
- /* Timer used to periodically poll the forwarder face and routing tables */
- int poll_timer_fd;
- hc_data_t * polled_routes;
-} hl_data_t;
+ hl_state_t state;
+
+ /* Timer used for forwarder reconnection */
+ int reconnect_timer_fd; /* 0 means no active timer */
-/* Forward declarations */
-int hl_timeout(interface_t * interface, int fd, void * unused);
+ /* Timer used to periodically poll the forwarder face and routing tables */
+ int poll_timer_fd;
+ hc_data_t *polled_routes;
+} hl_data_t;
#ifdef WITH_POLL
-int hl_process_state(interface_t * interface, int fd, void * unused)
+int hl_process_state(interface_t *interface, int fd, void *unused);
#else
-int hl_process_state(interface_t * interface)
+int hl_process_state(interface_t *interface);
#endif
-{
- hl_data_t * data = (hl_data_t *)interface->data;
-
- /*
- * Every tick we need to probe the forwarder for the list of faces and
- * associated routes.
- *
- * This is used to guess manually added faces and routes
- *
- * TODO ensure we are idle at tick time
- */
-
- switch(data->state)
- {
- case HL_STATE_IDLE:
- assert(!data->polled_routes);
-
- //DEBUG("[hl_process_state] Querying route list");
- if (hc_route_list_async(data->s) < 0) {
- DEBUG("[hl_process_state] Error querying route list");
- return -1;
- }
- data->state = HL_STATE_ROUTES_SENT;
- break;
+void start_poll_timer(interface_t *interface) {
+ hl_data_t *data = (hl_data_t *)interface->data;
- case HL_STATE_ROUTES_RECEIVED:
- //DEBUG("[hl_process_state] Querying face list");
- if (hc_face_list_async(data->s) < 0) {
- DEBUG("[hl_process_state] Error querying face list");
- return -1;
- }
- data->state = HL_STATE_FACES_SENT;
- break;
-
- case HL_STATE_FACES_RECEIVED:
- data->state = HL_STATE_IDLE;
- break;
-
- case HL_STATE_ROUTES_SENT:
- case HL_STATE_FACES_SENT:
- INFO("[hl_process_state] Out of sync... resetting state");
- if (data->polled_routes) {
- hc_data_free(data->polled_routes);
- data->polled_routes = NULL;
- }
- data->state = HL_STATE_IDLE;
- break;
+ data->poll_timer_fd = interface_register_timer(interface, INTERVAL_MS,
+ hl_process_state, interface);
+ if (data->poll_timer_fd < 0) {
+ ERROR("[start_poll_timer) Could not start polling timer");
+ }
+}
- case HL_STATE_UNDEFINED:
- case HL_STATE_N:
- ERROR("[hl_process_state] Unexpected state");
- return -1;
- }
+void stop_poll_timer(interface_t *interface) {
+ hl_data_t *data = (hl_data_t *)interface->data;
- return 0;
+ if (data->poll_timer_fd > 0)
+ if (interface_unregister_timer(interface, data->poll_timer_fd) < 0) {
+ ERROR("[stop_poll_timer] Could not stop polling timer");
+ }
}
-
-int
-hl_after_connect(interface_t * interface)
+#ifdef WITH_POLL
+int hl_process_state(interface_t *interface, int fd, void *unused)
+#else
+int hl_process_state(interface_t *interface)
+#endif
{
- hl_data_t * data = interface->data;
+ hl_data_t *data = (hl_data_t *)interface->data;
+
+ /*
+ * Every tick we need to probe the forwarder for the list of faces and
+ * associated routes.
+ *
+ * This is used to guess manually added faces and routes
+ *
+ * TODO ensure we are idle at tick time
+ */
+
+ switch (data->state) {
+ case HL_STATE_IDLE:
+ assert(!data->polled_routes);
+ stop_poll_timer(interface);
+
+ DEBUG("[hl_process_state] Querying route list");
+ if (hc_route_list_async(data->sp) < 0) {
+ DEBUG("[hl_process_state] Error querying route list");
+ return -1;
+ }
+ data->state = HL_STATE_ROUTES_SENT;
+ break;
+
+ case HL_STATE_ROUTES_RECEIVED:
+ DEBUG("[hl_process_state] Got route list");
+ DEBUG("[hl_process_state] Querying face list");
+ if (hc_face_list_async(data->sp) < 0) {
+ DEBUG("[hl_process_state] Error querying face list");
+ return -1;
+ }
+ data->state = HL_STATE_FACES_SENT;
+ break;
+
+ case HL_STATE_FACES_RECEIVED:
+ DEBUG("[hl_process_state] Got face list");
+ data->state = HL_STATE_IDLE;
+ start_poll_timer(interface);
+ break;
+
+ case HL_STATE_ROUTES_SENT:
+ case HL_STATE_FACES_SENT:
+ WARN("[hl_process_state] Out of sync... resetting state");
+ if (data->polled_routes) {
+ hc_data_free(data->polled_routes);
+ data->polled_routes = NULL;
+ }
+ data->state = HL_STATE_IDLE;
+ start_poll_timer(interface);
+ break;
+
+ case HL_STATE_UNDEFINED:
+ case HL_STATE_N:
+ ERROR("[hl_process_state] Unexpected state");
+ return -1;
+ }
+
+ return 0;
+}
- /* File descriptor for control socket operations */
- if (interface_register_fd(interface, hc_sock_get_fd(data->s), NULL) < 0) {
- ERROR("[hc_connect] Error registering fd");
- goto ERR_FD;
- }
+/*
+ * Called whenever a connection to both sockets succeeds.
+ * Polling will be useful to detect when connection to the forwarder is lost,
+ * and will allow to try reconnect both sockets (the control socket being UDP /
+ * in blocking mode will not detect such loss of connection). Operations on the
+ * control socket that will fail will be reattempted by higher layers.
+ */
+int hl_after_connect(interface_t *interface) {
+ hl_data_t *data = interface->data;
- /* We always restart from the idle phase */
- data->state = HL_STATE_IDLE;
+ /* File descriptor for polling socket operations */
+ if (interface_register_fd(interface, hc_sock_get_fd(data->sp), NULL) < 0) {
+ ERROR("[hc_connect] Error registering fd");
+ goto ERR_FD;
+ }
+ /* We always restart from the idle phase */
+ data->state = HL_STATE_IDLE;
/* poll will replace the original get, ideally we would get notifications */
#ifdef WITH_POLL
- data->poll_timer_fd = interface_register_timer(interface, INTERVAL_MS,
- hl_process_state, interface);
- if (data->poll_timer_fd < 0) {
- ERROR("[hc_connect] Could not initialize polling timer");
- return -1;
- }
+ start_poll_timer(interface);
#else
- hl_process_state(interface);
+ hl_process_state(interface);
#endif
- return 0;
+ return 0;
- //interface_unregister_fd(interface, hc_sock_get_fd(data->s));
+ // interface_unregister_fd(interface, hc_sock_get_fd(data->sp));
ERR_FD:
- return -1;
+ return -1;
}
-int _hl_connect(interface_t * interface);
+int _hl_connect(interface_t *interface);
-int
-hl_connect_timeout(interface_t * interface, int fd, void * unused)
-{
- hl_data_t * data = interface->data;
- assert(fd == data->reconnect_timer_fd);
- _unused(data);
+int hl_connect_timeout(interface_t *interface, int fd, void *unused) {
+ hl_data_t *data = interface->data;
+ assert(fd == data->reconnect_timer_fd);
+ _unused(data);
- int rc = _hl_connect(interface);
- if (rc < 0) {
- DEBUG("[hl_initialize] Error during connection reattempt; next attempt in %ds", INTERVAL_MS / 1000);
- return -1;
- }
+ int rc = _hl_connect(interface);
+ if (rc < 0) {
+ DEBUG(
+ "[hl_initialize] Error during connection reattempt; next attempt in "
+ "%ds",
+ INTERVAL_MS / 1000);
+ return -1;
+ }
- if (interface_unregister_timer(interface, fd) < 0) {
- ERROR("[hl_connect_timeout] Could not cancel timer after successful connect");
- }
+ if (interface_unregister_timer(interface, fd) < 0) {
+ ERROR(
+ "[hl_connect_timeout] Could not cancel timer after successful connect");
+ }
- /* Connect success */
- return hl_after_connect(interface);
+ /* Connect success */
+ return hl_after_connect(interface);
}
+/*
+ * Connection without reattempt. Both control and polling sockets should be
+ * connected to succeed.
+ */
+int _hl_connect(interface_t *interface) {
+ hl_data_t *data = interface->data;
+ assert(!data->s);
+ assert(!data->sp);
+
+ data->s = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, NULL);
+ if (data->s <= 0) {
+ ERROR("[hc_connect] Could not create control socket");
+ goto ERR_SOCK;
+ }
+
+ if (hc_sock_connect(data->s) < 0) {
+ DEBUG("[hc_connect] Could not connect control socket");
+ goto ERR_CONNECT;
+ }
+
+ data->sp = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, NULL);
+ if (data->sp <= 0) {
+ ERROR("[hc_connect] Could not create polling socket");
+ goto ERR_SOCK_POLL;
+ }
+
+ if (hc_sock_connect(data->sp) < 0) {
+ DEBUG("[hc_connect] Could not connect polling socket");
+ goto ERR_CONNECT_POLL;
+ }
+
+ return 0;
+
+ERR_CONNECT_POLL:
+ hc_sock_free(data->sp);
+ data->sp = NULL;
+ERR_SOCK_POLL:
+ERR_CONNECT:
+ hc_sock_free(data->s);
+ data->s = NULL;
+ERR_SOCK:
+ return -1;
+}
-int
-_hl_connect(interface_t * interface)
-{
- hl_data_t * data = interface->data;
- assert(!data->s);
-
- data->s = hc_sock_create();
- if (data->s <= 0) {
- ERROR("[hc_connect] Could not create control socket");
- goto ERR_SOCK;
- }
+int hl_disconnect(interface_t *interface) {
+ hl_data_t *data = (hl_data_t *)interface->data;
+ if (data->reconnect_timer_fd > 0)
+ interface_unregister_timer(interface, data->reconnect_timer_fd);
- if (hc_sock_connect(data->s) < 0) {
- DEBUG("[hc_connect] Could not connect control socket");
- goto ERR_CONNECT;
- }
+ stop_poll_timer(interface);
- return 0;
+ if (data->polled_routes) hc_data_free(data->polled_routes);
-ERR_CONNECT:
+ if (data->s) {
hc_sock_free(data->s);
data->s = NULL;
-ERR_SOCK:
+ }
+
+ if (data->sp) {
+ interface_unregister_fd(interface, hc_sock_get_fd(data->sp));
+ hc_sock_free(data->sp);
+ data->sp = NULL;
+ }
+
+ return 0;
+}
+
+/* Connection with reattempts */
+int hl_connect(interface_t *interface) {
+ hl_data_t *data = interface->data;
+
+ if (_hl_connect(interface) >= 0) return hl_after_connect(interface);
+
+ /* Timer for managing the connection to the forwarder */
+ DEBUG("Connection to forwarder failed... next retry in %ds",
+ INTERVAL_MS / 1000);
+ data->reconnect_timer_fd = interface_register_timer(interface, INTERVAL_MS,
+ hl_connect_timeout, NULL);
+ if (data->reconnect_timer_fd < 0) {
+ ERROR("[hc_connect] Could not initialize reattempt timer");
return -1;
+ }
+ return 0;
}
-int hl_disconnect(interface_t * interface)
-{
- hl_data_t * data = (hl_data_t *) interface->data;
- if (data->reconnect_timer_fd > 0)
- interface_unregister_timer(interface, data->reconnect_timer_fd);
+int hl_initialize(interface_t *interface, void *cfg) {
+ hl_data_t *data = malloc(sizeof(hl_data_t));
+ if (!data) {
+ ERROR("[hicn_light] Out of memory!");
+ goto ERR_MALLOC;
+ }
- if (data->poll_timer_fd > 0)
- interface_unregister_timer(interface, data->poll_timer_fd);
+ data->s = NULL;
+ data->sp = NULL;
+ data->reconnect_timer_fd = 0;
+ data->poll_timer_fd = 0;
+ data->polled_routes = NULL;
+ data->state = HL_STATE_UNDEFINED;
- if (data->polled_routes)
- hc_data_free(data->polled_routes);
+ interface->data = data;
- if (data->s) {
- interface_unregister_fd(interface, hc_sock_get_fd(data->s));
- hc_sock_free(data->s);
- }
+ /* Connect both control and polling sockets */
+ if (hl_connect(interface) < 0) {
+ ERROR("[hl_initialize] Error during connection to forwarder");
+ goto ERR_CONNECT;
+ }
- return 0;
+ return 0;
+
+ERR_CONNECT:
+ free(data);
+ERR_MALLOC:
+ return -1;
}
-int
-hl_connect(interface_t * interface)
-{
- hl_data_t * data = interface->data;
+int hl_finalize(interface_t *interface) {
+ hl_data_t *data = (hl_data_t *)interface->data;
- if (_hl_connect(interface) >= 0)
- return hl_after_connect(interface);
+ hl_disconnect(interface);
- /* Timer for managing the connection to the forwarder */
- DEBUG("Connection to forwarder failed... next retry in %ds", INTERVAL_MS / 1000);
- data->reconnect_timer_fd = interface_register_timer(interface, INTERVAL_MS, hl_connect_timeout, NULL);
- if (data->reconnect_timer_fd < 0) {
- ERROR("[hc_connect] Could not initialize reattempt timer");
- return -1;
- }
+ if (data->polled_routes) hc_data_free(data->polled_routes);
- return 0;
+ free(data);
+
+ return 0;
}
-int
-hl_initialize(interface_t * interface, void * cfg)
-{
- hl_data_t * data = malloc(sizeof(hl_data_t));
- if (!data) {
- ERROR("[hicn_light] Out of memory!");
- goto ERR_MALLOC;
+int hl_on_event(interface_t *interface, facelet_t *facelet) {
+ hc_route_t route;
+ int rc;
+ int ret = 0;
+ hl_data_t *data = (hl_data_t *)interface->data;
+ face_t *face = NULL;
+
+ /* NOTE
+ * - One example where this fails (and it is normal) is when we delete a
+ * face that was not completely created, because for instance bonjour did
+ * not give any data
+ */
+ if (facelet_get_face(facelet, &face) < 0) {
+ ERROR("Could not retrieve face from facelet");
+ ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
+ goto ERR_FACE;
+ }
+
+ if (!data->s) {
+ /* We are not connected to the forwarder */
+ ret = -FACELET_ERROR_REASON_FORWARDER_OFFLINE;
+ goto ERR;
+ }
+
+ switch (facelet_get_event(facelet)) {
+ case FACELET_EVENT_CREATE: {
+ /* Create face */
+ char buf[MAXSZ_FACELET];
+ facelet_snprintf(buf, MAXSZ_FACELET, facelet);
+ DEBUG("Create facelet %s", buf);
+
+ rc = hc_face_create(data->s, face);
+ if (rc < 0) {
+ ERROR("Failed to create face\n");
+ ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
+ goto ERR;
+ }
+ INFO("Created face id=%d - %s", face->id, buf);
}
- data->s = NULL;
- data->reconnect_timer_fd = 0;
- data->poll_timer_fd = 0;
+ hicn_route_t **route_array;
+ int n = facelet_get_route_array(facelet, &route_array);
+ if (n < 0) {
+ ERROR("Failed to create default hICN/IPv4 route");
+ ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
+ goto ERR;
+ }
+ if (n == 0) {
+ /* Adding default routes */
+ route = (hc_route_t){
+ .face_id = face->id,
+ .family = AF_INET,
+ .remote_addr = IPV4_ANY,
+ .len = 0,
+ .cost = DEFAULT_ROUTE_COST,
+
+ };
+ if (hc_route_create(data->s, &route) < 0) {
+ ERROR("Failed to create default hICN/IPv4 route");
+ ret = -1;
+ }
- interface->data = data;
+ route = (hc_route_t){
+ .face_id = face->id,
+ .family = AF_INET6,
+ .remote_addr = IPV6_ANY,
+ .len = 0,
+ .cost = DEFAULT_ROUTE_COST,
+ };
+ if (hc_route_create(data->s, &route) < 0) {
+ ERROR("Failed to create default hICN/IPv6 route");
+ ret = -1;
+ }
- if (hl_connect(interface) < 0) {
- ERROR("[hl_initialize] Error during connection to forwarder");
- goto ERR_CONNECT;
- }
+ INFO("Successfully created default route(s).");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ hicn_route_t *hicn_route = route_array[i];
+ hicn_ip_prefix_t prefix;
+ int cost;
+ if (hicn_route_get_prefix(hicn_route, &prefix) < 0) {
+ ERROR("Failed to get route prefix");
+ ret = -1;
+ continue;
+ }
+ if (hicn_route_get_cost(hicn_route, &cost) < 0) {
+ ERROR("Failed to get route cost");
+ ret = -1;
+ continue;
+ }
+ route = (hc_route_t){
+ .face_id = face->id,
+ .face_name = "", /* take face_id into account */
+ .family = prefix.family,
+ .remote_addr = prefix.address,
+ .len = prefix.len,
+ .cost = cost,
+ };
+ if (hc_route_create(data->s, &route) < 0) {
+ ERROR("Failed to create static route route");
+ ret = -1;
+ continue;
+ }
+ }
+ }
+ free(route_array);
- data->polled_routes = NULL;
+ break;
- return 0;
+ case FACELET_EVENT_DELETE:
+ /* Removing a face should also remove associated routes */
+ rc = hc_face_delete(data->s, face); // delete_listener= */ 1);
+ if (rc < 0) {
+ ERROR("Failed to delete face\n");
+ ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
+ goto ERR;
+ }
-ERR_CONNECT:
- free(data);
-ERR_MALLOC:
- return -1;
-}
+ char buf[MAXSZ_FACELET];
+ facelet_snprintf(buf, MAXSZ_FACELET, facelet);
+ INFO("Deleted face id=%d", face->id);
-int hl_finalize(interface_t * interface)
-{
- hl_data_t * data = (hl_data_t *) interface->data;
+ break;
- hl_disconnect(interface);
+ case FACELET_EVENT_UPDATE:
+ /* Currently, only admin_state & priority are supported */
+ if (facelet_get_admin_state_status(facelet) ==
+ FACELET_ATTR_STATUS_DIRTY) {
+ hc_data_t *face_found;
- if (data->polled_routes)
- hc_data_free(data->polled_routes);
+ rc = hc_face_get(data->s, face, &face_found);
+ if (rc < 0) {
+ ERROR("Failed to find face\n");
+ ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
+ goto ERR;
+ }
+ if (!face_found) {
+ ERROR("Face to update has not been found");
+ ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
+ goto ERR;
+ }
+ char conn_id_or_name[SYMBOLIC_NAME_LEN];
- free(data);
+ const hc_object_t *object = hc_data_get_object(face_found, 0);
+ snprintf(conn_id_or_name, SYMBOLIC_NAME_LEN, "%d", object->face.id);
+ hc_data_free(face_found);
- return 0;
-}
+ face_state_t admin_state;
+ if (facelet_get_admin_state(facelet, &admin_state) < 0) {
+ ERROR("Failed to retrieve facelet admin state");
+ ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
+ goto ERR;
+ }
-int hl_on_event(interface_t * interface, facelet_t * facelet)
-{
- hc_face_t hc_face;
- hc_route_t route;
- int rc;
- int ret = 0;
- hl_data_t * data = (hl_data_t *)interface->data;
- face_t * face = NULL;
-
- hc_face.id = 0;
- memset(hc_face.name, 0, sizeof(hc_face.name));
-
-
- /* NOTE
- * - One example where this fails (and it is normal) is when we delete a
- * face that was not completely created, because for instance bonjour did
- * not give any data
- */
- if (facelet_get_face(facelet, &face) < 0) {
- ERROR("Could not retrieve face from facelet");
- ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
- goto ERR_FACE;
- }
+ if (hc_connection_set_admin_state(data->s, conn_id_or_name,
+ admin_state) < 0) {
+ ERROR("Failed to update admin state");
+ ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
+ goto ERR;
+ }
+ facelet_set_admin_state_status(facelet, FACELET_ATTR_STATUS_CLEAN);
+ INFO("Updated face id=%d - admin_state=%s", face->id,
+ face_state_str(admin_state));
+ }
+ if (facelet_get_netdevice_type_status(facelet) ==
+ FACELET_ATTR_STATUS_DIRTY) {
+ hc_data_t *face_found;
+
+ rc = hc_face_get(data->s, face, &face_found);
+ if (rc < 0) {
+ ERROR("Failed to find face\n");
+ goto ERR;
+ }
+ if (!face_found) {
+ ERROR("Face to update has not been found");
+ goto ERR;
+ }
+ char conn_id_or_name[SYMBOLIC_NAME_LEN];
+ const hc_object_t *object = hc_data_get_object(face_found, 0);
+ snprintf(conn_id_or_name, SYMBOLIC_NAME_LEN, "%d", object->face.id);
+ hc_data_free(face_found);
+
+ netdevice_type_t netdevice_type;
+ if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
+ ERROR("Failed to retrieve facelet netdevice_type");
+ goto ERR;
+ }
- if (!data->s) {
- /* We are not connected to the forwarder */
- ret = -FACELET_ERROR_REASON_FORWARDER_OFFLINE;
- goto ERR;
- }
+ /* Encode netdevice type into tags */
+ policy_tags_t tags = POLICY_TAGS_EMPTY;
+ if (facelet_has_netdevice_type(facelet)) {
+ netdevice_type_t netdevice_type;
+ if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
+ ERROR("error getting netdevice_type");
+ goto ERR;
+ }
+
+ switch (netdevice_type) {
+ case NETDEVICE_TYPE_UNDEFINED:
+ case NETDEVICE_TYPE_LOOPBACK:
+ break;
+ case NETDEVICE_TYPE_WIRED:
+ policy_tags_add(&tags, POLICY_TAG_WIRED);
+ break;
+ case NETDEVICE_TYPE_WIFI:
+ policy_tags_add(&tags, POLICY_TAG_WIFI);
+ break;
+ case NETDEVICE_TYPE_CELLULAR:
+ policy_tags_add(&tags, POLICY_TAG_CELLULAR);
+ break;
+ default:
+ goto ERR;
+ }
+ }
+ // face->tags = tags;
- switch(facelet_get_event(facelet)) {
-
- case FACELET_EVENT_CREATE:
- {
- /* Create face */
- char buf[MAXSZ_FACELET];
- facelet_snprintf(buf, MAXSZ_FACELET, facelet);
- DEBUG("Create facelet %s", buf);
-
- hc_face.face = *face;
- rc = hc_face_create(data->s, &hc_face);
- if (rc < 0) {
- ERROR("Failed to create face\n");
- ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
- goto ERR;
- }
- INFO("Created face id=%d - %s", hc_face.id, buf);
- }
+ if (hc_connection_set_tags(data->s, conn_id_or_name, tags) < 0) {
+ ERROR("Failed to update tags");
+ goto ERR;
+ }
+ facelet_set_netdevice_type_status(facelet, FACELET_ATTR_STATUS_CLEAN);
+ INFO("Updated face id=%d - netdevice_type=%s", face->id,
+ netdevice_type_str(netdevice_type));
+ }
+ if (facelet_get_priority_status(facelet) == FACELET_ATTR_STATUS_DIRTY) {
+ INFO("Updating priority...");
+ hc_data_t *face_found;
+
+ rc = hc_face_get(data->s, face, &face_found);
+ if (rc < 0) {
+ ERROR("Failed to find face\n");
+ goto ERR;
+ }
+ if (!face_found) {
+ ERROR("Face to update has not been found");
+ goto ERR;
+ }
+ char conn_id_or_name[SYMBOLIC_NAME_LEN];
+ const hc_object_t *object = hc_data_get_object(face_found, 0);
+ snprintf(conn_id_or_name, SYMBOLIC_NAME_LEN, "%d", object->face.id);
+ hc_data_free(face_found);
+
+ uint32_t priority;
+ if (facelet_get_priority(facelet, &priority) < 0) {
+ ERROR("Failed to retrieve facelet priority");
+ goto ERR;
+ }
- hicn_route_t ** route_array;
- int n = facelet_get_route_array(facelet, &route_array);
- if (n < 0) {
- ERROR("Failed to create default hICN/IPv4 route");
- ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
- goto ERR;
- }
- if (n == 0) {
- /* Adding default routes */
- route = (hc_route_t) {
- .face_id = hc_face.id,
- .family = AF_INET,
- .remote_addr = IPV4_ANY,
- .len = 0,
- .cost = DEFAULT_ROUTE_COST,
-
- };
- if (hc_route_create(data->s, &route) < 0) {
- ERROR("Failed to create default hICN/IPv4 route");
- ret = -1;
- }
-
- route = (hc_route_t) {
- .face_id = hc_face.id,
- .family = AF_INET6,
- .remote_addr = IPV6_ANY,
- .len = 0,
- .cost = DEFAULT_ROUTE_COST,
- };
- if (hc_route_create(data->s, &route) < 0) {
- ERROR("Failed to create default hICN/IPv6 route");
- ret = -1;
- }
-
- INFO("Successfully created default route(s).");
- } else {
- for (unsigned i = 0; i < n; i++) {
- hicn_route_t * hicn_route = route_array[i];
- ip_prefix_t prefix;
- int cost;
- if (hicn_route_get_prefix(hicn_route, &prefix) < 0) {
- ERROR("Failed to get route prefix");
- ret = -1;
- continue;
- }
- if (hicn_route_get_cost(hicn_route, &cost) < 0) {
- ERROR("Failed to get route cost");
- ret = -1;
- continue;
- }
- route = (hc_route_t) {
- .face_id = hc_face.id,
- .family = prefix.family,
- .remote_addr = prefix.address,
- .len = prefix.len,
- .cost = cost,
- };
- if (hc_route_create(data->s, &route) < 0) {
- ERROR("Failed to create static route route");
- ret = -1;
- continue;
- }
- }
- }
- free(route_array);
-
- break;
-
- case FACELET_EVENT_DELETE:
- /* Removing a face should also remove associated routes */
- hc_face.face = *face;
- rc = hc_face_delete(data->s, &hc_face);
- if (rc < 0) {
- ERROR("Failed to delete face\n");
- ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
- goto ERR;
- }
+ INFO("Changing connection %s priority to %d", conn_id_or_name,
+ priority);
+ if (hc_connection_set_priority(data->s, conn_id_or_name, priority) <
+ 0) {
+ ERROR("Failed to update priority");
+ goto ERR;
+ }
+ facelet_set_priority_status(facelet, FACELET_ATTR_STATUS_CLEAN);
- char buf[MAXSZ_FACELET];
- facelet_snprintf(buf, MAXSZ_FACELET, facelet);
- INFO("Deleted face id=%d", hc_face.id);
-
- break;
-
- case FACELET_EVENT_UPDATE:
- /* Currently, only admin_state & priority are supported */
- if (facelet_get_admin_state_status(facelet) == FACELET_ATTR_STATUS_DIRTY) {
- hc_face.face = *face;
- hc_face_t * face_found;
-
- rc = hc_face_get(data->s, &hc_face, &face_found);
- if (rc < 0) {
- ERROR("Failed to find face\n");
- ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
- goto ERR;
- }
- if (!face_found) {
- ERROR("Face to update has not been found");
- ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
- goto ERR;
- }
- char conn_id_or_name[SYMBOLIC_NAME_LEN];
- snprintf(conn_id_or_name, SYMBOLIC_NAME_LEN, "%d", face_found->id);
- free(face_found);
-
- face_state_t admin_state;
- if (facelet_get_admin_state(facelet, &admin_state) < 0) {
- ERROR("Failed to retrieve facelet admin state");
- ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
- goto ERR;
- }
-
- if (hc_connection_set_admin_state(data->s, conn_id_or_name, admin_state) < 0) {
- ERROR("Failed to update admin state");
- ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR;
- goto ERR;
- }
- facelet_set_admin_state_status(facelet, FACELET_ATTR_STATUS_CLEAN);
- INFO("Updated face id=%d - admin_state=%s", hc_face.id,
- face_state_str[admin_state]);
- }
-#ifdef WITH_POLICY
- if (facelet_get_netdevice_type_status(facelet) == FACELET_ATTR_STATUS_DIRTY) {
- hc_face.face = *face;
- hc_face_t * face_found;
-
- rc = hc_face_get(data->s, &hc_face, &face_found);
- if (rc < 0) {
- ERROR("Failed to find face\n");
- goto ERR;
- }
- if (!face_found) {
- ERROR("Face to update has not been found");
- goto ERR;
- }
- char conn_id_or_name[SYMBOLIC_NAME_LEN];
- snprintf(conn_id_or_name, SYMBOLIC_NAME_LEN, "%d", face_found->id);
- free(face_found);
-
- netdevice_type_t netdevice_type;
- if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
- ERROR("Failed to retrieve facelet netdevice_type");
- goto ERR;
- }
-
- /* Encode netdevice type into tags */
- policy_tags_t tags = POLICY_TAGS_EMPTY;
- if (facelet_has_netdevice_type(facelet)) {
- netdevice_type_t netdevice_type;
- if (facelet_get_netdevice_type(facelet, &netdevice_type) < 0) {
- ERROR("error getting netdevice_type");
- goto ERR;
- }
-
-
- switch(netdevice_type) {
- case NETDEVICE_TYPE_UNDEFINED:
- case NETDEVICE_TYPE_LOOPBACK:
- break;
- case NETDEVICE_TYPE_WIRED:
- policy_tags_add(&tags, POLICY_TAG_WIRED);
- break;
- case NETDEVICE_TYPE_WIFI:
- policy_tags_add(&tags, POLICY_TAG_WIFI);
- break;
- case NETDEVICE_TYPE_CELLULAR:
- policy_tags_add(&tags, POLICY_TAG_CELLULAR);
- break;
- default:
- goto ERR;
- }
- }
- //face->tags = tags;
-
- if (hc_connection_set_tags(data->s, conn_id_or_name, tags) < 0) {
- ERROR("Failed to update tags");
- goto ERR;
- }
- facelet_set_netdevice_type_status(facelet, FACELET_ATTR_STATUS_CLEAN);
- INFO("Updated face id=%d - netdevice_type=%s", hc_face.id,
- netdevice_type_str[netdevice_type]);
- }
- if (facelet_get_priority_status(facelet) == FACELET_ATTR_STATUS_DIRTY) {
- INFO("Updating priority...");
- hc_face.face = *face;
- hc_face_t * face_found;
-
- rc = hc_face_get(data->s, &hc_face, &face_found);
- if (rc < 0) {
- ERROR("Failed to find face\n");
- goto ERR;
- }
- if (!face_found) {
- ERROR("Face to update has not been found");
- goto ERR;
- }
- char conn_id_or_name[SYMBOLIC_NAME_LEN];
- snprintf(conn_id_or_name, SYMBOLIC_NAME_LEN, "%d", face_found->id);
- free(face_found);
-
- uint32_t priority;
- if (facelet_get_priority(facelet, &priority) < 0) {
- ERROR("Failed to retrieve facelet priority");
- goto ERR;
- }
-
- INFO("Changing connection %s priority to %d", conn_id_or_name, priority);
- if (hc_connection_set_priority(data->s, conn_id_or_name, priority) < 0) {
- ERROR("Failed to update priority");
- goto ERR;
- }
- facelet_set_priority_status(facelet, FACELET_ATTR_STATUS_CLEAN);
-
- INFO("Updated face id=%d - priority=%d", hc_face.id, priority);
- }
-#endif /* WITH_POLICY */
- break;
+ INFO("Updated face id=%d - priority=%d", face->id, priority);
+ }
+ break;
- default:
- ERROR("Unknown event %s\n", facelet_event_str[facelet_get_event(facelet)]);
- /* Unsupported events */
- ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
- goto ERR;
- }
+ default:
+ ERROR("Unknown event %s\n",
+ facelet_event_str[facelet_get_event(facelet)]);
+ /* Unsupported events */
+ ret = -FACELET_ERROR_REASON_INTERNAL_ERROR;
+ goto ERR;
+ }
ERR:
- face_free(face);
+ face_free(face);
ERR_FACE:
- return ret;
+ return ret;
}
-int hl_callback(interface_t * interface, int fd, void * unused)
-{
- hl_data_t * data = (hl_data_t*)interface->data;
- hc_data_t * results;
- int ret = 0;
-
- /* In case of error, reconnect to forwarder */
- if (hc_sock_callback(data->s, &results) < 0) {
- DEBUG("Closing socket... reconnecting...");
- if (interface_unregister_fd(interface, hc_sock_get_fd(data->s)) < 0) {
- ERROR("[hl_callback] Error unregistering fd");
- }
-
- /* Stopping poll timer */
- if (interface_unregister_timer(interface, data->poll_timer_fd) < 0) {
- ERROR("[hl_callback] Could not cancel polling timer after forwarder disconnect");
- }
- if (data->polled_routes)
- hc_data_free(data->polled_routes);
+/*
+ * This should only receive data from the polling socket which is asynchronous,
+ * while all face creation, etc. operations are done synchronously in this
+ * version.
+ */
+int hl_callback(interface_t *interface, int fd, void *unused) {
+ hl_data_t *data = (hl_data_t *)interface->data;
+ hc_data_t *results;
+ int ret = 0;
+
+ /* Workaround: sometimes this is called with data = NULL */
+ if (!data) {
+ INFO("[hl_callback] no data");
+ return 0;
+ }
- hc_sock_free(data->s);
- data->s = NULL;
- hl_connect(interface);
- return ret;
+ /* In case of error, reconnect to forwarder */
+ if (hc_sock_receive_all(data->sp, &results) < 0) {
+ INFO("Closing socket... reconnecting...");
+ if (interface_unregister_fd(interface, hc_sock_get_fd(data->sp)) < 0) {
+ ERROR("[hl_callback] Error unregistering fd");
}
- /* Shall we wait for more data ? */
- if (!results->complete)
- return ret;
+ /* Stopping poll timer */
+ stop_poll_timer(interface);
+ if (data->polled_routes) hc_data_free(data->polled_routes);
+
+ hc_sock_free(data->s);
+ data->s = NULL;
+ hc_sock_free(data->sp);
+ data->sp = NULL;
- /* Process returned data */
- switch(data->state) {
+ hl_connect(interface);
+ return ret;
+ }
+
+ /* Shall we wait for more data ? */
+ if (!hc_data_is_complete(results)) {
+ INFO("[hl_callback] results incomplete");
+ return ret;
+ }
- case HL_STATE_ROUTES_SENT:
- //DEBUG("[hl_callback] Processing routes");
- data->polled_routes = results;
+ /* Process returned data */
+ // DEBUG("Processing data");
+ switch (data->state) {
+ case HL_STATE_ROUTES_SENT:
+ // DEBUG("[hl_callback] Processing routes");
+ data->polled_routes = results;
#if 0
foreach_route(r, results) {
@@ -622,19 +676,17 @@ int hl_callback(interface_t * interface, int fd, void * unused)
DEBUG("Route: %s", buf);
}
#endif
- data->state = HL_STATE_ROUTES_RECEIVED;
- if (hl_process_state(interface, fd, unused) < 0) {
- ERROR("[hl_callback] Error processing state after routes received");
- ret = -1;
- }
- break;
-
-
- case HL_STATE_FACES_SENT:
- //DEBUG("[hl_callback] Processing faces");
- assert(data->polled_routes);
- foreach_face(f, results) {
-
+ data->state = HL_STATE_ROUTES_RECEIVED;
+ if (hl_process_state(interface, fd, unused) < 0) {
+ ERROR("[hl_callback] Error processing state after routes received");
+ ret = -1;
+ }
+ break;
+
+ case HL_STATE_FACES_SENT:
+ // DEBUG("[hl_callback] Processing faces");
+ assert(data->polled_routes);
+ foreach_face(f, results) {
#if 0
char buf[MAXSZ_FACE];
int rc = hc_face_snprintf(buf, MAXSZ_FACE, f);
@@ -646,17 +698,16 @@ int hl_callback(interface_t * interface, int fd, void * unused)
DEBUG("Face: %s", buf);
#endif
- /* We can ignore faces on localhost */
+ /* We can ignore faces on localhost */
- facelet_t * facelet = facelet_create_from_face(&f->face);
- if (!facelet) {
- ERROR("[hl_callback] Could not create facelet... skipping");
- continue;
- }
+ facelet_t *facelet = facelet_create_from_face(f);
+ if (!facelet) {
+ ERROR("[hl_callback] Could not create facelet... skipping");
+ continue;
+ }
- foreach_route(r, data->polled_routes) {
- if (r->face_id != f->id)
- continue;
+ foreach_route(r, data->polled_routes) {
+ if (r->face_id != f->id) continue;
#if 0
char route_s[MAXSZ_HC_ROUTE];
@@ -668,41 +719,40 @@ int hl_callback(interface_t * interface, int fd, void * unused)
DEBUG("Associated route: %s", route_s);
#endif
- if (r->len == 0)
- continue;
-
- ip_prefix_t prefix = {
- .family = r->family,
- .address = r->remote_addr,
- .len = r->len,
- };
- hicn_route_t * route = hicn_route_create(&prefix, r->face_id, r->cost);
- facelet_add_route(facelet, route);
- }
+ if (r->len == 0) continue;
- facelet_set_event(facelet, FACELET_EVENT_GET);
- interface_raise_event(interface, facelet);
- }
- hc_data_free(results);
- hc_data_free(data->polled_routes);
- data->polled_routes = NULL;
- data->state = HL_STATE_FACES_RECEIVED;
- if (hl_process_state(interface, fd, unused) < 0) {
- ERROR("[hl_callback] Error processing state after faces received");
- ret = -1;
- }
- break;
-
- case HL_STATE_IDLE:
- case HL_STATE_FACES_RECEIVED:
- case HL_STATE_ROUTES_RECEIVED:
- case HL_STATE_UNDEFINED:
- case HL_STATE_N:
- ERROR("[hl_callback] Unexpected state");
- ret = -1;
- }
+ hicn_ip_prefix_t prefix = {
+ .family = r->family,
+ .address = r->remote_addr,
+ .len = r->len,
+ };
+ hicn_route_t *route = hicn_route_create(&prefix, r->face_id, r->cost);
+ facelet_add_route(facelet, route);
+ }
- return ret;
+ facelet_set_event(facelet, FACELET_EVENT_GET);
+ interface_raise_event(interface, facelet);
+ }
+ hc_data_free(results);
+ hc_data_free(data->polled_routes);
+ data->polled_routes = NULL;
+ data->state = HL_STATE_FACES_RECEIVED;
+ if (hl_process_state(interface, fd, unused) < 0) {
+ ERROR("[hl_callback] Error processing state after faces received");
+ ret = -1;
+ }
+ break;
+
+ case HL_STATE_IDLE:
+ case HL_STATE_FACES_RECEIVED:
+ case HL_STATE_ROUTES_RECEIVED:
+ case HL_STATE_UNDEFINED:
+ case HL_STATE_N:
+ ERROR("[hl_callback] Unexpected state");
+ ret = -1;
+ }
+
+ return ret;
}
const interface_ops_t hicn_light_ops = {
diff --git a/ctrl/facemgr/src/interfaces/netlink/CMakeLists.txt b/ctrl/facemgr/src/interfaces/netlink/CMakeLists.txt
index 7f44d87fe..5d46cb8b6 100644
--- a/ctrl/facemgr/src/interfaces/netlink/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/netlink/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/src/interfaces/netlink/netlink.c b/ctrl/facemgr/src/interfaces/netlink/netlink.c
index a1affd719..3c99dc5cc 100644
--- a/ctrl/facemgr/src/interfaces/netlink/netlink.c
+++ b/ctrl/facemgr/src/interfaces/netlink/netlink.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,9 +20,9 @@
#include <assert.h>
#include <linux/rtnetlink.h>
-#include <net/if_arp.h> // ARPHRD_LOOPBACK
-#include <sys/types.h> // getpid
-#include <unistd.h> // getpid
+#include <net/if_arp.h> // ARPHRD_LOOPBACK
+#include <sys/types.h> // getpid
+#include <unistd.h> // getpid
#include <hicn/facemgr.h>
#include <hicn/util/ip_address.h>
@@ -32,202 +32,188 @@
#include "../../interface.h"
typedef enum {
- NL_STATE_UNDEFINED,
- NL_STATE_LINK_SENT,
- NL_STATE_ADDR_SENT,
- NL_STATE_DONE,
+ NL_STATE_UNDEFINED,
+ NL_STATE_LINK_SENT,
+ NL_STATE_ADDR_SENT,
+ NL_STATE_DONE,
} nl_state_t;
/* Internal data storage */
typedef struct {
- int fd;
- nl_state_t state;
+ int fd;
+ nl_state_t state;
} nl_data_t;
-static inline void parse_rtattr(struct rtattr *tb[], int max, struct rtattr *rta, int len,
- unsigned short flags)
-{
- unsigned short type;
-
- memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
- while (RTA_OK(rta, len)) {
- type = rta->rta_type & ~flags;
- if (type <= max)
- tb[type] = rta;
- rta = RTA_NEXT(rta, len);
- }
+static inline void parse_rtattr(struct rtattr *tb[], int max,
+ struct rtattr *rta, int len,
+ unsigned short flags) {
+ unsigned short type;
+
+ memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
+ while (RTA_OK(rta, len)) {
+ type = rta->rta_type & ~flags;
+ if (type <= max) tb[type] = rta;
+ rta = RTA_NEXT(rta, len);
+ }
}
-int nl_process_state(interface_t * interface)
-{
- nl_data_t * data = (nl_data_t*)interface->data;
- int rc;
-
- switch(data->state) {
- case NL_STATE_UNDEFINED:
- {
- DEBUG("[nl_process_state] UNDEFINED->LINK_SENT");
- struct {
- struct nlmsghdr header;
- struct rtgenmsg payload;
- } msg2 = {
- .header = {
- .nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
- .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
- .nlmsg_type = RTM_GETLINK,
- .nlmsg_pid = getpid(),
- .nlmsg_seq = 3,
- },
+int nl_process_state(interface_t *interface) {
+ nl_data_t *data = (nl_data_t *)interface->data;
+ int rc;
+
+ switch (data->state) {
+ case NL_STATE_UNDEFINED: {
+ DEBUG("[nl_process_state] UNDEFINED->LINK_SENT");
+ struct {
+ struct nlmsghdr header;
+ struct rtgenmsg payload;
+ } msg2 = {.header =
+ {
+ .nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
+ .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
+ .nlmsg_type = RTM_GETLINK,
+ .nlmsg_pid = getpid(),
+ .nlmsg_seq = 3,
+ },
.payload = {
.rtgen_family = AF_PACKET,
- }
- };
-
- rc = send(data->fd, &msg2, msg2.header.nlmsg_len, 0);
- if (rc < 0)
- printf("E: Error sending netlink query\n");
+ }};
- data->state = NL_STATE_LINK_SENT;
- break;
- }
-
- case NL_STATE_LINK_SENT:
- {
- DEBUG("[nl_process_state] LINK_SENT->ADDR_SENT");
- /* Issue a first query to receive static state */
- struct {
- struct nlmsghdr header;
- struct ifaddrmsg payload;
- } msg = {
- .header = {
- .nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)),
- .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
- .nlmsg_type = RTM_GETADDR,
- .nlmsg_pid = getpid(),
- .nlmsg_seq = 7,
- },
- .payload = {
- .ifa_family = AF_INET,
- }
- };
+ rc = send(data->fd, &msg2, msg2.header.nlmsg_len, 0);
+ if (rc < 0) printf("E: Error sending netlink query\n");
- rc = send(data->fd, &msg, msg.header.nlmsg_len, 0);
- if (rc < 0)
- printf("E: Error sending netlink query\n");
-
- data->state = NL_STATE_ADDR_SENT;
- break;
- }
+ data->state = NL_STATE_LINK_SENT;
+ break;
+ }
- case NL_STATE_ADDR_SENT:
- {
- DEBUG("[nl_process_state] ADDR_SENT->DONE");
- data->state = NL_STATE_DONE;
- break;
- }
+ case NL_STATE_LINK_SENT: {
+ DEBUG("[nl_process_state] LINK_SENT->ADDR_SENT");
+ /* Issue a first query to receive static state */
+ struct {
+ struct nlmsghdr header;
+ struct ifaddrmsg payload;
+ } msg = {.header =
+ {
+ .nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)),
+ .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
+ .nlmsg_type = RTM_GETADDR,
+ .nlmsg_pid = getpid(),
+ .nlmsg_seq = 7,
+ },
+ .payload = {
+ .ifa_family = AF_INET,
+ }};
+
+ rc = send(data->fd, &msg, msg.header.nlmsg_len, 0);
+ if (rc < 0) printf("E: Error sending netlink query\n");
+
+ data->state = NL_STATE_ADDR_SENT;
+ break;
+ }
- default: /* NL_STATE_DONE never called */
- break;
+ case NL_STATE_ADDR_SENT: {
+ DEBUG("[nl_process_state] ADDR_SENT->DONE");
+ data->state = NL_STATE_DONE;
+ break;
}
- return 0;
+ default: /* NL_STATE_DONE never called */
+ break;
+ }
+
+ return 0;
}
-int nl_initialize(interface_t * interface, void * cfg)
-{
- nl_data_t * data = malloc(sizeof(nl_data_t));
- if (!data)
- goto ERR_MALLOC;
+int nl_initialize(interface_t *interface, void *cfg) {
+ nl_data_t *data = malloc(sizeof(nl_data_t));
+ if (!data) goto ERR_MALLOC;
- data->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
- if (data->fd < 0) {
- ERROR("[nl_initialize] Failed to create netlink socket: %s", (char*)strerror(errno));
- goto ERR_SOCKET;
- }
+ data->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
+ if (data->fd < 0) {
+ ERROR("[nl_initialize] Failed to create netlink socket: %s",
+ (char *)strerror(errno));
+ goto ERR_SOCKET;
+ }
- data->state = NL_STATE_UNDEFINED;
+ data->state = NL_STATE_UNDEFINED;
- struct sockaddr_nl local; // local addr struct
- memset(&local, 0, sizeof(local));
- local.nl_family = AF_NETLINK; // set protocol family
- // NOTE: RTNLGRP_LINK replaces obsolete RTMGRP_LINK, etc
- local.nl_groups = 0
- | RTMGRP_LINK
- | RTMGRP_IPV4_IFADDR
- | RTMGRP_IPV6_IFADDR
+ struct sockaddr_nl local; // local addr struct
+ memset(&local, 0, sizeof(local));
+ local.nl_family = AF_NETLINK; // set protocol family
+ // NOTE: RTNLGRP_LINK replaces obsolete RTMGRP_LINK, etc
+ local.nl_groups = 0 | RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR
#if 0
| RTMGRP_IPV4_ROUTE;
| RTMGRP_IPV6_ROUTE;
#endif
- ;
- local.nl_pid = getpid(); // set out id using current process id
+ ;
+ local.nl_pid = getpid(); // set out id using current process id
- if (bind(data->fd, (struct sockaddr*)&local, sizeof(local)) < 0) { // bind socket
- ERROR("[nl_initialize] Failed to bind netlink socket: %s", (char*)strerror(errno));
- goto ERR_BIND;
- }
+ if (bind(data->fd, (struct sockaddr *)&local, sizeof(local)) <
+ 0) { // bind socket
+ ERROR("[nl_initialize] Failed to bind netlink socket: %s",
+ (char *)strerror(errno));
+ goto ERR_BIND;
+ }
- interface->data = data;
+ interface->data = data;
- if (interface_register_fd(interface, data->fd, NULL) < 0) {
- ERROR("[nl_initialize] Error registering fd");
- goto ERR_FD;
- }
+ if (interface_register_fd(interface, data->fd, NULL) < 0) {
+ ERROR("[nl_initialize] Error registering fd");
+ goto ERR_FD;
+ }
#if 1
- nl_process_state(interface);
+ nl_process_state(interface);
#endif
- return 0;
+ return 0;
ERR_FD:
ERR_BIND:
- close(data->fd);
+ close(data->fd);
ERR_SOCKET:
- free(data);
+ free(data);
ERR_MALLOC:
- return -1;
+ return -1;
}
-int parse_link(struct nlmsghdr * h, facelet_t ** facelet,
- char * interface_name, size_t interface_name_size,
- bool * up, bool * running)
-{
- struct ifinfomsg *ifi; // structure for network interface info
- struct rtattr *tb[IFLA_MAX + 1];
+int parse_link(struct nlmsghdr *h, facelet_t **facelet, char *interface_name,
+ size_t interface_name_size, bool *up, bool *running) {
+ struct ifinfomsg *ifi; // structure for network interface info
+ struct rtattr *tb[IFLA_MAX + 1];
- assert(facelet);
+ assert(facelet);
- ifi = (struct ifinfomsg*) NLMSG_DATA(h); // get information about changed network interface
- parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(h), 1<<15);
+ ifi = (struct ifinfomsg *)NLMSG_DATA(
+ h); // get information about changed network interface
+ parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(h), 1 << 15);
- if (interface_name) {
- assert(tb[IFLA_IFNAME]);
- snprintf(interface_name, interface_name_size, "%s", (char*)RTA_DATA(tb[IFLA_IFNAME]));
- }
+ if (interface_name) {
+ assert(tb[IFLA_IFNAME]);
+ snprintf(interface_name, interface_name_size, "%s",
+ (char *)RTA_DATA(tb[IFLA_IFNAME]));
+ }
- if (up)
- *up = ifi->ifi_flags & IFF_UP;
- if (running)
- *running = ifi->ifi_flags & IFF_RUNNING;
+ if (up) *up = ifi->ifi_flags & IFF_UP;
+ if (running) *running = ifi->ifi_flags & IFF_RUNNING;
+ netdevice_t *netdevice = netdevice_create_from_name(interface_name);
+ if (!netdevice) {
+ ERROR("[netlink.parse_link] error creating netdevice '%s'", interface_name);
+ goto ERR_ND;
+ }
- netdevice_t * netdevice = netdevice_create_from_name(interface_name);
- if (!netdevice) {
- ERROR("[netlink.parse_link] error creating netdevice '%s'", interface_name);
- goto ERR_ND;
- }
+ *facelet = facelet_create();
+ if (!*facelet) {
+ ERROR("[netlink.parse_link] error creating facelet");
+ goto ERR_FACELET;
+ }
- *facelet = facelet_create();
- if (!*facelet) {
- ERROR("[netlink.parse_link] error creating facelet");
- goto ERR_FACELET;
- }
-
- if (facelet_set_netdevice(*facelet, *netdevice) < 0) {
- ERROR("[netlink.parse_link] error setting netdevice");
- goto ERR;
- }
+ if (facelet_set_netdevice(*facelet, *netdevice) < 0) {
+ ERROR("[netlink.parse_link] error setting netdevice");
+ goto ERR;
+ }
// FIXME Tags
#if 0
@@ -252,160 +238,162 @@ int parse_link(struct nlmsghdr * h, facelet_t ** facelet,
#endif
- // TODO
- // - ifi_change
- // - IFLA_PROTINFO
+ // TODO
+ // - ifi_change
+ // - IFLA_PROTINFO
- netdevice_free(netdevice);
- return 0;
+ netdevice_free(netdevice);
+ return 0;
ERR:
- facelet_free(*facelet);
- *facelet = NULL;
+ facelet_free(*facelet);
+ *facelet = NULL;
ERR_FACELET:
- netdevice_free(netdevice);
+ netdevice_free(netdevice);
ERR_ND:
- return -1;
+ return -1;
}
-int parse_addr(struct nlmsghdr * h, facelet_t ** facelet,
- char * interface_name, size_t interface_name_size,
- char * interface_address, size_t interface_address_size)
-{
- ip_address_t local_addr = IP_ADDRESS_EMPTY;
- struct ifaddrmsg *ifa; // structure for network interface data
- struct rtattr *tba[IFA_MAX+1];
-
- assert(facelet);
-
- ifa = (struct ifaddrmsg*)NLMSG_DATA(h); // get data from the network interface
-
- parse_rtattr(tba, IFA_MAX, IFA_RTA(ifa), IFA_PAYLOAD(h), 0);
-
- /* FIXME
- *
- * IFA_LOCAL ok for v4, not there for v6
- *
- * IFA_ADDRESS seems to work for both but with the following precaution
- *
- * IFA_ADDRESS is prefix address, rather than local interface address.
- * It makes no difference for normally configured broadcast interfaces,
- * but for point-to-point IFA_ADDRESS is DESTINATION address,
- * local address is supplied in IFA_LOCAL attribute.
- */
- if (!tba[IFA_ADDRESS]) {
- ERROR("[netlink.parse_addr] No local address");
- return -1;
- }
-
- switch(ifa->ifa_family) {
- case AF_INET:
- local_addr.v4.as_inaddr = *(struct in_addr*)RTA_DATA(tba[IFA_ADDRESS]);
- break;
- case AF_INET6:
- local_addr.v6.as_in6addr = *(struct in6_addr*)RTA_DATA(tba[IFA_ADDRESS]);
- break;
- default:
- return 0;
- }
-
- /* See comment in parse_link */
- if (interface_address) {
- assert(tba[IFA_ADDRESS]);
- ip_address_snprintf(interface_address, interface_address_size, &local_addr, ifa->ifa_family);
- }
-
- netdevice_t * netdevice = netdevice_create_from_index(ifa->ifa_index);
- if (!netdevice) {
- ERROR("[netlink.parse_addr] error creating netdevice from index '%d'", ifa->ifa_index);
- goto ERR_ND;
- }
-
- if (interface_name) {
- snprintf(interface_name, interface_name_size, "%s", netdevice->name);
- }
-
- *facelet = facelet_create();
- if (!*facelet) {
- ERROR("[netlink.parse_addr] error creating facelet");
- goto ERR_FACELET;
- }
- if (facelet_set_netdevice(*facelet, *netdevice) < 0) {
- ERROR("[netlink.parse_addr] error setting netdevice");
- goto ERR;
- }
- if (facelet_set_family(*facelet, ifa->ifa_family) < 0) {
- ERROR("[netlink.parse_addr] error setting family");
- goto ERR;
- }
- if (facelet_set_local_addr(*facelet, local_addr) < 0) {
- ERROR("[netlink.parse_addr] error setting local address");
- goto ERR;
- }
-
- netdevice_free(netdevice);
- return 0;
+int parse_addr(struct nlmsghdr *h, facelet_t **facelet, char *interface_name,
+ size_t interface_name_size, char *interface_address,
+ size_t interface_address_size) {
+ hicn_ip_address_t local_addr = IP_ADDRESS_EMPTY;
+ struct ifaddrmsg *ifa; // structure for network interface data
+ struct rtattr *tba[IFA_MAX + 1];
+
+ assert(facelet);
+
+ ifa =
+ (struct ifaddrmsg *)NLMSG_DATA(h); // get data from the network interface
+
+ parse_rtattr(tba, IFA_MAX, IFA_RTA(ifa), IFA_PAYLOAD(h), 0);
+
+ /* FIXME
+ *
+ * IFA_LOCAL ok for v4, not there for v6
+ *
+ * IFA_ADDRESS seems to work for both but with the following precaution
+ *
+ * IFA_ADDRESS is prefix address, rather than local interface address.
+ * It makes no difference for normally configured broadcast interfaces,
+ * but for point-to-point IFA_ADDRESS is DESTINATION address,
+ * local address is supplied in IFA_LOCAL attribute.
+ */
+ if (!tba[IFA_ADDRESS]) {
+ ERROR("[netlink.parse_addr] No local address");
+ return -1;
+ }
+
+ switch (ifa->ifa_family) {
+ case AF_INET:
+ local_addr.v4.as_inaddr = *(struct in_addr *)RTA_DATA(tba[IFA_ADDRESS]);
+ break;
+ case AF_INET6:
+ local_addr.v6.as_in6addr = *(struct in6_addr *)RTA_DATA(tba[IFA_ADDRESS]);
+ break;
+ default:
+ return 0;
+ }
+
+ /* See comment in parse_link */
+ if (interface_address) {
+ assert(tba[IFA_ADDRESS]);
+ hicn_ip_address_snprintf(interface_address, interface_address_size,
+ &local_addr);
+ }
+
+ netdevice_t *netdevice = netdevice_create_from_index(ifa->ifa_index);
+ if (!netdevice) {
+ ERROR("[netlink.parse_addr] error creating netdevice from index '%d'",
+ ifa->ifa_index);
+ goto ERR_ND;
+ }
+
+ if (interface_name) {
+ snprintf(interface_name, interface_name_size, "%s", netdevice->name);
+ }
+
+ *facelet = facelet_create();
+ if (!*facelet) {
+ ERROR("[netlink.parse_addr] error creating facelet");
+ goto ERR_FACELET;
+ }
+ if (facelet_set_netdevice(*facelet, *netdevice) < 0) {
+ ERROR("[netlink.parse_addr] error setting netdevice");
+ goto ERR;
+ }
+ if (facelet_set_family(*facelet, ifa->ifa_family) < 0) {
+ ERROR("[netlink.parse_addr] error setting family");
+ goto ERR;
+ }
+ if (facelet_set_local_addr(*facelet, local_addr) < 0) {
+ ERROR("[netlink.parse_addr] error setting local address");
+ goto ERR;
+ }
+
+ netdevice_free(netdevice);
+ return 0;
ERR:
- facelet_free(*facelet);
- *facelet = NULL;
+ facelet_free(*facelet);
+ *facelet = NULL;
ERR_FACELET:
- netdevice_free(netdevice);
+ netdevice_free(netdevice);
ERR_ND:
- return -1;
+ return -1;
}
-int nl_callback(interface_t * interface, int fd, void * unused)
-{
- nl_data_t * data = (nl_data_t*)interface->data;
+int nl_callback(interface_t *interface, int fd, void *unused) {
+ nl_data_t *data = (nl_data_t *)interface->data;
- struct sockaddr_nl local; // local addr struct
- memset(&local, 0, sizeof(local));
+ struct sockaddr_nl local; // local addr struct
+ memset(&local, 0, sizeof(local));
- char buf[8192]; // message buffer
- struct iovec iov; // message structure
- iov.iov_base = buf; // set message buffer as io
- iov.iov_len = sizeof(buf); // set size
+ char buf[8192]; // message buffer
+ struct iovec iov; // message structure
+ iov.iov_base = buf; // set message buffer as io
+ iov.iov_len = sizeof(buf); // set size
- // initialize protocol message header
- struct msghdr msg = {
- .msg_name = &local, // local address
- .msg_namelen = sizeof(local), // address size
- .msg_iov = &iov, // io vector
- .msg_iovlen = 1, // io size
- };
+ // initialize protocol message header
+ struct msghdr msg = {
+ .msg_name = &local, // local address
+ .msg_namelen = sizeof(local), // address size
+ .msg_iov = &iov, // io vector
+ .msg_iovlen = 1, // io size
+ };
- ssize_t status = recvmsg(data->fd, &msg, 0);
+ ssize_t status = recvmsg(data->fd, &msg, 0);
- // check status
- if (status < 0) {
-/*
- if (errno == EINTR || errno == EAGAIN)
- continue;
-*/
+ // check status
+ if (status < 0) {
+ /*
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+ */
- printf("Failed to read netlink: %s", (char*)strerror(errno));
- return -1;
- }
+ printf("Failed to read netlink: %s", (char *)strerror(errno));
+ return -1;
+ }
- if (msg.msg_namelen != sizeof(local)) { // check message length, just in case
- printf("Invalid length of the sender address struct\n");
- return -1;
- }
+ if (msg.msg_namelen != sizeof(local)) { // check message length, just in case
+ printf("Invalid length of the sender address struct\n");
+ return -1;
+ }
- // message parser
- struct nlmsghdr *h;
+ // message parser
+ struct nlmsghdr *h;
- for (h = (struct nlmsghdr*)buf; status >= (ssize_t)sizeof(*h); ) { // read all messagess headers
- int len = h->nlmsg_len;
- int l = len - sizeof(*h);
+ for (h = (struct nlmsghdr *)buf;
+ status >= (ssize_t)sizeof(*h);) { // read all messagess headers
+ int len = h->nlmsg_len;
+ int l = len - sizeof(*h);
- if ((l < 0) || (len > status)) {
- printf("Invalid message length: %i\n", len);
- continue;
- }
+ if ((l < 0) || (len > status)) {
+ printf("Invalid message length: %i\n", len);
+ continue;
+ }
- switch(h->nlmsg_type) {
+ switch (h->nlmsg_type) {
#if 0
case RTM_NEWROUTE:
case RTM_DELROUTE:
@@ -413,147 +401,123 @@ int nl_callback(interface_t * interface, int fd, void * unused)
break;
#endif
- case RTM_DELADDR:
- {
- facelet_t * facelet = NULL;
- char interface_name[IFNAMSIZ];
- char interface_address[MAXSZ_IP_ADDRESS] = {0};
-
- if (parse_addr(h, &facelet, interface_name, IFNAMSIZ,
- interface_address, MAXSZ_IP_ADDRESS) < 0) {
- ERROR("Error parsing address message");
- break;
- }
-
- DEBUG("[NETLINK] Interface %s: address was removed", interface_name);
- if (facelet) {
- facelet_set_event(facelet, FACELET_EVENT_SET_DOWN);
- facelet_set_attr_clean(facelet);
- interface_raise_event(interface, facelet);
- }
- break;
- }
-
- case RTM_NEWADDR:
- {
- facelet_t * facelet = NULL;
- char interface_name[IFNAMSIZ];
- char interface_address[MAXSZ_IP_ADDRESS] = {0};
-
- if (parse_addr(h, &facelet, interface_name, IFNAMSIZ,
- interface_address, MAXSZ_IP_ADDRESS) < 0) {
- ERROR("Error parsing address message");
- break;
- }
-
- DEBUG("[NETLINK] Interface %s: new address was assigned: %s", interface_name, interface_address);
-
- if (facelet) {
- facelet_set_event(facelet, FACELET_EVENT_UPDATE);
- facelet_set_attr_clean(facelet);
- interface_raise_event(interface, facelet);
- }
- break;
- }
+ case RTM_DELADDR: {
+ facelet_t *facelet = NULL;
+ char interface_name[IFNAMSIZ];
+ char interface_address[MAXSZ_IP_ADDRESS] = {0};
- case RTM_DELLINK:
- {
- /* This does not always seem to be called, hence we rely on
- * down, not running */
- facelet_t * facelet = NULL;
- char interface_name[IFNAMSIZ];
- if (parse_link(h, &facelet, interface_name, IFNAMSIZ,
- NULL, NULL) < 0) {
- ERROR("Error parsing link message");
- break;
- }
+ if (parse_addr(h, &facelet, interface_name, IFNAMSIZ, interface_address,
+ MAXSZ_IP_ADDRESS) < 0) {
+ ERROR("Error parsing address message");
+ break;
+ }
- DEBUG("[NETLINK] Network interface %s was removed", interface_name);
+ DEBUG("[NETLINK] Interface %s: address was removed", interface_name);
+ if (facelet) {
+ facelet_set_event(facelet, FACELET_EVENT_SET_DOWN);
+ facelet_set_attr_clean(facelet);
+ interface_raise_event(interface, facelet);
+ }
+ break;
+ }
+
+ case RTM_NEWADDR: {
+ facelet_t *facelet = NULL;
+ char interface_name[IFNAMSIZ];
+ char interface_address[MAXSZ_IP_ADDRESS] = {0};
+
+ if (parse_addr(h, &facelet, interface_name, IFNAMSIZ, interface_address,
+ MAXSZ_IP_ADDRESS) < 0) {
+ ERROR("Error parsing address message");
+ break;
+ }
- if (!facelet)
- break;
+ DEBUG("[NETLINK] Interface %s: new address was assigned: %s",
+ interface_name, interface_address);
- facelet_set_event(facelet, FACELET_EVENT_DELETE);
- facelet_set_attr_clean(facelet);
- interface_raise_event(interface, facelet);
+ if (facelet) {
+ facelet_set_event(facelet, FACELET_EVENT_UPDATE);
+ facelet_set_attr_clean(facelet);
+ interface_raise_event(interface, facelet);
+ }
+ break;
+ }
+
+ case RTM_DELLINK: {
+ /* This does not always seem to be called, hence we rely on
+ * down, not running */
+ facelet_t *facelet = NULL;
+ char interface_name[IFNAMSIZ];
+ if (parse_link(h, &facelet, interface_name, IFNAMSIZ, NULL, NULL) < 0) {
+ ERROR("Error parsing link message");
+ break;
+ }
- break;
- }
-
- case RTM_NEWLINK:
- {
- facelet_t * facelet = NULL;
- char interface_name[IFNAMSIZ];
- bool up, running;
-
- if (parse_link(h, &facelet, interface_name, IFNAMSIZ, &up, &running) < 0) {
- ERROR("Error parsing link message");
- break;
- }
-
- // UP RUNNING
- // UP NOT RUNNING
- // DOWN NOT RUNNING
-#if 1
- DEBUG("[NETLINK] New network interface %s, state: %s %s", interface_name,
- up ? "UP" : "DOWN",
- running ? "RUNNING" : "NOT_RUNNING");
-#endif
+ DEBUG("[NETLINK] Network interface %s was removed", interface_name);
- if (!facelet)
- break;
- if (up && running) {
- facelet_set_event(facelet, FACELET_EVENT_CREATE);
- //facelet_set_family(facelet, AF_INET);
- facelet_set_attr_clean(facelet);
- interface_raise_event(interface, facelet);
+ if (!facelet) break;
-#if 0
- facelet_t * facelet6 = facelet_dup(facelet);
- if (!facelet6) {
- ERROR("Could not duplicate face for v6");
- break;
- }
- facelet_set_family(facelet6, AF_INET6);
- interface_raise_event(interface, facelet6);
-#endif
-// } else {
-//#if 1
-// facelet_set_event(facelet, FACELET_EVENT_SET_DOWN);
-// facelet_set_attr_clean(facelet);
-// interface_raise_event(interface, facelet);
-//#else
-// facelet_free(facelet);
-//#endif
- }
- break;
- }
+ facelet_set_event(facelet, FACELET_EVENT_DELETE);
+ facelet_set_attr_clean(facelet);
+ interface_raise_event(interface, facelet);
- case NLMSG_ERROR:
- break;
- case NLMSG_DONE:
- nl_process_state(interface);
- break;
- default:
- break;
+ break;
+ }
+
+ case RTM_NEWLINK: {
+ facelet_t *facelet = NULL;
+ char interface_name[IFNAMSIZ];
+ bool up, running;
+ if (parse_link(h, &facelet, interface_name, IFNAMSIZ, &up, &running) <
+ 0) {
+ ERROR("Error parsing link message");
+ break;
}
- status -= NLMSG_ALIGN(len); // align offsets by the message length, this is important
+ // UP RUNNING
+ // UP NOT RUNNING
+ // DOWN NOT RUNNING
+#if 1
+ DEBUG("[NETLINK] New network interface %s, state: %s %s",
+ interface_name, up ? "UP" : "DOWN",
+ running ? "RUNNING" : "NOT_RUNNING");
+#endif
- h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len)); // get next message
+ if (!facelet) break;
+ if (up && running) {
+ facelet_set_event(facelet, FACELET_EVENT_CREATE);
+ facelet_set_attr_clean(facelet);
+ interface_raise_event(interface, facelet);
+ } else {
+ facelet_free(facelet);
+ }
+ break;
+ }
+
+ case NLMSG_ERROR:
+ break;
+ case NLMSG_DONE:
+ nl_process_state(interface);
+ break;
+ default:
+ break;
}
- return 0;
-}
+ status -= NLMSG_ALIGN(
+ len); // align offsets by the message length, this is important
-int nl_finalize(interface_t * interface)
-{
- nl_data_t * data = (nl_data_t*)interface->data;
- close(data->fd);
- free(interface->data);
- return 0;
+ h = (struct nlmsghdr *)((char *)h + NLMSG_ALIGN(len)); // get next message
+ }
+
+ return 0;
+}
+int nl_finalize(interface_t *interface) {
+ nl_data_t *data = (nl_data_t *)interface->data;
+ close(data->fd);
+ free(interface->data);
+ return 0;
}
const interface_ops_t netlink_ops = {
diff --git a/ctrl/facemgr/src/interfaces/network_framework/CMakeLists.txt b/ctrl/facemgr/src/interfaces/network_framework/CMakeLists.txt
index e8b0144b1..db96e390f 100644
--- a/ctrl/facemgr/src/interfaces/network_framework/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/network_framework/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/src/interfaces/network_framework/network_framework.c b/ctrl/facemgr/src/interfaces/network_framework/network_framework.c
index 2c4bff513..7f4a26c56 100644
--- a/ctrl/facemgr/src/interfaces/network_framework/network_framework.c
+++ b/ctrl/facemgr/src/interfaces/network_framework/network_framework.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -32,7 +32,7 @@
#include <hicn/util/map.h>
#include "../../common.h"
-#include <hicn/ctrl/face.h>
+#include <hicn/face.h>
#include "../../interface.h"
#include "network_framework.h"
@@ -41,7 +41,6 @@
#error "Network frameork requires MacOSX 10.14+"
#endif /* !defined(MAC_OS_X_VERSION_10_14) */
-
/*
* Bonjour service discovery for hICN forwarder
*
@@ -70,347 +69,339 @@
/* Generated variables */
#define BONJOUR_SERVICE_TYPE "_hicn._" STRINGIZE(BONJOUR_PROTOCOL)
#define BONJOUR_PROTOCOL_NAME STRINGIZE(BONJOUR_PROTOCOL)
-#define nw_parameters_create_fn PPCAT(nw_parameters_create_secure_, BONJOUR_PROTOCOL)
+#define nw_parameters_create_fn \
+ PPCAT(nw_parameters_create_secure_, BONJOUR_PROTOCOL)
#define DEFAULT_PORT 9695
typedef enum {
- INTERFACE_TYPE_OTHER,
- INTERFACE_TYPE_WIFI,
- INTERFACE_TYPE_CELLULAR,
- INTERFACE_TYPE_WIRED,
- INTERFACE_TYPE_LOOPBACK,
+ INTERFACE_TYPE_OTHER,
+ INTERFACE_TYPE_WIFI,
+ INTERFACE_TYPE_CELLULAR,
+ INTERFACE_TYPE_WIRED,
+ INTERFACE_TYPE_LOOPBACK,
} _nw_interface_type_t;
-const char * interface_type_str[] = {
+const char *interface_type_str[] = {
"OTHER", "WIFI", "CELLULAR", "WIRED", "LOOPBACK",
};
#if 1
typedef enum {
- PATH_STATUS_INVALID,
- PATH_STATUS_SATISTIED,
- PATH_STATUS_UNSATISFIED,
- PATH_STATUS_SATISFIABLE,
+ PATH_STATUS_INVALID,
+ PATH_STATUS_SATISTIED,
+ PATH_STATUS_UNSATISFIED,
+ PATH_STATUS_SATISFIABLE,
} _nw_path_status_t;
#endif
-const char * path_status_str[] = {
- "INVALID", "SATISFIED", "UNSATISFIED", "SATISFIABLE",
+const char *path_status_str[] = {
+ "INVALID",
+ "SATISFIED",
+ "UNSATISFIED",
+ "SATISFIABLE",
};
-const char * endpoint_type_str[] = {
- "INVALID", "ADDRESS", "HOST", "BONJOUR",
+const char *endpoint_type_str[] = {
+ "INVALID",
+ "ADDRESS",
+ "HOST",
+ "BONJOUR",
};
-const char * connection_state_str[] = {
+const char *connection_state_str[] = {
"INVALID", "WAITING", "PREPARING", "READY", "FAILED", "CANCELLED",
};
-int
-cmp_iface(const nw_interface_t iface1, const nw_interface_t iface2)
-{
- return INT_CMP(nw_interface_get_index(iface1), nw_interface_get_index(iface2));
+int cmp_iface(const nw_interface_t iface1, const nw_interface_t iface2) {
+ return INT_CMP(nw_interface_get_index(iface1),
+ nw_interface_get_index(iface2));
}
-//TYPEDEF_MAP(map_cnx, nw_interface_t, nw_connection_t, cmp_iface);
+// TYPEDEF_MAP(map_cnx, nw_interface_t, nw_connection_t, cmp_iface);
typedef struct {
- network_framework_cfg_t cfg;
- nw_path_monitor_t pm; /**< Main path monitor */
-// map_cnx_t map_cnx; /**< Map: interface -> connection for face status */
+ network_framework_cfg_t cfg;
+ nw_path_monitor_t pm; /**< Main path monitor */
+ // map_cnx_t map_cnx; /**< Map: interface -> connection for face status
+ // */
} nf_data_t;
-void
-dump_interface(nw_interface_t interface, int indent)
-{
- uint32_t index = nw_interface_get_index(interface);
- const char * name = nw_interface_get_name(interface);
- nw_interface_type_t type = nw_interface_get_type(interface);
+void dump_interface(nw_interface_t interface, int indent) {
+ uint32_t index = nw_interface_get_index(interface);
+ const char *name = nw_interface_get_name(interface);
+ nw_interface_type_t type = nw_interface_get_type(interface);
- printfi(indent+1, "%d: %s [%s]\n", index, name, interface_type_str[type]);
+ printfi(indent + 1, "%d: %s [%s]\n", index, name, interface_type_str[type]);
}
-void
-dump_endpoint(nw_endpoint_t endpoint, int indent)
-{
- if (!endpoint) {
- printfi(indent, "N/A\n");
- return;
- }
-
- nw_endpoint_type_t endpoint_type = nw_endpoint_get_type(endpoint);
- const char * hostname = nw_endpoint_get_hostname(endpoint);
- short port = nw_endpoint_get_port(endpoint);
- const struct sockaddr * address = nw_endpoint_get_address(endpoint);
-
- printfi(indent, "Type: %s\n", endpoint_type_str[endpoint_type]);
- printfi(indent, "Hostname: %s\n", hostname);
- printfi(indent, "Port: %d\n", port);
-
- if (address) {
- char *s = NULL;
- switch(address->sa_family) {
- case AF_INET: {
- struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
- s = malloc(INET_ADDRSTRLEN);
- inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
- break;
- }
- case AF_INET6: {
- struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)address;
- s = malloc(INET6_ADDRSTRLEN);
- inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
- break;
- }
- default:
- break;
- }
+void dump_endpoint(nw_endpoint_t endpoint, int indent) {
+ if (!endpoint) {
+ printfi(indent, "N/A\n");
+ return;
+ }
+
+ nw_endpoint_type_t endpoint_type = nw_endpoint_get_type(endpoint);
+ const char *hostname = nw_endpoint_get_hostname(endpoint);
+ short port = nw_endpoint_get_port(endpoint);
+ const struct sockaddr *address = nw_endpoint_get_address(endpoint);
+
+ printfi(indent, "Type: %s\n", endpoint_type_str[endpoint_type]);
+ printfi(indent, "Hostname: %s\n", hostname);
+ printfi(indent, "Port: %d\n", port);
+
+ if (address) {
+ char *s = NULL;
+ switch (address->sa_family) {
+ case AF_INET: {
+ struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
+ s = malloc(INET_ADDRSTRLEN);
+ inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
+ break;
+ }
+ case AF_INET6: {
+ struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)address;
+ s = malloc(INET6_ADDRSTRLEN);
+ inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
+ break;
+ default:
+ break;
+ }
printfi(indent, "IP address: %s\n", s);
free(s);
}
+ }
}
-void
-dump_path(nw_path_t path, int indent)
-{
- /* nw_path_enumerate_interfaces : not interesting */
- nw_path_status_t path_status = nw_path_get_status(path);
- printfi(indent, "Status: %s\n", path_status_str[path_status]);
- printfi(indent, "Expensive: %s\n", nw_path_is_expensive(path) ? "true" : "false");
- printfi(indent, "IPv4 enabled: %s\n", nw_path_has_ipv4(path) ? "true" : "false");
- printfi(indent, "IPv6 enabled: %s\n", nw_path_has_ipv6(path) ? "true" : "false");
- printfi(indent, "DNS: %s\n", nw_path_has_dns(path) ? "true" : "false");
- printfi(indent, "Interfaces:\n");
- nw_path_enumerate_interfaces(path, (nw_path_enumerate_interfaces_block_t)^(nw_interface_t interface) {
- dump_interface(interface, indent+1);
+void dump_path(nw_path_t path, int indent) {
+ /* nw_path_enumerate_interfaces : not interesting */
+ nw_path_status_t path_status = nw_path_get_status(path);
+ printfi(indent, "Status: %s\n", path_status_str[path_status]);
+ printfi(indent, "Expensive: %s\n",
+ nw_path_is_expensive(path) ? "true" : "false");
+ printfi(indent, "IPv4 enabled: %s\n",
+ nw_path_has_ipv4(path) ? "true" : "false");
+ printfi(indent, "IPv6 enabled: %s\n",
+ nw_path_has_ipv6(path) ? "true" : "false");
+ printfi(indent, "DNS: %s\n", nw_path_has_dns(path) ? "true" : "false");
+ printfi(indent, "Interfaces:\n");
+ nw_path_enumerate_interfaces(
+ path,
+ (nw_path_enumerate_interfaces_block_t) ^ (nw_interface_t interface) {
+ dump_interface(interface, indent + 1);
return true;
- });
+ });
- nw_endpoint_t local = nw_path_copy_effective_local_endpoint(path);
- printfi(indent, "Effective local endpoint:\n");
- dump_endpoint(local, indent+1);
- nw_release(local);
+ nw_endpoint_t local = nw_path_copy_effective_local_endpoint(path);
+ printfi(indent, "Effective local endpoint:\n");
+ dump_endpoint(local, indent + 1);
+ nw_release(local);
- nw_endpoint_t remote = nw_path_copy_effective_remote_endpoint(path);
- printfi(indent, "Effective remote endpoint:\n");
- dump_endpoint(remote, indent+1);
- nw_release(remote);
+ nw_endpoint_t remote = nw_path_copy_effective_remote_endpoint(path);
+ printfi(indent, "Effective remote endpoint:\n");
+ dump_endpoint(remote, indent + 1);
+ nw_release(remote);
}
-void
-dump_connection(nw_connection_t connection, int indent)
-{
- nw_endpoint_t remote = nw_connection_copy_endpoint(connection);
- nw_path_t path = nw_connection_copy_current_path(connection);
+void dump_connection(nw_connection_t connection, int indent) {
+ nw_endpoint_t remote = nw_connection_copy_endpoint(connection);
+ nw_path_t path = nw_connection_copy_current_path(connection);
- printfi(indent, "Remote endpoint:\n");
- dump_endpoint(remote, indent+1);
- printfi(indent, "Path:\n");
- dump_path(path, indent+1);
+ printfi(indent, "Remote endpoint:\n");
+ dump_endpoint(remote, indent + 1);
+ printfi(indent, "Path:\n");
+ dump_path(path, indent + 1);
- /*
- nw_connection_copy_protocol_metadata();
- nw_connection_get_maximum_datagram_size();
- */
+ /*
+ nw_connection_copy_protocol_metadata();
+ nw_connection_get_maximum_datagram_size();
+ */
- nw_release(remote);
- nw_release(path);
+ nw_release(remote);
+ nw_release(path);
}
#if defined(MAC_OS_X_VERSION_10_15)
-void
-dump_browse_result(nw_browse_result_t result, int indent)
-{
- /* Endpoint */
- nw_endpoint_t browse_endpoint = nw_browse_result_copy_endpoint(result);
- if (!browse_endpoint) {
- ERROR("[network_framework.dump_result] Failed to retrieve endpoint from Bonjour browse result");
- return;
- }
- printfi(indent + 1, "Endpoint:");
- dump_endpoint(browse_endpoint, indent + 2);
-
- /* Interfaces */
- printfi(indent + 1, "Interfaces:");
- nw_browse_result_enumerate_interfaces(result, (nw_browse_result_enumerate_interface_t) ^(nw_interface_t interface) {
+void dump_browse_result(nw_browse_result_t result, int indent) {
+ /* Endpoint */
+ nw_endpoint_t browse_endpoint = nw_browse_result_copy_endpoint(result);
+ if (!browse_endpoint) {
+ ERROR(
+ "[network_framework.dump_result] Failed to retrieve endpoint from "
+ "Bonjour browse result");
+ return;
+ }
+ printfi(indent + 1, "Endpoint:");
+ dump_endpoint(browse_endpoint, indent + 2);
+
+ /* Interfaces */
+ printfi(indent + 1, "Interfaces:");
+ nw_browse_result_enumerate_interfaces(
+ result,
+ (nw_browse_result_enumerate_interface_t) ^ (nw_interface_t interface) {
dump_interface(interface, indent + 2);
return true;
- });
+ });
}
#endif /* defined(MAC_OS_X_VERSION_10_15) */
-facelet_t *
-facelet_create_from_connection(nw_connection_t connection)
-{
- facelet_t * facelet;
- ip_address_t local_addr, remote_addr;
- uint16_t remote_port;
-
- nw_path_t path = nw_connection_copy_current_path(connection);
- nw_endpoint_t local = nw_path_copy_effective_local_endpoint(path);
- nw_endpoint_t remote = nw_path_copy_effective_remote_endpoint(path);
- __block nw_interface_t interface;
-
- const struct sockaddr * local_sa = nw_endpoint_get_address(local);
- const struct sockaddr * remote_sa = nw_endpoint_get_address(remote);
-
- assert (local_sa->sa_family == remote_sa->sa_family);
- switch(local_sa->sa_family) {
- case AF_INET:
- local_addr.v4.as_inaddr = ((struct sockaddr_in *)local_sa)->sin_addr;
- remote_addr.v4.as_inaddr = ((struct sockaddr_in *)remote_sa)->sin_addr;
- remote_port = ((struct sockaddr_in *)remote_sa)->sin_port;
- break;
- case AF_INET6:
- local_addr.v6.as_in6addr = ((struct sockaddr_in6 *)local_sa)->sin6_addr;
- remote_addr.v6.as_in6addr = ((struct sockaddr_in6 *)remote_sa)->sin6_addr;
- remote_port = ((struct sockaddr_in6 *)remote_sa)->sin6_port;
- break;
- default:
- ERROR("Unsupported address family: %d\n", local_sa->sa_family);
- return NULL;
- }
-
-
- /* Retrieving path interface type (a single one expected */
- nw_path_enumerate_interfaces(path, (nw_path_enumerate_interfaces_block_t)^(nw_interface_t path_interface) {
+facelet_t *facelet_create_from_connection(nw_connection_t connection) {
+ facelet_t *facelet;
+ hicn_ip_address_t local_addr, remote_addr;
+ uint16_t remote_port;
+
+ nw_path_t path = nw_connection_copy_current_path(connection);
+ nw_endpoint_t local = nw_path_copy_effective_local_endpoint(path);
+ nw_endpoint_t remote = nw_path_copy_effective_remote_endpoint(path);
+ __block nw_interface_t interface;
+
+ const struct sockaddr *local_sa = nw_endpoint_get_address(local);
+ const struct sockaddr *remote_sa = nw_endpoint_get_address(remote);
+
+ assert(local_sa->sa_family == remote_sa->sa_family);
+ switch (local_sa->sa_family) {
+ case AF_INET:
+ local_addr.v4.as_inaddr = ((struct sockaddr_in *)local_sa)->sin_addr;
+ remote_addr.v4.as_inaddr = ((struct sockaddr_in *)remote_sa)->sin_addr;
+ remote_port = ((struct sockaddr_in *)remote_sa)->sin_port;
+ break;
+ case AF_INET6:
+ local_addr.v6.as_in6addr = ((struct sockaddr_in6 *)local_sa)->sin6_addr;
+ remote_addr.v6.as_in6addr = ((struct sockaddr_in6 *)remote_sa)->sin6_addr;
+ remote_port = ((struct sockaddr_in6 *)remote_sa)->sin6_port;
+ break;
+ default:
+ ERROR("Unsupported address family: %d\n", local_sa->sa_family);
+ return NULL;
+ }
+
+ /* Retrieving path interface type (a single one expected */
+ nw_path_enumerate_interfaces(
+ path,
+ (nw_path_enumerate_interfaces_block_t) ^ (nw_interface_t path_interface) {
interface = path_interface;
return false;
- });
-
- const char * name = nw_interface_get_name(interface);
- netdevice_t netdevice;
- snprintf(netdevice.name, IFNAMSIZ, "%s", name);
- netdevice_update_index(&netdevice);
-
- netdevice_type_t netdevice_type;
- nw_interface_type_t type = nw_interface_get_type(interface);
-
- switch(type) {
- case INTERFACE_TYPE_OTHER:
- netdevice_type = NETDEVICE_TYPE_UNDEFINED;
- break;
- case INTERFACE_TYPE_WIFI:
- netdevice_type = NETDEVICE_TYPE_WIFI;
- break;
- case INTERFACE_TYPE_CELLULAR:
- netdevice_type = NETDEVICE_TYPE_CELLULAR;
- break;
- case INTERFACE_TYPE_WIRED:
- netdevice_type = NETDEVICE_TYPE_WIRED;
- break;
- case INTERFACE_TYPE_LOOPBACK:
- netdevice_type = NETDEVICE_TYPE_LOOPBACK;
- break;
- default:
- break;
-
- }
-
- nw_release(local);
- nw_release(remote);
- nw_release(path);
-
- facelet = facelet_create();
- if (!facelet)
- return NULL;
-
- facelet_set_netdevice(facelet, netdevice);
- facelet_set_netdevice_type(facelet, netdevice_type);
- facelet_set_family(facelet, local_sa->sa_family);
- facelet_set_local_addr(facelet, local_addr);
- facelet_set_remote_addr(facelet, remote_addr);
- facelet_set_remote_port(facelet, remote_port);
-
- return facelet;
+ });
+
+ const char *name = nw_interface_get_name(interface);
+ netdevice_t netdevice;
+ snprintf(netdevice.name, IFNAMSIZ, "%s", name);
+ netdevice_update_index(&netdevice);
+
+ netdevice_type_t netdevice_type;
+ nw_interface_type_t type = nw_interface_get_type(interface);
+
+ switch (type) {
+ case INTERFACE_TYPE_OTHER:
+ netdevice_type = NETDEVICE_TYPE_UNDEFINED;
+ break;
+ case INTERFACE_TYPE_WIFI:
+ netdevice_type = NETDEVICE_TYPE_WIFI;
+ break;
+ case INTERFACE_TYPE_CELLULAR:
+ netdevice_type = NETDEVICE_TYPE_CELLULAR;
+ break;
+ case INTERFACE_TYPE_WIRED:
+ netdevice_type = NETDEVICE_TYPE_WIRED;
+ break;
+ case INTERFACE_TYPE_LOOPBACK:
+ netdevice_type = NETDEVICE_TYPE_LOOPBACK;
+ break;
+ default:
+ break;
+ }
+
+ nw_release(local);
+ nw_release(remote);
+ nw_release(path);
+
+ facelet = facelet_create();
+ if (!facelet) return NULL;
+
+ facelet_set_netdevice(facelet, netdevice);
+ facelet_set_netdevice_type(facelet, netdevice_type);
+ facelet_set_family(facelet, local_sa->sa_family);
+ facelet_set_local_addr(facelet, local_addr);
+ facelet_set_remote_addr(facelet, remote_addr);
+ facelet_set_remote_port(facelet, remote_port);
+
+ return facelet;
}
-void
-on_connection_state_event(interface_t * interface, nw_interface_t iface,
- nw_connection_t cnx, nw_connection_state_t state, nw_error_t error)
-{
+void on_connection_state_event(interface_t *interface, nw_interface_t iface,
+ nw_connection_t cnx, nw_connection_state_t state,
+ nw_error_t error) {
#if 1
- DEBUG("Connection [new state = %s]:\n", connection_state_str[state]);
- nw_path_t path = nw_connection_copy_current_path(cnx);
- nw_path_enumerate_interfaces(path, (nw_path_enumerate_interfaces_block_t)^(nw_interface_t interface) {
- const char * name = nw_interface_get_name(interface);
+ DEBUG("Connection [new state = %s]:\n", connection_state_str[state]);
+ nw_path_t path = nw_connection_copy_current_path(cnx);
+ nw_path_enumerate_interfaces(
+ path,
+ (nw_path_enumerate_interfaces_block_t) ^ (nw_interface_t interface) {
+ const char *name = nw_interface_get_name(interface);
printf("NAME=%s\n", name);
return true;
- });
+ });
#endif
- /* We should get enough information to create the face and set if up
- * asap */
+ /* We should get enough information to create the face and set if up
+ * asap */
- nw_endpoint_t remote = nw_connection_copy_endpoint(cnx);
- errno = error ? nw_error_get_error_code(error) : 0;
+ nw_endpoint_t remote = nw_connection_copy_endpoint(cnx);
+ errno = error ? nw_error_get_error_code(error) : 0;
- switch(state) {
- case nw_connection_state_waiting:
- warn("connect to %s port %u (%s) failed, is waiting",
- nw_endpoint_get_hostname(remote),
- nw_endpoint_get_port(remote),
- BONJOUR_PROTOCOL_NAME);
- break;
+ switch (state) {
+ case nw_connection_state_waiting:
+ warn("connect to %s port %u (%s) failed, is waiting",
+ nw_endpoint_get_hostname(remote), nw_endpoint_get_port(remote),
+ BONJOUR_PROTOCOL_NAME);
+ break;
- case nw_connection_state_preparing:
- break;
+ case nw_connection_state_preparing:
+ break;
- case nw_connection_state_ready:
- {
- printf("info:\n");
- warn("connection ready");
+ case nw_connection_state_ready: {
+ printf("info:\n");
+ warn("connection ready");
#if 1
- WITH_DEBUG({
- dump_connection(cnx, 1);
- });
+ WITH_DEBUG({ dump_connection(cnx, 1); });
#endif
- facelet_t * facelet = facelet_create_from_connection(cnx);
- if (!facelet)
- return;
- facelet_set_event(facelet, FACELET_EVENT_CREATE);
- interface_raise_event(interface, facelet);
- break;
- }
- case nw_connection_state_failed:
- /* Can we fail with bonjour, or are we always waiting ? */
- warn("connect to %s port %u (%s) failed",
- nw_endpoint_get_hostname(remote),
- nw_endpoint_get_port(remote),
- BONJOUR_PROTOCOL_NAME);
- break;
-
- case nw_connection_state_cancelled:
- // Release the primary reference on the connection
- // that was taken at creation time
- nw_release(cnx);
- break;
-
- default: /* nw_connection_state_invalid */
- /* Should never be called */
- break;
-
+ facelet_t *facelet = facelet_create_from_connection(cnx);
+ if (!facelet) return;
+ facelet_set_event(facelet, FACELET_EVENT_CREATE);
+ interface_raise_event(interface, facelet);
+ break;
}
-
- nw_release(remote);
-
+ case nw_connection_state_failed:
+ /* Can we fail with bonjour, or are we always waiting ? */
+ warn("connect to %s port %u (%s) failed",
+ nw_endpoint_get_hostname(remote), nw_endpoint_get_port(remote),
+ BONJOUR_PROTOCOL_NAME);
+ break;
+
+ case nw_connection_state_cancelled:
+ // Release the primary reference on the connection
+ // that was taken at creation time
+ nw_release(cnx);
+ break;
+
+ default: /* nw_connection_state_invalid */
+ /* Should never be called */
+ break;
+ }
+
+ nw_release(remote);
}
-void
-on_connection_path_event(interface_t * interface, nw_interface_t iface,
- nw_connection_t cnx, nw_path_t path)
-{
+void on_connection_path_event(interface_t *interface, nw_interface_t iface,
+ nw_connection_t cnx, nw_path_t path) {
#if 1
- DEBUG("Connection [path changed]:\n");
- WITH_DEBUG({
- dump_connection(cnx, 1);
- });
+ DEBUG("Connection [path changed]:\n");
+ WITH_DEBUG({ dump_connection(cnx, 1); });
#endif
- /* redundant *//*
- DEBUG(1, "Path:\n");
- dump_path(path, 2);
- */
+ /* redundant */ /*
+ DEBUG(1, "Path:\n");
+ dump_path(path, 2);
+ */
}
/**
@@ -422,257 +413,254 @@ on_connection_path_event(interface_t * interface, nw_interface_t iface,
* Currently we only use Bonjour/TCP for remote hICN discovery and connection
* path monitoring.
*/
-void on_interface_event(interface_t * interface, nw_interface_t iface)
-{
- /* We can create an hICN face on this interface that will be down until
- * connected
- * It is however possible to have two default gateways on the same
- * interface, or more, or even zero. Somehow we need a strategy, timers, etc
- * to properly do the job.
- *
- * We have to determine:
- * - how many faces to build
- * - the face type : hICN, tunnel (TCP/UDP)
- * - the underlying protocol : v4, v6
- *
- * This depends on the configuration, end host and network capabilities.
- *
- * We can rely on several types of discovery:
- * - DHCP
- * - Bonjour
- * - ...
- *
- * So far:
- * - bonjour discovery attempt, we expect to discover one hICN interface
- * (how bonjour works with more than one is unclear), after a certain
- * time, if none is discovered, we cannot do any tunnel face.
- */
-
- // OLD CODE
-
- /* nw_parameters_create_secure_{udp,tcp} */
- nw_parameters_t parameters = nw_parameters_create_fn(
- NW_PARAMETERS_DISABLE_PROTOCOL, /* no (d)tls */
- NW_PARAMETERS_DEFAULT_CONFIGURATION /* default udp/tcp */);
-
- if (!parameters)
- goto ERR_PARAMETERS;
-
- nw_parameters_require_interface(parameters, iface);
- nw_parameters_set_reuse_local_address(parameters, true);
+void on_interface_event(interface_t *interface, nw_interface_t iface) {
+ /* We can create an hICN face on this interface that will be down until
+ * connected
+ * It is however possible to have two default gateways on the same
+ * interface, or more, or even zero. Somehow we need a strategy, timers, etc
+ * to properly do the job.
+ *
+ * We have to determine:
+ * - how many faces to build
+ * - the face type : hICN, tunnel (TCP/UDP)
+ * - the underlying protocol : v4, v6
+ *
+ * This depends on the configuration, end host and network capabilities.
+ *
+ * We can rely on several types of discovery:
+ * - DHCP
+ * - Bonjour
+ * - ...
+ *
+ * So far:
+ * - bonjour discovery attempt, we expect to discover one hICN interface
+ * (how bonjour works with more than one is unclear), after a certain
+ * time, if none is discovered, we cannot do any tunnel face.
+ */
+
+ // OLD CODE
+
+ /* nw_parameters_create_secure_{udp,tcp} */
+ nw_parameters_t parameters = nw_parameters_create_fn(
+ NW_PARAMETERS_DISABLE_PROTOCOL, /* no (d)tls */
+ NW_PARAMETERS_DEFAULT_CONFIGURATION /* default udp/tcp */);
+
+ if (!parameters) goto ERR_PARAMETERS;
+
+ nw_parameters_require_interface(parameters, iface);
+ nw_parameters_set_reuse_local_address(parameters, true);
#if defined(MAC_OS_X_VERSION_10_15)
- /*
- * Before being able to create a bonjour endpoint, we need to browse for
- * available services on the local network using the parameters specified
- * before.
- */
- nw_browse_descriptor_t descriptor = nw_browse_descriptor_create_bonjour_service(BONJOUR_SERVICE_TYPE, BONJOUR_SERVICE_DOMAIN);
- if (!descriptor) {
- ERROR("[network_framework.on_interface_event] Failed to create a bonjour browse descriptor");
- goto ERR_DESCRIPTOR;
+ /*
+ * Before being able to create a bonjour endpoint, we need to browse for
+ * available services on the local network using the parameters specified
+ * before.
+ */
+ nw_browse_descriptor_t descriptor =
+ nw_browse_descriptor_create_bonjour_service(BONJOUR_SERVICE_TYPE,
+ BONJOUR_SERVICE_DOMAIN);
+ if (!descriptor) {
+ ERROR(
+ "[network_framework.on_interface_event] Failed to create a bonjour "
+ "browse descriptor");
+ goto ERR_DESCRIPTOR;
+ }
+
+ nw_browser_t browser = nw_browser_create(descriptor, parameters);
+ nw_browser_set_queue(browser, dispatch_get_main_queue());
+ nw_browser_set_browse_results_changed_handler(browser, ^(
+ nw_browse_result_t result,
+ nw_browse_result_t result2,
+ bool flag) {
+ /* Dump result */
+ printfi(0, "NEW BROWSE RESULT");
+ printfi(1, "Result:");
+ dump_browse_result(result, 2);
+ printfi(1, "Result2:");
+ dump_browse_result(result2, 2);
+ printfi(1, "Flag: %s\n", (flag ? "ON" : "OFF"));
+
+ /* Changes */
+ nw_browse_result_change_t change =
+ nw_browse_result_get_changes(result, result2);
+ switch (change) {
+ case nw_browse_result_change_identical:
+ printfi(2, "The compared services are identical.");
+ break;
+ case nw_browse_result_change_result_added:
+ printfi(2, "A new service was discovered.");
+ break;
+
+ case nw_browse_result_change_result_removed:
+ printfi(2, "A previously discovered service was removed.");
+ break;
+
+ case nw_browse_result_change_txt_record_changed:
+ printfi(2, "The service's associated TXT record changed.");
+ break;
+
+ case nw_browse_result_change_interface_added:
+ printfi(2, "The service was discovered over a new interface.");
+ break;
+
+ case nw_browse_result_change_interface_removed:
+ printfi(
+ 2,
+ "The service was no longer discovered over a certain interface.");
+ break;
}
+ });
- nw_browser_t browser = nw_browser_create(descriptor, parameters);
- nw_browser_set_queue(browser, dispatch_get_main_queue());
- nw_browser_set_browse_results_changed_handler(browser, ^(nw_browse_result_t result, nw_browse_result_t result2, bool flag) {
- /* Dump result */
- printfi(0, "NEW BROWSE RESULT");
- printfi(1, "Result:");
- dump_browse_result(result, 2);
- printfi(1, "Result2:");
- dump_browse_result(result2, 2);
- printfi(1, "Flag: %s\n", (flag?"ON":"OFF"));
-
- /* Changes */
- nw_browse_result_change_t change = nw_browse_result_get_changes(result, result2);
- switch(change) {
- case nw_browse_result_change_identical:
- printfi(2, "The compared services are identical.");
- break;
- case nw_browse_result_change_result_added:
- printfi(2, "A new service was discovered.");
- break;
-
- case nw_browse_result_change_result_removed:
- printfi(2, "A previously discovered service was removed.");
- break;
-
- case nw_browse_result_change_txt_record_changed:
- printfi(2, "The service's associated TXT record changed.");
- break;
-
- case nw_browse_result_change_interface_added:
- printfi(2, "The service was discovered over a new interface.");
- break;
-
- case nw_browse_result_change_interface_removed:
- printfi(2, "The service was no longer discovered over a certain interface.");
- break;
- }
- });
-
- nw_browser_start(browser);
+ nw_browser_start(browser);
//#else
//#warning "Bonjour discovery only available in MacOS 10.15+"
#endif /* defined(MAC_OS_X_VERSION_10_15) */
- /*
- * Now that we have resolve the name of a bonjour remote, we can create a
- * connection to the corresponding endpoint identified by its name.
- */
- nw_endpoint_t endpoint;
-
- DEBUG("Creating bonjour service towards NAME=%s TYPE=%s DOMAIN=%s",
- BONJOUR_SERVICE_NAME, BONJOUR_SERVICE_TYPE, BONJOUR_SERVICE_DOMAIN);
- endpoint = nw_endpoint_create_bonjour_service(
- BONJOUR_SERVICE_NAME,
- BONJOUR_SERVICE_TYPE,
- BONJOUR_SERVICE_DOMAIN);
-
- if (!endpoint) {
- ERROR("[network_framework.on_interface_event] Failed to create bound Bonjour connection");
- goto ERR_ENDPOINT;
- }
+ /*
+ * Now that we have resolve the name of a bonjour remote, we can create a
+ * connection to the corresponding endpoint identified by its name.
+ */
+ nw_endpoint_t endpoint;
+
+ DEBUG("Creating bonjour service towards NAME=%s TYPE=%s DOMAIN=%s",
+ BONJOUR_SERVICE_NAME, BONJOUR_SERVICE_TYPE, BONJOUR_SERVICE_DOMAIN);
+ endpoint = nw_endpoint_create_bonjour_service(
+ BONJOUR_SERVICE_NAME, BONJOUR_SERVICE_TYPE, BONJOUR_SERVICE_DOMAIN);
+
+ if (!endpoint) {
+ ERROR(
+ "[network_framework.on_interface_event] Failed to create bound "
+ "Bonjour "
+ "connection");
+ goto ERR_ENDPOINT;
+ }
- nw_connection_t connection = nw_connection_create(endpoint, parameters);
- if (!connection)
- goto ERR_CONNECTION;
+ nw_connection_t connection = nw_connection_create(endpoint, parameters);
+ if (!connection) goto ERR_CONNECTION;
- nw_release(endpoint);
- nw_release(parameters);
+ nw_release(endpoint);
+ nw_release(parameters);
- /* Remember not to recreate connection */
- // XXX TODO
+ /* Remember not to recreate connection */
+ // XXX TODO
- /* Setup connection handlers */
+ /* Setup connection handlers */
- nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t error) {
+ nw_connection_set_state_changed_handler(
+ connection, ^(nw_connection_state_t state, nw_error_t error) {
on_connection_state_event(interface, iface, connection, state, error);
- });
+ });
- nw_connection_set_path_changed_handler(connection, ^(nw_path_t path) {
- on_connection_path_event(interface, iface, connection, path);
- });
+ nw_connection_set_path_changed_handler(connection, ^(nw_path_t path) {
+ on_connection_path_event(interface, iface, connection, path);
+ });
- nw_connection_set_better_path_available_handler(connection, ^(bool value) {
+ nw_connection_set_better_path_available_handler(connection, ^(bool value) {
#if 1
- DEBUG("Connection [better path = %s]\n", (value ? "true" : "false"));
- WITH_DEBUG({
- dump_connection(connection, 1);
- });
+ DEBUG("Connection [better path = %s]\n", (value ? "true" : "false"));
+ WITH_DEBUG({ dump_connection(connection, 1); });
#endif
- });
+ });
- nw_connection_set_viability_changed_handler(connection, ^(bool value) {
+ nw_connection_set_viability_changed_handler(connection, ^(bool value) {
#if 1
- DEBUG("Connection [viable = %s]\n", (value ? "true" : "false"));
- WITH_DEBUG({
- //dump_connection(connection, 1);
- });
+ DEBUG("Connection [viable = %s]\n", (value ? "true" : "false"));
+ WITH_DEBUG({
+ // dump_connection(connection, 1);
+ });
#endif
- /*
- * This is the first time we have a connection with address and port
- * and thus the full identification of an hICN face
- */
- facelet_t * facelet = facelet_create_from_connection(connection);
- if (!facelet)
- return;
- facelet_set_event(facelet, value ? FACELET_EVENT_CREATE : FACELET_EVENT_DELETE);
- interface_raise_event(interface, facelet);
-
- });
+ /*
+ * This is the first time we have a connection with address and port
+ * and thus the full identification of an hICN face
+ */
+ facelet_t *facelet = facelet_create_from_connection(connection);
+ if (!facelet) return;
+ facelet_set_event(facelet,
+ value ? FACELET_EVENT_CREATE : FACELET_EVENT_DELETE);
+ interface_raise_event(interface, facelet);
+ });
- nw_connection_start(connection);
+ nw_connection_start(connection);
- nw_connection_set_queue(connection, dispatch_get_main_queue());
- nw_retain(connection); // Hold a reference until cancelled
+ nw_connection_set_queue(connection, dispatch_get_main_queue());
+ nw_retain(connection); // Hold a reference until cancelled
#if 1
- DEBUG("Created Bonjour cnx on interface:");
- WITH_DEBUG({
- dump_interface(iface, 1);
- });
+ DEBUG("Created Bonjour cnx on interface:");
+ WITH_DEBUG({ dump_interface(iface, 1); });
#endif
- return;
+ return;
- nw_release(connection);
+ nw_release(connection);
ERR_CONNECTION:
- nw_release(endpoint);
+ nw_release(endpoint);
ERR_ENDPOINT:
#if defined(MAC_OS_X_VERSION_10_15)
- nw_release(descriptor);
+ nw_release(descriptor);
ERR_DESCRIPTOR:
#endif /* defined(MAC_OS_X_VERSION_10_15) */
- nw_release(parameters);
+ nw_release(parameters);
ERR_PARAMETERS:
- return;
+ return;
}
-void on_path_event(interface_t * interface, nw_path_t path)
-{
- /* Simplification: we handle path event only once.
- * Ideally, test whether we discover new interfaces or not
- */
+void on_path_event(interface_t *interface, nw_path_t path) {
+ /* Simplification: we handle path event only once.
+ * Ideally, test whether we discover new interfaces or not
+ */
#if 1
- DEBUG("Path [event]:\n");
- WITH_DEBUG({
- dump_path(path, 1);
- });
+ DEBUG("Path [event]:\n");
+ WITH_DEBUG({ dump_path(path, 1); });
#endif
- nw_path_enumerate_interfaces(path, (nw_path_enumerate_interfaces_block_t)^(nw_interface_t iface) {
- on_interface_event(interface, iface);
- return true;
- });
-
+ nw_path_enumerate_interfaces(
+ path, (nw_path_enumerate_interfaces_block_t) ^ (nw_interface_t iface) {
+ on_interface_event(interface, iface);
+ return true;
+ });
}
-int nf_initialize(interface_t * interface, void * cfg)
-{
- nf_data_t * data = malloc(sizeof(nf_data_t));
- if (!data)
- goto ERR_MALLOC;
+int nf_initialize(interface_t *interface, void *cfg) {
+ nf_data_t *data = malloc(sizeof(nf_data_t));
+ if (!data) goto ERR_MALLOC;
- if (cfg)
- data->cfg = * (network_framework_cfg_t *)cfg;
+ if (cfg) data->cfg = *(network_framework_cfg_t *)cfg;
- data->pm = nw_path_monitor_create();
- if (!data->pm)
- goto ERR_PM;
+ data->pm = nw_path_monitor_create();
+ if (!data->pm) goto ERR_PM;
- nw_path_monitor_set_queue(data->pm, dispatch_get_main_queue());
- nw_path_monitor_set_cancel_handler(data->pm, ^() { });
- nw_path_monitor_set_update_handler(data->pm, ^(nw_path_t path) {
- on_path_event(interface, path);
- });
+ nw_path_monitor_set_queue(data->pm, dispatch_get_main_queue());
+ nw_path_monitor_set_cancel_handler(data->pm, ^(){
+ });
+ nw_path_monitor_set_update_handler(data->pm, ^(nw_path_t path) {
+ on_path_event(interface, path);
+ });
- // XXX NEEDED ?
- nw_retain(data->pm);
+ // XXX NEEDED ?
+ nw_retain(data->pm);
- DEBUG("Starting network path monitor");
- nw_path_monitor_start(data->pm);
+ DEBUG("Starting network path monitor");
+ nw_path_monitor_start(data->pm);
- interface->data = data;
- return 0;
+ interface->data = data;
+ return 0;
ERR_PM:
- free(data);
+ free(data);
ERR_MALLOC:
- return -1;
+ return -1;
}
-int nf_finalize(interface_t * interface)
-{
- nf_data_t * data = (nf_data_t*)interface->data;
- if (data->pm) {
- nw_path_monitor_cancel(data->pm);
- data->pm = NULL;
- }
- return 0;
+int nf_finalize(interface_t *interface) {
+ nf_data_t *data = (nf_data_t *)interface->data;
+ if (data->pm) {
+ nw_path_monitor_cancel(data->pm);
+ data->pm = NULL;
+ }
+ return 0;
}
const interface_ops_t network_framework_ops = {
diff --git a/ctrl/facemgr/src/interfaces/network_framework/network_framework.h b/ctrl/facemgr/src/interfaces/network_framework/network_framework.h
index edb35e904..768edc253 100644
--- a/ctrl/facemgr/src/interfaces/network_framework/network_framework.h
+++ b/ctrl/facemgr/src/interfaces/network_framework/network_framework.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,4 +19,5 @@
*/
typedef struct {
+ void *_;
} network_framework_cfg_t;
diff --git a/ctrl/facemgr/src/interfaces/priority_controller/CMakeLists.txt b/ctrl/facemgr/src/interfaces/priority_controller/CMakeLists.txt
index 8d18800db..43ba31b0b 100644
--- a/ctrl/facemgr/src/interfaces/priority_controller/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/priority_controller/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.c b/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.c
index 67edc5e39..5d2f695f9 100644
--- a/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.c
+++ b/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -34,20 +34,21 @@
#define PC_DEFAULT_PORT 9533
typedef struct {
- priority_controller_cfg_t cfg;
- int fd;
+ priority_controller_cfg_t cfg;
+ int fd;
#ifdef PRIORITY_CONTROLLER_INTERNAL
- unsigned state;
- JNIEnv * env;
- jclass cls;
- jmethodID mid;
+ unsigned state;
+ JNIEnv *env;
+ jclass cls;
+ jmethodID mid;
#endif /* PRIORITY_CONTROLLER_INTERNAL */
} pc_data_t;
#ifdef PRIORITY_CONTROLLER_INTERNAL
#include <jni.h>
-#define ERR_STR_JAVA "Java VM parameters are required in the interface configuration."
+#define ERR_STR_JAVA \
+ "Java VM parameters are required in the interface configuration."
#define PREFER_CELLULAR 0
#define PREFER_WIFI 1
@@ -55,147 +56,146 @@ typedef struct {
#define INTERVAL_MS 500
-const char * prefer_str[] = { "Cellular", "WiFi", "both" };
+const char *prefer_str[] = {"Cellular", "WiFi", "both"};
-jclass find_class_global(JNIEnv* env, const char *name){
- jclass c = (*env)->FindClass(env, name);
- jclass c_global = 0;
- if (c){
- c_global = (jclass)(*env)->NewGlobalRef(env, c);
- (*env)->DeleteLocalRef(env, c);
- }
- return c_global;
+jclass find_class_global(JNIEnv *env, const char *name) {
+ jclass c = (*env)->FindClass(env, name);
+ jclass c_global = 0;
+ if (c) {
+ c_global = (jclass)(*env)->NewGlobalRef(env, c);
+ (*env)->DeleteLocalRef(env, c);
+ }
+ return c_global;
}
+int priority_controller_tick(interface_t *interface, int fd, void *unused) {
+ pc_data_t *data = (pc_data_t *)interface->data;
+ unsigned new_state = PREFER_BOTH;
-int priority_controller_tick(interface_t * interface, int fd, void * unused)
-{
- pc_data_t * data = (pc_data_t*)interface->data;
- unsigned new_state = PREFER_BOTH;
-
- jint rssi = (*data->env)->CallStaticIntMethod(data->env, data->cls, data->mid);
- DEBUG("[priority_controller_tick] rssi=%d\n", rssi);
- if (rssi > -67) {
- new_state = PREFER_WIFI;
+ jint rssi =
+ (*data->env)->CallStaticIntMethod(data->env, data->cls, data->mid);
+ DEBUG("[priority_controller_tick] rssi=%d\n", rssi);
+ if (rssi > -67) {
+ new_state = PREFER_WIFI;
#if 0
} else if ((rssi < -67) && (rssi > -70)) {
new_state = PREFER_BOTH;
#endif
- } else { /* rssi < -70 */
- new_state = PREFER_CELLULAR;
- }
+ } else { /* rssi < -70 */
+ new_state = PREFER_CELLULAR;
+ }
- if (new_state == data->state)
- return 0;
+ if (new_state == data->state) return 0;
- ERROR("[priority_controller_tick] Setting priority to %s", prefer_str[new_state]);
+ ERROR("[priority_controller_tick] Setting priority to %s",
+ prefer_str[new_state]);
- /* XXX Factor this */
+ /* XXX Factor this */
- facelet_t * facelet_w = facelet_create();
- facelet_t * facelet_c = facelet_create();
- facelet_set_netdevice_type(facelet_w, NETDEVICE_TYPE_WIFI);
- facelet_set_netdevice_type(facelet_c, NETDEVICE_TYPE_CELLULAR);
- facelet_set_attr_clean(facelet_w);
- facelet_set_attr_clean(facelet_c);
+ facelet_t *facelet_w = facelet_create();
+ facelet_t *facelet_c = facelet_create();
+ facelet_set_netdevice_type(facelet_w, NETDEVICE_TYPE_WIFI);
+ facelet_set_netdevice_type(facelet_c, NETDEVICE_TYPE_CELLULAR);
+ facelet_set_attr_clean(facelet_w);
+ facelet_set_attr_clean(facelet_c);
- switch(new_state) {
- case PREFER_CELLULAR:
- facelet_set_priority(facelet_w, 0);
- facelet_set_priority(facelet_c, 10);
- break;
- case PREFER_WIFI:
- facelet_set_priority(facelet_w, 10);
- facelet_set_priority(facelet_c, 0);
- break;
- case PREFER_BOTH:
- facelet_set_priority(facelet_w, 0);
- facelet_set_priority(facelet_c, 0);
- break;
- }
+ switch (new_state) {
+ case PREFER_CELLULAR:
+ facelet_set_priority(facelet_w, 0);
+ facelet_set_priority(facelet_c, 10);
+ break;
+ case PREFER_WIFI:
+ facelet_set_priority(facelet_w, 10);
+ facelet_set_priority(facelet_c, 0);
+ break;
+ case PREFER_BOTH:
+ facelet_set_priority(facelet_w, 0);
+ facelet_set_priority(facelet_c, 0);
+ break;
+ }
- facelet_set_event(facelet_w, FACELET_EVENT_UPDATE);
- facelet_set_event(facelet_c, FACELET_EVENT_UPDATE);
+ facelet_set_event(facelet_w, FACELET_EVENT_UPDATE);
+ facelet_set_event(facelet_c, FACELET_EVENT_UPDATE);
- interface_raise_event(interface, facelet_w);
- interface_raise_event(interface, facelet_c);
+ interface_raise_event(interface, facelet_w);
+ interface_raise_event(interface, facelet_c);
- data->state = new_state;
+ data->state = new_state;
- return 0;
+ return 0;
}
#endif /* PRIORITY_CONTROLLER_INTERNAL */
-int priority_controller_initialize(interface_t * interface, void * cfg)
-{
- INFO("Initializing priority controller");
+int priority_controller_initialize(interface_t *interface, void *cfg) {
+ INFO("Initializing priority controller");
- pc_data_t * data = malloc(sizeof(pc_data_t));
- if (!data) {
- INFO("Priority controller data memory allocation error");
- goto ERR_MALLOC;
- }
+ pc_data_t *data = malloc(sizeof(pc_data_t));
+ if (!data) {
+ INFO("Priority controller data memory allocation error");
+ goto ERR_MALLOC;
+ }
- interface->data = data;
+ interface->data = data;
- data->cfg = * (priority_controller_cfg_t *) cfg;
+ data->cfg = *(priority_controller_cfg_t *)cfg;
#ifdef PRIORITY_CONTROLLER_INTERNAL
- if (!cfg) {
- ERROR(ERR_STR_JAVA);
- goto ERR_CFG;
- }
-
- /* Retrieve RSSI information from SDK through AndroidUtility class */
- (*data->cfg.jvm)->AttachCurrentThread(data->cfg.jvm, &data->env, NULL);
- data->cls = find_class_global(data->env, FACEMGR_ANDROID_UTILITY_CLASS);
- if (data->cls == 0)
- goto ERR_JAVA;
- data->mid = (*data->env)->GetStaticMethodID(data->env, data->cls, "getWifiRSSI", "()I");
-
- data->fd = interface_register_timer(interface, INTERVAL_MS,
- priority_controller_tick, interface);
- if (data->fd < 0) {
- ERROR("[priority_controller_initialize] Could not initialize timer");
- goto ERR_FD;
- }
- data->state = PREFER_BOTH;
+ if (!cfg) {
+ ERROR(ERR_STR_JAVA);
+ goto ERR_CFG;
+ }
+
+ /* Retrieve RSSI information from SDK through AndroidUtility class */
+ (*data->cfg.jvm)->AttachCurrentThread(data->cfg.jvm, &data->env, NULL);
+ data->cls = find_class_global(data->env, FACEMGR_ANDROID_UTILITY_CLASS);
+ if (data->cls == 0) goto ERR_JAVA;
+ data->mid =
+ (*data->env)
+ ->GetStaticMethodID(data->env, data->cls, "getWifiRSSI", "()I");
+
+ data->fd = interface_register_timer(interface, INTERVAL_MS,
+ priority_controller_tick, interface);
+ if (data->fd < 0) {
+ ERROR("[priority_controller_initialize] Could not initialize timer");
+ goto ERR_FD;
+ }
+ data->state = PREFER_BOTH;
#else /* PRIORITY_CONTROLLER_INTERNAL */
- struct sockaddr_in addr;
-
- data->fd = socket(AF_INET, SOCK_DGRAM, 0);
- //data->fd = socket(AF_INET, SOCK_STREAM, 0);
- if (data->fd < 0) {
- INFO("Priority controller socket error");
- perror("socket error");
- goto ERR_SOCKET;
- }
-
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- addr.sin_port = htons(PC_DEFAULT_PORT);
-
- if (bind(data->fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
- INFO("Priority controller socket bind error");
- perror("bind error");
- goto ERR_BIND;
- }
-
- DEBUG("[priority_controller_initialize] register fd");
- if (interface_register_fd(interface, data->fd, NULL) < 0) {
- ERROR("[priority_controller_initialize] Error registering fd");
- goto ERR_FD;
- }
+ struct sockaddr_in addr;
+
+ data->fd = socket(AF_INET, SOCK_DGRAM, 0);
+ // data->fd = socket(AF_INET, SOCK_STREAM, 0);
+ if (data->fd < 0) {
+ INFO("Priority controller socket error");
+ perror("socket error");
+ goto ERR_SOCKET;
+ }
+
+ memset(&addr, 0, sizeof(addr));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = inet_addr("127.0.0.1");
+ addr.sin_port = htons(PC_DEFAULT_PORT);
+
+ if (bind(data->fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+ INFO("Priority controller socket bind error");
+ perror("bind error");
+ goto ERR_BIND;
+ }
+
+ DEBUG("[priority_controller_initialize] register fd");
+ if (interface_register_fd(interface, data->fd, NULL) < 0) {
+ ERROR("[priority_controller_initialize] Error registering fd");
+ goto ERR_FD;
+ }
#endif /* PRIORITY_CONTROLLER_INTERNAL */
- INFO("Priority controller successfully initialized");
- return 0;
+ INFO("Priority controller successfully initialized");
+ return 0;
#ifdef PRIORITY_CONTROLLER_INTERNAL
ERR_CFG:
@@ -204,86 +204,86 @@ ERR_JAVA:
ERR_FD:
#ifndef PRIORITY_CONTROLLER_INTERNAL
ERR_BIND:
- close(data->fd);
+ close(data->fd);
ERR_SOCKET:
#endif /* ! PRIORITY_CONTROLLER_INTERNAL */
- free(data);
+ free(data);
ERR_MALLOC:
- return -1;
+ return -1;
}
-int priority_controller_finalize(interface_t * interface)
-{
- pc_data_t * data = (pc_data_t*)interface->data;
+int priority_controller_finalize(interface_t *interface) {
+ pc_data_t *data = (pc_data_t *)interface->data;
#ifdef PRIORITY_CONTROLLER_INTERNAL
- DEBUG("[priority_controller_finalize] unregister timer");
- interface_unregister_timer(interface, data->fd);
+ DEBUG("[priority_controller_finalize] unregister timer");
+ interface_unregister_timer(interface, data->fd);
#else
- if (data->fd > 0) {
- interface_unregister_fd(interface, data->fd);
- close(data->fd);
- }
- free(data);
+ if (data->fd > 0) {
+ interface_unregister_fd(interface, data->fd);
+ close(data->fd);
+ }
+ free(data);
#endif /* PRIORITY_CONTROLLER_INTERNAL */
- return 0;
+ return 0;
}
#ifndef PRIORITY_CONTROLLER_INTERNAL
-int priority_controller_callback(interface_t * interface, int fd, void * unused)
-{
- pc_data_t * data = (pc_data_t*)interface->data;
- char buf[100];
- int rc;
-
- INFO("Priority controller receiving command");
-
- rc = recv(data->fd, buf, 100, 0);
-
- if (rc < 0) {
- INFO("Priority controller read error");
- return -1;
- }
-
- INFO("Priority controller received command: %02X", buf[0]);
-
- facelet_t * facelet_w = facelet_create();
- facelet_t * facelet_c = facelet_create();
- facelet_set_netdevice_type(facelet_w, NETDEVICE_TYPE_WIFI);
- facelet_set_netdevice_type(facelet_c, NETDEVICE_TYPE_CELLULAR);
- facelet_set_attr_clean(facelet_w);
- facelet_set_attr_clean(facelet_c);
- switch(buf[0]) {
- case '\0':
- facelet_set_priority(facelet_w, 0);
- facelet_set_priority(facelet_c, 10);
- INFO("Priority controller configuring Cellular preferred");
- break;
- case '\1':
- facelet_set_priority(facelet_w, 10);
- facelet_set_priority(facelet_c, 0);
- INFO("Priority controller configuring Wi-Fi preferred");
- break;
- case '\2':
- facelet_set_priority(facelet_w, 0);
- facelet_set_priority(facelet_c, 0);
- INFO("Priority controller configuring both Cellular and Wi-Fi preferred");
- break;
- default:
- INFO("Priority controller invalid data received from updown server. Ignoring...");
- facelet_free(facelet_w);
- facelet_free(facelet_c);
- return 0;
- }
-
- facelet_set_event(facelet_w, FACELET_EVENT_UPDATE);
- facelet_set_event(facelet_c, FACELET_EVENT_UPDATE);
-
- interface_raise_event(interface, facelet_w);
- interface_raise_event(interface, facelet_c);
-
- return 0;
+int priority_controller_callback(interface_t *interface, int fd, void *unused) {
+ pc_data_t *data = (pc_data_t *)interface->data;
+ char buf[100];
+ int rc;
+
+ INFO("Priority controller receiving command");
+
+ rc = recv(data->fd, buf, 100, 0);
+
+ if (rc < 0) {
+ INFO("Priority controller read error");
+ return -1;
+ }
+
+ INFO("Priority controller received command: %02X", buf[0]);
+
+ facelet_t *facelet_w = facelet_create();
+ facelet_t *facelet_c = facelet_create();
+ facelet_set_netdevice_type(facelet_w, NETDEVICE_TYPE_WIFI);
+ facelet_set_netdevice_type(facelet_c, NETDEVICE_TYPE_CELLULAR);
+ facelet_set_attr_clean(facelet_w);
+ facelet_set_attr_clean(facelet_c);
+ switch (buf[0]) {
+ case '\0':
+ facelet_set_priority(facelet_w, 0);
+ facelet_set_priority(facelet_c, 10);
+ INFO("Priority controller configuring Cellular preferred");
+ break;
+ case '\1':
+ facelet_set_priority(facelet_w, 10);
+ facelet_set_priority(facelet_c, 0);
+ INFO("Priority controller configuring Wi-Fi preferred");
+ break;
+ case '\2':
+ facelet_set_priority(facelet_w, 0);
+ facelet_set_priority(facelet_c, 0);
+ INFO("Priority controller configuring both Cellular and Wi-Fi preferred");
+ break;
+ default:
+ INFO(
+ "Priority controller invalid data received from updown server. "
+ "Ignoring...");
+ facelet_free(facelet_w);
+ facelet_free(facelet_c);
+ return 0;
+ }
+
+ facelet_set_event(facelet_w, FACELET_EVENT_UPDATE);
+ facelet_set_event(facelet_c, FACELET_EVENT_UPDATE);
+
+ interface_raise_event(interface, facelet_w);
+ interface_raise_event(interface, facelet_c);
+
+ return 0;
}
#endif /* ! PRIORITY_CONTROLLER_INTERNAL */
diff --git a/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.h b/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.h
index 247fc3c57..7f257ffcf 100644
--- a/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.h
+++ b/ctrl/facemgr/src/interfaces/priority_controller/priority_controller.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,7 +21,8 @@
#ifndef FACEMGR_INTERFACE_PRIORITY_CONTROLLER
#define FACEMGR_INTERFACE_PRIORITY_CONTROLLER
-#define FACEMGR_UTILITY_CLASS "com/cisco/hicn/facemgrlibrary/supportlibrary/FacemgrUtility"
+#define FACEMGR_UTILITY_CLASS \
+ "com/cisco/hicn/facemgrlibrary/supportlibrary/FacemgrUtility"
/*
* Uncomment this line to use a Priority controller interface internal to the
@@ -36,10 +37,9 @@
typedef struct {
#ifdef __ANDROID__
#ifdef PRIORITY_CONTROLLER_INTERNAL
- JavaVM * jvm;
+ JavaVM* jvm;
#endif /* PRIORITY_CONTROLLER_INTERNAL */
#endif /* __ANDROID__ */
} priority_controller_cfg_t;
-
#endif /* FACEMGR_INTERFACE_PRIORITY_CONTROLLER */
diff --git a/ctrl/facemgr/src/interfaces/updown/CMakeLists.txt b/ctrl/facemgr/src/interfaces/updown/CMakeLists.txt
index e5fd2167e..4c6c0ea6c 100644
--- a/ctrl/facemgr/src/interfaces/updown/CMakeLists.txt
+++ b/ctrl/facemgr/src/interfaces/updown/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/ctrl/facemgr/src/interfaces/updown/updown.c b/ctrl/facemgr/src/interfaces/updown/updown.c
index 7d305a5cd..8d31f6cd4 100644
--- a/ctrl/facemgr/src/interfaces/updown/updown.c
+++ b/ctrl/facemgr/src/interfaces/updown/updown.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,6 +26,7 @@
#include <unistd.h>
#include <hicn/facemgr.h>
+#include <hicn/util/sstrncpy.h>
#include "../../common.h"
#include "../../interface.h"
@@ -37,107 +38,101 @@
#define UNIX_PATH "\0updownsrv"
typedef struct {
- int fd; /* Unix client socket */
+ int fd; /* Unix client socket */
} updown_data_t;
-int updown_initialize(interface_t * interface, void * cfg)
-{
- struct sockaddr_un addr;
- char * socket_path = UNIX_PATH;
-
- updown_data_t * data = malloc(sizeof(updown_data_t));
- if (!data)
- goto ERR_MALLOC;
- interface->data = data;
-
- data->fd = socket(AF_UNIX, SOCK_STREAM, 0);
- if (data->fd == -1) {
- perror("socket error");
- goto ERR_SOCKET;
- }
-
- memset(&addr, 0, sizeof(addr));
- addr.sun_family = AF_UNIX;
- if (*socket_path == '\0') {
- *addr.sun_path = '\0';
- strncpy(addr.sun_path+1, socket_path+1, sizeof(addr.sun_path)-2);
- } else {
- strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1);
- }
-
- if (connect(data->fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
- perror("connect error");
- goto ERR_CONNECT;
- }
-
- if (interface_register_fd(interface, data->fd, NULL) < 0) {
- ERROR("[updown_initialize] Error registering fd");
- goto ERR_FD;
- }
-
- return 0;
+int updown_initialize(interface_t* interface, void* cfg) {
+ struct sockaddr_un addr;
+ char* socket_path = UNIX_PATH;
+
+ updown_data_t* data = malloc(sizeof(updown_data_t));
+ if (!data) goto ERR_MALLOC;
+ interface->data = data;
+
+ data->fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (data->fd == -1) {
+ perror("socket error");
+ goto ERR_SOCKET;
+ }
+
+ memset(&addr, 0, sizeof(addr));
+ addr.sun_family = AF_UNIX;
+ if (*socket_path == '\0') {
+ *addr.sun_path = '\0';
+ strcpy_s(addr.sun_path + 1, sizeof(addr.sun_path) - 2, socket_path + 1);
+ } else {
+ strcpy_s(addr.sun_path, sizeof(addr.sun_path) - 1, socket_path);
+ }
+
+ if (connect(data->fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
+ perror("connect error");
+ goto ERR_CONNECT;
+ }
+
+ if (interface_register_fd(interface, data->fd, NULL) < 0) {
+ ERROR("[updown_initialize] Error registering fd");
+ goto ERR_FD;
+ }
+
+ return 0;
ERR_FD:
ERR_CONNECT:
- close(data->fd);
+ close(data->fd);
ERR_SOCKET:
- free(data);
+ free(data);
ERR_MALLOC:
- return -1;
+ return -1;
}
-int updown_finalize(interface_t * interface)
-{
- updown_data_t * data = (updown_data_t*)interface->data;
+int updown_finalize(interface_t* interface) {
+ updown_data_t* data = (updown_data_t*)interface->data;
- if (data->fd > 0)
- close(data->fd);
- free(data);
+ if (data->fd > 0) close(data->fd);
+ free(data);
- return 0;
+ return 0;
}
-int updown_callback(interface_t * interface, int fd, void * unused)
-{
- updown_data_t * data = (updown_data_t*)interface->data;
- char buf[100];
- int rc;
-
- rc = read(data->fd, buf, sizeof(buf));
- if (rc < 0)
- return -1;
-
- /*
- * If the process is paused (eg. in a debugger, we might have more than one
- * read.
- * XXX how big is the buffer
- * XXX shall we drain the queue if it exceeds buffer size ?
- */
- //assert(rc == 1);
-
- /* Raise facelet update event */
- facelet_t * facelet = facelet_create();
- facelet_set_netdevice_type(facelet, NETDEVICE_TYPE_WIFI); //CELLULAR);
- facelet_set_attr_clean(facelet);
- switch(buf[0]) {
- case '\0':
- facelet_set_admin_state(facelet, FACE_STATE_DOWN);
- break;
- case '\1':
- facelet_set_admin_state(facelet, FACE_STATE_UP);
- break;
- break;
- default:
- ERROR("Invalid data received from updown server. Ignoring...");
- facelet_free(facelet);
- return -1;
- }
-
- facelet_set_event(facelet, FACELET_EVENT_UPDATE);
-
- interface_raise_event(interface, facelet);
-
- return 0;
+int updown_callback(interface_t* interface, int fd, void* unused) {
+ updown_data_t* data = (updown_data_t*)interface->data;
+ char buf[100];
+ int rc;
+
+ rc = read(data->fd, buf, sizeof(buf));
+ if (rc < 0) return -1;
+
+ /*
+ * If the process is paused (eg. in a debugger, we might have more than one
+ * read.
+ * XXX how big is the buffer
+ * XXX shall we drain the queue if it exceeds buffer size ?
+ */
+ // assert(rc == 1);
+
+ /* Raise facelet update event */
+ facelet_t* facelet = facelet_create();
+ facelet_set_netdevice_type(facelet, NETDEVICE_TYPE_WIFI); // CELLULAR);
+ facelet_set_attr_clean(facelet);
+ switch (buf[0]) {
+ case '\0':
+ facelet_set_admin_state(facelet, FACE_STATE_DOWN);
+ break;
+ case '\1':
+ facelet_set_admin_state(facelet, FACE_STATE_UP);
+ break;
+ break;
+ default:
+ ERROR("Invalid data received from updown server. Ignoring...");
+ facelet_free(facelet);
+ return -1;
+ }
+
+ facelet_set_event(facelet, FACELET_EVENT_UPDATE);
+
+ interface_raise_event(interface, facelet);
+
+ return 0;
}
interface_ops_t updown_ops = {
diff --git a/ctrl/facemgr/src/loop_dispatcher.c b/ctrl/facemgr/src/loop_dispatcher.c
index 499a1ccac..88e197492 100644
--- a/ctrl/facemgr/src/loop_dispatcher.c
+++ b/ctrl/facemgr/src/loop_dispatcher.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,57 +28,41 @@
#include <stdlib.h>
-#include <Dispatch/Dispatch.h>
+#include <dispatch/dispatch.h>
#include <hicn/facemgr/loop.h>
#include <hicn/util/log.h>
-struct loop_s {
-};
+struct loop_s {};
-loop_t *
-loop_create()
-{
- loop_t * loop = malloc(sizeof(loop_t));
- if (!loop) {
- ERROR("[loop_create] Failed to allocate memory");
- goto ERR_MALLOC;
- }
- return loop;
+loop_t* loop_create() {
+ loop_t* loop = malloc(sizeof(loop_t));
+ if (!loop) {
+ ERROR("[loop_create] Failed to allocate memory");
+ goto ERR_MALLOC;
+ }
+ return loop;
ERR_MALLOC:
- return NULL;
+ return NULL;
}
-void
-loop_free(loop_t * loop)
-{
- /* Nothing to do */
+void loop_free(loop_t* loop) { /* Nothing to do */
}
-int
-loop_dispatch(loop_t * loop)
-{
- dispatch_main();
- return 0;
+int loop_dispatch(loop_t* loop) {
+ dispatch_main();
+ return 0;
}
-int
-loop_undispatch(loop_t * loop)
-{
- /* Nothing to do */
- return 0;
+int loop_undispatch(loop_t* loop) {
+ /* Nothing to do */
+ return 0;
}
-void
-loop_break(loop_t * loop)
-{
- exit(0);
-}
+void loop_break(loop_t* loop) { exit(0); }
-int
-loop_callback(loop_t * loop, facemgr_cb_type_t type, void * data)
-{
- INFO("loop_callback not (yet) implemented");
- return 0;
+int loop_callback(loop_t* loop, facemgr_cb_type_t type, void* data) {
+ INFO("loop_callback not (yet) implemented");
+ return 0;
}
diff --git a/ctrl/facemgr/src/loop_libevent.c b/ctrl/facemgr/src/loop_libevent.c
index 674eee905..b619e02e6 100644
--- a/ctrl/facemgr/src/loop_libevent.c
+++ b/ctrl/facemgr/src/loop_libevent.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,13 +25,13 @@
#include <assert.h>
#include <event2/event.h>
#include <event2/thread.h>
-#include <fcntl.h> // fcntl
+#include <fcntl.h> // fcntl
#ifdef WITH_THREAD
#include <pthread.h>
#endif /* WITH_THREAD */
#include <stdlib.h>
#include <sys/timerfd.h>
-#include <unistd.h> // fcntl
+#include <unistd.h> // fcntl
#include <hicn/facemgr/api.h>
#include <hicn/util/log.h>
@@ -43,160 +43,150 @@
* \brief Holds all callback parameters
*/
typedef struct {
- void * owner;
- fd_callback_t callback;
- void * data;
+ void *owner;
+ fd_callback_t callback;
+ void *data;
} cb_wrapper_args_t;
TYPEDEF_MAP_H(event_map, int, struct event *);
-TYPEDEF_MAP(event_map, int, struct event *, int_cmp, int_snprintf, generic_snprintf);
+TYPEDEF_MAP(event_map, int, struct event *, int_cmp, int_snprintf,
+ generic_snprintf);
/* Map that associates timer fds with their associated cb_wrapper_args_t */
TYPEDEF_MAP_H(timer_fd_map, int, cb_wrapper_args_t *);
-TYPEDEF_MAP(timer_fd_map, int, cb_wrapper_args_t *, int_cmp, int_snprintf, generic_snprintf);
+TYPEDEF_MAP(timer_fd_map, int, cb_wrapper_args_t *, int_cmp, int_snprintf,
+ generic_snprintf);
struct loop_s {
- struct event_base * event_base;
- event_map_t * event_map;
- timer_fd_map_t * timer_fd_map;
+ struct event_base *event_base;
+ event_map_t *event_map;
+ timer_fd_map_t *timer_fd_map;
#ifdef WITH_THREAD
- pthread_t thread;
+ pthread_t thread;
#endif /* WITH_THREAD */
};
/* Forward declarations */
-int _loop_unregister_fd(loop_t * loop, int fd);
-int _loop_unregister_timer(loop_t * loop, int fd);
-
-loop_t *
-loop_create()
-{
- loop_t * loop = malloc(sizeof(loop_t));
- if (!loop) {
- ERROR("[loop_create] Failed to allocate memory");
- goto ERR_MALLOC;
- }
+int _loop_unregister_fd(loop_t *loop, int fd);
+int _loop_unregister_timer(loop_t *loop, int fd);
+
+loop_t *loop_create() {
+ loop_t *loop = malloc(sizeof(loop_t));
+ if (!loop) {
+ ERROR("[loop_create] Failed to allocate memory");
+ goto ERR_MALLOC;
+ }
#ifdef WITH_THREAD
- evthread_use_pthreads();
+ evthread_use_pthreads();
#endif /* WITH_THREAD */
- loop->event_base = event_base_new();
- if (!loop)
- goto ERR_EVENT;
+ loop->event_base = event_base_new();
+ if (!loop) goto ERR_EVENT;
- loop->event_map = event_map_create();
- if (!loop->event_map) {
- ERROR("[loop_create] Failed to create event_map");
- goto ERR_EVENT_MAP;
- }
+ loop->event_map = event_map_create();
+ if (!loop->event_map) {
+ ERROR("[loop_create] Failed to create event_map");
+ goto ERR_EVENT_MAP;
+ }
- loop->timer_fd_map = timer_fd_map_create();
- if (!loop->timer_fd_map) {
- ERROR("[loop_create] Failed to create timer_fd_map");
- goto ERR_TIMER_FD_MAP;
- }
+ loop->timer_fd_map = timer_fd_map_create();
+ if (!loop->timer_fd_map) {
+ ERROR("[loop_create] Failed to create timer_fd_map");
+ goto ERR_TIMER_FD_MAP;
+ }
- event_set_log_callback(NULL);
+ event_set_log_callback(NULL);
- return loop;
+ return loop;
- timer_fd_map_free(loop->timer_fd_map);
ERR_TIMER_FD_MAP:
- event_map_free(loop->event_map);
+ event_map_free(loop->event_map);
ERR_EVENT_MAP:
- event_base_free(loop->event_base);
+ event_base_free(loop->event_base);
ERR_EVENT:
- free(loop);
+ free(loop);
ERR_MALLOC:
- return NULL;
+ return NULL;
}
-void
-loop_free(loop_t * loop)
-{
- /*
- * Release all timer cb_wrapper_args_t
- *
- * We need to stop all timers, this should release associated fd events at
- * the same time... for that reason, this code has to be called before
- * releasing events
- */
-
- int * timer_fd_map_array;
- int n = timer_fd_map_get_key_array(loop->timer_fd_map, &timer_fd_map_array);
- if (n < 0) {
- ERROR("[loop_free] Could not get event map array");
- } else {
- for (unsigned i = 0; i < n; i++) {
- int fd = timer_fd_map_array[i];
- if (_loop_unregister_timer(loop, fd) < 0) {
- ERROR("[loop_free] Could not unregister timer");
- }
- }
- free(timer_fd_map_array);
+void loop_free(loop_t *loop) {
+ /*
+ * Release all timer cb_wrapper_args_t
+ *
+ * We need to stop all timers, this should release associated fd events at
+ * the same time... for that reason, this code has to be called before
+ * releasing events
+ */
+
+ int *timer_fd_map_array;
+ int n = timer_fd_map_get_key_array(loop->timer_fd_map, &timer_fd_map_array);
+ if (n < 0) {
+ ERROR("[loop_free] Could not get event map array");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ int fd = timer_fd_map_array[i];
+ if (_loop_unregister_timer(loop, fd) < 0) {
+ ERROR("[loop_free] Could not unregister timer");
+ }
}
- timer_fd_map_free(loop->timer_fd_map);
-
- /* Release all events */
-
- int * event_map_array;
- n = event_map_get_key_array(loop->event_map, &event_map_array);
- if (n < 0) {
- ERROR("[loop_free] Could not get event map array");
- } else {
- for (unsigned i = 0; i < n; i++) {
- int fd = event_map_array[i];
- if (_loop_unregister_fd(loop, fd) < 0) {
- ERROR("[loop_free] Could not unregister fd");
- }
- }
- free(event_map_array);
+ free(timer_fd_map_array);
+ }
+ timer_fd_map_free(loop->timer_fd_map);
+
+ /* Release all events */
+
+ int *event_map_array;
+ n = event_map_get_key_array(loop->event_map, &event_map_array);
+ if (n < 0) {
+ ERROR("[loop_free] Could not get event map array");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ int fd = event_map_array[i];
+ if (_loop_unregister_fd(loop, fd) < 0) {
+ ERROR("[loop_free] Could not unregister fd");
+ }
}
- event_map_free(loop->event_map);
+ free(event_map_array);
+ }
+ event_map_free(loop->event_map);
- event_base_free(loop->event_base);
+ event_base_free(loop->event_base);
- free(loop);
+ free(loop);
}
-int
-loop_dispatch(loop_t * loop)
-{
+int loop_dispatch(loop_t *loop) {
#ifdef WITH_THREAD
- if (pthread_create(&loop->thread, NULL, (void * (*)(void *))event_base_dispatch, loop->event_base)) {
- fprintf(stderr, "Error creating thread\n");
- return -1;
- }
+ if (pthread_create(&loop->thread, NULL,
+ (void *(*)(void *))event_base_dispatch,
+ loop->event_base)) {
+ fprintf(stderr, "Error creating thread\n");
+ return -1;
+ }
#else
- event_base_dispatch(loop->event_base);
+ event_base_dispatch(loop->event_base);
#endif /* WITH_THREAD */
- return 0;
+ return 0;
}
-int
-loop_undispatch(loop_t * loop)
-{
+int loop_undispatch(loop_t *loop) {
#ifdef WITH_THREAD
- DEBUG("Waiting for loop to terminate...");
- if(pthread_join(loop->thread, NULL)) {
- fprintf(stderr, "Error joining thread\n");
- return -1;
- }
- DEBUG("Loop terminated !");
+ DEBUG("Waiting for loop to terminate...");
+ if (pthread_join(loop->thread, NULL)) {
+ ERROR("Error joining thread\n");
+ return -1;
+ }
+ DEBUG("Loop terminated !");
#endif /* WITH_THREAD */
- return 0;
+ return 0;
}
-void
-loop_break(loop_t * loop)
-{
- event_base_loopbreak(loop->event_base);
-}
+void loop_break(loop_t *loop) { event_base_loopbreak(loop->event_base); }
-void cb_wrapper(evutil_socket_t fd, short what, void * arg) {
- cb_wrapper_args_t * cb_wrapper_args = arg;
- cb_wrapper_args->callback(cb_wrapper_args->owner, fd, cb_wrapper_args->data);
+void cb_wrapper(evutil_socket_t fd, short what, void *arg) {
+ cb_wrapper_args_t *cb_wrapper_args = arg;
+ cb_wrapper_args->callback(cb_wrapper_args->owner, fd, cb_wrapper_args->data);
}
/**
@@ -208,42 +198,41 @@ void cb_wrapper(evutil_socket_t fd, short what, void * arg) {
* \param [in] callback_data - User data to pass alongside callback invocation
* \return 0 in case of success, -1 otherwise
*/
-int
-_loop_register_fd(loop_t * loop, int fd, void * callback_owner,
- fd_callback_t callback, void * callback_data)
-{
- /* This will be freed with the event */
- cb_wrapper_args_t * cb_wrapper_args = malloc(sizeof(cb_wrapper_args_t));
- *cb_wrapper_args = (cb_wrapper_args_t) {
- .owner = callback_owner,
- .callback = callback,
- .data = callback_data,
- };
-
- evutil_make_socket_nonblocking(fd);
- struct event * event = event_new(loop->event_base, fd, EV_READ | EV_PERSIST, cb_wrapper, cb_wrapper_args);
- if (!event) {
- ERROR("[_loop_register_fd] event_new");
- goto ERR_EVENT_NEW;
- }
-
- if (event_add(event, NULL) < 0) {
- ERROR("[_loop_register_fd] event_add");
- goto ERR_EVENT_ADD;
- }
-
- if (event_map_add(loop->event_map, fd, event) < 0) {
- ERROR("[_loop_register_fd] event_map_add");
- goto ERR_EVENT_MAP;
- }
-
- return 0;
+int _loop_register_fd(loop_t *loop, int fd, void *callback_owner,
+ fd_callback_t callback, void *callback_data) {
+ /* This will be freed with the event */
+ cb_wrapper_args_t *cb_wrapper_args = malloc(sizeof(cb_wrapper_args_t));
+ *cb_wrapper_args = (cb_wrapper_args_t){
+ .owner = callback_owner,
+ .callback = callback,
+ .data = callback_data,
+ };
+
+ evutil_make_socket_nonblocking(fd);
+ struct event *event = event_new(loop->event_base, fd, EV_READ | EV_PERSIST,
+ cb_wrapper, cb_wrapper_args);
+ if (!event) {
+ ERROR("[_loop_register_fd] event_new");
+ goto ERR_EVENT_NEW;
+ }
+
+ if (event_add(event, NULL) < 0) {
+ ERROR("[_loop_register_fd] event_add");
+ goto ERR_EVENT_ADD;
+ }
+
+ if (event_map_add(loop->event_map, fd, event) < 0) {
+ ERROR("[_loop_register_fd] event_map_add");
+ goto ERR_EVENT_MAP;
+ }
+
+ return 0;
ERR_EVENT_MAP:
ERR_EVENT_ADD:
- event_free(event);
+ event_free(event);
ERR_EVENT_NEW:
- return -1;
+ return -1;
}
/**
@@ -251,183 +240,169 @@ ERR_EVENT_NEW:
* \param [in] fd - File descriptor to unregister
* \return 0 in case of success, -1 otherwise
*/
-int
-_loop_unregister_fd(loop_t * loop, int fd)
-{
- struct event * event = NULL;
+int _loop_unregister_fd(loop_t *loop, int fd) {
+ struct event *event = NULL;
- if (event_map_remove(loop->event_map, fd, &event) < 0) {
- ERROR("[_loop_unregister_fd] Error removing event associated to fd");
- return -1;
- }
+ if (event_map_remove(loop->event_map, fd, &event) < 0) {
+ ERROR("[_loop_unregister_fd] Error removing event associated to fd");
+ return -1;
+ }
- assert(event);
+ assert(event);
- cb_wrapper_args_t * cb_wrapper_args = event_get_callback_arg(event);
- free(cb_wrapper_args);
+ cb_wrapper_args_t *cb_wrapper_args = event_get_callback_arg(event);
+ free(cb_wrapper_args);
- event_del(event);
- event_free(event);
+ event_del(event);
+ event_free(event);
- return 0;
+ return 0;
}
-int
-loop_timer_callback(loop_t * loop, int fd, void * data)
-{
- char buf[1024]; /* size is not important */
- cb_wrapper_args_t * cb_wrapper_args = data;
- while (read(fd, &buf, sizeof(buf)) > 0)
- ;
+int loop_timer_callback(loop_t *loop, int fd, void *data) {
+ char buf[1024]; /* size is not important */
+ cb_wrapper_args_t *cb_wrapper_args = data;
+ while (read(fd, &buf, sizeof(buf)) > 0)
+ ;
- int rc = cb_wrapper_args->callback(cb_wrapper_args->owner, fd,
- cb_wrapper_args->data);
+ int rc = cb_wrapper_args->callback(cb_wrapper_args->owner, fd,
+ cb_wrapper_args->data);
- return rc;
+ return rc;
}
-int
-_loop_register_timer(loop_t * loop, timer_callback_data_t * timer_callback_data)
-{
- int fd = timerfd_create(CLOCK_MONOTONIC, 0);
- if (fd == -1) {
- perror("timerfd_create");
- return -1;
- }
+int _loop_register_timer(loop_t *loop,
+ timer_callback_data_t *timer_callback_data) {
+ int fd = timerfd_create(CLOCK_MONOTONIC, 0);
+ if (fd == -1) {
+ perror("timerfd_create");
+ return -1;
+ }
- if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
- perror("fcntl");
- return -1;
- }
+ if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
+ perror("fcntl");
+ return -1;
+ }
+
+ struct itimerspec ts = {
+ .it_interval =
+ {
+ .tv_sec = timer_callback_data->delay_ms / 1000,
+ .tv_nsec = (timer_callback_data->delay_ms % 1000) * 1000000,
+ },
+ .it_value = {
+ .tv_sec = timer_callback_data->delay_ms / 1000,
+ .tv_nsec = (timer_callback_data->delay_ms % 1000) * 1000000,
+ }};
+
+ if (timerfd_settime(fd, 0, &ts, NULL) == -1) {
+ perror("timerfd_settime");
+ return -1;
+ }
+
+ /* This should be freed together with the timer release */
+ cb_wrapper_args_t *cb_wrapper_args = malloc(sizeof(cb_wrapper_args_t));
+ *cb_wrapper_args = (cb_wrapper_args_t){
+ .owner = timer_callback_data->owner,
+ .callback = timer_callback_data->callback,
+ .data = timer_callback_data->data,
+ };
+
+ if (timer_fd_map_add(loop->timer_fd_map, fd, cb_wrapper_args) < 0) {
+ ERROR("[_loop_register_timer] Could not add cb_wrapper to timer map");
+ return -1;
+ }
- struct itimerspec ts = {
- .it_interval = {
- .tv_sec = timer_callback_data->delay_ms / 1000,
- .tv_nsec = (timer_callback_data->delay_ms % 1000) * 1000000,
- },
- .it_value = {
- .tv_sec = timer_callback_data->delay_ms / 1000,
- .tv_nsec = (timer_callback_data->delay_ms % 1000) * 1000000,
- }
- };
-
- if (timerfd_settime(fd, 0, &ts, NULL) == -1) {
- perror("timerfd_settime");
- return -1;
- }
+ if (_loop_register_fd(loop, fd, loop, (fd_callback_t)loop_timer_callback,
+ cb_wrapper_args) < 0) {
+ ERROR("[_loop_register_timer] Error registering fd to event loop");
+ return -1;
+ }
- /* This should be freed together with the timer release */
- cb_wrapper_args_t * cb_wrapper_args = malloc(sizeof(cb_wrapper_args_t));
- *cb_wrapper_args = (cb_wrapper_args_t) {
- .owner = timer_callback_data->owner,
- .callback = timer_callback_data->callback,
- .data = timer_callback_data->data,
- };
+ return fd;
+}
- if (timer_fd_map_add(loop->timer_fd_map, fd, cb_wrapper_args) < 0) {
- ERROR("[_loop_register_timer] Could not add cb_wrapper to timer map");
- return -1;
- }
+int _loop_unregister_timer(loop_t *loop, int fd) {
+ struct itimerspec ts = {.it_interval =
+ {
+ .tv_sec = 0,
+ .tv_nsec = 0,
+ },
+ .it_value = {
+ /* This value disables the timer */
+ .tv_sec = 0,
+ .tv_nsec = 0,
+ }};
+ ts.it_value.tv_sec = 0;
+
+ if (timerfd_settime(fd, 0, &ts, NULL) == -1) {
+ perror("timerfd_settime");
+ return -1;
+ }
- if (_loop_register_fd(loop, fd, loop,
- (fd_callback_t) loop_timer_callback, cb_wrapper_args) < 0) {
- ERROR("[_loop_register_timer] Error registering fd to event loop");
- return -1;
- }
+ cb_wrapper_args_t *cb_wrapper_args;
+ if (timer_fd_map_remove(loop->timer_fd_map, fd, &cb_wrapper_args) < 0) {
+ ERROR(
+ "[_loop_unregister_timer] Could not remove cb_wrapper from timer map");
+ return -1;
+ }
+ assert(cb_wrapper_args);
+ free(cb_wrapper_args);
+
+ if (_loop_unregister_fd(loop, fd) < 0) {
+ ERROR("[_loop_unregister_timer] Error unregistering fd from event loop");
+ return -1;
+ }
- return fd;
+ close(fd);
+
+ return 0;
}
-int
-_loop_unregister_timer(loop_t * loop, int fd)
-{
- struct itimerspec ts = {
- .it_interval = {
- .tv_sec = 0,
- .tv_nsec = 0,
- },
- .it_value = { /* This value disables the timer */
- .tv_sec = 0,
- .tv_nsec = 0,
- }
- };
- ts.it_value.tv_sec = 0;
-
- if (timerfd_settime(fd, 0, &ts, NULL) == -1) {
- perror("timerfd_settime");
+int loop_callback(loop_t *loop, facemgr_cb_type_t type, void *data) {
+ switch (type) {
+ case FACEMGR_CB_TYPE_REGISTER_FD: {
+ fd_callback_data_t *fd_callback_data = (fd_callback_data_t *)data;
+ if (_loop_register_fd(loop, fd_callback_data->fd, fd_callback_data->owner,
+ fd_callback_data->callback,
+ fd_callback_data->data) < 0) {
+ ERROR("[loop_callback] Error registering fd to event loop");
return -1;
+ }
+ break;
}
- cb_wrapper_args_t * cb_wrapper_args;
- if (timer_fd_map_remove(loop->timer_fd_map, fd, &cb_wrapper_args) < 0) {
- ERROR("[_loop_unregister_timer] Could not remove cb_wrapper from timer map");
+ case FACEMGR_CB_TYPE_UNREGISTER_FD: {
+ fd_callback_data_t *fd_callback_data = (fd_callback_data_t *)data;
+ /* We need a map to associate fd and events */
+ if (_loop_unregister_fd(loop, fd_callback_data->fd) < 0) {
+ ERROR("[loop_callback] Error unregistering fd from event loop");
return -1;
+ }
+ break;
}
- assert(cb_wrapper_args);
- free(cb_wrapper_args);
- if (_loop_unregister_fd(loop, fd) < 0) {
- ERROR("[_loop_unregister_timer] Error unregistering fd from event loop");
+ case FACEMGR_CB_TYPE_REGISTER_TIMER: {
+ timer_callback_data_t *timer_callback_data =
+ (timer_callback_data_t *)data;
+
+ int fd = _loop_register_timer(loop, timer_callback_data);
+ if (fd < 0) {
+ ERROR("[loop_callback] Error registering timer to event loop");
return -1;
+ }
+ return fd;
}
- return 0;
-}
+ case FACEMGR_CB_TYPE_UNREGISTER_TIMER: {
+ int fd = *(int *)data;
-int
-loop_callback(loop_t * loop, facemgr_cb_type_t type, void * data)
-{
- switch(type) {
- case FACEMGR_CB_TYPE_REGISTER_FD:
- {
- fd_callback_data_t * fd_callback_data = (fd_callback_data_t *)data;
- if (_loop_register_fd(loop, fd_callback_data->fd,
- fd_callback_data->owner,
- fd_callback_data->callback,
- fd_callback_data->data) < 0) {
-
- ERROR("[loop_callback] Error registering fd to event loop");
- return -1;
- }
- break;
- }
-
- case FACEMGR_CB_TYPE_UNREGISTER_FD:
- {
- fd_callback_data_t * fd_callback_data = (fd_callback_data_t *)data;
- /* We need a map to associate fd and events */
- if (_loop_unregister_fd(loop, fd_callback_data->fd) < 0) {
- ERROR("[loop_callback] Error unregistering fd from event loop");
- return -1;
- }
- break;
- }
-
- case FACEMGR_CB_TYPE_REGISTER_TIMER:
- {
- timer_callback_data_t * timer_callback_data = (timer_callback_data_t *)data;
-
- int fd = _loop_register_timer(loop, timer_callback_data);
- if (fd < 0) {
- ERROR("[loop_callback] Error registering timer to event loop");
- return -1;
- }
- return fd;
-
- }
-
- case FACEMGR_CB_TYPE_UNREGISTER_TIMER:
- {
- int fd = *(int*)data;
-
- if (_loop_unregister_timer(loop, fd) < 0) {
- ERROR("[loop_callback] Error unregistering timer from event loop");
- return -1;
- }
- return 0;
-
- }
+ if (_loop_unregister_timer(loop, fd) < 0) {
+ ERROR("[loop_callback] Error unregistering timer from event loop");
+ return -1;
+ }
+ return 0;
}
- return 0;
+ }
+ return 0;
}
-
diff --git a/ctrl/facemgr/src/main.c b/ctrl/facemgr/src/main.c
index 344b034ae..18d2f8f7c 100644
--- a/ctrl/facemgr/src/main.c
+++ b/ctrl/facemgr/src/main.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,7 +24,7 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
-#include <unistd.h> // sleep
+#include <unistd.h> // sleep
#include <hicn/facemgr.h>
#include <hicn/facemgr/cfg.h>
@@ -41,7 +41,7 @@
#if 0
static struct event_base * loop;
#endif
-static loop_t * loop = NULL;
+static loop_t* loop = NULL;
#ifdef __linux__
#ifdef WITH_THREAD
@@ -49,210 +49,193 @@ static bool stop = false;
#endif /* WITH_THREAD */
#endif /* __linux__ */
-static struct option long_options[] =
-{
- {"config", required_argument, 0, 'c'},
- {0, 0, 0, 0}
-};
+static struct option long_options[] = {{"config", required_argument, 0, 'c'},
+ {0, 0, 0, 0}};
typedef struct {
- char * cfgfile;
+ char* cfgfile;
} facemgr_options_t;
-void usage(const char * progname)
-{
- printf("%s: Face manager daemon\n", progname);
- printf("\n");
- printf("Usage: %s [OPTIONS]\n", progname);
- printf("\n");
- printf("OPTIONS:\n");
- printf(" -c --config [FILE|none] Sets the configuration file (unless none, default: /etc/facemgr.conf, ~/facemgr.conf)\n");
- printf("\n");
+void usage(const char* progname) {
+ printf("%s: Face manager daemon\n", progname);
+ printf("\n");
+ printf("Usage: %s [OPTIONS]\n", progname);
+ printf("\n");
+ printf("OPTIONS:\n");
+ printf(
+ " -c --config [FILE|none] Sets the configuration file (unless none, "
+ "default: /etc/facemgr.conf, ~/facemgr.conf)\n");
+ printf("\n");
}
void facemgr_signal_handler(int signal) {
- fprintf(stderr, "Received ^C... quitting !\n");
- if (loop) {
- loop_break(loop);
+ fprintf(stderr, "Received ^C... quitting !\n");
+ if (loop) {
+ loop_break(loop);
#ifdef __linux__
#ifdef WITH_THREAD
stop = true;
#endif /* WITH_THREAD */
#endif /* __linux__ */
- }
+ }
}
-int parse_cmdline(int argc, char ** argv, facemgr_options_t * opts)
-{
- int c;
- while ((c = getopt_long(argc, argv, "c:", long_options, NULL)) != -1) {
- switch(c) {
- case 'c':
- opts->cfgfile = optarg;
- break;
- case ':':
- case '?':
- default:
- usage(argv[0]);
- exit(EXIT_FAILURE);
- }
-
+int parse_cmdline(int argc, char** argv, facemgr_options_t* opts) {
+ int c;
+ while ((c = getopt_long(argc, argv, "c:", long_options, NULL)) != -1) {
+ switch (c) {
+ case 'c':
+ opts->cfgfile = optarg;
+ break;
+ case ':':
+ case '?':
+ default:
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
}
- return 0;
+ }
+ return 0;
}
-#ifdef __linux__
-
-#endif /* __linux__ */
-
-int
-dump_facelet(const facemgr_t * facemgr, const facelet_t * facelet,
- void * user_data)
-{
- char facelet_s[MAXSZ_FACELET];
- facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet);
- DEBUG("%s", facelet_s);
- return 0;
+int dump_facelet(const facemgr_t* facemgr, const facelet_t* facelet,
+ void* user_data) {
+ char facelet_s[MAXSZ_FACELET];
+ facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet);
+ DEBUG("%s", facelet_s);
+ return 0;
}
-int main(int argc, char ** argv)
-{
- facemgr_cfg_t * cfg = NULL;
- facemgr_t * facemgr;
+int main(int argc, char** argv) {
+ facemgr_cfg_t* cfg = NULL;
+ facemgr_t* facemgr;
- struct sigaction sigIntHandler;
- sigIntHandler.sa_handler = facemgr_signal_handler;
- sigemptyset(&sigIntHandler.sa_mask);
- sigIntHandler.sa_flags = 0;
- sigaction(SIGINT, &sigIntHandler, NULL);
+ struct sigaction sigIntHandler;
+ sigIntHandler.sa_handler = facemgr_signal_handler;
+ sigemptyset(&sigIntHandler.sa_mask);
+ sigIntHandler.sa_flags = 0;
+ sigaction(SIGINT, &sigIntHandler, NULL);
- char cfgfile[PATH_MAX];
+ char cfgfile[PATH_MAX];
- // TODO: default < config < commandline on a per option basis
+ // TODO: default < config < commandline on a per option basis
- /* Commandline */
- facemgr_options_t cmdline_opts = {0};
- if (parse_cmdline(argc, argv, &cmdline_opts) < 0) {
- ERROR("Error parsing commandline");
- goto ERR_CMDLINE;
- }
+ /* Commandline */
+ facemgr_options_t cmdline_opts = {0};
+ if (parse_cmdline(argc, argv, &cmdline_opts) < 0) {
+ ERROR("Error parsing commandline");
+ goto ERR_CMDLINE;
+ }
- /* Configuration file */
- //facemgr_options_t cfgfile_opts;
+ /* Configuration file */
+ // facemgr_options_t cfgfile_opts;
- if (cmdline_opts.cfgfile) {
- if (strcasecmp(cmdline_opts.cfgfile, "none") == 0)
- goto NO_CFGFILE;
+ if (cmdline_opts.cfgfile) {
+ if (strcasecmp(cmdline_opts.cfgfile, "none") == 0) goto NO_CFGFILE;
- if (!realpath(cmdline_opts.cfgfile, (char*)&cfgfile))
- goto ERR_PATH;
+ if (!realpath(cmdline_opts.cfgfile, (char*)&cfgfile)) goto ERR_PATH;
- goto PARSE_CFGFILE;
- }
+ goto PARSE_CFGFILE;
+ }
- /* No commandline path specifed, probe default locations... */
+ /* No commandline path specifed, probe default locations... */
- if (probe_cfgfile(cfgfile) < 0)
- goto NO_CFGFILE;
+ if (probe_cfgfile(cfgfile) < 0) goto NO_CFGFILE;
PARSE_CFGFILE:
- DEBUG("Using configuration file %s", cfgfile);
- cfg = facemgr_cfg_create();
- if (!cfg)
- goto ERR_FACEMGR_CFG;
+ DEBUG("Using configuration file %s", cfgfile);
+ cfg = facemgr_cfg_create();
+ if (!cfg) goto ERR_FACEMGR_CFG;
- if (parse_config_file(cfgfile, cfg) < 0) {
- ERROR("Error parsing configuration file %s", cfgfile);
- goto ERR_PARSE;
- }
+ if (parse_config_file(cfgfile, cfg) < 0) {
+ ERROR("Error parsing configuration file %s", cfgfile);
+ goto ERR_PARSE;
+ }
- facemgr = facemgr_create_with_config(cfg);
- if (!facemgr)
- goto ERR_FACEMGR_CONFIG;
+ facemgr = facemgr_create_with_config(cfg);
+ if (!facemgr) goto ERR_FACEMGR_CONFIG;
- goto MAIN_LOOP;
+ goto MAIN_LOOP;
NO_CFGFILE:
- facemgr = facemgr_create();
- if (!facemgr)
- goto ERR_FACEMGR;
+ facemgr = facemgr_create();
+ if (!facemgr) goto ERR_FACEMGR;
MAIN_LOOP:
- /* Main loop */
- loop = loop_create();
- facemgr_set_callback(facemgr, loop, (void*)loop_callback);
+ /* Main loop */
+ loop = loop_create();
+ if (!loop) {
+ ERROR("Failed to create main loop");
+ goto ERR_LOOP;
+ }
+ facemgr_set_callback(facemgr, loop, (void*)loop_callback);
#ifdef __ANDROID__
- facemgr_set_jvm(facemgr, NULL);
+ facemgr_set_jvm(facemgr, NULL);
#endif /* __ ANDROID__ */
- DEBUG("Bootstrap...");
+ DEBUG("Bootstrap...");
- if (facemgr_bootstrap(facemgr) < 0 )
- goto ERR_BOOTSTRAP;
+ if (facemgr_bootstrap(facemgr) < 0) goto ERR_BOOTSTRAP;
- if (loop_dispatch(loop) < 0) {
- ERROR("Failed to run main loop");
- return EXIT_FAILURE;
- }
+ if (loop_dispatch(loop) < 0) {
+ ERROR("Failed to run main loop");
+ goto ERR_DISPATCH;
+ }
#ifdef __linux__
#ifdef WITH_THREAD
- unsigned cpt = 0;
- while(!stop) {
- if (cpt == 10) {
- DEBUG("<facelets>");
+ unsigned cpt = 0;
+ while (!stop) {
+ if (cpt == 10) {
+ DEBUG("<facelets>");
#if 1
- facemgr_list_facelets(facemgr, dump_facelet, NULL);
+ facemgr_list_facelets(facemgr, dump_facelet, NULL);
#else
- char * buffer;
- int n = facemgr_list_facelets_json(facemgr, &buffer);
- printf("%s\n", buffer);
- free(buffer);
+ char* buffer;
+ int n = facemgr_list_facelets_json(facemgr, &buffer);
+ printf("%s\n", buffer);
+ free(buffer);
#endif
- DEBUG("</facelets>");
- cpt = 0;
- }
- usleep(500000);
- cpt++;
+ DEBUG("</facelets>");
+ cpt = 0;
}
+ usleep(500000);
+ cpt++;
+ }
#endif /* WITH_THREAD */
#endif /* __linux__ */
- facemgr_stop(facemgr);
+ facemgr_stop(facemgr);
- if (loop_undispatch(loop) < 0) {
- ERROR("Failed to terminate main loop");
- return EXIT_FAILURE;
- }
+ if (loop_undispatch(loop) < 0) {
+ ERROR("Failed to terminate main loop");
+ }
- facemgr_free(facemgr);
+ facemgr_free(facemgr);
- if (cfg)
- facemgr_cfg_free(cfg);
+ if (cfg) facemgr_cfg_free(cfg);
- loop_free(loop);
+ loop_free(loop);
- return EXIT_SUCCESS;
+ return EXIT_SUCCESS;
ERR_BOOTSTRAP:
+ facemgr_free(facemgr);
+ERR_DISPATCH:
+ loop_free(loop);
+ERR_LOOP:
- facemgr_free(facemgr);
- loop_free(loop);
ERR_FACEMGR_CONFIG:
ERR_FACEMGR:
ERR_PARSE:
- if (cfg)
- facemgr_cfg_free(cfg);
+ if (cfg) facemgr_cfg_free(cfg);
ERR_FACEMGR_CFG:
ERR_PATH:
ERR_CMDLINE:
- return EXIT_FAILURE;
-
-
+ return EXIT_FAILURE;
}
diff --git a/ctrl/libhicnctrl/CMakeLists.txt b/ctrl/libhicnctrl/CMakeLists.txt
index 22f81401f..bf5ffd699 100644
--- a/ctrl/libhicnctrl/CMakeLists.txt
+++ b/ctrl/libhicnctrl/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,50 +11,65 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Project and cmake version
+##############################################################
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-
project(libhicnctrl)
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
-endif()
+##############################################################
+# Cmake modules
+##############################################################
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
"${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/Modules"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
)
-include(BuildMacros)
-
-set(CMAKE_C_STANDARD 11)
-set(CMAKE_C_STANDARD_REQUIRED ON)
-
-set(CMAKE_MACOSX_RPATH ON)
-
+##############################################################
+# Libs and Bins names
+##############################################################
set(LIBHICNCTRL hicnctrl)
-
set(LIBHICNCTRL ${LIBHICNCTRL} CACHE INTERNAL "" FORCE)
set(LIBHICNCTRL_SHARED ${LIBHICNCTRL}.shared CACHE INTERNAL "" FORCE)
set(LIBHICNCTRL_STATIC ${LIBHICNCTRL}.static CACHE INTERNAL "" FORCE)
set(HICNCTRL hicnctrl CACHE INTERNAL "" FORCE)
-set(LIBHICNCTRL_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/includes CACHE INTERNAL "" FORCE)
+set(LIBHICNCTRL_COMPONENT lib${LIBHICNCTRL})
+set(LIBHICNCTRL_COMPONENT_MODULES ${LIBHICNCTRL_COMPONENT}-modules)
+
+
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../versions.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
+
+##############################################################
+# C Standard
+##############################################################
+set(CMAKE_C_STANDARD 11)
+set(CMAKE_C_STANDARD_REQUIRED ON)
+
+set(CMAKE_MACOSX_RPATH ON)
+
+
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- if (BUILD_HICNPLUGIN AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
- find_package_wrapper(HicnPlugin REQUIRED)
- endif()
+ include(CommonSetup)
- find_package_wrapper(Libhicn REQUIRED)
- list(APPEND HICN_LIBRARIES ${LIBHICN_SHARED})
+ find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
- set(HICN_INCLUDE_DIRS
- ${HICN_INCLUDE_DIRS}
- ${HICNPLUGIN_INCLUDE_DIRS}
- ${SAFE_VAPI_INCLUDE_DIRS})
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
+ list(APPEND HICN_LIBRARIES hicn::hicn.${LIBTYPE})
else()
if (DISABLE_SHARED_LIBRARIES)
if (WIN32)
@@ -65,36 +80,21 @@ else()
list(APPEND DEPENDENCIES
${LIBHICN_STATIC}
)
- elseif (BUILD_HICNPLUGIN AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
- set(
- HICN_INCLUDE_DIRS
- ${HICN_INCLUDE_DIRS}
- ${HICNPLUGIN_INCLUDE_DIRS}
- ${SAFE_VAPI_INCLUDE_DIRS}
- )
-
- list(APPEND DEPENDENCIES
- hicn_plugin
- ${SAFE_VAPI_SHARED}
- )
else ()
set(HICN_LIBRARIES ${LIBHICN_SHARED})
list(APPEND DEPENDENCIES
${LIBHICN_SHARED}
)
endif ()
-
endif()
-set(LIBHICNCTRL_COMPONENT lib${LIBHICNCTRL})
-set (LIBHICNCTRL_COMPONENT_MODULES ${LIBHICNCTRL_COMPONENT}-modules)
+##############################################################
+# Include directories
+##############################################################
add_subdirectory(includes)
add_subdirectory(src)
-include(Packaging)
-
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
+ make_packages()
endif()
diff --git a/ctrl/libhicnctrl/cmake/Modules/Packaging.cmake b/ctrl/libhicnctrl/cmake/packaging.cmake
index 2851375be..74905d6c4 100644
--- a/ctrl/libhicnctrl/cmake/Modules/Packaging.cmake
+++ b/ctrl/libhicnctrl/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -31,7 +31,7 @@ set(${LIBHICNCTRL_COMPONENT}_DEB_DEPENDENCIES
)
set(${LIBHICNCTRL_COMPONENT}-dev_DEB_DEPENDENCIES
- "${LIBHICNCTRL_COMPONENT} (>= stable_version)"
+ "${LIBHICNCTRL_COMPONENT} (= stable_version)"
CACHE STRING "Dependencies for deb/rpm package."
)
@@ -41,16 +41,16 @@ set(${LIBHICNCTRL_COMPONENT}_RPM_DEPENDENCIES
)
set(${LIBHICNCTRL_COMPONENT}-dev_RPM_DEPENDENCIES
- "${LIBHICNCTRL_COMPONENT} >= stable_version"
+ "${LIBHICNCTRL_COMPONENT} = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${LIBHICNCTRL_COMPONENT_MODULES}_DEB_DEPENDENCIES
- "hicn-plugin (>= stable_version)"
+ "hicn-plugin (= stable_version)"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${LIBHICNCTRL_COMPONENT_MODULES}_RPM_DEPENDENCIES
- "hicn-plugin >= stable_version"
+ "hicn-plugin = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
)
diff --git a/ctrl/libhicnctrl/examples/Makefile b/ctrl/libhicnctrl/examples/Makefile
index ad0e46a1e..a3aae11b0 100644
--- a/ctrl/libhicnctrl/examples/Makefile
+++ b/ctrl/libhicnctrl/examples/Makefile
@@ -1,7 +1,7 @@
EXEC = $(shell basename $$(pwd))
CC = gcc
-CFLAGS = -std=gnu11 -g -Wall -Wextra -Wpedantic -Wstrict-aliasing -DWITH_POLICY=1
+CFLAGS = -std=gnu11 -g -Wall -Wextra -Wpedantic -Wstrict-aliasing -DWITH_POLICY
LDFLAGS = -lhicn -lhicnctrl
SRC = $(wildcard *.c)
diff --git a/ctrl/libhicnctrl/examples/create_face.c b/ctrl/libhicnctrl/examples/create_face.c
index 5f92f5906..a2ef3e9db 100644
--- a/ctrl/libhicnctrl/examples/create_face.c
+++ b/ctrl/libhicnctrl/examples/create_face.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,125 +22,117 @@
*/
#include <stdlib.h>
-#include <sys/types.h> // getifaddrs
-#include <ifaddrs.h> // getifaddrs
+#include <sys/types.h> // getifaddrs
+#include <ifaddrs.h> // getifaddrs
#include <stdio.h>
-#include <string.h> /* for strncpy */
-#include <sys/socket.h> // socket
-#include <sys/ioctl.h> // ioctl
+#include <sys/socket.h> // socket
+#include <sys/ioctl.h> // ioctl
#include <unistd.h>
#include <hicn/ctrl.h>
#include <hicn/util/log.h>
-int get_local_info(char * if_name, ip_address_t * local_ip) {
- struct ifaddrs *addrs;
- struct ifreq ifr = {
- .ifr_addr.sa_family = AF_INET,
- };
- int ret = -1;
-
- int fd = socket(AF_INET, SOCK_DGRAM, 0);
-
- getifaddrs(&addrs);
-
- for (struct ifaddrs * tmp = addrs; tmp; tmp = tmp->ifa_next) {
- if (!tmp->ifa_addr || tmp->ifa_addr->sa_family != AF_PACKET)
- continue;
- if (strcmp(tmp->ifa_name, "lo") == 0)
- continue;
- snprintf(if_name, IFNAMSIZ, "%s", tmp->ifa_name);
-
- snprintf(ifr.ifr_name, IFNAMSIZ, "%s", tmp->ifa_name);
- if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) {
- //perror("ioctl");
- continue;
- }
-
- *local_ip = IP_ADDRESS_EMPTY;
- local_ip->v4.as_inaddr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
- if (ip_address_empty(local_ip))
- continue;
-
- ret = 0;
- break;
- }
-
- freeifaddrs(addrs);
- close(fd);
- return ret;
-}
-
-int main() {
- char remote_ip_str[INET_ADDRSTRLEN] = "1.1.1.1";
-
- ip_address_t local_ip;
- ip_address_t remote_ip;
- char if_name[IFNAMSIZ];
+int get_local_info(char *if_name, hicn_ip_address_t *local_ip) {
+ struct ifaddrs *addrs;
+ struct ifreq ifr = {
+ .ifr_addr.sa_family = AF_INET,
+ };
+ int ret = -1;
- /* Retrieving local info */
+ int fd = socket(AF_INET, SOCK_DGRAM, 0);
- if (get_local_info(if_name, &local_ip) < 0) {
- DEBUG("Error getting local information");
- goto ERR_INIT;
- }
+ getifaddrs(&addrs);
- char local_ip_str[MAXSZ_IP_ADDRESS];
- ip_address_snprintf(local_ip_str, MAXSZ_IP_ADDRESS, &local_ip, AF_INET);
- DEBUG("Local information :");
- DEBUG(" - Interface name : %s", if_name);
- DEBUG(" - IP address : %s", local_ip_str);
+ for (struct ifaddrs *tmp = addrs; tmp; tmp = tmp->ifa_next) {
+ if (!tmp->ifa_addr || tmp->ifa_addr->sa_family != AF_PACKET) continue;
+ if (strcmp(tmp->ifa_name, "lo") == 0) continue;
+ snprintf(if_name, IFNAMSIZ, "%s", tmp->ifa_name);
- if (ip_address_pton (remote_ip_str, &remote_ip) < 0){
- DEBUG("Error parsing remote IP address");
- goto ERR_INIT;
+ snprintf(ifr.ifr_name, IFNAMSIZ, "%s", tmp->ifa_name);
+ if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) {
+ // perror("ioctl");
+ continue;
}
- /* Filling face information */
- hc_face_t face = {
- .face = {
- .type = FACE_TYPE_UDP,
- .family = AF_INET,
- .local_addr = local_ip,
- .remote_addr = remote_ip,
- .local_port = 6000,
- .remote_port = 6000,
- .admin_state = FACE_STATE_UNDEFINED,
- .state = FACE_STATE_UNDEFINED,
-#ifdef WITH_POLICY
- .priority = 0,
- .tags = POLICY_TAGS_EMPTY,
-#endif /* WITH_POLICY */
- },
- };
- if (netdevice_set_name(&face.face.netdevice, if_name) < 0) {
- DEBUG("Error setting face netdevice name");
- goto ERR_INIT;
- }
+ *local_ip = IP_ADDRESS_EMPTY;
+ local_ip->v4.as_inaddr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
+ if (hicn_ip_address_empty(local_ip)) continue;
- /* Connecting to socket and creating face */
+ ret = 0;
+ break;
+ }
- hc_sock_t * socket = hc_sock_create();
- if (!socket){
- DEBUG("Error creating libhicnctrl socket");
- goto ERR_SOCK;
- }
-
- if (hc_sock_connect(socket) < 0){
- DEBUG("Error connecting to forwarder");
- goto ERR;
- }
-
- if (hc_face_create(socket, &face) < 0){
- DEBUG("Error creating face");
- goto ERR;
- }
+ freeifaddrs(addrs);
+ close(fd);
+ return ret;
+}
- DEBUG("Face created successfully");
+int main() {
+ char remote_ip_str[INET_ADDRSTRLEN] = "1.1.1.1";
+
+ hicn_ip_address_t local_ip;
+ hicn_ip_address_t remote_ip;
+ char if_name[IFNAMSIZ];
+
+ /* Retrieving local info */
+
+ if (get_local_info(if_name, &local_ip) < 0) {
+ DEBUG("Error getting local information");
+ goto ERR_INIT;
+ }
+
+ char local_ip_str[MAXSZ_IP_ADDRESS];
+ hicn_ip_address_snprintf(local_ip_str, MAXSZ_IP_ADDRESS, &local_ip);
+ DEBUG("Local information :");
+ DEBUG(" - Interface name : %s", if_name);
+ DEBUG(" - IP address : %s", local_ip_str);
+
+ if (hicn_ip_address_pton(remote_ip_str, &remote_ip) < 0) {
+ DEBUG("Error parsing remote IP address");
+ goto ERR_INIT;
+ }
+
+ /* Filling face information */
+ hc_face_t face = {
+ .type = FACE_TYPE_UDP,
+ .family = AF_INET,
+ .local_addr = local_ip,
+ .remote_addr = remote_ip,
+ .local_port = 6000,
+ .remote_port = 6000,
+ .admin_state = FACE_STATE_UNDEFINED,
+ .state = FACE_STATE_UNDEFINED,
+ .priority = 0,
+ .tags = POLICY_TAGS_EMPTY,
+ };
+ if (netdevice_set_name(&face.netdevice, if_name) < 0) {
+ DEBUG("Error setting face netdevice name");
+ goto ERR_INIT;
+ }
+
+ /* Connecting to socket and creating face */
+
+ hc_sock_t *socket = hc_sock_create_forwarder(FORWARDER_TYPE_HICNLIGHT);
+ if (!socket) {
+ DEBUG("Error creating libhicnctrl socket");
+ goto ERR_SOCK;
+ }
+
+ if (hc_sock_connect(socket) < 0) {
+ DEBUG("Error connecting to forwarder");
+ goto ERR;
+ }
+
+ if (hc_face_create(socket, &face) < 0) {
+ DEBUG("Error creating face");
+ goto ERR;
+ }
+
+ INFO("Face created successfully");
ERR:
- hc_sock_free(socket);
+ hc_sock_free(socket);
ERR_SOCK:
ERR_INIT:
- return 0;
+ return 0;
}
diff --git a/ctrl/libhicnctrl/examples/update_priority.c b/ctrl/libhicnctrl/examples/update_priority.c
index d350f71c9..6dd974067 100644
--- a/ctrl/libhicnctrl/examples/update_priority.c
+++ b/ctrl/libhicnctrl/examples/update_priority.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,37 +24,36 @@
#include <hicn/ctrl.h>
#include <hicn/util/log.h>
-int main(int argc, char **argv)
-{
- if (argc != 3) {
- fprintf(stderr, "Usage: %s FACE_ID PRIORITY\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- unsigned face_id = atoi(argv[1]);
- unsigned priority = atoi(argv[2]);
- char face_id_s[SYMBOLIC_NAME_LEN];
-
- hc_sock_t * socket = hc_sock_create();
- if (!socket){
- DEBUG("Error creating libhicnctrl socket");
- goto ERR_SOCK;
- }
-
- if (hc_sock_connect(socket) < 0){
- DEBUG("Error connecting to forwarder");
- goto ERR;
- }
-
- snprintf(face_id_s, SYMBOLIC_NAME_LEN, "%d", face_id);
- if (hc_face_set_priority(socket, face_id_s, priority) < 0) {
- DEBUG("Error setting face priority");
- goto ERR;
- }
-
- DEBUG("Face priority updated successfully");
+int main(int argc, char **argv) {
+ if (argc != 3) {
+ fprintf(stderr, "Usage: %s FACE_ID PRIORITY\n", argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ unsigned face_id = atoi(argv[1]);
+ unsigned priority = atoi(argv[2]);
+ char face_id_s[SYMBOLIC_NAME_LEN];
+
+ hc_sock_t *socket = hc_sock_create_forwarder(FORWARDER_TYPE_HICNLIGHT);
+ if (!socket) {
+ DEBUG("Error creating libhicnctrl socket");
+ goto ERR_SOCK;
+ }
+
+ if (hc_sock_connect(socket) < 0) {
+ DEBUG("Error connecting to forwarder");
+ goto ERR;
+ }
+
+ snprintf(face_id_s, SYMBOLIC_NAME_LEN, "%d", face_id);
+ if (hc_face_set_priority(socket, face_id_s, priority) < 0) {
+ DEBUG("Error setting face priority");
+ goto ERR;
+ }
+
+ DEBUG("Face priority updated successfully");
ERR:
- hc_sock_free(socket);
+ hc_sock_free(socket);
ERR_SOCK:
- return 0;
+ return 0;
}
diff --git a/ctrl/libhicnctrl/includes/CMakeLists.txt b/ctrl/libhicnctrl/includes/CMakeLists.txt
index 50cfa4ad5..63b8aa9a7 100644
--- a/ctrl/libhicnctrl/includes/CMakeLists.txt
+++ b/ctrl/libhicnctrl/includes/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,17 +11,46 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-set(LIBHICNCTRL_INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR} ""
+##############################################################
+# Public headers directory
+##############################################################
+set(Libhicnctrl_INCLUDE_DIRS
+ ${CMAKE_CURRENT_SOURCE_DIR}
CACHE INTERNAL
"" FORCE
)
+
+##############################################################
+# To install header files
+##############################################################
set(TO_INSTALL_HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/ctrl.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/api.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/commands.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/face.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/action.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/callback.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/command.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/data.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/fw_interface.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/hicn-light.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/object.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/object_type.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/active_interface.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/base.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/cache.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/connection.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/face.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/listener.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/mapme.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/policy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/punting.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/route.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/stats.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/strategy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/objects/subscription.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/parse.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/route.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/socket.h
PARENT_SCOPE
)
diff --git a/ctrl/libhicnctrl/includes/ctrl.h b/ctrl/libhicnctrl/includes/ctrl.h
index e61b7a482..477afd152 100644
--- a/ctrl/libhicnctrl/includes/ctrl.h
+++ b/ctrl/libhicnctrl/includes/ctrl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl.h b/ctrl/libhicnctrl/includes/hicn/ctrl.h
index e61b7a482..4decdf10f 100644
--- a/ctrl/libhicnctrl/includes/hicn/ctrl.h
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,5 +21,6 @@
#define HICNCTRL_H
#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/socket.h>
#endif /* HICNCTRL_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/action.h b/ctrl/libhicnctrl/includes/hicn/ctrl/action.h
new file mode 100644
index 000000000..55c4ebf77
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/action.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file action.h
+ * \brief Actions.
+ */
+
+#ifndef HICNCTRL_ACTION_H
+#define HICNCTRL_ACTION_H
+
+#define foreach_action \
+ _(UNDEFINED) \
+ _(CREATE) \
+ _(UPDATE) \
+ _(DELETE) \
+ _(LIST) \
+ _(GET) \
+ _(SET) \
+ _(SERVE) \
+ _(STORE) \
+ _(CLEAR) \
+ _(SUBSCRIBE) \
+ _(N)
+
+typedef enum {
+#define _(x) ACTION_##x,
+ foreach_action
+#undef _
+} hc_action_t;
+
+extern const char *action_str[];
+
+#define action_str(x) action_str[x]
+
+hc_action_t action_from_str(const char *action_str);
+
+#endif /* HICNCTRL_ACTION_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/api.h b/ctrl/libhicnctrl/includes/hicn/ctrl/api.h
index b5a968800..87f0e955d 100644
--- a/ctrl/libhicnctrl/includes/hicn/ctrl/api.h
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/api.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -58,8 +58,6 @@
* provide a set of defines to preserve backwards compatibility. At the
* moment, those defines are :
*
- * WITH_POLICY:
- *
*/
#ifndef HICNTRL_API
@@ -67,10 +65,27 @@
#include <stdbool.h>
#include <stdint.h>
-
+#include <stddef.h> // object_offset_t
+
+#include <hicn/ctrl/action.h>
+#include <hicn/ctrl/callback.h>
+#include <hicn/ctrl/data.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/object_type.h>
+#include <hicn/ctrl/objects.h>
+#include <hicn/ctrl/socket.h>
#include <hicn/util/ip_address.h>
-#include <hicn/ctrl/commands.h>
-#include "face.h"
+#include <hicn/face.h>
+#include <hicn/strategy.h>
+
+#include <hicn/base.h>
+/*
+ * This has to be common between hicn-light and hicn-plugin. We now we keep the
+ * minimum of the two
+ */
+#define SYMBOLIC_NAME_LEN 16
+
+#include <hicn/ctrl/objects.h>
#define HICN_DEFAULT_PORT 9695
@@ -95,266 +110,21 @@
})x) \
.b)
#endif
+
+#define MAX2(x1, x2) (x1 > x2 ? x1 : x2)
+#define MAX4(x1, x2, x3, x4) (MAX2(MAX2(x1, x2), MAX2(x3, x4)))
+#define MAX8(x1, x2, x3, x4, x5, x6, x7, x8) \
+ (MAX2(MAX4(x1, x2, x3, x4), MAX4(x5, x6, x7, x8)))
+
/******************************************************************************
* Message helper types and aliases
******************************************************************************/
-#define foreach_command \
- _(UNDEFINED) \
- _(CREATE) \
- _(UPDATE) \
- _(DELETE) \
- _(LIST) \
- _(SET) \
- _(N)
-
-typedef enum {
-#define _(x) ACTION_##x,
- foreach_command
-#undef _
-} hc_action_t;
-
/**
* \brief hICN control message header
*/
typedef struct hc_msg_s hc_msg_t;
-
-/******************************************************************************
- * Control Data
- ******************************************************************************/
-
-struct hc_data_s;
-typedef int (*data_callback_t)(struct hc_data_s *, void *);
-
-/**
- * \brief Holds the results of an hICN control request
- */
-typedef struct hc_data_s {
- size_t size;
- size_t current;
- size_t max_size_log;
- size_t in_element_size;
- size_t out_element_size;
- u8 command_id; /**< Expected message type (should give element size) */
- u8 *buffer;
- bool complete;
-
- /* Callbacks */
- data_callback_t complete_cb; // XXX int (*complete_cb)(struct hc_data_s * data);
- void *complete_cb_data;
- int ret;
-} hc_data_t;
-
-/**
- * Create a structure holding the results of an hICN control request.
- * \result The newly create data structure.
- */
-hc_data_t *hc_data_create(size_t in_element_size, size_t out_element_size, data_callback_t complete_cb);
-
-/**
- * Free a structure holding the results of an hICN control request.
- * \param [in] data - The data structure to free.
- */
-void hc_data_free(hc_data_t *data);
-
-/**
- * \brief Adds many new results at the end of the data structure, eventually
- * allocating buffer space for it.
- * \param [in] data - The data structure to which to add elements.
- * \param [in] elements - The array of elements to add.
- * \param [in] count - The number of elements to add.
- * \return Error code
- *
- * NOTE: The size of the element should match the one declared at structure
- * initialization.
- */
-int hc_data_push_many(hc_data_t *data, const void *elements, size_t count);
-
-/**
- * \brief Adds a new result at the end of the data structure, eventually
- * allocating buffer space for it.
- * \param [in] data - The data structure to which to add an element.
- * \param [in] element - The element to add
- * \return Error code
- *
- * NOTE: The size of the element should match the one declared at structure
- * initialization.
- */
-int hc_data_push(hc_data_t *data, const void *element);
-
-/**
- * \brief Configure a callback (along with private data) to be called upon
- * completion of a request
- * \param [in] data - hICN control data
- * \param [in] cb - Callback function
- * \param [in] cb_data - Callback private data
- */
-int hc_data_set_callback(hc_data_t *data, data_callback_t cb, void *cb_data);
-
-/**
- * \brief Mark the data structure as complete.
- * \param [in] data - The data structure to which to add an element.
- * \return The error code resulting from callback execution if any. 0 is
- * returned if the callback executed successfully, or if no callback were
- * defined.
- */
-int hc_data_set_complete(hc_data_t *data);
-
-/**
- * \brief Reset the data structure holding control data
- * \param [in] data - hICN control data
- * \return Error code
- */
-int hc_data_reset(hc_data_t *data);
-
-/**
- * \brief Find en element in the data structure
- * \param [in] data - The data structure in which to find
- * \param [in] element - The element to find
- * \param [out] found - A pointer to the element, or NULL if not found.
- * \return Error code
- */
-#define GENERATE_FIND_HEADER(TYPE) \
-int \
-hc_ ## TYPE ## _find(hc_data_t * data, const hc_ ## TYPE ## _t * element, \
- hc_ ## TYPE ## _t **found)
-
-#define GENERATE_FIND(TYPE) \
-int \
-hc_ ## TYPE ## _find(hc_data_t * data, const hc_ ## TYPE ## _t * element, \
- hc_ ## TYPE ## _t **found) \
-{ \
- foreach_type(hc_ ## TYPE ## _t, x, data) { \
- if (hc_ ## TYPE ## _cmp(x, element) == 0) { \
- *found = x; \
- return 0; \
- } \
- }; \
- *found = NULL; /* this is optional */ \
- return 0; \
-}
-
-/******************************************************************************
- * Control socket
- ******************************************************************************/
-
-/* This should be at least equal to the maximum packet size */
-#define RECV_BUFLEN 8192
-
-typedef enum {
- HICNLIGHT,
- VPP,
- UNDEFINED
-} forwarder_t;
-
-/**
- * \brief Holds the state of an hICN control socket
- */
-typedef struct hc_sock_s hc_sock_t;
-
-/**
- * \brief Create an hICN control socket using the specified URL.
- * \param [in] url - The URL to connect to.
- * \return an hICN control socket
- */
-hc_sock_t *
-hc_sock_create_url(const char * url);
-
-/**
- * \brief Create an hICN control socket using the provided forwarder.
- * \return an hICN control socket
- */
-hc_sock_t *
-hc_sock_create_forwarder(forwarder_t forwarder);
-
-/**
- * \brief Create an hICN control socket using the default connection type.
- * \return an hICN control socket
- */
-hc_sock_t *
-hc_sock_create(void);
-
-/**
- * \brief Frees an hICN control socket
- * \param [in] s - hICN control socket
- */
-void hc_sock_free(hc_sock_t *s);
-
-/**
- * \brief Returns the next available sequence number to use for requests to the
- * API.
- * \param [in] s - hICN control socket
- */
-int hc_sock_get_next_seq(hc_sock_t *s);
-
-/**
- * \brief Sets the socket as non-blocking
- * \param [in] s - hICN control socket
- * \return Error code
- */
-int hc_sock_set_nonblocking(hc_sock_t *s);
-
-/**
- * \brief Return the file descriptor associated to the hICN contorl sock
- * \param [in] s - hICN control socket
- * \return The file descriptor (positive value), or a negative integer in case
- * of error
- */
-int hc_sock_get_fd(hc_sock_t *s);
-
-/**
- * \brief Connect the socket
- * \return Error code
- */
-int hc_sock_connect(hc_sock_t *s);
-
-/**
- * \brief Return the offset and size of available buffer space
- * \param [in] s - hICN control socket
- * \param [out] buffer - Offset in buffer
- * \param [out] size - Remaining size
- * \return Error code
- */
-int hc_sock_get_available(hc_sock_t *s, u8 **buffer, size_t *size);
-
-/**
- * \brief Write/read iexchance on the control socket (internal helper function)
- * \param [in] s - hICN control socket
- * \param [in] msg - Message to send
- * \param [in] msglen - Length of the message to send
- * \return Error code
- */
-int hc_sock_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, int seq);
-
-/**
- * \brief Helper for reading socket contents
- * \param [in] s - hICN control socket
- * \return Error code
- */
-int hc_sock_recv(hc_sock_t *s);
-
-/**
- * \brief Processing data received by socket
- * \param [in] s - hICN control socket
- * \param [in] parse - Parse function to convert remote types into lib native
- * types, or NULL not to perform any translation.
- * \return Error code
- */
-int hc_sock_process(hc_sock_t *s, hc_data_t **data);
-
-/**
- * \brief Callback used in async mode when data is available on the socket
- * \param [in] s - hICN control socket
- * \return Error code
- */
-int hc_sock_callback(hc_sock_t *s, hc_data_t **data);
-
-/**
- * \brief Reset the state of the sock (eg. to handle a reconnecton)
- * \param [in] s - hICN control socket
- * \return Error code
- */
-int hc_sock_reset(hc_sock_t *s);
+typedef struct hc_result_s hc_result_t;
/******************************************************************************
* Command-specific structures and functions
@@ -368,7 +138,8 @@ int hc_sock_reset(hc_sock_t *s);
*
* We redefine command struct:
* - for uniformization
- * - to use enum instead of type specifiers more appropriate for packet format
+ * - to use enum instead of type specifiers more appropriate for packet
+ * format
* - to use more flexible types such as for manipulating IP addresses
* - host endianness
* - more intuitive field name, ordering, consistency, and hierarchy removal
@@ -380,9 +151,9 @@ int hc_sock_reset(hc_sock_t *s);
*
* RETURN DATA FIXME
*
- * \param [out] pdata - Pointer to the structure storing the results of the call
- * (NULL if no data has been received). If the pointer is NULL, no result will
- * be stored and only the error code will be exposed to the caller. It is
+ * \param [out] pdata - Pointer to the structure storing the results of the
+ * call (NULL if no data has been received). If the pointer is NULL, no result
+ * will be stored and only the error code will be exposed to the caller. It is
* expected that the caller frees this structure using hc_data_free() after
* usage.
* \see hc_data_free.
@@ -407,179 +178,95 @@ int hc_sock_reset(hc_sock_t *s);
#define NULLTERM 1
#endif
-#define INTERFACE_LEN 16
-
#define MAXSZ_HC_NAME_ SYMBOLIC_NAME_LEN
#define MAXSZ_HC_NAME MAXSZ_HC_NAME_ + NULLTERM
#define MAXSZ_HC_ID_ 10 /* Number of digits for MAX_INT */
#define MAXSZ_HC_ID MAXSZ_HC_ID_ + NULLTERM
-#define foreach_type(TYPE, VAR, data) \
- for (TYPE *VAR = (TYPE *)data->buffer; \
- VAR < (TYPE *)(data->buffer + data->size * data->out_element_size); \
- VAR++)
-
-/**
- * New type is defined to reconciliate different enum for add and list.
- * Also, values not implemented have been removed for clarity.
- */
-#define foreach_connection_type \
- _(UNDEFINED) \
- _(TCP) \
- _(UDP) \
- _(HICN) \
- _(N)
-
-typedef enum {
-#define _(x) CONNECTION_TYPE_##x,
- foreach_connection_type
-#undef _
-} hc_connection_type_t;
-
-#define MAXSZ_HC_CONNECTION_TYPE_ 9
-#define MAXSZ_HC_CONNECTION_TYPE MAXSZ_HC_CONNECTION_TYPE_ + NULLTERM + HOTFIXMARGIN
-
-extern const char *connection_type_str[];
-
-hc_connection_type_t connection_type_from_str(const char *str);
-
-/* Same order as connection_state_t in hicn/core/connectionState.h */
-#define foreach_connection_state \
- _(UNDEFINED) \
- _(DOWN) \
- _(UP) \
- _(N)
+#if 0
+#define foreach_type(TYPE, VAR, data) \
+ for (TYPE *VAR = (TYPE *)data->buffer; \
+ VAR < (TYPE *)((data)->buffer + (data)->size * sizeof(TYPE)); VAR++)
+#endif
-typedef enum {
-#define _(x) HC_CONNECTION_STATE_##x,
- foreach_connection_state
-#undef _
-} hc_connection_state_t;
+#define INPUT_ERROR -2
+#define UNSUPPORTED_CMD_ERROR -3
-#define MAXSZ_HC_CONNECTION_STATE_ 9
-#define MAXSZ_HC_CONNECTION_STATE MAXSZ_HC_CONNECTION_STATE_ + NULLTERM
+/*----------------------------------------------------------------------------*
+ * WLDR
+ *----------------------------------------------------------------------------*/
-extern const char *connection_state_str[];
+// per connection
+int hc_wldr_set(hc_sock_t *s /* XXX */);
-typedef int (*HC_PARSE)(const u8 *, u8 *);
+/* Object */
-/*----------------------------------------------------------------------------*
- * Listeners
- *----------------------------------------------------------------------------*/
+#define MAXSZ_HC_OBJECT \
+ MAX8(MAXSZ_HC_CONNECTION, MAXSZ_HC_LISTENER, MAXSZ_HC_ROUTE, MAXSZ_HC_FACE, \
+ MAXSZ_HC_PUNTING, MAXSZ_HC_STRATEGY, MAXSZ_HC_POLICY, MAXSZ_HC_STATS)
-// FIXME the listener should not require any port for hICN...
typedef struct {
- char name[SYMBOLIC_NAME_LEN]; /* K.w */ // XXX clarify what used for
- char interface_name[INTERFACE_LEN]; /* Kr. */
- u32 id;
- hc_connection_type_t type; /* .rw */
- int family; /* .rw */
- ip_address_t local_addr; /* .rw */
- u16 local_port; /* .rw */
-} hc_listener_t;
+ hc_action_t action;
+ hc_object_type_t object_type;
+ hc_object_t object;
+} hc_command_t;
+
+// NEW API CALLS
+
+int hc_execute(hc_sock_t *s, hc_action_t action, hc_object_type_t object_type,
+ hc_object_t *object, hc_data_t **pdata);
+int hc_execute_async(hc_sock_t *s, hc_action_t action,
+ hc_object_type_t object_type, hc_object_t *object,
+ hc_result_callback_t callback, void *callback_data);
+
+int hc_object_create(hc_sock_t *s, hc_object_type_t object_type,
+ hc_object_t *object);
+int hc_object_get(hc_sock_t *s, hc_object_type_t object_type,
+ hc_object_t *object, hc_object_t **found);
+int hc_object_delete(hc_sock_t *s, hc_object_type_t object_type,
+ hc_object_t *object);
+int hc_object_list(hc_sock_t *s, hc_object_type_t object_type,
+ hc_data_t **pdata);
+
+/* Former API */
int hc_listener_create(hc_sock_t *s, hc_listener_t *listener);
/* listener_found might eventually be allocated, and needs to be freed */
-int hc_listener_get(hc_sock_t *s, hc_listener_t *listener,
- hc_listener_t **listener_found);
+int hc_listener_get(hc_sock_t *s, hc_listener_t *listener, hc_data_t **pdata);
int hc_listener_delete(hc_sock_t *s, hc_listener_t *listener);
int hc_listener_list(hc_sock_t *s, hc_data_t **pdata);
-int hc_listener_validate(const hc_listener_t *listener);
-int hc_listener_cmp(const hc_listener_t *l1, const hc_listener_t *l2);
-int hc_listener_parse(void *in, hc_listener_t *listener);
-
-#define foreach_listener(VAR, data) foreach_type(hc_listener_t, VAR, data)
-
-#define MAXSZ_HC_LISTENER_ \
- INTERFACE_LEN + SPACE + MAXSZ_URL_ + SPACE + MAXSZ_HC_CONNECTION_TYPE_
-#define MAXSZ_HC_LISTENER MAXSZ_HC_LISTENER_ + NULLTERM
-
-GENERATE_FIND_HEADER(listener);
-
-int hc_listener_snprintf(char *s, size_t size, hc_listener_t *listener);
-
-/*----------------------------------------------------------------------------*
- * Connections
- *----------------------------------------------------------------------------*/
-
-/*
- * NOTE :
- * - interface_name is mainly used to derive listeners from connections, but is
- * not itself used to create connections.
- */
-typedef struct {
- u32 id; /* Kr. */
- char name[SYMBOLIC_NAME_LEN]; /* K.w */
- char interface_name[INTERFACE_LEN]; /* Kr. */
- hc_connection_type_t type; /* .rw */
- int family; /* .rw */
- ip_address_t local_addr; /* .rw */
- u16 local_port; /* .rw */
- ip_address_t remote_addr; /* .rw */
- u16 remote_port; /* .rw */
- hc_connection_state_t admin_state; /* .rw */
-#ifdef WITH_POLICY
- uint32_t priority; /* .rw */
- policy_tags_t tags; /* .rw */
-#endif /* WITH_POLICY */
- hc_connection_state_t state; /* .r. */
-} hc_connection_t;
-
int hc_connection_create(hc_sock_t *s, hc_connection_t *connection);
-/* connection_found will be allocated, and must be freed */
+/* connection_found might eventually be allocated, and needs to be freed */
int hc_connection_get(hc_sock_t *s, hc_connection_t *connection,
- hc_connection_t **connection_found);
+ hc_data_t **pdata);
+int hc_connection_delete(hc_sock_t *s, hc_connection_t *connection);
int hc_connection_update_by_id(hc_sock_t *s, int hc_connection_id,
hc_connection_t *connection);
int hc_connection_update(hc_sock_t *s, hc_connection_t *connection_current,
hc_connection_t *connection_updated);
-int hc_connection_delete(hc_sock_t *s, hc_connection_t *connection);
-/*
-int hc_connection_remove_by_id(hc_sock_t * s, char * name);
-int hc_connection_remove_by_name(hc_sock_t * s, char * name);
-*/
int hc_connection_list(hc_sock_t *s, hc_data_t **pdata);
-int hc_connection_validate(const hc_connection_t *connection);
-int hc_connection_cmp(const hc_connection_t *c1, const hc_connection_t *c2);
-int hc_connection_parse(void *in, hc_connection_t *connection);
-
-int hc_connection_set_admin_state(hc_sock_t * s, const char * conn_id_or_name, face_state_t state);
-#ifdef WITH_POLICY
-int hc_connection_set_priority(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority);
-int hc_connection_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags);
-#endif /* WITH_POLICY */
-
-#define foreach_connection(VAR, data) foreach_type(hc_connection_t, VAR, data)
-
-#define MAXSZ_HC_CONNECTION_ \
- MAXSZ_HC_CONNECTION_STATE_ + INTERFACE_LEN + SPACE + 2 * MAXSZ_URL_ + \
- MAXSZ_HC_CONNECTION_TYPE_ + SPACES(3)
-#define MAXSZ_HC_CONNECTION MAXSZ_HC_CONNECTION_ + NULLTERM
-
-GENERATE_FIND_HEADER(connection);
-
-int hc_connection_snprintf(char *s, size_t size,
- const hc_connection_t *connection);
-
-/*----------------------------------------------------------------------------*
- * Faces
- *
- * A face is an abstraction introduced by the control library to abstract the
- * forwarder implementation details. It encompasses connections and listeners
- * and ensures the right dependencies are enforced, eg that we always have a
- * listener when a connection is created.
- *
- *----------------------------------------------------------------------------*/
-
-typedef struct {
- face_id_t id;
- char name[SYMBOLIC_NAME_LEN];
- face_t face; // or embed ?
- // face_id_t parent; /* Pointer from connection to listener */
-} hc_face_t;
+int hc_connection_set_admin_state(hc_sock_t *s, const char *conn_id_or_name,
+ face_state_t state);
+int hc_connection_set_priority(hc_sock_t *s, const char *conn_id_or_name,
+ uint32_t priority);
+int hc_connection_set_tags(hc_sock_t *s, const char *conn_id_or_name,
+ policy_tags_t tags);
+
+int hc_connection_set_admin_state(hc_sock_t *s, const char *conn_id_or_name,
+ face_state_t state);
+int hc_connection_set_priority(hc_sock_t *s, const char *conn_id_or_name,
+ uint32_t priority);
+int hc_connection_set_tags(hc_sock_t *s, const char *conn_id_or_name,
+ policy_tags_t tags);
+
+int hc_route_create(hc_sock_t *s, hc_route_t *route);
+// hc_result_t *hc_route_create_conf(hc_sock_t *s, hc_route_t *route);
+int hc_route_delete(hc_sock_t *s, hc_route_t *route);
+int hc_route_list(hc_sock_t *s, hc_data_t **pdata);
+int hc_route_list_async(hc_sock_t *s);
/**
* \brief Create a face
@@ -590,73 +277,37 @@ typedef struct {
* The face parameters will be updated with the face ID.
*/
int hc_face_create(hc_sock_t *s, hc_face_t *face);
-int hc_face_get(hc_sock_t *s, hc_face_t *face, hc_face_t **face_found);
-int hc_face_delete(hc_sock_t *s, hc_face_t *face);
+int hc_face_get(hc_sock_t *s, hc_face_t *face, hc_data_t **pdata);
+int hc_face_delete(hc_sock_t *s,
+ hc_face_t *face); //, uint8_t delete_listener);
int hc_face_list(hc_sock_t *s, hc_data_t **pdata);
-int hc_face_list_async(hc_sock_t *s); //, hc_data_t ** pdata);
-
-int hc_face_set_admin_state(hc_sock_t * s, const char * conn_id_or_name, face_state_t state);
-#ifdef WITH_POLICY
-int hc_face_set_priority(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority);
-int hc_face_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags);
-#endif /* WITH_POLICY */
-
-#define foreach_face(VAR, data) foreach_type(hc_face_t, VAR, data)
-
-#define MAX_FACE_ID 255
-#define MAXSZ_FACE_ID_ 3
-#define MAXSZ_FACE_ID MAXSZ_FACE_ID_ + NULLTERM
-#define MAXSZ_FACE_NAME_ SYMBOLIC_NAME_LEN
-#define MAXSZ_FACE_NAME MAXSZ_FACE_NAME_ + NULLTERM
-
-#define MAXSZ_HC_FACE_ MAXSZ_FACE_ID_ + MAXSZ_FACE_NAME_ + MAXSZ_FACE_ + 5 + HOTFIXMARGIN
-#define MAXSZ_HC_FACE MAXSZ_HC_FACE_ + NULLTERM
-
-int hc_face_snprintf(char *s, size_t size, hc_face_t *face);
-
-/*----------------------------------------------------------------------------*
- * Routes
- *----------------------------------------------------------------------------*/
-
-typedef struct {
- face_id_t face_id; /* Kr. */
- int family; /* Krw */
- ip_address_t remote_addr; /* krw */
- u8 len; /* krw */
- u16 cost; /* .rw */
- hc_face_t face;
-} hc_route_t;
-
-int hc_route_parse(void *in, hc_route_t *route);
-
-int hc_route_create(hc_sock_t * s, hc_route_t * route);
-int hc_route_delete(hc_sock_t * s, hc_route_t * route);
-int hc_route_list(hc_sock_t * s, hc_data_t ** pdata);
-int hc_route_list_async(hc_sock_t * s);
+int hc_face_list_async(hc_sock_t *s);
-#define foreach_route(VAR, data) foreach_type(hc_route_t, VAR, data)
+int hc_face_set_admin_state(hc_sock_t *s, const char *conn_id_or_name,
+ face_state_t state);
+int hc_face_set_priority(hc_sock_t *s, const char *conn_id_or_name,
+ uint32_t priority);
+int hc_face_set_tags(hc_sock_t *s, const char *conn_id_or_name,
+ policy_tags_t tags);
-#define MAX_COST 65535
-#define MAXSZ_COST 5
-#define MAX_LEN 255
-#define MAXSZ_LEN 3
-
-#define MAXSZ_HC_ROUTE_ \
- MAXSZ_FACE_ID + 1 + MAXSZ_COST + 1 + MAXSZ_IP_ADDRESS + 1 + MAXSZ_LEN
-#define MAXSZ_HC_ROUTE MAXSZ_HC_ROUTE_ + NULLTERM
+int hc_strategy_list(hc_sock_t *s, hc_data_t **data);
+int hc_strategy_set(hc_sock_t *s, hc_strategy_t *strategy);
+int hc_strategy_add_local_prefix(hc_sock_t *s, hc_strategy_t *strategy);
-int hc_route_snprintf(char *s, size_t size, hc_route_t *route);
+int hc_cache_set_store(hc_sock_t *s, hc_cache_t *cache);
+int hc_cache_set_serve(hc_sock_t *s, hc_cache_t *cache);
+int hc_cache_clear(hc_sock_t *s, hc_cache_t *cache);
+int hc_cache_list(hc_sock_t *s, hc_data_t **pdata);
-/*----------------------------------------------------------------------------*
- * Punting
- *----------------------------------------------------------------------------*/
+int hc_mapme_set(hc_sock_t *s, hc_mapme_t *mapme);
+int hc_mapme_set_discovery(hc_sock_t *s, hc_mapme_t *mapme);
+int hc_mapme_set_timescale(hc_sock_t *s, hc_mapme_t *mapme);
+int hc_mapme_set_retx(hc_sock_t *s, hc_mapme_t *mapme);
+int hc_mapme_create(hc_sock_t *s, hc_mapme_t *mapme);
-typedef struct {
- face_id_t face_id; /* Kr. */ // XXX listener id, could be NULL for all ?
- int family; /* Krw */
- ip_address_t prefix; /* krw */
- u8 prefix_len; /* krw */
-} hc_punting_t;
+int hc_policy_create(hc_sock_t *s, hc_policy_t *policy);
+int hc_policy_delete(hc_sock_t *s, hc_policy_t *policy);
+int hc_policy_list(hc_sock_t *s, hc_data_t **pdata);
int hc_punting_create(hc_sock_t *s, hc_punting_t *punting);
int hc_punting_get(hc_sock_t *s, hc_punting_t *punting,
@@ -664,91 +315,12 @@ int hc_punting_get(hc_sock_t *s, hc_punting_t *punting,
int hc_punting_delete(hc_sock_t *s, hc_punting_t *punting);
int hc_punting_list(hc_sock_t *s, hc_data_t **pdata);
-int hc_punting_validate(const hc_punting_t *punting);
-int hc_punting_cmp(const hc_punting_t *c1, const hc_punting_t *c2);
-int hc_punting_parse(void *in, hc_punting_t *punting);
-
-#define foreach_punting(VAR, data) foreach_type(hc_punting_t, VAR, data)
-
-#define MAXSZ_HC_PUNTING_ 0
-#define MAXSZ_HC_PUNTING MAXSZ_HC_PUNTING_ + NULLTERM
-
-GENERATE_FIND_HEADER(punting);
-
-int hc_punting_snprintf(char *s, size_t size, hc_punting_t *punting);
-
-/*----------------------------------------------------------------------------*
- * Cache
- *----------------------------------------------------------------------------*/
-
-int hc_cache_set_store(hc_sock_t *s, int enabled);
-int hc_cache_set_serve(hc_sock_t *s, int enabled);
-
-/*----------------------------------------------------------------------------*
- * Strategy
- *----------------------------------------------------------------------------*/
-
-#define MAXSZ_STRATEGY_NAME 255
-
-typedef struct {
- char name[MAXSZ_STRATEGY_NAME];
-} hc_strategy_t;
-
-int hc_strategy_list(hc_sock_t *s, hc_data_t **data);
-
-#define foreach_strategy(VAR, data) foreach_type(hc_strategy_t, VAR, data)
-
-#define MAXSZ_HC_STRATEGY_ MAXSZ_STRATEGY_NAME
-#define MAXSZ_HC_STRATEGY MAXSZ_HC_STRATEGY_ + NULLTERM
-
-int hc_strategy_snprintf(char *s, size_t size, hc_strategy_t *strategy);
-
-// per prefix
-int hc_strategy_set(hc_sock_t *s /* XXX */);
-
-/*----------------------------------------------------------------------------*
- * WLDR
- *----------------------------------------------------------------------------*/
-
-// per connection
-int hc_wldr_set(hc_sock_t *s /* XXX */);
-
-/*----------------------------------------------------------------------------*
- * MAP-Me
- *----------------------------------------------------------------------------*/
-
-int hc_mapme_set(hc_sock_t *s, int enabled);
-int hc_mapme_set_discovery(hc_sock_t *s, int enabled);
-int hc_mapme_set_timescale(hc_sock_t *s, double timescale);
-int hc_mapme_set_retx(hc_sock_t *s, double timescale);
-
-/*----------------------------------------------------------------------------*
- * Policies
- *----------------------------------------------------------------------------*/
-
-#ifdef WITH_POLICY
-
-typedef struct {
- int family; /* Krw */
- ip_address_t remote_addr; /* krw */
- u8 len; /* krw */
- hicn_policy_t policy; /* .rw */
-} hc_policy_t;
-
-int hc_policy_parse(void *in, hc_policy_t *policy);
-
-int hc_policy_create(hc_sock_t *s, hc_policy_t *policy);
-int hc_policy_delete(hc_sock_t *s, hc_policy_t *policy);
-int hc_policy_list(hc_sock_t *s, hc_data_t **pdata);
-
-#define foreach_policy(VAR, data) foreach_type(hc_policy_t, VAR, data)
-
-/* TODO */
-#define MAXSZ_HC_POLICY_ 0
-#define MAXSZ_HC_POLICY MAXSZ_HC_POLICY_ + NULLTERM
-
-int hc_policy_snprintf(char *s, size_t size, hc_policy_t *policy);
+int hc_subscription_create(hc_sock_t *s, hc_subscription_t *subscription);
+int hc_subscription_delete(hc_sock_t *s, hc_subscription_t *subscription);
-#endif /* WITH_POLICY */
+int hc_stats_list(hc_sock_t *s, hc_data_t **pdata);
+int hc_stats_snprintf(char *s, size_t size, const hc_stats_t *stats);
+int hc_face_stats_list(hc_sock_t *s, hc_data_t **pdata);
+int hc_face_stats_snprintf(char *s, size_t size, const hc_face_stats_t *stats);
#endif /* HICNTRL_API */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/callback.h b/ctrl/libhicnctrl/includes/hicn/ctrl/callback.h
new file mode 100644
index 000000000..5b7f424d6
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/callback.h
@@ -0,0 +1,13 @@
+#ifndef HICNCTRL_CALLBACK_H
+#define HICNCTRL_CALLBACK_H
+
+#include <stdbool.h>
+
+#include <hicn/ctrl/data.h>
+
+typedef int (*hc_enable_callback_t)(bool enable);
+typedef void (*hc_state_callback_t)(bool enable, void *user_data);
+typedef void (*hc_result_callback_t)(hc_data_t *data, void *user_data);
+typedef void (*hc_notification_callback_t)(hc_data_t *data, void *user_data);
+
+#endif /* HICNCTRL_CALLBACK_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/command.h b/ctrl/libhicnctrl/includes/hicn/ctrl/command.h
new file mode 100644
index 000000000..1824d14c2
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/command.h
@@ -0,0 +1,191 @@
+#ifndef HICNLIGHT_CONFIG_COMMAND
+#define HICNLIGHT_CONFIG_COMMAND
+
+/**
+ * @file command.h
+ * @brief Commands.
+ */
+
+#include <stddef.h> // offsetof
+#include <hicn/util/ip_address.h>
+
+#include <hicn/ctrl/api.h>
+
+/* Update sscanf accordingly in parse_cmd.c */
+#define MAX_PARAMETERS 10
+#define MAX_SCANF_PARAM_LEN 100
+
+typedef int (*parser_hook_t)(void *arg);
+
+typedef enum {
+ TYPENAME_UNDEFINED,
+ TYPENAME_INT,
+ TYPENAME_UINT,
+ TYPENAME_INT16,
+ TYPENAME_UINT16,
+ TYPENAME_STR,
+ TYPENAME_SYMBOLIC_OR_ID,
+ TYPENAME_INTERFACE_NAME,
+ TYPENAME_IP_ADDRESS,
+ TYPENAME_IP_PREFIX,
+ TYPENAME_ON_OFF,
+ TYPENAME_ENUM,
+ TYPENAME_POLICY_STATE,
+} parser_typename_t;
+
+typedef struct {
+ parser_typename_t name;
+ union {
+ struct {
+ size_t max_size;
+ } str;
+ struct {
+ int min;
+ int max;
+ } integer;
+ struct {
+ int (*from_str)(const char *str);
+ } enum_;
+ struct {
+ policy_tag_t tag;
+ } policy_state;
+ };
+} parser_type_t;
+
+typedef struct {
+ const char *name;
+ const char *help;
+ parser_type_t type;
+ size_t offset;
+ /*
+ * quick hack to let the functions update two or more parameters, like for
+ * IP_ADDRESS or IP_PREFIX types
+ */
+ size_t offset2;
+ size_t offset3;
+} command_parameter_t;
+
+typedef struct {
+ hc_action_t action;
+ hc_object_type_t object_type;
+ unsigned nparams;
+ command_parameter_t parameters[MAX_PARAMETERS];
+ parser_hook_t post_hook;
+} command_parser_t;
+
+/*
+ * NOTE: we now use strings everywhere to parse in the same way parameters
+ * coming from the commandline through getopt (strings), and those coming from
+ * sscanf (used to be variables, now all strings also.
+ */
+
+#define TYPE_STRN(N) \
+ (parser_type_t) { \
+ .name = TYPENAME_STR, \
+ .str = { \
+ .max_size = N, \
+ }, \
+ }
+
+#define TYPE_INT(MIN, MAX) \
+ (parser_type_t) { \
+ .name = TYPENAME_INT, \
+ .integer = { \
+ .min = (MIN), \
+ .max = (MAX), \
+ }, \
+ }
+
+#define TYPE_UINT(MIN, MAX) \
+ (parser_type_t) { \
+ .name = TYPENAME_UINT, \
+ .integer = { \
+ .min = (MIN), \
+ .max = (MAX), \
+ }, \
+ }
+
+#define TYPE_INT16(MIN, MAX) \
+ (parser_type_t) { \
+ .name = TYPENAME_INT16, \
+ .integer = { \
+ .min = (MIN), \
+ .max = (MAX), \
+ }, \
+ }
+
+#define TYPE_UINT16(MIN, MAX) \
+ (parser_type_t) { \
+ .name = TYPENAME_UINT16, \
+ .integer = { \
+ .min = (MIN), \
+ .max = (MAX), \
+ }, \
+ }
+
+#define TYPE_SYMBOLIC_OR_ID TYPE_STRN(SYMBOLIC_NAME_LEN)
+
+#define TYPE_INTERFACE_NAME TYPE_STRN(INTERFACE_LEN)
+
+#define TYPE_IP_ADDRESS \
+ (parser_type_t) { .name = TYPENAME_IP_ADDRESS, }
+
+#define TYPE_IP_PREFIX \
+ (parser_type_t) { .name = TYPENAME_IP_PREFIX, }
+
+#define TYPE_ON_OFF \
+ (parser_type_t) { .name = TYPENAME_ON_OFF, }
+
+#define TYPE_ENUM(x) \
+ (parser_type_t) { \
+ .name = TYPENAME_ENUM, \
+ .enum_ = { \
+ .from_str = (int (*)(const char *))x##_from_str, \
+ }, \
+ }
+/* We need to allocate room for the intermediate string */
+
+#define TYPE_POLICY_STATE(TAG) \
+ (parser_type_t) { \
+ .name = TYPENAME_POLICY_STATE, \
+ .policy_state = { \
+ .tag = TAG, \
+ }, \
+ }
+/* We need to allocate room for the intermediate string */
+
+/**
+ * \brief Register a protocol
+ * \param protocol Pointer to a protocol_t structure describing the protocol to
+ * register \return None
+ */
+
+void command_register(const command_parser_t *command);
+
+/**
+ * \brief Search a registered protocol in the library according to its name
+ * \param[in] action The action of the command.
+ * \param[in] object The object of the command.
+ * \param[in] nparams The number of parameters expected in the command.
+ * \return A pointer to the corresponding command if any, NULL othewise
+ */
+const command_parser_t *command_search(hc_action_t action,
+ hc_object_type_t object,
+ unsigned nparams);
+
+/**
+ * @brief List the commands associated with the specified object and/or action.
+ * Use OBJECT_UNDEFINED and ACTION_UNDEFINED to list all the available objects.
+ * Use ACTION_UNDEFINED to list all the actions associated to the specified
+ * object.
+ *
+ * @param object The action of the command
+ * @param action The object of the command
+ */
+void command_list(hc_object_type_t object, hc_action_t action);
+
+#define COMMAND_REGISTER(MOD) \
+ static void __init_##MOD(void) __attribute__((constructor)); \
+ static void __init_##MOD(void) { command_register(&MOD); }
+
+#endif /* HICNLIGHT_CONFIG_COMMAND */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/commands.h b/ctrl/libhicnctrl/includes/hicn/ctrl/commands.h
deleted file mode 100644
index 3758f0f41..000000000
--- a/ctrl/libhicnctrl/includes/hicn/ctrl/commands.h
+++ /dev/null
@@ -1,434 +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.
- */
-
-/*
- * @file commands.h
- * @brief All hicn-light commands: 14 in total.
- *
- * Header and payload in binary format.
- */
-
-#ifndef commands_h
-#define commands_h
-
-#ifndef _WIN32
-#include <netinet/in.h>
-#include <sys/socket.h>
-#endif
-
-#include <stdint.h>
-#include <stdlib.h>
-
-#include <hicn/util/ip_address.h>
-#ifdef WITH_POLICY
-#include <hicn/policy.h>
-#endif /* WITH_POLICY */
-
-#define SYMBOLIC_NAME_LEN 16
-#define MAX_FWD_STRATEGY_RELATED_PREFIXES 10
-
-typedef struct in6_addr ipv6_addr_t;
-typedef uint32_t ipv4_addr_t;
-
-typedef enum {
- REQUEST_LIGHT = 0xc0, // this is a command
- RESPONSE_LIGHT,
- ACK_LIGHT,
- NACK_LIGHT,
- LAST_MSG_TYPE_VALUE
-} message_type;
-
-typedef enum {
- ADD_LISTENER = 0,
- ADD_CONNECTION,
- LIST_CONNECTIONS,
- ADD_ROUTE,
- LIST_ROUTES,
- REMOVE_CONNECTION,
- REMOVE_LISTENER,
- REMOVE_ROUTE,
- CACHE_STORE,
- CACHE_SERVE,
- CACHE_CLEAR,
- SET_STRATEGY,
- SET_WLDR,
- ADD_PUNTING,
- LIST_LISTENERS,
- MAPME_ENABLE,
- MAPME_DISCOVERY,
- MAPME_TIMESCALE,
- MAPME_RETX,
- MAPME_SEND_UPDATE,
- CONNECTION_SET_ADMIN_STATE,
-#ifdef WITH_POLICY
- ADD_POLICY,
- LIST_POLICIES,
- REMOVE_POLICY,
- UPDATE_CONNECTION,
- CONNECTION_SET_PRIORITY,
- CONNECTION_SET_TAGS,
-#endif /* WITH_POLICY */
- LAST_COMMAND_VALUE
-} command_id;
-
-typedef enum {
- ADDR_INET = 1,
- ADDR_INET6,
- ADDR_LINK,
- ADDR_IFACE,
- ADDR_UNIX /* PF_UNIX */
-} address_type;
-
-typedef enum {
- UDP_CONN,
- TCP_CONN,
- GRE_CONN, // not implemented
- HICN_CONN
-} connection_type;
-
-typedef enum { ACTIVATE_ON, ACTIVATE_OFF } activate_type;
-
-//========== HEADER ==========
-
-typedef struct {
- uint8_t messageType;
- uint8_t commandID;
- uint16_t length; // tells the number of structures in the payload
- uint32_t seqNum;
-} header_control_message;
-// for the moment has to be at least 8 bytes
-
-// SIZE=8
-
-//========== [00] ADD LISTENER ==========
-
-typedef enum { ETHER_MODE, IP_MODE, HICN_MODE } listener_mode;
-
-typedef struct {
- char symbolic[SYMBOLIC_NAME_LEN];
- char interfaceName[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint16_t port;
- // uint16_t etherType;
- uint8_t addressType;
- uint8_t listenerMode;
- uint8_t connectionType;
-} add_listener_command;
-
-// SIZE=56
-
-//========== [01] ADD CONNECTION ==========
-
-typedef struct {
- char symbolic[SYMBOLIC_NAME_LEN];
- //char interfaceName[SYMBOLIC_NAME_LEN];
- ip_address_t remoteIp;
- ip_address_t localIp;
- uint16_t remotePort;
- uint16_t localPort;
- uint8_t ipType;
- uint8_t connectionType;
- uint8_t admin_state;
-#ifdef WITH_POLICY
- uint32_t priority;
- policy_tags_t tags;
-#endif /* WITH_POLICY */
-} add_connection_command;
-
-// SIZE=56
-
-//========== [02] LIST CONNECTIONS ==========
-
-typedef enum {
- CONN_GRE,
- CONN_TCP,
- CONN_UDP,
- CONN_MULTICAST,
- CONN_L2,
- CONN_HICN
-} list_connections_type;
-
-typedef enum {
- IFACE_UP = 0,
- IFACE_DOWN = 1,
- IFACE_UNKNOWN = 2 // not used actually
-} connection_state;
-
-typedef struct {
- add_connection_command connectionData;
- uint32_t connid;
- uint8_t state;
- char interfaceName[SYMBOLIC_NAME_LEN];
- char connectionName[SYMBOLIC_NAME_LEN];
-} list_connections_command;
-
-// SIZE=80
-
-//========== [03] ADD ROUTE ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint16_t cost;
- uint8_t addressType;
- uint8_t len;
-} add_route_command;
-
-// SIZE=36
-
-//========== [04] LIST ROUTE ==========
-
-typedef struct {
- ip_address_t address;
- uint32_t connid;
- uint16_t cost;
- uint8_t addressType;
- uint8_t len;
-} list_routes_command;
-
-// SIZE=24
-
-//========== [05] REMOVE CONNECTION ==========
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
-} remove_connection_command;
-
-//========== [06] REMOVE LISTENER ==========
-typedef struct {
- char symbolicOrListenerid[SYMBOLIC_NAME_LEN];
-} remove_listener_command;
-
-// SIZE=16
-
-//========== [07] REMOVE ROUTE ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} remove_route_command;
-
-// SIZE=36
-
-//========== [08] CACHE STORE ==========
-
-typedef struct {
- uint8_t activate;
-} cache_store_command;
-
-// SIZE=1
-
-//========== [09] CACHE SERVE ==========
-
-typedef struct {
- uint8_t activate;
-} cache_serve_command;
-
-// SIZE=1
-
-//========== [10] SET STRATEGY ==========
-
-typedef enum {
- SET_STRATEGY_LOADBALANCER,
- SET_STRATEGY_RANDOM,
- SET_STRATEGY_LOW_LATENCY,
- LAST_STRATEGY_VALUE
-} strategy_type;
-
-typedef struct {
- ip_address_t address;
- uint8_t strategyType;
- uint8_t addressType;
- uint8_t len;
- uint8_t related_prefixes;
- ip_address_t addresses[MAX_FWD_STRATEGY_RELATED_PREFIXES];
- uint8_t lens[MAX_FWD_STRATEGY_RELATED_PREFIXES];
- uint8_t addresses_type[MAX_FWD_STRATEGY_RELATED_PREFIXES];
-} set_strategy_command;
-
-// SIZE=208
-
-//========== [11] SET WLDR ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint8_t activate;
-} set_wldr_command;
-
-// SIZE=17
-
-//========== [12] ADD PUNTING ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} add_punting_command;
-
-// SIZE=36
-
-//========== [13] LIST LISTENER ==========
-
-typedef struct {
- ip_address_t address;
- char listenerName[SYMBOLIC_NAME_LEN];
- char interfaceName[SYMBOLIC_NAME_LEN];
- uint32_t connid;
- uint16_t port;
- uint8_t addressType;
- uint8_t encapType;
-} list_listeners_command;
-
-// SIZE=56
-
-//========== [14] MAPME ==========
-
-// (enable/discovery/timescale/retx)
-
-typedef struct {
- uint8_t activate;
-} mapme_activator_command;
-
-// SIZE=1
-
-typedef struct {
- uint32_t timePeriod;
-} mapme_timing_command;
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} mapme_send_update_command;
-
-// SIZE=1
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint8_t admin_state;
- uint8_t pad8[3];
-} connection_set_admin_state_command;
-
-#ifdef WITH_POLICY
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
- hicn_policy_t policy;
-} add_policy_command;
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
- hicn_policy_t policy;
-} list_policies_command;
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} remove_policy_command;
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint8_t admin_state;
- uint32_t priority;
- policy_tags_t tags;
-} update_connection_command;
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint32_t priority;
-} connection_set_priority_command;
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- policy_tags_t tags;
-} connection_set_tags_command;
-
-#endif /* WITH_POLICY */
-
-//===== size of commands ======
-// REMINDER: when a new_command is added, the following switch has to be
-// updated.
-static inline int payloadLengthDaemon(command_id id) {
- switch (id) {
- case ADD_LISTENER:
- return sizeof(add_listener_command);
- case ADD_CONNECTION:
- return sizeof(add_connection_command);
- case LIST_CONNECTIONS:
- return 0; // list connections: payload always 0
- case ADD_ROUTE:
- return sizeof(add_route_command);
- case LIST_ROUTES:
- return 0; // list routes: payload always 0
- case REMOVE_CONNECTION:
- return sizeof(remove_connection_command);
- case REMOVE_LISTENER:
- return sizeof(remove_listener_command);
- case REMOVE_ROUTE:
- return sizeof(remove_route_command);
- case CACHE_STORE:
- return sizeof(cache_store_command);
- case CACHE_SERVE:
- return sizeof(cache_serve_command);
- case CACHE_CLEAR:
- return 0; // cache clear
- case SET_STRATEGY:
- return sizeof(set_strategy_command);
- case SET_WLDR:
- return sizeof(set_wldr_command);
- case ADD_PUNTING:
- return sizeof(add_punting_command);
- case LIST_LISTENERS:
- return 0; // list listeners: payload always 0
- case MAPME_ENABLE:
- return sizeof(mapme_activator_command);
- case MAPME_DISCOVERY:
- return sizeof(mapme_activator_command);
- case MAPME_TIMESCALE:
- return sizeof(mapme_timing_command);
- case MAPME_RETX:
- return sizeof(mapme_timing_command);
- case MAPME_SEND_UPDATE:
- return sizeof(mapme_send_update_command);
- case CONNECTION_SET_ADMIN_STATE:
- return sizeof(connection_set_admin_state_command);
-#ifdef WITH_POLICY
- case ADD_POLICY:
- return sizeof(add_policy_command);
- case LIST_POLICIES:
- return 0; // list policies: payload always 0
- case REMOVE_POLICY:
- return sizeof(remove_policy_command);
- case UPDATE_CONNECTION:
- return sizeof(update_connection_command);
- case CONNECTION_SET_PRIORITY:
- return sizeof(connection_set_priority_command);
- case CONNECTION_SET_TAGS:
- return sizeof(connection_set_tags_command);
-#endif /* WITH_POLICY */
- case LAST_COMMAND_VALUE:
- return 0;
- default:
- return 0;
- }
-}
-#endif
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/data.h b/ctrl/libhicnctrl/includes/hicn/ctrl/data.h
new file mode 100644
index 000000000..d2696db1c
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/data.h
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file data.h
+ * \brief Request result data.
+ */
+
+#ifndef HICNCTRL_DATA_H
+#define HICNCTRL_DATA_H
+
+#include <stdbool.h>
+#include <stddef.h> // size_t
+#include <stdint.h> // uint*_t
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <hicn/ctrl/object_type.h>
+#include <hicn/ctrl/object.h>
+
+/**
+ * \brief Holds the results of an hICN control request
+ */
+typedef struct hc_data_s hc_data_t;
+
+/**
+ * Create a structure holding the results of an hICN control request.
+ * \result The newly create data structure.
+ */
+hc_data_t *hc_data_create(hc_object_type_t object_type);
+
+/**
+ * Free a structure holding the results of an hICN control request.
+ * \param [in] data - The data structure to free.
+ */
+void hc_data_free(hc_data_t *data);
+
+/*
+ * This function can fail if the current data size is bigger than the requested
+ * maximum size
+ */
+int hc_data_set_max_size(hc_data_t *data, size_t max_size);
+
+const uint8_t *hc_data_get_buffer(hc_data_t *data);
+const uint8_t *hc_data_get_free(hc_data_t *data);
+void hc_data_inc_size(hc_data_t *data);
+
+hc_object_type_t hc_data_get_object_type(const hc_data_t *data);
+
+void hc_data_set_object_type(hc_data_t *data, hc_object_type_t object_type);
+
+ssize_t hc_data_get_size(const hc_data_t *data);
+
+/*
+ * This is used to perform manual allocation once after initialization is the
+ * size of the data to store is known in advance. This does not prevent future
+ * reallocations (in the limit though of the value in max_size, if applicable).
+ */
+int hc_data_allocate(hc_data_t *data, size_t size);
+
+int hc_data_clear(hc_data_t *data);
+
+#if 0
+int hc_data_ensure_available(hc_data_t *data, size_t count);
+#endif
+
+/**
+ * \brief Adds many new results at the end of the data structure, eventually
+ * allocating buffer space for it.
+ * \param [in] data - The data structure to which to add elements.
+ * \param [in] elements - The array of elements to add.
+ * \param [in] count - The number of elements to add.
+ * \return Error code
+ *
+ * NOTE: The size of the element should match the one declared at structure
+ * initialization.
+ */
+int hc_data_push_many(hc_data_t *data, const void *elements, size_t count);
+
+/**
+ * \brief Adds a new result at the end of the data structure, eventually
+ * allocating buffer space for it.
+ * \param [in] data - The data structure to which to add an element.
+ * \param [in] element - The element to add
+ * \return Error code
+ *
+ * NOTE: The size of the element should match the one declared at structure
+ * initialization.
+ */
+int hc_data_push(hc_data_t *data, const void *element);
+
+#if 0
+uint8_t *hc_data_get_next(hc_data_t *data);
+
+/**
+ * \brief Configure a callback (along with private data) to be called upon
+ * completion of a request
+ * \param [in] data - hICN control data
+ * \param [in] cb - Callback function
+ * \param [in] cb_data - Callback private data
+ */
+int hc_data_set_callback(hc_data_t *data, data_callback_t cb, void *cb_data);
+
+void hc_data_set_size(hc_data_t *data, int size);
+#endif
+
+void hc_data_set_complete(hc_data_t *data);
+bool hc_data_is_complete(const hc_data_t *data);
+
+void hc_data_set_error(hc_data_t *data);
+
+bool hc_data_get_result(hc_data_t *data);
+
+#if 0
+/**
+ * \brief Reset the data structure holding control data
+ * \param [in] data - hICN control data
+ * \return Error code
+ */
+int hc_data_reset(hc_data_t *data);
+#endif
+
+#define VAR(x) __##x
+#define hc_data_foreach(DATA, OBJECT, BODY) \
+ do { \
+ hc_object_t *OBJECT; \
+ size_t VAR(size) = hc_object_size(hc_data_get_object_type(DATA)); \
+ for (unsigned VAR(i) = 0; VAR(i) < hc_data_get_size(DATA); VAR(i)++) { \
+ OBJECT = (hc_object_t *)(hc_data_get_buffer(DATA) + VAR(i) * VAR(size)); \
+ BODY \
+ } \
+ } while (0)
+
+hc_object_t *hc_data_find(hc_data_t *data, hc_object_t *object);
+
+const hc_object_t *hc_data_get_object(const hc_data_t *data, off_t pos);
+
+#endif /* HICNCTRL_DATA_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/face.h b/ctrl/libhicnctrl/includes/hicn/ctrl/face.h
deleted file mode 100644
index 49a6a783c..000000000
--- a/ctrl/libhicnctrl/includes/hicn/ctrl/face.h
+++ /dev/null
@@ -1,206 +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.
- */
-
-/**
- * \file face.h
- * \brief Face abstraction
- */
-#ifndef HICN_FACE_H
-#define HICN_FACE_H
-
-#ifndef SPACES
-#define SPACES(x) x
-#endif
-#ifndef SPACE
-#define SPACE 1
-#endif
-#ifndef NULLTERM
-#define NULLTERM 1
-#endif
-
-#include <hicn/policy.h>
-
-#include <hicn/util/ip_address.h>
-
-//typedef unsigned int hash_t; //incompatible with vpp
-
-/* Netdevice type */
-
-#include <net/if.h> // IFNAMSIZ
-
-#define foreach_netdevice_type \
- _(UNDEFINED) \
- _(LOOPBACK) \
- _(WIRED) \
- _(WIFI) \
- _(CELLULAR) \
- _(VPN) \
- _(N)
-
-#define MAXSZ_NETDEVICE_TYPE_ 9
-#define MAXSZ_NETDEVICE_TYPE MAXSZ_NETDEVICE_TYPE_ + NULLTERM
-
-typedef enum {
-#define _(x) NETDEVICE_TYPE_ ## x,
-foreach_netdevice_type
-#undef _
-} netdevice_type_t;
-
-extern const char * netdevice_type_str[];
-
-
-/* Netdevice */
-
-/**
- * \brief Netdevice type
- *
- * NOTE
- * - This struct cannot be made opaque as it is currently part of face_t
- * - We recommand using the API as to keep redundant attributes consistent
- */
-typedef struct {
- u32 index;
- char name[IFNAMSIZ];
-} netdevice_t;
-
-#define NETDEVICE_EMPTY (netdevice_t) { \
- .index = 0, \
- .name = {0}, \
-}
-
-netdevice_t * netdevice_create_from_index(u32 index);
-netdevice_t * netdevice_create_from_name(const char * name);
-#define netdevice_initialize_from_index netdevice_set_index
-#define netdevice_initialize_from_name netdevice_set_name
-void netdevice_free(netdevice_t * netdevice);
-int netdevice_get_index(const netdevice_t * netdevice, u32 * index);
-int netdevice_set_index(netdevice_t * netdevice, u32 index);
-int netdevice_get_name(const netdevice_t * netdevice, const char ** name);
-int netdevice_set_name(netdevice_t * netdevice, const char * name);
-int netdevice_update_index(netdevice_t * netdevice);
-int netdevice_update_name(netdevice_t * netdevice);
-int netdevice_cmp(const netdevice_t * nd1, const netdevice_t * nd2);
-
-#define NETDEVICE_UNDEFINED_INDEX 0
-
-/* Face state */
-
-#define foreach_face_state \
- _(UNDEFINED) \
- _(DOWN) \
- _(UP) \
- _(N)
-
-
-#define MAXSZ_FACE_STATE_ 9
-#define MAXSZ_FACE_STATE MAXSZ_FACE_STATE_ + 1
-
-typedef enum {
-#define _(x) FACE_STATE_ ## x,
-foreach_face_state
-#undef _
-} face_state_t;
-
-extern const char * face_state_str[];
-
-
-/* Face type */
-
-#define foreach_face_type \
- _(UNDEFINED) \
- _(HICN) \
- _(HICN_LISTENER) \
- _(TCP) \
- _(TCP_LISTENER) \
- _(UDP) \
- _(UDP_LISTENER) \
- _(N)
-
-#define MAXSZ_FACE_TYPE_ 13
-#define MAXSZ_FACE_TYPE MAXSZ_FACE_TYPE_ + 1
-
-typedef enum {
-#define _(x) FACE_TYPE_ ## x,
-foreach_face_type
-#undef _
-} face_type_t;
-
-extern const char * face_type_str[];
-
-#ifdef WITH_POLICY
-#define MAXSZ_FACE_ MAXSZ_FACE_TYPE_ + 2 * MAXSZ_URL_ + 2 * MAXSZ_FACE_STATE_ + MAXSZ_POLICY_TAGS_ + 7
-#else
-#define MAXSZ_FACE_ MAXSZ_FACE_TYPE_ + 2 * MAXSZ_URL_ + 2 * MAXSZ_FACE_STATE_ + 4
-#endif /* WITH_POLICY */
-#define MAXSZ_FACE MAXSZ_FACE_ + 1
-
-/* Face */
-
-typedef u32 face_id_t;
-
-typedef struct {
- face_type_t type;
- face_state_t admin_state;
- face_state_t state;
-#ifdef WITH_POLICY
- uint32_t priority;
- policy_tags_t tags; /**< \see policy_tag_t */
-#endif /* WITH_POLICY */
-
- /*
- * Depending on the face type, some of the following fields will be unused
- */
- netdevice_t netdevice;
- int family; /* To access family independently of face type */
- ip_address_t local_addr;
- ip_address_t remote_addr;
- u16 local_port;
- u16 remote_port;
-} face_t;
-
-int face_initialize(face_t * face);
-int face_initialize_udp(face_t * face, const char * interface_name,
- const ip_address_t * local_addr, u16 local_port,
- const ip_address_t * remote_addr, u16 remote_port,
- int family);
-int face_initialize_udp_sa(face_t * face,
- const char * interface_name,
- const struct sockaddr * local_addr, const struct sockaddr * remote_addr);
-
-face_t * face_create();
-face_t * face_create_udp(const char * interface_name,
- const ip_address_t * local_addr, u16 local_port,
- const ip_address_t * remote_addr, u16 remote_port, int family);
-face_t * face_create_udp_sa(const char * interface_name,
- const struct sockaddr * local_addr,
- const struct sockaddr * remote_addr);
-
-int face_finalize(face_t * face);
-
-void face_free(face_t * face);
-
-typedef int (*face_cmp_t)(const face_t * f1, const face_t * f2);
-
-int face_cmp(const face_t * f1, const face_t * f2);
-unsigned int face_hash(const face_t * face);
-
-size_t
-face_snprintf(char * s, size_t size, const face_t * face);
-
-policy_tags_t face_get_tags(const face_t * face);
-int face_set_tags(face_t * face, policy_tags_t tags);
-
-#endif /* HICN_FACE_H */
-
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/fw_interface.h b/ctrl/libhicnctrl/includes/hicn/ctrl/fw_interface.h
new file mode 100644
index 000000000..0656de080
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/fw_interface.h
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+#ifndef HICNCTRL_FW_INTERFACE_H
+#define HICNCTRL_FW_INTERFACE_H
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/callback.h>
+
+/**
+ * \file fw_interface.h
+ * \brief Forwarder interface
+ *
+ * Forwarder interface is designed to be a reusable module (that might be
+ * wrapped in a C++ class), providing a fw-agnostic interface with the
+ * following goals:
+ * - maintaining a permanent connection to the fw (and keep track of the
+ * fw state, eventually caching some aspects)
+ * - allowing the tracking of multiplexed requests
+ * - supporting a stream of concurrent notifications that might be needed to
+ * synchronize states.
+ *
+ * It is design to be easily integrated with the different event loops used
+ * across the projects (libevent for C, asio for C++).
+ */
+
+#define foreach_fw_state \
+ _(UNDEFINED) \
+ _(DISABLED) /* stack is stopped */ \
+ _(REQUESTED) /* stack is starting */ \
+ _(AVAILABLE) /* forwarder is running */ \
+ _(CONNECTING) /* XXX NEW */ \
+ _(CONNECTED) /* control socket connected */ \
+ _(READY) /* listener is present */ \
+ _(N)
+
+typedef enum {
+#define _(x) FW_STATE_##x,
+ foreach_fw_state
+#undef _
+} fw_state_t;
+
+extern const char *fw_state_str[];
+
+#define fw_state_str(x) fw_state_str[x]
+
+typedef struct fw_interface_s fw_interface_t;
+
+fw_interface_t *fw_interface_create_url(forwarder_type_t type, const char *url);
+fw_interface_t *fw_interface_create(forwarder_type_t type);
+
+void fw_interface_free(fw_interface_t *fi);
+
+int fw_interface_get_fd(const fw_interface_t *fi);
+
+/*
+ * Enable the stack
+ */
+int fw_interface_enable(fw_interface_t *fi);
+
+/*
+ * Disable the stack
+ */
+int fw_interface_disable(fw_interface_t *fi);
+
+/*
+ * Request a permanent connection to the forwarder, starting it if needed.
+ */
+int fw_interface_connect(fw_interface_t *fi);
+
+/*
+ * Disconnect from the forwarder
+ */
+int fw_interface_disconnect(fw_interface_t *fi);
+
+fw_state_t fw_interface_get_state(const fw_interface_t *fi);
+
+int fw_interface_subscribe_all(fw_interface_t *fi);
+
+int fw_interface_unsubscribe_all(fw_interface_t *fi);
+
+int fw_interface_execute(fw_interface_t *fi, hc_action_t action,
+ hc_object_type_t object_type, hc_object_t *object,
+ hc_data_t **pdata);
+
+int fw_interface_execute_async(fw_interface_t *fi, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object,
+ hc_result_callback_t callback,
+ void *callback_data);
+
+int fw_interface_set_enable_callback(fw_interface_t *fi,
+ hc_enable_callback_t callback);
+
+int fw_interface_set_state_callback(fw_interface_t *fi,
+ hc_state_callback_t callback,
+ void *callback_data);
+
+int fw_interface_set_result_callback(fw_interface_t *fi,
+ hc_result_callback_t callback,
+ void *callback_data);
+
+int fw_interface_set_notification_callback(fw_interface_t *fi,
+ hc_notification_callback_t callback,
+ void *callback_data);
+
+// manage stack [android]
+// - not needed for face mgr
+// operations
+// - create face/route : facemgr, hproxy
+// - set fw strategy
+// - get listeners, hicn listener port
+// subscribe all
+// callbacks:
+// - forwarder available/unavailable
+// timers & reattempts : clarify
+// XXX remove_self on sock disconnect... should be in libhicnctrl
+
+int fw_interface_on_receive(fw_interface_t *fi, size_t count);
+int fw_interface_get_recv_buffer(fw_interface_t *fi, uint8_t **buffer,
+ size_t *size);
+
+#endif /* HICNCTRL_FW_INTERFACE_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light.h b/ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light.h
new file mode 100644
index 000000000..3e3e98c35
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light.h
@@ -0,0 +1,549 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/*
+ * @file hicn-light.h
+ * @brief hicn-light specifics.
+ *
+ * Header and payload in binary format.
+ */
+
+#ifndef HICN_CTRL_HICNLIGHT_H
+#define HICN_CTRL_HICNLIGHT_H
+
+#ifndef _WIN32
+#include <netinet/in.h>
+#include <sys/socket.h>
+#endif
+
+#include <stdint.h>
+#include <stdlib.h>
+
+#include <hicn/policy.h>
+#include <hicn/strategy.h>
+#include <hicn/util/ip_address.h>
+
+#include "api.h"
+
+#define SYMBOLIC_NAME_LEN 16
+
+typedef struct in6_addr ipv6_addr_t;
+typedef uint32_t ipv4_addr_t;
+
+typedef enum {
+ MESSAGE_COMMAND_SUBTYPE_UNDEFINED,
+ REQUEST_LIGHT = 0xc0, // this is a command
+ RESPONSE_LIGHT,
+ ACK_LIGHT,
+ NACK_LIGHT,
+ NOTIFICATION_LIGHT,
+ MESSAGE_COMMAND_SUBTYPE_N
+} message_command_subtype_t;
+
+#define message_type_is_valid(message_type) \
+ ((message_type != MESSAGE_TYPE_UNDEFINED) && \
+ (message_type != MESSAGE_COMMAND_SUBTYPE_N))
+
+#define message_type_from_uchar(x) \
+ (((x) < REQUEST_LIGHT) || (((x) >= MESSAGE_COMMAND_SUBTYPE_N)) \
+ ? MESSAGE_COMMAND_SUBTYPE_N \
+ : (message_command_subtype_t)(x))
+
+#define foreach_command_type \
+ _(listener_add, LISTENER_ADD) \
+ _(listener_remove, LISTENER_REMOVE) \
+ _(listener_list, LISTENER_LIST) \
+ _(connection_add, CONNECTION_ADD) \
+ _(connection_remove, CONNECTION_REMOVE) \
+ _(connection_list, CONNECTION_LIST) \
+ _(connection_update, CONNECTION_UPDATE) \
+ _(route_add, ROUTE_ADD) \
+ _(route_remove, ROUTE_REMOVE) \
+ _(route_list, ROUTE_LIST) \
+ _(cache_set_store, CACHE_SET_STORE) \
+ _(cache_set_serve, CACHE_SET_SERVE) \
+ _(cache_clear, CACHE_CLEAR) \
+ _(cache_list, CACHE_LIST) \
+ _(strategy_set, STRATEGY_SET) \
+ _(strategy_add_local_prefix, STRATEGY_ADD_LOCAL_PREFIX) \
+ _(wldr_set, WLDR_SET) \
+ _(punting_add, PUNTING_ADD) \
+ _(mapme_enable, MAPME_ENABLE) \
+ _(mapme_set_discovery, MAPME_SET_DISCOVERY) \
+ _(mapme_set_timescale, MAPME_SET_TIMESCALE) \
+ _(mapme_set_retx, MAPME_SET_RETX) \
+ _(mapme_add, MAPME_ADD) \
+ _(policy_add, POLICY_ADD) \
+ _(policy_remove, POLICY_REMOVE) \
+ _(policy_list, POLICY_LIST) \
+ _(active_interface_update, ACTIVE_INTERFACE_UPDATE) \
+ _(subscription_add, SUBSCRIPTION_ADD) \
+ _(subscription_remove, SUBSCRIPTION_REMOVE) \
+ _(stats_list, STATS_LIST) \
+ _(face_stats_list, FACE_STATS_LIST)
+
+typedef enum {
+ COMMAND_TYPE_UNDEFINED,
+#define _(l, u) COMMAND_TYPE_##u,
+ foreach_command_type
+#undef _
+ COMMAND_TYPE_N,
+} command_type_t;
+
+extern const char *command_type_str[];
+
+#define command_type_str(x) command_type_str[x]
+
+#define command_type_is_valid(command_type) \
+ ((command_type != COMMAND_TYPE_UNDEFINED) && (command_type != COMMAND_TYPE_N))
+
+#define command_type_from_uchar(x) \
+ (((x) >= COMMAND_TYPE_N) ? COMMAND_TYPE_N : (command_type_t)(x))
+
+/* Should be at least 8 bytes */
+typedef struct {
+ uint8_t message_type;
+ uint8_t command_id;
+ uint16_t length; /* Number of structures in the payload */
+ uint32_t seq_num;
+} cmd_header_t;
+
+typedef struct {
+ cmd_header_t header;
+} msg_header_t;
+
+/* Listener */
+
+typedef struct {
+ char symbolic[SYMBOLIC_NAME_LEN];
+ char interface_name[SYMBOLIC_NAME_LEN];
+ hicn_ip_address_t address;
+ uint16_t port;
+ uint8_t family;
+ uint8_t type;
+} cmd_listener_add_t;
+
+typedef struct {
+ char symbolicOrListenerid[SYMBOLIC_NAME_LEN];
+} cmd_listener_remove_t;
+
+typedef struct {
+ void *_; // Otherwise empty structs result in clang build error
+} cmd_listener_list_t;
+
+/* Connection */
+
+typedef struct {
+ char symbolic[SYMBOLIC_NAME_LEN];
+ // char interface_name[SYMBOLIC_NAME_LEN];
+ hicn_ip_address_t remote_ip;
+ hicn_ip_address_t local_ip;
+ uint16_t remote_port;
+ uint16_t local_port;
+ uint8_t family;
+ uint8_t type;
+ uint8_t admin_state;
+ uint8_t __pad;
+ uint32_t priority;
+ policy_tags_t tags;
+} cmd_connection_add_t;
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+} cmd_connection_remove_t;
+
+typedef struct {
+ void *_;
+} cmd_connection_list_t;
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ uint8_t admin_state;
+ uint8_t pad8[3];
+} cmd_connection_set_admin_state_t;
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ uint8_t admin_state;
+ uint32_t priority;
+ policy_tags_t tags;
+} cmd_connection_update_t;
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ uint32_t priority;
+} cmd_connection_set_priority_t;
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ policy_tags_t tags;
+} cmd_connection_set_tags_t;
+
+/* Route */
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ hicn_ip_address_t address;
+ uint16_t cost;
+ uint8_t family;
+ uint8_t len;
+} cmd_route_add_t;
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ hicn_ip_address_t address;
+ uint8_t family;
+ uint8_t len;
+} cmd_route_remove_t;
+
+typedef struct {
+ void *_;
+} cmd_route_list_t;
+
+/* Cache */
+
+typedef struct {
+ uint8_t activate;
+} cmd_cache_set_store_t;
+
+typedef struct {
+ uint8_t activate;
+} cmd_cache_set_serve_t;
+
+typedef struct {
+ void *_;
+} cmd_cache_clear_t;
+
+typedef struct {
+ void *_;
+} cmd_cache_list_t;
+
+typedef struct {
+ uint8_t store_in_cs;
+ uint8_t serve_from_cs;
+ uint32_t cs_size;
+ uint32_t num_stale_entries;
+} cmd_cache_list_reply_t;
+
+typedef struct {
+ cmd_header_t header;
+ cmd_cache_list_reply_t payload;
+} msg_cache_list_reply_t;
+
+/* WLDR */
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ uint8_t activate;
+} cmd_wldr_set_t;
+
+/* Strategy */
+
+typedef struct {
+ hicn_ip_address_t address;
+ uint8_t family;
+ uint8_t len;
+ uint8_t type;
+ uint8_t related_prefixes;
+ union {
+ struct {
+ hicn_ip_address_t addresses[MAX_FWD_STRATEGY_RELATED_PREFIXES];
+ uint8_t lens[MAX_FWD_STRATEGY_RELATED_PREFIXES];
+ uint8_t families[MAX_FWD_STRATEGY_RELATED_PREFIXES];
+ } low_latency;
+ };
+} cmd_strategy_set_t;
+
+typedef struct {
+ uint8_t type;
+ hicn_ip_address_t address;
+ uint8_t family;
+ uint8_t len;
+ hicn_ip_address_t local_address;
+ uint8_t local_family;
+ uint8_t local_len;
+} cmd_strategy_add_local_prefix_t;
+
+/* Punting */
+
+typedef struct {
+ char symbolic_or_connid[SYMBOLIC_NAME_LEN];
+ hicn_ip_address_t address;
+ uint8_t family;
+ uint8_t len;
+} cmd_punting_add_t;
+
+/* MAP-Me */
+
+typedef struct {
+ uint8_t activate;
+} cmd_mapme_activator_t;
+
+typedef cmd_mapme_activator_t cmd_mapme_enable_t;
+typedef cmd_mapme_activator_t cmd_mapme_set_discovery_t;
+
+typedef struct {
+ uint32_t timePeriod;
+} cmd_mapme_timing_t;
+
+typedef cmd_mapme_timing_t cmd_mapme_set_timescale_t;
+typedef cmd_mapme_timing_t cmd_mapme_set_retx_t;
+
+typedef struct {
+ hicn_ip_address_t address;
+ uint32_t face_id;
+ uint8_t family;
+ uint8_t len;
+} cmd_mapme_add_t;
+
+/* dummy */
+typedef struct {
+ void *_;
+} cmd_mapme_list_item_t;
+
+/* Policy */
+
+typedef struct {
+ hicn_ip_address_t address;
+ uint8_t family;
+ uint8_t len;
+ hicn_policy_t policy;
+} cmd_policy_add_t;
+
+typedef struct {
+ hicn_ip_address_t address;
+ uint8_t family;
+ uint8_t len;
+} cmd_policy_remove_t;
+
+typedef struct {
+ void *_;
+} cmd_policy_list_t;
+
+/* Subscription */
+
+typedef struct {
+ uint32_t topics;
+} cmd_subscription_add_t;
+
+typedef struct {
+ uint32_t topics;
+} cmd_subscription_remove_t;
+
+/* Statistics */
+
+// General stats
+typedef struct {
+ void *_;
+} cmd_stats_list_t;
+
+// Per-face stats
+typedef struct {
+ void *_;
+} cmd_face_stats_list_t;
+
+typedef void *cmd_active_interface_update_t;
+
+/* Full messages */
+
+#define _(l, u) \
+ typedef struct { \
+ cmd_header_t header; \
+ cmd_##l##_t payload; \
+ } msg_##l##_t;
+foreach_command_type
+#undef _
+
+ /* Serialized version of hc_listener_t */
+ typedef struct {
+ char name[SYMBOLIC_NAME_LEN];
+ char interface_name[INTERFACE_LEN];
+ hicn_ip_address_t local_addr;
+ uint32_t id;
+ uint16_t local_port;
+ uint8_t type;
+ uint8_t family;
+} cmd_listener_list_item_t;
+
+static_assert(sizeof(cmd_listener_list_item_t) == 56, "");
+
+typedef struct {
+ cmd_header_t header;
+ cmd_listener_list_item_t payload;
+} msg_listener_list_reply_t;
+
+/* Serialized version of hc_connection_t */
+typedef struct {
+ char name[SYMBOLIC_NAME_LEN];
+ char interface_name[INTERFACE_LEN];
+ hicn_ip_address_t local_addr;
+ hicn_ip_address_t remote_addr;
+ uint32_t id;
+ uint32_t priority;
+ uint16_t local_port;
+ uint16_t remote_port;
+ uint8_t netdevice_type;
+ uint8_t type;
+ uint8_t family;
+ uint8_t admin_state;
+ uint8_t tags;
+ uint8_t state;
+ uint8_t __pad[6];
+} cmd_connection_list_item_t;
+
+static_assert(POLICY_TAG_N <= 8, "");
+static_assert(sizeof(cmd_connection_list_item_t) == 88, "");
+
+typedef struct {
+ cmd_header_t header;
+ cmd_connection_list_item_t payload;
+} msg_connection_list_reply_t;
+
+typedef msg_connection_list_reply_t msg_connection_notify_t;
+
+typedef struct {
+ char interface_name[INTERFACE_LEN];
+ hicn_ip_address_t local_addr;
+ hicn_ip_address_t remote_addr;
+ uint32_t id;
+ uint32_t priority;
+ uint16_t local_port;
+ uint16_t remote_port;
+ uint8_t netdevice_type;
+ uint8_t type;
+ uint8_t family;
+ uint8_t admin_state;
+ uint8_t tags;
+ uint8_t state;
+ uint8_t __pad[6];
+} cmd_face_list_item_t;
+
+static_assert(sizeof(cmd_face_list_item_t) == 72, "");
+
+typedef struct {
+ char face_name[SYMBOLIC_NAME_LEN];
+ hicn_ip_address_t remote_addr;
+ uint32_t face_id;
+ uint16_t cost;
+ uint8_t family;
+ uint8_t len;
+ cmd_face_list_item_t face;
+} cmd_route_list_item_t;
+
+static_assert(sizeof(cmd_route_list_item_t) == 112, "");
+
+typedef struct {
+ cmd_header_t header;
+ cmd_route_list_item_t payload;
+} msg_route_list_reply_t;
+
+typedef msg_route_list_reply_t msg_route_notify_t;
+
+typedef struct {
+ uint8_t state;
+ uint8_t disabled;
+ uint16_t __pad;
+} _policy_tag_state_t;
+
+typedef struct {
+ uint32_t throughput;
+ uint32_t latency;
+ uint32_t loss_rate;
+} _interface_stats_t;
+
+typedef struct {
+ _interface_stats_t wired;
+ _interface_stats_t wifi;
+ _interface_stats_t cellular;
+ _interface_stats_t all;
+} _policy_stats_t;
+
+typedef struct {
+ char app_name[APP_NAME_LEN];
+ _policy_tag_state_t tags[POLICY_TAG_N];
+ _policy_stats_t stats;
+ uint8_t __pad[4];
+} _hicn_policy_t;
+
+static_assert(sizeof(_hicn_policy_t) == 208, "");
+
+typedef struct {
+ uint8_t policy[208];
+ hicn_ip_address_t remote_addr;
+ uint8_t family;
+ uint8_t len;
+ uint8_t __pad[6];
+} cmd_policy_list_item_t;
+
+static_assert(sizeof(cmd_policy_list_item_t) == 232, "");
+
+typedef struct {
+ cmd_header_t header;
+ cmd_policy_list_item_t payload;
+} msg_policy_list_reply_t;
+
+typedef msg_policy_list_reply_t msg_policy_notify_t;
+
+/* Those are needed to build but not used */
+typedef struct {
+ uint8_t _;
+} cmd_strategy_list_item_t;
+typedef struct {
+ uint8_t _;
+} cmd_subscription_list_item_t;
+
+/* Statistics */
+
+// General stats
+typedef struct {
+ hc_stats_t stats;
+} cmd_stats_list_item_t;
+
+typedef struct {
+ cmd_header_t header;
+ cmd_stats_list_item_t payload;
+} msg_stats_list_reply_t;
+
+// Per-face stats
+typedef struct {
+ hc_face_stats_t stats;
+} cmd_face_stats_list_item_t;
+
+typedef struct {
+ cmd_header_t header;
+ cmd_face_stats_list_item_t payload;
+} msg_face_stats_list_reply_t;
+
+//===== size of commands ======
+// REMINDER: when a new_command is added, the following switch has to be
+// updated.
+static inline int command_get_payload_len(command_type_t command_type) {
+ switch (command_type) {
+#define _(l, u) \
+ case COMMAND_TYPE_##u: \
+ return sizeof(cmd_##l##_t);
+ foreach_command_type
+#undef _
+ case COMMAND_TYPE_UNDEFINED : case COMMAND_TYPE_N : return 0;
+ }
+}
+
+ssize_t hc_light_command_serialize(hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object, uint8_t *msg);
+
+int hc_sock_initialize_module(hc_sock_t *s);
+
+#endif /* HICN_CTRL_HICNLIGHT_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/object.h b/ctrl/libhicnctrl/includes/hicn/ctrl/object.h
new file mode 100644
index 000000000..74b88c515
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/object.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file object.h
+ * \brief API object representation.
+ */
+
+#ifndef HICNCTRL_OBJECT_H
+#define HICNCTRL_OBJECT_H
+
+#include <hicn/ctrl/object_type.h>
+#include <hicn/ctrl/objects.h>
+
+typedef union {
+ hc_connection_t connection;
+ hc_listener_t listener;
+ hc_route_t route;
+ hc_face_t face;
+ // hc_data_t *data;
+ hc_punting_t punting;
+ hc_stats_t stats;
+ hc_face_stats_t face_stats;
+ hc_strategy_t strategy;
+ hc_policy_t policy;
+ hc_subscription_t subscription;
+ hc_cache_t cache;
+ hc_mapme_t mapme;
+ hc_active_interface_t active_interface;
+ uint8_t as_uint8;
+} hc_object_t;
+
+#define MAXSZ_OBJECT_T MAX
+
+#define IS_VALID_ACTION(x) IS_VALID_ENUM_TYPE(ACTION, x)
+
+bool hc_object_is_empty(const hc_object_t *object);
+
+size_t hc_object_size(hc_object_type_t object_type);
+
+int hc_object_validate(hc_object_type_t object_type, hc_object_t *object,
+ bool allow_partial);
+int hc_object_cmp(hc_object_type_t object_type, hc_object_t *object1,
+ hc_object_t *object2);
+int hc_object_snprintf(char *s, size_t size, hc_object_type_t object_type,
+ hc_object_t *object);
+
+#define foreach_object(VAR, data) foreach_type(hc_object_t, VAR, data)
+
+#define foreach_type(TYPE, VAR, DATA) \
+ for (TYPE *VAR = (TYPE *)hc_data_get_buffer(DATA); \
+ VAR < (TYPE *)(hc_data_get_buffer(DATA) + \
+ hc_data_get_size(DATA) * sizeof(TYPE)); \
+ VAR++)
+
+#endif /* HICNCTRL_OBJECT_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/object_type.h b/ctrl/libhicnctrl/includes/hicn/ctrl/object_type.h
new file mode 100644
index 000000000..4c5a8c425
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/object_type.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file object_type.h
+ * \brief Object type.
+ */
+
+#ifndef HICNCTRL_OBJECT_TYPE_H
+#define HICNCTRL_OBJECT_TYPE_H
+
+#define foreach_object_type \
+ _(UNDEFINED) \
+ _(CONNECTION) \
+ _(LISTENER) \
+ _(ROUTE) \
+ _(FACE) \
+ _(STRATEGY) \
+ _(PUNTING) \
+ _(POLICY) \
+ _(CACHE) \
+ _(MAPME) \
+ _(WLDR) \
+ _(LOCAL_PREFIX) \
+ _(PROBE) \
+ _(SUBSCRIPTION) \
+ _(ACTIVE_INTERFACE) \
+ _(STATS) \
+ _(FACE_STATS) \
+ _(N)
+
+typedef enum {
+#define _(x) OBJECT_TYPE_##x,
+ foreach_object_type
+#undef _
+} hc_object_type_t;
+
+extern const char *object_type_str[];
+
+#define object_type_str(x) object_type_str[x]
+
+hc_object_type_t object_type_from_str(const char *object_str);
+
+#define IS_VALID_OBJECT_TYPE(x) IS_VALID_ENUM_TYPE(OBJECT_TYPE, x)
+
+#endif /* HICNCTRL_OBJECT_TYPE_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects.h
new file mode 100644
index 000000000..5509f99a8
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects.h
@@ -0,0 +1,17 @@
+#ifndef HICNCTRL_OBJECTS_H
+#define HICNCTRL_OBJECTS_H
+
+#include <hicn/ctrl/objects/connection.h>
+#include <hicn/ctrl/objects/face.h>
+#include <hicn/ctrl/objects/listener.h>
+#include <hicn/ctrl/objects/route.h>
+#include <hicn/ctrl/objects/punting.h>
+#include <hicn/ctrl/objects/stats.h>
+#include <hicn/ctrl/objects/strategy.h>
+#include <hicn/ctrl/objects/policy.h>
+#include <hicn/ctrl/objects/subscription.h>
+#include <hicn/ctrl/objects/cache.h>
+#include <hicn/ctrl/objects/mapme.h>
+#include <hicn/ctrl/objects/active_interface.h>
+
+#endif /* HICNCTRL_OBJECTS_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/active_interface.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/active_interface.h
new file mode 100644
index 000000000..56a1d8cd5
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/active_interface.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/active_interface.h
+ * \brief Route.
+ */
+
+#ifndef HICNCTRL_OBJECTS_ACTIVE_INTERFACE_H
+#define HICNCTRL_OBJECTS_ACTIVE_INTERFACE_H
+
+#include <hicn/ctrl/objects/face.h>
+
+typedef struct {
+ hicn_ip_prefix_t prefix;
+ netdevice_flags_t interface_types;
+} hc_active_interface_t;
+
+#define foreach_active_interface(VAR, data) \
+ foreach_type(hc_active_interface_t, VAR, data)
+
+// XXX WRONG
+#define MAXSZ_HC_ACTIVE_INTERFACE_ \
+ MAXSZ_FACE_ID + 1 + MAXSZ_COST + 1 + MAXSZ_IP_ADDRESS + 1 + MAXSZ_LEN
+#define MAXSZ_HC_ACTIVE_INTERFACE MAXSZ_HC_ACTIVE_INTERFACE_ + NULLTERM
+
+int hc_active_interface_snprintf(char *s, size_t size,
+ const hc_active_interface_t *active_interface);
+int hc_active_interface_validate(const hc_active_interface_t *active_interface,
+ bool allow_partial);
+
+#endif
diff --git a/hicn-light/src/hicn/strategies/loadBalancer.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/base.h
index 74920768d..fc40f680e 100644
--- a/hicn-light/src/hicn/strategies/loadBalancer.h
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/base.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,14 +14,12 @@
*/
/**
- * Forward on the less loaded path
+ * \file base.h
+ * \brief Base definitions for objects.
*/
+#ifndef HICNCTRL_OBJECTS_BASE
+#define HICNCTRL_OBJECTS_BASE
-#ifndef loadBalancer_h
-#define loadBalancer_h
+#define INTERFACE_LEN 16
-#include <hicn/strategies/strategyImpl.h>
-
-StrategyImpl *strategyLoadBalancer_Create();
-
-#endif // loadBalancer_h
+#endif /* HICNCTRL_OBJECTS_BASE */
diff --git a/hicn-light/src/hicn/config/controlUpdateConnection.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/cache.h
index eea303202..1f8691be6 100644
--- a/hicn-light/src/hicn/config/controlUpdateConnection.h
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/cache.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,22 +14,25 @@
*/
/**
- * @file control_UpdateConnection.h
- * @brief Update a connection to an interface
- *
- * <#Detailed Description#>
- *
+ * \file objects/cache.h
+ * \brief Cache.
*/
-#ifndef Control_UpdateConnection_h
-#define Control_UpdateConnection_h
+#ifndef HICNCTRL_OBJECTS_CACHE_H
+#define HICNCTRL_OBJECTS_CACHE_H
-#ifdef WITH_POLICY
+typedef struct {
+ uint8_t serve; // 1 = on, 0 = off
+ uint8_t store; // 1 = on, 0 = off
+} hc_cache_t;
-#include <hicn/config/controlState.h>
-CommandOps *controlUpdateConnection_Create(ControlState *state);
-CommandOps *controlUpdateConnection_HelpCreate(ControlState *state);
+typedef struct {
+ bool store;
+ bool serve;
+ size_t cs_size;
+ size_t num_stale_entries;
+} hc_cache_info_t;
-#endif /* WITH_POLICY */
+int hc_cache_snprintf(char *s, size_t size, const hc_cache_info_t *cache_info);
-#endif // Control_UpdateConnection_h
+#endif /* HICNCTRL_OBJECTS_CACHE_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/connection.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/connection.h
new file mode 100644
index 000000000..771b48c20
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/connection.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/connection.h
+ * \brief Connection.
+ */
+
+#ifndef HICNCTRL_OBJECTS_CONNECTION_H
+#define HICNCTRL_OBJECTS_CONNECTION_H
+
+#include <stdint.h>
+#include <hicn/face.h>
+
+#include "base.h"
+
+/*
+ * NOTE :
+ * - interface_name is mainly used to derive listeners from connections,
+ * but is not itself used to create connections.
+ */
+typedef struct {
+ uint32_t id; /* Kr. */
+ char name[SYMBOLIC_NAME_LEN]; /* K.w */
+ char interface_name[INTERFACE_LEN]; /* Kr. */
+ netdevice_type_t netdevice_type; /* .r. */
+ face_type_t type; /* .rw */
+ int family; /* .rw */
+ hicn_ip_address_t local_addr; /* .rw */
+ uint16_t local_port; /* .rw */
+ hicn_ip_address_t remote_addr; /* .rw */
+ uint16_t remote_port; /* .rw */
+ face_state_t admin_state; /* .rw */
+ uint32_t priority; /* .rw */
+ policy_tags_t tags; /* .rw */
+ face_state_t state; /* .r. */
+} hc_connection_t;
+
+#define foreach_connection(VAR, data) foreach_type(hc_connection_t, VAR, data)
+
+#define MAXSZ_HC_CONNECTION_ \
+ MAXSZ_FACE_STATE_ + INTERFACE_LEN + SPACE + 2 * MAXSZ_URL_ + \
+ MAXSZ_FACE_TYPE_ + SPACES(3)
+#define MAXSZ_HC_CONNECTION MAXSZ_HC_CONNECTION_ + NULLTERM
+
+int hc_connection_validate(const hc_connection_t *connection,
+ bool allow_partial);
+int hc_connection_cmp(const hc_connection_t *c1, const hc_connection_t *c2);
+int hc_connection_snprintf(char *s, size_t size,
+ const hc_connection_t *connection);
+
+#endif /* HICNCTRL_OBJECTS_CONNECTION_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/face.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/face.h
new file mode 100644
index 000000000..1aa122f37
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/face.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file objects/face.h
+ * \brief Face.
+ *
+ * A face is an abstraction introduced by the control library to abstract the
+ * forwarder implementation details. It encompasses connections and listeners
+ * and ensures the right dependencies are enforced, eg that we always have a
+ * listener when a connection is created.
+ */
+
+#ifndef HICNCTRL_OBJECTS_FACE_H
+#define HICNCTRL_OBJECTS_FACE_H
+
+#include <hicn/face.h>
+
+#include "base.h"
+
+typedef face_t hc_face_t;
+
+#define foreach_face(VAR, data) foreach_type(hc_face_t, VAR, data)
+
+#define MAX_FACE_ID 255
+#define MAXSZ_FACE_ID_ 3
+#define MAXSZ_FACE_ID MAXSZ_FACE_ID_ + NULLTERM
+#define MAXSZ_FACE_NAME_ SYMBOLIC_NAME_LEN
+#define MAXSZ_FACE_NAME MAXSZ_FACE_NAME_ + NULLTERM
+
+#define MAXSZ_HC_FACE_ \
+ MAXSZ_FACE_ID_ + MAXSZ_FACE_NAME_ + MAXSZ_FACE_ + 5 + HOTFIXMARGIN
+#define MAXSZ_HC_FACE MAXSZ_HC_FACE_ + NULLTERM
+
+int hc_face_snprintf(char *s, size_t size, const hc_face_t *face);
+
+#endif /* HICNCTRL_OBJECTS_FACE_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/listener.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/listener.h
new file mode 100644
index 000000000..0fb74f558
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/listener.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/listener.h
+ * \brief Listener.
+ */
+
+#ifndef HICNCTRL_OBJECTS_LISTENER_H
+#define HICNCTRL_OBJECTS_LISTENER_H
+
+#include <stddef.h> // offsetof
+#include <stdint.h>
+#include <hicn/face.h>
+
+#include "base.h"
+
+// FIXME the listener should not require any port for hICN...
+typedef struct {
+ char name[SYMBOLIC_NAME_LEN]; /* K.w */
+ char interface_name[INTERFACE_LEN]; /* Kr. */
+ uint32_t id; /* Kr. */
+ face_type_t type; /* .rw */
+ int family; /* .rw */
+ hicn_ip_address_t local_addr; /* .rw */
+ uint16_t local_port; /* .rw */
+} hc_listener_t;
+
+int hc_listener_validate(const hc_listener_t *listener, bool allow_partial);
+int hc_listener_cmp(const hc_listener_t *l1, const hc_listener_t *l2);
+
+#define foreach_listener(VAR, data) foreach_type(hc_listener_t, VAR, data)
+
+#define MAXSZ_HC_LISTENER_ \
+ INTERFACE_LEN + SPACE + MAXSZ_URL_ + SPACE + MAXSZ_FACE_TYPE_
+#define MAXSZ_HC_LISTENER MAXSZ_HC_LISTENER_ + NULLTERM
+
+int hc_listener_snprintf(char *s, size_t size, const hc_listener_t *listener);
+
+#endif /* HICNCTRL_OBJECTS_LISTENER_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/mapme.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/mapme.h
new file mode 100644
index 000000000..3eda1bfaa
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/mapme.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file objects/mapme.h
+ * \brief MAP-Me.
+ */
+
+#ifndef HICNCTRL_OBJECTS_MAPME_H
+#define HICNCTRL_OBJECTS_MAPME_H
+
+typedef enum {
+ MAPME_TARGET_ENABLE,
+ MAPME_TARGET_DISCOVERY,
+ MAPME_TARGET_TIMESCALE,
+ MAPME_TARGET_RETX,
+} mapme_target_t;
+
+static inline mapme_target_t mapme_target_from_str(char *mapme_target_str) {
+ if (strcasecmp(mapme_target_str, "enable") == 0)
+ return MAPME_TARGET_ENABLE;
+ else if (strcasecmp(mapme_target_str, "discovery") == 0)
+ return MAPME_TARGET_DISCOVERY;
+ else if (strcasecmp(mapme_target_str, "timescale") == 0)
+ return MAPME_TARGET_TIMESCALE;
+ else
+ return MAPME_TARGET_RETX;
+}
+
+#define MAX_MAPME_ARG_LEN 30
+
+typedef struct {
+ mapme_target_t target;
+ // Command argument stored as a string
+ // before being parsed into 'enabled' or 'timescale'
+ char unparsed_arg[MAX_MAPME_ARG_LEN];
+
+ uint8_t enabled; // 1 = on, 0 = off
+ uint32_t timescale; // Milliseconds
+
+ hicn_ip_address_t address;
+ uint8_t family;
+ uint8_t len;
+ uint32_t face_id;
+} hc_mapme_t;
+
+#endif /* HICNCTRL_OBJECTS_MAPME_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/policy.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/policy.h
new file mode 100644
index 000000000..437387e4a
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/policy.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/policy.h
+ * \brief Policy.
+ */
+
+#ifndef HICNCTRL_OBJECTS_POLICY_H
+#define HICNCTRL_OBJECTS_POLICY_H
+
+typedef struct {
+ int family; /* Krw */
+ hicn_ip_address_t remote_addr; /* krw */
+ uint8_t len; /* krw */
+ hicn_policy_t policy; /* .rw */
+} hc_policy_t;
+
+#define foreach_policy(VAR, data) foreach_type(hc_policy_t, VAR, data)
+
+/* TODO */
+#define MAXSZ_HC_POLICY_ 0
+#define MAXSZ_HC_POLICY MAXSZ_HC_POLICY_ + NULLTERM
+
+int hc_policy_snprintf(char *s, size_t size, hc_policy_t *policy);
+int hc_policy_validate(const hc_policy_t *policy);
+
+#endif /* HICNCTRL_OBJECTS_POLICY_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/punting.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/punting.h
new file mode 100644
index 000000000..d18e596b1
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/punting.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/punting.h
+ * \brief Punting
+ */
+
+#ifndef HICNCTRL_OBJECTS_PUNTING_H
+#define HICNCTRL_OBJECTS_PUNTING_H
+
+typedef struct {
+ face_id_t face_id; /* Kr. */ // XXX listener id, could be NULL for all ?
+ int family; /* Krw */
+ hicn_ip_address_t prefix; /* krw */
+ u8 prefix_len; /* krw */
+} hc_punting_t;
+
+int hc_punting_validate(const hc_punting_t *punting);
+int hc_punting_cmp(const hc_punting_t *c1, const hc_punting_t *c2);
+
+#define foreach_punting(VAR, data) foreach_type(hc_punting_t, VAR, data)
+
+#define MAXSZ_HC_PUNTING_ 0
+#define MAXSZ_HC_PUNTING MAXSZ_HC_PUNTING_ + NULLTERM
+
+int hc_punting_snprintf(char *s, size_t size, hc_punting_t *punting);
+
+#endif /* HICNCTRL_OBJECTS_PUNTING_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/route.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/route.h
new file mode 100644
index 000000000..fb68e9430
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/route.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/route.h
+ * \brief Route.
+ */
+
+#ifndef HICNCTRL_OBJECTS_ROUTE_H
+#define HICNCTRL_OBJECTS_ROUTE_H
+
+#include <hicn/ctrl/objects/face.h>
+
+typedef struct {
+ face_id_t face_id; /* Kr. ID (used when face and face_name == NULL) */
+ char face_name[SYMBOLIC_NAME_LEN]; /* Kr. a name or an ID (if integer), used
+ if face is NULL */
+ int family; /* Krw */
+ hicn_ip_address_t remote_addr; /* krw */
+ uint8_t len; /* krw */
+ uint16_t cost; /* .rw */
+ hc_face_t face; /* use by default if not NULL, otherwise look at face_name,
+ then face_id */
+} hc_route_t;
+
+#define foreach_route(VAR, data) foreach_type(hc_route_t, VAR, data)
+
+#define MAX_COST 65535
+#define MAXSZ_COST 5
+#define MAX_LEN 255
+#define MAXSZ_LEN 3
+
+#define MAXSZ_HC_ROUTE_ \
+ MAXSZ_FACE_ID + 1 + MAXSZ_COST + 1 + MAXSZ_IP_ADDRESS + 1 + MAXSZ_LEN
+#define MAXSZ_HC_ROUTE MAXSZ_HC_ROUTE_ + NULLTERM
+
+int hc_route_snprintf(char *s, size_t size, const hc_route_t *route);
+int hc_route_validate(const hc_route_t *route, bool allow_partial);
+
+#endif /* HICNCTRL_OBJECTS_ROUTE_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/stats.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/stats.h
new file mode 100644
index 000000000..31c590dee
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/stats.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/stats.h
+ * \brief Stats.
+ */
+
+#ifndef HICNCTRL_OBJECTS_STATS_H
+#define HICNCTRL_OBJECTS_STATS_H
+
+#define MAXSZ_HC_STATS 600
+
+typedef hicn_light_stats_t hc_stats_t;
+typedef connection_stats_t hc_face_stats_t;
+
+#endif /* HICNCTRL_OBJECTS_STATS_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/strategy.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/strategy.h
new file mode 100644
index 000000000..208f4620b
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/strategy.h
@@ -0,0 +1,46 @@
+
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/strategy.h
+ * \brief Strategy.
+ */
+
+#ifndef HICNCTRL_OBJECTS_STRATEGY_H
+#define HICNCTRL_OBJECTS_STRATEGY_H
+
+#include <hicn/strategy.h>
+
+#define MAXSZ_STRATEGY_NAME 255
+
+typedef struct {
+ // The name is not set by the controller
+ // but populated by the daemon
+ char name[MAXSZ_STRATEGY_NAME];
+ strategy_type_t type;
+ hicn_ip_address_t address, local_address;
+ int family, local_family;
+ u8 len, local_len;
+} hc_strategy_t;
+
+#define foreach_strategy(VAR, data) foreach_type(hc_strategy_t, VAR, data)
+
+#define MAXSZ_HC_STRATEGY_ MAXSZ_STRATEGY_NAME
+#define MAXSZ_HC_STRATEGY MAXSZ_HC_STRATEGY_ + NULLTERM
+
+int hc_strategy_snprintf(char *s, size_t size, const hc_strategy_t *strategy);
+
+#endif /* HICNCTRL_OBJECTS_STRATEGY_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/objects/subscription.h b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/subscription.h
new file mode 100644
index 000000000..861341160
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/objects/subscription.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file objects/subscription.h
+ * \brief Subscription.
+ */
+
+#ifndef HICNCTRL_OBJECTS_SUBSCRIPTION_H
+#define HICNCTRL_OBJECTS_SUBSCRIPTION_H
+
+#include <limits.h>
+#include <stddef.h>
+#include <hicn/ctrl/object_type.h>
+
+#undef PUNTING // TODO(eloparco): Undefined to avoid collisions
+ // Fix the collision
+
+// Used only to create 'hc_topic_t'
+typedef struct {
+#define _(x) char x;
+ foreach_object_type
+#undef _
+} object_offset_t;
+
+// Flags for topic subscriptions
+typedef enum {
+#define _(x) TOPIC_##x = (1 << offsetof(object_offset_t, x)),
+ foreach_object_type
+#undef _
+ TOPIC_ALL = INT_MAX,
+} hc_topic_t;
+
+static inline hc_object_type_t object_from_topic(hc_topic_t topic) {
+#define _(x) \
+ if (topic == TOPIC_##x) return OBJECT_TYPE_##x;
+ foreach_object_type
+#undef _
+ return OBJECT_TYPE_UNDEFINED;
+}
+
+static inline hc_topic_t topic_from_object_type(hc_object_type_t object_type) {
+ if (object_type == OBJECT_TYPE_UNDEFINED) return TOPIC_ALL;
+#define _(x) \
+ if (object_type == OBJECT_TYPE_##x) return TOPIC_##x;
+ foreach_object_type
+#undef _
+ return TOPIC_UNDEFINED;
+}
+
+#define NUM_TOPICS OBJECT_TYPE_N // Because a topic is created for each object
+#define ALL_TOPICS ~0
+
+// Subscriptions
+typedef uint32_t hc_topics_t;
+typedef struct {
+ hc_topics_t topics;
+} hc_subscription_t;
+
+#if 0
+typedef struct {
+ netdevice_type_t interface_type;
+} hc_event_interface_update_t;
+
+typedef struct {
+ ip_prefix_t prefix;
+ netdevice_type_t interface_type;
+} hc_event_active_interface_update_t;
+#endif
+
+#endif /* HICNCTRL_OBJECTS_SUBSCRIPTION_H */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/parse.h b/ctrl/libhicnctrl/includes/hicn/ctrl/parse.h
new file mode 100644
index 000000000..8921d25ed
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/parse.h
@@ -0,0 +1,116 @@
+#ifndef HICNLIGHT_PARSE_CMD
+#define HICNLIGHT_PARSE_CMD
+
+#include <hicn/ctrl/api.h>
+
+#include "command.h"
+
+/* Update sscanf accordingly in parse_cmd.c */
+#define MAX_PARAMETERS 10
+#define MAX_SCANF_PARAM_LEN 100
+
+typedef int (*parser_hook_t)(void* arg);
+
+#if 0
+typedef struct {
+ const char* name;
+ const char* help;
+ parser_type_t type;
+ size_t offset;
+ /*
+ * quick hack to let the functions update two or more parameters, like for
+ * IP_ADDRESS or IP_PREFIX types
+ */
+ size_t offset2;
+ size_t offset3;
+} command_parameter_t;
+
+typedef struct {
+ hc_action_t action;
+ hc_object_type_t object;
+ unsigned nparams;
+ command_parameter_t parameters[MAX_PARAMETERS];
+ parser_hook_t post_hook;
+} command_parser_t;
+
+#define TYPE_STRN(N) \
+ (parser_type_t) { \
+ .name = TYPENAME_STR, \
+ .str = { \
+ .max_size = N, \
+ }, \
+ }
+#define TYPE_FMT_STRN(N) "%s"
+
+#define TYPE_INT(MIN, MAX) \
+ (parser_type_t) { \
+ .name = TYPENAME_INT, \
+ .sint = { \
+ .min = (MIN), \
+ .max = (MAX), \
+ }, \
+ }
+#define TYPE_FMT_INT "%d"
+
+#define TYPE_UINT(min, max) \
+ (parser_type_t) { \
+ .name = TYPENAME_UINT, \
+ .uint = { \
+ .min = min, \
+ .max = max, \
+ }, \
+ }
+#define TYPE_FMT_UINT "%u"
+
+#define TYPE_SYMBOLIC_OR_ID TYPE_STRN(SYMBOLIC_NAME_LEN)
+#define TYPE_FMT_SYMBOLIC_OR_ID "%s"
+
+#define TYPE_INTERFACE_NAME TYPE_STRN(INTERFACE_LEN)
+#define TYPE_FMT_INTERFACE_NAME "%s"
+
+#define TYPE_IP_ADDRESS \
+ (parser_type_t) { .name = TYPENAME_IP_ADDRESS, }
+#define TYPE_FMT_IP_ADDRESS "%s"
+
+#define TYPE_IP_PREFIX \
+ (parser_type_t) { .name = TYPENAME_IP_PREFIX, }
+#define TYPE_FMT_IP_PREFIX "%s"
+
+#define TYPE_ON_OFF \
+ (parser_type_t) { .name = TYPENAME_ON_OFF, }
+#define TYPE_FMT_ON_OFF "%s"
+
+#define TYPE_ENUM(x) \
+ (parser_type_t) { \
+ .name = TYPENAME_ENUM, \
+ .enum_ = { \
+ .from_str = (int (*)(const char*))x##_from_str, \
+ }, \
+ }
+/* We need to allocate room for the intermediate string */
+#define TYPE_FMT_ENUM "%s"
+
+#define TYPE_POLICY_STATE(TAG) \
+ (parser_type_t) { \
+ .name = TYPENAME_POLICY_STATE, \
+ .policy_state = { \
+ .tag = TAG, \
+ }, \
+ }
+/* We need to allocate room for the intermediate string */
+#define TYPE_FMT_POLICY_STATE "%s"
+#endif
+
+int parse_getopt_args(const command_parser_t* parser, int argc, char* argv[],
+ hc_command_t* command);
+
+int parse(const char* cmd, hc_command_t* command);
+int help(const char* cmd);
+
+/**
+ * @brief Convert the action enum to the action name used in the commands (e.g.
+ * from ACTION_CREATE to "add").
+ */
+const char* action_to_cmd_action(hc_action_t action);
+
+#endif /* HICNLIGHT_PARSE_CMD */
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/route.h b/ctrl/libhicnctrl/includes/hicn/ctrl/route.h
index d7ef6a26f..f1801d772 100644
--- a/ctrl/libhicnctrl/includes/hicn/ctrl/route.h
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/route.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,7 +21,7 @@
#define HICN_ROUTE_H
#include <hicn/util/ip_address.h>
-#include <hicn/ctrl/face.h>
+#include <hicn/face.h>
typedef u16 route_cost_t;
@@ -30,18 +30,23 @@ typedef struct hicn_route_s hicn_route_t;
#define MAXSZ_ROUTE_ MAXSZ_PREFIX + 3 + MAXSZ_COST
#define MAXSZ_ROUTE MAXSZ_ROUTE_ + NULLTERM
-hicn_route_t * hicn_route_create(ip_prefix_t * prefix, face_id_t face_id, route_cost_t cost);
-hicn_route_t * hicn_route_dup(const hicn_route_t * route);
-void hicn_route_free(hicn_route_t * route);
+#define MIN_ROUTE_COST 1
+#define MAX_ROUTE_COST 255
+#define IS_VALID_ROUTE_COST(x) ((x >= MIN_ROUTE_COST) && (x <= MAX_ROUTE_COST))
-int hicn_route_cmp(const hicn_route_t * route1, const hicn_route_t * route2);
+hicn_route_t* hicn_route_create(hicn_ip_prefix_t* prefix, face_id_t face_id,
+ route_cost_t cost);
+hicn_route_t* hicn_route_dup(const hicn_route_t* route);
+void hicn_route_free(hicn_route_t* route);
-int hicn_route_get_prefix(const hicn_route_t * route, ip_prefix_t * prefix);
-int hicn_route_set_prefix(hicn_route_t * route, const ip_prefix_t prefix);
+int hicn_route_cmp(const hicn_route_t* route1, const hicn_route_t* route2);
-int hicn_route_get_cost(const hicn_route_t * route, int * cost);
-int hicn_route_set_cost(hicn_route_t * route, const int cost);
+int hicn_route_get_prefix(const hicn_route_t* route, hicn_ip_prefix_t* prefix);
+int hicn_route_set_prefix(hicn_route_t* route, const hicn_ip_prefix_t prefix);
-size_t hicn_route_snprintf(char * s, size_t size, const hicn_route_t * route);
+int hicn_route_get_cost(const hicn_route_t* route, int* cost);
+int hicn_route_set_cost(hicn_route_t* route, const int cost);
+
+size_t hicn_route_snprintf(char* s, size_t size, const hicn_route_t* route);
#endif
diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/socket.h b/ctrl/libhicnctrl/includes/hicn/ctrl/socket.h
new file mode 100644
index 000000000..e53032955
--- /dev/null
+++ b/ctrl/libhicnctrl/includes/hicn/ctrl/socket.h
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file socket.h
+ * \brief Control socket
+ */
+
+#ifndef HICNCTRL_SOCKET_H
+#define HICNCTRL_SOCKET_H
+
+#include <hicn/ctrl/data.h>
+
+/* With UDP, the buffer should be able to receieve a full packet, and thus MTU
+ * (max 9000) is sufficient. Messages will be received fully one by one.
+ * With TCP, the buffer should be at least able to receive a message header and
+ * the maximum size of a data element, so any reasonable size will be correct,
+ * it might just optimize performance. Messages might arrive in chunks that the
+ * library is able to parse.
+ */
+#define JUMBO_MTU 9000
+#define RECV_BUFLEN 65535
+
+#define foreach_forwarder_type \
+ _(UNDEFINED) \
+ _(HICNLIGHT) \
+ _(VPP) \
+ _(N)
+
+typedef enum {
+#define _(x) FORWARDER_TYPE_##x,
+ foreach_forwarder_type
+#undef _
+} forwarder_type_t;
+
+extern const char *forwarder_type_str[];
+
+#define forwarder_type_str(x) forwarder_type_str[x]
+
+forwarder_type_t forwarder_type_from_str(const char *str);
+
+/**
+ * \brief Holds the state of an hICN control socket
+ */
+typedef struct hc_sock_s hc_sock_t;
+
+/**
+ * \brief Create an hICN control socket using the provided forwarder.
+ * \return an hICN control socket
+ */
+hc_sock_t *hc_sock_create_forwarder(forwarder_type_t forwarder);
+
+/**
+ * \brief Create an hICN control socket using the provided forwarder and a
+ * URL. \return an hICN control socket
+ */
+hc_sock_t *hc_sock_create_forwarder_url(forwarder_type_t forwarder,
+ const char *url);
+
+/**
+ * \brief Create an hICN control socket using the default connection type.
+ * XXX doc
+ * \return an hICN control socket
+ */
+hc_sock_t *hc_sock_create(forwarder_type_t forwarder, const char *url);
+
+/**
+ * \brief Frees an hICN control socket
+ * \param [in] s - hICN control socket
+ */
+void hc_sock_free(hc_sock_t *s);
+
+/**
+ * \brief Returns the next available sequence number to use for requests to
+ * the API. \param [in] s - hICN control socket
+ */
+int hc_sock_get_next_seq(hc_sock_t *s);
+
+/**
+ * \brief Sets the socket as non-blocking
+ * \param [in] s - hICN control socket
+ * \return Error code
+ */
+int hc_sock_set_nonblocking(hc_sock_t *s);
+
+/**
+ * \brief Return the file descriptor associated to the hICN contorl sock
+ * \param [in] s - hICN control socket
+ * \return The file descriptor (positive value), or a negative integer in case
+ * of error
+ */
+int hc_sock_get_fd(hc_sock_t *s);
+
+/**
+ * \brief Connect the socket
+ * \return Error code
+ */
+int hc_sock_connect(hc_sock_t *s);
+
+/**
+ * \brief Return the offset and size of available buffer space
+ * \param [in] s - hICN control socket
+ * \param [out] buffer - Offset in buffer
+ * \param [out] size - Remaining size
+ * \return Error code
+ */
+int hc_sock_get_recv_buffer(hc_sock_t *s, uint8_t **buffer, size_t *size);
+
+#if 0
+/**
+ * \brief Write/read iexchance on the control socket (internal helper
+ * function) \param [in] s - hICN control socket \param [in] msg - Message to
+ * send \param [in] msglen - Length of the message to send \return Error code
+ */
+int hc_sock_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, uint32_t seq);
+#endif
+
+/**
+ * \brief Processing data received by socket
+ * \param [in] s - hICN control socket
+ * \param [in] parse - Parse function to convert remote types into lib native
+ * types, or NULL not to perform any translation.
+ * \return Error code
+ */
+int hc_sock_process(hc_sock_t *s, hc_data_t **data);
+
+int hc_sock_receive(hc_sock_t *s, hc_data_t **data);
+int hc_sock_receive_all(hc_sock_t *s, hc_data_t **data);
+
+#if 0
+/**
+ * \brief Callback used in async mode when data is available on the socket
+ * \param [in] s - hICN control socket
+ * \return Error code
+ */
+int hc_sock_callback(hc_sock_t *s, hc_data_t **data);
+#endif
+
+/**
+ * \brief Reset the state of the sock (eg. to handle a reconnecton)
+ * \param [in] s - hICN control socket
+ * \return Error code
+ */
+int hc_sock_reset(hc_sock_t *s);
+
+void hc_sock_increment_woff(hc_sock_t *s, size_t bytes);
+
+#if 0
+int hc_sock_prepare_send(hc_sock_t *s, hc_result_t *result,
+ data_callback_t complete_cb, void *complete_cb_data);
+
+#endif
+
+int hc_sock_set_recv_timeout_ms(hc_sock_t *s, long timeout_ms);
+
+int hc_sock_set_async(hc_sock_t *s);
+
+int hc_sock_is_async(hc_sock_t *s);
+
+int hc_sock_on_receive(hc_sock_t *s, size_t count);
+
+#endif /* HICNCTRL_SOCKET_H */
diff --git a/ctrl/libhicnctrl/src/CMakeLists.txt b/ctrl/libhicnctrl/src/CMakeLists.txt
index f9934d70e..3ea5c5db9 100644
--- a/ctrl/libhicnctrl/src/CMakeLists.txt
+++ b/ctrl/libhicnctrl/src/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2023 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,80 +11,193 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-list(APPEND COMPILER_DEFINITIONS
- "-DWITH_POLICY"
-)
-
+##############################################################
+# Source files
+##############################################################
set(SOURCE_FILES
- face.c
- route.c
- api.c
+ action.c
+ api.c
+ command.c
+ commands/command_cache.c
+ commands/command_connection.c
+ commands/command_face.c
+ commands/command_listener.c
+ commands/command_mapme.c
+ commands/command_policy.c
+ commands/command_punting.c
+ commands/command_route.c
+ commands/command_stats.c
+ commands/command_strategy.c
+ commands/command_subscription.c
+ data.c
+ fw_interface.c
+ object.c
+ object_type.c
+ object_vft.c
+ objects/active_interface.c
+ objects/base.c
+ objects/connection.c
+ objects/face.c
+ objects/listener.c
+ objects/mapme.c
+ objects/route.c
+ objects/strategy.c
+ objects/stats.c
+ objects/subscription.c
+ parse.c
+ request.c
+ route.c
+ socket.c
)
set(HEADER_FILES
- api_private.h
+ object_vft.h
+ objects/active_interface.h
+ objects/base.h
+ objects/connection.h
+ objects/face.h
+ objects/listener.h
+ objects/mapme.h
+ objects/route.h
+ objects/stats.h
+ objects/strategy.h
+ objects/subscription.h
+ request.h
+ api_private.h
)
+
+##############################################################
+# Libraries to link
+##############################################################
set(LIBRARIES
- m
- dl
- ${HICN_LIBRARIES}
+ m
+ dl
+ ${HICN_LIBRARIES}
)
+
+##############################################################
+# Include directories
+##############################################################
set(INCLUDE_DIRS
+ PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}/../includes/
- ${HICN_INCLUDE_DIRS}
+ PUBLIC
+ $<BUILD_INTERFACE:${Libhicnctrl_INCLUDE_DIRS}>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
-# Android requires static libraries
+
+##############################################################
+# Library type
+##############################################################
if (DISABLE_SHARED_LIBRARIES)
- set(LIBRARIES ${LIBRARIES} ${LIBHICN_STATIC})
- set(LINK_TYPE STATIC)
+ set(LIBRARIES ${LIBRARIES} ${LIBHICN_STATIC})
+ set(LINK_TYPE STATIC)
else ()
- set(LINK_TYPE SHARED STATIC)
+ set(LINK_TYPE SHARED STATIC)
endif ()
-if (${CMAKE_SYSTEM_NAME} MATCHES Android)
- list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light_api.c
- )
+
+##############################################################
+# Compiler options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+)
+
+##############################################################
+# Do not use modules if Android
+##############################################################
+
+if (${CMAKE_SYSTEM_NAME} MATCHES Android OR ${CMAKE_SYSTEM_NAME} MATCHES iOS)
+ list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/connection.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/face.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/listener.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/mapme.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/route.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/stats.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/strategy.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/subscription.c
+ )
+ list(APPEND HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/connection.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/face.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/listener.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/mapme.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/route.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/stats.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/strategy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light/subscription.h
+ )
else()
- add_subdirectory(modules)
+ add_subdirectory(modules)
endif()
+
+##############################################################
+# Build main hicnctrl library
+##############################################################
build_library(${LIBHICNCTRL}
- ${LINK_TYPE}
- SOURCES ${SOURCE_FILES} ${HEADER_FILES}
- INSTALL_HEADERS ${TO_INSTALL_HEADER_FILES}
+ ${LINK_TYPE}
+ SOURCES ${SOURCE_FILES} ${HEADER_FILES}
+ INSTALL_HEADERS ${TO_INSTALL_HEADER_FILES}
+ LINK_LIBRARIES ${LIBRARIES}
+ DEPENDS ${DEPENDENCIES}
+ COMPONENT ${LIBHICNCTRL_COMPONENT}
+ INCLUDE_DIRS ${INCLUDE_DIRS}
+ DEFINITIONS PUBLIC ${COMPILER_DEFINITIONS}
+ VERSION ${CURRENT_VERSION}
+ EXPORT_NAME "${LIBHICNCTRL_COMPONENT}"
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
+
+##############################################################
+# Unit tests
+##############################################################
+if (${BUILD_TESTS})
+ add_subdirectory(test)
+endif()
+
+##############################################################
+# Cmake config files
+##############################################################
+create_cmake_config (
+ ${LIBHICNCTRL_COMPONENT}
+ INCLUDE_DIRS ${Libhicnctrl_INCLUDE_DIRS}
+ VERSION ${CURRENT_VERSION}
+ COMPONENT ${LIBHICNCTRL_COMPONENT}
+ NAMESPACE hicn
+)
+
+
+##############################################################
+# Build executables
+##############################################################
+if (NOT DISABLE_EXECUTABLES)
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBRARIES ${LIBRARIES} ${LIBHICNCTRL_STATIC})
+ set(DEPENDENCIES ${LIBHICNCTRL_STATIC})
+ else ()
+ set(LIBRARIES ${LIBRARIES} ${LIBHICN_SHARED} ${LIBHICNCTRL_SHARED})
+ set(DEPENDENCIES ${LIBHICNCTRL_SHARED})
+ endif ()
+
+ list(APPEND DAEMON_SRC
+ hicnctrl.c
+ )
+
+ build_executable(${HICNCTRL}
+ SOURCES ${DAEMON_SRC}
LINK_LIBRARIES ${LIBRARIES}
DEPENDS ${DEPENDENCIES}
COMPONENT ${LIBHICNCTRL_COMPONENT}
INCLUDE_DIRS ${INCLUDE_DIRS}
- HEADER_ROOT_DIR hicn
DEFINITIONS ${COMPILER_DEFINITIONS}
-)
-
-if (NOT DISABLE_EXECUTABLES)
- if (DISABLE_SHARED_LIBRARIES)
- set(LIBRARIES ${LIBRARIES} ${LIBHICNCTRL_STATIC})
- set(DEPENDENCIES ${LIBHICNCTRL_STATIC})
- else ()
- set(LIBRARIES ${LIBRARIES} ${LIBHICN_SHARED} ${LIBHICNCTRL_SHARED})
- set(DEPENDENCIES ${LIBHICNCTRL_SHARED})
- endif ()
-
- list(APPEND DAEMON_SRC
- cli.c
- )
-
- build_executable(${HICNCTRL}
- SOURCES ${DAEMON_SRC}
- LINK_LIBRARIES ${LIBRARIES}
- DEPENDS ${DEPENDENCIES}
- COMPONENT ${LIBHICNCTRL_COMPONENT}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- LINK_FLAGS ${LINK_FLAGS}
- )
+ LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ )
endif ()
diff --git a/ctrl/libhicnctrl/src/action.c b/ctrl/libhicnctrl/src/action.c
new file mode 100644
index 000000000..c8834d90c
--- /dev/null
+++ b/ctrl/libhicnctrl/src/action.c
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file action.c
+ * \brief Implementation of actions.
+ */
+
+#include <strings.h>
+
+#include <hicn/ctrl/action.h>
+
+const char *action_str[] = {
+#define _(x) [ACTION_##x] = #x,
+ foreach_action
+#undef _
+};
+
+hc_action_t action_from_str(const char *action_str) {
+#define _(x) \
+ if (strcasecmp(action_str, #x) == 0) \
+ return ACTION_##x; \
+ else
+ foreach_action
+#undef _
+ if (strcasecmp(action_str, "add") == 0) return ACTION_CREATE;
+ else if (strcasecmp(action_str, "remove") == 0) return ACTION_DELETE;
+ else return ACTION_UNDEFINED;
+}
diff --git a/ctrl/libhicnctrl/src/api.c b/ctrl/libhicnctrl/src/api.c
index 4bb66c784..c133b9123 100644
--- a/ctrl/libhicnctrl/src/api.c
+++ b/ctrl/libhicnctrl/src/api.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,1274 +18,275 @@
* \brief Implementation of hICN control library API
*/
-#include <hicn/util/log.h>
-#include "api_private.h"
-
-#include <math.h> // log2
+#include <assert.h>
#include <dlfcn.h> // dlopen
+#include <hicn/strategy.h>
+#include <hicn/util/log.h>
+#include <hicn/ctrl/route.h>
+#include <math.h> // log2
-/* /!\ Please update constants in public header file upon changes */
-const char * connection_state_str[] = {
-#define _(x) [HC_CONNECTION_STATE_ ## x] = STRINGIZE(x),
-foreach_connection_state
-#undef _
-};
-
-/* /!\ Please update constants in public header file upon changes */
-const char * connection_type_str[] = {
-#define _(x) [CONNECTION_TYPE_ ## x] = STRINGIZE(x),
-foreach_connection_type
-#undef _
-};
-
-hc_connection_type_t
-connection_type_from_str(const char * str)
-{
- if (strcasecmp(str, "TCP") == 0)
- return CONNECTION_TYPE_TCP;
- else if (strcasecmp(str, "UDP") == 0)
- return CONNECTION_TYPE_UDP;
- else if (strcasecmp(str, "HICN") == 0)
- return CONNECTION_TYPE_HICN;
- else
- return CONNECTION_TYPE_UNDEFINED;
-}
-
-/* Conversions to shield lib user from heterogeneity */
-
-#define IS_VALID_LIST_CONNECTIONS_TYPE(x) ((x >= CONN_GRE) && (x <= CONN_HICN))
-
-const hc_connection_type_t map_from_list_connections_type[] = {
- [CONN_GRE] = CONNECTION_TYPE_UNDEFINED,
- [CONN_TCP] = CONNECTION_TYPE_TCP,
- [CONN_UDP] = CONNECTION_TYPE_UDP,
- [CONN_MULTICAST] = CONNECTION_TYPE_UNDEFINED,
- [CONN_L2] = CONNECTION_TYPE_UNDEFINED,
- [CONN_HICN] = CONNECTION_TYPE_HICN,
-};
-
-#define IS_VALID_LIST_LISTENERS_TYPE(x) ((x >= ENCAP_TCP) && (x <= ENCAP_HICN))
-
-const hc_connection_type_t map_from_encap_type[] = {
- [ENCAP_TCP] = CONNECTION_TYPE_TCP,
- [ENCAP_UDP] = CONNECTION_TYPE_UDP,
- [ENCAP_ETHER] = CONNECTION_TYPE_UNDEFINED,
- [ENCAP_LOCAL] = CONNECTION_TYPE_UNDEFINED,
- [ENCAP_HICN] = CONNECTION_TYPE_HICN,
-};
-
-const connection_type map_to_connection_type[] = {
- [CONNECTION_TYPE_TCP] = TCP_CONN,
- [CONNECTION_TYPE_UDP] = UDP_CONN,
- [CONNECTION_TYPE_HICN] = HICN_CONN,
-};
-
-const listener_mode map_to_listener_mode[] = {
- [CONNECTION_TYPE_TCP] = IP_MODE,
- [CONNECTION_TYPE_UDP] = IP_MODE,
- [CONNECTION_TYPE_HICN] = HICN_MODE,
-};
-
-#define IS_VALID_LIST_CONNECTIONS_STATE(x) ((x >= IFACE_UP) && (x <= IFACE_UNKNOWN))
-
-/*
-#define IS_VALID_CONNECTION_STATE(x) IS_VALID_ENUM_TYPE(CONNECTION_STATE, x)
-
-static const connection_state map_to_connection_state[] = {
- [HC_CONNECTION_STATE_UP] = IFACE_UP,
- [HC_CONNECTION_STATE_DOWN] = IFACE_DOWN,
-};
-
-*/
-
-const hc_connection_state_t map_from_list_connections_state[] = {
- [IFACE_UP] = HC_CONNECTION_STATE_UP,
- [IFACE_DOWN] = HC_CONNECTION_STATE_DOWN,
- [IFACE_UNKNOWN] = HC_CONNECTION_STATE_UNDEFINED,
-};
-
-
-const int map_from_addr_type[] = {
- [ADDR_INET] = AF_INET,
- [ADDR_INET6] = AF_INET6,
- [ADDR_LINK] = AF_UNSPEC,
- [ADDR_IFACE] = AF_UNSPEC,
- [ADDR_UNIX] = AF_UNSPEC,
-};
-
-const address_type map_to_addr_type[] = {
- [AF_INET] = ADDR_INET,
- [AF_INET6] = ADDR_INET6,
-};
-
-/******************************************************************************
- * Control Data
- ******************************************************************************/
-
-hc_data_t *
-hc_data_create(size_t in_element_size, size_t out_element_size, data_callback_t complete_cb)
-{
- hc_data_t * data = malloc(sizeof(hc_data_t));
- if (!data)
- goto ERR_MALLOC;
-
- /* FIXME Could be NULL thanks to realloc provided size is 0 */
- data->max_size_log = DEFAULT_SIZE_LOG;
- data->in_element_size = in_element_size;
- data->out_element_size = out_element_size;
- data->size = 0;
- data->complete = false;
- data->command_id = 0; // TODO this could also be a busy mark in the socket
- /* No callback needed in blocking code for instance */
- data->complete_cb = complete_cb;
-
- data->buffer = malloc((1 << data->max_size_log) * data->out_element_size);
- if (!data->buffer)
- goto ERR_BUFFER;
- data->ret = 0;
-
- return data;
-
-ERR_BUFFER:
- hc_data_free(data);
-ERR_MALLOC:
- return NULL;
-}
-
-void
-hc_data_free(hc_data_t * data)
-{
- if (data->buffer)
- free(data->buffer);
- free(data);
-}
-
-int
-hc_data_ensure_available(hc_data_t * data, size_t count)
-{
- size_t new_size_log = (data->size + count - 1 > 0)
- ? log2(data->size + count - 1) + 1
- : 0;
- if (new_size_log > data->max_size_log) {
- data->max_size_log = new_size_log;
- data->buffer = realloc(data->buffer, (1 << new_size_log) * data->out_element_size);
- if (!data->buffer)
- return -1;
- }
-
- return 0;
-}
+#include "api_private.h"
+#include "object_vft.h"
+#include "request.h"
-int
-hc_data_push_many(hc_data_t * data, const void * elements, size_t count)
-{
- if (hc_data_ensure_available(data, count) < 0)
- return -1;
+#include <hicn/ctrl/socket.h>
+#include "socket_private.h"
- memcpy(data->buffer + data->size * data->out_element_size, elements,
- count * data->out_element_size);
- data->size += count;
+#define ENOIMPL 42
- return 0;
-}
+int hc_sock_on_init(hc_sock_t *s, hc_request_t *request) {
+ int rc;
+ ssize_t size;
-int
-hc_data_push(hc_data_t * data, const void * element)
-{
- return hc_data_push_many(data, element, 1);
-}
+ uint8_t *buffer;
-/**
- *
- * NOTE: This function make sure there is enough room available in the data
- * structure.
- */
-u8 *
-hc_data_get_next(hc_data_t * data)
-{
- if (hc_data_ensure_available(data, 1) < 0)
- return NULL;
+ size = s->ops.prepare(s, request, &buffer);
+ if (size < 0) goto ERR_PREPARE;
- return data->buffer + data->size * data->out_element_size;
-}
+ if (size == 0) return 1; /* Done */
-int
-hc_data_set_callback(hc_data_t * data, data_callback_t cb, void * cb_data)
-{
- data->complete_cb = cb;
- data->complete_cb_data = cb_data;
- return 0;
-}
+ assert(hc_request_get_data(hc_request_get_current(request)));
-int
-hc_data_set_complete(hc_data_t * data)
-{
- data->complete = true;
- data->ret = 0;
- if (data->complete_cb)
- return data->complete_cb(data, data->complete_cb_data);
- return 0;
-}
+ rc = s->ops.send(s, buffer, size);
+ if (rc < 0) goto ERR_SEND;
-int
-hc_data_set_error(hc_data_t * data)
-{
- data->ret = -1;
- return 0;
-}
+ return 0;
-int
-hc_data_reset(hc_data_t * data)
-{
- data->size = 0;
- return 0;
+ERR_PREPARE:
+ERR_SEND:
+ return -1;
}
-static hc_sock_t * _open_module(const char *name)
-{
- char complete_name[128];
-#ifdef __APPLE__
- sprintf(complete_name, "%s.dylib", name);
-#elif defined(__linux__)
- sprintf(complete_name, "%s.so", name);
-#else
- #error "System not supported for dynamic lynking"
-#endif
+int hc_sock_on_receive(hc_sock_t *s, size_t count) {
+ int rc;
- void *handle = 0;
- const char *error = 0;
- hc_sock_t *(*creator)(void) = 0;
- hc_sock_t *ret = 0;
+ DEBUG("hc_sock_on_receive: calling process with count=%ld", count);
+ rc = s->ops.process(s, count);
+ if (rc < 0) goto ERR_PROCESS;
- // open module
- handle = dlopen(complete_name, RTLD_LAZY);
- if (!handle) {
- if ((error = dlerror()) != 0) {
- ERROR("%s", error);
+ hc_request_t *request = hc_sock_get_request(s);
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_data_t *data = hc_request_get_data(current_request);
+ if (hc_data_is_complete(data)) {
+ /*
+ * We only notice a request is complete when trying to send the second
+ * time... either the state machine reaches the end, or in case of generic
+ * requests, we mark it as such.
+ */
+ ON_INIT:
+ rc = hc_sock_on_init(s, request);
+ if (rc < 0) goto ERR_INIT;
+ if (rc == 1) {
+ if (!hc_request_pop(request)) {
+ /* Free request context */
+ /* In case of error, data is NULL */
+ // hc_sock_free_request(s, request);
+ if (!hc_request_is_subscription(request))
+ hc_request_set_complete(request);
+ return 1; /* Done */
+ }
+ goto ON_INIT;
}
-
- return 0;
- }
-
- // get factory method
- creator = (hc_sock_t * (*)(void)) dlsym(handle, "_hc_sock_create");
- if (!creator) {
- if ((error = dlerror()) != 0) {
- ERROR("%s", error);
- return 0;
+#if 0
}
+#endif
}
-
- ret = (*creator)();
- ret->handle = handle;
-
- return ret;
-}
-
-hc_sock_t *hc_sock_create_forwarder(forwarder_t forwarder)
-{
- switch (forwarder)
- {
- case HICNLIGHT:
- return _open_module("hicnlightctrl_module");
- case VPP:
- return _open_module("vppctrl_module");
- default:
- return NULL;
+ return 0; /* Continue processing */
+
+ERR_INIT:
+ERR_PROCESS:
+ return -1;
+}
+
+// -1 error
+// 0 = request is not yet complete
+// 1 request is complete
+int hc_sock_receive(hc_sock_t *s, hc_data_t **pdata) {
+ int rc;
+ DEBUG("Waiting for data...");
+ rc = s->ops.recv(s);
+ if (rc < 0) return -1;
+
+ rc = hc_sock_on_receive(s, 0);
+ if (rc < 0) return -1;
+
+ hc_request_t *request = hc_sock_get_request(s);
+ /*
+ * If notification, display it, ideally callback. What to do with
+ * allocated data ?
+ */
+ // XXX problem we display object on ACK... but not subsequent
+ // notifications
+ // XXX we should rely on callback here in addition, even for a synchronous
+ // request
+ if (hc_request_is_subscription(request)) {
+ hc_data_t *data = hc_request_get_data(request);
+ assert(data);
+ hc_object_t *obj = (hc_object_t *)hc_data_get_buffer(data);
+ char buf[MAXSZ_HC_OBJECT];
+ hc_object_type_t object_type = hc_data_get_object_type(data);
+ if (hc_object_snprintf(buf, sizeof(buf), object_type, obj) > 0) {
+ ;
+ INFO("%s %s", object_type_str(object_type), buf);
}
-}
-
-#ifdef ANDROID
-// In android we do not load a module at runtime
-// but we link the hicnlight implmentation directly
-// to the main library
-extern hc_sock_t *_hc_sock_create();
-#endif
-
-hc_sock_t *hc_sock_create(void)
-{
-#ifdef ANDROID
- hc_sock_t *ret = _hc_sock_create();
- ret->handle = NULL;
- return ret;
-#else
- return hc_sock_create_forwarder(HICNLIGHT);
-#endif
-}
+ }
-void hc_sock_free(hc_sock_t *s)
-{
- void *handle = s->handle;
- s->hc_sock_free(s);
+ // XXX need same for async
+ if (rc != 1) return 0;
- if (handle) {
- dlclose(handle);
+ hc_request_t *current_request = hc_request_get_current(request);
+ if (hc_request_is_complete(current_request)) {
+ /* We either return the (last) allocated data, or free it */
+ if (pdata) {
+ *pdata = hc_request_get_data(request);
+ } else {
+ hc_request_reset_data(request);
}
+ hc_request_on_complete(request);
+ // hc_sock_free_request(s, request);
+ }
+ return 1;
}
-int hc_sock_get_next_seq(hc_sock_t *s)
-{
- return s->hc_sock_get_next_seq(s);
-}
-
-int hc_sock_set_nonblocking(hc_sock_t *s)
-{
- return s->hc_sock_get_next_seq(s);
-}
-
-int hc_sock_get_fd(hc_sock_t *s)
-{
- return s->hc_sock_get_fd(s);
-}
-
-int hc_sock_connect(hc_sock_t *s)
-{
- return s->hc_sock_connect(s);
-}
-
-int hc_sock_get_available(hc_sock_t *s, u8 **buffer, size_t *size)
-{
- return s->hc_sock_get_available(s, buffer, size);
-}
-
-int hc_sock_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, int seq)
-{
- return s->hc_sock_send(s, msg, msglen, seq);
-}
-
-int hc_sock_recv(hc_sock_t *s)
-{
- return s->hc_sock_recv(s);
-}
-
-int hc_sock_process(hc_sock_t *s, hc_data_t **data)
-{
- return s->hc_sock_process(s, data);
-}
-
-int hc_sock_callback(hc_sock_t *s, hc_data_t **data)
-{
- return s->hc_sock_callback(s, data);
-}
-
-int hc_sock_reset(hc_sock_t *s)
-{
- return s->hc_sock_reset(s);
-}
-
-int hc_listener_create(hc_sock_t *s, hc_listener_t *listener)
-{
- return s->hc_listener_create(s, listener);
-}
-
-int hc_listener_get(hc_sock_t *s, hc_listener_t *listener,
- hc_listener_t **listener_found)
-{
- return s->hc_listener_get(s, listener, listener_found);
-}
-
-int hc_listener_delete(hc_sock_t *s, hc_listener_t *listener)
-{
- return s->hc_listener_delete(s, listener);
-}
-
-int hc_listener_list(hc_sock_t *s, hc_data_t **pdata)
-{
- return s->hc_listener_list(s, pdata);
-}
-
-GENERATE_FIND(listener);
-
-/* LISTENER VALIDATE */
-
-int
-hc_listener_validate(const hc_listener_t * listener)
-{
- if (!IS_VALID_FAMILY(listener->family))
- return -1;
-
- if (!IS_VALID_CONNECTION_TYPE(listener->type))
- return -1;
-
- return 0;
-}
-
-/* LISTENER CMP */
-
-int
-hc_listener_cmp(const hc_listener_t * l1, const hc_listener_t * l2)
-{
- int rc;
-
- rc = INT_CMP(l1->type, l2->type);
- if (rc != 0)
- return rc;
-
- rc = INT_CMP(l1->family, l2->family);
- if (rc != 0)
- return rc;
-
- rc = strncmp(l1->interface_name, l2->interface_name, INTERFACE_LEN);
- if (rc != 0)
- return rc;
-
- rc = ip_address_cmp(&l1->local_addr, &l2->local_addr, l1->family);
- if (rc != 0)
- return rc;
-
- rc = INT_CMP(l1->local_port, l2->local_port);
- if (rc != 0)
- return rc;
-
- return rc;
-}
-
-/* LISTENER PARSE */
-
-int
-hc_listener_parse(void * in, hc_listener_t * listener)
-{
- int rc;
-
- list_listeners_command * cmd = (list_listeners_command *)in;
-
- if (!IS_VALID_LIST_LISTENERS_TYPE(cmd->encapType))
- return -1;
-
- hc_connection_type_t type = map_from_encap_type[cmd->encapType];
- if (type == CONNECTION_TYPE_UNDEFINED)
- return -1;
-
- if (!IS_VALID_ADDR_TYPE(cmd->addressType))
- return -1;
-
- int family = map_from_addr_type[cmd->addressType];
- if (!IS_VALID_FAMILY(family))
- return -1;
-
- *listener = (hc_listener_t) {
- .id = cmd->connid,
- .type = type,
- .family = family,
- .local_addr = UNION_CAST(cmd->address, ip_address_t),
- .local_port = ntohs(cmd->port),
- };
- rc = snprintf(listener->name, SYMBOLIC_NAME_LEN, "%s", cmd->listenerName);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[hc_listener_parse] Unexpected truncation of symbolic name string");
- rc = snprintf(listener->interface_name, INTERFACE_LEN, "%s", cmd->interfaceName);
- if (rc >= INTERFACE_LEN)
- WARN("[hc_listener_parse] Unexpected truncation of interface name string");
- return 0;
-}
-
-/* LISTENER SNPRINTF */
-
-/* /!\ Please update constants in header file upon changes */
-int
-hc_listener_snprintf(char * s, size_t size, hc_listener_t * listener)
-{
- char local[MAXSZ_URL];
- int rc;
- rc = url_snprintf(local, MAXSZ_URL,
- listener->family, &listener->local_addr, listener->local_port);
- if (rc >= MAXSZ_URL)
- WARN("[hc_listener_snprintf] Unexpected truncation of URL string");
- if (rc < 0)
- return rc;
-
- return snprintf(s, size, "%s %s %s", listener->interface_name, local,
- connection_type_str[listener->type]);
-}
-
-int hc_connection_create(hc_sock_t *s, hc_connection_t *connection)
-{
- return s->hc_connection_create(s, connection);
-}
-
-int hc_connection_get(hc_sock_t *s, hc_connection_t *connection,
- hc_connection_t **connection_found)
-{
- return s->hc_connection_get(s, connection, connection_found);
-}
-
-int hc_connection_update_by_id(hc_sock_t *s, int hc_connection_id,
- hc_connection_t *connection)
-{
- return s->hc_connection_update_by_id(s, hc_connection_id, connection);
-}
-
-int hc_connection_update(hc_sock_t *s, hc_connection_t *connection_current,
- hc_connection_t *connection_updated)
-{
- return s->hc_connection_update(s, connection_current, connection_updated);
-}
-
-int hc_connection_delete(hc_sock_t *s, hc_connection_t *connection)
-{
- return s->hc_connection_delete(s, connection);
-}
-
-int hc_connection_list(hc_sock_t *s, hc_data_t **pdata)
-{
- return s->hc_connection_list(s, pdata);
-}
-
-int hc_connection_set_admin_state(hc_sock_t * s, const char * conn_id_or_name, face_state_t state)
-{
- return s->hc_connection_set_admin_state(s, conn_id_or_name, state);
-}
-
-#ifdef WITH_POLICY
-int hc_connection_set_priority(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority)
-{
- return s->hc_connection_set_priority(s, conn_id_or_name, priority);
-}
-
-int hc_connection_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags)
-{
- return s->hc_connection_set_tags(s, conn_id_or_name, tags);
-}
-#endif // WITH_POLICY
-
-GENERATE_FIND(connection);
-
-/* CONNECTION VALIDATE */
-
-int
-hc_connection_validate(const hc_connection_t * connection)
-{
- if (!IS_VALID_FAMILY(connection->family))
- return -1;
-
- if (!IS_VALID_CONNECTION_TYPE(connection->type))
- return -1;
+int hc_sock_receive_all(hc_sock_t *s, hc_data_t **pdata) {
+ for (;;) {
+ int rc = hc_sock_receive(s, pdata);
+ if (rc < 0) return -1;
- /* TODO assert both local and remote have the right family */
-
- return 0;
+ /* If request is complete, stop */
+ if (rc == 1) break;
+ }
+ return 0;
}
-/* CONNECTION CMP */
-
-/*
- * hICN light uses ports even for hICN connections, but their value is ignored.
- * As connections are specific to hicn-light, we can safely use IP and ports for
- * comparison independently of the face type.
+/**
+ * @return <0 in case of error
+ * -1 : validation error
+ * -2 : error during send
+ * -3 : error receiving or parsing
+ *
+ * If the caller provider a non-NULL hc_data_t pointer to receive results
+ * back, it is responsible for freeing it.
*/
-int hc_connection_cmp(const hc_connection_t * c1, const hc_connection_t * c2)
-{
- int rc;
-
- rc = INT_CMP(c1->type, c2->type);
- if (rc != 0)
- return rc;
-
- rc = INT_CMP(c1->family, c2->family);
- if (rc != 0)
- return rc;
-
- rc = strncmp(c1->interface_name, c2->interface_name, INTERFACE_LEN);
- if (rc != 0)
- return rc;
-
- rc = ip_address_cmp(&c1->local_addr, &c2->local_addr, c1->family);
- if (rc != 0)
- return rc;
-
- rc = INT_CMP(c1->local_port, c2->local_port);
- if (rc != 0)
- return rc;
-
- rc = ip_address_cmp(&c1->remote_addr, &c2->remote_addr, c1->family);
- if (rc != 0)
- return rc;
-
- rc = INT_CMP(c1->remote_port, c2->remote_port);
- if (rc != 0)
- return rc;
-
- return rc;
-}
-
-/* CONNECTION PARSE */
-
-int
-hc_connection_parse(void * in, hc_connection_t * connection)
-{
- int rc;
- list_connections_command * cmd = (list_connections_command *)in;
-
- if (!IS_VALID_LIST_CONNECTIONS_TYPE(cmd->connectionData.connectionType))
- return -1;
+int _hc_execute(hc_sock_t *s, hc_action_t action, hc_object_type_t object_type,
+ hc_object_t *object, hc_result_callback_t callback,
+ void *callback_data, hc_data_t **pdata) {
+ assert(!(hc_sock_is_async(s) && pdata));
- hc_connection_type_t type = map_from_list_connections_type[cmd->connectionData.connectionType];
- if (type == CONNECTION_TYPE_UNDEFINED)
- return -1;
-
- if (!IS_VALID_LIST_CONNECTIONS_STATE(cmd->state))
- return -1;
-
- hc_connection_state_t state = map_from_list_connections_state[cmd->state];
- if (state == HC_CONNECTION_STATE_UNDEFINED)
- return -1;
-
- if (!IS_VALID_ADDR_TYPE(cmd->connectionData.ipType))
- return -1;
-
- int family = map_from_addr_type[cmd->connectionData.ipType];
- if (!IS_VALID_FAMILY(family))
- return -1;
-
- *connection = (hc_connection_t) {
- .id = cmd->connid,
- .type = type,
- .family = family,
- .local_addr = cmd->connectionData.localIp,
- //.local_addr = UNION_CAST(cmd->connectionData.localIp, ip_address_t),
- .local_port = ntohs(cmd->connectionData.localPort),
- .remote_addr = cmd->connectionData.remoteIp,
- //.remote_addr = UNION_CAST(cmd->connectionData.remoteIp, ip_address_t),
- .remote_port = ntohs(cmd->connectionData.remotePort),
- .admin_state = cmd->connectionData.admin_state,
-#ifdef WITH_POLICY
- .priority = cmd->connectionData.priority,
- .tags = cmd->connectionData.tags,
-#endif /* WITH_POLICY */
- .state = state,
- };
- rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "%s", cmd->connectionData.symbolic);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[hc_connection_parse] Unexpected truncation of symbolic name string");
- rc = snprintf(connection->interface_name, INTERFACE_LEN, "%s", cmd->interfaceName);
- if (rc >= INTERFACE_LEN)
- WARN("[hc_connection_parse] Unexpected truncation of interface name string");
- return 0;
-}
-
-/* CONNECTION SNPRINTF */
-
-/* /!\ Please update constants in header file upon changes */
-int
-hc_connection_snprintf(char * s, size_t size, const hc_connection_t * connection)
-{
- char local[MAXSZ_URL];
- char remote[MAXSZ_URL];
- int rc;
-
- // assert(connection->connection_state)
-
- rc = url_snprintf(local, MAXSZ_URL, connection->family,
- &connection->local_addr, connection->local_port);
- if (rc >= MAXSZ_URL)
- WARN("[hc_connection_snprintf] Unexpected truncation of URL string");
- if (rc < 0)
- return rc;
- rc = url_snprintf(remote, MAXSZ_URL, connection->family,
- &connection->remote_addr, connection->remote_port);
- if (rc >= MAXSZ_URL)
- WARN("[hc_connection_snprintf] Unexpected truncation of URL string");
- if (rc < 0)
- return rc;
-
- return snprintf(s, size, "%s %s %s %s %s",
- connection_state_str[connection->state],
- connection->interface_name,
- local,
- remote,
- connection_type_str[connection->type]);
-}
-
-int hc_face_create(hc_sock_t *s, hc_face_t *face)
-{
- return s->hc_face_create(s, face);
-}
-
-int hc_face_get(hc_sock_t *s, hc_face_t *face, hc_face_t **face_found)
-{
- return s->hc_face_get(s, face, face_found);
-}
-
-int hc_face_delete(hc_sock_t *s, hc_face_t *face)
-{
- return s->hc_face_delete(s, face);
-}
-
-int hc_face_list(hc_sock_t *s, hc_data_t **pdata)
-{
- return s->hc_face_list(s, pdata);
-}
-
-int hc_face_list_async(hc_sock_t *s)
-{
- return s->hc_face_list_async(s);
-}
-
-int hc_face_set_admin_state(hc_sock_t * s, const char * conn_id_or_name, face_state_t state)
-{
- return s->hc_face_set_admin_state(s, conn_id_or_name, state);
-}
-
-#ifdef WITH_POLICY
-int hc_face_set_priority(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority)
-{
- return s->hc_face_set_priority(s, conn_id_or_name, priority);
-}
-
-int hc_face_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags)
-{
- return s->hc_face_set_tags(s, conn_id_or_name, tags);
-}
-#endif /* WITH_POLICY */
-
-/* /!\ Please update constants in header file upon changes */
-int
-hc_face_snprintf(char * s, size_t size, hc_face_t * face)
-{
- /* URLs are also big enough to contain IP addresses in the hICN case */
- char local[MAXSZ_URL];
- char remote[MAXSZ_URL];
-#ifdef WITH_POLICY
- char tags[MAXSZ_POLICY_TAGS];
-#endif /* WITH_POLICY */
- int rc;
-
- switch(face->face.type) {
- case FACE_TYPE_HICN:
- case FACE_TYPE_HICN_LISTENER:
- rc = ip_address_snprintf(local, MAXSZ_URL,
- &face->face.local_addr,
- face->face.family);
- if (rc >= MAXSZ_URL)
- WARN("[hc_face_snprintf] Unexpected truncation of URL string");
- if (rc < 0)
- return rc;
- rc = ip_address_snprintf(remote, MAXSZ_URL,
- &face->face.remote_addr,
- face->face.family);
- if (rc >= MAXSZ_URL)
- WARN("[hc_face_snprintf] Unexpected truncation of URL string");
- if (rc < 0)
- return rc;
- break;
- case FACE_TYPE_TCP:
- case FACE_TYPE_UDP:
- case FACE_TYPE_TCP_LISTENER:
- case FACE_TYPE_UDP_LISTENER:
- rc = url_snprintf(local, MAXSZ_URL, face->face.family,
- &face->face.local_addr,
- face->face.local_port);
- if (rc >= MAXSZ_URL)
- WARN("[hc_face_snprintf] Unexpected truncation of URL string");
- if (rc < 0)
- return rc;
- rc = url_snprintf(remote, MAXSZ_URL, face->face.family,
- &face->face.remote_addr,
- face->face.remote_port);
- if (rc >= MAXSZ_URL)
- WARN("[hc_face_snprintf] Unexpected truncation of URL string");
- if (rc < 0)
- return rc;
- break;
- default:
- return -1;
- }
-
- // [#ID NAME] TYPE LOCAL_URL REMOTE_URL STATE/ADMIN_STATE (TAGS)
-#ifdef WITH_POLICY
- rc = policy_tags_snprintf(tags, MAXSZ_POLICY_TAGS, face->face.tags);
- if (rc >= MAXSZ_POLICY_TAGS)
- WARN("[hc_face_snprintf] Unexpected truncation of policy tags string");
- if (rc < 0)
- return rc;
-
- return snprintf(s, size, "[#%d %s] %s %s %s %s %s/%s [%d] (%s)",
- face->id,
- face->name,
- face->face.netdevice.index != NETDEVICE_UNDEFINED_INDEX ? face->face.netdevice.name : "*",
- face_type_str[face->face.type],
- local,
- remote,
- face_state_str[face->face.state],
- face_state_str[face->face.admin_state],
- face->face.priority,
- tags);
-#else
- return snprintf(s, size, "[#%d %s] %s %s %s %s %s/%s",
- face->id,
- face->name,
- face->face.netdevice.index != NETDEVICE_UNDEFINED_INDEX ? face->face.netdevice.name : "*",
- face_type_str[face->face.type],
- local,
- remote,
- face_state_str[face->face.state],
- face_state_str[face->face.admin_state]);
-#endif /* WITH_POLICY */
-}
-
-int
-hc_connection_parse_to_face(void * in, hc_face_t * face)
-{
- hc_connection_t connection;
-
- if (hc_connection_parse(in, &connection) < 0) {
- ERROR("[hc_connection_parse_to_face] Could not parse connection");
- return -1;
- }
-
- if (hc_connection_to_face(&connection, face) < 0) {
- ERROR("[hc_connection_parse_to_face] Could not convert connection to face.");
- return -1;
- }
-
- return 0;
-}
-
-int hc_route_create(hc_sock_t * s, hc_route_t * route)
-{
- return s->hc_route_create(s, route);
-}
-
-int hc_route_delete(hc_sock_t * s, hc_route_t * route)
-{
- return s->hc_route_delete(s, route);
-}
-
-int hc_route_list(hc_sock_t * s, hc_data_t ** pdata)
-{
- return s->hc_route_list(s, pdata);
-}
-
-int hc_route_list_async(hc_sock_t * s)
-{
- return s->hc_route_list_async(s);
-}
-
-/* ROUTE PARSE */
-
-int
-hc_route_parse(void * in, hc_route_t * route)
-{
- list_routes_command * cmd = (list_routes_command *) in;
+ if (hc_sock_is_async(s) && !s->ops.get_fd) {
+ return -1; /* No async support */
+ }
- if (!IS_VALID_ADDR_TYPE(cmd->addressType)) {
- ERROR("[hc_route_parse] Invalid address type");
- return -1;
- }
+ // XXX no need to pass pdata to the request
+ // XXX sync socket, no multiplexed requests, no notifications
+ /*
+ * The request will contain all state needed to identify and demultiplex
+ * replies and notifications arriving on the socket. We assume there is at
+ * most a single request/reply in progress for a given request, and that
+ * requests involving multiple queries will run them sequentially. The use
+ * of a sequence number that is transported by the requests and reply is
+ * thus sufficient to disambiguate them.
+ */
+ hc_request_t *request = hc_sock_create_request(s, action, object_type, object,
+ callback, callback_data);
+ if (!request) {
+ goto ERR_REQUEST;
+ }
- int family = map_from_addr_type[cmd->addressType];
- if (!IS_VALID_FAMILY(family)) {
- ERROR("[hc_route_parse] Invalid address family");
- return -1;
+ if (hc_request_requires_object(request)) {
+ if (hc_object_is_empty(object) ||
+ hc_object_validate(object_type, object, true) < 0) {
+ goto ERR_VALIDATE;
}
-
- *route = (hc_route_t) {
- .face_id = cmd->connid,
- .family = family,
- .remote_addr = UNION_CAST(cmd->address, ip_address_t),
- .len = cmd->len,
- .cost = cmd->cost,
- };
- return 0;
-}
-
-/* ROUTE SNPRINTF */
-
-/* /!\ Please update constants in header file upon changes */
-int
-hc_route_snprintf(char * s, size_t size, hc_route_t * route)
-{
- /* interface cost prefix length */
-
- char prefix[MAXSZ_IP_ADDRESS];
- int rc;
-
- rc = ip_address_snprintf(prefix, MAXSZ_IP_ADDRESS, &route->remote_addr,
- route->family);
- if (rc >= MAXSZ_IP_ADDRESS)
- ;
- if (rc < 0)
- return rc;
-
- return snprintf(s, size, "%*d %*d %s %*d", MAXSZ_FACE_ID, route->face_id,
- MAXSZ_COST, route->cost, prefix, MAXSZ_LEN, route->len);
-}
-
-/* FACE -> LISTENER */
-
-int
-hc_face_to_listener(const hc_face_t * face, hc_listener_t * listener)
-{
- const face_t * f = &face->face;
-
- switch(f->type) {
- case FACE_TYPE_HICN_LISTENER:
- break;
- case FACE_TYPE_TCP_LISTENER:
- break;
- case FACE_TYPE_UDP_LISTENER:
- break;
- default:
- return -1;
+ } else {
+ if (object && !hc_object_is_empty(object)) {
+ goto ERR_CHECK;
}
- return -1; /* XXX Not implemented */
-}
-
-/* LISTENER -> FACE */
-
-int
-hc_listener_to_face(const hc_listener_t * listener, hc_face_t * face)
-{
- return -1; /* XXX Not implemented */
-}
-
-/* FACE -> CONNECTION */
-
-int
-hc_face_to_connection(const hc_face_t * face, hc_connection_t * connection, bool generate_name)
-{
- int rc;
- const face_t * f = &face->face;
+ }
- switch(f->type) {
- case FACE_TYPE_HICN:
- *connection = (hc_connection_t) {
- .type = CONNECTION_TYPE_HICN,
- .family = f->family,
- .local_addr = f->local_addr,
- .local_port = 0,
- .remote_addr = f->remote_addr,
- .remote_port = 0,
- .admin_state = face_state_to_connection_state(f->admin_state),
- .state = face_state_to_connection_state(f->state),
-#ifdef WITH_POLICY
- .priority = f->priority,
- .tags = f->tags,
-#endif /* WITH_POLICY */
- };
- rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "%s",
- f->netdevice.name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[hc_face_to_connection] Unexpected truncation of symbolic name string");
- break;
- case FACE_TYPE_TCP:
- *connection = (hc_connection_t) {
- .type = CONNECTION_TYPE_TCP,
- .family = f->family,
- .local_addr = f->local_addr,
- .local_port = f->local_port,
- .remote_addr = f->remote_addr,
- .remote_port = f->remote_port,
- .admin_state = face_state_to_connection_state(f->admin_state),
- .state = face_state_to_connection_state(f->state),
-#ifdef WITH_POLICY
- .priority = f->priority,
- .tags = f->tags,
-#endif /* WITH_POLICY */
- };
- if (generate_name) {
- rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "tcp%u", RANDBYTE());
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[hc_face_to_connection] Unexpected truncation of symbolic name string");
- } else {
- memset(connection->name, 0, SYMBOLIC_NAME_LEN);
- }
- break;
- case FACE_TYPE_UDP:
- *connection = (hc_connection_t) {
- .type = CONNECTION_TYPE_UDP,
- .family = AF_INET,
- .local_addr = f->local_addr,
- .local_port = f->local_port,
- .remote_addr = f->remote_addr,
- .remote_port = f->remote_port,
- .admin_state = face_state_to_connection_state(f->admin_state),
- .state = face_state_to_connection_state(f->state),
-#ifdef WITH_POLICY
- .priority = f->priority,
- .tags = f->tags,
-#endif /* WITH_POLICY */
- };
- if (generate_name) {
- rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "udp%u", RANDBYTE());
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[hc_face_to_connection] Unexpected truncation of symbolic name string");
- } else {
- memset(connection->name, 0, SYMBOLIC_NAME_LEN);
- }
- snprintf(connection->interface_name, INTERFACE_LEN, "%s",
- f->netdevice.name);
- break;
- default:
- return -1;
+ /* Workaround for non-fd based modules */
+ if (s->ops.prepare && s->ops.send && s->ops.recv && s->ops.process) {
+ if (hc_sock_on_init(s, request) < 0) goto ERR_INIT;
+
+ if (hc_sock_is_async(s)) return 0;
+
+ if (hc_sock_receive_all(s, pdata) < 0) goto ERR_RECV;
+ } else if (s->ops.prepare) {
+ // hc_data_t *data = hc_data_create(OBJECT_TYPE_LISTENER);
+ // hc_data_push(data, NULL);
+ // No nested requests for now...
+ ssize_t size = s->ops.prepare(s, request, NULL);
+ _ASSERT(size == 0); /* Done */
+ if (hc_request_is_complete(request)) {
+ if (pdata) {
+ *pdata = hc_request_get_data(request);
+ } else {
+ hc_request_reset_data(request);
+ }
+ hc_request_on_complete(request);
}
+ }
- rc = snprintf(connection->interface_name, INTERFACE_LEN, "%s",
- f->netdevice.name);
- if (rc >= INTERFACE_LEN)
- WARN("hc_face_to_connection] Unexpected truncation of interface name string");
+ return 0;
- return 0;
+ERR_RECV:
+ hc_request_reset_data(request);
+ERR_INIT:
+ hc_sock_free_request(s, request, true);
+ERR_CHECK:
+ERR_REQUEST:
+ERR_VALIDATE:
+ if (pdata) *pdata = NULL;
+ return -1;
}
-/* CONNECTION -> FACE */
-
-int
-hc_connection_to_face(const hc_connection_t * connection, hc_face_t * face)
-{
- int rc;
- switch (connection->type) {
- case CONNECTION_TYPE_TCP:
- *face = (hc_face_t) {
- .id = connection->id,
- .face = {
- .type = FACE_TYPE_TCP,
- .family = connection->family,
- .local_addr = connection->local_addr,
- .local_port = connection->local_port,
- .remote_addr = connection->remote_addr,
- .remote_port = connection->remote_port,
- .admin_state = connection_state_to_face_state(connection->admin_state),
- .state = connection_state_to_face_state(connection->state),
-#ifdef WITH_POLICY
- .priority = connection->priority,
- .tags = connection->tags,
-#endif /* WITH_POLICY */
- },
- };
- break;
- case CONNECTION_TYPE_UDP:
- *face = (hc_face_t) {
- .id = connection->id,
- .face = {
- .type = FACE_TYPE_UDP,
- .family = connection->family,
- .local_addr = connection->local_addr,
- .local_port = connection->local_port,
- .remote_addr = connection->remote_addr,
- .remote_port = connection->remote_port,
- .admin_state = connection_state_to_face_state(connection->admin_state),
- .state = connection_state_to_face_state(connection->state),
-#ifdef WITH_POLICY
- .priority = connection->priority,
- .tags = connection->tags,
-#endif /* WITH_POLICY */
- },
- };
- break;
- case CONNECTION_TYPE_HICN:
- *face = (hc_face_t) {
- .id = connection->id,
- .face = {
- .type = FACE_TYPE_HICN,
- .family = connection->family,
- .netdevice.index = NETDEVICE_UNDEFINED_INDEX, // XXX
- .local_addr = connection->local_addr,
- .remote_addr = connection->remote_addr,
- .admin_state = connection_state_to_face_state(connection->admin_state),
- .state = connection_state_to_face_state(connection->state),
-#ifdef WITH_POLICY
- .priority = connection->priority,
- .tags = connection->tags,
-#endif /* WITH_POLICY */
- },
- };
- break;
- default:
- return -1;
- }
- face->face.netdevice.name[0] = '\0';
- face->face.netdevice.index = 0;
- rc = snprintf(face->name, SYMBOLIC_NAME_LEN, "%s", connection->name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[hc_connection_to_face] Unexpected truncation of symbolic name string");
- rc = snprintf(face->face.netdevice.name, INTERFACE_LEN, "%s", connection->interface_name);
- if (rc >= INTERFACE_LEN)
- WARN("[hc_connection_to_face] Unexpected truncation of interface name string");
- netdevice_update_index(&face->face.netdevice);
- return 0;
+int hc_execute(hc_sock_t *s, hc_action_t action, hc_object_type_t object_type,
+ hc_object_t *object, hc_data_t **pdata) {
+ return _hc_execute(s, action, object_type, object, NULL, NULL, pdata);
}
-/* CONNECTION -> LISTENER */
-
-int
-hc_connection_to_local_listener(const hc_connection_t * connection, hc_listener_t * listener)
-{
- int rc;
- *listener = (hc_listener_t) {
- .id = ~0,
- .type = connection->type,
- .family = connection->family,
- .local_addr = connection->local_addr,
- .local_port = connection->local_port,
- };
- rc = snprintf(listener->name, SYMBOLIC_NAME_LEN, "lst%u", RANDBYTE()); // generate name
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[hc_connection_to_local_listener] Unexpected truncation of symbolic name string");
- rc = snprintf(listener->interface_name, INTERFACE_LEN, "%s", connection->interface_name);
- if (rc >= INTERFACE_LEN)
- WARN("[hc_connection_to_local_listener] Unexpected truncation of interface name string");
-
- return 0;
-}
-
-int hc_punting_create(hc_sock_t *s, hc_punting_t *punting)
-{
- return s->hc_punting_create(s, punting);
+int hc_execute_async(hc_sock_t *s, hc_action_t action,
+ hc_object_type_t object_type, hc_object_t *object,
+ hc_result_callback_t callback, void *callback_data) {
+ return _hc_execute(s, action, object_type, object, callback, callback_data,
+ NULL);
}
-int hc_punting_get(hc_sock_t *s, hc_punting_t *punting,
- hc_punting_t **punting_found)
-{
- return s->hc_punting_get(s, punting, punting_found);
-}
+/*----------------------------------------------------------------------------*
+ * VFT
+ *----------------------------------------------------------------------------*/
-int hc_punting_delete(hc_sock_t *s, hc_punting_t *punting)
-{
- return s->hc_punting_delete(s, punting);
+int hc_object_create(hc_sock_t *s, hc_object_type_t object_type,
+ hc_object_t *object) {
+ return hc_execute(s, ACTION_CREATE, object_type, object, NULL);
}
-int hc_punting_list(hc_sock_t *s, hc_data_t **pdata)
-{
- return s->hc_punting_list(s, pdata);
+int hc_object_get(hc_sock_t *s, hc_object_type_t object_type,
+ hc_object_t *object, hc_object_t **found) {
+ return hc_execute(s, ACTION_GET, object_type, object, NULL);
}
-int hc_punting_validate(const hc_punting_t * punting)
-{
- if (!IS_VALID_FAMILY(punting->family))
- return -1;
-
- /*
- * We might use the zero value to add punting on all faces but this is not
- * (yet) implemented
- */
- if (punting->face_id == 0) {
- ERROR("Punting on all faces is not (yet) implemented.");
- return -1;
+int hc_object_find(hc_sock_t *s, hc_object_type_t object_type, hc_data_t *data,
+ const hc_object_t *element, hc_object_t **found) {
+// XXX NOT IMPLEMENTED
+#if 0
+ foreach_type(hc_object_t, x, data) {
+ if (hc_object_cmp(x, element) == 0) {
+ *found = x;
+ return 0;
}
-
- return 0;
-}
-
-int hc_punting_cmp(const hc_punting_t * p1, const hc_punting_t * p2)
-{
- int rc;
-
- rc = INT_CMP(p1->face_id, p2->face_id);
- if (rc != 0)
- return rc;
-
- rc = INT_CMP(p1->family, p2->family);
- if (rc != 0)
- return rc;
-
- rc = ip_address_cmp(&p1->prefix, &p2->prefix, p1->family);
- if (rc != 0)
- return rc;
-
- rc = INT_CMP(p1->prefix_len, p2->prefix_len);
- if (rc != 0)
- return rc;
-
- return rc;
-}
-
-int hc_punting_parse(void * in, hc_punting_t * punting)
-{
- ERROR("hc_punting_parse not (yet) implemented.");
- return -1;
-}
-
-int hc_punting_snprintf(char * s, size_t size, hc_punting_t * punting)
-{
- ERROR("hc_punting_snprintf not (yet) implemented.");
- return -1;
-}
-
-int hc_cache_set_store(hc_sock_t *s, int enabled)
-{
- return s->hc_cache_set_store(s, enabled);
-}
-
-int hc_cache_set_serve(hc_sock_t *s, int enabled)
-{
- return s->hc_cache_set_serve(s, enabled);
-}
-
-int hc_strategy_list(hc_sock_t *s, hc_data_t **data)
-{
- return s->hc_strategy_list(s, data);
-}
-
-int hc_strategy_set(hc_sock_t *s /* XXX */)
-{
- return s->hc_strategy_set(s);
-}
-
-/* /!\ Please update constants in header file upon changes */
-int
-hc_strategy_snprintf(char * s, size_t size, hc_strategy_t * strategy)
-{
- return snprintf(s, size, "%s", strategy->name);
-}
-
-int hc_wldr_set(hc_sock_t *s /* XXX */)
-{
- return s->hc_wldr_set(s);
-}
-
-int hc_mapme_set(hc_sock_t *s, int enabled)
-{
- return s->hc_mapme_set(s, enabled);
-}
-
-int hc_mapme_set_discovery(hc_sock_t *s, int enabled)
-{
- return s->hc_mapme_set_discovery(s, enabled);
-}
-
-int hc_mapme_set_timescale(hc_sock_t *s, double timescale)
-{
- return s->hc_mapme_set_timescale(s, timescale);
-}
-
-int hc_mapme_set_retx(hc_sock_t *s, double timescale)
-{
- return s->hc_mapme_set_retx(s, timescale);
+ };
+#endif
+ *found = NULL; /* this is optional */
+ return 0;
}
-#ifdef WITH_POLICY
-
-/* POLICY PARSE */
-
-int
-hc_policy_parse(void * in, hc_policy_t * policy)
-{
- list_policies_command * cmd = (list_policies_command *) in;
-
- if (!IS_VALID_ADDR_TYPE(cmd->addressType))
- return -1;
-
- int family = map_from_addr_type[cmd->addressType];
- if (!IS_VALID_FAMILY(family))
- return -1;
-
- *policy = (hc_policy_t) {
- .family = family,
- .remote_addr = UNION_CAST(cmd->address, ip_address_t),
- .len = cmd->len,
- .policy = cmd->policy,
- };
- return 0;
+int hc_object_delete(hc_sock_t *s, hc_object_type_t object_type,
+ hc_object_t *object) {
+ return hc_execute(s, ACTION_DELETE, object_type, object, NULL);
}
-/* POLICY SNPRINTF */
-
-/* /!\ Please update constants in header file upon changes */
-int
-hc_policy_snprintf(char * s, size_t size, hc_policy_t * policy)
-{
- return 0;
+int hc_object_list(hc_sock_t *s, hc_object_type_t object_type,
+ hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, object_type, NULL, pdata);
}
-
-#endif /* WITH_POLICY */ \ No newline at end of file
diff --git a/ctrl/libhicnctrl/src/api_private.h b/ctrl/libhicnctrl/src/api_private.h
index 3922e1f3c..2f483ad2d 100644
--- a/ctrl/libhicnctrl/src/api_private.h
+++ b/ctrl/libhicnctrl/src/api_private.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,192 +17,62 @@
#define HICN_API_PRIVATE_H
#include <hicn/ctrl/api.h>
-#include <hicn/ctrl/commands.h>
#include <hicn/util/token.h>
#include <hicn/util/log.h>
#include <hicn/util/map.h>
+#ifndef HICN_VPP_PLUGIN
+#include <hicn/util/sstrncpy.h>
+#endif
+#include <hicn/validation.h>
+#include <ctype.h>
-#define INT_CMP(x, y) ((x > y) ? 1 : (x < y) ? -1 : 0)
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(*array))
-#if 0
-#ifdef __APPLE__
-#define RANDBYTE() (u8)(arc4random() & 0xFF)
-#else
-#define RANDBYTE() (u8)(random() & 0xFF)
-#endif
-#endif
-#define RANDBYTE() (u8)(rand() & 0xFF)
-
-hc_connection_type_t
-connection_type_from_str(const char * str);
-
-extern const hc_connection_type_t map_from_list_connections_type[];
-extern const hc_connection_type_t map_from_encap_type[];
-extern const connection_type map_to_connection_type[];
-extern const listener_mode map_to_listener_mode[];
-extern const hc_connection_state_t map_from_list_connections_state[];
-extern const int map_from_addr_type[];
-extern const address_type map_to_addr_type[];
-extern const char * connection_state_str[];
-extern const char * connection_type_str[];
-
-typedef enum {
- ENCAP_TCP,
- ENCAP_UDP,
- ENCAP_ETHER,
- ENCAP_LOCAL,
- ENCAP_HICN
-} EncapType;
-
-#define connection_state_to_face_state(x) ((face_state_t)(x))
-#define face_state_to_connection_state(x) ((hc_connection_state_t)(x))
+/*
+ * Input validation
+ */
+
+static inline bool IS_VALID_ADDRESS(const hicn_ip_address_t *addr, int family) {
+ char addr_str[INET6_ADDRSTRLEN];
+ return !hicn_ip_address_empty(addr) &&
+ hicn_ip_address_ntop(addr, addr_str, INET6_ADDRSTRLEN, family) >= 0;
+}
+
+static inline bool IS_VALID_PREFIX_LEN(u8 len) {
+ return len <= MAX_IPV6_PREFIX_LEN;
+}
+// https://github.com/shemminger/iproute2/blob/50b668bdbf0ebc270495eb4b352d0c3982159d0a/lib/utils.c#L825
+static inline bool IS_VALID_INTERFACE_NAME(const char *name) {
+ size_t len = strnlen_s(name, INTERFACE_LEN);
+ if (len == 0 || len >= IFNAMSIZ) return true;
+
+ while (*name) {
+ if (*name == '/' || isspace(*name)) return false;
+ ++name;
+ }
+
+ return true;
+}
+
+static inline bool IS_VALID_NAME(const char *name) {
+ return is_symbolic_name(name, SYMBOLIC_NAME_LEN);
+}
+
+static inline bool IS_VALID_STR_ID(const char *name) {
+ return is_number(name, SYMBOLIC_NAME_LEN);
+}
+
+#define IS_VALID_TYPE(x) IS_VALID_ENUM_TYPE(FACE_TYPE, x)
#define IS_VALID_ADDR_TYPE(x) ((x >= ADDR_INET) && (x <= ADDR_UNIX))
+#define IS_VALID_FACE_ID(x) ((x) != INVALID_FACE_ID)
-#define IS_VALID_CONNECTION_TYPE(x) IS_VALID_ENUM_TYPE(CONNECTION_TYPE, x)
+#define IS_VALID_ID(x) (1)
+#define IS_VALID_POLICY(x) (1)
typedef struct hc_sock_impl_s hc_sock_impl_t;
-int hc_data_ensure_available(hc_data_t * data, size_t count);
-u8 *hc_data_get_next(hc_data_t * data);
-int hc_data_set_error(hc_data_t * data);
-
-int
-hc_connection_parse_to_face(void * in, hc_face_t * face);
-
-int
-hc_listener_to_face(const hc_listener_t * listener, hc_face_t * face);
-
-int
-hc_connection_to_face(const hc_connection_t * connection, hc_face_t * face);
-
-int
-hc_face_to_listener(const hc_face_t * face, hc_listener_t * listener);
-
-int
-hc_connection_to_local_listener(const hc_connection_t * connection, hc_listener_t * listener);
-
-int
-hc_face_to_connection(const hc_face_t * face, hc_connection_t * connection, bool generate_name);
-
-struct hc_sock_s {
- int (*hc_sock_get_next_seq)(hc_sock_t *s);
- int (*hc_sock_set_nonblocking)(hc_sock_t *s);
- int (*hc_sock_get_fd)(hc_sock_t *s);
- int (*hc_sock_connect)(hc_sock_t *s);
- int (*hc_sock_get_available)(hc_sock_t *s, u8 **buffer, size_t *size);
- int (*hc_sock_send)(hc_sock_t *s, hc_msg_t *msg, size_t msglen, int seq);
- int (*hc_sock_recv)(hc_sock_t *s);
- int (*hc_sock_process)(hc_sock_t *s, hc_data_t **data);
- int (*hc_sock_callback)(hc_sock_t *s, hc_data_t **data);
- int (*hc_sock_reset)(hc_sock_t *s);
- void (*hc_sock_free)(hc_sock_t *s);
-
- int (*hc_listener_create)(hc_sock_t *s, hc_listener_t *listener);
- int (*hc_listener_create_async)(hc_sock_t *s, hc_listener_t *listener);
- int (*hc_listener_get)(hc_sock_t *s, hc_listener_t *listener,
- hc_listener_t **listener_found);
- int (*hc_listener_delete)(hc_sock_t *s, hc_listener_t *listener);
- int (*hc_listener_delete_async)(hc_sock_t *s, hc_listener_t *listener);
- int (*hc_listener_list)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_listener_list_async)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_listener_validate)(const hc_listener_t *listener);
- int (*hc_listener_cmp)(const hc_listener_t *l1, const hc_listener_t *l2);
- int (*hc_listener_parse)(void *in, hc_listener_t *listener);
-
- int (*hc_connection_create)(hc_sock_t *s, hc_connection_t *connection);
- int (*hc_connection_create_async)(hc_sock_t *s, hc_connection_t *connection);
- int (*hc_connection_get)(hc_sock_t *s, hc_connection_t *connection,
- hc_connection_t **connection_found);
- int (*hc_connection_update_by_id)(hc_sock_t *s, int hc_connection_id,
- hc_connection_t *connection);
- int (*hc_connection_update)(hc_sock_t *s, hc_connection_t *connection_current,
- hc_connection_t *connection_updated);
- int (*hc_connection_delete)(hc_sock_t *s, hc_connection_t *connection);
- int (*hc_connection_delete_async)(hc_sock_t *s, hc_connection_t *connection);
- int (*hc_connection_list)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_connection_list_async)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_connection_validate)(const hc_connection_t *connection);
- int (*hc_connection_cmp)(const hc_connection_t *c1, const hc_connection_t *c2);
- int (*hc_connection_parse)(void *in, hc_connection_t *connection);
- int (*hc_connection_set_admin_state)(hc_sock_t * s, const char * conn_id_or_name, face_state_t state);
- int (*hc_connection_set_admin_state_async)(hc_sock_t * s, const char * conn_id_or_name, face_state_t state);
-
-#ifdef WITH_POLICY
- int (*hc_connection_set_priority)(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority);
- int (*hc_connection_set_priority_async)(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority);
- int (*hc_connection_set_tags)(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags);
- int (*hc_connection_set_tags_async)(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags);
-#endif // WITH_POLICY
-
- int (*hc_connection_snprintf)(char *s, size_t size,
- const hc_connection_t *connection);
-
- int (*hc_face_create)(hc_sock_t *s, hc_face_t *face);
- int (*hc_face_get)(hc_sock_t *s, hc_face_t *face, hc_face_t **face_found);
- int (*hc_face_delete)(hc_sock_t *s, hc_face_t *face);
- int (*hc_face_list)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_face_list_async)(hc_sock_t *s);
- int (*hc_face_set_admin_state)(hc_sock_t * s, const char * conn_id_or_name, face_state_t state);
- int (*hc_face_set_admin_state_async)(hc_sock_t * s, const char * conn_id_or_name, face_state_t state);
-
-#ifdef WITH_POLICY
- int (*hc_face_set_priority)(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority);
- int (*hc_face_set_priority_async)(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority);
- int (*hc_face_set_tags)(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags);
- int (*hc_face_set_tags_async)(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags);
-#endif // WITH_POLICY
-
- int (*hc_face_snprintf)(char *s, size_t size, hc_face_t *face);
-
- int (*hc_route_parse)(void *in, hc_route_t *route);
- int (*hc_route_create)(hc_sock_t * s, hc_route_t * route);
- int (*hc_route_create_async)(hc_sock_t * s, hc_route_t * route);
- int (*hc_route_delete)(hc_sock_t * s, hc_route_t * route);
- int (*hc_route_delete_async)(hc_sock_t * s, hc_route_t * route);
- int (*hc_route_list)(hc_sock_t * s, hc_data_t ** pdata);
- int (*hc_route_list_async)(hc_sock_t * s);
-
- int (*hc_punting_create)(hc_sock_t *s, hc_punting_t *punting);
- int (*hc_punting_create_async)(hc_sock_t *s, hc_punting_t *punting);
- int (*hc_punting_get)(hc_sock_t *s, hc_punting_t *punting,
- hc_punting_t **punting_found);
- int (*hc_punting_delete)(hc_sock_t *s, hc_punting_t *punting);
- int (*hc_punting_list)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_punting_validate)(const hc_punting_t *punting);
- int (*hc_punting_cmp)(const hc_punting_t *c1, const hc_punting_t *c2);
- int (*hc_punting_parse)(void *in, hc_punting_t *punting);
-
- int (*hc_cache_set_store)(hc_sock_t *s, int enabled);
- int (*hc_cache_set_serve)(hc_sock_t *s, int enabled);
- int (*hc_cache_set_store_async)(hc_sock_t *s, int enabled);
- int (*hc_cache_set_serve_async)(hc_sock_t *s, int enabled);
-
- int (*hc_strategy_list)(hc_sock_t *s, hc_data_t **data);
- int (*hc_strategy_snprintf)(char *s, size_t size, hc_strategy_t *strategy);
- int (*hc_strategy_set)(hc_sock_t *s /* XXX */);
-
- int (*hc_wldr_set)(hc_sock_t *s /* XXX */);
-
- int (*hc_mapme_set)(hc_sock_t *s, int enabled);
- int (*hc_mapme_set_discovery)(hc_sock_t *s, int enabled);
- int (*hc_mapme_set_timescale)(hc_sock_t *s, double timescale);
- int (*hc_mapme_set_retx)(hc_sock_t *s, double timescale);
-
-#ifdef WITH_POLICY
- int (*hc_policy_parse)(void *in, hc_policy_t *policy);
- int (*hc_policy_create)(hc_sock_t *s, hc_policy_t *policy);
- int (*hc_policy_create_async)(hc_sock_t *s, hc_policy_t *policy);
- int (*hc_policy_delete)(hc_sock_t *s, hc_policy_t *policy);
- int (*hc_policy_delete_async)(hc_sock_t *s, hc_policy_t *policy);
- int (*hc_policy_list)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_policy_list_async)(hc_sock_t *s, hc_data_t **pdata);
- int (*hc_policy_snprintf)(char *s, size_t size, hc_policy_t *policy);
-#endif // WITH_POLICY
-
- // Reference to module containing the implementation
- void *handle;
-};
-
-#endif // HICN_API_PRIVATE_H \ No newline at end of file
+int hc_data_ensure_available(hc_data_t *data, size_t count);
+u8 *hc_data_get_next(hc_data_t *data);
+
+#endif // HICN_API_PRIVATE_H
diff --git a/ctrl/libhicnctrl/src/cli.c b/ctrl/libhicnctrl/src/cli.c
deleted file mode 100644
index 064eb77e3..000000000
--- a/ctrl/libhicnctrl/src/cli.c
+++ /dev/null
@@ -1,883 +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.
- */
-
-/**
- * \file cli.c
- * \brief Command line interface
- */
-#include <ctype.h> // isalpha isalnum
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h> // getopt
-
-#include <hicn/ctrl.h>
-#include <hicn/util/ip_address.h>
-#include <hicn/util/token.h>
-
-
-#define die(LABEL, MESSAGE) do { \
- printf(MESSAGE "\n"); \
- rc = -1; \
- goto ERR_ ## LABEL; \
-} while(0)
-
-#define foreach_object \
- _(UNDEFINED) \
- _(FACE) \
- _(ROUTE) \
- _(STRATEGY) \
- _(LISTENER) \
- _(CONNECTION) \
- _(N)
-
-typedef enum {
-#define _(x) OBJECT_ ## x,
-foreach_object
-#undef _
-} hc_object_t;
-
-#define HICNLIGHT_PARAM "hicnlight"
-#define VPP_PARAM "vpp"
-
-void
-usage_header()
-{
- fprintf(stderr, "Usage:\n");
-}
-
-void
-usage_face_create(const char * prog, bool header, bool verbose)
-{
-
- if (header)
- usage_header();
- fprintf(stderr, "%s -f TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT [INTERFACE_NAME]\n", prog);
- if (verbose)
- fprintf(stderr, " Create a face on specified address and port.\n");
-}
-
-void
-usage_face_delete(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -df ID\n", prog);
- //fprintf(stderr, "%s -df NAME\n", prog);
- fprintf(stderr, "%s -df TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT [INTERFACE_NAME]\n", prog);
- if (verbose)
- fprintf(stderr, " Delete a face...\n");
-}
-
-void
-usage_face_list(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -F\n", prog);
- if (verbose)
- fprintf(stderr, " List all faces.\n");
-}
-
-void
-usage_face(const char * prog, bool header, bool verbose)
-{
- usage_face_create(prog, header, verbose);
- usage_face_delete(prog, header, verbose);
- usage_face_list(prog, header, verbose);
-}
-
-void
-usage_route_create(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -r FACE_ID PREFIX [COST]\n", prog);
- //fprintf(stderr, "%s -r [FACE_ID|NAME] PREFIX [COST]\n", prog);
- if (verbose)
- fprintf(stderr, " Create a route...\n");
-}
-
-void
-usage_route_delete(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -dr FACE_ID PREFIX\n", prog);
- //fprintf(stderr, "%s -dr [FACE_ID|NAME] PREFIX\n", prog);
- if (verbose)
- fprintf(stderr, " Delete a route...\n");
-}
-
-void
-usage_route_list(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -R\n", prog);
- if (verbose)
- fprintf(stderr, " List all routes.\n");
-}
-
-void
-usage_route(const char * prog, bool header, bool verbose)
-{
- usage_route_create(prog, header, verbose);
- usage_route_delete(prog, header, verbose);
- usage_route_list(prog, header, verbose);
-}
-
-void
-usage_forwarding_strategy_create(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
-}
-void
-usage_forwarding_strategy_delete(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
-}
-
-void
-usage_forwarding_strategy_list(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -S\n", prog);
- if (verbose)
- fprintf(stderr, " List all availble forwarding strategies.\n");
-}
-
-void
-usage_forwarding_strategy(const char * prog, bool header, bool verbose)
-{
- usage_forwarding_strategy_create(prog, header, verbose);
- usage_forwarding_strategy_delete(prog, header, verbose);
- usage_forwarding_strategy_list(prog, header, verbose);
-}
-
-void
-usage_listener_create(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -l NAME TYPE LOCAL_ADDRESS LOCAL_PORT [INTERFACE_NAME]\n", prog);
- if (verbose)
- fprintf(stderr, " Create a listener on specified address and port.\n");
-}
-
-void
-usage_listener_delete(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -dl ID\n", prog);
- fprintf(stderr, "%s -dl NAME\n", prog);
- fprintf(stderr, "%s -dl TYPE LOCAL_ADDRESS LOCAL_PORT [INTERFACE_NAME]\n", prog);
- if (verbose)
- fprintf(stderr, " Delete a listener...\n");
-}
-
-void
-usage_listener_list(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -L\n", prog);
- if (verbose)
- fprintf(stderr, " List all listeners.\n");
-}
-
-void
-usage_listener(const char * prog, bool header, bool verbose)
-{
- usage_listener_create(prog, header, verbose);
- usage_listener_delete(prog, header, verbose);
- usage_listener_list(prog, header, verbose);
-}
-void
-usage_connection_create(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -c NAME TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT [INTERFACE_NAME]\n", prog);
- if (verbose)
- fprintf(stderr, " Create a connection on specified address and port.\n");
-}
-
-void
-usage_connection_delete(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -dc ID\n", prog);
- fprintf(stderr, "%s -dc NAME\n", prog);
- fprintf(stderr, "%s -dc TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT [INTERFACE_NAME]\n", prog);
- if (verbose)
- fprintf(stderr, " Delete a connection...\n");
-}
-
-void
-usage_connection_list(const char * prog, bool header, bool verbose)
-{
- if (header)
- usage_header();
- fprintf(stderr, "%s -C\n", prog);
- if (verbose)
- fprintf(stderr, " List all connections.\n");
-}
-
-void
-usage_connection(const char * prog, bool header, bool verbose)
-{
- usage_connection_create(prog, header, verbose);
- usage_connection_delete(prog, header, verbose);
- usage_connection_list(prog, header, verbose);
-}
-
-void usage(const char * prog)
-{
- fprintf(stderr, "Usage: %s [ -z forwarder (hicnlight | vpp) ] [ [-d] [-f|-l|-c|-r] PARAMETERS | [-F|-L|-C|-R] ]\n", prog);
- fprintf(stderr, "\n");
- fprintf(stderr, "High-level commands\n");
- fprintf(stderr, "\n");
- usage_face(prog, false, true);
- usage_route(prog, false, true);
- usage_forwarding_strategy(prog, false, true);
- fprintf(stderr, "\n");
- fprintf(stderr, "Low level commands (hicn-light specific)\n");
- fprintf(stderr, "\n");
- usage_listener(prog, false, true);
- usage_connection(prog, false, true);
-}
-
-typedef struct {
- hc_action_t action;
- hc_object_t object;
- union {
- hc_face_t face;
- hc_route_t route;
- hc_connection_t connection;
- hc_listener_t listener;
- };
-} hc_command_t;
-
-/**
- * Return true if string is purely an integer
- */
-static inline
-bool
-is_number(const char *string) {
- size_t len = strlen(string);
- for (size_t i = 0; i < len; i++)
- if (!isdigit(string[i]))
- return false;
- return true;
-}
-
-/**
- * A symbolic name must be at least 1 character and must begin with an alpha.
- * The remainder must be an alphanum.
- */
-static inline
-bool
-is_symbolic_name(const char *name)
-{
- size_t len = strlen(name);
- if (len <= 0)
- return false;
- if (!isalpha(name[0]))
- return false;
- for (size_t i = 1; i < len; i++) {
- if (!isalnum(name[i]))
- return false;
- }
- return true;
-}
-
-face_type_t
-face_type_from_str(const char * str)
-{
-#define _(x) \
- if (strcasecmp(str, STRINGIZE(x)) == 0) \
- return FACE_TYPE_ ## x; \
- else
-foreach_face_type
-#undef _
- return FACE_TYPE_UNDEFINED;
-}
-
-
-int
-parse_options(int argc, char *argv[], hc_command_t * command, forwarder_t *forwarder)
-{
- command->object = OBJECT_UNDEFINED;
- command->action = ACTION_CREATE;
- int opt;
- int family;
-
- while ((opt = getopt(argc, argv, "dflcrFLCRShz:")) != -1) {
- switch (opt) {
- case 'z' :
- if (strncmp(optarg, VPP_PARAM, strlen(VPP_PARAM)) == 0) {
- *forwarder = VPP;
- } else if (strncmp(optarg, HICNLIGHT_PARAM, strlen(HICNLIGHT_PARAM))) {
- *forwarder = HICNLIGHT;
- } else {
- usage(argv[0]);
- exit(EXIT_FAILURE);
- }
- break;
- case 'd':
- command->action = ACTION_DELETE;
- break;
- case 'f':
- command->object = OBJECT_FACE;
- break;
- case 'l':
- command->object = OBJECT_LISTENER;
- break;
- case 'c':
- command->object = OBJECT_CONNECTION;
- break;
- case 'r':
- command->object = OBJECT_ROUTE;
- break;
- case 'F':
- command->action = ACTION_LIST;
- command->object = OBJECT_FACE;
- break;
- case 'L':
- command->action = ACTION_LIST;
- command->object = OBJECT_LISTENER;
- break;
- case 'C':
- command->action = ACTION_LIST;
- command->object = OBJECT_CONNECTION;
- break;
- case 'R':
- command->action = ACTION_LIST;
- command->object = OBJECT_ROUTE;
- break;
- case 'S':
- command->action = ACTION_LIST;
- command->object = OBJECT_STRATEGY;
- break;
- default: /* "h" */
- usage(argv[0]);
- exit(EXIT_SUCCESS);
- }
- }
-
- if (command->object == OBJECT_UNDEFINED) {
- fprintf(stderr, "Missing object specification: connection | listener | route\n");
- return -1;
- }
-
- /* Parse and validate parameters for add/delete */
- switch(command->object) {
- case OBJECT_FACE:
- switch(command->action) {
- case ACTION_CREATE:
- if ((argc - optind != 5) && (argc - optind != 6)) {
- usage_face_create(argv[0], true, false);
- goto ERR_PARAM;
- }
- /* NAME will be autogenerated (and currently not used) */
- //snprintf(command->face.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- command->face.face.type = face_type_from_str(argv[optind++]);
- if (command->face.face.type == FACE_TYPE_UNDEFINED)
- goto ERR_PARAM;
- command->face.face.family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(command->face.face.family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->face.face.local_addr) < 0)
- goto ERR_PARAM;
- command->face.face.local_port = atoi(argv[optind++]);
- family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(family) || (command->face.face.family != family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->face.face.remote_addr) < 0)
- goto ERR_PARAM;
- command->face.face.remote_port = atoi(argv[optind++]);
- if (argc != optind) {
- //netdevice_set_name(&command->face.face.netdevice, argv[optind++]);
- command->face.face.netdevice.index = atoi(argv[optind++]);
- }
-
- break;
- case ACTION_DELETE:
- if ((argc - optind != 1) && (argc - optind != 5) && (argc - optind != 6)) {
- usage_face_delete(argv[0], true, false);
- goto ERR_PARAM;
- }
-
- if (argc - optind == 1) {
- /* Id or name */
- if (is_number(argv[optind])) {
- command->face.id = atoi(argv[optind++]);
- snprintf(command->face.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- //} else if (is_symbolic_name(argv[optind])) {
- // snprintf(command->face.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- } else {
- fprintf(stderr, "Invalid argument\n");
- goto ERR_PARAM;
- }
- } else {
- command->face.face.type = face_type_from_str(argv[optind++]);
- if (command->face.face.type == FACE_TYPE_UNDEFINED)
- goto ERR_PARAM;
- command->face.face.family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(command->face.face.family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->face.face.local_addr) < 0)
- goto ERR_PARAM;
- command->face.face.local_port = atoi(argv[optind++]);
- family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(family) || (command->face.face.family != family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->face.face.remote_addr) < 0)
- goto ERR_PARAM;
- command->face.face.remote_port = atoi(argv[optind++]);
- if (argc != optind) {
- command->face.face.netdevice.index = atoi(argv[optind++]);
- //netdevice_set_name(&command->face.face.netdevice, argv[optind++]);
- }
- }
- break;
-
- case ACTION_LIST:
- if (argc - optind != 0) {
- usage_face_list(argv[0], true, false);
- goto ERR_PARAM;
- }
- break;
-
- default:
- goto ERR_COMMAND;
- break;
- }
- break;
-
- case OBJECT_ROUTE:
- switch(command->action) {
- case ACTION_CREATE:
- if ((argc - optind != 2) && (argc - optind != 3)) {
- usage_route_create(argv[0], true, false);
- goto ERR_PARAM;
- }
-
- command->route.face_id = atoi(argv[optind++]);
-
- {
- ip_prefix_t prefix;
- ip_prefix_pton(argv[optind++], &prefix);
- command->route.family = prefix.family;
- command->route.remote_addr = prefix.address;
- command->route.len = prefix.len;
- }
-
- if (argc != optind) {
- printf("parse cost\n");
- command->route.cost = atoi(argv[optind++]);
- }
- break;
-
- case ACTION_DELETE:
- if (argc - optind != 2) {
- usage_route_delete(argv[0], true, false);
- goto ERR_PARAM;
- }
-
- command->route.face_id = atoi(argv[optind++]);
-
- {
- ip_prefix_t prefix;
- ip_prefix_pton(argv[optind++], &prefix);
- command->route.family = prefix.family;
- command->route.remote_addr = prefix.address;
- command->route.len = prefix.len;
- }
- break;
-
- case ACTION_LIST:
- if (argc - optind != 0) {
- usage_route_list(argv[0], true, false);
- goto ERR_PARAM;
- }
- break;
-
- default:
- goto ERR_COMMAND;
- break;
- }
- break;
-
- case OBJECT_STRATEGY:
- switch(command->action) {
- case ACTION_LIST:
- if (argc - optind != 0) {
- usage_forwarding_strategy_list(argv[0], true, false);
- goto ERR_PARAM;
- }
- break;
- default:
- goto ERR_COMMAND;
- break;
- }
- break;
-
- case OBJECT_LISTENER:
- switch(command->action) {
- case ACTION_CREATE:
- if ((argc - optind != 4) && (argc - optind != 5)) {
- usage_listener_create(argv[0], true, false);
- goto ERR_PARAM;
- }
- snprintf(command->listener.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- command->listener.type = connection_type_from_str(argv[optind++]);
- if (command->listener.type == CONNECTION_TYPE_UNDEFINED)
- goto ERR_PARAM;
- command->listener.family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(command->listener.family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->listener.local_addr) < 0)
- goto ERR_PARAM;
- command->listener.local_port = atoi(argv[optind++]);
- if (argc != optind) {
- snprintf(command->listener.interface_name, INTERFACE_LEN, "%s", argv[optind++]);
- }
- break;
-
- case ACTION_DELETE:
- if ((argc - optind != 1) && (argc - optind != 3) && (argc - optind != 4)) {
- usage_listener_delete(argv[0], true, false);
- goto ERR_PARAM;
- }
-
- if (argc - optind == 1) {
- /* Id or name */
- if (is_number(argv[optind])) {
- command->listener.id = atoi(argv[optind++]);
- snprintf(command->listener.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- } else if (is_symbolic_name(argv[optind])) {
- snprintf(command->listener.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- } else {
- fprintf(stderr, "Invalid argument\n");
- goto ERR_PARAM;
- }
- } else {
- command->listener.type = connection_type_from_str(argv[optind++]);
- if (command->listener.type == CONNECTION_TYPE_UNDEFINED)
- goto ERR_PARAM;
- command->listener.family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(command->listener.family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->listener.local_addr) < 0)
- goto ERR_PARAM;
- command->listener.local_port = atoi(argv[optind++]);
- if (argc != optind) {
- snprintf(command->listener.interface_name, INTERFACE_LEN, "%s", argv[optind++]);
- }
- }
- break;
-
- case ACTION_LIST:
- if (argc - optind != 0) {
- usage_listener_list(argv[0], true, false);
- goto ERR_PARAM;
- }
- break;
-
- default:
- goto ERR_COMMAND;
- break;
- }
- break;
-
- case OBJECT_CONNECTION:
- switch(command->action) {
- case ACTION_CREATE:
- /* NAME TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT */
- if ((argc - optind != 6) && (argc - optind != 7)) {
- usage_connection_create(argv[0], true, false);
- goto ERR_PARAM;
- }
- snprintf(command->connection.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- command->connection.type = connection_type_from_str(argv[optind++]);
- if (command->connection.type == CONNECTION_TYPE_UNDEFINED)
- goto ERR_PARAM;
- command->connection.family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(command->connection.family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->connection.local_addr) < 0)
- goto ERR_PARAM;
- command->connection.local_port = atoi(argv[optind++]);
- family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(family) || (command->connection.family != family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->connection.remote_addr) < 0)
- goto ERR_PARAM;
- command->connection.remote_port = atoi(argv[optind++]);
-
- break;
-
- case ACTION_DELETE:
- if ((argc - optind != 1) && (argc - optind != 5) && (argc - optind != 6)) {
- usage_connection_delete(argv[0], true, false);
- goto ERR_PARAM;
- }
-
- if (argc - optind == 1) {
- /* Id or name */
- if (is_number(argv[optind])) {
- command->connection.id = atoi(argv[optind++]);
- snprintf(command->connection.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- } else if (is_symbolic_name(argv[optind])) {
- snprintf(command->connection.name, SYMBOLIC_NAME_LEN, "%s", argv[optind++]);
- } else {
- fprintf(stderr, "Invalid argument\n");
- goto ERR_PARAM;
- }
- } else {
- command->connection.type = connection_type_from_str(argv[optind++]);
- if (command->connection.type == CONNECTION_TYPE_UNDEFINED)
- goto ERR_PARAM;
- command->connection.family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(command->connection.family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->connection.local_addr) < 0)
- goto ERR_PARAM;
- command->connection.local_port = atoi(argv[optind++]);
- family = ip_address_get_family(argv[optind]);
- if (!IS_VALID_FAMILY(family) || (command->connection.family != family))
- goto ERR_PARAM;
- if (ip_address_pton(argv[optind++], &command->connection.remote_addr) < 0)
- goto ERR_PARAM;
- command->connection.remote_port = atoi(argv[optind++]);
- }
- break;
-
- case ACTION_LIST:
- if (argc - optind != 0) {
- usage_connection_list(argv[0], true, false);
- goto ERR_PARAM;
- }
- break;
-
- default:
- goto ERR_COMMAND;
- break;
- }
- break;
-
- default:
- goto ERR_COMMAND;
- break;
- }
-
- return 0;
-
-ERR_PARAM:
-ERR_COMMAND:
- return -1;
-}
-
-int main(int argc, char *argv[])
-{
- hc_data_t * data;
- int rc = 1;
- hc_command_t command = {0};
- char buf_listener[MAXSZ_HC_LISTENER];
- char buf_connection[MAXSZ_HC_CONNECTION];
- char buf_route[MAXSZ_HC_ROUTE];
- char buf_strategy[MAXSZ_HC_STRATEGY];
-
- forwarder_t forwarder = HICNLIGHT;
-
- if (parse_options(argc, argv, &command, &forwarder) < 0)
- die(OPTIONS, "Bad arguments");
-
- hc_sock_t * s = hc_sock_create_forwarder(forwarder);
- if (!s)
- die(SOCKET, "Error creating socket.");
-
- if (hc_sock_connect(s) < 0)
- die(CONNECT, "Error connecting to the forwarder.");
-
- switch(command.object) {
- case OBJECT_FACE:
- switch(command.action) {
- case ACTION_CREATE:
- if (hc_face_create(s, &command.face) < 0)
- die(COMMAND, "Error creating face");
- printf("OK\n");
- break;
-
- case ACTION_DELETE:
- if (hc_face_delete(s, &command.face) < 0)
- die(COMMAND, "Error creating face");
- printf("OK\n");
- break;
-
- case ACTION_LIST:
- if (hc_face_list(s, &data) < 0)
- die(COMMAND, "Error getting connections.");
-
- printf("Faces:\n");
- foreach_face(f, data) {
- if (hc_face_snprintf(buf_connection, MAXSZ_HC_FACE, f) >= MAXSZ_HC_FACE)
- die(COMMAND, "Display error");
- printf("[%s] %s\n", f->name, buf_connection);
- }
-
- hc_data_free(data);
- break;
- default:
- die(COMMAND, "Unsupported command for connection");
- break;
- }
- break;
-
- case OBJECT_ROUTE:
- switch(command.action) {
- case ACTION_CREATE:
- if (hc_route_create(s, &command.route) < 0)
- die(COMMAND, "Error creating route");
- printf("OK\n");
- break;
-
- case ACTION_DELETE:
- if (hc_route_delete(s, &command.route) < 0)
- die(COMMAND, "Error creating route");
- printf("OK\n");
- break;
-
- case ACTION_LIST:
- if (hc_route_list(s, &data) < 0)
- die(COMMAND, "Error getting routes.");
-
- printf("Routes:\n");
- foreach_route(r, data) {
- if (hc_route_snprintf(buf_route, MAXSZ_HC_ROUTE, r) >= MAXSZ_HC_ROUTE)
- die(COMMAND, "Display error");
- printf("%s\n", buf_route);
- }
-
- hc_data_free(data);
- break;
- default:
- die(COMMAND, "Unsupported command for route");
- break;
- }
- break;
-
- case OBJECT_STRATEGY:
- switch(command.action) {
- case ACTION_LIST:
- if (hc_strategy_list(s, &data) < 0)
- die(COMMAND, "Error getting routes.");
-
- printf("Forwarding strategies:\n");
- foreach_strategy(st, data) {
- if (hc_strategy_snprintf(buf_strategy, MAXSZ_HC_STRATEGY, st) >= MAXSZ_HC_STRATEGY)
- die(COMMAND, "Display error");
- printf("%s\n", buf_strategy);
- }
-
- hc_data_free(data);
- break;
- default:
- die(COMMAND, "Unsupported command for strategy");
- break;
- }
- break;
-
- case OBJECT_LISTENER:
- switch(command.action) {
- case ACTION_CREATE:
- if (hc_listener_create(s, &command.listener) < 0)
- die(COMMAND, "Error creating listener");
- printf("OK\n");
- break;
- case ACTION_DELETE:
- if (hc_listener_delete(s, &command.listener) < 0)
- die(COMMAND, "Error deleting listener");
- printf("OK\n");
- break;
- break;
- case ACTION_LIST:
- if (hc_listener_list(s, &data) < 0)
- die(COMMAND, "Error getting listeners.");
-
- printf("Listeners:\n");
- foreach_listener(l, data) {
- if (hc_listener_snprintf(buf_listener, MAXSZ_HC_LISTENER+17, l) >= MAXSZ_HC_LISTENER)
- die(COMMAND, "Display error");
- printf("[%d] %s\n", l->id, buf_listener);
- }
-
- hc_data_free(data);
- break;
- default:
- die(COMMAND, "Unsupported command for listener");
- break;
- }
- break;
-
- case OBJECT_CONNECTION:
- switch(command.action) {
- case ACTION_CREATE:
- if (hc_connection_create(s, &command.connection) < 0)
- die(COMMAND, "Error creating connection");
- printf("OK\n");
- break;
- case ACTION_DELETE:
- if (hc_connection_delete(s, &command.connection) < 0)
- die(COMMAND, "Error creating connection");
- printf("OK\n");
- break;
- case ACTION_LIST:
- if (hc_connection_list(s, &data) < 0)
- die(COMMAND, "Error getting connections.");
-
- printf("Connections:\n");
- foreach_connection(c, data) {
- if (hc_connection_snprintf(buf_connection, MAXSZ_HC_CONNECTION, c) >= MAXSZ_HC_CONNECTION)
- die(COMMAND, "Display error");
- printf("[%s] %s\n", c->name, buf_connection);
- }
-
- hc_data_free(data);
- break;
- default:
- die(COMMAND, "Unsupported command for connection");
- break;
- }
- break;
-
- default:
- die(COMMAND, "Unsupported object");
- break;
- }
-
-ERR_COMMAND:
-ERR_CONNECT:
- hc_sock_free(s);
-ERR_SOCKET:
-ERR_OPTIONS:
- return (rc < 0) ? EXIT_FAILURE : EXIT_SUCCESS;
-}
diff --git a/ctrl/libhicnctrl/src/cli.h b/ctrl/libhicnctrl/src/cli.h
new file mode 100644
index 000000000..b04448a6e
--- /dev/null
+++ b/ctrl/libhicnctrl/src/cli.h
@@ -0,0 +1,4 @@
+#include <hicn/ctrl.h>
+
+typedef int (*command_function)(hc_sock_t *, hc_command_t *);
+extern command_function command_vft[][ACTION_N];
diff --git a/ctrl/libhicnctrl/src/command.c b/ctrl/libhicnctrl/src/command.c
new file mode 100644
index 000000000..77b6eb7e8
--- /dev/null
+++ b/ctrl/libhicnctrl/src/command.c
@@ -0,0 +1,127 @@
+
+/**
+ * @file command.c
+ * @brief Implementation of commands.
+ */
+
+#ifdef __linux__
+#define _GNU_SOURCE
+#endif /* __linux__ */
+#include <search.h> /* tfind, tdestroy, twalk */
+#include <stdio.h>
+#include <ctype.h>
+#include <hicn/ctrl/command.h>
+
+#include <hicn/util/log.h>
+
+#include <hicn/ctrl/parse.h>
+
+/* Commands are registered in the following tree. */
+static void *commands_root = NULL; /**< Tree ordered by name */
+
+#ifdef __linux__
+static void nothing_to_free() {}
+
+__attribute__((destructor)) static void command_clear() {
+ tdestroy(commands_root, nothing_to_free);
+}
+#endif /* __linux__ */
+
+static int _command_compare(const command_parser_t *c1,
+ const command_parser_t *c2) {
+ if (c1->object_type != c2->object_type)
+ return c2->object_type - c1->object_type;
+ if (c1->action != c2->action) return c2->action - c1->action;
+ if (c1->nparams != c2->nparams) return c2->nparams - c1->nparams;
+ return 0;
+}
+
+#define command_compare (int (*)(const void *, const void *))(_command_compare)
+
+void command_register(const command_parser_t *command) {
+ // Insert the command in the tree if the keys does not exist yet
+ tsearch(command, &commands_root, command_compare);
+}
+
+const command_parser_t *command_search(const hc_action_t action,
+ hc_object_type_t object_type,
+ unsigned nparams) {
+ command_parser_t **command, search;
+
+ search.action = action;
+ search.object_type = object_type;
+ search.nparams = nparams;
+ command = tfind(&search, &commands_root, command_compare);
+
+ return command ? *command : NULL;
+}
+
+static inline void to_lowercase(char *p) {
+ for (; *p; ++p) *p = tolower(*p);
+}
+
+typedef struct {
+ hc_object_type_t object_type;
+ hc_action_t action;
+} cmd_search_params_t;
+
+static hc_object_type_t prev_obj = OBJECT_TYPE_UNDEFINED;
+static hc_action_t prev_action = ACTION_UNDEFINED;
+static void traversal_action(const void *nodep, VISIT which,
+ void *cmd_params0) {
+ cmd_search_params_t *cmd_params = cmd_params0;
+
+ // Execute this function during inorder traversal
+ if (which != postorder && which != leaf) return;
+
+ command_parser_t *datap;
+ datap = *(command_parser_t **)nodep;
+ char *obj_str = strdup(object_type_str(datap->object_type));
+ to_lowercase(obj_str);
+
+ // List all objects
+ if (cmd_params->object_type == OBJECT_TYPE_UNDEFINED &&
+ cmd_params->action == ACTION_UNDEFINED) {
+ if (datap->object_type == prev_obj) goto FREE_STR;
+ prev_obj = datap->object_type;
+
+ printf("\thelp %s\n", obj_str);
+ goto FREE_STR;
+ }
+
+ // List actions for specific object
+ if (datap->object_type != cmd_params->object_type) goto FREE_STR;
+ if (cmd_params->action == ACTION_UNDEFINED) {
+ if (datap->action == prev_action) goto FREE_STR;
+ prev_action = datap->action;
+
+ printf("\thelp %s %s\n", obj_str, action_to_cmd_action(datap->action));
+ goto FREE_STR;
+ }
+
+ // List commands for specific object and action
+ if (datap->action != cmd_params->action) goto FREE_STR;
+ printf(" %s %s ", action_to_cmd_action(datap->action), obj_str);
+ for (int i = 0; i < datap->nparams; i++)
+ printf("<%s> ", datap->parameters[i].name);
+ printf("\n\n");
+ // List options' details
+ if (datap->nparams == 0) goto FREE_STR;
+ for (int i = 0; i < datap->nparams; i++)
+ printf("%16s: %s\n", datap->parameters[i].name, datap->parameters[i].help);
+ printf("\n");
+
+FREE_STR:
+ free(obj_str);
+}
+
+void command_list(hc_object_type_t object_type, hc_action_t action) {
+#if defined(__linux__) && !defined(__ANDROID__)
+ cmd_search_params_t cmd_params = {.object_type = object_type,
+ .action = action};
+ twalk_r(commands_root, traversal_action, &cmd_params);
+#else
+ fprintf(stderr, "twalk_r() function only available on linux");
+ (void)traversal_action;
+#endif
+}
diff --git a/ctrl/libhicnctrl/src/commands/command_cache.c b/ctrl/libhicnctrl/src/commands/command_cache.c
new file mode 100644
index 000000000..22cb8baaa
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_cache.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_cache.h
+ * \brief Implementation of cache command.
+ */
+
+#include <math.h>
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define serve \
+ { \
+ .name = "serve", \
+ .help = \
+ "Enables/disables replies from local content store. Either the " \
+ "string 'on' or 'off'", \
+ .type = TYPE_ON_OFF, .offset = offsetof(hc_cache_t, serve), \
+ }
+
+#define store \
+ { \
+ .name = "store", \
+ .help = \
+ "enables/disables the storage of incoming data packets in the local " \
+ "content store. Either the string 'on' or 'off'", \
+ .type = TYPE_ON_OFF, .offset = offsetof(hc_cache_t, store), \
+ }
+
+/* Commands */
+
+static const command_parser_t command_cache_set_serve = {
+ .action = ACTION_SERVE,
+ .object_type = OBJECT_TYPE_CACHE,
+ .nparams = 1,
+ .parameters = {serve},
+};
+COMMAND_REGISTER(command_cache_set_serve);
+
+static const command_parser_t command_cache_set_store = {
+ .action = ACTION_STORE,
+ .object_type = OBJECT_TYPE_CACHE,
+ .nparams = 1,
+ .parameters = {store},
+};
+COMMAND_REGISTER(command_cache_set_store);
+
+static const command_parser_t command_cache_clear = {
+ .action = ACTION_CLEAR,
+ .object_type = OBJECT_TYPE_CACHE,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_cache_clear);
+
+static const command_parser_t command_cache_list = {
+ .action = ACTION_LIST,
+ .object_type = OBJECT_TYPE_CACHE,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_cache_list);
diff --git a/ctrl/libhicnctrl/src/commands/command_connection.c b/ctrl/libhicnctrl/src/commands/command_connection.c
new file mode 100644
index 000000000..a43934fdf
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_connection.c
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_connection.h
+ * \brief Implementation of connection command.
+ */
+#include <math.h>
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define type_hicn \
+ { \
+ .name = "type", .help = "connection type (hICN)", \
+ .type = TYPE_ENUM(face_type), .offset = offsetof(hc_connection_t, type), \
+ }
+
+#define type_tcp_udp \
+ { \
+ .name = "type", .help = "connection type [tcp | udp]", \
+ .type = TYPE_ENUM(face_type), .offset = offsetof(hc_connection_t, type), \
+ }
+
+#define symbolic \
+ { \
+ .name = "symbolic", \
+ .help = "symbolic name, e.g. 'conn1' (must be unique, start with alpha)", \
+ .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_connection_t, name), \
+ }
+
+#define local_address \
+ { \
+ .name = "local_addr", .help = "local IP address on which to bind.", \
+ .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_connection_t, local_addr), \
+ .offset2 = offsetof(hc_connection_t, family), \
+ }
+
+#define local_port \
+ { \
+ .name = "local_port", .help = "Local port.", \
+ .type = TYPE_UINT16(1, UINT16_MAX), \
+ .offset = offsetof(hc_connection_t, local_port), \
+ }
+
+#define remote_address \
+ { \
+ .name = "remote_address", \
+ .help = "The IPv4 or IPv6 or hostname of the remote system.", \
+ .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_connection_t, remote_addr), \
+ .offset2 = offsetof(hc_connection_t, family), \
+ }
+
+#define remote_port \
+ { \
+ .name = "remote_port", .help = "Remote port.", \
+ .type = TYPE_UINT16(1, UINT16_MAX), \
+ .offset = offsetof(hc_connection_t, remote_port), \
+ }
+
+#define interface \
+ { \
+ .name = "interface", .help = "Interface on which to bind", \
+ .type = TYPE_INTERFACE_NAME, \
+ .offset = offsetof(hc_connection_t, interface_name), \
+ }
+
+#define symbolic_or_id \
+ { \
+ .name = "symbolic", .help = "The connection symbolic name or id", \
+ .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_connection_t, name), \
+ }
+
+/* Commands */
+
+int on_connection_create(hc_connection_t* connection) {
+ connection->admin_state = FACE_STATE_UP;
+ return 0;
+}
+
+#if 0
+static command_parser_t command_connection_create4 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_CONNECTION,
+ .nparams = 4,
+ .parameters = {type_hicn, symbolic, local_address, remote_address},
+ .post_hook = (parser_hook_t)on_connection_create,
+};
+COMMAND_REGISTER(command_connection_create4);
+
+static const command_parser_t command_connection_create5 = {
+ .action = ACTION_CREATE,
+ .object = OBJECT_TYPE_CONNECTION,
+ .nparams = 5,
+ .parameters = {type_hicn, symbolic, local_address, remote_address,
+ interface},
+ .post_hook = (parser_hook_t)on_connection_create,
+};
+COMMAND_REGISTER(command_connection_create5);
+#endif
+
+static const command_parser_t command_connection_create4 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_CONNECTION,
+ .nparams = 4,
+ .parameters = {type_tcp_udp, symbolic, remote_address, remote_port},
+ .post_hook = (parser_hook_t)on_connection_create,
+};
+COMMAND_REGISTER(command_connection_create4);
+
+static const command_parser_t command_connection_create5 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_CONNECTION,
+ .nparams = 5,
+ .parameters = {type_tcp_udp, symbolic, remote_address, remote_port,
+ interface},
+ .post_hook = (parser_hook_t)on_connection_create,
+};
+COMMAND_REGISTER(command_connection_create5);
+
+static const command_parser_t command_connection_create6 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_CONNECTION,
+ .nparams = 6,
+ .parameters = {type_tcp_udp, symbolic, local_address, local_port,
+ remote_address, remote_port},
+ .post_hook = (parser_hook_t)on_connection_create,
+};
+COMMAND_REGISTER(command_connection_create6);
+
+static const command_parser_t command_connection_create7 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_CONNECTION,
+ .nparams = 7,
+ .parameters = {type_tcp_udp, symbolic, local_address, local_port,
+ remote_address, remote_port, interface},
+ .post_hook = (parser_hook_t)on_connection_create,
+};
+COMMAND_REGISTER(command_connection_create7);
+
+static const command_parser_t command_connection_list = {
+ .action = ACTION_LIST,
+ .object_type = OBJECT_TYPE_CONNECTION,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_connection_list);
+
+static const command_parser_t command_connection_remove = {
+ .action = ACTION_DELETE,
+ .object_type = OBJECT_TYPE_CONNECTION,
+ .nparams = 1,
+ .parameters = {symbolic_or_id},
+};
+COMMAND_REGISTER(command_connection_remove);
diff --git a/ctrl/libhicnctrl/src/commands/command_face.c b/ctrl/libhicnctrl/src/commands/command_face.c
new file mode 100644
index 000000000..e383de1b5
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_face.c
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_face.h
+ * \brief Implementation of face command.
+ */
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define type_hicn \
+ { \
+ .name = "type", .help = "face type (hICN)", .type = TYPE_ENUM(face_type), \
+ .offset = offsetof(hc_face_t, type), \
+ }
+
+#define type_tcp_udp \
+ { \
+ .name = "type", .help = "face type [tcp | udp]", \
+ .type = TYPE_ENUM(face_type), .offset = offsetof(hc_face_t, type), \
+ }
+
+#define local_address \
+ { \
+ .name = "local_addr", .help = "local IP address on which to bind.", \
+ .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_face_t, local_addr), \
+ .offset2 = offsetof(hc_face_t, family), \
+ }
+
+#define local_port \
+ { \
+ .name = "local_port", .help = "Local port.", \
+ .type = TYPE_UINT16(1, UINT16_MAX), \
+ .offset = offsetof(hc_face_t, local_port), \
+ }
+
+#define remote_address \
+ { \
+ .name = "remote_address", \
+ .help = "The IPv4 or IPv6 or hostname of the remote system.", \
+ .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_face_t, remote_addr), \
+ .offset2 = offsetof(hc_face_t, family), \
+ }
+
+#define remote_port \
+ { \
+ .name = "remote_port", .help = "Remote port.", \
+ .type = TYPE_UINT16(1, UINT16_MAX), \
+ .offset = offsetof(hc_face_t, remote_port), \
+ }
+
+#define interface \
+ { \
+ .name = "interface", .help = "Interface on which to bind", \
+ .type = TYPE_INTERFACE_NAME, \
+ .offset = offsetof(hc_face_t, netdevice.name), \
+ }
+
+#define symbolic_or_id \
+ { \
+ .name = "symbolic", .help = "The face symbolic name or id", \
+ .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_face_t, name), \
+ }
+
+/* Commands */
+
+int on_face_create(hc_face_t* face) {
+ face->admin_state = FACE_STATE_UP;
+ face->id = INVALID_FACE_ID;
+ return 0;
+}
+
+#if 0
+static command_parser_t command_face_create3 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 3,
+ .parameters = {type_hicn, local_address, remote_address},
+ .post_hook = (parser_hook_t)on_face_create,
+};
+COMMAND_REGISTER(command_face_create3);
+
+static const command_parser_t command_face_create4 = {
+ .action = ACTION_CREATE,
+ .object = OBJECT_TYPE_FACE,
+ .nparams = 4,
+ .parameters = {type_hicn, local_address, remote_address,
+ interface},
+ .post_hook = (parser_hook_t)on_face_create,
+};
+COMMAND_REGISTER(command_face_create4);
+#endif
+
+static const command_parser_t command_face_create3 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 3,
+ .parameters = {type_tcp_udp, remote_address, remote_port},
+ .post_hook = (parser_hook_t)on_face_create,
+};
+COMMAND_REGISTER(command_face_create3);
+
+static const command_parser_t command_face_create4 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 4,
+ .parameters = {type_tcp_udp, remote_address, remote_port, interface},
+ .post_hook = (parser_hook_t)on_face_create,
+};
+COMMAND_REGISTER(command_face_create4);
+
+static const command_parser_t command_face_create5 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 5,
+ .parameters = {type_tcp_udp, local_address, local_port, remote_address,
+ remote_port},
+ .post_hook = (parser_hook_t)on_face_create,
+};
+COMMAND_REGISTER(command_face_create5);
+
+static const command_parser_t command_face_create6 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 6,
+ .parameters = {type_tcp_udp, local_address, local_port, remote_address,
+ remote_port, interface},
+ .post_hook = (parser_hook_t)on_face_create,
+};
+COMMAND_REGISTER(command_face_create6);
+
+static const command_parser_t command_face_list = {
+ .action = ACTION_LIST,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_face_list);
+
+static const command_parser_t command_face_remove6 = {
+ .action = ACTION_DELETE,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 6,
+ .parameters = {type_tcp_udp, local_address, local_port, remote_address,
+ remote_port, interface},
+};
+COMMAND_REGISTER(command_face_remove6);
+
+static const command_parser_t command_face_remove1 = {
+ .action = ACTION_DELETE,
+ .object_type = OBJECT_TYPE_FACE,
+ .nparams = 1,
+ .parameters = {symbolic_or_id},
+};
+COMMAND_REGISTER(command_face_remove1);
diff --git a/ctrl/libhicnctrl/src/commands/command_listener.c b/ctrl/libhicnctrl/src/commands/command_listener.c
new file mode 100644
index 000000000..604c0a672
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_listener.c
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_listener.h
+ * \brief Implementation of listener command.
+ */
+#include <math.h>
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define protocol_hicn \
+ { \
+ .name = "protocol", .help = "Protocol [hicn].", \
+ .type = TYPE_ENUM(face_type), .offset = offsetof(hc_listener_t, type), \
+ }
+
+#define protocol_tcp_udp \
+ { \
+ .name = "protocol", .help = "Protocol [tcp | udp]", \
+ .type = TYPE_ENUM(face_type), .offset = offsetof(hc_listener_t, type), \
+ }
+
+#define symbolic \
+ { \
+ .name = "symbolic", \
+ .help = \
+ "User defined name for listener, must start with alpha and be " \
+ "alphanum", \
+ .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_listener_t, name), \
+ }
+
+#define local_address \
+ { \
+ .name = "local_addr", \
+ .help = \
+ "IPv4 or IPv6 address (or prefix protocol = hicn) assigend to the " \
+ "local interface", \
+ .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_listener_t, local_addr), \
+ .offset2 = offsetof(hc_listener_t, family), \
+ }
+
+#define local_port \
+ { \
+ .name = "local_port", .help = "Local port.", \
+ .type = TYPE_UINT16(1, UINT16_MAX), \
+ .offset = offsetof(hc_listener_t, local_port), \
+ }
+
+#define interface \
+ { \
+ .name = "interface", .help = "Interface on which to bind", \
+ .type = TYPE_INTERFACE_NAME, \
+ .offset = offsetof(hc_listener_t, interface_name), \
+ }
+
+#define symbolic_or_id \
+ { \
+ .name = "symbolic", .help = "The listener symbolic name or id", \
+ .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_listener_t, name), \
+ }
+
+/* Commands */
+
+/* The parse sets the wrong face_type_t for listener, we fix that here */
+int on_listener_create(hc_listener_t* listener) {
+ switch (listener->type) {
+ case FACE_TYPE_UDP:
+ listener->type = FACE_TYPE_UDP_LISTENER;
+ break;
+ case FACE_TYPE_TCP:
+ listener->type = FACE_TYPE_TCP_LISTENER;
+ break;
+ case FACE_TYPE_HICN:
+ listener->type = FACE_TYPE_HICN_LISTENER;
+ break;
+ case FACE_TYPE_UDP_LISTENER:
+ case FACE_TYPE_TCP_LISTENER:
+ case FACE_TYPE_HICN_LISTENER:
+ break;
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_N:
+ return -1;
+ }
+ return 0;
+}
+
+#if 0
+static const command_parser_t command_listener_create4 = {
+ .action = ACTION_CREATE,
+ .object = OBJECT_TYPE_LISTENER,
+ .nparams = 4,
+ .parameters = {protocol_hicn, symbolic, local_address, interface},
+ .post_hook = (parser_hook_t)on_listener_create,
+};
+COMMAND_REGISTER(command_listener_create4);
+#endif
+
+static const command_parser_t command_listener_create4 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_LISTENER,
+ .nparams = 4,
+ .parameters = {protocol_tcp_udp, symbolic, local_address, local_port},
+ .post_hook = (parser_hook_t)on_listener_create,
+};
+COMMAND_REGISTER(command_listener_create4);
+
+static const command_parser_t command_listener_create5 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_LISTENER,
+ .nparams = 5,
+ .parameters = {protocol_tcp_udp, symbolic, local_address, local_port,
+ interface},
+ .post_hook = (parser_hook_t)on_listener_create,
+};
+COMMAND_REGISTER(command_listener_create5);
+
+static const command_parser_t command_listener_list = {
+ .action = ACTION_LIST,
+ .object_type = OBJECT_TYPE_LISTENER,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_listener_list);
+
+static const command_parser_t command_listener_remove = {
+ .action = ACTION_DELETE,
+ .object_type = OBJECT_TYPE_LISTENER,
+ .nparams = 1,
+ .parameters = {symbolic_or_id},
+};
+COMMAND_REGISTER(command_listener_remove);
diff --git a/ctrl/libhicnctrl/src/commands/command_mapme.c b/ctrl/libhicnctrl/src/commands/command_mapme.c
new file mode 100644
index 000000000..7dcca038c
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_mapme.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_mapme.h
+ * \brief Implementation of mapme command.
+ */
+#include <math.h>
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define target \
+ { \
+ .name = "target", \
+ .help = \
+ "Target for the set action, e.g. enable, discovery, timescale, retx", \
+ .type = TYPE_ENUM(mapme_target), .offset = offsetof(hc_mapme_t, target), \
+ }
+
+#define value \
+ { \
+ .name = "value", \
+ .help = "Value to set for the target, e.g. 'on', 'off', milliseconds", \
+ .type = TYPE_STRN(4), .offset = offsetof(hc_mapme_t, unparsed_arg), \
+ }
+
+#define prefix \
+ { \
+ .name = "prefix", \
+ .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \
+ .type = TYPE_IP_PREFIX, .offset = offsetof(hc_mapme_t, address), \
+ .offset2 = offsetof(hc_mapme_t, len), \
+ .offset3 = offsetof(hc_mapme_t, family), \
+ }
+
+/* Commands */
+
+// Parse the raw string argument into 'timescale' or 'enabled',
+// necessary since the command dispatch is based on the number
+// of arguments and not their type
+int parse_args(hc_mapme_t* mapme) {
+ mapme->timescale = atoi(mapme->unparsed_arg);
+
+ if (strcasecmp(mapme->unparsed_arg, "off") == 0) mapme->enabled = 0;
+ if (strcasecmp(mapme->unparsed_arg, "on") == 0) mapme->enabled = 1;
+
+ return 0;
+}
+
+static const command_parser_t command_mapme_set = {
+ .action = ACTION_SET,
+ .object_type = OBJECT_TYPE_MAPME,
+ .nparams = 2,
+ .parameters = {target, value},
+ .post_hook = (parser_hook_t)parse_args,
+};
+COMMAND_REGISTER(command_mapme_set);
+
+static const command_parser_t command_mapme_update = {
+ .action = ACTION_UPDATE,
+ .object_type = OBJECT_TYPE_MAPME,
+ .nparams = 1,
+ .parameters = {prefix},
+};
+COMMAND_REGISTER(command_mapme_update);
diff --git a/ctrl/libhicnctrl/src/commands/command_policy.c b/ctrl/libhicnctrl/src/commands/command_policy.c
new file mode 100644
index 000000000..eaf949880
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_policy.c
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_policy.h
+ * \brief Implementation of policy command.
+ */
+
+#if 0
+#include <hicn/policy.h>
+
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define prefix \
+ { \
+ .name = "prefix", \
+ .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \
+ .type = TYPE_IP_PREFIX, .offset = offsetof(hc_policy_t, remote_addr), \
+ .offset2 = offsetof(hc_policy_t, len), \
+ .offset3 = offsetof(hc_policy_t, family), \
+ }
+
+#define app_name \
+ { \
+ .name = "app_name", \
+ .help = "The application name associated to this policy", \
+ .type = TYPE_STR, .offset = offsetof(hc_policy_t, policy.app_name), \
+ }
+
+/* Commands */
+
+static const command_parser_t command_policy_create = {
+ .action = ACTION_CREATE,
+ .object = OBJECT_POLICY,
+ .nparams = 2 + POLICY_TAG_N,
+ .parameters = {prefix, app_name,
+#define _(x, y) \
+ { \
+ .name = "flag:" #x, \
+ .help = \
+ "A value among [neutral|require|prefer|avoid|prohibit] with an " \
+ "optional '!' character prefix for disabling changes", \
+ .type = TYPE_POLICY_STATE(POLICY_TAG_##x), \
+ .offset = offsetof(hc_policy_t, policy.tags), \
+ },
+ foreach_policy_tag
+#undef _
+ },
+};
+COMMAND_REGISTER(command_policy_create);
+
+static const command_parser_t command_policy_list = {
+ .action = ACTION_LIST,
+ .object = OBJECT_POLICY,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_policy_list);
+#endif
diff --git a/ctrl/libhicnctrl/src/commands/command_punting.c b/ctrl/libhicnctrl/src/commands/command_punting.c
new file mode 100644
index 000000000..a274583b1
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_punting.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_punting.h
+ * \brief Implementation of punting command.
+ */
+
+#if 0
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define symbolic_or_id \
+ { \
+ .name = "symbolic_or_id", \
+ .help = \
+ "The symbolic name for an egress, or the egress punting id (see " \
+ "'help list puntings')", \
+ .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_punting_t, face_id), \
+ }
+
+#define prefix \
+ { \
+ .name = "prefix", \
+ .help = "Prefix to add as a punting rule. (example 1234::0/64)", \
+ .type = TYPE_IP_PREFIX, .offset = offsetof(hc_punting_t, prefix), \
+ .offset2 = offsetof(hc_punting_t, prefix_len), \
+ .offset3 = offsetof(hc_punting_t, family), \
+ }
+
+/* Commands */
+
+static const command_parser_t command_punting_create = {
+ .action = ACTION_CREATE,
+ .object = OBJECT_PUNTING,
+ .nparams = 2,
+ .parameters = {symbolic_or_id, prefix},
+};
+COMMAND_REGISTER(command_punting_create);
+
+static const command_parser_t command_punting_list = {
+ .action = ACTION_LIST,
+ .object = OBJECT_PUNTING,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_punting_list);
+#endif
diff --git a/ctrl/libhicnctrl/src/commands/command_route.c b/ctrl/libhicnctrl/src/commands/command_route.c
new file mode 100644
index 000000000..95d0a3a43
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_route.c
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_route.c
+ * \brief Implementation of route command.
+ */
+
+#include <math.h>
+#include <hicn/ctrl/command.h>
+#include "../objects/route.h"
+
+/* Parameters */
+
+#define symbolic_or_id \
+ { \
+ .name = "symbolic_or_id", \
+ .help = \
+ "The symbolic name for an egress, or the egress route id (see 'help " \
+ "list routes')", \
+ .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_route_t, face_name), \
+ }
+
+#define prefix \
+ { \
+ .name = "prefix", \
+ .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \
+ .type = TYPE_IP_PREFIX, .offset = offsetof(hc_route_t, remote_addr), \
+ .offset2 = offsetof(hc_route_t, len), \
+ .offset3 = offsetof(hc_route_t, family), \
+ }
+
+#define p_cost \
+ { \
+ .name = "cost", .help = "Positive integer representing cost.", \
+ .type = TYPE_INT(1, 255), .offset = offsetof(hc_route_t, cost), \
+ }
+
+/* Face parameters */
+
+#define type_tcp_udp \
+ { \
+ .name = "type", .help = "face type [tcp | udp]", \
+ .type = TYPE_ENUM(face_type), .offset = offsetof(hc_route_t, face.type), \
+ }
+
+#define local_address \
+ { \
+ .name = "local_addr", .help = "local IP address on which to bind.", \
+ .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_route_t, face.local_addr), \
+ .offset2 = offsetof(hc_route_t, face.family), \
+ }
+
+#define local_port \
+ { \
+ .name = "local_port", .help = "Local port.", \
+ .type = TYPE_UINT16(1, UINT16_MAX), \
+ .offset = offsetof(hc_route_t, face.local_port), \
+ }
+
+#define remote_address \
+ { \
+ .name = "remote_address", \
+ .help = "The IPv4 or IPv6 or hostname of the remote system.", \
+ .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_route_t, face.remote_addr), \
+ .offset2 = offsetof(hc_route_t, face.family), \
+ }
+
+#define remote_port \
+ { \
+ .name = "remote_port", .help = "Remote port.", \
+ .type = TYPE_UINT16(1, UINT16_MAX), \
+ .offset = offsetof(hc_route_t, face.remote_port), \
+ }
+
+#define interface \
+ { \
+ .name = "interface", .help = "Interface on which to bind", \
+ .type = TYPE_INTERFACE_NAME, \
+ .offset = offsetof(hc_route_t, face.netdevice.name), \
+ }
+
+/* Commands */
+
+int on_route_parsed(hc_route_t* route) {
+ if (hc_route_has_face(route)) {
+ route->face.admin_state = FACE_STATE_UP;
+ route->face.id = INVALID_FACE_ID;
+ }
+ route->face_id = INVALID_FACE_ID; // we populate face name
+ if (route->cost == 0) route->cost = 1;
+ return 0;
+}
+
+static const command_parser_t command_route_create1 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 1,
+ .parameters = {prefix},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_create1);
+
+static const command_parser_t command_route_create2 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 2,
+ .parameters = {symbolic_or_id, prefix},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_create2);
+
+static const command_parser_t command_route_create3 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 3,
+ .parameters = {symbolic_or_id, prefix, p_cost},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_create3);
+
+static const command_parser_t command_route_create5 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 5,
+ .parameters = {prefix, p_cost, type_tcp_udp, remote_address, remote_port},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_create5);
+
+static const command_parser_t command_route_create6 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 6,
+ .parameters = {prefix, p_cost, type_tcp_udp, remote_address, remote_port,
+ interface},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_create6);
+
+static const command_parser_t command_route_create7 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 7,
+ .parameters = {prefix, p_cost, type_tcp_udp, local_address, local_port,
+ remote_address, remote_port},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_create7);
+
+static const command_parser_t command_route_create8 = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 8,
+ .parameters = {prefix, p_cost, type_tcp_udp, local_address, local_port,
+ remote_address, remote_port, interface},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_create8);
+
+static const command_parser_t command_route_list = {
+ .action = ACTION_LIST,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_route_list);
+
+static const command_parser_t command_route_remove = {
+ .action = ACTION_DELETE,
+ .object_type = OBJECT_TYPE_ROUTE,
+ .nparams = 2,
+ .parameters = {symbolic_or_id, prefix},
+ .post_hook = (parser_hook_t)on_route_parsed,
+};
+COMMAND_REGISTER(command_route_remove);
diff --git a/hicn-light/src/hicn/config/controlListPolicies.h b/ctrl/libhicnctrl/src/commands/command_stats.c
index 7aa0bdd26..d69f22a19 100644
--- a/hicn-light/src/hicn/config/controlListPolicies.h
+++ b/ctrl/libhicnctrl/src/commands/command_stats.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,21 +14,24 @@
*/
/**
- * @file control_ListPolicies.h
- * @brief List the icn-light policies
- *
- * Implements the "list policies" and "help list policies" nodes of the command tree
- *
+ * \file command_stats.h
+ * \brief Implementation of stats command.
*/
-#ifndef Control_ListPolicies_h
-#define Control_ListPolicies_h
-
-#ifdef WITH_POLICY
+#include <math.h>
+#include <hicn/ctrl/command.h>
-#include <hicn/config/controlState.h>
-CommandOps *controlListPolicies_Create(ControlState *state);
-CommandOps *controlListPolicies_HelpCreate(ControlState *state);
+/* Commands */
-#endif /* WITH_POLICY */
+static const command_parser_t command_stats_list = {
+ .action = ACTION_LIST,
+ .object_type = OBJECT_TYPE_STATS,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_stats_list);
-#endif // Control_ListPolicies_h
+static const command_parser_t command_face_stats_list = {
+ .action = ACTION_LIST,
+ .object_type = OBJECT_TYPE_FACE_STATS,
+ .nparams = 0,
+};
+COMMAND_REGISTER(command_face_stats_list);
diff --git a/ctrl/libhicnctrl/src/commands/command_strategy.c b/ctrl/libhicnctrl/src/commands/command_strategy.c
new file mode 100644
index 000000000..2aac924c4
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_strategy.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_strategy.h
+ * \brief Implementation of strategy command.
+ */
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+#define prefix \
+ { \
+ .name = "prefix", \
+ .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \
+ .type = TYPE_IP_PREFIX, .offset = offsetof(hc_strategy_t, address), \
+ .offset2 = offsetof(hc_strategy_t, len), \
+ .offset3 = offsetof(hc_strategy_t, family), \
+ }
+
+#define strategy \
+ { \
+ .name = "strategy", \
+ .help = \
+ "Strategy type (e.g. 'random', 'loadbalancer', 'low_latency', " \
+ "'replication', 'bestpath', local_remote).", \
+ .type = TYPE_ENUM(strategy_type), .offset = offsetof(hc_strategy_t, type), \
+ }
+
+#define local_prefix \
+ { \
+ .name = "local_prefix", \
+ .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \
+ .type = TYPE_IP_PREFIX, .offset = offsetof(hc_strategy_t, local_address), \
+ .offset2 = offsetof(hc_strategy_t, local_len), \
+ .offset3 = offsetof(hc_strategy_t, local_family), \
+ }
+
+/* Commands */
+
+static const command_parser_t command_strategy_list = {
+ .action = ACTION_SET,
+ .object_type = OBJECT_TYPE_STRATEGY,
+ .nparams = 2,
+ .parameters = {prefix, strategy},
+};
+COMMAND_REGISTER(command_strategy_list);
+
+static const command_parser_t local_prefix_add = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_LOCAL_PREFIX,
+ .nparams = 3,
+ .parameters = {prefix, strategy, local_prefix},
+};
+COMMAND_REGISTER(local_prefix_add);
diff --git a/ctrl/libhicnctrl/src/commands/command_subscription.c b/ctrl/libhicnctrl/src/commands/command_subscription.c
new file mode 100644
index 000000000..ee2455b1c
--- /dev/null
+++ b/ctrl/libhicnctrl/src/commands/command_subscription.c
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file command_subscription.h
+ * \brief Implementation of subscription command.
+ */
+#include <limits.h>
+
+#include <hicn/ctrl/command.h>
+
+/* Parameters */
+
+#define topics \
+ { \
+ .name = "topics", \
+ .help = \
+ "Topics to subscribe to, e.g. 6 (110 in binary) means topic 2 (10 in " \
+ "binary, TOPIC_CONNECTION) and topic 4 (100 in binary, " \
+ "TOPIC_LISTENER).", \
+ .type = TYPE_INT(1, INT_MAX), \
+ .offset = offsetof(hc_subscription_t, topics), \
+ }
+
+/* Commands */
+
+static const command_parser_t command_subscription_create = {
+ .action = ACTION_CREATE,
+ .object_type = OBJECT_TYPE_SUBSCRIPTION,
+ .nparams = 1,
+ .parameters = {topics},
+};
+COMMAND_REGISTER(command_subscription_create);
diff --git a/ctrl/libhicnctrl/src/data.c b/ctrl/libhicnctrl/src/data.c
new file mode 100644
index 000000000..605e23601
--- /dev/null
+++ b/ctrl/libhicnctrl/src/data.c
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file data.c
+ * \brief Implementation of request result data.
+ */
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include <hicn/ctrl/data.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/util/log.h>
+
+#define MIN_ALLOC_SIZE 8
+#define MAX(x, y) (((x) > (y)) ? (x) : (y))
+
+struct hc_data_s {
+ hc_object_type_t object_type;
+ bool complete;
+
+ /**
+ * >=0 success, indicates the number of records in array
+ * <0 error
+ */
+ ssize_t size;
+ size_t alloc_size; /** Allocated size (a power of 2 when managed
+ automatically) */
+ size_t max_size; /** Maximum size defined at creation (0 = unlimited) */
+
+ uint8_t *buffer;
+};
+
+void _hc_data_clear(hc_data_t *data) {
+ data->complete = false;
+ data->buffer = NULL;
+ data->max_size = 0;
+ data->alloc_size = 0;
+ data->size = 0;
+}
+
+hc_data_t *hc_data_create(hc_object_type_t object_type) {
+ hc_data_t *data = malloc(sizeof(hc_data_t));
+ if (!data) return NULL;
+
+ data->object_type = object_type;
+
+ _hc_data_clear(data);
+
+ return data;
+ // data->buffer = malloc((1 << data->max_size_log) * data->out_element_size);
+ // if (!data->buffer) goto ERR_BUFFER;
+}
+
+void hc_data_free(hc_data_t *data) {
+ assert(data);
+
+ if (data->buffer) free(data->buffer);
+ free(data);
+}
+
+int hc_data_set_max_size(hc_data_t *data, size_t max_size) {
+ if (data->size > max_size) return -1;
+ data->max_size = max_size;
+ return 0;
+}
+
+const uint8_t *hc_data_get_buffer(hc_data_t *data) { return data->buffer; }
+
+const uint8_t *hc_data_get_free(hc_data_t *data) {
+ if (!data) return NULL;
+ if (data->max_size > 0 && data->size >= data->max_size) return NULL;
+ hc_object_type_t object_type = hc_data_get_object_type(data);
+ size_t object_size = hc_object_size(object_type);
+ return data->buffer + data->size * object_size;
+}
+
+void hc_data_inc_size(hc_data_t *data) { data->size++; }
+
+hc_object_type_t hc_data_get_object_type(const hc_data_t *data) {
+ return data->object_type;
+}
+
+void hc_data_set_object_type(hc_data_t *data, hc_object_type_t object_type) {
+ data->object_type = object_type;
+}
+
+ssize_t hc_data_get_size(const hc_data_t *data) { return data->size; }
+
+int hc_data_clear(hc_data_t *data) {
+ free(data->buffer);
+ _hc_data_clear(data);
+ return 0;
+}
+
+int _hc_data_allocate(hc_data_t *data, size_t size) {
+ data->buffer =
+ realloc(data->buffer, size * hc_object_size(data->object_type));
+ if (!data->buffer) goto ERR;
+ data->alloc_size = size;
+ return 0;
+ERR:
+ data->alloc_size = 0;
+ return -1;
+}
+
+int hc_data_allocate(hc_data_t *data, size_t size) {
+ /* Do not allocate twice */
+ if (data->buffer) return -1;
+ if (data->max_size > 0 && size > data->max_size) return -1;
+ return _hc_data_allocate(data, size);
+}
+
+int hc_data_ensure_available(hc_data_t *data, size_t count) {
+ size_t new_size = data->size + count;
+ if (new_size < data->alloc_size) return 0;
+ if (data->max_size > 0 && new_size > data->max_size) return -1;
+
+ size_t new_alloc_size = MAX(MIN_ALLOC_SIZE, next_pow2(new_size));
+ if (data->max_size > 0 && new_alloc_size > data->max_size)
+ new_alloc_size = data->max_size;
+
+ return _hc_data_allocate(data, new_alloc_size);
+}
+
+int hc_data_push_many(hc_data_t *data, const void *elements, size_t count) {
+ if (!data) return -1;
+ if (!elements) return -1;
+ if (count < 1) return -1;
+
+ if (hc_data_ensure_available(data, count) < 0) return -1;
+
+ hc_object_type_t object_type = hc_data_get_object_type(data);
+ size_t object_size = hc_object_size(object_type);
+
+ uint8_t *dst = data->buffer + data->size * object_size;
+ memcpy(dst, elements, count * object_size);
+ data->size += count;
+
+ return 0;
+}
+
+int hc_data_push(hc_data_t *data, const void *element) {
+ return hc_data_push_many(data, element, 1);
+}
+#if 0
+/**
+ *
+ * NOTE: This function make sure there is enough room available in the data
+ * structure.
+ */
+u8 *hc_data_get_next(hc_data_t *data) {
+ if (hc_data_ensure_available(data, 1) < 0) return NULL;
+
+ return data->buffer + data->size * data->out_element_size;
+}
+
+int hc_data_set_callback(hc_data_t *data, data_callback_t cb, void *cb_data) {
+ data->complete_cb = cb;
+ data->complete_cb_data = cb_data;
+ return 0;
+}
+#endif
+
+void hc_data_set_complete(hc_data_t *data) { data->complete = true; }
+
+bool hc_data_is_complete(const hc_data_t *data) { return data->complete; }
+
+void hc_data_set_error(hc_data_t *data) {
+ data->size = -1;
+ data->complete = true;
+}
+
+bool hc_data_get_result(hc_data_t *data) { return (data->size >= 0); }
+
+hc_object_t *hc_data_find(hc_data_t *data, hc_object_t *object) {
+ hc_object_type_t object_type = hc_data_get_object_type(data);
+ hc_data_foreach(data, found, {
+ if (hc_object_cmp(object_type, object, found) == 0) return found;
+ });
+ return NULL;
+}
+
+const hc_object_t *hc_data_get_object(const hc_data_t *data, off_t pos) {
+ size_t size = hc_data_get_size(data);
+ if (pos >= size) return NULL;
+
+ hc_object_type_t object_type = hc_data_get_object_type(data);
+ size_t object_size = hc_object_size(object_type);
+
+ return (const hc_object_t *)(data->buffer + pos * object_size);
+}
+
+#if 0
+int hc_data_reset(hc_data_t *data) {
+ data->size = 0;
+ return 0;
+}
+#endif
diff --git a/ctrl/libhicnctrl/src/face.c b/ctrl/libhicnctrl/src/face.c
deleted file mode 100644
index e617ff8a4..000000000
--- a/ctrl/libhicnctrl/src/face.c
+++ /dev/null
@@ -1,430 +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.
- */
-
-/**
- * \file face.c
- * \brief Implementation of face abstraction
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <hicn/util/token.h>
-
-#include <hicn/ctrl/face.h>
-#include "util/hash.h"
-
-#define member_size(type, member) sizeof(((type *)0)->member)
-
-
-/* Netdevice */
-
-const char * netdevice_type_str[] = {
-#define _(x) [NETDEVICE_TYPE_ ## x] = STRINGIZE(x),
-foreach_netdevice_type
-#undef _
-};
-
-netdevice_t *
-netdevice_create_from_index(u32 index)
-{
- netdevice_t * netdevice = malloc(sizeof(netdevice_t));
- if (!netdevice)
- goto ERR_MALLOC;
-
- int rc = netdevice_set_index(netdevice, index);
- if (rc < 0)
- goto ERR_INIT;
-
- return netdevice;
-
-ERR_INIT:
- free(netdevice);
-ERR_MALLOC:
- return NULL;
-}
-
-netdevice_t *
-netdevice_create_from_name(const char * name)
-{
- netdevice_t * netdevice = malloc(sizeof(netdevice_t));
- if (!netdevice)
- goto ERR_MALLOC;
-
- int rc = netdevice_set_name(netdevice, name);
- if (rc < 0)
- goto ERR_INIT;
-
- return netdevice;
-
-ERR_INIT:
- free(netdevice);
-ERR_MALLOC:
- return NULL;
-}
-
-/**
- * \brief Update the index of the netdevice based on the name
- */
-int
-netdevice_update_index(netdevice_t * netdevice)
-{
- netdevice->index = if_nametoindex(netdevice->name);
- if (netdevice->index == 0)
- return -1;
- return 0;
-}
-
-int
-netdevice_update_name(netdevice_t * netdevice)
-{
- if (!if_indextoname(netdevice->index, netdevice->name))
- return -1;
- return 0;
-}
-
-void
-netdevice_free(netdevice_t * netdevice)
-{
- free(netdevice);
-}
-
-int
-netdevice_get_index(const netdevice_t * netdevice, u32 * index)
-{
- if (netdevice->index == 0)
- return -1;
- *index = netdevice->index;
- return 0;
-}
-
-int
-netdevice_set_index(netdevice_t * netdevice, u32 index)
-{
- netdevice->index = index;
- return netdevice_update_name(netdevice);
-}
-
-int
-netdevice_get_name(const netdevice_t * netdevice, const char ** name)
-{
- if (netdevice->name[0] == '\0')
- return -1;
- *name = netdevice->name;
- return 0;
-}
-
-int
-netdevice_set_name(netdevice_t * netdevice, const char * name)
-{
- memset(netdevice->name, 0, sizeof(netdevice->name));
- int rc = snprintf(netdevice->name, IFNAMSIZ, "%s", name);
- if (rc < 0)
- return -1;
- if (rc >= IFNAMSIZ)
- return -2; /* truncated */
- return netdevice_update_index(netdevice);
-}
-
-int
-netdevice_cmp(const netdevice_t * nd1, const netdevice_t * nd2)
-{
- return (nd1->index - nd2->index);
-}
-
-
-/* Face state */
-
-const char * face_state_str[] = {
-#define _(x) [FACE_STATE_ ## x] = STRINGIZE(x),
-foreach_face_state
-#undef _
-};
-
-
-/* Face type */
-
-const char * face_type_str[] = {
-#define _(x) [FACE_TYPE_ ## x] = STRINGIZE(x),
-foreach_face_type
-#undef _
-};
-
-
-/* Face */
-
-int
-face_initialize(face_t * face)
-{
- memset(face, 0, sizeof(face_t)); /* 0'ed for hash */
- return 1;
-}
-
-int
-face_initialize_udp(face_t * face, const char * interface_name, const
- ip_address_t * local_addr, u16 local_port,
- const ip_address_t * remote_addr, u16 remote_port,
- int family)
-{
- if (!local_addr)
- return -1;
-
- *face = (face_t) {
- .type = FACE_TYPE_UDP,
- .family = family,
- .local_addr = *local_addr,
- .local_port = local_port,
- .remote_addr = remote_addr ? *remote_addr : IP_ADDRESS_EMPTY,
- .remote_port = remote_port,
- };
-
- snprintf(face->netdevice.name, IFNAMSIZ, "%s", interface_name);
-
- return 1;
-}
-
-int
-face_initialize_udp_sa(face_t * face, const char * interface_name,
- const struct sockaddr * local_addr,
- const struct sockaddr * remote_addr)
-{
- if (!local_addr)
- return -1;
-
- if (remote_addr && (local_addr->sa_family != remote_addr->sa_family))
- return -1;
-
- switch (local_addr->sa_family) {
- case AF_INET:
- {
- struct sockaddr_in *lsai = (struct sockaddr_in *)local_addr;
- struct sockaddr_in *rsai = (struct sockaddr_in *)remote_addr;
- *face = (face_t) {
- .type = FACE_TYPE_UDP,
- .family = AF_INET,
- .local_addr.v4.as_inaddr = lsai->sin_addr,
- .local_port = lsai ? ntohs(lsai->sin_port) : 0,
- .remote_addr = IP_ADDRESS_EMPTY,
- .remote_port = rsai ? ntohs(rsai->sin_port) : 0,
- };
- if (rsai)
- face->remote_addr.v4.as_inaddr = rsai->sin_addr;
- }
- break;
- case AF_INET6:
- {
- struct sockaddr_in6 *lsai = (struct sockaddr_in6 *)local_addr;
- struct sockaddr_in6 *rsai = (struct sockaddr_in6 *)remote_addr;
- *face = (face_t) {
- .type = FACE_TYPE_UDP,
- .family = AF_INET6,
- .local_addr.v6.as_in6addr = lsai->sin6_addr,
- .local_port = lsai ? ntohs(lsai->sin6_port) : 0,
- .remote_addr = IP_ADDRESS_EMPTY,
- .remote_port = rsai ? ntohs(rsai->sin6_port) : 0,
- };
- if (rsai)
- face->remote_addr.v6.as_in6addr = rsai->sin6_addr;
- }
- break;
- default:
- return -1;
- }
-
- snprintf(face->netdevice.name, IFNAMSIZ, "%s", interface_name);
-
- return 1;
-}
-
-face_t * face_create()
-{
- face_t * face = calloc(1, sizeof(face_t)); /* 0'ed for hash */
- return face;
-}
-
-face_t * face_create_udp(const char * interface_name,
- const ip_address_t * local_addr, u16 local_port,
- const ip_address_t * remote_addr, u16 remote_port, int family)
-{
- face_t * face = face_create();
- if (face_initialize_udp(face, interface_name, local_addr, local_port, remote_addr, remote_port, family) < 0)
- goto ERR_INIT;
- return face;
-
-ERR_INIT:
- free(face);
- return NULL;
-}
-
-face_t * face_create_udp_sa(const char * interface_name,
- const struct sockaddr * local_addr,
- const struct sockaddr * remote_addr)
-{
- face_t * face = face_create();
- if (face_initialize_udp_sa(face, interface_name, local_addr, remote_addr) < 0)
- goto ERR_INIT;
- return face;
-
-ERR_INIT:
- free(face);
- return NULL;
-}
-
-void face_free(face_t * face)
-{
- free(face);
-}
-
-/**
- * \brief Compare two faces
- * \param [in] f1 - First face
- * \param [in] f2 - Second face
- * \return whether faces are equal, ie both their types are parameters are
- * equal.
- *
- * NOTE: this function implements a partial order.
- */
-int
-face_cmp(const face_t * f1, const face_t * f2)
-{
-
- int ret = f1->type - f2->type;
- if (ret != 0)
- return ret;
-
- ret = f1->family - f2->family;
- if (ret != 0)
- return ret;
-
- /*
- * FIXME As hicn-light API might not return the netdevice, we can discard the
- * comparison when one of the two is not set for now...
- */
- if ((f1->netdevice.index != 0) && (f2->netdevice.index != 0)) {
- ret = netdevice_cmp(&f1->netdevice, &f2->netdevice);
- if (ret != 0)
- return ret;
- }
-
- switch(f1->type) {
- case FACE_TYPE_HICN:
- ret = ip_address_cmp(&f1->local_addr, &f2->local_addr, f1->family);
- if (ret != 0)
- return ret;
-
- ret = ip_address_cmp(&f1->remote_addr, &f2->remote_addr, f1->family);
- if (ret != 0)
- return ret;
-
- break;
-
- case FACE_TYPE_TCP:
- case FACE_TYPE_UDP:
- ret = ip_address_cmp(&f1->local_addr, &f2->local_addr, f1->family);
- if (ret != 0)
- return ret;
-
- ret = f1->local_port - f2->local_port;
- if (ret != 0)
- return ret;
-
- ret = ip_address_cmp(&f1->remote_addr, &f2->remote_addr, f1->family);
- if (ret != 0)
- return ret;
-
- ret = f1->remote_port - f2->remote_port;
- if (ret != 0)
- return ret;
-
- break;
- default:
- break;
- }
-
- return 0;
-}
-
-unsigned int
-face_hash(const face_t * face)
-{
- /* Assuming the unused part of the struct is set to zero */
- return hash_struct(face);
-}
-
-/* /!\ Please update constants in header file upon changes */
-size_t
-face_snprintf(char * s, size_t size, const face_t * face)
-{
- switch(face->type) {
- case FACE_TYPE_HICN:
- {
- char local[MAXSZ_IP_ADDRESS];
- char remote[MAXSZ_IP_ADDRESS];
- char tags[MAXSZ_POLICY_TAGS];
-
- ip_address_snprintf(local, MAXSZ_IP_ADDRESS,
- &face->local_addr,
- face->family);
- ip_address_snprintf(remote, MAXSZ_IP_ADDRESS,
- &face->remote_addr,
- face->family);
- policy_tags_snprintf(tags, MAXSZ_POLICY_TAGS, face->tags);
- return snprintf(s, size, "%s [%s -> %s] [%s]",
- face_type_str[face->type],
- local,
- remote,
- tags);
- }
- case FACE_TYPE_UNDEFINED:
- case FACE_TYPE_TCP:
- case FACE_TYPE_UDP:
- {
- char local[MAXSZ_IP_ADDRESS];
- char remote[MAXSZ_IP_ADDRESS];
- char tags[MAXSZ_POLICY_TAGS];
-
- ip_address_snprintf(local, MAXSZ_IP_ADDRESS,
- &face->local_addr,
- face->family);
- ip_address_snprintf(remote, MAXSZ_IP_ADDRESS,
- &face->remote_addr,
- face->family);
- policy_tags_snprintf(tags, MAXSZ_POLICY_TAGS, face->tags);
-
- return snprintf(s, size, "%s [%s:%d -> %s:%d] [%s]",
- face_type_str[face->type],
- local,
- face->local_port,
- remote,
- face->remote_port,
- tags);
- }
- default:
- return -1;
- }
-
-}
-
-policy_tags_t face_get_tags(const face_t * face)
-{
- return face->tags;
-}
-
-int
-face_set_tags(face_t * face, policy_tags_t tags)
-{
- face->tags = tags;
- return 1;
-}
diff --git a/ctrl/libhicnctrl/src/fw_interface.c b/ctrl/libhicnctrl/src/fw_interface.c
new file mode 100644
index 000000000..6d5e5fb34
--- /dev/null
+++ b/ctrl/libhicnctrl/src/fw_interface.c
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file fw_interface.c
+ * \brief Implementation of fw interface
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/callback.h>
+#include <hicn/util/log.h>
+#include <hicn/ctrl/fw_interface.h>
+
+const char *fw_state_str[] = {
+#define _(x) [FW_STATE_##x] = #x,
+ foreach_fw_state
+#undef _
+};
+
+struct fw_interface_s {
+ /*
+ * Type of forwarder to which we are connecting/connected : HICNLIGHT, VPP
+ */
+ forwarder_type_t type;
+ fw_state_t state;
+
+ hc_sock_t *sock;
+ char *url;
+
+ bool has_subscribe_all;
+
+ hc_enable_callback_t enable_callback;
+ hc_state_callback_t state_callback;
+ void *state_callback_data;
+ hc_result_callback_t result_callback;
+ void *result_callback_data;
+ hc_notification_callback_t notification_callback;
+ void *notification_callback_data;
+};
+
+fw_interface_t *fw_interface_create_url(forwarder_type_t type,
+ const char *url) {
+ fw_interface_t *fi = malloc(sizeof(fw_interface_t));
+ if (!fi) goto ERR_MALLOC;
+
+ fi->type = type;
+ /* Let's assume for now the forwarder is always on */
+ fi->state = FW_STATE_AVAILABLE;
+ fi->sock = NULL;
+ fi->has_subscribe_all = false;
+ fi->url = NULL;
+
+ // XXX make a single request to probe for forwarder size?
+
+ return fi;
+
+ERR_MALLOC:
+ return NULL;
+}
+
+fw_interface_t *fw_interface_create(forwarder_type_t type) {
+ return fw_interface_create_url(type, NULL);
+}
+
+void fw_interface_free(fw_interface_t *fi) {
+ fw_interface_disconnect(fi);
+ free(fi);
+}
+
+int fw_interface_get_fd(const fw_interface_t *fi) {
+ if (!fi) return 0;
+ return hc_sock_get_fd(fi->sock);
+}
+
+int fw_interface_set_enable_callback(fw_interface_t *fi,
+ hc_enable_callback_t callback) {
+ fi->enable_callback = callback;
+ return 0;
+}
+
+int fw_interface_set_state_callback(fw_interface_t *fi,
+ hc_state_callback_t callback,
+ void *callback_data) {
+ fi->state_callback = callback;
+ fi->state_callback_data = callback_data;
+ return 0;
+}
+
+int fw_interface_set_result_callback(fw_interface_t *fi,
+ hc_result_callback_t callback,
+ void *callback_data) {
+ fi->result_callback = callback;
+ fi->result_callback_data = callback_data;
+ return 0;
+}
+
+int fw_interface_set_notification_callback(fw_interface_t *fi,
+ hc_notification_callback_t callback,
+ void *callback_data) {
+ fi->notification_callback = callback;
+ fi->notification_callback_data = callback_data;
+ return 0;
+}
+
+int fw_interface_enable(fw_interface_t *fi) {
+ // TODO
+ return 0;
+}
+
+int fw_interface_disable(fw_interface_t *fi) {
+ // TODO
+ return 0;
+}
+
+// XXX blocking or non blocking ?
+int fw_interface_reschedule_connect(fw_interface_t *fi) {
+ INFO("Scheduling reconnect...");
+ // XXX TODO timer
+ return 0;
+}
+
+int _fw_interface_connect(fw_interface_t *fi, bool reattempt) {
+ fi->sock = hc_sock_create(fi->type, fi->url);
+ if (!fi->sock) goto ERR_SOCK;
+
+ if (hc_sock_set_async(fi->sock) < 0) goto ERR_ASYNC;
+
+ if (hc_sock_connect(fi->sock) < 0) {
+ ERROR("Error connecting to forwarder");
+ return -1;
+ }
+
+ return 0;
+
+ERR_ASYNC:
+ hc_sock_free(fi->sock);
+ERR_SOCK:
+
+ if (reattempt) return fw_interface_reschedule_connect(fi);
+ return -1;
+}
+
+int fw_interface_connect(fw_interface_t *fi) {
+ switch (fi->state) {
+ case FW_STATE_UNDEFINED:
+ // XXX connect, enable, (poll)?
+ break;
+ case FW_STATE_DISABLED:
+ fw_interface_enable(fi);
+ break;
+ case FW_STATE_REQUESTED:
+ // XXX waiting ? polling connect ?
+ break;
+ case FW_STATE_AVAILABLE:
+ _fw_interface_connect(fi, true);
+ // XXX
+ break;
+ case FW_STATE_CONNECTING:
+ case FW_STATE_CONNECTED:
+ case FW_STATE_READY:
+ /* Nothing to do */
+ return 0;
+ case FW_STATE_N:
+ return -1;
+ }
+ return 0;
+}
+
+int _fw_interface_disconnect(fw_interface_t *fi) {
+ if (fi->has_subscribe_all) fw_interface_unsubscribe_all(fi);
+ hc_sock_free(fi->sock);
+ return 0;
+}
+
+int fw_interface_disconnect(fw_interface_t *fi) {
+ switch (fi->state) {
+ case FW_STATE_UNDEFINED:
+ case FW_STATE_DISABLED:
+ case FW_STATE_REQUESTED:
+ case FW_STATE_AVAILABLE:
+ /* Nothing to do */
+ return 0;
+ case FW_STATE_CONNECTING:
+ case FW_STATE_CONNECTED:
+ case FW_STATE_READY:
+ _fw_interface_disconnect(fi);
+ return 0;
+ case FW_STATE_N:
+ return -1;
+ }
+ return 0;
+}
+
+fw_state_t fw_interface_get_state(const fw_interface_t *fi) {
+ return fi->state;
+}
+
+bool fw_interface_is_connected(const fw_interface_t *fi) {
+ return ((fi->state == FW_STATE_CONNECTED) || (fi->state == FW_STATE_READY));
+}
+
+bool fw_interface_is_ready(const fw_interface_t *fi) {
+ return (fi->state == FW_STATE_READY);
+}
+
+int fw_interface_subscribe_all(fw_interface_t *fi) {
+ INFO("fw_interface_subscribe_all");
+ int rc = hc_execute_async(fi->sock, ACTION_SUBSCRIBE, OBJECT_TYPE_UNDEFINED,
+ NULL, fi->notification_callback,
+ fi->notification_callback_data);
+ if (rc < 0) {
+ return -1;
+ }
+ fi->has_subscribe_all = true;
+ return 0;
+}
+
+int fw_interface_unsubscribe_all(fw_interface_t *fi) {
+ fi->has_subscribe_all = false;
+ return 0;
+}
+
+// face manager : upon completion, same as notification, CREATE/GET FACE
+// hproxy = event = function to call to proceed through state machine (also
+// depends if we handle face+route), for notifications, telemetry.
+// NOTE we should have a notif for our own events. how to handle ?
+// XXX user_data .... or user_callback
+int fw_interface_execute(fw_interface_t *fi, hc_action_t action,
+ hc_object_type_t object_type, hc_object_t *object,
+ hc_data_t **pdata) {
+ return hc_execute(fi->sock, action, object_type, object, pdata);
+}
+
+int fw_interface_execute_async(fw_interface_t *fi, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object,
+ hc_result_callback_t callback,
+ void *callback_data) {
+ if (!callback) {
+ callback = fi->result_callback;
+ callback_data = fi->result_callback_data;
+ }
+ return hc_execute_async(fi->sock, action, object_type, object, callback,
+ callback_data);
+}
+
+int fw_interface_on_receive(fw_interface_t *fi, size_t count) {
+ return hc_sock_on_receive(fi->sock, count);
+}
+
+int fw_interface_get_recv_buffer(fw_interface_t *fi, uint8_t **buffer,
+ size_t *size) {
+ return hc_sock_get_recv_buffer(fi->sock, buffer, size);
+}
diff --git a/ctrl/libhicnctrl/src/hicnctrl.c b/ctrl/libhicnctrl/src/hicnctrl.c
new file mode 100644
index 000000000..478997ec1
--- /dev/null
+++ b/ctrl/libhicnctrl/src/hicnctrl.c
@@ -0,0 +1,400 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file hicnctrl.c
+ * \brief Command line interface
+ */
+#include <ctype.h> // isalpha isalnum
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h> // getopt
+
+#include <hicn/ctrl.h>
+#include <hicn/util/ip_address.h>
+#include <hicn/util/log.h>
+#include <hicn/util/token.h>
+#include <hicn/validation.h>
+
+#include <hicn/ctrl/parse.h>
+
+#define die(LABEL, MESSAGE) \
+ do { \
+ printf(MESSAGE "\n"); \
+ goto ERR_##LABEL; \
+ } while (0)
+
+void usage_header() { fprintf(stderr, "Usage:\n"); }
+
+void usage_face_create(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr,
+ "%s -f TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT "
+ "[INTERFACE_NAME]\n",
+ prog);
+ if (verbose)
+ fprintf(stderr, " Create a face on specified address and port.\n");
+}
+
+void usage_face_delete(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -df ID\n", prog);
+ // fprintf(stderr, "%s -df NAME\n", prog);
+ fprintf(stderr,
+ "%s -df TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT "
+ "[INTERFACE_NAME]\n",
+ prog);
+ if (verbose) fprintf(stderr, " Delete a face...\n");
+}
+
+void usage_face_list(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -F\n", prog);
+ if (verbose) fprintf(stderr, " List all faces.\n");
+}
+
+void usage_face(const char *prog, bool header, bool verbose) {
+ usage_face_create(prog, header, verbose);
+ usage_face_delete(prog, header, verbose);
+ usage_face_list(prog, header, verbose);
+}
+
+void usage_route_create(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -r FACE_ID PREFIX [COST]\n", prog);
+ // fprintf(stderr, "%s -r [FACE_ID|NAME] PREFIX [COST]\n", prog);
+ if (verbose) fprintf(stderr, " Create a route...\n");
+}
+
+void usage_route_delete(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -dr FACE_ID PREFIX\n", prog);
+ // fprintf(stderr, "%s -dr [FACE_ID|NAME] PREFIX\n", prog);
+ if (verbose) fprintf(stderr, " Delete a route...\n");
+}
+
+void usage_route_list(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -R\n", prog);
+ if (verbose) fprintf(stderr, " List all routes.\n");
+}
+
+void usage_route(const char *prog, bool header, bool verbose) {
+ usage_route_create(prog, header, verbose);
+ usage_route_delete(prog, header, verbose);
+ usage_route_list(prog, header, verbose);
+}
+
+void usage_forwarding_strategy_create(const char *prog, bool header,
+ bool verbose) {
+ if (header) usage_header();
+}
+void usage_forwarding_strategy_delete(const char *prog, bool header,
+ bool verbose) {
+ if (header) usage_header();
+}
+
+void usage_forwarding_strategy_list(const char *prog, bool header,
+ bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -S\n", prog);
+ if (verbose)
+ fprintf(stderr, " List all availble forwarding strategies.\n");
+}
+
+void usage_forwarding_strategy(const char *prog, bool header, bool verbose) {
+ usage_forwarding_strategy_create(prog, header, verbose);
+ usage_forwarding_strategy_delete(prog, header, verbose);
+ usage_forwarding_strategy_list(prog, header, verbose);
+}
+
+void usage_listener_create(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -l TYPE NAME LOCAL_ADDRESS LOCAL_PORT [INTERFACE_NAME]\n",
+ prog);
+ if (verbose)
+ fprintf(stderr, " Create a listener on specified address and port.\n");
+}
+
+void usage_listener_delete(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -dl ID\n", prog);
+ fprintf(stderr, "%s -dl NAME\n", prog);
+ fprintf(stderr, "%s -dl TYPE LOCAL_ADDRESS LOCAL_PORT [INTERFACE_NAME]\n",
+ prog);
+ if (verbose) fprintf(stderr, " Delete a listener...\n");
+}
+
+void usage_listener_list(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -L\n", prog);
+ if (verbose) fprintf(stderr, " List all listeners.\n");
+}
+
+void usage_listener(const char *prog, bool header, bool verbose) {
+ usage_listener_create(prog, header, verbose);
+ usage_listener_delete(prog, header, verbose);
+ usage_listener_list(prog, header, verbose);
+}
+void usage_connection_create(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr,
+ "%s -c NAME TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT "
+ "[INTERFACE_NAME]\n",
+ prog);
+ if (verbose)
+ fprintf(stderr, " Create a connection on specified address and port.\n");
+}
+
+void usage_connection_delete(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -dc ID\n", prog);
+ fprintf(stderr, "%s -dc NAME\n", prog);
+ fprintf(stderr,
+ "%s -dc TYPE LOCAL_ADDRESS LOCAL_PORT REMOTE_ADDRESS REMOTE_PORT "
+ "[INTERFACE_NAME]\n",
+ prog);
+ if (verbose) fprintf(stderr, " Delete a connection...\n");
+}
+
+void usage_connection_list(const char *prog, bool header, bool verbose) {
+ if (header) usage_header();
+ fprintf(stderr, "%s -C\n", prog);
+ if (verbose) fprintf(stderr, " List all connections.\n");
+}
+
+void usage_connection(const char *prog, bool header, bool verbose) {
+ usage_connection_create(prog, header, verbose);
+ usage_connection_delete(prog, header, verbose);
+ usage_connection_list(prog, header, verbose);
+}
+
+void usage(const char *prog) {
+ fprintf(stderr,
+ "Usage: %s [ -z forwarder (hicnlight | vpp) ] [ [-d] [-f|-l|-c|-r] "
+ "PARAMETERS | [-F|-L|-C|-R] ]\n",
+ prog);
+ fprintf(stderr, "\n");
+ fprintf(stderr, "High-level commands\n");
+ fprintf(stderr, "\n");
+ usage_face(prog, false, true);
+ usage_route(prog, false, true);
+ usage_forwarding_strategy(prog, false, true);
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Low level commands (hicn-light specific)\n");
+ fprintf(stderr, "\n");
+ usage_listener(prog, false, true);
+ usage_connection(prog, false, true);
+}
+
+/*
+ * We only allow settings commands and object types once, with the default
+ * action being set to CREATE
+ */
+#define set_command(ACTION, OBJECT_TYPE) \
+ do { \
+ if ((ACTION) != ACTION_UNDEFINED) { \
+ if (command->action != ACTION_CREATE) goto USAGE; \
+ command->action = (ACTION); \
+ } \
+ if ((OBJECT_TYPE) != OBJECT_TYPE_UNDEFINED) { \
+ if (command->object_type != OBJECT_TYPE_UNDEFINED) goto USAGE; \
+ command->object_type = (OBJECT_TYPE); \
+ } \
+ } while (0)
+
+int parse_options(int argc, char *argv[], hc_command_t *command,
+ forwarder_type_t *forwarder) {
+ command->object_type = OBJECT_TYPE_UNDEFINED;
+ command->action = ACTION_CREATE;
+ int opt;
+
+ while ((opt = getopt(argc, argv, "cCdDfFlLrRsShz:")) != -1) {
+ switch (opt) {
+ case 'z':
+ *forwarder = forwarder_type_from_str(optarg);
+ if (*forwarder == FORWARDER_TYPE_UNDEFINED) goto USAGE;
+ break;
+ case 'd':
+ set_command(ACTION_DELETE, OBJECT_TYPE_UNDEFINED);
+ break;
+ case 's':
+ set_command(ACTION_SUBSCRIBE, OBJECT_TYPE_UNDEFINED);
+ break;
+ case 'f':
+ set_command(ACTION_UNDEFINED, OBJECT_TYPE_FACE);
+ break;
+ case 'c':
+ set_command(ACTION_UNDEFINED, OBJECT_TYPE_CONNECTION);
+ break;
+ case 'l':
+ set_command(ACTION_UNDEFINED, OBJECT_TYPE_LISTENER);
+ break;
+ case 'r':
+ set_command(ACTION_UNDEFINED, OBJECT_TYPE_ROUTE);
+ break;
+ case 'F':
+ set_command(ACTION_LIST, OBJECT_TYPE_FACE);
+ break;
+ case 'L':
+ set_command(ACTION_LIST, OBJECT_TYPE_LISTENER);
+ break;
+ case 'C':
+ set_command(ACTION_LIST, OBJECT_TYPE_CONNECTION);
+ break;
+ case 'R':
+ set_command(ACTION_LIST, OBJECT_TYPE_ROUTE);
+ break;
+ case 'S':
+ set_command(ACTION_LIST, OBJECT_TYPE_STRATEGY);
+ break;
+ case 'D':
+ log_conf.log_level = LOG_DEBUG;
+ break;
+ default: /* "h" */
+ usage(argv[0]);
+ exit(EXIT_SUCCESS);
+ }
+ }
+
+ // XXX The rest could be made a single parse function
+
+ /* A default action is always defined, let's verify we have an object type,
+ * unless we are subscribing to notifications. In that case, we can monitor
+ * all objects.
+ * XXX handle later
+ */
+ if ((command->object_type == OBJECT_TYPE_UNDEFINED) &&
+ (command->action != ACTION_SUBSCRIBE)) {
+ ERROR("Missing object specification");
+ goto USAGE;
+ }
+
+ /* Check the adequation between the number of parameters and the command */
+ size_t nparams = argc - optind;
+ if (nparams > 0) {
+ if (command->action == ACTION_LIST) command->action = ACTION_GET;
+ } else {
+ if ((command->action != ACTION_LIST) &&
+ (command->action != ACTION_SUBSCRIBE))
+ goto USAGE;
+ }
+
+ /*
+ * This checks is important even with 0 parameters as it checks whether the
+ * command exists.
+ */
+ if (command->action != ACTION_SUBSCRIBE) {
+ const command_parser_t *parser =
+ command_search(command->action, command->object_type, nparams);
+ if (!parser) {
+ ERROR("Could not find parser for command '%s %s'",
+ action_str(command->action), object_type_str(command->object_type));
+ return -1;
+ }
+
+ if (nparams > 0) {
+ if (parse_getopt_args(parser, argc - optind, argv + optind, command) <
+ 0) {
+ ERROR("Error parsing command arguments");
+ goto USAGE;
+ }
+ }
+ }
+
+ return 0;
+
+USAGE:
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+}
+
+int main(int argc, char *argv[]) {
+ int rc = 1;
+ hc_command_t command;
+ memset(&command, 0, sizeof(command));
+ char buf[MAXSZ_HC_OBJECT];
+
+ log_conf.log_level = LOG_INFO;
+
+ forwarder_type_t forwarder = FORWARDER_TYPE_HICNLIGHT;
+
+ if (parse_options(argc, argv, &command, &forwarder) < 0)
+ die(OPTIONS, "Bad arguments");
+
+ hc_sock_t *s = hc_sock_create(forwarder, /* url= */ NULL);
+ if (!s) die(SOCKET, "Error creating socket.");
+
+ if (hc_sock_connect(s) < 0)
+ die(CONNECT, "Error connecting to the forwarder.");
+
+ hc_data_t *data = NULL;
+
+ rc = hc_execute(s, command.action, command.object_type, &command.object,
+ &data);
+
+ if (rc < 0) {
+ switch (rc) {
+ case INPUT_ERROR:
+ ERROR("Wrong input parameters");
+ break;
+ case UNSUPPORTED_CMD_ERROR:
+ ERROR("Unsupported command");
+ break;
+ default:
+ ERROR("Error executing command");
+ break;
+ }
+ goto ERR_COMMAND;
+ }
+
+ if (!data) goto ERR_QUERY;
+
+ if (!hc_data_get_result(data)) goto ERR_DATA;
+
+ size_t size = hc_data_get_size(data);
+ if (size > 0) {
+ printf("Success: got %ld %s\n", size, object_type_str(command.object_type));
+ } else {
+ printf("Success.\n");
+ }
+
+ if (command.action == ACTION_LIST) {
+ hc_data_foreach(data, obj, {
+ rc = hc_object_snprintf(buf, MAXSZ_HC_OBJECT, command.object_type, obj);
+ if (rc < 0)
+ WARN("Display error");
+ else if (rc >= MAXSZ_HC_OBJECT)
+ WARN("Output truncated");
+ else
+ printf("%s\n", buf);
+ });
+ }
+
+ hc_data_free(data);
+ hc_sock_free(s);
+ return EXIT_SUCCESS;
+
+ERR_DATA:
+ hc_data_free(data);
+ERR_QUERY:
+ERR_COMMAND:
+ERR_CONNECT:
+ hc_sock_free(s);
+ERR_SOCKET:
+ERR_OPTIONS:
+ printf("Error.\n");
+ return EXIT_FAILURE;
+}
diff --git a/ctrl/libhicnctrl/src/libhicnctrl-config.cmake.in b/ctrl/libhicnctrl/src/libhicnctrl-config.cmake.in
new file mode 100644
index 000000000..a27d85cde
--- /dev/null
+++ b/ctrl/libhicnctrl/src/libhicnctrl-config.cmake.in
@@ -0,0 +1,8 @@
+@PACKAGE_INIT@
+
+set(Libhicnctrl_VERSION_MAJOR "@VERSION_MAJOR@")
+set(Libhicnctrl_VERSION_MINOR "@VERSION_MINOR@")
+set(Libhicnctrl_VERSION_PATCH "@VERSION_PATCH@")
+
+set_and_check(Libhicnctrl_INCLUDE_DIRS "@PACKAGE_Libhicnctrl_INCLUDE_DIRS@")
+include("${CMAKE_CURRENT_LIST_DIR}/libhicnctrl-targets.cmake")
diff --git a/ctrl/libhicnctrl/src/module.h b/ctrl/libhicnctrl/src/module.h
new file mode 100644
index 000000000..51fd9f942
--- /dev/null
+++ b/ctrl/libhicnctrl/src/module.h
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file modules.h
+ * \brief hicn-light module interface.
+ */
+
+#ifndef HICNCTRL_MODULE_H
+#define HICNCTRL_MODULE_H
+
+#include <stdint.h>
+
+#include <hicn/ctrl/data.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/socket.h>
+
+#include "request.h"
+
+/*
+ * execute is used for sync code (eg. in VPP), while serialize/parse for
+ * sync/async code (eg. in hicn-light).
+ */
+typedef int (*hc_execute_t)(hc_sock_t *, hc_object_t *, hc_data_t *);
+typedef int (*hc_serialize_t)(const hc_object_t *, uint8_t *);
+
+typedef struct {
+ int (*parse)(const uint8_t *buffer, size_t size, hc_object_t *object);
+ size_t serialized_size;
+ hc_serialize_t serialize[ACTION_N];
+ hc_execute_t execute[ACTION_N];
+} hc_module_object_ops_t;
+
+#define HC_MODULE_OBJECT_OPS_EMPTY \
+ (hc_module_object_ops_t) { \
+ .parse = NULL, .serialized_size = 0, \
+ .execute = \
+ { \
+ [ACTION_CREATE] = NULL, \
+ [ACTION_DELETE] = NULL, \
+ [ACTION_LIST] = NULL, \
+ [ACTION_SET] = NULL, \
+ }, \
+ .serialize = { \
+ [ACTION_CREATE] = NULL, \
+ [ACTION_DELETE] = NULL, \
+ [ACTION_LIST] = NULL, \
+ [ACTION_SET] = NULL, \
+ }, \
+ }
+
+#define DECLARE_MODULE_OBJECT_OPS_H(PREFIX, NAME) \
+ extern const hc_module_object_ops_t PREFIX##_##NAME##_module_ops;
+
+/* Underscore'd functions take a hc_object_t as a parameter */
+
+#define HC_MODULE_OBJECT_OPS(PREFIX, NAME) \
+ (hc_module_object_ops_t) { \
+ .parse = _##PREFIX##_##NAME##_parse, \
+ .serialized_size = sizeof(cmd_##NAME##_list_item_t), \
+ .execute = \
+ { \
+ [ACTION_CREATE] = NULL, \
+ [ACTION_DELETE] = NULL, \
+ [ACTION_LIST] = NULL, \
+ [ACTION_SET] = NULL, \
+ }, \
+ .serialize = { \
+ [ACTION_CREATE] = PREFIX##_##NAME##_serialize_create, \
+ [ACTION_DELETE] = PREFIX##_##NAME##_serialize_delete, \
+ [ACTION_LIST] = PREFIX##_##NAME##_serialize_list, \
+ [ACTION_SET] = PREFIX##_##NAME##_serialize_set, \
+ } \
+ }
+
+#define DECLARE_MODULE_OBJECT_OPS(PREFIX, NAME) \
+ const hc_module_object_ops_t PREFIX##_##NAME##_module_ops = { \
+ .parse = _##PREFIX##_##NAME##_parse, \
+ .serialized_size = sizeof(cmd_##NAME##_list_item_t), \
+ .execute = \
+ { \
+ [ACTION_CREATE] = NULL, \
+ [ACTION_DELETE] = NULL, \
+ [ACTION_LIST] = NULL, \
+ [ACTION_SET] = NULL, \
+ }, \
+ .serialize = { \
+ [ACTION_CREATE] = PREFIX##_##NAME##_serialize_create, \
+ [ACTION_DELETE] = PREFIX##_##NAME##_serialize_delete, \
+ [ACTION_LIST] = PREFIX##_##NAME##_serialize_list, \
+ [ACTION_SET] = PREFIX##_##NAME##_serialize_set, \
+ }};
+
+#define DECLARE_VPP_MODULE_OBJECT_OPS(PREFIX, NAME) \
+ const hc_module_object_ops_t PREFIX##_##NAME##_module_ops = { \
+ .execute = \
+ { \
+ [ACTION_CREATE] = PREFIX##_##NAME##_create, \
+ [ACTION_DELETE] = PREFIX##_##NAME##_delete, \
+ [ACTION_LIST] = PREFIX##_##NAME##_list, \
+ [ACTION_SET] = PREFIX##_##NAME##_set, \
+ }, \
+ .serialize = \
+ { \
+ [ACTION_CREATE] = NULL, \
+ [ACTION_DELETE] = NULL, \
+ [ACTION_LIST] = NULL, \
+ [ACTION_SET] = NULL, \
+ }, \
+ };
+
+typedef struct {
+ /** Create module-specific data storage */
+ void *(*create_data)(const char *);
+
+ /** Release module-specific data storage */
+ void (*free_data)(void *);
+
+ /** Retrieve underlying file descriptor */
+ int (*get_fd)(hc_sock_t *);
+
+ /** Retrieve underlying receive buffer */
+ int (*get_recv_buffer)(hc_sock_t *, uint8_t **buffer, size_t *size);
+
+ /** Connect control socket to the forwarder */
+ int (*connect)(hc_sock_t *);
+
+ /** Disconnect control socket from forwarder */
+ int (*disconnect)(hc_sock_t *);
+
+ /** Populate the TX buffer with the serialization of the next request to be
+ * sent */
+ ssize_t (*prepare)(hc_sock_t *, hc_request_t *, uint8_t **buffer);
+
+ /** Send the content of the TX buffer */
+ int (*send)(hc_sock_t *, uint8_t *buffer, size_t size);
+
+ /** Receive responses in the RX buffer */
+ int (*recv)(hc_sock_t *);
+
+ /** Process the content of the RX buffer to populate result data */
+ int (*process)(hc_sock_t *, size_t count);
+
+ hc_module_object_ops_t object_vft[OBJECT_TYPE_N];
+} hc_sock_ops_t;
+
+#endif /* HICNCTRL_MODULE_H */
diff --git a/ctrl/libhicnctrl/src/module_object.c b/ctrl/libhicnctrl/src/module_object.c
new file mode 100644
index 000000000..8b1378917
--- /dev/null
+++ b/ctrl/libhicnctrl/src/module_object.c
@@ -0,0 +1 @@
+
diff --git a/ctrl/libhicnctrl/src/module_object.h b/ctrl/libhicnctrl/src/module_object.h
new file mode 100644
index 000000000..5081aa715
--- /dev/null
+++ b/ctrl/libhicnctrl/src/module_object.h
@@ -0,0 +1,10 @@
+#ifndef HICNCTRL_MODULES_OBJECT_H
+#define HICNCTRL_MODULES_OBJECT_H
+
+ssize_t hc_object_serialize(hc_action_t action, hc_object_type_t object_type,
+ hc_object_t *object, hc_msg_t *msg);
+
+int hc_object_parse(hc_object_type_t object_type, uint8_t *buffer,
+ hc_object_t *object);
+
+#endif /* HICNCTRL_MODULES_OBJECT_H */
diff --git a/ctrl/libhicnctrl/src/modules/CMakeLists.txt b/ctrl/libhicnctrl/src/modules/CMakeLists.txt
index e07ab8c99..f3e1a6342 100644
--- a/ctrl/libhicnctrl/src/modules/CMakeLists.txt
+++ b/ctrl/libhicnctrl/src/modules/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2023 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,38 +11,99 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
-
-
+##############################################################
+# Hicn Light NG Module
+##############################################################
list(APPEND HICNLIGHT_MODULE_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light_api.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/connection.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/face.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/listener.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/mapme.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/route.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/stats.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/strategy.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/subscription.c
)
+list(APPEND HICNLIGHT_MODULE_HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/connection.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/face.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/listener.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/mapme.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/route.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/stats.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/strategy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light/subscription.h
+ )
+
build_module(hicnlightctrl_module
- SHARED
- SOURCES ${HICNLIGHT_MODULE_SOURCE_FILES}
- DEPENDS ${DEPENDENCIES}
- COMPONENT ${LIBHICNCTRL_COMPONENT}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- COMPILE_OPTIONS ${COMPILE_FLAGS}
+ SOURCES ${HICNLIGHT_MODULE_SOURCE_FILES} ${HICNLIGHT_MODULE_HEADER_FILES}
+ DEPENDS ${DEPENDENCIES}
+ COMPONENT ${LIBHICNCTRL_COMPONENT}
+ LINK_LIBRARIES PRIVATE ${HICN_LIBRARIES}
+ INCLUDE_DIRS PRIVATE ${INCLUDE_DIRS}
+ DEFINITIONS PRIVATE ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS PRIVATE ${COMPILE_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
+
+##############################################################
+# VPP Module
+##############################################################
if(BUILD_HICNPLUGIN AND ${CMAKE_SYSTEM_NAME} MATCHES "Linux")
- list(APPEND HICNLIGHT_PLUGIN_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin_api.c
+ if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ find_package(HicnPlugin ${CURRENT_VERSION} REQUIRED)
+ find_package(Safevapi ${CURRENT_VERSION} REQUIRED)
+ else()
+ list(APPEND DEPENDENCIES
+ ${SAFE_VAPI_SHARED}
+ )
+ endif()
+
+
+ list(APPEND HICN_PLUGIN_SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin/listener.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin/route.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin/strategy.c
)
- build_module(vppctrl_module
- SHARED
- SOURCES ${HICNLIGHT_PLUGIN_SOURCE_FILES}
- DEPENDS ${DEPENDENCIES}
- LINK_LIBRARIES ${HICNPLUGIN_LIBRARIES} ${SAFE_VAPI_LIBRARIES}
- COMPONENT ${LIBHICNCTRL_COMPONENT_MODULES}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- COMPILE_OPTIONS ${COMPILE_FLAGS}
- LINK_FLAGS "-Wl,-unresolved-symbols=ignore-in-shared-libs"
+ list(APPEND HICN_PLUGIN_HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin/base.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin/listener.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin/route.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_plugin/strategy.h
+ )
+
+ ##############################################################
+ # Compiler Options
+ ##############################################################
+ set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ ${MARCH_COMPILER_OPTIONS}
+ PRIVATE "-Wno-address-of-packed-member"
+ )
+
+ ##############################################################
+ # Compiler Definitions
+ ##############################################################
+ list(APPEND COMPILER_DEFINITIONS
+ PRIVATE "-DHICN_VPP_PLUGIN=1"
)
-endif() \ No newline at end of file
+ build_module(vppctrl_module
+ SOURCES ${HICN_PLUGIN_SOURCE_FILES} ${HICN_PLUGIN_HEADER_FILES}
+ DEPENDS ${DEPENDENCIES}
+ LINK_LIBRARIES
+ PRIVATE ${HICN_LIBRARIES}
+ PRIVATE ${HICNPLUGIN_LIBRARIES}
+ PRIVATE ${SAFE_VAPI_LIBRARIES}
+ COMPONENT ${LIBHICNCTRL_COMPONENT_MODULES}
+ INCLUDE_DIRS PRIVATE ${INCLUDE_DIRS}
+ DEFINITIONS PRIVATE ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ )
+endif()
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light.c b/ctrl/libhicnctrl/src/modules/hicn_light.c
new file mode 100644
index 000000000..96cdda2d2
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light.c
@@ -0,0 +1,1435 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file modules/hicn_light.c
+ * \brief Implementation of hicn-light module.
+ */
+
+#include <assert.h> // assert
+#include <fcntl.h> // fcntl
+#include <stdbool.h>
+#include <stdio.h> // snprintf
+#include <string.h> // memmove, strcasecmp
+#include <sys/socket.h> // socket
+#include <sys/types.h> // getpid
+#include <unistd.h> // close, fcntl, getpid
+
+#ifdef __linux__
+#include <sys/syscall.h>
+#define gettid() syscall(SYS_gettid)
+#endif /* __linux__ */
+
+#include <strings.h>
+
+#include <hicn/ctrl/hicn-light.h>
+#include <hicn/ctrl/socket.h>
+
+#include "../api_private.h"
+#include "../objects/connection.h" // hc_connection_has_local
+#include "../objects/listener.h" // hc_listener_is_local
+#include "../objects/route.h" // hc_route_has_face
+#include "../objects/stats.h"
+#include "../request.h"
+#include "../socket_private.h"
+#include "hicn_light.h"
+
+#include "hicn_light/base.h"
+#include "hicn_light/connection.h"
+#include "hicn_light/face.h"
+#include "hicn_light/listener.h"
+#include "hicn_light/mapme.h"
+#include "hicn_light/route.h"
+#include "hicn_light/stats.h"
+#include "hicn_light/strategy.h"
+#include "hicn_light/subscription.h"
+
+#pragma GCC diagnostic ignored "-Warray-bounds"
+
+#define DEFAULT_SOCK_RECV_TIMEOUT_MS 100
+
+#define PORT 9695
+
+#define BOOLSTR(x) ((x) ? "true" : "false")
+
+hc_sock_light_data_t *hc_sock_light_data_create(const char *url) {
+ hc_sock_light_data_t *s = malloc(sizeof(hc_sock_light_data_t));
+ if (!s) goto ERR_MALLOC;
+
+ s->roff = s->woff = 0;
+ s->remaining = 0;
+ s->got_header = false;
+
+ s->url = url ? strdup(url) : NULL;
+
+ s->fd = socket(AF_INET, SOCK_DGRAM, 0);
+ if (s->fd < 0) goto ERR_SOCKET;
+
+#if 0
+ struct timeval tv = {.tv_sec = 0,
+ .tv_usec = DEFAULT_SOCK_RECV_TIMEOUT_MS * 1000};
+ if (setsockopt(s->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
+ perror("setsockopt");
+ goto ERR_TIMEOUT;
+ }
+#endif
+
+ return s;
+
+#if 0
+ERR_TIMEOUT:
+#endif
+ close(s->fd);
+ERR_SOCKET:
+ if (s->url) free(s->url);
+ free(s);
+ERR_MALLOC:
+ return NULL;
+}
+
+void hc_sock_light_data_free(hc_sock_light_data_t *data) {
+ if (data->url) free(data->url);
+ free(data);
+}
+
+static const struct in6_addr loopback_addr = IN6ADDR_LOOPBACK_INIT;
+
+/******************************************************************************
+ * Control socket
+ ******************************************************************************/
+
+#define AVAILABLE(s) ((s)->woff - (s)->roff)
+
+/**
+ * \brief Parse a connection URL into a sockaddr
+ * \param [in] url - URL
+ * \param [out] sa - Resulting struct sockaddr, expected zero'ed.
+ * \return 0 if parsing succeeded, a negative error value otherwise.
+ */
+static int hicnlight_parse_url(const char *url, struct sockaddr *sa) {
+ char ip[100];
+ char protocol[100];
+ int port = PORT;
+ if (url) {
+ int ret = sscanf(url, "%99[^:]://%99[^:]:%99d[^/]", protocol, ip, &port);
+ if (ret == EOF) return -1;
+ }
+
+#ifdef __linux__
+ srand(time(NULL) ^ getpid() ^ gettid());
+#else
+ srand((unsigned int)(time(NULL) ^ getpid()));
+#endif /* __linux__ */
+
+ /*
+ * A temporary solution is to inspect the sa_family fields of the passed in
+ * sockaddr, which defaults to AF_UNSPEC (0) and thus creates an IPv4/TCP
+ * connection to localhost.
+ */
+ switch (sa->sa_family) {
+ case AF_UNSPEC:
+ case AF_INET: {
+ struct sockaddr_in *sai = (struct sockaddr_in *)sa;
+ sai->sin_family = AF_INET;
+ sai->sin_port = htons(port);
+ if (url) {
+ int ret = inet_pton(AF_INET, ip, &(sai->sin_addr.s_addr));
+ if (ret != 1) return -1;
+ } else {
+ sai->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ }
+ break;
+ }
+ case AF_INET6: {
+ struct sockaddr_in6 *sai6 = (struct sockaddr_in6 *)sa;
+ sai6->sin6_family = AF_INET6;
+ sai6->sin6_port = htons(port);
+ if (url) {
+ int ret = inet_pton(AF_INET6, ip, &(sai6->sin6_addr));
+ if (ret != 1) return -1;
+ } else {
+ sai6->sin6_addr = loopback_addr;
+ }
+ break;
+ }
+ default:
+ return -1;
+ }
+
+ return 0;
+}
+
+/*
+ * Return codes:
+ * < 0 : error; invalid buffer data -> flush
+ * otherwise, seq_num of the identified request
+ */
+static int hicnlight_process_header(hc_sock_t *sock) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+ hc_object_type_t object_type = OBJECT_TYPE_UNDEFINED;
+
+ /* Check we have at least a header's worth of data, and consume it */
+ if (AVAILABLE(s) < sizeof(hc_msg_header_t)) return 0;
+
+ hc_msg_t *msg = (hc_msg_t *)(s->buf + s->roff);
+
+ // INFO("Processing header header %s", command_type_str(msg->hdr.command_id));
+ s->roff += sizeof(hc_msg_header_t);
+ s->got_header = true;
+
+ /* How many elements are we expecting in the reply ? */
+ s->remaining = msg->header.length;
+
+ /* Identify request being parsed */
+ int seq = msg->header.seq_num;
+ hc_request_t *request = NULL;
+ if (hc_sock_map_get(sock->map, seq, &request) < 0) {
+ ERROR("[hc_sock_light_process] Error searching for matching request");
+ return -1;
+ }
+ if (!request) {
+ ERROR("[hc_sock_light_process] No request matching sequence number");
+ /*
+ * Currently: Ignore packet (alternatively: return 0 to discard in case of
+ * error; move s->got_header later in this case)
+ */
+ return -1;
+ }
+
+ sock->current_request = request;
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_data_t *data = hc_request_get_data(current_request);
+ _ASSERT(data);
+
+ switch (msg->header.message_type) {
+ case ACK_LIGHT:
+ _ASSERT(s->remaining == 0);
+
+ s->got_header = false;
+ if (!hc_request_is_subscription(request)) hc_data_set_complete(data);
+ break;
+
+ case NACK_LIGHT:
+ _ASSERT(s->remaining == 0);
+
+ s->got_header = false;
+ hc_data_set_error(data);
+ break;
+
+ case RESPONSE_LIGHT:
+ if (s->remaining == 0) {
+ /* Empty response (i.e. containing 0 elements) */
+ s->got_header = false;
+ hc_data_set_complete(data);
+ return 0;
+ }
+
+ /* Allocate buffer for response */
+ if (hc_data_allocate(data, s->remaining) < 0) {
+ ERROR("[hc_sock_light_process] Cannot allocate result buffer");
+ return -99;
+ }
+ break;
+
+ case NOTIFICATION_LIGHT: {
+ _ASSERT(s->remaining == 1);
+ /*
+ * Assumption: the whole notification data is returned in a single read
+ * and we immediately parse it.
+ */
+ // XXX assert enough buffer for object type + validate returned object
+ object_type = (hc_object_type_t)msg->header.command_id;
+ hc_data_clear(data);
+ hc_data_set_object_type(data, object_type);
+ if (hc_data_allocate(data, s->remaining) < 0) {
+ ERROR("[hc_sock_light_process] Cannot allocate result buffer");
+ return -1;
+ }
+
+ hc_data_push(data, s->buf + s->roff);
+
+ s->roff += AVAILABLE(s);
+
+ hc_request_on_notification(request);
+
+ /*
+ * The buffer is cleared just before the next notification, which means
+ * it will have to be released upon exit. Otherwise we break the code
+ * dumping the notification synchronously (eg. hicnctrl -s).
+ */
+ // hc_data_clear(data);
+
+ s->got_header = false;
+ break;
+ }
+
+ default:
+ ERROR("[hc_sock_light_process] Invalid response received");
+ return -99;
+ }
+
+ return 0;
+}
+
+size_t hc_light_object_size(hc_object_type_t object_type);
+
+static int hicnlight_process_payload(hc_sock_t *sock) {
+ int err = 0;
+ int rc;
+
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+ hc_request_t *request = hc_sock_get_request(sock);
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_data_t *data = hc_request_get_data(current_request);
+
+ hc_object_type_t object_type = hc_data_get_object_type(data);
+ size_t object_size = hc_light_object_size(object_type);
+ if (object_size == 0) return -1;
+
+ /* We only process full elements (size is stored in data) */
+ size_t num_chunks = AVAILABLE(s) / object_size;
+
+ /* Check whether we have enough data to process */
+ if (num_chunks == 0) return 0;
+
+ /* Safeguard: _ASSERT(num_chunks < s->remaining); */
+ if (num_chunks > s->remaining) {
+ WARN(
+ "[hicnlight_process_payload] Unexpected num_chunks > "
+ "s->remaining");
+ num_chunks = s->remaining;
+ }
+
+ for (size_t i = 0; i < num_chunks; i++) {
+ /*
+ * Get storage offset in hc_data_t, which we assume is correctly
+ * provisioned.
+ * XXX
+ */
+ u8 *src = s->buf + s->roff;
+ hc_object_t *dst = (hc_object_t *)hc_data_get_free(data);
+ if (!dst) {
+ ERROR("[hc_sock_light_process] Error in hc_data_get_next");
+ err = -2;
+ break;
+ }
+
+ // XXX we might want to display even incomplete data when printing (eg.
+ // string truncation), and be very strict when processing.
+ rc = hc_sock_parse_object(sock, hc_data_get_object_type(data), src,
+ object_size, dst);
+ s->roff += object_size;
+ if (rc < 0) {
+ ERROR("Error parsing received object");
+ continue;
+ }
+ hc_data_inc_size(data);
+ }
+
+ /*
+ * If we are not expecting any more data, mark the reply as complete
+ */
+ s->remaining -= num_chunks;
+ if (s->remaining == 0) {
+ s->got_header = false;
+ hc_data_set_complete(data);
+ }
+
+ return err;
+}
+
+/*----------------------------------------------------------------------------
+ * Socket operations
+ *----------------------------------------------------------------------------*/
+
+static int hicnlight_get_fd(hc_sock_t *sock) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+ return s->fd;
+}
+
+static int hicnlight_get_recv_buffer(hc_sock_t *sock, uint8_t **buffer,
+ size_t *size) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+ *buffer = s->buf + s->woff;
+ *size = RECV_BUFLEN - s->woff;
+
+ return 0;
+}
+
+static int hicnlight_connect(hc_sock_t *sock) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+ struct sockaddr_storage ss;
+ memset(&ss, 0, sizeof(struct sockaddr_storage));
+
+ if (hicnlight_parse_url(s->url, (struct sockaddr *)&ss) < 0) goto ERR_PARSE;
+
+ size_t size = ss.ss_family == AF_INET ? sizeof(struct sockaddr_in)
+ : sizeof(struct sockaddr_in6);
+ if (connect(s->fd, (struct sockaddr *)&ss, (socklen_t)size) < 0) {
+ perror("connect error");
+ goto ERR_CONNECT;
+ }
+ return 0;
+
+ERR_CONNECT:
+ERR_PARSE:
+ return -1;
+}
+
+static int hicnlight_disconnect(hc_sock_t *sock) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+
+ /* Remove the connection created to send the command.
+ *
+ * Note this is done as a best effort and we don't expect to receive any
+ * answer from the forwarder (hence the NULL pdata pointer in the request).
+ */
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.connection.id = 0;
+ int rc =
+ strcpy_s(object.connection.name, sizeof(object.connection.name), "SELF");
+ if (rc == EOK)
+ hc_execute_async(sock, ACTION_DELETE, OBJECT_TYPE_CONNECTION, &object, NULL,
+ NULL);
+
+ close(s->fd);
+
+ return 0;
+}
+
+static ssize_t hicnlight_prepare_generic(hc_sock_t *sock, hc_request_t *request,
+ uint8_t **buffer) {
+ /* Dispatch to subrequest if any */
+ hc_request_t *current_request = hc_request_get_current(request);
+
+ /* We discard any result from the child request */
+ hc_request_reset_data(current_request);
+
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+
+ _ASSERT(hc_request_get_data(current_request) == NULL);
+ hc_data_t *data = hc_data_create(object_type);
+ if (!data) {
+ ERROR("[hicnlight_prepare_generic] Could not create data storage");
+ return -1;
+ }
+ hc_request_set_data(current_request, data);
+
+ /* Serialize request into message */
+ DEBUG("Calling serialize on %s %s", action_str(action),
+ object_type_str(object_type));
+ ssize_t msg_len = hc_sock_serialize_object(sock, action, object_type, object,
+ (uint8_t *)&s->msg);
+ if (msg_len < 0) {
+ ERROR("[hicnlight_prepare_generic] Could not serialize command %s %s",
+ action_str(action), object_type_str(object_type));
+ return INPUT_ERROR;
+ }
+
+ s->msg.header.seq_num = hc_request_get_seq(current_request);
+
+ *buffer = (uint8_t *)&s->msg;
+ return msg_len;
+}
+
+static int hicnlight_send(hc_sock_t *sock, uint8_t *buffer, size_t size) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+
+ int rc = (int)send(s->fd, buffer, size, 0);
+ if (rc < 0) {
+ perror("[hicnlight_send] Error sending message");
+ return -1;
+ }
+
+ // XXX regular behaviour for others
+ return 0;
+}
+
+// Example : face create udp
+// 1) face to connection (immediate)
+// connection to local listener (immediate) : why not both at the same
+// time listener get
+// listener create / nothing
+// connection create
+// connection get (if needed for populating face_id for instance, aka
+// if we
+// need to return data)
+
+static ssize_t hicnlight_prepare(hc_sock_t *sock, hc_request_t *request,
+ uint8_t **buffer);
+
+static ssize_t hicnlight_prepare_subrequest(
+ hc_sock_t *sock, hc_request_t *request, hc_action_t action,
+ hc_object_type_t object_type, hc_object_t *object, uint8_t **buffer) {
+ WITH_DEBUG({
+ if (object) {
+ char buf[MAXSZ_HC_OBJECT];
+ hc_object_snprintf(buf, sizeof(buf), object_type, object);
+ DEBUG("Creating subrequest %s/%s %s", action_str(action),
+ object_type_str(object_type), buf);
+ }
+ });
+ hc_request_make_subrequest(request, action, object_type, object);
+ return hicnlight_prepare(sock, request, buffer);
+}
+
+/*
+ * XXX shall we update the object in the request for faces ? it is not done
+ * for other objects, but for faces it is needed to further add a route !!!
+ */
+static ssize_t hicnlight_prepare_face_create(hc_sock_t *sock,
+ hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_object_t *object = hc_request_get_object(current_request);
+ hc_data_t *data = hc_request_get_data(current_request);
+ hc_face_t *face = &object->face;
+
+ // XXX those objects are created on stack and expected to be valid across
+ // several calls. A quick fix is to make them static
+ static hc_object_t connection;
+ static hc_object_t listener;
+
+ hc_request_state_t state;
+ const hc_connection_t *conn;
+
+NEXT:
+ state = hc_request_get_state(current_request);
+ DEBUG("hicnlight_prepare_face_create > %s", hc_request_state_str(state));
+
+ switch (state) {
+ case REQUEST_STATE_INIT:
+ _ASSERT(!data);
+
+ switch (face->type) {
+ case FACE_TYPE_HICN:
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_UDP:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_CREATE_CONNECTION_CREATE);
+ goto NEXT;
+ case FACE_TYPE_HICN_LISTENER:
+ case FACE_TYPE_TCP_LISTENER:
+ case FACE_TYPE_UDP_LISTENER:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_CREATE_LISTENER_CREATE);
+ goto NEXT;
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_N:
+ return -99; // Not implemented
+ }
+
+ case REQUEST_STATE_FACE_CREATE_CONNECTION_CREATE:
+ if (hc_face_to_connection(face, &connection.connection, true) < 0) {
+ ERROR("[hc_face_create] Could not convert face to connection.");
+ return -1;
+ }
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_CREATE_CONNECTION_CHECK);
+
+ return hicnlight_prepare_subrequest(sock, request, ACTION_CREATE,
+ OBJECT_TYPE_CONNECTION, &connection,
+ buffer);
+
+ case REQUEST_STATE_FACE_CREATE_CONNECTION_CHECK:
+ /*
+ * If the newly created face_id was not need, we would only
+ * need to return the same data result, which contains a ack/nack,
+ * simply updating the object type.
+ *
+ * With the current API, once the connection is created, our only
+ * solution is to list all connections and compare with the current one
+ * to find the created connection ID, and thus face ID.
+ */
+ /* Has the connection been successfully created ? */
+ if (!data || !hc_data_get_result(data)) return -1;
+
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_CREATE_CONNECTION_GET);
+ goto NEXT;
+
+ case REQUEST_STATE_FACE_CREATE_CONNECTION_GET:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_CREATE_CONNECTION_VERIFY);
+ return hicnlight_prepare_subrequest(sock, request, ACTION_GET,
+ OBJECT_TYPE_CONNECTION, &connection,
+ buffer);
+
+ case REQUEST_STATE_FACE_CREATE_CONNECTION_VERIFY:
+ if (!data || hc_data_get_size(data) != 1) return -1;
+
+ /* Newly created connection was found */
+ conn = (hc_connection_t *)hc_data_get_buffer(data);
+ DEBUG("created connection id=%d", conn->id);
+ object->face.id = conn->id;
+
+ break;
+
+ case REQUEST_STATE_FACE_CREATE_LISTENER_CREATE:
+ if (hc_face_to_listener(face, &listener.listener) < 0) {
+ ERROR("Could not convert face to listener.");
+ return -1;
+ }
+
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_CREATE_LISTENER_CHECK);
+ return hicnlight_prepare_subrequest(sock, request, ACTION_CREATE,
+ OBJECT_TYPE_LISTENER, &listener,
+ buffer);
+
+ break;
+
+ case REQUEST_STATE_FACE_CREATE_LISTENER_CHECK:
+ /*
+ * No need for face id here, simply return the hc_data_t structure
+ * with the ack/nack, and the proper object type
+ */
+ if (!data) return -1;
+ hc_data_set_object_type(data, OBJECT_TYPE_FACE);
+ break;
+
+#if 0
+ case REQUEST_STATE_COMPLETE:
+ hc_data_set_complete(data);
+ break;
+#endif
+
+ default:
+ return -1;
+ }
+ return 0;
+}
+
+static ssize_t hicnlight_prepare_face_delete(hc_sock_t *sock,
+ hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_object_t *object = hc_request_get_object(current_request);
+ hc_data_t *data = hc_request_get_data(current_request);
+ hc_face_t *face = &object->face;
+
+ // XXX those objects are created on stack and expected to be valid across
+ // several calls. A quick fix is to make them static
+ static hc_object_t connection;
+
+ hc_request_state_t state;
+
+NEXT:
+ state = hc_request_get_state(current_request);
+ DEBUG("hicnlight_prepare_face_delete > %s", hc_request_state_str(state));
+
+ switch (state) {
+ case REQUEST_STATE_INIT:
+ _ASSERT(!data);
+
+ switch (face->type) {
+ case FACE_TYPE_HICN:
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_UDP:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_DELETE_CONNECTION_DELETE);
+ goto NEXT;
+ case FACE_TYPE_HICN_LISTENER:
+ case FACE_TYPE_TCP_LISTENER:
+ case FACE_TYPE_UDP_LISTENER:
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_N:
+ return -99; // Not implemented
+ }
+
+ case REQUEST_STATE_FACE_DELETE_CONNECTION_DELETE:
+ if (hc_face_to_connection(face, &connection.connection, true) < 0) {
+ ERROR("[hc_face_create] Could not convert face to connection.");
+ return -1;
+ }
+ hc_request_set_state(current_request, REQUEST_STATE_COMPLETE);
+
+ return hicnlight_prepare_subrequest(sock, request, ACTION_DELETE,
+ OBJECT_TYPE_CONNECTION, &connection,
+ buffer);
+ case REQUEST_STATE_COMPLETE:
+ break;
+
+ default:
+ return -1;
+ }
+
+ return 0;
+}
+
+static ssize_t hicnlight_prepare_face_list(hc_sock_t *sock,
+ hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+ hc_data_t *data = hc_request_get_data(current_request);
+ hc_face_t face;
+
+ _ASSERT(action == ACTION_LIST);
+ _ASSERT(object_type == OBJECT_TYPE_FACE);
+
+ hc_request_state_t state = hc_request_get_state(current_request);
+ DEBUG("hicnlight_prepare_face_list > %s", hc_request_state_str(state));
+
+ switch (state) {
+ case REQUEST_STATE_INIT:
+ _ASSERT(!data);
+
+ hc_request_set_state(current_request,
+ REQUEST_STATE_FACE_LIST_CONNECTION_LIST);
+ return hicnlight_prepare_subrequest(
+ sock, request, ACTION_LIST, OBJECT_TYPE_CONNECTION, object, buffer);
+
+ case REQUEST_STATE_FACE_LIST_CONNECTION_LIST:
+ _ASSERT(data);
+ /*
+ * 'list connection' succeeded, we just need to allocate hc_data_t,
+ * create faces from connections, and return the data structure as if it
+ * was created by the query
+ */
+ hc_data_t *face_data = hc_data_create(object_type);
+ hc_data_allocate(face_data, hc_data_get_size(data));
+ foreach_connection(c, data) {
+ if (hc_face_from_connection(c, &face) < 0) {
+ ERROR("[hc_face_list] Could not convert connection to face.");
+ return -1;
+ }
+ hc_data_push(face_data, &face);
+ }
+ hc_data_set_complete(face_data);
+
+ hc_request_reset_data(current_request);
+ hc_request_set_data(current_request, face_data);
+
+ /* FACE/LIST could be part of FACE/GET */
+ break;
+
+ default:
+ return -1;
+ }
+
+ return 0;
+}
+
+static ssize_t hicnlight_prepare_get(hc_sock_t *sock, hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+ hc_data_t *data = hc_request_get_data(current_request);
+ hc_object_t *found;
+
+ hc_request_state_t state = hc_request_get_state(current_request);
+ DEBUG("hicnlight_prepare_get > %s", hc_request_state_str(state));
+
+ switch (state) {
+ case REQUEST_STATE_INIT:
+ _ASSERT(!data);
+ hc_request_set_state(current_request, REQUEST_STATE_GET_LIST);
+ return hicnlight_prepare_subrequest(sock, request, ACTION_LIST,
+ object_type, NULL, buffer);
+ case REQUEST_STATE_GET_LIST:
+ _ASSERT(data);
+
+ found = hc_data_find(data, object);
+ hc_data_t *found_data = hc_data_create(object_type);
+ if (found) {
+ hc_data_allocate(found_data, 1);
+ hc_data_push(found_data, found);
+ }
+ hc_data_set_complete(found_data);
+ hc_request_reset_data(current_request);
+ hc_request_set_data(current_request, found_data);
+ return 0;
+ default:
+ return -1; /* Unexpected */
+ }
+}
+
+// XXX This should process the content of pdata (unless at init), and
+// terminate by sending something
+static ssize_t hicnlight_prepare_face(hc_sock_t *sock, hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+
+ _ASSERT(object_type == OBJECT_TYPE_FACE);
+
+ switch (action) {
+ case ACTION_CREATE:
+ return hicnlight_prepare_face_create(sock, request, buffer);
+ case ACTION_DELETE:
+ return hicnlight_prepare_face_delete(sock, request, buffer);
+ case ACTION_LIST:
+ return hicnlight_prepare_face_list(sock, request, buffer);
+ default:
+ return -99; // Not implemented
+ }
+ return 0;
+}
+
+static ssize_t hicnlight_prepare_connection_create(hc_sock_t *sock,
+ hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+
+ _ASSERT(action == ACTION_CREATE);
+ _ASSERT(object_type == OBJECT_TYPE_CONNECTION);
+
+ hc_data_t *data = hc_request_get_data(current_request);
+
+ size_t size;
+ unsigned pos;
+ static hc_object_t listener;
+ const hc_object_t *obj_listener;
+ hc_data_t *listener_data = NULL;
+
+ hc_request_state_t state;
+
+NEXT:
+ state = hc_request_get_state(current_request);
+ DEBUG("hicnlight_prepare_connection_create > %s",
+ hc_request_state_str(state));
+
+ switch (state) {
+ case REQUEST_STATE_INIT:
+ /* Two behaviours depending on the content of local_addr and local_port:
+ * - empty : create connection on all existing listeners, and raise an
+ * error if none
+ * - otherwise, check whether a corresponding listener exists, and
+ * create it if necessary
+ *
+ * We assume connection has been already validated.
+ */
+ if (hc_connection_has_local(&object->connection)) {
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_CREATE_LISTENER_GET);
+ } else {
+ /*
+ * At least part of the local socket specification is missing, match
+ * against existing listeners
+ */
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_CREATE_LISTENER_LIST);
+ }
+ goto NEXT;
+
+ case REQUEST_STATE_CONNECTION_CREATE_LISTENER_LIST:
+
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_CREATE_LISTENER_ITERATE);
+ // XXX We are currently assuming an object is present for rewrite, fix
+ // this
+ return hicnlight_prepare_subrequest(sock, request, ACTION_LIST,
+ OBJECT_TYPE_LISTENER, NULL, buffer);
+
+ case REQUEST_STATE_CONNECTION_CREATE_LISTENER_ITERATE:
+ /*
+ * NOTE: we could create all connections in parallel to speed up
+ * processing
+ */
+ size = hc_data_get_size(data);
+ if (size < 0) return -1;
+ if (size == 0)
+ /* We are done, we cannot create a connection, return a Nack */
+ ; // XXX TODO
+ //
+ /* Save the list of listeners for later iteration */
+ listener_data = data;
+ hc_request_clear_data(current_request); // don't free data
+ data = NULL;
+ hc_request_set_state_count(current_request, 0);
+ hc_request_set_state(current_request, REQUEST_STATE_CONNECTION_CREATE_N);
+ goto NEXT; /* Start iteration */
+
+ case REQUEST_STATE_CONNECTION_CREATE_N:
+ /*
+ * IMPORTANT
+ *
+ * For now we only create a connection with the first non-local
+ * listener.
+ *
+ * Creating N connections in a single commands requires other
+ * changes to the code that we might done later:
+ * - ack/nack is not sufficient, all create function should return the
+ * list of created connections
+ * - this would allow us to avoid a GET at the end of face creation to
+ * retrieve the connection id.
+ * - face create should correspond to N connection create (should work
+ * out of the box provided we don't expect a single connection back).
+ * - route+face creation might then create N faces, and thus we would
+ * have to add N routes.
+ */
+ assert(listener_data);
+
+ // We need to back it up as the subrequest will clear the results
+ pos = hc_request_get_state_count(current_request);
+ size = hc_data_get_size(listener_data);
+ /* We have data if pos > 0, and we did not skipped previous ones */
+ if (data && !hc_data_get_result(data)) {
+ INFO("Failed to create connection for listener %d / %d", pos - 1, size);
+ // XXX we might allow connections that already exist... how to manage
+ // the names
+ return -1;
+ }
+
+ /*
+ * Previous connection was successfully created, let's continue but
+ * first check whether we reached the last one, which would complete the
+ * request.
+ */
+ if (pos >= size) {
+ hc_data_free(listener_data);
+ hc_request_set_state(request, REQUEST_STATE_COMPLETE);
+ goto NEXT;
+ }
+
+ /* Sending count'th connection creation */
+ obj_listener = hc_data_get_object(listener_data, pos);
+
+ // Filter which listener we use
+ // same protocol ? ip ? port ?
+ // avoid local ?
+ if (hc_listener_is_local(&obj_listener->listener)) {
+ /* Skip listener */
+ DEBUG("Skipped local listener");
+ hc_request_set_state_count(current_request, pos + 1);
+ goto NEXT;
+ }
+
+ DEBUG("Creating connection with listener # %d / %d", pos, size);
+ /* We complement missing information from listener */
+ // XXX is_family, etc.
+ object->connection.family = obj_listener->listener.family;
+ object->connection.local_addr = obj_listener->listener.local_addr;
+ object->connection.local_port = obj_listener->listener.local_port;
+ snprintf(object->connection.interface_name, INTERFACE_LEN, "%s",
+ obj_listener->listener.interface_name);
+
+ hc_request_set_state_count(current_request, pos + 1);
+ return hicnlight_prepare_subrequest(
+ sock, request, ACTION_CREATE, OBJECT_TYPE_CONNECTION, object, buffer);
+
+ /* Request listener to further check existence */
+ case REQUEST_STATE_CONNECTION_CREATE_LISTENER_GET:
+ /* Ensure we have a corresponding local listener */
+ if (hc_connection_to_local_listener(&object->connection,
+ &listener.listener) < 0) {
+ ERROR(
+ "[hicnlight_prepare_connection_create] Could not "
+ "convert connection to local listener.");
+ return -1;
+ }
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_CREATE_LISTENER_VERIFY);
+ return hicnlight_prepare_subrequest(
+ sock, request, ACTION_GET, OBJECT_TYPE_LISTENER, &listener, buffer);
+
+ break;
+
+ /* Check whether listener exists in GET results */
+ case REQUEST_STATE_CONNECTION_CREATE_LISTENER_VERIFY:
+ if (!data) return -1;
+ switch (hc_data_get_size(data)) {
+ case 0:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_CREATE_LISTENER_CREATE);
+ break;
+ case 1:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_CREATE);
+ break;
+ default:
+ return -1;
+ }
+ goto NEXT;
+
+ /* Create associated listener */
+ case REQUEST_STATE_CONNECTION_CREATE_LISTENER_CREATE:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_CREATE_LISTENER_CHECK);
+ return hicnlight_prepare_subrequest(sock, request, ACTION_CREATE,
+ OBJECT_TYPE_LISTENER, &listener,
+ buffer);
+
+ /* Check whether listener creation succeeded */
+ case REQUEST_STATE_CONNECTION_CREATE_LISTENER_CHECK:
+ if (!data || !hc_data_get_result(data)) return -1;
+ hc_request_set_state(current_request, REQUEST_STATE_CONNECTION_CREATE);
+ goto NEXT;
+
+ /* Create connection */
+ case REQUEST_STATE_CONNECTION_CREATE:
+ /*
+ * Break recursion by directly calling hicnlight_prepare_generic on
+ * the initial request, that can now be executed since all
+ * prerequisites are validated.
+ */
+ // return hicnlight_prepare_subrequest(
+ // sock, request, ACTION_CREATE, OBJECT_TYPE_CONNECTION, object,
+ // buffer);
+ hc_request_reset_data(current_request);
+ hc_request_set_state(current_request, REQUEST_STATE_COMPLETE);
+ return hicnlight_prepare_generic(sock, request, buffer);
+
+ case REQUEST_STATE_COMPLETE:
+ if (data) {
+ hc_data_set_complete(data);
+ } else {
+ /*
+ * No connection has been created, and we freed the data due to
+ * subrequest
+ */
+ data = hc_data_create(OBJECT_TYPE_CONNECTION);
+ hc_data_set_error(data);
+ }
+ break;
+
+ default:
+ return -1;
+ }
+ return 0;
+}
+
+static ssize_t hicnlight_prepare_route_create(hc_sock_t *sock,
+ hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+
+ _ASSERT(action == ACTION_CREATE);
+ _ASSERT(object_type == OBJECT_TYPE_ROUTE);
+
+ hc_data_t *data = hc_request_get_data(current_request);
+ const hc_object_t *face_obj;
+
+ hc_request_state_t state;
+
+NEXT:
+ state = hc_request_get_state(current_request);
+ DEBUG("hicnlight_prepare_route_create > %s", hc_request_state_str(state));
+
+ switch (state) {
+ case REQUEST_STATE_INIT:
+ if (hc_route_has_face(&object->route))
+ hc_request_set_state(current_request,
+ REQUEST_STATE_ROUTE_CREATE_FACE_CREATE);
+ else
+ hc_request_set_state(current_request, REQUEST_STATE_ROUTE_CREATE);
+ goto NEXT;
+
+ case REQUEST_STATE_ROUTE_CREATE_FACE_CREATE:
+ hc_request_set_state(current_request,
+ REQUEST_STATE_ROUTE_CREATE_FACE_CHECK);
+ return hicnlight_prepare_subrequest(
+ sock, request, ACTION_CREATE, OBJECT_TYPE_FACE,
+ (hc_object_t *)&object->route.face, buffer);
+
+ case REQUEST_STATE_ROUTE_CREATE_FACE_CHECK:
+ if (!data) return -1;
+ int rc = hc_data_get_result(data);
+ if (rc < 0) return -1;
+
+ if (hc_data_get_size(data) != 1) return -1;
+
+ face_obj = hc_data_get_object(data, 0);
+ DEBUG("Created face id=%d", face_obj->face.id);
+ object->route.face_id = face_obj->face.id;
+
+ hc_request_set_state(current_request, REQUEST_STATE_ROUTE_CREATE);
+ goto NEXT;
+
+ /* Create route */
+ case REQUEST_STATE_ROUTE_CREATE:
+ /*
+ * Break recursion by directly calling hicnlight_prepare_generic on the
+ * initial request, that can now be executed since all prerequisites are
+ * validated.
+ */
+ hc_request_set_state(current_request, REQUEST_STATE_COMPLETE);
+ return hicnlight_prepare_generic(sock, request, buffer);
+
+ case REQUEST_STATE_COMPLETE:
+ hc_data_set_complete(data);
+ break;
+
+ default:
+ return -1;
+ }
+ return 0;
+}
+
+static ssize_t hicnlight_prepare_connection_delete(hc_sock_t *sock,
+ hc_request_t *request,
+ uint8_t **buffer) {
+ hc_request_t *current_request = hc_request_get_current(request);
+
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+
+ _ASSERT(action == ACTION_DELETE);
+ _ASSERT(object_type == OBJECT_TYPE_CONNECTION);
+
+ hc_data_t *data = hc_request_get_data(current_request);
+ hc_request_state_t state;
+
+NEXT:
+ state = hc_request_get_state(current_request);
+ DEBUG("hicnlight_prepare_connection_delete > %s",
+ hc_request_state_str(state));
+
+ switch (state) {
+ case REQUEST_STATE_INIT:
+ /* Two behaviours depending on the content of the connection id:
+ * - Valid Id : delete connection with provided ID
+ * - Invalid Id: Retrieve ID and then delete connection
+ *
+ * We assume connection has been already validated.
+ */
+ if (hc_connection_has_valid_id(&object->connection)) {
+ // Id is valid. Proceed with deleting the connection.
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_DELETE_WITH_ID);
+ } else {
+ // Id is not valid. Try to retrieve it using the info in the connection.
+ hc_request_set_state(current_request, REQUEST_STATE_CONNECTION_GET);
+ }
+ goto NEXT;
+
+ case REQUEST_STATE_CONNECTION_DELETE_WITH_ID:
+ // We have a valid id. Let's delete the connection.
+ hc_request_reset_data(current_request);
+ hc_request_set_state(current_request, REQUEST_STATE_COMPLETE);
+ return hicnlight_prepare_generic(sock, request, buffer);
+
+ case REQUEST_STATE_CONNECTION_GET:
+ // Get the connection info from the forwarder.
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_DELETE_AFTER_GET);
+ return hicnlight_prepare_subrequest(
+ sock, request, ACTION_GET, OBJECT_TYPE_CONNECTION, object, buffer);
+
+ case REQUEST_STATE_CONNECTION_DELETE_AFTER_GET:
+ // We got the response from the forwarder. If valid, let's take the ID and
+ // delete the connection by ID.
+ if (!data) return -1;
+
+ int rc = hc_data_get_result(data);
+ if (rc < 0) {
+ return -1;
+ }
+
+ if (hc_data_get_size(data) != 1) {
+ return -1;
+ }
+
+ _ASSERT(hc_data_get_object_type(data) == OBJECT_TYPE_CONNECTION);
+
+ object->connection.id = hc_data_get_object(data, 0)->connection.id;
+
+ hc_request_set_state(current_request,
+ REQUEST_STATE_CONNECTION_DELETE_WITH_ID);
+ goto NEXT;
+
+ case REQUEST_STATE_COMPLETE:
+ // Connection delete complete.
+ hc_data_set_complete(data);
+ break;
+
+ default:
+ return -1;
+ }
+
+ return 0;
+}
+
+static int hicnlight_recv(hc_sock_t *sock) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+ int rc;
+
+ /*
+ * This condition should be ensured to guarantee correct processing of
+ * messages. With TCP, we need at least a header as we will receive part of
+ * the stream. With UDP, we need the be able to receive the full datagram,
+ * otherwise the rest will be lost.
+ *
+ * Let's be sure to always be able to receive at least 1 JUMBO_MTU, which
+ * should be fine for al situations.
+ */
+ _ASSERT(RECV_BUFLEN - s->woff > JUMBO_MTU);
+
+ rc = (int)recv(s->fd, s->buf + s->woff, RECV_BUFLEN - s->woff, 0);
+ if (rc == 0) {
+ /* Connection has been closed */
+ return 0;
+ }
+ if (rc < 0) {
+ /*
+ * Let's not return 0 which currently means the socket has been closed
+ */
+ if (errno == EWOULDBLOCK) {
+ // XXX TODO ?if (hc_request_get_action(request) == ACTION_SUBSCRIBE)
+ // return 0;
+ return -1;
+ }
+ if (errno == EINTR) {
+ WARN("recv has been stopped by signal");
+ return -1;
+ }
+ perror("hc_sock_light_recv");
+ return -1;
+ }
+ DEBUG("Received rc=%ld bytes", rc);
+ s->woff += rc;
+
+ return rc;
+}
+
+/*
+ *
+ * @param [in] data - hc_data_t structure allocated for the request
+ *
+ * This function is the entry point for all requests, and from there we will
+ * decide whether
+ *
+ */
+static ssize_t hicnlight_prepare(hc_sock_t *sock, hc_request_t *request,
+ uint8_t **buffer) {
+ /* Dispatch to subrequest if any */
+ hc_request_t *current_request = hc_request_get_current(request);
+
+ // XXX when do we create data... once for every step
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+
+ static hc_object_t object_subscribe;
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HC_OBJECT];
+ hc_request_state_t state = hc_request_get_state(current_request);
+ hc_object_snprintf(buf, sizeof(buf), object_type, object);
+ DEBUG("[hicnlight_prepare] %s %s [%s] %s", action_str(action),
+ object_type_str(object_type), hc_request_state_str(state), buf);
+ });
+
+ /*
+ * Here the request is in progress and we just need to iterate through the
+ * FSM, or complete it.
+ */
+ /*
+ * Specific treatment for
+ * CREATE/ROUTE with face
+ * SUBSCRIBE/(*)
+ * GET/(*)
+ * (*)/FACE
+ */
+
+ /*
+ * Special treatment for faces.
+ *
+ * This function will be called multiple times in order to process the
+ * complex request, involving several calls to the API. The process is
+ * responsible for going through the related state machine, and complete the
+ * request when appropriate.
+ */
+ if (object_type == OBJECT_TYPE_FACE)
+ return hicnlight_prepare_face(sock, request, buffer);
+
+ switch (action) {
+ case ACTION_CREATE:
+ switch (object_type) {
+ case OBJECT_TYPE_ROUTE:
+ /* Route might require face creation */
+ return hicnlight_prepare_route_create(sock, request, buffer);
+ case OBJECT_TYPE_CONNECTION:
+ /* Connection could have no corresponging listener, or no local info
+ * provided */
+ return hicnlight_prepare_connection_create(sock, request, buffer);
+ default:
+ break;
+ }
+ break;
+
+ case ACTION_GET:
+ return hicnlight_prepare_get(sock, request, buffer);
+
+ case ACTION_SUBSCRIBE:
+ /* Transform subscription queries */
+ memset(&object_subscribe, 0, sizeof(hc_object_t));
+ object->subscription.topics = topic_from_object_type(object_type);
+
+ hc_request_set(request, ACTION_CREATE, OBJECT_TYPE_SUBSCRIPTION, object);
+ break;
+
+ case ACTION_DELETE:
+ switch (object_type) {
+ case OBJECT_TYPE_CONNECTION:
+ return hicnlight_prepare_connection_delete(sock, request, buffer);
+ break;
+
+ default:
+ break;
+ }
+
+ default:
+ break;
+ }
+
+ /*
+ * Generic requests should complete after a single call to hicnlight_send,
+ * with *pdata = NULL. If *pdata is not NULL, that means the request has
+ * completed and we can close it.
+ * It is the responsability of each state machine to complete the request
+ * otherwise.
+ */
+ hc_data_t *data = hc_request_get_data(current_request);
+ if (data) {
+ hc_request_set_complete(current_request);
+ return 0;
+ }
+
+ return hicnlight_prepare_generic(sock, request, buffer);
+}
+
+/*
+ * This function processes incoming data in the ring buffer. Multiple requests
+ * might be interleaves, including regular requests and notifications.
+ * Responses might arrive fragment over several read events, but our
+ * assumption is that fragments arrive consecutively and are not interleaves
+ * with fragments from other requests... otherwise we would have to way to
+ * reconstruct a message.
+ *
+ * count != 0 when an external process has added data to the ring buffer
+ * without updating indices
+ */
+static int hicnlight_process(hc_sock_t *sock, size_t count) {
+ hc_sock_light_data_t *s = (hc_sock_light_data_t *)sock->data;
+ int rc = -99;
+
+ if (count > 0) s->woff += count;
+
+ /*
+ * We loop consuming messages until there is no more data in the ring
+ * buffer, or that we can find an entire message. Messages are received
+ * sequentially, and we keep track of incomplete requests in s->cur_request.
+ */
+ while (AVAILABLE(s) > 0) {
+ if (!s->got_header) {
+ rc = hicnlight_process_header(sock);
+ } else {
+ rc = hicnlight_process_payload(sock);
+ }
+ if (rc < 0) break;
+ }
+
+ if ((rc == -99) || (s->roff == s->woff)) {
+ /* Flush buffer */
+ s->woff = 0;
+ } else {
+ /* Clean up read data from buffer */
+ memmove(s->buf, s->buf + s->roff, AVAILABLE(s));
+ s->woff -= s->roff;
+ }
+ s->roff = 0;
+
+ return rc;
+}
+
+hc_sock_ops_t hc_sock_light = (hc_sock_ops_t) {
+ .create_data = (void *(*)(const char *))hc_sock_light_data_create,
+ .free_data = (void (*)(void *))hc_sock_light_data_free,
+ .get_fd = hicnlight_get_fd, .get_recv_buffer = hicnlight_get_recv_buffer,
+ .connect = hicnlight_connect, .disconnect = hicnlight_disconnect,
+ .prepare = hicnlight_prepare, .send = hicnlight_send, .recv = hicnlight_recv,
+ .process = hicnlight_process,
+#if 0
+ .object_vft = {
+ [OBJECT_TYPE_LISTENER] = HC_MODULE_OBJECT_OPS(hicnlight, listener),
+ [OBJECT_TYPE_CONNECTION] = HC_MODULE_OBJECT_OPS(hicnlight, connection),
+ [OBJECT_TYPE_FACE] = HC_MODULE_OBJECT_OPS_EMPTY,
+ [OBJECT_TYPE_PUNTING] = HC_MODULE_OBJECT_OPS_EMPTY,
+ [OBJECT_TYPE_CACHE] = HC_MODULE_OBJECT_OPS_EMPTY,
+ [OBJECT_TYPE_MAPME] = HC_MODULE_OBJECT_OPS_EMPTY,
+ [OBJECT_TYPE_WLDR] = HC_MODULE_OBJECT_OPS_EMPTY,
+ [OBJECT_TYPE_POLICY] = HC_MODULE_OBJECT_OPS_EMPTY,
+ [OBJECT_TYPE_ROUTE] = HC_MODULE_OBJECT_OPS(hicnlight, route),
+ [OBJECT_TYPE_STRATEGY] = HC_MODULE_OBJECT_OPS(hicnlight, strategy),
+ [OBJECT_TYPE_SUBSCRIPTION] = HC_MODULE_OBJECT_OPS(hicnlight, subscription),
+}
+#endif
+};
+
+size_t hc_light_object_size(hc_object_type_t object_type) {
+ hc_module_object_ops_t *vft = &hc_sock_light.object_vft[object_type];
+ if (!vft) return 0;
+ return vft->serialized_size;
+}
+
+ssize_t hc_light_command_serialize(hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object, uint8_t *msg) {
+ hc_module_object_ops_t *vft = &hc_sock_light.object_vft[object_type];
+ if (!vft || !vft->serialize[action]) return 0;
+ return vft->serialize[action](object, msg);
+}
+
+// Public constructor
+
+int hc_sock_initialize_module(hc_sock_t *s) {
+ //
+ /*
+ * We do this because initialization in the static struct fails with
+ * 'initializer element is not constant'
+ */
+ hc_sock_light.object_vft[OBJECT_TYPE_LISTENER] =
+ hicnlight_listener_module_ops;
+ hc_sock_light.object_vft[OBJECT_TYPE_CONNECTION] =
+ hicnlight_connection_module_ops;
+ hc_sock_light.object_vft[OBJECT_TYPE_FACE] = HC_MODULE_OBJECT_OPS_EMPTY;
+ hc_sock_light.object_vft[OBJECT_TYPE_PUNTING] = HC_MODULE_OBJECT_OPS_EMPTY;
+ hc_sock_light.object_vft[OBJECT_TYPE_CACHE] = HC_MODULE_OBJECT_OPS_EMPTY;
+ hc_sock_light.object_vft[OBJECT_TYPE_MAPME] = hicnlight_mapme_module_ops;
+ hc_sock_light.object_vft[OBJECT_TYPE_WLDR] = HC_MODULE_OBJECT_OPS_EMPTY;
+ hc_sock_light.object_vft[OBJECT_TYPE_POLICY] = HC_MODULE_OBJECT_OPS_EMPTY;
+ hc_sock_light.object_vft[OBJECT_TYPE_ROUTE] = hicnlight_route_module_ops;
+ hc_sock_light.object_vft[OBJECT_TYPE_STATS] = hicnlight_stats_module_ops;
+ hc_sock_light.object_vft[OBJECT_TYPE_FACE_STATS] =
+ hicnlight_face_stats_module_ops;
+ hc_sock_light.object_vft[OBJECT_TYPE_STRATEGY] =
+ hicnlight_strategy_module_ops;
+ hc_sock_light.object_vft[OBJECT_TYPE_SUBSCRIPTION] =
+ hicnlight_subscription_module_ops;
+
+ if (s) s->ops = hc_sock_light;
+ return 0;
+}
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light.h b/ctrl/libhicnctrl/src/modules/hicn_light.h
new file mode 100644
index 000000000..0bdcf0b30
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file modules/hicn_light.h
+ * \brief hicn-light module.
+ */
+
+#ifndef HICNCTRL_MODULES_HICN_LIGHT_H
+#define HICNCTRL_MODULES_HICN_LIGHT_H
+
+#include "hicn_light/base.h"
+
+typedef struct {
+ char *url;
+ int fd;
+
+ /* Send buffer */
+ hc_msg_t msg;
+
+ /* Partial receive buffer */
+ u8 buf[RECV_BUFLEN];
+ size_t roff; /**< Read offset */
+ size_t woff; /**< Write offset */
+
+ bool got_header;
+ /*
+ * Because received messages are potentially unbounded in size, we might not
+ * guarantee that we can store a full packet before processing it. We must
+ * implement a very simple state machine remembering the current parsing
+ * status in order to partially process the packet.
+ */
+ size_t remaining;
+ u32 send_id;
+
+ /* Next sequence number to be used for requests */
+ int seq;
+} hc_sock_light_data_t;
+
+extern hc_sock_light_data_t *hc_sock_light_data_create(const char *url);
+extern void hc_sock_light_data_free(hc_sock_light_data_t *data);
+
+ssize_t hc_light_command_serialize(hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object, uint8_t *msg);
+
+#endif /* HICNCTRL_MODULES_HICN_LIGHT_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/base.h b/ctrl/libhicnctrl/src/modules/hicn_light/base.h
new file mode 100644
index 000000000..ea6fc1bc9
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/base.h
@@ -0,0 +1,49 @@
+#ifndef HICNCTRL_MODULES_HICNLIGHT_BASE_H
+#define HICNCTRL_MODULES_HICNLIGHT_BASE_H
+
+#include <hicn/ctrl/hicn-light.h>
+
+#ifdef __APPLE__
+#define RANDBYTE() (u8)(arc4random() & 0xFF)
+#else
+#define RANDBYTE() (u8)(random() & 0xFF)
+#endif
+
+// TODO: is this used?
+#define foreach_hc_command \
+ _(connection_add) \
+ _(connection_remove) \
+ _(connection_list) \
+ _(listener_add) \
+ _(listener_remove) \
+ _(listener_list) \
+ _(route_add) \
+ _(route_remove) \
+ _(route_list) \
+ _(cache_set_store) \
+ _(cache_set_serve) \
+ _(cache_clear) \
+ _(cache_list) \
+ _(strategy_set) \
+ _(strategy_add_local_prefix) \
+ _(wldr_set) \
+ _(punting_add) \
+ _(mapme_activator) \
+ _(mapme_timing) \
+ _(subscription_add) \
+ _(subscription_remove)
+
+typedef union {
+#define _(x) cmd_##x##_t x;
+ foreach_hc_command
+#undef _
+} hc_msg_payload_t;
+
+typedef cmd_header_t hc_msg_header_t;
+
+typedef struct hc_msg_s {
+ hc_msg_header_t header;
+ hc_msg_payload_t payload;
+} hc_msg_t;
+
+#endif /* HICNCTRL_MODULES_HICNLIGHT_BASE_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/cache.c b/ctrl/libhicnctrl/src/modules/hicn_light/cache.c
new file mode 100644
index 000000000..e085142d7
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/cache.c
@@ -0,0 +1,178 @@
+#include "cache.h"
+
+/* CACHE SET STORE */
+
+static int _hcng_cache_set_store_internal(hc_sock_t *socket, hc_cache_t *cache,
+ bool async) {
+#if 0
+ msg_cache_set_store_t msg = {
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CACHE_SET_STORE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .activate = cache->store,
+ }};
+
+ hc_command_params_t params = {
+ .cmd = ACTION_STORE,
+ .cmd_id = COMMAND_TYPE_CACHE_SET_STORE,
+ .size_in = sizeof(cmd_cache_set_store_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+#endif
+ return 0; // XXX added
+}
+
+static int _hcng_cache_set_store(hc_sock_t *s, hc_cache_t *cache) {
+ return _hcng_cache_set_store_internal(s, cache, false);
+}
+
+static int _hcng_cache_set_store_async(hc_sock_t *s, hc_cache_t *cache) {
+ return _hcng_cache_set_store_internal(s, cache, true);
+}
+
+/* CACHE SET SERVE */
+
+static int _hcng_cache_set_serve_internal(hc_sock_t *socket, hc_cache_t *cache,
+ bool async) {
+#if 0
+ msg_cache_set_serve_t msg = {
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CACHE_SET_SERVE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .activate = cache->serve,
+ }};
+
+ hc_command_params_t params = {
+ .cmd = ACTION_SERVE,
+ .cmd_id = COMMAND_TYPE_CACHE_SET_SERVE,
+ .size_in = sizeof(cmd_cache_set_serve_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+#endif
+ return 0; /// added
+}
+
+static int _hcng_cache_set_serve(hc_sock_t *s, hc_cache_t *cache) {
+ return _hcng_cache_set_serve_internal(s, cache, false);
+}
+
+static int _hcng_cache_set_serve_async(hc_sock_t *s, hc_cache_t *cache) {
+ return _hcng_cache_set_serve_internal(s, cache, true);
+}
+
+/* CACHE CLEAR */
+
+static int _hcng_cache_clear_internal(hc_sock_t *socket, hc_cache_t *cache,
+ bool async) {
+#if 0
+ msg_cache_clear_t msg = {.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CACHE_CLEAR,
+ .length = 1,
+ .seq_num = 0,
+ }};
+
+ hc_command_params_t params = {
+ .cmd = ACTION_CLEAR,
+ .cmd_id = COMMAND_TYPE_CACHE_CLEAR,
+ .size_in = sizeof(cmd_cache_clear_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+#endif
+ return 0; // XXX added
+}
+
+static int _hcng_cache_clear(hc_sock_t *s, hc_cache_t *cache) {
+ return _hcng_cache_clear_internal(s, cache, false);
+}
+
+/* CACHE PARSE */
+
+static int hc_cache_parse(void *in, hc_cache_info_t *cache_info) {
+ cmd_cache_list_reply_t *item = (cmd_cache_list_reply_t *)in;
+ *cache_info = (hc_cache_info_t){.store = item->store_in_cs,
+ .serve = item->serve_from_cs,
+ .cs_size = item->cs_size,
+ .num_stale_entries = item->num_stale_entries};
+
+ return 0;
+}
+
+/* CACHE LIST */
+
+static hc_result_t *_hcng_cache_list_serialize(hc_sock_t *socket,
+ hc_data_t **pdata, bool async) {
+ hc_result_t *res = malloc(sizeof(*res));
+ DEBUG("[hc_cache_list] async=%s", BOOLSTR(async));
+
+ msg_cache_list_t msg = {.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CACHE_LIST,
+ .length = 0,
+ .seq_num = 0,
+ }};
+
+ hc_command_params_t params = {
+ .cmd = ACTION_LIST,
+ .cmd_id = COMMAND_TYPE_CACHE_LIST,
+ .size_in = sizeof(cmd_cache_list_reply_t),
+ .size_out = sizeof(hc_cache_info_t),
+ .parse = (HC_PARSE)hc_cache_parse,
+ };
+
+ *res = (hc_result_t){
+ .msg =
+ (hc_msg_t){
+ .header = msg.header,
+ .payload.cache_list = msg.payload,
+ },
+ .params = params,
+ .async = async,
+ .success = true,
+ };
+ return res;
+}
+
+static int _hcng_cache_list_internal(hc_sock_t *socket, hc_data_t **pdata,
+ bool async) {
+#if 0
+ hc_result_t *result = _hcng_cache_list_serialize(socket, pdata, async);
+
+ int ret = INPUT_ERROR;
+ if (result->success) {
+ ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg,
+ sizeof(result->msg), &result->params, pdata,
+ result->async);
+ }
+
+ hc_result_free(result);
+ return ret;
+#endif
+ return 0; // XXX added
+}
+
+static int _hcng_cache_list(hc_sock_t *s, hc_data_t **pdata) {
+ return _hcng_cache_list_internal(s, pdata, false);
+}
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/connection.c b/ctrl/libhicnctrl/src/modules/hicn_light/connection.c
new file mode 100644
index 000000000..d5648d794
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/connection.c
@@ -0,0 +1,503 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <assert.h>
+#include <stdint.h>
+
+#include <hicn/util/log.h>
+
+#include "base.h"
+#include "connection.h"
+#include "../../object_private.h"
+
+int hc_connection_to_local_listener(const hc_connection_t *connection,
+ hc_listener_t *listener) {
+ int rc;
+
+ face_type_t listener_type;
+ switch (connection->type) {
+ case FACE_TYPE_UDP:
+ listener_type = FACE_TYPE_UDP_LISTENER;
+ break;
+ case FACE_TYPE_TCP:
+ listener_type = FACE_TYPE_TCP_LISTENER;
+ break;
+ default:
+ return -1;
+ }
+
+ *listener = (hc_listener_t){
+ .id = ~0,
+ .type = listener_type,
+ .family = connection->family,
+ .local_addr = connection->local_addr,
+ .local_port = connection->local_port,
+ };
+ rc = snprintf(listener->name, SYMBOLIC_NAME_LEN, "lst%u",
+ RANDBYTE()); // generate name
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[hc_connection_to_local_listener] Unexpected truncation of "
+ "symbolic name string");
+ rc = snprintf(listener->interface_name, INTERFACE_LEN, "%s",
+ connection->interface_name);
+ if (rc >= INTERFACE_LEN)
+ WARN(
+ "[hc_connection_to_local_listener] Unexpected truncation of "
+ "interface name string");
+
+ return 0;
+}
+
+/* CONNECTION PARSE */
+
+static int hicnlight_connection_parse(const uint8_t *buffer, size_t size,
+ hc_connection_t *connection) {
+ int rc;
+
+ if (size != sizeof(cmd_connection_list_item_t)) return -1;
+ cmd_connection_list_item_t *item = (cmd_connection_list_item_t *)buffer;
+
+ if (!IS_VALID_ID(item->id)) {
+ ERROR("[hc_connection_parse] Invalid id received");
+ return -1;
+ }
+
+ if (!IS_VALID_NAME(item->name)) {
+ ERROR("[hc_connection_parse] Invalid name received");
+ return -1;
+ }
+ if (!IS_VALID_INTERFACE_NAME(item->interface_name)) {
+ ERROR("[hc_connection_parse] Invalid interface_name received");
+ return -1;
+ }
+
+ if (!IS_VALID_TYPE(item->type)) {
+ ERROR("[hc_connection_parse] Invalid type received");
+ return -1;
+ }
+
+ if (!IS_VALID_FAMILY(item->family)) {
+ ERROR("[hc_connection_parse] Invalid family received");
+ return -1;
+ }
+
+ if (!IS_VALID_ADDRESS(item->local_address)) {
+ ERROR("[hc_connection_parse] Invalid local address received");
+ return -1;
+ }
+
+ if (!IS_VALID_PORT(ntohs(item->local_port))) {
+ ERROR("[hc_connection_parse] Invalid local port received");
+ return -1;
+ }
+
+ if (!IS_VALID_ADDRESS(item->remote_address)) {
+ ERROR("[hc_connection_parse] Invalid remote address received");
+ return -1;
+ }
+
+ if (!IS_VALID_PORT(ntohs(item->remote_port))) {
+ ERROR("[hc_connection_parse] Invalid remote port received");
+ return -1;
+ }
+
+ if (!IS_VALID_FACE_STATE(item->admin_state)) {
+ ERROR("[hc_connection_parse] Invalid admin_state received");
+ return -1;
+ }
+
+ // PRIORITY
+ // TAGS
+
+ if (!IS_VALID_FACE_STATE(item->state)) {
+ ERROR("[hc_connection_parse] Invalid state received");
+ return -1;
+ }
+
+ *connection = (hc_connection_t){
+ .id = item->id,
+ .type = (face_type_t)item->type,
+ .family = (int)item->family,
+ .local_addr = item->local_addr,
+ .local_port = ntohs(item->local_port),
+ .remote_addr = item->remote_addr,
+ .remote_port = ntohs(item->remote_port),
+ .admin_state = (face_state_t)item->admin_state,
+ .priority = item->priority,
+ .tags = item->tags,
+ .state = (face_state_t)item->state,
+ };
+ rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "%s", item->name);
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ rc = snprintf(connection->interface_name, INTERFACE_LEN, "%s",
+ item->interface_name);
+ if ((rc < 0) || (rc >= INTERFACE_LEN)) return -1;
+
+ if (hc_connection_validate(connection, false) < 0) return -1;
+ return 0;
+}
+
+int _hicnlight_connection_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_connection_parse(buffer, size, &object->connection);
+}
+
+/* CONNECTION CREATE */
+
+int hicnlight_connection_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ int rc;
+ const hc_connection_t *connection = &object->connection;
+
+ msg_connection_add_t *msg = (msg_connection_add_t *)packet;
+ *msg = (msg_connection_add_t){
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .remote_ip = connection->remote_addr,
+ .local_ip = connection->local_addr,
+ .remote_port = htons(connection->remote_port),
+ .local_port = htons(connection->local_port),
+ .family = (uint8_t)connection->family,
+ .type = (uint8_t)connection->type,
+ .admin_state = (uint8_t)connection->admin_state,
+ .__pad = 0,
+ .priority = connection->priority,
+ .tags = connection->tags,
+ }};
+
+ rc = snprintf(msg->payload.symbolic, SYMBOLIC_NAME_LEN, "%s",
+ connection->name);
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ return sizeof(msg_connection_add_t);
+}
+
+/* CONNECTION DELETE */
+
+int hicnlight_connection_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ int rc;
+ const hc_connection_t *connection = &object->connection;
+
+ msg_connection_remove_t *msg = (msg_connection_remove_t *)packet;
+ *msg = (msg_connection_remove_t){
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_REMOVE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ };
+
+ if (connection->id) {
+ rc = snprintf(msg->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%d",
+ connection->id);
+ // XXX
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[_hc_connection_delete] Unexpected truncation of symbolic name "
+ "string");
+ } else if (*connection->name) {
+ rc = snprintf(msg->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ connection->name);
+ // XXX
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[_hc_connection_delete] Unexpected truncation of symbolic name "
+ "string");
+#if 0
+ } else {
+ hc_connection_t *connection_found;
+ if (hc_connection_get(socket, connection, &connection_found) < 0)
+ return res;
+ if (!connection_found) return res;
+ rc = snprintf(payload->symbolic_or_connid, SYMBOLIC_NAME_LEN, "%d",
+ connection_found->id);
+ // XXX
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[_hc_connection_delete] Unexpected truncation of symbolic name "
+ "string");
+ free(connection_found);
+#endif
+ }
+
+ return sizeof(msg_connection_remove_t);
+}
+
+// XXX How to update a connection XXX
+// Key attributes are mandatory
+// Enum can be undefined
+// family UNSPEC
+// ip address NULL
+// port NULL
+// priority = int ????????? specific negative value == unspec
+// tags = bitmap ????????? 0xFFFFFF special value == unspec
+
+// u32 id; /* Kr. */
+// char name[SYMBOLIC_NAME_LEN]; /* K.w */
+// char interface_name[INTERFACE_LEN]; /* Kr. */
+//
+// netdevice_type_t netdevice_type; undefined
+// face_type_t type;
+// int family;
+// ip_address_t local_addr;
+// u16 local_port;
+// ip_address_t remote_addr;
+// u16 remote_port;
+// face_state_t admin_state;
+// uint32_t priority; /* .rw */
+// policy_tags_t tags; /* .rw */
+// face_state_t state; /* .r. */
+int hicnlight_connection_serialize_update(const hc_object_t *object,
+ uint8_t *packet) {
+ int rc;
+ const hc_connection_t *connection = &object->connection;
+
+ msg_connection_update_t *msg = (msg_connection_update_t *)packet;
+ *msg = (msg_connection_update_t){
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_UPDATE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ //.remote_ip = connection->remote_updater,
+ //.local_ip = connection->local_updater,
+ //.remote_port = htons(connection->remote_port),
+ //.local_port = htons(connection->local_port),
+ //.family = connection->family,
+ //.type = connection->type,
+ .admin_state = connection->admin_state,
+ .priority = connection->priority,
+ .tags = connection->tags,
+ }};
+
+ rc = snprintf(msg->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ connection->name);
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ // snprintf(msg.payload.interface_name, INTERFACE_NAME_LEN, "%s",
+ // connection->interface_name);
+
+ return sizeof(msg_connection_update_t);
+}
+
+#if 0
+/* CONNECTION SET ADMIN STATE */
+
+static int _hicnlight_connection_set_admin_state_internal(
+ hc_sock_t *socket, const char *conn_id_or_name, face_state_t state,
+ bool async) {
+ int rc;
+ DEBUG(
+ "[hc_connection_set_admin_state] connection_id/name=%s admin_state=%s "
+ "async=%s",
+ conn_id_or_name, face_state_str(state), BOOLSTR(async));
+
+ struct {
+ cmd_header_t hdr;
+ cmd_connection_set_admin_state_t payload;
+ } msg = {
+ .hdr =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_SET_ADMIN_STATE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload =
+ {
+ .admin_state = state,
+ },
+ };
+ rc = snprintf(msg.payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ conn_id_or_name);
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[_hc_connection_set_admin_state] Unexpected truncation of symbolic "
+ "name string");
+
+ hc_command_params_t params = {
+ .cmd = ACTION_SET,
+ .cmd_id = COMMAND_TYPE_CONNECTION_SET_ADMIN_STATE,
+ .size_in = sizeof(cmd_connection_set_admin_state_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hicnlight_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+}
+
+static int _hicnlight_connection_set_admin_state(hc_sock_t *s,
+ const char *conn_id_or_name,
+ face_state_t state) {
+ return _hicnlight_connection_set_admin_state_internal(s, conn_id_or_name, state,
+ false);
+}
+
+static int _hicnlight_connection_set_admin_state_async(hc_sock_t *s,
+ const char *conn_id_or_name,
+ face_state_t state) {
+ return _hicnlight_connection_set_admin_state_internal(s, conn_id_or_name, state,
+ true);
+}
+
+
+static int _hicnlight_connection_set_priority_internal(hc_sock_t *socket,
+ const char *conn_id_or_name,
+ uint32_t priority,
+ bool async) {
+ int rc;
+ DEBUG(
+ "[hc_connection_set_priority] connection_id/name=%s priority=%d "
+ "async=%s",
+ conn_id_or_name, priority, BOOLSTR(async));
+ struct {
+ cmd_header_t hdr;
+ cmd_connection_set_priority_t payload;
+ } msg = {
+ .hdr =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_SET_PRIORITY,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload =
+ {
+ .priority = priority,
+ },
+ };
+ rc = snprintf(msg.payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ conn_id_or_name);
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[_hc_connection_set_priority] Unexpected truncation of symbolic "
+ "name "
+ "string");
+
+ hc_command_params_t params = {
+ .cmd = ACTION_SET,
+ .cmd_id = COMMAND_TYPE_CONNECTION_SET_PRIORITY,
+ .size_in = sizeof(cmd_connection_set_priority_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hicnlight_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+}
+
+static int _hicnlight_connection_set_priority(hc_sock_t *s,
+ const char *conn_id_or_name,
+ uint32_t priority) {
+ return _hicnlight_connection_set_priority_internal(s, conn_id_or_name, priority,
+ false);
+}
+
+static int _hicnlight_connection_set_priority_async(hc_sock_t *s,
+ const char *conn_id_or_name,
+ uint32_t priority) {
+ return _hicnlight_connection_set_priority_internal(s, conn_id_or_name, priority,
+ true);
+}
+
+
+static int _hicnlight_connection_set_tags_internal(hc_sock_t *s,
+ const char *conn_id_or_name,
+ policy_tags_t tags, bool async) {
+ int rc;
+ DEBUG("[hc_connection_set_tags] connection_id/name=%s tags=%d async=%s",
+ conn_id_or_name, tags, BOOLSTR(async));
+ struct {
+ cmd_header_t hdr;
+ cmd_connection_set_tags_t payload;
+ } msg = {
+ .hdr =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_SET_TAGS,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload =
+ {
+ .tags = tags,
+ },
+ };
+ rc = snprintf(msg.payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ conn_id_or_name);
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[_hc_connection_set_tags] Unexpected truncation of symbolic name "
+ "string");
+
+ hc_command_params_t params = {
+ .cmd = ACTION_SET,
+ .cmd_id = COMMAND_TYPE_CONNECTION_SET_TAGS,
+ .size_in = sizeof(cmd_connection_set_tags_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hicnlight_execute_command(s, (hc_msg_t *)&msg, sizeof(msg), &params, NULL,
+ async);
+}
+
+static int _hicnlight_connection_set_tags(hc_sock_t *s, const char *conn_id_or_name,
+ policy_tags_t tags) {
+ return _hicnlight_connection_set_tags_internal(s, conn_id_or_name, tags, false);
+}
+
+static int _hicnlight_connection_set_tags_async(hc_sock_t *s,
+ const char *conn_id_or_name,
+ policy_tags_t tags) {
+ return _hicnlight_connection_set_tags_internal(s, conn_id_or_name, tags, true);
+}
+#endif
+
+/* CONNECTION LIST */
+
+int hicnlight_connection_serialize_list(const hc_object_t *object,
+ uint8_t *packet) {
+ msg_connection_list_t *msg = (msg_connection_list_t *)packet;
+ *msg = (msg_connection_list_t){.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_LIST,
+ .length = 0,
+ .seq_num = 0,
+ }};
+ return sizeof(msg_header_t); // Do not use msg_connection_list_t
+}
+
+int hicnlight_connection_serialize_set(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, connection);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/connection.h b/ctrl/libhicnctrl/src/modules/hicn_light/connection.h
new file mode 100644
index 000000000..21f3a2fbc
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/connection.h
@@ -0,0 +1,11 @@
+#ifndef HICNCTRL_MODULE_HICNLIGHT_CONNECTION_H
+#define HICNCTRL_MODULE_HICNLIGHT_CONNECTION_H
+
+#include "../../module.h"
+
+int hc_connection_to_local_listener(const hc_connection_t *connection,
+ hc_listener_t *listener);
+
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, connection);
+
+#endif /* HICNCTRL_MODULE_HICNLIGHT_CONNECTION_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/face.c b/ctrl/libhicnctrl/src/modules/hicn_light/face.c
new file mode 100644
index 000000000..4dcd96191
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/face.c
@@ -0,0 +1,165 @@
+#include <hicn/ctrl/objects/listener.h>
+#include <hicn/util/log.h>
+
+#include "base.h"
+#include "face.h"
+
+int hc_face_from_connection(const hc_connection_t *connection,
+ hc_face_t *face) {
+ int rc;
+ switch (connection->type) {
+ case FACE_TYPE_TCP:
+ *face = (hc_face_t){
+ .id = connection->id,
+ .type = FACE_TYPE_TCP,
+ .family = connection->family,
+ .local_addr = connection->local_addr,
+ .local_port = connection->local_port,
+ .remote_addr = connection->remote_addr,
+ .remote_port = connection->remote_port,
+ .admin_state = connection->admin_state,
+ .state = connection->state,
+ .priority = connection->priority,
+ .tags = connection->tags,
+ };
+ break;
+ case FACE_TYPE_UDP:
+ *face = (hc_face_t){
+ .id = connection->id,
+ .type = FACE_TYPE_UDP,
+ .family = connection->family,
+ .local_addr = connection->local_addr,
+ .local_port = connection->local_port,
+ .remote_addr = connection->remote_addr,
+ .remote_port = connection->remote_port,
+ .admin_state = connection->admin_state,
+ .state = connection->state,
+ .priority = connection->priority,
+ .tags = connection->tags,
+ };
+ break;
+ case FACE_TYPE_HICN:
+ *face = (hc_face_t){
+ .id = connection->id,
+ .type = FACE_TYPE_HICN,
+ .family = connection->family,
+ .netdevice.index = NETDEVICE_UNDEFINED_INDEX, // XXX
+ .local_addr = connection->local_addr,
+ .remote_addr = connection->remote_addr,
+ .admin_state = connection->admin_state,
+ .state = connection->state,
+ .priority = connection->priority,
+ .tags = connection->tags,
+ };
+ break;
+ default:
+ return -1;
+ }
+ face->netdevice.name[0] = '\0';
+ face->netdevice.index = 0;
+ rc = snprintf(face->name, SYMBOLIC_NAME_LEN, "%s", connection->name);
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[hc_connection_to_face] Unexpected truncation of symbolic name "
+ "string");
+ rc = snprintf(face->netdevice.name, INTERFACE_LEN, "%s",
+ connection->interface_name);
+ if (rc >= INTERFACE_LEN)
+ WARN(
+ "[hc_connection_to_face] Unexpected truncation of interface name "
+ "string");
+ netdevice_update_index(&face->netdevice);
+ return 0;
+}
+
+int hc_face_to_connection(const hc_face_t *face, hc_connection_t *connection,
+ bool generate_name) {
+ int rc;
+
+ switch (face->type) {
+ case FACE_TYPE_HICN:
+ *connection = (hc_connection_t){
+ .type = FACE_TYPE_HICN,
+ .family = face->family,
+ .local_addr = face->local_addr,
+ .local_port = 0,
+ .remote_addr = face->remote_addr,
+ .remote_port = 0,
+ .admin_state = face->admin_state,
+ .state = face->state,
+ .priority = face->priority,
+ .tags = face->tags,
+ };
+ rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "%s",
+ face->netdevice.name);
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[hc_face_to_connection] Unexpected truncation of symbolic "
+ "name string");
+ break;
+ case FACE_TYPE_TCP:
+ *connection = (hc_connection_t){
+ .type = FACE_TYPE_TCP,
+ .family = face->family,
+ .local_addr = face->local_addr,
+ .local_port = face->local_port,
+ .remote_addr = face->remote_addr,
+ .remote_port = face->remote_port,
+ .admin_state = face->admin_state,
+ .state = face->state,
+ .priority = face->priority,
+ .tags = face->tags,
+ };
+ if (generate_name) {
+ rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "tcp%u", RANDBYTE());
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[hc_face_to_connection] Unexpected truncation of "
+ "symbolic name string");
+ } else {
+ memset(connection->name, 0, SYMBOLIC_NAME_LEN);
+ }
+ break;
+ case FACE_TYPE_UDP:
+ *connection = (hc_connection_t){
+ .type = FACE_TYPE_UDP,
+ .family = face->family,
+ .local_addr = face->local_addr,
+ .local_port = face->local_port,
+ .remote_addr = face->remote_addr,
+ .remote_port = face->remote_port,
+ .admin_state = face->admin_state,
+ .state = face->state,
+ .priority = face->priority,
+ .tags = face->tags,
+ };
+ if (generate_name) {
+ rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "udp%u", RANDBYTE());
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN(
+ "[hc_face_to_connection] Unexpected truncation of "
+ "symbolic name string");
+ } else {
+ memset(connection->name, 0, SYMBOLIC_NAME_LEN);
+ }
+ snprintf(connection->interface_name, INTERFACE_LEN, "%s",
+ face->netdevice.name);
+ break;
+ default:
+ return -1;
+ }
+
+ connection->id = face->id;
+ rc = snprintf(connection->interface_name, INTERFACE_LEN, "%s",
+ face->netdevice.name);
+ if (rc >= INTERFACE_LEN)
+ WARN(
+ "hc_face_to_connection] Unexpected truncation of interface name "
+ "string");
+
+ return 0;
+}
+
+int hc_face_to_listener(const hc_face_t *face, hc_listener_t *listener) {
+ return -99; /* XXX Not implemented */
+}
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/face.h b/ctrl/libhicnctrl/src/modules/hicn_light/face.h
new file mode 100644
index 000000000..6f202b4ce
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/face.h
@@ -0,0 +1,16 @@
+#ifndef HICNCTRL_MODULE_HICNLIGHT_FACE
+#define HICNCTRL_MODULE_HICNLIGHT_FACE
+
+#include <hicn/ctrl/objects/connection.h>
+#include <hicn/ctrl/objects/face.h>
+
+int hc_connection_to_face(const hc_connection_t *connection, hc_face_t *face);
+
+int hc_face_from_connection(const hc_connection_t *connection, hc_face_t *face);
+
+int hc_face_to_connection(const hc_face_t *face, hc_connection_t *connection,
+ bool generate_name);
+
+int hc_face_to_listener(const hc_face_t *face, hc_listener_t *listener);
+
+#endif /* HICNCTRL_MODULES_HICNLIGHT_FACE */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/listener.c b/ctrl/libhicnctrl/src/modules/hicn_light/listener.c
new file mode 100644
index 000000000..46fded2ca
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/listener.c
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <assert.h>
+#include <hicn/ctrl/api.h>
+#include <hicn/util/log.h>
+
+#include "base.h"
+#include "../../object_private.h"
+#include "listener.h"
+
+static int hicnlight_listener_parse(const u8 *buffer, size_t size,
+ hc_listener_t *listener) {
+ int rc;
+
+ if (size != sizeof(cmd_listener_list_item_t)) return -1;
+ cmd_listener_list_item_t *item = (cmd_listener_list_item_t *)buffer;
+
+ if (!IS_VALID_ADDRESS(item->local_address)) {
+ ERROR("[hc_listener_parse] Invalid address received");
+ return -1;
+ }
+ if (!IS_VALID_NAME(item->name)) {
+ ERROR("[hc_listener_parse] Invalid name received");
+ return -1;
+ }
+ if (!IS_VALID_INTERFACE_NAME(item->interface_name)) {
+ ERROR("[hc_listener_parse] Invalid interface_name received");
+ return -1;
+ }
+ if (!IS_VALID_ID(item->id)) {
+ ERROR("[hc_listener_parse] Invalid id received");
+ return -1;
+ }
+ if (!IS_VALID_PORT(ntohs(item->local_port))) {
+ ERROR("[hc_listener_parse] Invalid port received");
+ return -1;
+ }
+ if (!IS_VALID_FAMILY(item->family)) {
+ ERROR("[hc_listener_parse] Invalid family received");
+ return -1;
+ }
+ if (!IS_VALID_TYPE(item->type)) {
+ ERROR("[hc_listener_parse] Invalid type received");
+ return -1;
+ }
+ // if (!(IS_VALID_CONNECTION_TYPE(item->type)))
+ // return -1;
+
+ *listener = (hc_listener_t){
+ .id = item->id,
+ .type = (face_type_t)(item->type),
+ .family = (int)(item->family),
+ .local_addr =
+ item->local_addr, // UNION_CAST(item->local_addr, ip_address_t),
+ .local_port = ntohs(item->local_port),
+ };
+
+ rc = snprintf(listener->name, SYMBOLIC_NAME_LEN, "%s", item->name);
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ rc = snprintf(listener->interface_name, INTERFACE_LEN, "%s",
+ item->interface_name);
+ if ((rc < 0) || (rc >= INTERFACE_LEN)) return -1;
+
+ if (hc_listener_validate(listener, false) < 0) return -1;
+ return 0;
+}
+
+int _hicnlight_listener_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_listener_parse(buffer, size, &object->listener);
+}
+
+/* LISTENER CREATE */
+
+int hicnlight_listener_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ int rc;
+ const hc_listener_t *listener = &object->listener;
+
+ msg_listener_add_t *msg = (msg_listener_add_t *)packet;
+ *msg = (msg_listener_add_t){.header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_LISTENER_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+
+ .payload = {
+ .address = listener->local_addr,
+ .port = htons(listener->local_port),
+ .family = (uint8_t)listener->family,
+ .type = (uint8_t)listener->type,
+ }};
+
+ rc = snprintf(msg->payload.symbolic, SYMBOLIC_NAME_LEN, "%s", listener->name);
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ rc = snprintf(msg->payload.interface_name, INTERFACE_LEN, "%s",
+ listener->interface_name);
+ if ((rc < 0) || (rc >= INTERFACE_LEN)) return -1;
+
+ return sizeof(msg_listener_add_t);
+}
+
+/* LISTENER DELETE */
+
+int hicnlight_listener_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ int rc;
+ const hc_listener_t *listener = &object->listener;
+
+ msg_listener_remove_t *msg = (msg_listener_remove_t *)packet;
+ *msg = (msg_listener_remove_t){.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_LISTENER_REMOVE,
+ .length = 1,
+ .seq_num = 0,
+ }};
+
+ if (listener->id) {
+ rc = snprintf(msg->payload.symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%d",
+ listener->id);
+ } else if (*listener->name) {
+ rc = snprintf(msg->payload.symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%s",
+ listener->name);
+ } else {
+ return -1;
+ }
+
+ // For now we only support delete by name or id
+#if 0
+ hc_listener_t *listener_found;
+ if (hc_listener_get(socket, listener, &listener_found) < 0) return -1;
+ if (!listener_found) return -1;
+ rc = snprintf(payload->symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%d",
+ listener_found->id);
+ free(listener_found);
+ }
+#endif
+
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ return sizeof(msg_listener_remove_t);
+}
+
+/* LISTENER LIST */
+
+int hicnlight_listener_serialize_list(const hc_object_t *object,
+ uint8_t *packet) {
+ msg_listener_list_t *msg = (msg_listener_list_t *)packet;
+ *msg = (msg_listener_list_t){.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_LISTENER_LIST,
+ .length = 0,
+ .seq_num = 0,
+ }};
+
+ return sizeof(msg_header_t); // Do not use msg_listener_list_t
+}
+
+int hicnlight_listener_serialize_set(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, listener);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/listener.h b/ctrl/libhicnctrl/src/modules/hicn_light/listener.h
new file mode 100644
index 000000000..67eadfbb1
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/listener.h
@@ -0,0 +1,8 @@
+#ifndef HICNCTRL_MODULE_HICNLIGHT_LISTENER_H
+#define HICNCTRL_MODULE_HICNLIGHT_LISTENER_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, listener);
+
+#endif /* HICNCTRL_MODULE_HICNLIGHT_LISTENER_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/mapme.c b/ctrl/libhicnctrl/src/modules/hicn_light/mapme.c
new file mode 100644
index 000000000..04eb36e24
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/mapme.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file modules/hicn_light/mapme.c
+ * \brief Implementation of mapme object VFT for hicn_light.
+ */
+
+#include <hicn/ctrl/hicn-light.h>
+#include "mapme.h"
+
+static int hicnlight_mapme_parse(const uint8_t *buffer, size_t size,
+ hc_mapme_t *mapme) {
+ return -1;
+}
+
+int _hicnlight_mapme_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_mapme_parse(buffer, size, &object->mapme);
+}
+
+int hicnlight_mapme_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ const hc_mapme_t *mapme = &object->mapme;
+
+ msg_mapme_add_t *msg = (msg_mapme_add_t *)packet;
+ *msg = (msg_mapme_add_t){.header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_MAPME_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+
+ .payload = {.face_id = mapme->face_id,
+ .family = mapme->family,
+ .address = mapme->address,
+ .len = mapme->len}};
+
+ return sizeof(msg_mapme_add_t);
+}
+
+int hicnlight_mapme_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_mapme_serialize_list(const hc_object_t *object, uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_mapme_serialize_set(const hc_object_t *object, uint8_t *packet) {
+ return -1;
+}
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, mapme);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/mapme.h b/ctrl/libhicnctrl/src/modules/hicn_light/mapme.h
new file mode 100644
index 000000000..58a943b67
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/mapme.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file modules/hicn_light/mapme.h
+ * \brief mapme object VFT for hicn_light.
+ */
+
+#ifndef HICNCTRL_MODULE_HICNLIGHT_MAPME_H
+#define HICNCTRL_MODULE_HICNLIGHT_MAPME_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, mapme);
+
+#endif /* HICNCTRL_MODULE_HICNLIGHT_MAPME_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/policy.c b/ctrl/libhicnctrl/src/modules/hicn_light/policy.c
new file mode 100644
index 000000000..d48ce014d
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/policy.c
@@ -0,0 +1,162 @@
+#include "policy.h"
+
+/* POLICY CREATE */
+
+static int _hcng_policy_create_internal(hc_sock_t *socket, hc_policy_t *policy,
+ bool async) {
+#if 0
+ if (!IS_VALID_FAMILY(policy->family)) return -1;
+
+ struct {
+ cmd_header_t hdr;
+ cmd_policy_add_t payload;
+ } msg = {.hdr =
+ {
+ .message_type = REQUEST_LIGHT,
+ COMMAND_TYPE_POLICY_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .address = policy->remote_addr,
+ .family = policy->family,
+ .len = policy->len,
+ .policy = policy->policy,
+ }};
+
+ hc_command_params_t params = {
+ .cmd = ACTION_CREATE,
+ .cmd_id = COMMAND_TYPE_POLICY_ADD,
+ .size_in = sizeof(cmd_policy_add_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+#endif
+ return 0; // XXX added
+}
+
+static int _hcng_policy_create(hc_sock_t *s, hc_policy_t *policy) {
+ return _hcng_policy_create_internal(s, policy, false);
+}
+
+static int _hcng_policy_create_async(hc_sock_t *s, hc_policy_t *policy) {
+ return _hcng_policy_create_internal(s, policy, true);
+}
+
+/* POLICY DELETE */
+
+static int _hcng_policy_delete_internal(hc_sock_t *socket, hc_policy_t *policy,
+ bool async) {
+#if 0
+ if (!IS_VALID_FAMILY(policy->family)) return -1;
+
+ struct {
+ cmd_header_t hdr;
+ cmd_policy_remove_t payload;
+ } msg = {.hdr =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_POLICY_REMOVE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .address = policy->remote_addr,
+ .family = policy->family,
+ .len = policy->len,
+ }};
+
+ hc_command_params_t params = {
+ .cmd = ACTION_DELETE,
+ .cmd_id = COMMAND_TYPE_POLICY_REMOVE,
+ .size_in = sizeof(cmd_policy_remove_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+#endif
+ return 0; // XXX added
+}
+
+static int _hcng_policy_delete(hc_sock_t *s, hc_policy_t *policy) {
+ return _hcng_policy_delete_internal(s, policy, false);
+}
+
+static int _hcng_policy_delete_async(hc_sock_t *s, hc_policy_t *policy) {
+ return _hcng_policy_delete_internal(s, policy, true);
+}
+
+/* POLICY PARSE */
+
+static int hc_policy_parse(void *in, hc_policy_t *policy) {
+ hc_policy_t *item = (hc_policy_t *)in;
+
+ if (!IS_VALID_ADDRESS(item->address)) {
+ ERROR("[hc_policy_parse] Invalid address");
+ return -1;
+ }
+ if (!IS_VALID_FAMILY(item->family)) {
+ ERROR("[hc_policy_parse] Invalid family");
+ return -1;
+ }
+ if (!IS_VALID_PREFIX_LEN(item->len)) {
+ ERROR("[hc_policy_parse] Invalid len");
+ return -1;
+ }
+ if (!IS_VALID_POLICY(item->policy)) {
+ ERROR("[hc_policy_parse] Invalid policy");
+ return -1;
+ }
+
+ *policy = (hc_policy_t){
+ .family = item->family,
+ .remote_addr = item->remote_addr,
+ .len = item->len,
+ .policy = item->policy,
+ };
+ return 0;
+}
+
+/* POLICY LIST */
+
+static int _hcng_policy_list_internal(hc_sock_t *socket, hc_data_t **pdata,
+ bool async) {
+#if 0
+ struct {
+ cmd_header_t hdr;
+ } msg = {
+ .hdr =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_POLICY_LIST,
+ .length = 0,
+ .seq_num = 0,
+ },
+ };
+
+ hc_command_params_t params = {
+ .cmd = ACTION_LIST,
+ .cmd_id = COMMAND_TYPE_POLICY_LIST,
+ .size_in = sizeof(hc_policy_t),
+ .size_out = sizeof(hc_policy_t),
+ .parse = (HC_PARSE)hc_policy_parse,
+ };
+
+ return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ pdata, async);
+#endif
+ return 0; // XXX added
+}
+
+static int _hcng_policy_list(hc_sock_t *s, hc_data_t **pdata) {
+ return _hcng_policy_list_internal(s, pdata, false);
+}
+
+static int _hcng_policy_list_async(hc_sock_t *s, hc_data_t **pdata) {
+ return _hcng_policy_list_internal(s, pdata, true);
+}
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/punting.c b/ctrl/libhicnctrl/src/modules/hicn_light/punting.c
new file mode 100644
index 000000000..7886ff839
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/punting.c
@@ -0,0 +1,74 @@
+#include "punting.h"
+
+static int _hcng_punting_create_internal(hc_sock_t *socket,
+ hc_punting_t *punting, bool async) {
+#if 0
+ int rc;
+
+ if (hc_punting_validate(punting) < 0) return -1;
+
+ struct {
+ cmd_header_t hdr;
+ cmd_punting_add_t payload;
+ } msg = {.hdr =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_PUNTING_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .address = punting->prefix,
+ .family = punting->family,
+ .len = punting->prefix_len,
+ }};
+ rc = snprintf(msg.payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%d",
+ punting->face_id);
+ if (rc >= SYMBOLIC_NAME_LEN)
+ WARN("[_hc_punting_create] Unexpected truncation of symbolic name string");
+
+ hc_command_params_t params = {
+ .cmd = ACTION_CREATE,
+ .cmd_id = COMMAND_TYPE_PUNTING_ADD,
+ .size_in = sizeof(cmd_punting_add_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), &params,
+ NULL, async);
+#endif
+ return 0; // XXX added
+}
+
+static int _hcng_punting_create(hc_sock_t *s, hc_punting_t *punting) {
+ return _hcng_punting_create_internal(s, punting, false);
+}
+
+static int _hcng_punting_create_async(hc_sock_t *s, hc_punting_t *punting) {
+ return _hcng_punting_create_internal(s, punting, true);
+}
+
+static int _hcng_punting_get(hc_sock_t *s, hc_punting_t *punting,
+ hc_punting_t **punting_found) {
+ ERROR("hc_punting_get not (yet) implemented.");
+ return -1;
+}
+
+static int _hcng_punting_delete(hc_sock_t *s, hc_punting_t *punting) {
+ ERROR("hc_punting_delete not (yet) implemented.");
+ return -1;
+}
+
+#if 0
+static int hc_punting_parse(void * in, hc_punting_t * punting)
+{
+ ERROR("hc_punting_parse not (yet) implemented.");
+ return -1;
+}
+#endif
+
+static int _hcng_punting_list(hc_sock_t *s, hc_data_t **pdata) {
+ ERROR("hc_punting_list not (yet) implemented.");
+ return -1;
+}
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/route.c b/ctrl/libhicnctrl/src/modules/hicn_light/route.c
new file mode 100644
index 000000000..38510704c
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/route.c
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file modules/hicn_light/route.c
+ * \brief Implementation of route object VFT for hicn_light.
+ */
+
+#include <assert.h>
+#include <hicn/ctrl/api.h>
+#include <hicn/util/log.h>
+#include "base.h"
+#include "route.h"
+#include <hicn/ctrl/hicn-light.h>
+
+#include "../../object_private.h"
+
+static int hicnlight_route_parse(const uint8_t *buffer, size_t size,
+ hc_route_t *route) {
+ if (size != sizeof(cmd_route_list_item_t)) return -1;
+ cmd_route_list_item_t *item = (cmd_route_list_item_t *)buffer;
+
+ if (!IS_VALID_NAME(item->face_name)) {
+ ERROR("[hc_route_parse] Invalid face_name received");
+ return -1;
+ }
+
+ if (!IS_VALID_ID(item->face_id)) {
+ ERROR("[hc_route_parse] Invalid face_id received");
+ return -1;
+ }
+
+ if (!IS_VALID_FAMILY(item->family)) {
+ ERROR("[hc_route_parse] Invalid family received");
+ return -1;
+ }
+
+ if (!IS_VALID_ADDRESS(item->remote_addr)) {
+ ERROR("[hc_route_parse] Invalid address received");
+ return -1;
+ }
+
+ // LEN
+ // COST
+
+ *route = (hc_route_t){
+ .face_name = "", /* This is not reported back */
+ .face_id = item->face_id,
+ .family = (int)(item->family),
+ .remote_addr = item->remote_addr,
+ .len = item->len,
+ .cost = item->cost,
+ };
+
+ if (hc_route_validate(route, false) < 0) return -1;
+ return 0;
+}
+
+int _hicnlight_route_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_route_parse(buffer, size, &object->route);
+}
+
+/* ROUTE CREATE */
+
+int hicnlight_route_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ const hc_route_t *route = &object->route;
+ int rc;
+
+ msg_route_add_t *msg = (msg_route_add_t *)packet;
+ *msg = (msg_route_add_t){.header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_ROUTE_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .address = route->remote_addr,
+ .cost = route->cost,
+ .family = route->family,
+ .len = route->len,
+ }};
+
+ /*
+ * The route commands expects the ID or name as part of the
+ * symbolic_or_connid attribute.
+ */
+ if (route->face_name[0] != '\0') {
+ rc = snprintf(msg->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ route->face_name);
+ } else {
+ rc = snprintf(msg->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%d",
+ route->face_id);
+ }
+
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ return sizeof(msg_route_add_t);
+}
+
+/* ROUTE DELETE */
+
+int hicnlight_route_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ const hc_route_t *route = &object->route;
+ int rc;
+
+ msg_route_remove_t *msg = (msg_route_remove_t *)packet;
+ memset(msg, 0, sizeof(msg_route_remove_t));
+ *msg = (msg_route_remove_t){.header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_ROUTE_REMOVE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .family = (uint8_t)route->family,
+ .len = route->len,
+ }};
+
+ /*
+ * Direct copy as part of the previous assignment does not work correctly...
+ * to be investigated
+ */
+ memcpy(&msg->payload.address, &route->remote_addr, sizeof(hicn_ip_address_t));
+
+ /*
+ * The route commands expects the ID or name as part of the
+ * symbolic_or_connid attribute.
+ */
+ if (route->face_name[0] != '\0') {
+ rc = snprintf(msg->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ route->face_name);
+ } else {
+ rc = snprintf(msg->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%d",
+ route->face_id);
+ }
+
+ if ((rc < 0) || (rc >= SYMBOLIC_NAME_LEN)) return -1;
+
+ return sizeof(msg_route_remove_t);
+}
+
+/* ROUTE LIST */
+
+int hicnlight_route_serialize_list(const hc_object_t *object, uint8_t *packet) {
+ msg_route_list_t *msg = (msg_route_list_t *)packet;
+ *msg = (msg_route_list_t){.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_ROUTE_LIST,
+ .length = 0,
+ .seq_num = 0,
+ }};
+
+ return sizeof(msg_header_t); // Do not use msg_route_list_t
+}
+
+int hicnlight_route_serialize_set(const hc_object_t *object, uint8_t *packet) {
+ return -1;
+}
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, route);
diff --git a/hicn-light/src/hicn/config/controlMapMeRetx.h b/ctrl/libhicnctrl/src/modules/hicn_light/route.h
index 3e3b2de15..825253a42 100644
--- a/hicn-light/src/hicn/config/controlMapMeRetx.h
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/route.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,10 +13,16 @@
* limitations under the License.
*/
-#ifndef Control_MapMeRetx_h
-#define Control_MapMeRetx_h
+/**
+ * \file modules/hicn_light/route.h
+ * \brief route object VFT for hicn_light.
+ */
+
+#ifndef HICNCTRL_MODULE_HICNLIGHT_ROUTE_H
+#define HICNCTRL_MODULE_HICNLIGHT_ROUTE_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, route);
-#include <hicn/config/controlState.h>
-CommandOps *controlMapMeRetx_Create(ControlState *state);
-CommandOps *controlMapMeRetx_HelpCreate(ControlState *state);
-#endif // Control_MapMeRetx_h
+#endif /* HICNCTRL_MODULE_HICNLIGHT_ROUTE_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/stats.c b/ctrl/libhicnctrl/src/modules/hicn_light/stats.c
new file mode 100644
index 000000000..a60190a13
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/stats.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file modules/hicn_light/stats.c
+ * \brief Implementation of stats object VFT for hicn_light.
+ */
+
+#include <hicn/util/log.h>
+#include "base.h"
+#include "stats.h"
+
+/* GENERAL STATS */
+
+int hicnlight_stats_parse(const uint8_t *buffer, size_t size,
+ hc_stats_t *stats) {
+ if (size != sizeof(cmd_stats_list_item_t)) return -1;
+
+ cmd_stats_list_item_t *item = (cmd_stats_list_item_t *)buffer;
+ *stats = item->stats;
+ return 0;
+}
+
+int _hicnlight_stats_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_stats_parse(buffer, size, &object->stats);
+}
+
+int hicnlight_stats_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_stats_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_stats_serialize_list(const hc_object_t *object, uint8_t *packet) {
+ msg_stats_list_t *msg = (msg_stats_list_t *)packet;
+ *msg = (msg_stats_list_t){.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_STATS_LIST,
+ .length = 0,
+ .seq_num = 0,
+ }};
+
+ return sizeof(msg_header_t); // Do not use msg_stats_list_t
+}
+
+int hicnlight_stats_serialize_set(const hc_object_t *object, uint8_t *packet) {
+ return -1;
+}
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, stats);
+
+/* PER-FACE STATS */
+
+int hicnlight_face_stats_parse(const uint8_t *buffer, size_t size,
+ hc_face_stats_t *stats) {
+ if (size != sizeof(cmd_face_stats_list_item_t)) return -1;
+
+ cmd_face_stats_list_item_t *item = (cmd_face_stats_list_item_t *)buffer;
+ *stats = item->stats;
+ return 0;
+}
+
+int _hicnlight_face_stats_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_face_stats_parse(buffer, size, &object->face_stats);
+}
+
+int hicnlight_face_stats_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_face_stats_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_face_stats_serialize_list(const hc_object_t *object,
+ uint8_t *packet) {
+ msg_face_stats_list_t *msg = (msg_face_stats_list_t *)packet;
+ *msg = (msg_face_stats_list_t){.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_FACE_STATS_LIST,
+ .length = 0,
+ .seq_num = 0,
+ }};
+
+ return sizeof(msg_header_t); // Do not use msg_stats_list_t
+}
+
+int hicnlight_face_stats_serialize_set(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, face_stats);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/stats.h b/ctrl/libhicnctrl/src/modules/hicn_light/stats.h
new file mode 100644
index 000000000..9509be86c
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/stats.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HICNCTRL_MODULE_HICNLIGHT_STATS_H
+#define HICNCTRL_MODULE_HICNLIGHT_STATS_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, stats);
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, face_stats);
+
+#endif /* HICNCTRL_MODULE_HICNLIGHT_STATS_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/strategy.c b/ctrl/libhicnctrl/src/modules/hicn_light/strategy.c
new file mode 100644
index 000000000..16ce2d047
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/strategy.c
@@ -0,0 +1,138 @@
+#include <assert.h>
+#include "strategy.h"
+
+#include <hicn/ctrl/hicn-light.h>
+
+static int hicnlight_strategy_parse(const u8 *buffer, size_t size,
+ hc_strategy_t *strategy) {
+ return -1;
+}
+
+int _hicnlight_strategy_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_strategy_parse(buffer, size, &object->strategy);
+}
+
+int hicnlight_strategy_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_strategy_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+int hicnlight_strategy_serialize_list(const hc_object_t *object,
+ uint8_t *packet) {
+ assert(!object);
+ return -1;
+}
+
+int hicnlight_strategy_serialize_set(const hc_object_t *object,
+ uint8_t *packet) {
+ const hc_strategy_t *strategy = &object->strategy;
+
+ msg_strategy_set_t *msg = (msg_strategy_set_t *)packet;
+ *msg = (msg_strategy_set_t){.header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_STRATEGY_SET,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .address = strategy->address,
+ .family = strategy->family,
+ .len = strategy->len,
+ .type = strategy->type,
+ }};
+
+ return sizeof(msg_strategy_set_t);
+}
+
+#if 0
+static hc_result_t *_strategy_add_local_prefix_serialize(
+ hc_sock_t *socket, hc_strategy_t *strategy) {
+ hc_result_t *res = malloc(sizeof(*res));
+ char strategy_s[MAXSZ_HC_STRATEGY];
+ strncpy(strategy->name, strategy_str(strategy->type),
+ MAXSZ_STRATEGY_NAME - 1);
+
+ int rc = hc_strategy_snprintf(strategy_s, MAXSZ_HC_STRATEGY, strategy);
+ if (rc >= MAXSZ_HC_STRATEGY)
+ WARN("[hicnlight_strategy_create] Unexpected truncation of strategy string");
+ DEBUG("[hicnlight_strategy_create] strategy=%s", strategy_s);
+
+ if (!IS_VALID_FAMILY(strategy->family) ||
+ !IS_VALID_STRATEGY_TYPE(strategy->type) ||
+ !IS_VALID_FAMILY(strategy->local_family)) {
+ res->success = false;
+ return res;
+ }
+
+ msg_strategy_add_local_prefix_t msg = {
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_STRATEGY_ADD_LOCAL_PREFIX,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {
+ .type = strategy->type,
+ .address = strategy->address,
+ .family = strategy->family,
+ .len = strategy->len,
+ .local_address = strategy->local_address,
+ .local_family = strategy->local_family,
+ .local_len = strategy->local_len,
+ }};
+
+ hc_command_params_t params = {
+ .cmd = ACTION_SET,
+ .cmd_id = COMMAND_TYPE_STRATEGY_ADD_LOCAL_PREFIX,
+ .size_in = sizeof(cmd_strategy_add_local_prefix_t),
+ .size_out = 0,
+ .parse = NULL,
+ };
+
+ *res = (hc_result_t){
+ .msg =
+ (hc_msg_t){
+ .header = msg.header,
+ .payload.strategy_add_local_prefix = msg.payload,
+ },
+ .params = params,
+ .async = false,
+ .success = true,
+ };
+ return res;
+}
+
+/* How to retrieve that from the forwarder ? */
+static const char *strategies[] = {
+ "random",
+ "load_balancer",
+};
+
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(*array))
+
+static int hicnlight_strategy_list(hc_sock_t *s, hc_data_t **data) {
+ int rc;
+
+ *data = hc_data_create(0, sizeof(hc_strategy_t), NULL);
+
+ for (unsigned i = 0; i < ARRAY_SIZE(strategies); i++) {
+ hc_strategy_t *strategy = (hc_strategy_t *)hc_data_get_next(*data);
+ if (!strategy) return -1;
+ rc = snprintf(strategy->name, MAXSZ_STRATEGY_NAME, "%s", strategies[i]);
+ if (rc >= MAXSZ_STRATEGY_NAME)
+ WARN("[hc_strategy_list] Unexpected truncation of strategy name string");
+ (*data)->size++;
+ }
+ return -1;
+}
+#endif
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, strategy);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/strategy.h b/ctrl/libhicnctrl/src/modules/hicn_light/strategy.h
new file mode 100644
index 000000000..9fa809751
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/strategy.h
@@ -0,0 +1,8 @@
+#ifndef HICNCTRL_MODULE_HICNLIGHT_STRATEGY_H
+#define HICNCTRL_MODULE_HICNLIGHT_STRATEGY_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, strategy);
+
+#endif /* HICNCTRL_MODULE_HICNLIGHT_STRATEGY_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/subscription.c b/ctrl/libhicnctrl/src/modules/hicn_light/subscription.c
new file mode 100644
index 000000000..e2de09bf5
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/subscription.c
@@ -0,0 +1,71 @@
+#include <assert.h>
+#include <hicn/ctrl/api.h>
+#include <hicn/util/log.h>
+
+#include "base.h"
+#include "../../object_private.h"
+#include "subscription.h"
+
+static int hicnlight_subscription_parse(const u8 *buffer, size_t size,
+ hc_subscription_t *subscription) {
+ /* We should never have to parse subscriptions */
+ return -1;
+}
+
+int _hicnlight_subscription_parse(const uint8_t *buffer, size_t size,
+ hc_object_t *object) {
+ return hicnlight_subscription_parse(buffer, size, &object->subscription);
+}
+
+/* SUBSCRIPTION CREATE */
+
+int hicnlight_subscription_serialize_create(const hc_object_t *object,
+ uint8_t *packet) {
+ const hc_subscription_t *subscription = &object->subscription;
+
+ msg_subscription_add_t *msg = (msg_subscription_add_t *)packet;
+ *msg = (msg_subscription_add_t){
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_SUBSCRIPTION_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {.topics = subscription->topics}};
+
+ return sizeof(msg_subscription_add_t);
+}
+
+/* SUBSCRIPTION DELETE */
+
+int hicnlight_subscription_serialize_delete(const hc_object_t *object,
+ uint8_t *packet) {
+ const hc_subscription_t *subscription = &object->subscription;
+
+ msg_subscription_remove_t *msg = (msg_subscription_remove_t *)packet;
+ *msg = (msg_subscription_remove_t){
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_SUBSCRIPTION_REMOVE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {.topics = subscription->topics}};
+
+ return sizeof(msg_subscription_remove_t);
+}
+
+int hicnlight_subscription_serialize_list(const hc_object_t *object,
+ uint8_t *packet) {
+ assert(!object);
+ return -1;
+}
+
+int hicnlight_subscription_serialize_set(const hc_object_t *object,
+ uint8_t *packet) {
+ return -1;
+}
+
+DECLARE_MODULE_OBJECT_OPS(hicnlight, subscription);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/subscription.h b/ctrl/libhicnctrl/src/modules/hicn_light/subscription.h
new file mode 100644
index 000000000..d67bdd9ba
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/subscription.h
@@ -0,0 +1,8 @@
+#ifndef HICNCTRL_MODULE_HICNLIGHT_SUBSCRIPTION_H
+#define HICNCTRL_MODULE_HICNLIGHT_SUBSCRIPTION_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(hicnlight, subscription);
+
+#endif /* HICNCTRL_MODULE_HICNLIGHT_SUBSCRIPTION_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light/wldr.c b/ctrl/libhicnctrl/src/modules/hicn_light/wldr.c
new file mode 100644
index 000000000..7d1812ab2
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_light/wldr.c
@@ -0,0 +1,3 @@
+#include "wldr.h"
+
+static int _hcng_wldr_set(hc_sock_t *s /* XXX */) { return 0; }
diff --git a/ctrl/libhicnctrl/src/modules/hicn_light_api.c b/ctrl/libhicnctrl/src/modules/hicn_light_api.c
deleted file mode 100644
index d1a055777..000000000
--- a/ctrl/libhicnctrl/src/modules/hicn_light_api.c
+++ /dev/null
@@ -1,2278 +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.
- */
-
-/**
- * \file api.c
- * \brief Implementation of hICN control library API
- */
-
-#include "api_private.h"
-
-#include <assert.h> // assert
-#include <stdbool.h>
-#include <stdio.h> // snprintf
-#include <string.h> // memmove, strcasecmp
-#include <sys/socket.h> // socket
-#include <unistd.h> // close, fcntl
-#include <fcntl.h> // fcntl
-#include <sys/types.h> // getpid
-#include <unistd.h> // getpid
-#ifdef __linux__
-#include <sys/syscall.h>
-#define gettid() syscall(SYS_gettid)
-#endif /* __linux__ */
-#include <strings.h>
-
-#define PORT 9695
-
-#define BOOLSTR(x) ((x) ? "true" : "false")
-
-/*
- * Internal state associated to a pending request
- */
-typedef struct {
- int seq;
- hc_data_t * data;
- /* Information used to process results */
- int size_in;
- int (*parse)(const u8 * src, u8 * dst);
-} hc_sock_request_t;
-
-/**
- * Messages to the forwarder might be multiplexed thanks to the seqNum fields in
- * the header_control_message structure. The forwarder simply answers back the
- * original sequence number. We maintain a map of such sequence number to
- * outgoing queries so that replied can be demultiplexed and treated
- * appropriately.
- */
-TYPEDEF_MAP_H(hc_sock_map, int, hc_sock_request_t *);
-TYPEDEF_MAP(hc_sock_map, int, hc_sock_request_t *, int_cmp, int_snprintf, generic_snprintf);
-
-struct hc_sock_light_s {
- /* This must be the first element of the struct */
- hc_sock_t vft;
-
- char * url;
- int fd;
-
- /* Partial receive buffer */
- u8 buf[RECV_BUFLEN];
- size_t roff; /**< Read offset */
- size_t woff; /**< Write offset */
-
- /*
- * Because received messages are potentially unbounded in size, we might not
- * guarantee that we can store a full packet before processing it. We must
- * implement a very simple state machine remembering the current parsing
- * status in order to partially process the packet.
- */
- size_t remaining;
- u32 send_id;
-
- /* Next sequence number to be used for requests */
- int seq;
-
- /* Request being parsed (NULL if none) */
- hc_sock_request_t * cur_request;
-
- bool async;
- hc_sock_map_t * map;
-};
-
-typedef struct hc_sock_light_s hc_sock_light_t;
-
-#define TO_HC_SOCK_LIGHT(s) (hc_sock_light_t*)(s)
-
-hc_sock_request_t *
-hc_sock_request_create(int seq, hc_data_t * data, HC_PARSE parse)
-{
- assert(data);
-
- hc_sock_request_t * request = malloc(sizeof(hc_sock_request_t));
- if (!request)
- return NULL;
- request->seq = seq;
- request->data = data;
- request->parse = parse;
- return request;
-}
-
-void
-hc_sock_light_request_free(hc_sock_request_t * request)
-{
- free(request);
-}
-
-/*
- * list was working with all seq set to 0, but it seems hicnLightControl uses
- * 1, and replies with the same seqno
- */
-#define HICN_CTRL_SEND_SEQ_INIT 1
-#define HICN_CTRL_RECV_SEQ_INIT 1
-
-#define MAX(x, y) ((x > y) ? x : y)
-
-/**
- * In practise, we want to preserve enough room to store a full packet of
- * average expected size (say a header + N payload elements).
- */
-#define AVG_ELEMENTS (1 << DEFAULT_SIZE_LOG)
-#define AVG_BUFLEN (sizeof(hc_msg_header_t) + AVG_ELEMENTS * sizeof(hc_msg_payload_t))
-
-/*
- * We should at least have buffer space allowing to store one processable unit
- * of data, either the header of the maximum possible payload
- */
-#define MIN_BUFLEN MAX(sizeof(hc_msg_header_t), sizeof(hc_msg_payload_t))
-
-static const struct in6_addr loopback_addr = IN6ADDR_LOOPBACK_INIT;
-
-/******************************************************************************
- * Message helper types and aliases
- ******************************************************************************/
-
-#define foreach_hc_command \
- _(add_connection) \
- _(remove_connection) \
- _(list_connections) \
- _(add_listener) \
- _(remove_listener) \
- _(list_listeners) \
- _(add_route) \
- _(remove_route) \
- _(list_routes) \
- _(cache_store) \
- _(cache_serve) \
- /*_(cache_clear) */ \
- _(set_strategy) \
- _(set_wldr) \
- _(add_punting) \
- _(mapme_activator) \
- _(mapme_timing)
-
-typedef header_control_message hc_msg_header_t;
-
-typedef union {
-#define _(x) x ## _command x;
- foreach_hc_command
-#undef _
-} hc_msg_payload_t;
-
-
-typedef struct hc_msg_s {
- hc_msg_header_t hdr;
- hc_msg_payload_t payload;
-} hc_msg_t;
-
-/******************************************************************************
- * Control socket
- ******************************************************************************/
-
-/**
- * \brief Parse a connection URL into a sockaddr
- * \param [in] url - URL
- * \param [out] sa - Resulting struct sockaddr, expected zero'ed.
- * \return 0 if parsing succeeded, a negative error value otherwise.
- */
-static int
-_hc_sock_light_parse_url(const char * url, struct sockaddr * sa)
-{
- /* FIXME URL parsing is currently not implemented */
- assert(!url);
-
-#ifdef __linux__
- srand(time(NULL) ^ getpid() ^ gettid());
-#else
- srand((unsigned int )(time(NULL) ^ getpid()));
-#endif /* __linux__ */
-
- /*
- * A temporary solution is to inspect the sa_family fields of the passed in
- * sockaddr, which defaults to AF_UNSPEC (0) and thus creates an IPv4/TCP
- * connection to localhost.
- */
- switch (sa->sa_family) {
- case AF_UNSPEC:
- case AF_INET:
- {
- struct sockaddr_in * sai = (struct sockaddr_in *)sa;
- sai->sin_family = AF_INET;
- sai->sin_port = htons(PORT);
- sai->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- break;
- }
- case AF_INET6:
- {
- struct sockaddr_in6 * sai6 = (struct sockaddr_in6 *)sa;
- sai6->sin6_family = AF_INET6;
- sai6->sin6_port = htons(PORT);
- sai6->sin6_addr = loopback_addr;
- break;
- }
- default:
- return -1;
- }
-
- return 0;
-}
-
-static int
-_hc_sock_light_reset(hc_sock_t * socket)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- s->roff = s->woff = 0;
- s->remaining = 0;
- return 0;
-}
-
-void
-_hc_sock_light_free(hc_sock_t * socket)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- hc_sock_request_t ** request_array = NULL;
- int n = hc_sock_map_get_value_array(s->map, &request_array);
- if (n < 0) {
- ERROR("Could not retrieve pending request array for freeing up resources");
- } else {
- for (unsigned i = 0; i < n; i++) {
- hc_sock_request_t * request = request_array[i];
- if (hc_sock_map_remove(s->map, request->seq, NULL) < 0)
- ERROR("[hc_sock_light_process] Error removing request from map");
- hc_sock_light_request_free(request);
- }
- free(request_array);
- }
-
- hc_sock_map_free(s->map);
- if (s->url)
- free(s->url);
- close(s->fd);
- free(s);
-}
-
-static int
-_hc_sock_light_get_next_seq(hc_sock_t * socket)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- return s->seq++;
-}
-
-static int
-_hc_sock_light_set_nonblocking(hc_sock_t * socket)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- return (fcntl(s->fd, F_SETFL, fcntl(s->fd, F_GETFL) | O_NONBLOCK) < 0);
-}
-
-static int
-_hc_sock_light_get_fd(hc_sock_t * socket)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- return s->fd;
-}
-
-static int
-_hc_sock_light_connect(hc_sock_t * socket)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- struct sockaddr_storage ss;
- memset(&ss, 0, sizeof(struct sockaddr_storage));
-
- if (_hc_sock_light_parse_url(s->url, (struct sockaddr *)&ss) < 0)
- goto ERR_PARSE;
-
- size_t size = ss.ss_family == AF_INET
- ? sizeof(struct sockaddr_in)
- : sizeof(struct sockaddr_in6);
- if (connect(s->fd, (struct sockaddr *)&ss, (socklen_t)size) < 0) //sizeof(struct sockaddr)) < 0)
- goto ERR_CONNECT;
-
- return 0;
-
-ERR_CONNECT:
-ERR_PARSE:
- return -1;
-}
-
-static int
-_hc_sock_light_send(hc_sock_t * socket, hc_msg_t * msg, size_t msglen, int seq)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- int rc;
- msg->hdr.seqNum = seq;
- rc = (int)send(s->fd, msg, msglen, 0);
- if (rc < 0) {
- perror("hc_sock_light_send");
- return -1;
- }
- return 0;
-}
-
-static int
-_hc_sock_light_get_available(hc_sock_t * socket, u8 ** buffer, size_t * size)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- *buffer = s->buf + s->woff;
- *size = RECV_BUFLEN - s->woff;
-
- return 0;
-}
-
-static int
-_hc_sock_light_recv(hc_sock_t * socket)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- int rc;
-
- /*
- * This condition should be ensured to guarantee correct processing of
- * messages
- */
- assert(RECV_BUFLEN - s->woff > MIN_BUFLEN);
-
- rc = (int)recv(s->fd, s->buf + s->woff, RECV_BUFLEN - s->woff, 0);
- if (rc == 0) {
- /* Connection has been closed */
- return 0;
- }
- if (rc < 0) {
- /*
- * Let's not return 0 which currently means the socket has been closed
- */
- if (errno == EWOULDBLOCK)
- return -1;
- perror("hc_sock_light_recv");
- return -1;
- }
- s->woff += rc;
- return rc;
-}
-
-/*
- * Returns -99 in case of internal error, -1 in case of API command failure
- */
-static int
-_hc_sock_light_process(hc_sock_t * socket, hc_data_t ** data)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- int err = 0;
-
- /* We must have received at least one byte */
- size_t available = s->woff - s->roff;
-
- while(available > 0) {
-
- if (!s->cur_request) { // No message being parsed, alternatively (remaining == 0)
- hc_msg_t * msg = (hc_msg_t*)(s->buf + s->roff);
-
- /* We expect a message header */
- if (available < sizeof(hc_msg_header_t)) {
- break;
- }
-
- hc_sock_request_t * request = NULL;
- if (hc_sock_map_get(s->map, msg->hdr.seqNum, &request) < 0) {
- ERROR("[hc_sock_light_process] Error searching for matching request");
- return -99;
- }
- if (!request) {
- ERROR("[hc_sock_light_process] No request matching received sequence number");
- return -99;
- }
-
- s->remaining = msg->hdr.length;
- switch(msg->hdr.messageType) {
- case ACK_LIGHT:
- assert(s->remaining == 1);
- assert(!data);
- s->cur_request = request;
- break;
- case NACK_LIGHT:
- assert(s->remaining == 1);
- assert(!data);
- hc_data_set_error(request->data);
- s->cur_request = request;
- err = -1;
- break;
- case RESPONSE_LIGHT:
- assert(data);
- if (s->remaining == 0) {
- hc_data_set_complete(request->data);
- *data = request->data;
- if (hc_sock_map_remove(s->map, request->seq, NULL) < 0)
- ERROR("[hc_sock_light_process] Error removing request from map");
- hc_sock_light_request_free(request);
- } else {
- /* We only remember it if there is still data to parse */
- s->cur_request = request;
- }
- break;
- default:
- ERROR("[hc_sock_light_process] Invalid response received");
- return -99;
- }
-
- available -= sizeof(hc_msg_header_t);
- s->roff += sizeof(hc_msg_header_t);
- } else {
- /* We expect the complete payload, or at least a chunk of it */
- size_t num_chunks = available / s->cur_request->data->in_element_size;
- if (num_chunks == 0)
- break;
- if (num_chunks > s->remaining)
- num_chunks = s->remaining;
-
- if (!s->cur_request->parse) {
- /* If we don't need to parse results, then we can directly push
- * all of them into the result data structure */
- hc_data_push_many(s->cur_request->data, s->buf + s->roff, num_chunks);
- } else {
- int rc;
- rc = hc_data_ensure_available(s->cur_request->data, num_chunks);
- if (rc < 0) {
- ERROR("[hc_sock_light_process] Error in hc_data_ensure_available");
- return -99;
- }
- for (int i = 0; i < num_chunks; i++) {
- u8 * dst = hc_data_get_next(s->cur_request->data);
- if (!dst) {
- ERROR("[hc_sock_light_process] Error in hc_data_get_next");
- return -99;
- }
-
- rc = s->cur_request->parse(s->buf + s->roff + i * s->cur_request->data->in_element_size, dst);
- if (rc < 0) {
- ERROR("[hc_sock_light_process] Error in parse");
- err = -99; /* FIXME we let the loop complete (?) */
- }
- s->cur_request->data->size++;
- }
- }
-
- s->remaining -= num_chunks;
- available -= num_chunks * s->cur_request->data->in_element_size;
- s->roff += num_chunks * s->cur_request->data->in_element_size;
- if (s->remaining == 0) {
- if (hc_sock_map_remove(s->map, s->cur_request->seq, NULL) < 0) {
- ERROR("[hc_sock_light_process] Error removing request from map");
- return -99;
- }
- hc_data_set_complete(s->cur_request->data);
- if (data)
- *data = s->cur_request->data;
- hc_sock_light_request_free(s->cur_request);
- s->cur_request = NULL;
- }
-
- }
- }
-
- /* Make sure there is enough remaining space in the buffer */
- if (RECV_BUFLEN - s->woff < AVG_BUFLEN) {
- /*
- * There should be no overlap provided a sufficiently large BUFLEN, but
- * who knows.
- */
- memmove(s->buf, s->buf + s->roff, s->woff - s->roff);
- s->woff -= s->roff;
- s->roff = 0;
- }
-
- return err;
-}
-
-static int
-_hc_sock_light_callback(hc_sock_t * socket, hc_data_t ** pdata)
-{
- hc_data_t * data;
-
- for (;;) {
- int n = _hc_sock_light_recv(socket);
- if (n == 0)
- goto ERR_EOF;
- if (n < 0) {
- switch(errno) {
- case ECONNRESET:
- case ENODEV:
- /* Forwarder restarted */
- WARN("Forwarder likely restarted: not (yet) implemented");
- goto ERR;
- case EWOULDBLOCK:
- //DEBUG("Would block... stop reading from socket");
- goto END;
- default:
- perror("hc_sock_light_recv");
- goto ERR;
- }
- }
- if (_hc_sock_light_process(socket, &data) < 0) {
- goto ERR;
- }
- }
-END:
- if (pdata)
- *pdata = data;
- else
- hc_data_free(data);
- return 0;
-
-ERR:
- hc_data_free(data);
-ERR_EOF:
- return -1;
-}
-
-/******************************************************************************
- * Command-specific structures and functions
- ******************************************************************************/
-
-typedef int (*HC_PARSE)(const u8 *, u8 *);
-
-typedef struct {
- hc_action_t cmd;
- command_id cmd_id;
- size_t size_in;
- size_t size_out;
- HC_PARSE parse;
-} hc_command_params_t;
-
-static int
-_hc_execute_command(hc_sock_t * socket, hc_msg_t * msg, size_t msg_len,
- hc_command_params_t * params, hc_data_t ** pdata, bool async)
-{
- hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket);
- int ret;
- if (async)
- assert(!pdata);
-
- /* Sanity check */
- switch(params->cmd) {
- case ACTION_CREATE:
- assert(params->size_in != 0); /* payload repeated */
- assert(params->size_out == 0);
- assert(params->parse == NULL);
- break;
- case ACTION_DELETE:
- assert(params->size_in != 0); /* payload repeated */
- assert(params->size_out == 0);
- assert(params->parse == NULL);
- break;
- case ACTION_LIST:
- assert(params->size_in != 0);
- assert(params->size_out != 0);
- assert(params->parse != NULL);
- break;
- case ACTION_SET:
- assert(params->size_in != 0);
- assert(params->size_out == 0);
- assert(params->parse == NULL);
- break;
- default:
- return -1;
- }
-
- //hc_sock_light_reset(s);
-
- /* XXX data will at least store the result (complete) */
- hc_data_t * data = hc_data_create(params->size_in, params->size_out, NULL);
- if (!data) {
- ERROR("[_hc_execute_command] Could not create data storage");
- goto ERR_DATA;
- }
-
- int seq = _hc_sock_light_get_next_seq(socket);
-
- /* Create state used to process the request */
- hc_sock_request_t * request = NULL;
- request = hc_sock_request_create(seq, data, params->parse);
- if (!request) {
- ERROR("[_hc_execute_command] Could not create request state");
- goto ERR_REQUEST;
- }
-
- /* Add state to map */
- if (hc_sock_map_add(s->map, seq, request) < 0) {
- ERROR("[_hc_execute_command] Error adding request state to map");
- goto ERR_MAP;
- }
-
- if (_hc_sock_light_send(socket, msg, msg_len, seq) < 0) {
- ERROR("[_hc_execute_command] Error sending message");
- goto ERR_PROCESS;
- }
-
- if (async)
- return 0;
-
- while(!data->complete) {
- /*
- * As the socket is non blocking it might happen that we need to read
- * several times before success... shall we alternate between blocking
- * and non-blocking mode ?
- */
- int n = _hc_sock_light_recv(socket);
- if (n == 0)
- goto ERR_EOF;
- if (n < 0)
- continue; //break;
- int rc = _hc_sock_light_process(socket, pdata);
- switch(rc) {
- case 0:
- break;
- case -1:
- ret = rc;
- break;
- case -99:
- ERROR("[_hc_execute_command] Error processing socket results");
- goto ERR;
- break;
- default:
- ERROR("[_hc_execute_command] Unexpected return value");
- goto ERR;
- }
- }
-
-ERR_EOF:
- ret = data->ret;
- if (!data->complete)
- return -1;
- if (!pdata)
- hc_data_free(data);
-
- return ret;
-
-ERR_PROCESS:
-ERR_MAP:
- hc_sock_light_request_free(request);
-ERR:
-ERR_REQUEST:
- hc_data_free(data);
-ERR_DATA:
- return -99;
-}
-
-/*----------------------------------------------------------------------------*
- * Listeners
- *----------------------------------------------------------------------------*/
-
-/* LISTENER CREATE */
-
-static int
-_hc_listener_create_internal(hc_sock_t * socket, hc_listener_t * listener, bool async)
-{
- char listener_s[MAXSZ_HC_LISTENER];
- int rc = hc_listener_snprintf(listener_s, MAXSZ_HC_LISTENER, listener);
- if (rc >= MAXSZ_HC_LISTENER)
- WARN("[_hc_listener_create] Unexpected truncation of listener string");
- DEBUG("[_hc_listener_create] listener=%s async=%s", listener_s,
- BOOLSTR(async));
-
- if (!IS_VALID_FAMILY(listener->family))
- return -1;
-
- if (!IS_VALID_CONNECTION_TYPE(listener->type))
- return -1;
-
- struct {
- header_control_message hdr;
- add_listener_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = ADD_LISTENER,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .address = listener->local_addr,
- .port = htons(listener->local_port),
- .addressType = (u8)map_to_addr_type[listener->family],
- .listenerMode = (u8)map_to_listener_mode[listener->type],
- .connectionType = (u8)map_to_connection_type[listener->type],
- }
- };
-
- rc = snprintf(msg.payload.symbolic, SYMBOLIC_NAME_LEN, "%s", listener->name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_listener_create] Unexpected truncation of symbolic name string");
-
- rc = snprintf(msg.payload.interfaceName, INTERFACE_LEN, "%s", listener->interface_name);
- if (rc >= INTERFACE_LEN)
- WARN("[_hc_listener_create] Unexpected truncation of interface name string");
-
- hc_command_params_t params = {
- .cmd = ACTION_CREATE,
- .cmd_id = ADD_LISTENER,
- .size_in = sizeof(add_listener_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_listener_create(hc_sock_t * s, hc_listener_t * listener)
-{
- return _hc_listener_create_internal(s, listener, false);
-}
-
-static int
-_hc_listener_create_async(hc_sock_t * s, hc_listener_t * listener)
-{
- return _hc_listener_create_internal(s, listener, true);
-}
-
-/* LISTENER LIST */
-
-static int
-_hc_listener_list_internal(hc_sock_t * socket, hc_data_t ** pdata, bool async)
-{
- DEBUG("[hc_listener_list] async=%s", BOOLSTR(async));
-
- struct {
- header_control_message hdr;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = LIST_LISTENERS,
- .length = 0,
- .seqNum = 0,
- },
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_LIST,
- .cmd_id = LIST_LISTENERS,
- .size_in = sizeof(list_listeners_command),
- .size_out = sizeof(hc_listener_t),
- .parse = (HC_PARSE)hc_listener_parse,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, pdata, async);
-}
-
-static int
-_hc_listener_list(hc_sock_t * s, hc_data_t ** pdata)
-{
- return _hc_listener_list_internal(s, pdata, false);
-}
-
-static int
-_hc_listener_list_async(hc_sock_t * s, hc_data_t ** pdata)
-{
- return _hc_listener_list_internal(s, pdata, true);
-}
-
-/* LISTENER GET */
-
-static int
-_hc_listener_get(hc_sock_t * socket, hc_listener_t * listener,
- hc_listener_t ** listener_found)
-{
- hc_data_t * listeners;
- hc_listener_t * found;
-
- char listener_s[MAXSZ_HC_LISTENER];
- int rc = hc_listener_snprintf(listener_s, MAXSZ_HC_LISTENER, listener);
- if (rc >= MAXSZ_HC_LISTENER)
- WARN("[hc_listener_get] Unexpected truncation of listener string");
- DEBUG("[hc_listener_get] listener=%s", listener_s);
-
- if (_hc_listener_list(socket, &listeners) < 0)
- return -1;
-
- /* Test */
- if (hc_listener_find(listeners, listener, &found) < 0) {
- hc_data_free(listeners);
- return -1;
- }
-
- if (found) {
- *listener_found = malloc(sizeof(hc_listener_t));
- if (!*listener_found)
- return -1;
- **listener_found = *found;
- } else {
- *listener_found = NULL;
- }
-
- hc_data_free(listeners);
-
- return 0;
-}
-
-
-/* LISTENER DELETE */
-
-static int
-_hc_listener_delete_internal(hc_sock_t * socket, hc_listener_t * listener, bool async)
-{
- char listener_s[MAXSZ_HC_LISTENER];
- int rc = hc_listener_snprintf(listener_s, MAXSZ_HC_LISTENER, listener);
- if (rc >= MAXSZ_HC_LISTENER)
- WARN("[_hc_listener_delete] Unexpected truncation of listener string");
- DEBUG("[_hc_listener_delete] listener=%s async=%s", listener_s,
- BOOLSTR(async));
-
- struct {
- header_control_message hdr;
- remove_listener_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = REMOVE_LISTENER,
- .length = 1,
- .seqNum = 0,
- },
- };
-
- if (listener->id) {
- rc = snprintf(msg.payload.symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%d", listener->id);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_listener_delete] Unexpected truncation of symbolic name string");
- } else if (*listener->name) {
- rc = snprintf(msg.payload.symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%s", listener->name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_listener_delete] Unexpected truncation of symbolic name string");
- } else {
- hc_listener_t * listener_found;
- if (_hc_listener_get(socket, listener, &listener_found) < 0)
- return -1;
- if (!listener_found)
- return -1;
- rc = snprintf(msg.payload.symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%d", listener_found->id);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_listener_delete] Unexpected truncation of symbolic name string");
- free(listener_found);
- }
-
- hc_command_params_t params = {
- .cmd = ACTION_DELETE,
- .cmd_id = REMOVE_LISTENER,
- .size_in = sizeof(remove_listener_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_listener_delete(hc_sock_t * s, hc_listener_t * listener)
-{
- return _hc_listener_delete_internal(s, listener, false);
-}
-
-static int
-_hc_listener_delete_async(hc_sock_t * s, hc_listener_t * listener)
-{
- return _hc_listener_delete_internal(s, listener, true);
-}
-
-/*----------------------------------------------------------------------------*
- * CONNECTION
- *----------------------------------------------------------------------------*/
-
-/* CONNECTION CREATE */
-
-static int
-_hc_connection_create_internal(hc_sock_t * socket, hc_connection_t * connection, bool async)
-{
- char connection_s[MAXSZ_HC_CONNECTION];
- int rc = hc_connection_snprintf(connection_s, MAXSZ_HC_CONNECTION, connection);
- if (rc >= MAXSZ_HC_CONNECTION)
- WARN("[_hc_connection_create] Unexpected truncation of connection string");
- DEBUG("[_hc_connection_create] connection=%s async=%s", connection_s, BOOLSTR(async));
-
- if (hc_connection_validate(connection) < 0)
- return -1;
-
- struct {
- header_control_message hdr;
- add_connection_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = ADD_CONNECTION,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .remoteIp = connection->remote_addr,
- .localIp = connection->local_addr,
- .remotePort = htons(connection->remote_port),
- .localPort = htons(connection->local_port),
- .ipType = (u8)map_to_addr_type[connection->family],
- .connectionType = (u8)map_to_connection_type[connection->type],
- .admin_state = connection->admin_state,
-#ifdef WITH_POLICY
- .priority = connection->priority,
- .tags = connection->tags,
-#endif /* WITH_POLICY */
- }
- };
- rc = snprintf(msg.payload.symbolic, SYMBOLIC_NAME_LEN, "%s", connection->name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_connection_create] Unexpected truncation of symbolic name string");
- //snprintf(msg.payload.interfaceName, INTERFACE_NAME_LEN, "%s", connection->interface_name);
-
- hc_command_params_t params = {
- .cmd = ACTION_CREATE,
- .cmd_id = ADD_CONNECTION,
- .size_in = sizeof(add_connection_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_connection_create(hc_sock_t * s, hc_connection_t * connection)
-{
- return _hc_connection_create_internal(s, connection, false);
-}
-
-static int
-_hc_connection_create_async(hc_sock_t * s, hc_connection_t * connection)
-{
- return _hc_connection_create_internal(s, connection, true);
-}
-
-/* CONNECTION LIST */
-
-static int
-_hc_connection_list_internal(hc_sock_t * socket, hc_data_t ** pdata, bool async)
-{
- DEBUG("[hc_connection_list] async=%s", BOOLSTR(async));
-
- struct {
- header_control_message hdr;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = LIST_CONNECTIONS,
- .length = 0,
- .seqNum = 0,
- },
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_LIST,
- .cmd_id = LIST_CONNECTIONS,
- .size_in = sizeof(list_connections_command),
- .size_out = sizeof(hc_connection_t),
- .parse = (HC_PARSE)hc_connection_parse,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, pdata, async);
-}
-
-static int
-_hc_connection_list(hc_sock_t * s, hc_data_t ** pdata)
-{
- return _hc_connection_list_internal(s, pdata, false);
-}
-
-static int
-_hc_connection_list_async(hc_sock_t * s, hc_data_t ** pdata)
-{
- return _hc_connection_list_internal(s, pdata, true);
-}
-
-/* CONNECTION GET */
-
-static int
-_hc_connection_get(hc_sock_t * socket, hc_connection_t * connection,
- hc_connection_t ** connection_found)
-{
- hc_data_t * connections;
- hc_connection_t * found;
-
- char connection_s[MAXSZ_HC_CONNECTION];
- int rc = hc_connection_snprintf(connection_s, MAXSZ_HC_CONNECTION, connection);
- if (rc >= MAXSZ_HC_CONNECTION)
- WARN("[hc_connection_get] Unexpected truncation of connection string");
- DEBUG("[hc_connection_get] connection=%s", connection_s);
-
- if (_hc_connection_list(socket, &connections) < 0)
- return -1;
-
- /* Test */
- if (hc_connection_find(connections, connection, &found) < 0) {
- hc_data_free(connections);
- return -1;
- }
-
- if (found) {
- *connection_found = malloc(sizeof(hc_connection_t));
- if (!*connection_found)
- return -1;
- **connection_found = *found;
- } else {
- *connection_found = NULL;
- }
-
- hc_data_free(connections);
-
- return 0;
-}
-
-
-/* CONNECTION DELETE */
-
-static int
-_hc_connection_delete_internal(hc_sock_t * socket, hc_connection_t * connection, bool async)
-{
- char connection_s[MAXSZ_HC_CONNECTION];
- int rc = hc_connection_snprintf(connection_s, MAXSZ_HC_CONNECTION, connection);
- if (rc >= MAXSZ_HC_CONNECTION)
- WARN("[_hc_connection_delete] Unexpected truncation of connection string");
- DEBUG("[_hc_connection_delete] connection=%s async=%s", connection_s, BOOLSTR(async));
-
- struct {
- header_control_message hdr;
- remove_connection_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = REMOVE_CONNECTION,
- .length = 1,
- .seqNum = 0,
- },
- };
-
- if (connection->id) {
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%d", connection->id);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_connection_delete] Unexpected truncation of symbolic name string");
- } else if (*connection->name) {
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%s", connection->name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_connection_delete] Unexpected truncation of symbolic name string");
- } else {
- hc_connection_t * connection_found;
- if (_hc_connection_get(socket, connection, &connection_found) < 0)
- return -1;
- if (!connection_found)
- return -1;
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%d", connection_found->id);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_connection_delete] Unexpected truncation of symbolic name string");
- free(connection_found);
- }
-
- hc_command_params_t params = {
- .cmd = ACTION_DELETE,
- .cmd_id = REMOVE_CONNECTION,
- .size_in = sizeof(remove_connection_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_connection_delete(hc_sock_t * s, hc_connection_t * connection)
-{
- return _hc_connection_delete_internal(s, connection, false);
-}
-
-static int
-_hc_connection_delete_async(hc_sock_t * s, hc_connection_t * connection)
-{
- return _hc_connection_delete_internal(s, connection, true);
-}
-
-static int
-_hc_connection_update_by_id(hc_sock_t *s, int hc_connection_id,
- hc_connection_t *connection)
-{
- // Not implemented
- return -1;
-}
-
-static int
-_hc_connection_update(hc_sock_t *s, hc_connection_t *connection_current,
- hc_connection_t *connection_updated)
-{
- // Not implemented
- return -1;
-}
-
-/* CONNECTION SET ADMIN STATE */
-
-static int
-_hc_connection_set_admin_state_internal(hc_sock_t * socket, const char * conn_id_or_name,
- face_state_t state, bool async)
-{
- int rc;
- DEBUG("[hc_connection_set_admin_state] connection_id/name=%s admin_state=%s async=%s",
- conn_id_or_name, face_state_str[state], BOOLSTR(async));
- struct {
- header_control_message hdr;
- connection_set_admin_state_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = CONNECTION_SET_ADMIN_STATE,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .admin_state = state,
- },
- };
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%s", conn_id_or_name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_connection_set_admin_state] Unexpected truncation of symbolic name string");
-
- hc_command_params_t params = {
- .cmd = ACTION_SET,
- .cmd_id = CONNECTION_SET_ADMIN_STATE,
- .size_in = sizeof(connection_set_admin_state_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_connection_set_admin_state(hc_sock_t * s, const char * conn_id_or_name,
- face_state_t state)
-{
- return _hc_connection_set_admin_state_internal(s, conn_id_or_name, state, false);
-}
-
-static int
-_hc_connection_set_admin_state_async(hc_sock_t * s, const char * conn_id_or_name,
- face_state_t state)
-{
- return _hc_connection_set_admin_state_internal(s, conn_id_or_name, state, true);
-}
-
-#ifdef WITH_POLICY
-
-static int
-_hc_connection_set_priority_internal(hc_sock_t * socket, const char * conn_id_or_name,
- uint32_t priority, bool async)
-{
- int rc;
- DEBUG("[hc_connection_set_priority] connection_id/name=%s priority=%d async=%s",
- conn_id_or_name, priority, BOOLSTR(async));
- struct {
- header_control_message hdr;
- connection_set_priority_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = CONNECTION_SET_PRIORITY,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .priority = priority,
- },
- };
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%s", conn_id_or_name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_connection_set_priority] Unexpected truncation of symbolic name string");
-
- hc_command_params_t params = {
- .cmd = ACTION_SET,
- .cmd_id = CONNECTION_SET_PRIORITY,
- .size_in = sizeof(connection_set_priority_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_connection_set_priority(hc_sock_t * s, const char * conn_id_or_name,
- uint32_t priority)
-{
- return _hc_connection_set_priority_internal(s, conn_id_or_name, priority, false);
-}
-
-static int
-_hc_connection_set_priority_async(hc_sock_t * s, const char * conn_id_or_name,
- uint32_t priority)
-{
- return _hc_connection_set_priority_internal(s, conn_id_or_name, priority, true);
-}
-
-#endif // WITH_POLICY
-
-static int
-_hc_connection_set_tags_internal(hc_sock_t * s, const char * conn_id_or_name,
- policy_tags_t tags, bool async)
-{
- int rc;
- DEBUG("[hc_connection_set_tags] connection_id/name=%s tags=%d async=%s",
- conn_id_or_name, tags, BOOLSTR(async));
- struct {
- header_control_message hdr;
- connection_set_tags_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = CONNECTION_SET_TAGS,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .tags = tags,
- },
- };
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%s", conn_id_or_name);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_connection_set_tags] Unexpected truncation of symbolic name string");
-
- hc_command_params_t params = {
- .cmd = ACTION_SET,
- .cmd_id = CONNECTION_SET_TAGS,
- .size_in = sizeof(connection_set_tags_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(s, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_connection_set_tags(hc_sock_t * s, const char * conn_id_or_name,
- policy_tags_t tags)
-{
- return _hc_connection_set_tags_internal(s, conn_id_or_name, tags, false);
-}
-
-static int
-_hc_connection_set_tags_async(hc_sock_t * s, const char * conn_id_or_name,
- policy_tags_t tags)
-{
- return _hc_connection_set_tags_internal(s, conn_id_or_name, tags, true);
-}
-
-/*----------------------------------------------------------------------------*
- * Routes
- *----------------------------------------------------------------------------*/
-
-/* ROUTE CREATE */
-
-static int
-_hc_route_create_internal(hc_sock_t * socket, hc_route_t * route, bool async)
-{
- char route_s[MAXSZ_HC_ROUTE];
- int rc = hc_route_snprintf(route_s, MAXSZ_HC_ROUTE, route);
- if (rc >= MAXSZ_HC_ROUTE)
- WARN("[_hc_route_create] Unexpected truncation of route string");
- if (rc < 0)
- WARN("[_hc_route_create] Error building route string");
- else
- DEBUG("[hc_route_create] route=%s async=%s", route_s, BOOLSTR(async));
-
- if (!IS_VALID_FAMILY(route->family))
- return -1;
-
- struct {
- header_control_message hdr;
- add_route_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = ADD_ROUTE,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .address = route->remote_addr,
- .cost = route->cost,
- .addressType = (u8)map_to_addr_type[route->family],
- .len = route->len,
- }
- };
-
- /*
- * The route commands expects the ID (or name that we don't use) as part of
- * the symbolicOrConnid attribute.
- */
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%d", route->face_id);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_route_create] Unexpected truncation of symbolic name string");
-
- hc_command_params_t params = {
- .cmd = ACTION_CREATE,
- .cmd_id = ADD_ROUTE,
- .size_in = sizeof(add_route_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_route_create(hc_sock_t * s, hc_route_t * route)
-{
- return _hc_route_create_internal(s, route, false);
-}
-
-static int
-_hc_route_create_async(hc_sock_t * s, hc_route_t * route)
-{
- return _hc_route_create_internal(s, route, true);
-}
-
-/* ROUTE DELETE */
-
-static int
-_hc_route_delete_internal(hc_sock_t * socket, hc_route_t * route, bool async)
-{
- char route_s[MAXSZ_HC_ROUTE];
- int rc = hc_route_snprintf(route_s, MAXSZ_HC_ROUTE, route);
- if (rc >= MAXSZ_HC_ROUTE)
- WARN("[_hc_route_delete] Unexpected truncation of route string");
- DEBUG("[hc_route_delete] route=%s async=%s", route_s, BOOLSTR(async));
-
- if (!IS_VALID_FAMILY(route->family))
- return -1;
-
- struct {
- header_control_message hdr;
- remove_route_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = REMOVE_ROUTE,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .address = route->remote_addr,
- .addressType = (u8)map_to_addr_type[route->family],
- .len = route->len,
- }
- };
-
- /*
- * The route commands expects the ID (or name that we don't use) as part of
- * the symbolicOrConnid attribute.
- */
- snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%d", route->face_id);
-
- hc_command_params_t params = {
- .cmd = ACTION_DELETE,
- .cmd_id = REMOVE_ROUTE,
- .size_in = sizeof(remove_route_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_route_delete(hc_sock_t * s, hc_route_t * route)
-{
- return _hc_route_delete_internal(s, route, false);
-}
-
-static int
-_hc_route_delete_async(hc_sock_t * s, hc_route_t * route)
-{
- return _hc_route_delete_internal(s, route, true);
-}
-
-/* ROUTE LIST */
-
-static int
-_hc_route_list_internal(hc_sock_t * socket, hc_data_t ** pdata, bool async)
-{
- //DEBUG("[hc_route_list] async=%s", BOOLSTR(async));
-
- struct {
- header_control_message hdr;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = LIST_ROUTES,
- .length = 0,
- .seqNum = 0,
- },
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_LIST,
- .cmd_id = LIST_ROUTES,
- .size_in = sizeof(list_routes_command),
- .size_out = sizeof(hc_route_t),
- .parse = (HC_PARSE)hc_route_parse,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, pdata, async);
-}
-
-static int
-_hc_route_list(hc_sock_t * s, hc_data_t ** pdata)
-{
- return _hc_route_list_internal(s, pdata, false);
-}
-
-static int
-_hc_route_list_async(hc_sock_t * s)
-{
- return _hc_route_list_internal(s, NULL, true);
-}
-
-/*----------------------------------------------------------------------------*
- * Face
- *
- * Face support is not directly available in hicn-light, but we can offer such
- * an interface through a combination of listeners and connections. The code
- * starts with some conversion functions between faces/listeners/connections.
- *
- * We also need to make sure that there always exist a (single) listener when a
- * connection is created, and in the hICN face case, that there is a single
- * connection attached to this listener.
- *
- *----------------------------------------------------------------------------*/
-
-/* FACE CREATE */
-
-static int
-_hc_face_create(hc_sock_t * socket, hc_face_t * face)
-{
- hc_listener_t listener;
- hc_listener_t * listener_found;
-
- hc_connection_t connection;
- hc_connection_t * connection_found;
-
- char face_s[MAXSZ_HC_FACE];
- int rc = hc_face_snprintf(face_s, MAXSZ_HC_FACE, face);
- if (rc >= MAXSZ_HC_FACE)
- WARN("[hc_face_create] Unexpected truncation of face string");
- DEBUG("[hc_face_create] face=%s", face_s);
-
- switch(face->face.type)
- {
- case FACE_TYPE_HICN:
- case FACE_TYPE_TCP:
- case FACE_TYPE_UDP:
- if (hc_face_to_connection(face, &connection, true) < 0) {
- ERROR("[hc_face_create] Could not convert face to connection.");
- return -1;
- }
-
- /* Ensure we have a corresponding local listener */
- if (hc_connection_to_local_listener(&connection, &listener) < 0) {
- ERROR("[hc_face_create] Could not convert face to local listener.");
- return -1;
- }
-
- if (_hc_listener_get(socket, &listener, &listener_found) < 0) {
- ERROR("[hc_face_create] Could not retrieve listener");
- return -1;
- }
-
- if (!listener_found) {
- /* We need to create the listener if it does not exist */
- if (_hc_listener_create(socket, &listener) < 0) {
- ERROR("[hc_face_create] Could not create listener.");
- free(listener_found);
- return -1;
- }
- } else {
- free(listener_found);
- }
-
- /* Create corresponding connection */
- if (_hc_connection_create(socket, &connection) < 0) {
- ERROR("[hc_face_create] Could not create connection.");
- return -1;
- }
-
- /*
- * Once the connection is created, we need to list all connections
- * and compare with the current one to find the created face ID.
- */
- if (_hc_connection_get(socket, &connection, &connection_found) < 0) {
- ERROR("[hc_face_create] Could not retrieve connection");
- return -1;
- }
-
- if (!connection_found) {
- ERROR("[hc_face_create] Could not find newly created connection.");
- return -1;
- }
-
- face->id = connection_found->id;
- free(connection_found);
-
- break;
-
- case FACE_TYPE_HICN_LISTENER:
- case FACE_TYPE_TCP_LISTENER:
- case FACE_TYPE_UDP_LISTENER:
- if (hc_face_to_listener(face, &listener) < 0) {
- ERROR("Could not convert face to listener.");
- return -1;
- }
- if (_hc_listener_create(socket, &listener) < 0) {
- ERROR("[hc_face_create] Could not create listener.");
- return -1;
- }
- return -1;
- break;
- default:
- ERROR("[hc_face_create] Unknwon face type.");
-
- return -1;
- };
-
- return 0;
-}
-
-static int
-_hc_face_get(hc_sock_t * socket, hc_face_t * face, hc_face_t ** face_found)
-{
- hc_listener_t listener;
- hc_listener_t * listener_found;
-
- hc_connection_t connection;
- hc_connection_t * connection_found;
-
- char face_s[MAXSZ_HC_FACE];
- int rc = hc_face_snprintf(face_s, MAXSZ_HC_FACE, face);
- if (rc >= MAXSZ_HC_FACE)
- WARN("[hc_face_get] Unexpected truncation of face string");
- DEBUG("[hc_face_get] face=%s", face_s);
-
- switch(face->face.type)
- {
- case FACE_TYPE_HICN:
- case FACE_TYPE_TCP:
- case FACE_TYPE_UDP:
- if (hc_face_to_connection(face, &connection, false) < 0)
- return -1;
- if (_hc_connection_get(socket, &connection, &connection_found) < 0)
- return -1;
- if (!connection_found) {
- *face_found = NULL;
- return 0;
- }
- *face_found = malloc(sizeof(hc_face_t));
- hc_connection_to_face(connection_found, *face_found);
- free(connection_found);
- break;
-
- case FACE_TYPE_HICN_LISTENER:
- case FACE_TYPE_TCP_LISTENER:
- case FACE_TYPE_UDP_LISTENER:
- if (hc_face_to_listener(face, &listener) < 0)
- return -1;
- if (_hc_listener_get(socket, &listener, &listener_found) < 0)
- return -1;
- if (!listener_found) {
- *face_found = NULL;
- return 0;
- }
- *face_found = malloc(sizeof(hc_face_t));
- hc_listener_to_face(listener_found, *face_found);
- free(listener_found);
- break;
-
- default:
- return -1;
- }
-
- return 0;
-
-}
-
-/* FACE DELETE */
-
-static int
-_hc_face_delete(hc_sock_t * socket, hc_face_t * face)
-{
- char face_s[MAXSZ_HC_FACE];
- int rc = hc_face_snprintf(face_s, MAXSZ_HC_FACE, face);
- if (rc >= MAXSZ_HC_FACE)
- WARN("[hc_face_delete] Unexpected truncation of face string");
- DEBUG("[hc_face_delete] face=%s", face_s);
-
- hc_connection_t connection;
- if (hc_face_to_connection(face, &connection, false) < 0) {
- ERROR("[hc_face_delete] Could not convert face to connection.");
- return -1;
- }
-
- if (_hc_connection_delete(socket, &connection) < 0) {
- ERROR("[hc_face_delete] Error removing connection");
- return -1;
- }
-
- /* If this is the last connection attached to the listener, remove it */
-
- hc_data_t * connections;
- hc_listener_t listener = {{0}};
-
- /*
- * Ensure we have a corresponding local listener
- * NOTE: hc_face_to_listener is not appropriate
- */
- if (hc_connection_to_local_listener(&connection, &listener) < 0) {
- ERROR("[hc_face_create] Could not convert face to local listener.");
- return -1;
- }
-#if 1
- /*
- * The name is generated to prepare listener creation, we need it to be
- * empty for deletion. The id should not need to be reset though.
- */
- listener.id = 0;
- memset(listener.name, 0, sizeof(listener.name));
-#endif
- if (_hc_connection_list(socket, &connections) < 0) {
- ERROR("[hc_face_delete] Error getting the list of listeners");
- return -1;
- }
-
- bool delete = true;
- foreach_connection(c, connections) {
- if ((ip_address_cmp(&c->local_addr, &listener.local_addr, c->family) == 0) &&
- (c->local_port == listener.local_port) &&
- (strcmp(c->interface_name, listener.interface_name) == 0)) {
- delete = false;
- }
- }
-
- if (delete) {
- if (_hc_listener_delete(socket, &listener) < 0) {
- ERROR("[hc_face_delete] Error removing listener");
- return -1;
- }
- }
-
- hc_data_free(connections);
-
- return 0;
-
-
-}
-
-/* FACE LIST */
-
-static int
-_hc_face_list(hc_sock_t * socket, hc_data_t ** pdata)
-{
- hc_data_t * connection_data;
- hc_face_t face;
-
- //DEBUG("[hc_face_list]");
-
- if (_hc_connection_list(socket, &connection_data) < 0) {
- ERROR("[hc_face_list] Could not list connections.");
- return -1;
- }
-
- hc_data_t * face_data = hc_data_create(sizeof(hc_connection_t), sizeof(hc_face_t), NULL);
- foreach_connection(c, connection_data) {
- if (hc_connection_to_face(c, &face) < 0) {
- ERROR("[hc_face_list] Could not convert connection to face.");
- goto ERR;
- }
- hc_data_push(face_data, &face);
- }
-
- *pdata = face_data;
- hc_data_free(connection_data);
- return 0;
-
-ERR:
- hc_data_free(connection_data);
- return -1;
-}
-
-static int
-_hc_face_list_async(hc_sock_t * socket)
-{
- struct {
- header_control_message hdr;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = LIST_CONNECTIONS,
- .length = 0,
- .seqNum = 0,
- },
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_LIST,
- .cmd_id = LIST_CONNECTIONS,
- .size_in = sizeof(list_connections_command),
- .size_out = sizeof(hc_face_t),
- .parse = (HC_PARSE)hc_connection_parse_to_face,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, true);
-}
-
-static int
-_hc_face_set_admin_state(hc_sock_t * s, const char * conn_id_or_name,
- face_state_t admin_state)
-{
- return hc_connection_set_admin_state(s, conn_id_or_name, admin_state);
-}
-
-#ifdef WITH_POLICY
-static int
-_hc_face_set_priority(hc_sock_t * s, const char * conn_id_or_name,
- uint32_t priority)
-{
- return hc_connection_set_priority(s, conn_id_or_name, priority);
-}
-
-static int
-_hc_face_set_tags(hc_sock_t * s, const char * conn_id_or_name,
- policy_tags_t tags)
-{
- return hc_connection_set_tags(s, conn_id_or_name, tags);
-}
-#endif // WITH_POLICY
-
-/*----------------------------------------------------------------------------*
- * Punting
- *----------------------------------------------------------------------------*/
-
-static int
-_hc_punting_create_internal(hc_sock_t * socket, hc_punting_t * punting, bool async)
-{
- int rc;
-
- if (hc_punting_validate(punting) < 0)
- return -1;
-
- struct {
- header_control_message hdr;
- add_punting_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = ADD_PUNTING,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .address = punting->prefix,
- .addressType = (u8)map_to_addr_type[punting->family],
- .len = punting->prefix_len,
- }
- };
- rc = snprintf(msg.payload.symbolicOrConnid, SYMBOLIC_NAME_LEN, "%d", punting->face_id);
- if (rc >= SYMBOLIC_NAME_LEN)
- WARN("[_hc_punting_create] Unexpected truncation of symbolic name string");
-
- hc_command_params_t params = {
- .cmd = ACTION_CREATE,
- .cmd_id = ADD_PUNTING,
- .size_in = sizeof(add_punting_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_punting_create(hc_sock_t * s, hc_punting_t * punting)
-{
- return _hc_punting_create_internal(s, punting, false);
-}
-
-static int
-_hc_punting_create_async(hc_sock_t * s, hc_punting_t * punting)
-{
- return _hc_punting_create_internal(s, punting, true);
-}
-
-static int
-_hc_punting_get(hc_sock_t * s, hc_punting_t * punting, hc_punting_t ** punting_found)
-{
- ERROR("hc_punting_get not (yet) implemented.");
- return -1;
-}
-
-static int
-_hc_punting_delete(hc_sock_t * s, hc_punting_t * punting)
-{
- ERROR("hc_punting_delete not (yet) implemented.");
- return -1;
-}
-
-static int
-_hc_punting_list(hc_sock_t * s, hc_data_t ** pdata)
-{
- ERROR("hc_punting_list not (yet) implemented.");
- return -1;
-}
-
-
-/*----------------------------------------------------------------------------*
- * Cache
- *----------------------------------------------------------------------------*/
-
-static int
-_hc_cache_set_store_internal(hc_sock_t * socket, int enabled, bool async)
-{
- struct {
- header_control_message hdr;
- cache_store_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = CACHE_STORE,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .activate = enabled,
- }
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_SET,
- .cmd_id = CACHE_STORE,
- .size_in = sizeof(cache_store_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_cache_set_store(hc_sock_t * s, int enabled)
-{
- return _hc_cache_set_store_internal(s, enabled, false);
-}
-
-static int
-_hc_cache_set_store_async(hc_sock_t * s, int enabled)
-{
- return _hc_cache_set_store_internal(s, enabled, true);
-}
-
-static int
-_hc_cache_set_serve_internal(hc_sock_t * socket, int enabled, bool async)
-{
- struct {
- header_control_message hdr;
- cache_serve_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = CACHE_SERVE,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .activate = enabled,
- }
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_SET,
- .cmd_id = CACHE_SERVE,
- .size_in = sizeof(cache_serve_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_cache_set_serve(hc_sock_t * s, int enabled)
-{
- return _hc_cache_set_serve_internal(s, enabled, false);
-}
-
-static int
-_hc_cache_set_serve_async(hc_sock_t * s, int enabled)
-{
- return _hc_cache_set_serve_internal(s, enabled, true);
-}
-
-/*----------------------------------------------------------------------------*
- * Strategy
- *----------------------------------------------------------------------------*/
-
-// per prefix
-static int
-_hc_strategy_set(hc_sock_t * s /* XXX */)
-{
- return 0;
-}
-
-/* How to retrieve that from the forwarder ? */
-static const char * strategies[] = {
- "random",
- "load_balancer",
-};
-
-#define ARRAY_SIZE(array) (sizeof(array) / sizeof(*array))
-
-static int
-_hc_strategy_list(hc_sock_t * s, hc_data_t ** data)
-{
- int rc;
-
- *data = hc_data_create(0, sizeof(hc_strategy_t), NULL);
-
- for (unsigned i = 0; i < ARRAY_SIZE(strategies); i++) {
- hc_strategy_t * strategy = (hc_strategy_t*)hc_data_get_next(*data);
- if (!strategy)
- return -1;
- rc = snprintf(strategy->name, MAXSZ_HC_STRATEGY, "%s", strategies[i]);
- if (rc >= MAXSZ_HC_STRATEGY)
- WARN("[hc_strategy_list] Unexpected truncation of strategy name string");
- (*data)->size++;
- }
-
- return 0;
-}
-
-/*----------------------------------------------------------------------------*
- * WLDR
- *----------------------------------------------------------------------------*/
-
-// per connection
-static int
-_hc_wldr_set(hc_sock_t * s /* XXX */)
-{
- return 0;
-}
-
-/*----------------------------------------------------------------------------*
- * MAP-Me
- *----------------------------------------------------------------------------*/
-
-static int
-_hc_mapme_set(hc_sock_t * s, int enabled)
-{
- return 0;
-}
-
-static int
-_hc_mapme_set_discovery(hc_sock_t * s, int enabled)
-{
- return 0;
-}
-
-static int
-_hc_mapme_set_timescale(hc_sock_t * s, double timescale)
-{
- return 0;
-}
-
-static int
-_hc_mapme_set_retx(hc_sock_t * s, double timescale)
-{
- return 0;
-}
-
-/*----------------------------------------------------------------------------*
- * Policy
- *----------------------------------------------------------------------------*/
-
-#ifdef WITH_POLICY
-
-/* POLICY CREATE */
-
-static int
-_hc_policy_create_internal(hc_sock_t * socket, hc_policy_t * policy, bool async)
-{
- if (!IS_VALID_FAMILY(policy->family))
- return -1;
-
- struct {
- header_control_message hdr;
- add_policy_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = ADD_POLICY,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .address = policy->remote_addr,
- .addressType = (u8)map_to_addr_type[policy->family],
- .len = policy->len,
- .policy = policy->policy,
- }
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_CREATE,
- .cmd_id = ADD_POLICY,
- .size_in = sizeof(add_policy_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_policy_create(hc_sock_t * s, hc_policy_t * policy)
-{
- return _hc_policy_create_internal(s, policy, false);
-}
-
-static int
-_hc_policy_create_async(hc_sock_t * s, hc_policy_t * policy)
-{
- return _hc_policy_create_internal(s, policy, true);
-}
-
-/* POLICY DELETE */
-
-static int
-_hc_policy_delete_internal(hc_sock_t * socket, hc_policy_t * policy, bool async)
-{
- if (!IS_VALID_FAMILY(policy->family))
- return -1;
-
- struct {
- header_control_message hdr;
- remove_policy_command payload;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = REMOVE_POLICY,
- .length = 1,
- .seqNum = 0,
- },
- .payload = {
- .address = policy->remote_addr,
- .addressType = (u8)map_to_addr_type[policy->family],
- .len = policy->len,
- }
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_DELETE,
- .cmd_id = REMOVE_POLICY,
- .size_in = sizeof(remove_policy_command),
- .size_out = 0,
- .parse = NULL,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, NULL, async);
-}
-
-static int
-_hc_policy_delete(hc_sock_t * s, hc_policy_t * policy)
-{
- return _hc_policy_delete_internal(s, policy, false);
-}
-
-static int
-_hc_policy_delete_async(hc_sock_t * s, hc_policy_t * policy)
-{
- return _hc_policy_delete_internal(s, policy, true);
-}
-
-/* POLICY LIST */
-
-static int
-_hc_policy_list_internal(hc_sock_t * socket, hc_data_t ** pdata, bool async)
-{
- struct {
- header_control_message hdr;
- } msg = {
- .hdr = {
- .messageType = REQUEST_LIGHT,
- .commandID = LIST_POLICIES,
- .length = 0,
- .seqNum = 0,
- },
- };
-
- hc_command_params_t params = {
- .cmd = ACTION_LIST,
- .cmd_id = LIST_POLICIES,
- .size_in = sizeof(list_policies_command),
- .size_out = sizeof(hc_policy_t),
- .parse = (HC_PARSE)hc_policy_parse,
- };
-
- return _hc_execute_command(socket, (hc_msg_t*)&msg, sizeof(msg), &params, pdata, async);
-}
-
-static int
-_hc_policy_list(hc_sock_t * s, hc_data_t ** pdata)
-{
- return _hc_policy_list_internal(s, pdata, false);
-}
-
-static int
-_hc_policy_list_async(hc_sock_t * s, hc_data_t ** pdata)
-{
- return _hc_policy_list_internal(s, pdata, true);
-}
-
-#endif /* WITH_POLICY */
-
-static hc_sock_t hc_sock_light_interface = (hc_sock_t) {
- .hc_sock_get_next_seq = _hc_sock_light_get_next_seq,
- .hc_sock_set_nonblocking = _hc_sock_light_set_nonblocking,
- .hc_sock_get_fd = _hc_sock_light_get_fd,
- .hc_sock_connect = _hc_sock_light_connect,
- .hc_sock_get_available = _hc_sock_light_get_available,
- .hc_sock_send = _hc_sock_light_send,
- .hc_sock_recv = _hc_sock_light_recv,
- .hc_sock_process = _hc_sock_light_process,
- .hc_sock_callback = _hc_sock_light_callback,
- .hc_sock_reset = _hc_sock_light_reset,
- .hc_sock_free = _hc_sock_light_free,
- .hc_listener_create = _hc_listener_create,
- .hc_listener_create_async = _hc_listener_create_async,
- .hc_listener_get = _hc_listener_get,
- .hc_listener_delete = _hc_listener_delete,
- .hc_listener_delete_async = _hc_listener_delete_async,
- .hc_listener_list = _hc_listener_list,
- .hc_listener_list_async = _hc_listener_list_async,
- .hc_connection_create = _hc_connection_create,
- .hc_connection_create_async = _hc_connection_create_async,
- .hc_connection_get = _hc_connection_get,
- .hc_connection_update_by_id = _hc_connection_update_by_id,
- .hc_connection_update = _hc_connection_update,
- .hc_connection_delete = _hc_connection_delete,
- .hc_connection_delete_async = _hc_connection_delete_async,
- .hc_connection_list = _hc_connection_list,
- .hc_connection_list_async = _hc_connection_list_async,
- .hc_connection_set_admin_state = _hc_connection_set_admin_state,
- .hc_connection_set_admin_state_async = _hc_connection_set_admin_state_async,
-
-#ifdef WITH_POLICY
- .hc_connection_set_priority = _hc_connection_set_priority,
- .hc_connection_set_priority_async = _hc_connection_set_priority_async,
- .hc_connection_set_tags = _hc_connection_set_tags,
- .hc_connection_set_tags_async = _hc_connection_set_tags_async,
-#endif // WITH_POLICY
-
- .hc_face_create = _hc_face_create,
- .hc_face_get = _hc_face_get,
- .hc_face_delete = _hc_face_delete,
- .hc_face_list = _hc_face_list,
- .hc_face_list_async = _hc_face_list_async,
- .hc_face_set_admin_state = _hc_face_set_admin_state,
-
-#ifdef WITH_POLICY
- .hc_face_set_priority = _hc_face_set_priority,
- .hc_face_set_tags = _hc_face_set_tags,
-#endif // WITH_POLICY
-
- .hc_route_create = _hc_route_create,
- .hc_route_create_async = _hc_route_create_async,
- .hc_route_delete = _hc_route_delete,
- .hc_route_delete_async = _hc_route_delete_async,
- .hc_route_list = _hc_route_list,
- .hc_route_list_async = _hc_route_list_async,
-
- .hc_punting_create = _hc_punting_create,
- .hc_punting_create_async = _hc_punting_create_async,
- .hc_punting_get = _hc_punting_get,
- .hc_punting_delete = _hc_punting_delete,
- .hc_punting_list = _hc_punting_list,
-
- .hc_cache_set_store = _hc_cache_set_store,
- .hc_cache_set_store_async = _hc_cache_set_store_async,
- .hc_cache_set_serve = _hc_cache_set_serve,
- .hc_cache_set_serve_async = _hc_cache_set_serve_async,
-
- .hc_strategy_list = _hc_strategy_list,
- .hc_strategy_set = _hc_strategy_set,
- .hc_wldr_set = _hc_wldr_set,
-
- .hc_mapme_set = _hc_mapme_set,
- .hc_mapme_set_discovery = _hc_mapme_set_discovery,
- .hc_mapme_set_timescale = _hc_mapme_set_timescale,
- .hc_mapme_set_retx = _hc_mapme_set_retx,
-
-#ifdef WITH_POLICY
- .hc_policy_create = _hc_policy_create,
- .hc_policy_create_async = _hc_policy_create_async,
- .hc_policy_delete = _hc_policy_delete,
- .hc_policy_delete_async = _hc_policy_delete_async,
- .hc_policy_list = _hc_policy_list,
- .hc_policy_list_async = _hc_policy_list_async
-#endif // WITH_POLICY
-};
-
-// Public contructors
-
-hc_sock_t *
-_hc_sock_create_url(const char * url)
-{
- hc_sock_light_t * s = malloc(sizeof(hc_sock_light_t));
- if (!s)
- goto ERR_MALLOC;
-
- s->vft = hc_sock_light_interface;
- s->url = url ? strdup(url) : NULL;
-
- s->fd = socket(AF_INET, SOCK_STREAM, 0);
- if (s->fd < 0)
- goto ERR_SOCKET;
-
- if (_hc_sock_light_reset((hc_sock_t*)s) < 0)
- goto ERR_RESET;
-
- s->seq = 0;
- s->cur_request = NULL;
-
- s->map = hc_sock_map_create();
- if (!s->map)
- goto ERR_MAP;
-
- return (hc_sock_t*)(s);
-
- //hc_sock_light_map_free(s->map);
-ERR_MAP:
-ERR_RESET:
- if (s->url)
- free(s->url);
- close(s->fd);
-ERR_SOCKET:
- free(s);
-ERR_MALLOC:
- return NULL;
-}
-
-hc_sock_t *
-_hc_sock_create(void)
-{
- return _hc_sock_create_url(NULL);
-}
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin.c b/ctrl/libhicnctrl/src/modules/hicn_plugin.c
new file mode 100644
index 000000000..b8606daf7
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin.c
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file api.c
+ * \brief Implementation of hICN control library API
+ */
+
+#include <assert.h> // assert
+#include <fcntl.h> // fcntl
+#include <math.h> // log2
+#include <stdbool.h>
+#include <stdio.h> // snprintf
+#include <string.h> // memmove, strcasecmp
+#include <sys/socket.h> // socket
+#include <unistd.h> // close, fcntl
+
+#include <hicn/ctrl/data.h>
+#include <hicn/ctrl/socket.h>
+
+#include <vapi/vapi_safe.h>
+#include <vppinfra/clib.h>
+#include <vpp_plugins/hicn/error.h>
+
+#include "../socket_private.h"
+
+#include "hicn_plugin/base.h" // hc_sock_vpp_data_t
+#include "hicn_plugin/listener.h"
+#include "hicn_plugin/route.h"
+#include "hicn_plugin/strategy.h"
+
+/******************************************************************************
+ * Message helper types and aliases
+ ******************************************************************************/
+
+#if 0
+
+#define foreach_hc_command \
+ _(hicn_api_node_params_set) \
+ _(hicn_api_node_params_set_reply) \
+ _(hicn_api_node_params_get_reply) \
+ _(hicn_api_node_stats_get_reply) \
+ _(hicn_api_face_get) \
+ _(hicn_api_faces_details) \
+ _(hicn_api_face_stats_details) \
+ _(hicn_api_face_get_reply) \
+ _(hicn_api_route_get) \
+ _(hicn_api_route_get_reply) \
+ _(hicn_api_routes_details) \
+ _(hicn_api_strategies_get_reply) \
+ _(hicn_api_strategy_get) \
+ _(hicn_api_strategy_get_reply)
+
+
+typedef vapi_type_msg_header2_t hc_msg_header_t;
+
+typedef union {
+#define _(a) vapi_payload_##a a;
+ foreach_hc_command
+#undef _
+} hc_msg_payload_t;
+
+typedef struct __attribute__((__packed__)) {
+ hc_msg_header_t hdr;
+ hc_msg_payload_t payload;
+} hc_hicnp_t;
+
+typedef void (*NTOH)(void *msg);
+
+typedef struct __attribute__((__packed__)) {
+ hc_data_t *data;
+ uint32_t curr_msg;
+} callback_ctx_t;
+
+typedef struct __attribute__((__packed__)) {
+ hc_hicnp_t *msg;
+ vapi_cb_t callback;
+ callback_ctx_t *callback_ctx;
+ NTOH ntoh;
+} hc_msg_s;
+
+/******************************************************************************
+ * Control socket
+ ******************************************************************************/
+
+static void vpp_free(hc_sock_t *socket) {
+ hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
+ if (s->url) free(s->url);
+ free(s);
+
+ vapi_disconnect_safe();
+}
+
+static int vpp_get_next_seq(hc_sock_t *socket) {
+ hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
+ return vapi_gen_req_context(s->g_vapi_ctx_instance);
+}
+
+static int vpp_set_nonblocking(hc_sock_t *socket) {
+ hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
+ return 0;
+}
+
+static int vpp_callback(hc_sock_t *socket, hc_data_t **pdata) {
+ // NOT IMPLEMENTED
+ return -1;
+}
+
+static int vpp_reset(hc_sock_t *socket) {
+ // NOT IMPLEMENTED
+ return -1;
+}
+#endif
+
+/*----------------------------------------------------------------------------*
+ * Listeners
+ *----------------------------------------------------------------------------*/
+
+/******************************************************************************
+ * Module functions
+ ******************************************************************************/
+
+hc_sock_vpp_data_t *hc_sock_vpp_data_create(const char *url) {
+ hc_sock_vpp_data_t *s = malloc(sizeof(hc_sock_vpp_data_t));
+ if (!s) goto ERR_MALLOC;
+
+ s->roff = s->woff = 0;
+ s->url = url ? strdup(url) : NULL;
+
+ return s;
+
+ERR_MALLOC:
+ return NULL;
+}
+
+void hc_sock_vpp_data_free(hc_sock_vpp_data_t *s) {
+ vapi_disconnect_safe();
+
+ if (s->url) free(s->url);
+ free(s);
+}
+
+static int vpp_connect(hc_sock_t *sock) {
+ hc_sock_vpp_data_t *s = (hc_sock_vpp_data_t *)sock->data;
+ vapi_error_e rv =
+ vapi_connect_safe(&s->g_vapi_ctx_instance, hc_sock_is_async(sock));
+ if (rv != VAPI_OK) goto ERR_CONNECT;
+
+ return 0;
+
+ERR_CONNECT:
+ ERROR("[hc_sock_connect] connection failed");
+ return -1;
+}
+
+static ssize_t vpp_prepare(hc_sock_t *sock, hc_request_t *request,
+ uint8_t **buffer) {
+ assert(!buffer);
+
+ // XXX all the beginning is generic and could be shared across multiple
+ // modules
+
+ /* Dispatch to subrequest if any */
+ hc_request_t *current_request = hc_request_get_current(request);
+
+ _ASSERT(!hc_request_get_data(current_request));
+
+ hc_action_t action = hc_request_get_action(current_request);
+ hc_object_type_t object_type = hc_request_get_object_type(current_request);
+ hc_object_t *object = hc_request_get_object(current_request);
+
+ _ASSERT(hc_request_get_data(current_request) == NULL);
+ hc_data_t *data = hc_data_create(object_type);
+ if (!data) {
+ ERROR("[vpp_prepare] Could not create data storage");
+ goto ERR;
+ }
+ hc_request_set_data(current_request, data);
+
+ hc_module_object_ops_t *vft = &sock->ops.object_vft[object_type];
+ if (!vft) goto ERR;
+ hc_execute_t execute = vft->execute[action];
+ if (!execute) goto ERR;
+ int rc = execute(sock, object, data);
+ if (rc < 0) goto ERR;
+
+ /* The result is fully contained in data */
+ (void)rc;
+
+ hc_request_set_complete(request);
+ return 0;
+
+ERR:
+ hc_data_set_error(data);
+ hc_request_set_complete(request);
+ return 0;
+}
+
+static hc_sock_ops_t hc_sock_vpp = (hc_sock_ops_t){
+ .create_data = (void *(*)(const char *))hc_sock_vpp_data_create,
+ .free_data = (void (*)(void *))hc_sock_vpp_data_free,
+ .get_fd = NULL, // not fd based
+ .get_recv_buffer = NULL, // no async support
+ .connect = vpp_connect,
+ .prepare = vpp_prepare,
+ .send = NULL,
+ .recv = NULL,
+ .process = NULL,
+};
+
+ssize_t vpp_command_serialize(hc_action_t action, hc_object_type_t object_type,
+ hc_object_t *object, uint8_t *msg) {
+ return hc_sock_vpp.object_vft[object_type].serialize[action](object, msg);
+}
+
+// Public constructor
+
+int hc_sock_initialize_module(hc_sock_t *s) {
+ s->ops = hc_sock_vpp;
+ // XXX shall we memset the VFT ?
+ /* LISTENER: CREATE, GET, DELETE not implemented, LIST ok */
+ s->ops.object_vft[OBJECT_TYPE_LISTENER] = vpp_listener_module_ops;
+ /* CONNECTION : CREATE, GET, UPDATE, DELETE, LIST, SET_* not
+ implemented */
+ s->ops.object_vft[OBJECT_TYPE_CONNECTION] = HC_MODULE_OBJECT_OPS_EMPTY;
+ s->ops.object_vft[OBJECT_TYPE_FACE] = HC_MODULE_OBJECT_OPS_EMPTY;
+ s->ops.object_vft[OBJECT_TYPE_PUNTING] = HC_MODULE_OBJECT_OPS_EMPTY;
+ s->ops.object_vft[OBJECT_TYPE_CACHE] = HC_MODULE_OBJECT_OPS_EMPTY;
+ s->ops.object_vft[OBJECT_TYPE_MAPME] = HC_MODULE_OBJECT_OPS_EMPTY;
+ s->ops.object_vft[OBJECT_TYPE_WLDR] = HC_MODULE_OBJECT_OPS_EMPTY;
+ s->ops.object_vft[OBJECT_TYPE_POLICY] = HC_MODULE_OBJECT_OPS_EMPTY;
+ s->ops.object_vft[OBJECT_TYPE_ROUTE] = vpp_route_module_ops;
+ s->ops.object_vft[OBJECT_TYPE_STRATEGY] = vpp_strategy_module_ops;
+ s->ops.object_vft[OBJECT_TYPE_SUBSCRIPTION] = HC_MODULE_OBJECT_OPS_EMPTY;
+ return 0;
+}
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin/base.h b/ctrl/libhicnctrl/src/modules/hicn_plugin/base.h
new file mode 100644
index 000000000..05565e938
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin/base.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file modules/hicn_plugin/base.h
+ * \brief Base structures for hICN plugin module
+ */
+
+#include <vapi/vapi_safe.h>
+#include "../../module.h"
+#include "../../socket_private.h"
+
+typedef struct {
+ vapi_ctx_t g_vapi_ctx_instance;
+ char *url;
+
+ size_t roff; /**< Read offset */
+ size_t woff; /**< Write offset */
+ u32 buffer[RECV_BUFLEN];
+ /* Next sequence number to be used for requests */
+ int seq;
+
+ bool async;
+} hc_sock_vpp_data_t;
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin/listener.c b/ctrl/libhicnctrl/src/modules/hicn_plugin/listener.c
new file mode 100644
index 000000000..4d9792256
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin/listener.c
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file modules/hicn_plugin/listener.c
+ * \brief Implementation of listener object VFT for hicn_plugin.
+ */
+
+#include <hicn/util/vector.h>
+
+#include "base.h"
+#include "listener.h"
+
+struct listener_data_s {
+ hc_listener_t listener;
+ hc_data_t *data;
+};
+
+/**
+ * This is a callback used to append in callback_ctx which is a hc_data_t
+ * designed to hold hc_listener_t, a list of listener, each corresponding to an
+ * IP address (v4 then v6) of the interfaces, and thus build a list of hICN
+ * listeners.
+ */
+static vapi_error_e process_ip_info(struct vapi_ctx_s *ctx, void *callback_ctx,
+ vapi_error_e rv, bool is_last,
+ vapi_payload_ip_address_details *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+ if (reply && is_last) printf("COUCOU\n");
+ if (is_last) return 0;
+
+ struct listener_data_s *ld = (struct listener_data_s *)callback_ctx;
+
+ if (reply->prefix.address.af == ADDRESS_IP4) {
+ memcpy(&(ld->listener.local_addr.v4), reply->prefix.address.un.ip4,
+ IPV4_ADDR_LEN);
+ ld->listener.family = AF_INET;
+ } else {
+ memcpy(&(ld->listener.local_addr.v6), reply->prefix.address.un.ip6,
+ IPV6_ADDR_LEN);
+ ld->listener.family = AF_INET6;
+ }
+ ld->listener.local_port = 0;
+
+ ld->listener.id = reply->sw_if_index;
+ hc_data_t *data = ld->data;
+ hc_listener_t *listener = &ld->listener;
+ hc_data_push(data, listener);
+
+ return rv;
+}
+
+/* LISTENER LIST */
+
+typedef struct {
+ u32 swif;
+ char interface_name[INTERFACE_LEN];
+} hc_vapi_interface_t;
+
+/*
+ * A pointer to hc_data_t is passed in the callback context
+ * Objective is to store a vector of hc_vapi_interface_t inside
+ */
+static vapi_error_e on_listener_list_complete_cb(
+ struct vapi_ctx_s *ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_sw_interface_details *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ if (is_last) return 0;
+
+ hc_vapi_interface_t **vpp_interfaces_vec =
+ (hc_vapi_interface_t **)callback_ctx;
+
+ hc_vapi_interface_t interface = {.swif = reply->sw_if_index};
+ // XXX bug
+ memcpy(interface.interface_name, reply->interface_name, INTERFACE_LEN);
+
+ vector_push(*vpp_interfaces_vec, interface);
+
+ return rv;
+}
+
+static int _vpp_listener_list(hc_sock_t *sock, hc_data_t *data) {
+ hc_sock_vpp_data_t *s = (hc_sock_vpp_data_t *)sock->data;
+
+ int retval = -1; // VAPI_OK;
+
+ hc_vapi_interface_t *vpp_interfaces_vec = NULL;
+ vector_init(vpp_interfaces_vec, 0, 0);
+
+ vapi_lock();
+
+ vapi_msg_sw_interface_dump *msg =
+ vapi_alloc_sw_interface_dump(s->g_vapi_ctx_instance);
+ if (!msg) {
+ retval = VAPI_ENOMEM;
+ goto ERR_MSG;
+ }
+ msg->payload.sw_if_index = ~0;
+ msg->payload.name_filter_valid = 0;
+
+ /* Retrieve the list of interfaces in vpp_interfaces_vec */
+ int ret =
+ vapi_sw_interface_dump(s->g_vapi_ctx_instance, msg,
+ on_listener_list_complete_cb, &vpp_interfaces_vec);
+
+ if (ret != VAPI_OK) goto ERR_LIST_INTERFACES;
+
+ /* Query the forwarder for each interface */
+ // stored in data->buffer == hc_vapi_interface_t* []
+ // 2 calls for each interface
+ //
+ // This function is called twice for each interface, to get resp. the v4 and
+ // v6 IP addresses associated to it:
+ // ip_address_dump(sw_if_index, is_ipv6)
+ //
+ // Function call :
+ // vapi_msg_XXX *msg = vapi_alloc_XXX(s->g_vapi_ctx_instance);
+ // msg->payload.ATTR = VALUE;
+ // [...]
+ // int ret = vapi_XXX((s->g_vapi_ctx_instance, msg, CALLBACK, USER_DATA);
+ //
+ // CALLBACK = process_ip_info
+ // USER_DATA = data2
+ //
+ // We can assume the callbacks are executed before the function returns, and
+ // that there is no async code.
+ //
+ int rc;
+
+ hc_vapi_interface_t *interface;
+ vapi_msg_ip_address_dump *msg2;
+
+ struct listener_data_s ld;
+ vector_foreach(vpp_interfaces_vec, interface, {
+ memset(&ld, 0, sizeof(struct listener_data_s));
+ ld.listener.type = FACE_TYPE_HICN;
+ rc = snprintf(ld.listener.interface_name, INTERFACE_LEN, "%s",
+ interface->interface_name);
+ if (rc < 0 || rc >= INTERFACE_LEN) goto ERR_FOREACH;
+
+ ld.data = data;
+
+ for (unsigned i = 0; i < 2; i++) {
+ msg2 = vapi_alloc_ip_address_dump(s->g_vapi_ctx_instance);
+ msg2->payload.sw_if_index = interface->swif;
+ msg2->payload.is_ipv6 = i;
+ retval = vapi_ip_address_dump(s->g_vapi_ctx_instance, msg2,
+ process_ip_info, &ld);
+ if (ret != VAPI_OK) goto ERR_GET_IP;
+ }
+ });
+ retval = 0;
+ERR_GET_IP:
+ERR_FOREACH:
+ vector_free(vpp_interfaces_vec);
+ERR_LIST_INTERFACES:
+ERR_MSG:
+ vapi_unlock();
+ return retval;
+}
+
+#define vpp_listener_create NULL
+#define vpp_listener_delete NULL
+
+static int vpp_listener_list(hc_sock_t *sock, hc_object_t *object,
+ hc_data_t *data) {
+ assert(!object || hc_object_is_empty(object));
+ return _vpp_listener_list(sock, data);
+}
+
+static int vpp_listener_set(hc_sock_t *sock, hc_object_t *object,
+ hc_data_t *data) {
+ return -1;
+}
+
+DECLARE_VPP_MODULE_OBJECT_OPS(vpp, listener);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin/listener.h b/ctrl/libhicnctrl/src/modules/hicn_plugin/listener.h
new file mode 100644
index 000000000..f75c58db6
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin/listener.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file modules/hicn_plugin/listener.h
+ * \brief listener object VFT for hicn_plugin.
+ */
+
+#ifndef HICNCTRL_MODULE_VPP_LISTENER_H
+#define HICNCTRL_MODULE_VPP_LISTENER_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(vpp, listener);
+
+#endif /* HICNCTRL_MODULE_VPP_LISTENER_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin/route.c b/ctrl/libhicnctrl/src/modules/hicn_plugin/route.c
new file mode 100644
index 000000000..4c9f8a638
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin/route.c
@@ -0,0 +1,552 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file modules/hicn_plugin/route.c
+ * \brief Implementation of route object VFT for hicn_plugin.
+ */
+
+#include "base.h"
+#include "route.h"
+
+static vapi_error_e create_udp_tunnel_cb(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_hicn_api_udp_tunnel_add_del_reply *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ if (reply->retval != VAPI_OK) return reply->retval;
+
+ u32 *uei = (u32 *)callback_ctx;
+ *uei = reply->uei;
+
+ return reply->retval;
+}
+
+static vapi_error_e parse_route_create(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_ip_route_add_del_reply *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ return reply->retval;
+}
+
+static vapi_error_e hicn_enable_cb(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_hicn_api_enable_disable_reply *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+ face_id_t *faceid = (face_id_t *)callback_ctx;
+
+ if (reply->nfaces) {
+ *faceid = reply->faceids[0];
+ }
+
+ return reply->retval;
+}
+
+static int _vpp_route_create(hc_sock_t *sock, hc_route_t *route) {
+ if (!IS_VALID_FAMILY(route->family)) return -1;
+
+ hc_sock_vpp_data_t *s = (hc_sock_vpp_data_t *)sock->data;
+ int ret = -1;
+ vapi_lock();
+
+ vapi_msg_ip_route_add_del *msg =
+ vapi_alloc_ip_route_add_del(s->g_vapi_ctx_instance, 1);
+
+ msg->payload.is_add = 1;
+ if (route->family == AF_INET) {
+ memcpy(&msg->payload.route.prefix.address.un.ip4[0], &route->remote_addr.v4,
+ 4);
+ msg->payload.route.prefix.address.af = ADDRESS_IP4;
+ msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP4;
+ } else {
+ memcpy(&msg->payload.route.prefix.address.un.ip6[0], &route->remote_addr.v6,
+ 16);
+ msg->payload.route.prefix.address.af = ADDRESS_IP6;
+ msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP6;
+ }
+
+ msg->payload.route.prefix.len = route->len;
+
+ msg->payload.route.paths[0].sw_if_index = ~0;
+ msg->payload.route.paths[0].table_id = 0;
+
+ hc_face_t *face = &(route->face);
+
+ face->netdevice.index = ~0;
+ face->id = INVALID_FACE_ID;
+
+ switch (face->type) {
+ case FACE_TYPE_HICN: {
+ if (hicn_ip_address_is_v4(&(face->remote_addr))) {
+ memcpy(&(msg->payload.route.paths[0].nh.address.ip4),
+ &face->remote_addr.v4, sizeof(ip4_address_t));
+ msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP4;
+ } else {
+ memcpy(&(msg->payload.route.paths[0].nh.address.ip6),
+ &face->remote_addr.v6, sizeof(ip6_address_t));
+ msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP6;
+ }
+
+ msg->payload.route.paths[0].type = FIB_API_PATH_TYPE_NORMAL;
+ msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
+
+ break;
+ }
+ case FACE_TYPE_UDP: {
+ vapi_msg_hicn_api_udp_tunnel_add_del *msg2 = NULL;
+ u32 uei = ~0;
+
+ if (hicn_ip_address_is_v4(&(face->remote_addr)) &&
+ hicn_ip_address_is_v4(&(face->local_addr))) {
+ msg2 = vapi_alloc_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance);
+ if (msg2 == NULL) {
+ ret = -1;
+ goto done;
+ }
+ memcpy(msg2->payload.src_addr.un.ip4, &face->local_addr.v4,
+ sizeof(ip4_address_t));
+ msg2->payload.src_addr.af = ADDRESS_IP4;
+
+ memcpy(msg2->payload.dst_addr.un.ip4, &face->remote_addr.v4,
+ sizeof(ip4_address_t));
+ msg2->payload.dst_addr.af = ADDRESS_IP4;
+
+ } else if (!hicn_ip_address_is_v4(&(route->face.remote_addr)) &&
+ !hicn_ip_address_is_v4(&(route->face.local_addr))) {
+ msg2 = vapi_alloc_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance);
+ if (msg2 == NULL) {
+ ret = -1;
+ goto done;
+ }
+ memcpy(msg2->payload.src_addr.un.ip6, &face->local_addr.v6,
+ sizeof(ip6_address_t));
+ msg2->payload.src_addr.af = ADDRESS_IP6;
+
+ memcpy(msg2->payload.dst_addr.un.ip6, &face->remote_addr.v6,
+ sizeof(ip6_address_t));
+ msg2->payload.dst_addr.af = ADDRESS_IP6;
+ } else {
+ // NOT IMPLEMENTED
+ ret = -1;
+ goto done;
+ }
+
+ msg2->payload.src_port = face->local_port;
+ msg2->payload.dst_port = face->remote_port;
+ msg2->payload.is_add = 1;
+
+ int ret = vapi_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance, msg2,
+ create_udp_tunnel_cb, &uei);
+
+ if (ret) {
+ ERROR("Error in vapi_hicn_api_udp_tunnel_add_del");
+ vapi_msg_free(s->g_vapi_ctx_instance, msg);
+ goto done;
+ }
+
+ msg->payload.route.paths[0].type = FIB_API_PATH_TYPE_UDP_ENCAP;
+ msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
+ msg->payload.route.paths[0].nh.obj_id = uei;
+
+ face->netdevice.index = uei;
+
+ break;
+ }
+ default:
+ ret = -1;
+ goto done;
+ }
+
+ ret = vapi_ip_route_add_del(s->g_vapi_ctx_instance, msg, parse_route_create,
+ NULL);
+
+ if (ret) {
+ ERROR("Error in vapi_ip_route_add_del");
+ goto done;
+ }
+
+ vapi_msg_hicn_api_enable_disable *msg3 =
+ vapi_alloc_hicn_api_enable_disable(s->g_vapi_ctx_instance);
+
+ if (route->family == AF_INET) {
+ memcpy(&msg3->payload.prefix.address.un.ip4[0], &route->remote_addr.v4, 4);
+ msg3->payload.prefix.address.af = ADDRESS_IP4;
+ } else {
+ memcpy(&msg3->payload.prefix.address.un.ip6[0], &route->remote_addr.v6, 16);
+ msg3->payload.prefix.address.af = ADDRESS_IP6;
+ }
+
+ msg3->payload.prefix.len = route->len;
+ msg3->payload.enable_disable = 1;
+
+ ret = vapi_hicn_api_enable_disable(s->g_vapi_ctx_instance, msg3,
+ hicn_enable_cb, &face->id);
+
+ if (ret) {
+ ERROR("Error in vapi_hicn_api_enable_disable");
+ }
+
+done:
+ vapi_unlock();
+ return ret;
+}
+
+static vapi_error_e hicn_disable_cb(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_hicn_api_enable_disable_reply *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ return reply->retval;
+}
+
+static vapi_error_e parse_route_delete(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_ip_route_add_del_reply *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ return reply->retval;
+}
+
+static int _vpp_route_delete(hc_sock_t *sock, hc_route_t *route) {
+ if (!IS_VALID_FAMILY(route->family)) return -1;
+
+ hc_sock_vpp_data_t *s = (hc_sock_vpp_data_t *)sock->data;
+
+ vapi_lock();
+
+ vapi_msg_hicn_api_enable_disable *msg =
+ vapi_alloc_hicn_api_enable_disable(s->g_vapi_ctx_instance);
+
+ if (route->family == AF_INET) {
+ memcpy(&msg->payload.prefix.address.un.ip4[0], &route->remote_addr.v4, 4);
+ msg->payload.prefix.address.af = ADDRESS_IP4;
+ } else {
+ memcpy(&msg->payload.prefix.address.un.ip6[0], &route->remote_addr.v6, 16);
+ msg->payload.prefix.address.af = ADDRESS_IP6;
+ }
+
+ msg->payload.prefix.len = route->len;
+ msg->payload.enable_disable = 0;
+
+ vapi_error_e ret = vapi_hicn_api_enable_disable(s->g_vapi_ctx_instance, msg,
+ hicn_disable_cb, NULL);
+
+ if (ret) {
+ ERROR("Error in vapi_hicn_api_enable_disable in route delete");
+ goto done;
+ }
+
+ vapi_msg_ip_route_add_del *msg2 =
+ vapi_alloc_ip_route_add_del(s->g_vapi_ctx_instance, 1);
+
+ msg2->payload.is_add = 0;
+ if (route->family == AF_INET) {
+ memcpy(&msg2->payload.route.prefix.address.un.ip4[0],
+ &route->remote_addr.v4, 4);
+ msg2->payload.route.prefix.address.af = ADDRESS_IP4;
+ } else {
+ memcpy(&msg2->payload.route.prefix.address.un.ip6[0],
+ &route->remote_addr.v6, 16);
+ msg2->payload.route.prefix.address.af = ADDRESS_IP6;
+ }
+
+ msg2->payload.route.prefix.len = route->len;
+
+ msg2->payload.route.paths[0].sw_if_index = ~0;
+ msg2->payload.route.paths[0].table_id = 0;
+
+ hc_face_t *face = &(route->face);
+ switch (face->type) {
+ case FACE_TYPE_HICN: {
+ if (hicn_ip_address_is_v4(&(face->remote_addr))) {
+ memcpy(&(msg2->payload.route.paths[0].nh.address.ip4),
+ &face->remote_addr.v4, sizeof(ip4_address_t));
+ msg2->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP4;
+ } else {
+ memcpy(&(msg2->payload.route.paths[0].nh.address.ip6),
+ &face->remote_addr.v6, sizeof(ip6_address_t));
+ msg2->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP6;
+ }
+
+ msg2->payload.route.paths[0].type = FIB_API_PATH_TYPE_NORMAL;
+ msg2->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
+
+ break;
+ }
+ case FACE_TYPE_UDP: {
+ msg2->payload.route.paths[0].type = FIB_API_PATH_TYPE_UDP_ENCAP;
+ msg2->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
+ msg2->payload.route.paths[0].nh.obj_id = face->netdevice.index;
+ break;
+ }
+ default:
+ return -1;
+ }
+
+ ret = vapi_ip_route_add_del(s->g_vapi_ctx_instance, msg2, parse_route_delete,
+ NULL);
+
+ if (ret) {
+ ERROR("Error in vapi_ip_route_add_del in route delete");
+ goto done;
+ }
+
+done:
+
+ vapi_unlock();
+ return ret;
+}
+
+/* ROUTE LIST */
+
+static vapi_error_e parse_udp_encap_list(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_udp_encap_details *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ hc_face_t *face = (hc_face_t *)callback_ctx;
+
+ if (face->netdevice.index == reply->udp_encap.id) {
+ switch (reply->udp_encap.src_ip.af) {
+ case ADDRESS_IP4: {
+ memcpy(&face->local_addr.v4, &(reply->udp_encap.src_ip.un.ip4),
+ sizeof(ip4_address_t));
+ memcpy(&face->remote_addr.v4, &(reply->udp_encap.dst_ip.un.ip4),
+ sizeof(ip4_address_t));
+ break;
+ }
+ case ADDRESS_IP6: {
+ memcpy(&face->local_addr.v6, &(reply->udp_encap.src_ip.un.ip6),
+ sizeof(ip6_address_t));
+ memcpy(&face->remote_addr.v6, &(reply->udp_encap.dst_ip.un.ip6),
+ sizeof(ip6_address_t));
+ break;
+ }
+ default:
+ break;
+ }
+
+ face->local_port = reply->udp_encap.src_port;
+ face->remote_port = reply->udp_encap.dst_port;
+ }
+ return rv;
+}
+
+static int _fill_face_with_info(hc_face_t *face, vapi_type_fib_path *path) {
+ switch (path->type) {
+ case FIB_API_PATH_FLAG_NONE: {
+ face->type = FACE_TYPE_HICN;
+ switch (path->proto) {
+ case FIB_API_PATH_NH_PROTO_IP4:
+ memcpy(&face->remote_addr.v4, &(path->nh.address.ip4),
+ sizeof(ipv4_address_t));
+ break;
+ case FIB_API_PATH_NH_PROTO_IP6:
+ memcpy(&face->remote_addr.v6, &(path->nh.address.ip6),
+ sizeof(ipv6_address_t));
+ break;
+ default:
+ break;
+ }
+ face->netdevice.index = path->sw_if_index;
+ } break;
+ case FIB_API_PATH_TYPE_UDP_ENCAP: {
+ face->type = FACE_TYPE_UDP;
+ face->netdevice.index = clib_net_to_host_u32(path->nh.obj_id);
+ // Let's make the compiler happy
+ (void)parse_udp_encap_list;
+ // vapi_msg_udp_encap_dump *msg;
+ // msg = vapi_alloc_udp_encap_dump(s->g_vapi_ctx_instance);
+ // vapi_udp_encap_dump(s->g_vapi_ctx_instance, msg, parse_udp_encap_list,
+ // face);
+ } break;
+ default:
+ return -1;
+ }
+ return 0;
+}
+
+static vapi_error_e parse_route_list(vapi_ctx_t ctx, void *callback_ctx,
+ vapi_error_e rv, bool is_last,
+ vapi_payload_ip_route_details *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ // XXX DEBUG XXX
+ if (reply && is_last) printf("COUCOU\n");
+
+ if (is_last) return 0;
+
+ hc_data_t *data = (hc_data_t *)callback_ctx;
+
+ /*
+ * Implementation:
+ * A route has n paths... we iterate for each path and search for a
+ * corresponding face in the hc_data_t result struct... and we fill the face
+ * info with the route path.
+ *
+ * TODO
+ * - comment on paths
+ * - explain the jump to END, this was previously implemented with a
+ * boolean flags skipping all remaining tests in the function...
+ */
+ for (int j = 0; j < reply->route.n_paths; j++) {
+ hc_data_foreach(data, obj, {
+ hc_route_t *route = &obj->route;
+
+ if (hicn_ip_address_is_v4(&(route->remote_addr)) &&
+ memcmp(route->remote_addr.v4.as_u8,
+ reply->route.prefix.address.un.ip4,
+ sizeof(ipv4_address_t)) == 0 &&
+ route->len == reply->route.prefix.len && route->face_id == ~0) {
+ _fill_face_with_info(&(route->face), &reply->route.paths[j]);
+ goto END;
+
+ } else if (memcmp(route->remote_addr.v6.as_u8,
+ reply->route.prefix.address.un.ip6,
+ sizeof(ipv6_address_t)) == 0 &&
+ route->len == reply->route.prefix.len &&
+ route->face_id == ~0) {
+ _fill_face_with_info(&(route->face), &reply->route.paths[j]);
+ goto END;
+ }
+ });
+ }
+
+END:
+ return rv;
+}
+
+/**
+ * Populates the hc_data_t structure passed as the context with...
+ */
+static vapi_error_e parse_hicn_route_list(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_hicn_api_routes_details *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+
+ if (reply && is_last) printf("COUCOU\n");
+ if (is_last) return 0;
+
+ hc_data_t *data = (hc_data_t *)callback_ctx;
+
+ for (int i = 0; i < reply->nfaces; i++) {
+ hc_route_t route;
+ memset(&route, 0, sizeof(hc_route_t));
+
+ /*
+ * We set the face_id to ~0 to act as a marker in parse_route_list that
+ * the route is missing face information.
+ */
+ route.face_id = ~0;
+ route.cost = 1;
+ route.len = reply->prefix.len;
+ if (reply->prefix.address.af == ADDRESS_IP6) {
+ memcpy(route.remote_addr.v6.as_u8, reply->prefix.address.un.ip6, 16);
+ route.family = AF_INET6;
+ } else {
+ memcpy(route.remote_addr.v4.as_u8, reply->prefix.address.un.ip4, 4);
+ route.family = AF_INET;
+ }
+
+ hc_data_push(data, &route);
+ }
+
+ return rv;
+}
+
+/*
+ * hicn_api_routes_dump
+ * ip_route_dump
+ *
+ * @returns hc_data_t<hc_route_t>
+ */
+static int _vpp_route_list(hc_sock_t *sock, hc_data_t *data) {
+ int ret;
+ hc_sock_vpp_data_t *s = (hc_sock_vpp_data_t *)sock->data;
+
+ vapi_lock();
+
+ /* Start by retrieving hicn routes (we have no face information at this
+ * stage)... */
+ vapi_msg_hicn_api_routes_dump *msg;
+ msg = vapi_alloc_hicn_api_routes_dump(s->g_vapi_ctx_instance);
+ if (!msg) goto ERR_MSG;
+
+ ret = vapi_hicn_api_routes_dump(s->g_vapi_ctx_instance, msg,
+ parse_hicn_route_list, data);
+ if (ret != VAPI_OK) goto ERR_API;
+
+ /*
+ * ... an complement them using IP (v4 and v6 routes). Similar routes will
+ * be aggregated, based on IP prefix, in parse_*_route_list.
+ */
+ vapi_msg_ip_route_dump *msg2;
+ for (unsigned i = 0; i < 2; i++) {
+ msg2 = vapi_alloc_ip_route_dump(s->g_vapi_ctx_instance);
+ if (!msg2) goto ERR_MSG;
+
+ msg2->payload.table.table_id = 0;
+ msg2->payload.table.is_ip6 = i;
+
+ ret = vapi_ip_route_dump(s->g_vapi_ctx_instance, msg2, parse_route_list,
+ data);
+ if (ret != VAPI_OK) goto ERR_API;
+ }
+
+ goto END;
+
+ERR_MSG:
+ ret = VAPI_ENOMEM;
+ goto END;
+
+ERR_API:
+END:
+ vapi_unlock();
+ return ret;
+}
+
+static int vpp_route_create(hc_sock_t *sock, hc_object_t *object,
+ hc_data_t *data) {
+ int rc = _vpp_route_create(sock, &object->route);
+ if (rc < 0)
+ hc_data_set_complete(data);
+ else
+ hc_data_set_error(data);
+ return rc;
+}
+
+static int vpp_route_delete(hc_sock_t *sock, hc_object_t *object,
+ hc_data_t *data) {
+ int rc = _vpp_route_delete(sock, &object->route);
+ if (rc < 0)
+ hc_data_set_complete(data);
+ else
+ hc_data_set_error(data);
+ return rc;
+}
+
+static int vpp_route_list(hc_sock_t *sock, hc_object_t *object,
+ hc_data_t *data) {
+ assert(!object || hc_object_is_empty(object));
+ return _vpp_route_list(sock, data);
+}
+
+static int vpp_route_set(hc_sock_t *sock, hc_object_t *object,
+ hc_data_t *data) {
+ return -1;
+}
+
+DECLARE_VPP_MODULE_OBJECT_OPS(vpp, route);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin/route.h b/ctrl/libhicnctrl/src/modules/hicn_plugin/route.h
new file mode 100644
index 000000000..652d3e89a
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin/route.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file modules/hicn_plugin/route.h
+ * \brief route object VFT for hicn_plugin.
+ */
+
+#ifndef HICNCTRL_MODULE_VPP_ROUTE_H
+#define HICNCTRL_MODULE_VPP_ROUTE_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(vpp, route);
+
+#endif /* HICNCTRL_MODULE_VPP_ROUTE_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.c b/ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.c
new file mode 100644
index 000000000..17d29a1d7
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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 "base.h"
+#include "strategy.h"
+
+#include <vpp_plugins/hicn/hicn_enums.h>
+
+static int _ip_prefix_encode(const hicn_ip_address_t *address,
+ int prefix_length, int family,
+ vapi_type_prefix *out) {
+ out->len = prefix_length;
+ int ret = 0;
+
+ switch (family) {
+ case AF_INET:
+ memcpy(&out->address.un.ip4[0], &address->v4, 4);
+ out->address.af = ADDRESS_IP4;
+ break;
+ case AF_INET6:
+ memcpy(&out->address.un.ip6[0], &address->v6, 16);
+ out->address.af = ADDRESS_IP6;
+ break;
+ default:
+ // This should never happen
+ ret = -1;
+ }
+
+ return ret;
+}
+
+static vapi_enum_hicn_strategy _vpp_strategy_libhicn_to_hicnplugin_strategy(
+ strategy_type_t strategy) {
+ switch (strategy) {
+ case STRATEGY_TYPE_LOADBALANCER:
+ return HICN_STRATEGY_RR;
+ case STRATEGY_TYPE_LOCAL_REMOTE:
+ return HICN_STRATEGY_LR;
+ case STRATEGY_TYPE_REPLICATION:
+ return HICN_STRATEGY_RP;
+ case STRATEGY_TYPE_BESTPATH:
+ return HICN_STRATEGY_MW;
+ default:
+ return HICN_STRATEGY_NULL;
+ }
+}
+
+static vapi_error_e _hicn_strategy_set_cb(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_hicn_api_strategy_set_reply *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
+ return reply->retval;
+}
+
+static int _vpp_strategy_set(hc_sock_vpp_data_t *s,
+ const hc_strategy_t *strategy) {
+ int ret = -1;
+
+ // Convert libhicn strategy enum to hicnplugin strategy enum and make sure it
+ // is valid
+ vapi_enum_hicn_strategy strategy_id =
+ _vpp_strategy_libhicn_to_hicnplugin_strategy(strategy->type);
+
+ if (strategy_id == HICN_STRATEGY_NULL) {
+ return -1;
+ }
+
+ // Construct API message
+ vapi_msg_hicn_api_strategy_set *msg =
+ vapi_alloc_hicn_api_strategy_set(s->g_vapi_ctx_instance);
+
+ // Fill it
+ msg->payload.strategy_id = strategy_id;
+ ret = _ip_prefix_encode(&strategy->address, strategy->len, strategy->family,
+ &msg->payload.prefix);
+
+ if (ret != 0) {
+ return -1;
+ }
+
+ vapi_lock();
+ ret = vapi_hicn_api_strategy_set(s->g_vapi_ctx_instance, msg,
+ _hicn_strategy_set_cb, NULL);
+ vapi_unlock();
+
+ return ret;
+}
+
+int vpp_strategy_create(hc_sock_t *sock, hc_object_t *object, hc_data_t *data) {
+ return -1;
+}
+
+int vpp_strategy_delete(hc_sock_t *sock, hc_object_t *object, hc_data_t *data) {
+ return -1;
+}
+
+int vpp_strategy_list(hc_sock_t *sock, hc_object_t *object, hc_data_t *data) {
+ return -1;
+}
+
+int vpp_strategy_set(hc_sock_t *sock, hc_object_t *object, hc_data_t *data) {
+ hc_sock_vpp_data_t *s = (hc_sock_vpp_data_t *)sock->data;
+ return _vpp_strategy_set(s, &object->strategy);
+}
+
+DECLARE_VPP_MODULE_OBJECT_OPS(vpp, strategy);
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.h b/ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.h
new file mode 100644
index 000000000..6dd6df6e4
--- /dev/null
+++ b/ctrl/libhicnctrl/src/modules/hicn_plugin/strategy.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file modules/hicn_plugin/route.h
+ * \brief route object VFT for hicn_plugin.
+ */
+
+#ifndef HICNCTRL_MODULE_VPP_STRATEGY_H
+#define HICNCTRL_MODULE_VPP_STRATEGY_H
+
+#include "../../module.h"
+
+DECLARE_MODULE_OBJECT_OPS_H(vpp, strategy);
+
+#endif /* HICNCTRL_MODULE_VPP_STRATEGY_H */
diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin_api.c b/ctrl/libhicnctrl/src/modules/hicn_plugin_api.c
deleted file mode 100644
index e59a2e41e..000000000
--- a/ctrl/libhicnctrl/src/modules/hicn_plugin_api.c
+++ /dev/null
@@ -1,1305 +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.
- */
-
-/**
- * \file api.c
- * \brief Implementation of hICN control library API
- */
-
-#include "api_private.h"
-
-#include <assert.h> // assert
-#include <fcntl.h> // fcntl
-#include <math.h> // log2
-#include <stdbool.h>
-#include <stdio.h> // snprintf
-#include <string.h> // memmove, strcasecmp
-#include <sys/socket.h> // socket
-#include <unistd.h> // close, fcntl
-#include <vapi/vapi_safe.h>
-#include <vapi/hicn.api.vapi.h>
-#include <vapi/ip.api.vapi.h>
-#include <vapi/udp.api.vapi.h>
-#include <vapi/interface.api.vapi.h>
-
-
-#if __GNUC__ >= 9
-#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
-#endif
-
-#include <vnet/ip/ip46_address.h>
-
-#if __GNUC__ >= 9
-#pragma GCC diagnostic pop
-#endif
-
-#define APP_NAME "hicn_plugin"
-#define MAX_OUTSTANDING_REQUESTS 4
-#define RESPONSE_QUEUE_SIZE 2
-
-DEFINE_VAPI_MSG_IDS_HICN_API_JSON
-DEFINE_VAPI_MSG_IDS_INTERFACE_API_JSON
-DEFINE_VAPI_MSG_IDS_IP_API_JSON
-DEFINE_VAPI_MSG_IDS_UDP_API_JSON
-
-typedef struct {
- vapi_ctx_t g_vapi_ctx_instance;
- bool async;
-} vapi_skc_ctx_t;
-
-vapi_skc_ctx_t vapi_skc = {
- .g_vapi_ctx_instance = NULL,
- .async = false,
-};
-
-/**
- * Messages to the forwarder might be multiplexed thanks to the seqNum fields in
- * the header_control_message structure. The forwarder simply answers back the
- * original sequence number. We maintain a map of such sequence number to
- * outgoing queries so that replied can be demultiplexed and treated
- * appropriately.
- */
-/* TYPEDEF_MAP_H(hc_sock_map, int, hc_sock_request_t *); */
-/* TYPEDEF_MAP(hc_sock_map, int, hc_sock_request_t *, int_cmp, int_snprintf, */
-/* generic_snprintf); */
-
-struct hc_sock_vpp_s {
- /* This must be the first element of the struct */
- hc_sock_t vft;
-
- vapi_ctx_t g_vapi_ctx_instance;
- char *url;
- int fd;
-
- size_t roff; /**< Read offset */
- size_t woff; /**< Write offset */
- u32 buffer[RECV_BUFLEN];
- /* Next sequence number to be used for requests */
- int seq;
-
- bool async;
-};
-
-typedef struct hc_sock_vpp_s hc_sock_vpp_t;
-
-#define TO_HC_SOCK_VPP(s) (hc_sock_vpp_t*)(s)
-
-/******************************************************************************
- * Message helper types and aliases
- ******************************************************************************/
-
-#define foreach_hc_command \
- _(hicn_api_node_params_set) \
- _(hicn_api_node_params_set_reply) \
- _(hicn_api_node_params_get_reply) \
- _(hicn_api_node_stats_get_reply) \
- _(hicn_api_face_get) \
- _(hicn_api_faces_details) \
- _(hicn_api_face_stats_details) \
- _(hicn_api_face_get_reply) \
- _(hicn_api_route_get) \
- _(hicn_api_route_get_reply) \
- _(hicn_api_routes_details) \
- _(hicn_api_strategies_get_reply) \
- _(hicn_api_strategy_get) \
- _(hicn_api_strategy_get_reply)
-
-
-typedef vapi_type_msg_header2_t hc_msg_header_t;
-
-typedef union {
-#define _(a) vapi_payload_ ## a a;
- foreach_hc_command
-#undef _
-} hc_msg_payload_t;
-
-typedef struct __attribute__ ((__packed__)) {
- hc_msg_header_t hdr;
- hc_msg_payload_t payload;
-} hc_hicnp_t;
-
-typedef void (* NTOH)(void *msg);
-
-typedef struct __attribute__((__packed__)) {
- hc_data_t *data;
- uint32_t curr_msg;
-} callback_ctx_t;
-
-typedef struct __attribute__((__packed__)) {
- hc_hicnp_t * hicnp_msg;
- vapi_cb_t callback;
- callback_ctx_t *callback_ctx;
- NTOH ntoh;
-} hc_msg_s;
-
-/******************************************************************************
- * Control socket
- ******************************************************************************/
-
-static void _hc_sock_vpp_free(hc_sock_t *socket) {
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
- if (s->url) free(s->url);
- close(s->fd);
- free(s);
-
- vapi_disconnect_safe();
- vapi_skc.g_vapi_ctx_instance = NULL;
-}
-
-static int _hc_sock_vpp_get_next_seq(hc_sock_t *socket) {
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
- return vapi_gen_req_context(s->g_vapi_ctx_instance);
-}
-
-static int _hc_sock_vpp_set_nonblocking(hc_sock_t *socket) {
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
- s->async = 1;
- return 0;
-}
-
-static int _hc_sock_vpp_get_fd(hc_sock_t *s) { return 1; }
-
-static int _hc_sock_vpp_connect(hc_sock_t *socket) {
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
- vapi_error_e rv = vapi_connect_safe(&s->g_vapi_ctx_instance, s->async);
- if (rv != VAPI_OK)
- goto ERR_CONNECT;
-
- return 0;
-
-ERR_CONNECT:
- ERROR("[hc_sock_connect] connection failed");
- return -1;
-}
-
-static int _hc_sock_vpp_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, int seq) {
- return -1;
-}
-
-static int _hc_sock_vpp_get_available(hc_sock_t *s, u8 **buffer, size_t *size) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_sock_vpp_recv(hc_sock_t *s) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_sock_vpp_process(hc_sock_t *s, hc_data_t **pdata) {
- //NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_sock_vpp_callback(hc_sock_t * socket, hc_data_t ** pdata) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_sock_vpp_reset(hc_sock_t * socket) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/******************************************************************************
- * Command-specific structures and functions
- ******************************************************************************/
-
-
-/*----------------------------------------------------------------------------*
- * Listeners
- *----------------------------------------------------------------------------*/
-
-/* LISTENER CREATE */
-
-static int _hc_listener_create(hc_sock_t *s, hc_listener_t *listener) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_listener_create_async(hc_sock_t *s, hc_listener_t *listener) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/* LISTENER GET */
-static int _hc_listener_get(hc_sock_t *s, hc_listener_t *listener,
- hc_listener_t **listener_found) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/* LISTENER DELETE */
-
-static int _hc_listener_delete(hc_sock_t *s, hc_listener_t *listener) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_listener_delete_async(hc_sock_t *s, hc_listener_t *listener) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static vapi_error_e process_ip_info(struct vapi_ctx_s *ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_ip_address_details *reply) {
-
- if (is_last)
- return 0;
- hc_data_t *data = (hc_data_t *)callback_ctx;
-
- if (data->size == data->current) {
- data->buffer = realloc(data->buffer, sizeof(hc_listener_t) * data->size * 2);
-
- if (!data->buffer)
- return VAPI_ENOMEM;
-
- data->size *=2;
- }
-
- hc_listener_t * listener = (hc_listener_t *)(data->buffer + data->current * sizeof(hc_listener_t));
-
- if(reply->prefix.address.af == ADDRESS_IP4) {
- memcpy(listener->local_addr.v4.as_u8, reply->prefix.address.un.ip4, IPV4_ADDR_LEN);
- listener->family = AF_INET;
- }
- else {
- memcpy(listener->local_addr.v6.as_u8, reply->prefix.address.un.ip6, IPV6_ADDR_LEN);
- listener->family = AF_INET6;
- }
-
- listener->id = reply->sw_if_index;
- data->current++;
- return rv;
-}
-
-typedef struct {
- u32 swif;
- char interface_name[INTERFACE_LEN];
-} hc_vapi_interface_t;
-
-static vapi_error_e listener_list_complete_cb (
- struct vapi_ctx_s *ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_sw_interface_details *reply) {
-
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- if (is_last)
- return 0;
-
- hc_data_t *data = (hc_data_t *)callback_ctx;
-
- if (data->size == data->current) {
- data->buffer = realloc(data->buffer, sizeof(hc_vapi_interface_t) * data->size * 2);
-
- if (!data->buffer)
- return VAPI_ENOMEM;
-
- data->size *=2;
- }
-
- hc_vapi_interface_t *swif = &((hc_vapi_interface_t*)data->buffer)[data->current];
-
- swif[0].swif = reply->sw_if_index;
- memcpy(swif[0].interface_name, reply->interface_name, INTERFACE_LEN);
-
- data->current++;
-
- return rv;
-}
-
-
-/* LISTENER LIST */
-static int _hc_listener_list(hc_sock_t *socket, hc_data_t **pdata) {
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
- int retval = VAPI_OK;
- vapi_lock();
- vapi_msg_sw_interface_dump *hicnp_msg;
- hicnp_msg = vapi_alloc_sw_interface_dump(s->g_vapi_ctx_instance);
-
- if (!hicnp_msg) {
- retval = VAPI_ENOMEM;
- goto END;
- }
-
- hicnp_msg->payload.sw_if_index = ~0;
- hicnp_msg->payload.name_filter_valid = 0;
-
- hc_data_t *data = hc_data_create(0, sizeof(hc_vapi_interface_t),NULL);
-
- if (!data) {
- retval = -1;
- goto END;
- }
-
- hc_data_t *data2 = hc_data_create(0, 1,NULL);
-
- if (!data2) {
- retval = -1;
- goto END;
- }
-
- data->buffer = malloc(sizeof(hc_vapi_interface_t));
- data->size = 1;
-
- if (!data->buffer) {
- free (data);
- retval = -1;
- goto FREE_DATA;
- }
-
- int ret = vapi_sw_interface_dump(s->g_vapi_ctx_instance, hicnp_msg, listener_list_complete_cb, data);
-
- if (ret != VAPI_OK) {
- free(data->buffer);
- free(data);
- retval = -1;
- goto FREE_DATA_BUFFER;
- }
-
- data2->buffer = malloc(sizeof(hc_listener_t));
- data2->size = 1;
- data2->out_element_size = 1;
-
- if (!data2->buffer) {
- free (data2->buffer);
- retval =1 -1;
- goto CLEAN;
- }
-
- /* Query the forwarder for each interface */
- for(int i = 0; i < data->current; i++) {
- int index = data2->current;
- vapi_msg_ip_address_dump* msg = vapi_alloc_ip_address_dump(s->g_vapi_ctx_instance);
- msg->payload.sw_if_index = ((hc_vapi_interface_t *)data->buffer)[i].swif;
- msg->payload.is_ipv6 = 0;
- retval = vapi_ip_address_dump(s->g_vapi_ctx_instance, msg, process_ip_info, data2);
- vapi_msg_ip_address_dump* msg2 = vapi_alloc_ip_address_dump(s->g_vapi_ctx_instance);
-
- if (retval) goto CLEAN;
-
- msg2->payload.sw_if_index = ((hc_vapi_interface_t *)data->buffer)[i].swif;
- msg2->payload.is_ipv6 = 1;
- retval = vapi_ip_address_dump(s->g_vapi_ctx_instance, msg2, process_ip_info, data2);
- for (size_t j = index; j < data2->current; j++) {
- memcpy(((hc_listener_t *)(data2->buffer))[j].interface_name, ((hc_vapi_interface_t*)(data->buffer))[i].interface_name, INTERFACE_LEN);
- ((hc_listener_t *)(data2->buffer))[j].type = CONNECTION_TYPE_HICN;
- }
-
- if (retval) goto CLEAN;
- }
-
-CLEAN:
-FREE_DATA_BUFFER:
- free(data->buffer);
-FREE_DATA:
- free(data);
-
- data2->size = data2->current;
- data2->out_element_size = sizeof(hc_listener_t);
- *pdata = data2;
- END:
- vapi_unlock();
- return retval;
-}
-
-static int _hc_listener_list_async(hc_sock_t *s, hc_data_t **pdata) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/*----------------------------------------------------------------------------*
- * CONNECTION
- *----------------------------------------------------------------------------*/
-
-/* CONNECTION CREATE */
-
-static int _hc_connection_create(hc_sock_t *s, hc_connection_t *connection) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_connection_create_async(hc_sock_t *s, hc_connection_t *connection) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/* CONNECTION GET */
-
-static int _hc_connection_get(hc_sock_t *s, hc_connection_t *connection,
- hc_connection_t **connection_found) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_connection_update_by_id(hc_sock_t *s, int hc_connection_id, hc_connection_t *connection) {
- // Not implemented
- return -1;
-}
-
-static int _hc_connection_update(hc_sock_t *s, hc_connection_t *connection_current, hc_connection_t *connection_updated) {
- // Not implemented
- return -1;
-}
-
-/* CONNECTION DELETE */
-
-static int _hc_connection_delete(hc_sock_t *s, hc_connection_t *connection) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_connection_delete_async(hc_sock_t *s, hc_connection_t *connection) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/* CONNECTION LIST */
-
-static int _hc_connection_list(hc_sock_t *s, hc_data_t **pdata) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_connection_list_async(hc_sock_t *s, hc_data_t **pdata) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/* CONNECTION SET ADMIN STATE */
-
-static int _hc_connection_set_admin_state(hc_sock_t *s, const char *conn_id_or_name,
- face_state_t state) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_connection_set_admin_state_async(hc_sock_t *s,
- const char *conn_id_or_name,
- face_state_t state) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-#ifdef WITH_POLICY
-
-static int _hc_connection_set_priority(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_connection_set_priority_async(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-#endif // WITH_POLICY
-
-static int _hc_connection_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-static int _hc_connection_set_tags_async(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags) {
- // NOT IMPLEMENTED
- return -1;
-}
-
-/*----------------------------------------------------------------------------*
- * Routes
- *----------------------------------------------------------------------------*/
-
-static vapi_error_e create_udp_tunnel_cb( vapi_ctx_t ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_udp_tunnel_add_del_reply *reply) {
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- if (reply->retval != VAPI_OK)
- return reply->retval;
-
- u32 * uei = (u32*) callback_ctx;
- *uei = reply->uei;
-
- return reply->retval;
-}
-
-/* ROUTE CREATE */
-static vapi_error_e parse_route_create( vapi_ctx_t ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_ip_route_add_del_reply *reply) {
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- if (reply->retval != VAPI_OK)
- return reply->retval;
-
- return reply->retval;
-}
-
-static vapi_error_e hicn_enable_cb( vapi_ctx_t ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_enable_disable_reply *reply) {
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- return reply->retval;
-}
-
-static int _hc_route_create_internal(hc_sock_t *socket, hc_route_t *route, bool async) {
- if (!IS_VALID_FAMILY(route->family)) return -1;
-
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
- int ret;
- vapi_lock();
-
- vapi_msg_ip_route_add_del *hicnp_msg = vapi_alloc_ip_route_add_del(s->g_vapi_ctx_instance, 1);
-
- hicnp_msg->payload.is_add = 1;
- if (route->family == AF_INET) {
- memcpy(&hicnp_msg->payload.route.prefix.address.un.ip4[0], &route->remote_addr.v4, 4);
- hicnp_msg->payload.route.prefix.address.af = ADDRESS_IP4;
- }
- else {
- memcpy(&hicnp_msg->payload.route.prefix.address.un.ip6[0], &route->remote_addr.v6, 16);
- hicnp_msg->payload.route.prefix.address.af = ADDRESS_IP6;
- }
-
- hicnp_msg->payload.route.prefix.len = route->len;
-
- hicnp_msg->payload.route.paths[0].sw_if_index = ~0;
- hicnp_msg->payload.route.paths[0].table_id = 0;
-
- hc_face_t *face = &(route->face);
- switch (face->face.type) {
- case FACE_TYPE_HICN:
- {
- if (ip46_address_is_ip4((ip46_address_t *)(&(face->face.remote_addr)))) {
- memcpy(&(hicnp_msg->payload.route.paths[0].nh.address.ip4), &face->face.remote_addr.v4, sizeof(ip4_address_t));
- hicnp_msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP4;
- }
- else{
- memcpy(&(hicnp_msg->payload.route.paths[0].nh.address.ip6), &face->face.remote_addr.v6, sizeof(ip6_address_t));
- hicnp_msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP6;
- }
-
- hicnp_msg->payload.route.paths[0].type = FIB_API_PATH_FLAG_NONE;
- hicnp_msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
-
- break;
- }
- case FACE_TYPE_UDP:
- {
- vapi_msg_hicn_api_udp_tunnel_add_del *msg = NULL;
- u32 uei = ~0;
-
- if (ip46_address_is_ip4((ip46_address_t *)(&(face->face.remote_addr))) &&
- ip46_address_is_ip4((ip46_address_t *)(&(face->face.local_addr)))) {
-
- msg = vapi_alloc_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance);
- memcpy(msg->payload.src_addr.un.ip4, &face->face.local_addr.v4, sizeof(ip4_address_t));
- msg->payload.src_addr.af = ADDRESS_IP4;
-
- memcpy(msg->payload.dst_addr.un.ip4, &face->face.remote_addr.v4, sizeof(ip4_address_t));
- msg->payload.dst_addr.af = ADDRESS_IP4;
-
- } else if (!ip46_address_is_ip4((ip46_address_t *)(&(route->face.face.remote_addr))) &&
- !ip46_address_is_ip4((ip46_address_t *)(&(route->face.face.local_addr)))) {
-
- msg = vapi_alloc_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance);
- memcpy(msg->payload.src_addr.un.ip6, &face->face.local_addr.v6, sizeof(ip6_address_t));
- msg->payload.src_addr.af = ADDRESS_IP4;
-
- memcpy(msg->payload.dst_addr.un.ip6, &face->face.remote_addr.v6, sizeof(ip6_address_t));
- msg->payload.dst_addr.af = ADDRESS_IP6;
-
- } else {
- //NOT IMPLEMENTED
- ret = -1;
- goto done;
- }
-
- msg->payload.src_port = face->face.local_port;
- msg->payload.dst_port = face->face.remote_port;
- msg->payload.is_add = 1;
-
- int ret = vapi_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance, msg, create_udp_tunnel_cb, &uei);
-
- if(ret) {
- vapi_msg_free(s->g_vapi_ctx_instance, hicnp_msg);
- goto done;
- }
-
- hicnp_msg->payload.route.paths[0].type = FIB_API_PATH_TYPE_UDP_ENCAP;
- hicnp_msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
- hicnp_msg->payload.route.paths[0].nh.obj_id = uei;
- break;
- }
- default:
- ret = -1;
- goto done;
- }
-
- ret = vapi_ip_route_add_del(s->g_vapi_ctx_instance, hicnp_msg, parse_route_create, NULL);
-
- if (ret)
- goto done;
-
- vapi_msg_hicn_api_enable_disable *msg = vapi_alloc_hicn_api_enable_disable(s->g_vapi_ctx_instance);
-
- if (route->family == AF_INET) {
- memcpy(&msg->payload.prefix.address.un.ip4[0], &route->remote_addr.v4, 4);
- msg->payload.prefix.address.af = ADDRESS_IP4;
- }
- else {
- memcpy(&msg->payload.prefix.address.un.ip6[0], &route->remote_addr.v6, 16);
- msg->payload.prefix.address.af = ADDRESS_IP6;
- }
-
- msg->payload.prefix.len = route->len;
- msg->payload.enable_disable = 1;
-
- ret = vapi_hicn_api_enable_disable(s->g_vapi_ctx_instance, msg, hicn_enable_cb, NULL);
-done:
- vapi_unlock();
- return ret;
-}
-
-static int _hc_route_create(hc_sock_t *s, hc_route_t *route) {
- return _hc_route_create_internal(s, route, false);
-}
-
-static int _hc_route_create_async(hc_sock_t *s, hc_route_t *route) {
- return _hc_route_create_internal(s, route, true);
-}
-
-/* ROUTE DELETE */
-static vapi_error_e parse_route_delete( vapi_ctx_t ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_ip_route_add_del_reply *reply) {
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- return reply->retval;
-}
-
-static int _hc_route_delete_internal(hc_sock_t *socket, hc_route_t *route, bool async) {
- if (!IS_VALID_FAMILY(route->family)) return -1;
-
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
-
- vapi_lock();
- vapi_msg_ip_route_add_del *hicnp_msg = vapi_alloc_ip_route_add_del(s->g_vapi_ctx_instance, 1);
-
- hicnp_msg->payload.is_add = 0;
- if (route->family == AF_INET) {
- memcpy(&hicnp_msg->payload.route.prefix.address.un.ip4[0], &route->remote_addr.v4, 4);
- hicnp_msg->payload.route.prefix.address.af = ADDRESS_IP4;
- }
- else {
- memcpy(&hicnp_msg->payload.route.prefix.address.un.ip6[0], &route->remote_addr.v6, 16);
- hicnp_msg->payload.route.prefix.address.af = ADDRESS_IP6;
- }
-
- hicnp_msg->payload.route.prefix.len = route->len;
-
- hicnp_msg->payload.route.paths[0].sw_if_index = ~0;
- hicnp_msg->payload.route.paths[0].table_id = 0;
-
- hc_face_t *face = &(route->face);
- switch (face->face.type) {
- case FACE_TYPE_HICN:
- {
- if (ip46_address_is_ip4((ip46_address_t *)(&(face->face.remote_addr)))) {
- memcpy(&(hicnp_msg->payload.route.paths[0].nh.address.ip4), &face->face.remote_addr.v4, sizeof(ip4_address_t));
- hicnp_msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP4;
- }
- else{
- memcpy(&(hicnp_msg->payload.route.paths[0].nh.address.ip6), &face->face.remote_addr.v6, sizeof(ip6_address_t));
- hicnp_msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP6;
- }
-
- hicnp_msg->payload.route.paths[0].type = FIB_API_PATH_FLAG_NONE;
- hicnp_msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
-
- break;
- }
- case FACE_TYPE_UDP:
- {
- hicnp_msg->payload.route.paths[0].type = FIB_API_PATH_TYPE_UDP_ENCAP;
- hicnp_msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
- hicnp_msg->payload.route.paths[0].nh.obj_id = face->face.netdevice.index;
- break;
- }
- default:
- return -1;
- }
-
- vapi_error_e ret = vapi_ip_route_add_del(s->g_vapi_ctx_instance, hicnp_msg, parse_route_delete, NULL);
-
- vapi_unlock();
- return ret;
-}
-
-static int _hc_route_delete(hc_sock_t *s, hc_route_t *route) {
- return _hc_route_delete_internal(s, route, false);
-}
-
-static int _hc_route_delete_async(hc_sock_t *s, hc_route_t *route) {
- return _hc_route_delete_internal(s, route, true);
-}
-
-static vapi_error_e parse_udp_encap_list( vapi_ctx_t ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_udp_encap_details *reply) {
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- hc_face_t * face = (hc_face_t *)callback_ctx;
-
- if (face->face.netdevice.index == reply->udp_encap.id)
- {
- switch(reply->udp_encap.src_ip.af) {
- case ADDRESS_IP4:
- {
- memcpy(&face->face.local_addr.v4, &(reply->udp_encap.src_ip.un.ip4), sizeof(ip4_address_t));
- memcpy(&face->face.remote_addr.v4, &(reply->udp_encap.dst_ip.un.ip4), sizeof(ip4_address_t));
- break;
- }
- case ADDRESS_IP6:
- {
- memcpy(&face->face.local_addr.v6, &(reply->udp_encap.src_ip.un.ip6), sizeof(ip6_address_t));
- memcpy(&face->face.remote_addr.v6, &(reply->udp_encap.dst_ip.un.ip6), sizeof(ip6_address_t));
- break;
- }
- default:
- break;
- }
-
- face->face.local_port = reply->udp_encap.src_port;
- face->face.remote_port = reply->udp_encap.dst_port;
- }
- return rv;
-}
-
-static int _fill_face_with_info(hc_face_t * face, vapi_type_fib_path *path, hc_sock_t *s) {
- switch(path->type){
- case FIB_API_PATH_FLAG_NONE:
- {
- face->face.type = FACE_TYPE_HICN;
- switch(path->proto){
- case FIB_API_PATH_NH_PROTO_IP4:
- memcpy(&face->face.remote_addr.v4, &(path->nh.address.ip4), sizeof(ip4_address_t));
- break;
- case FIB_API_PATH_NH_PROTO_IP6:
- memcpy(&face->face.remote_addr.v6, &(path->nh.address.ip6), sizeof(ip6_address_t));
- break;
- default:
- break;
- }
- face->face.netdevice.index = path->sw_if_index;
- }
- break;
- case FIB_API_PATH_TYPE_UDP_ENCAP:
- {
- face->face.type = FACE_TYPE_UDP;
- face->face.netdevice.index = clib_net_to_host_u32(path->nh.obj_id);
- // Let's make the compiler happy
- (void)parse_udp_encap_list;
- //vapi_msg_udp_encap_dump *msg;
- //msg = vapi_alloc_udp_encap_dump(s->g_vapi_ctx_instance);
- //vapi_udp_encap_dump(s->g_vapi_ctx_instance, msg, parse_udp_encap_list, face);
- }
- break;
- default:
- return -1;
- }
- return 0;
-}
-
-/* ROUTE LIST */
-typedef struct hicn_route_socket_s {
- hc_data_t *data;
- hc_sock_t *s;
-} hicn_route_socket_t;
-
-static vapi_error_e parse_route_list( vapi_ctx_t ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_ip_route_details *reply) {
-
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- hicn_route_socket_t *rs = (hicn_route_socket_t *)callback_ctx;
- hc_data_t *data = rs->data;
-
- u8 found = false;
- for (int j = 0; j < reply->route.n_paths; j++){
- for (int i = 0; i < data->size && !found; i++) {
- hc_route_t * route = &((hc_route_t*)(data->buffer))[i];
-
- if(ip46_address_is_ip4((ip46_address_t *)&(route->remote_addr)) &&
- memcmp(route->remote_addr.v4.as_u8, reply->route.prefix.address.un.ip4, sizeof(ip4_address_t)) == 0 &&
- route->len == reply->route.prefix.len && route->face_id == ~0) {
- _fill_face_with_info(&(route->face), &reply->route.paths[j], rs->s);
- found = true;
- } else if (memcmp(route->remote_addr.v6.as_u8, reply->route.prefix.address.un.ip6, sizeof(ip6_address_t)) == 0 &&
- route->len == reply->route.prefix.len && route->face_id == ~0) {
- _fill_face_with_info(&(route->face), &reply->route.paths[j], rs->s);
- found = true;
- }
- }
- }
-
- return rv;
-}
-
-static vapi_error_e parse_hicn_route_list( vapi_ctx_t ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_routes_details *reply) {
-
- if (reply == NULL || rv != VAPI_OK)
- return rv;
-
- hc_data_t *data = (hc_data_t *)callback_ctx;
-
- int empty_spots = data->size - data->current;
- if (empty_spots < reply->nfaces) {
- int new_size = data->size + (reply->nfaces - empty_spots);
- data->buffer = realloc(data->buffer, sizeof(hc_route_t) * (new_size));
- if (!data->buffer)
- return VAPI_ENOMEM;
-
- data->size =new_size;
- }
-
- for (int i = 0; i < reply->nfaces; i++) {
- hc_route_t * route = &((hc_route_t*)(data->buffer))[data->current];
- route->face_id = ~0;
- route->cost = 1;
- route->len = reply->prefix.len;
- if (reply->prefix.address.af == ADDRESS_IP6)
- {
- memcpy(route->remote_addr.v6.as_u8, reply->prefix.address.un.ip6, 16);
- }
- else
- {
- memcpy(route->remote_addr.v4.as_u8, reply->prefix.address.un.ip4, 4);
- }
- route->family = reply->prefix.address.af == ADDRESS_IP6? AF_INET6 : AF_INET;
- data->current++;
- }
-
- return rv;
-}
-
-static int _hc_route_list_internal(hc_sock_t *socket, hc_data_t **pdata, bool async) {
- hc_sock_vpp_t *s = TO_HC_SOCK_VPP(socket);
- vapi_lock();
-
- vapi_msg_hicn_api_routes_dump *msg;
- msg = vapi_alloc_hicn_api_routes_dump(s->g_vapi_ctx_instance);
-
- hc_data_t *data = hc_data_create(0, sizeof(hc_route_t),NULL);
- int ret = VAPI_OK;
-
- if (!data){
- ret = -1;
- goto err;
- }
-
- data->buffer = malloc(sizeof(hc_route_t));
- data->size = 1;
-
- if (!data->buffer) {
- ret = -1;
- goto err_free;
- }
-
- ret = vapi_hicn_api_routes_dump(s->g_vapi_ctx_instance, msg, parse_hicn_route_list, data);
-
- if (ret != VAPI_OK)
- goto err_free;
-
- vapi_msg_ip_route_dump *hicnp_msg;
- hicnp_msg = vapi_alloc_ip_route_dump(s->g_vapi_ctx_instance);
- hicnp_msg->payload.table.table_id = 0;
- hicnp_msg->payload.table.is_ip6 = 1;
-
- hicn_route_socket_t ctx = {
- .data = data,
- .s = socket,
- };
-
- ret = vapi_ip_route_dump(s->g_vapi_ctx_instance, hicnp_msg, parse_route_list, &ctx);
-
- hicnp_msg = vapi_alloc_ip_route_dump(s->g_vapi_ctx_instance);
- hicnp_msg->payload.table.table_id = 0;
- hicnp_msg->payload.table.is_ip6 = 0;
-
- ret = vapi_ip_route_dump(s->g_vapi_ctx_instance, hicnp_msg, parse_route_list, &ctx);
-
- if (ret != VAPI_OK)
- goto err_free;
-
- *pdata = data;
-
- vapi_unlock();
- return ret;
-
- err_free:
- free(data);
- err:
- vapi_unlock();
- return ret;
-}
-
-static int _hc_route_list(hc_sock_t *s, hc_data_t **pdata) {
- return _hc_route_list_internal(s, pdata, false);
-}
-
-static int _hc_route_list_async(hc_sock_t *s) {
- return _hc_route_list_internal(s, NULL, true);
-}
-
-/*----------------------------------------------------------------------------*
- * Face
- *
- * Face support is not directly available in hicn-light, but we can offer such
- * an interface through a combination of listeners and connections. The code
- * starts with some conversion functions between faces/listeners/connections.
- *
- * We also need to make sure that there always exist a (single) listener when a
- * connection is created, and in the hICN face case, that there is a single
- * connection attached to this listener.
- *
- *----------------------------------------------------------------------------*/
-
-static int _hc_face_create(hc_sock_t *s, hc_face_t *face) {
- ERROR("Face creation implemented.");
- return -1;
-}
-
-static int _hc_face_get(hc_sock_t * socket, hc_face_t * face, hc_face_t ** face_found) {
- ERROR("Face deletion not implemented.");
- return -1;
-}
-
-static int _hc_face_delete(hc_sock_t *s, hc_face_t *face) {
- ERROR("Face deletion not implemented.");
- return -1;
-}
-
-/* FACE LIST */
-
-static int _hc_face_list(hc_sock_t *s, hc_data_t **pdata) {
- ERROR("Face list not implemented.");
- return -1;
-}
-
-static int _hc_face_list_async(hc_sock_t *s) {
- return 0;
-}
-
-static int _hc_face_set_admin_state(
- hc_sock_t *s, const char *conn_id_or_name, // XXX wrong identifier
- face_state_t admin_state) {
- return 0;
-}
-
-#ifdef WITH_POLICY
-static int _hc_face_set_priority(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority) {
- ERROR("Face set priority not implemented.");
- return -1;
-}
-
-static int _hc_face_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags) {
- ERROR("Face set tags not implemented.");
- return -1;
-}
-#endif // WITH_POLICY
-
-/*----------------------------------------------------------------------------*
- * Punting
- *----------------------------------------------------------------------------*/
-
-static int _hc_punting_create_internal(hc_sock_t *s, hc_punting_t *punting, bool async) {
- return -1;
-}
-
-static int _hc_punting_create(hc_sock_t *s, hc_punting_t *punting) {
- return _hc_punting_create_internal(s, punting, false);
-}
-
-static int _hc_punting_create_async(hc_sock_t *s, hc_punting_t *punting) {
- return _hc_punting_create_internal(s, punting, true);
-}
-
-static int _hc_punting_get(hc_sock_t *s, hc_punting_t *punting,
- hc_punting_t **punting_found) {
- ERROR("hc_punting_get not (yet) implemented.");
- return -1;
-}
-
-static int _hc_punting_delete(hc_sock_t *s, hc_punting_t *punting) {
- ERROR("hc_punting_delete not (yet) implemented.");
- return -1;
-}
-
-static int _hc_punting_list(hc_sock_t *s, hc_data_t **pdata) {
- ERROR("hc_punting_list not (yet) implemented.");
- return -1;
-}
-
-/*----------------------------------------------------------------------------*
- * Cache
- *----------------------------------------------------------------------------*/
-
-static int _hc_cache_set_store_internal(hc_sock_t *s, int enabled, bool async) {
- return 0;
-}
-
-static int _hc_cache_set_store(hc_sock_t *s, int enabled) {
- return _hc_cache_set_store_internal(s, enabled, false);
-}
-
-static int _hc_cache_set_store_async(hc_sock_t *s, int enabled) {
- return _hc_cache_set_store_internal(s, enabled, true);
-}
-
-static int _hc_cache_set_serve_internal(hc_sock_t *s, int enabled, bool async) {
- return 0;
-}
-
-static int _hc_cache_set_serve(hc_sock_t *s, int enabled) {
- return _hc_cache_set_serve_internal(s, enabled, false);
-}
-
-static int _hc_cache_set_serve_async(hc_sock_t *s, int enabled) {
- return _hc_cache_set_serve_internal(s, enabled, true);
-}
-
-/*----------------------------------------------------------------------------*
- * Strategy
- *----------------------------------------------------------------------------*/
-
-// per prefix
-static int _hc_strategy_set(hc_sock_t *s /* XXX */) { return 0; }
-
-static int _hc_strategy_list(hc_sock_t *s, hc_data_t **data) {
- return 0;
-}
-
-/*----------------------------------------------------------------------------*
- * WLDR
- *----------------------------------------------------------------------------*/
-
-// per connection
-static int _hc_wldr_set(hc_sock_t *s /* XXX */) { return 0; }
-
-/*----------------------------------------------------------------------------*
- * MAP-Me
- *----------------------------------------------------------------------------*/
-
-static int _hc_mapme_set(hc_sock_t *s, int enabled) { return 0; }
-
-static int _hc_mapme_set_discovery(hc_sock_t *s, int enabled) { return 0; }
-
-static int _hc_mapme_set_timescale(hc_sock_t *s, double timescale) { return 0; }
-
-static int _hc_mapme_set_retx(hc_sock_t *s, double timescale) { return 0; }
-
-/*----------------------------------------------------------------------------*
- * Policy
- *----------------------------------------------------------------------------*/
-
-#ifdef WITH_POLICY
-
-/* POLICY CREATE */
-
-static int _hc_policy_create_internal(hc_sock_t * socket, hc_policy_t * policy, bool async) {
- return -1;
-}
-
-static int
-_hc_policy_create(hc_sock_t * s, hc_policy_t * policy) {
- return _hc_policy_create_internal(s, policy, false);
-}
-
-static int _hc_policy_create_async(hc_sock_t * s, hc_policy_t * policy) {
- return _hc_policy_create_internal(s, policy, true);
-}
-
-/* POLICY DELETE */
-
-static int _hc_policy_delete_internal(hc_sock_t * socket, hc_policy_t * policy, bool async) {
- return -1;
-}
-
-static int _hc_policy_delete(hc_sock_t * s, hc_policy_t * policy) {
- return _hc_policy_delete_internal(s, policy, false);
-}
-
-static int _hc_policy_delete_async(hc_sock_t * s, hc_policy_t * policy) {
- return _hc_policy_delete_internal(s, policy, true);
-}
-
-/* POLICY LIST */
-
-static int
-_hc_policy_list_internal(hc_sock_t * socket, hc_data_t ** pdata, bool async) {
- return -1;
-}
-
-static int _hc_policy_list(hc_sock_t * s, hc_data_t ** pdata) {
- return _hc_policy_list_internal(s, pdata, false);
-}
-
-static int _hc_policy_list_async(hc_sock_t * s, hc_data_t ** pdata) {
- return _hc_policy_list_internal(s, pdata, true);
-}
-
-#endif /* WITH_POLICY */
-
-static hc_sock_t hc_sock_vpp_interface = (hc_sock_t) {
- .hc_sock_get_next_seq = _hc_sock_vpp_get_next_seq,
- .hc_sock_set_nonblocking = _hc_sock_vpp_set_nonblocking,
- .hc_sock_get_fd = _hc_sock_vpp_get_fd,
- .hc_sock_connect = _hc_sock_vpp_connect,
- .hc_sock_get_available = _hc_sock_vpp_get_available,
- .hc_sock_send = _hc_sock_vpp_send,
- .hc_sock_recv = _hc_sock_vpp_recv,
- .hc_sock_process = _hc_sock_vpp_process,
- .hc_sock_callback = _hc_sock_vpp_callback,
- .hc_sock_reset = _hc_sock_vpp_reset,
- .hc_sock_free = _hc_sock_vpp_free,
- .hc_listener_create = _hc_listener_create,
- .hc_listener_create_async = _hc_listener_create_async,
- .hc_listener_get = _hc_listener_get,
- .hc_listener_delete = _hc_listener_delete,
- .hc_listener_delete_async = _hc_listener_delete_async,
- .hc_listener_list = _hc_listener_list,
- .hc_listener_list_async = _hc_listener_list_async,
- .hc_connection_create = _hc_connection_create,
- .hc_connection_create_async = _hc_connection_create_async,
- .hc_connection_get = _hc_connection_get,
- .hc_connection_update_by_id = _hc_connection_update_by_id,
- .hc_connection_update = _hc_connection_update,
- .hc_connection_delete = _hc_connection_delete,
- .hc_connection_delete_async = _hc_connection_delete_async,
- .hc_connection_list = _hc_connection_list,
- .hc_connection_list_async = _hc_connection_list_async,
- .hc_connection_set_admin_state = _hc_connection_set_admin_state,
- .hc_connection_set_admin_state_async = _hc_connection_set_admin_state_async,
-
-#ifdef WITH_POLICY
- .hc_connection_set_priority = _hc_connection_set_priority,
- .hc_connection_set_priority_async = _hc_connection_set_priority_async,
- .hc_connection_set_tags = _hc_connection_set_tags,
- .hc_connection_set_tags_async = _hc_connection_set_tags_async,
-#endif // WITH_POLICY
-
- .hc_face_create = _hc_face_create,
- .hc_face_get = _hc_face_get,
- .hc_face_delete = _hc_face_delete,
- .hc_face_list = _hc_face_list,
- .hc_face_list_async = _hc_face_list_async,
- .hc_face_set_admin_state = _hc_face_set_admin_state,
-
-#ifdef WITH_POLICY
- .hc_face_set_priority = _hc_face_set_priority,
- .hc_face_set_tags = _hc_face_set_tags,
-#endif // WITH_POLICY
-
- .hc_route_create = _hc_route_create,
- .hc_route_create_async = _hc_route_create_async,
- .hc_route_delete = _hc_route_delete,
- .hc_route_delete_async = _hc_route_delete_async,
- .hc_route_list = _hc_route_list,
- .hc_route_list_async = _hc_route_list_async,
-
- .hc_punting_create = _hc_punting_create,
- .hc_punting_create_async = _hc_punting_create_async,
- .hc_punting_get = _hc_punting_get,
- .hc_punting_delete = _hc_punting_delete,
- .hc_punting_list = _hc_punting_list,
-
- .hc_cache_set_store = _hc_cache_set_store,
- .hc_cache_set_store_async = _hc_cache_set_store_async,
- .hc_cache_set_serve = _hc_cache_set_serve,
- .hc_cache_set_serve_async = _hc_cache_set_serve_async,
-
- .hc_strategy_list = _hc_strategy_list,
- .hc_strategy_set = _hc_strategy_set,
- .hc_wldr_set = _hc_wldr_set,
-
- .hc_mapme_set = _hc_mapme_set,
- .hc_mapme_set_discovery = _hc_mapme_set_discovery,
- .hc_mapme_set_timescale = _hc_mapme_set_timescale,
- .hc_mapme_set_retx = _hc_mapme_set_retx,
-
-#ifdef WITH_POLICY
- .hc_policy_create = _hc_policy_create,
- .hc_policy_create_async = _hc_policy_create_async,
- .hc_policy_delete = _hc_policy_delete,
- .hc_policy_delete_async = _hc_policy_delete_async,
- .hc_policy_list = _hc_policy_list,
- .hc_policy_list_async = _hc_policy_list_async
-#endif // WITH_POLICY
-};
-
-hc_sock_t *_hc_sock_create_url(const char *url) {
- // NOT IMPLEMENTED
- return NULL;
-}
-
-hc_sock_t *_hc_sock_create(void) {
- hc_sock_vpp_t *s = malloc(sizeof(hc_sock_vpp_t));
-
- if (!s) goto ERR_SOCK;
-
- memset(s, 0, sizeof(hc_sock_vpp_t));
-
- s->vft = hc_sock_vpp_interface;
-
- // By default the socket is blocking -- not async
- s->async = 0;
-
- return (hc_sock_t *)(s);
-
-ERR_SOCK:
- return NULL;
-} \ No newline at end of file
diff --git a/ctrl/libhicnctrl/src/object.c b/ctrl/libhicnctrl/src/object.c
new file mode 100644
index 000000000..d9863308e
--- /dev/null
+++ b/ctrl/libhicnctrl/src/object.c
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file object.c
+ * \brief Implementation of API object representation.
+ */
+
+#include <hicn/ctrl/action.h>
+#include <hicn/ctrl/object.h>
+
+#include "objects/base.h" // iszero
+#include "object_vft.h"
+
+bool hc_object_is_empty(const hc_object_t *object) {
+ return iszero(object, sizeof(hc_object_t));
+}
+
+int hc_object_validate(hc_object_type_t object_type, hc_object_t *object,
+ bool allow_partial) {
+ const hc_object_ops_t *vft = object_vft[object_type];
+ if (!vft) return -1;
+ return vft->validate(object, allow_partial);
+}
+
+int hc_object_cmp(hc_object_type_t object_type, hc_object_t *object1,
+ hc_object_t *object2) {
+ const hc_object_ops_t *vft = object_vft[object_type];
+ if (!vft) return -1;
+ return vft->cmp(object1, object2);
+}
+
+int hc_object_snprintf(char *s, size_t size, hc_object_type_t object_type,
+ hc_object_t *object) {
+ if (!object) {
+ if (size == 0) return -1;
+ *s = '\0';
+ return 1;
+ }
+
+ const hc_object_ops_t *vft = object_vft[object_type];
+ if (!vft) return -1;
+ return vft->obj_snprintf(s, size, object);
+}
+
+size_t hc_object_size(hc_object_type_t object_type) {
+ const hc_object_ops_t *vft = object_vft[object_type];
+ if (!vft) return -1;
+ return vft->size;
+}
diff --git a/ctrl/libhicnctrl/src/object_private.h b/ctrl/libhicnctrl/src/object_private.h
new file mode 100644
index 000000000..1aea86639
--- /dev/null
+++ b/ctrl/libhicnctrl/src/object_private.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file object_private.h
+ * \brief Helper functions for object management.
+ */
+
+#ifndef HICNCTRL_OBJECT_PRIVATE_H
+#define HICNCTRL_OBJECT_PRIVATE_H
+
+#include <hicn/face.h>
+
+#define INT_CMP(x, y) ((x > y) ? 1 : (x < y) ? -1 : 0)
+
+// XXX Those are always true
+#define IS_VALID_ADDRESS(x) (1)
+#define IS_VALID_CONNECTION_ID(x) (x != INVALID_FACE_ID)
+#define IS_VALID_ROUTE_COST(x) (1)
+#define IS_VALID_PREFIX_LEN(x) (1)
+#define IS_VALID_POLICY(x) (1)
+#define IS_VALID_ID(x) (1)
+#define IS_VALID_INTERFACE_NAME(x) (1)
+#define IS_VALID_NAME(x) (1)
+#define IS_VALID_TYPE(x) IS_VALID_ENUM_TYPE(FACE_TYPE, x)
+#define IS_VALID_FACE_STATE(x) (1)
+
+#define IS_VALID_ADDR_TYPE(x) ((x >= ADDR_INET) && (x <= ADDR_UNIX))
+
+#define IS_VALID_CONNECTION_TYPE(x) IS_VALID_ENUM_TYPE(CONNECTION_TYPE, x)
+
+#define GENERATE_FIND(TYPE) \
+ int hc_##TYPE##_find(hc_data_t *data, const hc_##TYPE##_t *element, \
+ hc_##TYPE##_t **found) { \
+ foreach_type(hc_##TYPE##_t, x, data) { \
+ if (hc_##TYPE##_cmp(x, element) == 0) { \
+ *found = x; \
+ return 0; \
+ } \
+ }; \
+ *found = NULL; /* this is optional */ \
+ return 0; \
+ }
+
+#endif /* HICNCTRL_OBJECT_PRIVATE_H */
diff --git a/hicn-light/src/hicn/config/controlRemovePolicy.h b/ctrl/libhicnctrl/src/object_type.c
index ebe098985..0303fce75 100644
--- a/hicn-light/src/hicn/config/controlRemovePolicy.h
+++ b/ctrl/libhicnctrl/src/object_type.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,23 +14,26 @@
*/
/**
- * @file control_RemovePolicy.h
- * @brief Remove a policy from the FIB
- *
- * Implements the "remove policy" and "help remove policy" nodes of the command
- * tree
- *
+ * \file object_type.c
+ * \brief Implementation of object type.
*/
-#ifndef Control_RemovePolicy_h
-#define Control_RemovePolicy_h
-
-#ifdef WITH_POLICY
+#include <strings.h>
-#include <hicn/config/controlState.h>
-CommandOps *controlRemovePolicy_Create(ControlState *state);
-CommandOps *controlRemovePolicy_HelpCreate(ControlState *state);
+#include <hicn/ctrl/object_type.h>
-#endif /* WITH_POLICY */
+const char *object_type_str[] = {
+#define _(x) [OBJECT_TYPE_##x] = #x,
+ foreach_object_type
+#undef _
+};
-#endif // Control_RemovePolicy_h
+hc_object_type_t object_type_from_str(const char *object_str) {
+#define _(x) \
+ if (strcasecmp(object_str, #x) == 0) \
+ return OBJECT_TYPE_##x; \
+ else
+ foreach_object_type
+#undef _
+ return OBJECT_TYPE_UNDEFINED;
+}
diff --git a/ctrl/libhicnctrl/src/object_vft.c b/ctrl/libhicnctrl/src/object_vft.c
new file mode 100644
index 000000000..4dc59c378
--- /dev/null
+++ b/ctrl/libhicnctrl/src/object_vft.c
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file object_vft.c
+ * \brief Implementation of object VFT.
+ */
+
+#include "object_vft.h"
+
+#include "objects/listener.h"
+#include "objects/connection.h"
+#include "objects/route.h"
+#include "objects/face.h"
+#include "objects/mapme.h"
+#include "objects/stats.h"
+#include "objects/strategy.h"
+#include "objects/subscription.h"
+#include "objects/active_interface.h"
+
+const hc_object_ops_t *object_vft[] = {
+ [OBJECT_TYPE_CONNECTION] = &hc_connection_ops,
+ [OBJECT_TYPE_LISTENER] = &hc_listener_ops,
+ [OBJECT_TYPE_ROUTE] = &hc_route_ops,
+ [OBJECT_TYPE_FACE] = &hc_face_ops,
+ [OBJECT_TYPE_STRATEGY] = &hc_strategy_ops,
+ [OBJECT_TYPE_MAPME] = &hc_mapme_ops,
+ [OBJECT_TYPE_SUBSCRIPTION] = &hc_subscription_ops,
+ [OBJECT_TYPE_ACTIVE_INTERFACE] = &hc_active_interface_ops,
+ [OBJECT_TYPE_STATS] = &hc_stats_ops,
+ [OBJECT_TYPE_FACE_STATS] = &hc_face_stats_ops,
+};
diff --git a/ctrl/libhicnctrl/src/object_vft.h b/ctrl/libhicnctrl/src/object_vft.h
new file mode 100644
index 000000000..e27fe5d36
--- /dev/null
+++ b/ctrl/libhicnctrl/src/object_vft.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file object_vft.h
+ * \brief Object VFT.
+ */
+
+#ifndef HICNCTRL_OBJECT_VFT
+#define HICNCTRL_OBJECT_VFT
+
+#include <stddef.h> // size_t
+#include <hicn/ctrl/object_type.h>
+#include <hicn/ctrl/object.h>
+
+typedef struct {
+ hc_object_type_t object_type;
+ const char *object_name;
+ size_t size;
+ int (*validate)(const hc_object_t *object, bool allow_partial);
+ int (*cmp)(const hc_object_t *object1, const hc_object_t *object2);
+ /* cannot be named snprintf as it collides with a macro in clang/iOS */
+ int (*obj_snprintf)(char *s, size_t size, const hc_object_t *object);
+} hc_object_ops_t;
+
+#define DECLARE_OBJECT_OPS_H(TYPE, NAME) \
+ extern const hc_object_ops_t hc_##NAME##_ops;
+
+#define DECLARE_OBJECT_OPS(TYPE, NAME) \
+ const hc_object_ops_t hc_##NAME##_ops = { \
+ .object_type = TYPE, \
+ .object_name = #NAME, \
+ .size = sizeof(hc_##NAME##_t), \
+ .validate = _hc_##NAME##_validate, \
+ .cmp = _hc_##NAME##_cmp, \
+ .obj_snprintf = _hc_##NAME##_snprintf, \
+ };
+
+extern const hc_object_ops_t *object_vft[];
+
+#endif /* HICNCTRL_OBJECT_VFT */
diff --git a/ctrl/libhicnctrl/src/objects/active_interface.c b/ctrl/libhicnctrl/src/objects/active_interface.c
new file mode 100644
index 000000000..796123963
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/active_interface.c
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file active_interface.c
+ * \brief Implementation of active_interface object.
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/active_interface.h>
+#include <hicn/util/log.h>
+#include <hicn/util/ip_address.h>
+
+#include "../object_private.h"
+#include "../object_vft.h"
+
+/* ACTIVE_INTERFACE VALIDATE */
+
+int hc_active_interface_validate(const hc_active_interface_t *active_interface,
+ bool allow_partial) {
+ return 0; // XXX TODO
+}
+
+int _hc_active_interface_validate(const hc_object_t *object,
+ bool allow_partial) {
+ return hc_active_interface_validate(&object->active_interface, allow_partial);
+}
+
+/* ACTIVE_INTERFACE CMP */
+
+// XXX TODO
+int hc_active_interface_cmp(const hc_active_interface_t *active_interface1,
+ const hc_active_interface_t *active_interface2) {
+ return -1;
+}
+
+int _hc_active_interface_cmp(const hc_object_t *object1,
+ const hc_object_t *object2) {
+ return hc_active_interface_cmp(&object1->active_interface,
+ &object2->active_interface);
+}
+
+/* ACTIVE_INTERFACE SNPRINTF */
+
+/* /!\ Please update constants in header file upon changes */
+int hc_active_interface_snprintf(
+ char *s, size_t size, const hc_active_interface_t *active_interface) {
+ int rc;
+ char *pos = s;
+
+ rc = hicn_ip_prefix_snprintf(pos, size, &active_interface->prefix);
+ if ((rc < 0) || (rc >= size)) return rc;
+ pos += rc;
+ size -= rc;
+
+ for (netdevice_type_t type = NETDEVICE_TYPE_UNDEFINED + 1;
+ type < NETDEVICE_TYPE_N; type++) {
+ if (!netdevice_flags_has(active_interface->interface_types, type)) continue;
+ rc = snprintf(pos, size, " %s", netdevice_type_str(type));
+ if ((rc < 0) || (rc >= size)) return (int)(pos - s + rc);
+
+ pos += rc;
+ size -= rc;
+ }
+ return (int)(pos - s);
+}
+
+int _hc_active_interface_snprintf(char *s, size_t size,
+ const hc_object_t *object) {
+ return hc_active_interface_snprintf(s, size, &object->active_interface);
+}
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_ACTIVE_INTERFACE, active_interface);
diff --git a/hicn-light/src/hicn/config/controlRemovePunting.h b/ctrl/libhicnctrl/src/objects/active_interface.h
index 858d6f969..973b08e40 100644
--- a/hicn-light/src/hicn/config/controlRemovePunting.h
+++ b/ctrl/libhicnctrl/src/objects/active_interface.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,14 +14,15 @@
*/
/**
- * @file control_RemovePunting.h
- *
+ * \file active_interface.h
+ * \brief Route.
*/
-#ifndef Control_RemovePunting_h
-#define Control_RemovePunting_h
+#ifndef HICNCTRL_IMPL_OBJECTS_ACTIVE_INTERFACE_H
+#define HICNCTRL_IMPL_OBJECTS_ACTIVE_INTERFACE_H
+
+#include "../object_vft.h"
+
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_ACTIVE_INTERFACE, active_interface);
-#include <hicn/config/controlState.h>
-CommandOps *controlRemovePunting_Create(ControlState *state);
-CommandOps *controlRemovePunting_HelpCreate(ControlState *state);
-#endif // Control_RemovePunting_h
+#endif /* HICNCTRL_IMPL_OBJECTS_ACTIVE_INTERFACE_H */
diff --git a/hicn-light/src/hicn/config/controlAdd.h b/ctrl/libhicnctrl/src/objects/base.c
index 7c160b5f7..86e4bfb72 100644
--- a/hicn-light/src/hicn/config/controlAdd.h
+++ b/ctrl/libhicnctrl/src/objects/base.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,19 +14,21 @@
*/
/**
- * @file control_Add.h
- * @brief Command-line "add" node
- *
- * Implements the "add" node of the CLI tree
- *
- *
+ * \file base.c
+ * \brief Implementation of base functions for object APIs.
*/
-#ifndef control_Add_h
-#define control_Add_h
+#include <stdbool.h>
+
+#include "base.h"
+
+#include <hicn/util/log.h>
-#include <hicn/config/controlState.h>
+bool iszero(const void *ptr, int bytes) {
+ char *bptr = (char *)ptr;
+ while (bytes--)
+ if (*bptr++) return false;
+ return true;
+}
-CommandOps *webControlAdd_Create(ControlState *state);
-CommandOps *controlAdd_CreateHelp(ControlState *state);
-#endif // control_Add_h
+bool isempty(const char *str) { return str[0] == '\0'; }
diff --git a/ctrl/libhicnctrl/src/objects/base.h b/ctrl/libhicnctrl/src/objects/base.h
new file mode 100644
index 000000000..eb85483e9
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/base.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file base.h
+ * \brief Base functions for object APIs.
+ */
+
+#ifndef HICNCTRL_OBJECTS_BASE_H
+#define HICNCTRL_OBJECTS_BASE_H
+
+bool iszero(const void *ptr, int bytes);
+bool isempty(const char *str);
+
+#endif /* HICNCTRL_OBJECTS_BASE_H */
diff --git a/ctrl/libhicnctrl/src/objects/connection.c b/ctrl/libhicnctrl/src/objects/connection.c
new file mode 100644
index 000000000..ca09d9a54
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/connection.c
@@ -0,0 +1,298 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file connection.c
+ * \brief Implementation of connection object.
+ */
+
+#include <assert.h>
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/connection.h>
+#include <hicn/util/log.h>
+
+#include "../object_private.h"
+#include "../object_vft.h"
+#include "base.h"
+
+bool hc_connection_is_local(const hc_connection_t *connection) {
+ return (strncmp(connection->interface_name, "lo", INTERFACE_LEN) == 0);
+}
+
+bool hc_connection_has_local(const hc_connection_t *connection) {
+ assert(connection);
+ return IS_VALID_PORT(connection->local_port) &&
+ IS_VALID_ADDRESS(connection->local_addr);
+}
+
+/* CONNECTION VALIDATE */
+
+int hc_connection_validate(const hc_connection_t *connection,
+ bool allow_partial) {
+ int has_id = 0;
+ int has_name = 0;
+#if 0
+ int has_interface_name = 0;
+#endif
+ int has_netdevice_type = 0;
+ int has_type = 0;
+ int has_family = 0;
+ int has_local_addr = 0;
+ int has_local_port = 0;
+ int has_remote_addr = 0;
+ int has_remote_port = 0;
+ int has_admin_state = 0;
+ int has_priority = 0;
+ int has_tags = 0;
+ int has_state = 0;
+
+ if (connection->id == ~0) {
+ ERROR("[hc_listener_validate] Invalid id specified");
+ return -1;
+ }
+ has_id = 1;
+
+ if (!isempty(connection->name)) {
+ if (!IS_VALID_NAME(connection->name)) {
+ ERROR("[hc_connection_validate] Invalid name specified");
+ return -1;
+ }
+ has_name = 1;
+ }
+
+#if 0
+ if (!isempty(connection->interface_name)) {
+ if (!IS_VALID_INTERFACE_NAME(connection->interface_name)) {
+ ERROR("[hc_connection_validate] Invalid interface_name specified");
+ return -1;
+ }
+ has_interface_name = 1;
+ }
+#endif
+
+ if (connection->type != FACE_TYPE_UNDEFINED) {
+ if (!IS_VALID_TYPE(connection->type)) {
+ ERROR("[hc_connection_validate] Invalid type specified");
+ return -1;
+ }
+ has_type = 1;
+ }
+
+ if (connection->family != AF_UNSPEC) {
+ if (!IS_VALID_FAMILY(connection->family)) {
+ ERROR("[hc_connection_validate] Invalid family specified");
+ return -1;
+ }
+ has_family = 1;
+ }
+
+ if (!hicn_ip_address_empty(&connection->local_addr)) {
+ if (!IS_VALID_ADDRESS(connection->local_addr)) {
+ ERROR("[hc_connection_validate] Invalid local_addr specified");
+ return -1;
+ }
+ has_local_addr = 1;
+ }
+
+ if (connection->local_port != 0) {
+ if (!IS_VALID_PORT(connection->local_port)) {
+ ERROR("[hc_connection_validate] Invalid local_port specified");
+ return -1;
+ }
+ has_local_port = 1;
+ }
+
+ if (!hicn_ip_address_empty(&connection->remote_addr)) {
+ if (!IS_VALID_ADDRESS(connection->remote_addr)) {
+ ERROR("[hc_connection_validate] Invalid remote_addr specified");
+ return -1;
+ }
+ has_remote_addr = 1;
+ }
+
+ if (connection->remote_port != 0) {
+ if (!IS_VALID_PORT(connection->remote_port)) {
+ ERROR("[hc_connection_validate] Invalid remote_port specified");
+ return -1;
+ }
+ has_remote_port = 1;
+ }
+
+ /* Interface name is optional */
+ int has_key = has_id || has_name;
+ int has_mandatory_attributes = has_type && has_family && has_local_addr &&
+ has_local_port && has_remote_addr &&
+ has_remote_port;
+ int has_optional_attributes =
+ has_netdevice_type && has_admin_state && has_state;
+ has_optional_attributes = has_optional_attributes && has_priority && has_tags;
+
+ if (allow_partial) {
+ if (has_key && !has_mandatory_attributes && !has_optional_attributes)
+ return 0;
+ else if (has_mandatory_attributes)
+ return 0;
+ else
+ return -1;
+ } else {
+ if (has_key && has_mandatory_attributes) return 0;
+ return -1;
+ }
+}
+
+int _hc_connection_validate(const hc_object_t *object, bool allow_partial) {
+ return hc_connection_validate(&object->connection, allow_partial);
+}
+
+/* CONNECTION CMP */
+
+/*
+ * hICN light uses ports even for hICN connections, but their value is
+ * ignored. As connections are specific to hicn-light, we can safely use IP
+ * and ports for comparison independently of the face type.
+ */
+int hc_connection_cmp(const hc_connection_t *c1, const hc_connection_t *c2) {
+ int rc;
+
+ rc = INT_CMP(c1->type, c2->type);
+ if (rc != 0) return rc;
+
+ rc = INT_CMP(c1->family, c2->family);
+ if (rc != 0) return rc;
+
+ if (!isempty(c1->interface_name) && !isempty(c2->interface_name)) {
+ rc = strncmp(c1->interface_name, c2->interface_name, INTERFACE_LEN);
+ if (rc != 0) return rc;
+ }
+
+ rc = hicn_ip_address_cmp(&c1->local_addr, &c2->local_addr);
+ if (rc != 0) return rc;
+
+ rc = INT_CMP(c1->local_port, c2->local_port);
+ if (rc != 0) return rc;
+
+ rc = hicn_ip_address_cmp(&c1->remote_addr, &c2->remote_addr);
+ if (rc != 0) return rc;
+
+ rc = INT_CMP(c1->remote_port, c2->remote_port);
+
+ return rc;
+}
+
+int _hc_connection_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ return hc_connection_cmp(&object1->connection, &object2->connection);
+}
+
+int hc_connection_has_valid_id(const hc_connection_t *connection) {
+ return connection->id != INVALID_FACE_ID;
+}
+
+/* CONNECTION SNPRINTF */
+
+/* /!\ Please update constants in header file upon changes */
+int hc_connection_snprintf(char *s, size_t size,
+ const hc_connection_t *connection) {
+ char local[MAXSZ_URL];
+ char remote[MAXSZ_URL];
+ int rc;
+
+ // assert(connection->connection_state)
+ if (strcmp(connection->name, "SELF") == 0) {
+ return snprintf(s, size, "%s", connection->name);
+ }
+
+ rc = url_snprintf(local, MAXSZ_URL, &connection->local_addr,
+ connection->local_port);
+ if (rc >= MAXSZ_URL)
+ WARN("[hc_connection_snprintf] Unexpected truncation of URL string");
+ if (rc < 0) return rc;
+ rc = url_snprintf(remote, MAXSZ_URL, &connection->remote_addr,
+ connection->remote_port);
+ if (rc >= MAXSZ_URL)
+ WARN("[hc_connection_snprintf] Unexpected truncation of URL string");
+ if (rc < 0) return rc;
+
+ return snprintf(s, size, "%s %s %s %s", connection->name, local, remote,
+ face_type_str(connection->type));
+}
+
+int _hc_connection_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_connection_snprintf(s, size, &object->connection);
+}
+
+int hc_connection_create(hc_sock_t *s, hc_connection_t *connection) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.connection = *connection;
+ return hc_execute(s, ACTION_CREATE, OBJECT_TYPE_CONNECTION, &object, NULL);
+}
+
+int hc_connection_get(hc_sock_t *s, hc_connection_t *connection,
+ hc_data_t **pdata) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.connection = *connection;
+ return hc_execute(s, ACTION_GET, OBJECT_TYPE_CONNECTION, &object, pdata);
+}
+
+int hc_connection_delete(hc_sock_t *s, hc_connection_t *connection) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.connection = *connection;
+ return hc_execute(s, ACTION_DELETE, OBJECT_TYPE_CONNECTION, &object, NULL);
+}
+
+int hc_connection_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_CONNECTION, NULL, pdata);
+}
+
+int hc_connection_set_admin_state(hc_sock_t *s, const char *conn_id_or_name,
+ face_state_t state) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ int rc = snprintf(object.connection.name, SYMBOLIC_NAME_LEN, "%s",
+ conn_id_or_name);
+ if (rc < 0 || rc >= SYMBOLIC_NAME_LEN) return -1;
+ object.connection.admin_state = state;
+ return hc_execute(s, ACTION_UPDATE, OBJECT_TYPE_CONNECTION, &object, NULL);
+}
+
+int hc_connection_set_priority(hc_sock_t *s, const char *conn_id_or_name,
+ uint32_t priority) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ int rc = snprintf(object.connection.name, SYMBOLIC_NAME_LEN, "%s",
+ conn_id_or_name);
+ if (rc < 0 || rc >= SYMBOLIC_NAME_LEN) return -1;
+ object.connection.priority = priority;
+ return hc_execute(s, ACTION_UPDATE, OBJECT_TYPE_CONNECTION, &object, NULL);
+}
+
+int hc_connection_set_tags(hc_sock_t *s, const char *conn_id_or_name,
+ policy_tags_t tags) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ int rc = snprintf(object.connection.name, SYMBOLIC_NAME_LEN, "%s",
+ conn_id_or_name);
+ if (rc < 0 || rc >= SYMBOLIC_NAME_LEN) return -1;
+ object.connection.tags = tags;
+ return hc_execute(s, ACTION_UPDATE, OBJECT_TYPE_CONNECTION, &object, NULL);
+}
+
+GENERATE_FIND(connection);
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_CONNECTION, connection);
diff --git a/hicn-light/src/hicn/core/connectionState.h b/ctrl/libhicnctrl/src/objects/connection.h
index 9daa15c9c..1e9bf0376 100644
--- a/hicn-light/src/hicn/core/connectionState.h
+++ b/ctrl/libhicnctrl/src/objects/connection.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,24 +14,19 @@
*/
/**
- * @file connection_state.h
- * @brief Represents the state of a connection
- *
+ * \file connection.h
+ * \brief Connection.
*/
-#ifndef connection_state_h
-#define connection_state_h
+#ifndef HICNCTRL_IMPL_OBJECTS_CONNECTION_H
+#define HICNCTRL_IMPL_OBJECTS_CONNECTION_H
+
+#include "../object_vft.h"
-#define foreach_connection_state \
- _(UNDEFINED) \
- _(DOWN) \
- _(UP) \
- _(N)
+bool hc_connection_is_local(const hc_connection_t *connection);
+bool hc_connection_has_local(const hc_connection_t *connection);
+bool hc_connection_has_valid_id(const hc_connection_t *connection);
-typedef enum {
-#define _(x) CONNECTION_STATE_ ## x,
-foreach_connection_state
-#undef _
-} connection_state_t;
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_CONNECTION, connection);
-#endif /* connection_state_h */
+#endif /* HICNCTRL_IMPL_OBJECTS_CONNECTION_H */
diff --git a/ctrl/libhicnctrl/src/objects/face.c b/ctrl/libhicnctrl/src/objects/face.c
new file mode 100644
index 000000000..5dbe1c8dc
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/face.c
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file face.c
+ * \brief Implementation of face object.
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/face.h>
+#include <hicn/util/log.h>
+
+#include "../object_private.h"
+#include "../object_vft.h"
+
+bool hc_face_has_netdevice(const hc_face_t *face) {
+ return netdevice_is_empty(&face->netdevice);
+}
+
+/* FACE VALIDATE */
+
+int hc_face_validate(const hc_face_t *face, bool allow_partial) {
+ if ((!allow_partial || !hc_face_has_netdevice(face)) &&
+ !IS_VALID_INTERFACE_NAME(face->interface_name)) {
+ ERROR("[hc_face_validate] Invalid interface_name specified");
+ return -1;
+ }
+ if (!IS_VALID_TYPE(face->type)) {
+ ERROR("[hc_face_validate] Invalid type specified");
+ return -1;
+ }
+ if ((!allow_partial || face->family != AF_UNSPEC) &&
+ !IS_VALID_FAMILY(face->family)) {
+ ERROR("[hc_face_validate] Invalid family specified");
+ return -1;
+ }
+ if ((!allow_partial || !hicn_ip_address_empty(&face->local_addr)) &&
+ !IS_VALID_ADDRESS(face->local_addr)) {
+ ERROR("[hc_face_validate] Invalid local_addr specified");
+ return -1;
+ }
+ if ((!allow_partial || !(face->local_port == 0)) &&
+ !IS_VALID_PORT(face->local_port)) {
+ ERROR("[hc_face_validate] Invalid local_port specified");
+ return -1;
+ }
+ if (!IS_VALID_ADDRESS(face->remote_addr)) {
+ ERROR("[hc_face_validate] Invalid remote_addr specified");
+ return -1;
+ }
+ if (!IS_VALID_PORT(face->remote_port)) {
+ ERROR("[hc_face_validate] Invalid remote_port specified");
+ return -1;
+ }
+ return 0;
+}
+
+int _hc_face_validate(const hc_object_t *object, bool allow_partial) {
+ return hc_face_validate(&object->face, allow_partial);
+}
+
+/* FACE CMP */
+
+int hc_face_cmp(const hc_face_t *c1, const hc_face_t *c2) {
+ return -99; // Not implemented
+}
+
+int _hc_face_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ return hc_face_cmp(&object1->face, &object2->face);
+}
+
+/* FACE SNPRINTF */
+
+/* /!\ Please update constants in header file upon changes */
+int hc_face_snprintf(char *s, size_t size, const hc_face_t *face) {
+ /* URLs are also big enough to contain IP addresses in the hICN case */
+ char local[MAXSZ_URL];
+ char remote[MAXSZ_URL];
+ char tags[MAXSZ_POLICY_TAGS];
+ int rc;
+
+ switch (face->type) {
+ case FACE_TYPE_HICN:
+ case FACE_TYPE_HICN_LISTENER:
+ rc = hicn_ip_address_snprintf(local, MAXSZ_URL, &face->local_addr);
+ if (rc >= MAXSZ_URL)
+ WARN("[hc_face_snprintf] Unexpected truncation of URL string");
+ if (rc < 0) return rc;
+ rc = hicn_ip_address_snprintf(remote, MAXSZ_URL, &face->remote_addr);
+ if (rc >= MAXSZ_URL)
+ WARN("[hc_face_snprintf] Unexpected truncation of URL string");
+ if (rc < 0) return rc;
+ break;
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_UDP:
+ case FACE_TYPE_TCP_LISTENER:
+ case FACE_TYPE_UDP_LISTENER:
+ rc = url_snprintf(local, MAXSZ_URL, &face->local_addr, face->local_port);
+ if (rc >= MAXSZ_URL)
+ WARN("[hc_face_snprintf] Unexpected truncation of URL string");
+ if (rc < 0) return rc;
+ rc = url_snprintf(remote, MAXSZ_URL, &face->remote_addr,
+ face->remote_port);
+ if (rc >= MAXSZ_URL)
+ WARN("[hc_face_snprintf] Unexpected truncation of URL string");
+ if (rc < 0) return rc;
+ break;
+ default:
+ return -1;
+ }
+
+ // [#ID NAME] TYPE LOCAL_URL REMOTE_URL STATE/ADMIN_STATE (TAGS)
+ rc = policy_tags_snprintf(tags, MAXSZ_POLICY_TAGS, face->tags);
+ if (rc >= MAXSZ_POLICY_TAGS)
+ WARN("[hc_face_snprintf] Unexpected truncation of policy tags string");
+ if (rc < 0) return rc;
+
+ return snprintf(
+ s, size, "[#%d %s] %s %s %s %s %s/%s [%d] (%s)", face->id, face->name,
+ face->netdevice.index != NETDEVICE_UNDEFINED_INDEX ? face->netdevice.name
+ : "*",
+ face_type_str(face->type), local, remote, face_state_str(face->state),
+ face_state_str(face->admin_state), face->priority, tags);
+}
+
+int _hc_face_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_face_snprintf(s, size, &object->face);
+}
+
+int hc_face_create(hc_sock_t *s, hc_face_t *face) {
+ int rc;
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.face = *face;
+ rc = hc_execute(s, ACTION_CREATE, OBJECT_TYPE_FACE, &object, NULL);
+ face->id = object.face.id;
+ return rc;
+}
+
+int hc_face_get(hc_sock_t *s, hc_face_t *face, hc_data_t **pdata) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.face = *face;
+ return hc_execute(s, ACTION_GET, OBJECT_TYPE_FACE, &object, pdata);
+}
+
+int hc_face_delete(hc_sock_t *s, hc_face_t *face) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.face = *face;
+ return hc_execute(s, ACTION_DELETE, OBJECT_TYPE_FACE, &object, NULL);
+}
+
+int hc_face_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_FACE, NULL, pdata);
+}
+
+int hc_face_list_async(hc_sock_t *s) {
+ return hc_execute_async(s, ACTION_LIST, OBJECT_TYPE_FACE, NULL, NULL, NULL);
+}
+
+int hc_face_set_priority(hc_sock_t *s, const char *conn_id_or_name,
+ uint32_t priority) {
+ return -1; // Not implemented
+#if 0
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ return hc_execute(s, ACTION_UPDATE, OBJECT_TYPE_FACE, &object, NULL);
+#endif
+}
+
+GENERATE_FIND(face);
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_FACE, face);
diff --git a/ctrl/libhicnctrl/src/objects/face.h b/ctrl/libhicnctrl/src/objects/face.h
new file mode 100644
index 000000000..08f90f195
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/face.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file face.h
+ * \brief Face.
+ */
+
+#ifndef HICNCTRL_IMPL_OBJECTS_FACE_H
+#define HICNCTRL_IMPL_OBJECTS_FACE_H
+
+#include "../object_vft.h"
+
+int hc_face_validate(const hc_face_t *face, bool allow_partial);
+
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_FACE, face);
+
+#endif /* HICNCTRL_IMPL_OBJECTS_FACE_H */
diff --git a/ctrl/libhicnctrl/src/objects/listener.c b/ctrl/libhicnctrl/src/objects/listener.c
new file mode 100644
index 000000000..97a2430d8
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/listener.c
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file listener.c
+ * \brief Implementation of listener.
+ */
+
+#include <string.h>
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/listener.h>
+#include <hicn/util/log.h>
+
+#include "../object_vft.h"
+#include "../object_private.h"
+#include "base.h"
+
+bool hc_listener_is_local(const hc_listener_t *listener) {
+ return (strncmp(listener->interface_name, "lo", INTERFACE_LEN) == 0);
+}
+
+/* LISTENER VALIDATE */
+
+int hc_listener_validate(const hc_listener_t *listener, bool allow_partial) {
+ // if a field is specified it should be valid
+ // then we allow different specification, by key or by attributes, if
+ // allow_partial
+
+ int has_id = 0;
+ int has_name = 0;
+#if 0
+ int has_interface_name = 0;
+#endif
+ int has_type = 0;
+ int has_family = 0;
+ int has_local_addr = 0;
+ int has_local_port = 0;
+
+ if (listener->id == ~0) {
+ ERROR("[hc_listener_validate] Invalid id specified");
+ return -1;
+ }
+ has_id = 1;
+
+ if (!isempty(listener->name)) {
+ if (!IS_VALID_NAME(listener->name)) {
+ ERROR("[hc_listener_validate] Invalid name specified");
+ return -1;
+ }
+ has_name = 1;
+ }
+
+#if 0
+ if (!isempty(listener->interface_name)) {
+ if (!IS_VALID_INTERFACE_NAME(listener->interface_name)) {
+ ERROR("[hc_listener_validate] Invalid interface_name specified");
+ return -1;
+ }
+ has_interface_name = 1;
+ }
+#endif
+
+ if (listener->type != FACE_TYPE_UNDEFINED) {
+ if (!IS_VALID_TYPE(listener->type)) {
+ ERROR("[hc_listener_validate] Invalid type specified");
+ return -1;
+ }
+ has_type = 1;
+ }
+
+ if (listener->family != AF_UNSPEC) {
+ if (!IS_VALID_FAMILY(listener->family)) {
+ ERROR("[hc_listener_validat] Invalid family specified");
+ return -1;
+ }
+ has_family = 1;
+ }
+
+ if (!hicn_ip_address_empty(&listener->local_addr)) {
+ if (!IS_VALID_ADDRESS(listener->local_addr)) {
+ ERROR("[hc_listener_validate] Invalid local_addr specified");
+ return -1;
+ }
+ has_local_addr = 1;
+ }
+
+ if (listener->local_port != 0) {
+ if (!IS_VALID_PORT(listener->local_port)) {
+ ERROR("[hc_listener_validate] Invalid local_port specified");
+ return -1;
+ }
+ has_local_port = 1;
+ }
+
+ if (allow_partial) {
+ if ((has_id || has_name) && !has_type && !has_family && !has_local_port &&
+ !has_local_port)
+ return 0;
+ else if (has_name && has_type && has_family && has_local_addr &&
+ has_local_port)
+ return 0;
+ else
+ return -1;
+ } else {
+ /* name and interface are optional */
+ if (has_id && has_type && has_family && has_local_addr && has_local_port)
+ return 0;
+ return -1;
+ }
+}
+
+int _hc_listener_validate(const hc_object_t *object, bool allow_partial) {
+ return hc_listener_validate(&object->listener, allow_partial);
+}
+
+/* LISTENER CMP */
+
+int hc_listener_cmp(const hc_listener_t *l1, const hc_listener_t *l2) {
+ int rc;
+
+ rc = INT_CMP(l1->type, l2->type);
+ if (rc != 0) return rc;
+
+ rc = INT_CMP(l1->family, l2->family);
+ if (rc != 0) return rc;
+
+ if (!isempty(l1->interface_name) && !isempty(l2->interface_name)) {
+ rc = strncmp(l1->interface_name, l2->interface_name, INTERFACE_LEN);
+ if (rc != 0) return rc;
+ }
+
+ rc = hicn_ip_address_cmp(&l1->local_addr, &l2->local_addr);
+ if (rc != 0) return rc;
+
+ rc = INT_CMP(l1->local_port, l2->local_port);
+ if (rc != 0) return rc;
+
+ return 0;
+}
+
+int _hc_listener_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ return hc_listener_cmp(&object1->listener, &object2->listener);
+}
+
+/* LISTENER SNPRINTF */
+
+/* /!\ Please update constants in header file upon changes */
+int hc_listener_snprintf(char *s, size_t size, const hc_listener_t *listener) {
+ char local[MAXSZ_URL];
+ int rc;
+ rc = url_snprintf(local, MAXSZ_URL, &listener->local_addr,
+ listener->local_port);
+ if (rc >= MAXSZ_URL)
+ WARN("[hc_listener_snprintf] Unexpected truncation of URL string");
+ if (rc < 0) return rc;
+
+ return snprintf(s, size, "%s %s %s interface=%s", listener->name, local,
+ face_type_str(listener->type), listener->interface_name);
+}
+
+int _hc_listener_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_listener_snprintf(s, size, &object->listener);
+}
+
+/* OPERATIONS */
+
+int hc_listener_create(hc_sock_t *s, hc_listener_t *listener) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.listener = *listener;
+ return hc_execute(s, ACTION_CREATE, OBJECT_TYPE_LISTENER, &object, NULL);
+}
+
+int hc_listener_get(hc_sock_t *s, hc_listener_t *listener, hc_data_t **pdata) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.listener = *listener;
+ return hc_execute(s, ACTION_GET, OBJECT_TYPE_LISTENER, &object, pdata);
+}
+
+int hc_listener_delete(hc_sock_t *s, hc_listener_t *listener) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.listener = *listener;
+ return hc_execute(s, ACTION_DELETE, OBJECT_TYPE_LISTENER, &object, NULL);
+}
+
+int hc_listener_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_LISTENER, NULL, pdata);
+}
+
+GENERATE_FIND(listener);
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_LISTENER, listener);
diff --git a/ctrl/libhicnctrl/src/objects/listener.h b/ctrl/libhicnctrl/src/objects/listener.h
new file mode 100644
index 000000000..515c8f0ad
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/listener.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file listener.h
+ * \brief Listener.
+ */
+
+#ifndef HICNCTRL_IMPL_OBJECTS_LISTENER_H
+#define HICNCTRL_IMPL_OBJECTS_LISTENER_H
+
+#include "../object_vft.h"
+
+bool hc_listener_is_local(const hc_listener_t *listener);
+
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_LISTENER, listener);
+
+#endif /* HICNCTRL_IMPL_OBJECTS_LISTENER_H */
diff --git a/ctrl/libhicnctrl/src/objects/mapme.c b/ctrl/libhicnctrl/src/objects/mapme.c
new file mode 100644
index 000000000..1acdcb35a
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/mapme.c
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file mapme.c
+ * \brief Implementation of mapme object.
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/mapme.h>
+#include <hicn/util/log.h>
+
+#include "../object_private.h"
+#include "../object_vft.h"
+#include "face.h"
+#include "base.h"
+
+/* MAPME VALIDATE */
+
+int hc_mapme_validate(const hc_mapme_t *mapme, bool allow_partial) {
+ int has_family = 0;
+ int has_address = 0;
+ int has_len = 0;
+
+ if (allow_partial) return 0;
+
+ if (mapme->family != AF_UNSPEC) {
+ if (!IS_VALID_FAMILY(mapme->family)) {
+ ERROR("[hc_mapme_validate] Invalid family specified");
+ return -1;
+ }
+ has_family = 1;
+ }
+
+ if (!hicn_ip_address_empty(&mapme->address)) {
+ if (!IS_VALID_ADDRESS(mapme->address)) {
+ ERROR("[hc_mapme_validate] Invalid remote_addr specified");
+ return -1;
+ }
+ has_address = 1;
+ }
+
+ if (!IS_VALID_PREFIX_LEN(mapme->len)) {
+ ERROR("[hc_mapme_validate] Invalid len");
+ return -1;
+ }
+ has_len = 1;
+ return has_family && has_address && has_len;
+}
+
+int _hc_mapme_validate(const hc_object_t *object, bool allow_partial) {
+ return hc_mapme_validate(&object->mapme, allow_partial);
+}
+
+/* MAPME CMP */
+
+int hc_mapme_cmp(const hc_mapme_t *mapme1, const hc_mapme_t *mapme2) {
+ return -1;
+}
+
+int _hc_mapme_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ return -1;
+}
+
+/* MAPME SNPRINTF */
+
+int hc_mapme_snprintf(char *s, size_t size, const hc_mapme_t *mapme) {
+ return -1;
+}
+
+int _hc_mapme_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return -1;
+}
+
+int hc_mapme_create(hc_sock_t *s, hc_mapme_t *mapme) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.mapme = *mapme;
+ return hc_execute(s, ACTION_CREATE, OBJECT_TYPE_MAPME, &object, NULL);
+}
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_MAPME, mapme);
diff --git a/ctrl/libhicnctrl/src/objects/mapme.h b/ctrl/libhicnctrl/src/objects/mapme.h
new file mode 100644
index 000000000..488f97cd5
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/mapme.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file mapme.h
+ * \brief Route.
+ */
+
+#ifndef HICNCTRL_IMPL_OBJECTS_MAPME_H
+#define HICNCTRL_IMPL_OBJECTS_MAPME_H
+
+#include "../object_vft.h"
+
+bool hc_mapme_has_face(const hc_mapme_t* mapme);
+
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_MAPME, mapme);
+
+#endif /* HICNCTRL_IMPL_OBJECTS_MAPME_H */
diff --git a/ctrl/libhicnctrl/src/objects/route.c b/ctrl/libhicnctrl/src/objects/route.c
new file mode 100644
index 000000000..4bdaa0afb
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/route.c
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file route.c
+ * \brief Implementation of route object.
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/route.h>
+#include <hicn/util/log.h>
+
+#include "../object_private.h"
+#include "../object_vft.h"
+#include "face.h"
+#include "base.h"
+
+bool hc_route_has_face(const hc_route_t *route) {
+ return !iszero(&route->face, sizeof(hc_face_t));
+}
+
+/* ROUTE VALIDATE */
+
+int hc_route_validate(const hc_route_t *route, bool allow_partial) {
+ int has_id = 0;
+ int has_name = 0;
+ int has_face = 0;
+
+ int has_family = 0;
+ int has_remote_addr = 0;
+
+ if (IS_VALID_CONNECTION_ID(route->face_id)) {
+ has_id = 1;
+ }
+
+ if (!isempty(route->face_name)) {
+ if (!IS_VALID_NAME(route->face_name)) {
+ ERROR("[hc_route_validate] Invalid name specified");
+ return -1;
+ }
+ has_name = 1;
+ }
+
+ if (route->family != AF_UNSPEC) {
+ if (!IS_VALID_FAMILY(route->family)) {
+ ERROR("[hc_route_validate] Invalid family specified");
+ return -1;
+ }
+ has_family = 1;
+ }
+
+ //::/0 is a valid remote addr
+#if 0
+ if (!hicn_ip_address_empty(&route->remote_addr)) {
+ if (!IS_VALID_ADDRESS(route->remote_addr)) {
+ ERROR("[hc_route_validate] Invalid remote_addr specified");
+ return -1;
+ }
+ has_remote_addr = 1;
+ }
+#else
+ has_remote_addr = 1;
+#endif
+
+ if (!IS_VALID_ROUTE_COST(route->cost)) {
+ ERROR("[hc_route_validate] Invalid cost");
+ return -1;
+ }
+
+#if 0
+ if (!IS_VALID_PREFIX_LEN(route->len)) {
+ ERROR("[hc_route_validate] Invalid len");
+ return -1;
+ }
+#endif
+
+ if (hc_route_has_face(route)) {
+ if (hc_face_validate(&route->face, allow_partial) < 0) {
+ ERROR("[hc_route_validate] Invalid face");
+ return -1;
+ }
+ has_face = 1;
+ }
+
+ /* We also allow routes without faces, hence the '>' sign */
+ if (allow_partial && (has_id + has_name + has_face > 1)) return -1;
+ // if (has_face_info && has_family && has_remote_addr) return 0;
+ if (has_family && has_remote_addr) return 0;
+
+ return -1;
+}
+
+int _hc_route_validate(const hc_object_t *object, bool allow_partial) {
+ return hc_route_validate(&object->route, allow_partial);
+}
+
+/* ROUTE CMP */
+
+// XXX TODO
+int hc_route_cmp(const hc_route_t *route1, const hc_route_t *route2) {
+ return -1;
+}
+
+int _hc_route_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ return hc_route_cmp(&object1->route, &object2->route);
+}
+
+/* ROUTE SNPRINTF */
+
+/* /!\ Please update constants in header file upon changes */
+int hc_route_snprintf(char *s, size_t size, const hc_route_t *route) {
+ /* interface cost prefix length */
+
+ char prefix[MAXSZ_IP_ADDRESS];
+ int rc;
+
+ rc = hicn_ip_address_snprintf(prefix, MAXSZ_IP_ADDRESS, &route->remote_addr);
+ if (rc >= MAXSZ_IP_ADDRESS)
+ ;
+ if (rc < 0) return rc;
+
+ return snprintf(s, size, "%d (%s) %*d %s %*d", route->face_id,
+ route->face_name, MAXSZ_COST, route->cost, prefix, MAXSZ_LEN,
+ route->len);
+}
+
+int _hc_route_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_route_snprintf(s, size, &object->route);
+}
+
+int hc_route_create(hc_sock_t *s, hc_route_t *route) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.route = *route;
+ return hc_execute(s, ACTION_CREATE, OBJECT_TYPE_ROUTE, &object, NULL);
+}
+
+int hc_route_get(hc_sock_t *s, hc_route_t *route, hc_data_t **pdata) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.route = *route;
+ return hc_execute(s, ACTION_GET, OBJECT_TYPE_ROUTE, &object, pdata);
+}
+
+int hc_route_delete(hc_sock_t *s, hc_route_t *route) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.route = *route;
+ return hc_execute(s, ACTION_DELETE, OBJECT_TYPE_ROUTE, &object, NULL);
+}
+
+int hc_route_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_ROUTE, NULL, pdata);
+}
+
+int hc_route_list_async(hc_sock_t *s) {
+ return hc_execute_async(s, ACTION_LIST, OBJECT_TYPE_ROUTE, NULL, NULL, NULL);
+}
+
+// XXX difference between GET and FIND
+GENERATE_FIND(route);
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_ROUTE, route);
diff --git a/ctrl/libhicnctrl/src/objects/route.h b/ctrl/libhicnctrl/src/objects/route.h
new file mode 100644
index 000000000..854bd70a6
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/route.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file route.h
+ * \brief Route.
+ */
+
+#ifndef HICNCTRL_IMPL_OBJECTS_ROUTE_H
+#define HICNCTRL_IMPL_OBJECTS_ROUTE_H
+
+#include "../object_vft.h"
+
+bool hc_route_has_face(const hc_route_t* route);
+
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_ROUTE, route);
+
+#endif /* HICNCTRL_IMPL_OBJECTS_ROUTE_H */
diff --git a/ctrl/libhicnctrl/src/objects/stats.c b/ctrl/libhicnctrl/src/objects/stats.c
new file mode 100644
index 000000000..f9d0e1de7
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/stats.c
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file stats.c
+ * \brief Implementation of stats.
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/util/log.h>
+
+#include "../object_vft.h"
+
+/* GENERAL STATS */
+
+int _hc_stats_validate(const hc_object_t *object, bool allow_partial) {
+ // Nothing to validate
+ return 0;
+}
+
+int _hc_stats_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ ERROR("[_hc_stats_cmp] Not implemented");
+ return -1;
+}
+
+int _hc_stats_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_stats_snprintf(s, size, &object->stats);
+}
+
+int hc_stats_snprintf(char *s, size_t size, const hc_stats_t *stats) {
+ return snprintf(
+ s, size,
+ "*** STATS ***\nreceived = %u (interest = %u, data = %u)\ndropped = %u "
+ "(interest = %u, data = %u, other = %u)\nforwarded = { interests = "
+ "%u, data = %u }\ndropped_reason = { connection_not_found = %u, "
+ "send_failure = %u, no_route_in_fib = %u }\ninterest processing = { "
+ "aggregated = %u, retransmitted = %u, satisfied_from_cs = %u, "
+ "expired_interests = %u, expired_data = %u }\ndata processing = { "
+ "no_reverse_path = %u }\npacket cache = {PIT size = %u, CS size = %u, "
+ "eviction = %u}",
+ stats->forwarder.countReceived, stats->forwarder.countInterestsReceived,
+ stats->forwarder.countObjectsReceived, stats->forwarder.countDropped,
+ stats->forwarder.countInterestsDropped,
+ stats->forwarder.countObjectsDropped, stats->forwarder.countOtherDropped,
+ stats->forwarder.countInterestForwarded,
+ stats->forwarder.countObjectsForwarded,
+ stats->forwarder.countDroppedConnectionNotFound,
+ stats->forwarder.countSendFailures, stats->forwarder.countDroppedNoRoute,
+ stats->forwarder.countInterestsAggregated,
+ stats->forwarder.countInterestsRetransmitted,
+ stats->forwarder.countInterestsSatisfiedFromStore,
+ stats->forwarder.countInterestsExpired, stats->forwarder.countDataExpired,
+ stats->forwarder.countDroppedNoReversePath,
+ stats->pkt_cache.n_pit_entries, stats->pkt_cache.n_cs_entries,
+ stats->pkt_cache.n_lru_evictions);
+}
+
+int hc_stats_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_STATS, NULL, pdata);
+}
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_STATS, stats);
+
+/* PER-FACE STATS */
+
+int _hc_face_stats_validate(const hc_object_t *object, bool allow_partial) {
+ // Nothing to validate
+ return 0;
+}
+
+int _hc_face_stats_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ ERROR("[_hc_stats_cmp] Not implemented");
+ return -1;
+}
+
+int _hc_face_stats_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_face_stats_snprintf(s, size, &object->face_stats);
+}
+
+int hc_face_stats_snprintf(char *s, size_t size, const hc_face_stats_t *stats) {
+ return snprintf(
+ s, size,
+ "conn #%u:\tinterests =\t{ rx packets = %u, rx bytes = %u, "
+ "tx packets = %u, tx bytes = %u }\n\t\tdata =\t\t{ rx packets "
+ "= %u, rx bytes = %u, "
+ "tx packets = %u, tx bytes = %u }",
+ stats->conn_id, stats->interests.rx_pkts, stats->interests.rx_bytes,
+ stats->interests.tx_pkts, stats->interests.tx_bytes, stats->data.rx_pkts,
+ stats->data.rx_bytes, stats->data.tx_pkts, stats->data.tx_bytes);
+}
+
+int hc_face_stats_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_FACE_STATS, NULL, pdata);
+}
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_FACE_STATS, face_stats); \ No newline at end of file
diff --git a/ctrl/libhicnctrl/src/objects/stats.h b/ctrl/libhicnctrl/src/objects/stats.h
new file mode 100644
index 000000000..3a4f04b2e
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/stats.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file stats.h
+ * \brief Stats.
+ */
+
+#ifndef HICNCTRL_IMPL_OBJECTS_STATS_H
+#define HICNCTRL_IMPL_OBJECTS_STATS_H
+
+#include "../object_vft.h"
+
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_STATS, stats);
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_FACE_STATS, face_stats);
+
+#endif /* HICNCTRL_IMPL_OBJECTS_STATS_H */ \ No newline at end of file
diff --git a/ctrl/libhicnctrl/src/objects/strategy.c b/ctrl/libhicnctrl/src/objects/strategy.c
new file mode 100644
index 000000000..0e7a5787e
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/strategy.c
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file strategy.c
+ * \brief Implementation of strategy.
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/strategy.h>
+#include <hicn/util/log.h>
+
+#include "../object_vft.h"
+#include "../object_private.h"
+
+/* STREATEGY VALIDATE */
+
+int hc_strategy_validate(const hc_strategy_t *strategy, bool allow_partial) {
+ // TODO verify name
+ return 0;
+}
+
+int _hc_strategy_validate(const hc_object_t *object, bool allow_partial) {
+ return hc_strategy_validate(&object->strategy, allow_partial);
+}
+
+/* STRATEGY CMP */
+
+int hc_strategy_cmp(const hc_strategy_t *s1, const hc_strategy_t *s2) {
+ return strcmp(s1->name, s2->name);
+}
+
+int _hc_strategy_cmp(const hc_object_t *object1, const hc_object_t *object2) {
+ return hc_strategy_cmp(&object1->strategy, &object2->strategy);
+}
+
+/* STRATEGY SNPRINTF */
+
+/* /!\ Please update constants in header file upon changes */
+int hc_strategy_snprintf(char *s, size_t size, const hc_strategy_t *strategy) {
+ return snprintf(s, size, "%s", strategy->name);
+}
+
+int _hc_strategy_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_strategy_snprintf(s, size, &object->strategy);
+}
+
+/* OPERATIONS */
+
+int hc_strategy_create(hc_sock_t *s, hc_strategy_t *strategy) { return -1; }
+
+int hc_strategy_get(hc_sock_t *s, hc_strategy_t *strategy, hc_data_t **pdata) {
+ return -1;
+}
+
+int hc_strategy_delete(hc_sock_t *s, hc_strategy_t *strategy) { return -1; }
+
+int hc_strategy_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_STRATEGY, NULL, pdata);
+}
+
+/* new api */
+
+int hc_strategy_set(hc_sock_t *s, hc_strategy_t *strategy) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.strategy = *strategy;
+ return hc_execute(s, ACTION_SET, OBJECT_TYPE_STRATEGY, &object, NULL);
+}
+
+#if 0
+int hc_strategy_add_local_prefix(hc_sock_t *s, hc_strategy_t *strategy) {
+ return s->hc_strategy_add_local_prefix(s, strategy);
+}
+#endif
+
+GENERATE_FIND(strategy);
+
+DECLARE_OBJECT_OPS(OBJECT_TYPE_STRATEGY, strategy);
diff --git a/ctrl/libhicnctrl/src/objects/strategy.h b/ctrl/libhicnctrl/src/objects/strategy.h
new file mode 100644
index 000000000..0cc4f525d
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/strategy.h
@@ -0,0 +1,29 @@
+
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file listener.h
+ * \brief Listener.
+ */
+
+#ifndef HICNCTRL_IMPL_OBJECTS_STRATEGY_H
+#define HICNCTRL_IMPL_OBJECTS_STRATEGY_H
+
+#include "../object_vft.h"
+
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_STRATEGY, strategy);
+
+#endif /* HICNCTRL_IMPL_OBJECTS_STRATEGY_H */
diff --git a/ctrl/libhicnctrl/src/objects/subscription.c b/ctrl/libhicnctrl/src/objects/subscription.c
new file mode 100644
index 000000000..8db55660d
--- /dev/null
+++ b/ctrl/libhicnctrl/src/objects/subscription.c
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file subscription.c
+ * \brief Implementation of subscription.
+ */
+
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/subscription.h>
+#include <hicn/util/log.h>
+
+#include "../object_vft.h"
+#include "../object_private.h"
+
+/* SUBSCRIPTION VALIDATE */
+
+int hc_subscription_validate(const hc_subscription_t *subscription,
+ bool allow_partial) {
+ /* Any topic is considered valid */
+ return 0;
+}
+
+int _hc_subscription_validate(const hc_object_t *object, bool allow_partial) {
+ return hc_subscription_validate(&object->subscription, allow_partial);
+}
+
+/* LISTENER CMP */
+
+int hc_subscription_cmp(const hc_subscription_t *l1,
+ const hc_subscription_t *l2) {
+ return -1;
+}
+
+int _hc_subscription_cmp(const hc_object_t *object1,
+ const hc_object_t *object2) {
+ return hc_subscription_cmp(&object1->subscription, &object2->subscription);
+}
+
+/* SUBSCRIPTION SNPRINTF */
+
+/* /!\ Please update constants in header file upon changes */
+int hc_subscription_snprintf(char *s, size_t size,
+ const hc_subscription_t *subscription) {
+ return -99; /* Not implemented */
+}
+
+int _hc_subscription_snprintf(char *s, size_t size, const hc_object_t *object) {
+ return hc_subscription_snprintf(s, size, &object->subscription);
+}
+
+/* OPERATIONS */
+
+int hc_subscription_create(hc_sock_t *s, hc_subscription_t *subscription) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.subscription = *subscription;
+ return hc_execute(s, ACTION_CREATE, OBJECT_TYPE_SUBSCRIPTION, &object, NULL);
+}
+
+int hc_subscription_get(hc_sock_t *s, hc_subscription_t *subscription,
+ hc_data_t **pdata) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.subscription = *subscription;
+ return hc_execute(s, ACTION_GET, OBJECT_TYPE_SUBSCRIPTION, &object, pdata);
+}
+
+int hc_subscription_delete(hc_sock_t *s, hc_subscription_t *subscription) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+ object.subscription = *subscription;
+ return hc_execute(s, ACTION_DELETE, OBJECT_TYPE_SUBSCRIPTION, &object, NULL);
+}
+
+int hc_subscription_list(hc_sock_t *s, hc_data_t **pdata) {
+ return hc_execute(s, ACTION_LIST, OBJECT_TYPE_SUBSCRIPTION, NULL, pdata);
+}
+
+GENERATE_FIND(subscription);
+DECLARE_OBJECT_OPS(OBJECT_TYPE_SUBSCRIPTION, subscription);
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.h b/ctrl/libhicnctrl/src/objects/subscription.h
index 16f65e5c4..6eb7583c6 100644
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.h
+++ b/ctrl/libhicnctrl/src/objects/subscription.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,13 +13,16 @@
* limitations under the License.
*/
-#ifndef __HICN_LIGHT_H__
-#define __HICN_LIGHT_H__
+/**
+ * \file subscription.h
+ * \brief Listener.
+ */
+
+#ifndef HICNCTRL_IMPL_OBJECTS_SUBSCRIPTION_H
+#define HICNCTRL_IMPL_OBJECTS_SUBSCRIPTION_H
-#include "hicn_light_comm.h"
+#include "../object_vft.h"
-// functions that sysrepo-plugin need
-int sr_plugin_init_cb(sr_session_ctx_t *session, void **private_ctx);
-void sr_plugin_cleanup_cb(sr_session_ctx_t *session, void *private_ctx);
+DECLARE_OBJECT_OPS_H(OBJECT_TYPE_SUBSCRIPTION, subscription);
-#endif //__HICN_LIGHT_H__ \ No newline at end of file
+#endif /* HICNCTRL_IMPL_OBJECTS_SUBSCRIPTION_H */
diff --git a/ctrl/libhicnctrl/src/parse.c b/ctrl/libhicnctrl/src/parse.c
new file mode 100644
index 000000000..25fa98de2
--- /dev/null
+++ b/ctrl/libhicnctrl/src/parse.c
@@ -0,0 +1,412 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <limits.h>
+
+//#include <hicn/ctrl/cli.h>
+#include <hicn/ctrl/action.h>
+#include <hicn/util/log.h>
+#include <hicn/util/sstrncpy.h>
+#include <hicn/ctrl/parse.h>
+
+/*
+ * As there is no portable way to generate a va_list to use with sscanf to
+ * support a variable number of arguments, and no way to use a variable array
+ * initialize in a nested struct, we use a fixed maximum number of parameters
+ *
+ * NOTE: update sscanf accordingly
+ */
+
+//#include "command.h"
+
+const char *action_to_cmd_action(hc_action_t action) {
+ switch (action) {
+ case ACTION_CREATE:
+ return "add";
+ case ACTION_UPDATE:
+ return "update";
+ case ACTION_DELETE:
+ return "remove";
+ case ACTION_LIST:
+ return "list";
+ case ACTION_SET:
+ return "set";
+ case ACTION_SERVE:
+ return "serve";
+ case ACTION_STORE:
+ return "store";
+ case ACTION_CLEAR:
+ return "clear";
+ default:
+ return "UNDEFINED";
+ }
+}
+
+/*
+ * This function now assumes all parameteres in src are received as string
+ */
+int parser_type_func(const parser_type_t *type, const char *src, void *dst,
+ void *dst2, void *dst3) {
+ hicn_ip_address_t addr;
+ char *addr_str;
+ char *len_str;
+ int len, rc;
+ long tmp;
+
+ switch (type->name) {
+ case TYPENAME_INT:
+ tmp = strtol(src, NULL, 10);
+ if ((tmp < INT32_MIN) || (tmp > INT32_MAX)) {
+ ERROR("Input number (%d) not matching type 'signed integer'", tmp);
+ return -1;
+ }
+ if ((tmp < type->integer.min) || (tmp > type->integer.max)) {
+ ERROR("Input number (%d) not inside range [%d, %d]", tmp,
+ type->integer.min, type->integer.max);
+ return -1;
+ }
+ if (tmp > INT_MAX) return -1;
+ *(int *)dst = (int)tmp;
+ break;
+ case TYPENAME_UINT:
+ tmp = strtol(src, NULL, 10);
+ if ((tmp < 0) || (tmp > UINT32_MAX)) {
+ ERROR("Input number (%d) not matching type 'signed integer'", tmp);
+ return -1;
+ }
+ if ((tmp < type->integer.min) || (tmp > type->integer.max)) {
+ ERROR("Input number (%d) not inside range [%d, %d]", tmp,
+ type->integer.min, type->integer.max);
+ return -1;
+ }
+ if (tmp > UINT_MAX) return -1;
+ *(unsigned *)dst = (unsigned)tmp;
+ break;
+ case TYPENAME_INT16:
+ tmp = strtol(src, NULL, 10);
+ if ((tmp < INT16_MIN) || (tmp > INT16_MAX)) {
+ ERROR("Input number (%d) not matching type 'signed integer'", tmp);
+ return -1;
+ }
+ if ((tmp < type->integer.min) || (tmp > type->integer.max)) {
+ ERROR("Input number (%d) not inside range [%d, %d]", tmp,
+ type->integer.min, type->integer.max);
+ return -1;
+ }
+ *(int16_t *)dst = tmp;
+ break;
+ case TYPENAME_UINT16:
+ tmp = strtol(src, NULL, 10);
+ if ((tmp < 0) || (tmp > UINT16_MAX)) {
+ ERROR("Input number (%d) not matching type 'signed integer'", tmp);
+ return -1;
+ }
+ if ((tmp < type->integer.min) || (tmp > type->integer.max)) {
+ ERROR("Input number (%d) not inside range [%d, %d]", tmp,
+ type->integer.min, type->integer.max);
+ return -1;
+ }
+ *(uint16_t *)dst = tmp;
+ break;
+ case TYPENAME_STR:
+ rc = strcpy_s(dst, type->str.max_size, src);
+ if (rc != EOK) {
+ ERROR("Input string is too long");
+ return -1;
+ }
+ break;
+ case TYPENAME_IP_ADDRESS:
+ rc = hicn_ip_address_pton((char *)src, &addr);
+ if (rc < 0) {
+ ERROR("Wrong IP address format");
+ return -1;
+ }
+
+ *(hicn_ip_address_t *)dst = addr;
+ *(int *)dst2 = hicn_ip_address_str_get_family((char *)src);
+ break;
+ case TYPENAME_ON_OFF:
+ if (strcmp((char *)src, "off") == 0) {
+ *(unsigned *)dst = 0;
+ } else if (strcmp((char *)src, "on") == 0) {
+ *(unsigned *)dst = 1;
+ } else {
+ ERROR("on/off are the only possible values");
+ return -1;
+ }
+ break;
+ case TYPENAME_IP_PREFIX:
+ addr_str = strtok((char *)src, "/");
+ len_str = strtok(NULL, " ");
+ rc = hicn_ip_address_pton((char *)src, &addr);
+ if (rc < 0) {
+ ERROR("Wrong IP address format");
+ return -1;
+ }
+ len = atoi(len_str);
+
+ *(hicn_ip_address_t *)dst = addr;
+ *(int *)dst2 = len;
+ *(int *)dst3 = hicn_ip_address_str_get_family(addr_str);
+ break;
+ case TYPENAME_ENUM:
+ /* Enum index from string */
+ assert(type->enum_.from_str);
+ *(int *)dst = type->enum_.from_str((char *)src);
+ break;
+ case TYPENAME_POLICY_STATE: {
+ assert(IS_VALID_POLICY_TAG(type->policy_state.tag));
+ policy_tag_t tag = type->policy_state.tag;
+ /* Format string is "%ms" */
+ const char *str = *(const char **)src;
+ policy_tag_state_t *pts = ((policy_tag_state_t *)dst);
+ pts[tag].disabled = (str[0] == '!') ? 1 : 0;
+ pts[tag].state = policy_state_from_str(str + pts[tag].disabled);
+ break;
+ }
+ case TYPENAME_UNDEFINED:
+ default:
+ ERROR("Unknown format");
+ return -1;
+ }
+ return 0;
+}
+
+// NEW FUNCTION
+int parse_getopt_args(const command_parser_t *parser, int argc, char *argv[],
+ hc_command_t *command) {
+ /* Loop over remaining commandline positional arguments */
+ for (unsigned i = 0; i < argc; i++) {
+ const command_parameter_t *p = &parser->parameters[i];
+
+ if (parser_type_func(&p->type, argv[i],
+ &command->object.as_uint8 + p->offset,
+ &command->object.as_uint8 + p->offset2,
+ &command->object.as_uint8 + p->offset3) < 0) {
+ ERROR("Error during parsing of parameter '%s' value", p->name);
+ goto ERR;
+ }
+ }
+ if (parser->post_hook) parser->post_hook(&command->object.as_uint8);
+ return 0;
+
+ERR:
+ return -1;
+}
+
+/* Build a format string to parse all params as a string */
+int parse_params(const command_parser_t *parser, const char *params_s,
+ hc_command_t *command) {
+ char fmt[1024];
+ int n;
+ size_t size = 0;
+ char *pos = fmt;
+ /* Update MAX_PARAMETERS accordingly in command.h */
+ char sscanf_params[MAX_PARAMETERS][MAX_SCANF_PARAM_LEN];
+
+ unsigned count = 0;
+ for (unsigned i = 0; i < parser->nparams; i++) {
+ const char *_fmt = "%s";
+ n = snprintf(pos, 1024 - size, "%s", _fmt);
+ pos += n;
+
+ *pos = ' ';
+ pos++;
+
+ size += n + 1;
+ count++;
+ }
+ *pos = '\0';
+ DEBUG("parser format: %s", fmt);
+
+ int ret = sscanf(params_s, fmt, sscanf_params[0], sscanf_params[1],
+ sscanf_params[2], sscanf_params[3], sscanf_params[4],
+ sscanf_params[5], sscanf_params[6], sscanf_params[7],
+ sscanf_params[8], sscanf_params[9]);
+ if (ret != parser->nparams) {
+ ERROR("Parsing failed: check for string used where integer was expected");
+ goto ERR;
+ }
+
+ for (unsigned i = 0; i < count; i++) {
+ const command_parameter_t *p = &parser->parameters[i];
+ if (parser_type_func(&p->type, sscanf_params[i],
+ &command->object.as_uint8 + p->offset,
+ &command->object.as_uint8 + p->offset2,
+ &command->object.as_uint8 + p->offset3) < 0) {
+ ERROR("Error during parsing of parameter '%s' value", p->name);
+ goto ERR;
+ }
+ }
+ return 0;
+
+ERR:
+ return -1;
+}
+
+int parse(const char *cmd, hc_command_t *command) {
+ int nparams = 0;
+ char action_s[MAX_SCANF_PARAM_LEN];
+ char object_s[MAX_SCANF_PARAM_LEN];
+ char params_s[MAX_SCANF_PARAM_LEN];
+
+ // if n = 2 later, params_s is uninitialized
+ memset(params_s, 0, MAX_SCANF_PARAM_LEN * sizeof(char));
+
+ errno = 0;
+ int n = sscanf(cmd, "%s %s%[^\n]s", action_s, object_s, params_s);
+ if ((n < 2) || (n > 3)) {
+ if (errno != 0) perror("scanf");
+ return -1;
+ }
+
+ command->action = action_from_str(action_s);
+ command->object_type = object_type_from_str(object_s);
+
+ if (strnlen_s(params_s, MAX_SCANF_PARAM_LEN) > 0) {
+ for (char *ptr = params_s; (ptr = strchr(ptr, ' ')) != NULL; ptr++)
+ nparams++;
+ }
+
+ /*
+ * This checks is important even with 0 parameters as it checks whether the
+ * command exists.
+ */
+ const command_parser_t *parser =
+ command_search(command->action, command->object_type, nparams);
+ if (!parser) {
+ ERROR("Could not find parser for command '%s %s'", action_s, object_s);
+ return -1;
+ }
+
+ if (strnlen_s(params_s, MAX_SCANF_PARAM_LEN) > 0) {
+ if (parse_params(parser, params_s, command) < 0) return -1;
+ }
+
+ if (parser->post_hook) parser->post_hook(&command->object.as_uint8);
+ return 0;
+}
+
+int help(const char *cmd) {
+ int nparams = 1;
+ char action_s[MAX_SCANF_PARAM_LEN];
+ char object_s[MAX_SCANF_PARAM_LEN];
+ char params_s[MAX_SCANF_PARAM_LEN];
+ hc_object_type_t object_type = OBJECT_TYPE_UNDEFINED;
+ hc_action_t action = ACTION_UNDEFINED;
+
+ int n = sscanf(cmd, "help %[^\n]s", params_s);
+
+ // No arguments provided to the help command: just list available objects
+ if (n != 1) goto CMD_LIST;
+
+ // Count number of provided parameters
+ for (char *ptr = params_s; (ptr = strchr(ptr, ' ')) != NULL; ptr++) nparams++;
+ if (nparams > 2) {
+ fprintf(stderr, "Error: too many arguments.\n");
+ return -1;
+ }
+
+ // Object specified: list actions available for that object
+ if (nparams == 1) {
+ object_type = object_type_from_str(params_s);
+ if (object_type == OBJECT_TYPE_UNDEFINED) {
+ fprintf(stderr, "Error: undefined object type.\n");
+ return -1;
+ }
+
+ goto CMD_LIST;
+ }
+
+ // Object and action specified: list detailed commands
+ n = sscanf(params_s, "%s %[^\n]s", object_s, action_s);
+ assert(n == 2);
+ object_type = object_type_from_str(object_s);
+ if (object_type == OBJECT_TYPE_UNDEFINED) {
+ fprintf(stderr, "Error: undefined object type.\n");
+ return -1;
+ }
+ action = action_from_str(action_s);
+ assert(action != ACTION_UNDEFINED);
+
+CMD_LIST:
+ printf("Available commands:\n");
+ command_list(object_type, action);
+ return 0;
+}
+
+#if 0 // tests
+/* For the tests, we will need to test all non-compliant inputs */
+const char * cmds[] = {
+ "add connection hicn conn1 8.8.8.8 127.0.0.1 eth0",
+ "add connection udp <symbolic> <remote_ip> <port> <local_ip> <port> eth0",
+ "add listener udp lst1 127.0.0.1 9695 eth0",
+ //"add face",
+ "add route 3 b001::/16 1",
+ //"add punting",
+ //"add strategy",
+ "add policy b001::/16 webex require avoid prohibit !prohibit neutral !require prefer",
+ "list connection", // need pluralize
+ "list listener",
+ "list face",
+ "list route",
+ "list punting",
+ "list strategy",
+ "list policy",
+ "remove connection 1",
+ "remove listener 1",
+ //"remove face",
+ "remove route 1 b001::/16",
+ //"remove punting",
+ //"remove policy",
+ "set debug",
+ "unset debug",
+ "set strategy b001::/16 random", // related prefixes (10 max) ?
+ "set strategy b001::/16 load_balancer",
+ "set strategy b001::/16 low_latency",
+ "set strategy b001::/16 replication",
+ "set strategy b001::/16 bestpath",
+ "set strategy b001::/16 local_remote",
+ "set wldr <on|off> <connection_id>", // on-off vs unset
+ "cache clear",
+ "cache store on/off", // set/unset
+ "cache serve on/off",
+ "mapme enable on/off",
+ "mapme discovery on/off",
+ "mapme timescale 500ms",
+ "mapme retx 500ms",
+ "update connection conn1 WT",
+};
+
+#define array_size(x) sizeof(x) / sizeof(typeof(x[0]))
+int main()
+{
+ for (unsigned i = 0; i < array_size(cmds); i++) {
+ printf("PARSING [%d] %s\n", i, cmds[i]);
+ if (parse(cmds[i]) < 0) {
+ ERROR("Could not parse command: %s\n", cmds[i]);
+ continue;
+ }
+ }
+ exit(EXIT_SUCCESS);
+
+ERR:
+ exit(EXIT_FAILURE);
+}
+#endif
diff --git a/ctrl/libhicnctrl/src/request.c b/ctrl/libhicnctrl/src/request.c
new file mode 100644
index 000000000..0e1d07b04
--- /dev/null
+++ b/ctrl/libhicnctrl/src/request.c
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file request.c
+ * \brief Implementation of pending requests.
+ */
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include <hicn/util/log.h>
+
+#include "request.h"
+
+const char *hc_request_state_str[] = {
+#define _(x) [REQUEST_STATE_##x] = #x,
+ foreach_request_state
+#undef _
+};
+
+struct hc_request_s {
+ int seq;
+ hc_action_t action;
+ hc_object_type_t object_type;
+ hc_object_t *object;
+
+#if 0
+ int (*parse)(const uint8_t *src, uint8_t *dst);
+#endif
+
+ /* Callbacks */
+ hc_result_callback_t callback;
+ void *callback_data;
+
+ /* Temp data used for the execution of the request */
+ hc_data_t *data;
+
+ /* Nested requests support
+ *
+ * In order to answer complex requests, involving a combination of requests to
+ * the forwarder, we will allow maintaining a Finite State Machine in the
+ * requests (and a tree of requests)
+ *
+ * The entry point for the modules will always remain the initial request,
+ * however, we will chain nested requests in their parent fields, and point to
+ * the one currently under execution in current.
+ * */
+ hc_request_state_t state;
+ unsigned state_count; /* Usefor for iterative requests */
+ hc_request_t *parent;
+ hc_request_t *current;
+};
+
+hc_request_t *hc_request_create(int seq, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object,
+ hc_result_callback_t callback,
+ void *callback_data) {
+ hc_request_t *request = malloc(sizeof(hc_request_t));
+ if (!request) return NULL;
+ request->seq = seq;
+
+ request->action = action;
+ request->object_type = object_type;
+ request->object = object;
+
+ request->callback = callback;
+ request->callback_data = callback_data;
+
+ request->data = NULL;
+
+ request->state = REQUEST_STATE_INIT;
+ request->state_count = 0;
+ request->parent = NULL;
+ request->current = NULL;
+
+ return request;
+}
+
+void hc_request_free(hc_request_t *request) { free(request); }
+
+void hc_request_set(hc_request_t *request, hc_action_t action,
+ hc_object_type_t object_type, hc_object_t *object) {
+ request->action = action;
+ request->object_type = object_type;
+ request->object = object;
+}
+
+int hc_request_get_seq(const hc_request_t *request) { return request->seq; }
+
+hc_request_t *hc_request_get_current(hc_request_t *request) {
+ return request->current ? request->current : request;
+}
+
+hc_request_t *hc_request_pop(hc_request_t *request) {
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_request_t *parent = current_request->parent;
+ request->current = parent;
+ if (parent) {
+ parent->data = current_request->data;
+ /* We only free the current_request if it was not the root */
+ hc_request_free(current_request);
+ }
+ return parent;
+}
+
+hc_request_state_t hc_request_get_state(const hc_request_t *request) {
+ return request->state;
+}
+
+void hc_request_set_state(hc_request_t *request, hc_request_state_t state) {
+ request->state = state;
+}
+
+int hc_request_get_state_count(const hc_request_t *request) {
+ return request->state_count;
+}
+
+void hc_request_set_state_count(hc_request_t *request, unsigned count) {
+ request->state_count = count;
+}
+
+hc_action_t hc_request_get_action(const hc_request_t *request) {
+ return request->action;
+}
+
+hc_object_type_t hc_request_get_object_type(const hc_request_t *request) {
+ return request->object_type;
+}
+
+hc_object_t *hc_request_get_object(const hc_request_t *request) {
+ return request->object;
+}
+
+hc_data_t *hc_request_get_data(const hc_request_t *request) {
+ return request->data;
+}
+
+void hc_request_set_data(hc_request_t *request, hc_data_t *data) {
+ assert(!request->data);
+ request->data = data;
+}
+
+void hc_request_reset_data(hc_request_t *request) {
+ if (!request->data) return;
+ hc_data_free(request->data);
+ request->data = NULL;
+}
+
+bool hc_request_is_subscription(const hc_request_t *request) {
+ hc_action_t action = hc_request_get_action(request);
+ hc_object_type_t object_type = hc_request_get_object_type(request);
+ return (action == ACTION_SUBSCRIBE) ||
+ (action == ACTION_CREATE && object_type == OBJECT_TYPE_SUBSCRIPTION);
+}
+
+bool hc_request_requires_object(const hc_request_t *request) {
+ hc_action_t action = hc_request_get_action(request);
+ return (action != ACTION_LIST) && (action != ACTION_SUBSCRIBE);
+}
+
+void hc_request_clear_data(hc_request_t *request) { request->data = NULL; }
+
+void hc_request_set_complete(hc_request_t *request) {
+ request->state = REQUEST_STATE_COMPLETE;
+}
+
+bool hc_request_is_complete(const hc_request_t *request) {
+ return request->state == REQUEST_STATE_COMPLETE;
+}
+
+void hc_request_on_complete(hc_request_t *request) {
+ // request->state = REQUEST_STATE_COMPLETE;
+ if (!request->callback) return;
+ request->callback(request->data, request->callback_data);
+}
+
+void hc_request_on_notification(hc_request_t *request) {
+ if (!request->callback) return;
+ request->callback(request->data, request->callback_data);
+}
+
+hc_request_t *hc_request_make_subrequest(hc_request_t *request,
+ hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object) {
+ hc_request_t *sr =
+ hc_request_create(request->seq, action, object_type, object,
+ request->callback, request->callback_data);
+
+ /* The parent is either the current one, or the request itself if NULL */
+ hc_request_t *current_request = hc_request_get_current(request);
+ hc_request_reset_data(current_request);
+ sr->parent = current_request;
+ request->current = sr;
+ return sr;
+}
diff --git a/ctrl/libhicnctrl/src/request.h b/ctrl/libhicnctrl/src/request.h
new file mode 100644
index 000000000..aa07cad00
--- /dev/null
+++ b/ctrl/libhicnctrl/src/request.h
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file request.h
+ * \brief Pending requests.
+ */
+
+#ifndef HC_REQUEST_H
+#define HC_REQUEST_H
+
+#include <stdbool.h>
+
+#include <hicn/ctrl/action.h>
+#include <hicn/ctrl/callback.h>
+#include <hicn/ctrl/data.h>
+#include <hicn/ctrl/object.h>
+
+#if 0
+typedef int (*HC_PARSE)(const uint8_t *, uint8_t *);
+#endif
+
+#define foreach_request_state \
+ _(UNDEFINED) \
+ _(INIT) \
+ _(CONNECTION_CREATE_LISTENER_LIST) \
+ _(CONNECTION_CREATE_LISTENER_ITERATE) \
+ _(CONNECTION_CREATE_LISTENER_GET) \
+ _(CONNECTION_CREATE_LISTENER_VERIFY) \
+ _(CONNECTION_CREATE_LISTENER_CREATE) \
+ _(CONNECTION_CREATE_LISTENER_CHECK) \
+ _(CONNECTION_CREATE) \
+ _(CONNECTION_CREATE_N) \
+ _(CONNECTION_GET) \
+ _(CONNECTION_DELETE_WITH_ID) \
+ _(CONNECTION_DELETE_AFTER_GET) \
+ _(FACE_CREATE_CONNECTION_CREATE) \
+ _(FACE_DELETE_CONNECTION_DELETE) \
+ _(FACE_CREATE_CONNECTION_CHECK) \
+ _(FACE_CREATE_CONNECTION_GET) \
+ _(FACE_CREATE_CONNECTION_VERIFY) \
+ _(FACE_CREATE_LISTENER_CREATE) \
+ _(FACE_CREATE_LISTENER_CHECK) \
+ _(FACE_LIST_CONNECTION_LIST) \
+ _(ROUTE_CREATE_FACE_CREATE) \
+ _(ROUTE_CREATE_FACE_CHECK) \
+ _(ROUTE_CREATE) \
+ _(GET_LIST) \
+ _(COMPLETE) \
+ _(N)
+
+typedef enum {
+#define _(x) REQUEST_STATE_##x,
+ foreach_request_state
+#undef _
+} hc_request_state_t;
+
+extern const char *hc_request_state_str[];
+
+#define hc_request_state_str(x) hc_request_state_str[x]
+
+/*
+ * Internal state associated to a pending request
+ */
+typedef struct hc_request_s hc_request_t;
+
+hc_request_t *hc_request_create(int seq, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object,
+ hc_result_callback_t callback,
+ void *callback_data);
+
+void hc_request_free(hc_request_t *request);
+
+void hc_request_set(hc_request_t *request, hc_action_t action,
+ hc_object_type_t object_type, hc_object_t *object);
+
+int hc_request_get_seq(const hc_request_t *request);
+hc_request_t *hc_request_get_current(hc_request_t *request);
+hc_request_t *hc_request_pop(hc_request_t *request);
+
+hc_request_state_t hc_request_get_state(const hc_request_t *request);
+void hc_request_set_state(hc_request_t *request, hc_request_state_t state);
+
+int hc_request_get_state_count(const hc_request_t *request);
+void hc_request_set_state_count(hc_request_t *request, unsigned count);
+
+hc_action_t hc_request_get_action(const hc_request_t *request);
+hc_object_type_t hc_request_get_object_type(const hc_request_t *request);
+hc_object_t *hc_request_get_object(const hc_request_t *request);
+hc_data_t *hc_request_get_data(const hc_request_t *request);
+void hc_request_set_data(hc_request_t *request, hc_data_t *data);
+void hc_request_reset_data(hc_request_t *request);
+
+bool hc_request_is_subscription(const hc_request_t *request);
+bool hc_request_requires_object(const hc_request_t *request);
+
+// do not free data which might be invalid
+// XXX to be removed if we replace "ensure_data_size_and_free" functions and the
+// like, with equivalent functions acting on request
+void hc_request_clear_data(hc_request_t *request);
+
+void hc_request_set_complete(hc_request_t *request);
+bool hc_request_is_complete(const hc_request_t *request);
+
+void hc_request_on_complete(hc_request_t *request);
+void hc_request_on_notification(hc_request_t *request);
+
+/*
+ * Same seq & callbacks
+ */
+hc_request_t *hc_request_make_subrequest(hc_request_t *request,
+ hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object);
+
+#endif /* HC_REQUEST_H */
diff --git a/ctrl/libhicnctrl/src/route.c b/ctrl/libhicnctrl/src/route.c
index 703b4763f..71e39d7ad 100644
--- a/ctrl/libhicnctrl/src/route.c
+++ b/ctrl/libhicnctrl/src/route.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,84 +25,64 @@
#define DEFAULT_HICN_ROUTE_COST 1
struct hicn_route_s {
- ip_prefix_t prefix;
- face_id_t face_id;
- route_cost_t cost; /* Optional, 0 means no value, defaults to 1 */
+ hicn_ip_prefix_t prefix;
+ face_id_t face_id;
+ route_cost_t cost; /* Optional, 0 means no value, defaults to 1 */
};
-hicn_route_t *
-hicn_route_create(ip_prefix_t * prefix, face_id_t face_id, route_cost_t cost)
-{
- hicn_route_t * route = malloc(sizeof(hicn_route_t));
- if (!route)
- return NULL;
- route->prefix = *prefix;
- route->face_id = face_id;
- route->cost = cost != 0 ? cost : DEFAULT_HICN_ROUTE_COST;
+hicn_route_t* hicn_route_create(hicn_ip_prefix_t* prefix, face_id_t face_id,
+ route_cost_t cost) {
+ hicn_route_t* route = malloc(sizeof(hicn_route_t));
+ if (!route) return NULL;
+ route->prefix = *prefix;
+ route->face_id = face_id;
+ route->cost = cost != 0 ? cost : DEFAULT_HICN_ROUTE_COST;
- return route;
+ return route;
}
-hicn_route_t *
-hicn_route_dup(const hicn_route_t * route)
-{
- hicn_route_t * new_route = malloc(sizeof(hicn_route_t));
- if (!route)
- return NULL;
- memcpy(new_route, route, sizeof(hicn_route_t));
- return new_route;
+hicn_route_t* hicn_route_dup(const hicn_route_t* route) {
+ hicn_route_t* new_route = malloc(sizeof(hicn_route_t));
+ if (!route) return NULL;
+ memcpy(new_route, route, sizeof(hicn_route_t));
+ return new_route;
}
-void hicn_route_free(hicn_route_t * route)
-{
- free(route);
-}
+void hicn_route_free(hicn_route_t* route) { free(route); }
-int
-hicn_route_cmp(const hicn_route_t * route1, const hicn_route_t * route2)
-{
- int rc;
- rc = ip_prefix_cmp(&route1->prefix, &route2->prefix);
- if (rc != 0)
- return rc;
+int hicn_route_cmp(const hicn_route_t* route1, const hicn_route_t* route2) {
+ int rc;
+ rc = hicn_ip_prefix_cmp(&route1->prefix, &route2->prefix);
+ if (rc != 0) return rc;
- return (route1->face_id > route2->face_id) ? 1 :
- (route1->face_id < route2->face_id) ? -1 : 0;
+ return (route1->face_id > route2->face_id) ? 1
+ : (route1->face_id < route2->face_id) ? -1
+ : 0;
}
-int
-hicn_route_get_prefix(const hicn_route_t * route, ip_prefix_t * prefix)
-{
- *prefix = route->prefix;
- return 0;
+int hicn_route_get_prefix(const hicn_route_t* route, hicn_ip_prefix_t* prefix) {
+ *prefix = route->prefix;
+ return 0;
}
-int
-hicn_route_set_prefix(hicn_route_t * route, const ip_prefix_t prefix)
-{
- route->prefix = prefix;
- return 0;
+int hicn_route_set_prefix(hicn_route_t* route, const hicn_ip_prefix_t prefix) {
+ route->prefix = prefix;
+ return 0;
}
-int
-hicn_route_get_cost(const hicn_route_t * route, int * cost)
-{
- *cost = route->cost;
- return 0;
+int hicn_route_get_cost(const hicn_route_t* route, int* cost) {
+ *cost = route->cost;
+ return 0;
}
-int
-hicn_route_set_cost(hicn_route_t * route, const int cost)
-{
- route->cost = cost;
- return 0;
+int hicn_route_set_cost(hicn_route_t* route, const int cost) {
+ route->cost = cost;
+ return 0;
}
/* /!\ Please update constants in header file upon changes */
-size_t
-hicn_route_snprintf(char * s, size_t size, const hicn_route_t * route)
-{
- char prefix_s[MAXSZ_PREFIX];
- ip_prefix_ntop(&route->prefix, prefix_s, MAXSZ_PREFIX);
- return snprintf(s, size, "%s [%d]", prefix_s, route->cost);
+size_t hicn_route_snprintf(char* s, size_t size, const hicn_route_t* route) {
+ char prefix_s[MAXSZ_IP_PREFIX];
+ hicn_ip_prefix_ntop(&route->prefix, prefix_s, MAXSZ_IP_PREFIX);
+ return snprintf(s, size, "%s [%d]", prefix_s, route->cost);
}
diff --git a/ctrl/libhicnctrl/src/socket.c b/ctrl/libhicnctrl/src/socket.c
new file mode 100644
index 000000000..956dc07c8
--- /dev/null
+++ b/ctrl/libhicnctrl/src/socket.c
@@ -0,0 +1,308 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file socket.c
+ * \brief Implementation of control socket.
+ */
+
+#include <dlfcn.h>
+#include <stdio.h>
+
+#include <hicn/ctrl/socket.h>
+#include <hicn/util/log.h>
+
+#ifdef ANDROID
+/*
+ * In android we do not load a module at runtime but we link the hicnlight
+ * implementation directly to the main library.
+ */
+#include "modules/hicn_light.h"
+#endif /* ANDROID */
+
+#include "socket_private.h"
+
+TYPEDEF_MAP(hc_sock_map, int, hc_request_t *, int_cmp, int_snprintf,
+ generic_snprintf);
+
+const char *forwarder_type_str[] = {
+#define _(x) [FORWARDER_TYPE_##x] = #x,
+ foreach_forwarder_type
+#undef _
+};
+
+forwarder_type_t forwarder_type_from_str(const char *str) {
+ for (forwarder_type_t i = FORWARDER_TYPE_UNDEFINED + 1; i < FORWARDER_TYPE_N;
+ i++) {
+ if (strcasecmp(str, forwarder_type_str[i]) == 0) return i;
+ }
+ return FORWARDER_TYPE_UNDEFINED;
+}
+
+#ifndef ANDROID
+static int hc_sock_set_ops(hc_sock_t *s, const char *name, const char *url) {
+ char complete_name[128];
+#ifdef __APPLE__
+ sprintf(complete_name, "%s.dylib", name);
+#elif defined(__linux__)
+ snprintf(complete_name, 128, "%s.so", name);
+#else
+#error "System not supported for dynamic lynking"
+#endif
+
+ void *handle = 0;
+ const char *error = 0;
+ int (*initialize_module)(hc_sock_t *) = 0;
+ int rc = 0;
+
+ // open module
+ handle = dlopen(complete_name, RTLD_LAZY);
+ if (!handle) {
+ if ((error = dlerror()) != 0) {
+ ERROR("%s", error);
+ }
+ goto ERR_DL;
+ return -1;
+ }
+ s->handle = handle;
+
+ // get factory method
+ initialize_module =
+ (int (*)(hc_sock_t *))dlsym(handle, "hc_sock_initialize_module");
+ if (!initialize_module) {
+ if ((error = dlerror()) != 0) {
+ ERROR("%s", error);
+ }
+ goto ERR_INIT;
+ }
+ initialize_module(s);
+
+ return rc;
+ERR_INIT:
+ dlclose(s->handle);
+ s->handle = NULL;
+ERR_DL:
+ return -1;
+}
+#endif /* ! ANDROID */
+
+int hc_sock_is_async(hc_sock_t *s) { return s->async; }
+
+int hc_sock_set_async(hc_sock_t *s) {
+ s->async = true;
+ return 0;
+}
+
+hc_sock_t *hc_sock_create(forwarder_type_t forwarder, const char *url) {
+#ifndef ANDROID
+ int rc;
+#endif
+
+ hc_sock_t *s = malloc(sizeof(hc_sock_t));
+ if (!s) goto ERR_MALLOC;
+
+#ifdef ANDROID
+ assert(forwarder == HICNLIGHT);
+ s->data = hc_sock_light_data_create(url);
+ s->handle = NULL;
+#else
+ switch (forwarder) {
+ case FORWARDER_TYPE_HICNLIGHT:
+ rc = hc_sock_set_ops(s, "hicnlightctrl_module", url);
+ break;
+ case FORWARDER_TYPE_VPP:
+ rc = hc_sock_set_ops(s, "vppctrl_module", url);
+ break;
+ default:
+ goto ERR_INIT;
+ }
+
+ if (rc < 0) goto ERR_INIT;
+
+ s->data = s->ops.create_data(url);
+#endif
+
+ if (!s->data) goto ERR_DATA;
+
+ s->map = hc_sock_map_create();
+ if (!s->map) goto ERR_MAP;
+
+ s->async = false;
+
+ s->seq_request = 0;
+ s->current_request = NULL;
+
+ return s;
+
+ERR_MAP:
+#ifdef ANDROID
+ hc_sock_light_data_free(s->data);
+#else
+ ; // XXX VFT() free
+#endif
+ERR_DATA:
+#ifndef ANDROID
+ERR_INIT:
+#endif
+ free(s);
+ERR_MALLOC:
+ return NULL;
+}
+
+hc_sock_t *hc_sock_create_forwarder(forwarder_type_t forwarder) {
+ return hc_sock_create(forwarder, NULL);
+}
+
+void hc_sock_free(hc_sock_t *s) {
+ if (s->ops.disconnect) s->ops.disconnect(s);
+#ifdef ANDROID
+ hc_sock_light_data_free(s->data);
+#else
+ if (s->ops.free_data) s->ops.free_data(s->data);
+ if (s->handle) {
+ dlclose(s->handle);
+ }
+#endif /* ANDROID */
+
+ hc_request_t **request_array = NULL;
+ int n = hc_sock_map_get_value_array(s->map, &request_array);
+ if (n < 0) {
+ ERROR("Could not retrieve pending request array for freeing up resources");
+ } else {
+ for (unsigned i = 0; i < n; i++) {
+ hc_request_t *request = request_array[i];
+ if (hc_sock_map_remove(s->map, hc_request_get_seq(request), NULL) < 0)
+ ERROR("[hc_sock_light_process] Error removing request from map");
+ hc_request_free(request);
+ }
+ free(request_array);
+ }
+
+ hc_sock_map_free(s->map);
+
+ free(s);
+}
+
+#if 0
+int hc_sock_get_next_seq(hc_sock_t *s) { return s->hc_sock_get_next_seq(s); }
+
+int hc_sock_set_nonblocking(hc_sock_t *s) { return s->hc_sock_get_next_seq(s); }
+
+#endif
+
+int hc_sock_get_fd(hc_sock_t *s) { return s->ops.get_fd(s); }
+
+int hc_sock_connect(hc_sock_t *s) { return s->ops.connect(s); }
+
+int hc_sock_get_recv_buffer(hc_sock_t *s, u8 **buffer, size_t *size) {
+ return s->ops.get_recv_buffer(s, buffer, size);
+}
+#if 0
+
+int hc_sock_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, uint32_t seq) {
+ return s->hc_sock_send(s, msg, msglen, seq);
+}
+
+int hc_sock_recv(hc_sock_t *s) { return s->ops.recv(s); }
+#endif
+
+#if 0
+int hc_sock_process(hc_sock_t *s, hc_data_t **data) {
+ return s->hc_sock_process(s, data);
+}
+
+int hc_sock_callback(hc_sock_t *s, hc_data_t **data) {
+ return s->hc_sock_callback(s, data);
+}
+
+int hc_sock_reset(hc_sock_t *s) { return s->hc_sock_reset(s); }
+
+void hc_sock_increment_woff(hc_sock_t *s, size_t bytes) {
+ s->hc_sock_increment_woff(s, bytes);
+}
+
+int hc_sock_prepare_send(hc_sock_t *s, hc_result_t *result,
+ data_callback_t complete_cb, void *complete_cb_data) {
+ return s->hc_sock_prepare_send(s, result, complete_cb, complete_cb_data);
+}
+
+int hc_sock_set_recv_timeout_ms(hc_sock_t *s, long timeout_ms) {
+ return s->hc_sock_set_recv_timeout_ms(s, timeout_ms);
+}
+#endif
+
+hc_request_t *hc_sock_create_request(hc_sock_t *s, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object,
+ hc_result_callback_t callback,
+ void *callback_data) {
+ /* Create request state */
+ int seq = s->seq_request++;
+ hc_request_t *request = hc_request_create(seq, action, object_type, object,
+ callback, callback_data);
+ if (!request) goto ERR_MALLOC;
+
+ hc_request_set_state(request, REQUEST_STATE_INIT);
+
+ // Add state to map
+ if (hc_sock_map_add(s->map, seq, request) < 0) {
+ ERROR("[hc_sock_create_request] Error adding request state to map");
+ goto ERR_MAP;
+ }
+
+ return request;
+
+ERR_MAP:
+ free(request);
+ERR_MALLOC:
+ return NULL;
+}
+
+hc_request_t *hc_sock_get_request(hc_sock_t *s) { return s->current_request; }
+
+void hc_sock_free_request(hc_sock_t *s, hc_request_t *request, bool recursive) {
+ if (hc_sock_map_remove(s->map, hc_request_get_seq(request), NULL) < 0) {
+ ERROR("[hc_sock_free_request] Error removing request from map");
+ }
+ if (recursive) {
+ hc_request_t *r = NULL;
+ do {
+ r = hc_request_pop(request);
+ } while (r);
+ }
+ hc_request_free(request);
+ s->current_request = NULL;
+}
+
+/**
+ * TODO: return code:
+ * -1 object not found
+ * -2 action not found
+ * -3 error during serialization
+ *
+ * @return the size of the created message
+ */
+ssize_t hc_sock_serialize_object(hc_sock_t *s, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object, uint8_t *msg) {
+ hc_serialize_t fn = (s->ops.object_vft[object_type]).serialize[action];
+ if (!fn) return -1;
+ return fn(object, msg);
+}
+
+int hc_sock_parse_object(hc_sock_t *s, hc_object_type_t object_type,
+ uint8_t *buffer, size_t size, hc_object_t *object) {
+ return s->ops.object_vft[object_type].parse(buffer, size, object);
+}
diff --git a/ctrl/libhicnctrl/src/socket_private.h b/ctrl/libhicnctrl/src/socket_private.h
new file mode 100644
index 000000000..30f3bcb6e
--- /dev/null
+++ b/ctrl/libhicnctrl/src/socket_private.h
@@ -0,0 +1,47 @@
+#ifndef HICNCTRL_SOCKET_PRIVATE_H
+#define HICNCTRL_SOCKET_PRIVATE_H
+
+#include <hicn/util/map.h>
+#include <hicn/ctrl/socket.h>
+
+#include "module.h"
+
+TYPEDEF_MAP_H(hc_sock_map, int, hc_request_t *);
+
+struct hc_sock_s {
+ int request_seq;
+ hc_sock_map_t *map;
+
+ bool async;
+ int seq_request;
+
+ /*
+ * Stores the current request being parsed in case of fragmented reception or
+ * analysis (as it is the case now) between header and payload
+ */
+ hc_request_t *current_request;
+
+ hc_sock_ops_t ops;
+
+ void *data;
+ void *handle;
+};
+
+hc_request_t *hc_sock_create_request(hc_sock_t *s, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object,
+ hc_result_callback_t callback,
+ void *callback_data);
+
+hc_request_t *hc_sock_get_request(hc_sock_t *s);
+
+void hc_sock_free_request(hc_sock_t *s, hc_request_t *request, bool recursive);
+
+ssize_t hc_sock_serialize_object(hc_sock_t *sock, hc_action_t action,
+ hc_object_type_t object_type,
+ hc_object_t *object, uint8_t *msg);
+
+int hc_sock_parse_object(hc_sock_t *sock, hc_object_type_t object_type,
+ uint8_t *buffer, size_t size, hc_object_t *object);
+
+#endif /* HICNCTRL_SOCKET_PRIVATE_H */
diff --git a/ctrl/libhicnctrl/src/test/CMakeLists.txt b/ctrl/libhicnctrl/src/test/CMakeLists.txt
new file mode 100644
index 000000000..7fdff476d
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/CMakeLists.txt
@@ -0,0 +1,51 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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.
+
+##############################################################
+# Test sources
+##############################################################
+list(APPEND TESTS_SRC
+ main.cc
+ common.cc
+ test_data.cc
+ test_hicnlight_listener.cc
+ test_hicnlight_connection.cc
+ test_hicnlight_route.cc
+ ../modules/hicn_light/connection.c
+ ../modules/hicn_light/face.c
+ ../modules/hicn_light/listener.c
+ ../modules/hicn_light/route.c
+)
+
+##############################################################
+# Build single unit test executable and add it to test list
+##############################################################
+build_executable(libhicnctrl_tests
+ NO_INSTALL
+ SOURCES ${TESTS_SRC}
+ LINK_LIBRARIES
+ ${LIBRARIES}
+ ${LIBHICNCTRL_SHARED}
+ ${GTEST_LIBRARIES}
+ pthread
+ INCLUDE_DIRS
+ $<TARGET_PROPERTY:${LIBHICNCTRL_SHARED},INCLUDE_DIRECTORIES>
+ ${GTEST_INCLUDE_DIRS}
+ DEPENDS gtest ${LIBHICNCTRL_SHARED}
+ COMPONENT ${LIBHICNCTRL_COMPONENT}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ LINK_FLAGS ${LINK_FLAGS}
+)
+
+add_test_internal(libhicnctrl_tests)
diff --git a/ctrl/libhicnctrl/src/test/common.cc b/ctrl/libhicnctrl/src/test/common.cc
new file mode 100644
index 000000000..075281d2e
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/common.cc
@@ -0,0 +1,13 @@
+#include "common.h"
+
+std::string dump_buffer(const char *name, uint8_t *buffer, size_t size) {
+ std::ostringstream oss;
+ oss << "const std::vector<uint8_t> " << name << " = {";
+ for (size_t i = 0; i < size; i++) {
+ if (i > 0) oss << ", ";
+ oss << "0x" << std::setw(2) << std::setfill('0') << std::hex
+ << static_cast<int>(buffer[i]);
+ }
+ oss << "};" << std::endl;
+ return oss.str();
+}
diff --git a/ctrl/libhicnctrl/src/test/common.h b/ctrl/libhicnctrl/src/test/common.h
new file mode 100644
index 000000000..8927c86ec
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/common.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HICNCTRL_TEST_COMMON
+#define HICNCTRL_TEST_COMMON
+
+#define BUFSIZE 8192
+
+#include <gtest/gtest.h>
+
+class TestHicnLight : public ::testing::Test {
+ protected:
+ TestHicnLight() {}
+ virtual ~TestHicnLight() {}
+ virtual void SetUp() {}
+ virtual void TearDown() {}
+};
+
+class TestHicnLightSerialize : public TestHicnLight {
+ // TestHicnLightSerialize() {}
+ // virtual ~TestHicnLightSerialize() {}
+};
+
+class TestHicnLightParse : public TestHicnLight {
+ // TestHicnLightParse() {}
+ // virtual ~TestHicnLightParse() {}
+};
+
+std::string dump_buffer(const char *name, uint8_t *buffer, size_t size);
+
+#define EXPECT_PAYLOAD_EQ(BUFFER, SIZE, PAYLOAD) \
+ EXPECT_EQ(memcmp((BUFFER), &(PAYLOAD)[0], PAYLOAD.size()), 0) \
+ << dump_buffer(#PAYLOAD, (BUFFER), SIZE);
+
+#define EXPECT_PAYLOAD_EQ_STRUCT(BUFFER, SIZE, PAYLOAD) \
+ EXPECT_EQ(memcmp((BUFFER), (PAYLOAD), SIZE), 0) \
+ << dump_buffer("expected:", (uint8_t *)(BUFFER), SIZE);
+
+#endif /* HICNCTRL_TEST_COMMON */
diff --git a/ctrl/libhicnctrl/src/test/main.cc b/ctrl/libhicnctrl/src/test/main.cc
new file mode 100644
index 000000000..49cc28f66
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/main.cc
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+int main(int argc, char **argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/ctrl/libhicnctrl/src/test/test_data.cc b/ctrl/libhicnctrl/src/test/test_data.cc
new file mode 100644
index 000000000..46debb0e7
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/test_data.cc
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <sstream>
+
+extern "C" {
+#include <hicn/ctrl/objects.h>
+#include <hicn/ctrl/data.h>
+#include <hicn/ctrl/object.h>
+}
+
+#include "common.h"
+
+namespace {
+
+TEST_F(TestHicnLight, TestHicnLightData) {
+ hc_object_t object;
+ memset(&object, 0, sizeof(hc_object_t));
+
+ int rc;
+ hc_data_t* data = hc_data_create(OBJECT_TYPE_FACE);
+ hc_data_set_max_size(data, 2);
+
+ ASSERT_EQ(hc_data_get_size(data), 0) << "Initial data size should be zero";
+
+ /* Try to allocate more than max */
+ rc = hc_data_allocate(data, 5);
+ ASSERT_EQ(rc, -1) << "Allocating above max_size should fail";
+
+ /* Allocate room for two objects */
+ rc = hc_data_allocate(data, 2);
+ ASSERT_EQ(rc, 0) << "Allocating data the first time should succeed";
+
+ ASSERT_EQ(hc_data_get_size(data), 0)
+ << "Initial size should be 0 after allocation";
+
+ /* Try to allocate twice */
+ rc = hc_data_allocate(data, 2);
+ ASSERT_EQ(rc, -1) << "Allocating data multiple times should fail";
+
+ ASSERT_EQ(hc_data_get_size(data), 0)
+ << "Size after failed push should remain unchanged";
+
+ /* Push a first object */
+ rc = hc_data_push(data, &object);
+ ASSERT_EQ(rc, 0) << "First push should succeed";
+
+ ASSERT_EQ(hc_data_get_size(data), 1)
+ << "Data size first successful push should be 1";
+
+ /* Push a second object */
+ rc = hc_data_push(data, &object);
+ ASSERT_EQ(rc, 0) << "Second push should succeed";
+
+ ASSERT_EQ(hc_data_get_size(data), 2)
+ << "Data size after second successful push should be 2";
+
+ /* Push a third object, exceeding the allocated size */
+ rc = hc_data_push(data, &object);
+ ASSERT_EQ(rc, -1) << "Third push on full data of size 2 should fail";
+
+ /* Clear */
+ rc = hc_data_clear(data);
+ ASSERT_EQ(rc, 0) << "Clear should always succeed";
+
+ rc = hc_data_push(data, &object);
+ ASSERT_EQ(rc, 0) << "Pushing element after reallocation should succeed";
+
+ ASSERT_EQ(hc_data_get_size(data), 1) << "Size after first push should be one";
+ // XXX
+
+ /* Try to push an invalid object */
+ // XXX so far NULL
+ rc = hc_data_push(data, NULL);
+ ASSERT_EQ(rc, -1) << "Pushing invalid element should fail";
+
+ ASSERT_EQ(hc_data_get_size(data), 1)
+ << "Size after push failure should remain unchanged";
+ // XXX
+
+ hc_data_free(data);
+}
+
+} // namespace
diff --git a/ctrl/libhicnctrl/src/test/test_hicnlight_connection.cc b/ctrl/libhicnctrl/src/test/test_hicnlight_connection.cc
new file mode 100644
index 000000000..53dd88ac3
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/test_hicnlight_connection.cc
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <sstream>
+
+#include <hicn/ctrl/object.h>
+
+#include "../modules/hicn_light/connection.h"
+#include "common.h"
+
+namespace {
+
+const hc_object_t valid_connection = {
+ .connection = {.id = 0,
+ .name = {'l', 's', 't', 0},
+ .interface_name = {'l', 'o', 0},
+ .netdevice_type = NETDEVICE_TYPE_WIRED,
+ .type = FACE_TYPE_UDP,
+ .family = AF_INET,
+ .local_addr = IPV4_LOOPBACK,
+ .local_port = 9695,
+ .remote_addr = IPV4_LOOPBACK,
+ .remote_port = 9695,
+ .admin_state = FACE_STATE_UP,
+ .priority = 0,
+ .tags = POLICY_TAGS_EMPTY,
+ .state = FACE_STATE_UP}};
+
+const std::vector<uint8_t> valid_connection_create_payload = {
+ /* header */
+ 0xc0, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+ /* char name[SYMBOLIC_NAME_LEN] = "lst"; */
+ 0x6c, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* ip_address_t local_addr = [padding] 127.0.0.1 */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x7f, 0x00, 0x00, 0x01,
+ /* ip_address_t remote_addr = [padding] 127.0.0.1 */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x7f, 0x00, 0x00, 0x01,
+ /* uint16_t local_port = 9695; */
+ 0x25, 0xdf,
+ /* uint16_t remote_port = 9695; */
+ 0x25, 0xdf,
+ /* int family = AF_INET; */
+ 0x02,
+ /* face_type_t type = FACE_TYPE_UDP_LISTENER; */
+ 0x05,
+ /* uint8_t admin_state = FACE_STATE_UP; */
+ 0x02,
+ /* Padding ? */
+ 0x00,
+ /* uint32_t priority = 0; */
+ 0x00, 0x00, 0x00, 0x00,
+ /* policy_tags_t tags; */
+ 0x00, 0x00, 0x00, 0x00};
+
+const std::vector<uint8_t> valid_connection_delete_payload = {
+ 0xc0, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0x73, 0x74, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+const std::vector<uint8_t> valid_connection_list_payload = {
+ 0xc0, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeConnectionCreate) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.connection, &valid_connection, sizeof(hc_connection_t));
+
+ hc_serialize_t fn = hicnlight_connection_module_ops.serialize[ACTION_CREATE];
+ size_t n = fn(&obj, buf);
+
+ // XXX debug
+ // THIS HAS UNINIT VALUES
+ std::cout << "n=" << n << std::endl;
+ EXPECT_EQ(memcmp(buf, buf, 60), 0);
+ EXPECT_EQ(memcmp(buf, buf, 62), 0);
+ EXPECT_EQ(memcmp(buf, buf, 64), 0); // XXX we start having issues
+ EXPECT_EQ(memcmp(buf, buf, 66), 0);
+ EXPECT_EQ(memcmp(buf, buf, 68), 0);
+ EXPECT_EQ(memcmp(buf, buf, 70), 0);
+ EXPECT_EQ(memcmp(buf, buf, 72), 0);
+ // XXX debug
+
+ EXPECT_EQ(n, valid_connection_create_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_connection_create_payload);
+}
+
+// TODO
+// - create with id != 0
+// - create with invalid fields, non zero-terminated strings, etc.
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeConnectionDelete) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.connection, &valid_connection, sizeof(hc_connection_t));
+
+ hc_serialize_t fn = hicnlight_connection_module_ops.serialize[ACTION_DELETE];
+ size_t n = fn(&obj, buf);
+
+ EXPECT_EQ(n, valid_connection_delete_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_connection_delete_payload);
+}
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeConnectionList) {
+ uint8_t buf[BUFSIZE];
+
+ hc_serialize_t fn = hicnlight_connection_module_ops.serialize[ACTION_LIST];
+ size_t n = fn(NULL, buf);
+
+ EXPECT_EQ(n, valid_connection_list_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_connection_list_payload);
+}
+
+} // namespace
diff --git a/ctrl/libhicnctrl/src/test/test_hicnlight_listener.cc b/ctrl/libhicnctrl/src/test/test_hicnlight_listener.cc
new file mode 100644
index 000000000..fb3df39a8
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/test_hicnlight_listener.cc
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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 <sstream>
+
+extern "C" {
+#include <hicn/ctrl/object.h>
+#include <hicn/ctrl/objects/listener.h>
+#include "../modules/hicn_light/listener.h"
+}
+
+#include "common.h"
+
+namespace {
+
+static const hc_object_t valid_listener = {
+ .listener = {.name = {'l', 's', 't', 0},
+ .interface_name = {'l', 'o', 0},
+ .id = 0,
+ .type = FACE_TYPE_UDP_LISTENER,
+ .family = AF_INET,
+ .local_addr = IPV4_LOOPBACK,
+ .local_port = 9695}};
+
+const std::vector<uint8_t> valid_listener_create_payload = {
+ /* header */
+ 0xc0, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+ /* char name[SYMBOLIC_NAME_LEN] = "lst"; */
+ 0x6c, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* char interface_name[INTERFACE_LEN] = "lo"; */
+ 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* ip_address_t local_addr = [padding] 127.0.0.1 */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x7f, 0x00, 0x00, 0x01,
+ /* uint16_t local_port = 9695; */
+ 0x25, 0xdf,
+ /* int family = AF_INET; */
+ 0x02,
+ /* face_type_t type = FACE_TYPE_UDP_LISTENER; */
+ 0x06};
+
+const std::vector<uint8_t> valid_listener_delete_payload = {
+ /* header */
+ 0xc0, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+ /* char symbolicOrListenerid[SYMBOLIC_NAME_LEN] = "lst"; */
+ 0x6c, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00};
+
+const std::vector<uint8_t> valid_listener_list_payload = {
+ /* header */
+ 0xc0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+/* @see <hicn/ctrl/objects/listener.h> */
+const std::vector<uint8_t> valid_listener_payload = {
+ /* char name[SYMBOLIC_NAME_LEN] = "lst"; */
+ 0x6c, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* char interface_name[INTERFACE_LEN] = "lo"; */
+ 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* ip_address_t local_addr = [padding] 127.0.0.1 */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x7f, 0x00, 0x00, 0x01,
+ /* uint32_t id = 0; */
+ 0x00, 0x00, 0x00, 0x00,
+ /* uint16_t local_port = 9695; */
+ 0x25, 0xdf,
+ /* face_type_t type = FACE_TYPE_UDP */
+ 0x06,
+ /* int family = AF_INET; */
+ 0x02};
+
+TEST_F(TestHicnLightParse, TestHicnLightParseListener) {
+ /* Parse payload into an object */
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ int rc = hicnlight_listener_module_ops.parse(
+ &valid_listener_payload[0], valid_listener_payload.size(), &obj);
+ EXPECT_EQ(rc, 0);
+ EXPECT_EQ(hc_listener_cmp(&obj.listener, &valid_listener.listener), 0);
+}
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeListenerCreate) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.listener, &valid_listener, sizeof(hc_listener_t));
+
+ hc_serialize_t fn = hicnlight_listener_module_ops.serialize[ACTION_CREATE];
+ size_t n = fn(&obj, buf);
+
+ EXPECT_EQ(n, valid_listener_create_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_listener_create_payload);
+}
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeListenerDelete) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.listener, &valid_listener, sizeof(hc_listener_t));
+
+ hc_serialize_t fn = hicnlight_listener_module_ops.serialize[ACTION_DELETE];
+ size_t n = fn(&obj, buf);
+
+ EXPECT_EQ(n, valid_listener_delete_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_listener_delete_payload);
+}
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeListenerList) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.listener, &valid_listener, sizeof(hc_listener_t));
+
+ hc_serialize_t fn = hicnlight_listener_module_ops.serialize[ACTION_LIST];
+ size_t n = fn(&obj, buf);
+
+ EXPECT_EQ(n, valid_listener_list_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_listener_list_payload);
+}
+} // namespace
diff --git a/ctrl/libhicnctrl/src/test/test_hicnlight_route.cc b/ctrl/libhicnctrl/src/test/test_hicnlight_route.cc
new file mode 100644
index 000000000..d48066ba2
--- /dev/null
+++ b/ctrl/libhicnctrl/src/test/test_hicnlight_route.cc
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <sstream>
+
+extern "C" {
+#include <hicn/ctrl/object.h>
+#include "../modules/hicn_light/route.h"
+}
+
+#include "common.h"
+
+namespace {
+
+const hc_object_t valid_route = {
+ .route = {.face_id = 1,
+ .face_name = {0}, // NULL, use face_id instead
+ .family = AF_INET,
+ .remote_addr = IPV4_LOOPBACK,
+ .len = 16,
+ .cost = 1,
+ .face = {0}}};
+
+const std::vector<uint8_t> valid_route_create_payload = {
+ /* uint8_t message_type = REQUEST_LIGHT */
+ 0xc0,
+ /* uint8_t command_id = COMMAND_TYPE_ROUTE_ADD */
+ 0x08,
+ /* uint16_t length = 1 */
+ 0x01, 0x00,
+ /* uint32_t seq_num = 0 */
+ 0x00, 0x00, 0x00, 0x00,
+ /* char symbolic_or_connid[16] = "1\0" */
+ 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* hicn_ip_address_t address = {0, 0, 0, 127.0.0.1} */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x7f, 0x00, 0x00, 0x01,
+ /* */
+ 0x01,
+ /* */
+ 0x00,
+ /* */
+ 0x02,
+ /* */
+ 0x10};
+
+const std::vector<uint8_t> valid_route_delete_payload = {
+ /* uint8_t message_type = REQUEST_LIGHT */
+ 0xc0,
+ /* uint8_t command_id = COMMAND_TYPE_ROUTE_REMOVE */
+ 0x09,
+ /* uint16_t length = 1 */
+ 0x01, 0x00,
+ /* uint32_t seq_num = 0 */
+ 0x00, 0x00, 0x00, 0x00,
+
+ /* char symbolic_or_connid[16] = "1\0" */
+ 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ /* hicn_ip_address_t address = {0, 0, 0, 127.0.0.1} */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x7f, 0x00, 0x00, 0x01,
+ /* uint8_t family = AF_INET (2) */
+ 0x02,
+ /* uint8_t len = 16 */
+ 0x10,
+ /* 2-byte padding */
+ 0x00, 0x00};
+
+const std::vector<uint8_t> valid_route_list_payload = {0xc0, 0x0a, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00};
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeRouteCreate) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.route, &valid_route, sizeof(hc_route_t));
+
+ hc_serialize_t fn = hicnlight_route_module_ops.serialize[ACTION_CREATE];
+ size_t n = fn(&obj, buf);
+
+ EXPECT_EQ(n, valid_route_create_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_route_create_payload);
+}
+
+// TODO
+// - create with id != 0
+// - create with invalid fields, non zero-terminated strings, etc.
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeRouteDelete) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.route, &valid_route, sizeof(hc_route_t));
+
+ hc_serialize_t fn = hicnlight_route_module_ops.serialize[ACTION_DELETE];
+ size_t n = fn(&obj, buf);
+
+ EXPECT_EQ(n, valid_route_delete_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_route_delete_payload);
+}
+
+TEST_F(TestHicnLightSerialize, TestHicnLightSerializeRouteList) {
+ uint8_t buf[BUFSIZE];
+
+ hc_object_t obj;
+ memset(&obj, 0, sizeof(hc_object_t));
+ memcpy(&obj.route, &valid_route, sizeof(hc_route_t));
+
+ hc_serialize_t fn = hicnlight_route_module_ops.serialize[ACTION_LIST];
+ size_t n = fn(&obj, buf);
+
+ EXPECT_EQ(n, valid_route_list_payload.size());
+ EXPECT_PAYLOAD_EQ(buf, n, valid_route_list_payload);
+}
+
+} // namespace
diff --git a/ctrl/libhicnctrl/src/util/hash.h b/ctrl/libhicnctrl/src/util/hash.h
index 7c7bb1e3a..f3a1eedcc 100644
--- a/ctrl/libhicnctrl/src/util/hash.h
+++ b/ctrl/libhicnctrl/src/util/hash.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -27,67 +27,88 @@
#ifndef UTIL_HASH_H
#define UTIL_HASH_H
-#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
- __BYTE_ORDER == __LITTLE_ENDIAN) || \
+#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
+ __BYTE_ORDER == __LITTLE_ENDIAN) || \
(defined(i386) || defined(__i386__) || defined(__i486__) || \
- defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
-# define HASH_LITTLE_ENDIAN 1
-# define HASH_BIG_ENDIAN 0
+ defined(__i586__) || defined(__i686__) || defined(vax) || \
+ defined(MIPSEL))
+#define HASH_LITTLE_ENDIAN 1
+#define HASH_BIG_ENDIAN 0
#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
- __BYTE_ORDER == __BIG_ENDIAN) || \
- (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
-# define HASH_LITTLE_ENDIAN 0
-# define HASH_BIG_ENDIAN 1
+ __BYTE_ORDER == __BIG_ENDIAN) || \
+ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
+#define HASH_LITTLE_ENDIAN 0
+#define HASH_BIG_ENDIAN 1
#else
-# define HASH_LITTLE_ENDIAN 0
-# define HASH_BIG_ENDIAN 0
+#define HASH_LITTLE_ENDIAN 0
+#define HASH_BIG_ENDIAN 0
#endif
-#define hashsize(n) ((uint32_t)1<<(n))
-#define hashmask(n) (hashsize(n)-1)
-#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
-
-#define mix(a,b,c) \
-{ \
- a -= c; a ^= rot(c, 4); c += b; \
- b -= a; b ^= rot(a, 6); a += c; \
- c -= b; c ^= rot(b, 8); b += a; \
- a -= c; a ^= rot(c,16); c += b; \
- b -= a; b ^= rot(a,19); a += c; \
- c -= b; c ^= rot(b, 4); b += a; \
-}
+#define hashsize(n) ((uint32_t)1 << (n))
+#define hashmask(n) (hashsize(n) - 1)
+#define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
-#define final(a,b,c) \
-{ \
- c ^= b; c -= rot(b,14); \
- a ^= c; a -= rot(c,11); \
- b ^= a; b -= rot(a,25); \
- c ^= b; c -= rot(b,16); \
- a ^= c; a -= rot(c,4); \
- b ^= a; b -= rot(a,14); \
- c ^= b; c -= rot(b,24); \
-}
+#define mix(a, b, c) \
+ { \
+ a -= c; \
+ a ^= rot(c, 4); \
+ c += b; \
+ b -= a; \
+ b ^= rot(a, 6); \
+ a += c; \
+ c -= b; \
+ c ^= rot(b, 8); \
+ b += a; \
+ a -= c; \
+ a ^= rot(c, 16); \
+ c += b; \
+ b -= a; \
+ b ^= rot(a, 19); \
+ a += c; \
+ c -= b; \
+ c ^= rot(b, 4); \
+ b += a; \
+ }
-static inline
-uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
-{
- uint32_t a,b,c; /* internal state */
- union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+#define final(a, b, c) \
+ { \
+ c ^= b; \
+ c -= rot(b, 14); \
+ a ^= c; \
+ a -= rot(c, 11); \
+ b ^= a; \
+ b -= rot(a, 25); \
+ c ^= b; \
+ c -= rot(b, 16); \
+ a ^= c; \
+ a -= rot(c, 4); \
+ b ^= a; \
+ b -= rot(a, 14); \
+ c ^= b; \
+ c -= rot(b, 24); \
+ }
+
+static inline uint32_t hashlittle(const void *key, size_t length,
+ uint32_t initval) {
+ uint32_t a, b, c; /* internal state */
+ union {
+ const void *ptr;
+ size_t i;
+ } u; /* needed for Mac Powerbook G4 */
/* Set up the internal state */
a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
u.ptr = key;
if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
- const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
- while (length > 12)
- {
+ while (length > 12) {
a += k[0];
b += k[1];
c += k[2];
- mix(a,b,c);
+ mix(a, b, c);
length -= 12;
k += 3;
}
@@ -104,136 +125,214 @@ uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
*/
#ifndef VALGRIND
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
- case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
- case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
- case 6 : b+=k[1]&0xffff; a+=k[0]; break;
- case 5 : b+=k[1]&0xff; a+=k[0]; break;
- case 4 : a+=k[0]; break;
- case 3 : a+=k[0]&0xffffff; break;
- case 2 : a+=k[0]&0xffff; break;
- case 1 : a+=k[0]&0xff; break;
- case 0 : return c; /* zero length strings require no mixing */
+ switch (length) {
+ case 12:
+ c += k[2];
+ b += k[1];
+ a += k[0];
+ break;
+ case 11:
+ c += k[2] & 0xffffff;
+ b += k[1];
+ a += k[0];
+ break;
+ case 10:
+ c += k[2] & 0xffff;
+ b += k[1];
+ a += k[0];
+ break;
+ case 9:
+ c += k[2] & 0xff;
+ b += k[1];
+ a += k[0];
+ break;
+ case 8:
+ b += k[1];
+ a += k[0];
+ break;
+ case 7:
+ b += k[1] & 0xffffff;
+ a += k[0];
+ break;
+ case 6:
+ b += k[1] & 0xffff;
+ a += k[0];
+ break;
+ case 5:
+ b += k[1] & 0xff;
+ a += k[0];
+ break;
+ case 4:
+ a += k[0];
+ break;
+ case 3:
+ a += k[0] & 0xffffff;
+ break;
+ case 2:
+ a += k[0] & 0xffff;
+ break;
+ case 1:
+ a += k[0] & 0xff;
+ break;
+ case 0:
+ return c; /* zero length strings require no mixing */
}
#else /* make valgrind happy */
k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]; break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
- case 1 : a+=k8[0]; break;
- case 0 : return c;
+ switch (length) {
+ case 12:
+ c += k[2];
+ b += k[1];
+ a += k[0];
+ break;
+ case 11:
+ c += ((uint32_t)k8[10]) << 16; /* fall through */
+ case 10:
+ c += ((uint32_t)k8[9]) << 8; /* fall through */
+ case 9:
+ c += k8[8]; /* fall through */
+ case 8:
+ b += k[1];
+ a += k[0];
+ break;
+ case 7:
+ b += ((uint32_t)k8[6]) << 16; /* fall through */
+ case 6:
+ b += ((uint32_t)k8[5]) << 8; /* fall through */
+ case 5:
+ b += k8[4]; /* fall through */
+ case 4:
+ a += k[0];
+ break;
+ case 3:
+ a += ((uint32_t)k8[2]) << 16; /* fall through */
+ case 2:
+ a += ((uint32_t)k8[1]) << 8; /* fall through */
+ case 1:
+ a += k8[0];
+ break;
+ case 0:
+ return c;
}
#endif /* !valgrind */
} else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
- const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
- const uint8_t *k8;
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
/*--------------- all but last block: aligned reads and different mixing */
- while (length > 12)
- {
- a += k[0] + (((uint32_t)k[1])<<16);
- b += k[2] + (((uint32_t)k[3])<<16);
- c += k[4] + (((uint32_t)k[5])<<16);
- mix(a,b,c);
+ while (length > 12) {
+ a += k[0] + (((uint32_t)k[1]) << 16);
+ b += k[2] + (((uint32_t)k[3]) << 16);
+ c += k[4] + (((uint32_t)k[5]) << 16);
+ mix(a, b, c);
length -= 12;
k += 6;
}
/*----------------------------- handle the last (probably partial) block */
k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[4]+(((uint32_t)k[5])<<16);
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=k[4];
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=k[2];
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=k[0];
- break;
- case 1 : a+=k8[0];
- break;
- case 0 : return c; /* zero length requires no mixing */
+ switch (length) {
+ case 12:
+ c += k[4] + (((uint32_t)k[5]) << 16);
+ b += k[2] + (((uint32_t)k[3]) << 16);
+ a += k[0] + (((uint32_t)k[1]) << 16);
+ break;
+ case 11:
+ c += ((uint32_t)k8[10]) << 16; /* fall through */
+ case 10:
+ c += k[4];
+ b += k[2] + (((uint32_t)k[3]) << 16);
+ a += k[0] + (((uint32_t)k[1]) << 16);
+ break;
+ case 9:
+ c += k8[8]; /* fall through */
+ case 8:
+ b += k[2] + (((uint32_t)k[3]) << 16);
+ a += k[0] + (((uint32_t)k[1]) << 16);
+ break;
+ case 7:
+ b += ((uint32_t)k8[6]) << 16; /* fall through */
+ case 6:
+ b += k[2];
+ a += k[0] + (((uint32_t)k[1]) << 16);
+ break;
+ case 5:
+ b += k8[4]; /* fall through */
+ case 4:
+ a += k[0] + (((uint32_t)k[1]) << 16);
+ break;
+ case 3:
+ a += ((uint32_t)k8[2]) << 16; /* fall through */
+ case 2:
+ a += k[0];
+ break;
+ case 1:
+ a += k8[0];
+ break;
+ case 0:
+ return c; /* zero length requires no mixing */
}
- } else { /* need to read the key one byte at a time */
+ } else { /* need to read the key one byte at a time */
const uint8_t *k = (const uint8_t *)key;
/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
- while (length > 12)
- {
+ while (length > 12) {
a += k[0];
- a += ((uint32_t)k[1])<<8;
- a += ((uint32_t)k[2])<<16;
- a += ((uint32_t)k[3])<<24;
+ a += ((uint32_t)k[1]) << 8;
+ a += ((uint32_t)k[2]) << 16;
+ a += ((uint32_t)k[3]) << 24;
b += k[4];
- b += ((uint32_t)k[5])<<8;
- b += ((uint32_t)k[6])<<16;
- b += ((uint32_t)k[7])<<24;
+ b += ((uint32_t)k[5]) << 8;
+ b += ((uint32_t)k[6]) << 16;
+ b += ((uint32_t)k[7]) << 24;
c += k[8];
- c += ((uint32_t)k[9])<<8;
- c += ((uint32_t)k[10])<<16;
- c += ((uint32_t)k[11])<<24;
- mix(a,b,c);
+ c += ((uint32_t)k[9]) << 8;
+ c += ((uint32_t)k[10]) << 16;
+ c += ((uint32_t)k[11]) << 24;
+ mix(a, b, c);
length -= 12;
k += 12;
}
/*-------------------------------- last block: affect all 32 bits of (c) */
- switch(length) /* all the case statements fall through */
+ switch (length) /* all the case statements fall through */
{
- case 12: c+=((uint32_t)k[11])<<24;
- case 11: c+=((uint32_t)k[10])<<16;
- case 10: c+=((uint32_t)k[9])<<8;
- case 9 : c+=k[8];
- case 8 : b+=((uint32_t)k[7])<<24;
- case 7 : b+=((uint32_t)k[6])<<16;
- case 6 : b+=((uint32_t)k[5])<<8;
- case 5 : b+=k[4];
- case 4 : a+=((uint32_t)k[3])<<24;
- case 3 : a+=((uint32_t)k[2])<<16;
- case 2 : a+=((uint32_t)k[1])<<8;
- case 1 : a+=k[0];
- break;
- case 0 : return c;
+ case 12:
+ c += ((uint32_t)k[11]) << 24;
+ case 11:
+ c += ((uint32_t)k[10]) << 16;
+ case 10:
+ c += ((uint32_t)k[9]) << 8;
+ case 9:
+ c += k[8];
+ case 8:
+ b += ((uint32_t)k[7]) << 24;
+ case 7:
+ b += ((uint32_t)k[6]) << 16;
+ case 6:
+ b += ((uint32_t)k[5]) << 8;
+ case 5:
+ b += k[4];
+ case 4:
+ a += ((uint32_t)k[3]) << 24;
+ case 3:
+ a += ((uint32_t)k[2]) << 16;
+ case 2:
+ a += ((uint32_t)k[1]) << 8;
+ case 1:
+ a += k[0];
+ break;
+ case 0:
+ return c;
}
}
- final(a,b,c);
+ final(a, b, c);
return c;
}
@@ -241,7 +340,7 @@ uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
#define HASH_INITVAL 1
//#define hash(buf, len) (hash_t)hashlittle(buf, len, HASH_INITVAL)
-#define hash(buf, len) hashlittle(buf, len, HASH_INITVAL)
+#define hash(buf, len) hashlittle(buf, len, HASH_INITVAL)
#define hash_struct(buf) hash(buf, sizeof(buf))
#endif /* UTIL_JENKINS_HASH_H */
diff --git a/ctrl/sysrepo-plugins/AUTHORS b/ctrl/sysrepo-plugins/AUTHORS
deleted file mode 100644
index 35097a36c..000000000
--- a/ctrl/sysrepo-plugins/AUTHORS
+++ /dev/null
@@ -1,5 +0,0 @@
-hicn sysrepo plugin authors are listed below:
-
- Masoud Hemmatpour <mhemmatp@cisco.com>
- Alberto Compagno <acompagn@cisco.com>
- Luca Muscariello <lumuscar@cisco.com>
diff --git a/ctrl/sysrepo-plugins/CMakeLists.txt b/ctrl/sysrepo-plugins/CMakeLists.txt
deleted file mode 100644
index 2412d5688..000000000
--- a/ctrl/sysrepo-plugins/CMakeLists.txt
+++ /dev/null
@@ -1,69 +0,0 @@
-#
-# Copyright (c) 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.10 FATAL_ERROR)
-project(hicn_sysrepo_plugin)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
-"${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/Modules"
-)
-
-include(GNUInstallDirs)
-include(BuildMacros)
-
-find_package(PkgConfig REQUIRED)
-find_package(Sysrepo REQUIRED)
-
-if (NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
- message(FATAL_ERROR "Sysrepo plugin supported only on Linux systems")
-endif()
-
-if (NOT SRPD_PLUGINS_PATH)
- if (PKG_CONFIG_FOUND)
- execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} "--variable=SRPD_PLUGINS_PATH" "libsysrepo" OUTPUT_VARIABLE SRPD_PLUGINS_PATH)
- string(STRIP ${SRPD_PLUGINS_PATH} SRPD_PLUGINS_PATH)
- endif()
-endif()
-
-if (NOT SRPD_PLUGINS_PATH)
- message(FATAL_ERROR "Cannot get sysrepo plugins directory due to missing pkg-config, set SRPD_PLUGINS_PATH manually.")
-endif()
-
-find_package(Vpp REQUIRED)
-
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- find_package(HicnPlugin REQUIRED)
-else()
- list(APPEND DEPENDENCIES
- hicn_plugin
- )
-endif()
-
-add_subdirectory(hicn-plugin)
-
-INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/yang/hicn/hicn.yang
- ${CMAKE_CURRENT_SOURCE_DIR}/yang/ietf/iana-if-type@2014-05-08.yang
- ${CMAKE_CURRENT_SOURCE_DIR}/yang/ietf/ietf-interfaces.yang
- ${CMAKE_CURRENT_SOURCE_DIR}/yang/ietf/ietf-ip@2014-06-16.yang
- ${CMAKE_CURRENT_SOURCE_DIR}/yang/ietf/ietf-yang-types@2013-07-15.yang
- DESTINATION ${CMAKE_INSTALL_LIBDIR}/modules_yang/
- COMPONENT hicn-sysrepo-plugin)
-
-
-include(Packaging)
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
-endif()
diff --git a/ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake b/ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake
deleted file mode 100644
index 323c9d01a..000000000
--- a/ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake
+++ /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.
-
-######################
-# Packages section
-######################
-
-set(hicn-sysrepo-plugin_DESCRIPTION
- "A Plugin to enable hICN VPP in sysrepo."
- CACHE STRING "Description for deb/rpm package."
-)
-
-set(hicn-sysrepo-plugin_DEB_DEPENDENCIES
- "hicn-plugin (>= stable_version-release), sysrepo (>= 1.0)"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(hicn-sysrepo-plugin_RPM_DEPENDENCIES
- "hicn-plugin >= stable_version-release, sysrepo >= 1.0"
- CACHE STRING "Dependencies for deb/rpm package."
-)
diff --git a/ctrl/sysrepo-plugins/hicn-light/CMakeLists.txt b/ctrl/sysrepo-plugins/hicn-light/CMakeLists.txt
deleted file mode 100644
index 5ba7045c1..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/CMakeLists.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-#
-# Copyright (c) 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.
-#
-
-# set compiler options
-set(CMAKE_EXPORT_COMPILE_COMMANDS 1)
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -std=gnu99")
-set(CMAKE_C_FLAGS_RELEASE "-DNDEBUG -O2")
-set(CMAKE_C_FLAGS_DEBUG "-g -O0")
-set (CMAKE_INSTALL_LIBDIR "/usr/lib")
-
-project(sysrepo-light-plugins)
-
-# Cmake find modules
-list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/../cmake/Modules"
-"${CMAKE_CURRENT_LIST_DIR}/../../../cmake/Modules"
-)
-
-find_package(PkgConfig)
-find_package(HicnLight)
-find_package(Sysrepo)
-
-#pkg_check_modules(SYSREPO libsysrepo)
-
-# get sysrepo plugins directory from pkgconfig
-if (NOT SR_PLUGINS_DIR)
- if (PKG_CONFIG_FOUND)
- execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} "--variable=SR_PLUGINS_DIR" "libsysrepo" OUTPUT_VARIABLE SR_PLUGINS_DIR)
- string(STRIP ${SR_PLUGINS_DIR} SR_PLUGINS_DIR)
- endif()
-endif()
-if (NOT SR_PLUGINS_DIR)
- message(FATAL_ERROR "Cannot get sysrepo plugins directory due to missing pkg-config, set SR_PLUGINS_DIR manually.")
-endif()
-
-# plugins sources
-set(PLUGINS_SOURCES
- plugin/model/hicn_model.c
- plugin/model/tlock.c
- plugin/hicn_light_comm.c
- plugin/hicn_light.c
-)
-
-# build the source code into shared library
-add_library(hicnlight SHARED ${PLUGINS_SOURCES})
-target_include_directories(hicnlight PUBLIC ${HICNLIGHT_INCLUDE_DIRS})
-target_link_libraries(hicnlight ${SYSREPO_LIBRARIES} ${HICNLIGHT_LIBRARIES})
-
-# install the plugin into plugins dir
-install(TARGETS hicnlight DESTINATION ${SR_PLUGINS_DIR} COMPONENT hicn_sysrepo_plugin)
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt b/ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt
deleted file mode 100644
index 85da0d3e9..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt
+++ /dev/null
@@ -1,59 +0,0 @@
-#
-# Copyright (c) 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.
-#
-
-# set compiler options
-set(CMAKE_EXPORT_COMPILE_COMMANDS 1)
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -std=gnu99")
-set(CMAKE_C_FLAGS_RELEASE "-DNDEBUG -O2")
-set(CMAKE_C_FLAGS_DEBUG "-g -O0")
-set (CMAKE_INSTALL_LIBDIR "/usr/lib")
-
-project(sysrepo-light-plugins)
-
-# Cmake find modules
-list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/../cmake")
-
-find_package(PkgConfig)
-find_package(HicnLight)
-find_package(Sysrepo)
-
-#pkg_check_modules(SYSREPO libsysrepo)
-
-# get sysrepo plugins directory from pkgconfig
-if (NOT SR_PLUGINS_DIR)
- if (PKG_CONFIG_FOUND)
- execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} "--variable=SR_PLUGINS_DIR" "libsysrepo" OUTPUT_VARIABLE SR_PLUGINS_DIR)
- string(STRIP ${SR_PLUGINS_DIR} SR_PLUGINS_DIR)
- endif()
-endif()
-if (NOT SR_PLUGINS_DIR)
- message(FATAL_ERROR "Cannot get sysrepo plugins directory due to missing pkg-config, set SR_PLUGINS_DIR manually.")
-endif()
-
-# plugins sources
-set(PLUGINS_SOURCES
- model/hicn_model.c
- model/tlock.c
- hicn_light_comm.c
- hicn_light.c
-)
-
-# build the source code into shared library
-add_library(hicnlight SHARED ${PLUGINS_SOURCES})
-target_include_directories(hicnlight PUBLIC ${HICNLIGHT_INCLUDE_DIRS})
-target_link_libraries(hicnlight ${SYSREPO_LIBRARIES} ${HICNLIGHT_LIBRARIES})
-
-# install the plugin into plugins dir
-install(TARGETS hicnlight DESTINATION ${SR_PLUGINS_DIR} COMPONENT hicn_sysrepo_plugin) \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c
deleted file mode 100644
index 6cfc0b52b..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (c) 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 <inttypes.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include "hicn_light.h"
-#include "model/hicn_model.h"
-
-
-
-sr_subscription_ctx_t *subscription = NULL;
-volatile int exit_application = 0;
-
-int sr_plugin_init_cb(sr_session_ctx_t *session, void **private_ctx) {
- sr_subscription_ctx_t *subscription = NULL;
- int rc = SR_ERR_OK;
- rc = hicn_connect_light();
- if (SR_ERR_OK != rc) {
- HICN_LOG_ERR("hicn light connect error , with return %d.", rc);
- return SR_ERR_INTERNAL;
- }
-
- hicn_subscribe_events(session, &subscription);
-
-
- /* set subscription as our private context */
- *private_ctx = subscription;
- return SR_ERR_OK;
-}
-
-void sr_plugin_cleanup_cb(sr_session_ctx_t *session, void *private_ctx) {
- /* subscription was set as our private context */
- sr_unsubscribe(private_ctx);
- HICN_LOG_DBG_MSG("hicn light unload plugin ok.");
- hicn_disconnect_light();
- HICN_LOG_DBG_MSG("hicn light disconnect ok.");
-}
-
-static void sigint_handler(int signum) { exit_application = 1; }
-int subscribe_all_module_events(sr_session_ctx_t *session) {
- sr_plugin_init_cb(session, (void **)&subscription);
- return 0;
-}
-
-int main(int argc, char **argv) {
- sr_conn_ctx_t *connection = NULL;
- sr_session_ctx_t *session = NULL;
- int rc = SR_ERR_OK;
-
- /* connect to hicn light */
- rc = hicn_connect_light();
- if (-1 == rc) {
- fprintf(stderr, "hicn light connect error");
- return -1;
- }
-
- /* connect to sysrepo */
- rc = sr_connect(SR_CONN_DEFAULT, &connection);
- if (SR_ERR_OK != rc) {
- fprintf(stderr, "Error by sr_connect: %s\n", sr_strerror(rc));
- goto cleanup;
- }
-
- /* start session */
- rc = sr_session_start(connection, SR_DS_STARTUP, &session);
- if (SR_ERR_OK != rc) {
- fprintf(stderr, "Error by sr_session_start: %s\n", sr_strerror(rc));
- goto cleanup;
- }
-
- /* subscribe all module events */
- rc = subscribe_all_module_events(session);
- if (SR_ERR_OK != rc) {
- fprintf(stderr, "Error by subscribe module events: %s\n", sr_strerror(rc));
- goto cleanup;
- }
-
- /* loop until ctrl-c is pressed / SIGINT is received */
- signal(SIGINT, sigint_handler);
- signal(SIGPIPE, SIG_IGN);
-
- while (!exit_application) {
- sleep(2);
- }
-
- printf("Application exit requested, exiting.\n");
-
-cleanup:
- if (NULL != subscription) {
- sr_unsubscribe(subscription);
- }
- if (NULL != session) {
- sr_session_stop(session);
- }
- if (NULL != connection) {
- sr_disconnect(connection);
- }
- hicn_disconnect_light();
- return rc;
-} \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c
deleted file mode 100644
index 6c4f938ce..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 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_light_comm.h"
-
-hc_sock_t * hsocket;
-
-int hicn_connect_light() {
-
- hsocket = hc_sock_create();
- if (!hsocket)
- HICN_LOG_ERR_MSG("Error creating socket\n");
- if (hc_sock_connect(hsocket) < 0)
- HICN_LOG_ERR_MSG("Error connecting to the forwarder\n");
- return 0;
-
-}
-
-int hicn_disconnect_light() {
- hc_sock_free(hsocket);
- return 0;
-} \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.h b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.h
deleted file mode 100644
index ca67cf0b7..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 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.
- */
-
-#ifndef __HICN_LIGHT_COMMM_H__
-#define __HICN_LIGHT_COMMM_H__
-#include <sysrepo.h>
-#include <sysrepo/values.h>
-
-
-#include <hicn/ctrl/api.h>
-
-#ifndef HICN_THIS_FUNC
-#ifdef __FUNCTION__
-#define HICN_THIS_FUNC __FUNCTION__
-#else
-#define HICN_THIS_FUNC __func__
-#endif
-#endif
-
-#define ARG_CHECK(retval, arg) \
- do { \
- if (NULL == (arg)) { \
- HICN_LOG_ERR_MSG(#arg ":NULL pointer passed."); \
- return (retval); \
- } \
- } while (0)
-
-
-
-#define ARG_CHECK2(retval, arg1, arg2) \
- ARG_CHECK(retval, arg1); \
- ARG_CHECK(retval, arg2)
-
-#define ARG_CHECK5(retval, arg1, arg2, arg3, arg4, arg5) \
- ARG_CHECK(retval, arg1); \
- ARG_CHECK(retval, arg2); \
- ARG_CHECK(retval, arg3); \
- ARG_CHECK(retval, arg4); \
- ARG_CHECK(retval, arg5)
-
-
-#define MEM_ALIGN 4096
-
-int hicn_connect_light();
-int hicn_disconnect_light();
-extern hc_sock_t * hsocket;
-#endif //__HICN_LIGHT_COMMM_H__
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.c b/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.c
deleted file mode 100644
index 47e07d196..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.c
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (c) 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 <stdio.h>
-#include <malloc.h>
-#include <sysrepo/xpath.h>
-
-/* Hicn headers */
-
-#include "hicn_model.h"
-#include "tlock.h"
-#include "../hicn_light.h"
-#include "../hicn_light_comm.h"
-
-
-
-/**
- * @brief API to add hicn face ip in hicn-light.
- */
-static int hicn_face_ip_add_cb(sr_session_ctx_t *session, const char *path, const sr_val_t *input, const size_t input_cnt,
- sr_event_t event, uint32_t request_id, sr_val_t **output, size_t *output_cnt, void *private_data) {
-
- SRP_LOG_DBGMSG("hicn face ip add received successfully");
- hc_face_t face;
- if(strcmp(input[0].data.string_val,"-1")){
-
- struct sockaddr_in sa;
- // store this IP address in sa:
- inet_pton(AF_INET, input[0].data.string_val, &(sa.sin_addr));
- face.face.family=AF_INET;
- face.face.local_addr.v4.as_inaddr=sa.sin_addr;
-
-
- }else if(strcmp(input[1].data.string_val,"-1")){
-
- struct in6_addr *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, input[1].data.string_val, dst);
- face.face.family=AF_INET6;
- face.face.local_addr.v6.as_in6addr = *dst;
-
- }else{
- SRP_LOG_DBGMSG("Invalid local IP address");
- return SR_ERR_OPERATION_FAILED;
- }
-
- if(strcmp(input[2].data.string_val,"-1")){
-
- struct sockaddr_in sa;
- // store this IP address in sa:
- inet_pton(AF_INET, input[2].data.string_val, &(sa.sin_addr));
- face.face.family=AF_INET;
- face.face.remote_addr.v4.as_inaddr=sa.sin_addr;
-
-
- }else if(strcmp(input[3].data.string_val,"-1")){
-
- struct in6_addr *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, input[3].data.string_val, dst);
- face.face.family=AF_INET6;
- face.face.remote_addr.v6.as_in6addr = *dst;
-
- }else{
- SRP_LOG_DBGMSG("Invalid local IP address");
- return SR_ERR_OPERATION_FAILED;
- }
-
-
- face.face.netdevice.index = input[4].data.uint32_val; // This is the idx number of interface
-
-
- face.id=0;//can be empty
- strcpy(face.name,"hicn_face");
- face.face.type=1;
-
- int rc;
- rc = hc_face_create(hsocket, &face);
- if (rc > 0) {
- SRP_LOG_DBGMSG("Face added successfully");
- return SR_ERR_OK;
- }
-
- SRP_LOG_DBGMSG("Operation Failed");
- return SR_ERR_OPERATION_FAILED;
-}
-
-/**
- * @brief API to del hicn face ip in vpp.
- */
-static int hicn_face_ip_del_cb(sr_session_ctx_t *session, const char *path, const sr_val_t *input, const size_t input_cnt,
- sr_event_t event, uint32_t request_id, sr_val_t **output, size_t *output_cnt, void *private_data) {
-
- SRP_LOG_DBGMSG("hicn face ip del received successfully");
- face_t * face=NULL;
-
-
- face_free(face);
-
-
-
- SRP_LOG_DBGMSG("Operation Failed");
- return SR_ERR_OPERATION_FAILED;
-
-}
-
-
-/**
- * @brief API to del hicn face ip in vpp.
- */
-static int hicn_route_add_cb(sr_session_ctx_t *session, const char *path, const sr_val_t *input, const size_t input_cnt,
- sr_event_t event, uint32_t request_id, sr_val_t **output, size_t *output_cnt, void *private_data) {
-
-/*
-
- SRP_LOG_DBG_MSG("hicn route add received successfully");
-
- hc_route_t * route;
-
- if(strcmp(input[0].data.string_val,"-1")){
-
- struct sockaddr_in sa;
- // store this IP address in sa:
- inet_pton(AF_INET, input[0].data.string_val, &(sa.sin_addr));
- route.family=AF_INET;
- route.face.hicn.local_addr.v4.as_inaddr=sa.sin_addr;
-
-
- }else if(strcmp(input[1].data.string_val,"-1")){
-
- struct in6_addr *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, input[1].data.string_val, dst);
- face.face.hicn.family=AF_INET6;
- face.face.hicn.local_addr.v6.as_in6addr = *dst;
-
- }else{
- SRP_LOG_DBG_MSG("Invalid local IP address");
- return SR_ERR_OPERATION_FAILED;
- }
-
-
-hc_route_create(hsocket, route);
-*/
- return SR_ERR_OK;
-}
-
-
-
-int hicn_subscribe_events(sr_session_ctx_t *session,
- sr_subscription_ctx_t **subscription) {
-
-
- int rc;
- rc = sr_rpc_subscribe(session, "/hicn:face-ip-add", hicn_face_ip_add_cb,
- session, 100,SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription stat-get\n");
- goto error;
- }
-
-
- rc = sr_rpc_subscribe(session, "/hicn:face-ip-del", hicn_face_ip_del_cb,
- session, 100,SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription face-ip-del\n");
- goto error;
- }
-
-
- rc = sr_rpc_subscribe(session, "/hicn:route-nhops-add",
- hicn_route_add_cb, session, 100,SR_SUBSCR_CTX_REUSE, subscription);
- if (rc!= SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription route-nhops-add\n");
- goto error;
- }
-
-
- SRP_LOG_DBGMSG("hicn light initialized successfully.");
- return SR_ERR_OK;
-
-error:
- SRP_LOG_ERRMSG("Error by initialization of the hicn plugin.");
- sr_plugin_cleanup_cb(session, hsocket);
- return rc;
-
-}
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.h b/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.h
deleted file mode 100644
index e6e857bff..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 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.
- */
-
-#ifndef __IETF_HICN_H__
-#define __IETF_HICN_H__
-
-#include "../hicn_light_comm.h"
-
-
-#define MEM_ALIGN 4096
-
-// Number of locks is equal to number of nodes in hicn-state
-// It is a coarse grain approach later can be changed to fine grained
-// better to initialize the lock by 0
-#define NLOCKS 5
-#define LOCK_INIT 0
-
-
-enum locks_name {lstate, lstrategy, lstrategies, lroute, lface_ip_params};
-
-#define NSTATE_LEAVES 15
-#define NSTRATEGY_LEAVES 1
-#define NSTRATEGIES_LEAVES 2
-#define NROUTE_LEAVES 2
-#define NFACE_IP_PARAMS_LEAVES 3
-
-int hicn_subscribe_events(sr_session_ctx_t *session,
- sr_subscription_ctx_t **subscription);
-
-#endif /* __IETF_HICN_H__ */ \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c b/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c
deleted file mode 100644
index 2f7b11efa..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c
+++ /dev/null
@@ -1,21 +0,0 @@
-#include"tlock.h"
-
-
-void Ticket_init ( int Lock_Number , long int init ){
-
-__atomic_store( &En[Lock_Number] , &init , __ATOMIC_SEQ_CST );
-__atomic_store( &De[Lock_Number] , &init , __ATOMIC_SEQ_CST );
-//En[Lock_Number]=init;
-//De[Lock_Number]=init;
-}
-
-void Ticket_Lock(int Lock_Number ){
-
- int my_ticket = __sync_fetch_and_add(&En[Lock_Number] , 1 );
- while ( my_ticket != De[ Lock_Number ] ) {};
-
-}
-
-void Ticket_Unlock(int Lock_Number ){
-De[Lock_Number]++;
-}
diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.h b/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.h
deleted file mode 100644
index 36698115a..000000000
--- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 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.
- */
-
-
-#ifndef __TLOCK_H__
-#define __TLOCK_H__
-
-
-// limit on the number of locks: it shoud be matched with the number of hicn-state leaves
-#define MAX_LOCK_SIZE 5
-
-volatile long int En[MAX_LOCK_SIZE] , De[MAX_LOCK_SIZE] ; // For Ticket Algorithm
-
-
-void Ticket_init ( int Lock_Number , long int init );
-void Ticket_Lock(int Lock_Number );
-void Ticket_Unlock(int Lock_Number );
-
-#endif /* __IETF_HICN_H__ */ \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/CMakeLists.txt b/ctrl/sysrepo-plugins/hicn-plugin/CMakeLists.txt
deleted file mode 100644
index 10e106f51..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/CMakeLists.txt
+++ /dev/null
@@ -1,49 +0,0 @@
-#
-# Copyright (c) 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 find modules
-list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/../../../cmake/Modules"
- "${CMAKE_CURRENT_LIST_DIR}/../cmake/Modules"
-)
-
-# plugins sources
-set(SOURCE_FILES
- plugin/ietf/ietf_interface.c
- plugin/model/hicn_model.c
- plugin/model/tlock.c
- plugin/hicn_vpp_comm.c
- plugin/hicn_plugin.c
-)
-
-list(APPEND SYSREPO_PLUGIN_INCLUDE_DIRS
- ${VPP_INCLUDE_DIRS}
- ${HICNPLUGIN_INCLUDE_DIRS}
- ${SYSREPO_INCLUDE_DIRS}
-)
-
-list(APPEND LIBRARIES
- ${SYSREPO_LIBRARIES}
- ${VPP_LIBRARIES}
-)
-
-build_library(sysrepohicn
- SHARED
- SOURCES ${SOURCE_FILES}
- LINK_LIBRARIES ${LIBRARIES}
- DEPENDS ${DEPENDENCIES}
- COMPONENT hicn-sysrepo-plugin
- INCLUDE_DIRS ${SYSREPO_PLUGIN_INCLUDE_DIRS}
- INSTALL_FULL_PATH_DIR ${SRPD_PLUGINS_PATH}
- DEFINITIONS ${COMPILER_DEFINITIONS}
-) \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/Doxyfile b/ctrl/sysrepo-plugins/hicn-plugin/Doxyfile
deleted file mode 100644
index 61e503c1f..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/Doxyfile
+++ /dev/null
@@ -1,2494 +0,0 @@
-# Doxyfile 1.8.13
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project.
-#
-# All text after a double hash (##) is considered a comment and is placed in
-# front of the TAG it is preceding.
-#
-# All text after a single hash (#) is considered a comment and will be ignored.
-# The format is:
-# TAG = value [value, ...]
-# For lists, items can also be appended using:
-# TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (\" \").
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# This tag specifies the encoding used for all characters in the config file
-# that follow. The default is UTF-8 which is also the encoding used for all text
-# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
-# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
-# for the list of possible encodings.
-# The default value is: UTF-8.
-
-DOXYFILE_ENCODING = UTF-8
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
-# double-quotes, unless you are using Doxywizard) that should identify the
-# project for which the documentation is generated. This name is used in the
-# title of most generated pages and in a few other places.
-# The default value is: My Project.
-
-PROJECT_NAME = "hICN Sysrepo plugin"
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
-# could be handy for archiving the generated documentation or if some version
-# control system is used.
-
-PROJECT_NUMBER =
-
-# Using the PROJECT_BRIEF tag one can provide an optional one line description
-# for a project that appears at the top of each page and should give viewer a
-# quick idea about the purpose of the project. Keep the description short.
-
-PROJECT_BRIEF =
-
-# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
-# in the documentation. The maximum height of the logo should not exceed 55
-# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
-# the logo to the output directory.
-
-PROJECT_LOGO =
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
-# into which the generated documentation will be written. If a relative path is
-# entered, it will be relative to the location where doxygen was started. If
-# left blank the current directory will be used.
-
-OUTPUT_DIRECTORY =
-
-# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
-# directories (in 2 levels) under the output directory of each output format and
-# will distribute the generated files over these directories. Enabling this
-# option can be useful when feeding doxygen a huge amount of source files, where
-# putting all generated files in the same directory would otherwise causes
-# performance problems for the file system.
-# The default value is: NO.
-
-CREATE_SUBDIRS = NO
-
-# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
-# characters to appear in the names of generated files. If set to NO, non-ASCII
-# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
-# U+3044.
-# The default value is: NO.
-
-ALLOW_UNICODE_NAMES = NO
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all constant output in the proper language.
-# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
-# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
-# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
-# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
-# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
-# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
-# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
-# Ukrainian and Vietnamese.
-# The default value is: English.
-
-OUTPUT_LANGUAGE = English
-
-# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
-# descriptions after the members that are listed in the file and class
-# documentation (similar to Javadoc). Set to NO to disable this.
-# The default value is: YES.
-
-BRIEF_MEMBER_DESC = YES
-
-# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
-# description of a member or function before the detailed description
-#
-# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-# The default value is: YES.
-
-REPEAT_BRIEF = YES
-
-# This tag implements a quasi-intelligent brief description abbreviator that is
-# used to form the text in various listings. Each string in this list, if found
-# as the leading text of the brief description, will be stripped from the text
-# and the result, after processing the whole list, is used as the annotated
-# text. Otherwise, the brief description is used as-is. If left blank, the
-# following values are used ($name is automatically replaced with the name of
-# the entity):The $name class, The $name widget, The $name file, is, provides,
-# specifies, contains, represents, a, an and the.
-
-ABBREVIATE_BRIEF = "The $name class" \
- "The $name widget" \
- "The $name file" \
- is \
- provides \
- specifies \
- contains \
- represents \
- a \
- an \
- the
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# doxygen will generate a detailed section even if there is only a brief
-# description.
-# The default value is: NO.
-
-ALWAYS_DETAILED_SEC = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
-# inherited members of a class in the documentation of that class as if those
-# members were ordinary class members. Constructors, destructors and assignment
-# operators of the base classes will not be shown.
-# The default value is: NO.
-
-INLINE_INHERITED_MEMB = NO
-
-# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
-# before files name in the file list and in the header files. If set to NO the
-# shortest path that makes the file name unique will be used
-# The default value is: YES.
-
-FULL_PATH_NAMES = YES
-
-# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
-# Stripping is only done if one of the specified strings matches the left-hand
-# part of the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the path to
-# strip.
-#
-# Note that you can specify absolute paths here, but also relative paths, which
-# will be relative from the directory where doxygen is started.
-# This tag requires that the tag FULL_PATH_NAMES is set to YES.
-
-STRIP_FROM_PATH =
-
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
-# path mentioned in the documentation of a class, which tells the reader which
-# header file to include in order to use a class. If left blank only the name of
-# the header file containing the class definition is used. Otherwise one should
-# specify the list of include paths that are normally passed to the compiler
-# using the -I flag.
-
-STRIP_FROM_INC_PATH =
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
-# less readable) file names. This can be useful is your file systems doesn't
-# support long names like on DOS, Mac, or CD-ROM.
-# The default value is: NO.
-
-SHORT_NAMES = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
-# first line (until the first dot) of a Javadoc-style comment as the brief
-# description. If set to NO, the Javadoc-style will behave just like regular Qt-
-# style comments (thus requiring an explicit @brief command for a brief
-# description.)
-# The default value is: NO.
-
-JAVADOC_AUTOBRIEF = NO
-
-# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
-# line (until the first dot) of a Qt-style comment as the brief description. If
-# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
-# requiring an explicit \brief command for a brief description.)
-# The default value is: NO.
-
-QT_AUTOBRIEF = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
-# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
-# a brief description. This used to be the default behavior. The new default is
-# to treat a multi-line C++ comment block as a detailed description. Set this
-# tag to YES if you prefer the old behavior instead.
-#
-# Note that setting this tag to YES also means that rational rose comments are
-# not recognized any more.
-# The default value is: NO.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
-# documentation from any documented member that it re-implements.
-# The default value is: YES.
-
-INHERIT_DOCS = YES
-
-# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
-# page for each member. If set to NO, the documentation of a member will be part
-# of the file/class/namespace that contains it.
-# The default value is: NO.
-
-SEPARATE_MEMBER_PAGES = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
-# uses this value to replace tabs by spaces in code fragments.
-# Minimum value: 1, maximum value: 16, default value: 4.
-
-TAB_SIZE = 4
-
-# This tag can be used to specify a number of aliases that act as commands in
-# the documentation. An alias has the form:
-# name=value
-# For example adding
-# "sideeffect=@par Side Effects:\n"
-# will allow you to put the command \sideeffect (or @sideeffect) in the
-# documentation, which will result in a user-defined paragraph with heading
-# "Side Effects:". You can put \n's in the value part of an alias to insert
-# newlines.
-
-ALIASES =
-
-# This tag can be used to specify a number of word-keyword mappings (TCL only).
-# A mapping has the form "name=value". For example adding "class=itcl::class"
-# will allow you to use the command class in the itcl::class meaning.
-
-TCL_SUBST =
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
-# only. Doxygen will then generate output that is more tailored for C. For
-# instance, some of the names that are used will be different. The list of all
-# members will be omitted, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_FOR_C = NO
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
-# Python sources only. Doxygen will then generate output that is more tailored
-# for that language. For instance, namespaces will be presented as packages,
-# qualified scopes will look different, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_JAVA = NO
-
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources. Doxygen will then generate output that is tailored for Fortran.
-# The default value is: NO.
-
-OPTIMIZE_FOR_FORTRAN = NO
-
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for VHDL.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_VHDL = NO
-
-# Doxygen selects the parser to use depending on the extension of the files it
-# parses. With this tag you can assign which parser to use for a given
-# extension. Doxygen has a built-in mapping, but you can override or extend it
-# using this tag. The format is ext=language, where ext is a file extension, and
-# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
-# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
-# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
-# Fortran. In the later case the parser tries to guess whether the code is fixed
-# or free formatted code, this is the default for Fortran type files), VHDL. For
-# instance to make doxygen treat .inc files as Fortran files (default is PHP),
-# and .f files as C (default is Fortran), use: inc=Fortran f=C.
-#
-# Note: For files without extension you can use no_extension as a placeholder.
-#
-# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
-# the files are not read by doxygen.
-
-EXTENSION_MAPPING =
-
-# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
-# according to the Markdown format, which allows for more readable
-# documentation. See http://daringfireball.net/projects/markdown/ for details.
-# The output of markdown processing is further processed by doxygen, so you can
-# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
-# case of backward compatibilities issues.
-# The default value is: YES.
-
-MARKDOWN_SUPPORT = YES
-
-# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
-# to that level are automatically included in the table of contents, even if
-# they do not have an id attribute.
-# Note: This feature currently applies only to Markdown headings.
-# Minimum value: 0, maximum value: 99, default value: 0.
-# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
-
-TOC_INCLUDE_HEADINGS = 0
-
-# When enabled doxygen tries to link words that correspond to documented
-# classes, or namespaces to their corresponding documentation. Such a link can
-# be prevented in individual cases by putting a % sign in front of the word or
-# globally by setting AUTOLINK_SUPPORT to NO.
-# The default value is: YES.
-
-AUTOLINK_SUPPORT = YES
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should set this
-# tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string);
-# versus func(std::string) {}). This also make the inheritance and collaboration
-# diagrams that involve STL classes more complete and accurate.
-# The default value is: NO.
-
-BUILTIN_STL_SUPPORT = NO
-
-# If you use Microsoft's C++/CLI language, you should set this option to YES to
-# enable parsing support.
-# The default value is: NO.
-
-CPP_CLI_SUPPORT = NO
-
-# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
-# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
-# will parse them like normal C++ but will assume all classes use public instead
-# of private inheritance when no explicit protection keyword is present.
-# The default value is: NO.
-
-SIP_SUPPORT = NO
-
-# For Microsoft's IDL there are propget and propput attributes to indicate
-# getter and setter methods for a property. Setting this option to YES will make
-# doxygen to replace the get and set methods by a property in the documentation.
-# This will only work if the methods are indeed getting or setting a simple
-# type. If this is not the case, or you want to show the methods anyway, you
-# should set this option to NO.
-# The default value is: YES.
-
-IDL_PROPERTY_SUPPORT = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
-# The default value is: NO.
-
-DISTRIBUTE_GROUP_DOC = NO
-
-# If one adds a struct or class to a group and this option is enabled, then also
-# any nested class or struct is added to the same group. By default this option
-# is disabled and one has to add nested compounds explicitly via \ingroup.
-# The default value is: NO.
-
-GROUP_NESTED_COMPOUNDS = NO
-
-# Set the SUBGROUPING tag to YES to allow class member groups of the same type
-# (for instance a group of public functions) to be put as a subgroup of that
-# type (e.g. under the Public Functions section). Set it to NO to prevent
-# subgrouping. Alternatively, this can be done per class using the
-# \nosubgrouping command.
-# The default value is: YES.
-
-SUBGROUPING = YES
-
-# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
-# are shown inside the group in which they are included (e.g. using \ingroup)
-# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
-# and RTF).
-#
-# Note that this feature does not work in combination with
-# SEPARATE_MEMBER_PAGES.
-# The default value is: NO.
-
-INLINE_GROUPED_CLASSES = NO
-
-# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
-# with only public data fields or simple typedef fields will be shown inline in
-# the documentation of the scope in which they are defined (i.e. file,
-# namespace, or group documentation), provided this scope is documented. If set
-# to NO, structs, classes, and unions are shown on a separate page (for HTML and
-# Man pages) or section (for LaTeX and RTF).
-# The default value is: NO.
-
-INLINE_SIMPLE_STRUCTS = NO
-
-# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
-# enum is documented as struct, union, or enum with the name of the typedef. So
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
-# with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically be
-# useful for C code in case the coding convention dictates that all compound
-# types are typedef'ed and only the typedef is referenced, never the tag name.
-# The default value is: NO.
-
-TYPEDEF_HIDES_STRUCT = NO
-
-# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
-# cache is used to resolve symbols given their name and scope. Since this can be
-# an expensive process and often the same symbol appears multiple times in the
-# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
-# doxygen will become slower. If the cache is too large, memory is wasted. The
-# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
-# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
-# symbols. At the end of a run doxygen will report the cache usage and suggest
-# the optimal cache size from a speed point of view.
-# Minimum value: 0, maximum value: 9, default value: 0.
-
-LOOKUP_CACHE_SIZE = 0
-
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
-# documentation are documented, even if no documentation was available. Private
-# class members and static file members will be hidden unless the
-# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
-# Note: This will also disable the warnings about undocumented members that are
-# normally produced when WARNINGS is set to YES.
-# The default value is: NO.
-
-EXTRACT_ALL = NO
-
-# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
-# be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PRIVATE = NO
-
-# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
-# scope will be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PACKAGE = NO
-
-# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
-# included in the documentation.
-# The default value is: NO.
-
-EXTRACT_STATIC = NO
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
-# locally in source files will be included in the documentation. If set to NO,
-# only classes defined in header files are included. Does not have any effect
-# for Java sources.
-# The default value is: YES.
-
-EXTRACT_LOCAL_CLASSES = YES
-
-# This flag is only useful for Objective-C code. If set to YES, local methods,
-# which are defined in the implementation section but not in the interface are
-# included in the documentation. If set to NO, only methods in the interface are
-# included.
-# The default value is: NO.
-
-EXTRACT_LOCAL_METHODS = NO
-
-# If this flag is set to YES, the members of anonymous namespaces will be
-# extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base name of
-# the file that contains the anonymous namespace. By default anonymous namespace
-# are hidden.
-# The default value is: NO.
-
-EXTRACT_ANON_NSPACES = NO
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
-# undocumented members inside documented classes or files. If set to NO these
-# members will be included in the various overviews, but no documentation
-# section is generated. This option has no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_MEMBERS = NO
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy. If set
-# to NO, these classes will be included in the various overviews. This option
-# has no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_CLASSES = NO
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
-# (class|struct|union) declarations. If set to NO, these declarations will be
-# included in the documentation.
-# The default value is: NO.
-
-HIDE_FRIEND_COMPOUNDS = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
-# documentation blocks found inside the body of a function. If set to NO, these
-# blocks will be appended to the function's detailed documentation block.
-# The default value is: NO.
-
-HIDE_IN_BODY_DOCS = NO
-
-# The INTERNAL_DOCS tag determines if documentation that is typed after a
-# \internal command is included. If the tag is set to NO then the documentation
-# will be excluded. Set it to YES to include the internal documentation.
-# The default value is: NO.
-
-INTERNAL_DOCS = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
-# names in lower-case letters. If set to YES, upper-case letters are also
-# allowed. This is useful if you have classes or files whose names only differ
-# in case and if your file system supports case sensitive file names. Windows
-# and Mac users are advised to set this option to NO.
-# The default value is: system dependent.
-
-CASE_SENSE_NAMES = YES
-
-# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
-# their full class and namespace scopes in the documentation. If set to YES, the
-# scope will be hidden.
-# The default value is: NO.
-
-HIDE_SCOPE_NAMES = NO
-
-# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
-# append additional text to a page's title, such as Class Reference. If set to
-# YES the compound reference will be hidden.
-# The default value is: NO.
-
-HIDE_COMPOUND_REFERENCE= NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
-# the files that are included by a file in the documentation of that file.
-# The default value is: YES.
-
-SHOW_INCLUDE_FILES = YES
-
-# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
-# grouped member an include statement to the documentation, telling the reader
-# which file to include in order to use the member.
-# The default value is: NO.
-
-SHOW_GROUPED_MEMB_INC = NO
-
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
-# files with double quotes in the documentation rather than with sharp brackets.
-# The default value is: NO.
-
-FORCE_LOCAL_INCLUDES = NO
-
-# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
-# documentation for inline members.
-# The default value is: YES.
-
-INLINE_INFO = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
-# (detailed) documentation of file and class members alphabetically by member
-# name. If set to NO, the members will appear in declaration order.
-# The default value is: YES.
-
-SORT_MEMBER_DOCS = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
-# descriptions of file, namespace and class members alphabetically by member
-# name. If set to NO, the members will appear in declaration order. Note that
-# this will also influence the order of the classes in the class list.
-# The default value is: NO.
-
-SORT_BRIEF_DOCS = NO
-
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
-# (brief and detailed) documentation of class members so that constructors and
-# destructors are listed first. If set to NO the constructors will appear in the
-# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
-# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
-# member documentation.
-# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
-# detailed member documentation.
-# The default value is: NO.
-
-SORT_MEMBERS_CTORS_1ST = NO
-
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
-# of group names into alphabetical order. If set to NO the group names will
-# appear in their defined order.
-# The default value is: NO.
-
-SORT_GROUP_NAMES = NO
-
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
-# fully-qualified names, including namespaces. If set to NO, the class list will
-# be sorted only by class name, not including the namespace part.
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the alphabetical
-# list.
-# The default value is: NO.
-
-SORT_BY_SCOPE_NAME = NO
-
-# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
-# type resolution of all parameters of a function it will reject a match between
-# the prototype and the implementation of a member function even if there is
-# only one candidate or it is obvious which candidate to choose by doing a
-# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
-# accept a match between prototype and implementation in such cases.
-# The default value is: NO.
-
-STRICT_PROTO_MATCHING = NO
-
-# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
-# list. This list is created by putting \todo commands in the documentation.
-# The default value is: YES.
-
-GENERATE_TODOLIST = YES
-
-# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
-# list. This list is created by putting \test commands in the documentation.
-# The default value is: YES.
-
-GENERATE_TESTLIST = YES
-
-# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
-# list. This list is created by putting \bug commands in the documentation.
-# The default value is: YES.
-
-GENERATE_BUGLIST = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
-# the deprecated list. This list is created by putting \deprecated commands in
-# the documentation.
-# The default value is: YES.
-
-GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional documentation
-# sections, marked by \if <section_label> ... \endif and \cond <section_label>
-# ... \endcond blocks.
-
-ENABLED_SECTIONS =
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
-# initial value of a variable or macro / define can have for it to appear in the
-# documentation. If the initializer consists of more lines than specified here
-# it will be hidden. Use a value of 0 to hide initializers completely. The
-# appearance of the value of individual variables and macros / defines can be
-# controlled using \showinitializer or \hideinitializer command in the
-# documentation regardless of this setting.
-# Minimum value: 0, maximum value: 10000, default value: 30.
-
-MAX_INITIALIZER_LINES = 30
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
-# the bottom of the documentation of classes and structs. If set to YES, the
-# list will mention the files that were used to generate the documentation.
-# The default value is: YES.
-
-SHOW_USED_FILES = YES
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
-# will remove the Files entry from the Quick Index and from the Folder Tree View
-# (if specified).
-# The default value is: YES.
-
-SHOW_FILES = YES
-
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
-# page. This will remove the Namespaces entry from the Quick Index and from the
-# Folder Tree View (if specified).
-# The default value is: YES.
-
-SHOW_NAMESPACES = YES
-
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that
-# doxygen should invoke to get the current version for each file (typically from
-# the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command command input-file, where command is the value of the
-# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
-# by doxygen. Whatever the program writes to standard output is used as the file
-# version. For an example see the documentation.
-
-FILE_VERSION_FILTER =
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
-# by doxygen. The layout file controls the global structure of the generated
-# output files in an output format independent way. To create the layout file
-# that represents doxygen's defaults, run doxygen with the -l option. You can
-# optionally specify a file name after the option, if omitted DoxygenLayout.xml
-# will be used as the name of the layout file.
-#
-# Note that if you run doxygen from a directory containing a file called
-# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
-# tag is left empty.
-
-LAYOUT_FILE =
-
-# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
-# the reference definitions. This must be a list of .bib files. The .bib
-# extension is automatically appended if omitted. This requires the bibtex tool
-# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
-# For LaTeX the style of the bibliography can be controlled using
-# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
-# search path. See also \cite for info how to create references.
-
-CITE_BIB_FILES =
-
-#---------------------------------------------------------------------------
-# Configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated to
-# standard output by doxygen. If QUIET is set to YES this implies that the
-# messages are off.
-# The default value is: NO.
-
-QUIET = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
-# this implies that the warnings are on.
-#
-# Tip: Turn warnings on while writing the documentation.
-# The default value is: YES.
-
-WARNINGS = YES
-
-# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
-# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
-# will automatically be disabled.
-# The default value is: YES.
-
-WARN_IF_UNDOCUMENTED = YES
-
-# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some parameters
-# in a documented function, or documenting parameters that don't exist or using
-# markup commands wrongly.
-# The default value is: YES.
-
-WARN_IF_DOC_ERROR = YES
-
-# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
-# are documented, but have no documentation for their parameters or return
-# value. If set to NO, doxygen will only warn about wrong or incomplete
-# parameter documentation, but not about the absence of documentation.
-# The default value is: NO.
-
-WARN_NO_PARAMDOC = NO
-
-# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
-# a warning is encountered.
-# The default value is: NO.
-
-WARN_AS_ERROR = NO
-
-# The WARN_FORMAT tag determines the format of the warning messages that doxygen
-# can produce. The string should contain the $file, $line, and $text tags, which
-# will be replaced by the file and line number from which the warning originated
-# and the warning text. Optionally the format may contain $version, which will
-# be replaced by the version of the file (if it could be obtained via
-# FILE_VERSION_FILTER)
-# The default value is: $file:$line: $text.
-
-WARN_FORMAT = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning and error
-# messages should be written. If left blank the output is written to standard
-# error (stderr).
-
-WARN_LOGFILE =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag is used to specify the files and/or directories that contain
-# documented source files. You may enter file names like myfile.cpp or
-# directories like /usr/src/myproject. Separate the files or directories with
-# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
-# Note: If this tag is empty the current directory is searched.
-
-INPUT = plugin/ plugin/model
-
-# This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
-# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
-# documentation (see: http://www.gnu.org/software/libiconv) for the list of
-# possible encodings.
-# The default value is: UTF-8.
-
-INPUT_ENCODING = UTF-8
-
-# If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
-# *.h) to filter out the source-files in the directories.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# read by doxygen.
-#
-# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
-# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
-# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
-# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,
-# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf.
-
-FILE_PATTERNS = *.c \
- *.cc \
- *.cxx \
- *.cpp \
- *.c++ \
- *.java \
- *.ii \
- *.ixx \
- *.ipp \
- *.i++ \
- *.inl \
- *.idl \
- *.ddl \
- *.odl \
- *.h \
- *.hh \
- *.hxx \
- *.hpp \
- *.h++ \
- *.cs \
- *.d \
- *.php \
- *.php4 \
- *.php5 \
- *.phtml \
- *.inc \
- *.m \
- *.markdown \
- *.md \
- *.mm \
- *.dox \
- *.py \
- *.pyw \
- *.f90 \
- *.f95 \
- *.f03 \
- *.f08 \
- *.f \
- *.for \
- *.tcl \
- *.vhd \
- *.vhdl \
- *.ucf \
- *.qsf
-
-# The RECURSIVE tag can be used to specify whether or not subdirectories should
-# be searched for input files as well.
-# The default value is: NO.
-
-RECURSIVE = NO
-
-# The EXCLUDE tag can be used to specify files and/or directories that should be
-# excluded from the INPUT source files. This way you can easily exclude a
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-#
-# Note that relative paths are relative to the directory from which doxygen is
-# run.
-
-EXCLUDE =
-
-# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
-# directories that are symbolic links (a Unix file system feature) are excluded
-# from the input.
-# The default value is: NO.
-
-EXCLUDE_SYMLINKS = NO
-
-# If the value of the INPUT tag contains directories, you can use the
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories.
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories for example use the pattern */test/*
-
-EXCLUDE_PATTERNS =
-
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
-# (namespaces, classes, functions, etc.) that should be excluded from the
-# output. The symbol name can be a fully qualified name, a word, or if the
-# wildcard * is used, a substring. Examples: ANamespace, AClass,
-# AClass::ANamespace, ANamespace::*Test
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories use the pattern */test/*
-
-EXCLUDE_SYMBOLS =
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or directories
-# that contain example code fragments that are included (see the \include
-# command).
-
-EXAMPLE_PATH =
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
-# *.h) to filter out the source-files in the directories. If left blank all
-# files are included.
-
-EXAMPLE_PATTERNS = *
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude commands
-# irrespective of the value of the RECURSIVE tag.
-# The default value is: NO.
-
-EXAMPLE_RECURSIVE = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or directories
-# that contain images that are to be included in the documentation (see the
-# \image command).
-
-IMAGE_PATH =
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should
-# invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command:
-#
-# <filter> <input-file>
-#
-# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
-# name of an input file. Doxygen will then use the output that the filter
-# program writes to standard output. If FILTER_PATTERNS is specified, this tag
-# will be ignored.
-#
-# Note that the filter must not add or remove lines; it is applied before the
-# code is scanned, but not when the output code is generated. If lines are added
-# or removed, the anchors will not be placed correctly.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# properly processed by doxygen.
-
-INPUT_FILTER =
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis. Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match. The filters are a list of the form: pattern=filter
-# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
-# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
-# patterns match the file name, INPUT_FILTER is applied.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# properly processed by doxygen.
-
-FILTER_PATTERNS =
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER) will also be used to filter the input files that are used for
-# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
-# The default value is: NO.
-
-FILTER_SOURCE_FILES = NO
-
-# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
-# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
-# it is also possible to disable source filtering for a specific pattern using
-# *.ext= (so without naming a filter).
-# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
-
-FILTER_SOURCE_PATTERNS =
-
-# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
-# is part of the input, its contents will be placed on the main page
-# (index.html). This can be useful if you have a project on for instance GitHub
-# and want to reuse the introduction page also for the doxygen output.
-
-USE_MDFILE_AS_MAINPAGE =
-
-#---------------------------------------------------------------------------
-# Configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
-# generated. Documented entities will be cross-referenced with these sources.
-#
-# Note: To get rid of all source code in the generated output, make sure that
-# also VERBATIM_HEADERS is set to NO.
-# The default value is: NO.
-
-SOURCE_BROWSER = NO
-
-# Setting the INLINE_SOURCES tag to YES will include the body of functions,
-# classes and enums directly into the documentation.
-# The default value is: NO.
-
-INLINE_SOURCES = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
-# special comment blocks from generated source code fragments. Normal C, C++ and
-# Fortran comments will always remain visible.
-# The default value is: YES.
-
-STRIP_CODE_COMMENTS = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
-# function all documented functions referencing it will be listed.
-# The default value is: NO.
-
-REFERENCED_BY_RELATION = NO
-
-# If the REFERENCES_RELATION tag is set to YES then for each documented function
-# all documented entities called/used by that function will be listed.
-# The default value is: NO.
-
-REFERENCES_RELATION = NO
-
-# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
-# to YES then the hyperlinks from functions in REFERENCES_RELATION and
-# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
-# link to the documentation.
-# The default value is: YES.
-
-REFERENCES_LINK_SOURCE = YES
-
-# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
-# source code will show a tooltip with additional information such as prototype,
-# brief description and links to the definition and documentation. Since this
-# will make the HTML file larger and loading of large files a bit slower, you
-# can opt to disable this feature.
-# The default value is: YES.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-SOURCE_TOOLTIPS = YES
-
-# If the USE_HTAGS tag is set to YES then the references to source code will
-# point to the HTML generated by the htags(1) tool instead of doxygen built-in
-# source browser. The htags tool is part of GNU's global source tagging system
-# (see http://www.gnu.org/software/global/global.html). You will need version
-# 4.8.6 or higher.
-#
-# To use it do the following:
-# - Install the latest version of global
-# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
-# - Make sure the INPUT points to the root of the source tree
-# - Run doxygen as normal
-#
-# Doxygen will invoke htags (and that will in turn invoke gtags), so these
-# tools must be available from the command line (i.e. in the search path).
-#
-# The result: instead of the source browser generated by doxygen, the links to
-# source code will now point to the output of htags.
-# The default value is: NO.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-USE_HTAGS = NO
-
-# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
-# verbatim copy of the header file for each class for which an include is
-# specified. Set to NO to disable this.
-# See also: Section \class.
-# The default value is: YES.
-
-VERBATIM_HEADERS = YES
-
-# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
-# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the
-# cost of reduced performance. This can be particularly helpful with template
-# rich C++ code for which doxygen's built-in parser lacks the necessary type
-# information.
-# Note: The availability of this option depends on whether or not doxygen was
-# generated with the -Duse-libclang=ON option for CMake.
-# The default value is: NO.
-
-CLANG_ASSISTED_PARSING = NO
-
-# If clang assisted parsing is enabled you can provide the compiler with command
-# line options that you would normally use when invoking the compiler. Note that
-# the include paths will already be set by doxygen for the files and directories
-# specified with INPUT and INCLUDE_PATH.
-# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
-
-CLANG_OPTIONS =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
-# compounds will be generated. Enable this if the project contains a lot of
-# classes, structs, unions or interfaces.
-# The default value is: YES.
-
-ALPHABETICAL_INDEX = YES
-
-# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
-# which the alphabetical index list will be split.
-# Minimum value: 1, maximum value: 20, default value: 5.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-COLS_IN_ALPHA_INDEX = 5
-
-# In case all classes in a project start with a common prefix, all classes will
-# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
-# can be used to specify a prefix (or a list of prefixes) that should be ignored
-# while generating the index headers.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-IGNORE_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
-# The default value is: YES.
-
-GENERATE_HTML = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_OUTPUT = html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
-# generated HTML page (for example: .htm, .php, .asp).
-# The default value is: .html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FILE_EXTENSION = .html
-
-# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
-# each generated HTML page. If the tag is left blank doxygen will generate a
-# standard header.
-#
-# To get valid HTML the header file that includes any scripts and style sheets
-# that doxygen needs, which is dependent on the configuration options used (e.g.
-# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
-# default header using
-# doxygen -w html new_header.html new_footer.html new_stylesheet.css
-# YourConfigFile
-# and then modify the file new_header.html. See also section "Doxygen usage"
-# for information on how to generate the default header that doxygen normally
-# uses.
-# Note: The header is subject to change so you typically have to regenerate the
-# default header when upgrading to a newer version of doxygen. For a description
-# of the possible markers and block names see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_HEADER =
-
-# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
-# generated HTML page. If the tag is left blank doxygen will generate a standard
-# footer. See HTML_HEADER for more information on how to generate a default
-# footer and what special commands can be used inside the footer. See also
-# section "Doxygen usage" for information on how to generate the default footer
-# that doxygen normally uses.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FOOTER =
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
-# sheet that is used by each HTML page. It can be used to fine-tune the look of
-# the HTML output. If left blank doxygen will generate a default style sheet.
-# See also section "Doxygen usage" for information on how to generate the style
-# sheet that doxygen normally uses.
-# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
-# it is more robust and this tag (HTML_STYLESHEET) will in the future become
-# obsolete.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_STYLESHEET =
-
-# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
-# cascading style sheets that are included after the standard style sheets
-# created by doxygen. Using this option one can overrule certain style aspects.
-# This is preferred over using HTML_STYLESHEET since it does not replace the
-# standard style sheet and is therefore more robust against future updates.
-# Doxygen will copy the style sheet files to the output directory.
-# Note: The order of the extra style sheet files is of importance (e.g. the last
-# style sheet in the list overrules the setting of the previous ones in the
-# list). For an example see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_STYLESHEET =
-
-# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the HTML output directory. Note
-# that these files will be copied to the base HTML output directory. Use the
-# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
-# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
-# files will be copied as-is; there are no commands or markers available.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_FILES =
-
-# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
-# will adjust the colors in the style sheet and background images according to
-# this color. Hue is specified as an angle on a colorwheel, see
-# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
-# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
-# purple, and 360 is red again.
-# Minimum value: 0, maximum value: 359, default value: 220.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_HUE = 220
-
-# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
-# in the HTML output. For a value of 0 the output will use grayscales only. A
-# value of 255 will produce the most vivid colors.
-# Minimum value: 0, maximum value: 255, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_SAT = 100
-
-# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
-# luminance component of the colors in the HTML output. Values below 100
-# gradually make the output lighter, whereas values above 100 make the output
-# darker. The value divided by 100 is the actual gamma applied, so 80 represents
-# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
-# change the gamma.
-# Minimum value: 40, maximum value: 240, default value: 80.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_GAMMA = 80
-
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
-# page will contain the date and time when the page was generated. Setting this
-# to YES can help to show when doxygen was last run and thus if the
-# documentation is up to date.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_TIMESTAMP = NO
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
-# documentation will contain sections that can be hidden and shown after the
-# page has loaded.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_DYNAMIC_SECTIONS = NO
-
-# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
-# shown in the various tree structured indices initially; the user can expand
-# and collapse entries dynamically later on. Doxygen will expand the tree to
-# such a level that at most the specified number of entries are visible (unless
-# a fully collapsed tree already exceeds this amount). So setting the number of
-# entries 1 will produce a full collapsed tree by default. 0 is a special value
-# representing an infinite number of entries and will result in a full expanded
-# tree by default.
-# Minimum value: 0, maximum value: 9999, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_INDEX_NUM_ENTRIES = 100
-
-# If the GENERATE_DOCSET tag is set to YES, additional index files will be
-# generated that can be used as input for Apple's Xcode 3 integrated development
-# environment (see: http://developer.apple.com/tools/xcode/), introduced with
-# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
-# Makefile in the HTML output directory. Running make will produce the docset in
-# that directory and running make install will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
-# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
-# for more information.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_DOCSET = NO
-
-# This tag determines the name of the docset feed. A documentation feed provides
-# an umbrella under which multiple documentation sets from a single provider
-# (such as a company or product suite) can be grouped.
-# The default value is: Doxygen generated docs.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_FEEDNAME = "Doxygen generated docs"
-
-# This tag specifies a string that should uniquely identify the documentation
-# set bundle. This should be a reverse domain-name style string, e.g.
-# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_BUNDLE_ID = org.doxygen.Project
-
-# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
-# the documentation publisher. This should be a reverse domain-name style
-# string, e.g. com.mycompany.MyDocSet.documentation.
-# The default value is: org.doxygen.Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_ID = org.doxygen.Publisher
-
-# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
-# The default value is: Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_NAME = Publisher
-
-# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
-# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
-# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
-# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
-# Windows.
-#
-# The HTML Help Workshop contains a compiler that can convert all HTML output
-# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
-# files are now used as the Windows 98 help format, and will replace the old
-# Windows help format (.hlp) on all Windows platforms in the future. Compressed
-# HTML files also contain an index, a table of contents, and you can search for
-# words in the documentation. The HTML workshop also contains a viewer for
-# compressed HTML files.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_HTMLHELP = NO
-
-# The CHM_FILE tag can be used to specify the file name of the resulting .chm
-# file. You can add a path in front of the file if the result should not be
-# written to the html output directory.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_FILE =
-
-# The HHC_LOCATION tag can be used to specify the location (absolute path
-# including file name) of the HTML help compiler (hhc.exe). If non-empty,
-# doxygen will try to run the HTML help compiler on the generated index.hhp.
-# The file has to be specified with full path.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-HHC_LOCATION =
-
-# The GENERATE_CHI flag controls if a separate .chi index file is generated
-# (YES) or that it should be included in the master .chm file (NO).
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-GENERATE_CHI = NO
-
-# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
-# and project file content.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_INDEX_ENCODING =
-
-# The BINARY_TOC flag controls whether a binary table of contents is generated
-# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
-# enables the Previous and Next buttons.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-BINARY_TOC = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members to
-# the table of contents of the HTML help documentation and to the tree view.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-TOC_EXPAND = NO
-
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
-# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
-# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
-# (.qch) of the generated HTML documentation.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_QHP = NO
-
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
-# the file name of the resulting .qch file. The path specified is relative to
-# the HTML output folder.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QCH_FILE =
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
-# Project output. For more information please see Qt Help Project / Namespace
-# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_NAMESPACE = org.doxygen.Project
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
-# Help Project output. For more information please see Qt Help Project / Virtual
-# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
-# folders).
-# The default value is: doc.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_VIRTUAL_FOLDER = doc
-
-# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
-# filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_NAME =
-
-# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
-# custom filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_ATTRS =
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
-# project's filter section matches. Qt Help Project / Filter Attributes (see:
-# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_SECT_FILTER_ATTRS =
-
-# The QHG_LOCATION tag can be used to specify the location of Qt's
-# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
-# generated .qhp file.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHG_LOCATION =
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
-# generated, together with the HTML files, they form an Eclipse help plugin. To
-# install this plugin and make it available under the help contents menu in
-# Eclipse, the contents of the directory containing the HTML and XML files needs
-# to be copied into the plugins directory of eclipse. The name of the directory
-# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
-# After copying Eclipse needs to be restarted before the help appears.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_ECLIPSEHELP = NO
-
-# A unique identifier for the Eclipse help plugin. When installing the plugin
-# the directory name containing the HTML and XML files should also have this
-# name. Each documentation set should have its own identifier.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
-
-ECLIPSE_DOC_ID = org.doxygen.Project
-
-# If you want full control over the layout of the generated HTML pages it might
-# be necessary to disable the index and replace it with your own. The
-# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
-# of each HTML page. A value of NO enables the index and the value YES disables
-# it. Since the tabs in the index contain the same information as the navigation
-# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-DISABLE_INDEX = NO
-
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information. If the tag
-# value is set to YES, a side panel will be generated containing a tree-like
-# index structure (just like the one that is generated for HTML Help). For this
-# to work a browser that supports JavaScript, DHTML, CSS and frames is required
-# (i.e. any modern browser). Windows users are probably better off using the
-# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
-# further fine-tune the look of the index. As an example, the default style
-# sheet generated by doxygen has an example that shows how to put an image at
-# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
-# the same information as the tab index, you could consider setting
-# DISABLE_INDEX to YES when enabling this option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_TREEVIEW = NO
-
-# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
-# doxygen will group on one line in the generated HTML documentation.
-#
-# Note that a value of 0 will completely suppress the enum values from appearing
-# in the overview section.
-# Minimum value: 0, maximum value: 20, default value: 4.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-ENUM_VALUES_PER_LINE = 4
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
-# to set the initial width (in pixels) of the frame in which the tree is shown.
-# Minimum value: 0, maximum value: 1500, default value: 250.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-TREEVIEW_WIDTH = 250
-
-# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
-# external symbols imported via tag files in a separate window.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-EXT_LINKS_IN_WINDOW = NO
-
-# Use this tag to change the font size of LaTeX formulas included as images in
-# the HTML documentation. When you change the font size after a successful
-# doxygen run you need to manually remove any form_*.png images from the HTML
-# output directory to force them to be regenerated.
-# Minimum value: 8, maximum value: 50, default value: 10.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_FONTSIZE = 10
-
-# Use the FORMULA_TRANPARENT tag to determine whether or not the images
-# generated for formulas are transparent PNGs. Transparent PNGs are not
-# supported properly for IE 6.0, but are supported on all modern browsers.
-#
-# Note that when changing this option you need to delete any form_*.png files in
-# the HTML output directory before the changes have effect.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_TRANSPARENT = YES
-
-# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
-# http://www.mathjax.org) which uses client side Javascript for the rendering
-# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
-# installed or if you want to formulas look prettier in the HTML output. When
-# enabled you may also need to install MathJax separately and configure the path
-# to it using the MATHJAX_RELPATH option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-USE_MATHJAX = NO
-
-# When MathJax is enabled you can set the default output format to be used for
-# the MathJax output. See the MathJax site (see:
-# http://docs.mathjax.org/en/latest/output.html) for more details.
-# Possible values are: HTML-CSS (which is slower, but has the best
-# compatibility), NativeMML (i.e. MathML) and SVG.
-# The default value is: HTML-CSS.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_FORMAT = HTML-CSS
-
-# When MathJax is enabled you need to specify the location relative to the HTML
-# output directory using the MATHJAX_RELPATH option. The destination directory
-# should contain the MathJax.js script. For instance, if the mathjax directory
-# is located at the same level as the HTML output directory, then
-# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
-# Content Delivery Network so you can quickly see the result without installing
-# MathJax. However, it is strongly recommended to install a local copy of
-# MathJax from http://www.mathjax.org before deployment.
-# The default value is: http://cdn.mathjax.org/mathjax/latest.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest
-
-# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
-# extension names that should be enabled during MathJax rendering. For example
-# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_EXTENSIONS =
-
-# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
-# of code that will be used on startup of the MathJax code. See the MathJax site
-# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
-# example see the documentation.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_CODEFILE =
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
-# the HTML output. The underlying search engine uses javascript and DHTML and
-# should work on any modern browser. Note that when using HTML help
-# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
-# there is already a search function so this one should typically be disabled.
-# For large projects the javascript based search engine can be slow, then
-# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
-# search using the keyboard; to jump to the search box use <access key> + S
-# (what the <access key> is depends on the OS and browser, but it is typically
-# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
-# key> to jump into the search results window, the results can be navigated
-# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
-# the search. The filter options can be selected when the cursor is inside the
-# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
-# to select a filter and <Enter> or <escape> to activate or cancel the filter
-# option.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-SEARCHENGINE = YES
-
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
-# implemented using a web server instead of a web client using Javascript. There
-# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
-# setting. When disabled, doxygen will generate a PHP script for searching and
-# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
-# and searching needs to be provided by external tools. See the section
-# "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SERVER_BASED_SEARCH = NO
-
-# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
-# script for searching. Instead the search results are written to an XML file
-# which needs to be processed by an external indexer. Doxygen will invoke an
-# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
-# search results.
-#
-# Doxygen ships with an example indexer (doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: http://xapian.org/).
-#
-# See the section "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH = NO
-
-# The SEARCHENGINE_URL should point to a search engine hosted by a web server
-# which will return the search results when EXTERNAL_SEARCH is enabled.
-#
-# Doxygen ships with an example indexer (doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: http://xapian.org/). See the section "External Indexing and
-# Searching" for details.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHENGINE_URL =
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
-# search data is written to a file for indexing by an external tool. With the
-# SEARCHDATA_FILE tag the name of this file can be specified.
-# The default file is: searchdata.xml.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHDATA_FILE = searchdata.xml
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
-# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
-# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
-# projects and redirect the results back to the right project.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH_ID =
-
-# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
-# projects other than the one defined by this configuration file, but that are
-# all added to the same external search index. Each project needs to have a
-# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
-# to a relative location where the documentation can be found. The format is:
-# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTRA_SEARCH_MAPPINGS =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
-# The default value is: YES.
-
-GENERATE_LATEX = YES
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: latex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_OUTPUT = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked.
-#
-# Note that when enabling USE_PDFLATEX this option is only used for generating
-# bitmaps for formulas in the HTML output, but not in the Makefile that is
-# written to the output directory.
-# The default file is: latex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_CMD_NAME = latex
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
-# index for LaTeX.
-# The default file is: makeindex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-MAKEINDEX_CMD_NAME = makeindex
-
-# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-COMPACT_LATEX = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used by the
-# printer.
-# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
-# 14 inches) and executive (7.25 x 10.5 inches).
-# The default value is: a4.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PAPER_TYPE = a4
-
-# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
-# that should be included in the LaTeX output. The package can be specified just
-# by its name or with the correct syntax as to be used with the LaTeX
-# \usepackage command. To get the times font for instance you can specify :
-# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
-# To use the option intlimits with the amsmath package you can specify:
-# EXTRA_PACKAGES=[intlimits]{amsmath}
-# If left blank no extra packages will be included.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-EXTRA_PACKAGES =
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
-# generated LaTeX document. The header should contain everything until the first
-# chapter. If it is left blank doxygen will generate a standard header. See
-# section "Doxygen usage" for information on how to let doxygen write the
-# default header to a separate file.
-#
-# Note: Only use a user-defined header if you know what you are doing! The
-# following commands have a special meaning inside the header: $title,
-# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
-# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
-# string, for the replacement values of the other commands the user is referred
-# to HTML_HEADER.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HEADER =
-
-# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
-# generated LaTeX document. The footer should contain everything after the last
-# chapter. If it is left blank doxygen will generate a standard footer. See
-# LATEX_HEADER for more information on how to generate a default footer and what
-# special commands can be used inside the footer.
-#
-# Note: Only use a user-defined footer if you know what you are doing!
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_FOOTER =
-
-# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
-# LaTeX style sheets that are included after the standard style sheets created
-# by doxygen. Using this option one can overrule certain style aspects. Doxygen
-# will copy the style sheet files to the output directory.
-# Note: The order of the extra style sheet files is of importance (e.g. the last
-# style sheet in the list overrules the setting of the previous ones in the
-# list).
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EXTRA_STYLESHEET =
-
-# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the LATEX_OUTPUT output
-# directory. Note that the files will be copied as-is; there are no commands or
-# markers available.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EXTRA_FILES =
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
-# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
-# contain links (just like the HTML output) instead of page references. This
-# makes the output suitable for online browsing using a PDF viewer.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PDF_HYPERLINKS = YES
-
-# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
-# the PDF file directly from the LaTeX files. Set this option to YES, to get a
-# higher quality PDF documentation.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-USE_PDFLATEX = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
-# command to the generated LaTeX files. This will instruct LaTeX to keep running
-# if errors occur, instead of asking the user for help. This option is also used
-# when generating formulas in HTML.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BATCHMODE = NO
-
-# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
-# index chapters (such as File Index, Compound Index, etc.) in the output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HIDE_INDICES = NO
-
-# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
-# code with syntax highlighting in the LaTeX output.
-#
-# Note that which sources are shown also depends on other settings such as
-# SOURCE_BROWSER.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_SOURCE_CODE = NO
-
-# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
-# bibliography, e.g. plainnat, or ieeetr. See
-# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
-# The default value is: plain.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BIB_STYLE = plain
-
-# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
-# page will contain the date and time when the page was generated. Setting this
-# to NO can help when comparing the output of multiple runs.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_TIMESTAMP = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
-# RTF output is optimized for Word 97 and may not look too pretty with other RTF
-# readers/editors.
-# The default value is: NO.
-
-GENERATE_RTF = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: rtf.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_OUTPUT = rtf
-
-# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-COMPACT_RTF = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
-# contain hyperlink fields. The RTF file will contain links (just like the HTML
-# output) instead of page references. This makes the output suitable for online
-# browsing using Word or some other Word compatible readers that support those
-# fields.
-#
-# Note: WordPad (write) and others do not support links.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_HYPERLINKS = NO
-
-# Load stylesheet definitions from file. Syntax is similar to doxygen's config
-# file, i.e. a series of assignments. You only have to provide replacements,
-# missing definitions are set to their default value.
-#
-# See also section "Doxygen usage" for information on how to generate the
-# default style sheet that doxygen normally uses.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_STYLESHEET_FILE =
-
-# Set optional variables used in the generation of an RTF document. Syntax is
-# similar to doxygen's config file. A template extensions file can be generated
-# using doxygen -e rtf extensionFile.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_EXTENSIONS_FILE =
-
-# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
-# with syntax highlighting in the RTF output.
-#
-# Note that which sources are shown also depends on other settings such as
-# SOURCE_BROWSER.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_SOURCE_CODE = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
-# classes and files.
-# The default value is: NO.
-
-GENERATE_MAN = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it. A directory man3 will be created inside the directory specified by
-# MAN_OUTPUT.
-# The default directory is: man.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_OUTPUT = man
-
-# The MAN_EXTENSION tag determines the extension that is added to the generated
-# man pages. In case the manual section does not start with a number, the number
-# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
-# optional.
-# The default value is: .3.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_EXTENSION = .3
-
-# The MAN_SUBDIR tag determines the name of the directory created within
-# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
-# MAN_EXTENSION with the initial . removed.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_SUBDIR =
-
-# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
-# will generate one additional man file for each entity documented in the real
-# man page(s). These additional files only source the real man page, but without
-# them the man command would be unable to find the correct page.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_LINKS = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
-# captures the structure of the code including all documentation.
-# The default value is: NO.
-
-GENERATE_XML = NO
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: xml.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_OUTPUT = xml
-
-# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
-# listings (including syntax highlighting and cross-referencing information) to
-# the XML output. Note that enabling this will significantly increase the size
-# of the XML output.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_PROGRAMLISTING = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to the DOCBOOK output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
-# that can be used to generate PDF.
-# The default value is: NO.
-
-GENERATE_DOCBOOK = NO
-
-# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
-# front of it.
-# The default directory is: docbook.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_OUTPUT = docbook
-
-# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
-# program listings (including syntax highlighting and cross-referencing
-# information) to the DOCBOOK output. Note that enabling this will significantly
-# increase the size of the DOCBOOK output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_PROGRAMLISTING = NO
-
-#---------------------------------------------------------------------------
-# Configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
-# AutoGen Definitions (see http://autogen.sf.net) file that captures the
-# structure of the code including all documentation. Note that this feature is
-# still experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_AUTOGEN_DEF = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
-# file that captures the structure of the code including all documentation.
-#
-# Note that this feature is still experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_PERLMOD = NO
-
-# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
-# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
-# output from the Perl module output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_LATEX = NO
-
-# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
-# formatted so it can be parsed by a human reader. This is useful if you want to
-# understand what is going on. On the other hand, if this tag is set to NO, the
-# size of the Perl module output will be much smaller and Perl will parse it
-# just the same.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_PRETTY = YES
-
-# The names of the make variables in the generated doxyrules.make file are
-# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
-# so different doxyrules.make files included by the same Makefile don't
-# overwrite each other's variables.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_MAKEVAR_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
-# C-preprocessor directives found in the sources and include files.
-# The default value is: YES.
-
-ENABLE_PREPROCESSING = YES
-
-# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
-# in the source code. If set to NO, only conditional compilation will be
-# performed. Macro expansion can be done in a controlled way by setting
-# EXPAND_ONLY_PREDEF to YES.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-MACRO_EXPANSION = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
-# the macro expansion is limited to the macros specified with the PREDEFINED and
-# EXPAND_AS_DEFINED tags.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_ONLY_PREDEF = NO
-
-# If the SEARCH_INCLUDES tag is set to YES, the include files in the
-# INCLUDE_PATH will be searched if a #include is found.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SEARCH_INCLUDES = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by the
-# preprocessor.
-# This tag requires that the tag SEARCH_INCLUDES is set to YES.
-
-INCLUDE_PATH =
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
-# patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will be
-# used.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-INCLUDE_FILE_PATTERNS =
-
-# The PREDEFINED tag can be used to specify one or more macro names that are
-# defined before the preprocessor is started (similar to the -D option of e.g.
-# gcc). The argument of the tag is a list of macros of the form: name or
-# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
-# is assumed. To prevent a macro definition from being undefined via #undef or
-# recursively expanded use the := operator instead of the = operator.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-PREDEFINED =
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
-# tag can be used to specify a list of macro names that should be expanded. The
-# macro definition that is found in the sources will be used. Use the PREDEFINED
-# tag if you want to use a different macro definition that overrules the
-# definition found in the source code.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_AS_DEFINED =
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
-# remove all references to function-like macros that are alone on a line, have
-# an all uppercase name, and do not end with a semicolon. Such function macros
-# are typically used for boiler-plate code, and will confuse the parser if not
-# removed.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SKIP_FUNCTION_MACROS = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES tag can be used to specify one or more tag files. For each tag
-# file the location of the external documentation should be added. The format of
-# a tag file without this location is as follows:
-# TAGFILES = file1 file2 ...
-# Adding location for the tag files is done as follows:
-# TAGFILES = file1=loc1 "file2 = loc2" ...
-# where loc1 and loc2 can be relative or absolute paths or URLs. See the
-# section "Linking to external documentation" for more information about the use
-# of tag files.
-# Note: Each tag file must have a unique name (where the name does NOT include
-# the path). If a tag file is not located in the directory in which doxygen is
-# run, you must also specify the path to the tagfile here.
-
-TAGFILES =
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
-# tag file that is based on the input files it reads. See section "Linking to
-# external documentation" for more information about the usage of tag files.
-
-GENERATE_TAGFILE =
-
-# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
-# the class index. If set to NO, only the inherited external classes will be
-# listed.
-# The default value is: NO.
-
-ALLEXTERNALS = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
-# in the modules index. If set to NO, only the current project's groups will be
-# listed.
-# The default value is: YES.
-
-EXTERNAL_GROUPS = YES
-
-# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
-# the related pages index. If set to NO, only the current project's pages will
-# be listed.
-# The default value is: YES.
-
-EXTERNAL_PAGES = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script
-# interpreter (i.e. the result of 'which perl').
-# The default file (with absolute path) is: /usr/bin/perl.
-
-PERL_PATH = /usr/bin/perl
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
-# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
-# NO turns the diagrams off. Note that this option also works with HAVE_DOT
-# disabled, but it is recommended to install and use dot, since it yields more
-# powerful graphs.
-# The default value is: YES.
-
-CLASS_DIAGRAMS = YES
-
-# You can define message sequence charts within doxygen comments using the \msc
-# command. Doxygen will then run the mscgen tool (see:
-# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
-# documentation. The MSCGEN_PATH tag allows you to specify the directory where
-# the mscgen tool resides. If left empty the tool is assumed to be found in the
-# default search path.
-
-MSCGEN_PATH =
-
-# You can include diagrams made with dia in doxygen documentation. Doxygen will
-# then run dia to produce the diagram and insert it in the documentation. The
-# DIA_PATH tag allows you to specify the directory where the dia binary resides.
-# If left empty dia is assumed to be found in the default search path.
-
-DIA_PATH =
-
-# If set to YES the inheritance and collaboration graphs will hide inheritance
-# and usage relations if the target is undocumented or is not a class.
-# The default value is: YES.
-
-HIDE_UNDOC_RELATIONS = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz (see:
-# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
-# Bell Labs. The other options in this section have no effect if this option is
-# set to NO
-# The default value is: YES.
-
-HAVE_DOT = YES
-
-# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
-# to run in parallel. When set to 0 doxygen will base this on the number of
-# processors available in the system. You can set it explicitly to a value
-# larger than 0 to get control over the balance between CPU load and processing
-# speed.
-# Minimum value: 0, maximum value: 32, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_NUM_THREADS = 0
-
-# When you want a differently looking font in the dot files that doxygen
-# generates you can specify the font name using DOT_FONTNAME. You need to make
-# sure dot is able to find the font, which can be done by putting it in a
-# standard location or by setting the DOTFONTPATH environment variable or by
-# setting DOT_FONTPATH to the directory containing the font.
-# The default value is: Helvetica.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTNAME = Helvetica
-
-# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
-# dot graphs.
-# Minimum value: 4, maximum value: 24, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTSIZE = 10
-
-# By default doxygen will tell dot to use the default font as specified with
-# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
-# the path where dot can find it using this tag.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTPATH =
-
-# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
-# each documented class showing the direct and indirect inheritance relations.
-# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CLASS_GRAPH = YES
-
-# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
-# graph for each documented class showing the direct and indirect implementation
-# dependencies (inheritance, containment, and class references variables) of the
-# class with other documented classes.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-COLLABORATION_GRAPH = YES
-
-# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
-# groups, showing the direct groups dependencies.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GROUP_GRAPHS = YES
-
-# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
-# collaboration diagrams in a style similar to the OMG's Unified Modeling
-# Language.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LOOK = NO
-
-# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
-# class node. If there are many fields or methods and many nodes the graph may
-# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
-# number of items for each type to make the size more manageable. Set this to 0
-# for no limit. Note that the threshold may be exceeded by 50% before the limit
-# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
-# but if the number exceeds 15, the total amount of fields shown is limited to
-# 10.
-# Minimum value: 0, maximum value: 100, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LIMIT_NUM_FIELDS = 10
-
-# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
-# collaboration graphs will show the relations between templates and their
-# instances.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-TEMPLATE_RELATIONS = NO
-
-# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
-# YES then doxygen will generate a graph for each documented file showing the
-# direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDE_GRAPH = YES
-
-# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
-# set to YES then doxygen will generate a graph for each documented file showing
-# the direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDED_BY_GRAPH = YES
-
-# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable call graphs for selected
-# functions only using the \callgraph command. Disabling a call graph can be
-# accomplished by means of the command \hidecallgraph.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALL_GRAPH = NO
-
-# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable caller graphs for selected
-# functions only using the \callergraph command. Disabling a caller graph can be
-# accomplished by means of the command \hidecallergraph.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALLER_GRAPH = NO
-
-# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
-# hierarchy of all classes instead of a textual one.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GRAPHICAL_HIERARCHY = YES
-
-# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
-# dependencies a directory has on other directories in a graphical way. The
-# dependency relations are determined by the #include relations between the
-# files in the directories.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DIRECTORY_GRAPH = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot. For an explanation of the image formats see the section
-# output formats in the documentation of the dot tool (Graphviz (see:
-# http://www.graphviz.org/)).
-# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
-# to make the SVG files visible in IE 9+ (other browsers do not have this
-# requirement).
-# Possible values are: png, png:cairo, png:cairo:cairo, png:cairo:gd, png:gd,
-# png:gd:gd, jpg, jpg:cairo, jpg:cairo:gd, jpg:gd, jpg:gd:gd, gif, gif:cairo,
-# gif:cairo:gd, gif:gd, gif:gd:gd, svg, png:gd, png:gd:gd, png:cairo,
-# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
-# png:gdiplus:gdiplus.
-# The default value is: png.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_IMAGE_FORMAT = png
-
-# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
-# enable generation of interactive SVG images that allow zooming and panning.
-#
-# Note that this requires a modern browser other than Internet Explorer. Tested
-# and working are Firefox, Chrome, Safari, and Opera.
-# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
-# the SVG files visible. Older versions of IE do not have SVG support.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INTERACTIVE_SVG = NO
-
-# The DOT_PATH tag can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found in the path.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_PATH =
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the \dotfile
-# command).
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOTFILE_DIRS =
-
-# The MSCFILE_DIRS tag can be used to specify one or more directories that
-# contain msc files that are included in the documentation (see the \mscfile
-# command).
-
-MSCFILE_DIRS =
-
-# The DIAFILE_DIRS tag can be used to specify one or more directories that
-# contain dia files that are included in the documentation (see the \diafile
-# command).
-
-DIAFILE_DIRS =
-
-# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
-# path where java can find the plantuml.jar file. If left blank, it is assumed
-# PlantUML is not used or called during a preprocessing step. Doxygen will
-# generate a warning when it encounters a \startuml command in this case and
-# will not generate output for the diagram.
-
-PLANTUML_JAR_PATH =
-
-# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
-# configuration file for plantuml.
-
-PLANTUML_CFG_FILE =
-
-# When using plantuml, the specified paths are searched for files specified by
-# the !include statement in a plantuml block.
-
-PLANTUML_INCLUDE_PATH =
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
-# that will be shown in the graph. If the number of nodes in a graph becomes
-# larger than this value, doxygen will truncate the graph, which is visualized
-# by representing a node as a red box. Note that doxygen if the number of direct
-# children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
-# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-# Minimum value: 0, maximum value: 10000, default value: 50.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_GRAPH_MAX_NODES = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
-# generated by dot. A depth value of 3 means that only nodes reachable from the
-# root by following a path via at most 3 edges will be shown. Nodes that lay
-# further from the root node will be omitted. Note that setting this option to 1
-# or 2 may greatly reduce the computation time needed for large code bases. Also
-# note that the size of a graph can be further restricted by
-# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
-# Minimum value: 0, maximum value: 1000, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-MAX_DOT_GRAPH_DEPTH = 0
-
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not seem
-# to support this out of the box.
-#
-# Warning: Depending on the platform used, enabling this option may lead to
-# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
-# read).
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_TRANSPARENT = NO
-
-# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
-# files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10) support
-# this, this feature is disabled by default.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_MULTI_TARGETS = NO
-
-# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
-# explaining the meaning of the various boxes and arrows in the dot generated
-# graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GENERATE_LEGEND = YES
-
-# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
-# files that are used to generate the various graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_CLEANUP = YES
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c
deleted file mode 100644
index bbcc2e9bf..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (c) 2019-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 <inttypes.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include "hicn_plugin.h"
-#include "model/hicn_model.h"
-#include "ietf/ietf_interface.h"
-
-
-sr_subscription_ctx_t *subscription = NULL;
-volatile int exit_application = 0;
-
-int sr_plugin_init_cb(sr_session_ctx_t *session, void **private_ctx) {
-
- sr_subscription_ctx_t *subscription = NULL;
- int rc = SR_ERR_OK;
- rc = hicn_connect_vpp();
- if (SR_ERR_OK != rc) {
- return SR_ERR_INTERNAL;
- }
-
- // HICN subscribe
- hicn_subscribe_events(session, &subscription);
-
- //sr_subscription_ctx_t *subscription2 = NULL;
-
- // IETF subscribe
- //ietf_subscribe_events(session, &subscription2);
-
-
- /* set subscription as our private context */
- *private_ctx = subscription;
-
- return SR_ERR_OK;
-}
-
-void sr_plugin_cleanup_cb(sr_session_ctx_t *session, void *private_ctx) {
-
- /* subscription was set as our private context */
- sr_unsubscribe(private_ctx);
- hicn_disconnect_vpp();
-}
-
-static void sigint_handler(int signum) { exit_application = 1; }
-int subscribe_all_module_events(sr_session_ctx_t *session) {
- sr_plugin_init_cb(session, (void **)&subscription);
- return 0;
-}
-
-int main(int argc, char **argv) {
- sr_conn_ctx_t *connection = NULL;
- sr_session_ctx_t *session = NULL;
- int rc = SR_ERR_OK;
- /* connect to vpp */
- rc = hicn_connect_vpp();
- if (-1 == rc) {
- fprintf(stderr, "vpp connect error");
- return -1;
- }
-
- /* connect to sysrepo */
- rc = sr_connect(SR_CONN_DEFAULT, &connection);
- if (SR_ERR_OK != rc) {
- fprintf(stderr, "Error by sr_connect: %s\n", sr_strerror(rc));
- goto cleanup;
- }
-
- /* start session */
- rc = sr_session_start(connection, SR_DS_STARTUP, &session);
- if (SR_ERR_OK != rc) {
- fprintf(stderr, "Error by sr_session_start: %s\n", sr_strerror(rc));
- goto cleanup;
- }
-
- /* subscribe all module events */
- rc = subscribe_all_module_events(session);
- if (SR_ERR_OK != rc) {
- fprintf(stderr, "Error by subscribe module events: %s\n", sr_strerror(rc));
- goto cleanup;
- }
-
- /* loop until ctrl-c is pressed / SIGINT is received */
- signal(SIGINT, sigint_handler);
- signal(SIGPIPE, SIG_IGN);
-
- while (!exit_application) {
- sleep(2);
- }
-
- printf("Application exit requested, exiting.\n");
-
-cleanup:
- if (NULL != subscription) {
- sr_unsubscribe(subscription);
- }
- if (NULL != session) {
- sr_session_stop(session);
- }
- if (NULL != connection) {
- sr_disconnect(connection);
- }
- hicn_disconnect_vpp();
- return rc;
-} \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.h
deleted file mode 100644
index 0890c3f03..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 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.
- */
-
-/**
- * @file hicn_plugin.h
- * @brief This file contains init and cleanup for the sysrepo.
- */
-
-#ifndef __HICN_PLUGIN_H__
-#define __HICN_PLUGIN_H__
-
-#include "hicn_vpp_comm.h"
-
-
-/**
- * @brief initialize function for sysrepo plugin,
- * In this function we connect to vpp from one side
- * and subscribe for all hICN events as well as interface events (if any)
- * @param session pointer to the sesssion context
- * @param private_ctx pointer to the context
- * @return in success the function returns SR_ERR_OK otherwise it pass error
- */
-int sr_plugin_init_cb(sr_session_ctx_t *session, void **private_ctx);
-
-/**
- * @brief cleanup function for sysrepo,
- * In this function we connect to vpp from one side
- * and and unsubscribe for all hICN events as well as interface events (if any)
- * @param session pointer to the sesssion context
- * @param private_ctx pointer to the context
- */
-void sr_plugin_cleanup_cb(sr_session_ctx_t *session, void *private_ctx);
-
-#endif //__HICN_PLUGIN_H__ \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c
deleted file mode 100644
index 73eab66ea..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 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_vpp_comm.h"
-#include <vapi/vapi.h>
-
-#define APP_NAME "hicn_plugin"
-#define MAX_OUTSTANDING_REQUESTS 4
-#define RESPONSE_QUEUE_SIZE 2
-
-
-vapi_ctx_t g_vapi_ctx_instance=NULL;
-
-
-
-
-
-int hicn_connect_vpp() {
-
- if (g_vapi_ctx_instance == NULL) {
- vapi_error_e rv = vapi_ctx_alloc(&g_vapi_ctx_instance);
- rv = vapi_connect(g_vapi_ctx_instance, APP_NAME, NULL,
- MAX_OUTSTANDING_REQUESTS, RESPONSE_QUEUE_SIZE,
- VAPI_MODE_BLOCKING, true);
- if (rv != VAPI_OK) {
- SRP_LOG_DBGMSG("Error connection");
- vapi_ctx_free(g_vapi_ctx_instance);
- return -1;
- }
- SRP_LOG_DBGMSG("*connected ok");
- } else {
- SRP_LOG_DBGMSG("connection keeping");
- }
- return 0;
-}
-
-int hicn_disconnect_vpp() {
- if (NULL != g_vapi_ctx_instance) {
- vapi_disconnect(g_vapi_ctx_instance);
- vapi_ctx_free(g_vapi_ctx_instance);
- g_vapi_ctx_instance = NULL;
- }
- return 0;
-} \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.h
deleted file mode 100644
index 9abe4e5d4..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (c) 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.
- */
-
-
-/**
- * @file hicn_vpp_comm.h
- * @brief This file contains binary api to connect to the VPP.
- */
-
-
-#ifndef __HICN_VPP_COMMM_H__
-#define __HICN_VPP_COMMM_H__
-#include <sysrepo.h>
-#include <sysrepo/values.h>
-#include <vapi/vapi.h>
-
-#ifndef HICN_THIS_FUNC
-#ifdef __FUNCTION__
-#define HICN_THIS_FUNC __FUNCTION__
-#else
-#define HICN_THIS_FUNC __func__
-#endif
-#endif
-
-/**
- * @brief This is the context to connect to the vpp
- */
-
-extern vapi_ctx_t g_vapi_ctx_instance;
-
-
-/**
- * @brief This macro is interface.c to communicate with vpp
- */
-#define VPP_INTFC_NAME_LEN 64
-#define VPP_MAC_ADDRESS_LEN 8
-#define VPP_IP6_ADDRESS_LEN 16
-
-
-
-/**
- * @brief This macro checks the arg is NULL or not, if the arg is NULL it returns retval
- */
-#define ARG_CHECK(retval, arg) \
- do { \
- if (NULL == (arg)) { \
- SRP_LOG_DBGMSG("NULL pointer passed."); \
- return (retval); \
- } \
- } while (0)
-
-
-/**
- * @brief Please check ARG_CHECK
- */
-#define ARG_CHECK2(retval, arg1, arg2) \
- ARG_CHECK(retval, arg1); \
- ARG_CHECK(retval, arg2)
-
-/**
- * @brief This Macro is the multiple check of ARG_CHECK
- */
-#define ARG_CHECK5(retval, arg1, arg2, arg3, arg4, arg5) \
- ARG_CHECK(retval, arg1); \
- ARG_CHECK(retval, arg2); \
- ARG_CHECK(retval, arg3); \
- ARG_CHECK(retval, arg4); \
- ARG_CHECK(retval, arg5)
-
-/**
- * @brief This function is used to connect to the vpp
- */
-int hicn_connect_vpp();
-/**
- * @brief This function is used to close the connection of the vpp
- */
-int hicn_disconnect_vpp();
-
-#endif //__HICN_VPP_COMMM_H__
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c
deleted file mode 100644
index 3e0c90cf9..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c
+++ /dev/null
@@ -1,607 +0,0 @@
-/*
- * Copyright (c) 2016-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 <stdio.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#include <sysrepo.h>
-#include <sysrepo/values.h>
-#include <sysrepo/xpath.h>
-#include <vnet/interface.h>
-#include <vnet/vnet.h>
-#include <vnet/ip/ip.h>
-#include <vapi/interface.api.vapi.h>
-
-#include "ietf_interface.h"
-#include "../hicn_vpp_comm.h"
-
-
-DEFINE_VAPI_MSG_IDS_INTERFACE_API_JSON;
-
-typedef struct hicn_interface_
-{
- u32 sw_if_index;
- char interface_name[VPP_INTFC_NAME_LEN];
- u8 l2_address[VPP_MAC_ADDRESS_LEN];
- u64 link_speed;
- u32 flags;
- u16 link_mtu;
- u8 admin_up_down;
- u8 link_up_down;
-} hicnIntfc;
-
-typedef struct _ietf_sw_interface_dump_ctx
-{
- u8 last_called;
- int num_ifs;
- int capacity;
- hicnIntfc * intfcArray;
-} ietf_sw_interface_dump_ctx;
-
-static i32 ietf_setInterfaceFlags(u32 sw_if_index, u8 admin_up_down);
-static i32 ietf_interface_name2index(const char *name, u32* if_index);
-static i32 ietf_interface_add_del_addr(u32 sw_if_index, u8 is_add, u8 is_ipv6,
- u8 del_all, u8 address_length,
- u8 address[VPP_IP6_ADDRESS_LEN]);
-static int ietf_initSwInterfaceDumpCTX(ietf_sw_interface_dump_ctx * dctx);
-static int ietf_freeSwInterfaceDumpCTX(ietf_sw_interface_dump_ctx * dctx);
-
-/**
- * @brief Helper function for converting netmask into prefix length.
- */
-static uint8_t
-netmask_to_prefix(const char *netmask)
-{
- in_addr_t n = 0;
- uint8_t i = 0;
-
- inet_pton(AF_INET, netmask, &n);
-
- while (n > 0) {
- n = n >> 1;
- i++;
- }
-
- return i;
-}
-
-/**
- * @brief Helper function for converting IPv4/IPv6 address string into binary representation.
- */
-static int
-ip_addr_str_to_binary(const char *ip_address_str, uint8_t *ip_address_bin, bool is_ipv6)
-{
- struct in6_addr addr6 = { 0, };
- struct in_addr addr4 = { 0, };
- int ret = 0;
-
- if (is_ipv6) {
- ret = inet_pton(AF_INET6, ip_address_str, &(addr6));
- if (1 == ret)
- {
- memcpy(ip_address_bin, &addr6, sizeof(addr6));
- }
- } else {
- ret = inet_pton(AF_INET, ip_address_str, &(addr4));
- if (1 == ret)
- {
- memcpy(ip_address_bin, &addr4, sizeof(addr4));
- }
- }
-
- return ret;
-}
-
-/**
- * @brief Enable or disable given interface.
- */
-static int
-interface_enable_disable(const char *if_name, bool enable)
-{
- uint32_t if_index = ~0;
- int rc = 0;
-
-
- /* get interface index */
- rc = ietf_interface_name2index(if_name, &if_index);
- if (0 != rc) {
- SRP_LOG_ERRMSG("Invalid interface name");
- return SR_ERR_INVAL_ARG;
- }
-
- /* enable/disable interface */
- rc = ietf_setInterfaceFlags(if_index, (uint8_t)enable);
- if (0 != rc) {
- SRP_LOG_ERRMSG("Error by processing of the sw_interface_set_flags request");
- return SR_ERR_OPERATION_FAILED;
- } else {
- return SR_ERR_OK;
- }
-}
-
-
-vapi_error_e call_sw_interface_add_del_address(struct vapi_ctx_s *ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_sw_interface_add_del_address_reply *reply){
-if(!reply->retval){
- SRP_LOG_DBGMSG("Successfully done");
- return VAPI_OK;
- }else
- return VAPI_EUSER;
-}
-
-vapi_error_e call_sw_interface_set_flags(struct vapi_ctx_s *ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_sw_interface_set_flags_reply *reply){
-if(!reply->retval){
- SRP_LOG_DBGMSG("Successfully done");
- return VAPI_OK;
- }else
- return VAPI_EUSER;
-}
-
-
-
-/**
- * @brief Callback to be called by any config change of "/ietf-interfaces:interfaces/interface/enabled" leaf.
- */
-static int
-ietf_interface_enable_disable_cb(sr_session_ctx_t *session, const char *module_name, const char *xpath, sr_event_t event,
- uint32_t request_id, void *private_data)
-{
- char *if_name = NULL;
- sr_change_iter_t *iter = NULL;
- sr_change_oper_t op = SR_OP_CREATED;
- sr_val_t *old_val = NULL;
- sr_val_t *new_val = NULL;
- sr_xpath_ctx_t xpath_ctx = { 0, };
- int rc = SR_ERR_OK, op_rc = SR_ERR_OK;
-
- /* no-op for apply, we only care about SR_EV_ENABLED, SR_EV_VERIFY, SR_EV_ABORT */
- if (SR_EV_DONE == event) {
- return SR_ERR_OK;
- }
-
- /* get changes iterator */
- rc = sr_get_changes_iter(session, xpath, &iter);
- if (SR_ERR_OK != rc) {
- SRP_LOG_ERRMSG("Unable to retrieve change iterator");
- return rc;
- }
-
- /* iterate over all changes */
- while ((SR_ERR_OK == op_rc || event == SR_EV_ABORT) &&
- (SR_ERR_OK == (rc = sr_get_change_next(session, iter, &op, &old_val, &new_val)))) {
-
- SRP_LOG_DBGMSG("A change detected");
- if_name = sr_xpath_key_value(new_val ? new_val->xpath : old_val->xpath, "interface", "name", &xpath_ctx);
- switch (op) {
- case SR_OP_CREATED:
- case SR_OP_MODIFIED:
- op_rc = interface_enable_disable(if_name, new_val->data.bool_val);
- break;
- case SR_OP_DELETED:
- op_rc = interface_enable_disable(if_name, false /* !enable */);
- break;
- default:
- break;
- }
- sr_xpath_recover(&xpath_ctx);
- if (SR_ERR_INVAL_ARG == op_rc) {
- sr_set_error(session, "Invalid interface name.", new_val ? new_val->xpath : old_val->xpath);
- }
- sr_free_val(old_val);
- sr_free_val(new_val);
- }
- sr_free_change_iter(iter);
-
- return op_rc;
-}
-
-/**
- * @brief Add or remove IPv4/IPv6 address to/from an interface.
- */
-static int
-interface_ipv46_config_add_remove(const char *if_name, uint8_t *addr, uint8_t prefix, bool is_ipv6, bool add)
-{
- uint32_t if_index = ~0;
- int rc = 0;
-
- /* get interface index */
- rc = ietf_interface_name2index(if_name, &if_index);
- if (0 != rc) {
- SRP_LOG_ERRMSG("Invalid interface name");
- return SR_ERR_INVAL_ARG;
- }
-
- /* add del addr */
- rc = ietf_interface_add_del_addr(if_index, (uint8_t)add, (uint8_t)is_ipv6, 0, prefix, addr);
- if (0 != rc) {
- SRP_LOG_ERRMSG("Error by processing of the sw_interface_set_flags request");
- return SR_ERR_OPERATION_FAILED;
- } else {
- return SR_ERR_OK;
- }
-}
-int ietf_initSwInterfaceDumpCTX(ietf_sw_interface_dump_ctx * dctx)
-{
- if(dctx == NULL)
- return -1;
-
- dctx->intfcArray = NULL;
- dctx->last_called = false;
- dctx->capacity = 0;
- dctx->num_ifs = 0;
- return 0;
-}
-int ietf_freeSwInterfaceDumpCTX(ietf_sw_interface_dump_ctx * dctx)
-{
- if(dctx == NULL)
- return -1;
-
- if(dctx->intfcArray != NULL)
- {
- free(dctx->intfcArray);
- }
-
- return ietf_initSwInterfaceDumpCTX(dctx);
-}
-vapi_error_e
-ietf_sw_interface_dump_cb (struct vapi_ctx_s *ctx, void *callback_ctx,
- vapi_error_e rv, bool is_last,
- vapi_payload_sw_interface_details * reply)
-{
- ietf_sw_interface_dump_ctx *dctx = callback_ctx;
- if (is_last)
- {
- dctx->last_called = true;
- }
- else
- {
- if(dctx->capacity == 0 && dctx->intfcArray == NULL)
- {
- dctx->capacity = 10;
- dctx->intfcArray = (hicnIntfc*)malloc( sizeof(hicnIntfc)*dctx->capacity );
- }
- if(dctx->num_ifs >= dctx->capacity-1)
- {
-
- dctx->capacity += 10;
- dctx->intfcArray = (hicnIntfc*)realloc(dctx->intfcArray, sizeof(hicnIntfc)*dctx->capacity );
- }
-
- hicnIntfc * thisIntfc = &dctx->intfcArray[dctx->num_ifs];
-
- thisIntfc->sw_if_index = reply->sw_if_index;
- memcpy(thisIntfc->interface_name, reply->interface_name, VPP_INTFC_NAME_LEN);
- memcpy(thisIntfc->l2_address, reply->l2_address, VPP_MAC_ADDRESS_LEN );
- //thisIntfc->link_speed = reply->link_speed;
-#define ONE_MEGABIT (uint64_t)1000000
- switch (reply->link_speed << VNET_HW_INTERFACE_FLAG_SPEED_SHIFT)
- {
- default:
- thisIntfc->link_speed = 0;
- break;
- }
-
- thisIntfc->link_mtu = reply->link_mtu;
- thisIntfc->flags = reply->flags;
-
- dctx->num_ifs += 1;
- }
- return VAPI_OK;
-}
-
-static i32 ietf_interface_name2index(const char *name, u32* if_index)
-{
- ARG_CHECK2(-1, name, if_index);
-
- i32 ret = -1;
- ietf_sw_interface_dump_ctx dctx = {false, 0, 0, 0};
- vapi_msg_sw_interface_dump *dump;
- vapi_error_e rv;
- dctx.last_called = false;
-
- dump = vapi_alloc_sw_interface_dump(g_vapi_ctx_instance);
- dump->payload.name_filter_valid = true;
- memcpy(&dump->payload.name_filter, name, sizeof(dump->payload.name_filter));
-
- while (VAPI_EAGAIN == (rv = vapi_sw_interface_dump(g_vapi_ctx_instance, dump, ietf_sw_interface_dump_cb, &dctx)))
- ;
-
- int i = 0;
- for (; i < dctx.num_ifs; ++i)
- {
- if (strcmp(dctx.intfcArray[i].interface_name, name) == 0)
- {
- *if_index = dctx.intfcArray[i].sw_if_index;
- ret = 0;
- break;
- }
- }
- ietf_freeSwInterfaceDumpCTX(&dctx);
-
- return ret;
-}
-
-i32 ietf_interface_add_del_addr( u32 sw_if_index, u8 is_add, u8 is_ipv6, u8 del_all,
- u8 address_length, u8 address[VPP_IP6_ADDRESS_LEN] )
-{
- i32 ret = -1;
- vapi_msg_sw_interface_add_del_address *msg = vapi_alloc_sw_interface_add_del_address(g_vapi_ctx_instance);
- msg->payload.sw_if_index = sw_if_index;
- msg->payload.is_add = is_add;
- msg->payload.prefix.address.af = is_ipv6 ? ADDRESS_IP6 : ADDRESS_IP4;
- msg->payload.del_all = del_all;
- msg->payload.prefix.len = address_length;
- memcpy(msg->payload.prefix.address.un.ip6, address, VPP_IP6_ADDRESS_LEN);
-
- if(vapi_sw_interface_add_del_address(g_vapi_ctx_instance,msg,call_sw_interface_add_del_address,NULL)!=VAPI_OK){
- SRP_LOG_DBGMSG("Operation failed");
- return SR_ERR_OPERATION_FAILED;
- }
-
- return ret;
-}
-
-i32 ietf_setInterfaceFlags(u32 sw_if_index, u8 admin_up_down)
-{
- i32 ret = -1;
- vapi_msg_sw_interface_set_flags *msg = vapi_alloc_sw_interface_set_flags(g_vapi_ctx_instance);
- msg->payload.sw_if_index = sw_if_index;
- msg->payload.flags = admin_up_down? IF_STATUS_API_FLAG_ADMIN_UP : 0;
-
- if(vapi_sw_interface_set_flags(g_vapi_ctx_instance,msg,call_sw_interface_set_flags,NULL)!=VAPI_OK){
- SRP_LOG_DBGMSG("Operation failed");
- return SR_ERR_OPERATION_FAILED;
- }
-
-
- return ret;
-}
-
-
-/**
- * @brief Modify existing IPv4/IPv6 config on an interface.
- */
-static int
-interface_ipv46_config_modify(sr_session_ctx_t *session, const char *if_name,
- sr_val_t *old_val, sr_val_t *new_val, bool is_ipv6)
-{
- sr_xpath_ctx_t xpath_ctx = { 0, };
- char *addr_str = NULL;
- uint8_t addr[16] = { 0, };
- uint8_t prefix = 0;
- int rc = SR_ERR_OK;
-
- SRP_LOG_DBGMSG("Updating IP config on interface");
-
- /* get old config to be deleted */
- if (SR_UINT8_T == old_val->type) {
- prefix = old_val->data.uint8_val;
- } else if (SR_STRING_T == old_val->type) {
- prefix = netmask_to_prefix(old_val->data.string_val);
- } else {
- return SR_ERR_INVAL_ARG;
- }
- addr_str = sr_xpath_key_value((char*)old_val->xpath, "address", "ip", &xpath_ctx);
- ip_addr_str_to_binary(addr_str, addr, is_ipv6);
- sr_xpath_recover(&xpath_ctx);
-
- /* delete old IP config */
- rc = interface_ipv46_config_add_remove(if_name, addr, prefix, is_ipv6, false /* remove */);
- if (SR_ERR_OK != rc) {
- SRP_LOG_ERRMSG("Unable to remove old IP address config");
- return rc;
- }
-
- /* update the config with the new value */
- if (sr_xpath_node_name_eq(new_val->xpath, "prefix-length")) {
- prefix = new_val->data.uint8_val;
- } else if (sr_xpath_node_name_eq(new_val->xpath, "netmask")) {
- prefix = netmask_to_prefix(new_val->data.string_val);
- }
-
- /* set new IP config */
- rc = interface_ipv46_config_add_remove(if_name, addr, prefix, is_ipv6, true /* add */);
- if (SR_ERR_OK != rc) {
- SRP_LOG_ERRMSG("Unable to remove old IP address config");
- return rc;
- }
-
- return rc;
-}
-
-/**
- * @brief Callback to be called by any config change in subtrees "/ietf-interfaces:interfaces/interface/ietf-ip:ipv4/address"
- * or "/ietf-interfaces:interfaces/interface/ietf-ip:ipv6/address".
- */
-static int
-ietf_interface_ipv46_address_change_cb(sr_session_ctx_t *session, const char *module_name, const char *xpath, sr_event_t event,
- uint32_t request_id, void *private_data)
-{
- sr_change_iter_t *iter = NULL;
- sr_change_oper_t op = SR_OP_CREATED;
- sr_val_t *old_val = NULL;
- sr_val_t *new_val = NULL;
- sr_xpath_ctx_t xpath_ctx = { 0 };
- bool is_ipv6 = false, has_addr = false, has_prefix = false;
- uint8_t addr[16] = { 0, };
- uint8_t prefix = 0;
- char *node_name = NULL, *if_name = NULL;
- int rc = SR_ERR_OK, op_rc = SR_ERR_OK;
-
- /* no-op for apply, we only care about SR_EV_ENABLED, SR_EV_VERIFY, SR_EV_ABORT */
- if (SR_EV_DONE == event) {
- return SR_ERR_OK;
- }
-
- /* check whether we are handling ipv4 or ipv6 config */
- node_name = sr_xpath_node_idx((char*)xpath, 2, &xpath_ctx);
- if (NULL != node_name && 0 == strcmp(node_name, "ipv6")) {
- is_ipv6 = true;
- }
- sr_xpath_recover(&xpath_ctx);
-
- /* get changes iterator */
- rc = sr_get_changes_iter(session, xpath, &iter);
- if (SR_ERR_OK != rc) {
- // SRP_LOG_ERR("Unable to retrieve change iterator: %s", sr_strerror(rc));
- return rc;
- }
-
- /* iterate over all changes */
- while ((SR_ERR_OK == op_rc || event == SR_EV_ABORT) &&
- (SR_ERR_OK == (rc = sr_get_change_next(session, iter, &op, &old_val, &new_val)))) {
-
- if_name = strdup(sr_xpath_key_value(new_val ? new_val->xpath : old_val->xpath, "interface", "name", &xpath_ctx));
- sr_xpath_recover(&xpath_ctx);
-
- switch (op) {
- case SR_OP_CREATED:
- if (SR_LIST_T == new_val->type) {
- /* create on list item - reset state vars */
- has_addr = has_prefix = false;
- } else {
- if (sr_xpath_node_name_eq(new_val->xpath, "ip")) {
- ip_addr_str_to_binary(new_val->data.string_val, addr, is_ipv6);
- has_addr = true;
- } else if (sr_xpath_node_name_eq(new_val->xpath, "prefix-length")) {
- prefix = new_val->data.uint8_val;
- has_prefix = true;
- } else if (sr_xpath_node_name_eq(new_val->xpath, "netmask")) {
- prefix = netmask_to_prefix(new_val->data.string_val);
- has_prefix = true;
- }
- if (has_addr && has_prefix) {
- op_rc = interface_ipv46_config_add_remove(if_name, addr, prefix, is_ipv6, true /* add */);
- }
- }
- break;
- case SR_OP_MODIFIED:
- op_rc = interface_ipv46_config_modify(session, if_name, old_val, new_val, is_ipv6);
- break;
- case SR_OP_DELETED:
- if (SR_LIST_T == old_val->type) {
- /* delete on list item - reset state vars */
- has_addr = has_prefix = false;
- } else {
- if (sr_xpath_node_name_eq(old_val->xpath, "ip")) {
- ip_addr_str_to_binary(old_val->data.string_val, addr, is_ipv6);
- has_addr = true;
- } else if (sr_xpath_node_name_eq(old_val->xpath, "prefix-length")) {
- prefix = old_val->data.uint8_val;
- has_prefix = true;
- } else if (sr_xpath_node_name_eq(old_val->xpath, "netmask")) {
- prefix = netmask_to_prefix(old_val->data.string_val);
- has_prefix = true;
- }
- if (has_addr && has_prefix) {
- op_rc = interface_ipv46_config_add_remove(if_name, addr, prefix, is_ipv6, false /* !add */);
- }
- }
- break;
- default:
- break;
- }
- if (SR_ERR_INVAL_ARG == op_rc) {
- sr_set_error(session, "Invalid interface name.", new_val ? new_val->xpath : old_val->xpath);
- }
- free(if_name);
- sr_free_val(old_val);
- sr_free_val(new_val);
- }
- sr_free_change_iter(iter);
-
- return op_rc;
-}
-
-/**
- * @brief Callback to be called by any config change under "/ietf-interfaces:interfaces-state/interface" path.
- * Does not provide any functionality, needed just to cover not supported config leaves.
- */
-static int
-ietf_interface_change_cb(sr_session_ctx_t *session, const char *module_name, const char *xpath, sr_event_t event,
- uint32_t request_id, void *private_data)
-{
- return SR_ERR_OK;
-}
-
-
-int ietf_subscribe_events(sr_session_ctx_t *session,
- sr_subscription_ctx_t **subscription){
-
- int rc = SR_ERR_OK;
- SRP_LOG_DBGMSG("Subscriging ietf.");
-
- //
- rc = sr_module_change_subscribe(session, "ietf-interfaces","/ietf-interfaces:interfaces/interface", ietf_interface_change_cb,
- NULL,
- 0, SR_SUBSCR_CTX_REUSE | SR_SUBSCR_ENABLED, subscription);
-
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription /ietf-interfaces:interfaces/interface\n");
- goto error;
- }
-
- rc = sr_module_change_subscribe(session, "ietf-interfaces","/ietf-interfaces:interfaces/interface/enabled", ietf_interface_enable_disable_cb,
- NULL,
- 100, SR_SUBSCR_CTX_REUSE | SR_SUBSCR_ENABLED, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription /ietf-interfaces:interfaces/interface/enabled\n");
- goto error;
- }
-
- //rc = sr_module_change_subscribe(session, "ietf-interfaces","/ietf-interfaces:interfaces/interface/ietf-ip:ipv4/address", ietf_interface_ipv46_address_change_cb,
- rc = sr_module_change_subscribe(session, "ietf-interfaces","/ietf-interfaces:interfaces", ietf_interface_ipv46_address_change_cb,
- NULL,
- 99, SR_SUBSCR_CTX_REUSE | SR_SUBSCR_ENABLED, subscription);
-
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription /ietf-interfaces:interfaces/interface/ietf-ip:ipv4/address\n");
- goto error;
- }
-
- //rc = sr_module_change_subscribe(session, "ietf-interfaces","/ietf-interfaces:interfaces/interface/ietf-ip:ipv6/address", ietf_interface_ipv46_address_change_cb,
- // NULL,
- // 98, SR_SUBSCR_CTX_REUSE | SR_SUBSCR_ENABLED, subscription);
-
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription /ietf-interfaces:interfaces/interface/ietf-ip:ipv6/address\n");
- goto error;
- }
-
- /* rc = sr_dp_get_items_subscribe(session, "/ietf-interfaces:interfaces-state", ietf_interface_state_cb,
- NULL, SR_SUBSCR_CTX_REUSE,
- subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBG_MSG("Problem in subscription /ietf-interfaces:interfaces-state\n");
- goto error;
- }*/
-
-
- SRP_LOG_INFMSG("ietf initialized successfully.");
- return SR_ERR_OK;
-
- error:
- SRP_LOG_ERRMSG("Error by initialization of the ietf.");
- return rc;
-}
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/mainpage.dox b/ctrl/sysrepo-plugins/hicn-plugin/plugin/mainpage.dox
deleted file mode 100644
index 978578039..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/mainpage.dox
+++ /dev/null
@@ -1,211 +0,0 @@
-/** @mainpage About hICN sysrepo plugin
-*This plugin serves as a data management agent. It provides yang models via
-*NETCONF to allow the management of hicn-plugin which runs in VPP instance from out-of-box.
-
-*The following sections contain more details:
-*- @subpage subp1 "hICN yang model"
-*- @subpage subp2 "User Guide"
-*- @subpage subp3 "Developer Guide"
-*/
-
-/** @page subp1
-*hicn.yang consists of one container for providing the state data (i.e., hicn-state).
-*It consists of state, route, and face-ip-params
-*nodes with the corresponding leaves. In the hicn model a variety of RPCs are provided
-*to allow controller to communicate with the hicn-plugin as well as update the state
-*data in hicn-state. You can install the yang model using the following bash script:
-
-```
-EXIT_CODE=0
-command -v sysrepoctl > /dev/null
-if [ $? != 0 ]; then
- echo "Could not find command \"sysrepoctl\"."
- exit ${EXIT_CODE}
-else
-sysrepoctl --install path_to_hicn_yang_model
-fi
-```
-
-*Here you can find different examples to run RPC in the yang-model.
-
-```
-<hicn-enable xmlns="urn:sysrepo:hicn">
- <prefix>b001::/64</prefix>
-</hicn-enable>
-
-<hicn-disable xmlns="urn:sysrepo:hicn">
- <prefix>b001::/64</prefix>
-</hicn-disable>
-```
- */
-
-/** @page subp2
-
-*Firstly, verify the plugin and binary libraries are located correctly, then run
-*the vpp through (service vpp start). Next, run the sysrepo plugin (sysrepo-plugind),
-*for debug mode: sysrep-plugind -d -v 4 which
-*runs with high verbosity. When the hicn sysrepo plugin is loaded, run the
-*netopeer2-server which serves as NETCONF server.
-
-
-*## Connect from netopeer2-cli
-
-*In order to connect through the netopeer client run the netopeer2-cli. Then, follow these steps:
-```
-*- connect --host XXX --login XXX
-*- get (you can get the configuration and operational data)
-*- user-rpc (you can call one of the rpc proposed by hicn model but it needs an xml input)
-```
-
-*## Connect from OpenDaylight (ODL) controller
-
-
-*In order to connect through the OpenDaylight follow these procedure:
-
-*- run karaf distribution (./opendayligh_installation_folder/bin/karaf)
-*- install the required feature list in DOL (feature:install odl-netconf-server
-* odl-netconf-connector odl-restconf-all odl-netconf-topology or
-* odl-netconf-clustered-topology)
-*- run a rest client program (e.g., postman or RESTClient)
-*- mount the remote netopeer2-server to the OpenDaylight by the following REST API:
-
-*PUT http://localhost:8181/restconf/config/network-topology:network-topology/topology/topology-netconf/node/hicn-node
-
-* with the following body
-```
- <node xmlns="urn:TBD:params:xml:ns:yang:network-topology">
- <node-id>hicn-node</node-id>
- <host xmlns="urn:opendaylight:netconf-node-topology">Remote_NETCONF_SERVER_IP</host>
- <port xmlns="urn:opendaylight:netconf-node-topology">830</port>
- <username xmlns="urn:opendaylight:netconf-node-topology">username</username>
- <password xmlns="urn:opendaylight:netconf-node-topology">password</password>
- <tcp-only xmlns="urn:opendaylight:netconf-node-topology">false</tcp-only>
- <keepalive-delay xmlns="urn:opendaylight:netconf-node-topology">1</keepalive-delay>
- </node>
-```
-*Note that the header files must be set to Content-Type: application/xml, Accept: application/xml.
-
-*- send the operation through the following REST API:
-
-*POST http://localhost:8181/restconf/operations/network-topology:network-topology/topology/topology-netconf/node/hicn-node/yang-ext:mount/ietf-netconf:edit-config
-
-*The body can be used the same as edit-config in netopeer2-cli.
-
-*## Connect from Network Services Orchestrator (NSO)
-
-*To connect NSO to the netopeer2-server, first, you need to write a NED package
-*for your device. The procedure to create NED for hicn is explained in the following:
-
-*Place hicn.yang model in a folder called hicn-yang-model, and follow these steps:
-
-*- ncs-make-package --netconf-ned ./hicn-yang-model ./hicn-nso
-*- cd hicn-nso/src; make
-*- ncs-setup --ned-package ./hicn-nso --dest ./hicn-nso-project
-*- cd hicn-nso-project
-*- ncs
-*- ncs_cli -C -u admin
-*- configure
-*- devices authgroups group authhicn default-map remote-name user_name remote-password password
-*- devices device hicn address IP_device port 830 authgroup authhicn device-type netconf
-*- state admin-state unlocked
-*- commit
-*- ssh fetch-host-keys
-
-
-*At this point, we are able to connect to the remote device.
-
-
- */
-
- /** @page subp3
-
-*This guide contains information intended for developers that need to extend/modify the hICN yang model.
-
-*# Adding configuration data
-*In order to add configuration data, firstly it requires to update yang model and define the configuration paramters
-*through a container and define the leaves. Once the yang model is updated in the sysrepo plugin you need to subscribe
-*for ```sr_module_change_subscribe``` and provide the appropriate callback.
-*
-*
-*# Adding new RPC
-*
-*In order to add RPC call, firstly it requires to update the yang model by new ```rpc``` statements and define the input to them.
-
-
-*# Adding new operational data
-*
-*In order to add operational data, firstly it requires to add operational data in yang model by adding ```confg false``` to the container.
-*Then, update the sysrepo plugin by the adding the ```sr_oper_get_items_subscribe```.
-
- Example:
-I have a switch with two ports. I am going to write an RPC call to switch them on/off
-, moreover I need to read operational data from each port. So, the following yang model can be proposed:
-
-```
-module switch {
-namespace "urn:sysrepo:switch";
-prefix swtch;
-
-revision 2019-12-08{
- description "Initial revision.";
-}
-
-
-grouping status-reply{
- list port{
- key portid;
- leaf portid {
- description "the port id.";
- type uint32;
- }
- leaf status {
- description "the status of the port.";
- type boolean;
- }
-
-}
-}
-
-rpc power {
- description "Operation to power on/off switch.";
- input {
- leaf turned-on {
- description "indicating on or off.";
- type boolean;
- default false;
- }
- }
-}
-
-
-container switch-state {
-
- config false;
- description "operational data container for the switch.";
- container status{
- uses status-reply;
- }
-```
-Afterwards, the following subscribes are required in the sysrepo plugin.
-
-```
-sr_rpc_subscribe(session, "/switch:power", callback,
- session, 100,SR_SUBSCR_CTX_REUSE, subscription);
-
-```
-
-session is the opened session with sysrepo, xpath is the path in the yang model, callback is the function
-when RPC arrives, private context passed to the callback function, priprity which is set to 100 here indicates the priority if there re multiple RPCs,
-options can alter the normal behaviour, and subscription is the subscribtion when initialize the connection towards the sysrepo
-
-
-```
- rc = sr_oper_get_items_subscribe(session, "switch","/switch:switch-state/status",
- callback, NULL, SR_SUBSCR_CTX_REUSE,
- subscription);
-```
-session is the opened session with sysrepo, xpath is the path in the yang model, callback is the function
-when RPC arrives, private context passed to the callback which is NULL here,
-options can alter the normal behaviour, and subscription is the subscribtion when initialize the connection towards the sysrepo
-
-*/ \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c
deleted file mode 100644
index 63685e10a..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c
+++ /dev/null
@@ -1,875 +0,0 @@
-/*
- * Copyright (c) 2019-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.
- */
-
-/** @file hicn_model.c
- * @brief This file contains implementations of the main calls
- */
-
-#define _GNU_SOURCE
-
-#include <inttypes.h>
-#include <malloc.h>
-#include <pthread.h>
-#include <sched.h>
-#include <stdio.h>
-#include <string.h>
-#include <sysrepo/xpath.h>
-#include <unistd.h>
-/* Hicn headers */
-
-#include <hicn/util/ip_address.h>
-
-#include "../hicn_plugin.h"
-#include "../hicn_vpp_comm.h"
-#include "hicn_model.h"
-#include "tlock.h"
-
-DEFINE_VAPI_MSG_IDS_HICN_API_JSON
-
-// Shared local variables between state and RPCs
-
-/**
- * @brief this shared variable keeps the hicn state
- */
-volatile hicn_state_t *hicn_state = NULL;
-/**
- * @brief this shared variable keeps hicn strategies
- */
-volatile hicn_strategies_t *hicn_strategies = NULL;
-/**
- * @brief this shared variable keeps statistics of hicn faces
- */
-volatile hicn_faces_t *hicn_faces = NULL;
-/**
- * @brief this shared variable keeps routes information in hicn
- */
-volatile hicn_routes_t *hicn_routes = NULL;
-/**
- * @brief this shared variable is the link list to maintain all the faces (up to
- * MAX_FACES)
- */
-struct hicn_faces_s *fcurrent = NULL;
-/**
- * @brief this shared variable is the link list to maintain all the routes
- */
-struct hicn_routes_s *rcurrent = NULL;
-
-static int init_buffer(void) {
- hicn_state = memalign(MEM_ALIGN, sizeof(hicn_state_t));
- memset((hicn_state_t *)hicn_state, 0, sizeof(hicn_state_t));
-
- hicn_strategies = memalign(MEM_ALIGN, sizeof(hicn_strategies_t));
- memset((hicn_strategies_t *)hicn_strategies, 0, sizeof(hicn_strategies_t));
-
- hicn_faces = memalign(MEM_ALIGN, sizeof(hicn_faces_t));
- hicn_faces->next = memalign(MEM_ALIGN, sizeof(struct hicn_faces_s));
- fcurrent = hicn_faces->next;
-
- hicn_routes = memalign(MEM_ALIGN, sizeof(hicn_routes_t));
- hicn_routes->next = memalign(MEM_ALIGN, sizeof(struct hicn_routes_s));
- rcurrent = hicn_routes->next;
-
- int retval = -1;
- ARG_CHECK5(retval, hicn_state, hicn_strategies, fcurrent, hicn_faces,
- hicn_routes);
- hicn_routes->nroute = 0;
- hicn_faces->nface = 0;
- retval = 0;
-
- return retval;
-}
-
-static int init_face_pool(struct hicn_faces_s *head) {
- for (int i = 0; i < MAX_FACE_POOL; i++) {
- head->next = memalign(MEM_ALIGN, sizeof(struct hicn_faces_s));
- head = head->next;
- }
- SRP_LOG_DBGMSG("Face memory pool allocated\n");
- head->next = NULL;
- return 0;
-}
-
-static int init_route_pool(struct hicn_routes_s *head) {
- for (int i = 0; i < MAX_ROUTE_POOL; i++) {
- head->next = memalign(MEM_ALIGN, sizeof(struct hicn_routes_s));
- head = head->next;
- }
- SRP_LOG_DBGMSG("Route memory pool allocated\n");
- head->next = NULL;
- return 0;
-}
-
-/* VAPI CALLBACKS */
-
-static vapi_error_e call_hicn_api_strategies_get(
- struct vapi_ctx_s *ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_strategies_get_reply *reply) {
- if (!reply->retval) {
- SRP_LOG_DBGMSG("Successfully done");
- return VAPI_OK;
- } else
- return VAPI_EUSER;
-}
-
-static vapi_error_e call_hicn_api_face_params_get(
- struct vapi_ctx_s *ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_face_params_get_reply *reply) {
- if (!reply->retval) {
- if (callback_ctx != NULL) {
- struct hicn_faces_s *tmp;
- tmp = (struct hicn_faces_s *)callback_ctx;
- tmp->face.intfc = reply->swif;
- }
- return VAPI_OK;
- } else
- return VAPI_EUSER;
-}
-
-static vapi_error_e call_vapi_hicn_api_node_stats_get(
- struct vapi_ctx_s *ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_node_stats_get_reply *reply) {
- if (!reply->retval) {
- hicn_state->pkts_processed = reply->pkts_processed;
- hicn_state->pkts_interest_count = reply->pkts_interest_count;
- hicn_state->pkts_data_count = reply->pkts_data_count;
- hicn_state->pkts_from_cache_count = reply->pkts_from_cache_count;
- hicn_state->pkts_no_pit_count = reply->pkts_no_pit_count;
- hicn_state->pit_expired_count = reply->pit_expired_count;
- hicn_state->cs_expired_count = reply->cs_expired_count;
- hicn_state->cs_lru_count = reply->cs_lru_count;
- hicn_state->pkts_drop_no_buf = reply->pkts_drop_no_buf;
- hicn_state->interests_aggregated = reply->interests_aggregated;
- hicn_state->interests_retx = reply->interests_retx;
- hicn_state->pit_entries_count = reply->pit_entries_count;
- hicn_state->cs_entries_count = reply->cs_entries_count;
- hicn_state->cs_entries_ntw_count = reply->cs_entries_ntw_count;
- return VAPI_OK;
- } else
- return VAPI_EUSER;
-}
-
-static inline void state_update(sr_val_t *vals, struct lyd_node **parent,
- sr_session_ctx_t *session) {
- char buf[20];
-
- sr_val_set_xpath(&vals[0], "/hicn:hicn-state/states/pkts_processed");
- vals[0].type = SR_UINT64_T;
- vals[0].data.uint64_val = hicn_state->pkts_processed;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pkts_processed);
- *parent =
- lyd_new_path(NULL, sr_get_context(sr_session_get_connection(session)),
- vals[0].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[1], "/hicn:hicn-state/states/pkts_interest_count");
- vals[1].type = SR_UINT64_T;
- vals[1].data.uint64_val = hicn_state->pkts_interest_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pkts_interest_count);
- lyd_new_path(*parent, NULL, vals[1].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[2], "/hicn:hicn-state/states/pkts_data_count");
- vals[2].type = SR_UINT64_T;
- vals[2].data.uint64_val = hicn_state->pkts_data_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pkts_data_count);
- lyd_new_path(*parent, NULL, vals[2].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[3], "/hicn:hicn-state/states/pkts_from_cache_count");
- vals[3].type = SR_UINT64_T;
- vals[3].data.uint64_val = hicn_state->pkts_from_cache_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pkts_from_cache_count);
- lyd_new_path(*parent, NULL, vals[3].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[4], "/hicn:hicn-state/states/pkts_no_pit_count");
- vals[4].type = SR_UINT64_T;
- vals[4].data.uint64_val = hicn_state->pkts_no_pit_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pkts_no_pit_count);
- lyd_new_path(*parent, NULL, vals[4].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[5], "/hicn:hicn-state/states/pit_expired_count");
- vals[5].type = SR_UINT64_T;
- vals[5].data.uint64_val = hicn_state->pit_expired_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pit_expired_count);
- lyd_new_path(*parent, NULL, vals[5].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[6], "/hicn:hicn-state/states/cs_expired_count");
- vals[6].type = SR_UINT64_T;
- vals[6].data.uint64_val = hicn_state->cs_expired_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->cs_expired_count);
- lyd_new_path(*parent, NULL, vals[6].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[7], "/hicn:hicn-state/states/cs_lru_count");
- vals[7].type = SR_UINT64_T;
- vals[7].data.uint64_val = hicn_state->cs_lru_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->cs_lru_count);
- lyd_new_path(*parent, NULL, vals[7].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[8], "/hicn:hicn-state/states/pkts_drop_no_buf");
- vals[8].type = SR_UINT64_T;
- vals[8].data.uint64_val = hicn_state->pkts_drop_no_buf;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pkts_drop_no_buf);
- lyd_new_path(*parent, NULL, vals[8].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[9], "/hicn:hicn-state/states/interests_aggregated");
- vals[9].type = SR_UINT64_T;
- vals[9].data.uint64_val = hicn_state->interests_aggregated;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->interests_aggregated);
- lyd_new_path(*parent, NULL, vals[9].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[10], "/hicn:hicn-state/states/interests_retx");
- vals[10].type = SR_UINT64_T;
- vals[10].data.uint64_val = hicn_state->interests_retx;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->interests_retx);
- lyd_new_path(*parent, NULL, vals[10].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[11],
- "/hicn:hicn-state/states/interests_hash_collision");
- vals[11].type = SR_UINT64_T;
- vals[11].data.uint64_val = hicn_state->interests_hash_collision;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->interests_hash_collision);
- lyd_new_path(*parent, NULL, vals[11].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[12], "/hicn:hicn-state/states/pit_entries_count");
- vals[12].type = SR_UINT64_T;
- vals[12].data.uint64_val = hicn_state->pit_entries_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->pit_entries_count);
- lyd_new_path(*parent, NULL, vals[12].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[13], "/hicn:hicn-state/states/cs_entries_count");
- vals[13].type = SR_UINT64_T;
- vals[13].data.uint64_val = hicn_state->cs_entries_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->cs_entries_count);
- lyd_new_path(*parent, NULL, vals[13].xpath, buf, 0, 0);
-
- sr_val_set_xpath(&vals[14], "/hicn:hicn-state/states/cs_entries_ntw_count");
- vals[14].type = SR_UINT64_T;
- vals[14].data.uint64_val = hicn_state->cs_entries_ntw_count;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, hicn_state->cs_entries_ntw_count);
- lyd_new_path(*parent, NULL, vals[14].xpath, buf, 0, 0);
-}
-
-static inline int routes_update(sr_val_t *vals, uint32_t nleaves,
- struct lyd_node **parent,
- sr_session_ctx_t *session) {
- struct hicn_routes_s *temp = hicn_routes->next;
- char buf[20];
- int route = 0;
- for (int count = 0; count < nleaves; count++) {
- sr_val_build_xpath(&vals[route], "%s[routeid='%d']/prefix",
- "/hicn:hicn-state/routes/route", temp->route.route_id);
- vals[route].type = SR_STRING_T;
-
- memset(buf, 0x00, 20);
- if (temp->route.prefix.address.af == ADDRESS_IP4) {
- struct sockaddr_in sa;
- memcpy(&sa.sin_addr.s_addr, temp->route.prefix.address.un.ip4,
- IPV4_ADDR_LEN);
- inet_ntop(AF_INET, &(sa.sin_addr), buf, INET_ADDRSTRLEN);
- vals[route].data.string_val = buf;
- } else {
- struct sockaddr_in6 sa;
- memcpy(&sa.sin6_addr, temp->route.prefix.address.un.ip6, IPV6_ADDR_LEN);
- inet_ntop(AF_INET6, &(sa.sin6_addr), buf, INET6_ADDRSTRLEN);
- vals[route].data.string_val = buf;
- }
-
- lyd_new_path(*parent, NULL, vals[route].xpath, buf, 0, 0);
-
- route++;
-
- sr_val_build_xpath(&vals[route], "%s[routeid='%d']/strategy_id",
- "/hicn:hicn-state/routes/route", temp->route.route_id);
- vals[route].type = SR_UINT32_T;
- vals[route].data.uint32_val = temp->route.strategy_id;
- memset(buf, 0x00, 20);
- sprintf(buf, "%d", temp->route.strategy_id);
- lyd_new_path(*parent, NULL, vals[route].xpath, buf, 0, 0);
-
- route++;
-
- temp = temp->next;
- }
-
- SRP_LOG_DBGMSG("Routes state updated \n");
- return SR_ERR_OK;
-}
-
-static inline int faces_update(sr_val_t *vals, uint32_t nleaves,
- struct lyd_node **parent,
- sr_session_ctx_t *session) {
- struct hicn_faces_s *temp = hicn_faces->next;
- char buf[20];
- int face = 0;
-
- for (int count = 0; count < nleaves; count++) {
- vapi_msg_hicn_api_face_params_get *msg;
- msg = vapi_alloc_hicn_api_face_params_get(g_vapi_ctx_instance);
-
- msg->payload.faceid = temp->face.faceid;
-
- if (vapi_hicn_api_face_params_get(g_vapi_ctx_instance, msg,
- call_hicn_api_face_params_get,
- (void *)temp) != VAPI_OK) {
- SRP_LOG_DBGMSG("Operation failed");
- return SR_ERR_OPERATION_FAILED;
- }
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/intfc",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT32_T;
- vals[face].data.uint32_val = temp->face.intfc;
- memset(buf, 0x00, 20);
- sprintf(buf, "%u", temp->face.intfc);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/irx_packets",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.irx_packets;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.irx_packets);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/irx_bytes",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.irx_bytes;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.irx_bytes);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/itx_packets",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.itx_packets;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.itx_packets);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/itx_bytes",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.itx_bytes;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.itx_bytes);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/drx_packets",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.drx_packets;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.drx_packets);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/drx_bytes",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.drx_bytes;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.drx_packets);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/dtx_packets",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.dtx_packets;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.dtx_packets);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- sr_val_build_xpath(&vals[face], "%s[faceid='%d']/dtx_bytes",
- "/hicn:hicn-state/faces/face", temp->face.faceid);
- vals[face].type = SR_UINT64_T;
- vals[face].data.uint64_val = temp->face.dtx_bytes;
- memset(buf, 0x00, 20);
- sprintf(buf, "%" PRIu64, temp->face.dtx_bytes);
- lyd_new_path(*parent, NULL, vals[face].xpath, buf, 0, 0);
-
- face++;
-
- temp = temp->next;
- }
- SRP_LOG_DBGMSG("Faces state updated \n");
- return SR_ERR_OK;
-}
-
-static int hicn_state_states_cb(sr_session_ctx_t *session,
- const char *module_name, const char *path,
- const char *request_xpath, uint32_t request_id,
- struct lyd_node **parent, void *private_data) {
- sr_val_t *vals;
- int rc;
- enum locks_name state;
- state = lstate;
- SRP_LOG_DBGMSG("Requesting state data");
-
- rc = sr_new_values(NSTATE_LEAVES, &vals);
- if (SR_ERR_OK != rc) {
- return rc;
- }
-
- tlock(state);
- state_update(vals, parent, session);
- tunlock(state);
-
- return SR_ERR_OK;
-}
-
-static int hicn_state_route_cb(sr_session_ctx_t *session,
- const char *module_name, const char *path,
- const char *request_xpath, uint32_t request_id,
- struct lyd_node **parent, void *private_data) {
- sr_val_t *vals;
- int rc;
- enum locks_name route;
- route = lroute;
- uint32_t NROUTE_NODES = hicn_routes->nroute * ROUTES_CHILDREN;
-
- rc = sr_new_values(NROUTE_NODES, &vals);
- if (SR_ERR_OK != rc) {
- return rc;
- }
-
- tlock(route);
- routes_update(vals, NROUTE_NODES / ROUTES_CHILDREN, parent, session);
- tunlock(route);
-
- return SR_ERR_OK;
-}
-
-static int hicn_state_faces_cb(sr_session_ctx_t *session,
- const char *module_name, const char *path,
- const char *request_xpath, uint32_t request_id,
- struct lyd_node **parent, void *private_data) {
- sr_val_t *vals;
- int rc;
- enum locks_name faces;
- faces = lfaces;
- uint32_t NFACES_NODES = hicn_faces->nface * FACES_CHILDREN;
-
- rc = sr_new_values(NFACES_NODES, &vals);
- if (SR_ERR_OK != rc) {
- return rc;
- }
-
- tlock(faces);
- faces_update(vals, NFACES_NODES / FACES_CHILDREN, parent, session);
- tunlock(faces);
-
- return SR_ERR_OK;
-}
-
-static int hicn_strategies_get_cb(sr_session_ctx_t *session, const char *path,
- const sr_val_t *input, const size_t input_cnt,
- sr_event_t event, uint32_t request_id,
- sr_val_t **output, size_t *output_cnt,
- void *private_data) {
- SRP_LOG_DBGMSG("hicn strategies received successfully");
- vapi_msg_hicn_api_strategies_get *msg;
-
- msg = vapi_alloc_hicn_api_strategies_get(g_vapi_ctx_instance);
-
- if (vapi_hicn_api_strategies_get(g_vapi_ctx_instance, msg,
- call_hicn_api_strategies_get,
- NULL) != VAPI_OK) {
- SRP_LOG_DBGMSG("Operation failed");
- return SR_ERR_OPERATION_FAILED;
- }
- return SR_ERR_OK;
-}
-
-static int hicn_face_params_get_cb(sr_session_ctx_t *session, const char *path,
- const sr_val_t *input,
- const size_t input_cnt, sr_event_t event,
- uint32_t request_id, sr_val_t **output,
- size_t *output_cnt, void *private_data) {
- SRP_LOG_DBGMSG("hicn face ip params get received successfully");
- vapi_msg_hicn_api_face_params_get *msg;
-
- msg = vapi_alloc_hicn_api_face_params_get(g_vapi_ctx_instance);
-
- msg->payload.faceid = input[0].data.uint32_val;
-
- if (vapi_hicn_api_face_params_get(g_vapi_ctx_instance, msg,
- call_hicn_api_face_params_get,
- NULL) != VAPI_OK) {
- SRP_LOG_DBGMSG("Operation failed");
- return SR_ERR_OPERATION_FAILED;
- }
-
- return SR_ERR_OK;
-}
-
-static vapi_error_e call_hicn_api_enable_disable(
- struct vapi_ctx_s *ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_enable_disable_reply *reply) {
- if (!reply->retval) {
- SRP_LOG_DBGMSG("Successfully done");
- return VAPI_OK;
- } else
- return VAPI_EUSER;
-}
-
-static int hicn_enable_cb(sr_session_ctx_t *session, const char *path,
- const sr_val_t *input, const size_t input_cnt,
- sr_event_t event, uint32_t request_id,
- sr_val_t **output, size_t *output_cnt,
- void *private_data) {
- SRP_LOG_DBGMSG("hicn enable received successfully");
- vapi_msg_hicn_api_enable_disable *msg;
-
- msg = vapi_alloc_hicn_api_enable_disable(g_vapi_ctx_instance);
-
- const char *delim = "/";
- if (input->type != SR_STRING_T) {
- SRP_LOG_DBGMSG("Expected prefix of type string");
- return SR_ERR_OPERATION_FAILED;
- }
- char *token;
-
- /* get the first token */
- token = strtok(input->data.string_val, delim);
-
- /* if null the address is ipv4 else ipv6*/
- if (strrchr(token, ':') == NULL) {
- struct sockaddr_in sa;
- inet_pton(AF_INET, token, &(sa.sin_addr));
- unsigned char *tmp = (unsigned char *)&sa.sin_addr.s_addr;
- memcpy(&msg->payload.prefix.address.un.ip4[0], tmp, B32);
- msg->payload.prefix.address.af = ADDRESS_IP4;
- } else {
- void *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, token, dst);
- unsigned char *tmp = (unsigned char *)((struct in6_addr *)dst)->s6_addr;
- memcpy(&msg->payload.prefix.address.un.ip6[0], tmp, B128);
- msg->payload.prefix.address.af = ADDRESS_IP6;
- }
-
- /* The second token is the prefix len*/
- token = strtok(NULL, delim);
-
- msg->payload.prefix.len = atoi(token);
- msg->payload.enable_disable = 1;
-
- if (vapi_hicn_api_enable_disable(g_vapi_ctx_instance, msg,
- call_hicn_api_enable_disable,
- NULL) != VAPI_OK) {
- SRP_LOG_DBGMSG("Operation failed");
- return SR_ERR_OPERATION_FAILED;
- }
-
- return SR_ERR_OK;
-}
-
-static int hicn_disable_cb(sr_session_ctx_t *session, const char *path,
- const sr_val_t *input, const size_t input_cnt,
- sr_event_t event, uint32_t request_id,
- sr_val_t **output, size_t *output_cnt,
- void *private_data) {
- SRP_LOG_DBGMSG("hicn disable received successfully");
- vapi_msg_hicn_api_enable_disable *msg;
-
- msg = vapi_alloc_hicn_api_enable_disable(g_vapi_ctx_instance);
-
- const char *delim = "/";
- if (input->type != SR_STRING_T) {
- SRP_LOG_DBGMSG("Expected prefix of type string");
- return SR_ERR_OPERATION_FAILED;
- }
- char *token;
-
- /* get the first token */
- token = strtok(input->data.string_val, delim);
-
- /* if null the address is ipv4 else ipv6*/
- if (strrchr(token, ':') == NULL) {
- struct sockaddr_in sa;
- inet_pton(AF_INET, token, &(sa.sin_addr));
- unsigned char *tmp = (unsigned char *)&sa.sin_addr.s_addr;
- memcpy(&msg->payload.prefix.address.un.ip4[0], tmp, B32);
- msg->payload.prefix.address.af = ADDRESS_IP4;
- } else {
- void *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, token, dst);
- unsigned char *tmp = (unsigned char *)((struct in6_addr *)dst)->s6_addr;
- memcpy(&msg->payload.prefix.address.un.ip6[0], tmp, B128);
- msg->payload.prefix.address.af = ADDRESS_IP6;
- }
-
- /* The second token is the prefix len*/
- token = strtok(NULL, delim);
-
- msg->payload.prefix.len = atoi(token);
- msg->payload.enable_disable = 0;
-
- if (vapi_hicn_api_enable_disable(g_vapi_ctx_instance, msg,
- call_hicn_api_enable_disable,
- NULL) != VAPI_OK) {
- SRP_LOG_DBGMSG("Operation failed");
- return SR_ERR_OPERATION_FAILED;
- }
-
- return SR_ERR_OK;
-}
-
-static vapi_error_e hicn_api_routes_dump_cb(
- struct vapi_ctx_s *ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_routes_details *reply) {
- static int counter = 0;
-
- tlock(lroute);
- if (reply != NULL) {
- rcurrent->route.route_id = counter;
- rcurrent->route.prefix = reply->prefix;
- rcurrent->route.nfaces = reply->nfaces;
- rcurrent->route.strategy_id = reply->strategy_id;
- for (int cnt = 0; cnt < rcurrent->route.nfaces; cnt++)
- rcurrent->route.faceids[cnt] = rcurrent->route.faceids[cnt];
-
- counter++;
- rcurrent = rcurrent->next;
-
- SRP_LOG_DBG("nfaces %d", reply->nfaces);
- SRP_LOG_DBG("strategy_id %d", reply->strategy_id);
-
- } else {
- SRP_LOG_DBGMSG("---------Routes------- \n");
- hicn_routes->nroute = counter;
- counter = 0;
- rcurrent = hicn_routes->next;
- }
- tunlock(lroute);
- return SR_ERR_OK;
-}
-
-static vapi_error_e hicn_api_face_stats_dump_cb(
- struct vapi_ctx_s *ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_face_stats_details *reply) {
- static int counter = 0;
-
- tlock(lfaces);
- if (reply != NULL) {
- fcurrent->face.faceid = reply->faceid;
- fcurrent->face.intfc = 1;
- fcurrent->face.irx_packets = reply->irx_packets;
- fcurrent->face.irx_bytes = reply->irx_bytes;
- fcurrent->face.itx_packets = reply->itx_packets;
- fcurrent->face.itx_bytes = reply->itx_bytes;
- fcurrent->face.drx_packets = reply->drx_packets;
- fcurrent->face.drx_bytes = reply->drx_bytes;
- fcurrent->face.dtx_packets = reply->dtx_packets;
- fcurrent->face.dtx_bytes = reply->dtx_bytes;
- counter++;
- fcurrent = fcurrent->next;
- SRP_LOG_DBG("faceid %d", reply->faceid);
- SRP_LOG_DBG("drxB %d", reply->drx_bytes);
- SRP_LOG_DBG("dtxB %d", reply->dtx_bytes);
-
- } else {
- SRP_LOG_DBGMSG("---------Faces------- \n");
- hicn_faces->nface = counter;
- counter = 0;
- fcurrent = hicn_faces->next;
- }
- tunlock(lfaces);
- return SR_ERR_OK;
-}
-
-static void *state_thread(void *arg) {
- // mapping can be retrieved by cpuinfo
- int map = 0;
- cpu_set_t cpuset;
- CPU_ZERO(&cpuset);
- CPU_SET(map, &cpuset);
-
- // pin the thread to a core
- if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset)) {
- SRP_LOG_DBGMSG("Thread pining failed\n");
- exit(1);
- }
-
- vapi_msg_hicn_api_node_stats_get *msg = NULL;
- enum locks_name state;
- state = lstate;
-
- while (true) {
- tlock(state);
- // dump faces
- vapi_msg_hicn_api_face_stats_dump *fmsg;
- fmsg = vapi_alloc_hicn_api_face_stats_dump(g_vapi_ctx_instance);
- vapi_hicn_api_face_stats_dump(g_vapi_ctx_instance, fmsg,
- hicn_api_face_stats_dump_cb, fcurrent);
-
- // dump routes
- vapi_msg_hicn_api_routes_dump *rmsg;
- rmsg = vapi_alloc_hicn_api_routes_dump(g_vapi_ctx_instance);
- vapi_hicn_api_routes_dump(g_vapi_ctx_instance, rmsg,
- hicn_api_routes_dump_cb, rcurrent);
-
- msg = vapi_alloc_hicn_api_node_stats_get(g_vapi_ctx_instance);
-
- if (vapi_hicn_api_node_stats_get(g_vapi_ctx_instance, msg,
- call_vapi_hicn_api_node_stats_get,
- NULL) != VAPI_OK) {
- SRP_LOG_DBGMSG(" State operation failed");
- }
-
- tunlock(state);
- sleep(1);
-
- SRP_LOG_DBGMSG("state cached");
- }
- return NULL;
-}
-
-int hicn_subscribe_events(sr_session_ctx_t *session,
- sr_subscription_ctx_t **subscription) {
- int rc = SR_ERR_OK;
- SRP_LOG_DBGMSG("Subscriging hicn.");
-
- // Initializing the locks
- for (int i = 0; i < NLOCKS; i++) ticket_init(i, LOCK_INIT);
-
- // Initializing the buffer
- rc = init_buffer();
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in initializing the buffers\n");
- goto error;
- }
-
- SRP_LOG_DBGMSG("buffer initialized successfully.");
-
- rc = init_face_pool(fcurrent);
- if (rc) {
- SRP_LOG_DBGMSG("Problem in initializing the pools\n");
- goto error;
- }
-
- rc = init_route_pool(rcurrent);
- if (rc) {
- SRP_LOG_DBGMSG("Problem in initializing the pools\n");
- goto error;
- }
-
- SRP_LOG_DBGMSG("pools created successfully.");
-
- // Create state thread observation
- pthread_t state_tid;
- rc = pthread_create((pthread_t *)&state_tid, NULL, state_thread, NULL);
- if (rc != 0) {
- SRP_LOG_DBGMSG("Error making hicn state thread");
- return SR_ERR_OPERATION_FAILED;
- }
- SRP_LOG_DBGMSG("State thread created successfully.");
-
- // strategies subscriptions
-
- rc = sr_rpc_subscribe(session, "/hicn:strategies-get", hicn_strategies_get_cb,
- session, 98, SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription strategies-get\n");
- goto error;
- }
-
- // face ip subscriptions
-
- rc = sr_rpc_subscribe(session, "/hicn:face-params-get",
- hicn_face_params_get_cb, session, 93,
- SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription face-params-get\n");
- goto error;
- }
-
- // hICN enable-disable subscriptions
-
- rc = sr_rpc_subscribe(session, "/hicn:hicn-enable", hicn_enable_cb, session,
- 94, SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription hicn-enable\n");
- goto error;
- }
-
- rc = sr_rpc_subscribe(session, "/hicn:hicn-disable", hicn_disable_cb, session,
- 95, SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription hicn-enable\n");
- goto error;
- }
-
- // subscribe as hicn state data provider
-
- rc = sr_oper_get_items_subscribe(session, "hicn", "/hicn:hicn-state/states",
- hicn_state_states_cb, NULL,
- SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription /hicn:hicn-state/states\n");
- goto error;
- }
-
- rc = sr_oper_get_items_subscribe(session, "hicn", "/hicn:hicn-state/routes",
- hicn_state_route_cb, NULL,
- SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription /hicn:hicn-state/routes\n");
- goto error;
- }
-
- rc = sr_oper_get_items_subscribe(session, "hicn", "/hicn:hicn-state/faces",
- hicn_state_faces_cb, NULL,
- SR_SUBSCR_CTX_REUSE, subscription);
- if (rc != SR_ERR_OK) {
- SRP_LOG_DBGMSG("Problem in subscription /hicn:hicn-state/faces\n");
- goto error;
- }
-
- SRP_LOG_DBGMSG("hicn plugin initialized successfully.\n");
- return SR_ERR_OK;
-
-error:
- SRP_LOG_ERRMSG("Error by initialization of the hicn plugin.");
- sr_plugin_cleanup_cb(session, &g_vapi_ctx_instance);
- return rc;
-}
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h
deleted file mode 100644
index 62fb15340..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
-* Copyright (c) 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.
-*/
-
-/**
- * @file hicn_model.h
- * @brief This file contains main calls for hICN events coresponding to the hICN yang models
- */
-
-#ifndef __IETF_HICN_H__
-#define __IETF_HICN_H__
-
-#include "../hicn_vpp_comm.h"
-#include <vapi/hicn.api.vapi.h>
-
-/**
- * @brief Align memory to one page boundary
- */
-#define MEM_ALIGN 4096
-
-/**
- * @brief 32 bits = 4 bytes
- */
-#define B32 4
-/**
- * @brief 64bits = 8 bytes
- */
-#define B64 8
-/**
- * @brief 128 bits = 16 bytes
- */
-#define B128 16
-
-/**
- * @brief set number of lock to 5
- */
-#define NLOCKS 5
-
-/**
- * @brief initialize all locks by 0, better to initialize by 0 :)
- */
-#define LOCK_INIT 0
-
-/**
- * @brief enumeration for the locks
- */
-enum locks_name {lstate, lstrategy, lstrategies, lroute, lfaces};
-
-
-// It is a coarse grain approach later can be changed to fine grained
-
-
-/**
- * @brief This indicates the number of leaves for the hICN state
- */
-#define NSTATE_LEAVES 15
-/**
- * @brief This indicates the number of leaves for strategy
- */
-#define NSTRATEGY_LEAVES 1
-/**
- * @brief This indicates the number of leaves for strategies
- */
-#define NSTRATEGIES_LEAVES 2
-/**
- * @brief This indicates the maximum faces which can be read as operational data
- */
-#define MAX_FACE_POOL 100
-/**
- * @brief This indicates the maximum routes which can be read as operational data
- */
-#define MAX_ROUTE_POOL 100
-/**
- * @brief This indicates the number of leaves for faces
- */
-#define FACES_CHILDREN 9 /*this is the number of children of each leave in face except the key*/
-/**
- * @brief This indicates the number of leaves for routes
- */
-#define ROUTES_CHILDREN 2 /*this is the number of children of each leave in face except the key*/
-
-typedef struct __attribute__ ((__packed__)) {
- int32_t retval;
- uint64_t pkts_processed;
- uint64_t pkts_interest_count;
- uint64_t pkts_data_count;
- uint64_t pkts_from_cache_count;
- uint64_t pkts_no_pit_count;
- uint64_t pit_expired_count;
- uint64_t cs_expired_count;
- uint64_t cs_lru_count;
- uint64_t pkts_drop_no_buf;
- uint64_t interests_aggregated;
- uint64_t interests_retx;
- uint64_t interests_hash_collision;
- uint64_t pit_entries_count;
- uint64_t cs_entries_count;
- uint64_t cs_entries_ntw_count;
-} hicn_state_t;
-
-
-typedef struct __attribute__ ((__packed__)) {
-
- uint8_t n_strategies;
- uint32_t strategy_id[256];
- int32_t retval;
-} hicn_strategies_t;
-
-
-typedef struct __attribute__ ((__packed__)) {
- uint32_t faceid;
- uint32_t intfc;
- uint64_t irx_packets;
- uint64_t irx_bytes;
- uint64_t itx_packets;
- uint64_t itx_bytes;
- uint64_t drx_packets;
- uint64_t drx_bytes;
- uint64_t dtx_packets;
- uint64_t dtx_bytes;
-} hicn_face_inf_t;
-
-
-typedef struct __attribute__ ((__packed__)) {
- u32 route_id;
- vapi_type_prefix prefix;
- u32 faceids[5];
- u8 nfaces;
- u32 strategy_id;
-} hicn_route_inf_t;
-
-/**
- * @brief This is the link list to maintain the statistics of the faces
- */
-struct hicn_faces_s{
- hicn_face_inf_t face;
- struct hicn_faces_s * next;
-};
-
-
-typedef struct __attribute__ ((__packed__)) {
- uint32_t nface;
- struct hicn_faces_s * next;
-} hicn_faces_t;
-
-/**
- * @brief This is the link list to maintain the route informations
- */
-struct hicn_routes_s{
- hicn_route_inf_t route;
- struct hicn_routes_s * next;
-};
-
-
-typedef struct __attribute__ ((__packed__)) {
- uint32_t nroute;
- struct hicn_routes_s * next;
-} hicn_routes_t;
-
-/**
- * @brief This function subscribes the hICN evens consisting of all RPCs
- * as well as operational data
- */
-int hicn_subscribe_events(sr_session_ctx_t *session,
- sr_subscription_ctx_t **subscription);
-
-#endif /* __IETF_HICN_H__ */
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.c
deleted file mode 100644
index d27ae6492..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.c
+++ /dev/null
@@ -1,21 +0,0 @@
-#include"tlock.h"
-
-
-void ticket_init ( int Lock_Number , long int init ){
-
-//__atomic_store( &En[Lock_Number] , &init , __ATOMIC_SEQ_CST );
-//__atomic_store( &De[Lock_Number] , &init , __ATOMIC_SEQ_CST );
-En[Lock_Number]=init;
-De[Lock_Number]=init;
-}
-
-void tlock(int Lock_Number ){
-
- int my_ticket = __sync_fetch_and_add(&En[Lock_Number] , 1 );
- while ( my_ticket != De[ Lock_Number ] ) {};
-
-}
-
-void tunlock(int Lock_Number ){
-De[Lock_Number]++;
-}
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.h
deleted file mode 100644
index a871705a3..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 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.
- */
-
-
-
-/**
- * @file tlock.h
- * @brief This file contains ticket lock APIs.
- */
-
-#ifndef __TLOCK_H__
-#define __TLOCK_H__
-
-
-/**
-
- * @brief limit the number of locks: it shoud be matched with the
- * number of hicn-state leaves
- */
-#define MAX_LOCK_SIZE 5
-
-/**
- * @brief Ticket lock counters
- */
-volatile long int En[MAX_LOCK_SIZE] ;
-
-/**
- * @brief Ticket lock counters
- */
-volatile long int De[MAX_LOCK_SIZE] ;
-
-
-/**
- * @brief This function initialize the ticket lock
- * @param Lock_Number describes the number of locks need to be initialized
- * @param init describes the init number
- */
-void ticket_init ( int Lock_Number , long int init );
-/**
- * @brief this function acquire the lock
- * Description of what the function does. This part may refer to the parameters
- * @param Lock_Number pass the lock
- */
-void tlock(int Lock_Number );
-/**
- * @briefthis function release the lock
- * @param Lock_Number lock number
-
- */
-void tunlock(int Lock_Number );
-
-#endif /* __IETF_HICN_H__ */ \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/README.md b/ctrl/sysrepo-plugins/hicn-plugin/test/README.md
deleted file mode 100644
index a1c9bedff..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/README.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# test hICN sysrepo plugin
-
-Two simple tests are provided to verify the functionality of the plugin. In ```netconf-test``` you can find ```test.py``` which uses netconf-clinet library to send NETCONF command toward the sysrepo. This is the usage:
-```
-python test.py host user password operation
-```
-<b>host</b> indicates the host information. <b>user</b>, <b>password</b> are credentials to connect to the device. <b>Operation</b> can be one of the following:
-```
-- route_dump
- It receives the route operational data from vpp
-- face_dump
- It receives the face operational data from vpp
-- face_add
- It adds an hICN face in the vpp
-- punt_add
- It adds a punt in the vpp
-- route_add
- It adds route in the vpp
-- face_dell
- It deletes face from vpp
-- route_del
- It deletes route from vpp
-- punt_del
- It deletes punt from vpp
-```
-
-In the ```vapi-test``` you can find testing the VAPI for the communication between the hICN sysrepo plugin and vpp. This is the usage:
-
-```
-./test [route_add [4|6], punt_add [4|6], face_add [4|6], route_dump, face_dump]
-```
-The definition for the argument is the same as the netconf-test except that here you can choose the test for IPV4 and IPV6.
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aface.xml b/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aface.xml
deleted file mode 100644
index e1452f722..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aface.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<face-ip-add xmlns="urn:sysrepo:hicn">
- <lip4>192.168.20.10</lip4>
- <lip6>-1</lip6>
- <rip4>192.168.100.1</rip4>
- <rip6>-1</rip6>
- <swif>0</swif>
-</face-ip-add>
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/apunt.xml b/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/apunt.xml
deleted file mode 100644
index b7fa8b741..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/apunt.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<punting-add xmlns="urn:sysrepo:hicn">
- <ip4>192.168.0.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <swif>0</swif>
-</punting-add>
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aroute.xml b/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aroute.xml
deleted file mode 100644
index 9997452b9..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/aroute.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<route-nhops-add xmlns="urn:sysrepo:hicn">
- <ip4>192.168.1.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <face_ids0>0</face_ids0>
- <face_ids1>0</face_ids1>
- <face_ids2>0</face_ids2>
- <face_ids3>0</face_ids3>
- <face_ids4>0</face_ids4>
- <face_ids5>0</face_ids5>
- <face_ids6>0</face_ids6>
- <n_faces>1</n_faces>
-</route-nhops-add>
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dface.xml b/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dface.xml
deleted file mode 100644
index 07a9488a9..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dface.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<face-ip-del xmlns="urn:sysrepo:hicn">
- <faceid>0</faceid>
-</face-ip-del>
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dpunt.xml b/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dpunt.xml
deleted file mode 100644
index 72d5c3c88..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/dpunt.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<punting-del xmlns="urn:sysrepo:hicn">
- <ip4>192.168.0.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <swif>0</swif>
-</punting-del>
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/droute.xml b/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/droute.xml
deleted file mode 100644
index ded28eecf..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/droute.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<route-nhops-del xmlns="urn:sysrepo:hicn">
- <ip4>192.168.1.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <faceid>0</faceid>
-</route-nhops-del>
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/test.py b/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/test.py
deleted file mode 100755
index 7c6163521..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/netconf-test/test.py
+++ /dev/null
@@ -1,66 +0,0 @@
-import sys
-import xml.etree.ElementTree as ET
-from netconf.client import connect_ssh
-
-def usage():
- print('usage: test.py host user password operation{route_dump, face_dump, face_add, route_add, punt_add, face_del, punt_del, route_del}')
-
-def test(host,user,password,operation):
- with connect_ssh(host, 830, user, password) as session:
- if (operation=='face_dump'):
- config = session.get()
- for root in config:
- if root.tag=="{urn:sysrepo:hicn}hicn-state":
- for entity in root:
- if entity.tag=="{urn:sysrepo:hicn}faces":
- print('Faces')
- for face in entity:
- for elem in face:
- print(elem.tag +" : "+ elem.text)
- elif (operation=='state_dump'):
- config = session.get()
- for root in config:
- if root.tag=="{urn:sysrepo:hicn}hicn-state":
- for entity in root:
- if entity.tag=="{urn:sysrepo:hicn}states":
- print('States')
- for state in entity:
- print(state.tag +" : "+ state.text)
- elif (operation=='route_dump'):
- config = session.get()
- for root in config:
- if root.tag=="{urn:sysrepo:hicn}hicn-state":
- for entity in root:
- if entity.tag=="{urn:sysrepo:hicn}routes":
- print('Routes')
- for route in entity:
- for elem in route:
- print(elem.tag +" : "+ elem.text)
- elif(operation=='face_add'):
- root = ET.parse('aface.xml').getroot()
- session.send_rpc(ET.tostring(root, encoding='utf8').decode('utf8'))
- elif(operation=='punt_add'):
- root = ET.parse('apunt.xml').getroot()
- session.send_rpc(ET.tostring(root, encoding='utf8').decode('utf8'))
- elif(operation=='route_add'):
- root = ET.parse('aroute.xml').getroot()
- session.send_rpc(ET.tostring(root, encoding='utf8').decode('utf8'))
- elif(operation=='face_del'):
- root = ET.parse('dface.xml').getroot()
- session.send_rpc(ET.tostring(root, encoding='utf8').decode('utf8'))
- elif(operation=='punt_del'):
- root = ET.parse('dpunt.xml').getroot()
- session.send_rpc(ET.tostring(root, encoding='utf8').decode('utf8'))
- elif(operation=='route_del'):
- root = ET.parse('droute.xml').getroot()
- session.send_rpc(ET.tostring(root, encoding='utf8').decode('utf8'))
- else:
- usage()
-
-if __name__ == '__main__':
- if(len(sys.argv)<4):
- usage()
- else:
- test(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
-
-
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/Makefile b/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/Makefile
deleted file mode 100755
index 8ab5d27de..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/Makefile
+++ /dev/null
@@ -1,2 +0,0 @@
-main:
- sudo gcc -g -o test test.c -lvapiclient
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/test.c b/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/test.c
deleted file mode 100755
index f7b92c3c5..000000000
--- a/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/test.c
+++ /dev/null
@@ -1,290 +0,0 @@
-#include <vapi/vapi.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <signal.h>
-#include <inttypes.h>
-
-#include<vapi/hicn.api.vapi.h>
-
-
-DEFINE_VAPI_MSG_IDS_HICN_API_JSON;
-
-vapi_ctx_t g_vapi_ctx_instance;
-
-
-#define APP_NAME "test_hicn_plugin"
-#define MAX_OUTSTANDING_REQUESTS 4
-#define RESPONSE_QUEUE_SIZE 2
-
-vapi_ctx_t g_vapi_ctx_instance = NULL;
-
-
-void usage(){
- printf("choose the test [route_add [4|6], punt_add [4|6], face_add [4|6], route_dump, face_dump]\n");
-}
-
-static vapi_error_e call_hicn_api_punting_add(struct vapi_ctx_s *ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_punting_add_reply *reply){
-if(!reply->retval){
- printf("Successfully done");
- return VAPI_OK;
- }else
- return VAPI_EUSER;
-}
-
-static vapi_error_e call_hicn_api_face_ip_add(struct vapi_ctx_s *ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_face_ip_add_reply *reply){
-if(!reply->retval){
- printf("Successfully done");
- return VAPI_OK;
- }else
- return VAPI_EUSER;
-
-}
-
-static vapi_error_e call_hicn_api_route_nhops_add(struct vapi_ctx_s *ctx,
- void *callback_ctx,
- vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_route_nhops_add_reply *reply){
-if(!reply->retval){
- printf("Successfully done");
- return VAPI_OK;
- }else
- return VAPI_EUSER;
-}
-
-static vapi_error_e
-hicn_api_routes_dump_cb(struct vapi_ctx_s *ctx, void *callback_ctx,
- vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_routes_details *reply)
-{
-
- char buf[20];
- if (reply!=NULL){
- memset(buf, 0x00, 20);
- if (reply->prefix.address.af==ADDRESS_IP4){
- struct sockaddr_in sa;
- memcpy(&sa.sin_addr.s_addr, reply->prefix.address.un.ip4, 4);
- inet_ntop(AF_INET, &(sa.sin_addr.s_addr), buf, INET_ADDRSTRLEN);
- printf("Prefix:%s\n",buf);
- }else{
- struct sockaddr_in6 sa;
- memcpy(&sa.sin6_addr,reply->prefix.address.un.ip6,6);
- inet_ntop(AF_INET6, &(sa.sin6_addr), buf, INET6_ADDRSTRLEN);
- printf("Prefix:%s\n",buf);
- }
- }else
- {
- printf("---------Routes------- \n");
- }
- return 0;
-
-}
-
-
-
-static vapi_error_e
-hicn_api_face_stats_dump_cb(struct vapi_ctx_s *ctx, void *callback_ctx,
- vapi_error_e rv, bool is_last,
- vapi_payload_hicn_api_face_stats_details *reply)
-{
- if (reply!=NULL){
-
- printf("face_id:%d \n", reply->faceid);
- printf("irx_packets:%" PRId64 "\n", reply->irx_packets);
- printf("irx_bytes:%" PRId64 "\n", reply->irx_bytes);
- printf("itx_packets:%" PRId64 "\n", reply->itx_packets);
- printf("itx_bytes:%" PRId64 "\n", reply->itx_bytes);
- printf("drx_packets:%" PRId64 "\n", reply->drx_packets);
- printf("drx_bytes:%" PRId64 "\n", reply->drx_bytes);
- printf("dtx_packets:%" PRId64 "\n", reply->dtx_packets);
- printf("dtx_bytes:%" PRId64 "\n", reply->dtx_bytes);
-
- }else
- {
- printf("---------Facees------- \n");
- }
- return 0;
-}
-
-
-int hicn_connect_vpp()
-{
-
- if (g_vapi_ctx_instance == NULL)
- {
- vapi_error_e rv = vapi_ctx_alloc(&g_vapi_ctx_instance);
- rv = vapi_connect(g_vapi_ctx_instance, APP_NAME, NULL, MAX_OUTSTANDING_REQUESTS, RESPONSE_QUEUE_SIZE, VAPI_MODE_BLOCKING, true);
- if (rv != VAPI_OK)
- {
- vapi_ctx_free(g_vapi_ctx_instance);
- return -1;
- }
- }
- else
- {
- }
- return 0;
-}
-
-int hicn_disconnect_vpp()
-{
- if (NULL != g_vapi_ctx_instance)
- {
- vapi_disconnect(g_vapi_ctx_instance);
- vapi_ctx_free(g_vapi_ctx_instance);
- g_vapi_ctx_instance = NULL;
- }
- return 0;
-}
-
-int main(int argc, char **argv)
-{
-
- if (argc<2){
- usage();
- return 1;
- }
-
- /* connect to vpp */
- int rc = hicn_connect_vpp();
- if (-1 == rc){
- perror("vpp connect error");
- return -1;
- }
-
- if (!strcmp(argv[1],"route_add")){
- vapi_msg_hicn_api_route_nhops_add *msg;
- msg = vapi_alloc_hicn_api_route_nhops_add(g_vapi_ctx_instance);
-
- if (!strcmp(argv[2],"4")){
- struct sockaddr_in sa;
- inet_pton(AF_INET, "192.168.10.10", &(sa.sin_addr));
- unsigned char * tmp = (unsigned char *) &sa.sin_addr.s_addr;
- memcpy(&msg->payload.prefix.address.un.ip4[0],tmp,4);
- msg->payload.prefix.address.af = ADDRESS_IP4;
- }else{
- void *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, "2001::1", dst);
- unsigned char * tmp = (unsigned char *) ((struct in6_addr *)dst)->s6_addr;
- memcpy(&msg->payload.prefix.address.un.ip6[0],tmp,16);
- msg->payload.prefix.address.af = ADDRESS_IP6;
- }
-
- msg->payload.prefix.len = 24;
- msg->payload.face_ids[0] = 0;
- msg->payload.face_ids[1] = 0;
- msg->payload.face_ids[2] = 0;
- msg->payload.face_ids[3] = 0;
- msg->payload.face_ids[4] = 0;
- msg->payload.face_ids[5] = 0;
- msg->payload.face_ids[6] = 0;
- msg->payload.n_faces = 1;
-
- if(vapi_hicn_api_route_nhops_add(g_vapi_ctx_instance,msg,call_hicn_api_route_nhops_add,NULL)!=VAPI_OK){
- perror("Operation failed");
- return -1;
- }
- }else if (!strcmp(argv[1],"face_add")){
-
- vapi_msg_hicn_api_face_ip_add *fmsg;
- fmsg = vapi_alloc_hicn_api_face_ip_add(g_vapi_ctx_instance);
-
-
- if (!strcmp(argv[2],"4")){
- struct sockaddr_in sa;
- inet_pton(AF_INET, "192.168.50.19", &(sa.sin_addr));
- unsigned char * tmp = (unsigned char *) &sa.sin_addr.s_addr;
- memcpy(&fmsg->payload.face.local_addr.un.ip4[0],tmp,4);
- fmsg->payload.face.local_addr.af = ADDRESS_IP4;
-
-
- inet_pton(AF_INET, "192.168.60.10", &(sa.sin_addr));
- tmp = (unsigned char *)&sa.sin_addr.s_addr;
- memcpy(&fmsg->payload.face.remote_addr.un.ip4[0],tmp,4);
- fmsg->payload.face.remote_addr.af = ADDRESS_IP4;
-
- }else{
-
- void *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, "2001::1", dst);
- unsigned char * tmp = (unsigned char *) ((struct in6_addr *)dst)->s6_addr;
- memcpy(&fmsg->payload.face.local_addr.un.ip6[0],tmp,16);
- fmsg->payload.face.local_addr.af = ADDRESS_IP6;
-
-
- inet_pton(AF_INET6, "3001::1", dst);
- tmp =(unsigned char *) ((struct in6_addr *)dst)->s6_addr;
- memcpy(&fmsg->payload.face.remote_addr.un.ip6[0],tmp,16);
- fmsg->payload.face.remote_addr.af = ADDRESS_IP6;
- }
-
- fmsg->payload.face.swif = 0; // This is the idx number of interface
-
- if(vapi_hicn_api_face_ip_add(g_vapi_ctx_instance,fmsg,call_hicn_api_face_ip_add,NULL)!=VAPI_OK){
- perror("Operation failed");
- return -1;
- }
- }else if (!strcmp(argv[1],"route_dump")){
- // routes dump
- vapi_msg_hicn_api_routes_dump *rmsg;
- rmsg = vapi_alloc_hicn_api_routes_dump(g_vapi_ctx_instance);
- vapi_hicn_api_routes_dump(g_vapi_ctx_instance, rmsg, hicn_api_routes_dump_cb, NULL);
-
- }else if (!strcmp(argv[1],"face_dump")){
- // faces dump
- vapi_msg_hicn_api_face_stats_dump *fmsg;
- fmsg = vapi_alloc_hicn_api_face_stats_dump(g_vapi_ctx_instance);
- vapi_hicn_api_face_stats_dump(g_vapi_ctx_instance, fmsg, hicn_api_face_stats_dump_cb, NULL);
- }else if (!strcmp(argv[1],"punt_add")){
-
- vapi_msg_hicn_api_punting_add *pmsg;
-
- pmsg = vapi_alloc_hicn_api_punting_add(g_vapi_ctx_instance);
-
- pmsg->payload.type=IP_PUNT;
-
- if(!strcmp(argv[2],"4")){
-
- struct sockaddr_in sa;
- // store this IP address in sa:
- inet_pton(AF_INET, "192.168.10.20", &(sa.sin_addr));
- unsigned char * tmp = (unsigned char *) &sa.sin_addr.s_addr;
- memcpy(&pmsg->payload.rule.ip.prefix.address.un.ip4[0],tmp,4);
- pmsg->payload.rule.ip.prefix.address.af = ADDRESS_IP4;
-
-
- }else{
-
- void *dst = malloc(sizeof(struct in6_addr));
- inet_pton(AF_INET6, "3001::1", dst);
- unsigned char * tmp =(unsigned char *) ((struct in6_addr *)dst)->s6_addr;
- memcpy(&pmsg->payload.rule.ip.prefix.address.un.ip6[0],tmp,16);
- pmsg->payload.rule.ip.prefix.address.af = ADDRESS_IP6;
- }
-
- pmsg->payload.rule.ip.prefix.len = 24;
- pmsg->payload.rule.ip.swif = 0;
-
- if (vapi_hicn_api_punting_add(g_vapi_ctx_instance, pmsg, call_hicn_api_punting_add, NULL)!=VAPI_OK){
- perror("Operation failed");
- return -1;
- }
- }else
- {
- usage();
- return 1;
- }
-
- hicn_disconnect_vpp();
-
- return rc;
-}
diff --git a/ctrl/sysrepo-plugins/yang/hicn/hicn.yang b/ctrl/sysrepo-plugins/yang/hicn/hicn.yang
deleted file mode 100644
index 0514a7a2a..000000000
--- a/ctrl/sysrepo-plugins/yang/hicn/hicn.yang
+++ /dev/null
@@ -1,247 +0,0 @@
-module hicn {
- namespace "urn:sysrepo:hicn";
- prefix hcn;
-
- import ietf-inet-types {
- prefix inet;
- }
-
- revision 2020-04-29{
- description "revised revision focus on telemetry.";
- }
-
- /* new data types and grouping definition to forward the remote request toward hicn controler--to-->hicn */
-
- typedef float {
- type decimal64 {
- fraction-digits 2;
- }
- }
-
- grouping states-reply {
-
- leaf pkts_processed {
- description "ICN packets processed.";
- type uint64;
- }
-
- leaf pkts_interest_count {
- description "PIT maximum size, otherwise -1 to assign default value.";
- type uint64;
- }
-
- leaf pkts_data_count {
- description "CS maximum size, otherwise -1 to assign default value.";
- type uint64;
- }
-
- leaf pkts_from_cache_count {
- description "Portion of CS reserved to application, otherwise -1 to assign default value.";
- type uint64;
- }
-
- leaf pkts_no_pit_count {
- description "Default PIT entry lifetime, otherwise -1 to assign default value.";
- type uint64;
- }
-
- leaf pit_expired_count {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value.";
- type uint64;
- }
-
- leaf cs_expired_count {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf cs_lru_count {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf pkts_drop_no_buf {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf interests_aggregated {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf interests_retx {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf interests_hash_collision {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf pit_entries_count {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf cs_entries_count {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf cs_entries_ntw_count {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- }
-
- grouping face-stats-reply {
- list face{
- key faceid;
- leaf faceid {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint32;
- }
-
- leaf intfc {
- description "This is the idx number of the faceid.";
- type uint32;
- }
-
- leaf irx_packets {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf irx_bytes {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf itx_packets {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf itx_bytes {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
-
- leaf drx_packets {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf drx_bytes {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
- leaf dtx_packets {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
-
-
- leaf dtx_bytes {
- description "Upper bound on PIT entry lifetime, otherwise -1 to assign default value .";
- type uint64;
- }
- }
- }
-
- grouping route-reply {
-
- list route{
- key routeid;
- leaf routeid {
- description "the unique key for each item.";
- type uint32;
- }
- leaf prefix {
- description "IP address.";
- type string;
-
- }
- leaf strategy_id {
- description "compile-time plugin features.";
- type uint32;
- }
- }
- }
-
- grouping strategies-reply {
- leaf n_strategies {
- description "Enable / disable ICN forwarder in VPP.";
- type uint8;
- }
- leaf strategy_id {
- description "Enable / disable ICN forwarder in VPP.";
- type uint32;
- }
-
- }
-
- typedef hicn-prefix {
- description "hICN prefix.";
- type inet:ip-prefix;
- }
-
-
- /* Hicn operational data */
-
- container hicn-state {
-
- config false;
- description "operational data container for the hicn.";
- container faces{
- uses face-stats-reply;
- }
- container states{
- uses states-reply;
- }
- container routes{
- uses route-reply;
- }
- }
-
-
- /* RPC Definitions */
-
- rpc strategies-get {
- description "Operation to get hicn strategies.";
- }
-
- rpc face-params-get {
- description "Operation to del hicn route.";
- input {
- leaf faceid {
- description "Face to be retrieved .";
- type uint32;
- }
- }
- }
-
- rpc hicn-enable {
- description "Enable hicn on a gie prefix.";
- input {
- leaf prefix {
- type hicn-prefix;
- }
- }
- }
-
- rpc hicn-disable {
- description "Disable hicn on a gie prefix.";
- input {
- leaf prefix {
- type hicn-prefix;
- }
- }
- }
-
-}
diff --git a/ctrl/sysrepo-plugins/yang/hicn/rpc_call_samples.xml b/ctrl/sysrepo-plugins/yang/hicn/rpc_call_samples.xml
deleted file mode 100644
index db79fd4ef..000000000
--- a/ctrl/sysrepo-plugins/yang/hicn/rpc_call_samples.xml
+++ /dev/null
@@ -1,78 +0,0 @@
-<node-params-get xmlns="urn:sysrepo:hicn"/>
-
-<node-stat-get xmlns="urn:sysrepo:hicn"/>
-
-<strategy-get xmlns="urn:sysrepo:hicn">
- <strategy_id>0</strategy_id>
-</strategy-get>
-
-<strategies-get xmlns="urn:sysrepo:hicn"/>
-
-
-<route-get xmlns="urn:sysrepo:hicn">
- <ip4>192.168.1.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
-</route-get>
-
-<route-del xmlns="urn:sysrepo:hicn">
- <ip4>192.168.1.1</ip4>
- <ip6>-1</ip6>
- <len>30</len>
-</route-del>
-
-<route-nhops-add xmlns="urn:sysrepo:hicn">
- <ip4>192.168.1.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <face_ids0>0</face_ids0>
- <face_ids1>0</face_ids1>
- <face_ids2>0</face_ids2>
- <face_ids3>0</face_ids3>
- <face_ids4>0</face_ids4>
- <face_ids5>0</face_ids5>
- <face_ids6>0</face_ids6>
- <n_faces>1</n_faces>
-</route-nhops-add>
-
-<route-nhops-del xmlns="urn:sysrepo:hicn">
- <ip4>192.168.1.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <faceid>0</faceid>
-</route-nhops-del>
-
-
-<face-ip-params-get xmlns="urn:sysrepo:hicn">
- <faceid>10</faceid>
-</face-ip-params-get>
-
-<face-ip-add xmlns="urn:sysrepo:hicn">
- <lip4>192.168.1.10</lip4>
- <lip6>-1</lip6>
- <rip4>192.168.1.1</rip4>
- <rip6>-1</rip6>
- <swif>0</swif>
-</face-ip-add>
-
-
-<face-ip-del xmlns="urn:sysrepo:hicn">
- <faceid>0</faceid>
-</face-ip-del>
-
-<punting-add xmlns="urn:sysrepo:hicn">
- <ip4>192.168.0.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <swif>0</swif>
-</punting-add>
-
-
-<punting-del xmlns="urn:sysrepo:hicn">
- <ip4>192.168.0.1</ip4>
- <ip6>-1</ip6>
- <len>24</len>
- <swif>0</swif>
-</punting-del>
-
-<face-stats-details xmlns="urn:sysrepo:hicn"/>
diff --git a/ctrl/sysrepo-plugins/yang/hicn/sysrepo_startup.xml b/ctrl/sysrepo-plugins/yang/hicn/sysrepo_startup.xml
deleted file mode 100644
index f88e13ea2..000000000
--- a/ctrl/sysrepo-plugins/yang/hicn/sysrepo_startup.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<hicn-conf xmlns="urn:sysrepo:hicn">
-<params>
- <enable_disable>false</enable_disable>
- <pit_max_size>-1</pit_max_size>
- <cs_max_size>-1</cs_max_size>
- <cs_reserved_app>-1</cs_reserved_app>
- <pit_dflt_lifetime_sec>-1</pit_dflt_lifetime_sec>
- <pit_max_lifetime_sec>-1</pit_max_lifetime_sec>
- <pit_min_lifetime_sec>-1</pit_min_lifetime_sec>
-</params>
-</hicn-conf> \ No newline at end of file
diff --git a/ctrl/sysrepo-plugins/yang/ietf/iana-if-type@2014-05-08.yang b/ctrl/sysrepo-plugins/yang/ietf/iana-if-type@2014-05-08.yang
deleted file mode 100644
index 4138ba46e..000000000
--- a/ctrl/sysrepo-plugins/yang/ietf/iana-if-type@2014-05-08.yang
+++ /dev/null
@@ -1,1704 +0,0 @@
-module iana-if-type {
-
- yang-version 1;
-
- namespace
- "urn:ietf:params:xml:ns:yang:iana-if-type";
-
- prefix ianaift;
-
- import ietf-interfaces {
- prefix if;
- }
-
- organization "IANA";
-
- contact
- " Internet Assigned Numbers Authority
-
- Postal: ICANN
- 4676 Admiralty Way, Suite 330
- Marina del Rey, CA 90292
-
- Tel: +1 310 823 9358
- <mailto:iana@iana.org>";
-
- description
- "This YANG module defines YANG identities for IANA-registered
- interface types.
-
- This YANG module is maintained by IANA and reflects the
- 'ifType definitions' registry.
-
- The latest revision of this YANG module can be obtained from
- the IANA web site.
-
- Requests for new values should be made to IANA via
- email (iana@iana.org).
-
- Copyright (c) 2014 IETF Trust and the persons identified as
- authors of the code. All rights reserved.
-
- Redistribution and use in source and binary forms, with or
- without modification, is permitted pursuant to, and subject
- to the license terms contained in, the Simplified BSD License
- set forth in Section 4.c of the IETF Trust's Legal Provisions
- Relating to IETF Documents
- (http://trustee.ietf.org/license-info).
-
- The initial version of this YANG module is part of RFC 7224;
- see the RFC itself for full legal notices.";
-
- reference
- "IANA 'ifType definitions' registry.
- <http://www.iana.org/assignments/smi-numbers>";
-
-
- revision "2014-05-08" {
- description "Initial revision.";
- reference
- "RFC 7224: IANA Interface Type YANG Module";
-
- }
-
-
- identity iana-interface-type {
- base if:interface-type;
- description
- "This identity is used as a base for all interface types
- defined in the 'ifType definitions' registry.";
- }
-
- identity other {
- base iana-interface-type;
- }
-
- identity regular1822 {
- base iana-interface-type;
- }
-
- identity hdh1822 {
- base iana-interface-type;
- }
-
- identity ddnX25 {
- base iana-interface-type;
- }
-
- identity rfc877x25 {
- base iana-interface-type;
- reference
- "RFC 1382 - SNMP MIB Extension for the X.25 Packet Layer";
-
- }
-
- identity ethernetCsmacd {
- base iana-interface-type;
- description
- "For all Ethernet-like interfaces, regardless of speed,
- as per RFC 3635.";
- reference
- "RFC 3635 - Definitions of Managed Objects for the
- Ethernet-like Interface Types";
-
- }
-
- identity iso88023Csmacd {
- base iana-interface-type;
- status deprecated;
- description
- "Deprecated via RFC 3635.
- Use ethernetCsmacd(6) instead.";
- reference
- "RFC 3635 - Definitions of Managed Objects for the
- Ethernet-like Interface Types";
-
- }
-
- identity iso88024TokenBus {
- base iana-interface-type;
- }
-
- identity iso88025TokenRing {
- base iana-interface-type;
- }
-
- identity iso88026Man {
- base iana-interface-type;
- }
-
- identity starLan {
- base iana-interface-type;
- status deprecated;
- description
- "Deprecated via RFC 3635.
- Use ethernetCsmacd(6) instead.";
- reference
- "RFC 3635 - Definitions of Managed Objects for the
- Ethernet-like Interface Types";
-
- }
-
- identity proteon10Mbit {
- base iana-interface-type;
- }
-
- identity proteon80Mbit {
- base iana-interface-type;
- }
-
- identity hyperchannel {
- base iana-interface-type;
- }
-
- identity fddi {
- base iana-interface-type;
- reference
- "RFC 1512 - FDDI Management Information Base";
-
- }
-
- identity lapb {
- base iana-interface-type;
- reference
- "RFC 1381 - SNMP MIB Extension for X.25 LAPB";
-
- }
-
- identity sdlc {
- base iana-interface-type;
- }
-
- identity ds1 {
- base iana-interface-type;
- description "DS1-MIB.";
- reference
- "RFC 4805 - Definitions of Managed Objects for the
- DS1, J1, E1, DS2, and E2 Interface Types";
-
- }
-
- identity e1 {
- base iana-interface-type;
- status obsolete;
- description "Obsolete; see DS1-MIB.";
- reference
- "RFC 4805 - Definitions of Managed Objects for the
- DS1, J1, E1, DS2, and E2 Interface Types";
-
- }
-
- identity basicISDN {
- base iana-interface-type;
- description
- "No longer used. See also RFC 2127.";
- }
-
- identity primaryISDN {
- base iana-interface-type;
- description
- "No longer used. See also RFC 2127.";
- }
-
- identity propPointToPointSerial {
- base iana-interface-type;
- description "Proprietary serial.";
- }
-
- identity ppp {
- base iana-interface-type;
- }
-
- identity softwareLoopback {
- base iana-interface-type;
- }
-
- identity eon {
- base iana-interface-type;
- description "CLNP over IP.";
- }
-
- identity ethernet3Mbit {
- base iana-interface-type;
- }
-
- identity nsip {
- base iana-interface-type;
- description "XNS over IP.";
- }
-
- identity slip {
- base iana-interface-type;
- description "Generic SLIP.";
- }
-
- identity ultra {
- base iana-interface-type;
- description "Ultra Technologies.";
- }
-
- identity ds3 {
- base iana-interface-type;
- description "DS3-MIB.";
- reference
- "RFC 3896 - Definitions of Managed Objects for the
- DS3/E3 Interface Type";
-
- }
-
- identity sip {
- base iana-interface-type;
- description "SMDS, coffee.";
- reference
- "RFC 1694 - Definitions of Managed Objects for SMDS
- Interfaces using SMIv2";
-
- }
-
- identity frameRelay {
- base iana-interface-type;
- description "DTE only.";
- reference
- "RFC 2115 - Management Information Base for Frame Relay
- DTEs Using SMIv2";
-
- }
-
- identity rs232 {
- base iana-interface-type;
- reference
- "RFC 1659 - Definitions of Managed Objects for RS-232-like
- Hardware Devices using SMIv2";
-
- }
-
- identity para {
- base iana-interface-type;
- description "Parallel-port.";
- reference
- "RFC 1660 - Definitions of Managed Objects for
- Parallel-printer-like Hardware Devices using
- SMIv2";
-
- }
-
- identity arcnet {
- base iana-interface-type;
- description "ARCnet.";
- }
-
- identity arcnetPlus {
- base iana-interface-type;
- description "ARCnet Plus.";
- }
-
- identity atm {
- base iana-interface-type;
- description "ATM cells.";
- }
-
- identity miox25 {
- base iana-interface-type;
- reference
- "RFC 1461 - SNMP MIB extension for Multiprotocol
- Interconnect over X.25";
-
- }
-
- identity sonet {
- base iana-interface-type;
- description "SONET or SDH.";
- }
-
- identity x25ple {
- base iana-interface-type;
- reference
- "RFC 2127 - ISDN Management Information Base using SMIv2";
-
- }
-
- identity iso88022llc {
- base iana-interface-type;
- }
-
- identity localTalk {
- base iana-interface-type;
- }
-
- identity smdsDxi {
- base iana-interface-type;
- }
-
- identity frameRelayService {
- base iana-interface-type;
- description "FRNETSERV-MIB.";
- reference
- "RFC 2954 - Definitions of Managed Objects for Frame
- Relay Service";
-
- }
-
- identity v35 {
- base iana-interface-type;
- }
-
- identity hssi {
- base iana-interface-type;
- }
-
- identity hippi {
- base iana-interface-type;
- }
-
- identity modem {
- base iana-interface-type;
- description "Generic modem.";
- }
-
- identity aal5 {
- base iana-interface-type;
- description "AAL5 over ATM.";
- }
-
- identity sonetPath {
- base iana-interface-type;
- }
-
- identity sonetVT {
- base iana-interface-type;
- }
-
- identity smdsIcip {
- base iana-interface-type;
- description
- "SMDS InterCarrier Interface.";
- }
-
- identity propVirtual {
- base iana-interface-type;
- description
- "Proprietary virtual/internal.";
- reference
- "RFC 2863 - The Interfaces Group MIB";
-
- }
-
- identity propMultiplexor {
- base iana-interface-type;
- description
- "Proprietary multiplexing.";
- reference
- "RFC 2863 - The Interfaces Group MIB";
-
- }
-
- identity ieee80212 {
- base iana-interface-type;
- description "100BaseVG.";
- }
-
- identity fibreChannel {
- base iana-interface-type;
- description "Fibre Channel.";
- }
-
- identity hippiInterface {
- base iana-interface-type;
- description "HIPPI interfaces.";
- }
-
- identity frameRelayInterconnect {
- base iana-interface-type;
- status obsolete;
- description
- "Obsolete; use either
- frameRelay(32) or frameRelayService(44).";
- }
-
- identity aflane8023 {
- base iana-interface-type;
- description
- "ATM Emulated LAN for 802.3.";
- }
-
- identity aflane8025 {
- base iana-interface-type;
- description
- "ATM Emulated LAN for 802.5.";
- }
-
- identity cctEmul {
- base iana-interface-type;
- description "ATM Emulated circuit.";
- }
-
- identity fastEther {
- base iana-interface-type;
- status deprecated;
- description
- "Obsoleted via RFC 3635.
- ethernetCsmacd(6) should be used instead.";
- reference
- "RFC 3635 - Definitions of Managed Objects for the
- Ethernet-like Interface Types";
-
- }
-
- identity isdn {
- base iana-interface-type;
- description "ISDN and X.25.";
- reference
- "RFC 1356 - Multiprotocol Interconnect on X.25 and ISDN
- in the Packet Mode";
-
- }
-
- identity v11 {
- base iana-interface-type;
- description "CCITT V.11/X.21.";
- }
-
- identity v36 {
- base iana-interface-type;
- description "CCITT V.36.";
- }
-
- identity g703at64k {
- base iana-interface-type;
- description "CCITT G703 at 64Kbps.";
- }
-
- identity g703at2mb {
- base iana-interface-type;
- status obsolete;
- description "Obsolete; see DS1-MIB.";
- }
-
- identity qllc {
- base iana-interface-type;
- description "SNA QLLC.";
- }
-
- identity fastEtherFX {
- base iana-interface-type;
- status deprecated;
- description
- "Obsoleted via RFC 3635.
- ethernetCsmacd(6) should be used instead.";
- reference
- "RFC 3635 - Definitions of Managed Objects for the
- Ethernet-like Interface Types";
-
- }
-
- identity channel {
- base iana-interface-type;
- description "Channel.";
- }
-
- identity ieee80211 {
- base iana-interface-type;
- description "Radio spread spectrum.";
- }
-
- identity ibm370parChan {
- base iana-interface-type;
- description
- "IBM System 360/370 OEMI Channel.";
- }
-
- identity escon {
- base iana-interface-type;
- description
- "IBM Enterprise Systems Connection.";
- }
-
- identity dlsw {
- base iana-interface-type;
- description "Data Link Switching.";
- }
-
- identity isdns {
- base iana-interface-type;
- description "ISDN S/T interface.";
- }
-
- identity isdnu {
- base iana-interface-type;
- description "ISDN U interface.";
- }
-
- identity lapd {
- base iana-interface-type;
- description "Link Access Protocol D.";
- }
-
- identity ipSwitch {
- base iana-interface-type;
- description "IP Switching Objects.";
- }
-
- identity rsrb {
- base iana-interface-type;
- description
- "Remote Source Route Bridging.";
- }
-
- identity atmLogical {
- base iana-interface-type;
- description "ATM Logical Port.";
- reference
- "RFC 3606 - Definitions of Supplemental Managed Objects
- for ATM Interface";
-
- }
-
- identity ds0 {
- base iana-interface-type;
- description "Digital Signal Level 0.";
- reference
- "RFC 2494 - Definitions of Managed Objects for the DS0
- and DS0 Bundle Interface Type";
-
- }
-
- identity ds0Bundle {
- base iana-interface-type;
- description
- "Group of ds0s on the same ds1.";
- reference
- "RFC 2494 - Definitions of Managed Objects for the DS0
- and DS0 Bundle Interface Type";
-
- }
-
- identity bsc {
- base iana-interface-type;
- description "Bisynchronous Protocol.";
- }
-
- identity async {
- base iana-interface-type;
- description "Asynchronous Protocol.";
- }
-
- identity cnr {
- base iana-interface-type;
- description "Combat Net Radio.";
- }
-
- identity iso88025Dtr {
- base iana-interface-type;
- description "ISO 802.5r DTR.";
- }
-
- identity eplrs {
- base iana-interface-type;
- description "Ext Pos Loc Report Sys.";
- }
-
- identity arap {
- base iana-interface-type;
- description
- "Appletalk Remote Access Protocol.";
- }
-
- identity propCnls {
- base iana-interface-type;
- description
- "Proprietary Connectionless Protocol.";
- }
-
- identity hostPad {
- base iana-interface-type;
- description
- "CCITT-ITU X.29 PAD Protocol.";
- }
-
- identity termPad {
- base iana-interface-type;
- description
- "CCITT-ITU X.3 PAD Facility.";
- }
-
- identity frameRelayMPI {
- base iana-interface-type;
- description
- "Multiproto Interconnect over FR.";
- }
-
- identity x213 {
- base iana-interface-type;
- description "CCITT-ITU X213.";
- }
-
- identity adsl {
- base iana-interface-type;
- description
- "Asymmetric Digital Subscriber Loop.";
- }
-
- identity radsl {
- base iana-interface-type;
- description
- "Rate-Adapt. Digital Subscriber Loop.";
- }
-
- identity sdsl {
- base iana-interface-type;
- description
- "Symmetric Digital Subscriber Loop.";
- }
-
- identity vdsl {
- base iana-interface-type;
- description
- "Very H-Speed Digital Subscrib. Loop.";
- }
-
- identity iso88025CRFPInt {
- base iana-interface-type;
- description "ISO 802.5 CRFP.";
- }
-
- identity myrinet {
- base iana-interface-type;
- description "Myricom Myrinet.";
- }
-
- identity voiceEM {
- base iana-interface-type;
- description
- "Voice recEive and transMit.";
- }
-
- identity voiceFXO {
- base iana-interface-type;
- description
- "Voice Foreign Exchange Office.";
- }
-
- identity voiceFXS {
- base iana-interface-type;
- description
- "Voice Foreign Exchange Station.";
- }
-
- identity voiceEncap {
- base iana-interface-type;
- description "Voice encapsulation.";
- }
-
- identity voiceOverIp {
- base iana-interface-type;
- description
- "Voice over IP encapsulation.";
- }
-
- identity atmDxi {
- base iana-interface-type;
- description "ATM DXI.";
- }
-
- identity atmFuni {
- base iana-interface-type;
- description "ATM FUNI.";
- }
-
- identity atmIma {
- base iana-interface-type;
- description "ATM IMA.";
- }
-
- identity pppMultilinkBundle {
- base iana-interface-type;
- description "PPP Multilink Bundle.";
- }
-
- identity ipOverCdlc {
- base iana-interface-type;
- description "IBM ipOverCdlc.";
- }
-
- identity ipOverClaw {
- base iana-interface-type;
- description
- "IBM Common Link Access to Workstn.";
- }
-
- identity stackToStack {
- base iana-interface-type;
- description "IBM stackToStack.";
- }
-
- identity virtualIpAddress {
- base iana-interface-type;
- description "IBM VIPA.";
- }
-
- identity mpc {
- base iana-interface-type;
- description
- "IBM multi-protocol channel support.";
- }
-
- identity ipOverAtm {
- base iana-interface-type;
- description "IBM ipOverAtm.";
- reference
- "RFC 2320 - Definitions of Managed Objects for Classical IP
- and ARP Over ATM Using SMIv2 (IPOA-MIB)";
-
- }
-
- identity iso88025Fiber {
- base iana-interface-type;
- description
- "ISO 802.5j Fiber Token Ring.";
- }
-
- identity tdlc {
- base iana-interface-type;
- description
- "IBM twinaxial data link control.";
- }
-
- identity gigabitEthernet {
- base iana-interface-type;
- status deprecated;
- description
- "Obsoleted via RFC 3635.
- ethernetCsmacd(6) should be used instead.";
- reference
- "RFC 3635 - Definitions of Managed Objects for the
- Ethernet-like Interface Types";
-
- }
-
- identity hdlc {
- base iana-interface-type;
- description "HDLC.";
- }
-
- identity lapf {
- base iana-interface-type;
- description "LAP F.";
- }
-
- identity v37 {
- base iana-interface-type;
- description "V.37.";
- }
-
- identity x25mlp {
- base iana-interface-type;
- description "Multi-Link Protocol.";
- }
-
- identity x25huntGroup {
- base iana-interface-type;
- description "X25 Hunt Group.";
- }
-
- identity transpHdlc {
- base iana-interface-type;
- description "Transp HDLC.";
- }
-
- identity interleave {
- base iana-interface-type;
- description "Interleave channel.";
- }
-
- identity fast {
- base iana-interface-type;
- description "Fast channel.";
- }
-
- identity ip {
- base iana-interface-type;
- description
- "IP (for APPN HPR in IP networks).";
- }
-
- identity docsCableMaclayer {
- base iana-interface-type;
- description "CATV Mac Layer.";
- }
-
- identity docsCableDownstream {
- base iana-interface-type;
- description
- "CATV Downstream interface.";
- }
-
- identity docsCableUpstream {
- base iana-interface-type;
- description "CATV Upstream interface.";
- }
-
- identity a12MppSwitch {
- base iana-interface-type;
- description
- "Avalon Parallel Processor.";
- }
-
- identity tunnel {
- base iana-interface-type;
- description "Encapsulation interface.";
- }
-
- identity coffee {
- base iana-interface-type;
- description "Coffee pot.";
- reference
- "RFC 2325 - Coffee MIB";
-
- }
-
- identity ces {
- base iana-interface-type;
- description
- "Circuit Emulation Service.";
- }
-
- identity atmSubInterface {
- base iana-interface-type;
- description "ATM Sub Interface.";
- }
-
- identity l2vlan {
- base iana-interface-type;
- description
- "Layer 2 Virtual LAN using 802.1Q.";
- }
-
- identity l3ipvlan {
- base iana-interface-type;
- description
- "Layer 3 Virtual LAN using IP.";
- }
-
- identity l3ipxvlan {
- base iana-interface-type;
- description
- "Layer 3 Virtual LAN using IPX.";
- }
-
- identity digitalPowerline {
- base iana-interface-type;
- description "IP over Power Lines.";
- }
-
- identity mediaMailOverIp {
- base iana-interface-type;
- description "Multimedia Mail over IP.";
- }
-
- identity dtm {
- base iana-interface-type;
- description
- "Dynamic synchronous Transfer Mode.";
- }
-
- identity dcn {
- base iana-interface-type;
- description
- "Data Communications Network.";
- }
-
- identity ipForward {
- base iana-interface-type;
- description "IP Forwarding Interface.";
- }
-
- identity msdsl {
- base iana-interface-type;
- description
- "Multi-rate Symmetric DSL.";
- }
-
- identity ieee1394 {
- base iana-interface-type;
- description
- "IEEE1394 High Performance Serial Bus.";
- }
-
- identity if-gsn {
- base iana-interface-type;
- description "HIPPI-6400.";
- }
-
- identity dvbRccMacLayer {
- base iana-interface-type;
- description "DVB-RCC MAC Layer.";
- }
-
- identity dvbRccDownstream {
- base iana-interface-type;
- description
- "DVB-RCC Downstream Channel.";
- }
-
- identity dvbRccUpstream {
- base iana-interface-type;
- description
- "DVB-RCC Upstream Channel.";
- }
-
- identity atmVirtual {
- base iana-interface-type;
- description "ATM Virtual Interface.";
- }
-
- identity mplsTunnel {
- base iana-interface-type;
- description
- "MPLS Tunnel Virtual Interface.";
- }
-
- identity srp {
- base iana-interface-type;
- description "Spatial Reuse Protocol.";
- }
-
- identity voiceOverAtm {
- base iana-interface-type;
- description "Voice over ATM.";
- }
-
- identity voiceOverFrameRelay {
- base iana-interface-type;
- description "Voice Over Frame Relay.";
- }
-
- identity idsl {
- base iana-interface-type;
- description
- "Digital Subscriber Loop over ISDN.";
- }
-
- identity compositeLink {
- base iana-interface-type;
- description
- "Avici Composite Link Interface.";
- }
-
- identity ss7SigLink {
- base iana-interface-type;
- description "SS7 Signaling Link.";
- }
-
- identity propWirelessP2P {
- base iana-interface-type;
- description
- "Prop. P2P wireless interface.";
- }
-
- identity frForward {
- base iana-interface-type;
- description "Frame Forward Interface.";
- }
-
- identity rfc1483 {
- base iana-interface-type;
- description
- "Multiprotocol over ATM AAL5.";
- reference
- "RFC 1483 - Multiprotocol Encapsulation over ATM
- Adaptation Layer 5";
-
- }
-
- identity usb {
- base iana-interface-type;
- description "USB Interface.";
- }
-
- identity ieee8023adLag {
- base iana-interface-type;
- description
- "IEEE 802.3ad Link Aggregate.";
- }
-
- identity bgppolicyaccounting {
- base iana-interface-type;
- description "BGP Policy Accounting.";
- }
-
- identity frf16MfrBundle {
- base iana-interface-type;
- description
- "FRF.16 Multilink Frame Relay.";
- }
-
- identity h323Gatekeeper {
- base iana-interface-type;
- description "H323 Gatekeeper.";
- }
-
- identity h323Proxy {
- base iana-interface-type;
- description
- "H323 Voice and Video Proxy.";
- }
-
- identity mpls {
- base iana-interface-type;
- description "MPLS.";
- }
-
- identity mfSigLink {
- base iana-interface-type;
- description
- "Multi-frequency signaling link.";
- }
-
- identity hdsl2 {
- base iana-interface-type;
- description
- "High Bit-Rate DSL - 2nd generation.";
- }
-
- identity shdsl {
- base iana-interface-type;
- description "Multirate HDSL2.";
- }
-
- identity ds1FDL {
- base iana-interface-type;
- description
- "Facility Data Link (4Kbps) on a DS1.";
- }
-
- identity pos {
- base iana-interface-type;
- description
- "Packet over SONET/SDH Interface.";
- }
-
- identity dvbAsiIn {
- base iana-interface-type;
- description "DVB-ASI Input.";
- }
-
- identity dvbAsiOut {
- base iana-interface-type;
- description "DVB-ASI Output.";
- }
-
- identity plc {
- base iana-interface-type;
- description
- "Power Line Communications.";
- }
-
- identity nfas {
- base iana-interface-type;
- description
- "Non-Facility Associated Signaling.";
- }
-
- identity tr008 {
- base iana-interface-type;
- description "TR008.";
- }
-
- identity gr303RDT {
- base iana-interface-type;
- description "Remote Digital Terminal.";
- }
-
- identity gr303IDT {
- base iana-interface-type;
- description
- "Integrated Digital Terminal.";
- }
-
- identity isup {
- base iana-interface-type;
- description "ISUP.";
- }
-
- identity propDocsWirelessMaclayer {
- base iana-interface-type;
- description
- "Cisco proprietary Maclayer.";
- }
-
- identity propDocsWirelessDownstream {
- base iana-interface-type;
- description
- "Cisco proprietary Downstream.";
- }
-
- identity propDocsWirelessUpstream {
- base iana-interface-type;
- description
- "Cisco proprietary Upstream.";
- }
-
- identity hiperlan2 {
- base iana-interface-type;
- description
- "HIPERLAN Type 2 Radio Interface.";
- }
-
- identity propBWAp2Mp {
- base iana-interface-type;
- description
- "PropBroadbandWirelessAccesspt2Multipt (use of this value
- for IEEE 802.16 WMAN interfaces as per IEEE Std 802.16f
- is deprecated, and ieee80216WMAN(237) should be used
- instead).";
- }
-
- identity sonetOverheadChannel {
- base iana-interface-type;
- description "SONET Overhead Channel.";
- }
-
- identity digitalWrapperOverheadChannel {
- base iana-interface-type;
- description "Digital Wrapper.";
- }
-
- identity aal2 {
- base iana-interface-type;
- description "ATM adaptation layer 2.";
- }
-
- identity radioMAC {
- base iana-interface-type;
- description
- "MAC layer over radio links.";
- }
-
- identity atmRadio {
- base iana-interface-type;
- description "ATM over radio links.";
- }
-
- identity imt {
- base iana-interface-type;
- description "Inter-Machine Trunks.";
- }
-
- identity mvl {
- base iana-interface-type;
- description
- "Multiple Virtual Lines DSL.";
- }
-
- identity reachDSL {
- base iana-interface-type;
- description "Long Reach DSL.";
- }
-
- identity frDlciEndPt {
- base iana-interface-type;
- description
- "Frame Relay DLCI End Point.";
- }
-
- identity atmVciEndPt {
- base iana-interface-type;
- description "ATM VCI End Point.";
- }
-
- identity opticalChannel {
- base iana-interface-type;
- description "Optical Channel.";
- }
-
- identity opticalTransport {
- base iana-interface-type;
- description "Optical Transport.";
- }
-
- identity propAtm {
- base iana-interface-type;
- description "Proprietary ATM.";
- }
-
- identity voiceOverCable {
- base iana-interface-type;
- description
- "Voice Over Cable Interface.";
- }
-
- identity infiniband {
- base iana-interface-type;
- description "Infiniband.";
- }
-
- identity teLink {
- base iana-interface-type;
- description "TE Link.";
- }
-
- identity q2931 {
- base iana-interface-type;
- description "Q.2931.";
- }
-
- identity virtualTg {
- base iana-interface-type;
- description "Virtual Trunk Group.";
- }
-
- identity sipTg {
- base iana-interface-type;
- description "SIP Trunk Group.";
- }
-
- identity sipSig {
- base iana-interface-type;
- description "SIP Signaling.";
- }
-
- identity docsCableUpstreamChannel {
- base iana-interface-type;
- description "CATV Upstream Channel.";
- }
-
- identity econet {
- base iana-interface-type;
- description "Acorn Econet.";
- }
-
- identity pon155 {
- base iana-interface-type;
- description
- "FSAN 155Mb Symetrical PON interface.";
- }
-
- identity pon622 {
- base iana-interface-type;
- description
- "FSAN 622Mb Symetrical PON interface.";
- }
-
- identity bridge {
- base iana-interface-type;
- description
- "Transparent bridge interface.";
- }
-
- identity linegroup {
- base iana-interface-type;
- description
- "Interface common to multiple lines.";
- }
-
- identity voiceEMFGD {
- base iana-interface-type;
- description
- "Voice E&M Feature Group D.";
- }
-
- identity voiceFGDEANA {
- base iana-interface-type;
- description
- "Voice FGD Exchange Access North American.";
- }
-
- identity voiceDID {
- base iana-interface-type;
- description
- "Voice Direct Inward Dialing.";
- }
-
- identity mpegTransport {
- base iana-interface-type;
- description
- "MPEG transport interface.";
- }
-
- identity sixToFour {
- base iana-interface-type;
- status deprecated;
- description
- "6to4 interface (DEPRECATED).";
- reference
- "RFC 4087 - IP Tunnel MIB";
-
- }
-
- identity gtp {
- base iana-interface-type;
- description
- "GTP (GPRS Tunneling Protocol).";
- }
-
- identity pdnEtherLoop1 {
- base iana-interface-type;
- description "Paradyne EtherLoop 1.";
- }
-
- identity pdnEtherLoop2 {
- base iana-interface-type;
- description "Paradyne EtherLoop 2.";
- }
-
- identity opticalChannelGroup {
- base iana-interface-type;
- description "Optical Channel Group.";
- }
-
- identity homepna {
- base iana-interface-type;
- description "HomePNA ITU-T G.989.";
- }
-
- identity gfp {
- base iana-interface-type;
- description
- "Generic Framing Procedure (GFP).";
- }
-
- identity ciscoISLvlan {
- base iana-interface-type;
- description
- "Layer 2 Virtual LAN using Cisco ISL.";
- }
-
- identity actelisMetaLOOP {
- base iana-interface-type;
- description
- "Acteleis proprietary MetaLOOP High Speed Link.";
- }
-
- identity fcipLink {
- base iana-interface-type;
- description "FCIP Link.";
- }
-
- identity rpr {
- base iana-interface-type;
- description
- "Resilient Packet Ring Interface Type.";
- }
-
- identity qam {
- base iana-interface-type;
- description "RF Qam Interface.";
- }
-
- identity lmp {
- base iana-interface-type;
- description
- "Link Management Protocol.";
- reference
- "RFC 4327 - Link Management Protocol (LMP) Management
- Information Base (MIB)";
-
- }
-
- identity cblVectaStar {
- base iana-interface-type;
- description
- "Cambridge Broadband Networks Limited VectaStar.";
- }
-
- identity docsCableMCmtsDownstream {
- base iana-interface-type;
- description
- "CATV Modular CMTS Downstream Interface.";
- }
-
- identity adsl2 {
- base iana-interface-type;
- status deprecated;
- description
- "Asymmetric Digital Subscriber Loop Version 2
- (DEPRECATED/OBSOLETED - please use adsl2plus(238)
- instead).";
- reference
- "RFC 4706 - Definitions of Managed Objects for Asymmetric
- Digital Subscriber Line 2 (ADSL2)";
-
- }
-
- identity macSecControlledIF {
- base iana-interface-type;
- description "MACSecControlled.";
- }
-
- identity macSecUncontrolledIF {
- base iana-interface-type;
- description "MACSecUncontrolled.";
- }
-
- identity aviciOpticalEther {
- base iana-interface-type;
- description
- "Avici Optical Ethernet Aggregate.";
- }
-
- identity atmbond {
- base iana-interface-type;
- description "atmbond.";
- }
-
- identity voiceFGDOS {
- base iana-interface-type;
- description
- "Voice FGD Operator Services.";
- }
-
- identity mocaVersion1 {
- base iana-interface-type;
- description
- "MultiMedia over Coax Alliance (MoCA) Interface
- as documented in information provided privately to IANA.";
- }
-
- identity ieee80216WMAN {
- base iana-interface-type;
- description
- "IEEE 802.16 WMAN interface.";
- }
-
- identity adsl2plus {
- base iana-interface-type;
- description
- "Asymmetric Digital Subscriber Loop Version 2 -
- Version 2 Plus and all variants.";
- }
-
- identity dvbRcsMacLayer {
- base iana-interface-type;
- description "DVB-RCS MAC Layer.";
- reference
- "RFC 5728 - The SatLabs Group DVB-RCS MIB";
-
- }
-
- identity dvbTdm {
- base iana-interface-type;
- description "DVB Satellite TDM.";
- reference
- "RFC 5728 - The SatLabs Group DVB-RCS MIB";
-
- }
-
- identity dvbRcsTdma {
- base iana-interface-type;
- description "DVB-RCS TDMA.";
- reference
- "RFC 5728 - The SatLabs Group DVB-RCS MIB";
-
- }
-
- identity x86Laps {
- base iana-interface-type;
- description
- "LAPS based on ITU-T X.86/Y.1323.";
- }
-
- identity wwanPP {
- base iana-interface-type;
- description "3GPP WWAN.";
- }
-
- identity wwanPP2 {
- base iana-interface-type;
- description "3GPP2 WWAN.";
- }
-
- identity voiceEBS {
- base iana-interface-type;
- description
- "Voice P-phone EBS physical interface.";
- }
-
- identity ifPwType {
- base iana-interface-type;
- description
- "Pseudowire interface type.";
- reference
- "RFC 5601 - Pseudowire (PW) Management Information Base (MIB)";
-
- }
-
- identity ilan {
- base iana-interface-type;
- description
- "Internal LAN on a bridge per IEEE 802.1ap.";
- }
-
- identity pip {
- base iana-interface-type;
- description
- "Provider Instance Port on a bridge per IEEE 802.1ah PBB.";
- }
-
- identity aluELP {
- base iana-interface-type;
- description
- "Alcatel-Lucent Ethernet Link Protection.";
- }
-
- identity gpon {
- base iana-interface-type;
- description
- "Gigabit-capable passive optical networks (G-PON) as per
- ITU-T G.948.";
- }
-
- identity vdsl2 {
- base iana-interface-type;
- description
- "Very high speed digital subscriber line Version 2
- (as per ITU-T Recommendation G.993.2).";
- reference
- "RFC 5650 - Definitions of Managed Objects for Very High
- Speed Digital Subscriber Line 2 (VDSL2)";
-
- }
-
- identity capwapDot11Profile {
- base iana-interface-type;
- description "WLAN Profile Interface.";
- reference
- "RFC 5834 - Control and Provisioning of Wireless Access
- Points (CAPWAP) Protocol Binding MIB for
- IEEE 802.11";
-
- }
-
- identity capwapDot11Bss {
- base iana-interface-type;
- description "WLAN BSS Interface.";
- reference
- "RFC 5834 - Control and Provisioning of Wireless Access
- Points (CAPWAP) Protocol Binding MIB for
- IEEE 802.11";
-
- }
-
- identity capwapWtpVirtualRadio {
- base iana-interface-type;
- description
- "WTP Virtual Radio Interface.";
- reference
- "RFC 5833 - Control and Provisioning of Wireless Access
- Points (CAPWAP) Protocol Base MIB";
-
- }
-
- identity bits {
- base iana-interface-type;
- description "bitsport.";
- }
-
- identity docsCableUpstreamRfPort {
- base iana-interface-type;
- description
- "DOCSIS CATV Upstream RF Port.";
- }
-
- identity cableDownstreamRfPort {
- base iana-interface-type;
- description "CATV downstream RF Port.";
- }
-
- identity vmwareVirtualNic {
- base iana-interface-type;
- description
- "VMware Virtual Network Interface.";
- }
-
- identity ieee802154 {
- base iana-interface-type;
- description
- "IEEE 802.15.4 WPAN interface.";
- reference
- "IEEE 802.15.4-2006";
-
- }
-
- identity otnOdu {
- base iana-interface-type;
- description "OTN Optical Data Unit.";
- }
-
- identity otnOtu {
- base iana-interface-type;
- description
- "OTN Optical channel Transport Unit.";
- }
-
- identity ifVfiType {
- base iana-interface-type;
- description
- "VPLS Forwarding Instance Interface Type.";
- }
-
- identity g9981 {
- base iana-interface-type;
- description
- "G.998.1 bonded interface.";
- }
-
- identity g9982 {
- base iana-interface-type;
- description
- "G.998.2 bonded interface.";
- }
-
- identity g9983 {
- base iana-interface-type;
- description
- "G.998.3 bonded interface.";
- }
-
- identity aluEpon {
- base iana-interface-type;
- description
- "Ethernet Passive Optical Networks (E-PON).";
- }
-
- identity aluEponOnu {
- base iana-interface-type;
- description
- "EPON Optical Network Unit.";
- }
-
- identity aluEponPhysicalUni {
- base iana-interface-type;
- description
- "EPON physical User to Network interface.";
- }
-
- identity aluEponLogicalLink {
- base iana-interface-type;
- description
- "The emulation of a point-to-point link over the EPON
- layer.";
- }
-
- identity aluGponOnu {
- base iana-interface-type;
- description
- "GPON Optical Network Unit.";
- reference
- "ITU-T G.984.2";
-
- }
-
- identity aluGponPhysicalUni {
- base iana-interface-type;
- description
- "GPON physical User to Network interface.";
- reference
- "ITU-T G.984.2";
-
- }
-
- identity vmwareNicTeam {
- base iana-interface-type;
- description "VMware NIC Team.";
- }
- } // module iana-if-type
diff --git a/ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang b/ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang
deleted file mode 100644
index f66c205ce..000000000
--- a/ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang
+++ /dev/null
@@ -1,1123 +0,0 @@
-module ietf-interfaces {
- yang-version 1.1;
- namespace "urn:ietf:params:xml:ns:yang:ietf-interfaces";
- prefix if;
-
- import ietf-yang-types {
- prefix yang;
- }
-
- organization
- "IETF NETMOD (Network Modeling) Working Group";
-
- contact
- "WG Web: <https://datatracker.ietf.org/wg/netmod/>
- WG List: <mailto:netmod@ietf.org>
-
- Editor: Martin Bjorklund
- <mailto:mbj@tail-f.com>";
-
- description
- "This module contains a collection of YANG definitions for
- managing network interfaces.
-
- Copyright (c) 2018 IETF Trust and the persons identified as
- authors of the code. All rights reserved.
-
- Redistribution and use in source and binary forms, with or
- without modification, is permitted pursuant to, and subject
- to the license terms contained in, the Simplified BSD License
- set forth in Section 4.c of the IETF Trust's Legal Provisions
- Relating to IETF Documents
- (https://trustee.ietf.org/license-info).
-
- This version of this YANG module is part of RFC 8343; see
- the RFC itself for full legal notices.";
-
- revision 2018-02-20 {
- description
- "Updated to support NMDA.";
- reference
- "RFC 8343: A YANG Data Model for Interface Management";
- }
-
- revision 2014-05-08 {
- description
- "Initial revision.";
- reference
- "RFC 7223: A YANG Data Model for Interface Management";
- }
-
- /*
- * Typedefs
- */
-
- typedef interface-ref {
- type leafref {
- path "/if:interfaces/if:interface/if:name";
- }
- description
- "This type is used by data models that need to reference
- interfaces.";
- }
-
- /*
- * Identities
- */
-
- identity interface-type {
- description
- "Base identity from which specific interface types are
- derived.";
- }
-
- /*
- * Features
- */
-
- feature arbitrary-names {
- description
- "This feature indicates that the device allows user-controlled
- interfaces to be named arbitrarily.";
- }
- feature pre-provisioning {
- description
- "This feature indicates that the device supports
- pre-provisioning of interface configuration, i.e., it is
- possible to configure an interface whose physical interface
- hardware is not present on the device.";
- }
- feature if-mib {
- description
- "This feature indicates that the device implements
- the IF-MIB.";
- reference
- "RFC 2863: The Interfaces Group MIB";
- }
-
- /*
- * Data nodes
- */
-
- container interfaces {
- description
- "Interface parameters.";
-
- list interface {
- key "name";
-
- description
- "The list of interfaces on the device.
-
- The status of an interface is available in this list in the
- operational state. If the configuration of a
- system-controlled interface cannot be used by the system
- (e.g., the interface hardware present does not match the
- interface type), then the configuration is not applied to
- the system-controlled interface shown in the operational
- state. If the configuration of a user-controlled interface
- cannot be used by the system, the configured interface is
- not instantiated in the operational state.
-
- System-controlled interfaces created by the system are
- always present in this list in the operational state,
- whether or not they are configured.";
-
- leaf name {
- type string;
- description
- "The name of the interface.
-
- A device MAY restrict the allowed values for this leaf,
- possibly depending on the type of the interface.
- For system-controlled interfaces, this leaf is the
- device-specific name of the interface.
-
- If a client tries to create configuration for a
- system-controlled interface that is not present in the
- operational state, the server MAY reject the request if
- the implementation does not support pre-provisioning of
- interfaces or if the name refers to an interface that can
- never exist in the system. A Network Configuration
- Protocol (NETCONF) server MUST reply with an rpc-error
- with the error-tag 'invalid-value' in this case.
-
- If the device supports pre-provisioning of interface
- configuration, the 'pre-provisioning' feature is
- advertised.
-
- If the device allows arbitrarily named user-controlled
- interfaces, the 'arbitrary-names' feature is advertised.
-
- When a configured user-controlled interface is created by
- the system, it is instantiated with the same name in the
- operational state.
-
- A server implementation MAY map this leaf to the ifName
- MIB object. Such an implementation needs to use some
- mechanism to handle the differences in size and characters
- allowed between this leaf and ifName. The definition of
- such a mechanism is outside the scope of this document.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifName";
- }
-
- leaf description {
- type string;
- description
- "A textual description of the interface.
-
- A server implementation MAY map this leaf to the ifAlias
- MIB object. Such an implementation needs to use some
- mechanism to handle the differences in size and characters
- allowed between this leaf and ifAlias. The definition of
- such a mechanism is outside the scope of this document.
-
- Since ifAlias is defined to be stored in non-volatile
- storage, the MIB implementation MUST map ifAlias to the
- value of 'description' in the persistently stored
- configuration.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifAlias";
- }
-
- leaf type {
- type identityref {
- base interface-type;
- }
- mandatory true;
- description
- "The type of the interface.
-
- When an interface entry is created, a server MAY
- initialize the type leaf with a valid value, e.g., if it
- is possible to derive the type from the name of the
- interface.
-
- If a client tries to set the type of an interface to a
- value that can never be used by the system, e.g., if the
- type is not supported or if the type does not match the
- name of the interface, the server MUST reject the request.
- A NETCONF server MUST reply with an rpc-error with the
- error-tag 'invalid-value' in this case.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifType";
- }
-
- leaf enabled {
- type boolean;
- default "true";
- description
- "This leaf contains the configured, desired state of the
- interface.
-
- Systems that implement the IF-MIB use the value of this
- leaf in the intended configuration to set
- IF-MIB.ifAdminStatus to 'up' or 'down' after an ifEntry
- has been initialized, as described in RFC 2863.
-
- Changes in this leaf in the intended configuration are
- reflected in ifAdminStatus.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
- }
-
- leaf link-up-down-trap-enable {
- if-feature if-mib;
- type enumeration {
- enum enabled {
- value 1;
- description
- "The device will generate linkUp/linkDown SNMP
- notifications for this interface.";
- }
- enum disabled {
- value 2;
- description
- "The device will not generate linkUp/linkDown SNMP
- notifications for this interface.";
- }
- }
- description
- "Controls whether linkUp/linkDown SNMP notifications
- should be generated for this interface.
-
- If this node is not configured, the value 'enabled' is
- operationally used by the server for interfaces that do
- not operate on top of any other interface (i.e., there are
- no 'lower-layer-if' entries), and 'disabled' otherwise.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifLinkUpDownTrapEnable";
- }
-
- leaf admin-status {
- if-feature if-mib;
- type enumeration {
- enum up {
- value 1;
- description
- "Ready to pass packets.";
- }
- enum down {
- value 2;
- description
- "Not ready to pass packets and not in some test mode.";
- }
- enum testing {
- value 3;
- description
- "In some test mode.";
- }
- }
- config false;
- mandatory true;
- description
- "The desired state of the interface.
-
- This leaf has the same read semantics as ifAdminStatus.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
- }
-
- leaf oper-status {
- type enumeration {
- enum up {
- value 1;
- description
- "Ready to pass packets.";
- }
- enum down {
- value 2;
-
- description
- "The interface does not pass any packets.";
- }
- enum testing {
- value 3;
- description
- "In some test mode. No operational packets can
- be passed.";
- }
- enum unknown {
- value 4;
- description
- "Status cannot be determined for some reason.";
- }
- enum dormant {
- value 5;
- description
- "Waiting for some external event.";
- }
- enum not-present {
- value 6;
- description
- "Some component (typically hardware) is missing.";
- }
- enum lower-layer-down {
- value 7;
- description
- "Down due to state of lower-layer interface(s).";
- }
- }
- config false;
- mandatory true;
- description
- "The current operational state of the interface.
-
- This leaf has the same semantics as ifOperStatus.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifOperStatus";
- }
-
- leaf last-change {
- type yang:date-and-time;
- config false;
- description
- "The time the interface entered its current operational
- state. If the current state was entered prior to the
- last re-initialization of the local network management
- subsystem, then this node is not present.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifLastChange";
- }
-
- leaf if-index {
- if-feature if-mib;
- type int32 {
- range "1..2147483647";
- }
- config false;
- mandatory true;
- description
- "The ifIndex value for the ifEntry represented by this
- interface.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifIndex";
- }
-
- leaf phys-address {
- type yang:phys-address;
- config false;
- description
- "The interface's address at its protocol sub-layer. For
- example, for an 802.x interface, this object normally
- contains a Media Access Control (MAC) address. The
- interface's media-specific modules must define the bit
- and byte ordering and the format of the value of this
- object. For interfaces that do not have such an address
- (e.g., a serial line), this node is not present.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifPhysAddress";
- }
-
- leaf-list higher-layer-if {
- type interface-ref;
- config false;
- description
- "A list of references to interfaces layered on top of this
- interface.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifStackTable";
- }
-
- leaf-list lower-layer-if {
- type interface-ref;
- config false;
-
- description
- "A list of references to interfaces layered underneath this
- interface.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifStackTable";
- }
-
- leaf speed {
- type yang:gauge64;
- units "bits/second";
- config false;
- description
- "An estimate of the interface's current bandwidth in bits
- per second. For interfaces that do not vary in
- bandwidth or for those where no accurate estimation can
- be made, this node should contain the nominal bandwidth.
- For interfaces that have no concept of bandwidth, this
- node is not present.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifSpeed, ifHighSpeed";
- }
-
- container statistics {
- config false;
- description
- "A collection of interface-related statistics objects.";
-
- leaf discontinuity-time {
- type yang:date-and-time;
- mandatory true;
- description
- "The time on the most recent occasion at which any one or
- more of this interface's counters suffered a
- discontinuity. If no such discontinuities have occurred
- since the last re-initialization of the local management
- subsystem, then this node contains the time the local
- management subsystem re-initialized itself.";
- }
-
- leaf in-octets {
- type yang:counter64;
- description
- "The total number of octets received on the interface,
- including framing characters.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCInOctets";
- }
-
- leaf in-unicast-pkts {
- type yang:counter64;
- description
- "The number of packets, delivered by this sub-layer to a
- higher (sub-)layer, that were not addressed to a
- multicast or broadcast address at this sub-layer.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCInUcastPkts";
- }
-
- leaf in-broadcast-pkts {
- type yang:counter64;
- description
- "The number of packets, delivered by this sub-layer to a
- higher (sub-)layer, that were addressed to a broadcast
- address at this sub-layer.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCInBroadcastPkts";
- }
-
- leaf in-multicast-pkts {
- type yang:counter64;
- description
- "The number of packets, delivered by this sub-layer to a
- higher (sub-)layer, that were addressed to a multicast
- address at this sub-layer. For a MAC-layer protocol,
- this includes both Group and Functional addresses.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCInMulticastPkts";
- }
-
- leaf in-discards {
- type yang:counter32;
- description
- "The number of inbound packets that were chosen to be
- discarded even though no errors had been detected to
- prevent their being deliverable to a higher-layer
- protocol. One possible reason for discarding such a
- packet could be to free up buffer space.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifInDiscards";
- }
-
- leaf in-errors {
- type yang:counter32;
- description
- "For packet-oriented interfaces, the number of inbound
- packets that contained errors preventing them from being
- deliverable to a higher-layer protocol. For character-
- oriented or fixed-length interfaces, the number of
- inbound transmission units that contained errors
- preventing them from being deliverable to a higher-layer
- protocol.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifInErrors";
- }
-
- leaf in-unknown-protos {
- type yang:counter32;
-
- description
- "For packet-oriented interfaces, the number of packets
- received via the interface that were discarded because
- of an unknown or unsupported protocol. For
- character-oriented or fixed-length interfaces that
- support protocol multiplexing, the number of
- transmission units received via the interface that were
- discarded because of an unknown or unsupported protocol.
- For any interface that does not support protocol
- multiplexing, this counter is not present.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifInUnknownProtos";
- }
-
- leaf out-octets {
- type yang:counter64;
- description
- "The total number of octets transmitted out of the
- interface, including framing characters.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCOutOctets";
- }
-
- leaf out-unicast-pkts {
- type yang:counter64;
- description
- "The total number of packets that higher-level protocols
- requested be transmitted and that were not addressed
- to a multicast or broadcast address at this sub-layer,
- including those that were discarded or not sent.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCOutUcastPkts";
- }
-
- leaf out-broadcast-pkts {
- type yang:counter64;
- description
- "The total number of packets that higher-level protocols
- requested be transmitted and that were addressed to a
- broadcast address at this sub-layer, including those
- that were discarded or not sent.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCOutBroadcastPkts";
- }
-
- leaf out-multicast-pkts {
- type yang:counter64;
- description
- "The total number of packets that higher-level protocols
- requested be transmitted and that were addressed to a
- multicast address at this sub-layer, including those
- that were discarded or not sent. For a MAC-layer
- protocol, this includes both Group and Functional
- addresses.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCOutMulticastPkts";
- }
-
- leaf out-discards {
- type yang:counter32;
- description
- "The number of outbound packets that were chosen to be
- discarded even though no errors had been detected to
- prevent their being transmitted. One possible reason
- for discarding such a packet could be to free up buffer
- space.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifOutDiscards";
- }
-
- leaf out-errors {
- type yang:counter32;
- description
- "For packet-oriented interfaces, the number of outbound
- packets that could not be transmitted because of errors.
- For character-oriented or fixed-length interfaces, the
- number of outbound transmission units that could not be
- transmitted because of errors.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifOutErrors";
- }
- }
-
- }
- }
-
- /*
- * Legacy typedefs
- */
-
- typedef interface-state-ref {
- type leafref {
- path "/if:interfaces-state/if:interface/if:name";
- }
- status deprecated;
- description
- "This type is used by data models that need to reference
- the operationally present interfaces.";
- }
-
- /*
- * Legacy operational state data nodes
- */
-
- container interfaces-state {
- config false;
- status deprecated;
- description
- "Data nodes for the operational state of interfaces.";
-
- list interface {
- key "name";
- status deprecated;
-
- description
- "The list of interfaces on the device.
-
- System-controlled interfaces created by the system are
- always present in this list, whether or not they are
- configured.";
-
- leaf name {
- type string;
- status deprecated;
- description
- "The name of the interface.
-
- A server implementation MAY map this leaf to the ifName
- MIB object. Such an implementation needs to use some
- mechanism to handle the differences in size and characters
- allowed between this leaf and ifName. The definition of
- such a mechanism is outside the scope of this document.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifName";
- }
-
- leaf type {
- type identityref {
- base interface-type;
- }
- mandatory true;
- status deprecated;
- description
- "The type of the interface.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifType";
- }
-
- leaf admin-status {
- if-feature if-mib;
- type enumeration {
- enum up {
- value 1;
- description
- "Ready to pass packets.";
- }
- enum down {
- value 2;
- description
- "Not ready to pass packets and not in some test mode.";
- }
- enum testing {
- value 3;
- description
- "In some test mode.";
- }
- }
- mandatory true;
- status deprecated;
- description
- "The desired state of the interface.
-
- This leaf has the same read semantics as ifAdminStatus.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
- }
-
- leaf oper-status {
- type enumeration {
- enum up {
- value 1;
- description
- "Ready to pass packets.";
- }
- enum down {
- value 2;
- description
- "The interface does not pass any packets.";
- }
- enum testing {
- value 3;
- description
- "In some test mode. No operational packets can
- be passed.";
- }
- enum unknown {
- value 4;
- description
- "Status cannot be determined for some reason.";
- }
- enum dormant {
- value 5;
- description
- "Waiting for some external event.";
- }
- enum not-present {
- value 6;
- description
- "Some component (typically hardware) is missing.";
- }
- enum lower-layer-down {
- value 7;
- description
- "Down due to state of lower-layer interface(s).";
- }
- }
- mandatory true;
- status deprecated;
- description
- "The current operational state of the interface.
-
- This leaf has the same semantics as ifOperStatus.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifOperStatus";
- }
-
- leaf last-change {
- type yang:date-and-time;
- status deprecated;
- description
- "The time the interface entered its current operational
- state. If the current state was entered prior to the
- last re-initialization of the local network management
- subsystem, then this node is not present.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifLastChange";
- }
-
- leaf if-index {
- if-feature if-mib;
- type int32 {
- range "1..2147483647";
- }
- mandatory true;
- status deprecated;
- description
- "The ifIndex value for the ifEntry represented by this
- interface.";
-
- reference
- "RFC 2863: The Interfaces Group MIB - ifIndex";
- }
-
- leaf phys-address {
- type yang:phys-address;
- status deprecated;
- description
- "The interface's address at its protocol sub-layer. For
- example, for an 802.x interface, this object normally
- contains a Media Access Control (MAC) address. The
- interface's media-specific modules must define the bit
- and byte ordering and the format of the value of this
- object. For interfaces that do not have such an address
- (e.g., a serial line), this node is not present.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifPhysAddress";
- }
-
- leaf-list higher-layer-if {
- type interface-state-ref;
- status deprecated;
- description
- "A list of references to interfaces layered on top of this
- interface.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifStackTable";
- }
-
- leaf-list lower-layer-if {
- type interface-state-ref;
- status deprecated;
- description
- "A list of references to interfaces layered underneath this
- interface.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifStackTable";
- }
-
- leaf speed {
- type yang:gauge64;
- units "bits/second";
- status deprecated;
- description
- "An estimate of the interface's current bandwidth in bits
- per second. For interfaces that do not vary in
- bandwidth or for those where no accurate estimation can
-
- be made, this node should contain the nominal bandwidth.
- For interfaces that have no concept of bandwidth, this
- node is not present.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifSpeed, ifHighSpeed";
- }
-
- container statistics {
- status deprecated;
- description
- "A collection of interface-related statistics objects.";
-
- leaf discontinuity-time {
- type yang:date-and-time;
- mandatory true;
- status deprecated;
- description
- "The time on the most recent occasion at which any one or
- more of this interface's counters suffered a
- discontinuity. If no such discontinuities have occurred
- since the last re-initialization of the local management
- subsystem, then this node contains the time the local
- management subsystem re-initialized itself.";
- }
-
- leaf in-octets {
- type yang:counter64;
- status deprecated;
- description
- "The total number of octets received on the interface,
- including framing characters.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCInOctets";
- }
-
- leaf in-unicast-pkts {
- type yang:counter64;
- status deprecated;
- description
- "The number of packets, delivered by this sub-layer to a
- higher (sub-)layer, that were not addressed to a
- multicast or broadcast address at this sub-layer.
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCInUcastPkts";
- }
-
- leaf in-broadcast-pkts {
- type yang:counter64;
- status deprecated;
- description
- "The number of packets, delivered by this sub-layer to a
- higher (sub-)layer, that were addressed to a broadcast
- address at this sub-layer.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCInBroadcastPkts";
- }
-
- leaf in-multicast-pkts {
- type yang:counter64;
- status deprecated;
- description
- "The number of packets, delivered by this sub-layer to a
- higher (sub-)layer, that were addressed to a multicast
- address at this sub-layer. For a MAC-layer protocol,
- this includes both Group and Functional addresses.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCInMulticastPkts";
- }
-
- leaf in-discards {
- type yang:counter32;
- status deprecated;
-
- description
- "The number of inbound packets that were chosen to be
- discarded even though no errors had been detected to
- prevent their being deliverable to a higher-layer
- protocol. One possible reason for discarding such a
- packet could be to free up buffer space.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifInDiscards";
- }
-
- leaf in-errors {
- type yang:counter32;
- status deprecated;
- description
- "For packet-oriented interfaces, the number of inbound
- packets that contained errors preventing them from being
- deliverable to a higher-layer protocol. For character-
- oriented or fixed-length interfaces, the number of
- inbound transmission units that contained errors
- preventing them from being deliverable to a higher-layer
- protocol.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifInErrors";
- }
-
- leaf in-unknown-protos {
- type yang:counter32;
- status deprecated;
- description
- "For packet-oriented interfaces, the number of packets
- received via the interface that were discarded because
- of an unknown or unsupported protocol. For
- character-oriented or fixed-length interfaces that
- support protocol multiplexing, the number of
- transmission units received via the interface that were
- discarded because of an unknown or unsupported protocol.
- For any interface that does not support protocol
- multiplexing, this counter is not present.
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifInUnknownProtos";
- }
-
- leaf out-octets {
- type yang:counter64;
- status deprecated;
- description
- "The total number of octets transmitted out of the
- interface, including framing characters.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCOutOctets";
- }
-
- leaf out-unicast-pkts {
- type yang:counter64;
- status deprecated;
- description
- "The total number of packets that higher-level protocols
- requested be transmitted and that were not addressed
- to a multicast or broadcast address at this sub-layer,
- including those that were discarded or not sent.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifHCOutUcastPkts";
- }
-
- leaf out-broadcast-pkts {
- type yang:counter64;
- status deprecated;
-
- description
- "The total number of packets that higher-level protocols
- requested be transmitted and that were addressed to a
- broadcast address at this sub-layer, including those
- that were discarded or not sent.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCOutBroadcastPkts";
- }
-
- leaf out-multicast-pkts {
- type yang:counter64;
- status deprecated;
- description
- "The total number of packets that higher-level protocols
- requested be transmitted and that were addressed to a
- multicast address at this sub-layer, including those
- that were discarded or not sent. For a MAC-layer
- protocol, this includes both Group and Functional
- addresses.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB -
- ifHCOutMulticastPkts";
- }
-
- leaf out-discards {
- type yang:counter32;
- status deprecated;
- description
- "The number of outbound packets that were chosen to be
- discarded even though no errors had been detected to
- prevent their being transmitted. One possible reason
- for discarding such a packet could be to free up buffer
- space.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifOutDiscards";
- }
-
- leaf out-errors {
- type yang:counter32;
- status deprecated;
- description
- "For packet-oriented interfaces, the number of outbound
- packets that could not be transmitted because of errors.
- For character-oriented or fixed-length interfaces, the
- number of outbound transmission units that could not be
- transmitted because of errors.
-
- Discontinuities in the value of this counter can occur
- at re-initialization of the management system and at
- other times as indicated by the value of
- 'discontinuity-time'.";
- reference
- "RFC 2863: The Interfaces Group MIB - ifOutErrors";
- }
- }
- }
- }
-}
diff --git a/ctrl/sysrepo-plugins/yang/ietf/ietf-ip@2014-06-16.yang b/ctrl/sysrepo-plugins/yang/ietf/ietf-ip@2014-06-16.yang
deleted file mode 100644
index 79606cc07..000000000
--- a/ctrl/sysrepo-plugins/yang/ietf/ietf-ip@2014-06-16.yang
+++ /dev/null
@@ -1,742 +0,0 @@
-module ietf-ip {
-
- yang-version 1;
-
- namespace
- "urn:ietf:params:xml:ns:yang:ietf-ip";
-
- prefix ip;
-
- import ietf-interfaces {
- prefix if;
- }
- import ietf-inet-types {
- prefix inet;
- }
- import ietf-yang-types {
- prefix yang;
- }
-
- organization
- "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
-
- contact
- "WG Web: <http://tools.ietf.org/wg/netmod/>
- WG List: <mailto:netmod@ietf.org>
-
- WG Chair: Thomas Nadeau
- <mailto:tnadeau@lucidvision.com>
-
- WG Chair: Juergen Schoenwaelder
- <mailto:j.schoenwaelder@jacobs-university.de>
-
- Editor: Martin Bjorklund
- <mailto:mbj@tail-f.com>";
-
- description
- "This module contains a collection of YANG definitions for
- configuring IP implementations.
-
- Copyright (c) 2014 IETF Trust and the persons identified as
- authors of the code. All rights reserved.
-
- Redistribution and use in source and binary forms, with or
- without modification, is permitted pursuant to, and subject
- to the license terms contained in, the Simplified BSD License
- set forth in Section 4.c of the IETF Trust's Legal Provisions
- Relating to IETF Documents
- (http://trustee.ietf.org/license-info).
-
- This version of this YANG module is part of RFC 7277; see
- the RFC itself for full legal notices.";
-
- revision "2014-06-16" {
- description "Initial revision.";
- reference
- "RFC 7277: A YANG Data Model for IP Management";
-
- }
-
-
- feature ipv4-non-contiguous-netmasks {
- description
- "Indicates support for configuring non-contiguous
- subnet masks.";
- }
-
- feature ipv6-privacy-autoconf {
- description
- "Indicates support for Privacy Extensions for Stateless Address
- Autoconfiguration in IPv6.";
- reference
- "RFC 4941: Privacy Extensions for Stateless Address
- Autoconfiguration in IPv6";
-
- }
-
- typedef ip-address-origin {
- type enumeration {
- enum "other" {
- value 0;
- description
- "None of the following.";
- }
- enum "static" {
- value 1;
- description
- "Indicates that the address has been statically
- configured - for example, using NETCONF or a Command Line
- Interface.";
- }
- enum "dhcp" {
- value 2;
- description
- "Indicates an address that has been assigned to this
- system by a DHCP server.";
- }
- enum "link-layer" {
- value 3;
- description
- "Indicates an address created by IPv6 stateless
- autoconfiguration that embeds a link-layer address in its
- interface identifier.";
- }
- enum "random" {
- value 4;
- description
- "Indicates an address chosen by the system at
-
- random, e.g., an IPv4 address within 169.254/16, an
- RFC 4941 temporary address, or an RFC 7217 semantically
- opaque address.";
- reference
- "RFC 4941: Privacy Extensions for Stateless Address
- Autoconfiguration in IPv6
- RFC 7217: A Method for Generating Semantically Opaque
- Interface Identifiers with IPv6 Stateless
- Address Autoconfiguration (SLAAC)";
-
- }
- }
- description
- "The origin of an address.";
- }
-
- typedef neighbor-origin {
- type enumeration {
- enum "other" {
- value 0;
- description
- "None of the following.";
- }
- enum "static" {
- value 1;
- description
- "Indicates that the mapping has been statically
- configured - for example, using NETCONF or a Command Line
- Interface.";
- }
- enum "dynamic" {
- value 2;
- description
- "Indicates that the mapping has been dynamically resolved
- using, e.g., IPv4 ARP or the IPv6 Neighbor Discovery
- protocol.";
- }
- }
- description
- "The origin of a neighbor entry.";
- }
-
- augment /if:interfaces/if:interface {
- description
- "Parameters for configuring IP on interfaces.
-
- If an interface is not capable of running IP, the server
- must not allow the client to configure these parameters.";
- container ipv4 {
- presence
- "Enables IPv4 unless the 'enabled' leaf
- (which defaults to 'true') is set to 'false'";
- description
- "Parameters for the IPv4 address family.";
- leaf enabled {
- type boolean;
- default 'true';
- description
- "Controls whether IPv4 is enabled or disabled on this
- interface. When IPv4 is enabled, this interface is
- connected to an IPv4 stack, and the interface can send
- and receive IPv4 packets.";
- }
-
- leaf forwarding {
- type boolean;
- default 'false';
- description
- "Controls IPv4 packet forwarding of datagrams received by,
- but not addressed to, this interface. IPv4 routers
- forward datagrams. IPv4 hosts do not (except those
- source-routed via the host).";
- }
-
- leaf mtu {
- type uint16 {
- range "68..max";
- }
- units "octets";
- description
- "The size, in octets, of the largest IPv4 packet that the
- interface will send and receive.
-
- The server may restrict the allowed values for this leaf,
- depending on the interface's type.
-
- If this leaf is not configured, the operationally used MTU
- depends on the interface's type.";
- reference
- "RFC 791: Internet Protocol";
-
- }
-
- list address {
- key "ip";
- description
- "The list of configured IPv4 addresses on the interface.";
- leaf ip {
- type inet:ipv4-address-no-zone;
- description
- "The IPv4 address on the interface.";
- }
-
- choice subnet {
- mandatory true;
- description
- "The subnet can be specified as a prefix-length, or,
- if the server supports non-contiguous netmasks, as
- a netmask.";
- leaf prefix-length {
- type uint8 {
- range "0..32";
- }
- description
- "The length of the subnet prefix.";
- }
- leaf netmask {
- if-feature ipv4-non-contiguous-netmasks;
- type yang:dotted-quad;
- description
- "The subnet specified as a netmask.";
- }
- } // choice subnet
- } // list address
-
- list neighbor {
- key "ip";
- description
- "A list of mappings from IPv4 addresses to
- link-layer addresses.
-
- Entries in this list are used as static entries in the
- ARP Cache.";
- reference
- "RFC 826: An Ethernet Address Resolution Protocol";
-
- leaf ip {
- type inet:ipv4-address-no-zone;
- description
- "The IPv4 address of the neighbor node.";
- }
-
- leaf link-layer-address {
- type yang:phys-address;
- mandatory true;
- description
- "The link-layer address of the neighbor node.";
- }
- } // list neighbor
- } // container ipv4
-
- container ipv6 {
- presence
- "Enables IPv6 unless the 'enabled' leaf
- (which defaults to 'true') is set to 'false'";
- description
- "Parameters for the IPv6 address family.";
- leaf enabled {
- type boolean;
- default 'true';
- description
- "Controls whether IPv6 is enabled or disabled on this
- interface. When IPv6 is enabled, this interface is
- connected to an IPv6 stack, and the interface can send
- and receive IPv6 packets.";
- }
-
- leaf forwarding {
- type boolean;
- default 'false';
- description
- "Controls IPv6 packet forwarding of datagrams received by,
- but not addressed to, this interface. IPv6 routers
- forward datagrams. IPv6 hosts do not (except those
- source-routed via the host).";
- reference
- "RFC 4861: Neighbor Discovery for IP version 6 (IPv6)
- Section 6.2.1, IsRouter";
-
- }
-
- leaf mtu {
- type uint32 {
- range "1280..max";
- }
- units "octets";
- description
- "The size, in octets, of the largest IPv6 packet that the
- interface will send and receive.
-
- The server may restrict the allowed values for this leaf,
- depending on the interface's type.
-
- If this leaf is not configured, the operationally used MTU
- depends on the interface's type.";
- reference
- "RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
- Section 5";
-
- }
-
- list address {
- key "ip";
- description
- "The list of configured IPv6 addresses on the interface.";
- leaf ip {
- type inet:ipv6-address-no-zone;
- description
- "The IPv6 address on the interface.";
- }
-
- leaf prefix-length {
- type uint8 {
- range "0..128";
- }
- mandatory true;
- description
- "The length of the subnet prefix.";
- }
- } // list address
-
- list neighbor {
- key "ip";
- description
- "A list of mappings from IPv6 addresses to
- link-layer addresses.
-
- Entries in this list are used as static entries in the
- Neighbor Cache.";
- reference
- "RFC 4861: Neighbor Discovery for IP version 6 (IPv6)";
-
- leaf ip {
- type inet:ipv6-address-no-zone;
- description
- "The IPv6 address of the neighbor node.";
- }
-
- leaf link-layer-address {
- type yang:phys-address;
- mandatory true;
- description
- "The link-layer address of the neighbor node.";
- }
- } // list neighbor
-
- leaf dup-addr-detect-transmits {
- type uint32;
- default '1';
- description
- "The number of consecutive Neighbor Solicitation messages
- sent while performing Duplicate Address Detection on a
- tentative address. A value of zero indicates that
- Duplicate Address Detection is not performed on
- tentative addresses. A value of one indicates a single
- transmission with no follow-up retransmissions.";
- reference
- "RFC 4862: IPv6 Stateless Address Autoconfiguration";
-
- }
-
- container autoconf {
- description
- "Parameters to control the autoconfiguration of IPv6
- addresses, as described in RFC 4862.";
- reference
- "RFC 4862: IPv6 Stateless Address Autoconfiguration";
-
- leaf create-global-addresses {
- type boolean;
- default 'true';
- description
- "If enabled, the host creates global addresses as
- described in RFC 4862.";
- reference
- "RFC 4862: IPv6 Stateless Address Autoconfiguration
- Section 5.5";
-
- }
-
- leaf create-temporary-addresses {
- if-feature ipv6-privacy-autoconf;
- type boolean;
- default 'false';
- description
- "If enabled, the host creates temporary addresses as
- described in RFC 4941.";
- reference
- "RFC 4941: Privacy Extensions for Stateless Address
- Autoconfiguration in IPv6";
-
- }
-
- leaf temporary-valid-lifetime {
- if-feature ipv6-privacy-autoconf;
- type uint32;
- units "seconds";
- default '604800';
- description
- "The time period during which the temporary address
- is valid.";
- reference
- "RFC 4941: Privacy Extensions for Stateless Address
- Autoconfiguration in IPv6
- - TEMP_VALID_LIFETIME";
-
- }
-
- leaf temporary-preferred-lifetime {
- if-feature ipv6-privacy-autoconf;
- type uint32;
- units "seconds";
- default '86400';
- description
- "The time period during which the temporary address is
- preferred.";
- reference
- "RFC 4941: Privacy Extensions for Stateless Address
- Autoconfiguration in IPv6
- - TEMP_PREFERRED_LIFETIME";
-
- }
- } // container autoconf
- } // container ipv6
- }
-
- augment /if:interfaces-state/if:interface {
- description
- "Data nodes for the operational state of IP on interfaces.";
- container ipv4 {
- presence
- "Present if IPv4 is enabled on this interface";
- config false;
- description
- "Interface-specific parameters for the IPv4 address family.";
- leaf forwarding {
- type boolean;
- description
- "Indicates whether IPv4 packet forwarding is enabled or
- disabled on this interface.";
- }
-
- leaf mtu {
- type uint16 {
- range "68..max";
- }
- units "octets";
- description
- "The size, in octets, of the largest IPv4 packet that the
- interface will send and receive.";
- reference
- "RFC 791: Internet Protocol";
-
- }
-
- list address {
- key "ip";
- description
- "The list of IPv4 addresses on the interface.";
- leaf ip {
- type inet:ipv4-address-no-zone;
- description
- "The IPv4 address on the interface.";
- }
-
- choice subnet {
- description
- "The subnet can be specified as a prefix-length, or,
- if the server supports non-contiguous netmasks, as
- a netmask.";
- leaf prefix-length {
- type uint8 {
- range "0..32";
- }
- description
- "The length of the subnet prefix.";
- }
- leaf netmask {
- if-feature ipv4-non-contiguous-netmasks;
- type yang:dotted-quad;
- description
- "The subnet specified as a netmask.";
- }
- } // choice subnet
-
- leaf origin {
- type ip-address-origin;
- description
- "The origin of this address.";
- }
- } // list address
-
- list neighbor {
- key "ip";
- description
- "A list of mappings from IPv4 addresses to
- link-layer addresses.
-
- This list represents the ARP Cache.";
- reference
- "RFC 826: An Ethernet Address Resolution Protocol";
-
- leaf ip {
- type inet:ipv4-address-no-zone;
- description
- "The IPv4 address of the neighbor node.";
- }
-
- leaf link-layer-address {
- type yang:phys-address;
- description
- "The link-layer address of the neighbor node.";
- }
-
- leaf origin {
- type neighbor-origin;
- description
- "The origin of this neighbor entry.";
- }
- } // list neighbor
- } // container ipv4
-
- container ipv6 {
- presence
- "Present if IPv6 is enabled on this interface";
- config false;
- description
- "Parameters for the IPv6 address family.";
- leaf forwarding {
- type boolean;
- default 'false';
- description
- "Indicates whether IPv6 packet forwarding is enabled or
- disabled on this interface.";
- reference
- "RFC 4861: Neighbor Discovery for IP version 6 (IPv6)
- Section 6.2.1, IsRouter";
-
- }
-
- leaf mtu {
- type uint32 {
- range "1280..max";
- }
- units "octets";
- description
- "The size, in octets, of the largest IPv6 packet that the
- interface will send and receive.";
- reference
- "RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
- Section 5";
-
- }
-
- list address {
- key "ip";
- description
- "The list of IPv6 addresses on the interface.";
- leaf ip {
- type inet:ipv6-address-no-zone;
- description
- "The IPv6 address on the interface.";
- }
-
- leaf prefix-length {
- type uint8 {
- range "0..128";
- }
- mandatory true;
- description
- "The length of the subnet prefix.";
- }
-
- leaf origin {
- type ip-address-origin;
- description
- "The origin of this address.";
- }
-
- leaf status {
- type enumeration {
- enum "preferred" {
- value 0;
- description
- "This is a valid address that can appear as the
- destination or source address of a packet.";
- }
- enum "deprecated" {
- value 1;
- description
- "This is a valid but deprecated address that should
- no longer be used as a source address in new
- communications, but packets addressed to such an
- address are processed as expected.";
- }
- enum "invalid" {
- value 2;
- description
- "This isn't a valid address, and it shouldn't appear
- as the destination or source address of a packet.";
- }
- enum "inaccessible" {
- value 3;
- description
- "The address is not accessible because the interface
- to which this address is assigned is not
- operational.";
- }
- enum "unknown" {
- value 4;
- description
- "The status cannot be determined for some reason.";
- }
- enum "tentative" {
- value 5;
- description
- "The uniqueness of the address on the link is being
- verified. Addresses in this state should not be
- used for general communication and should only be
- used to determine the uniqueness of the address.";
- }
- enum "duplicate" {
- value 6;
- description
- "The address has been determined to be non-unique on
- the link and so must not be used.";
- }
- enum "optimistic" {
- value 7;
- description
- "The address is available for use, subject to
- restrictions, while its uniqueness on a link is
- being verified.";
- }
- }
- description
- "The status of an address. Most of the states correspond
- to states from the IPv6 Stateless Address
- Autoconfiguration protocol.";
- reference
- "RFC 4293: Management Information Base for the
- Internet Protocol (IP)
- - IpAddressStatusTC
- RFC 4862: IPv6 Stateless Address Autoconfiguration";
-
- }
- } // list address
-
- list neighbor {
- key "ip";
- description
- "A list of mappings from IPv6 addresses to
- link-layer addresses.
-
- This list represents the Neighbor Cache.";
- reference
- "RFC 4861: Neighbor Discovery for IP version 6 (IPv6)";
-
- leaf ip {
- type inet:ipv6-address-no-zone;
- description
- "The IPv6 address of the neighbor node.";
- }
-
- leaf link-layer-address {
- type yang:phys-address;
- description
- "The link-layer address of the neighbor node.";
- }
-
- leaf origin {
- type neighbor-origin;
- description
- "The origin of this neighbor entry.";
- }
-
- leaf is-router {
- type empty;
- description
- "Indicates that the neighbor node acts as a router.";
- }
-
- leaf state {
- type enumeration {
- enum "incomplete" {
- value 0;
- description
- "Address resolution is in progress, and the link-layer
- address of the neighbor has not yet been
- determined.";
- }
- enum "reachable" {
- value 1;
- description
- "Roughly speaking, the neighbor is known to have been
- reachable recently (within tens of seconds ago).";
- }
- enum "stale" {
- value 2;
- description
- "The neighbor is no longer known to be reachable, but
- until traffic is sent to the neighbor no attempt
- should be made to verify its reachability.";
- }
- enum "delay" {
- value 3;
- description
- "The neighbor is no longer known to be reachable, and
- traffic has recently been sent to the neighbor.
- Rather than probe the neighbor immediately, however,
- delay sending probes for a short while in order to
- give upper-layer protocols a chance to provide
- reachability confirmation.";
- }
- enum "probe" {
- value 4;
- description
- "The neighbor is no longer known to be reachable, and
- unicast Neighbor Solicitation probes are being sent
- to verify reachability.";
- }
- }
- description
- "The Neighbor Unreachability Detection state of this
- entry.";
- reference
- "RFC 4861: Neighbor Discovery for IP version 6 (IPv6)
- Section 7.3.2";
-
- }
- } // list neighbor
- } // container ipv6
- }
- } // module ietf-ip
diff --git a/ctrl/sysrepo-plugins/yang/ietf/ietf-yang-types@2013-07-15.yang b/ctrl/sysrepo-plugins/yang/ietf/ietf-yang-types@2013-07-15.yang
deleted file mode 100644
index ee58fa3ab..000000000
--- a/ctrl/sysrepo-plugins/yang/ietf/ietf-yang-types@2013-07-15.yang
+++ /dev/null
@@ -1,474 +0,0 @@
-module ietf-yang-types {
-
- namespace "urn:ietf:params:xml:ns:yang:ietf-yang-types";
- prefix "yang";
-
- organization
- "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
-
- contact
- "WG Web: <http://tools.ietf.org/wg/netmod/>
- WG List: <mailto:netmod@ietf.org>
-
- WG Chair: David Kessens
- <mailto:david.kessens@nsn.com>
-
- WG Chair: Juergen Schoenwaelder
- <mailto:j.schoenwaelder@jacobs-university.de>
-
- Editor: Juergen Schoenwaelder
- <mailto:j.schoenwaelder@jacobs-university.de>";
-
- description
- "This module contains a collection of generally useful derived
- YANG data types.
-
- Copyright (c) 2013 IETF Trust and the persons identified as
- authors of the code. All rights reserved.
-
- Redistribution and use in source and binary forms, with or
- without modification, is permitted pursuant to, and subject
- to the license terms contained in, the Simplified BSD License
- set forth in Section 4.c of the IETF Trust's Legal Provisions
- Relating to IETF Documents
- (http://trustee.ietf.org/license-info).
-
- This version of this YANG module is part of RFC 6991; see
- the RFC itself for full legal notices.";
-
- revision 2013-07-15 {
- description
- "This revision adds the following new data types:
- - yang-identifier
- - hex-string
- - uuid
- - dotted-quad";
- reference
- "RFC 6991: Common YANG Data Types";
- }
-
- revision 2010-09-24 {
- description
- "Initial revision.";
- reference
- "RFC 6021: Common YANG Data Types";
- }
-
- /*** collection of counter and gauge types ***/
-
- typedef counter32 {
- type uint32;
- description
- "The counter32 type represents a non-negative integer
- that monotonically increases until it reaches a
- maximum value of 2^32-1 (4294967295 decimal), when it
- wraps around and starts increasing again from zero.
-
- Counters have no defined 'initial' value, and thus, a
- single value of a counter has (in general) no information
- content. Discontinuities in the monotonically increasing
- value normally occur at re-initialization of the
- management system, and at other times as specified in the
- description of a schema node using this type. If such
- other times can occur, for example, the creation of
- a schema node of type counter32 at times other than
- re-initialization, then a corresponding schema node
- should be defined, with an appropriate type, to indicate
- the last discontinuity.
-
- The counter32 type should not be used for configuration
- schema nodes. A default statement SHOULD NOT be used in
- combination with the type counter32.
-
- In the value set and its semantics, this type is equivalent
- to the Counter32 type of the SMIv2.";
- reference
- "RFC 2578: Structure of Management Information Version 2
- (SMIv2)";
- }
-
- typedef zero-based-counter32 {
- type yang:counter32;
- default "0";
- description
- "The zero-based-counter32 type represents a counter32
- that has the defined 'initial' value zero.
-
- A schema node of this type will be set to zero (0) on creation
- and will thereafter increase monotonically until it reaches
- a maximum value of 2^32-1 (4294967295 decimal), when it
- wraps around and starts increasing again from zero.
-
- Provided that an application discovers a new schema node
- of this type within the minimum time to wrap, it can use the
- 'initial' value as a delta. It is important for a management
- station to be aware of this minimum time and the actual time
- between polls, and to discard data if the actual time is too
- long or there is no defined minimum time.
-
- In the value set and its semantics, this type is equivalent
- to the ZeroBasedCounter32 textual convention of the SMIv2.";
- reference
- "RFC 4502: Remote Network Monitoring Management Information
- Base Version 2";
- }
-
- typedef counter64 {
- type uint64;
- description
- "The counter64 type represents a non-negative integer
- that monotonically increases until it reaches a
- maximum value of 2^64-1 (18446744073709551615 decimal),
- when it wraps around and starts increasing again from zero.
-
- Counters have no defined 'initial' value, and thus, a
- single value of a counter has (in general) no information
- content. Discontinuities in the monotonically increasing
- value normally occur at re-initialization of the
- management system, and at other times as specified in the
- description of a schema node using this type. If such
- other times can occur, for example, the creation of
- a schema node of type counter64 at times other than
- re-initialization, then a corresponding schema node
- should be defined, with an appropriate type, to indicate
- the last discontinuity.
-
- The counter64 type should not be used for configuration
- schema nodes. A default statement SHOULD NOT be used in
- combination with the type counter64.
-
- In the value set and its semantics, this type is equivalent
- to the Counter64 type of the SMIv2.";
- reference
- "RFC 2578: Structure of Management Information Version 2
- (SMIv2)";
- }
-
- typedef zero-based-counter64 {
- type yang:counter64;
- default "0";
- description
- "The zero-based-counter64 type represents a counter64 that
- has the defined 'initial' value zero.
-
- A schema node of this type will be set to zero (0) on creation
- and will thereafter increase monotonically until it reaches
- a maximum value of 2^64-1 (18446744073709551615 decimal),
- when it wraps around and starts increasing again from zero.
-
- Provided that an application discovers a new schema node
- of this type within the minimum time to wrap, it can use the
- 'initial' value as a delta. It is important for a management
- station to be aware of this minimum time and the actual time
- between polls, and to discard data if the actual time is too
- long or there is no defined minimum time.
-
- In the value set and its semantics, this type is equivalent
- to the ZeroBasedCounter64 textual convention of the SMIv2.";
- reference
- "RFC 2856: Textual Conventions for Additional High Capacity
- Data Types";
- }
-
- typedef gauge32 {
- type uint32;
- description
- "The gauge32 type represents a non-negative integer, which
- may increase or decrease, but shall never exceed a maximum
- value, nor fall below a minimum value. The maximum value
- cannot be greater than 2^32-1 (4294967295 decimal), and
- the minimum value cannot be smaller than 0. The value of
- a gauge32 has its maximum value whenever the information
- being modeled is greater than or equal to its maximum
- value, and has its minimum value whenever the information
- being modeled is smaller than or equal to its minimum value.
- If the information being modeled subsequently decreases
- below (increases above) the maximum (minimum) value, the
- gauge32 also decreases (increases).
-
- In the value set and its semantics, this type is equivalent
- to the Gauge32 type of the SMIv2.";
- reference
- "RFC 2578: Structure of Management Information Version 2
- (SMIv2)";
- }
-
- typedef gauge64 {
- type uint64;
- description
- "The gauge64 type represents a non-negative integer, which
- may increase or decrease, but shall never exceed a maximum
- value, nor fall below a minimum value. The maximum value
- cannot be greater than 2^64-1 (18446744073709551615), and
- the minimum value cannot be smaller than 0. The value of
- a gauge64 has its maximum value whenever the information
- being modeled is greater than or equal to its maximum
- value, and has its minimum value whenever the information
- being modeled is smaller than or equal to its minimum value.
- If the information being modeled subsequently decreases
- below (increases above) the maximum (minimum) value, the
- gauge64 also decreases (increases).
-
- In the value set and its semantics, this type is equivalent
- to the CounterBasedGauge64 SMIv2 textual convention defined
- in RFC 2856";
- reference
- "RFC 2856: Textual Conventions for Additional High Capacity
- Data Types";
- }
-
- /*** collection of identifier-related types ***/
-
- typedef object-identifier {
- type string {
- pattern '(([0-1](\.[1-3]?[0-9]))|(2\.(0|([1-9]\d*))))'
- + '(\.(0|([1-9]\d*)))*';
- }
- description
- "The object-identifier type represents administratively
- assigned names in a registration-hierarchical-name tree.
-
- Values of this type are denoted as a sequence of numerical
- non-negative sub-identifier values. Each sub-identifier
- value MUST NOT exceed 2^32-1 (4294967295). Sub-identifiers
- are separated by single dots and without any intermediate
- whitespace.
-
- The ASN.1 standard restricts the value space of the first
- sub-identifier to 0, 1, or 2. Furthermore, the value space
- of the second sub-identifier is restricted to the range
- 0 to 39 if the first sub-identifier is 0 or 1. Finally,
- the ASN.1 standard requires that an object identifier
- has always at least two sub-identifiers. The pattern
- captures these restrictions.
-
- Although the number of sub-identifiers is not limited,
- module designers should realize that there may be
- implementations that stick with the SMIv2 limit of 128
- sub-identifiers.
-
- This type is a superset of the SMIv2 OBJECT IDENTIFIER type
- since it is not restricted to 128 sub-identifiers. Hence,
- this type SHOULD NOT be used to represent the SMIv2 OBJECT
- IDENTIFIER type; the object-identifier-128 type SHOULD be
- used instead.";
- reference
- "ISO9834-1: Information technology -- Open Systems
- Interconnection -- Procedures for the operation of OSI
- Registration Authorities: General procedures and top
- arcs of the ASN.1 Object Identifier tree";
- }
-
- typedef object-identifier-128 {
- type object-identifier {
- pattern '\d*(\.\d*){1,127}';
- }
- description
- "This type represents object-identifiers restricted to 128
- sub-identifiers.
-
- In the value set and its semantics, this type is equivalent
- to the OBJECT IDENTIFIER type of the SMIv2.";
- reference
- "RFC 2578: Structure of Management Information Version 2
- (SMIv2)";
- }
-
- typedef yang-identifier {
- type string {
- length "1..max";
- pattern '[a-zA-Z_][a-zA-Z0-9\-_.]*';
- pattern '.|..|[^xX].*|.[^mM].*|..[^lL].*';
- }
- description
- "A YANG identifier string as defined by the 'identifier'
- rule in Section 12 of RFC 6020. An identifier must
- start with an alphabetic character or an underscore
- followed by an arbitrary sequence of alphabetic or
- numeric characters, underscores, hyphens, or dots.
-
- A YANG identifier MUST NOT start with any possible
- combination of the lowercase or uppercase character
- sequence 'xml'.";
- reference
- "RFC 6020: YANG - A Data Modeling Language for the Network
- Configuration Protocol (NETCONF)";
- }
-
- /*** collection of types related to date and time***/
-
- typedef date-and-time {
- type string {
- pattern '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?'
- + '(Z|[\+\-]\d{2}:\d{2})';
- }
- description
- "The date-and-time type is a profile of the ISO 8601
- standard for representation of dates and times using the
- Gregorian calendar. The profile is defined by the
- date-time production in Section 5.6 of RFC 3339.
-
- The date-and-time type is compatible with the dateTime XML
- schema type with the following notable exceptions:
-
- (a) The date-and-time type does not allow negative years.
-
- (b) The date-and-time time-offset -00:00 indicates an unknown
- time zone (see RFC 3339) while -00:00 and +00:00 and Z
- all represent the same time zone in dateTime.
-
- (c) The canonical format (see below) of data-and-time values
- differs from the canonical format used by the dateTime XML
- schema type, which requires all times to be in UTC using
- the time-offset 'Z'.
-
- This type is not equivalent to the DateAndTime textual
- convention of the SMIv2 since RFC 3339 uses a different
- separator between full-date and full-time and provides
- higher resolution of time-secfrac.
-
- The canonical format for date-and-time values with a known time
- zone uses a numeric time zone offset that is calculated using
- the device's configured known offset to UTC time. A change of
- the device's offset to UTC time will cause date-and-time values
- to change accordingly. Such changes might happen periodically
- in case a server follows automatically daylight saving time
- (DST) time zone offset changes. The canonical format for
- date-and-time values with an unknown time zone (usually
- referring to the notion of local time) uses the time-offset
- -00:00.";
- reference
- "RFC 3339: Date and Time on the Internet: Timestamps
- RFC 2579: Textual Conventions for SMIv2
- XSD-TYPES: XML Schema Part 2: Datatypes Second Edition";
- }
-
- typedef timeticks {
- type uint32;
- description
- "The timeticks type represents a non-negative integer that
- represents the time, modulo 2^32 (4294967296 decimal), in
- hundredths of a second between two epochs. When a schema
- node is defined that uses this type, the description of
- the schema node identifies both of the reference epochs.
-
- In the value set and its semantics, this type is equivalent
- to the TimeTicks type of the SMIv2.";
- reference
- "RFC 2578: Structure of Management Information Version 2
- (SMIv2)";
- }
-
- typedef timestamp {
- type yang:timeticks;
- description
- "The timestamp type represents the value of an associated
- timeticks schema node at which a specific occurrence
- happened. The specific occurrence must be defined in the
- description of any schema node defined using this type. When
- the specific occurrence occurred prior to the last time the
- associated timeticks attribute was zero, then the timestamp
- value is zero. Note that this requires all timestamp values
- to be reset to zero when the value of the associated timeticks
- attribute reaches 497+ days and wraps around to zero.
-
- The associated timeticks schema node must be specified
- in the description of any schema node using this type.
-
- In the value set and its semantics, this type is equivalent
- to the TimeStamp textual convention of the SMIv2.";
- reference
- "RFC 2579: Textual Conventions for SMIv2";
- }
-
- /*** collection of generic address types ***/
-
- typedef phys-address {
- type string {
- pattern '([0-9a-fA-F]{2}(:[0-9a-fA-F]{2})*)?';
- }
-
- description
- "Represents media- or physical-level addresses represented
- as a sequence octets, each octet represented by two hexadecimal
- numbers. Octets are separated by colons. The canonical
- representation uses lowercase characters.
-
- In the value set and its semantics, this type is equivalent
- to the PhysAddress textual convention of the SMIv2.";
- reference
- "RFC 2579: Textual Conventions for SMIv2";
- }
-
- typedef mac-address {
- type string {
- pattern '[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}';
- }
- description
- "The mac-address type represents an IEEE 802 MAC address.
- The canonical representation uses lowercase characters.
-
- In the value set and its semantics, this type is equivalent
- to the MacAddress textual convention of the SMIv2.";
- reference
- "IEEE 802: IEEE Standard for Local and Metropolitan Area
- Networks: Overview and Architecture
- RFC 2579: Textual Conventions for SMIv2";
- }
-
- /*** collection of XML-specific types ***/
-
- typedef xpath1.0 {
- type string;
- description
- "This type represents an XPATH 1.0 expression.
-
- When a schema node is defined that uses this type, the
- description of the schema node MUST specify the XPath
- context in which the XPath expression is evaluated.";
- reference
- "XPATH: XML Path Language (XPath) Version 1.0";
- }
-
- /*** collection of string types ***/
-
- typedef hex-string {
- type string {
- pattern '([0-9a-fA-F]{2}(:[0-9a-fA-F]{2})*)?';
- }
- description
- "A hexadecimal string with octets represented as hex digits
- separated by colons. The canonical representation uses
- lowercase characters.";
- }
-
- typedef uuid {
- type string {
- pattern '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-'
- + '[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
- }
- description
- "A Universally Unique IDentifier in the string representation
- defined in RFC 4122. The canonical representation uses
- lowercase characters.
-
- The following is an example of a UUID in string representation:
- f81d4fae-7dec-11d0-a765-00a0c91e6bf6
- ";
- reference
- "RFC 4122: A Universally Unique IDentifier (UUID) URN
- Namespace";
- }
-
- typedef dotted-quad {
- type string {
- pattern
- '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
- + '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
- }
- description
- "An unsigned 32-bit number expressed in the dotted-quad
- notation, i.e., four octets written as decimal numbers
- and separated with the '.' (full stop) character.";
- }
-}
diff --git a/docs/etc/requirements.txt b/docs/etc/requirements.txt
index 5b037c693..3ce3a7e00 100644
--- a/docs/etc/requirements.txt
+++ b/docs/etc/requirements.txt
@@ -1,27 +1,5 @@
-alabaster==0.7.12
-Babel==2.8.0
-certifi==2019.11.28
-chardet==3.0.4
-commonmark==0.9.1
-docutils==0.16
-idna==2.8
-imagesize==1.2.0
-Jinja2==2.10.3
-MarkupSafe==1.1.1
-packaging==20.0
-Pygments==2.5.2
-pyparsing==2.4.6
-pytz==2019.3
-recommonmark==0.6.0
-requests==2.22.0
-six==1.14.0
-snowballstemmer==2.0.0
-Sphinx==2.3.1
-sphinx-rtd-theme==0.4.3
-sphinxcontrib-applehelp==1.0.1
-sphinxcontrib-devhelp==1.0.1
-sphinxcontrib-htmlhelp==1.0.2
-sphinxcontrib-jsmath==1.0.1
-sphinxcontrib-qthelp==1.0.2
-sphinxcontrib-serializinghtml==1.1.3
-urllib3==1.25.8
+pip-tools==6.5.0 # BSD
+sphinx # BSD
+sphinx-rtd-theme # MIT
+sphinx-markdown-tables # GPLv3
+recommonmark # MIT \ No newline at end of file
diff --git a/docs/source/1-architecture.md b/docs/source/1-architecture.md
new file mode 100644
index 000000000..8f3cfc78a
--- /dev/null
+++ b/docs/source/1-architecture.md
@@ -0,0 +1,42 @@
+# Data identifiers and locators
+
+Hybrid ICN makes use of data identifiers to name the data produced by an end
+host. Data identifiers are encoded using a routable name prefix and a non
+routable name suffix to provide the ability to index a single IP packet in an
+prefix is unambigous manner. A full data name is composed of 160 bits. A
+routable name prefix in IPv4 network is 32 bits long while in IPv6 is 128 bits
+long. A name prefix is a valid IPv4 or IPv6 address. The 32 rightmost bits are
+used by the applications to index data within the same stream.
+
+A data source that is using the hicn stack is reacheable through IP routing
+where a producer socket is listening as the producer name prefix is IP routable.
+
+Locators are IP interface identifiers and are IPv4 or IPv6 addresses. Data
+consumers are reacheable through IP routing over their locators.
+
+For requests, the name prefix is stored in the destination address field of the
+IP header while the source address field stored the locator of the consumer.
+
+
+# Producer/Consumer Architecture
+Applications make use of the hicn network architecture by using a Prod/Cons API.
+Each communication socket is connection-less as a data producer makes data
+available to data consumer by pushing data into a named buffer. Consumers are
+responsible for pulling data from data producers by sending requests indexing
+the full data name which index a single MTU sized data packet. The core
+
+# Packet forwarding
+Packet forwarding leverages IP routing as requests are forwarded using name
+prefixes and replies using locators.
+
+# Relay nodes
+A relay node is implemented by using a packet cache which is used to temporarily
+store requests and replies. The relay node acts as a virtual proxy for the data
+producers as it caches data packets which can be sent back to data consumer by
+using the full name as an index. Requests must be cached and forwarded upstream
+towards data producers which will be able reach back the relay nodes by using
+the IP locators of the relays. Cached requests store all locators as currently
+written in the source address field of the request while requests forwarded
+upstream will get the source address rewritten with the relay node locator. Data
+packets can reach the original consumers via the relay nodes by using the
+requence of cached locators.
diff --git a/docs/source/apps.md b/docs/source/apps.md
index 64c3d9a68..4131eba82 100644
--- a/docs/source/apps.md
+++ b/docs/source/apps.md
@@ -18,7 +18,6 @@ Basic dependencies:
- OpenSSL
- pthreads
- libevent
-- libparc
- libcurl
- libhicntransport
diff --git a/docs/source/conf.py b/docs/source/conf.py
index bb6715564..d00e821ab 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -19,13 +19,13 @@
# -- Project information -----------------------------------------------------
project = u'Hybrid ICN'
-copyright = u'(c) 2017-2020 Cisco and/or its affiliates.'
-author = u'Luca Muscariello'
+copyright = u'(c) 2018-2022 Cisco and/or its affiliates.'
+author = u'HICN Team Members'
# The short X.Y version
version = u''
# The full version, including alpha/beta/rc tags
-release = u'20.01'
+release = u'22.02'
# -- General configuration ---------------------------------------------------
@@ -37,7 +37,7 @@ release = u'20.01'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
-extensions = ['recommonmark']
+extensions = ['recommonmark', 'sphinx_markdown_tables']
# Prefix document path to section labels, otherwise autogenerated labels would look like 'heading'
# rather than 'path/to/file:heading'
@@ -88,7 +88,7 @@ html_theme = "sphinx_rtd_theme"
html_static_path = ['_static']
def setup(app):
- app.add_stylesheet('css/rules.css')
+ app.add_css_file('css/rules.css')
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
diff --git a/docs/source/control.md b/docs/source/control.md
index 9564a23af..fb6b7faf3 100644
--- a/docs/source/control.md
+++ b/docs/source/control.md
@@ -1,333 +1,3 @@
# Control plane support
-Control plane functionalities are provides via SDN controllers or via standard
-IP routing protocols. SDN support is provided by using the NETCONF/YANG protocol
-for network management, control and telemetry.
-
-Routing is supported via synchronization of the IP FIB and the IP RIB as implemented
-by one of the routing protocols in FRR. Without loss of generality we have reported
-below one example of IGP routing via OSPF for IPv6.
-
-The VPP IP FIB can be controlled and updated by one FRR routing protocol which
-is used for routing over locators and also over hICN name prefixes.
-
-## NETCONF/YANG
-
-### Getting started
-
-NETCONF/YANG support is provided via several external components such as
-libyang, sysrepo, libnetconf and netopeer.
-The hicn project provides a sysrepo plugin and a YANG model for two devices:
-the VPP based hicn virtual switch and the portable forwarder.
-The YANG model for the VPP based hICN vSwitch is based the full hICN C API
-exported by the VPP plugin with the addition of some VPP APIs such as
-interface and FIB management which are required by the hICN plugin.
-
-To install libyang, sysrepo, libnetconf and netopeer2 for Ubuntu18 amd64/arm64
-or CentOS 7 and ad-hoc repository is available and maintained in bintray
-at <https://dl.bintray.com/icn-team/apt-hicn-extras>.
-
-For instance in Ubuntu 18 LTS:
-
-Install the sysrepo YANG data store and a NETCONF server:
-
-```bash
-echo "deb [trusted=yes] https://dl.bintray.com/icn-team/apt-hicn-extras bionic main" \
- | tee -a /etc/apt/sources.list
-apt-get update && apt-get install -y libyang sysrepo libnetconf2 netopeer2-server
-```
-
-Install the VPP based hICN virtual switch:
-
-```bash
-curl -s https://packagecloud.io/install/repositories/fdio/release/script.deb.sh | bash
-apt-get update && apt-get install -y hicn-plugin vpp-plugin-dpdk hicn-sysrepo-plugin
-```
-
-The hICN YANG models are installed under `/usr/lib/$(uname -m)-linux-gnu/modules_yang`.
-
-Configure the NETCONF/YANG components:
-
-```bash
-bash /usr/bin/setup.sh sysrepoctl /usr/lib/$(uname -m)-linux-gnu/modules_yang root
-bash /usr/bin/merge_hostkey.sh sysrepocfg openssl
-bash /usr/bin/merge_config.sh sysrepocfg genkey
-```
-
-You can manually install the yang model using the following bash script:
-
-```bash
-EXIT_CODE=0
-command -v sysrepoctl > /dev/null
-if [ $? != 0 ]; then
- echo "Could not find command \"sysrepoctl\"."
- exit ${EXIT_CODE}
-else
-sysrepoctl --install --yang=path_to_hicn_yang_model
-fi
-```
-
-### YANG model
-
-hicn.yang can be found in the yang-model. It consists of two container nodes:
-
-```text
-|--+ hicn-conf: holds the configuration data;
-| |--+ params: contains all configuration parameters;
-|--+ hicn-state: provides the state data
-| |--+ state,
-| |--+ strategy,
-| |--+ strategies,
-| |--+ route,
-| |--+ face-ip-params
-and corresponding leaves.
-```
-
-A controller can configure these parameters through the edit-config RPC
-call. This node can be used to enable and to initialize the hicn-plugin in VPP
-instance. hicn-state container is used to provide the state data to the
-controller. It consists of state, strategy, strategies, route, and face-ip-params
-nodes with the corresponding leaves. In the hicn model a variety of RPCs are provided
-to allow controller to communicate with the hicn-plugin as well as update the state
-data in hicn-state.
-
-### Example
-
-To setup the startup configuration you can use the following script:
-
-```bash
-EXIT_CODE=0
-command -v sysrepocfg > /dev/null
-if [ $? != 0 ]; then
- echo "Could not find command \"sysrepocfg\"."
- exit ${EXIT_CODE}
-else
-sysrepocfg -d startup -i path_to_startup_xml -f xml hicn
-fi
-```
-
-startup.xml is placed in the yang-model. Here you can find the content:
-
-```xml
-<hicn-conf xmlns="urn:sysrepo:hicn">
-<params>
- <enable_disable>false</enable_disable>
- <pit_max_size>-1</pit_max_size>
- <cs_max_size>-1</cs_max_size>
- <cs_reserved_app>-1</cs_reserved_app>
- <pit_dflt_lifetime_sec>-1</pit_dflt_lifetime_sec>
- <pit_max_lifetime_sec>-1</pit_max_lifetime_sec>
- <pit_min_lifetime_sec>-1</pit_min_lifetime_sec>
-</params>
-</hicn-conf>
-```
-
-It contains the leaves of the parameters in hicn-conf node which is
-used as the startup configuration. This configuration can be changed through the
-controller by subscribing which changes the target to the running state. hicn
-yang model provides a list of RPCs which allows controller to communicate
-directly with the hicn-plugin. This RPCs may also cause the modification in
-state data.
-
-In order to run different RPCs from controller you can use the examples in the
-controler_rpcs_instances.xml in the yang-model. Here you can find the content:
-
-```xml
-<node-params-get xmlns="urn:sysrepo:hicn"/>
-
-<node-stat-get xmlns="urn:sysrepo:hicn"/>
-
-<strategy-get xmlns="urn:sysrepo:hicn">
- <strategy_id>0</strategy_id>
-</strategy-get>
-
-<strategies-get xmlns="urn:sysrepo:hicn"/>
-
-<route-get xmlns="urn:sysrepo:hicn">
- <prefix0>10</prefix0>
- <prefix1>20</prefix1>
- <len>30</len>
-</route-get>
-
-<face-params-get xmlns="urn:sysrepo:hicn">
- <faceid>10</faceid>
-</face-params-get>
-
-<hicn-enable xmlns="urn:sysrepo:hicn">
- <prefix>b001::/64</prefix>
-</hicn-enable>
-
-<hicn-disable xmlns="urn:sysrepo:hicn">
- <prefix>b001::/64</prefix>
-</hicn-disable>
-```
-
-#### Run the plugin
-
-First, verify the plugin and binary libraries are located correctly, then run
-the vpp through (service vpp start). Next, run the sysrepo plugin
-(sysrepo-plugind), for debug mode: sysrep-plugind -d -v 4 which runs with high
-verbosity. Now, the hicn sysrepo plugin is loaded. Then, run the
-netopeer2-server which serves as NETCONF server
-
-#### Connect from netopeer2-cli
-
-In order to connect through the netopeer client run the netopeer2-cli. Then,
-follow these steps:
-
-- connect --host XXX --login XXX
-- get (you can get the configuration and operational data)
-- get-config (you can get the configuration data)
-- edit-config --target running --config
-
-With the default netopeer2-server configuration the authentication required by
-netopeer2-cli reflects the ssh authentication (username and password or public
-key). For other means of authentication please refer to netopeer2-server
-documentation (e.g., netopeer2/server/configuration/README.md).
-
-You can modify the configuration but it needs an xml configuration input.
-
-```xml
-<hicn-conf xmlns="urn:sysrepo:hicn">
-<params>
- <enable_disable>false</enable_disable>
- <pit_max_size>-1</pit_max_size>
- <cs_max_size>-1</cs_max_size>
- <cs_reserved_app>-1</cs_reserved_app>
- <pit_dflt_lifetime_sec>-1</pit_dflt_lifetime_sec>
- <pit_max_lifetime_sec>-1</pit_max_lifetime_sec>
- <pit_min_lifetime_sec>-1</pit_min_lifetime_sec>
-</params>
-</hicn-conf>
-```
-
-- user-rpc (you can call one of the rpc proposed by hicn model but it needs an xml input)
-
-#### Connect from OpenDaylight (ODL) controller
-
-In order to connect through the OpenDaylight follow these procedure:
-
-- run karaf distribution (./opendayligh_installation_folder/bin/karaf)
-- install the required feature list in DOL (feature:install odl-netconf-server
- odl-netconf-connector odl-restconf-all odl-netconf-topology or
- odl-netconf-clustered-topology)
-- run a rest client program (e.g., postman or RESTClient)
-- mount the remote netopeer2-server to the OpenDaylight by the following REST API:
-
- ```
- PUT <http://localhost:8181/restconf/config/network-topology:network-topology/topology/topology-netconf/node/hicn-node>`
- ```
- with the following body:
-
- ```xml
- <node xmlns="urn:TBD:params:xml:ns:yang:network-topology">
- <node-id>hicn-node</node-id>
- <host xmlns="urn:opendaylight:netconf-node-topology">Remote_NETCONF_SERVER_IP</host>
- <port xmlns="urn:opendaylight:netconf-node-topology">830</port>
- <username xmlns="urn:opendaylight:netconf-node-topology">username</username>
- <password xmlns="urn:opendaylight:netconf-node-topology">password</password>
- <tcp-only xmlns="urn:opendaylight:netconf-node-topology">false</tcp-only>
- <keepalive-delay xmlns="urn:opendaylight:netconf-node-topology">1</keepalive-delay>
- </node>
- ```
-
- Note that the header files must be set to `Content-Type: application/xml, Accept: application/xml`.
-
-- send the operation through the following REST API:
-
-POST <http://localhost:8181/restconf/operations/network-topology:network-topology/topology/topology-netconf/node/hicn-node/yang-ext:mount/ietf-netconf:edit-config>
-
-The body can be used the same as edit-config in netopeer2-cli.
-
-#### Connect from Cisco Network Services Orchestrator (NSO)
-
-To connect NSO to the netopeer2-server, first, you need to write a NED package
-for your device. The procedure to create NED for hicn is explained in the
-following:
-
-Place hicn.yang model in a folder called hicn-yang-model, and follow these steps:
-
-- ncs-make-package --netconf-ned ./hicn-yang-model ./hicn-nso
-- cd hicn-nso/src; make
-- ncs-setup --ned-package ./hicn-nso --dest ./hicn-nso-project
-- cd hicn-nso-project
-- ncs
-- ncs_cli -C -u admin
-- configure
-- devices authgroups group authhicn default-map remote-name user_name remote-password password
-- devices device hicn address IP_device port 830 authgroup authhicn device-type netconf
-- state admin-state unlocked
-- commit
-- ssh fetch-host-keys
-
-At this point, we are able to connect to the remote device.
-
-## Release note
-
-The current version is compatible with the 20.01 VPP stable and sysrepo devel.
-
-## Routing plugin for VPP and FRRouting for OSPF6
-
-This document describes how to configure the VPP with hicn_router
-plugin and FRR to enable the OSPF protocol. The VPP and FRR
-are configured in a docker file.
-
-### DPDK configuration on host machine
-
-Install and configure DPDK:
-```bash
-make install T=x86_64-native-linux-gcc && cd x86_64-native-linux-gcc && sudo make install
-modprobe uio
-modprobe uio_pci_generic
-dpdk-devbind --status
-the PCIe number of the desired device can be observed ("xxx")
-sudo dpdk-devbind -b uio_pci_generic "xxx"
-```
-
-### VPP configuration
-
-Run and configure the VPP (hICN router plugin is required to be installed in VPP):
-```bash
-vpp# set int state TenGigabitEtherneta/0/0 up
-vpp# set int ip address TenGigabitEtherneta/0/0 a001::1/24
-vpp# create loopback interface
-vpp# set interface state loop0 up
-vpp# set interface ip address loop0 b001::1/128
-vpp# enable tap-inject # This creates the taps by router plugin
-vpp# show tap-inject # This shows the created taps
-vpp# ip mroute add ff02::/64 via local Forward # ff02:: is multicast ip address
-vpp# ip mroute add ff02::/64 via TenGigabitEtherneta/0/0 Accept
-vpp# ip mroute add ff02::/64 via loop0 Accept
-```
-
-Setup the tap interface:
-```bash
-ip addr add a001::1/24 dev vpp0
-ip addr add b001::1/128 dev vpp1
-ip link set dev vpp0 up
-ip link set dev vpp1 up
-```
-
-### FRR configuration
-
-Install FRR in Ubuntu 18 LTS:
-<http://docs.frrouting.org/projects/dev-guide/en/latest/building-frr-for-ubuntu1804.html>
-
-Run and configure FRRouting (ospf):
-```text
-/usr/lib/frr/frrinit.sh start &
-vtysh
-configure terminal
-router ospf6
-area 0.0.0.0 range a001::1/24
-area 0.0.0.0 range b001::1/128
-interface vpp0 area 0.0.0.0
-interface vpp1 area 0.0.0.0
-end
-wr
-add "no ipv6 nd suppress-ra" to the first configurtion part of the /etc/frr/frr.conf
-```
-
-After the following configuration, the traffic over tap interface can be observed
-via `tcpdump- i vpp1`. The neighborhood and route can be seen with the
-`show ipv6 ospf6 neighbor/route` command.
+A new control plane for hicn is under construction.
diff --git a/docs/source/hicn-light.md b/docs/source/hicn-light.md
index 90e0afc91..f5012f8e9 100644
--- a/docs/source/hicn-light.md
+++ b/docs/source/hicn-light.md
@@ -11,15 +11,14 @@ to communicate.
Build dependencies:
-- C99 ( clang / gcc )
-- CMake 3.4
+- C11 ( clang / gcc )
+- CMake 3.10
Basic dependencies:
- OpenSSL
- pthreads
- libevent
-- libparc
## hicn-light executables
@@ -37,31 +36,27 @@ The command `hicn-light-daemon` runs the hicn-light forwarder. The forwarder can
with the following options:
```bash
-hicn-light-daemon [--port port] [--daemon] [--capacity objectStoreSize] [--log facility=level]
+hicn-light-daemon [--port port] [--daemon] [--capacity objectStoreSize] [--log level]
[--log-file filename] [--config file]
Options:
---port <tcp_port> = tcp port for local in-bound connections
---daemon = start as daemon process
---capacity <capacity> = maximum number of content objects to cache. To disable the cache
- objectStoreSize must be 0.
- Default vaule for objectStoreSize is 100000
---log <log_granularity> = sets a facility to a given log level. You can have multiple of these.
- facilities: all, config, core, io, message, processor
- levels: debug, info, notice, warning, error, critical, alert, off
- example: hicn-light-daemon --log io=debug --log core=off
---log-file <output_logfile> = file to write log messages to (required in daemon mode)
---config <config_path> = configuration filename
+--port <tcp_port> = tcp port for local in-bound connections
+--daemon = start as daemon process
+--capacity <objectStoreSize> = maximum number of content objects to cache. To disable the cache
+ objectStoreSize must be 0.
+ Default vaule for objectStoreSize is 100000
+--log <log_granularity> = sets the log level. Available levels: trace, debug, info, warn, error, fatal
+--log-file <output_logfile> = file to write log messages to (required in daemon mode)
+--config <config_path> = configuration filename
```
The configuration file contains configuration lines as per hicn-light-control (see below for all
the available commands). If logging level or content store capacity is set in the configuration
-file, it overrides the command_line. When a configuration file is specified, no default listeners
-are setup. Only 'add listener' lines in the configuration file matter.
+file, it overrides the command_line.
-If no configuration file is specified, hicn-light-daemon will listen on TCP and UDP ports specified
-by the --port flag (or default port). It will listen on both IPv4 and IPv6 if available. The
-default port for hicn-light is 9695. Commands are expected on port 2001.
+In addition to the listeners setup in the configuration file, hicn-light-daemon will listen
+on TCP and UDP ports specified by the --port flag (or default port).
+It will listen on both IPv4 and IPv6 if available. The default port for hicn-light is 9695.
### hicn-light-control
@@ -82,28 +77,20 @@ This is the full list of available commands in `hicn-light-control`. This comman
from the command line running `hicn-light-control` as explained before, or listing them in a
configuration file.
-Information about the commands are also available in the `hicn-light-control` help message.
+The list of commands can be navigated using `hicn-light-control help`, `hicn-light-control help <object>`, `hicn-light-control help <object> <action>`.
`add listener`: creates a TCP or UDP listener with the specified options on the local forwarder.
For local connections (application to hicn-light) we expect a TCP listener. The default port for
the local listener is 9695.
```bash
-add listener <protocol> <symbolic> <local_adress> <local_port>
+add listener <protocol> <symbolic> <local_address> <local_port> <interface>
<symbolic> :User defined name for listener, must start with alpha and bealphanum
<protocol> :tcp | udp
<localAddress> :IPv4 or IPv6 address
<local_port> :TCP/UDP port
-```
-
-`add listener hicn`: creates a hicn listener with the specified options on the local forwarder.
-
-```bash
-add listener hicn <symbolic> <local_adress>
-
- <symbolic> :User defined name for listener, must start with alpha and be alphanum
- <localAddress> :IPv4 or IPv6 address
+ <interface> :interface on which to bind
```
`add connection`: creates a TCP or UDP connection on the local forwarder with the specified options.
@@ -119,17 +106,6 @@ add connection <protocol> <symbolic> <remote_ip> <remote_port> <local_ip> <local
<local_port> : local TCP/UDP port
```
-`add connection hicn`: creates an hicn connection on the local forwarder with the specified options.
-
-```bash
-add connection hicn <symbolic> <remote_ip> <local_ip>
-
- <symbolic> : symbolic name, e.g. 'conn1' (must be unique, start with alpha)
- <remote_ip> : the IPv4 or IPv6 of the remote system
- <local_ip> : local IP address to bind to
-
-```
-
`list`: lists the connections, routes or listeners available on the local hicn-light forwarder.
```bash
@@ -142,7 +118,7 @@ list <connections | routes | listeners>
add route <symbolic | connid> <prefix> <cost>
<symbolic> :The symbolic name for an exgress (must be unique, start with alpha)
- <connid>: :The egress connection id (see 'help list connections')
+ <connid>: :The egress connection id (see 'list connection' command)
<prefix>: :ipAddress/netmask
<cost>: :positive integer representing cost
```
@@ -151,11 +127,10 @@ add route <symbolic | connid> <prefix> <cost>
only for UDP connections, TCP is ignored.
```bash
-remove connection <protocol> <symbolic | connid>
+remove connection <symbolic | connid>
- <protocol> : tcp | upd. This is the protocol used to create the connection.
<symbolic> :The symbolic name for an exgress (must be unique, start with alpha)
- <connid>: :The egress connection id (see 'help list connections')
+ <connid>: :The egress connection id (see 'list connection' command)
```
@@ -168,24 +143,24 @@ remove route <symbolic | connid> <prefix>
<prefix> : the prefix (ipAddress/netmask) to remove
```
-`cache serve`: enables/disables replies from local content store (if available).
+`serve cache`: enables/disables replies from local content store (if available).
```bash
-cache serve <on|off>
+serve cache <on|off>
```
-`cache store`: enables/disables the storage of incoming data packets in the local content store
+`store cache`: enables/disables the storage of incoming data packets in the local content store
(if available).
```bash
-cache store <on|off>
+store cache <on|off>
```
-`cache clear`: removes all the cached data form the local content store (if available).
+`clear cache`: removes all the cached data form the local content store (if available).
```bash
-cache clear
+clear cache
```
`set strategy`: sets the forwarding strategy for a give prefix. There are 4 different strategies
@@ -200,12 +175,14 @@ implemented in hicn-light:
ICNP 2013.
- **low_latency**: uses the face with the lowest latency. In case more faces have similar
latency the strategy uses them in parallel.
+- **replication**
+- **bastpath**
```bash
set strategy <prefix> <strategy>
<preifx> : the prefix to which apply the forwarding strategy
- <strategy> : random | loadbalancer | low_latency
+ <strategy> : random | loadbalancer | low_latency | replication | bestpath
```
`set wldr`: turns on/off WLDR on the specified connection. WLDR (Wireless Loss Detiection and
@@ -224,36 +201,13 @@ set wldr <on|off> <symbolic | connid>
```
-`add punting`: add punting rules to the forwarders.
-
-```bash
-add punting <symbolic> <prefix>
-
- <symbolic> : listener symbolic name
- <address> : prefix to add as a punting rule. (example 1234::0/64)
-```
-
-`mapme enable`: enables/disables mapme.
-
-```bash
-mapme enable <on|off>
-```
-`mapme discovery`: enables/disables mapme discovery.
-
-```bash
-mapme discovery <on|off>
-```
-
-`mapme timescale`: set the timescale value expressed in milliseconds.
-
-```bash
-mapme timescale <milliseconds>
-```
-
-`mapme retx`: set the retransmission time value expressed in millisecond.
+`set mapme`: enables/disables mapme, enables/disables mapme discovery, set the timescale value (expressed in milliseconds), set the retransmission time value (expressed in milliseconds).
```bash
-mapme retx <milliseconds>
+mapme set enable <on|off>
+mapme set discovery <on|off>
+mapme set timescale <milliseconds>
+mapme set retx <milliseconds>
```
`quit`: exits the interactive bash.
@@ -264,13 +218,12 @@ This is an example of a simple configuration file for hicn-light. It can be load
the command `hicn-light-daemon --config configFile.cfg`, assuming the file name is `configFile.cfg`.
```bash
-#create a local listener on port 9199. This will be used by the applications to talk
-with the forwarder
-add listener udp local0 192.168.0.1 9199
+# Create a local listener on port 9199. This will be used by the applications to talk with the forwarder
+add listener udp local0 192.168.0.1 9199 eth0
-#create a connection with a remote hicn-light-daemon, with a listener on 192.168.0.20 12345
-add connection udp conn0 192.168.0.20 12345 192.168.0.1 9199
+# Create a connection with a remote hicn-light-daemon, with a listener on 192.168.0.20 12345
+add connection udp conn0 192.168.0.20 12345 192.168.0.1 9199 eth0
-#add a route toward the remote node
+# Add a route toward the remote node
add route conn0 c001::/64 1
```
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 99ea39afa..c41df95ca 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -1,27 +1,76 @@
Hybrid Information-Centric Networking
=====================================
-Hybrid Information-Centric Networking (hICN) is a network architecture that makes
-use of IPv6 or IPv4 to realize location-independent communications. It is largely
-inspired by the pioneer work of Van Jacobson on Content-Centric Networking, that was
-a clean-slate architecture whereas hICN is based on the Internet protocol and easy to
-deploy in today networks and applications. hICN brings many-to-many communications,
-multi-homing, multi-path, multi-source, group communications to the Internet protocol
-without replicated unicast. The project implements novel transport protocols, with a socket API,
-for real-time and capacity seeking applications. A scalable stack is available based
-on VPP and a client stack is provided to support any mobile and desktop operating system.
+Hybrid Information-Centric Networking (hICN) is a network architecture that
+makes use of IPv6 or IPv4 to implement location-independent communications. It
+is largely inspired by the pioneer work of Van Jacobson on Content-Centric
+Networking (RFC 8569, RFC 8609) that is a clean-slate architecture. hICN is
+based on the Internet protocol and easyier to deploy in today networks and
+applications. hICN brings many-to-many communications, multi-homing, multi-path,
+multi-source, group communications to the Internet protocol. The current code
+implements also transport protocols, with a socket API, for real-time and
+capacity seeking applications. A scalable stack is available based on VPP and a
+client stack is provided to support mobile and desktop operating systems.
+
+A detailed description of the architecture is described in the paper
+
+Giovanna Carofiglio, Luca Muscariello, Jordan Augé, Michele Papalini, Mauro
+Sardara, and Alberto Compagno. 2019. Enabling ICN in the Internet Protocol:
+Analysis and Evaluation of the Hybrid-ICN Architecture. In Proceedings of the
+6th ACM SIGCOMM Conference on Information-Centric Networking (ICN '19).
+Association for Computing Machinery, New York, NY, USA, 55–66. DOI:
+https://doi.org/10.1145/3357150.3357394
+
+The project wiki page is full of resources https://wiki.fd.io/view/HICN
+
+.. toctree::
+ :caption: Architecture
+
+ 1-architecture
+
.. toctree::
+ :caption: Getting started
+ :maxdepth: 1
started
+
+.. toctree::
+ :caption: Core library
+ :maxdepth: 1
+
lib
+
+.. toctree::
+ :caption: The VPP Plugin
+ :maxdepth: 1
+
vpp-plugin
+
+.. toctree::
+ :caption: The Transport Library
+ :maxdepth: 1
+
transport
+
+.. toctree::
+ :caption: The Portable Forwarder
+ :maxdepth: 1
+
hicn-light
+
+.. toctree::
+ :caption: Network Control and Management
+ :maxdepth: 1
+
interface
control
telemetry
- utils
- apps
+.. toctree::
+ :caption: Applications and Tools
+ :maxdepth: 1
+ utils
+ apps
+ packethicn \ No newline at end of file
diff --git a/docs/source/interface.md b/docs/source/interface.md
index cf05a5c7b..909f60bfa 100644
--- a/docs/source/interface.md
+++ b/docs/source/interface.md
@@ -45,35 +45,6 @@ interfaces:
link and address information, interface types, and bonjour service
discovery.
-### Architectural overview
-
-#### Facelets
-
-TODO:
-
-```text
-- Key attributes (netdevice and protocol family)
-- Facelet API
-```
-
-#### Events
-
-TODO
-
-#### Facelet cache & event scheduling
-
-TODO:
-
-```text
- - Facelet cache
- - Joins
- - How synchronization work
-```
-
-### Interface API
-
-TODO
-
## Developing a new interface
### Dummy template
@@ -261,7 +232,7 @@ error.
```
While support for multiple file descriptors might be added in the future, an
-alternative short-term implementation might consider the instanciation of
+alternative short-term implementation might consider the instantiation of
multiple interface, as is done for Bonjour in the current codebase, in
`src/api.c`.
@@ -304,8 +275,6 @@ The build system is based on CMake. Each interface should declare its source
files, private and public header files, as well as link dependencies in the
local `CMakeLists.txt` file.
-TODO: detail the structure of the file
-
### Hands-on
#### Architecture
diff --git a/docs/source/packethicn.md b/docs/source/packethicn.md
index cf4976837..acf2d7cc9 100644
--- a/docs/source/packethicn.md
+++ b/docs/source/packethicn.md
@@ -1,11 +1,13 @@
HICN Plugin for Wireshark
===================
-The `packethicn` plugin adds support to Wireshark to parse and dissect HICN traffic.
+The `packethicn` plugin adds support to Wireshark to parse and dissect HICN
+traffic.
`packethicn` can be compiled and installed in two ways:
-1. Alongside HICN, from the HICN root dir (see [Build with HICN](#Build-with-HICN))
+1. Alongside HICN, from the HICN root dir (see [Build with
+ HICN](#Build-with-HICN))
2. As a standalone component (see [Standalone build](#Standalone-build))
@@ -14,13 +16,12 @@ The second one is preferred if HICN is already installed in the system.
# Supported platforms
`packethicn` has been tested in
-- Ubuntu 18.04
- Ubuntu 20.04
-- macOS 11.2
+- macOS 12.3
Other platforms and architectures may work.
-# Installation
+# Installation
## Build with HICN
### Dependencies
@@ -38,15 +39,10 @@ From the root HICN dir add the `-DBUILD_WSPLUGIN` flag to cmake.
```bash
$ cd hicn
-
$ mkdir build; cd build
-
-$ cmake -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl\@1.1 -DBUILD_APPS=ON -DBUILD_WSPLUGIN=ON ..
-
+$ cmake -DBUILD_APPS=ON -DBUILD_WSPLUGIN=ON ..
$ make -j`nproc`
-
$ sudo make install
-
```
## Standalone build
@@ -55,22 +51,16 @@ $ sudo make install
#### Install dependencies
```bash
$ sudo add-apt-repository ppa:wireshark-dev/stable
-
$ curl -s https://packagecloud.io/install/repositories/fdio/release/script.deb.sh | sudo bash
-
$ sudo apt install -y build-essential cmake libhicn-dev wireshark wireshark-dev libgcrypt-dev libgnutls28-dev
```
-#### Compile and install HICN plugin
+#### Compile and install HICN wireshark plugin
```bash
$ cd packethicn
-
$ mkdir build; cd build
-
$ cmake ..
-
$ make
-
$ sudo make install
```
@@ -80,15 +70,10 @@ If installing wireshark via brew use the `./install_macos.sh` script as shown be
```bash
$ brew tap icn-team/hicn-tap
-
$ brew install hicn
-
$ brew install wireshark
-
$ brew install cask wireshark
-
$ cd packethicn
-
$ ./install_macos.sh
```
@@ -96,13 +81,9 @@ Otherwise (if wireshark was compiled from sources) you can follow the setup for
```bash
$ cd packethicn
-
$ mkdir build; cd build
-
$ cmake ..
-
$ make
-
$ sudo make install
```
@@ -110,6 +91,7 @@ $ sudo make install
## Filters
+
| Filter | Description | Example |
| --- | --- | --- |
| `hicn` | HICN traffic only | *hicn* |
diff --git a/docs/source/started.md b/docs/source/started.md
index ef3763366..dd2f83bab 100644
--- a/docs/source/started.md
+++ b/docs/source/started.md
@@ -1,15 +1,16 @@
-# Getting started
+# Code structure
## Introduction
-hicn is an open source implementation of Cisco's hICN. It includes a network stack, that implements
-ICN forwarding path in IPv6, and a transport stack that implements two main transport protocols and
-a socket API. The transport protocols provide one reliable transport service implementation and a
-real-time transport service for audio/video media.
+hicn is an open source implementation of Cisco's hICN. It includes a network
+stack, that implements ICN forwarding path in IPv6, and a transport stack that
+implements two main transport protocols and a socket API. The transport
+protocols provide one reliable transport service implementation and a real-time
+transport service for audio/video media.
## Directory layout
-```text
+
| Directory name | Description |
| -------------- | --------------------------------------------------------- |
| lib | Core support library |
@@ -19,39 +20,36 @@ real-time transport service for audio/video media.
| utils | Tools for testing |
| apps | Application examples using hicn stack |
| ctrl | Tools and libraries for network management and control |
-```
-hicn plugin is a VPP plugin that implement hicn packet processing as specified in
-<https://datatracker.ietf.org/doc/draft-muscariello-intarea-hicn/.> The transport library is used to
-implement the hicn host stack and makes use of libmemif as high performance connector between
-transport and the network stack. The transport library makes use of VPP binary API to configure the
-local namespace (local face management).
+hicn plugin is a VPP plugin that implement hicn packet processing as specified
+in [1] The transport library is used to implement the hicn host stack and makes
+use of libmemif as high performance connector between transport and the network
+stack. The transport library makes use of VPP binary API to configure the local
+namespace (local face management).
## Release note
-The current master branch provides the latest release which is compatible with the latest VPP stable.
-No other VPP releases are supported nor maintained. At every new VPP release distribution hicn
-master branch is updated to work with the latest stable release. All previous stable releases
-are discontinued and not maintained. The user who is interested in a specific release can always
-checkout the right code tree by searching the latest commit under a given git tag carrying the
-release version.
+The current master branch provides the latest release which is compatible with
+the latest VPP stable. No other VPP releases are supported nor maintained. At
+every new VPP release distribution hicn master branch is updated to work with
+the latest stable release. All previous stable releases are discontinued and not
+maintained. The user who is interested in a specific release can always checkout
+the right code tree by searching the latest commit under a given git tag
+carrying the release version.
-The Hybrid ICN software distribution can be installed for several platforms.
-The network stack comes in two different implementations: one scalable based
-on VPP and one portable based on IPC and sockets.
+The Hybrid ICN software distribution can be installed for several platforms. The
+network stack comes in two different implementations: one scalable based on VPP
+and one portable based on IPC and sockets.
-The transport stack is a unique library that is used for both the scalable
-and portable network stacks.
+The transport stack is a unique library that is used for both the scalable and
+portable network stacks.
## Supported platforms
-- Ubuntu 18.04 LTS (amd64, arm64)
-- Debian Stable/Testing
-- Red Hat Enterprise Linux 7
-- CentOS 7
+- Ubuntu 20.04 LTS (amd64, arm64)
- Android 10 (amd64, arm64)
-- iOS 13
-- macOS 10.15
+- iOS 15
+- macOS 12.3
- Windows 10
Other platforms and architectures may work.
@@ -63,35 +61,97 @@ You can either use released packages, or compile hicn from sources.
curl -s https://packagecloud.io/install/repositories/fdio/release/script.deb.sh | sudo bash
```
-### CentOS
+The following debian packages for Ubuntu are available dor amd64 and arm64
```bash
-curl -s https://packagecloud.io/install/repositories/fdio/release/script.rpm.sh | sudo bash
+facemgr-dev
+facemgr
+hicn-apps-dev
+hicn-apps
+hicn-light
+hicn-plugin-dev
+hicn-plugin
+libhicn-dev
+libhicn
+libhicnctrl-dev
+libhicnctrl-modules
+libhicnctrl
+libhicntransport-dev
+libhicntransport-io-modules
+libhicntransport
```
### macOS
```bash
+brew tap icn-team/hicn-tap
brew install hicn
```
+or
+
+```bash
+git clone https://github.com/FDio/hicn.git
+$ cd hicn
+$ OPENSSL_ROOT_DIR=/usr/local/opt/openssl\@1.1 make build-release
+```
+
### Android
+hICN is built as a native library for the Android NDK which are packaged
+as Android archives AAR and made available in a Maven repository in
+Github Packages in
+
+<https://github.com/orgs/icn-team/packages>
+
+To build from sources, refer to the Android SDK in
+
+<https://github.com/icn-team/android-sdk>
Install the applications via the Google Play Store
+
<https://play.google.com/store/apps/developer?id=ICN+Team>
### iOS
-Coming soon.
+Clone this distro
+
+```bash
+git clone https://github.com/icn-team/ios-sdk.git
+cd ios-sdk
+```
+Compile everything (dependencies and hICN modules)
+
+```bash
+make update
+make all
+```
+Compile everything with Qt (dependencies, hICN modules and Viper dependencies)
+
+```bash
+make update
+make all_qt
+```
### Windows
-Coming soon.
+Install vcpkg
+
+```bash
+git clone https://github.com/icn-team/windows-sdk
+.\windows-sdk\scripts\init.bat
+```
+
+
+```bash
+cd windows-sdk
+make all
+```
### Docker
-Several docker images are nightly built with the latest software for Ubuntu 18 LTS (amd64/arm64),
-and available on docker hub at <https://hub.docker.com/u/icnteam>.
+Several docker images are nightly built with the latest software for Ubuntu 18
+LTS (amd64/arm64), and available on docker hub at
+<https://hub.docker.com/u/icnteam>.
The following images are nightly built and maintained.
@@ -106,6 +166,8 @@ docker pull icnteam/vhttpproxy:amd64
docker pull icnteam/vhttpproxy:arm64
```
+Other Dockerfiles are included in the main git repo for development.
+
### Vagrant
Vagrant boxes for a virtual switch are available at
@@ -117,12 +179,21 @@ vagrant box add icnteam/vswitch
Supported providers are libvirt, vmware and virtualbox.
+## References
+
+Giovanna Carofiglio, Luca Muscariello, Jordan Augé, Michele Papalini, Mauro
+Sardara, and Alberto Compagno. 2019. Enabling ICN in the Internet Protocol:
+Analysis and Evaluation of the Hybrid-ICN Architecture. In Proceedings of the
+6th ACM Conference on Information-Centric Networking (ICN '19). Association for
+Computing Machinery, New York, NY, USA, 55–66.
+DOI: https://doi.org/10.1145/3357150.3357394
+
## License
This software is distributed under the following license:
```bash
-Copyright (c) 2017-2020 Cisco and/or its affiliates.
+Copyright (c) 2019-2022 Cisco and/or its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at:
diff --git a/docs/source/telemetry.md b/docs/source/telemetry.md
index 8887b8f1f..b4d538d76 100644
--- a/docs/source/telemetry.md
+++ b/docs/source/telemetry.md
@@ -31,22 +31,19 @@ sudo make install
hICN collectd plugins have been tested in:
-- Ubuntu 16.04 LTS (x86_64)
-- Ubuntu 18.04 LTS (x86_64)
-- Debian Stable/Testing
-- Red Hat Enterprise Linux 7
-- CentOS 7
+- Ubuntu 20.04 LTS
### Dependencies
Build dependencies:
-- VPP 20.01, Debian packages can be found on [packagecloud](https://packagecloud.io/fdio/release/install):
+VPP 22.02, Debian packages can be found on
+[packagecloud](https://packagecloud.io/fdio/release/install):
- vpp
- libvppinfra-dev
- vpp-dev
- hicn-plugin-dev
-- `collectd` and `collectd-dev`: `sudo apt install collectd collectd-dev`
+- `collectd` and `collectd-dev`: `sudo apt install collectd collectd-dev libyajl-dev`
## Getting started
@@ -62,14 +59,18 @@ Before running collectd, a vpp forwarder must be started. If the vpp-hicn plugin
is used, the hicn-plugin must be available in the vpp forwarder.
If you need the custom types that the two plugins define, they are present in
-`telemetry/custom_types.db`. It is useful if you are using InfluxDB as it requires
-the type database for multi-value metrics
-(see [CollectD protocol support in InfluxDB](https://docs.influxdata.com/influxdb/v1.7/supported_protocols/collectd/)).
+`telemetry/custom_types.db`. It is useful if you are using InfluxDB as it
+requires the type database for multi-value metrics (see [CollectD protocol
+support in
+InfluxDB](https://docs.influxdata.com/influxdb/v1.7/supported_protocols/collectd/)).
## Plugin options
`vpp` and `vpp-hicn` have the same two options:
-- `Verbose` enables additional statistics. You can check the sources to have an exact list of available metrics.
-- `Tag` tags the data with the given string. Useful for identifying the context in which the data was retrieved in InfluxDB for instance. If the tag value is `None`, no tag is applied.
+- `Verbose` enables additional statistics. You can check the sources to have an
+ exact list of available metrics.
+- `Tag` tags the data with the given string. Useful for identifying the context
+ in which the data was retrieved in InfluxDB for instance. If the tag value is
+ `None`, no tag is applied.
### Example: storing statistics from vpp and vpp-hicn
diff --git a/docs/source/transport.md b/docs/source/transport.md
index 3e7844ad5..c5250023a 100644
--- a/docs/source/transport.md
+++ b/docs/source/transport.md
@@ -1,38 +1,51 @@
-# Transport library
-
## Introduction
-This library provides transport services and socket API for applications willing to communicate
-using the hICN protocol stack.
+The transport library provides transport services and socket API for
+applications willing to communicate using the hICN protocol stack.
Overview:
- Implementation of the hICN core objects (interest, data, name..) exploiting
- the API provided by [libhicn](../lib).
-- Connectors for connecting the application to either the hicn-plugin or the
- hicn-light forwarder.
+ the API provided by [libhicn](./lib.md).
+- IO modules for seamlessly connecting the application to the hicn-plugin for [VPP](https://github.com/FDio/vpp) or the
+ [hicn-light](./hicn-light.md) forwarder.
- Transport protocols (RAAQM, CBR, RTC)
-- Transport services (authentication, integrity, segmentation, reassembly, naming)
+- Transport services (authentication, integrity, segmentation, reassembly,
+ naming)
- Interfaces for applications (from low-level interfaces for interest-data
interaction to high level interfaces for Application Data Unit interaction)
+
## Build dependencies
### Ubuntu
-- libparc
-- libmemif (linux only, if compiling with VPP support)
-- libasio
+```bash
+sudo apt install libasio-dev libconfig++-dev libssl-dev
+```
If you wish to use the library for connecting to the vpp hicn-plugin, you will
-need to also install vpp, the vpp libraries and the libmemif libraries:
+need to also install vpp and its libraries.
-- DEB packages:
- - vpp
- - vpp-lib
- - vpp-dev
+```bash
+# Prevent vpp to set sysctl
+export VPP_INSTALL_SKIP_SYSCTL=1
+VPP_VERSION=$(cat "${VERSION_PATH}" | grep VPP_DEFAULT_VERSION | cut -d ' ' -f 2 | tr -d '"' | grep -Po '\d\d.\d\d')
-You can get them either from from the vpp packages or the source code. Check
-the [VPP wiki](https://wiki.fd.io/view/VPP) for instructions.
+curl -s https://packagecloud.io/install/repositories/fdio/${VPP_VERSION//./}/script.deb.sh | bash
+curl -L https://packagecloud.io/fdio/${VPP_VERSION//./}/gpgkey | apt-key add -
+sed -E -i 's/(deb.*)(\[.*\])(.*)/\1\3/g' /etc/apt/sources.list.d/fdio_${VPP_VERSION//./}.list
+apt-get update
+
+apt-get install -y \
+ vpp-dev \
+ libvppinfra-dev \
+ vpp-plugin-core \
+ vpp \
+ libvppinfra
+```
+
+You can get them either from from the vpp packages or the source code. Check the
+[VPP wiki](https://wiki.fd.io/view/VPP) for instructions.
### macOS
@@ -40,31 +53,23 @@ We recommend to use [HomeBrew](https://brew.sh/) for installing the libasio
dependency:
```bash
-brew install asio
+brew install asio libconfig openssl@1.1
```
-Download, compile and install libparc:
-
-```bash
-git clone -b cframework/master https://gerrit.fd.io/r/cicn cframework && cd cframework
-mkdir -p libparc.build && cd libparc.build
-cmake ../libparc
-make
-make install
-```
+Since VPP does not support macOS, the IO module memif is not built.
-Libparc will be installed by default under `/usr/local/lib` and `/usr/local/include`.
-Since VPP does not support macOS, the hicn-plugin connector is not built.
## Build the library
-From the project root folder:
+The library is built by default from the main CMakeLists.txt.
+If you have all the dependencies installed, including [libhicn](./lib.md),
+you can also build libtransport alone:
```bash
cd libtransport
mkdir build && cd build
cmake ..
-make
+cmake --build .
```
### Compile options
@@ -75,11 +80,7 @@ The build process can be customized with the following options:
- `CMAKE_BUILD_TYPE`: The build configuration. Options: `Release`, `Debug`.
Default is `Release`.
- `ASIO_HOME`: The folder containing the libasio headers.
-- `LIBPARC_HOME`: The folder containing the libparc headers and libraries.
- `VPP_HOME`: The folder containing the installation of VPP.
-- `LIBMEMIF_HOME`: The folder containing the libmemif headers and libraries.
-- `BUILD_MEMIF_CONNECTOR`: On linux, set this value to `ON` for building the
- VPP connector.
An option can be set using cmake -D`OPTION`=`VALUE`.
@@ -88,5 +89,269 @@ An option can be set using cmake -D`OPTION`=`VALUE`.
For installing the library, from the cmake build folder:
```bash
-sudo make install
+cmake --build . -- install
+```
+
+
+## Usage
+
+Examples on how to use the library can be found in the apps folder of the project.
+In particular you can check the **hiperf** application, which demonstrates
+how to use the API to interact with the hicn transport, both for consumer and producer.
+
+### Configuration file
+
+The transport can be configured using a configuration file. There are two ways
+to tell libransport where to find the configuration file:
+
+- programmatically - you set the configuration file path in your application:
+```cpp
+// Set conf file path
+std::string conf_file = "/opt/hicn/etc/transport.config"
+// Parse config file
+transport::interface::global_config::parseConfigurationFile(conf_file);
+```
+
+- using the environment variable `TRANSPORT_CONFIG`:
+```bash
+export TRANSPORT_CONFIG=/opt/hicn/etc/transport.config
+./hiperf -C b001::1
+```
+
+Here is an example of configuration file:
+
+```
+// Configuration for io_module
+io_module = {
+ path = [];
+ name = "forwarder_module";
+};
+
+// Configuration for forwarder io_module
+forwarder = {
+ n_threads = 1;
+
+ connectors = {
+ c0 = {
+ /* local_address and local_port are optional */
+ local_address = "127.0.0.1";
+ local_port = 33436;
+ remote_address = "127.0.0.1";
+ remote_port = 33436;
+ }
+ };
+
+ listeners = {
+ l0 = {
+ local_address = "127.0.0.1";
+ local_port = 33437;
+ }
+ };
+};
+
+// Logging
+log = {
+ // Log level (INFO (0), WARNING (1), ERROR (2), FATAL (3))
+ minloglevel = 0;
+
+ // Verbosity level for debug logs
+ v= 2;
+
+ // Log to stderr
+ logtostderr = true;
+
+ // Get fancy colored logs
+ colorlogtostderr = true;
+
+ // Log messages above this level also to stderr
+ stderrthreshold = 2;
+
+ // Set log prefix for each line log
+ log_prefix = true;
+
+ // Log dir
+ log_dir = "/tmp";
+
+ // Log only specific modules.
+ // Example: "membuf=2,rtc=3"
+ vmodule = "";
+
+ // Max log size in MB
+ max_log_size = 10;
+
+ // Log rotation
+ stop_logging_if_full_disk = true;
+};
+```
+
+
+## Security
+
+hICN has built-in authentication and integrity features by either:
+* Cryptographically signing all packets using an asymmetric key (like RSA) or a
+ symmetric one (like HMAC). The latter requires that all parties have prior
+ access to the same key. Beware that this method is computationally expensive
+ and impacts max throughput and CPU usage.
+* Using manifests. Manifests are special packets that holds the digests of a
+ group of data packets. Only the manifest needs to be signed and authenticated;
+ other packets are authenticated simply by verifying that their digest is
+ present in a manifest.
+
+### Per-packet signatures
+
+To enable per-packet signature with asymmetric signing:
+* On the producer, disable manifests (which are ON by default):
+ ```cpp
+ producer_socket->setSocketOption(GeneralTransportOptions::MANIFEST_MAX_CAPACITY, 0u);
+ ```
+* On the producer, instantiate an `AsymmetricSigner` object by passing either an
+ asymmetric pair of keys as
+ [EVP_KEY](https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_new.html) object
+ or a keystore path and password as strings:
+ ```cpp
+ std::shared_ptr<Signer> signer = std::make_shared<AsymmetricSigner>("./rsa.p12", "hunter2");
+ ```
+* Pass the signer object to libtransport:
+ ```cpp
+ producer_socket->setSocketOption(GeneralTransportOptions::SIGNER, signer);
+ ```
+* On the consumer, instantiate an `AsymmetricVerifer` object by passing either a
+ certificate as a [X509](https://www.openssl.org/docs/man1.0.2/man3/x509.html)
+ object, an asymmetric public key as a
+ [EVP_KEY](https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_new.html) object
+ or a certificate path as a string:
+ ```cpp
+ std::shared_ptr<Verifier> verifier = std::make_shared<Verifier>("./rsa.crt");
+ ```
+* Pass the verifier object to libtransport:
+ ```cpp
+ consumer_socket->setSocketOption(GeneralTransportOptions::VERIFIER, verifier);
+ ```
+
+To enable per-packet signature with symmetric signing, follow the above steps
+replacing `AsymmetricSigner` with `SymmetricSigner` and `AsymmetricVerifer` with
+`SymmetricSigner`. A `SymmetricSigner` only has one constructor which expects a
+`CryptoSuite` and a passphrase. A `SymmetricVerifier` also has a single
+constructor which expects a passphrase:
+```cpp
+std::shared_ptr<Signer> signer = std::make_shared<SymmetricSigner>(CryptoSuite::HMAC_SHA256, "hunter2");
+std::shared_ptr<Verifier> verifier = std::make_shared<SymmetricVerifier>("hunter2");
+```
+
+Check [Supported crypto suites](#supported-crypto-suites) for the list of
+available suites.
+
+### Enabling manifests
+
+* Follow steps 2-5 in [Per-packet signatures](#per-packet-signatures).
+* By default, a manifest has a maximum capacity `C_max` of 30 packets. To change
+ this value:
+ ```cpp
+ producer_socket->setSocketOption(GeneralTransportOptions::MANIFEST_MAX_CAPACITY, 20u);
+ ```
+
+In the case of RTC, manifests are sent after the data they contain and on the
+consumer side, data packets are immediately forwarded to the application, *even
+if they weren't authenticated yet via a manifest*. This is to minimize latency.
+The digest of incoming data packets are kept in a buffer while waiting for
+manifests to arrive. When the buffer size goes above a threshold `T`, an alert
+is raised by the verifier object. That alert threshold is computed as follows:
+```
+T = manifest_factor_alert * C_max
+```
+
+The value of `C_max` is passed by the producer to the consumer at the start of
+the connection. `manifest_factor_alert` is a consumer socket option. It
+basically acts on the resilience of manifests against networks losses and
+reflects the application's tolerance to unverified packets: a higher value gives
+the transport the time needed to recover from several manifest losses but
+potentially allows a larger number of unverified packet to go the application
+before alerts are triggered. It is set to `20` by default and should always be
+`>= 1`. To change it:
+```cpp
+consumer_socket_->setSocketOption(GeneralTransportOptions::MANIFEST_FACTOR_ALERT, 10u);
+```
+
+The buffer does not keep unverified packets indefinitely. After a certain amount
+of packets have been received and processed (and were verified or not), older
+packets still unverified are flushed out. This is to prevent the buffer to grow
+uncontrollably and to raise alerts for packets that are not relevant to the
+application anymore. That threshold of relevance is computed as follows:
+```
+T = manifest_factor_relevant * C_max
+```
+
+`manifest_factor_relevant` is a consumer socket option. It is set to `100` by
+default. Its value must be set so that `manifest_factor_relevant >
+manifest_factor_alert >= 1`. If `manifest_factor_relevant <=
+manifest_factor_alert`, no alert will ever be raised. To change it:
+```cpp
+consumer_socket_->setSocketOption(GeneralTransportOptions::MANIFEST_FACTOR_RELEVANT, 200u);
+```
+
+### Handling authentication failures
+
+When a data packet fails authentication, or when the unverified buffer is full
+in the case of RTC, an alert is triggered by the verifier object. By default
+libtransport aborts the connection upon reception of that alert. You may want to
+intercept authentication failures in your application:
+* Define a callback with arguments an `uint32_t` integer, which will be set to
+ the suffix of the faulty packet, and a `auth::VerificationPolicy`, which will
+ be set to the action suggested by the verifier object. The callback must
+ return another `auth::VerificationPolicy` which will be the actual action
+ taken by libtransport:
+ ```cpp
+ auth::VerificationPolicy onAuthFailed(uint32_t suffix, auth::VerificationPolicy policy) {
+ std::cout << "auth failed for packet " << suffix << std::endl;
+ return auth::VerificationPolicy::ACCEPT;
+ }
+ ```
+* Give that callback to your `Verifier` object as well as a list of
+ `auth::VerificationPolicy` to intercept (if left empty, will be set by
+ default to `{ABORT, DROP}`):
+ ```cpp
+ verifier->setVerificationFailedCallback(&onAuthFailed, {
+ auth::VerificationPolicy::ABORT,
+ auth::VerificationPolicy::DROP,
+ auth::VerificationPolicy::UNKNOWN,
+ });
+ ```
+
+### Supported crypto suites
+
+The following `CryptoSuite` are supported by libtransport:
```
+ECDSA_BLAKE2B512
+ECDSA_BLAKE2S256
+ECDSA_SHA256
+ECDSA_SHA512
+RSA_BLAKE2B512
+RSA_BLAKE2S256
+RSA_SHA256
+RSA_SHA512
+HMAC_BLAKE2B512
+HMAC_BLAKE2S256
+HMAC_SHA256
+HMAC_SHA512
+DSA_BLAKE2B512
+DSA_BLAKE2S256
+DSA_SHA256
+DSA_SHA512
+```
+
+
+## Logging
+
+Internally libtransport uses glog as logging library. If you want to have a more
+verbose transport log when launching a test or an app, you can set environment
+variables in this way:
+
+```
+GLOG_v=4 hiperf -S b001::/64
+```
+
+For a more exhaustive list of options, please check the instructions in the glog
+[README](https://github.com/google/glog#setting-flags).
+
+Useful options include enabling logging *per module*. Also you can compile out
+useless messages in release builds.
diff --git a/docs/source/utils.md b/docs/source/utils.md
index 79ada8985..42e407ff0 100644
--- a/docs/source/utils.md
+++ b/docs/source/utils.md
@@ -19,7 +19,6 @@ Basic dependencies:
- OpenSSL
- pthreads
- libevent
-- libparc
- libhicntransport
## Executables
@@ -43,9 +42,6 @@ Options:
-l <lifetime> = data lifetime
-r = always reply with a reset flag (default false)
-t <ttl> = set ttl (default 64)
--V = verbose, prints statistics about the messagges sent and received (default false)
--D = dump, dumps sent and received packets (default false)
--q = quiet, no printing (default false)
-d = daemon mode
-H = help
```
@@ -75,9 +71,6 @@ Options:
-A = send always ack messages (default false)
-n <hicn_name> = hicn name (default b001::1)
-l <lifetime> = interest lifetime in milliseconds (default 500ms)
--V = verbose, prints statistics about the messagges sent and received (default false)
--D = dump, dumps sent and received packets (default false)
--q = quiet, no printing (default false)
-H = help
```
@@ -92,45 +85,59 @@ The command `hiperf` is a tool for performing network throughput measurements
with hicn. It can be executed as server or client using the following options:
```bash
+HIPERF - Instrumentation tool for performing active networkmeasurements with hICN
usage: hiperf [-S|-C] [options] [prefix|name]
SERVER OR CLIENT:
--D = Run as a daemon
--R = Run RTC protocol (client or server)
--f <filename> = Log file
+-D Run as a daemon
+-R Run RTC protocol (client or server)
+-f <filename> Log file
+-z <io_module> IO module to use. Default: hicnlightng_module
+-F <conf_file> Path to optional configuration file for libtransport
+-a Enables data packet aggregation. Works only in RTC mode
+-X <param> Set FEC params. Options are Rely_K#_N# or RS_K#_N#
SERVER SPECIFIC:
--A <content_size> = Size of the content to publish. This is not the size of the packet (see -s for it).
--s <packet_size> = Size of the payload of each data packet.
--r = Produce real content of <content_size> bytes
--m = Produce transport manifest
--l = Start producing content upon the reception of the first interest
--K <keystore_path> = Path of p12 file containing the crypto material used for signing packets
--k <passphrase> = String from which a 128-bit symmetric key will be derived for signing packets
--y <hash_algorithm> = Use the selected hash algorithm for calculating manifest digests
--p <password> = Password for p12 keystore
--x = Produce a content of <content_size>, then after downloading it produce a new content of <content_size> without resetting the suffix to 0.
--B <bitrate> = Bitrate for RTC producer, to be used with the -R option.
--I = Interactive mode, start/stop real time content production by pressing return. To be used with the -R option
--E = Enable encrypted communication. Requires the path to a p12 file containing the crypto material used for the TLS handshake
+-A <content_size> Sends an application data unit in bytes that is published once before exit
+-s <packet_size> Data packet payload size.
+-r Produce real content of <content_size> bytes
+-m <manifest_capacity> Produce transport manifest
+-l Start producing content upon the reception of the first interest
+-K <keystore_path> Path of p12 file containing the crypto material used for signing packets
+-k <passphrase> String from which a 128-bit symmetric key will be derived for signing packets
+-p <password> Password for p12 keystore
+-y <hash_algorithm> Use the selected hash algorithm for computing manifest digests (default: SHA256)
+-x Produces application data units of size <content_size> without resetting the name suffix to 0.
+-B <bitrate> RTC producer data bitrate, to be used with the -R option.
+-I Interactive mode, start/stop real time content production by pressing return. To be used with the -R option
+-T <filename> Trace based mode, hiperf takes as input a file with a trace. Each line of the file indicates the timestamp and the size of the packet to generate. To be used with the -R option. -B and -I will be ignored.
+-E Enable encrypted communication. Requires the path to a p12 file containing the crypto material used for the TLS handshake
+-G <port> Input stream from localhost at the specified port
CLIENT SPECIFIC:
--b <beta_parameter> = RAAQM beta parameter
--d <drop_factor_parameter> = RAAQM drop factor parameter
--L <interest lifetime> = Set interest lifetime.
--M <Download for real> = Store the content downloaded.
--W <window_size> = Use a fixed congestion window for retrieving the data.
--i <stats_interval> = Show the statistics every <stats_interval> milliseconds.
--v = Enable verification of received data
--c <certificate_path> = Path of the producer certificate to be used for verifying the origin of the packets received. Must be used with -v.
--k <passphrase> = String from which is derived the symmetric key used by the producer to sign packets and by the consumer to verify them. Must be used with -v.
--t = Test mode, check if the client is receiving the correct data. This is an RTC specific option, to be used with the -R (default false)
--P = Prefix of the producer where to do the handshake
+-b <beta_parameter> RAAQM beta parameter
+-d <drop_factor_parameter> RAAQM drop factor parameter
+-L <interest lifetime> Set interest lifetime.
+-u <delay> Set max lifetime of unverified packets.
+-M <input_buffer_size> Size of consumer input buffer. If 0, reassembly of packets will be disabled.
+-W <window_size> Use a fixed congestion window for retrieving the data.
+-i <stats_interval> Show the statistics every <stats_interval> milliseconds.
+-c <certificate_path> Path of the producer certificate to be used for verifying the origin of the packets received.
+-k <passphrase> String from which is derived the symmetric key used by the producer to sign packets and by the consumer to verify them.
+-t Test mode, check if the client is receiving the correct data. This is an RTC specific option, to be used with the -R (default: false)
+-P Prefix of the producer where to do the handshake
+-j <relay_name> Publish received content under the name relay_name.This is an RTC specific option, to be used with the -R (default: false)
+-g <port> Output stream to localhost at the specified port
+-e <strategy> Enance the network with a realiability strategy. Options 1: unreliable, 2: rtx only, 3: fec only, 4: delay based, 5: low rate, 6: low rate and best path 7: low rate and replication, 8: low rate and best path/replication(default: 2 = rtx only)
+-H Disable periodic print headers in stats report.
+-n <nb_iterations> Print the stats report <nb_iterations> times and exit.
+ This option limits the duration of the run to <nb_iterations> * <stats_interval> milliseconds.
```
Example:
```
-hiperf -S c001::/64
+hiperf -S b001::/64
+hiperf -C b001::
```
## Client/Server benchmarking using `hiperf`
@@ -161,8 +168,7 @@ apt-get install -y git \
build-essential \
libasio-dev \
libcurl4-openssl-dev \
- --no-install-recommends \
- libparc-dev
+ --no-install-recommends
mkdir hicn-suite && cd hicn-suite
git clone https://github.com/FDio/hicn.git hicn-src
mkdir hicn-build && cd hicn-build
@@ -289,8 +295,7 @@ apt-get install -y git \
vpp vpp-dev vpp-plugin-core libvppinfra \
libmemif libmemif-dev \
python3-ply \
- --no-install-recommends \
- libparc-dev
+ --no-install-recommends
mkdir hicn-suite && cd hicn-suite
git clone https://github.com/FDio/hicn.git hicn-src
mkdir hicn-build && cd hicn-build
diff --git a/docs/source/vpp-plugin.md b/docs/source/vpp-plugin.md
index 7f49cd8b9..b6b469494 100644
--- a/docs/source/vpp-plugin.md
+++ b/docs/source/vpp-plugin.md
@@ -22,7 +22,7 @@ mkdir -p build
cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/usr
make
-sudo make install
+sudo cmake --build . -- install
```
VPP source code - build type `RELEASE`:
@@ -32,7 +32,7 @@ mkdir -p build
cd build
cmake .. -DVPP_HOME=<vpp dir>/build-root/install-vpp-native/vpp -DCMAKE_INSTALL_PREFIX=<vpp src>/build-root/install-vpp-native/vpp
make
-sudo make install
+cmake --build . -- install
```
VPP source code - build type `DEBUG`:
@@ -42,7 +42,7 @@ mkdir -p build
cd build
cmake .. -DCMAKE_BUILD_TYPE=DEBUG -DVPP_HOME=<vpp dir>/build-root/install-vpp_debug-native/vpp -DCMAKE_INSTALL_PREFIX=<vpp src>/build-root/install-vpp_debug-native/vpp
make
-sudo make install
+cmake --build . -- install
```
CMAKE variables:
@@ -57,7 +57,7 @@ CMAKE variables:
Build dependencies:
-- VPP 20.01
+- VPP 22.02
- DEB packages (can be found <https://packagecloud.io/fdio/release/install):>
- vpp
- libvppinfra-dev
@@ -65,11 +65,11 @@ Build dependencies:
Runtime dependencies:
-- VPP 20.01
+- VPP 22.02
- DEB packages (can be found <https://packagecloud.io/fdio/release/install):>
- vpp
- vpp-plugin-core
- - vpp-plugin-dpdk (only to use DPDK compatible nics)
+ - vpp-plugin-dpdk (optional - only to use DPDK compatible nics)
Hardware support (not mandatory):
@@ -91,7 +91,7 @@ Detailed information for configuring VPP can be found at
### Setup the host for VPP
-Hugepages must be enabled in the system.
+It is preferable to have hugepages enabled in the system, although it is not a requirement:
```bash
sudo sysctl -w vm.nr_hugepages=1024
@@ -163,7 +163,7 @@ interface.
VPP can be started as a process or a service:
-Start VPP as a service in Ubuntu 16.04+:
+Start VPP as a service in Ubuntu 20.04+:
```bash
sudo systemctl start vpp
```
@@ -299,22 +299,22 @@ vpp# set interface ip address TenGigabitEtherneta/0/1 2001::3/64
vpp# set interface state TenGigabitEtherneta/0/1 up
```
-Once the two forwarder are started, run the `ping_server` application on the
+Once the two forwarder are started, run the `hicn-ping-server` application on the
host where the forwarder B is running:
```bash
-sudo ping_server -n b002::1
+sudo hicn-ping-server -n b002::1/128 -z memif_module
```
-Then `ping_client` on the host where forwarder B is running:
+Then `hicn-ping-client` on the host where forwarder B is running:
```bash
-sudo ping_client -n b002::1
+sudo hicn-ping-client -n b002::1 -z memif_module
```
### Example: packet generator
-The packet generator can be used to test the performace of the hICN plugin, as
+The packet generator can be used to test the performance of the hICN plugin, as
well as a tool to inject packet in a forwarder or network for other test use
cases It is made of two entities, a client that inject interest into a vpp
forwarder and a server that replies to any interest with the corresponding
diff --git a/extras/CMakeLists.txt b/extras/CMakeLists.txt
index 4cda43992..31628cba3 100644
--- a/extras/CMakeLists.txt
+++ b/extras/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -17,13 +17,10 @@ list(APPEND CMAKE_MODULE_PATH
${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules
)
+include("${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake")
set (DESTDIR ${CMAKE_BINARY_DIR}/extras-root)
-# add_subdirectory(router-plugin)
add_subdirectory(libmemif)
-# add_subdirectory(libyang)
-# add_subdirectory(sysrepo)
-
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
include(Packager)
diff --git a/extras/libmemif/CMakeLists.txt b/extras/libmemif/CMakeLists.txt
deleted file mode 100644
index e407078e4..000000000
--- a/extras/libmemif/CMakeLists.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (c) 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.10)
-project(libmemif)
-
-list(APPEND MODULE_PATH
- ${CMAKE_MODULE_PATH}
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules
-)
-
-string(REPLACE ";" "|" MODULE_PATH "${MODULE_PATH}")
-
-include(ExternalProject)
-
-ExternalProject_Add(libmemif
- GIT_REPOSITORY https://github.com/FDio/vpp.git
- GIT_TAG v21.01
- GIT_SHALLOW TRUE
- PREFIX ${CMAKE_CURRENT_BINARY_DIR}/libmemif
- PATCH_COMMAND bash -c "cp ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists1.patch ./extras/libmemif/CMakeLists.txt && cp ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists2.patch ./extras/libmemif/src/CMakeLists.txt"
- # Use the alternate list separator
- # (https://cmake.org/cmake/help/latest/manual/cmake-language.7.html#lists)
- LIST_SEPARATOR |
- CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_MODULE_PATH=${MODULE_PATH}
- SOURCE_SUBDIR ./extras/libmemif
- BUILD_COMMAND ${CMAKE_COMMAND} --build . -- package
-)
-
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
-endif()
diff --git a/extras/libmemif/CMakeLists1.patch b/extras/libmemif/CMakeLists1.patch
deleted file mode 100644
index adf41a417..000000000
--- a/extras/libmemif/CMakeLists1.patch
+++ /dev/null
@@ -1,75 +0,0 @@
-# Copyright (c) 2017 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.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)
-
-project(memif)
-set(CMAKE_C_STANDARD 11)
-
-list(APPEND CMAKE_MODULE_PATH
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake
-)
-
-include(CheckCCompilerFlag)
-include(CheckFunctionExists)
-
-execute_process(
- COMMAND find ${VPP_SRC} -type d -name "cmake"
- OUTPUT_VARIABLE CMAKE_DEPS_FOLDER
- OUTPUT_STRIP_TRAILING_WHITESPACE
-)
-include(BuildMacros)
-
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
-endif ()
-
-set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -DMEMIF_DBG -DICMP_DBG")
-set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
-set(CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib)
-set(CMAKE_INSTALL_MESSAGE NEVER)
-
-find_package(Threads REQUIRED)
-include_directories(${CMAKE_THREADS_INCLUDE_DIRS})
-
-check_function_exists(memfd_create HAVE_MEMFD_CREATE)
-if(${HAVE_MEMFD_CREATE})
- add_definitions(-DHAVE_MEMFD_CREATE)
-endif()
-
-include_directories(src)
-set(LIBMEMIF memif)
-set(COMPONENT libmemif)
-set(LIBMEMIF_SHARED ${LIBMEMIF}.shared)
-
-set(LIBMEMIF_INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR}
- "" CACHE INTERNAL
- "" FORCE
-)
-
-set(LIBMEMIF_LIBRARIES
- ${LIBMEMIF_SHARED}
- "" CACHE INTERNAL
- "" FORCE
-)
-
-include (Packaging)
-
-add_subdirectory(src)
-
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
-endif() \ No newline at end of file
diff --git a/extras/libmemif/CMakeLists2.patch b/extras/libmemif/CMakeLists2.patch
deleted file mode 100644
index 1a02cd725..000000000
--- a/extras/libmemif/CMakeLists2.patch
+++ /dev/null
@@ -1,44 +0,0 @@
-# Copyright (c) 2017 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.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)
-
-set(HEADERS_DIR ${CMAKE_CURRENT_SOURCE_DIR})
-
-list(APPEND MEMIF_HEADERS
- libmemif.h
- memif.h
-)
-
-list(APPEND MEMIF_PRIVATE_HEADERS
- memif_private.h
- socket.h
-)
-
-list(APPEND MEMIF_SOURCES
- main.c
- socket.c
-)
-
-include_directories(${HEADERS_DIR})
-
-build_library(${LIBMEMIF}
- SHARED
- SOURCES ${MEMIF_SOURCES}
- INSTALL_HEADERS ${MEMIF_HEADERS}
- LINK_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}
- HEADER_ROOT_DIR memif
- COMPONENT ${COMPONENT}
-)
-
-remove_flag_from_target(${LIBMEMIF_SHARED} -Werror) \ No newline at end of file
diff --git a/extras/libmemif/cmake/Modules/Packaging.cmake b/extras/libmemif/cmake/Modules/Packaging.cmake
deleted file mode 100644
index 2b0f54200..000000000
--- a/extras/libmemif/cmake/Modules/Packaging.cmake
+++ /dev/null
@@ -1,44 +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.
-
-######################
-# Packages section
-######################
-
-set(${COMPONENT}_DESCRIPTION
- "Libmemif, shared memory interface"
- CACHE STRING "Description for deb/rpm package."
-)
-
-set(${COMPONENT}_DEB_DEPENDENCIES
- "" CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${COMPONENT}_RPM_DEPENDENCIES
- "" CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${COMPONENT}-dev_DESCRIPTION
- "Libmemif, shared memory interface header files"
- CACHE STRING "Description for deb/rpm package."
-)
-
-set(${COMPONENT}-dev_DEB_DEPENDENCIES
- "${COMPONENT} (>= stable_version)"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${COMPONENT}-dev_RPM_DEPENDENCIES
- "${COMPONENT} >= stable_version"
- CACHE STRING "Dependencies for deb/rpm package."
-)
diff --git a/extras/libyang/CMakeLists.txt b/extras/libyang/CMakeLists.txt
deleted file mode 100644
index 1956d185a..000000000
--- a/extras/libyang/CMakeLists.txt
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright (c) 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.10)
-project(libyang)
-
-list(APPEND MODULE_PATH
- ${CMAKE_MODULE_PATH}
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules
-)
-
-string(REPLACE ";" "|" MODULE_PATH "${MODULE_PATH}")
-
-include(ExternalProject)
-
-ExternalProject_Add(libyang
- GIT_REPOSITORY https://github.com/CESNET/libyang.git
- GIT_TAG devel
- GIT_SHALLOW TRUE
- PREFIX ${CMAKE_CURRENT_BINARY_DIR}/libyang
- PATCH_COMMAND git apply ${CMAKE_CURRENT_SOURCE_DIR}/libyang.patch
- # Use the alternate list separator
- # (https://cmake.org/cmake/help/latest/manual/cmake-language.7.html#lists)
- LIST_SEPARATOR |
- CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_MODULE_PATH=${MODULE_PATH}
- BUILD_COMMAND make package
- INSTALL_COMMAND make DESTDIR=${DESTDIR} install
-)
-
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
-endif() \ No newline at end of file
diff --git a/extras/libyang/cmake/Modules/Packaging.cmake b/extras/libyang/cmake/Modules/Packaging.cmake
deleted file mode 100644
index 853b18e58..000000000
--- a/extras/libyang/cmake/Modules/Packaging.cmake
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Generate DEB / RPM packages
-
-######################
-# Packages section
-######################
-
-set(libyang_DESCRIPTION
- "libyang is a YANG data modelling language parser and toolkit written (and providing API) in C."
- CACHE STRING "Description for deb/rpm package."
-)
-
-set(libyang_DEB_DEPENDENCIES
- "libpcre3 (>= 2:8.38-3.1)"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(libyang_RPM_DEPENDENCIES
- "pcre >= 8.32-17"
- CACHE STRING "Dependencies for deb/rpm package."
-) \ No newline at end of file
diff --git a/extras/libyang/libyang.patch b/extras/libyang/libyang.patch
deleted file mode 100644
index ac6a63746..000000000
--- a/extras/libyang/libyang.patch
+++ /dev/null
@@ -1,50 +0,0 @@
-diff --git a/CMakeLists.txt b/CMakeLists.txt
-index 3e0fe79..037d60b 100644
---- a/CMakeLists.txt
-+++ b/CMakeLists.txt
-@@ -317,14 +317,14 @@ find_package(PCRE REQUIRED)
- include_directories(${PCRE_INCLUDE_DIRS})
- target_link_libraries(yang ${PCRE_LIBRARIES})
-
--install(TARGETS yang DESTINATION ${CMAKE_INSTALL_LIBDIR})
--install(FILES ${headers} ${PROJECT_BINARY_DIR}/src/libyang.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libyang)
-+install(TARGETS yang DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libyang)
-+install(FILES ${headers} ${PROJECT_BINARY_DIR}/src/libyang.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libyang COMPONENT libyang)
-
- find_package(PkgConfig)
- if(PKG_CONFIG_FOUND)
- # generate and install pkg-config file
- configure_file("libyang.pc.in" "libyang.pc" @ONLY)
-- install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libyang.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
-+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libyang.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig" COMPONENT libyang)
- # check that pkg-config includes the used path
- execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable pc_path pkg-config RESULT_VARIABLE RETURN OUTPUT_VARIABLE PC_PATH ERROR_QUIET)
- if(RETURN EQUAL 0)
-@@ -410,14 +410,14 @@ configure_file(${PROJECT_SOURCE_DIR}/src/plugin_config.h.in ${PROJECT_BINARY_DIR
- # yanglint
- add_executable(yanglint ${lintsrc})
- target_link_libraries(yanglint yang)
--install(TARGETS yanglint DESTINATION ${CMAKE_INSTALL_BINDIR})
--install(FILES ${PROJECT_SOURCE_DIR}/tools/lint/yanglint.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
-+install(TARGETS yanglint DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT libyang)
-+install(FILES ${PROJECT_SOURCE_DIR}/tools/lint/yanglint.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 COMPONENT libyang)
-
- #yangre
- add_executable(yangre ${resrc})
- target_link_libraries(yangre yang)
--install(TARGETS yangre DESTINATION ${CMAKE_INSTALL_BINDIR})
--install(FILES ${PROJECT_SOURCE_DIR}/tools/re/yangre.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
-+install(TARGETS yangre DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT libyang)
-+install(FILES ${PROJECT_SOURCE_DIR}/tools/re/yangre.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 COMPONENT libyang)
-
- # yang2yin
- add_executable(yang2yin ${yang2yinsrc})
-@@ -446,3 +446,8 @@ endif(ENABLE_BUILD_FUZZ_TARGETS)
- if(GEN_LANGUAGE_BINDINGS AND GEN_CPP_BINDINGS)
- add_subdirectory(swig)
- endif()
-+
-+
-+include(Packaging)
-+include(Packager)
-+make_packages()
diff --git a/extras/packethicn/CMakeLists.txt b/extras/packethicn/CMakeLists.txt
index cb168ae1f..a4615708a 100644
--- a/extras/packethicn/CMakeLists.txt
+++ b/extras/packethicn/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,19 +11,39 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-cmake_minimum_required(VERSION 3.5)
+##############################################################
+# Project and cmake version
+##############################################################
+cmake_minimum_required(VERSION 3.10)
cmake_policy(SET CMP0048 NEW)
-
project(packethicn VERSION 0.0.1 DESCRIPTION "hICN protocol plugin" LANGUAGES C)
+
+##############################################################
+# Cmake modules
+##############################################################
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/Modules
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules
)
+
+##############################################################
+# Naming
+##############################################################
set(PACKETHICN packethicn)
+
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../versions.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
+
+
+##############################################################
+# Dependencies and third party libs
+##############################################################
if(APPLE)
find_package(Wireshark CONFIG REQUIRED
PATHS /usr/local/opt/wireshark/lib/wireshark/cmake/ /usr/local/Cellar/wireshark/*/lib/wireshark/cmake
@@ -35,8 +55,21 @@ endif()
MATH(EXPR Wireshark_PATCH_NEXT_VERSION "${Wireshark_PATCH_VERSION}+1")
set(Wireshark_NEXT_VERSION ${Wireshark_MAJOR_VERSION}.${Wireshark_MINOR_VERSION}.${Wireshark_PATCH_NEXT_VERSION})
+
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- find_package(Libhicn REQUIRED)
+ include(CommonSetup)
+ find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
+
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
+
+ list(APPEND HICN_LIBRARIES hicn::hicn.${LIBTYPE})
else()
if(DISABLE_SHARED_LIBRARIES)
if(WIN32)
@@ -55,39 +88,56 @@ else()
endif()
endif()
+
+##############################################################
+# Check if wiresharks supports plugins
+##############################################################
if(NOT Wireshark_PLUGINS_ENABLED)
message(FATAL_ERROR "Wireshark was compiled without support for plugins")
endif()
+
+##############################################################
+# Compilaer flags
+##############################################################
set(CMAKE_C_VISIBILITY_PRESET hidden)
-if (CMAKE_COMPILER_IS_GNUCC)
- set(CMAKE_C_FLAGS "-Wall -Wextra ${CMAKE_C_FLAGS}")
-endif()
+
+##############################################################
+# Compiler definitions
+##############################################################
set(COMPILER_DEFINITIONS -DVERSION=\"${PROJECT_VERSION}\")
+
+##############################################################
+# Sources
+##############################################################
set(SOURCE_FILES
packet-hicn.c
)
+
+##############################################################
+# Include dirs
+##############################################################
list(APPEND PACKETHICN_INCLUDE_DIRS
${HICN_INCLUDE_DIRS}
)
+
+##############################################################
+# Libraries
+##############################################################
list(APPEND LIBRARIES
${HICN_LIBRARIES}
epan
)
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- set(LIBHICN hicn CACHE INTERNAL "" FORCE)
-endif()
-
-include(Packaging)
-include(BuildMacros)
+##############################################################
+# Build library
+##############################################################
build_library(${PACKETHICN}
- MODULE
SOURCES ${SOURCE_FILES}
LINK_LIBRARIES ${LIBRARIES}
DEPENDS ${DEPENDENCIES}
@@ -95,10 +145,12 @@ build_library(${PACKETHICN}
INCLUDE_DIRS ${PACKETHICN_INCLUDE_DIRS}
INSTALL_FULL_PATH_DIR ${Wireshark_PLUGIN_INSTALL_DIR}/epan
DEFINITIONS ${COMPILER_DEFINITIONS}
- EMPTY_PREFIX true
)
+
+##############################################################
+# Make package if needed
+##############################################################
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
make_packages()
endif() \ No newline at end of file
diff --git a/extras/packethicn/cmake/Modules/Packaging.cmake b/extras/packethicn/cmake/packaging.cmake
index 5bea05c3c..b7a7f4552 100644
--- a/extras/packethicn/cmake/Modules/Packaging.cmake
+++ b/extras/packethicn/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -21,11 +21,11 @@ set(${PACKETHICN}_DESCRIPTION
)
set(${PACKETHICN}_DEB_DEPENDENCIES
- "lib${LIBHICN} (>= stable_version), wireshark (>= ${Wireshark_VERSION}), wireshark (<< ${Wireshark_NEXT_VERSION})"
+ "lib${LIBHICN} (= stable_version), wireshark (>= ${Wireshark_VERSION}), wireshark (<< ${Wireshark_NEXT_VERSION})"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${PACKETHICN}_RPM_DEPENDENCIES
- "lib${LIBHICN} >= stable_version, wireshark >= ${Wireshark_VERSION}, wireshark < ${Wireshark_NEXT_VERSION}"
+ "lib${LIBHICN} = stable_version, wireshark >= ${Wireshark_VERSION}, wireshark < ${Wireshark_NEXT_VERSION}"
CACHE STRING "Dependencies for deb/rpm package."
) \ No newline at end of file
diff --git a/extras/packethicn/packet-hicn.c b/extras/packethicn/packet-hicn.c
index c17252bb7..87466fdbf 100644
--- a/extras/packethicn/packet-hicn.c
+++ b/extras/packethicn/packet-hicn.c
@@ -17,11 +17,11 @@
#include <gmodule.h>
#define WS_BUILD_DLL
-#include "ws_symbol_export.h"
#include "config.h"
+#include "ws_symbol_export.h"
-#include "epan/proto.h"
#include "epan/etypes.h"
+#include "epan/proto.h"
#include <hicn/hicn.h>
@@ -36,14 +36,14 @@
/* TCP-HICN flags */
#define FLAGS_BITS_LEN 8
#define FLAGS_MASK 0xFF
-#define TH_FIN 0x01
-#define TH_SYN 0x02
-#define TH_RST 0x04
-#define TH_ACK 0x10
-#define TH_CWR 0x80
-#define TH_ID 0x40
-#define TH_MAN 0x20
-#define TH_SIG 0x08
+#define TH_FIN 0x01
+#define TH_SYN 0x02
+#define TH_RST 0x04
+#define TH_ACK 0x10
+#define TH_CWR 0x80
+#define TH_ID 0x40
+#define TH_MAN 0x20
+#define TH_SIG 0x08
#define HICN_PORT 9695
@@ -84,7 +84,6 @@ static gint ett_hicn_l3 = -1;
static gint ett_hicn_l4 = -1;
static gint ett_hicn_l4_flags = -1;
-
static uint8_t *_p_hdr = NULL;
bool is_interest(const hicn_header_t *header) {
@@ -97,39 +96,38 @@ bool is_interest(const hicn_header_t *header) {
// TODO: HANDLE ERRORS
-hicn_header_t *get_header(tvbuff_t *tvb, const gint offset, const gint length){
+hicn_header_t *get_header(tvbuff_t *tvb, const gint offset, const gint length) {
tvb_ensure_bytes_exist(tvb, offset, length);
- hicn_header_t *pkt_hdr = (hicn_header_t *) tvb_get_ptr(tvb, offset, length);
- _p_hdr = (uint8_t *) pkt_hdr;
+ hicn_header_t *pkt_hdr = (hicn_header_t *)tvb_get_ptr(tvb, offset, length);
+ _p_hdr = (uint8_t *)pkt_hdr;
return pkt_hdr;
}
-uint32_t get_offset(uint8_t *data_addr){
- return data_addr - _p_hdr;
-}
+uint32_t get_offset(uint8_t *data_addr) { return data_addr - _p_hdr; }
-static int
-dissect_hicn(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
-{
+static int dissect_hicn(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
+ void *data _U_) {
gint i = 0;
guint bpos;
hicn_header_t *pkt_hdr = get_header(tvb, 0, HICN_V6_TCP_HDRLEN);
wmem_strbuf_t *flags_strbuf = wmem_strbuf_new_label(wmem_packet_scope());
- static const gchar *flags[] = {"_FIN", "_SYN", "_RST", "SIG", "_ACK", "MAN", "ID", "_CWR"};
+ static const gchar *flags[] = {"_FIN", "_SYN", "_RST", "SIG",
+ "_ACK", "MAN", "ID", "_CWR"};
wmem_strbuf_append(flags_strbuf, "<None>");
- uint32_t flags_offset = get_offset((uint8_t *) &(pkt_hdr->v6.tcp.flags));
+ uint32_t flags_offset = get_offset((uint8_t *)&(pkt_hdr->v6.tcp.flags));
gboolean first_flag = TRUE;
- for(i=0; i<9; i++) {
+ for (i = 0; i < 9; i++) {
bpos = 1 << i;
- if(pkt_hdr->v6.tcp.flags & bpos) {
- if(first_flag) {
+ if (pkt_hdr->v6.tcp.flags & bpos) {
+ if (first_flag) {
wmem_strbuf_truncate(flags_strbuf, 0);
}
- wmem_strbuf_append_printf(flags_strbuf, "%s%s", first_flag ? "" : ", ", flags[i]);
+ wmem_strbuf_append_printf(flags_strbuf, "%s%s", first_flag ? "" : ", ",
+ flags[i]);
first_flag = FALSE;
}
}
@@ -138,99 +136,176 @@ dissect_hicn(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_
col_set_str(pinfo->cinfo, COL_PROTOCOL, "HICN");
col_clear(pinfo->cinfo, COL_INFO);
- proto_item *ti = proto_tree_add_item(tree, proto_hicn, tvb, 0, HICN_V6_TCP_HDRLEN, ENC_NA);
+ proto_item *ti =
+ proto_tree_add_item(tree, proto_hicn, tvb, 0, HICN_V6_TCP_HDRLEN, ENC_NA);
proto_tree *hicn_tree = proto_item_add_subtree(ti, ett_hicn);
// L3
proto_item *ti_l3;
- proto_tree *hicn_l3_tree = proto_tree_add_subtree(hicn_tree, tvb, 0, IPV6_HDRLEN, ett_hicn_l3, &ti_l3, "HICN Layer 3");
+ proto_tree *hicn_l3_tree = proto_tree_add_subtree(
+ hicn_tree, tvb, 0, IPV6_HDRLEN, ett_hicn_l3, &ti_l3, "HICN Layer 3");
- if(is_interest(pkt_hdr)){
+ if (is_interest(pkt_hdr)) {
proto_item_append_text(ti, ", Interest Packet");
col_set_str(pinfo->cinfo, COL_INFO, "Interest Packet");
- proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_src, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.ip.saddr)), sizeof(pkt_hdr->v6.ip.saddr), ENC_BIG_ENDIAN);
- proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_dst_interest, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.ip.daddr)), sizeof(pkt_hdr->v6.ip.daddr), ENC_BIG_ENDIAN);
+ proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_src, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.ip.saddr)),
+ sizeof(pkt_hdr->v6.ip.saddr), ENC_BIG_ENDIAN);
+ proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_dst_interest, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.ip.daddr)),
+ sizeof(pkt_hdr->v6.ip.daddr), ENC_BIG_ENDIAN);
} else {
// TODO: NEW LABEL FOR NACKS
proto_item_append_text(ti, ", Data Packet");
col_set_str(pinfo->cinfo, COL_INFO, "Data Packet");
- proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_src_data, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.ip.saddr)), sizeof(pkt_hdr->v6.ip.saddr), ENC_BIG_ENDIAN);
- proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_dst, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.ip.daddr)), sizeof(pkt_hdr->v6.ip.daddr), ENC_BIG_ENDIAN);
+ proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_src_data, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.ip.saddr)),
+ sizeof(pkt_hdr->v6.ip.saddr), ENC_BIG_ENDIAN);
+ proto_tree_add_item(hicn_l3_tree, hf_hicn_ipv6_dst, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.ip.daddr)),
+ sizeof(pkt_hdr->v6.ip.daddr), ENC_BIG_ENDIAN);
}
// L4
proto_item *ti_l4;
- proto_tree *hicn_l4_tree = proto_tree_add_subtree(hicn_tree, tvb, IPV6_HDRLEN, TCP_HDRLEN, ett_hicn_l4, &ti_l4, "HICN Layer 4");
-
- proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_namesuffix, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.tcp.name_suffix)), sizeof(pkt_hdr->v6.tcp.name_suffix), ENC_BIG_ENDIAN);
- proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_pathlabel, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.tcp.pathlabel))+PATHLABEL_PAD_LEN, sizeof(pkt_hdr->v6.tcp.pathlabel), ENC_BIG_ENDIAN);
- proto_item *ti_l4_ts = proto_tree_add_bits_item(hicn_l4_tree, hf_hicn_tcp_timescale, tvb,
- get_offset((uint8_t *) &(pkt_hdr->v6.tcp.data_offset_and_reserved))*8 + TIMESCALE_BITS_OFFSET, TIMESCALE_BITS_LENGTH, ENC_BIG_ENDIAN);
- proto_item_append_text(ti_l4_ts, " (Lifetime scaling factor: %dx)", pkt_hdr->v6.tcp.timescale+1);
- proto_item *hicn_l4_flags_tree = proto_tree_add_uint_format_value(hicn_l4_tree, hf_hicn_tcp_flags, tvb,
- get_offset((uint8_t *) &(pkt_hdr->v6.tcp.flags)), 1, pkt_hdr->v6.tcp.flags, "0x%02x (%s)", pkt_hdr->v6.tcp.flags, wmem_strbuf_get_str(flags_strbuf)
- );
- proto_tree *field_tree = proto_item_add_subtree(hicn_l4_flags_tree, ett_hicn_l4_flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_cwr, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_id, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_man, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_ack, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_sig, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_rst, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_syn, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_fin, tvb, flags_offset, 1, pkt_hdr->v6.tcp.flags);
- proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_ldr, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.tcp.ldr)), sizeof(pkt_hdr->v6.tcp.ldr), ENC_BIG_ENDIAN);
- proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_csum, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.tcp.csum)), sizeof(pkt_hdr->v6.tcp.ldr), ENC_BIG_ENDIAN);
- proto_item *ti_l4_lt = proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_lifetime, tvb, get_offset((uint8_t *) &(pkt_hdr->v6.tcp.lifetime)), sizeof(pkt_hdr->v6.tcp.ldr), ENC_BIG_ENDIAN);
+ proto_tree *hicn_l4_tree =
+ proto_tree_add_subtree(hicn_tree, tvb, IPV6_HDRLEN, TCP_HDRLEN,
+ ett_hicn_l4, &ti_l4, "HICN Layer 4");
+
+ proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_namesuffix, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.tcp.name_suffix)),
+ sizeof(pkt_hdr->v6.tcp.name_suffix), ENC_BIG_ENDIAN);
+ proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_pathlabel, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.tcp.pathlabel)) +
+ PATHLABEL_PAD_LEN,
+ sizeof(pkt_hdr->v6.tcp.pathlabel), ENC_BIG_ENDIAN);
+ proto_item *ti_l4_ts = proto_tree_add_bits_item(
+ hicn_l4_tree, hf_hicn_tcp_timescale, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.tcp.data_offset_and_reserved)) * 8 +
+ TIMESCALE_BITS_OFFSET,
+ TIMESCALE_BITS_LENGTH, ENC_BIG_ENDIAN);
+ proto_item_append_text(ti_l4_ts, " (Lifetime scaling factor: %dx)",
+ pkt_hdr->v6.tcp.timescale + 1);
+ proto_item *hicn_l4_flags_tree = proto_tree_add_uint_format_value(
+ hicn_l4_tree, hf_hicn_tcp_flags, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.tcp.flags)), 1, pkt_hdr->v6.tcp.flags,
+ "0x%02x (%s)", pkt_hdr->v6.tcp.flags, wmem_strbuf_get_str(flags_strbuf));
+ proto_tree *field_tree =
+ proto_item_add_subtree(hicn_l4_flags_tree, ett_hicn_l4_flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_cwr, tvb, flags_offset,
+ 1, pkt_hdr->v6.tcp.flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_id, tvb, flags_offset, 1,
+ pkt_hdr->v6.tcp.flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_man, tvb, flags_offset,
+ 1, pkt_hdr->v6.tcp.flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_ack, tvb, flags_offset,
+ 1, pkt_hdr->v6.tcp.flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_sig, tvb, flags_offset,
+ 1, pkt_hdr->v6.tcp.flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_rst, tvb, flags_offset,
+ 1, pkt_hdr->v6.tcp.flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_syn, tvb, flags_offset,
+ 1, pkt_hdr->v6.tcp.flags);
+ proto_tree_add_boolean(field_tree, hf_hicn_tcp_flags_fin, tvb, flags_offset,
+ 1, pkt_hdr->v6.tcp.flags);
+ proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_ldr, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.tcp.ldr)),
+ sizeof(pkt_hdr->v6.tcp.ldr), ENC_BIG_ENDIAN);
+ proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_csum, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.tcp.csum)),
+ sizeof(pkt_hdr->v6.tcp.ldr), ENC_BIG_ENDIAN);
+ proto_item *ti_l4_lt =
+ proto_tree_add_item(hicn_l4_tree, hf_hicn_tcp_lifetime, tvb,
+ get_offset((uint8_t *)&(pkt_hdr->v6.tcp.lifetime)),
+ sizeof(pkt_hdr->v6.tcp.ldr), ENC_BIG_ENDIAN);
proto_item_append_text(ti_l4_lt, " milliseconds");
dissector_handle_t data_handle = find_dissector("data");
- call_dissector(data_handle, tvb_new_subset_remaining(tvb, HICN_V6_TCP_HDRLEN), pinfo, tree);
+ call_dissector(data_handle, tvb_new_subset_remaining(tvb, HICN_V6_TCP_HDRLEN),
+ pinfo, tree);
return tvb_captured_length(tvb);
}
-static void
-proto_register_hicn(void)
-{
+static void proto_register_hicn(void) {
static hf_register_info hf[] = {
- { &hf_hicn_ipv6_src, { "Source Address", "hicn.l3.src", FT_IPv6, BASE_NONE, NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_ipv6_src_data, { "Name Prefix", "hicn.l3.src", FT_IPv6, BASE_NONE, NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_ipv6_dst, { "Destination Address", "hicn.l3.dst", FT_IPv6, BASE_NONE, NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_ipv6_dst_interest, { "Name Prefix", "hicn.l3.dst", FT_IPv6, BASE_NONE, NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_namesuffix, { "Name Suffix", "hicn.l4.namesuffix", FT_UINT32, BASE_HEX_DEC , NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_pathlabel, { "Path Label", "hicn.l4.pathlabel", FT_UINT8, BASE_HEX_DEC , NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_hdrlen_timescale, { "Header length and Timescale", "hicn.l4.hdrlen_ts", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_hdrlen, { "Header length", "hicn.l4.hdrlen", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_timescale, { "Timescale", "hicn.l4.timescale", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_flags, { "Flags", "hicn.l4.flags", FT_UINT8, BASE_HEX, NULL, FLAGS_MASK, NULL, HFILL }},
- { &hf_hicn_tcp_flags_cwr, { "_CWR", "hicn.l4.flags.cwr", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset), TH_CWR, NULL, HFILL }},
- { &hf_hicn_tcp_flags_id, { "ID", "hicn.l4.flags.id", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset),TH_ID, NULL, HFILL }},
- { &hf_hicn_tcp_flags_man, { "MAN", "hicn.l4.flags.man", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset), TH_MAN, NULL, HFILL }},
- { &hf_hicn_tcp_flags_ack, { "_ACK", "hicn.l4.flags.ack", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset), TH_ACK, NULL, HFILL }},
- { &hf_hicn_tcp_flags_sig, { "SIG", "hicn.l4.flags.sig", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset), TH_SIG, NULL, HFILL }},
- { &hf_hicn_tcp_flags_rst, { "_RST", "hicn.l4.flags.reset", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset), TH_RST, NULL, HFILL }},
- { &hf_hicn_tcp_flags_syn, { "_SYN", "hicn.l4.flags.syn", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset), TH_SYN, NULL, HFILL }},
- { &hf_hicn_tcp_flags_fin, { "_FIN", "hicn.l4.flags.fin", FT_BOOLEAN, FLAGS_BITS_LEN, TFS(&tfs_set_notset), TH_FIN, NULL, HFILL }},
- { &hf_hicn_tcp_ldr, { "Loss Detection and Recovery", "hicn.l4.ldr", FT_UINT16, BASE_HEX , NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_csum, { "Checksum", "hicn.l4.csum", FT_UINT16, BASE_HEX , NULL, 0x0, NULL, HFILL }},
- { &hf_hicn_tcp_lifetime, { "Lifetime", "hicn.l4.lifetime", FT_UINT16, BASE_DEC , NULL, 0x0, NULL, HFILL }}
- };
+ {&hf_hicn_ipv6_src,
+ {"Source Address", "hicn.l3.src", FT_IPv6, BASE_NONE, NULL, 0x0, NULL,
+ HFILL}},
+ {&hf_hicn_ipv6_src_data,
+ {"Name Prefix", "hicn.l3.src", FT_IPv6, BASE_NONE, NULL, 0x0, NULL,
+ HFILL}},
+ {&hf_hicn_ipv6_dst,
+ {"Destination Address", "hicn.l3.dst", FT_IPv6, BASE_NONE, NULL, 0x0,
+ NULL, HFILL}},
+ {&hf_hicn_ipv6_dst_interest,
+ {"Name Prefix", "hicn.l3.dst", FT_IPv6, BASE_NONE, NULL, 0x0, NULL,
+ HFILL}},
+ {&hf_hicn_tcp_namesuffix,
+ {"Name Suffix", "hicn.l4.namesuffix", FT_UINT32, BASE_HEX_DEC, NULL, 0x0,
+ NULL, HFILL}},
+ {&hf_hicn_tcp_pathlabel,
+ {"Path Label", "hicn.l4.pathlabel", FT_UINT8, BASE_HEX_DEC, NULL, 0x0,
+ NULL, HFILL}},
+ {&hf_hicn_tcp_hdrlen_timescale,
+ {"Header length and Timescale", "hicn.l4.hdrlen_ts", FT_UINT8, BASE_HEX,
+ NULL, 0x0, NULL, HFILL}},
+ {&hf_hicn_tcp_hdrlen,
+ {"Header length", "hicn.l4.hdrlen", FT_UINT8, BASE_DEC, NULL, 0x0, NULL,
+ HFILL}},
+ {&hf_hicn_tcp_timescale,
+ {"Timescale", "hicn.l4.timescale", FT_UINT8, BASE_DEC, NULL, 0x0, NULL,
+ HFILL}},
+ {&hf_hicn_tcp_flags,
+ {"Flags", "hicn.l4.flags", FT_UINT8, BASE_HEX, NULL, FLAGS_MASK, NULL,
+ HFILL}},
+ {&hf_hicn_tcp_flags_cwr,
+ {"_CWR", "hicn.l4.flags.cwr", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_CWR, NULL, HFILL}},
+ {&hf_hicn_tcp_flags_id,
+ {"ID", "hicn.l4.flags.id", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_ID, NULL, HFILL}},
+ {&hf_hicn_tcp_flags_man,
+ {"MAN", "hicn.l4.flags.man", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_MAN, NULL, HFILL}},
+ {&hf_hicn_tcp_flags_ack,
+ {"_ACK", "hicn.l4.flags.ack", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_ACK, NULL, HFILL}},
+ {&hf_hicn_tcp_flags_sig,
+ {"SIG", "hicn.l4.flags.sig", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_SIG, NULL, HFILL}},
+ {&hf_hicn_tcp_flags_rst,
+ {"_RST", "hicn.l4.flags.reset", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_RST, NULL, HFILL}},
+ {&hf_hicn_tcp_flags_syn,
+ {"_SYN", "hicn.l4.flags.syn", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_SYN, NULL, HFILL}},
+ {&hf_hicn_tcp_flags_fin,
+ {"_FIN", "hicn.l4.flags.fin", FT_BOOLEAN, FLAGS_BITS_LEN,
+ TFS(&tfs_set_notset), TH_FIN, NULL, HFILL}},
+ {&hf_hicn_tcp_ldr,
+ {"Loss Detection and Recovery", "hicn.l4.ldr", FT_UINT16, BASE_HEX, NULL,
+ 0x0, NULL, HFILL}},
+ {&hf_hicn_tcp_csum,
+ {"Checksum", "hicn.l4.csum", FT_UINT16, BASE_HEX, NULL, 0x0, NULL,
+ HFILL}},
+ {&hf_hicn_tcp_lifetime,
+ {"Lifetime", "hicn.l4.lifetime", FT_UINT16, BASE_DEC, NULL, 0x0, NULL,
+ HFILL}}};
static gint *ett[] = {
- &ett_hicn,
- &ett_hicn_l3,
- &ett_hicn_l4,
- &ett_hicn_l4_flags,
+ &ett_hicn,
+ &ett_hicn_l3,
+ &ett_hicn_l4,
+ &ett_hicn_l4_flags,
};
- proto_hicn = proto_register_protocol ("Hybrid Information-Centric Networking Protocol", "HICN", "hicn");
+ proto_hicn = proto_register_protocol(
+ "Hybrid Information-Centric Networking Protocol", "HICN", "hicn");
proto_register_field_array(proto_hicn, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
}
-static void
-proto_reg_handoff_hicn(void)
-{
+static void proto_reg_handoff_hicn(void) {
static dissector_handle_t hicn_handle;
hicn_handle = create_dissector_handle(dissect_hicn, proto_hicn);
@@ -239,8 +314,7 @@ proto_reg_handoff_hicn(void)
dissector_add_uint("ethertype", ETHERTYPE_IPv6, hicn_handle);
}
-void plugin_register(void)
-{
+void plugin_register(void) {
static proto_plugin plug_hicn;
plug_hicn.register_protoinfo = proto_register_hicn;
plug_hicn.register_handoff = proto_reg_handoff_hicn;
diff --git a/extras/router-plugin/CMakeLists.txt b/extras/router-plugin/CMakeLists.txt
deleted file mode 100644
index 81ad2e628..000000000
--- a/extras/router-plugin/CMakeLists.txt
+++ /dev/null
@@ -1,102 +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.10 FATAL_ERROR)
-project(router-plugin)
-
-include(GNUInstallDirs)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
- "${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/Modules/"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/"
-)
-
-set (CMAKE_C_STANDARD 11)
-
-include (Packaging)
-
-set(HICN_EXTRA_PLUGIN hicn-router-plugin)
-
-# Dependencies
-
-find_package(Vpp REQUIRED)
-
-include_directories(${VPP_INCLUDE_DIR})
-
-set(HICN_EXTRA_PLUGIN_SOURCE_FILES
- rtinject/tap_inject.c
- rtinject/tap_inject_netlink.c
- rtinject/tap_inject_node.c
- rtinject/tap_inject_tap.c
- devices/rtnetlink/mapper.c
- devices/rtnetlink/netns.c
- devices/rtnetlink/rtnl.c
-)
-
-set(HICN_EXTRA_PLUGIN_HEADER_FILES
- devices/rtnetlink/mapper.h
- devices/rtnetlink/netns.h
- devices/rtnetlink/rtnl.h
-)
-
-if (NOT VPP_HOME)
- set(VPP_HOME /usr)
-endif()
-
-if (NOT CMAKE_BUILD_TYPE)
- set (CMAKE_BUILD_TYPE "Release")
-endif (NOT CMAKE_BUILD_TYPE)
-
-SET(EXTRA_INSTALL_PREFIX
- ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}
- CACHE STRING "extra_install_prefix"
-)
-
-if (CMAKE_BUILD_TYPE STREQUAL "Release")
- set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -Wall -march=native -O3 -g")
-elseif (CMAKE_BUILD_TYPE STREQUAL "Debug")
- set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wall -march=native -O0 -g")
- add_definitions(-DCLIB_DEBUG -fPIC -fstack-protector-all)
-endif()
-
-include_directories(SYSTEM)
-include_directories(${CMAKE_CURRENT_BINARY_DIR})
-
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DEXTRA_VPP_PLUGIN=1")
-
-add_library(hicn_router_plugin SHARED
- ${HICN_EXTRA_PLUGIN_SOURCE_FILES}
-)
-
-include_directories(${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins)
-
-set(VPP_INSTALL_PLUGIN ${EXTRA_INSTALL_PREFIX}/vpp_plugins)
-
-set_target_properties(hicn_router_plugin
- PROPERTIES
- LINKER_LANGUAGE C
- INSTALL_RPATH ${VPP_INSTALL_PLUGIN}
- PREFIX ""
- LIBRARY_OUTPUT_NAME "hicn_router"
-)
-
-install(DIRECTORY
- DESTINATION ${VPP_INSTALL_PLUGIN}
- COMPONENT ${HICN_EXTRA_PLUGIN}
-)
-
-install(TARGETS hicn_router_plugin
- DESTINATION
- ${VPP_INSTALL_PLUGIN}
- COMPONENT ${HICN_EXTRA_PLUGIN}
-)
diff --git a/extras/router-plugin/cmake/Modules/Packaging.cmake b/extras/router-plugin/cmake/Modules/Packaging.cmake
deleted file mode 100644
index 69f63971f..000000000
--- a/extras/router-plugin/cmake/Modules/Packaging.cmake
+++ /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.
-
-######################
-# Packages section
-######################
-
-set(${HICN_EXTRA_PLUGIN}_DESCRIPTION
- "A extra plugin to VPP."
- CACHE STRING "Description for deb/rpm package."
-)
-
-set(${HICN_EXTRA_PLUGIN}_DEB_DEPENDENCIES
- "vpp (>= stable_version-release), vpp (<< next_version-release), vpp-plugin-core (>= stable_version-release), vpp-plugin-core (<< next_version-release)"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${HICN_EXTRA_PLUGIN}_RPM_DEPENDENCIES
- "vpp >= stable_version-release, vpp < next_version-release, vpp-plugins >= stable_version-release, vpp-plugins < next_version-release"
- CACHE STRING "Dependencies for deb/rpm package."
-)
diff --git a/extras/router-plugin/devices/rtnetlink/mapper.c b/extras/router-plugin/devices/rtnetlink/mapper.c
deleted file mode 100644
index ed4fa5634..000000000
--- a/extras/router-plugin/devices/rtnetlink/mapper.c
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Copyright (c) 2016-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 <vnet/ip/ip.h>
-#include <vnet/ip/lookup.h>
-#include <vnet/fib/fib.h>
-
-#include "netns.h"
-#include "mapper.h"
-
-typedef struct {
- int linux_ifindex;
- u32 sw_if_index;
-} mapper_map_t;
-
-typedef struct {
- char nsname[RTNL_NETNS_NAMELEN + 1];
- mapper_map_t *mappings;
- u32 netns_handle; //Used to receive notifications
- u32 v4fib_index; //One fib index for the namespace
- u32 v6fib_index;
-} mapper_ns_t;
-
-typedef struct {
- mapper_ns_t *namespaces;
-} mapper_main_t;
-
-static mapper_main_t mapper_main;
-
-mapper_map_t *mapper_get_by_ifindex(mapper_ns_t *ns, int ifindex)
-{
- mapper_map_t *map;
- pool_foreach(map, ns->mappings, {
- if (ifindex == map->linux_ifindex)
- return map;
- });
- return NULL;
-}
-
-int mapper_add_del_route(mapper_ns_t *ns, ns_route_t *route, int del)
-{
- mapper_main_t *mm = &mapper_main;
- clib_warning("NS %d %s %U", ns - mm->namespaces, del?"del":"add", format_ns_route, route);
-
- mapper_map_t *map = mapper_get_by_ifindex(ns, route->oif);
- if (!map)
- return 0;
-
- if (route->rtm.rtm_family == AF_INET6) {
-
- //Filter-out multicast
- if (route->rtm.rtm_dst_len >= 8 && route->dst[0] == 0xff)
- return 0;
-
- fib_prefix_t prefix;
- ip46_address_t nh;
-
- memset (&prefix, 0, sizeof (prefix));
- prefix.fp_len = route->rtm.rtm_dst_len;
- prefix.fp_proto = FIB_PROTOCOL_IP6;
- clib_memcpy (&prefix.fp_addr.ip6, route->dst, sizeof (prefix.fp_addr.ip6));
-
- memset (&nh, 0, sizeof (nh));
- clib_memcpy (&nh.ip6, route->gateway, sizeof (nh.ip6));
-
- fib_table_entry_path_add (ns->v6fib_index, &prefix, FIB_SOURCE_API,
- FIB_ENTRY_FLAG_NONE, prefix.fp_proto,
- &nh, map->sw_if_index, ns->v6fib_index,
- 0 /* weight */,
- (fib_mpls_label_t *) MPLS_LABEL_INVALID,
- FIB_ROUTE_PATH_FLAG_NONE);
- } else {
- fib_prefix_t prefix;
- ip46_address_t nh;
-
- memset (&prefix, 0, sizeof (prefix));
- prefix.fp_len = route->rtm.rtm_dst_len;
- prefix.fp_proto = FIB_PROTOCOL_IP4;
- clib_memcpy (&prefix.fp_addr.ip4, route->dst, sizeof (prefix.fp_addr.ip4));
-
- memset (&nh, 0, sizeof (nh));
- clib_memcpy (&nh.ip4, route->gateway, sizeof (nh.ip4));
-
- fib_table_entry_path_add (ns->v4fib_index, &prefix, FIB_SOURCE_API,
- FIB_ENTRY_FLAG_NONE, prefix.fp_proto,
- &nh, map->sw_if_index, ns->v4fib_index,
- 0 /* weight */,
- (fib_mpls_label_t *) MPLS_LABEL_INVALID,
- FIB_ROUTE_PATH_FLAG_NONE);
- }
-
- return 0;
-}
-
-static void
-mapper_netns_notify_cb(void *obj, netns_type_t type,
- u32 flags, uword opaque)
-{
- mapper_main_t *mm = &mapper_main;
- mapper_ns_t *ns = &mm->namespaces[(u32) opaque];
- ASSERT(!pool_is_free_index(mm->namespaces, (u32) opaque));
- if (type != NETNS_TYPE_ROUTE)
- return; //For now...
-
- ns_route_t *route = obj;
- if (flags & NETNS_F_DEL) {
- mapper_add_del_route(ns, route, 1);
- } else if (flags & NETNS_F_ADD) {
- mapper_add_del_route(ns, route, 0);
- }
-}
-
-void
-mapper_delmap(mapper_ns_t*ns, mapper_map_t *map)
-{
- ns_route_t *route;
- netns_t *netns = netns_getns(ns->netns_handle);
- pool_foreach(route, netns->routes, {
- if (route->oif == map->linux_ifindex)
- mapper_add_del_route(ns, route, 1);
- });
- pool_put(ns->mappings, map);
-}
-
-mapper_map_t *
-mapper_getmap(mapper_ns_t*ns, u32 sw_if_index,
- int linux_ifindex, int create)
-{
- mapper_map_t *map;
- pool_foreach(map, ns->mappings, {
- if (linux_ifindex == map->linux_ifindex) {
- if (sw_if_index != map->sw_if_index)
- return NULL; //Cannot have multiple mapping with the same ifindex
- else
- return map;
- }
- });
-
- if (!create)
- return NULL;
-
- pool_get(ns->mappings, map);
- map->linux_ifindex = linux_ifindex;
- map->sw_if_index = sw_if_index;
- ip6_main.fib_index_by_sw_if_index[sw_if_index] = ns->v6fib_index;
- ip4_main.fib_index_by_sw_if_index[sw_if_index] = ns->v4fib_index;
-
- //Load available routes
- ns_route_t *route;
- netns_t *netns = netns_getns(ns->netns_handle);
- pool_foreach(route, netns->routes, {
- if (route->oif == map->linux_ifindex)
- mapper_add_del_route(ns, route, 0);
- });
- return map;
-}
-
-u32
-mapper_get_ns(char *nsname)
-{
- mapper_main_t *mm = &mapper_main;
- mapper_ns_t *ns;
- pool_foreach(ns, mm->namespaces, {
- if (!strcmp(nsname, ns->nsname))
- return ns - mm->namespaces;
- });
- return ~0;
-}
-
-int
-mapper_add_del(u32 nsindex, int linux_ifindex,
- u32 sw_if_index, int del)
-{
- mapper_main_t *mm = &mapper_main;
- //ip6_main_t *im6 = &ip6_main;
- mapper_ns_t *ns = &mm->namespaces[nsindex];
- mapper_map_t *map;
- //vnet_sw_interface_t *iface = vnet_get_sw_interface(vnet_get_main(), sw_if_index);
-
- if (pool_is_free(mm->namespaces, ns))
- return -1;
-
- /*if (!del) {
- if ((iface->flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) &&
- im6->fib_index_by_sw_if_index[sw_if_index] != ~0) {
- //A custom fib index will be used...
- clib_warning("Cannot add interface with a custom fib index (current is %d)",
- im6->fib_index_by_sw_if_index[sw_if_index]);
- return -1;
- }
- }*/
-
- if (!(map = mapper_getmap(ns, sw_if_index, linux_ifindex, !del)))
- return -1;
-
- if (del)
- mapper_delmap(ns, map);
-
- return 0;
-}
-
-int
-mapper_add_ns(char *nsname, u32 v4fib_index, u32 v6fib_index, u32 *nsindex)
-{
- mapper_main_t *mm = &mapper_main;
- mapper_ns_t *ns;
- if (mapper_get_ns(nsname) != ~0)
- return -1; //Already exists
-
- pool_get(mm->namespaces, ns);
- strcpy(ns->nsname, nsname);
- ns->v4fib_index = v4fib_index;
- ns->v6fib_index = v6fib_index;
- ns->mappings = 0;
-
- netns_sub_t sub;
- sub.notify = mapper_netns_notify_cb;
- sub.opaque = (uword)(ns - mm->namespaces);
- if ((ns->netns_handle = netns_open(ns->nsname, &sub)) == ~0) {
- pool_put(mm->namespaces, ns);
- return -1;
- }
- *nsindex = ns - mm->namespaces;
- return 0;
-}
-
-int
-mapper_del_ns(u32 nsindex)
-{
- mapper_main_t *mm = &mapper_main;
- mapper_ns_t *ns = &mm->namespaces[nsindex];
- if (pool_is_free(mm->namespaces, ns))
- return -1;
-
- //Remove all existing mappings
- int i, *indexes = 0;
- pool_foreach_index(i, ns->mappings, {
- vec_add1(indexes, i);
- });
- vec_foreach_index(i, indexes) {
- mapper_delmap(ns, &ns->mappings[indexes[i]]);
- }
- vec_free(indexes);
-
- netns_close(ns->netns_handle);
- pool_put(mm->namespaces, ns);
- return 0;
-}
-
-clib_error_t *
-mapper_init (vlib_main_t * vm)
-{
- mapper_main_t *mm = &mapper_main;
- mm->namespaces = 0;
- return 0;
-}
-
-VLIB_INIT_FUNCTION (mapper_init);
diff --git a/extras/router-plugin/devices/rtnetlink/mapper.h b/extras/router-plugin/devices/rtnetlink/mapper.h
deleted file mode 100644
index 32e95d48f..000000000
--- a/extras/router-plugin/devices/rtnetlink/mapper.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2016-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.
- */
-
-#ifndef MAPPER_H_
-#define MAPPER_H_
-
-#include "netns.h"
-
-/*
- * Automatically map linux network routes to VPP.
- * Each namespace is associated with an individual fib.
- *
- * One linux interface can only be mapped to a single VPP
- * interface, but one VPP interface can be mapped to
- * multiple linux interfaces.
- * A mapped VPP interface must not have any configured fib.
- */
-
-int mapper_add_ns(char *nsname, u32 v4fib_index, u32 v6fib_index, u32 *nsindex);
-int mapper_del_ns(u32 nsindex);
-int mapper_add_del(u32 nsindex, int linux_ifindex, u32 sw_if_index, int del);
-
-#endif /* MAPPER_H_ */
diff --git a/extras/router-plugin/devices/rtnetlink/netns.c b/extras/router-plugin/devices/rtnetlink/netns.c
deleted file mode 100644
index 19adb469a..000000000
--- a/extras/router-plugin/devices/rtnetlink/netns.c
+++ /dev/null
@@ -1,787 +0,0 @@
-/*
- * Copyright (c) 2016-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 <vlib/vlib.h>
-#include <vlib/unix/unix.h>
-#include <vnet/ethernet/ethernet.h>
-#include <vnet/ip/ip4_packet.h>
-#include <vnet/ip/ip6_packet.h>
-#include <vnet/ip/format.h>
-#include <stddef.h>
-
-#include "netns.h"
-
-/* Enable some RTA values debug */
-//#define RTNL_CHECK
-
-#define is_nonzero(x) \
- ({ \
- u8 __is_zero_zero[sizeof(x)] = {}; \
- memcmp(__is_zero_zero, &x, sizeof(x)); \
- })
-
-typedef struct {
- u8 type; //Attribute identifier
- u8 unique; //Part of the values uniquely identifying an entry
- u16 offset; //Offset where stored in struct
- u16 size; //Length of the attribute
-} rtnl_mapping_t;
-
-#define ns_foreach_ifla \
- _(IFLA_ADDRESS, hwaddr) \
- _(IFLA_BROADCAST, broadcast) \
- _(IFLA_IFNAME, ifname) \
- _(IFLA_MASTER, master) \
- _(IFLA_MTU, mtu) \
- _(IFLA_QDISC, qdisc)
-
-static rtnl_mapping_t ns_ifmap[] = {
-#define _(t, e) \
- { \
- .type = t, \
- .offset = offsetof(ns_link_t, e), \
- .size = sizeof(((ns_link_t*)0)->e) \
- },
- ns_foreach_ifla
-#undef _
- { .type = 0 }
-};
-
-u8 *format_ns_link (u8 *s, va_list *args)
-{
- ns_link_t *l = va_arg(*args, ns_link_t *);
- s = format(s, "%s index %u", l->ifname, l->ifi.ifi_index);
- return s;
-}
-
-#define ns_foreach_rta \
- _(RTA_DST, dst, 1) \
- _(RTA_SRC, src, 1) \
- _(RTA_GATEWAY, gateway, 1) \
- _(RTA_IIF, iif, 1) \
- _(RTA_OIF, oif, 1) \
- _(RTA_PREFSRC, prefsrc, 0) \
- _(RTA_TABLE, table, 0) \
- _(RTA_PRIORITY, priority, 0) \
- _(RTA_CACHEINFO, cacheinfo, 0) \
- _(RTA_ENCAP, encap, 1)
-
-static rtnl_mapping_t ns_routemap[] = {
-#define _(t, e, u) \
- { \
- .type = t, .unique = u, \
- .offset = offsetof(ns_route_t, e), \
- .size = sizeof(((ns_route_t*)0)->e) \
- },
- ns_foreach_rta
-#undef _
- { .type = 0 }
-};
-
-u8 *format_ns_route (u8 *s, va_list *args)
-{
- ns_route_t *r = va_arg(*args, ns_route_t *);
- void *format_ip = r->rtm.rtm_family == AF_INET ? format_ip4_address : format_ip6_address;
- s = format(s, "%U/%d", format_ip, r->dst, r->rtm.rtm_dst_len);
- if (r->rtm.rtm_src_len)
- s = format(s, " from %U/%d", format_ip, r->src, r->rtm.rtm_src_len);
- if (is_nonzero(r->gateway))
- s = format(s, " via %U", format_ip, r->gateway);
- if (r->iif)
- s = format(s, " iif %d", r->iif);
- if (r->oif)
- s = format(s, " oif %d", r->oif);
- if (is_nonzero(r->prefsrc))
- s = format(s, " src %U", format_ip, r->prefsrc);
- if (r->table)
- s = format(s, " table %d", r->table);
- if (r->priority)
- s = format(s, " priority %u", r->priority);
- return s;
-}
-
-#define ns_foreach_ifaddr \
- _(IFA_ADDRESS, addr, 1) \
- _(IFA_LOCAL, local, 1) \
- _(IFA_LABEL, label, 0) \
- _(IFA_BROADCAST, broadcast, 0) \
- _(IFA_ANYCAST, anycast, 0) \
- _(IFA_CACHEINFO, cacheinfo, 0)
-
-static rtnl_mapping_t ns_addrmap[] = {
-#define _(t, e, u) \
- { \
- .type = t, .unique = u, \
- .offset = offsetof(ns_addr_t, e), \
- .size = sizeof(((ns_addr_t*)0)->e) \
- },
- ns_foreach_ifaddr
-#undef _
- { .type = 0 }
-};
-
-u8 *format_ns_addr (u8 *s, va_list *args)
-{
- ns_addr_t *a = va_arg(*args, ns_addr_t *);
- void *format_ip = a->ifaddr.ifa_family == AF_INET ? format_ip4_address : format_ip6_address;
- s = format(s, "%U/%d", format_ip, a->addr, a->ifaddr.ifa_prefixlen);
- if (is_nonzero(a->label))
- s = format(s, " dev %s", a->label);
- if (is_nonzero(a->broadcast))
- s = format(s, " broadcast %U", format_ip, a->broadcast);
- if (is_nonzero(a->anycast))
- s = format(s, " anycast %U", format_ip, a->anycast);
- if (is_nonzero(a->local))
- s = format(s, " local %U", format_ip, a->local);
- return s;
-}
-
-#ifndef NDA_RTA
-#define NDA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ndmsg))))
-#define NDA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ndmsg))
-#endif
-
-#define ns_foreach_neigh \
- _(NDA_DST, dst, 1) \
- _(NDA_LLADDR, lladdr, 0) \
- _(NDA_PROBES, probes, 0) \
- _(NDA_CACHEINFO, cacheinfo, 0)
-
-static rtnl_mapping_t ns_neighmap[] = {
-#define _(t, e, u) \
- { \
- .type = t, .unique = u, \
- .offset = offsetof(ns_neigh_t, e), \
- .size = sizeof(((ns_neigh_t*)0)->e) \
- },
- ns_foreach_neigh
-#undef _
- { .type = 0 }
-};
-
-u8 *format_ns_neigh (u8 *s, va_list *args)
-{
- ns_neigh_t *n = va_arg(*args, ns_neigh_t *);
- void *format_ip = n->nd.ndm_family == AF_INET ? format_ip4_address : format_ip6_address;
- s = format(s, "%U", format_ip, n->dst);
- if (is_nonzero(n->lladdr))
- s = format(s, " lladdr %U", format_ethernet_address, n->lladdr);
- if (n->probes)
- s = format(s, " probes %d", n->probes);
- return s;
-}
-
-typedef struct {
- void (*notify)(void *obj, netns_type_t type, u32 flags, uword opaque);
- uword opaque;
- u32 netns_index;
-} netns_handle_t;
-
-typedef struct {
- netns_t netns;
- u32 rtnl_handle;
- u32 subscriber_count;
-} netns_p;
-
-typedef struct {
- netns_p *netnss;
- netns_handle_t *handles;
-} netns_main_t;
-
-netns_main_t netns_main;
-
-static int
-rtnl_parse_rtattr(struct rtattr *db[], size_t max,
- struct rtattr *rta, size_t len) {
- for(; RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
- if (rta->rta_type <= max)
- db[rta->rta_type] = rta;
-#ifdef RTNL_CHECK
- else
- clib_warning("RTA type too high: %d", rta->rta_type);
-#endif
- }
-
- if(len) {
- clib_warning("rattr lenght mistmatch %d %d len",
- (int) len, (int) rta->rta_len);
- return -1;
- }
- return 0;
-}
-
-/*
- * Debug function to display when
- * we receive an RTA that I forgot in
- * the mapping table (there are so many of them).
- */
-#ifdef RTNL_CHECK
-static void
-rtnl_entry_check(struct rtattr *rtas[],
- size_t rta_len,
- rtnl_mapping_t map[],
- char *logstr)
-{
- int i;
- for (i=0; i<rta_len; i++) {
- if (!rtas[i])
- continue;
-
- rtnl_mapping_t *m = map;
- for (m = map; m->type; m++) {
- if (m->type == rtas[i]->rta_type)
- break;
- }
- if (!m->type)
- clib_warning("Unknown RTA type %d (%s)", rtas[i]->rta_type, logstr);
- }
-}
-#endif
-
-/*
- * Check if the provided entry matches the parsed and unique rtas
- */
-static int
-rtnl_entry_match(void *entry,
- struct rtattr *rtas[],
- rtnl_mapping_t map[])
-{
- u8 zero[1024] = {};
- for ( ;map->type != 0; map++) {
- struct rtattr *rta = rtas[map->type];
- size_t rta_len = rta?RTA_PAYLOAD(rta):0;
- if (!map->unique)
- continue;
-
- if (rta && RTA_PAYLOAD(rta) > map->size) {
- clib_warning("rta (type=%d len=%d) too long (max %d)",
- rta->rta_type, rta->rta_len, map->size);
- return -1;
- }
-
- if ((rta && memcmp(RTA_DATA(rta), entry + map->offset, rta_len)) ||
- memcmp(entry + map->offset + rta_len, zero, map->size - rta_len)) {
- return 0;
- }
- }
- return 1;
-}
-
-static int
-rtnl_entry_set(void *entry,
- struct rtattr *rtas[],
- rtnl_mapping_t map[],
- int init)
-{
- for (; map->type != 0; map++) {
-
- struct rtattr *rta = rtas[map->type];
-
- if(map->type == RTA_ENCAP && rta) {
- /*Data of RTA_ENCAP is a pointer to rta attributes for MPLS*/
- rta = (struct rtattr*)RTA_DATA(rta);
- if (RTA_PAYLOAD(rta) > map->size) {
- clib_warning("rta (type=%d len=%d) too long (max %d)", rta->rta_type, rta->rta_len, map->size);
- return -1;
- }
- memcpy(entry + map->offset, RTA_DATA(rta), map->size);
- memset(entry + map->offset + map->size, 0, 0);
- } else if (rta) {
- if (RTA_PAYLOAD(rta) > map->size) {
- clib_warning("rta (type=%d len=%d) too long (max %d)", rta->rta_type, rta->rta_len, map->size);
- return -1;
- }
- memcpy(entry + map->offset, RTA_DATA(rta), RTA_PAYLOAD(rta));
- memset(entry + map->offset + RTA_PAYLOAD(rta), 0, map->size - RTA_PAYLOAD(rta));
- } else if (init) {
- memset(entry + map->offset, 0, map->size);
- }
- }
- return 0;
-}
-
-void
-netns_notify(netns_p *ns, void *obj, netns_type_t type, u32 flags)
-{
- netns_main_t *nm = &netns_main;
- netns_handle_t *h;
- pool_foreach(h, nm->handles, {
- if (h->netns_index == (ns - nm->netnss) && h->notify)
- h->notify(obj, type, flags, h->opaque);
- });
-}
-
-static_always_inline int
-mask_match(void *a, void *b, void *mask, size_t len)
-{
- u8 *va = (u8 *) a;
- u8 *vb = (u8 *) b;
- u8 *vm = (u8 *) mask;
- while (len--) {
- if ((va[len] ^ vb[len]) & vm[len])
- return 0;
- }
- return 1;
-}
-
-static ns_link_t *
-ns_get_link(netns_p *ns, struct ifinfomsg *ifi, struct rtattr *rtas[])
-{
- ns_link_t *link;
- pool_foreach(link, ns->netns.links, {
- if(ifi->ifi_index == link->ifi.ifi_index)
- return link;
- });
- return NULL;
-}
-
-static int
-ns_rcv_link(netns_p *ns, struct nlmsghdr *hdr)
-{
- ns_link_t *link;
- struct ifinfomsg *ifi;
- struct rtattr *rtas[IFLA_MAX + 1] = {};
- size_t datalen = hdr->nlmsg_len - NLMSG_ALIGN(sizeof(*hdr));
-
- if(datalen < sizeof(*ifi))
- return -1;
-
- ifi = NLMSG_DATA(hdr);
- if((datalen > NLMSG_ALIGN(sizeof(*ifi))) &&
- rtnl_parse_rtattr(rtas, IFLA_MAX, IFLA_RTA(ifi),
- IFLA_PAYLOAD(hdr))) {
- return -1;
- }
-#ifdef RTNL_CHECK
- rtnl_entry_check(rtas, IFLA_MAX + 1, ns_ifmap, "link");
-#endif
-
- link = ns_get_link(ns, ifi, rtas);
-
- if (hdr->nlmsg_type == RTM_DELLINK) {
- if (!link)
- return -1;
- pool_put(ns->netns.links, link);
- netns_notify(ns, link, NETNS_TYPE_LINK, NETNS_F_DEL);
- return 0;
- }
-
- if (!link) {
- pool_get(ns->netns.links, link);
- rtnl_entry_set(link, rtas, ns_ifmap, 1);
- } else {
- rtnl_entry_set(link, rtas, ns_ifmap, 0);
- }
-
- link->ifi = *ifi;
- link->last_updated = vlib_time_now(vlib_get_main());
- netns_notify(ns, link, NETNS_TYPE_LINK, NETNS_F_ADD);
- return 0;
-}
-
-static ns_route_t *
-ns_get_route(netns_p *ns, struct rtmsg *rtm, struct rtattr *rtas[])
-{
- ns_route_t *route;
-
- //This describes the values which uniquely identify a route
- struct rtmsg msg = {
- .rtm_family = 0xff,
- .rtm_dst_len = 0xff,
- .rtm_src_len = 0xff,
- .rtm_table = 0xff,
- .rtm_protocol = 0xff,
- .rtm_type = 0xff
- };
-
- pool_foreach(route, ns->netns.routes, {
- if(mask_match(&route->rtm, rtm, &msg, sizeof(struct rtmsg)) &&
- rtnl_entry_match(route, rtas, ns_routemap))
- return route;
- });
- return NULL;
-}
-
-static int
-ns_rcv_route(netns_p *ns, struct nlmsghdr *hdr)
-{
- ns_route_t *route;
- struct rtmsg *rtm;
- struct rtattr *rtas[RTA_MAX + 1] = {};
- size_t datalen = hdr->nlmsg_len - NLMSG_ALIGN(sizeof(*hdr));
-
- if(datalen < sizeof(*rtm))
- return -1;
-
- rtm = NLMSG_DATA(hdr);
- if((datalen > NLMSG_ALIGN(sizeof(*rtm))) &&
- rtnl_parse_rtattr(rtas, RTA_MAX, RTM_RTA(rtm),
- RTM_PAYLOAD(hdr))) {
- return -1;
- }
-#ifdef RTNL_CHECK
- rtnl_entry_check(rtas, RTA_MAX + 1, ns_routemap, "route");
-#endif
- route = ns_get_route(ns, rtm, rtas);
-
- if (hdr->nlmsg_type == RTM_DELROUTE) {
- if (!route)
- return -1;
- pool_put(ns->netns.routes, route);
- netns_notify(ns, route, NETNS_TYPE_ROUTE, NETNS_F_DEL);
- return 0;
- }
-
- if (!route) {
- pool_get(ns->netns.routes, route);
- memset(route, 0, sizeof(*route));
- rtnl_entry_set(route, rtas, ns_routemap, 1);
- } else {
- rtnl_entry_set(route, rtas, ns_routemap, 0);
- }
-
- route->rtm = *rtm;
- route->last_updated = vlib_time_now(vlib_get_main());
- netns_notify(ns, route, NETNS_TYPE_ROUTE, NETNS_F_ADD);
- return 0;
-}
-
-static ns_addr_t *
-ns_get_addr(netns_p *ns, struct ifaddrmsg *ifaddr, struct rtattr *rtas[])
-{
- ns_addr_t *addr;
-
- //This describes the values which uniquely identify a route
- struct ifaddrmsg msg = {
- .ifa_family = 0xff,
- .ifa_prefixlen = 0xff,
- };
-
- pool_foreach(addr, ns->netns.addresses, {
- if(mask_match(&addr->ifaddr, ifaddr, &msg, sizeof(struct ifaddrmsg)) &&
- rtnl_entry_match(addr, rtas, ns_addrmap))
- return addr;
- });
- return NULL;
-}
-
-static int
-ns_rcv_addr(netns_p *ns, struct nlmsghdr *hdr)
-{
- ns_addr_t *addr;
- struct ifaddrmsg *ifaddr;
- struct rtattr *rtas[IFA_MAX + 1] = {};
- size_t datalen = hdr->nlmsg_len - NLMSG_ALIGN(sizeof(*hdr));
-
- if(datalen < sizeof(*ifaddr))
- return -1;
-
- ifaddr = NLMSG_DATA(hdr);
- if((datalen > NLMSG_ALIGN(sizeof(*ifaddr))) &&
- rtnl_parse_rtattr(rtas, IFA_MAX, IFA_RTA(ifaddr),
- IFA_PAYLOAD(hdr))) {
- return -1;
- }
-#ifdef RTNL_CHECK
- rtnl_entry_check(rtas, IFA_MAX + 1, ns_addrmap, "addr");
-#endif
- addr = ns_get_addr(ns, ifaddr, rtas);
-
- if (hdr->nlmsg_type == RTM_DELADDR) {
- if (!addr)
- return -1;
- pool_put(ns->netns.addresses, addr);
- netns_notify(ns, addr, NETNS_TYPE_ADDR, NETNS_F_DEL);
- return 0;
- }
-
- if (!addr) {
- pool_get(ns->netns.addresses, addr);
- memset(addr, 0, sizeof(*addr));
- rtnl_entry_set(addr, rtas, ns_addrmap, 1);
- } else {
- rtnl_entry_set(addr, rtas, ns_addrmap, 0);
- }
-
- addr->ifaddr = *ifaddr;
- addr->last_updated = vlib_time_now(vlib_get_main());
- netns_notify(ns, addr, NETNS_TYPE_ADDR, NETNS_F_ADD);
- return 0;
-}
-
-static ns_neigh_t *
-ns_get_neigh(netns_p *ns, struct ndmsg *nd, struct rtattr *rtas[])
-{
- ns_neigh_t *neigh;
-
- //This describes the values which uniquely identify a route
- struct ndmsg msg = {
- .ndm_family = 0xff,
- .ndm_ifindex = 0xff,
- };
-
- pool_foreach(neigh, ns->netns.neighbors, {
- if(mask_match(&neigh->nd, nd, &msg, sizeof(&msg)) &&
- rtnl_entry_match(neigh, rtas, ns_neighmap))
- return neigh;
- });
- return NULL;
-}
-
-static int
-ns_rcv_neigh(netns_p *ns, struct nlmsghdr *hdr)
-{
- ns_neigh_t *neigh;
- struct ndmsg *nd;
- struct rtattr *rtas[NDA_MAX + 1] = {};
- size_t datalen = hdr->nlmsg_len - NLMSG_ALIGN(sizeof(*hdr));
-
- if(datalen < sizeof(*nd))
- return -1;
-
- nd = NLMSG_DATA(hdr);
- if((datalen > NLMSG_ALIGN(sizeof(*nd))) &&
- rtnl_parse_rtattr(rtas, NDA_MAX, NDA_RTA(nd),
- NDA_PAYLOAD(hdr))) {
- return -1;
- }
-#ifdef RTNL_CHECK
- rtnl_entry_check(rtas, NDA_MAX + 1, ns_neighmap, "nd");
-#endif
- neigh = ns_get_neigh(ns, nd, rtas);
-
- if (hdr->nlmsg_type == RTM_DELNEIGH) {
- if (!neigh)
- return -1;
- pool_put(ns->netns.neighbors, neigh);
- netns_notify(ns, neigh, NETNS_TYPE_NEIGH, NETNS_F_DEL);
- return 0;
- }
-
- if (!neigh) {
- pool_get(ns->netns.neighbors, neigh);
- memset(neigh, 0, sizeof(*neigh));
- rtnl_entry_set(neigh, rtas, ns_neighmap, 1);
- } else {
- rtnl_entry_set(neigh, rtas, ns_neighmap, 0);
- }
-
- neigh->nd = *nd;
- neigh->last_updated = vlib_time_now(vlib_get_main());
- netns_notify(ns, neigh, NETNS_TYPE_NEIGH, NETNS_F_ADD);
- return 0;
-}
-
-#define ns_object_foreach \
- _(neighbors, NETNS_TYPE_NEIGH) \
- _(routes, NETNS_TYPE_ROUTE) \
- _(addresses, NETNS_TYPE_ADDR) \
- _(links, NETNS_TYPE_LINK)
-
-static void
-ns_recv_error(rtnl_error_t err, uword o)
-{
- //An error was received. Reset everything.
- netns_p *ns = &netns_main.netnss[o];
- u32 *indexes = 0;
- u32 *i = 0;
-
-#define _(pool, type) \
- pool_foreach_index(*i, ns->netns.pool, { \
- vec_add1(indexes, *i); \
- }) \
- vec_foreach(i, indexes) { \
- pool_put_index(ns->netns.pool, *i); \
- netns_notify(ns, &ns->netns.pool[*i], type, NETNS_F_DEL); \
- } \
- vec_reset_length(indexes);
-
- ns_object_foreach
-
-#undef _
- vec_free(indexes);
-}
-
-static void
-ns_recv_rtnl(struct nlmsghdr *hdr, uword o)
-{
- netns_p *ns = &netns_main.netnss[o];
- switch (hdr->nlmsg_type) {
- case RTM_NEWROUTE:
- case RTM_DELROUTE:
- ns_rcv_route(ns, hdr);
- break;
- case RTM_NEWLINK:
- case RTM_DELLINK:
- ns_rcv_link(ns, hdr);
- break;
- case RTM_NEWADDR:
- case RTM_DELADDR:
- ns_rcv_addr(ns, hdr);
- break;
- case RTM_NEWNEIGH:
- case RTM_DELNEIGH:
- ns_rcv_neigh(ns, hdr);
- break;
- default:
- clib_warning("unknown rtnl type %d", hdr->nlmsg_type);
- break;
- }
-}
-
-static void
-netns_destroy(netns_p *ns)
-{
- netns_main_t *nm = &netns_main;
- rtnl_stream_close(ns->rtnl_handle);
- pool_put(nm->netnss, ns);
- pool_free(ns->netns.links);
- pool_free(ns->netns.addresses);
- pool_free(ns->netns.routes);
- pool_free(ns->netns.neighbors);
-}
-
-static netns_p *
-netns_get(char *name)
-{
- netns_main_t *nm = &netns_main;
- netns_p *ns;
- pool_foreach(ns, nm->netnss, {
- if (!strcmp(name, ns->netns.name))
- return ns;
- });
-
- if (strlen(name) > RTNL_NETNS_NAMELEN)
- return NULL;
-
- pool_get(nm->netnss, ns);
- rtnl_stream_t s = {
- .recv_message = ns_recv_rtnl,
- .error = ns_recv_error,
- .opaque = (uword)(ns - nm->netnss),
- };
- strcpy(s.name, name);
-
- u32 handle;
- if ((handle = rtnl_stream_open(&s)) == ~0) {
- pool_put(nm->netnss, ns);
- return NULL;
- }
-
- strcpy(ns->netns.name, name);
- ns->netns.addresses = 0;
- ns->netns.links = 0;
- ns->netns.neighbors = 0;
- ns->netns.routes = 0;
- ns->subscriber_count = 0;
- ns->rtnl_handle = handle;
- return ns;
-}
-
-u32 netns_open(char *name, netns_sub_t *sub)
-{
- netns_main_t *nm = &netns_main;
- netns_p *ns;
- netns_handle_t *p;
- if (!(ns = netns_get(name)))
- return ~0;
-
- pool_get(nm->handles, p);
- p->netns_index = ns - nm->netnss;
- p->notify = sub->notify;
- p->opaque = sub->opaque;
- ns->subscriber_count++;
- return p - nm->handles;
-}
-
-netns_t *netns_getns(u32 handle)
-{
- netns_main_t *nm = &netns_main;
- netns_handle_t *h = pool_elt_at_index(nm->handles, handle);
- netns_p *ns = pool_elt_at_index(nm->netnss, h->netns_index);
- return &ns->netns;
-}
-
-void netns_close(u32 handle)
-{
- netns_main_t *nm = &netns_main;
- netns_handle_t *h = pool_elt_at_index(nm->handles, handle);
- netns_p *ns = pool_elt_at_index(nm->netnss, h->netns_index);
- pool_put(h, nm->handles);
- ns->subscriber_count--;
- if (!ns->subscriber_count)
- netns_destroy(ns);
-}
-
-void netns_callme(u32 handle, char del)
-{
- netns_main_t *nm = &netns_main;
- netns_handle_t *h = pool_elt_at_index(nm->handles, handle);
- netns_p *ns = pool_elt_at_index(nm->netnss, h->netns_index);
- u32 i = 0;
- if (!h->notify)
- return;
-
-#define _(pool, type) \
- pool_foreach_index(i, ns->netns.pool, { \
- h->notify(&ns->netns.pool[i], type, \
- del?NETNS_F_DEL:NETNS_F_ADD, h->opaque); \
- });
-
- ns_object_foreach
-#undef _
-
- }
-
-u8 *format_ns_object(u8 *s, va_list *args)
-{
- netns_type_t t = va_arg(*args, netns_type_t);
- void *o = va_arg(*args, void *);
- switch (t) {
- case NETNS_TYPE_ADDR:
- return format(s, "addr %U", format_ns_addr, o);
- case NETNS_TYPE_ROUTE:
- return format(s, "route %U", format_ns_route, o);
- case NETNS_TYPE_LINK:
- return format(s, "link %U", format_ns_link, o);
- case NETNS_TYPE_NEIGH:
- return format(s, "neigh %U", format_ns_neigh, o);
- }
- return s;
-}
-
-u8 *format_ns_flags(u8 *s, va_list *args)
-{
- u32 flags = va_arg(*args, u32);
- if (flags & NETNS_F_ADD)
- s = format(s, "add");
- else if (flags & NETNS_F_DEL)
- s = format(s, "del");
- else
- s = format(s, "mod");
- return s;
-}
-
-clib_error_t *
-netns_init (vlib_main_t * vm)
-{
- netns_main_t *nm = &netns_main;
- nm->netnss = 0;
- nm->handles = 0;
- return 0;
-}
-
-VLIB_INIT_FUNCTION (netns_init);
diff --git a/extras/router-plugin/devices/rtnetlink/netns.h b/extras/router-plugin/devices/rtnetlink/netns.h
deleted file mode 100644
index 53effe5ce..000000000
--- a/extras/router-plugin/devices/rtnetlink/netns.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (c) 2016-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.
- */
-
-#ifndef NETNS_H_
-#define NETNS_H_
-
-#include <vlib/vlib.h>
-
-#include <sys/socket.h>
-#include <linux/rtnetlink.h>
-#include <linux/netlink.h>
-#include <net/if.h>
-
-#include "rtnl.h"
-
-/*include it for 'struct mpls_label'*/
-#include <linux/mpls.h>
-/*so far depth is fixed, looking into ways to be dynamic*/
-#define MPLS_STACK_DEPTH 7
-
-typedef struct {
- struct ifinfomsg ifi;
- u8 hwaddr[IFHWADDRLEN];
- u8 broadcast[IFHWADDRLEN];
- u8 ifname[IFNAMSIZ];
- u32 mtu;
- u32 master;
- u8 qdisc[IFNAMSIZ];
- struct rtnl_link_stats stats; //This struct is big and only comes as a response to a request
- f64 last_updated;
-} ns_link_t;
-
-typedef struct {
- struct rtmsg rtm;
- u8 dst[16];
- u8 src[16];
- u8 via[16];
- u8 prefsrc[16];
- u32 iif;
- u32 oif;
- u32 table;
- u8 gateway[16];
- u32 priority;
- struct rta_cacheinfo cacheinfo;
- struct mpls_label encap[MPLS_STACK_DEPTH];
- f64 last_updated;
-} ns_route_t;
-
-typedef struct {
- struct ifaddrmsg ifaddr;
- u8 addr[16];
- u8 local[16];
- u8 label[IFNAMSIZ];
- u8 broadcast[16];
- u8 anycast[16];
- struct ifa_cacheinfo cacheinfo;
- f64 last_updated;
-} ns_addr_t;
-
-typedef struct {
- struct ndmsg nd;
- u8 dst[16];
- u8 lladdr[IFHWADDRLEN];
- u32 probes;
- struct nda_cacheinfo cacheinfo;
- f64 last_updated;
-} ns_neigh_t;
-
-typedef struct {
- char name[RTNL_NETNS_NAMELEN + 1];
- ns_link_t *links;
- ns_route_t *routes;
- ns_addr_t *addresses;
- ns_neigh_t *neighbors;
-} netns_t;
-
-
-typedef enum {
- NETNS_TYPE_LINK,
- NETNS_TYPE_ROUTE,
- NETNS_TYPE_ADDR,
- NETNS_TYPE_NEIGH,
-} netns_type_t;
-
-//Flags used in notification functions call
-#define NETNS_F_ADD 0x01
-#define NETNS_F_DEL 0x02
-
-typedef struct {
- void (*notify)(void *obj, netns_type_t type, u32 flags, uword opaque);
- uword opaque;
-} netns_sub_t;
-
-/*
- * Subscribe for events related to the given namespace.
- * When another subscriber already uses the namespace,
- * this call will not trigger updates for already
- * existing routes (This is to protect against
- * synch. Vs asynch. issues).
- */
-u32 netns_open(char *name, netns_sub_t *sub);
-
-/*
- * Retrieves the namespace structure associated with a
- * given namespace handler.
- */
-netns_t *netns_getns(u32 handle);
-
-/*
- * Terminates a subscriber session.
- */
-void netns_close(u32 handle);
-
-/*
- * Calls the callback associated with the handle
- * for all existing objects with the flags
- * set to (del?NETNS_F_DEL:NETNS_F_ADD).
- */
-void netns_callme(u32 handle, char del);
-
-/*
- * netns struct format functions.
- * Taking the struct as single argument.
- */
-u8 *format_ns_neigh(u8 *s, va_list *args);
-u8 *format_ns_addr(u8 *s, va_list *args);
-u8 *format_ns_route(u8 *s, va_list *args);
-u8 *format_ns_link(u8 *s, va_list *args);
-
-u8 *format_ns_object(u8 *s, va_list *args);
-u8 *format_ns_flags(u8 *s, va_list *args);
-
-#endif
diff --git a/extras/router-plugin/devices/rtnetlink/rtnl.c b/extras/router-plugin/devices/rtnetlink/rtnl.c
deleted file mode 100644
index ed3db9e72..000000000
--- a/extras/router-plugin/devices/rtnetlink/rtnl.c
+++ /dev/null
@@ -1,604 +0,0 @@
-/*
- * Copyright (c) 2016-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.
- */
-
-#define _GNU_SOURCE
-#include <sched.h>
-
-#include <vlib/vlib.h>
-#include <vlib/unix/unix.h>
-#include <vppinfra/error.h>
-
-#include <sys/socket.h>
-#include <linux/netlink.h>
-#include <linux/rtnetlink.h>
-#include <float.h>
-#include <fcntl.h>
-
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <errno.h>
-#include <string.h>
-
-#include "netns.h"
-#include "rtnl.h"
-
-#undef DBL_MAX
-#define DBL_MAX 1000000000.0
-
-typedef enum {
- RTNL_E_OPEN,
- RTNL_E_CLOSE,
- RTNL_E_READ,
-} rtnl_event_t;
-
-typedef enum {
- RTNL_S_INIT,
- RTNL_S_SYNC,
- RTNL_S_READY,
-} rtnl_state_t;
-
-typedef enum {
- RTNL_SS_OPENING,
- RTNL_SS_LINK,
- RTNL_SS_ADDR,
- RTNL_SS_ROUTE4,
- RTNL_SS_ROUTE6,
- RTNL_SS_NEIGH,
-} rtnl_sync_state_t;
-
-typedef struct {
- rtnl_stream_t stream;
- rtnl_state_t state;
- rtnl_sync_state_t sync_state;
- int ns_fd;
- int rtnl_socket;
- u32 unix_index;
- u32 rtnl_seq;
- f64 timeout;
-} rtnl_ns_t;
-
-typedef struct {
- f64 now;
- rtnl_ns_t *streams;
-} rtnl_main_t;
-
-static rtnl_main_t rtnl_main;
-static vlib_node_registration_t rtnl_process_node;
-
-#define RTNL_BUFFSIZ 16384
-#define RTNL_DUMP_TIMEOUT 1
-
-static inline u32 grpmask(u32 g)
-{
- ASSERT (g <= 31);
- if (g) {
- return 1 << (g - 1);
- } else
- return 0;
-}
-
-
-u8 *format_rtnl_nsname2path(u8 *s, va_list *args)
-{
- char *nsname = va_arg(*args, char *);
- if (!nsname || !strlen(nsname)) {
- return format(s, "/proc/self/ns/net");
- } else if (strpbrk(nsname, "/") != NULL) {
- return format(s, "%s", nsname);
- } else {
- return format(s, "/var/run/netns/%s", nsname);
- }
-}
-
-static_always_inline void
-rtnl_schedule_timeout(rtnl_ns_t *ns, f64 when)
-{
- ns->timeout = when;
-}
-
-static_always_inline void
-rtnl_cancel_timeout(rtnl_ns_t *ns)
-{
- ns->timeout = DBL_MAX;
-}
-
-static clib_error_t *rtnl_read_cb(struct clib_file * f)
-{
- rtnl_main_t *rm = &rtnl_main;
- vlib_main_t *vm = vlib_get_main();
- rtnl_ns_t *ns = &rm->streams[f->private_data];
- vlib_process_signal_event(vm, rtnl_process_node.index, RTNL_E_READ, (uword)(ns - rm->streams));
- return 0;
-}
-
-int rtnl_dump_request(rtnl_ns_t *ns, int type, void *req, size_t len)
-{
- struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
- struct nlmsghdr nlh = {
- .nlmsg_len = NLMSG_LENGTH(len),
- .nlmsg_type = type,
- .nlmsg_flags = NLM_F_DUMP|NLM_F_REQUEST,
- .nlmsg_pid = 0,
- .nlmsg_seq = ++ns->rtnl_seq,
- };
- struct iovec iov[2] = {
- { .iov_base = &nlh, .iov_len = sizeof(nlh) },
- { .iov_base = req, .iov_len = len }
- };
- struct msghdr msg = {
- .msg_name = &nladdr,
- .msg_namelen = sizeof(nladdr),
- .msg_iov = iov,
- .msg_iovlen = 2,
- };
- if(sendmsg(ns->rtnl_socket, &msg, 0) < 0) {
- clib_warning("sendmsg error: %s", strerror(errno));
- return -1;
- }
- return 0;
-}
-
-static void rtnl_socket_close(rtnl_ns_t *ns)
-{
- clib_file_del(&file_main, &file_main.file_pool[ns->unix_index]);
- close(ns->rtnl_socket);
-}
-
-struct rtnl_thread_exec {
- int fd;
- void *(*fn)(void *);
- void *arg;
- void **ret;
-};
-
-static void *rtnl_exec_in_thread_fn(void *p)
-{
- struct rtnl_thread_exec *ex = (struct rtnl_thread_exec *) p;
- if (setns(ex->fd, 0))
- return (void *) ((uword) (-errno));
-
- *ex->ret = ex->fn(ex->arg);
- return NULL;
-}
-
-static int rtnl_exec_in_namespace_byfd(int fd, void *(*fn)(void *), void *arg, void **ret)
-{
- pthread_t thread;
- void *thread_ret;
- struct rtnl_thread_exec ex = {
- .fd = fd,
- .fn = fn,
- .arg = arg,
- .ret = ret
- };
- if(pthread_create(&thread, NULL, rtnl_exec_in_thread_fn, &ex))
- return -errno;
-
- if(pthread_join(thread, &thread_ret))
- return -errno;
-
- if (thread_ret)
- return (int) ((uword)thread_ret);
-
- return 0;
-}
-
-int rtnl_exec_in_namespace(u32 stream_index, void *(*fn)(void *), void *arg, void **ret)
-{
- rtnl_main_t *rm = &rtnl_main;
- if (pool_is_free_index(rm->streams, stream_index))
- return -EBADR;
-
- rtnl_ns_t *ns = pool_elt_at_index(rm->streams, stream_index);
- return rtnl_exec_in_namespace_byfd(ns->ns_fd, fn, arg, ret);
-}
-
-int rtnl_exec_in_namespace_by_name(char *nsname, void *(*fn)(void *), void *arg, void **ret)
-{
- int fd;
- u8 *s = format((u8 *)0, "%U", format_rtnl_nsname2path, nsname);
-
- if ((fd = open((char *)s, O_RDONLY)) < 0) {
- vec_free(s);
- return -errno;
- }
-
- int r = rtnl_exec_in_namespace_byfd(fd, fn, arg, ret);
- vec_free(s);
- close(fd);
- return r;
-}
-
-/* this function is run by the second thread */
-static void *rtnl_thread_fn(void *p)
-{
- rtnl_ns_t *ns = (rtnl_ns_t *) p;
- if (setns(ns->ns_fd, 0)) {
- clib_warning("setns(%d, %d) error %d", ns->ns_fd, CLONE_NEWNET, errno);
- return (void *) -1;
- }
-
- if ((ns->rtnl_socket = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) == -1) {
- clib_warning("Cannot open socket");
- return (void *) -2;
- }
-
- return NULL;
-}
-
-static int rtnl_socket_open(rtnl_ns_t *ns)
-{
- rtnl_main_t *rm = &rtnl_main;
- pthread_t thread;
- void *thread_ret;
- if(pthread_create(&thread, NULL, rtnl_thread_fn, ns)) {
- clib_warning("Can't create opening thread");
- return -1;
- }
-
- if(pthread_join(thread, &thread_ret)) {
- clib_warning("Can't join opening thread");
- return -2;
- }
-
- if (thread_ret) {
- clib_warning("Could not open netlink socket");
- return -3;
- }
-
- struct sockaddr_nl addr = {
- .nl_family = AF_NETLINK,
- .nl_pad = 0,
- .nl_pid = 0,
- /*add mpls message group*/
- .nl_groups = grpmask(RTNLGRP_LINK)| grpmask(RTNLGRP_IPV6_IFADDR) |
- grpmask(RTNLGRP_IPV4_IFADDR) | grpmask(RTNLGRP_IPV4_ROUTE) |
- grpmask(RTNLGRP_IPV6_ROUTE) | grpmask(RTNLGRP_NEIGH) |
- grpmask(RTNLGRP_NOTIFY) /* | grpmask(RTNLGRP_MPLS_ROUTE)*/,
- };
-
- if (bind(ns->rtnl_socket, (struct sockaddr*) &addr, sizeof(addr))) {
- close(ns->rtnl_socket);
- return -3;
- }
-
- clib_file_t template = {0};
- template.read_function = rtnl_read_cb;
- template.file_descriptor = ns->rtnl_socket;
- template.private_data = (uword) (ns - rm->streams);
- ns->unix_index = clib_file_add (&file_main, &template);
- return 0;
-}
-
-static int
-rtnl_rcv_error(rtnl_ns_t *ns, struct nlmsghdr *hdr, int *error)
-{
- struct nlmsgerr *err = NLMSG_DATA(hdr);
- size_t datalen = hdr->nlmsg_len - NLMSG_ALIGN(sizeof(*hdr));
- if(datalen < sizeof(*err))
- return -1;
-
- *error = err->error;
- return 0;
-}
-
-static void
-rtnl_sync_reset(rtnl_ns_t *ns)
-{
- if (ns->sync_state == RTNL_SS_OPENING)
- return;
-
- rtnl_socket_close(ns);
- ns->sync_state = RTNL_SS_OPENING;
-}
-
-static void
-rtnl_sync_done(rtnl_ns_t *ns)
-{
- rtnl_main_t *rm = &rtnl_main;
- struct ifaddrmsg addrmsg;
- struct rtmsg rtmsg;
- struct ndmsg ndmsg;
- switch (ns->sync_state) {
- case RTNL_SS_OPENING:
- //Cannot happen here
- break;
- case RTNL_SS_LINK:
- memset(&addrmsg, 0, sizeof(addrmsg));
- addrmsg.ifa_family = AF_UNSPEC;
- if(rtnl_dump_request(ns, RTM_GETADDR, &addrmsg, sizeof(addrmsg))) {
- rtnl_sync_reset(ns);
- rtnl_schedule_timeout(ns, rm->now + 1);
- return;
- }
- rtnl_schedule_timeout(ns, rm->now + RTNL_DUMP_TIMEOUT);
- ns->sync_state = RTNL_SS_ADDR;
- break;
- case RTNL_SS_ADDR:
- case RTNL_SS_ROUTE4:
- memset(&rtmsg, 0, sizeof(rtmsg));
- rtmsg.rtm_family = (ns->sync_state == RTNL_SS_ADDR)?AF_INET:AF_INET6;
- rtmsg.rtm_table = RT_TABLE_UNSPEC;
- if(rtnl_dump_request(ns, RTM_GETROUTE, &rtmsg, sizeof(rtmsg))) {
- rtnl_sync_reset(ns);
- rtnl_schedule_timeout(ns, rm->now + 1);
- return;
- }
- rtnl_schedule_timeout(ns, rm->now + RTNL_DUMP_TIMEOUT);
- ns->sync_state = (ns->sync_state == RTNL_SS_ADDR)?RTNL_SS_ROUTE4:RTNL_SS_ROUTE6;
- break;
- case RTNL_SS_ROUTE6:
- memset(&ndmsg, 0, sizeof(ndmsg));
- ndmsg.ndm_family = AF_UNSPEC;
- if(rtnl_dump_request(ns, RTM_GETNEIGH, &ndmsg, sizeof(ndmsg))) {
- rtnl_sync_reset(ns);
- rtnl_schedule_timeout(ns, rm->now + 1);
- return;
- }
- rtnl_schedule_timeout(ns, rm->now + RTNL_DUMP_TIMEOUT);
- ns->sync_state = RTNL_SS_NEIGH;
- break;
- case RTNL_SS_NEIGH:
- ns->state = RTNL_S_READY;
- ns->sync_state = 0;
- rtnl_cancel_timeout(ns);
- break;
- }
-}
-
-static void
-rtnl_sync_timeout(rtnl_ns_t *ns)
-{
- rtnl_main_t *rm = &rtnl_main;
- struct ifinfomsg imsg = {};
- switch (ns->sync_state) {
- case RTNL_SS_OPENING:
- if (rtnl_socket_open(ns)) {
- rtnl_schedule_timeout(ns, rm->now + 10);
- return;
- }
- imsg.ifi_family = AF_UNSPEC;
- if (rtnl_dump_request(ns, RTM_GETLINK, &imsg, sizeof(imsg))) {
- rtnl_sync_reset(ns);
- rtnl_schedule_timeout(ns, rm->now + 10);
- }
- ns->sync_state = RTNL_SS_LINK;
- rtnl_schedule_timeout(ns, rm->now + 2);
- break;
- case RTNL_SS_LINK:
- case RTNL_SS_ADDR:
- case RTNL_SS_ROUTE4:
- case RTNL_SS_ROUTE6:
- case RTNL_SS_NEIGH:
- //Timeout happened while synchronizing
- rtnl_sync_reset(ns);
- rtnl_schedule_timeout(ns, rm->now + 1);
- break;
- }
-}
-
-static int
-rtnl_ns_recv(rtnl_ns_t *ns, struct nlmsghdr *hdr)
-{
- rtnl_main_t *rm = &rtnl_main;
- int ret, error = 0;
-
- if (ns->state == RTNL_S_SYNC &&
- ((hdr->nlmsg_flags & RTM_F_NOTIFY) ||
- (hdr->nlmsg_seq != (ns->rtnl_seq)))) {
- clib_warning("Received notification while in sync. Restart synchronization.");
- rtnl_sync_reset(ns);
- rtnl_schedule_timeout(ns, rm->now);
- }
-
- switch (hdr->nlmsg_type) {
- case NLMSG_DONE:
- rtnl_sync_done(ns);
- break;
- case NLMSG_ERROR:
- if((ret = rtnl_rcv_error(ns, hdr, &error)))
- return ret;
- break;
- case RTM_NEWROUTE:
- case RTM_DELROUTE:
- case RTM_NEWLINK:
- case RTM_DELLINK:
- case RTM_NEWADDR:
- case RTM_DELADDR:
- case RTM_NEWNEIGH:
- case RTM_DELNEIGH:
- if (ns->stream.recv_message)
- ns->stream.recv_message(hdr, ns->stream.opaque);
- break;
- default:
- clib_warning("Unknown rtnetlink type %d", hdr->nlmsg_type);
- break;
- }
- return 0;
-}
-
-static void
-rtnl_process_open(rtnl_ns_t *ns)
-{
- rtnl_main_t *rm = &rtnl_main;
- if (ns->state != RTNL_S_INIT)
- return;
-
- ns->state = RTNL_S_SYNC;
- ns->sync_state = RTNL_SS_OPENING;
- rtnl_schedule_timeout(ns, rm->now);
-}
-
-static void
-rtnl_process_close(rtnl_ns_t *ns)
-{
- rtnl_main_t *rm = &rtnl_main;
- if (ns->state == RTNL_S_INIT)
- return;
-
- rtnl_socket_close(ns);
- close(ns->ns_fd);
- pool_put(rm->streams, ns);
-}
-
-static int
-rtnl_process_read(rtnl_ns_t *ns)
-{
- uint8_t buff[RTNL_BUFFSIZ];
- ssize_t len;
- struct nlmsghdr *hdr;
- while(1) {
- if((len = recv(ns->rtnl_socket, buff, RTNL_BUFFSIZ, MSG_DONTWAIT)) < 0) {
- if(errno != EAGAIN) {
- clib_warning("rtnetlink recv error (%d) [%s]: %s", ns->rtnl_socket, ns->stream.name, strerror(errno));
- return -1;
- }
- return 0;
- }
-
- for(hdr = (struct nlmsghdr *) buff;
- len > 0;
- len -= NLMSG_ALIGN(hdr->nlmsg_len),
- hdr = (struct nlmsghdr *) (((uint8_t *) hdr) + NLMSG_ALIGN(hdr->nlmsg_len))) {
- if((sizeof(*hdr) > (size_t)len) || (hdr->nlmsg_len > (size_t)len)) {
- clib_warning("rtnetlink buffer too small (%d Vs %d)", (int) hdr->nlmsg_len, (int) len);
- return -1;
- }
- if (rtnl_ns_recv(ns, hdr))
- return -1;
- }
- }
- return 0;
-}
-
-static void
-rtnl_process_timeout(rtnl_ns_t *ns)
-{
- switch (ns->state) {
- case RTNL_S_SYNC:
- rtnl_sync_timeout(ns);
- break;
- case RTNL_S_INIT:
- case RTNL_S_READY:
- clib_warning("Should not happen");
- break;
- }
-}
-
-static uword
-rtnl_process (vlib_main_t * vm,
- vlib_node_runtime_t * node,
- vlib_frame_t * frame)
-{
- rtnl_main_t *rm = &rtnl_main;
- uword event_type;
- uword *event_data = 0;
- rm->now = vlib_time_now(vm);
- f64 timeout = DBL_MAX;
- rtnl_ns_t *ns;
-
- //Setting up
- while (1) {
- vlib_process_wait_for_event_or_clock(vm, timeout - rm->now);
- event_type = vlib_process_get_events(vm, &event_data);
- rm->now = vlib_time_now(vm);
-
- if (event_type == ~0) { //Clock event or no event
- pool_foreach(ns, rm->streams, {
- if (ns->timeout < rm->now) {
- ns->timeout = DBL_MAX;
- rtnl_process_timeout(ns);
- }
- });
- } else {
- rtnl_ns_t *ns;
- uword *d;
- vec_foreach(d, event_data) {
- ns = &rm->streams[d[0]];
- switch (event_type)
- {
- case RTNL_E_CLOSE:
- rtnl_process_close(ns);
- break;
- case RTNL_E_OPEN:
- rtnl_process_open(ns);
- break;
- case RTNL_E_READ:
- rtnl_process_read(ns);
- break;
- }
- }
- }
-
- vec_reset_length (event_data);
-
- timeout = DBL_MAX;
- pool_foreach(ns, rm->streams, {
- if (ns->timeout < timeout)
- timeout = ns->timeout;
- });
- }
- return frame->n_vectors;
-}
-
-VLIB_REGISTER_NODE(rtnl_process_node, static) = {
- .function = rtnl_process,
- .name = "rtnl-process",
- .type = VLIB_NODE_TYPE_PROCESS,
-};
-
-u32
-rtnl_stream_open(rtnl_stream_t *template)
-{
- vlib_main_t *vm = vlib_get_main();
- rtnl_main_t *rm = &rtnl_main;
- rtnl_ns_t *ns;
- int fd;
- u8 *s = format((u8 *)0, "%U", format_rtnl_nsname2path, template->name);
- vec_add1(s, 0);
-
- if ((fd = open((char *)s, O_RDONLY)) < 0) {
- clib_unix_warning("open stream %s: ", s);
- vec_free(s);
- return ~0;
- }
-
- vec_free(s);
- pool_get(rm->streams, ns);
- ns->state = RTNL_S_INIT;
- ns->ns_fd = fd;
- ns->stream = *template;
- vlib_process_signal_event(vm, rtnl_process_node.index, RTNL_E_OPEN, (uword)(ns - rm->streams));
- return ns - rm->streams;
-}
-
-void
-rtnl_stream_close(u32 stream_index)
-{
- vlib_main_t *vm = vlib_get_main();
- rtnl_main_t *rm = &rtnl_main;
- ASSERT(!pool_is_free_index(rm->streams, stream_index));
- vlib_process_signal_event(vm, rtnl_process_node.index, RTNL_E_CLOSE, stream_index);
-}
-
-clib_error_t *
-rtnl_init (vlib_main_t * vm)
-{
- rtnl_main_t *rm = &rtnl_main;
- rm->streams = 0;
- return 0;
-}
-
-VLIB_INIT_FUNCTION (rtnl_init);
diff --git a/extras/router-plugin/devices/rtnetlink/rtnl.h b/extras/router-plugin/devices/rtnetlink/rtnl.h
deleted file mode 100644
index 3f96252c1..000000000
--- a/extras/router-plugin/devices/rtnetlink/rtnl.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2016-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.
- */
-
-#ifndef RTNL_H_
-#define RTNL_H_
-
-#include <vlib/vlib.h>
-
-#include <linux/netlink.h>
-#include <vppinfra/clib.h>
-
-typedef enum {
- RTNL_ERR_UNKNOWN,
-} rtnl_error_t;
-
-#define RTNL_NETNS_NAMELEN 128
-
-/*
- * RTNL stream implements an RTNL overlay
- * for receiving continuous updates for a given namespace.
- * When the stream is initially opened, dump requests are sent
- * in order to retrieve the original state.
- * handle_error is called any time synchronization cannot be
- * achieved. When called, state is reset to its original state and
- * new dump requests are sent.
- */
-
-typedef struct rtnl_stream_s {
- char name[RTNL_NETNS_NAMELEN + 1];
- void (*recv_message)(struct nlmsghdr *hdr, uword opaque);
- void (*error)(rtnl_error_t err, uword opaque);
- uword opaque;
-} rtnl_stream_t;
-
-u32 rtnl_stream_open(rtnl_stream_t *template);
-void rtnl_stream_close(u32 handle);
-
-/*
- * Executes a function in a synchronously executed thread in the
- * given namespace.
- * Returns 0 on success, and -errno on error.
- */
-int rtnl_exec_in_namespace(u32 handle, void *(*fn)(void *), void *arg, void **ret);
-int rtnl_exec_in_namespace_by_name(char *nsname, void *(*fn)(void *), void *arg, void **ret);
-
-u8 *format_rtnl_nsname2path(u8 *s, va_list *args);
-
-#endif
diff --git a/extras/router-plugin/devices/rtnetlink/test.c b/extras/router-plugin/devices/rtnetlink/test.c
deleted file mode 100644
index 031748dd3..000000000
--- a/extras/router-plugin/devices/rtnetlink/test.c
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (c) 2016-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 <librtnl/netns.h>
-
-#include <vnet/plugin/plugin.h>
-#include <librtnl/mapper.h>
-#include <vnet/ip/ip.h>
-#include <vnet/fib/fib.h>
-#include <vnet/fib/ip4_fib.h>
-#include <vnet/fib/ip6_fib.h>
-
-u32 handles[10];
-
-static void
-test_notify(void *obj, netns_type_t type, u32 flags, uword opaque) {
- u32 index = (u32) opaque;
- const char *action = (flags & NETNS_F_ADD)?"add":(flags & NETNS_F_DEL)?"del":"mod";
-
- switch (type) {
- case NETNS_TYPE_ADDR:
- clib_warning("%d: addr %s %U", index, action, format_ns_addr, (ns_addr_t *)obj);
- break;
- case NETNS_TYPE_ROUTE:
- clib_warning("%d: route %s %U", index, action, format_ns_route, (ns_route_t *)obj);
- break;
- case NETNS_TYPE_LINK:
- clib_warning("%d:link %s %U", index, action, format_ns_link, (ns_link_t *)obj);
- break;
- case NETNS_TYPE_NEIGH:
- clib_warning("%d: neigh %s %U", index, action, format_ns_neigh, (ns_neigh_t *)obj);
- break;
- }
-}
-
-static clib_error_t *
-test_enable_command_fn (vlib_main_t * vm,
- unformat_input_t * input,
- vlib_cli_command_t * cmd)
-{
- char *nsname = 0;
- u32 index;
- if (!unformat(input, "%s", &nsname)) {
- return clib_error_return(0, "unknown input `%U'",
- format_unformat_error, input);
- }
- if (!unformat(input, "%d", &index)) {
- return clib_error_return(0, "unknown input `%U'",
- format_unformat_error, input);
- }
-
- if (!strcmp(nsname, "default"))
- nsname[0] = 0;
-
- netns_sub_t sub;
- sub.notify = test_notify;
- sub.opaque = index;
- handles[index] = netns_open(nsname, &sub);
- if (handles[index] == ~0) {
- return clib_error_create("Could not open netns with name %s", nsname);
- }
- return 0;
-}
-
-static clib_error_t *
-test_disable_command_fn (vlib_main_t * vm,
- unformat_input_t * input,
- vlib_cli_command_t * cmd)
-{
- u32 index;
- if (!unformat(input, "%d", &index)) {
- return clib_error_return(0, "unknown input `%U'",
- format_unformat_error, input);
- }
-
- netns_close(handles[index]);
- return 0;
-}
-
-VLIB_CLI_COMMAND (rtnl_enable_command, static) = {
- .path = "test netns enable",
- .short_help = "test netns enable [<ns-name>|default] <index>",
- .function = test_enable_command_fn,
-};
-
-VLIB_CLI_COMMAND (rtnl_disable_command, static) = {
- .path = "test netns disable",
- .short_help = "test rtnl disable <index>",
- .function = test_disable_command_fn,
-};
-
-u32 mapper_indexes[10];
-
-static clib_error_t *
-mapper_ns_add_command_fn (vlib_main_t * vm,
- unformat_input_t * input,
- vlib_cli_command_t * cmd)
-{
- u32 index;
- char *nsname;
- u32 table_id;
- if (!unformat(input, "%d", &index))
- return clib_error_return(0, "invalid index `%U'",
- format_unformat_error, input);
- if (!unformat(input, "%s", &nsname))
- return clib_error_return(0, "invalid nsname `%U'",
- format_unformat_error, input);
- if (!unformat(input, "%d", &table_id))
- return clib_error_return(0, "invalid fib index `%U'",
- format_unformat_error, input);
-
- if (!strcmp(nsname, "default"))
- nsname[0] = 0;
-
- u32 fib4 = ip4_fib_index_from_table_id(table_id);
- u32 fib6 = ip6_fib_index_from_table_id(table_id);
-
- if (mapper_add_ns(nsname, fib4, fib6, &mapper_indexes[index]))
- return clib_error_return(0, "Could not add ns %s", nsname);
- return 0;
-}
-
-VLIB_CLI_COMMAND (mapper_ns_add_command, static) = {
- .path = "test mapper ns add",
- .short_help = "test mapper ns add <index> <nsname> <table-id>",
- .function = mapper_ns_add_command_fn,
-};
-
-static clib_error_t *
-mapper_ns_del_command_fn (vlib_main_t * vm,
- unformat_input_t * input,
- vlib_cli_command_t * cmd)
-{
- u32 index;
- if (!unformat(input, "%d", &index))
- return clib_error_return(0, "invalid index `%U'",
- format_unformat_error, input);
-
- if (mapper_del_ns(mapper_indexes[index]))
- return clib_error_return(0, "Could not del ns %d", index);
- return 0;
-}
-
-VLIB_CLI_COMMAND (mapper_ns_del_command, static) = {
- .path = "test mapper ns delete",
- .short_help = "test mapper ns delete <index>",
- .function = mapper_ns_del_command_fn,
-};
-
-static clib_error_t *
-mapper_iface_command_fn (vlib_main_t * vm,
- unformat_input_t * input,
- vlib_cli_command_t * cmd)
-{
- u32 nsindex;
- u32 ifindex;
- u32 sw_if_index;
- int del = 0;
- if (!unformat(input, "%d", &nsindex))
- return clib_error_return(0, "invalid nsindex `%U'",
- format_unformat_error, input);
- if (!unformat(input, "%d", &ifindex))
- return clib_error_return(0, "invalid ifindex `%U'",
- format_unformat_error, input);
- if (!unformat(input, "%d", &sw_if_index))
- return clib_error_return(0, "invalid sw_if_index `%U'",
- format_unformat_error, input);
- if (unformat(input, "del"))
- del = 1;
-
- clib_warning("mapper_add_del %d %d %d %d", mapper_indexes[nsindex], ifindex, sw_if_index, del);
-
- if (mapper_add_del(mapper_indexes[nsindex], ifindex, sw_if_index, del))
- return clib_error_return(0, "Could not add iface");
- return 0;
-}
-
-
-VLIB_CLI_COMMAND (mapper_iface_command, static) = {
- .path = "test mapper iface",
- .short_help = "test mapper iface <nsindex> <linux-ifindex> <sw_if_index> [del]",
- .function = mapper_iface_command_fn,
-};
-
-/* *INDENT-OFF* */
-VLIB_PLUGIN_REGISTER () = {
- //.version = VPP_BUILD_VER, FIXME
- .description = "netlink",
-};
-/* *INDENT-ON* */
-
diff --git a/extras/router-plugin/rtinject/tap_inject.c b/extras/router-plugin/rtinject/tap_inject.c
deleted file mode 100644
index f41ae86c8..000000000
--- a/extras/router-plugin/rtinject/tap_inject.c
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * Copyright 2016 Intel Corporation
- *
- * Licensed under the Apache License, Version 2.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 "tap_inject.h"
-
-#include <vnet/mfib/mfib_table.h>
-#include <vnet/ip/ip.h>
-#include <vnet/ip/lookup.h>
-#include <vnet/fib/fib.h>
-
-static tap_inject_main_t tap_inject_main;
-extern dpo_type_t tap_inject_dpo_type;
-
-tap_inject_main_t *
-tap_inject_get_main (void)
-{
- return &tap_inject_main;
-}
-
-void
-tap_inject_insert_tap (u32 sw_if_index, u32 tap_fd, u32 tap_if_index)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- vec_validate_init_empty (im->sw_if_index_to_tap_fd, sw_if_index, ~0);
- vec_validate_init_empty (im->sw_if_index_to_tap_if_index, sw_if_index, ~0);
-
- vec_validate_init_empty (im->tap_fd_to_sw_if_index, tap_fd, ~0);
-
- im->sw_if_index_to_tap_fd[sw_if_index] = tap_fd;
- im->sw_if_index_to_tap_if_index[sw_if_index] = tap_if_index;
-
- im->tap_fd_to_sw_if_index[tap_fd] = sw_if_index;
-
- hash_set (im->tap_if_index_to_sw_if_index, tap_if_index, sw_if_index);
-}
-
-void
-tap_inject_delete_tap (u32 sw_if_index)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
- u32 tap_fd = im->sw_if_index_to_tap_fd[sw_if_index];
- u32 tap_if_index = im->sw_if_index_to_tap_if_index[sw_if_index];
-
- im->sw_if_index_to_tap_if_index[sw_if_index] = ~0;
- im->sw_if_index_to_tap_fd[sw_if_index] = ~0;
- im->tap_fd_to_sw_if_index[tap_fd] = ~0;
-
- hash_unset (im->tap_if_index_to_sw_if_index, tap_if_index);
-}
-
-u32
-tap_inject_lookup_tap_fd (u32 sw_if_index)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- vec_validate_init_empty (im->sw_if_index_to_tap_fd, sw_if_index, ~0);
- return im->sw_if_index_to_tap_fd[sw_if_index];
-}
-
-u32
-tap_inject_lookup_sw_if_index_from_tap_fd (u32 tap_fd)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- vec_validate_init_empty (im->tap_fd_to_sw_if_index, tap_fd, ~0);
- return im->tap_fd_to_sw_if_index[tap_fd];
-}
-
-u32
-tap_inject_lookup_sw_if_index_from_tap_if_index (u32 tap_if_index)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
- uword * sw_if_index;
-
- sw_if_index = hash_get (im->tap_if_index_to_sw_if_index, tap_if_index);
- return sw_if_index ? *(u32 *)sw_if_index : ~0;
-}
-
-/* *INDENT-OFF* */
-VLIB_PLUGIN_REGISTER () = {
- // .version = VPP_BUILD_VER, FIXME
- .description = "router",
-};
-/* *INDENT-ON* */
-
-
-static void
-tap_inject_disable (void)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- im->flags &= ~TAP_INJECT_F_ENABLED;
-
- clib_warning ("tap-inject is not actually disabled.");
-}
-
-static clib_error_t *
-tap_inject_enable (void)
-{
- vlib_main_t * vm = vlib_get_main ();
- tap_inject_main_t * im = tap_inject_get_main ();
-
- if (tap_inject_is_enabled ())
- return 0;
-
- tap_inject_enable_netlink ();
-
- /* Only enable netlink? */
- if (im->flags & TAP_INJECT_F_CONFIG_NETLINK)
- {
- im->flags |= TAP_INJECT_F_ENABLED;
- return 0;
- }
-
- /* Register ARP and ICMP6 as neighbor nodes. */
- ethernet_register_input_type (vm, ETHERNET_TYPE_ARP, im->neighbor_node_index);
- ip6_register_protocol (IP_PROTOCOL_ICMP6, im->neighbor_node_index);
-
- /* Register remaining protocols. */
- ip4_register_protocol (IP_PROTOCOL_ICMP, im->tx_node_index);
-
- ip4_register_protocol (IP_PROTOCOL_OSPF, im->tx_node_index);
- ip4_register_protocol (IP_PROTOCOL_TCP, im->tx_node_index);
- ip4_register_protocol (IP_PROTOCOL_UDP, im->tx_node_index);
-
- ip6_register_protocol (IP_PROTOCOL_OSPF, im->tx_node_index);
- ip6_register_protocol (IP_PROTOCOL_TCP, im->tx_node_index);
- ip6_register_protocol (IP_PROTOCOL_UDP, im->tx_node_index);
-
- {
- dpo_id_t dpo = DPO_INVALID;
-
- const mfib_prefix_t pfx_224_0_0_0 = {
- .fp_len = 24,
- .fp_proto = FIB_PROTOCOL_IP4,
- .fp_grp_addr = {
- .ip4.as_u32 = clib_host_to_net_u32(0xe0000000),
- },
- .fp_src_addr = {
- .ip4.as_u32 = 0,
- },
- };
-
- dpo_set(&dpo, tap_inject_dpo_type, DPO_PROTO_IP4, ~0);
-
- index_t repi = replicate_create(1, DPO_PROTO_IP4);
- replicate_set_bucket(repi, 0, &dpo);
-
- mfib_table_entry_special_add(0,
- &pfx_224_0_0_0,
- MFIB_SOURCE_API,
- MFIB_ENTRY_FLAG_ACCEPT_ALL_ITF,
- repi);
-
- dpo_reset(&dpo);
- }
-
- im->flags |= TAP_INJECT_F_ENABLED;
-
- return 0;
-}
-
-static uword
-tap_inject_iface_isr (vlib_main_t * vm, vlib_node_runtime_t * node,
- vlib_frame_t * f)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
- vnet_hw_interface_t * hw;
- u32 * hw_if_index;
- clib_error_t * err = 0;
-
- vec_foreach (hw_if_index, im->interfaces_to_enable)
- {
- hw = vnet_get_hw_interface (vnet_get_main (), *hw_if_index);
-
- if (hw->hw_class_index == ethernet_hw_interface_class.index)
- {
- err = tap_inject_tap_connect (hw);
- if (err)
- break;
- }
- }
-
- vec_foreach (hw_if_index, im->interfaces_to_disable)
- tap_inject_tap_disconnect (*hw_if_index);
-
- vec_free (im->interfaces_to_enable);
- vec_free (im->interfaces_to_disable);
-
- return err ? -1 : 0;
-}
-
-VLIB_REGISTER_NODE (tap_inject_iface_isr_node, static) = {
- .function = tap_inject_iface_isr,
- .name = "tap-inject-iface-isr",
- .type = VLIB_NODE_TYPE_INPUT,
- .state = VLIB_NODE_STATE_INTERRUPT,
- .vector_size = sizeof (u32),
-};
-
-
-static clib_error_t *
-tap_inject_interface_add_del (struct vnet_main_t * vnet_main, u32 hw_if_index,
- u32 add)
-{
- vlib_main_t * vm = vlib_get_main ();
- tap_inject_main_t * im = tap_inject_get_main ();
-
- if (!tap_inject_is_config_enabled ())
- return 0;
-
- tap_inject_enable ();
-
- if (add)
- vec_add1 (im->interfaces_to_enable, hw_if_index);
- else
- vec_add1 (im->interfaces_to_disable, hw_if_index);
-
- vlib_node_set_interrupt_pending (vm, tap_inject_iface_isr_node.index);
-
- return 0;
-}
-
-VNET_HW_INTERFACE_ADD_DEL_FUNCTION (tap_inject_interface_add_del);
-
-
-static clib_error_t *
-tap_inject_enable_disable_all_interfaces (int enable)
-{
- vnet_main_t * vnet_main = vnet_get_main ();
- tap_inject_main_t * im = tap_inject_get_main ();
- vnet_hw_interface_t * interfaces;
- vnet_hw_interface_t * hw;
- u32 ** indices;
-
- if (enable)
- tap_inject_enable ();
- else
- tap_inject_disable ();
-
- /* Collect all the interface indices. */
- interfaces = vnet_main->interface_main.hw_interfaces;
- indices = enable ? &im->interfaces_to_enable : &im->interfaces_to_disable;
- pool_foreach (hw, interfaces, vec_add1 (*indices, hw - interfaces));
-
- if (tap_inject_iface_isr (vlib_get_main (), 0, 0))
- return clib_error_return (0, "tap-inject interface add del isr failed");
-
- return 0;
-}
-
-static clib_error_t *
-tap_inject_cli (vlib_main_t * vm, unformat_input_t * input,
- vlib_cli_command_t * cmd)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- if (cmd->function_arg)
- {
- clib_error_t * err;
-
- if (tap_inject_is_config_disabled ())
- return clib_error_return (0,
- "tap-inject is disabled in config, thus cannot be enabled.");
-
- /* Enable */
- err = tap_inject_enable_disable_all_interfaces (1);
- if (err)
- {
- tap_inject_enable_disable_all_interfaces (0);
- return err;
- }
-
- im->flags |= TAP_INJECT_F_CONFIG_ENABLE;
- }
- else
- {
- /* Disable */
- tap_inject_enable_disable_all_interfaces (0);
- im->flags &= ~TAP_INJECT_F_CONFIG_ENABLE;
- }
-
- return 0;
-}
-
-VLIB_CLI_COMMAND (tap_inject_enable_cmd, static) = {
- .path = "enable tap-inject",
- .short_help = "enable tap-inject",
- .function = tap_inject_cli,
- .function_arg = 1,
-};
-
-VLIB_CLI_COMMAND (tap_inject_disable_cmd, static) = {
- .path = "disable tap-inject",
- .short_help = "disable tap-inject",
- .function = tap_inject_cli,
- .function_arg = 0,
-};
-
-
-static clib_error_t *
-show_tap_inject (vlib_main_t * vm, unformat_input_t * input,
- vlib_cli_command_t * cmd)
-{
- vnet_main_t * vnet_main = vnet_get_main ();
- tap_inject_main_t * im = tap_inject_get_main ();
- u32 k, v;
-
- if (tap_inject_is_config_disabled ())
- {
- vlib_cli_output (vm, "tap-inject is disabled in config.\n");
- return 0;
- }
-
- if (!tap_inject_is_enabled ())
- {
- vlib_cli_output (vm, "tap-inject is not enabled.\n");
- return 0;
- }
-
- hash_foreach (k, v, im->tap_if_index_to_sw_if_index, {
- vlib_cli_output (vm, "%U -> %U",
- format_vnet_sw_interface_name, vnet_main,
- vnet_get_sw_interface (vnet_main, v),
- format_tap_inject_tap_name, k);
- });
-
- return 0;
-}
-
-VLIB_CLI_COMMAND (show_tap_inject_cmd, static) = {
- .path = "show tap-inject",
- .short_help = "show tap-inject",
- .function = show_tap_inject,
-};
-
-
-static clib_error_t *
-tap_inject_config (vlib_main_t * vm, unformat_input_t * input)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
- {
- if (unformat (input, "enable"))
- im->flags |= TAP_INJECT_F_CONFIG_ENABLE;
-
- else if (unformat (input, "disable"))
- im->flags |= TAP_INJECT_F_CONFIG_DISABLE;
-
- else if (unformat (input, "netlink-only"))
- im->flags |= TAP_INJECT_F_CONFIG_NETLINK;
-
- else
- return clib_error_return (0, "syntax error `%U'",
- format_unformat_error, input);
- }
-
- if (tap_inject_is_config_enabled () && tap_inject_is_config_disabled ())
- return clib_error_return (0,
- "tap-inject cannot be both enabled and disabled.");
-
- return 0;
-}
-
-VLIB_CONFIG_FUNCTION (tap_inject_config, "tap-inject");
diff --git a/extras/router-plugin/rtinject/tap_inject.h b/extras/router-plugin/rtinject/tap_inject.h
deleted file mode 100644
index ec5121a09..000000000
--- a/extras/router-plugin/rtinject/tap_inject.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright 2016 Intel Corporation
- *
- * Licensed under the Apache License, Version 2.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.
- */
-
-#ifndef _TAP_INJECT_H
-#define _TAP_INJECT_H
-
-#include <vnet/plugin/plugin.h>
-#include <vnet/ip/ip.h>
-
-#ifndef ETHER_ADDR_LEN
-#define ETHER_ADDR_LEN 6
-#endif
-
-typedef struct {
- /*
- * tap-inject can be enabled or disabled in config file or during runtime.
- * When disabled in config, it is not possible to enable during runtime.
- *
- * When the netlink-only option is used, netlink configuration is monitored
- * and mirrored to the data plane but no traffic is passed between the host
- * and the data plane.
- */
-#define TAP_INJECT_F_CONFIG_ENABLE (1U << 0)
-#define TAP_INJECT_F_CONFIG_DISABLE (1U << 1)
-#define TAP_INJECT_F_CONFIG_NETLINK (1U << 2)
-#define TAP_INJECT_F_ENABLED (1U << 3)
-
- u32 flags;
-
- u32 * sw_if_index_to_tap_fd;
- u32 * sw_if_index_to_tap_if_index;
- u32 * tap_fd_to_sw_if_index;
- u32 * tap_if_index_to_sw_if_index;
-
- u32 * interfaces_to_enable;
- u32 * interfaces_to_disable;
-
- u32 * rx_file_descriptors;
-
- u32 rx_node_index;
- u32 tx_node_index;
- u32 neighbor_node_index;
-
- u32 * rx_buffers;
-
-} tap_inject_main_t;
-
-
-tap_inject_main_t * tap_inject_get_main (void);
-
-void tap_inject_insert_tap (u32 sw_if_index, u32 tap_fd, u32 tap_if_index);
-void tap_inject_delete_tap (u32 sw_if_index);
-
-u32 tap_inject_lookup_tap_fd (u32 sw_if_index);
-u32 tap_inject_lookup_sw_if_index_from_tap_fd (u32 tap_fd);
-u32 tap_inject_lookup_sw_if_index_from_tap_if_index (u32 tap_if_index);
-
-static inline int
-tap_inject_is_enabled (void)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- return !!(im->flags & TAP_INJECT_F_ENABLED);
-}
-
-static inline int
-tap_inject_is_config_enabled (void)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- return !!(im->flags & TAP_INJECT_F_CONFIG_ENABLE);
-}
-
-static inline int
-tap_inject_is_config_disabled (void)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- return !!(im->flags & TAP_INJECT_F_CONFIG_DISABLE);
-}
-
-
-/* Netlink */
-
-void tap_inject_enable_netlink (void);
-
-
-/* Tap */
-
-clib_error_t * tap_inject_tap_connect (vnet_hw_interface_t * hw);
-clib_error_t * tap_inject_tap_disconnect (u32 sw_if_index);
-
-u8 * format_tap_inject_tap_name (u8 * s, va_list * args);
-
-#endif /* _TAP_INJECT_H */
diff --git a/extras/router-plugin/rtinject/tap_inject_netlink.c b/extras/router-plugin/rtinject/tap_inject_netlink.c
deleted file mode 100644
index a221e8eaa..000000000
--- a/extras/router-plugin/rtinject/tap_inject_netlink.c
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright 2016 Intel Corporation
- *
- * Licensed under the Apache License, Version 2.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 "../devices/rtnetlink/netns.h"
-#include <vlibmemory/api.h>
-#include <vnet/ip/ip6_neighbor.h>
-#include <vnet/ip/lookup.h>
-#include <vnet/fib/fib.h>
-#include <vnet/ethernet/arp.h>
-#include <arpa/inet.h>
-#include <linux/mpls.h>
-#include <vnet/mpls/packet.h>
-
-#include "tap_inject.h"
-
-static void
-add_del_addr (ns_addr_t * a, int is_del)
-{
- vlib_main_t * vm = vlib_get_main ();
- u32 sw_if_index;
-
- sw_if_index = tap_inject_lookup_sw_if_index_from_tap_if_index (
- a->ifaddr.ifa_index);
-
- if (sw_if_index == ~0)
- return;
-
- if (a->ifaddr.ifa_family == AF_INET)
- {
- ip4_add_del_interface_address (vm, sw_if_index,
- (ip4_address_t *) a->local, a->ifaddr.ifa_prefixlen, is_del);
- }
- else if (a->ifaddr.ifa_family == AF_INET6)
- {
- ip6_add_del_interface_address (vm, sw_if_index,
- (ip6_address_t *) a->addr, a->ifaddr.ifa_prefixlen, is_del);
- }
-}
-
-
-struct set_flags_args {
- u32 index;
- u8 flags;
-};
-
-static void
-set_flags_cb (struct set_flags_args * a)
-{
- vnet_sw_interface_set_flags (vnet_get_main (), a->index, a->flags);
-}
-
-static void
-add_del_link (ns_link_t * l, int is_del)
-{
- struct set_flags_args args = { ~0, 0 };
- vnet_sw_interface_t * sw;
- u8 flags = 0;
- u32 sw_if_index;
-
- sw_if_index = tap_inject_lookup_sw_if_index_from_tap_if_index (
- l->ifi.ifi_index);
-
- if (sw_if_index == ~0)
- return;
-
- sw = vnet_get_sw_interface (vnet_get_main (), sw_if_index);
-
- flags = sw->flags;
-
- if (l->ifi.ifi_flags & IFF_UP)
- flags |= VNET_SW_INTERFACE_FLAG_ADMIN_UP;
- else
- flags &= ~VNET_SW_INTERFACE_FLAG_ADMIN_UP;
-
- args.index = sw_if_index;
- args.flags = flags;
-
- vl_api_rpc_call_main_thread (set_flags_cb, (u8 *)&args, sizeof (args));
-}
-
-
-static void
-add_del_neigh (ns_neigh_t * n, int is_del)
-{
- vnet_main_t * vnet_main = vnet_get_main ();
- vlib_main_t * vm = vlib_get_main ();
- u32 sw_if_index;
-
- sw_if_index = tap_inject_lookup_sw_if_index_from_tap_if_index (
- n->nd.ndm_ifindex);
-
- if (sw_if_index == ~0)
- return;
-
- if (n->nd.ndm_family == AF_INET)
- {
- ethernet_arp_ip4_over_ethernet_address_t a;
-
- memset (&a, 0, sizeof (a));
-
- clib_memcpy (&a.mac, n->lladdr, ETHER_ADDR_LEN);
- clib_memcpy (&a.ip4, n->dst, sizeof (a.ip4));
-
-
- if (n->nd.ndm_state & NUD_REACHABLE)
- {
- vnet_arp_set_ip4_over_ethernet (vnet_main, sw_if_index,
- &a,
- IP_NEIGHBOR_FLAG_NO_FIB_ENTRY);
-
- }
- else if (n->nd.ndm_state & NUD_FAILED)
- {
- vnet_arp_unset_ip4_over_ethernet (vnet_main, sw_if_index, &a);
- }
- }
- else if (n->nd.ndm_family == AF_INET6)
- {
- if (n->nd.ndm_state & NUD_REACHABLE)
- {
-
- mac_address_t * mac1;
- mac1=malloc(sizeof(mac_address_t));
- memcpy (mac1, n->lladdr, ETHER_ADDR_LEN);
- vnet_set_ip6_ethernet_neighbor (vm, sw_if_index,
- (ip6_address_t *) n->dst, (mac_address_t *) mac1,
- IP_NEIGHBOR_FLAG_NONE);
- }
- else
- vnet_unset_ip6_ethernet_neighbor (vm, sw_if_index,
- (ip6_address_t *) n->dst);
- }
-}
-
-
-#define TAP_INJECT_HOST_ROUTE_TABLE_MAIN 254
-
-static void
-get_mpls_label_stack(struct mpls_label *addr, u32* l)
-{
- u32 entry = ntohl(addr[0].entry);
- u32 label = (entry & MPLS_LS_LABEL_MASK) >> MPLS_LS_LABEL_SHIFT;
-
- for(int i = 1; label != 0; i++) {
- *l++ = label;
- if(entry & MPLS_LS_S_MASK)
- return;
- entry = ntohl(addr[i].entry);
- label = (entry & MPLS_LS_LABEL_MASK) >> MPLS_LS_LABEL_SHIFT;
- }
-}
-
-static void
-add_del_route (ns_route_t * r, int is_del)
-{
- u32 sw_if_index;
-
- sw_if_index = tap_inject_lookup_sw_if_index_from_tap_if_index (r->oif);
-
- if (sw_if_index == ~0)
- return;
-
- if (r->rtm.rtm_family == AF_INET)
- {
- u32 stack[MPLS_STACK_DEPTH] = {0};
-
- fib_prefix_t prefix;
- ip46_address_t nh;
-
- memset (&prefix, 0, sizeof (prefix));
- prefix.fp_len = r->rtm.rtm_dst_len;
- prefix.fp_proto = FIB_PROTOCOL_IP4;
- clib_memcpy (&prefix.fp_addr.ip4, r->dst, sizeof (prefix.fp_addr.ip4));
- get_mpls_label_stack(r->encap, stack);
- memset (&nh, 0, sizeof (nh));
- clib_memcpy (&nh.ip4, r->gateway, sizeof (nh.ip4));
- if(*stack == 0)
- fib_table_entry_path_add (0, &prefix, FIB_SOURCE_API,
- FIB_ENTRY_FLAG_NONE, prefix.fp_proto,
- &nh, sw_if_index, 0,
- 0 /* weight */, NULL,
- FIB_ROUTE_PATH_FLAG_NONE);
- else {
- fib_route_path_t *rpaths = NULL, rpath;
- memset(&rpath, 0, sizeof(rpath));
- rpath.frp_weight = 1;
- rpath.frp_proto = DPO_PROTO_IP4;
- clib_memcpy(&rpath.frp_addr.ip4, r->gateway, sizeof(rpath.frp_addr.ip4));
- rpath.frp_sw_if_index = sw_if_index;
- for(int i = 0; i < MPLS_STACK_DEPTH && stack[i] != 0; i++) {
- fib_mpls_label_t fib_label = {stack[i],0,0,0};
- vec_add1(rpath.frp_label_stack, fib_label);
- }
- vec_add1(rpaths, rpath);
- fib_table_entry_path_add2(0,
- &prefix,
- FIB_SOURCE_API,
- FIB_ENTRY_FLAG_NONE,
- rpaths);
- }
- }
- else if (r->rtm.rtm_family == AF_INET6)
- {
- fib_prefix_t prefix;
- ip46_address_t nh;
- memset (&prefix, 0, sizeof (prefix));
- prefix.fp_len = r->rtm.rtm_dst_len;
- prefix.fp_proto = FIB_PROTOCOL_IP6;
- clib_memcpy (&prefix.fp_addr.ip6, r->dst, sizeof (prefix.fp_addr.ip6));
- memset (&nh, 0, sizeof (nh));
- clib_memcpy (&nh.ip6, r->gateway, sizeof (nh.ip6));
- fib_table_entry_path_add (0, &prefix, FIB_SOURCE_API,
- FIB_ENTRY_FLAG_NONE, prefix.fp_proto,
- &nh, sw_if_index, 0,
- 0 /* weight */, NULL,
- FIB_ROUTE_PATH_FLAG_NONE);
- }
-/* else if (r->rtm.rtm_family == AF_MPLS)
- {
- u32 dst_label;
- get_mpls_label_stack((struct mpls_label*) r->dst, &dst_label);
- struct rtvia *via = (struct rtvia*) r->via;
- fib_prefix_t prefix;
- fib_route_path_t *rpaths = NULL, rpath;
- memset (&prefix, 0, sizeof (prefix));
- prefix.fp_len = 21;
- prefix.fp_label = dst_label;
- prefix.fp_proto = FIB_PROTOCOL_MPLS;
- prefix.fp_payload_proto = DPO_PROTO_IP4;
- memset(&rpath, 0, sizeof(rpath));
- clib_memcpy (&rpath.frp_addr.ip4, via->rtvia_addr, sizeof (rpath.frp_addr.ip4));
- rpath.frp_weight = 1;
- rpath.frp_proto = DPO_PROTO_IP4;
- rpath.frp_fib_index = 0;
- rpath.frp_sw_if_index = sw_if_index;
- vec_add1(rpaths, rpath);
- fib_table_entry_path_add2(0,
- &prefix,
- FIB_SOURCE_API,
- FIB_ENTRY_FLAG_NONE,
- rpaths);
- }*/
-}
-
-
-static void
-netns_notify_cb (void * obj, netns_type_t type, u32 flags, uword opaque)
-{
- if (type == NETNS_TYPE_ADDR)
- add_del_addr ((ns_addr_t *)obj, flags & NETNS_F_DEL);
-
- else if (type == NETNS_TYPE_LINK)
- add_del_link ((ns_link_t *)obj, flags & NETNS_F_DEL);
-
- else if (type == NETNS_TYPE_NEIGH)
- add_del_neigh ((ns_neigh_t *)obj, flags & NETNS_F_DEL);
-
- else if (type == NETNS_TYPE_ROUTE)
- add_del_route ((ns_route_t *)obj, flags & NETNS_F_DEL);
-}
-
-void
-tap_inject_enable_netlink (void)
-{
- char nsname = 0;
- netns_sub_t sub = {
- .notify = netns_notify_cb,
- .opaque = 0,
- };
-
- netns_open (&nsname, &sub);
-}
diff --git a/extras/router-plugin/rtinject/tap_inject_node.c b/extras/router-plugin/rtinject/tap_inject_node.c
deleted file mode 100644
index 73c296451..000000000
--- a/extras/router-plugin/rtinject/tap_inject_node.c
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright 2016 Intel Corporation
- *
- * Licensed under the Apache License, Version 2.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 "tap_inject.h"
-#include <sys/uio.h>
-#include <netinet/in.h>
-#include <vnet/ethernet/arp_packet.h>
-
-vlib_node_registration_t tap_inject_rx_node;
-vlib_node_registration_t tap_inject_tx_node;
-vlib_node_registration_t tap_inject_neighbor_node;
-
-enum {
- NEXT_NEIGHBOR_ARP,
- NEXT_NEIGHBOR_ICMP6,
-};
-
-/**
- * @brief Dynamically added tap_inject DPO type
- */
-dpo_type_t tap_inject_dpo_type;
-
-static inline void
-tap_inject_tap_send_buffer (int fd, vlib_buffer_t * b)
-{
- struct iovec iov;
- ssize_t n_bytes;
-
- iov.iov_base = vlib_buffer_get_current (b);
- iov.iov_len = b->current_length;
-
- n_bytes = writev (fd, &iov, 1);
-
- if (n_bytes < 0)
- clib_warning ("writev failed");
- else if (n_bytes < b->current_length || b->flags & VLIB_BUFFER_NEXT_PRESENT)
- clib_warning ("buffer truncated");
-}
-
-static uword
-tap_inject_tx (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * f)
-{
- vlib_buffer_t * b;
- u32 * pkts;
- u32 fd;
- u32 i;
-
- pkts = vlib_frame_vector_args (f);
-
- for (i = 0; i < f->n_vectors; ++i)
- {
- b = vlib_get_buffer (vm, pkts[i]);
-
- fd = tap_inject_lookup_tap_fd (vnet_buffer (b)->sw_if_index[VLIB_RX]);
- if (fd == ~0)
- continue;
-
- /* Re-wind the buffer to the start of the Ethernet header. */
- vlib_buffer_advance (b, -b->current_data);
-
- tap_inject_tap_send_buffer (fd, b);
- }
-
- vlib_buffer_free (vm, pkts, f->n_vectors);
- return f->n_vectors;
-}
-
-VLIB_REGISTER_NODE (tap_inject_tx_node) = {
- .function = tap_inject_tx,
- .name = "tap-inject-tx",
- .vector_size = sizeof (u32),
- .type = VLIB_NODE_TYPE_INTERNAL,
-};
-
-
-static uword
-tap_inject_neighbor (vlib_main_t * vm,
- vlib_node_runtime_t * node, vlib_frame_t * f)
-{
- vlib_buffer_t * b;
- u32 * pkts;
- u32 fd;
- u32 i;
- u32 bi;
- u32 next_index = node->cached_next_index;
- u32 next = ~0;
- u32 n_left;
- u32 * to_next;
-
- pkts = vlib_frame_vector_args (f);
-
- for (i = 0; i < f->n_vectors; ++i)
- {
- bi = pkts[i];
- b = vlib_get_buffer (vm, bi);
-
- fd = tap_inject_lookup_tap_fd (vnet_buffer (b)->sw_if_index[VLIB_RX]);
- if (fd == ~0)
- {
- vlib_buffer_free (vm, &bi, 1);
- continue;
- }
-
- /* Re-wind the buffer to the start of the Ethernet header. */
- vlib_buffer_advance (b, -b->current_data);
-
- tap_inject_tap_send_buffer (fd, b);
-
- /* Send the buffer to a neighbor node too? */
- {
- ethernet_header_t * eth = vlib_buffer_get_current (b);
- u16 ether_type = htons (eth->type);
-
- if (ether_type == ETHERNET_TYPE_ARP)
- {
- ethernet_arp_header_t * arp = (void *)(eth + 1);
-
- if (arp->opcode == ntohs (ETHERNET_ARP_OPCODE_reply))
- next = NEXT_NEIGHBOR_ARP;
- }
- else if (ether_type == ETHERNET_TYPE_IP6)
- {
- ip6_header_t * ip = (void *)(eth + 1);
- icmp46_header_t * icmp = (void *)(ip + 1);
-
- if (ip->protocol == IP_PROTOCOL_ICMP6 &&
- icmp->type == ICMP6_neighbor_advertisement)
- next = NEXT_NEIGHBOR_ICMP6;
- }
- }
-
- if (next == ~0)
- {
- vlib_buffer_free (vm, &bi, 1);
- continue;
- }
-
- /* ARP and ICMP6 expect to start processing after the Ethernet header. */
- vlib_buffer_advance (b, sizeof (ethernet_header_t));
-
- vlib_get_next_frame (vm, node, next_index, to_next, n_left);
-
- *(to_next++) = bi;
- --n_left;
-
- vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
- n_left, bi, next);
- vlib_put_next_frame (vm, node, next_index, n_left);
- }
-
- return f->n_vectors;
-}
-
-VLIB_REGISTER_NODE (tap_inject_neighbor_node) = {
- .function = tap_inject_neighbor,
- .name = "tap-inject-neighbor",
- .vector_size = sizeof (u32),
- .type = VLIB_NODE_TYPE_INTERNAL,
- .n_next_nodes = 2,
- .next_nodes = {
- [NEXT_NEIGHBOR_ARP] = "arp-input",
- [NEXT_NEIGHBOR_ICMP6] = "icmp6-neighbor-solicitation",
- },
-};
-
-
-#define MTU 1500
-#define MTU_BUFFERS ((MTU + vlib_buffer_get_default_data_size(vm) - 1) / vlib_buffer_get_default_data_size(vm))
-#define NUM_BUFFERS_TO_ALLOC 32
-
-static inline uword
-tap_rx (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * f, int fd)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
- u32 sw_if_index;
- struct iovec iov[MTU_BUFFERS];
- u32 bi[MTU_BUFFERS];
- vlib_buffer_t * b;
- ssize_t n_bytes;
- ssize_t n_bytes_left;
- u32 i, j;
-
- sw_if_index = tap_inject_lookup_sw_if_index_from_tap_fd (fd);
- if (sw_if_index == ~0)
- return 0;
-
- /* Allocate buffers in bulk when there are less than enough to rx an MTU. */
- if (vec_len (im->rx_buffers) < MTU_BUFFERS)
- {
- u32 len = vec_len (im->rx_buffers);
-
-
- u8 index = vlib_buffer_pool_get_default_for_numa (vm,0);
- len = vlib_buffer_alloc_from_pool(vm,
- &im->rx_buffers[len], NUM_BUFFERS_TO_ALLOC,
- index);
-
- _vec_len (im->rx_buffers) += len;
-
- if (vec_len (im->rx_buffers) < MTU_BUFFERS)
- {
- clib_warning ("failed to allocate buffers");
- return 0;
- }
- }
-
- /* Fill buffers from the end of the list to make it easier to resize. */
- for (i = 0, j = vec_len (im->rx_buffers) - 1; i < MTU_BUFFERS; ++i, --j)
- {
- vlib_buffer_t * b;
-
- bi[i] = im->rx_buffers[j];
-
- b = vlib_get_buffer (vm, bi[i]);
-
- iov[i].iov_base = b->data;
- iov[i].iov_len = VLIB_BUFFER_DEFAULT_DATA_SIZE;
- }
-
- n_bytes = readv (fd, iov, MTU_BUFFERS);
- if (n_bytes < 0)
- {
- clib_warning ("readv failed");
- return 0;
- }
-
- b = vlib_get_buffer (vm, bi[0]);
-
- vnet_buffer (b)->sw_if_index[VLIB_RX] = sw_if_index;
- vnet_buffer (b)->sw_if_index[VLIB_TX] = sw_if_index;
-
- n_bytes_left = n_bytes - VLIB_BUFFER_DEFAULT_DATA_SIZE;
-
- if (n_bytes_left > 0)
- {
- b->total_length_not_including_first_buffer = n_bytes_left;
- b->flags |= VLIB_BUFFER_TOTAL_LENGTH_VALID;
- }
-
- b->current_length = n_bytes;
-
- /* If necessary, configure any remaining buffers in the chain. */
- for (i = 1; n_bytes_left > 0; ++i, n_bytes_left -= VLIB_BUFFER_DEFAULT_DATA_SIZE)
- {
- b = vlib_get_buffer (vm, bi[i - 1]);
- b->current_length = VLIB_BUFFER_DEFAULT_DATA_SIZE;
- b->flags |= VLIB_BUFFER_NEXT_PRESENT;
- b->next_buffer = bi[i];
-
- b = vlib_get_buffer (vm, bi[i]);
- b->current_length = n_bytes_left;
- }
-
- _vec_len (im->rx_buffers) -= i;
-
- /* Get the packet to the output node. */
- {
- vnet_hw_interface_t * hw;
- vlib_frame_t * new_frame;
- u32 * to_next;
-
- hw = vnet_get_hw_interface (vnet_get_main (), sw_if_index);
-
- new_frame = vlib_get_frame_to_node (vm, hw->output_node_index);
- to_next = vlib_frame_vector_args (new_frame);
- to_next[0] = bi[0];
- new_frame->n_vectors = 1;
-
- vlib_put_frame_to_node (vm, hw->output_node_index, new_frame);
- }
-
- return 1;
-}
-
-static uword
-tap_inject_rx (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * f)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
- u32 * fd;
- uword count = 0;
-
- vec_foreach (fd, im->rx_file_descriptors)
- {
- if (tap_rx (vm, node, f, *fd) != 1)
- {
- clib_warning ("rx failed");
- count = 0;
- break;
- }
- ++count;
- }
-
- vec_free (im->rx_file_descriptors);
-
- return count;
-}
-
-VLIB_REGISTER_NODE (tap_inject_rx_node) = {
- .function = tap_inject_rx,
- .name = "tap-inject-rx",
- .type = VLIB_NODE_TYPE_INPUT,
- .state = VLIB_NODE_STATE_INTERRUPT,
- .vector_size = sizeof (u32),
-};
-
-/**
- * @brief no-op lock function.
- */
-static void
-tap_inject_dpo_lock (dpo_id_t * dpo)
-{
-}
-
-/**
- * @brief no-op unlock function.
- */
-static void
-tap_inject_dpo_unlock (dpo_id_t * dpo)
-{
-}
-
-u8 *
-format_tap_inject_dpo (u8 * s, va_list * args)
-{
- return (format (s, "tap-inject:[%d]", 0));
-}
-
-const static dpo_vft_t tap_inject_vft = {
- .dv_lock = tap_inject_dpo_lock,
- .dv_unlock = tap_inject_dpo_unlock,
- .dv_format = format_tap_inject_dpo,
-};
-
-const static char *const tap_inject_tx_nodes[] = {
- "tap-inject-tx",
- NULL,
-};
-
-const static char *const *const tap_inject_nodes[DPO_PROTO_NUM] = {
- [DPO_PROTO_IP4] = tap_inject_tx_nodes,
- [DPO_PROTO_IP6] = tap_inject_tx_nodes,
-};
-
-static clib_error_t *
-tap_inject_init (vlib_main_t * vm)
-{
- tap_inject_main_t * im = tap_inject_get_main ();
-
- im->rx_node_index = tap_inject_rx_node.index;
- im->tx_node_index = tap_inject_tx_node.index;
- im->neighbor_node_index = tap_inject_neighbor_node.index;
-
- tap_inject_dpo_type = dpo_register_new_type (&tap_inject_vft, tap_inject_nodes);
-
- vec_alloc (im->rx_buffers, NUM_BUFFERS_TO_ALLOC);
- vec_reset_length (im->rx_buffers);
-
- return 0;
-}
-
-VLIB_INIT_FUNCTION (tap_inject_init);
diff --git a/extras/router-plugin/rtinject/tap_inject_tap.c b/extras/router-plugin/rtinject/tap_inject_tap.c
deleted file mode 100644
index a3ec9ffef..000000000
--- a/extras/router-plugin/rtinject/tap_inject_tap.c
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright 2016 Intel Corporation
- *
- * Licensed under the Apache License, Version 2.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 "tap_inject.h"
-
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <linux/if.h>
-#include <linux/if_arp.h>
-#include <linux/if_ether.h>
-#include <linux/if_tun.h>
-#include <netinet/in.h>
-#include <vnet/unix/tuntap.h>
-
-#include <vlib/unix/unix.h>
-
-
-static clib_error_t *
-tap_inject_tap_read (clib_file_t * f)
-{
- vlib_main_t * vm = vlib_get_main ();
- tap_inject_main_t * im = tap_inject_get_main ();
-
- vec_add1 (im->rx_file_descriptors, f->file_descriptor);
-
- vlib_node_set_interrupt_pending (vm, im->rx_node_index);
-
- return 0;
-}
-
-#define TAP_INJECT_TAP_BASE_NAME "vpp"
-
-clib_error_t *
-tap_inject_tap_connect (vnet_hw_interface_t * hw)
-{
- vnet_main_t * vnet_main = vnet_get_main ();
- vnet_sw_interface_t * sw = vnet_get_sw_interface (vnet_main, hw->hw_if_index);
- static const int one = 1;
- int fd;
- struct ifreq ifr;
- clib_file_t template;
- u32 tap_fd;
- u8 * name;
-
- memset (&ifr, 0, sizeof (ifr));
- memset (&template, 0, sizeof (template));
-
- ASSERT (hw->hw_if_index == sw->sw_if_index);
-
- /* Create the tap. */
- tap_fd = open ("/dev/net/tun", O_RDWR);
-
- if ((int)tap_fd < 0)
- return clib_error_return (0, "failed to open tun device");
-
- name = format (0, TAP_INJECT_TAP_BASE_NAME "%u%c", hw->hw_instance, 0);
-
- strncpy (ifr.ifr_name, (char *) name, sizeof (ifr.ifr_name) - 1);
- ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
-
- if (ioctl (tap_fd, TUNSETIFF, (void *)&ifr) < 0)
- {
- close (tap_fd);
- return clib_error_return (0, "failed to create tap");
- }
-
- if (ioctl (tap_fd, FIONBIO, &one) < 0)
- {
- close (tap_fd);
- return clib_error_return (0, "failed to set tap to non-blocking io");
- }
-
- /* Open a socket to configure the device. */
- fd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL));
-
- if (fd < 0)
- {
- close (tap_fd);
- return clib_error_return (0, "failed to configure tap");
- }
-
- if (hw->hw_address)
- clib_memcpy (ifr.ifr_hwaddr.sa_data, hw->hw_address, ETHER_ADDR_LEN);
-
- ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
-
- /* Set the hardware address. */
- if (ioctl (fd, SIOCSIFHWADDR, &ifr) < 0)
- {
- close (tap_fd);
- close (fd);
- return clib_error_return (0, "failed to set tap hardware address");
- }
-
- /* Get the tap if index. */
- if (ioctl (fd, SIOCGIFINDEX, &ifr) < 0)
- {
- close (tap_fd);
- close (fd);
- return clib_error_return (0, "failed to procure tap if index");
- }
-
- close (fd);
-
- /* Get notified when the tap needs to be read. */
- template.read_function = tap_inject_tap_read;
- template.file_descriptor = tap_fd;
-
- clib_file_add (&file_main, &template);
-
- tap_inject_insert_tap (sw->sw_if_index, tap_fd, ifr.ifr_ifindex);
-
- return 0;
-}
-
-clib_error_t *
-tap_inject_tap_disconnect (u32 sw_if_index)
-{
- u32 tap_fd;
-
- tap_fd = tap_inject_lookup_tap_fd (sw_if_index);
- if (tap_fd == ~0)
- return clib_error_return (0, "failed to disconnect tap");
-
- tap_inject_delete_tap (sw_if_index);
-
- close (tap_fd);
- return 0;
-}
-
-
-u8 *
-format_tap_inject_tap_name (u8 * s, va_list * args)
-{
- int fd;
- struct ifreq ifr;
-
- fd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL));
-
- if (fd < 0)
- return 0;
-
- memset (&ifr, 0, sizeof (ifr));
-
- ifr.ifr_ifindex = va_arg (*args, u32);
-
- if (ioctl (fd, SIOCGIFNAME, &ifr) < 0)
- {
- close (fd);
- return 0;
- }
-
- close (fd);
-
- return format (s, "%s", ifr.ifr_name);
-}
diff --git a/extras/sysrepo/CMakeLists.txt b/extras/sysrepo/CMakeLists.txt
deleted file mode 100644
index edf78105a..000000000
--- a/extras/sysrepo/CMakeLists.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (c) 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.10)
-project(sysrepo)
-
-list(APPEND MODULE_PATH
- ${CMAKE_MODULE_PATH}
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules
-)
-
-string(REPLACE ";" "|" MODULE_PATH "${MODULE_PATH}")
-
-include(ExternalProject)
-
-ExternalProject_Add(sysrepo
- GIT_REPOSITORY https://github.com/sysrepo/sysrepo.git
- GIT_TAG devel
- GIT_SHALLOW TRUE
- DEPENDS libyang
- PREFIX ${CMAKE_CURRENT_BINARY_DIR}/sysrepo
- PATCH_COMMAND git apply ${CMAKE_CURRENT_SOURCE_DIR}/sysrepo.patch
- # Use the alternate list separator
- # (https://cmake.org/cmake/help/latest/manual/cmake-language.7.html#lists)
- LIST_SEPARATOR |
- CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_MODULE_PATH=${MODULE_PATH} -DBUILD_EXAMPLES=OFF -DCMAKE_PREFIX_PATH=${DESTDIR}/usr
- BUILD_COMMAND make package
- INSTALL_COMMAND make DESTDIR=${DESTDIR} install
-)
-
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
-endif() \ No newline at end of file
diff --git a/extras/sysrepo/cmake/Modules/Packaging.cmake b/extras/sysrepo/cmake/Modules/Packaging.cmake
deleted file mode 100644
index 2433539c7..000000000
--- a/extras/sysrepo/cmake/Modules/Packaging.cmake
+++ /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.
-
-# Generate DEB / RPM packages
-
-######################
-# Packages section
-######################
-
-set(sysrepo_DESCRIPTION
-"Sysrepo is a YANG-based configuration and operational datastore."
- CACHE STRING "Description for deb/rpm package."
-)
-
-set(sysrepo_DEB_DEPENDENCIES
- "libyang (>= 1.0)"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(sysrepo_RPM_DEPENDENCIES
- "libyang >= 1.0"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-
diff --git a/extras/sysrepo/sysrepo.patch b/extras/sysrepo/sysrepo.patch
deleted file mode 100644
index ef3fa510d..000000000
--- a/extras/sysrepo/sysrepo.patch
+++ /dev/null
@@ -1,55 +0,0 @@
-diff --git a/CMakeLists.txt b/CMakeLists.txt
-index 181387b0..356bf32c 100644
---- a/CMakeLists.txt
-+++ b/CMakeLists.txt
-@@ -6,6 +6,11 @@ include(CheckSymbolExists)
- include(CheckIncludeFile)
- include(CheckStructHasMember)
-
-+set(CMAKE_MODULE_PATH
-+ ${CMAKE_MODULE_PATH}
-+ "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules"
-+)
-+
- # osx specific
- set(CMAKE_MACOSX_RPATH TRUE)
-
-@@ -81,7 +86,7 @@ endif()
- option(GEN_LANGUAGE_BINDINGS "Enable library bindings for different languages." OFF)
-
- option(GEN_CPP_BINDINGS "Enable C++ bindings." ON)
--option(BUILD_CPP_EXAMPLES "Enable C++ example application compilation." ON)
-+option(BUILD_CPP_EXAMPLES "Enable C++ example application compilation." OFF)
-
- option(GEN_PYTHON_BINDINGS "Enable Python bindings." ON)
- option(ENABLE_PYTHON_TESTS "Enable Python tests." ON)
-@@ -206,13 +211,13 @@ add_executable(sysrepo-plugind ${SYSREPOPLUGIND_SRC})
- target_link_libraries(sysrepo-plugind sysrepo dl)
-
- # installation
--install(TARGETS sysrepo DESTINATION ${CMAKE_INSTALL_LIBDIR})
--install(FILES ${PROJECT_SOURCE_DIR}/src/sysrepo.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
-+install(TARGETS sysrepo DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT sysrepo)
-+install(FILES ${PROJECT_SOURCE_DIR}/src/sysrepo.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} COMPONENT sysrepo)
- install(FILES ${PROJECT_SOURCE_DIR}/src/utils/values.h ${PROJECT_SOURCE_DIR}/src/utils/xpath.h
-- DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/sysrepo)
--install(TARGETS sysrepoctl sysrepocfg sysrepo-plugind DESTINATION ${CMAKE_INSTALL_BINDIR})
-+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/sysrepo COMPONENT sysrepo)
-+install(TARGETS sysrepoctl sysrepocfg sysrepo-plugind DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT sysrepo)
-
--install(FILES "${PROJECT_BINARY_DIR}/libsysrepo.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
-+install(FILES "${PROJECT_BINARY_DIR}/libsysrepo.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig" COMPONENT sysrepo)
-
- # doxygen documentation
- find_package(Doxygen)
-@@ -266,3 +271,9 @@ add_custom_target(sr_clean
- add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_MODULE_PATH}/uninstall.cmake")
- add_custom_target(uninstall_with_repo "${CMAKE_COMMAND}" -P "${CMAKE_MODULE_PATH}/uninstall.cmake"
- COMMAND rm -rf ${REPOSITORY_LOC})
-+
-+ include(Packaging)
-+ if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
-+ include(Packager)
-+ make_packages()
-+ endif()
-\ No newline at end of file
diff --git a/cmake/Modules/FindUncrustify.cmake b/hicn-light/.clang-format
index f8f6b00b8..2dc5c0c54 100644
--- a/cmake/Modules/FindUncrustify.cmake
+++ b/hicn-light/.clang-format
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,11 +11,5 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# Find uncrustify program
-#
-find_program( UNCRUSTIFY_BIN uncrustify
- PATHS
- $ENV{UNCRUSTIFY_HOME}
- )
-
-message( "-- UNCRUSTIFY found in ${UNCRUSTIFY_BIN}" )
+BasedOnStyle: Google
+SortIncludes: false
diff --git a/hicn-light/CMakeLists.txt b/hicn-light/CMakeLists.txt
index 64b93d997..e82100a91 100644
--- a/hicn-light/CMakeLists.txt
+++ b/hicn-light/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,115 +11,104 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Project and cmake version
+##############################################################
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-
project(hicn-light)
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
-endif()
+##############################################################
+# Libs and Bins names
+##############################################################
+set(LIBHICN_LIGHT hicn-light)
+set(LIBHICN_LIGHT_STATIC ${LIBHICN_LIGHT}.static)
+set(HICN_LIGHT hicn-light CACHE INTERNAL "" FORCE)
+set(HICN_LIGHT_CONTROL ${HICN_LIGHT}-control CACHE INTERNAL "" FORCE)
+set(HICN_LIGHT_SHELL ${HICN_LIGHT}-shell CACHE INTERNAL "" FORCE)
+set(HICN_LIGHT_DAEMON ${HICN_LIGHT}-daemon CACHE INTERNAL "" FORCE)
+
+
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake)
+
+
+##############################################################
+# Cmake modules
+##############################################################
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
"${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules"
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
)
+
+##############################################################
+# C Standard
+##############################################################
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
-option(ENABLE_PUNTING "Enable punting on linux systems" ON)
-
-include( CTest )
-include( detectCacheSize )
-
-if(NOT WIN32)
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
-else ()
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4996")
-endif ()
-
-if(${CMAKE_SYSTEM_NAME} STREQUAL "Android")
- message("############ Detected cross compile for $ENV{CMAKE_SYSTEM_NAME}")
- # Android uses static libs, so we need to link all the dependencies to the executable
- find_package(OpenSSL REQUIRED)
- find_package(LibEvent REQUIRED)
- set(ANDROID_LIBRARIES ${LIBEVENT_LIBRARIES} ${OPENSSL_LIBRARIES})
-endif()
-set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -DLIBRTA_DISABLE_VALIDATION -DPARCLibrary_DISABLE_VALIDATION")
+##############################################################
+# Dependencies and third party libs
+##############################################################
+find_package(LibEvent ${LIBEVENT_DEFAULT_VERSION} REQUIRED)
+find_package(Threads REQUIRED)
-include(IosMacros)
-include(WindowsMacros)
-find_package(Libparc REQUIRED)
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
+if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ include(CommonSetup)
+ find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
+ find_package(Libhicnctrl ${CURRENT_VERSION} REQUIRED NO_MODULE)
-set(HICN_LIGHT hicn-light CACHE INTERNAL "" FORCE)
-set(HICN_LIGHT_CONTROL ${HICN_LIGHT}-control CACHE INTERNAL "" FORCE)
-set(HICN_LIGHT_DAEMON ${HICN_LIGHT}-daemon CACHE INTERNAL "" FORCE)
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
-if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- find_package(Libhicn REQUIRED)
+ list(APPEND HICN_LIBRARIES hicn::hicn.${LIBTYPE})
+ list(APPEND LIBHICNCTRL_LIBRARIES hicn::hicnctrl.${LIBTYPE})
else()
if (DISABLE_SHARED_LIBRARIES)
- if (WIN32)
- set(HICN_LIBRARIES ${LIBHICN_STATIC})
+ if (WIN32)
+ set(HICN_LIBRARIES ${LIBHICN_STATIC} ${LIBHICNCTRL_STATIC})
else ()
- set(HICN_LIBRARIES ${LIBHICN_STATIC} log)
+ set(HICN_LIBRARIES ${LIBHICN_STATIC} ${LIBHICNCTRL_STATIC} log)
endif ()
list(APPEND DEPENDENCIES
${LIBHICN_STATIC}
+ ${LIBHICNCTRL_STATIC}
)
else ()
- set(HICN_LIBRARIES ${LIBHICN_SHARED})
+ set(HICN_LIBRARIES
+ ${LIBHICN_SHARED}
+ ${LIBHICNCTRL_SHARED}
+ )
list(APPEND DEPENDENCIES
${LIBHICN_SHARED}
+ ${LIBHICNCTRL_SHARED}
)
endif ()
endif()
-include(Packaging)
-
-find_package(Threads REQUIRED)
-
-set(LIBHICN_LIGHT hicn-light)
-set(LIBHICN_LIGHT_STATIC ${LIBHICN_LIGHT}.static)
-
-set(LIBRARIES
- ${LIBPARC_LIBRARIES}
- ${HICN_LIBRARIES}
- ${CMAKE_THREAD_LIBS_INIT}
- ${WINDOWS_LIBRARIES}
- ${ANDROID_LIBRARIES}
-)
-
-set(HICN_LIGHT_LIBRARIES_LIST "${LIBPARC_LIBRARIES};${CMAKE_THREAD_LIBS_INIT};${WINDOWS_LIBRARIES}" CACHE INTERNAL "HICN_LIGHT_LIBRARIES_LIST")
-
-
-# Include dirs -- Order does matter!
-list(APPEND HICN_LIGHT_INCLUDE_DIRS
- ${HICN_INCLUDE_DIRS}
- ${LIBPARC_INCLUDE_DIRS}
- ${WINDOWS_INCLUDE_DIRS}
-)
-
-if (UNIX)
- list(APPEND LIBRARIES
- m
- )
-endif()
-
-set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib")
-
-if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang")
- set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "${CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS} -undefined dynamic_lookup")
- message(STATUS "Set \"-undefined dynamic_lookup\" for shared libraries")
-endif()
+##############################################################
+# Subdirectories
+##############################################################
add_subdirectory(src/hicn)
+
+##############################################################
# Install service file in linux systems
+##############################################################
include(ServiceScript)
install_service_script(
${CMAKE_CURRENT_SOURCE_DIR}/config/hicn-light.service
diff --git a/hicn-light/cmake/Modules/Packaging.cmake b/hicn-light/cmake/packaging.cmake
index 2b9f4a7b9..97b3e0dbf 100644
--- a/hicn-light/cmake/Modules/Packaging.cmake
+++ b/hicn-light/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -21,7 +21,7 @@ set(${HICN_LIGHT}_DESCRIPTION
)
set(${HICN_LIGHT}_DEB_DEPENDENCIES
- "lib${LIBHICN} (>= stable_version), libparc (>= 1.0)"
+ "lib${LIBHICN} (= stable_version), libevent-2.1-7 (= 2.1.11-stable-1)"
CACHE STRING "Dependencies for deb/rpm package."
)
@@ -31,7 +31,7 @@ set(${HICN_LIGHT}_DEB_PACKAGE_CONTROL_EXTRA
)
set(${HICN_LIGHT}_RPM_DEPENDENCIES
- "lib${LIBHICN} >= stable_version, libparc >= 1.0"
+ "lib${LIBHICN} = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
)
diff --git a/hicn-light/config/hicn-light.service b/hicn-light/config/hicn-light.service
index f269b2f26..79d5ced93 100644
--- a/hicn-light/config/hicn-light.service
+++ b/hicn-light/config/hicn-light.service
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/hicn-light/config/post b/hicn-light/config/post
index 91f596050..f2f566426 100755
--- a/hicn-light/config/post
+++ b/hicn-light/config/post
@@ -2,4 +2,4 @@
if pidof systemd; then
systemctl enable hicn-light
-fi
+fi \ No newline at end of file
diff --git a/hicn-light/config/postinst b/hicn-light/config/postinst
index dced2a093..f2f566426 100755
--- a/hicn-light/config/postinst
+++ b/hicn-light/config/postinst
@@ -1,3 +1,5 @@
#!/bin/bash
-systemctl enable hicn-light \ No newline at end of file
+if pidof systemd; then
+ systemctl enable hicn-light
+fi \ No newline at end of file
diff --git a/hicn-light/config/prerm b/hicn-light/config/prerm
index 4584c7057..c1d3d55a1 100755
--- a/hicn-light/config/prerm
+++ b/hicn-light/config/prerm
@@ -1,3 +1,5 @@
#!/bin/bash
-systemctl disable hicn-light \ No newline at end of file
+if pidof systemd; then
+ systemctl disable hicn-light
+fi \ No newline at end of file
diff --git a/hicn-light/config/preun b/hicn-light/config/preun
index 4584c7057..c1d3d55a1 100755
--- a/hicn-light/config/preun
+++ b/hicn-light/config/preun
@@ -1,3 +1,5 @@
#!/bin/bash
-systemctl disable hicn-light \ No newline at end of file
+if pidof systemd; then
+ systemctl disable hicn-light
+fi \ No newline at end of file
diff --git a/hicn-light/src/hicn/CMakeLists.txt b/hicn-light/src/hicn/CMakeLists.txt
index 639bfa179..feaac5c39 100644
--- a/hicn-light/src/hicn/CMakeLists.txt
+++ b/hicn-light/src/hicn/CMakeLists.txt
@@ -1,55 +1,130 @@
-# Define a few configuration variables that we want accessible in the software
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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(BuildMacros)
+##############################################################
+# Libraries to link
+##############################################################
+set(LIBRARIES
+ PUBLIC ${HICN_LIBRARIES}
+ PUBLIC ${LIBHICNCTRL_LIBRARIES}
+ PRIVATE ${LIBEVENT_LIBRARIES}
+ PRIVATE ${CMAKE_THREAD_LIBS_INIT}
+)
+
+if (UNIX)
+ list(APPEND LIBRARIES
+ m
+ )
+endif()
+
+
+##############################################################
+# Configuration file
+##############################################################
configure_file(config.h.in hicn-light/config.h @ONLY)
-if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux" AND ENABLE_PUNTING)
+
+##############################################################
+# Compiler definitions
+##############################################################
+list(APPEND COMPILER_DEFINITIONS
+ PRIVATE -DLIBRTA_DISABLE_VALIDATION
+)
+
+list(APPEND COMPILER_DEFINITIONS
+# "-DWITH_GRO"
+# "-DWITH_GSO"
+# "-DWITH_ZEROCOPY"
+ PRIVATE "-DWITH_POLICY_STATS"
+ PRIVATE "-DWITH_CLI"
+# "-DNDEBUG=1" # disable assertions
+)
+
+if (UNIX AND NOT APPLE)
list(APPEND COMPILER_DEFINITIONS
- "-DPUNTING"
+ "-D_GNU_SOURCE" # batching support through struct mmsghdr
)
endif()
-list(APPEND COMPILER_DEFINITIONS
- "-DWITH_MAPME"
- "-DWITH_POLICY"
+
+##############################################################
+# Compiler options
+##############################################################
+set(COMPILER_OPTIONS
+ PRIVATE ${DEFAULT_COMPILER_OPTIONS}
+ #PRIVATE "-Wno-address-of-packed-member"
)
+##############################################################
+# Sources
+##############################################################
if (NOT DISABLE_EXECUTABLES)
- add_subdirectory(command_line)
+ add_subdirectory(cli)
endif()
+add_subdirectory(base)
add_subdirectory(config)
add_subdirectory(content_store)
add_subdirectory(core)
add_subdirectory(io)
-add_subdirectory(messenger)
add_subdirectory(platforms)
-add_subdirectory(processor)
add_subdirectory(socket)
add_subdirectory(strategies)
add_subdirectory(utils)
+list(APPEND TO_INSTALL_HEADER_FILES
+ ${HEADER_FILES}
+)
+
list(APPEND HEADER_FILES
${CMAKE_CURRENT_BINARY_DIR}/hicn-light/config.h
)
-list(INSERT HICN_LIGHT_INCLUDE_DIRS 0
- ${CMAKE_CURRENT_SOURCE_DIR}/..
- ${CMAKE_CURRENT_BINARY_DIR}/..
+
+##############################################################
+# Includes
+##############################################################
+list(APPEND HICN_LIGHT_INCLUDE_DIRS
+ PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/..>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+ PRIVATE
+ ${LIBEVENT_INCLUDE_DIRS}
+ ${WINDOWS_INCLUDE_DIRS}
)
list(APPEND TO_INSTALL_HEADER_FILES
${CMAKE_CURRENT_BINARY_DIR}/hicn-light/config.h
)
+
+##############################################################
+# Build type
+##############################################################
+set(LIB_BUILD_TYPE STATIC)
if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Android")
- set(LIB_BUILD_TYPE "NO_DEV")
-else()
- set(LIB_BUILD_TYPE "")
+ list(APPEND LIB_BUILD_TYPE
+ "NO_DEV"
+ )
endif()
+
+##############################################################
+# Build forwarder library
+##############################################################
build_library(${LIBHICN_LIGHT}
- STATIC ${LIB_BUILD_TYPE}
+ ${LIB_BUILD_TYPE}
SOURCES ${SOURCE_FILES}
INSTALL_HEADERS ${TO_INSTALL_HEADER_FILES}
LINK_LIBRARIES ${LIBRARIES}
@@ -57,6 +132,14 @@ build_library(${LIBHICN_LIGHT}
COMPONENT ${HICN_LIGHT}
INCLUDE_DIRS ${HICN_LIGHT_INCLUDE_DIRS}
HEADER_ROOT_DIR hicn
- DEFINITIONS ${COMPILER_DEFINITIONS}
+ DEFINITIONS PUBLIC ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
+
+##############################################################
+# Build tests
+##############################################################
+if (BUILD_TESTS)
+ add_subdirectory(test)
+endif()
diff --git a/hicn-light/src/hicn/base/CMakeLists.txt b/hicn-light/src/hicn/base/CMakeLists.txt
new file mode 100644
index 000000000..2541ed830
--- /dev/null
+++ b/hicn-light/src/hicn/base/CMakeLists.txt
@@ -0,0 +1,29 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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.
+
+list(APPEND HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/loop.h
+)
+
+list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/loop.c
+)
+
+set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
+set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
+
+set(TO_INSTALL_HEADER_FILES
+ ${TO_INSTALL_HEADER_FILES}
+ ${HEADER_FILES}
+ PARENT_SCOPE
+)
diff --git a/hicn-light/src/hicn/base/loop.c b/hicn-light/src/hicn/base/loop.c
new file mode 100644
index 000000000..3407bfc1c
--- /dev/null
+++ b/hicn-light/src/hicn/base/loop.c
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file loop.c
+ * @brief Implementation of event loop based on libevent
+ */
+
+#include <assert.h>
+#include <event2/event.h>
+#include <event2/event_struct.h>
+#include <event2/thread.h>
+#include <fcntl.h> // fcntl
+#ifdef WITH_THREAD
+#include <pthread.h>
+#endif /* WITH_THREAD */
+#include <hicn/util/log.h>
+#include <stdlib.h>
+#include <unistd.h> // fcntl
+
+#include "loop.h"
+
+loop_t *MAIN_LOOP = NULL;
+
+/**
+ * \brief Holds all callback parameters
+ */
+typedef struct {
+ void *owner;
+ fd_callback_t callback;
+ unsigned id;
+ void *data;
+} cb_wrapper_args_t;
+
+typedef enum {
+ EVTYPE_TIMER,
+ EVTYPE_FD,
+} event_type_t;
+
+struct loop_s {
+ /* Libevent-based implementation */
+ struct event_base *event_base;
+};
+
+struct event_s {
+ /* Reference to loop */
+ loop_t *loop;
+
+ /* Event type*/
+ event_type_t event_type;
+
+ /* Raw event */
+ struct event raw_event;
+
+ /* Callback on event */
+ cb_wrapper_args_t callback;
+};
+
+loop_t *loop_create() {
+ loop_t *loop = malloc(sizeof(loop_t));
+
+ if (!loop) {
+ ERROR("[loop_create] Failed to allocate memory");
+ goto ERR_MALLOC;
+ }
+
+#ifdef WITH_THREAD
+ evthread_use_pthreads();
+#endif /* WITH_THREAD */
+
+ loop->event_base = event_base_new();
+ if (!loop->event_base) goto ERR_EVENT;
+
+ event_set_log_callback(NULL);
+
+ return loop;
+
+ERR_EVENT:
+ERR_MALLOC:
+ return NULL;
+}
+
+void loop_free(loop_t *loop) {
+ event_base_free(loop->event_base);
+ free(loop);
+}
+
+int _loop_dispatch(loop_t *loop, int flags) {
+ event_base_loop(loop->event_base, flags);
+ return 0;
+}
+
+int loop_dispatch(loop_t *loop) {
+ return _loop_dispatch(loop, EVLOOP_NO_EXIT_ON_EMPTY);
+}
+
+int loop_break(loop_t *loop) { return event_base_loopbreak(loop->event_base); }
+
+int loop_undispatch(loop_t *loop) { return 0; }
+
+void cb_wrapper(evutil_socket_t fd, short what, void *arg) {
+ cb_wrapper_args_t *cb_wrapper_args = arg;
+ cb_wrapper_args->callback(cb_wrapper_args->owner, fd, cb_wrapper_args->id,
+ cb_wrapper_args->data);
+}
+
+static inline void _event_create(event_t **event, loop_t *loop,
+ event_type_t type, void *callback_owner,
+ fd_callback_t callback, unsigned id,
+ void *callback_data) {
+ *event = malloc(sizeof(event_t));
+ (*event)->callback = (cb_wrapper_args_t){
+ .owner = callback_owner,
+ .callback = callback,
+ .id = id,
+ .data = callback_data,
+ };
+ (*event)->event_type = type;
+ (*event)->loop = loop;
+}
+
+int loop_fd_event_create(event_t **event, loop_t *loop, int fd,
+ void *callback_owner, fd_callback_t callback,
+ unsigned id, void *callback_data) {
+ _event_create(event, loop, EVTYPE_FD, callback_owner, callback, id,
+ callback_data);
+
+ evutil_make_socket_nonblocking(fd);
+ event_assign(&(*event)->raw_event, loop->event_base, fd, EV_READ | EV_PERSIST,
+ cb_wrapper, &(*event)->callback);
+
+ return 0;
+}
+
+int loop_fd_event_register(event_t *event) {
+ assert(event->event_type == EVTYPE_FD);
+
+ if (event_add(&event->raw_event, NULL) < 0) {
+ ERROR("[loop_fd_event_register] event_add");
+ goto ERR_EVENT_ADD;
+ }
+
+ return 0;
+
+ERR_EVENT_ADD:
+ return -1;
+}
+
+int loop_event_unregister(event_t *event) {
+ event_del(&event->raw_event);
+ return 0;
+}
+
+int loop_timer_create(event_t **timer, loop_t *loop, void *callback_owner,
+ fd_callback_t callback, void *callback_data) {
+ _event_create(timer, loop, EVTYPE_TIMER, callback_owner, callback, 0,
+ callback_data);
+
+ evtimer_assign(&(*timer)->raw_event, loop->event_base, cb_wrapper,
+ &(*timer)->callback);
+
+ return 0;
+}
+
+static inline void _ms_to_timeval(unsigned delay_ms, struct timeval *tv) {
+ tv->tv_sec = delay_ms / 1000;
+ tv->tv_usec = (delay_ms % 1000) * 1000;
+}
+
+int loop_timer_register(event_t *timer, unsigned delay_ms) {
+ assert(timer->event_type == EVTYPE_TIMER);
+
+ struct timeval tv;
+ _ms_to_timeval(delay_ms, &tv);
+
+ if (tv.tv_sec == 0 && tv.tv_usec == 0) {
+ event_active(&timer->raw_event, EV_TIMEOUT, 0);
+ } else {
+ event_add(&timer->raw_event, &tv);
+ }
+
+ return 0;
+}
+
+int loop_timer_is_enabled(event_t *timer) {
+ return evtimer_pending(&timer->raw_event, NULL) != 0;
+}
+
+int loop_event_free(event_t *event) {
+ int ret = loop_event_unregister(event);
+ free(event);
+ return ret;
+}
diff --git a/hicn-light/src/hicn/base/loop.h b/hicn-light/src/hicn/base/loop.h
new file mode 100644
index 000000000..0eecb60fe
--- /dev/null
+++ b/hicn-light/src/hicn/base/loop.h
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file loop.h
+ * \brief Face manager main loop
+ */
+
+#ifndef UTIL_LOOP_H
+#define UTIL_LOOP_H
+
+/* fd & timer callbacks */
+
+typedef int (*fd_callback_t)(void *owner, int fd, unsigned id, void *data);
+
+typedef struct {
+ int fd;
+ void *owner;
+ fd_callback_t callback;
+ unsigned id;
+ void *data;
+} fd_callback_data_t;
+
+/* loop */
+
+typedef struct loop_s loop_t;
+typedef struct event_s event_t;
+
+extern loop_t *MAIN_LOOP;
+
+/**
+ * \brief Creates a main loop
+ * \return Pointer to the newly created loop, or NULL in case of error
+ */
+loop_t *loop_create();
+
+/**
+ * \brief Releases a loop instance and frees all associated memory
+ * \param [in] loop - Pointer to the loop instance to free
+ */
+void loop_free(loop_t *loop);
+
+/**
+ * \brief Runs the loop instance to process events (helper).
+ * \param [in] loop - Pointer to the loop instance
+ * \param [in] flags - Loop mode: EVLOOP_ONCE, EVLOOP_NONBLOCK or
+ * EVLOOP_NO_EXIT_ON_EMPTY \return 0 if successful, -1 otherwise
+ */
+int _loop_dispatch(loop_t *loop, int flags);
+
+/**
+ * \brief Runs the loop instance to process events.
+ * \param [in] loop - Pointer to the loop instance
+ * \return 0 if successful, -1 otherwise
+ */
+int loop_dispatch(loop_t *loop);
+
+/**
+ * \brief Terminates the dispatching of events
+ * \param [in] loop - Pointer to the loop instance
+ */
+int loop_break(loop_t *loop);
+
+int loop_undispatch(loop_t *loop);
+
+/** Create new event associated with given fd.
+ * \param [out] event - Struct representing new fd event
+ * \param [in] loop - Loop running events
+ * \param [in] fd - fd to register
+ * \param [in] callback_owner - Pointer to the owner of the callack (first
+ * parameter of callback function)
+ * \param [in] callback - Callback function
+ * \param [in] id - User parameter to pass alongside callback invocation,
+ * allowing to pass an id without allocating memory.
+ * \param [in] callback_data - User data to pass alongside callback invocation
+ * \return 0 in case of success, -1 otherwise
+ */
+int loop_fd_event_create(event_t **event, loop_t *loop, int fd,
+ void *callback_owner, fd_callback_t callback,
+ unsigned id, void *callback_data);
+
+/**
+ * Register event in corresponding event loop.
+ * \param [in] event - Struct representing fd event
+ * \return 0 in case of success, -1 otherwise
+ */
+int loop_fd_event_register(event_t *event);
+
+/**
+ * Unregister event from corresponding event loop.
+ * \param [in] event - Struct representing fd event
+ * \return 0 in case of success, -1 otherwise
+ */
+int loop_event_unregister(event_t *event);
+
+/**
+ * Free event object.
+ * \param [in] event - Struct representing the event
+ * \return 0 in case of success, -1 otherwise
+ */
+int loop_event_free(event_t *event);
+
+/** Create new timer event.
+ * \param [out] event - Struct representing new timer event
+ * \param [in] loop - Loop running events
+ * \param [in] callback_owner - Pointer to the owner of the callack (first
+ * parameter of callback function)
+ * \param [in] callback - Callback function
+ * \param [in] callback_data - User data to pass alongside callback invocation
+ * \return 0 in case of success, -1 otherwise
+ */
+int loop_timer_create(event_t **timer, loop_t *loop, void *callback_owner,
+ fd_callback_t callback, void *callback_data);
+
+/**
+ * Register event in corresponding event loop.
+ * \param [in] timer - Struct representing timer event
+ * \return 0 in case of success, -1 otherwise
+ */
+int loop_timer_register(event_t *timer, unsigned delay_ms);
+
+/**
+ * Check if timer is enabled.
+ * \param [in] timer - Struct representing timer event
+ * \return 1 if enabled, 0 otherwise
+ */
+int loop_timer_is_enabled(event_t *timer);
+
+#endif /* UTIL_LOOP_H */
diff --git a/hicn-light/src/hicn/cli/CMakeLists.txt b/hicn-light/src/hicn/cli/CMakeLists.txt
new file mode 100644
index 000000000..39581e6ad
--- /dev/null
+++ b/hicn-light/src/hicn/cli/CMakeLists.txt
@@ -0,0 +1,93 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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.
+
+
+if (NOT DISABLE_EXECUTABLES)
+##############################################################
+# Force libhicn library to whole archive mode
+##############################################################
+ if (APPLE)
+ set(
+ LIBHICN_LIGHT_WHOLE_ARCHIVE
+ "-Wl,-force_load"
+ "${LIBHICN_LIGHT_STATIC}"
+ )
+ else()
+ set(
+ LIBHICN_LIGHT_WHOLE_ARCHIVE
+ "-Wl,--whole-archive"
+ "${LIBHICN_LIGHT_STATIC}"
+ "-Wl,--no-whole-archive"
+ )
+ endif()
+
+##############################################################
+# Sources
+##############################################################
+ list(APPEND CONTROLLER_SRC
+ color.c
+ hicnc.c
+ )
+
+
+##############################################################
+# Build hicn-light-control
+##############################################################
+ build_executable(${HICN_LIGHT_CONTROL}
+ SOURCES ${CONTROLLER_SRC}
+ LINK_LIBRARIES ${LIBHICN_LIGHT_WHOLE_ARCHIVE}
+ DEPENDS ${LIBHICN_LIGHT_STATIC}
+ COMPONENT ${HICN_LIGHT}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ )
+
+
+##############################################################
+# Build hicn-light-shell
+##############################################################
+ list(APPEND SHELL_SRC
+ color.c
+ hicns.c
+ )
+
+ build_executable(${HICN_LIGHT_SHELL}
+ SOURCES ${SHELL_SRC}
+ LINK_LIBRARIES ${LIBHICN_LIGHT_WHOLE_ARCHIVE}
+ DEPENDS ${LIBHICN_LIGHT_STATIC}
+ COMPONENT ${HICN_LIGHT}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ )
+
+
+##############################################################
+# Build hicn-light-shell
+##############################################################
+ list(APPEND DAEMON_SRC
+ color.c
+ hicnd.c
+ )
+
+ # hicn-light-daemon does not compile under Android due to bindSocket
+ if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Android")
+ build_executable(${HICN_LIGHT_DAEMON}
+ SOURCES ${DAEMON_SRC}
+ LINK_LIBRARIES ${LIBHICN_LIGHT_WHOLE_ARCHIVE}
+ DEPENDS ${LIBHICN_LIGHT_STATIC}
+ COMPONENT ${HICN_LIGHT}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ )
+ endif ()
+endif ()
diff --git a/hicn-light/src/hicn/cli/color.c b/hicn-light/src/hicn/cli/color.c
new file mode 100644
index 000000000..aed22e302
--- /dev/null
+++ b/hicn-light/src/hicn/cli/color.c
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include "color.h"
+
+#ifndef _WIN32
+
+void vprintfc(color_t color, const char* fmt, va_list ap) {
+ char* color_s;
+ switch (color) {
+#define _(x, y, z) \
+ case COLOR_##x: \
+ color_s = y; \
+ break;
+ foreach_color
+#undef _
+
+ case COLOR_UNDEFINED : case COLOR_N : default : // XXX
+ color_s = "";
+ break;
+ }
+ printf("%s", color_s);
+ vprintf(fmt, ap);
+}
+#else
+void vprintfc(color_t color, const char* fmt, va_list ap) {
+ int color_id;
+ switch (color) {
+#define _(x, y, z) \
+ case COLOR_##x: \
+ color_id = z; \
+ break;
+ foreach_color
+#undef _
+
+ case COLOR_UNDEFINED : case COLOR_N : color_id = 0;
+ break;
+ }
+ HANDLE hConsole = NULL;
+ WORD currentConsoleAttr;
+ CONSOLE_SCREEN_BUFFER_INFO csbi;
+ hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
+ if (GetConsoleScreenBufferInfo(hConsole, &csbi))
+ currentConsoleAttr = csbi.wAttributes;
+ if (color_id != 0) SetConsoleTextAttribute(hConsole, color_id);
+ fprintf("%s", color);
+ vfprintf(fmt, ap);
+ SetConsoleTextAttribute(hConsole, currentConsoleAttr);
+}
+#endif
+
+void printfc(color_t color, const char* fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ vprintfc(color, fmt, ap);
+ va_end(ap);
+}
diff --git a/hicn-light/src/hicn/cli/color.h b/hicn-light/src/hicn/cli/color.h
new file mode 100644
index 000000000..a9b71c047
--- /dev/null
+++ b/hicn-light/src/hicn/cli/color.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HICNLIGHT_COLOR
+#define HICNLIGHT_COLOR
+
+#include <stdarg.h>
+
+/*
+ * Format : color_name, escape sequence, windows id
+ */
+#define foreach_color \
+ _(RED, "\033[0;31m", 4) \
+ _(WHITE, "\033[0m", 7)
+
+typedef enum {
+ COLOR_UNDEFINED,
+#define _(x, y, z) COLOR_##x,
+ foreach_color
+#undef _
+ COLOR_N,
+} color_t;
+
+#define IS_VALID_COLOR(color) ((color != COLOR_UNDEFINED) && (color != COLOR_N))
+
+void vprintfc(color_t color, const char* fmt, va_list ap);
+
+void printfc(color_t color, const char* fmt, ...);
+
+#endif /* HICNLIGHT_COLOR */
diff --git a/hicn-light/src/hicn/cli/hicnc.c b/hicn-light/src/hicn/cli/hicnc.c
new file mode 100644
index 000000000..ed8d4ed97
--- /dev/null
+++ b/hicn-light/src/hicn/cli/hicnc.c
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <limits.h> // LONG_MAX, LONG_MIN
+#include <signal.h>
+#include <hicn/ctrl.h>
+
+#ifndef _WIN32
+#include <getopt.h>
+#endif
+
+#include "color.h"
+#include <hicn/ctrl/parse.h>
+#include <hicn/ctrl/hicn-light.h>
+#include <hicn/util/log.h>
+#include <hicn/util/sstrncpy.h>
+
+#define PORT 9695
+
+/*
+ * Duplicated from hicn_light_ng_api.c while is only available as a module in
+ * libhicnctrl
+ */
+const char *command_type_str[] = {
+#define _(l, u) [COMMAND_TYPE_##u] = STRINGIZE(u),
+ foreach_command_type
+#undef _
+};
+
+static struct option longFormOptions[] = {{"help", no_argument, 0, 'h'},
+ {"server", required_argument, 0, 'S'},
+ {"port", required_argument, 0, 'P'},
+ {0, 0, 0, 0}};
+
+static void usage(char *prog) {
+ printf("%s: portable hICN forwarder\n", prog);
+ printf("\n");
+ printf("Usage: %s COMMAND [PARAMETERS]\n", prog);
+ printf("\n");
+ printf(" %s -h This help screen.\n", prog);
+ printf(" %s help Obtain a list of available commands.\n", prog);
+ printf("\n");
+}
+
+static bool stop = false;
+void signal_handler(int sig) {
+ fprintf(stderr, "Received ^C... quitting !\n");
+ stop = true;
+}
+
+int main(int argc, char *const *argv) {
+ log_conf.log_level = LOG_INFO;
+
+ // Handle termination signal
+ struct sigaction sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = signal_handler;
+ sigaction(SIGINT, &sa, NULL);
+
+ /* Parse commandline */
+ char *server_ip = NULL;
+ uint16_t server_port = 0;
+
+ for (;;) {
+ // getopt_long stores the option index here.
+ int optind = 0;
+
+ int c = getopt_long(argc, argv, "dhS:P:", longFormOptions, &optind);
+ if (c == -1) break;
+
+ switch (c) {
+ case 'd':
+ log_conf.log_level = LOG_DEBUG;
+ break;
+ case 'S':
+ server_ip = optarg;
+ break;
+
+ case 'P': {
+ char *endptr;
+ long val = strtol(optarg, &endptr, 10);
+
+ errno = 0; /* To distinguish success/failure after call */
+
+ if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) ||
+ (errno != 0 && val == 0)) {
+ perror("strtol");
+ exit(EXIT_FAILURE);
+ }
+
+ if (endptr == optarg) {
+ fprintf(stderr, "No digits were found.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ if (*endptr != '\0') {
+ fprintf(stderr, "Spurious characters after number: %s.\n", endptr);
+ exit(EXIT_FAILURE);
+ }
+
+ if ((val < 1) || (val > 65535)) {
+ fprintf(stderr, "Invalid port number: %ld.\n", val);
+ exit(EXIT_FAILURE);
+ }
+
+ server_port = val;
+ break;
+ }
+
+ case 'h':
+ usage(argv[0]);
+ exit(EXIT_SUCCESS);
+
+ default:
+ fprintf(stderr, "Invalid argument.\n");
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ /* Parse */
+ char *param = argv[optind];
+ for (; optind < argc - 1; optind++) {
+ char *arg = argv[optind];
+ arg[strlen(arg)] = ' ';
+ }
+
+ if (!param) {
+ usage(argv[0]);
+ goto ERR_PARAM;
+ }
+
+ if (strncmp(param, "help", 4) == 0) {
+ if (help(param) < 0) {
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ exit(EXIT_SUCCESS);
+ }
+
+ hc_command_t command = {};
+ if (parse(param, &command) < 0) {
+ fprintf(stderr, "Error parsing command : '%s'\n", param);
+ goto ERR_PARSE;
+ }
+
+ hc_sock_t *s;
+ if (server_ip) {
+ if (server_port == 0) server_port = PORT;
+#define BUFSIZE 255
+ char url[BUFSIZE];
+ snprintf(url, BUFSIZE, "tcp://%s:%d/", server_ip, server_port);
+ s = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, url);
+ } else {
+ s = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, NULL);
+ }
+ if (!s) {
+ fprintf(stderr, "Could not create socket.\n");
+ goto ERR_SOCKET;
+ }
+
+ if (hc_sock_connect(s) < 0) {
+ fprintf(stderr, "Could not establish connection to forwarder.\n");
+ goto ERR_CONNECT;
+ }
+
+ if (!IS_VALID_OBJECT_TYPE(command.object_type) ||
+ !IS_VALID_ACTION(command.action)) {
+ fprintf(stderr, "Unsupported command");
+ goto ERR_PARAM;
+ }
+
+ int rc = UNSUPPORTED_CMD_ERROR;
+ hc_data_t *data = NULL;
+
+ rc = hc_execute(s, command.action, command.object_type, &command.object,
+ &data);
+
+ if (rc < 0) {
+ switch (rc) {
+ case INPUT_ERROR:
+ ERROR("Wrong input parameters");
+ break;
+ case UNSUPPORTED_CMD_ERROR:
+ ERROR("Unsupported command");
+ break;
+ default:
+ ERROR("Error executing command");
+ break;
+ }
+ goto ERR_COMMAND;
+ }
+
+ if (!data) goto ERR_QUERY;
+ if (!hc_data_get_result(data)) goto ERR_DATA;
+
+ if (command.action == ACTION_LIST) {
+ char buf[MAXSZ_HC_OBJECT];
+ hc_data_foreach(data, obj, {
+ rc = hc_object_snprintf(buf, MAXSZ_HC_OBJECT, command.object_type, obj);
+ if (rc < 0)
+ WARN("Display error");
+ else if (rc >= MAXSZ_HC_OBJECT)
+ WARN("Output truncated");
+ else
+ printf("%s\n", buf);
+ });
+ }
+
+ hc_data_free(data);
+ hc_sock_free(s);
+ return EXIT_SUCCESS;
+
+ERR_DATA:
+ hc_data_free(data);
+ERR_QUERY:
+ERR_COMMAND:
+ERR_CONNECT:
+ hc_sock_free(s);
+ERR_SOCKET:
+ERR_PARSE:
+ERR_PARAM:
+ ERROR("Error");
+ return EXIT_FAILURE;
+}
diff --git a/hicn-light/src/hicn/cli/hicnd.c b/hicn-light/src/hicn/cli/hicnd.c
new file mode 100644
index 000000000..fa1b1c024
--- /dev/null
+++ b/hicn-light/src/hicn/cli/hicnd.c
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include <hicn/util/log.h>
+#include <hicn/base/loop.h>
+
+#include "logo.h"
+#include "../core/forwarder.h"
+#include "../config/configuration.h" // XXX needed ?
+#include "../config/configuration_file.h"
+
+static void usage(const char *prog) {
+ printf(
+ "Usage: %s [--port port]"
+#ifndef _WIN32
+ " [--daemon]"
+#endif
+ " [--capacity objectStoreSize] [--log level]"
+ "[--log-file filename] [--config file]\n",
+ prog);
+ printf("\n");
+ printf(
+ "hicn-light run as a daemon is the program to launch the forwarder, "
+ "either as a console program\n");
+ printf(
+ "or a background daemon (detatched from console). Once running, use the "
+ "program controller to\n");
+ printf("configure hicn-light.\n");
+ printf("\n");
+ printf(
+ "The configuration file contains configuration lines as per "
+ "controller\n");
+ printf(
+ "If logging level or content store capacity is set in the configuraiton "
+ "file, it overrides the command_line\n");
+ printf(
+ "When a configuration file is specified, no default listeners on 'port' "
+ "are setup. Only 'add listener' lines\n");
+ printf("in the configuration file matter.\n");
+ printf("\n");
+ printf(
+ "If no configuration file is specified, daemon will listen on TCP and "
+ "UDP ports specified by\n");
+ printf(
+ "the --port flag (or default port). It will listen on both IPv4 and "
+ "IPv6 if available.\n");
+ printf("\n");
+ printf("Options:\n");
+ printf("%-30s = tcp port for in-bound connections\n", "--port <tcp_port>");
+#ifndef _WIN32
+ printf("%-30s = start as daemon process\n", "--daemon");
+#endif
+ printf(
+ "%-30s = maximum number of content objects to cache. To disable the "
+ "cache objectStoreSize must be 0.\n",
+ "--capacity <objectStoreSize>");
+ printf("%-30s Default vaule for objectStoreSize is 100000\n", "");
+ printf(
+ "%-30s = sets the log level. Available levels: trace, debug, info, warn, "
+ "error, fatal\n",
+ "--log <level>");
+ printf("%-30s = file to write log messages to (required in daemon mode)\n",
+ "--log-file <output_logfile>");
+ printf("%-30s = configuration filename\n", "--config <config_path>");
+ printf("\n");
+}
+
+#ifndef _WIN32
+static int daemonize(int logfile_fd) {
+ /* Check whether we already are a daemon */
+ if (getppid() == 1) return 0;
+
+ int rc = fork();
+ if (rc < 0) {
+ ERROR("Fork error");
+ goto ERR_FORK;
+ } else if (rc > 0) {
+ /* Parent exits successfully */
+ exit(EXIT_SUCCESS);
+ }
+
+ /* Child daemon detaches */
+ DEBUG("child continuing, pid = %u\n", getpid());
+
+ /* get a new process group independent from old parent */
+ setsid();
+
+ /* close all descriptors (apart from the logfile) */
+#ifdef __ANDROID__
+ for (int i = sysconf(_SC_OPEN_MAX); i >= 0; --i) close(i);
+#else
+ for (int i = getdtablesize(); i >= 0; --i) {
+ if (i != logfile_fd) close(i);
+ }
+#endif
+
+ /*
+ * Reset errno because it might be seg to EBADF from the close calls above
+ */
+ errno = 0;
+ /* Redirect stdin and stdout and stderr to /dev/null */
+ const char *devnull = "/dev/null";
+ int nullfile = open(devnull, O_RDWR);
+ if (nullfile < 0) {
+ ERROR("Error opening file '%s': (%d) %s", devnull, errno, strerror(errno));
+ goto ERR_DEVNULL;
+ }
+
+ /* Redirect stdout and stderr to the logfile */
+ rc = dup2(logfile_fd, STDOUT_FILENO);
+ if (rc != STDOUT_FILENO) {
+ ERROR("Error duping fd 1 got %d file: (%d) %s", rc, errno, strerror(errno));
+ goto ERR_DUP1;
+ }
+ rc = dup2(logfile_fd, STDERR_FILENO);
+ if (rc != STDERR_FILENO) {
+ ERROR("Error duping fd 2 got %d file: (%d) %s", rc, errno, strerror(errno));
+ goto ERR_DUP2;
+ }
+
+ /* Forwarder will capture signals */
+ return 0;
+
+ERR_DUP2:
+ERR_DUP1:
+ERR_DEVNULL:
+ERR_FORK:
+ return -1;
+}
+#endif
+
+static void signal_cb(int sig) {
+ switch (sig) {
+ case SIGTERM:
+ case SIGINT:
+ INFO("caught an interrupt signal, exiting cleanly");
+ break;
+#ifndef _WIN32
+ case SIGUSR1:
+ // dump stats
+ break;
+#endif
+ default:
+ break;
+ }
+
+ if (loop_break(MAIN_LOOP) < 0) {
+ ERROR("Failed to terminate main loop");
+ _exit(1);
+ }
+}
+
+static void signal_setup() {
+#ifndef _WIN32
+ signal(SIGUSR1, signal_cb);
+
+ /* ignore child */
+ signal(SIGCHLD, SIG_IGN);
+
+ /* ignore tty signals */
+ signal(SIGTSTP, SIG_IGN);
+ signal(SIGTTOU, SIG_IGN);
+ signal(SIGTTIN, SIG_IGN);
+#endif
+ signal(SIGINT, signal_cb);
+ signal(SIGTERM, signal_cb);
+}
+
+configuration_t *parse_commandline(int argc, const char *argv[]) {
+ if (argc == 2 && strcasecmp(argv[1], "-h") == 0) {
+ usage(argv[0]);
+ exit(EXIT_SUCCESS); // XXX redundant
+ }
+
+ configuration_t *configuration = configuration_create();
+
+ // XXX use getoptlong ????
+ for (int i = 0; i < argc; i++) {
+ if (argv[i][0] == '-') {
+ if (strcmp(argv[i], "--config") == 0) {
+ const char *fn_config = argv[i + 1];
+ configuration_set_fn_config(configuration, fn_config);
+ i++;
+ } else if (strcmp(argv[i], "--port") == 0) {
+ uint16_t port = atoi(argv[i + 1]);
+ configuration_set_port(configuration, port);
+ i++;
+#ifndef _WIN32
+ } else if (strcmp(argv[i], "--daemon") == 0) {
+ configuration_set_daemon(configuration, true);
+#endif
+ } else if (strcmp(argv[i], "--capacity") == 0 ||
+ strcmp(argv[i], "-c") == 0) {
+ int capacity = atoi(argv[i + 1]);
+ configuration_set_cs_size(configuration, capacity);
+ i++;
+ } else if (strcmp(argv[i], "--log") == 0) {
+ int loglevel = loglevel_from_str(argv[i + 1]);
+ configuration_set_loglevel(configuration, loglevel);
+ i++;
+ } else if (strcmp(argv[i], "--log-file") == 0) {
+ if (configuration_get_logfile(configuration)) {
+ fprintf(stderr, "Cannot specify --log-file more than once\n");
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+
+ const char *logfile = argv[i + 1];
+ configuration_set_logfile(configuration, logfile);
+ i++;
+ } else {
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ }
+ }
+
+ return configuration;
+}
+
+int main(int argc, const char *argv[]) {
+ signal_setup();
+ logo();
+
+ configuration_t *configuration = parse_commandline(argc, argv);
+ const char *logfile = configuration_get_logfile(configuration);
+ bool daemon = configuration_get_daemon(configuration);
+
+ // set restrictive umask, in case we create any files
+ umask(027);
+
+#ifndef _WIN32
+ if (daemon && (logfile == NULL)) {
+ fprintf(stderr, "Must specify a logfile when running in daemon mode\n");
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+
+ /* In daemon mode, parent will exit and child will continue */
+ if (daemon && daemonize(configuration_get_logfile_fd(configuration)) < 0) {
+ ERROR("Could not daemonize process");
+ exit(EXIT_FAILURE);
+ }
+#endif
+
+ /*
+ * The loop should be created before the forwarder instance as it is needed
+ * for timers
+ */
+ MAIN_LOOP = loop_create();
+
+ forwarder_t *forwarder = forwarder_create(configuration);
+ if (!forwarder) {
+ ERROR(
+ "Forwarder initialization failed. Are you running it with sudo "
+ "privileges?");
+ return -1;
+ }
+
+ forwarder_setup_local_listeners(forwarder,
+ configuration_get_port(configuration));
+
+ /* If specified, process the configuration file */
+ const char *fn_config = configuration_get_fn_config(configuration);
+ if (fn_config) configuration_file_process(forwarder, fn_config);
+ INFO("%s running port %d configuration-port %d", argv[0],
+ configuration_get_port(configuration),
+ configuration_get_configuration_port(configuration));
+
+ /* Main loop */
+ if (loop_dispatch(MAIN_LOOP) < 0) {
+ ERROR("Failed to run main loop");
+ return EXIT_FAILURE;
+ }
+
+ INFO("loop stopped");
+ forwarder_free(forwarder);
+ loop_free(MAIN_LOOP);
+ MAIN_LOOP = NULL;
+
+#ifdef _WIN32
+ WSACleanup(); // XXX why is this needed here ?
+#endif
+
+ configuration_flush_log();
+ return 0;
+}
diff --git a/hicn-light/src/hicn/cli/hicns.c b/hicn-light/src/hicn/cli/hicns.c
new file mode 100644
index 000000000..c03fa8599
--- /dev/null
+++ b/hicn-light/src/hicn/cli/hicns.c
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <limits.h> // LONG_MAX, LONG_MIN
+#include <hicn/ctrl.h>
+
+#ifndef _WIN32
+#include <getopt.h>
+#endif
+
+#include "logo.h"
+#include <hicn/ctrl/parse.h>
+#include <hicn/util/sstrncpy.h>
+
+#define PORT 9695
+
+static struct option longFormOptions[] = {{"help", no_argument, 0, 'h'},
+ {"server", required_argument, 0, 'S'},
+ {"port", required_argument, 0, 'P'},
+ {0, 0, 0, 0}};
+
+static void usage(char *prog) {
+ printf("%s: interactive shell for hicn-light\n", prog);
+ printf("\n");
+ printf("Usage: %s", prog);
+ printf("\n");
+ printf(" %s -h This help screen.\n", prog);
+ printf("\n");
+}
+
+void prompt(void) {
+ fputs("hicn> ", stdout);
+ fflush(stdout);
+}
+
+int shell(hc_sock_t *s) {
+ char *line = NULL;
+ size_t len = 0;
+ hc_data_t *data = NULL;
+ ssize_t nread;
+
+ hc_data_t *connections;
+
+ prompt();
+ while ((nread = getline(&line, &len, stdin)) != -1) {
+ hc_command_t command = {0};
+
+ char *pos;
+ if (line != NULL && (pos = strchr(line, '\n')) != NULL) {
+ *pos = '\0';
+ } else {
+ fprintf(stderr, "Error while reading command.\n");
+ goto CONTINUE;
+ }
+
+ if (strlen(line) == 0) goto CONTINUE;
+
+ if (strncmp(line, "exit", 4) == 0) break;
+ if (strncmp(line, "quit", 4) == 0) break;
+
+ if (parse(line, &command) < 0) {
+ fprintf(stderr, "Unknown command '%s'\n", line);
+ goto CONTINUE;
+ }
+
+ /* XXX connection list */
+ if (hc_connection_list(s, &connections) < 0) {
+ fprintf(stderr, "Error running command.\n");
+ goto CONTINUE;
+ }
+ // data = command.object.data;
+
+ char buf[MAXSZ_HC_CONNECTION]; // XXX
+ foreach_connection(c, data) {
+ /* XXX connection print */
+ int rc = hc_connection_snprintf(buf, MAXSZ_HC_CONNECTION, c);
+ if (rc < 0) {
+ strcpy_s(buf, sizeof(buf), "(Error)");
+ } else if (rc >= MAXSZ_HC_CONNECTION) {
+ buf[MAXSZ_HC_CONNECTION - 1] = '\0';
+ buf[MAXSZ_HC_CONNECTION - 2] = '.';
+ buf[MAXSZ_HC_CONNECTION - 3] = '.';
+ buf[MAXSZ_HC_CONNECTION - 4] = '.';
+ }
+ printf("%s\n", buf);
+ }
+
+ hc_data_free(data);
+ CONTINUE:
+ prompt();
+ }
+
+ return 0;
+}
+
+int main(int argc, char *const *argv) {
+ logo();
+ printf("Type 'help' for a list of available commands\n");
+ printf("\n");
+ printf("\n");
+
+ /* Parse commandline */
+ char *server_ip = NULL;
+ uint16_t server_port = 0;
+
+ for (;;) {
+ // getopt_long stores the option index here.
+ int optind = 0;
+
+ int c = getopt_long(argc, argv, "hS:P:", longFormOptions, &optind);
+ if (c == -1) break;
+
+ switch (c) {
+ case 'S':
+ server_ip = optarg;
+ break;
+
+ case 'P': {
+ char *endptr;
+ long val = strtol(optarg, &endptr, 10);
+
+ errno = 0; /* To distinguish success/failure after call */
+
+ if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) ||
+ (errno != 0 && val == 0)) {
+ perror("strtol");
+ exit(EXIT_FAILURE);
+ }
+
+ if (endptr == optarg) {
+ fprintf(stderr, "No digits were found.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ if (*endptr != '\0') {
+ fprintf(stderr, "Spurious characters after number: %s.\n", endptr);
+ exit(EXIT_FAILURE);
+ }
+
+ if ((val < 1) || (val > 65535)) {
+ fprintf(stderr, "Invalid port number: %ld.\n", val);
+ exit(EXIT_FAILURE);
+ }
+
+ server_port = (uint16_t)val;
+ break;
+ }
+
+ case 'h':
+ usage(argv[0]);
+ exit(EXIT_SUCCESS);
+
+ default:
+ fprintf(stderr, "Invalid argument.\n");
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ if (optind != argc) {
+ fprintf(stderr, "Invalid parameters.\n");
+ usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+
+ hc_sock_t *s;
+ if (server_ip) {
+ if (server_port == 0) server_port = PORT;
+#define BUFSIZE 255
+ char url[BUFSIZE];
+ snprintf(url, BUFSIZE, "tcp://%s:%d/", server_ip, server_port);
+ s = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, url);
+ } else {
+ s = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, NULL);
+ }
+ if (!s) {
+ fprintf(stderr, "Could not create socket.\n");
+ goto ERR_SOCK;
+ }
+
+ if (hc_sock_connect(s) < 0) {
+ fprintf(stderr, "Could not establish connection to forwarder.\n");
+ goto ERR_CONNECT;
+ }
+
+ int rc = shell(s);
+
+ exit((rc < 0) ? EXIT_FAILURE : EXIT_SUCCESS);
+
+ERR_CONNECT:
+ hc_sock_free(s);
+ERR_SOCK:
+ exit(EXIT_FAILURE);
+}
diff --git a/hicn-light/src/hicn/cli/logo.h b/hicn-light/src/hicn/cli/logo.h
new file mode 100644
index 000000000..a69097f91
--- /dev/null
+++ b/hicn-light/src/hicn/cli/logo.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HICNLIGHT_LOGO
+#define HICNLIGHT_LOGO
+
+#include "color.h"
+
+static void logo(void) {
+ printfc(COLOR_RED, " ____ ___ _ ");
+ printfc(COLOR_WHITE, " __ _ __ _ __ __\n");
+ printfc(COLOR_RED, " / __// _ \\ (_)___ ");
+ printfc(COLOR_WHITE, " / / (_)____ ___ ____/ /(_)___ _ / / / /_\n");
+ printfc(COLOR_RED, " / _/ / // /_ / // _ \\ ");
+ printfc(COLOR_WHITE, " / _ \\ / // __// _ \\___/ // // _ `// _ \\/ __/\n");
+ printfc(COLOR_RED, "/_/ /____/(_)/_/ \\___/ ");
+ printfc(COLOR_WHITE, "/_//_//_/ \\__//_//_/ /_//_/ \\_, //_//_/\\__/\n");
+ printfc(
+ COLOR_WHITE,
+ " /___/ "
+ "\n");
+ printf("\n");
+}
+
+#endif /* HICNLIGHT_LOGO */
diff --git a/hicn-light/src/hicn/command_line/CMakeLists.txt b/hicn-light/src/hicn/command_line/CMakeLists.txt
deleted file mode 100644
index 16c23dc5c..000000000
--- a/hicn-light/src/hicn/command_line/CMakeLists.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-add_subdirectory(controller)
-add_subdirectory(daemon)
diff --git a/hicn-light/src/hicn/command_line/controller/CMakeLists.txt b/hicn-light/src/hicn/command_line/controller/CMakeLists.txt
deleted file mode 100644
index 4cbd49220..000000000
--- a/hicn-light/src/hicn/command_line/controller/CMakeLists.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-list(APPEND CONTROLLER_SRC
- hicnLightControl_main.c
-)
-
-if (WIN32)
- set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:\"LIBCMT\"" )
-endif()
-
-if (NOT DISABLE_EXECUTABLES)
- if (${CMAKE_SYSTEM_NAME} MATCHES Android)
- set(LINK_FLAGS "-Wl,--unresolved-symbols=ignore-in-object-files")
- endif()
-
- build_executable(${HICN_LIGHT_CONTROL}
- SOURCES ${CONTROLLER_SRC}
- LINK_LIBRARIES ${LIBHICN_LIGHT_STATIC}
- DEPENDS ${LIBHICN_LIGHT_STATIC}
- COMPONENT ${HICN_LIGHT}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- LINK_FLAGS ${LINK_FLAGS}
- )
-endif ()
diff --git a/hicn-light/src/hicn/command_line/controller/hicnLightControl_main.c b/hicn-light/src/hicn/command_line/controller/hicnLightControl_main.c
deleted file mode 100644
index e6a97c4e2..000000000
--- a/hicn-light/src/hicn/command_line/controller/hicnLightControl_main.c
+++ /dev/null
@@ -1,382 +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/hicn-light/config.h>
-#include <hicn/utils/utils.h>
-
-
-#ifndef _WIN32
-#include <arpa/inet.h>
-#include <getopt.h>
-#include <netinet/in.h>
-#include <sys/socket.h>
-#include <sys/uio.h>
-#include <unistd.h>
-#include <arpa/inet.h>
-#endif
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <string.h>
-
-#include <parc/security/parc_IdentityFile.h>
-#include <parc/security/parc_Security.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_List.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_SafeMemory.h>
-
-#include <hicn/core/dispatcher.h>
-#include <hicn/core/forwarder.h>
-
-#include <errno.h>
-#include <hicn/config/controlRoot.h>
-#include <hicn/config/controlState.h>
-
-#include <hicn/utils/commands.h>
-
-
-
-size_t commandOutputLen = 0; // preserve the number of structs composing
- // payload in case on not interactive call.
-
-// REMINDER: when a new_command is added, the following array has to be updated
-// with the sizeof(new_command). It allows to allocate the buffer for receiving
-// the payload of the DAEMON RESPONSE after the header has beed read. Each
-// command identifier (typedef enum command_id) corresponds to a position in the
-// following array.
-static int payloadLengthController[LAST_COMMAND_VALUE] = {
- sizeof(add_listener_command),
- sizeof(add_connection_command),
- sizeof(list_connections_command), // needed when get response from FWD
- sizeof(add_route_command),
- sizeof(list_routes_command), // needed when get response from FWD
- sizeof(remove_connection_command),
- sizeof(remove_listener_command),
- sizeof(remove_route_command),
- sizeof(cache_store_command),
- sizeof(cache_serve_command),
- 0, // cache clear
- sizeof(set_strategy_command),
- sizeof(set_wldr_command),
- sizeof(add_punting_command),
- sizeof(list_listeners_command), // needed when get response from FWD
- sizeof(mapme_activator_command),
- sizeof(mapme_activator_command),
- sizeof(mapme_timing_command),
- sizeof(mapme_timing_command),
- sizeof(mapme_send_update_command),
- sizeof(connection_set_admin_state_command),
-#ifdef WITH_POLICY
- sizeof(add_policy_command),
- sizeof(list_policies_command),
- sizeof(remove_policy_command),
- sizeof(update_connection_command),
- sizeof(connection_set_priority_command),
- sizeof(connection_set_tags_command),
-#endif
-};
-
-typedef struct controller_main_state {
- ControlState *controlState;
-} ControlMainState;
-
-static void _printRed(const char *output) {
-#ifndef _WIN32
- printf("\033[0;31m%s", output);
-#else
- HANDLE hConsole = NULL;
- WORD currentConsoleAttr;
- CONSOLE_SCREEN_BUFFER_INFO csbi;
- hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
- if (GetConsoleScreenBufferInfo(hConsole, &csbi))
- currentConsoleAttr = csbi.wAttributes;
- SetConsoleTextAttribute(hConsole, 4);
- printf("%s", output);
- SetConsoleTextAttribute(hConsole, currentConsoleAttr);
-#endif
-}
-
-static void _printWhite(const char *output) {
-#ifndef _WIN32
- printf("\033[0m%s", output);
-#else
- HANDLE hConsole = NULL;
- WORD currentConsoleAttr;
- CONSOLE_SCREEN_BUFFER_INFO csbi;
- hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
- if (GetConsoleScreenBufferInfo(hConsole, &csbi))
- currentConsoleAttr = csbi.wAttributes;
- SetConsoleTextAttribute(hConsole, 7);
- printf("%s", output);
- SetConsoleTextAttribute(hConsole, currentConsoleAttr);
-#endif
-}
-
-static void _displayForwarderLogo(void) {
- _printRed(" ____ ___ _ ");
- _printWhite(" __ _ __ _ __ __\n");
- _printRed(" / __// _ \\ (_)___ ");
- _printWhite(" / / (_)____ ___ ____/ /(_)___ _ / / / /_\n");
- _printRed(" / _/ / // /_ / // _ \\ ");
- _printWhite(" / _ \\ / // __// _ \\___/ // // _ `// _ \\/ __/\n");
- _printRed("/_/ /____/(_)/_/ \\___/ ");
- _printWhite("/_//_//_/ \\__//_//_/ /_//_/ \\_, //_//_/\\__/\n");
- _printWhite(
- " /___/ "
- "\n");
- printf("\n");
-}
-
-static void _displayUsage(char *programName) {
- printf("Usage: %s -h\n", programName);
- printf(
- "hicn-light is the 1.0 source, which runs on each end system and as a "
- "software source\n");
- printf(
- "on intermediate systems. controller is the program to configure the "
- "source, daemon.\n");
- printf("\n");
- printf("Options:\n");
- printf("-h = This help screen\n");
- printf(
- "commands = configuration line to send to hicn-light (use 'help' "
- "for list)\n");
- printf("\n");
-}
-
-static int _parseArgs(int argc, char *argv[], char **server_ip,
- uint16_t *server_port, PARCList *commandList){
- static struct option longFormOptions[] = {
- {"help", no_argument, 0, 'h'},
- {"server", required_argument, 0, 'S'},
- {"port", required_argument, 0, 'P'},
- {0, 0, 0, 0}};
-
- int c;
-
- while (1) {
- // getopt_long stores the option index here.
- int optionIndex = 0;
-
- c = getopt_long(argc, argv, "hS:P:", longFormOptions, &optionIndex);
-
- // Detect the end of the options.
- if (c == -1) {
- break;
- }
-
- switch (c) {
- case 'S':
- {
- *server_ip = optarg;
- struct sockaddr_in sa;
- int result = inet_pton(AF_INET, *server_ip, &(sa.sin_addr));
- //inet_pton() returns 1 on success
- if(result != 1){
- return 0;
- }
- break;
- }
- case 'P':
- {
- char * port_str = optarg;
- if(utils_IsNumber(port_str)){
- *server_port = (uint16_t) strtol(port_str, NULL, 10);
- } else {
- return 0;
- }
- break;
- }
- case 'h':
- default:
- return 0;
- }
- }
-
- if (optind < argc) {
- while (optind < argc) {
- parcList_Add(commandList, argv[optind]);
- optind++;
- }
- }
-
- return 1;
-}
-
-struct iovec *_writeAndReadMessage(ControlState *state, struct iovec *msg) {
- parcAssertNotNull(msg, "Parameter msg must be non-null");
- int sockfd = controlState_GetSockfd(state);
-
- // check if request has a payload
- if (((header_control_message *)msg[0].iov_base)->length >
- 0) { // command with payload
- // write header + payload (compatibility issue: two write needed instead of
- // the writev)
-#ifndef _WIN32
- if (write(sockfd, msg[0].iov_base, (unsigned int)msg[0].iov_len) < 0 ||
- write(sockfd, msg[1].iov_base, (unsigned int)msg[1].iov_len) < 0) {
-#else
- if (send(sockfd, msg[0].iov_base, (int)msg[0].iov_len, 0) == SOCKET_ERROR ||
- send(sockfd, msg[1].iov_base, (int)msg[1].iov_len, 0) == SOCKET_ERROR) {
-#endif
- printf("\nError while sending the Message: cannot write on socket \n");
- exit(EXIT_FAILURE);
- }
- parcMemory_Deallocate(&msg[1].iov_base);
- } else { // command without payload, e.g. 'list'
- // write header only
-#ifndef _WIN32
- if (write(sockfd, msg[0].iov_base, msg[0].iov_len) < 0) {
-#else
- int result = send(sockfd, msg[0].iov_base, (int)msg[0].iov_len, 0);
- if (result == SOCKET_ERROR) {
-#endif
- printf("\nError while sending the Message: cannot write on socket \n");
- exit(EXIT_FAILURE);
- }
- }
- parcMemory_Deallocate(&msg[0].iov_base);
-
- // ======= RECEIVE =======
-
- header_control_message *headerResponse =
- (header_control_message *)parcMemory_AllocateAndClear(
- sizeof(header_control_message));
- if (recv(sockfd, (char *)headerResponse, sizeof(header_control_message), 0) <
- 0) {
- printf("\nError in Receiving the Message \n");
- exit(EXIT_FAILURE);
- }
-
- if (headerResponse->messageType < RESPONSE_LIGHT ||
- headerResponse->messageType >= LAST_MSG_TYPE_VALUE) {
- char *checkFinMsg = parcMemory_Reallocate(headerResponse, 32);
-#ifndef _WIN32
- if (recv(sockfd, checkFinMsg, sizeof(checkFinMsg),
- MSG_PEEK | MSG_DONTWAIT) == 0) {
-#else
- if (recv(sockfd, checkFinMsg, sizeof(checkFinMsg), MSG_PEEK) == 0) {
-#endif
- // if recv returns zero, that means the connection has been closed:
- close(sockfd);
- printf("\nConnection terminated by the Daemon. Exiting... \n");
- exit(EXIT_SUCCESS);
- } else {
- printf("\nError: Unrecognized message type received \n");
- exit(EXIT_FAILURE);
- }
- }
-
- void *payloadResponse = NULL;
-
- if ((commandOutputLen = headerResponse->length) > 0) {
- payloadResponse = parcMemory_AllocateAndClear(
- payloadLengthController[headerResponse->commandID] *
- headerResponse->length);
-
- if (recv(sockfd, payloadResponse,
- payloadLengthController[headerResponse->commandID] *
- headerResponse->length,
- 0) < 0) {
- printf("\nError in Receiving the Message \n");
- exit(EXIT_FAILURE);
- }
- }
-
- struct iovec *response =
- parcMemory_AllocateAndClear(sizeof(struct iovec) * 2);
-
- response[0].iov_base = headerResponse;
- response[0].iov_len = sizeof(header_control_message);
- response[1].iov_base = payloadResponse;
- response[1].iov_len = payloadLengthController[headerResponse->commandID] *
- headerResponse->length;
-
- return response;
-}
-
-int main(int argc, char *argv[]) {
- _displayForwarderLogo();
-
-#ifdef _WIN32
- WSADATA wsaData;
- WSAStartup(MAKEWORD(2, 2), &wsaData);
-#endif
-
- if (argc == 2 && strcmp("-h", argv[1]) == 0) {
- _displayUsage(argv[0]);
- exit(EXIT_SUCCESS);
- }
-
- PARCList *commands =
- parcList(parcArrayList_Create(NULL), PARCArrayListAsPARCList);
-
- char *server_ip = SRV_CTRL_IP;
- uint16_t server_port = SRV_CTRL_PORT;
- if (!_parseArgs(argc, argv, &server_ip,
- &server_port, commands)) {
- _displayUsage(argv[0]);
- parcList_Release(&commands);
- exit(EXIT_FAILURE);
- }
-
- ControlMainState mainState;
- mainState.controlState =
- controlState_Create(&mainState, _writeAndReadMessage, true,
- server_ip, server_port);
- if (mainState.controlState == NULL) {
- exit(EXIT_FAILURE);
- }
-
- controlState_RegisterCommand(mainState.controlState,
- controlRoot_HelpCreate(mainState.controlState));
- controlState_RegisterCommand(mainState.controlState,
- controlRoot_Create(mainState.controlState));
-
- if (parcList_Size(commands) > 0) {
- controlState_SetInteractiveFlag(mainState.controlState, false);
- char output[8192];
- controlState_DispatchCommand(mainState.controlState, commands, output, sizeof(output));
- printf("%s", output);
- char **commandOutputMain =
- controlState_GetCommandOutput(mainState.controlState);
- if (commandOutputMain != NULL && commandOutputLen > 0) {
-#if 0
- for (size_t j = 0; j < commandOutputLen; j++) {
- printf("Output %zu: %s \n", j, commandOutputMain[j]);
- }
-#endif
- controlState_ReleaseCommandOutput(mainState.controlState,
- commandOutputMain, commandOutputLen);
- }
- // release
-
- } else {
- controlState_Interactive(mainState.controlState);
- }
-
- parcList_Release(&commands);
-
- controlState_Destroy(&mainState.controlState);
-#ifdef _WIN32
- WSACleanup();
-#endif
- return EXIT_SUCCESS;
-}
diff --git a/hicn-light/src/hicn/command_line/daemon/hicnLightDaemon_main.c b/hicn-light/src/hicn/command_line/daemon/hicnLightDaemon_main.c
deleted file mode 100644
index ab7039f5e..000000000
--- a/hicn-light/src/hicn/command_line/daemon/hicnLightDaemon_main.c
+++ /dev/null
@@ -1,414 +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.
- */
-
-#ifndef _WIN32
-#include <unistd.h>
-#endif
-#include <errno.h>
-#include <fcntl.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-
-#include <hicn/hicn-light/config.h>
-#include <parc/algol/parc_FileOutputStream.h>
-#include <parc/logging/parc_LogLevel.h>
-#include <parc/logging/parc_LogReporterFile.h>
-#include <parc/logging/parc_LogReporterTextStdout.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/core/dispatcher.h>
-#include <hicn/core/forwarder.h>
-
-static void _printRed(const char *output) {
-#ifndef _WIN32
- printf("\033[0;31m%s", output);
-#else
- HANDLE hConsole = NULL;
- WORD currentConsoleAttr;
- CONSOLE_SCREEN_BUFFER_INFO csbi;
- hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
- if (GetConsoleScreenBufferInfo(hConsole, &csbi))
- currentConsoleAttr = csbi.wAttributes;
- SetConsoleTextAttribute(hConsole, 4);
- printf("%s", output);
- SetConsoleTextAttribute(hConsole, currentConsoleAttr);
-#endif
-}
-
-static void _printWhite(const char *output) {
-#ifndef _WIN32
- printf("\033[0m%s", output);
-#else
- HANDLE hConsole = NULL;
- WORD currentConsoleAttr;
- CONSOLE_SCREEN_BUFFER_INFO csbi;
- hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
- if (GetConsoleScreenBufferInfo(hConsole, &csbi))
- currentConsoleAttr = csbi.wAttributes;
- SetConsoleTextAttribute(hConsole, 7);
- printf("%s", output);
- SetConsoleTextAttribute(hConsole, currentConsoleAttr);
-#endif
-}
-
-static void _displayForwarderLogo(void) {
- _printRed(" ____ ___ _ ");
- _printWhite(" __ _ __ _ __ __\n");
- _printRed(" / __// _ \\ (_)___ ");
- _printWhite(" / / (_)____ ___ ____/ /(_)___ _ / / / /_\n");
- _printRed(" / _/ / // /_ / // _ \\ ");
- _printWhite(" / _ \\ / // __// _ \\___/ // // _ `// _ \\/ __/\n");
- _printRed("/_/ /____/(_)/_/ \\___/ ");
- _printWhite("/_//_//_/ \\__//_//_/ /_//_/ \\_, //_//_/\\__/\n");
- _printWhite(
- " /___/ "
- "\n");
- printf("\n");
-}
-
-static void _usage(int exitCode) {
-#ifndef _WIN32
- printf(
- "Usage: hicn-light-daemon [--port port] [--capacity objectStoreSize] "
- "[--log facility=level] [--log-file filename] [--config file]\n");
-#else
- printf(
- "Usage: hicn-light-daemon.exe [--port port] [--daemon] [--capacity objectStoreSize] "
- "[--log facility=level] [--log-file filename] [--config file]\n");
-#endif
- printf("\n");
- printf(
- "hicn-light run as a daemon is the program to launch the forwarder, "
- "either as a console program\n");
- printf(
- "or a background daemon (detatched from console). Once running, use the "
- "program controller to\n");
- printf("configure hicn-light.\n");
- printf("\n");
- printf(
- "The configuration file contains configuration lines as per "
- "controller\n");
- printf(
- "If logging level or content store capacity is set in the configuraiton "
- "file, it overrides the command_line\n");
- printf(
- "When a configuration file is specified, no default listeners on 'port' "
- "are setup. Only 'add listener' lines\n");
- printf("in the configuration file matter.\n");
- printf("\n");
- printf(
- "If no configuration file is specified, daemon will listen on TCP and "
- "UDP ports specified by\n");
- printf(
- "the --port flag (or default port). It will listen on both IPv4 and "
- "IPv6 if available.\n");
- printf("\n");
- printf("Options:\n");
- printf("--port = tcp port for in-bound connections\n");
-#ifndef _WIN32
- printf("--daemon = start as daemon process\n");
-#endif
- printf("--objectStoreSize = maximum number of content objects to cache\n");
- printf(
- "--log = sets a facility to a given log level. You can have "
- "multiple of these.\n");
- printf(
- " facilities: all, config, core, io, message, "
- "processor\n");
- printf(
- " levels: debug, info, notice, warning, error, "
- "critical, alert, off\n");
- printf(" example: daemon --log io=debug --log core=off\n");
- printf(
- "--log-file = file to write log messages to (required in daemon "
- "mode)\n");
- printf("--config = configuration filename\n");
- printf("\n");
- exit(exitCode);
-}
-
-static void _setLogLevelToLevel(int logLevelArray[LoggerFacility_END],
- LoggerFacility facility,
- const char *levelString) {
- PARCLogLevel level = parcLogLevel_FromString(levelString);
-
- if (level < PARCLogLevel_All) {
- // we have a good facility and level
- logLevelArray[facility] = level;
- } else {
- printf("Invalid log level string %s\n", levelString);
- _usage(EXIT_FAILURE);
- }
-}
-
-/**
- * string: "facility=level"
- * Set the right thing in the logger
- */
-static void _setLogLevel(int logLevelArray[LoggerFacility_END],
- const char *string) {
- char *tofree = parcMemory_StringDuplicate(string, strlen(string));
- char *p = tofree;
-
- char *facilityString = strtok(p, "=");
- if (facilityString) {
- char *levelString = strtok(NULL, "=");
-
- if (strcasecmp(facilityString, "all") == 0) {
- for (LoggerFacility facility = 0; facility < LoggerFacility_END;
- facility++) {
- _setLogLevelToLevel(logLevelArray, facility, levelString);
- }
- } else {
- LoggerFacility facility;
- for (facility = 0; facility < LoggerFacility_END; facility++) {
- if (strcasecmp(facilityString, logger_FacilityString(facility)) == 0) {
- break;
- }
- }
-
- if (facility < LoggerFacility_END) {
- _setLogLevelToLevel(logLevelArray, facility, levelString);
- } else {
- printf("Invalid facility string %s\n", facilityString);
- _usage(EXIT_FAILURE);
- }
- }
- }
-
- parcMemory_Deallocate((void **)&tofree);
-}
-
-#ifndef _WIN32
-static void _daemonize(void) {
- if (getppid() == 1) {
- // already a daemon
- return;
- }
-
- int forkReturn = fork();
- parcTrapUnexpectedStateIf(forkReturn < 0, "Fork error")
-
- if (forkReturn > 0) {
- // parent exits
- exit(EXIT_SUCCESS);
- }
-
- // Child daemon detaches
- printf("child continuing, pid = %u\n", getpid());
-
- // get a new process group independent from old parent
- setsid();
-
- /* close all descriptors */
-#ifdef __ANDROID__
- for (int i = sysconf(_SC_OPEN_MAX); i >= 0; --i) {
- close(i);
- }
-#else
- for (int i = getdtablesize(); i >= 0; --i) {
- close(i);
- }
-#endif
- // reset errno because it might be seg to EBADF from the close calls above
- errno = 0;
-
- // Redirect stdin and stdout and stderr to /dev/null
- const char *devnull = "/dev/null";
- int nullfile = open(devnull, O_RDWR);
- parcAssertTrue(nullfile >= 0, "Error opening file '%s': (%d) %s", devnull,
- errno, strerror(errno));
-
- int ret;
- ret = dup(nullfile);
- parcAssertTrue(ret == 1, "Error duping fd 1 got %d file: (%d) %s", ret, errno,
- strerror(errno));
- ret = dup(nullfile);
- parcAssertTrue(ret == 2, "Error duping fd 2, got %d file: (%d) %s", ret,
- errno, strerror(errno));
-
- // forwarder will capture signals
-}
-#endif
-
-static Logger *_createLogfile(const char *logfile) {
-#ifndef _WIN32
- int logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT, S_IWUSR | S_IRUSR);
-#else
- int logfd =
- _open(logfile, _O_WRONLY | _O_APPEND | _O_CREAT, _S_IWRITE | _S_IREAD);
-#endif
- if (logfd < 0) {
- fprintf(stderr, "Error opening %s for writing: (%d) %s\n", logfile, errno,
- strerror(errno));
- exit(EXIT_FAILURE);
- }
-
-#ifndef _WIN32
- chmod(logfile, S_IRWXU);
-#endif
-
- PARCFileOutputStream *fos = parcFileOutputStream_Create(logfd);
- PARCOutputStream *pos = parcFileOutputStream_AsOutputStream(fos);
- PARCLogReporter *reporter = parcLogReporterFile_Create(pos);
-
- Logger *logger = logger_Create(reporter, parcClock_Wallclock());
-
- parcOutputStream_Release(&pos);
- parcLogReporter_Release(&reporter);
-
- return logger;
-}
-
-int main(int argc, const char *argv[]) {
- _displayForwarderLogo();
-#ifndef _WIN32
- bool daemon = false;
-#else
- WSADATA wsaData = {0};
- WSAStartup(MAKEWORD(2, 2), &wsaData);
-#endif
-
- uint16_t port = PORT_NUMBER;
- uint16_t configurationPort = 2001;
- int capacity = -1;
- const char *configFileName = NULL;
-
- char *logfile = NULL;
-
- if (argc == 2 && strcasecmp(argv[1], "-h") == 0) {
- _usage(EXIT_SUCCESS);
- }
-
- int logLevelArray[LoggerFacility_END];
- for (int i = 0; i < LoggerFacility_END; i++) {
- logLevelArray[i] = -1;
- }
-
- for (int i = 0; i < argc; i++) {
- if (argv[i][0] == '-') {
- if (strcmp(argv[i], "--config") == 0) {
- configFileName = argv[i + 1];
- i++;
- } else if (strcmp(argv[i], "--port") == 0) {
- port = atoi(argv[i + 1]);
- i++;
-#ifndef _WIN32
- } else if (strcmp(argv[i], "--daemon") == 0) {
- daemon = true;
-#endif
- } else if (strcmp(argv[i], "--capacity") == 0 ||
- strcmp(argv[i], "-c") == 0) {
- capacity = atoi(argv[i + 1]);
- i++;
- } else if (strcmp(argv[i], "--log") == 0) {
- _setLogLevel(logLevelArray, argv[i + 1]);
- i++;
- } else if (strcmp(argv[i], "--log-file") == 0) {
- if (logfile) {
- // error cannot repeat
- fprintf(stderr, "Cannot specify --log-file more than once\n");
- _usage(EXIT_FAILURE);
- }
-
- logfile = parcMemory_StringDuplicate(argv[i + 1], strlen(argv[i + 1]));
- i++;
- } else {
- _usage(EXIT_FAILURE);
- }
- }
- }
-
- // set restrictive umask, in case we create any files
- umask(027);
-
-#ifndef _WIN32
- if (daemon && (logfile == NULL)) {
- fprintf(stderr, "Must specify a logfile when running in daemon mode\n");
- _usage(EXIT_FAILURE);
- }
-
- if (daemon) {
- // inside this call, parent will EXIT_SUCCESS and child will continue
- _daemonize();
- }
-#endif
-
- Logger *logger = NULL;
- if (logfile) {
- logger = _createLogfile(logfile);
- parcMemory_Deallocate((void **)&logfile);
- } else {
- PARCLogReporter *stdoutReporter = parcLogReporterTextStdout_Create();
- logger = logger_Create(stdoutReporter, parcClock_Wallclock());
- parcLogReporter_Release(&stdoutReporter);
- }
-
- for (int i = 0; i < LoggerFacility_END; i++) {
- if (logLevelArray[i] > -1) {
- logger_SetLogLevel(logger, i, logLevelArray[i]);
- }
- }
-
- // this will update the clock to the tick clock
- Forwarder *forwarder = forwarder_Create(logger);
-
- if (forwarder == NULL) {
- logger_Log(logger, LoggerFacility_Core, PARCLogLevel_Error, "daemon",
- "Forwarder initialization failed. Are you running it with sudo "
- "privileges?");
- logger_Release(&logger);
- return -1;
- }
-
- Configuration *configuration = forwarder_GetConfiguration(forwarder);
-
- if (capacity > -1) {
- configuration_SetObjectStoreSize(configuration, capacity);
- }
-
- forwarder_SetupLocalListeners(forwarder, port);
- if (configFileName) {
- forwarder_SetupFromConfigFile(forwarder, configFileName);
- }
-
- Dispatcher *dispatcher = forwarder_GetDispatcher(forwarder);
-
- logger_Log(logger, LoggerFacility_Core, PARCLogLevel_Alert, "daemon",
- "hicn-light running port %d configuration-port %d", port,
- configurationPort);
-
- dispatcher_Run(dispatcher);
-
- logger_Log(logger, LoggerFacility_Core, PARCLogLevel_Alert, "daemon",
- "hicn-light exiting port %d", port);
-
- forwarder_Destroy(&forwarder);
-
-#ifndef _WIN32
- //sleep(2);
-#else
- //Sleep(2000);
- WSACleanup();
-#endif
-
- logger_Release(&logger);
- return 0;
-}
diff --git a/hicn-light/src/hicn/config.h.in b/hicn-light/src/hicn/config.h.in
index 90ab8e83f..6c2915b7e 100644
--- a/hicn-light/src/hicn/config.h.in
+++ b/hicn-light/src/hicn/config.h.in
@@ -2,7 +2,8 @@
#define LEVEL1_DCACHE_LINESIZE @LEVEL1_DCACHE_LINESIZE@
#ifndef _WIN32
-#define _GNU_SOURCE
+// This is now in CMakeLists.txt
+//#define _GNU_SOURCE
#else
#include <hicn/platforms/windows/win_portability.h>
#endif
diff --git a/hicn-light/src/hicn/config/CMakeLists.txt b/hicn-light/src/hicn/config/CMakeLists.txt
index 104026355..8e9415f7d 100644
--- a/hicn-light/src/hicn/config/CMakeLists.txt
+++ b/hicn-light/src/hicn/config/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2023 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -12,95 +12,35 @@
# limitations under the License.
list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/commandOps.h
- ${CMAKE_CURRENT_SOURCE_DIR}/commandParser.h
- ${CMAKE_CURRENT_SOURCE_DIR}/configuration.h
- ${CMAKE_CURRENT_SOURCE_DIR}/commandReturn.h
- ${CMAKE_CURRENT_SOURCE_DIR}/symbolicNameTable.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlState.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRoot.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddConnection.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAdd.h
- ${CMAKE_CURRENT_SOURCE_DIR}/configurationFile.h
- ${CMAKE_CURRENT_SOURCE_DIR}/configurationListeners.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddRoute.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPolicy.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddListener.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListConnections.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlList.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListListeners.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListRoutes.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListPolicies.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlQuit.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemove.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveListener.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveConnection.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveRoute.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePolicy.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSet.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUnset.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSetDebug.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUnsetDebug.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMe.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeEnable.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeDiscovery.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeTimescale.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheServe.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheStore.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheClear.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCache.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSetStrategy.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSetWldr.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPunting.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePunting.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdate.h
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdateConnection.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/configuration.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/commands.h
)
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/commandOps.c
- ${CMAKE_CURRENT_SOURCE_DIR}/commandParser.c
- ${CMAKE_CURRENT_SOURCE_DIR}/configuration.c
- ${CMAKE_CURRENT_SOURCE_DIR}/configurationFile.c
- ${CMAKE_CURRENT_SOURCE_DIR}/configurationListeners.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlState.c
- ${CMAKE_CURRENT_SOURCE_DIR}/symbolicNameTable.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAdd.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddConnection.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddRoute.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPolicy.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddListener.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlList.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListConnections.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListListeners.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListRoutes.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlListPolicies.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlQuit.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemove.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveListener.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveConnection.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveRoute.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePolicy.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRoot.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSet.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSetDebug.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUnset.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUnsetDebug.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMe.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeEnable.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeDiscovery.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeTimescale.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeRetx.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheServe.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheStore.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheClear.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlCache.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSetStrategy.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlSetWldr.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPunting.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePunting.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdate.c
- ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdateConnection.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/module_object.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/connection.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/listener.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/face.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/mapme.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/route.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/stats.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/strategy.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/modules/hicn_light/subscription.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/configuration.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/configuration_file.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_cache.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_connection.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_face.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_listener.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_mapme.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_policy.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_punting.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_route.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_stats.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_strategy.c
+ #${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_subscription.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/commands.c
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
diff --git a/hicn-light/src/hicn/config/commandOps.c b/hicn-light/src/hicn/config/commandOps.c
deleted file mode 100644
index dd8e148d0..000000000
--- a/hicn-light/src/hicn/config/commandOps.c
+++ /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.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#ifndef __ANDROID__
-#ifdef HAVE_ERRNO_H
-#include <errno.h>
-#else
-#ifndef _WIN32
-extern int errno;
-#endif
-#endif
-#endif
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/config/commandOps.h>
-#include <hicn/config/commandParser.h>
-
-CommandOps *commandOps_Create(void *closure, const char *command,
- void (*init)(CommandParser *parser,
- CommandOps *ops),
- CommandReturn (*execute)(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size),
- void (*destroyer)(CommandOps **opsPtr)) {
- parcAssertNotNull(command, "Parameter command must be non-null");
- parcAssertNotNull(execute, "Parameter execute must be non-null");
- CommandOps *ops = parcMemory_AllocateAndClear(sizeof(CommandOps));
- parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(CommandOps));
-
- ops->closure = closure;
- ops->command = parcMemory_StringDuplicate(command, strlen(command) + 1);
- ops->init = init;
- ops->execute = execute;
- ops->destroyer = destroyer;
- return ops;
-}
-
-void commandOps_Destroy(CommandOps **opsPtr) {
- parcAssertNotNull(opsPtr, "Parameter opsPtr must be non-null");
- parcAssertNotNull(*opsPtr,
- "Parameter opsPtr must dereference to non-null pointer");
-
- CommandOps *ops = *opsPtr;
- parcMemory_Deallocate((void **)&(ops->command));
- // DO NOT call ops->destroyer, we are one!
- parcMemory_Deallocate((void **)&ops);
-
- *opsPtr = NULL;
-}
diff --git a/hicn-light/src/hicn/config/commandOps.h b/hicn-light/src/hicn/config/commandOps.h
deleted file mode 100644
index 784b91eb8..000000000
--- a/hicn-light/src/hicn/config/commandOps.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file command_Ops.h
- * @brief The function structure defining a CLI command
- *
- * The function structure that defines a CLI command. Each command will return
- * one of these which defines how to run the command.
- *
- */
-
-#ifndef command_Ops_h
-#define command_Ops_h
-
-#include <parc/algol/parc_List.h>
-
-#include <hicn/config/commandReturn.h>
-
-// forward reference
-struct command_parser;
-
-struct command_ops;
-typedef struct command_ops CommandOps;
-
-/**
- * @typedef CommandOps
- * @abstract Each command implements a CommandOps
- * @constant closure is a user-specified pointer for any state the user needs
- * @constant command The text string of the command, must be the spelled out
- * string, e.g. "help list routes"
- * @constant init A function to call to initialize the command at program
- * startup
- * @constant execute A function to call to execute the command
- * @constant destroyer A function to call to release the command
- * @discussion
- * Typically, the root of the thee has an Init function that then initilizes
- * the rest of the tree. For example:
- *
- * @code
- * const CommandOps control_Root = {
- * .closure = NULL,
- * .command = "", // empty string for root
- * .init = control_Root_Init,
- * .execute = control_Root_Execute
- * .destroyer = NULL
- * };
- * @endcode
- *
- * The control_Root_Init function will then begin adding the subtree under root.
- * For example:
- *
- * @code
- * const CommandOps control_Add = {
- * .closure = NULL,
- * .command = "add",
- * .init = control_Add_Init,
- * .execute = control_Add_Execute,
- * .destroyer = NULL
- * };
- *
- * static void
- * control_Root_Init(ControlState *state, CommandOps *ops)
- * {
- * controlState_RegisterCommand(state, &control_Add);
- * }
- * @endcode
- */
-struct command_ops {
- void *closure;
- char *command;
- void (*init)(struct command_parser *parser, CommandOps *ops);
- CommandReturn (*execute)(struct command_parser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
- void (*destroyer)(CommandOps **opsPtr);
-};
-
-/**
- * A helper function to create the pubically defined CommandOps.
- *
- * Retruns allocated memory of the command
- *
- * @param [in] command The string is copied
- *
- * @retval <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-CommandOps *commandOps_Create(
- void *closure, const char *command,
- void (*init)(struct command_parser *parser, CommandOps *ops),
- CommandReturn (*execute)(struct command_parser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size),
- void (*destroyer)(CommandOps **opsPtr));
-
-/**
- * De-allocates the memory of the CommandOps and the copied command string
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @retval <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void commandOps_Destroy(CommandOps **opsPtr);
-#endif // command_Ops_h
diff --git a/hicn-light/src/hicn/config/commandParser.c b/hicn-light/src/hicn/config/commandParser.c
deleted file mode 100644
index f4652fe39..000000000
--- a/hicn-light/src/hicn/config/commandParser.c
+++ /dev/null
@@ -1,221 +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/hicn-light/config.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <parc/security/parc_Security.h>
-
-#include <parc/algol/parc_List.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Time.h>
-#include <parc/algol/parc_TreeRedBlack.h>
-
-#include <hicn/config/commandParser.h>
-
-#ifndef __ANDROID__
-#ifdef HAVE_ERRNO_H
-#include <errno.h>
-#else
-#ifndef _WIN32
-extern int errno;
-#endif
-#endif
-#endif
-
-struct command_parser {
- // key = command, value = CommandOps
- PARCTreeRedBlack *commandTree;
- bool debugFlag;
-};
-
-static int _stringCompare(const void *key1, const void *key2) {
- return strcasecmp((const char *)key1, (const char *)key2);
-}
-
-CommandParser *commandParser_Create(void) {
- CommandParser *state = parcMemory_AllocateAndClear(sizeof(CommandParser));
- parcAssertNotNull(state, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(CommandParser));
-
- state->commandTree = parcTreeRedBlack_Create(_stringCompare, // key compare
- NULL, // key free
- NULL, // key copy
- NULL, // value equals
- NULL, // value free
- NULL // value copy
- );
- state->debugFlag = false;
- return state;
-}
-
-void commandParser_Destroy(CommandParser **parserPtr) {
- CommandParser *parser = *parserPtr;
-
- // destroy every element if it has a destroyer
- PARCArrayList *values = parcTreeRedBlack_Values(parser->commandTree);
- if (values) {
- for (int i = 0; i < parcArrayList_Size(values); i++) {
- CommandOps *ops = parcArrayList_Get(values, i);
- parcTreeRedBlack_Remove(parser->commandTree, ops->command);
- if (ops->destroyer) {
- ops->destroyer(&ops);
- }
- }
- parcArrayList_Destroy(&values);
- }
-
- parcTreeRedBlack_Destroy(&parser->commandTree);
-
- parcMemory_Deallocate((void **)&parser);
- *parserPtr = NULL;
-}
-
-void commandParser_SetDebug(CommandParser *state, bool debugFlag) {
- state->debugFlag = debugFlag;
-}
-
-bool commandParser_GetDebug(CommandParser *state) { return state->debugFlag; }
-
-void commandParser_RegisterCommand(CommandParser *state, CommandOps *ops) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(ops->command, "Operation command string must be non-null");
-
- void *exists = parcTreeRedBlack_Get(state->commandTree, ops->command);
- parcAssertNull(exists, "Command '%s' already exists in the tree %p\n",
- ops->command, (void *)exists);
-
- parcTreeRedBlack_Insert(state->commandTree, (void *)ops->command,
- (void *)ops);
-
- // if the command being registered asked for an init function to be called,
- // call it
- if (ops->init != NULL) {
- ops->init(state, ops);
- }
-}
-
-static PARCList *parseStringIntoTokens(const char *originalString) {
- PARCList *list =
- parcList(parcArrayList_Create(parcArrayList_StdlibFreeFunction),
- PARCArrayListAsPARCList);
-
- char *token;
-
- char *tofree =
- parcMemory_StringDuplicate(originalString, strlen(originalString) + 1);
- char *string = tofree;
-
- token = strtok(string, " \t\n");
- while (token != NULL) {
- if (strlen(token) > 0) {
- parcList_Add(list, strdup(token));
- }
- token = strtok(NULL, " \t\n");
- }
-
- parcMemory_Deallocate((void **)&tofree);
-
- return list;
-}
-
-/**
- * Matches the user arguments to available commands, returning the command or
- * NULL if not found
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-static CommandOps *commandParser_MatchCommand(CommandParser *state,
- PARCList *args) {
- // Find the longest matching prefix command.
- // Pretty wildly inefficient
-
- size_t longest_token_count = 0;
- char *longest_command = NULL;
-
- PARCArrayList *commands = parcTreeRedBlack_Keys(state->commandTree);
- for (int i = 0; i < parcArrayList_Size(commands); i++) {
- char *command = parcArrayList_Get(commands, i);
- PARCList *command_tokens = parseStringIntoTokens(command);
-
- // is it a prefix match?
- if (parcList_Size(args) >= parcList_Size(command_tokens)) {
- bool possible_match = true;
- for (int i = 0; i < parcList_Size(command_tokens) && possible_match;
- i++) {
- const char *a = parcList_GetAtIndex(command_tokens, i);
- const char *b = parcList_GetAtIndex(args, i);
- if (strncasecmp(a, b, strlen(a) + 1) != 0) {
- possible_match = false;
- }
- }
-
- if (possible_match &&
- parcList_Size(command_tokens) > longest_token_count) {
- longest_token_count = parcList_Size(command_tokens);
- longest_command = command;
- }
- }
-
- parcList_Release(&command_tokens);
- }
-
- parcArrayList_Destroy(&commands);
-
- if (longest_token_count == 0) {
- return NULL;
- } else {
- CommandOps *ops = parcTreeRedBlack_Get(state->commandTree, longest_command);
- parcAssertNotNull(ops, "Got null operations for command '%s'\n",
- longest_command);
- return ops;
- }
-}
-
-CommandReturn commandParser_DispatchCommand(CommandParser *state,
- PARCList *args,
- char *output,
- size_t output_size) {
- parcAssertNotNull(output, "output buffer is null\n");
- CommandOps *ops = commandParser_MatchCommand(state, args);
-
- if (ops == NULL) {
- snprintf(output, output_size, "Command not found.\n");
- return CommandReturn_Failure;
- } else {
- return ops->execute(state, ops, args, output, output_size);
- }
-}
-
-bool commandParser_ContainsCommand(CommandParser *parser, const char *command) {
- CommandOps *ops = parcTreeRedBlack_Get(parser->commandTree, command);
- return (ops != NULL);
-}
diff --git a/hicn-light/src/hicn/config/commandParser.h b/hicn-light/src/hicn/config/commandParser.h
deleted file mode 100644
index 882d55d26..000000000
--- a/hicn-light/src/hicn/config/commandParser.h
+++ /dev/null
@@ -1,200 +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.
- */
-
-/**
- * @file command_Parser.h
- * @brief Creates a dictionary of commands and parses a command_line to match
- * against them
- *
- * A user creates individual CommandParserEntry that map a command_line to a
- * function to execute. The CommandParser then does a longest-matching prefix
- * match of a command_line to the dictionary of commands and executes the
- * appropriate command.
- *
- */
-
-#ifndef command_parser_h
-#define command_parser_h
-
-#include <hicn/config/commandOps.h>
-#include <hicn/config/commandReturn.h>
-
-struct command_parser;
-typedef struct command_parser CommandParser;
-
-/**
- * controlState_Create
- *
- * Creates the global state for the Control program
- *
- * @return non-null A command parser
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-CommandParser *commandParser_Create(void);
-
-/**
- * Destroys the control state, closing all network connections
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void commandParser_Destroy(CommandParser **statePtr);
-
-/**
- * Registers a CommandOps with the system.
- *
- * Each command has its complete command prefix in the "command" field.
- * RegisterCommand will put these command prefixes in to a tree and then match
- * what a user types against the longest-matching prefix in the tree. If
- * there's a match, it will call the "execute" function.
- *
- * When the parser is destroyed, each command's destroyer function will be
- * called.
- *
- * @param [in] state An allocated ControlState
- * @param [in] command The command to register with the system
- *
- * Example:
- * @code
- * static ControlReturn
- * control_Root_Execute(CommandParser *parser, CommandOps *ops, PARCList
- * *args)
- * {
- * printf("Root Command\n");
- * return CommandReturn_Success;
- * }
- *
- * static ControlReturn
- * control_FooBar_Execute(CommandParser *parser, CommandOps *ops, PARCList
- * *args)
- * {
- * printf("Foo Bar Command\n");
- * return CommandReturn_Success;
- * }
- *
- * const CommandOps control_Root = {
- * .closure = NULL,
- * .command = "", // empty string for root
- * .init = NULL,
- * .execute = control_Root_Execute
- * };
- *
- * const CommandOps control_FooBar = {
- * .closure = NULL,
- * .command = "foo bar", // empty string for root
- * .init = NULL,
- * .execute = control_FooBar_Execute
- * };
- *
- * void startup(void)
- * {
- * ControlState *state = controlState_Create("happy", "day");
- * controlState_RegisterCommand(state, control_FooBar);
- * controlState_RegisterCommand(state, control_Root);
- *
- * // this executes "root"
- * controlState_DispatchCommand(state, "foo");
- * controlState_Destroy(&state);
- * }
- * @endcode
- */
-void commandParser_RegisterCommand(CommandParser *state, CommandOps *command);
-
-/**
- * Performs a longest-matching prefix of the args to the command tree
- *
- * The command tree is created with controlState_RegisterCommand.
- *
- * @param [in] state The allocated ControlState
- * @param [in] args Each command_line word parsed to the ordered list
- * @param [in] output The allocated output string, if null, the normal printf is executed
- * @param [in] output_size the size of output array string. It is ignored if the output string is null
- *
- * @return CommandReturn_Success the command was successful
- * @return CommandReturn_Failure the command failed or was not found
- * @return CommandReturn_Exit the command indicates that the interactive mode
- * should exit
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-CommandReturn commandParser_DispatchCommand(CommandParser *state,
- PARCList *args,
- char *output,
- size_t output_size);
-
-/**
- * Sets the Debug mode, which will print out much more information.
- *
- * Prints out much more diagnostic information about what hicn-light controller
- * is doing. yes, you would make a CommandOps to set and unset this :)
- *
- * @param [in] debugFlag true means to print debug info, false means to turn it
- * off
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void commandParser_SetDebug(CommandParser *state, bool debugFlag);
-
-/**
- * Returns the debug state of ControlState
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-bool commandParser_GetDebug(CommandParser *state);
-
-/**
- * Checks if the command is registered
- *
- * Checks if the exact command given is registered. This is not a prefix match.
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return true The command is registered
- * @return false The command is not registered
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-bool commandParser_ContainsCommand(CommandParser *parser, const char *command);
-#endif // command_parser_h
diff --git a/hicn-light/src/hicn/config/commandReturn.h b/hicn-light/src/hicn/config/commandReturn.h
deleted file mode 100644
index 16ee93db1..000000000
--- a/hicn-light/src/hicn/config/commandReturn.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file command_Return.h
- * @brief The return code used by CLI commands
- *
- * This return code is used throughout the command parser and command
- * implementations to indicate success, failure, or if the program should exit.
- *
- */
-
-#ifndef command_return_h
-#define command_return_h
-
-/**
- * @typedef ControlReturn
- * @abstract A command returns one of (SUCCESS, FAILURE, EXIT)
- * @constant SUCCESS means the command succeeded
- * @constant FAILURE indicates failure
- * @constant EXIT means the command indicated that hicn-light controller should
- * exit.
- * @discussion <#Discussion#>
- */
-typedef enum command_return {
- CommandReturn_Success, // command returned success
- CommandReturn_Failure, // command failure
- CommandReturn_Exit // command indicates program should exit
-} CommandReturn;
-
-#endif // command_return_h
diff --git a/hicn-light/src/hicn/config/commands.c b/hicn-light/src/hicn/config/commands.c
new file mode 100644
index 000000000..47ea23a8a
--- /dev/null
+++ b/hicn-light/src/hicn/config/commands.c
@@ -0,0 +1,1737 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ *
+ * Example:
+ * @code
+ * <#example#>
+ * @endcode
+ */
+
+#ifndef _WIN32
+#include <arpa/inet.h>
+#include <unistd.h>
+#endif
+#include <ctype.h>
+#include <hicn/hicn-light/config.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <hicn/core/connection.h>
+#include <hicn/core/connection_table.h>
+#include <hicn/core/forwarder.h>
+//#include <hicn/core/system.h>
+#ifdef WITH_MAPME
+#include <hicn/core/mapme.h>
+#endif /* WITH_MAPME */
+
+#include <hicn/core/listener.h> //the listener list
+#include <hicn/core/listener_table.h>
+#include <hicn/core/subscription.h>
+#include <hicn/ctrl/hicn-light.h>
+//#include <hicn/utils/utils.h>
+#include <hicn/utils/punting.h>
+#include <hicn/util/log.h>
+#include <hicn/validation.h>
+#include <hicn/face.h>
+
+#include "commands.h"
+#include "configuration.h"
+
+#define ETHERTYPE 0x0801
+#define DEFAULT_COST 1
+#define DEFAULT_PORT 1234
+
+#define make_ack(msg) \
+ do { \
+ ((msg_header_t *)msg)->header.message_type = ACK_LIGHT; \
+ ((msg_header_t *)msg)->header.length = 0; \
+ } while (0)
+
+#define make_nack(msg) \
+ do { \
+ ((msg_header_t *)msg)->header.message_type = NACK_LIGHT; \
+ ((msg_header_t *)msg)->header.length = 0; \
+ } while (0)
+
+#define msg_malloc_list(msg, COMMAND_ID, N, seq_number) \
+ do { \
+ msg = calloc(1, sizeof((msg)->header) + N * sizeof((msg)->payload)); \
+ (msg)->header.message_type = RESPONSE_LIGHT; \
+ (msg)->header.command_id = (COMMAND_ID); \
+ (msg)->header.length = (uint16_t)(N); \
+ (msg)->header.seq_num = (seq_number); \
+ } while (0);
+
+// conn_id = UINT_MAX when symbolic_name is not found
+static inline unsigned _symbolic_to_conn_id(forwarder_t *forwarder,
+ const char *symbolic_or_connid,
+ bool allow_self,
+ unsigned ingress_id) {
+ unsigned conn_id;
+ const connection_table_t *table = forwarder_get_connection_table(forwarder);
+
+ if (allow_self && strcmp(symbolic_or_connid, "SELF") == 0) {
+ conn_id = ingress_id;
+ } else if (is_number(symbolic_or_connid, SYMBOLIC_NAME_LEN)) {
+ // case for conn_id as input
+ // XXX type issue ! XXX No check, see man
+ unsigned id = atoi(symbolic_or_connid);
+ if (id < 0) return CONNECTION_ID_UNDEFINED;
+ conn_id = id;
+
+ if (!connection_table_validate_id(table, conn_id)) {
+ ERROR("ConnID not found, check list connections");
+ conn_id = CONNECTION_ID_UNDEFINED;
+ }
+ } else {
+ // case for symbolic as input: check if symbolic name can be resolved
+ conn_id = (unsigned int)connection_table_get_id_by_name(table,
+ symbolic_or_connid);
+ if (connection_id_is_valid(conn_id)) {
+ DEBUG("Resolved symbolic name '%s' to conn_id %u", symbolic_or_connid,
+ conn_id);
+ } else {
+ WARN("Symbolic name '%s' could not be resolved", symbolic_or_connid);
+ }
+ }
+
+ return conn_id;
+}
+
+#define symbolic_to_conn_id(forwarder, symbolic) \
+ _symbolic_to_conn_id(forwarder, symbolic, false, 0)
+
+#define symbolic_to_conn_id_self(forwarder, symbolic, ingress_id) \
+ _symbolic_to_conn_id(forwarder, symbolic, true, ingress_id)
+
+connection_t *getConnectionBySymbolicOrId(forwarder_t *forwarder,
+ const char *symbolic_or_connid) {
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ unsigned conn_id = symbolic_to_conn_id(forwarder, symbolic_or_connid);
+ if (!connection_id_is_valid(conn_id)) return NULL;
+
+ /* conn_id is assumed validated here */
+ return connection_table_at(table, conn_id);
+}
+
+/* Listener */
+
+uint8_t *configuration_on_listener_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: listener add (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_listener_add_t *msg = (msg_listener_add_t *)packet;
+ cmd_listener_add_t *control = &msg->payload;
+
+ switch (control->type) {
+ case FACE_TYPE_UDP_LISTENER:
+ case FACE_TYPE_TCP_LISTENER:
+ case FACE_TYPE_HICN_LISTENER:
+ break;
+ case FACE_TYPE_UDP:
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_HICN:
+ ERROR("Wrong listener type");
+ goto NACK;
+ }
+
+ listener_table_t *table = forwarder_get_listener_table(forwarder);
+ assert(table);
+
+ /* Verify that the listener DOES NOT exist */
+ listener_t *listener = listener_table_get_by_name(table, control->symbolic);
+ if (listener) {
+ ERROR("Listener with name=%s already exists", control->symbolic);
+ goto NACK;
+ }
+
+ address_t address;
+ memset(&address, 0, sizeof(address_t));
+ if (address_from_ip_port(&address, control->family, &control->address,
+ control->port) < 0) {
+ WARN(
+ "Unsupported address type for HICN (ingress id %u): "
+ "must be either IPV4 or IPV6",
+ ingress_id);
+ goto NACK;
+ }
+
+ if (!face_type_is_defined(control->type)) {
+ WARN("[configuration_on_listener_add] Invalid listener type");
+ goto NACK;
+ }
+
+ listener = listener_table_get_by_address(table, control->type, &address);
+ if (listener) {
+ char addr_str[NI_MAXHOST];
+ int port;
+ address_to_string(&address, addr_str, &port);
+ ERROR("Listener for address=%s, type=%s already exists", addr_str,
+ face_type_str(control->type));
+ goto NACK;
+ }
+
+ // NOTE: interface_name is expected NULL for hICN listener
+
+ listener = listener_create(control->type, &address, control->interface_name,
+ control->symbolic, forwarder);
+ if (!listener) goto NACK;
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+unsigned symbolic_to_listener_id(forwarder_t *forwarder,
+ const char *symbolic_or_listener_id) {
+ unsigned listener_id;
+ const listener_table_t *table = forwarder_get_listener_table(forwarder);
+
+ if (is_number(symbolic_or_listener_id, SYMBOLIC_NAME_LEN)) {
+ // XXX type issue ! XXX No check, see man
+ unsigned id = atoi(symbolic_or_listener_id);
+ if (id < 0) return LISTENER_ID_UNDEFINED;
+ listener_id = id;
+
+ if (!listener_table_validate_id(table, listener_id)) {
+ ERROR("Listener ID %d not found", id);
+ listener_id = LISTENER_ID_UNDEFINED;
+ }
+ } else {
+ // case for symbolic as input: check if symbolic name can be resolved
+ listener_id = (unsigned int)listener_table_get_id_by_name(
+ table, symbolic_or_listener_id);
+ if (listener_id_is_valid(listener_id)) {
+ DEBUG("Resolved symbolic name '%s' to conn_id %u",
+ symbolic_or_listener_id, listener_id);
+ } else {
+ WARN("Symbolic name '%s' could not be resolved", symbolic_or_listener_id);
+ }
+ }
+
+ return listener_id;
+}
+
+uint8_t *configuration_on_listener_remove(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: listener remove (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_listener_remove_t *msg = (msg_listener_remove_t *)packet;
+ cmd_listener_remove_t *control = &msg->payload;
+
+ unsigned listener_id =
+ symbolic_to_listener_id(forwarder, control->symbolicOrListenerid);
+ if (!listener_id_is_valid(listener_id)) {
+ ERROR("Invalid listener id=%u", listener_id);
+ goto NACK;
+ }
+
+ listener_table_t *listener_table = forwarder_get_listener_table(forwarder);
+ listener_t *listener = listener_table_get_by_id(listener_table, listener_id);
+ if (!listener) {
+ ERROR("Listener ID not found, check list listeners");
+ goto NACK;
+ }
+
+ // Do not remove listener if it is the one curretly used to send the command
+ connection_table_t *conn_table = forwarder_get_connection_table(forwarder);
+ connection_t *curr_connection =
+ connection_table_get_by_id(conn_table, ingress_id);
+ const address_pair_t *pair = connection_get_pair(curr_connection);
+ if (address_equals(listener_get_address(listener),
+ address_pair_get_local(pair))) {
+ ERROR("Cannot remove current listener");
+ goto NACK;
+ }
+
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ connection_t *connection;
+ connection_table_foreach(table, connection, {
+ const address_pair_t *pair = connection_get_pair(connection);
+ if (!address_equals(listener_get_address(listener),
+ address_pair_get_local(pair)))
+ continue;
+
+ unsigned conn_id =
+ (unsigned)connection_table_get_connection_id(table, connection);
+
+ /* Remove connection from the FIB */
+ // XXX TODO get entries, raise notifications...
+ // XXX isn't it possible to implement this in the forwarder ?????
+ forwarder_remove_connection_id_from_routes(forwarder, conn_id);
+
+ /* Remove connection */
+ connection_table_remove_by_id(table, conn_id);
+ });
+
+ /* Remove listener */
+ listener_table_remove_by_id(listener_table, listener_id);
+ listener_finalize(listener);
+ WITH_DEBUG(listener_table_print_by_key(listener_table);)
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+// TODO(eloparco): Unused forwarder param
+static inline void fill_listener_command(const listener_t *listener,
+ cmd_listener_list_item_t *cmd) {
+ assert(listener);
+ assert(cmd);
+
+ struct sockaddr_in *sin;
+ struct sockaddr_in6 *sin6;
+
+ const address_t *addr = listener_get_address(listener);
+
+ cmd->id = (uint32_t)listener_get_id(listener);
+ cmd->type = (uint8_t)listener_get_type(listener);
+
+ switch (addr->as_ss.ss_family) {
+ case AF_INET:
+ sin = (struct sockaddr_in *)addr;
+ cmd->family = (uint8_t)AF_INET;
+ cmd->local_addr.v4.as_inaddr = sin->sin_addr;
+ cmd->local_port = sin->sin_port;
+ break;
+ case AF_INET6:
+ sin6 = (struct sockaddr_in6 *)addr;
+ cmd->family = (uint8_t)AF_INET6;
+ cmd->local_addr.v6.as_in6addr = sin6->sin6_addr;
+ cmd->local_port = sin6->sin6_port;
+ break;
+ default:
+ break;
+ }
+
+ const char *name = listener_get_name(listener);
+ snprintf(cmd->name, SYMBOLIC_NAME_LEN, "%s", name);
+ const char *interface_name = listener_get_interface_name(listener);
+ snprintf(cmd->interface_name, SYMBOLIC_NAME_LEN, "%s", interface_name);
+}
+
+uint8_t *configuration_on_listener_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: listener list (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ listener_table_t *table = forwarder_get_listener_table(forwarder);
+ size_t n = listener_table_len(table);
+ msg_listener_list_t *msg_received = (msg_listener_list_t *)packet;
+ uint8_t command_id = msg_received->header.command_id;
+ INFO("listener list seq num %d", msg_received->header.seq_num);
+ uint32_t seq_num = msg_received->header.seq_num;
+
+ msg_listener_list_reply_t *msg = NULL;
+ msg_malloc_list(msg, command_id, n, seq_num);
+ if (!msg) goto NACK;
+
+ cmd_listener_list_item_t *payload = &msg->payload;
+ listener_table_foreach(table, listener, {
+ fill_listener_command(listener, payload);
+ payload++;
+ });
+
+ *reply_size = sizeof(msg->header) + n * sizeof(msg->payload);
+ return (uint8_t *)msg;
+
+NACK:
+ *reply_size = sizeof(msg_header_t);
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/* Connection */
+
+uint8_t *configuration_on_connection_add(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: connection add (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_connection_add_t *msg = (msg_connection_add_t *)packet;
+ cmd_connection_add_t *control = &msg->payload;
+
+ switch (control->type) {
+ case FACE_TYPE_UDP:
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_HICN:
+ break;
+ case FACE_TYPE_UDP_LISTENER:
+ case FACE_TYPE_TCP_LISTENER:
+ case FACE_TYPE_HICN_LISTENER:
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_N:
+ goto NACK;
+ }
+
+ if (!face_type_is_defined(control->type)) goto NACK;
+
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ char *symbolic_name = control->symbolic;
+
+ // Generate connection name if not specified
+ if (symbolic_name[0] == '\0') {
+ int rc = connection_table_get_random_name(table, symbolic_name);
+ if (rc < 0) {
+ ERROR("Unable to generate new connection name");
+ goto NACK;
+ }
+ } else {
+ if (connection_table_get_by_name(table, symbolic_name)) {
+ ERROR("Connection symbolic name already exists");
+ goto NACK;
+ }
+ }
+
+ address_pair_t pair;
+ if (address_pair_from_ip_port(&pair, control->family, &control->local_ip,
+ control->local_port, &control->remote_ip,
+ control->remote_port) < 0)
+ goto NACK;
+
+ if (forwarder_add_connection(forwarder, symbolic_name, control->type, &pair,
+ control->tags, control->priority,
+ control->admin_state) < 0)
+ goto NACK;
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/**
+ * Add an IP-based tunnel.
+ *
+ * The call can fail if the symbolic name is a duplicate. It could also fail if
+ * there's an problem creating the local side of the tunnel (i.e. the local
+ * socket address is not usable).
+ *
+ * @return true Tunnel added
+ * @return false Tunnel not added (an error)
+ */
+
+uint8_t *configuration_on_connection_remove(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: connection remove (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_connection_remove_t *msg = (msg_connection_remove_t *)packet;
+ cmd_connection_remove_t *control = &msg->payload;
+
+ unsigned conn_id = symbolic_to_conn_id_self(
+ forwarder, control->symbolic_or_connid, ingress_id);
+ if (!connection_id_is_valid(conn_id)) {
+ ERROR("Invalid connection id=%u", conn_id);
+ goto NACK;
+ }
+
+ if (strcmp(control->symbolic_or_connid, "SELF") != 0 &&
+ conn_id == ingress_id) {
+ ERROR("Cannot remove current connection");
+ goto NACK;
+ }
+
+ /*
+ *
+ * Don't close the fd for SELF otherwise it won't be possible
+ * to send the reply back. The connection is finalized later in
+ * _forwarder_finalize_connection_if_self
+ */
+ bool finalize = (strcmp(control->symbolic_or_connid, "SELF") != 0);
+
+ if (forwarder_remove_connection(forwarder, conn_id, finalize) < 0) goto NACK;
+
+ WITH_DEBUG({
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ connection_table_print_by_pair(table);
+ })
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+static inline void tolower_str(char *str) {
+ char *p = str;
+ for (; *p; p++) *p = tolower(*p);
+}
+
+// TODO(eloparco): Forwarder param not used
+static inline void fill_connections_command(const connection_t *connection,
+ cmd_connection_list_item_t *cmd) {
+ assert(connection);
+ assert(cmd);
+
+ struct sockaddr_in *sin;
+ struct sockaddr_in6 *sin6;
+ const address_pair_t *pair = connection_get_pair(connection);
+
+ cmd->id = connection_get_id(connection),
+ cmd->state = (uint8_t)connection_get_state(connection),
+ cmd->admin_state = (uint8_t)connection_get_admin_state(connection),
+ cmd->type = (uint8_t)connection_get_type(connection),
+#ifdef WITH_POLICY
+ cmd->priority = connection_get_priority(connection),
+ cmd->tags = (uint8_t)connection_get_tags(connection),
+#endif /* WITH_POLICY */
+
+ snprintf(cmd->name, SYMBOLIC_NAME_LEN, "%s", connection_get_name(connection));
+ tolower_str(cmd->name);
+
+ snprintf(cmd->interface_name, SYMBOLIC_NAME_LEN, "%s",
+ connection_get_interface_name(connection));
+
+ switch (pair->local.as_ss.ss_family) {
+ case AF_INET:
+ cmd->family = (uint8_t)AF_INET;
+
+ sin = (struct sockaddr_in *)(&pair->local);
+ cmd->local_port = sin->sin_port;
+ cmd->local_addr.v4.as_inaddr = sin->sin_addr;
+
+ sin = (struct sockaddr_in *)(&pair->remote);
+ cmd->remote_port = sin->sin_port;
+ cmd->remote_addr.v4.as_inaddr = sin->sin_addr;
+ break;
+
+ case AF_INET6:
+ cmd->family = (uint8_t)AF_INET6;
+
+ sin6 = (struct sockaddr_in6 *)(&pair->local);
+ cmd->local_port = sin6->sin6_port;
+ cmd->local_addr.v6.as_in6addr = sin6->sin6_addr;
+
+ sin6 = (struct sockaddr_in6 *)(&pair->remote);
+ cmd->remote_port = sin6->sin6_port;
+ cmd->remote_addr.v6.as_in6addr = sin6->sin6_addr;
+ break;
+
+ default:
+ break;
+ }
+}
+
+uint8_t *configuration_on_connection_list(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: connection list (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ // -1 since current connection (i.e. the one used to send
+ // the command) is not considered
+ size_t n = connection_table_len(table) - 1;
+
+ msg_connection_list_t *msg_received = (msg_connection_list_t *)packet;
+ uint8_t command_id = msg_received->header.command_id;
+ uint32_t seq_num = msg_received->header.seq_num;
+
+ msg_connection_list_reply_t *msg = NULL;
+ msg_malloc_list(msg, command_id, n, seq_num);
+ if (!msg) goto NACK;
+
+ cmd_connection_list_item_t *payload = &msg->payload;
+ connection_table_foreach_new(table, connection, {
+ if (connection->id == ingress_id) continue;
+ fill_connections_command(connection, payload);
+ payload++;
+ });
+
+ *reply_size = sizeof(msg->header) + n * sizeof(msg->payload);
+ return (uint8_t *)msg;
+
+NACK:
+ *reply_size = sizeof(msg_header_t);
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+#if 0
+uint8_t *configuration_on_connection_set_admin_state(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+ msg_connection_set_admin_state_t *msg =
+ (msg_connection_set_admin_state_t *)packet;
+ cmd_connection_set_admin_state_t *control = &msg->payload;
+
+ if ((control->admin_state != FACE_STATE_UP) &&
+ (control->admin_state != FACE_STATE_DOWN))
+ goto NACK;
+
+ connection_t *conn =
+ getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid);
+ if (!conn) goto NACK;
+
+ connection_set_admin_state(conn, control->admin_state);
+
+ /* Hook: connection event */
+ forwarder_on_connection_event(forwarder, conn,
+ control->admin_state == FACE_STATE_UP
+ ? CONNECTION_EVENT_SET_UP
+ : CONNECTION_EVENT_SET_DOWN);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+#endif
+uint8_t *configuration_on_connection_update(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+#ifdef WITH_POLICY
+ msg_connection_update_t *msg = (msg_connection_update_t *)packet;
+ cmd_connection_update_t *control = &msg->payload;
+
+ connection_t *conn =
+ getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid);
+ if (!conn) goto NACK;
+
+ connection_set_tags(conn, control->tags);
+ connection_set_admin_state(conn, control->admin_state);
+ if (control->priority > 0) connection_set_priority(conn, control->priority);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+#endif /* WITH_POLICY */
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+#if 0
+
+uint8_t *configuration_on_connection_set_priority(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+#ifdef WITH_POLICY
+ msg_connection_set_priority_t *msg = (msg_connection_set_priority_t *)packet;
+ cmd_connection_set_priority_t *control = &msg->payload;
+
+ connection_t *conn =
+ getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid);
+ if (!conn) goto NACK;
+
+ connection_set_priority(conn, control->priority);
+
+ /* Hook: connection event */
+ forwarder_on_connection_event(forwarder, conn,
+ CONNECTION_EVENT_PRIORITY_CHANGED);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+#endif /* WITH_POLICY */
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_connection_set_tags(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+#ifdef WITH_POLICY
+ msg_connection_set_tags_t *msg = (msg_connection_set_tags_t *)packet;
+ cmd_connection_set_tags_t *control = &msg->payload;
+
+ connection_t *conn =
+ getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid);
+ if (!conn) goto NACK;
+
+ connection_set_tags(conn, control->tags);
+
+ /* Hook: connection event */
+ forwarder_on_connection_event(forwarder, conn, CONNECTION_EVENT_TAGS_CHANGED);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+#endif /* WITH_POLICY */
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+#endif
+
+/* Route */
+
+uint8_t *configuration_on_route_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ INFO("CMD: route add (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_route_add_t *msg = (msg_route_add_t *)packet;
+ cmd_route_add_t *control = &msg->payload;
+
+ unsigned conn_id = symbolic_to_conn_id_self(
+ forwarder, control->symbolic_or_connid, ingress_id);
+
+ /* We accept routes without conn_id */
+#if 0
+ if (!connection_id_is_valid(conn_id)) goto NACK;
+#endif
+
+ hicn_ip_prefix_t prefix = {.family = control->family,
+ .address = control->address,
+ .len = control->len};
+
+ if (!forwarder_add_or_update_route(forwarder, &prefix, conn_id)) goto NACK;
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_route_remove(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: route remove (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_route_remove_t *msg = (msg_route_remove_t *)packet;
+ cmd_route_remove_t *control = &msg->payload;
+
+ unsigned conn_id =
+ symbolic_to_conn_id(forwarder, control->symbolic_or_connid);
+ if (!connection_id_is_valid(conn_id)) goto NACK;
+
+ hicn_ip_prefix_t prefix = {.family = control->family,
+ .address = control->address,
+ .len = control->len};
+
+ if (!forwarder_remove_route(forwarder, &prefix, conn_id)) goto NACK;
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+static inline off_t fill_route_command(const fib_entry_t *entry,
+ cmd_route_list_item_t *cmd) {
+ const nexthops_t *nexthops = fib_entry_get_nexthops(entry);
+ assert(nexthops_get_len(nexthops) == nexthops_get_curlen(nexthops));
+ size_t num_nexthops = nexthops_get_len(nexthops);
+ off_t pos = 0;
+
+ if (num_nexthops == 0) return 0;
+
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(entry);
+ const hicn_ip_address_t *address = hicn_prefix_get_ip_address(prefix);
+ int family = hicn_ip_address_get_family(address);
+
+ nexthops_foreach(nexthops, nexthop, {
+ cmd->family = family;
+ cmd->remote_addr = *address;
+ cmd->face_id = nexthop;
+ cmd->len = hicn_prefix_get_len(prefix);
+ cmd->cost = DEFAULT_COST;
+
+ pos++;
+ cmd++;
+ });
+ return pos;
+}
+
+uint8_t *configuration_on_route_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ INFO("CMD: route list (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ msg_route_list_t *msg_received = (msg_route_list_t *)packet;
+ uint8_t command_id = msg_received->header.command_id;
+ uint32_t seq_num = msg_received->header.seq_num;
+ const fib_t *fib = forwarder_get_fib(forwarder);
+
+ /*
+ * Two step approach to precompute the number of entries to allocate
+ *
+ * NOTE: we might have routes with no or multiple next hops.
+ */
+ size_t n = 0;
+ fib_foreach_entry(fib, entry, {
+ const nexthops_t *nexthops = fib_entry_get_nexthops(entry);
+ assert(nexthops_get_len(nexthops) == nexthops_get_curlen(nexthops));
+ n += nexthops_get_len(nexthops);
+ });
+
+ msg_route_list_reply_t *msg = NULL;
+ msg_malloc_list(msg, command_id, n, seq_num);
+ if (!msg) goto NACK;
+
+ cmd_route_list_item_t *payload = &msg->payload;
+ off_t pos = 0;
+ fib_foreach_entry(fib, entry,
+ { pos += fill_route_command(entry, payload + pos); });
+
+ *reply_size = sizeof(msg->header) + n * sizeof(msg->payload);
+ return (uint8_t *)msg;
+
+NACK:
+ *reply_size = sizeof(msg_header_t);
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/* Cache */
+
+uint8_t *configuration_on_cache_set_store(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: cache set store (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_cache_set_store_t *msg = (msg_cache_set_store_t *)packet;
+ cmd_cache_set_store_t *control = &msg->payload;
+
+ if ((control->activate != 0) && (control->activate != 1)) goto NACK;
+ bool value = (bool)control->activate;
+
+ forwarder_cs_set_store(forwarder, value);
+ assert(forwarder_cs_get_store(forwarder) == value);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_cache_set_serve(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: cache set serve (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_cache_set_serve_t *msg = (msg_cache_set_serve_t *)packet;
+ cmd_cache_set_serve_t *control = &msg->payload;
+
+ if ((control->activate != 0) && (control->activate != 1)) goto NACK;
+ bool value = (bool)control->activate;
+
+ forwarder_cs_set_serve(forwarder, value);
+ assert(forwarder_cs_get_serve(forwarder) == value);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_cache_clear(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ INFO("CMD: cache clear (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_cache_clear_t *msg = (msg_cache_clear_t *)packet;
+
+ forwarder_cs_clear(forwarder);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_cache_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ INFO("CMD: cache list (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ msg_cache_list_t *msg_received = (msg_cache_list_t *)packet;
+ uint32_t seq_num = msg_received->header.seq_num;
+
+ msg_cache_list_reply_t *msg = malloc(sizeof(*msg));
+ *msg = (msg_cache_list_reply_t){
+ .header = {.message_type = RESPONSE_LIGHT,
+ .length = 1,
+ .seq_num = seq_num},
+ .payload = {
+ .store_in_cs = forwarder_cs_get_store(forwarder),
+ .serve_from_cs = forwarder_cs_get_serve(forwarder),
+ .cs_size = (unsigned int)forwarder_cs_get_size(forwarder),
+ .num_stale_entries =
+ (unsigned int)forwarder_cs_get_num_stale_entries(forwarder)}};
+
+ *reply_size = sizeof(*msg);
+ return (uint8_t *)msg;
+}
+
+/* Strategy */
+
+uint8_t *configuration_on_strategy_set(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: strategy set (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_strategy_set_t *msg = (msg_strategy_set_t *)packet;
+ cmd_strategy_set_t *control = &msg->payload;
+
+ char prefix_s[MAXSZ_IP_PREFIX];
+ hicn_ip_prefix_t prefix = {
+ .family = control->family,
+ .address = control->address,
+ .len = control->len,
+ };
+ int rc = hicn_ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, &prefix);
+ assert(rc < MAXSZ_IP_PREFIX);
+ if (rc < 0) goto NACK;
+
+ strategy_type_t strategy = control->type;
+ configuration_t *config = forwarder_get_configuration(forwarder);
+ strategy_type_t existingFwdStrategy =
+ configuration_get_strategy(config, prefix_s);
+ strategy_options_t *options = NULL;
+
+ // XXX check control->family
+ hicn_prefix_t name_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&control->address, control->len,
+ &name_prefix);
+
+ // The strategy is not present in the hash table
+ // or has to be updated or to be restarted
+ if (existingFwdStrategy == STRATEGY_TYPE_UNDEFINED ||
+ strategy != existingFwdStrategy ||
+ (strategy == existingFwdStrategy && strategy == STRATEGY_TYPE_BESTPATH)) {
+ configuration_set_strategy(config, prefix_s, strategy);
+
+ forwarder_set_strategy(forwarder, &name_prefix, strategy, options);
+ } else {
+ WITH_WARN({
+ char buf[MAXSZ_HICN_PREFIX];
+ hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, &name_prefix);
+ WARN("Strategy for prefix %s not updated", buf);
+ })
+ }
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_strategy_add_local_prefix(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: strategy add local prefix (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_strategy_add_local_prefix_t *msg =
+ (msg_strategy_add_local_prefix_t *)packet;
+ cmd_strategy_add_local_prefix_t *control = &msg->payload;
+
+ char prefix_s[MAXSZ_IP_PREFIX];
+ hicn_ip_prefix_t prefix = {
+ .family = control->family,
+ .address = control->address,
+ .len = control->len,
+ };
+ int rc = hicn_ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, &prefix);
+ assert(rc < MAXSZ_IP_PREFIX);
+ if (rc < 0) goto NACK;
+
+ strategy_type_t strategy = control->type;
+ configuration_t *config = forwarder_get_configuration(forwarder);
+ strategy_type_t existingFwdStrategy =
+ configuration_get_strategy(config, prefix_s);
+
+ if (strategy != existingFwdStrategy) goto NACK;
+
+ if (strategy != STRATEGY_TYPE_BESTPATH &&
+ strategy != STRATEGY_TYPE_REPLICATION)
+ goto NACK;
+
+ hicn_prefix_t name_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&control->address, control->len,
+ &name_prefix);
+
+ strategy_options_t options;
+ hicn_prefix_t local_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&control->address, control->len,
+ &local_prefix);
+
+ // for the moment bestpath and replication are the same but we distinguish
+ // the two in case they will diverge in the future
+ if (strategy == STRATEGY_TYPE_BESTPATH) {
+ options.bestpath.local_prefixes = create_local_prefixes();
+ local_prefixes_add_prefix(options.bestpath.local_prefixes, &local_prefix);
+ } else {
+ options.replication.local_prefixes = create_local_prefixes();
+ local_prefixes_add_prefix(options.replication.local_prefixes,
+ &local_prefix);
+ }
+
+ forwarder_add_strategy_options(forwarder, &name_prefix, strategy, &options);
+
+ free_local_prefixes(options.bestpath.local_prefixes);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/* Statistics */
+
+uint8_t *configuration_on_stats_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ assert(forwarder && packet);
+ INFO("CMD: stats list (ingress=%d)", ingress_id);
+
+ size_t n = 1;
+ msg_stats_list_t *msg_received = (msg_stats_list_t *)packet;
+ uint8_t command_id = msg_received->header.command_id;
+ uint32_t seq_num = msg_received->header.seq_num;
+
+ msg_stats_list_reply_t *msg = NULL;
+ msg_malloc_list(msg, command_id, n, seq_num);
+ if (!msg) goto NACK;
+
+ cmd_stats_list_item_t *payload = &msg->payload;
+ payload->stats.forwarder = forwarder_get_stats(forwarder);
+ payload->stats.pkt_cache =
+ pkt_cache_get_stats(forwarder_get_pkt_cache(forwarder));
+
+ *reply_size = sizeof(msg->header) + n * sizeof(msg->payload);
+ return (uint8_t *)msg;
+
+NACK:
+ *reply_size = sizeof(msg_header_t);
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_face_stats_list(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ assert(forwarder && packet);
+ INFO("CMD: face stats list (ingress=%d)", ingress_id);
+
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ // -1 since current connection (i.e. the one used to send
+ // the command) is not considered
+ size_t n = connection_table_len(table) - 1;
+ msg_face_stats_list_t *msg_received = (msg_face_stats_list_t *)packet;
+ uint8_t command_id = msg_received->header.command_id;
+ uint32_t seq_num = msg_received->header.seq_num;
+
+ msg_face_stats_list_reply_t *msg = NULL;
+ msg_malloc_list(msg, command_id, n, seq_num);
+ if (!msg) goto NACK;
+
+ cmd_face_stats_list_item_t *payload = &msg->payload;
+ connection_t *connection;
+ connection_table_foreach(table, connection, {
+ if (connection->id == ingress_id) continue;
+ payload->stats = connection->stats;
+ payload++;
+ });
+
+ *reply_size = sizeof(msg->header) + n * sizeof(msg->payload);
+ return (uint8_t *)msg;
+
+NACK:
+ *reply_size = sizeof(msg_header_t);
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/* WLDR */
+
+uint8_t *configuration_on_wldr_set(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+ msg_wldr_set_t *msg = (msg_wldr_set_t *)packet;
+ cmd_wldr_set_t *control = &msg->payload;
+
+ if ((control->activate != 0) && (control->activate != 1)) goto NACK;
+ bool value = (bool)control->activate;
+
+ unsigned conn_id =
+ symbolic_to_conn_id(forwarder, control->symbolic_or_connid);
+ if (!connection_id_is_valid(conn_id)) goto NACK;
+
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ connection_t *conn = connection_table_at(table, conn_id);
+
+ if (value) connection_wldr_enable(conn, value);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/* Punting */
+
+uint8_t *configuration_on_punting_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ // #if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING)
+ msg_punting_add_t *msg = (msg_punting_add_t *)packet;
+
+#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING)
+ cmd_punting_add_t *control = &msg->payload;
+ if (hicn_ip_address_empty(&control->address)) goto NACK;
+
+ /* This is for hICN listeners only */
+ // XXX add check !
+ // comments:
+ // EncapType: I use the Hicn encap since the punting is available only for
+ // Hicn listeners LocalAddress: The only listern for which we need punting
+ // rules is the main one, which has no address
+ // so I create a fake empty address. This need to be consistent
+ // with the address set at creation time
+ address_t fakeaddr;
+ memset(&fakeaddr, 0, sizeof(address_t));
+ fakeaddr = ADDRESS_ANY(control->family, DEFAULT_PORT);
+
+ listener_table_t *table = forwarder_get_listener_table(forwarder);
+ listener_t *listener =
+ listener_table_get_by_address(table, FACE_TYPE_HICN, &fakeaddr);
+ if (!listener) {
+ ERROR("the main listener does not exist");
+ goto NACK;
+ }
+
+ hicn_ip_prefix_t prefix = {.family = control->family,
+ .address = control->address,
+ .len = control->len};
+ char prefix_s[MAXSZ_IP_PREFIX];
+ int rc = hicn_ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, &prefix);
+ assert(rc < MAXSZ_IP_PREFIX);
+ if (rc < 0) goto NACK;
+
+ if (listener_punt(listener, prefix_s) < 0) {
+ ERROR("error while adding the punting rule");
+ goto NACK;
+ }
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+#endif
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/* MAP-Me */
+
+#ifdef WITH_MAPME
+uint8_t *configuration_on_mapme_enable(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: mapme enable (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_mapme_enable_t *msg = (msg_mapme_enable_t *)packet;
+ cmd_mapme_enable_t *control = &msg->payload;
+
+ if ((control->activate != 0) && (control->activate != 1)) goto NACK;
+ bool value = (bool)control->activate;
+
+ INFO("MAP-Me SET enable: %s", value ? "on" : "off");
+ mapme_t *mapme = forwarder_get_mapme(forwarder);
+ if (!mapme) goto NACK;
+ mapme_set_enable(mapme, value);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_mapme_set_discovery(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: mapme discovery (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_mapme_set_discovery_t *msg = (msg_mapme_set_discovery_t *)packet;
+ cmd_mapme_set_discovery_t *control = &msg->payload;
+
+ if ((control->activate != 0) && (control->activate != 1)) goto NACK;
+ bool value = (bool)control->activate;
+
+ INFO("MAP-Me SET discovery: %s", value ? "on" : "off");
+ mapme_t *mapme = forwarder_get_mapme(forwarder);
+ if (!mapme) goto NACK;
+ mapme_set_discovery(mapme, value);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_mapme_set_timescale(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: mapme timescale (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_mapme_set_timescale_t *msg = (msg_mapme_set_timescale_t *)packet;
+ cmd_mapme_set_timescale_t *control = &msg->payload;
+
+ INFO("MAP-Me SET timescale: %u", control->timePeriod);
+ mapme_t *mapme = forwarder_get_mapme(forwarder);
+ if (!mapme) goto NACK;
+ mapme_set_timescale(mapme, control->timePeriod);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_mapme_set_retx(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: mapme retransmission (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_mapme_set_retx_t *msg = (msg_mapme_set_retx_t *)packet;
+ cmd_mapme_set_retx_t *control = &msg->payload;
+
+ INFO("MAP-Me SET retx: %u", control->timePeriod);
+ mapme_t *mapme = forwarder_get_mapme(forwarder);
+ if (!mapme) goto NACK;
+ mapme_set_retransmision(mapme, control->timePeriod);
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_mapme_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+ /* Check ingress is local (for now this is only used locally) */
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ const connection_t *connection = connection_table_at(table, ingress_id);
+
+ msg_mapme_add_t *msg = (msg_mapme_add_t *)packet;
+
+ if (!connection_is_local(connection)) goto NACK;
+
+ *reply_size = sizeof(msg_header_t);
+
+ fib_t *fib = forwarder_get_fib(forwarder);
+ if (!fib) goto NACK;
+
+ mapme_t *mapme = forwarder_get_mapme(forwarder);
+
+ cmd_mapme_add_t *control = &msg->payload;
+ /* If the message comes from the producer, address, family, len and
+ * face_id will be NULL
+ */
+ if (hicn_ip_address_empty(&control->address) && (control->len == 0) &&
+ (control->family == 0) && (control->face_id == 0)) {
+ /*
+ * The command triggers a mapme update for all prefixes produced on this
+ * face
+ *
+ * XXX This should in fact be an UPDATE command
+ */
+
+ fib_foreach_entry(fib, entry, {
+ const nexthops_t *nexthops = fib_entry_get_nexthops(entry);
+ nexthops_foreach(nexthops, nexthop, {
+ if (nexthop != ingress_id) continue;
+ /* This entry points to the producer face */
+ mapme_set_all_adjacencies(mapme, entry);
+ break;
+ });
+ });
+
+ goto END;
+ }
+
+ /* Control plane triggered
+ *
+ * We might not only receive MAP-Me update requests for prefixes we own,
+ * but also for more specific ones (for instance, we have a /64 and
+ * want to send an update on a /128). This requires a FIB lookup.
+ *
+ * NOTE: we need to avoid modifying the FIB because of this.
+ *
+ * TODO:
+ * - assert face_id is valid and exists
+ * - assert family is correct
+ */
+
+ hicn_prefix_t name_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&control->address, control->len,
+ &name_prefix);
+
+#ifdef HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY
+ fib_entry_t *entry = fib_contains(fib, &name_prefix);
+ if (!entry) {
+ entry = mapme_create_fib_entry(mapme, &name_prefix, INVALID_FACE_ID);
+ if (!entry) goto NACK; // we could also perform as in the other branch
+ }
+ mapme_set_adjacency(mapme, entry, control->face_id, NULL);
+
+#else
+ fib_entry_t *entry = fib_match_prefix(fib, &name_prefix);
+
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(entry);
+ if (hicn_prefix_get_len(prefix) == control->len) {
+ mapme_set_adjacency(mapme, entry, control->face_id, NULL);
+ } else {
+ mapme_set_adjacency(mapme, NULL, control->face_id, prefix);
+ }
+#endif
+
+END:
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+#endif /* WITH_MAPME */
+
+/* Policy */
+
+uint8_t *configuration_on_policy_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+#ifdef WITH_POLICY
+ msg_policy_add_t *msg = (msg_policy_add_t *)packet;
+ cmd_policy_add_t *control = &msg->payload;
+
+ hicn_ip_prefix_t prefix = {.family = control->family,
+ .address = control->address,
+ .len = control->len};
+
+ if (!forwarder_add_or_update_policy(forwarder, &prefix, &control->policy))
+ goto NACK;
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+#endif /* WITH_POLICY */
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_policy_remove(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+#ifdef WITH_POLICY
+ msg_policy_remove_t *msg = (msg_policy_remove_t *)packet;
+ cmd_policy_remove_t *control = &msg->payload;
+
+ hicn_ip_prefix_t prefix = {.family = control->family,
+ .address = control->address,
+ .len = control->len};
+
+ if (!forwarder_remove_policy(forwarder, &prefix)) goto NACK;
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+#endif /* WITH_POLICY */
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+static inline void fill_policy_command(const fib_entry_t *entry,
+ cmd_policy_list_item_t *cmd) {
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(entry);
+ const hicn_ip_address_t *ip_address = hicn_prefix_get_ip_address(prefix);
+ cmd->remote_addr = *ip_address;
+ cmd->family = hicn_ip_address_get_family(ip_address);
+ cmd->len = hicn_prefix_get_len(prefix);
+
+ hicn_policy_t policy = fib_entry_get_policy(entry);
+ _hicn_policy_t _policy = {
+ .stats = {
+ .wired = {.throughput = htonf(policy.stats.wired.throughput),
+ .latency = htonf(policy.stats.wired.latency),
+ .loss_rate = htonf(policy.stats.wired.loss_rate)},
+ .wifi = {.throughput = htonf(policy.stats.wifi.throughput),
+ .latency = htonf(policy.stats.wifi.latency),
+ .loss_rate = htonf(policy.stats.wifi.loss_rate)},
+ .cellular = {.throughput = htonf(policy.stats.cellular.throughput),
+ .latency = htonf(policy.stats.cellular.latency),
+ .loss_rate = htonf(policy.stats.cellular.loss_rate)},
+ .all = {.throughput = htonf(policy.stats.all.throughput),
+ .latency = htonf(policy.stats.all.latency),
+ .loss_rate = htonf(policy.stats.all.loss_rate)}}};
+ for (unsigned i = 0; i < POLICY_TAG_N; i++) {
+ _policy.tags[i] = (_policy_tag_state_t){
+ .state = policy.tags[i].state,
+ .disabled = policy.tags[i].disabled,
+ };
+ }
+ memcpy(_policy.app_name, policy.app_name, APP_NAME_LEN);
+ memcpy(cmd->policy, &_policy, sizeof(_policy));
+}
+
+uint8_t *configuration_on_policy_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ assert(forwarder);
+ assert(packet);
+
+ const fib_t *fib = forwarder_get_fib(forwarder);
+ assert(fib);
+ size_t n = fib_get_size(fib);
+
+#ifdef WITH_POLICY
+ msg_policy_list_t *msg_received = (msg_policy_list_t *)packet;
+ uint8_t command_id = msg_received->header.command_id;
+ uint32_t seq_num = msg_received->header.seq_num;
+
+ msg_policy_list_reply_t *msg = NULL;
+ msg_malloc_list(msg, command_id, n, seq_num);
+ if (!msg) goto NACK;
+
+ cmd_policy_list_item_t *payload = &msg->payload;
+
+ fib_foreach_entry(fib, entry, {
+ fill_policy_command(entry, payload);
+ payload++;
+ });
+
+ return (uint8_t *)msg;
+#endif /* WITH_POLICY */
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+/* Subscription */
+
+uint8_t *configuration_on_subscription_add(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: subscription add (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_subscription_add_t *msg = (msg_subscription_add_t *)packet;
+ cmd_subscription_add_t *control = &msg->payload;
+ hc_topics_t topics = control->topics;
+
+ subscription_table_t *subscriptions = forwarder_get_subscriptions(forwarder);
+ assert(subscriptions);
+
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ ingress_id);
+ if (ret < 0) goto NACK;
+
+ WITH_DEBUG(subscription_table_print(subscriptions);)
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+
+NACK:
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_subscription_remove(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ INFO("CMD: subscription remove (ingress=%d)", ingress_id);
+ assert(forwarder);
+ assert(packet);
+
+ *reply_size = sizeof(msg_header_t);
+ msg_subscription_add_t *msg = (msg_subscription_add_t *)packet;
+ cmd_subscription_add_t *control = &msg->payload;
+ hc_topics_t topics = control->topics;
+
+ subscription_table_t *subscriptions = forwarder_get_subscriptions(forwarder);
+ assert(subscriptions);
+
+ subscription_table_remove_topics_for_connection(subscriptions, topics,
+ ingress_id);
+ WITH_DEBUG(subscription_table_print(subscriptions);)
+
+ make_ack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *configuration_on_active_interface_update(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size) {
+ msg_active_interface_update_t *msg = (msg_active_interface_update_t *)packet;
+ make_nack(msg);
+ return (uint8_t *)msg;
+}
+
+uint8_t *command_process(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size) {
+ uint8_t *reply = NULL;
+
+ /*
+ * For most commands, the packet will simply be transformed into an ack.
+ * For list commands, a new message will be allocated, and the return value
+ * might eventually be NULL in case of an error. That is why the free the
+ * reply at the end in these circumstances.
+ *
+ * XXX rework this part.
+ */
+ command_type_t command_type = ((msg_header_t *)packet)->header.command_id;
+ switch (command_type) {
+#define _(l, u) \
+ case COMMAND_TYPE_##u: \
+ reply = configuration_on_##l(forwarder, packet, ingress_id, reply_size); \
+ assert(reply); \
+ break;
+ foreach_command_type
+#undef _
+ case COMMAND_TYPE_UNDEFINED : case COMMAND_TYPE_N
+ : ERROR("Unexpected command type");
+ reply = packet;
+ make_nack(reply);
+ if (reply_size) *reply_size = sizeof(msg_header_t);
+ break;
+ }
+
+ return reply;
+}
+
+ssize_t command_process_msgbuf(forwarder_t *forwarder, msgbuf_t *msgbuf) {
+ assert(forwarder);
+ assert(msgbuf);
+
+ uint8_t *packet = msgbuf_get_packet(msgbuf);
+ unsigned ingress_id = msgbuf_get_connection_id(msgbuf);
+
+ uint8_t *reply = NULL;
+ size_t reply_size = 0;
+
+ reply = command_process(forwarder, packet, ingress_id, &reply_size);
+ if (connection_id_is_valid(msgbuf->connection_id)) {
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ const connection_t *connection = connection_table_at(table, ingress_id);
+ connection_send_packet(connection, reply, reply_size);
+ }
+
+ /* Free allocated replies */
+ if (reply != packet) free(reply);
+ return msgbuf_get_len(msgbuf);
+}
+
+void commands_notify(const forwarder_t *forwarder, hc_topic_t topic,
+ uint8_t *msg, size_t size) {
+ // Retrieve subscribed connections
+ subscription_table_t *subscriptions = forwarder_get_subscriptions(forwarder);
+ unsigned *subscribed_conn_ids =
+ subscription_table_get_connections_for_topic(subscriptions, topic);
+
+ // Send notification to subscribed connections
+ const connection_table_t *table = forwarder_get_connection_table(forwarder);
+ for (int i = 0; i < vector_len(subscribed_conn_ids); i++) {
+ const connection_t *conn =
+ connection_table_at(table, subscribed_conn_ids[i]);
+ connection_send_packet(conn, msg, size);
+ }
+}
+
+void commands_notify_connection(const forwarder_t *forwarder,
+ connection_event_t event,
+ const connection_t *connection) {
+#if 0
+ uint8_t command_id;
+ switch (event) {
+ case CONNECTION_EVENT_CREATE:
+ command_id = COMMAND_TYPE_CONNECTION_ADD;
+ break;
+ case CONNECTION_EVENT_DELETE:
+ command_id = COMMAND_TYPE_CONNECTION_REMOVE;
+ break;
+ case CONNECTION_EVENT_UPDATE:
+ case CONNECTION_EVENT_SET_UP:
+ case CONNECTION_EVENT_SET_DOWN:
+ case CONNECTION_EVENT_PRIORITY_CHANGED:
+ case CONNECTION_EVENT_TAGS_CHANGED:
+ command_id = COMMAND_TYPE_CONNECTION_UPDATE;
+ break;
+ case CONNECTION_EVENT_UNDEFINED:
+ case CONNECTION_EVENT_N:
+ default:
+ return;
+ }
+#endif
+
+ msg_connection_notify_t msg = {.header = {
+ .message_type = NOTIFICATION_LIGHT,
+ .command_id = OBJECT_TYPE_CONNECTION,
+ .length = 1,
+ .seq_num = 0,
+ }};
+ fill_connections_command(connection, &msg.payload);
+
+ commands_notify(forwarder, TOPIC_CONNECTION, (uint8_t *)&msg, sizeof(msg));
+}
+
+void commands_notify_route(const forwarder_t *forwarder,
+ const fib_entry_t *entry) {
+ const nexthops_t *nexthops = fib_entry_get_nexthops(entry);
+ size_t n = nexthops_get_len(nexthops);
+ msg_route_notify_t *msg = NULL;
+ msg_malloc_list(msg, OBJECT_TYPE_ROUTE, n, 0);
+ if (!msg) return;
+
+ fill_route_command(entry, &msg->payload);
+
+ commands_notify(forwarder, TOPIC_ROUTE, (uint8_t *)&msg, sizeof(msg));
+ free(msg);
+}
+
+void commands_notify_active_interface_update(const forwarder_t *forwarder,
+ hicn_ip_prefix_t *prefix,
+ netdevice_flags_t flags) {
+ struct {
+ cmd_header_t header;
+ hc_active_interface_t payload;
+ } msg = {.header =
+ {
+ .message_type = NOTIFICATION_LIGHT,
+ .command_id = OBJECT_TYPE_ACTIVE_INTERFACE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload = {.prefix = *prefix, .interface_types = flags}};
+
+ INFO("Notify active interface");
+ commands_notify(forwarder, TOPIC_ACTIVE_INTERFACE, (uint8_t *)&msg,
+ sizeof(msg));
+}
diff --git a/hicn-light/src/hicn/config/commands.h b/hicn-light/src/hicn/config/commands.h
new file mode 100644
index 000000000..f212c1b0b
--- /dev/null
+++ b/hicn-light/src/hicn/config/commands.h
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file commands.h
+ * @brief hicn-light configuration, such as in-band commands or CLI
+ *
+ * Manages all user configuration of the system, such as from the CLI or web
+ * interface It remembers the user commands and will be able to write out a
+ * config file.
+ *
+ */
+
+#ifndef HICNLIGHT_COMMANDS_H
+#define HICNLIGHT_COMMANDS_H
+
+#include "../core/msgbuf.h"
+#include "../core/strategy.h"
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/hicn-light.h>
+
+uint8_t *command_process(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+ssize_t command_process_msgbuf(forwarder_t *forwarder, msgbuf_t *msgbuf);
+
+uint8_t *configuration_on_listener_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_listener_remove(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_listener_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_connection_add(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_connection_remove(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_connection_list(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_connection_set_admin_state(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_connection_update(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_connection_set_priority(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_connection_set_tags(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_route_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_route_remove(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_route_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_cache_set_store(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_cache_set_serve(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_cache_clear(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_strategy_set(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_strategy_add_local_prefix(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_wldr_set(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_punting_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+#ifdef WITH_MAPME
+uint8_t *configuration_on_mapme_enable(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_mapme_set_discovery(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_mapme_set_timescale(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_mapme_set_retx(forwarder_t *forwarder,
+ uint8_t *packet, unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_mapme_send_update(forwarder_t *forwarder,
+ uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+#endif /* WITH_MAPME */
+
+uint8_t *configuration_on_policy_add(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_policy_remove(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id,
+ size_t *reply_size);
+
+uint8_t *configuration_on_policy_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+uint8_t *configuration_on_stats_list(forwarder_t *forwarder, uint8_t *packet,
+ unsigned ingress_id, size_t *reply_size);
+
+void commands_notify_connection(const forwarder_t *forwarder,
+ connection_event_t event,
+ const connection_t *connection);
+
+void commands_notify_route(const forwarder_t *forwarder,
+ const fib_entry_t *entry);
+
+void commands_notify_active_interface_update(const forwarder_t *forwarder,
+ hicn_ip_prefix_t *prefix,
+ netdevice_flags_t flags);
+
+#endif // HICNLIGHT_COMMANDS_H
diff --git a/hicn-light/src/hicn/config/configuration.c b/hicn-light/src/hicn/config/configuration.c
index e414f05e3..b7e931e53 100644
--- a/hicn-light/src/hicn/config/configuration.c
+++ b/hicn-light/src/hicn/config/configuration.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,1504 +26,202 @@
#include <unistd.h>
#endif
#include <ctype.h>
-#include <parc/assert/parc_Assert.h>
#include <hicn/hicn-light/config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <parc/algol/parc_HashMap.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_String.h>
-
-#include <hicn/config/configurationListeners.h>
-#include <hicn/config/symbolicNameTable.h>
-
#include <hicn/core/connection.h>
-#include <hicn/core/connectionTable.h>
+#include <hicn/core/connection_table.h>
#include <hicn/core/forwarder.h>
-#include <hicn/core/system.h>
+//#include <hicn/core/system.h>
#ifdef WITH_MAPME
#include <hicn/core/mapme.h>
#endif /* WITH_MAPME */
-#include <hicn/io/streamConnection.h>
-
-#include <hicn/io/hicnTunnel.h>
-#include <hicn/io/tcpTunnel.h>
-#include <hicn/io/udpTunnel.h>
+#include <hicn/core/listener.h> //the listener list
+#include <hicn/core/listener_table.h>
+#include <hicn/ctrl/hicn-light.h>
+//#include <hicn/utils/utils.h>
+#include <hicn/utils/punting.h>
+#include <hicn/util/log.h>
+#include <hicn/face.h>
+#include <hicn/util/slab.h>
+#include <hicn/util/sstrncpy.h>
-#include <parc/algol/parc_Unsigned.h>
-#include <hicn/io/listener.h> //the listener list
-#include <hicn/io/listenerSet.h> // needed to print
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-#include <hicn/utils/address.h>
+#include "configuration.h"
#define ETHERTYPE 0x0801
-
-struct configuration {
- Forwarder *forwarder;
- Logger *logger;
-
- size_t maximumContentObjectStoreSize;
-
- // map from prefix (parcString) to strategy (parcString)
- PARCHashMap *strategy_map;
-
- // translates between a symblic name and a connection id
- SymbolicNameTable *symbolicNameTable;
+#define DEFAULT_COST 1
+#define DEFAULT_PORT 1234
+#define DEFAULT_LOGLEVEL "info"
+#define DEFAULT_CS_CAPACITY 100000
+
+#define msg_malloc_list(msg, N, seq_number) \
+ do { \
+ msg = malloc(sizeof((msg)->header) + N * sizeof((msg)->payload)); \
+ (msg)->header.message_type = RESPONSE_LIGHT; \
+ (msg)->header.length = (uint16_t)(N); \
+ (msg)->header.seq_num = (seq_number); \
+ } while (0);
+
+typedef struct {
+ char prefix[MAXSZ_HICN_PREFIX];
+} prefix_key_t;
+
+struct configuration_s {
+ const char *fn_config;
+ uint16_t port;
+ uint16_t configuration_port;
+ size_t cs_capacity;
+ int loglevel;
+ const char *logfile;
+ int logfile_fd;
+ bool daemon;
+
+ kh_strategy_map_t *strategy_map;
+ slab_t *prefix_keys;
+
+ size_t n_suffixes_per_split;
+ int_manifest_split_strategy_t split_strategy;
};
-// ========================================================================================
-
-Connection *
-getConnectionBySymbolicOrId(Configuration * config, const char * symbolicOrConnid)
-{
- ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder);
- unsigned connid;
- Connection *conn = NULL;
-
- /* Try to resolve an eventual symbolic name as input */
- if (utils_IsNumber(symbolicOrConnid)) {
- connid = (unsigned int)strtold(symbolicOrConnid, NULL);
-
- } else {
- connid = symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid);
- if (connid == UINT32_MAX) {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Warning)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- __func__, "Symbolic name '%s' could not be resolved",
- symbolicOrConnid);
- }
- }
- }
-
- /* Get connection by ID */
- conn = (Connection *)connectionTable_FindById( table, connid);
- if (!conn) {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Warning)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- __func__, "ConnID not found, check list connections");
- }
- }
-
- return conn;
-}
-
-// ========================================================================================
-
-Configuration *configuration_Create(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter hicn-fwd must be non-null");
- Configuration *config = parcMemory_AllocateAndClear(sizeof(Configuration));
- parcAssertNotNull(config, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Configuration));
- config->forwarder = forwarder;
- config->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- config->maximumContentObjectStoreSize = 100000;
- config->strategy_map = parcHashMap_Create();
- config->symbolicNameTable = symbolicNameTable_Create();
-
- return config;
-}
-
-void configuration_Destroy(Configuration **configPtr) {
- parcAssertNotNull(configPtr, "Parameter must be non-null double poitner");
- parcAssertNotNull(*configPtr,
- "Parameter must dereference to non-null pointer");
-
- Configuration *config = *configPtr;
- logger_Release(&config->logger);
- parcHashMap_Release(&(config->strategy_map));
- symbolicNameTable_Destroy(&config->symbolicNameTable);
- parcMemory_Deallocate((void **)&config);
- *configPtr = NULL;
-}
-
-struct iovec *configuration_ProcessRegisterHicnPrefix(Configuration *config,
- struct iovec *request,
- unsigned ingressId) {
- header_control_message *header = request[0].iov_base;
- add_route_command *control = request[1].iov_base;
-
- bool success = false;
-
- const char *symbolicOrConnid = control->symbolicOrConnid;
-
- if (strcmp(symbolicOrConnid, "SELF") == 0) {
- success = forwarder_AddOrUpdateRoute(config->forwarder, control, ingressId);
- } else if (utils_IsNumber(symbolicOrConnid)) {
- // case for connid as input
- unsigned connid = (unsigned)strtold(symbolicOrConnid, NULL);
- ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder);
-
- // check if iconnID present in the fwd table
- if (connectionTable_FindById(table, connid)) {
- success = forwarder_AddOrUpdateRoute(config->forwarder, control, connid);
- } else {
- logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO,
- PARCLogLevel_Error, __func__,
- "ConnID not found, check list connections");
- // failure
- }
-
- } else {
- // case for symbolic as input: check if symbolic name can be resolved
- unsigned connid =
- symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid);
- // connid = UINT_MAX when symbolicName is not found
- if (connid != UINT32_MAX) {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Debug)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug,
- __func__, "Add route resolve name '%s' to connid %u",
- symbolicOrConnid, connid);
- }
-
- success = forwarder_AddOrUpdateRoute(config->forwarder, control, connid);
-
- } else {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Warning)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Warning,
- __func__,
- "Add route symbolic name '%s' could not be resolved",
- symbolicOrConnid);
- }
- // failure
- }
- }
-
- // generate ACK/NACK
- struct iovec *response;
-
- if (success) { // ACK
- response = utils_CreateAck(header, control, sizeof(add_route_command));
- } else { // NACK
- response = utils_CreateNack(header, control, sizeof(add_route_command));
- }
-
- return response;
-}
-
-struct iovec *configuration_ProcessUnregisterHicnPrefix(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- remove_route_command *control = request[1].iov_base;
-
- bool success = false;
-
- const char *symbolicOrConnid = control->symbolicOrConnid;
-
- if (utils_IsNumber(symbolicOrConnid)) {
- // case for connid as input
- unsigned connid = (unsigned)strtold(symbolicOrConnid, NULL);
- ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder);
-
- // check if interface index present in the fwd table
- if (connectionTable_FindById(table, connid)) {
- success = forwarder_RemoveRoute(config->forwarder, control, connid);
- } else {
- logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO,
- PARCLogLevel_Error, __func__,
- "ConnID not found, check list connections");
- // failure
- }
-
- } else {
- // case for symbolic as input: chech if symbolic name can be resolved
- unsigned connid =
- symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid);
- // connid = UINT_MAX when symbolicName is not found
- if (connid != UINT32_MAX) {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Debug)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug,
- __func__, "Remove route resolve name '%s' to connid %u",
- symbolicOrConnid, connid);
- }
- success = forwarder_RemoveRoute(config->forwarder, control, connid);
- } else {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Warning)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Warning,
- __func__,
- "Remove route symbolic name '%s' could not be resolved",
- symbolicOrConnid);
- }
- // failure
- }
- }
-
- // generate ACK/NACK
- struct iovec *response;
-
- if (success) { // ACK
- response = utils_CreateAck(header, control, sizeof(remove_route_command));
- } else { // NACK
- response = utils_CreateNack(header, control, sizeof(remove_route_command));
- }
-
- return response;
-}
-
-struct iovec *configuration_ProcessRegistrationList(Configuration *config,
- struct iovec *request) {
- FibEntryList *fibList = forwarder_GetFibEntries(config->forwarder);
-
- size_t payloadSize = fibEntryList_Length(fibList);
- size_t effective_payloadSize = 0;
- size_t pointerLocation = 0;
- struct sockaddr_in tmpAddr;
- struct sockaddr_in6 tmpAddr6;
-
- // allocate payload, cast from void* to uint8_t* = bytes granularity
- uint8_t *payloadResponse =
- parcMemory_AllocateAndClear(sizeof(list_routes_command) * payloadSize);
-
- for (size_t i = 0; i < fibEntryList_Length(fibList); i++) {
- FibEntry *entry = (FibEntry *)fibEntryList_Get(fibList, i);
- NameBitvector *prefix = name_GetContentName(fibEntry_GetPrefix(entry));
- const NumberSet *nexthops = fibEntry_GetNexthops(entry);
-
- if (numberSet_Length(nexthops) == 0)
- continue;
-
- if (numberSet_Length(nexthops) > 1) {
- // payload extended, need reallocate, further entries via nexthops
- payloadSize = payloadSize + numberSet_Length(nexthops) - 1;
- payloadResponse = (uint8_t *) parcMemory_Reallocate(
- payloadResponse, sizeof(list_routes_command) * payloadSize);
- }
-
- for (size_t j = 0; j < numberSet_Length(nexthops); j++) {
- list_routes_command *listRouteCommand =
- (list_routes_command *)(payloadResponse +
- (pointerLocation *
- sizeof(list_routes_command)));
-
- Address *addressEntry = nameBitvector_ToAddress(prefix);
- if (addressGetType(addressEntry) == ADDR_INET) {
- addressGetInet(addressEntry, &tmpAddr);
- listRouteCommand->addressType = ADDR_INET;
- listRouteCommand->address.v4.as_inaddr = tmpAddr.sin_addr;
- } else if (addressGetType(addressEntry) == ADDR_INET6) {
- addressGetInet6(addressEntry, &tmpAddr6);
- listRouteCommand->addressType = ADDR_INET6;
- listRouteCommand->address.v6.as_in6addr = tmpAddr6.sin6_addr;
- }
- listRouteCommand->connid = numberSet_GetItem(nexthops, j);
- listRouteCommand->len = nameBitvector_GetLength(prefix);
- listRouteCommand->cost = 1; // cost
-
- pointerLocation++;
- effective_payloadSize++;
- addressDestroy(&addressEntry);
- }
- }
-
- // send response
- header_control_message *header = request[0].iov_base;
- header->messageType = RESPONSE_LIGHT;
- header->length = (unsigned)effective_payloadSize;
-
- struct iovec *response =
- parcMemory_AllocateAndClear(sizeof(struct iovec) * 2);
-
- response[0].iov_base = header;
- response[0].iov_len = sizeof(header_control_message);
- response[1].iov_base = payloadResponse;
- response[1].iov_len = sizeof(list_routes_command) * effective_payloadSize;
-
- fibEntryList_Destroy(&fibList);
- return response;
-}
-
-static void configuration_SendResponse(Configuration *config, struct iovec *msg,
- unsigned egressId) {
- ConnectionTable *connectionTable =
- forwarder_GetConnectionTable(config->forwarder);
- const Connection *conn = connectionTable_FindById(connectionTable, egressId);
-
- if (conn == NULL) {
- return;
- }
- connection_SendIOVBuffer(conn, msg, 2);
-}
-
-struct iovec *configuration_ProcessCreateTunnel(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- add_connection_command *control = request[1].iov_base;
-
- bool success = false;
-
- Connection *conn;
- const char *symbolicName = control->symbolic;
-
- Address *source = NULL;
- Address *destination = NULL;
-
- if (symbolicNameTable_Exists(config->symbolicNameTable, symbolicName)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- __func__, "Connection symbolic name already exists");
- goto ERR;
- }
-
- if (control->ipType == ADDR_INET) {
- source =
- addressFromInaddr4Port(&control->localIp.v4.as_u32, &control->localPort);
- destination =
- addressFromInaddr4Port(&control->remoteIp.v4.as_u32, &control->remotePort);
- } else if (control->ipType == ADDR_INET6) {
- source =
- addressFromInaddr6Port(&control->localIp.v6.as_in6addr, &control->localPort);
- destination =
- addressFromInaddr6Port(&control->remoteIp.v6.as_in6addr, &control->remotePort);
- } else {
- printf("Invalid IP type.\n"); // will generate a Nack
- }
-
- AddressPair *pair = addressPair_Create(source, destination);
- conn = (Connection *)connectionTable_FindByAddressPair(
- forwarder_GetConnectionTable(config->forwarder), pair);
-
- addressPair_Release(&pair);
+configuration_t *configuration_create() {
+ configuration_t *config = malloc(sizeof(configuration_t));
+ if (!config) return NULL;
- if (!conn) {
- IoOperations *ops = NULL;
- switch (control->connectionType) {
- case TCP_CONN:
- // logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- // __func__,
- // "Unsupported tunnel protocol: TCP");
- ops = tcpTunnel_Create(config->forwarder, source, destination);
- break;
- case UDP_CONN:
- ops = udpTunnel_Create(config->forwarder, source, destination);
- break;
- case GRE_CONN:
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- __func__, "Unsupported tunnel protocol: GRE");
- break;
-#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING)
- case HICN_CONN:
- ops = hicnTunnel_Create(config->forwarder, source, destination);
- break;
-#endif /* __APPLE__ _WIN32*/
- default:
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- __func__, "Unsupported tunnel protocol: %d",
- control->connectionType);
- break;
- }
-
- if (ops != NULL) {
- Connection *conn = connection_Create(ops);
-#ifdef WITH_POLICY
- connection_SetTags(conn, control->tags);
- connection_SetPriority(conn, control->priority);
-#endif /* WITH_POLICY */
-
- connection_SetAdminState(conn, control->admin_state);
-
- connectionTable_Add(forwarder_GetConnectionTable(config->forwarder),
- conn);
- symbolicNameTable_Add(config->symbolicNameTable, symbolicName,
- connection_GetConnectionId(conn));
-
-#ifdef WITH_MAPME
- /* Hook: new connection created through the control protocol */
- forwarder_onConnectionEvent(config->forwarder, conn, CONNECTION_EVENT_CREATE);
-#endif /* WITH_MAPME */
-
- success = true;
-
- } else {
- printf("failed, could not create IoOperations");
- }
-
- } else {
-#ifdef WITH_POLICY
- connection_SetTags(conn, control->tags);
- connection_SetPriority(conn, control->priority);
- connection_SetAdminState(conn, control->admin_state);
-
-#ifdef WITH_MAPME
- /* Hook: new connection created through the control protocol */
- forwarder_onConnectionEvent(config->forwarder, conn, CONNECTION_EVENT_UPDATE);
-#endif /* WITH_MAPME */
- if (source)
- addressDestroy(&source);
- if (destination)
- addressDestroy(&destination);
-
- success = true;
+ config->fn_config = NULL;
+ config->port = PORT_NUMBER;
+ config->configuration_port = 2001; // TODO(eloparco): What is this?
+ config->cs_capacity = DEFAULT_CS_CAPACITY;
+ config->logfile = NULL;
+ config->logfile_fd = -1;
+#ifndef _WIN32
+ config->daemon = false;
#else
- printf("failed, symbolic name or connection already exist\n");
-#endif /* WITH_POLICY */
- }
-
- if (source)
- addressDestroy(&source);
- if (destination)
- addressDestroy(&destination);
-
- if (!success)
- goto ERR;
-
- // ACK
- return utils_CreateAck(header, control, sizeof(add_connection_command));
-
-ERR:
- return utils_CreateNack(header, control, sizeof(add_connection_command));
-}
-
-struct iovec *configuration_ProcessRemoveListener(Configuration *config,
- struct iovec *request,
- unsigned ingressId) {
- header_control_message *header = request[0].iov_base;
- remove_listener_command *control = request[1].iov_base;
-
- bool success = false;
-
- const char *symbolicOrListenerid = control->symbolicOrListenerid;
- int listenerId = -1;
- ListenerSet *listenerSet = forwarder_GetListenerSet(config->forwarder);
- if (utils_IsNumber(symbolicOrListenerid)) {
- // case for connid as input
- listenerId = (unsigned)strtold(symbolicOrListenerid, NULL);
- } else {
- listenerId = listenerSet_FindIdByListenerName(listenerSet, symbolicOrListenerid);
- }
-
- if (listenerId >= 0) {
-
- ConnectionTable *connTable = forwarder_GetConnectionTable(config->forwarder);
- ListenerOps *listenerOps = listenerSet_FindById(listenerSet, listenerId);
- if (listenerOps) {
- ConnectionList *connectionList = connectionTable_GetEntries(connTable);
- for (size_t i = 0; i < connectionList_Length(connectionList); i++) {
- Connection *connection = connectionList_Get(connectionList, i);
- const AddressPair *addressPair = connection_GetAddressPair(connection);
- const Address *address = addressPair_GetLocal(addressPair);
- if (addressEquals(listenerOps->getListenAddress(listenerOps),address)) {
- // case for connid as input
- unsigned connid = connection_GetConnectionId(connection);
- // remove connection from the FIB
- forwarder_RemoveConnectionIdFromRoutes(config->forwarder, connid);
- // remove connection
- connectionTable_RemoveById(connTable, connid);
- const char *symbolicConnection = symbolicNameTable_GetNameByIndex(config->symbolicNameTable,connid);
- symbolicNameTable_Remove(config->symbolicNameTable, symbolicConnection);
- }
- }
- connectionList_Destroy(&connectionList);
- // remove listener
- listenerSet_RemoveById(listenerSet, listenerId);
- success = true;
- } else {
- logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO,
- PARCLogLevel_Error, __func__,
- "Listener Id not found, check list listeners");
- }
- }
-
- // generate ACK/NACK
- struct iovec *response;
-
- if (success) { // ACK
- response =
- utils_CreateAck(header, control, sizeof(remove_listener_command));
- } else { // NACK
- response =
- utils_CreateNack(header, control, sizeof(remove_connection_command));
- }
-
- return response;
-}
-
-
-/**
- * Add an IP-based tunnel.
- *
- * The call cal fail if the symbolic name is a duplicate. It could also fail if
- * there's an problem creating the local side of the tunnel (i.e. the local
- * socket address is not usable).
- *
- * @return true Tunnel added
- * @return false Tunnel not added (an error)
- */
-
-struct iovec *configuration_ProcessRemoveTunnel(Configuration *config,
- struct iovec *request,
- unsigned ingressId) {
- header_control_message *header = request[0].iov_base;
- remove_connection_command *control = request[1].iov_base;
-
- bool success = false;
-
- const char *symbolicOrConnid = control->symbolicOrConnid;
- ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder);
- if (strcmp(symbolicOrConnid, "SELF") == 0) {
- forwarder_RemoveConnectionIdFromRoutes(config->forwarder, ingressId);
- connectionTable_RemoveById(table, ingressId);
-
-#ifdef WITH_MAPME
- /* Hook: new connection created through the control protocol */
- forwarder_onConnectionEvent(config->forwarder, NULL, CONNECTION_EVENT_DELETE);
-#endif /* WITH_MAPME */
-
- success = true;
- } else if (utils_IsNumber(symbolicOrConnid)) {
- // case for connid as input
- unsigned connid = (unsigned)strtold(symbolicOrConnid, NULL);
-
- // check if interface index present in the fwd table
- //(it was missing and therefore caused a program crash)
- if (connectionTable_FindById(table, connid)) {
- // remove connection from the FIB
- forwarder_RemoveConnectionIdFromRoutes(config->forwarder, connid);
- // remove connection
- connectionTable_RemoveById(table, connid);
- // remove connection from symbolicNameTable
- const char *symbolicConnection = symbolicNameTable_GetNameByIndex(config->symbolicNameTable,connid);
- symbolicNameTable_Remove(config->symbolicNameTable, symbolicConnection);
-
-#ifdef WITH_MAPME
- /* Hook: new connection created through the control protocol */
- forwarder_onConnectionEvent(config->forwarder, NULL, CONNECTION_EVENT_DELETE);
-#endif /* WITH_MAPME */
-
- success = true;
- } else {
- logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO,
- PARCLogLevel_Error, __func__,
- "ConnID not found, check list connections");
- // failure
- }
-
- } else {
- // case for symbolic as input
- // chech if symbolic name can be resolved
- unsigned connid =
- symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid);
- // connid = UINT_MAX when symbolicName is not found
- if (connid != UINT32_MAX) {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Debug)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug,
- __func__, "Remove connection resolve name '%s' to connid %u",
- symbolicOrConnid, connid);
- }
-
- // remove connection from the FIB
- forwarder_RemoveConnectionIdFromRoutes(config->forwarder, connid);
- // remove connection
- connectionTable_RemoveById(table, connid);
- // remove connection from symbolicNameTable since we have symbolic input
- symbolicNameTable_Remove(config->symbolicNameTable, symbolicOrConnid);
-
-#ifdef WITH_MAPME
- /* Hook: new connection created through the control protocol */
- forwarder_onConnectionEvent(config->forwarder, NULL, CONNECTION_EVENT_DELETE);
-#endif /* WITH_MAPME */
-
- success = true; // to write
- } else {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Warning)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- __func__,
- "Remove connection symbolic name '%s' could not be resolved",
- symbolicOrConnid);
- }
- // failure
- }
- }
-
-
-
- // generate ACK/NACK
- struct iovec *response;
-
- if (success) { // ACK
- response =
- utils_CreateAck(header, control, sizeof(remove_connection_command));
- } else { // NACK
- response =
- utils_CreateNack(header, control, sizeof(remove_connection_command));
- }
-
- return response;
-}
-
-void _parc_strlwr(char *string) {
- char *p = string;
- while ((*p = tolower(*p))) {
- p++;
- }
-}
-
-struct iovec *configuration_ProcessConnectionList(Configuration *config,
- struct iovec *request) {
- ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder);
- ConnectionList *connList = connectionTable_GetEntries(table);
- struct sockaddr_in tmpAddr;
- struct sockaddr_in6 tmpAddr6;
-
- // allocate payload, cast from void* to uint8_t* fot bytes granularity
- uint8_t *payloadResponse = parcMemory_AllocateAndClear(
- sizeof(list_connections_command) * connectionList_Length(connList));
-
- for (size_t i = 0; i < connectionList_Length(connList); i++) {
- // Don't release original, it is not stored
- Connection *original = connectionList_Get(connList, i);
-
- const AddressPair *addressPair = connection_GetAddressPair(original);
- Address *localAddress = addressCopy(addressPair_GetLocal(addressPair));
- Address *remoteAddress = addressCopy(addressPair_GetRemote(addressPair));
-
- // Fill payload by shifting and casting at each 'i' step.
- list_connections_command *listConnectionsCommand =
- (list_connections_command *)(payloadResponse +
- (i * sizeof(list_connections_command)));
- // set structure fields
-
- listConnectionsCommand->connid = connection_GetConnectionId(original);
-
- const char *connectionName = symbolicNameTable_GetNameByIndex(config->symbolicNameTable, connection_GetConnectionId(original));
- snprintf(listConnectionsCommand->connectionName, SYMBOLIC_NAME_LEN, "%s", connectionName);
- _parc_strlwr(listConnectionsCommand->connectionName);
-
- snprintf(listConnectionsCommand->interfaceName, SYMBOLIC_NAME_LEN, "%s", ioOperations_GetInterfaceName(connection_GetIoOperations(original)));
-
- listConnectionsCommand->state =
- connection_IsUp(original) ? IFACE_UP : IFACE_DOWN;
- listConnectionsCommand->connectionData.admin_state =
- (connection_GetAdminState(original) == CONNECTION_STATE_UP) ? IFACE_UP : IFACE_DOWN;
- listConnectionsCommand->connectionData.connectionType =
- ioOperations_GetConnectionType(connection_GetIoOperations(original));
-
- listConnectionsCommand->connectionData.admin_state = connection_GetAdminState(original);
-
-#ifdef WITH_POLICY
- listConnectionsCommand->connectionData.priority = connection_GetPriority(original);
- listConnectionsCommand->connectionData.tags = connection_GetTags(original);
-#endif /* WITH_POLICY */
-
- if (addressGetType(localAddress) == ADDR_INET &&
- addressGetType(remoteAddress) == ADDR_INET) {
- listConnectionsCommand->connectionData.ipType = ADDR_INET;
-
- // get local port/address
- addressGetInet(localAddress, &tmpAddr);
- listConnectionsCommand->connectionData.localPort = tmpAddr.sin_port;
- listConnectionsCommand->connectionData.localIp.v4.as_inaddr =
- tmpAddr.sin_addr;
- memset(&tmpAddr, 0, sizeof(tmpAddr));
- // get remote port/address
- addressGetInet(remoteAddress, &tmpAddr);
- listConnectionsCommand->connectionData.remotePort = tmpAddr.sin_port;
- listConnectionsCommand->connectionData.remoteIp.v4.as_inaddr =
- tmpAddr.sin_addr;
-
- } else if (addressGetType(localAddress) == ADDR_INET6 &&
- addressGetType(remoteAddress) == ADDR_INET6) {
- listConnectionsCommand->connectionData.ipType = ADDR_INET6;
-
- // get local port/address
- addressGetInet6(localAddress, &tmpAddr6);
- listConnectionsCommand->connectionData.localPort = tmpAddr6.sin6_port;
- listConnectionsCommand->connectionData.localIp.v6.as_in6addr = tmpAddr6.sin6_addr;
- memset(&tmpAddr6, 0, sizeof(tmpAddr6));
- // get remote port/address
- addressGetInet6(remoteAddress, &tmpAddr6);
- listConnectionsCommand->connectionData.remotePort = tmpAddr6.sin6_port;
- listConnectionsCommand->connectionData.remoteIp.v6.as_in6addr = tmpAddr6.sin6_addr;
-
- } // no need further else, control on the addressed already done at the
- // time of insertion in the connection table
- addressDestroy(&localAddress);
- addressDestroy(&remoteAddress);
- }
-
- // send response
- header_control_message *header = request[0].iov_base;
- header->messageType = RESPONSE_LIGHT;
- header->length = (uint16_t)connectionList_Length(connList);
-
- struct iovec *response =
- parcMemory_AllocateAndClear(sizeof(struct iovec) * 2);
-
- response[0].iov_base = header;
- response[0].iov_len = sizeof(header_control_message);
- response[1].iov_base = payloadResponse;
- response[1].iov_len =
- sizeof(list_connections_command) * connectionList_Length(connList);
-
- connectionList_Destroy(&connList);
- return response;
-}
-
-struct iovec *configuration_ProcessListenersList(Configuration *config,
- struct iovec *request) {
- ListenerSet *listenerList = forwarder_GetListenerSet(config->forwarder);
- struct sockaddr_in tmpAddr;
- struct sockaddr_in6 tmpAddr6;
-
- // allocate payload, cast from void* to uint8_t* fot bytes granularity
- uint8_t *payloadResponse = parcMemory_AllocateAndClear(
- sizeof(list_listeners_command) * listenerSet_Length(listenerList));
-
- for (size_t i = 0; i < listenerSet_Length(listenerList); i++) {
- ListenerOps *listenerEntry = listenerSet_Get(listenerList, i);
-
- // Fill payload by shifting and casting at each 'i' step.
- list_listeners_command *listListenersCommand =
- (list_listeners_command *)(payloadResponse +
- (i * sizeof(list_listeners_command)));
-
- listListenersCommand->connid =
- (uint32_t)listenerEntry->getInterfaceIndex(listenerEntry);
- listListenersCommand->encapType =
- (uint8_t)listenerEntry->getEncapType(listenerEntry);
- if (addressGetType((const Address *)listenerEntry->getListenAddress(
- listenerEntry)) == ADDR_INET) {
- addressGetInet(
- (const Address *)listenerEntry->getListenAddress(listenerEntry),
- &tmpAddr);
- listListenersCommand->addressType = ADDR_INET;
- listListenersCommand->address.v4.as_inaddr = tmpAddr.sin_addr;
- listListenersCommand->port = tmpAddr.sin_port;
- } else if (addressGetType((const Address *)listenerEntry->getListenAddress(
- listenerEntry)) == ADDR_INET6) {
- addressGetInet6(
- (const Address *)listenerEntry->getListenAddress(listenerEntry),
- &tmpAddr6);
- listListenersCommand->addressType = ADDR_INET6;
- listListenersCommand->address.v6.as_in6addr = tmpAddr6.sin6_addr;
- listListenersCommand->port = tmpAddr6.sin6_port;
- }
-
- const char * listenerName = listenerEntry->getListenerName(listenerEntry);
- snprintf(listListenersCommand->listenerName, SYMBOLIC_NAME_LEN, "%s", listenerName);
- if (listenerEntry->getEncapType(listenerEntry) == ENCAP_TCP ||
- listenerEntry->getEncapType(listenerEntry) == ENCAP_UDP) {
- const char * interfaceName = listenerEntry->getInterfaceName(listenerEntry);
- snprintf(listListenersCommand->interfaceName, SYMBOLIC_NAME_LEN, "%s", interfaceName);
- }
- }
-
- // send response
- header_control_message *header = request[0].iov_base;
- header->messageType = RESPONSE_LIGHT;
- header->length = (uint16_t)listenerSet_Length(listenerList);
-
- struct iovec *response =
- parcMemory_AllocateAndClear(sizeof(struct iovec) * 2);
-
- response[0].iov_base = header;
- response[0].iov_len = sizeof(header_control_message);
- response[1].iov_base = payloadResponse;
- response[1].iov_len =
- sizeof(list_listeners_command) * listenerSet_Length(listenerList);
-
- return response;
-}
-
-struct iovec *configuration_ProcessCacheStore(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- ;
- cache_store_command *control = request[1].iov_base;
- ;
-
- bool success = false;
-
- switch (control->activate) {
- case ACTIVATE_ON:
- forwarder_SetChacheStoreFlag(config->forwarder, true);
- if (forwarder_GetChacheStoreFlag(config->forwarder)) {
- success = true;
- }
- break;
-
- case ACTIVATE_OFF:
- forwarder_SetChacheStoreFlag(config->forwarder, false);
- if (!forwarder_GetChacheStoreFlag(config->forwarder)) {
- success = true;
- }
- break;
-
- default:
- break;
- }
-
- struct iovec *response;
- if (success) { // ACK
- response = utils_CreateAck(header, control, sizeof(cache_store_command));
- } else { // NACK
- response = utils_CreateNack(header, control, sizeof(cache_store_command));
- }
-
- return response;
-}
-
-struct iovec *configuration_ProcessCacheServe(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- cache_serve_command *control = request[1].iov_base;
-
- bool success = false;
-
- switch (control->activate) {
- case ACTIVATE_ON:
- forwarder_SetChacheServeFlag(config->forwarder, true);
- if (forwarder_GetChacheServeFlag(config->forwarder)) {
- success = true;
- }
- break;
-
- case ACTIVATE_OFF:
- forwarder_SetChacheServeFlag(config->forwarder, false);
- if (!forwarder_GetChacheServeFlag(config->forwarder)) {
- success = true;
- }
- break;
-
- default:
- break;
- }
-
- struct iovec *response;
- if (success) { // ACK
- response = utils_CreateAck(header, control, sizeof(cache_store_command));
- } else { // NACK
- response = utils_CreateNack(header, control, sizeof(cache_store_command));
- }
+ WSADATA wsaData = {0};
+ WSAStartup(MAKEWORD(2, 2), &wsaData);
+#endif
+ configuration_set_loglevel(config, loglevel_from_str(DEFAULT_LOGLEVEL));
+ config->strategy_map = kh_init_strategy_map();
+ config->prefix_keys = slab_create(prefix_key_t, SLAB_INIT_SIZE);
+ config->n_suffixes_per_split = DEFAULT_N_SUFFIXES_PER_SPLIT;
+ config->split_strategy = DEFAULT_DISAGGREGATION_STRATEGY;
- return response;
+ return config;
}
-struct iovec *configuration_ProcessCacheClear(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
+void configuration_free(configuration_t *config) {
+ assert(config);
- forwarder_ClearCache(config->forwarder);
+ kh_destroy_strategy_map(config->strategy_map);
+ slab_free(config->prefix_keys);
- struct iovec *response = utils_CreateAck(header, NULL, 0);
- return response;
+ free(config);
}
-size_t configuration_GetObjectStoreSize(Configuration *config) {
- return config->maximumContentObjectStoreSize;
+size_t configuration_get_cs_size(const configuration_t *config) {
+ return config->cs_capacity;
}
-void _configuration_StoreFwdStrategy(Configuration *config, const char *prefix,
- strategy_type strategy) {
- PARCString *prefixStr = parcString_Create(prefix);
- PARCUnsigned *strategyValue = parcUnsigned_Create((unsigned)strategy);
- parcHashMap_Put(config->strategy_map, prefixStr, strategyValue);
- parcUnsigned_Release(&strategyValue);
- parcString_Release(&prefixStr);
+void configuration_set_cs_size(configuration_t *config, size_t size) {
+ config->cs_capacity = size;
}
-struct iovec *configuration_SetWldr(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- set_wldr_command *control = request[1].iov_base;
- ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder);
- Connection *conn = NULL;
- bool success = false;
-
- const char *symbolicOrConnid = control->symbolicOrConnid;
-
- if (utils_IsNumber(symbolicOrConnid)) {
- // case for connid as input: check if connID present in the fwd table
- conn = (Connection *)connectionTable_FindById(
- table, (unsigned)strtold(symbolicOrConnid, NULL));
- if (conn) {
- success = true;
- } else {
- logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO,
- PARCLogLevel_Error, __func__,
- "ConnID not found, check list connections"); // failure
- }
- } else {
- // case for symbolic as input: check if symbolic name can be resolved
- unsigned connid =
- symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid);
- if (connid != UINT32_MAX) {
- conn = (Connection *)connectionTable_FindById(table, connid);
- if (conn) {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Debug)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug,
- __func__, "Set wldr resolve name '%s' to connid %u",
- symbolicOrConnid, connid);
- }
- success = true;
- }
- } else {
- if (logger_IsLoggable(config->logger, LoggerFacility_Config,
- PARCLogLevel_Warning)) {
- logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error,
- __func__, "Symbolic name '%s' could not be resolved",
- symbolicOrConnid);
- } // failure
- }
- }
-
- // generate ACK/NACK
- struct iovec *response;
-
- if (success) {
- switch (control->activate) {
- case ACTIVATE_ON:
- connection_EnableWldr(conn);
- response = utils_CreateAck(header, control, sizeof(set_wldr_command));
- break;
-
- case ACTIVATE_OFF:
- connection_DisableWldr(conn);
- response = utils_CreateAck(header, control, sizeof(set_wldr_command));
- break;
-
- default: // received wrong value
- response = utils_CreateNack(header, control, sizeof(set_wldr_command));
- break;
- }
- } else {
- response = utils_CreateNack(header, control, sizeof(set_wldr_command));
- }
-
- return response;
+const char *configuration_get_fn_config(const configuration_t *config) {
+ return config->fn_config;
}
-strategy_type configuration_GetForwardingStrategy(Configuration *config,
- const char *prefix) {
- PARCString *prefixStr = parcString_Create(prefix);
- const unsigned *val = parcHashMap_Get(config->strategy_map, prefixStr);
- parcString_Release(&prefixStr);
-
- if (val == NULL) {
- return LAST_STRATEGY_VALUE;
- } else {
- return (strategy_type)*val;
- }
+void configuration_set_fn_config(configuration_t *config,
+ const char *fn_config) {
+ config->fn_config = fn_config;
}
-struct iovec *configuration_SetForwardingStrategy(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- set_strategy_command *control = request[1].iov_base;
-
- const char *prefix = utils_PrefixLenToString(
- control->addressType, &control->address, &control->len);
- strategy_type strategy = control->strategyType;
- strategy_type existingFwdStrategy =
- configuration_GetForwardingStrategy(config, prefix);
-
- if (existingFwdStrategy == LAST_STRATEGY_VALUE ||
- strategy != existingFwdStrategy) {
- // means such a new strategy is not present in the hash table or has to be
- // updated
- _configuration_StoreFwdStrategy(config, prefix, strategy);
- Name *hicnPrefix = name_CreateFromAddress(control->addressType,
- control->address, control->len);
- Name *related_prefixes[MAX_FWD_STRATEGY_RELATED_PREFIXES];
- if(control->related_prefixes != 0){
- for(int i = 0; i < control->related_prefixes; i++){
- related_prefixes[i] = name_CreateFromAddress(
- control->addresses_type[i],
- control->addresses[i], control->lens[i]);
- }
- }
- forwarder_SetStrategy(config->forwarder, hicnPrefix, strategy,
- control->related_prefixes, related_prefixes);
- name_Release(&hicnPrefix);
- if(control->related_prefixes != 0){
- for(int i = 0; i < control->related_prefixes; i++){
- name_Release(&related_prefixes[i]);
- }
- }
- }
-
- free((char *) prefix);
- struct iovec *response =
- utils_CreateAck(header, control, sizeof(set_strategy_command));
-
- return response;
+void configuration_set_suffixes_per_split(configuration_t *config,
+ size_t n_suffixes_per_split) {
+ config->n_suffixes_per_split = n_suffixes_per_split;
}
-void configuration_SetObjectStoreSize(Configuration *config,
- size_t maximumObjectCount) {
- config->maximumContentObjectStoreSize = maximumObjectCount;
-
- forwarder_SetContentObjectStoreSize(config->forwarder,
- config->maximumContentObjectStoreSize);
+size_t configuration_get_suffixes_per_split(const configuration_t *config) {
+ return config->n_suffixes_per_split;
}
-Forwarder *configuration_GetForwarder(const Configuration *config) {
- return config->forwarder;
+void configuration_set_split_strategy(
+ configuration_t *config, int_manifest_split_strategy_t split_strategy) {
+ config->split_strategy = split_strategy;
}
-Logger *configuration_GetLogger(const Configuration *config) {
- return config->logger;
+int_manifest_split_strategy_t configuration_get_split_strategy(
+ const configuration_t *config) {
+ return config->split_strategy;
}
-struct iovec *configuration_MapMeEnable(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- mapme_activator_command *control = request[1].iov_base;
- const char *stateString[2] = {"on", "off"};
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
- parcBufferComposer_Format(composer,
- "The mapme enable setting received is: %s",
- stateString[control->activate]);
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
- puts(result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
-
- return utils_CreateAck(header, control, sizeof(mapme_timing_command));
+void configuration_set_port(configuration_t *config, uint16_t port) {
+ config->port = port;
}
-struct iovec *configuration_MapMeDiscovery(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- mapme_activator_command *control = request[1].iov_base;
- const char *stateString[2] = {"on", "off"};
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
- parcBufferComposer_Format(composer,
- "The mapme discovery setting received is: %s",
- stateString[control->activate]);
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
- puts(result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
-
- return utils_CreateAck(header, control, sizeof(mapme_timing_command));
+uint16_t configuration_get_port(const configuration_t *config) {
+ return config->port;
}
-struct iovec *configuration_MapMeTimescale(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- mapme_timing_command *control = request[1].iov_base;
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
- parcBufferComposer_Format(composer,
- "The mapme timescale value received is: %u",
- control->timePeriod);
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
- puts(result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
-
- return utils_CreateAck(header, control, sizeof(mapme_timing_command));
+void configuration_set_configuration_port(configuration_t *config,
+ uint16_t configuration_port) {
+ config->configuration_port = configuration_port;
}
-struct iovec *configuration_MapMeRetx(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- mapme_timing_command *control = request[1].iov_base;
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
- parcBufferComposer_Format(
- composer, "The mapme retransmission time value received is: %u",
- control->timePeriod);
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
- puts(result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
-
- return utils_CreateAck(header, control, sizeof(mapme_timing_command));
+uint16_t configuration_get_configuration_port(const configuration_t *config) {
+ return config->configuration_port;
}
-struct iovec * configuration_MapMeSendUpdate(Configuration *config,
- struct iovec *request, unsigned ingressId) {
- header_control_message *header = request[0].iov_base;
- mapme_send_update_command *control = request[1].iov_base;
-
- FIB * fib = forwarder_getFib(config->forwarder);
- if (!fib)
- goto ERR;
- Name *prefix = name_CreateFromAddress(control->addressType, control->address,
- control->len);
- if (!prefix)
- goto ERR;
- FibEntry *entry = fib_Contains(fib, prefix);
- name_Release(&prefix);
- if (!entry)
- goto ERR;
-
- const NumberSet * nexthops = fibEntry_GetNexthops(entry);
- unsigned size = (unsigned) numberSet_Length(nexthops);
-
- /* The command is accepted iif triggered by (one of) the producer of this prefix */
- for (unsigned i = 0; i < size; i++) {
- unsigned nhop = numberSet_GetItem(nexthops, i);
- if (nhop == ingressId) {
- MapMe * mapme = forwarder_getMapmeInstance(config->forwarder);
- mapme_send_updates(mapme, entry, nexthops);
- return utils_CreateAck(header, control, sizeof(mapme_timing_command));
- }
- }
-
-ERR:
- return utils_CreateNack(header, control, sizeof(connection_set_admin_state_command));
+void configuration_set_loglevel(configuration_t *config, int loglevel) {
+ config->loglevel = loglevel;
+ log_conf.log_level = loglevel;
}
-
-struct iovec *configuration_ConnectionSetAdminState(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- connection_set_admin_state_command *control = request[1].iov_base;
-
- if ((control->admin_state != CONNECTION_STATE_UP) && (control->admin_state != CONNECTION_STATE_DOWN))
- return utils_CreateNack(header, control, sizeof(connection_set_admin_state_command));
-
- Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid);
- if (!conn)
- return utils_CreateNack(header, control, sizeof(connection_set_admin_state_command));
-
- connection_SetAdminState(conn, control->admin_state);
-
-#ifdef WITH_MAPME
- /* Hook: connection event */
- forwarder_onConnectionEvent(config->forwarder, conn,
- control->admin_state == CONNECTION_STATE_UP
- ? CONNECTION_EVENT_SET_UP
- : CONNECTION_EVENT_SET_DOWN);
-#endif /* WITH_MAPME */
-
- return utils_CreateAck(header, control, sizeof(connection_set_admin_state_command));
+int configuration_get_loglevel(const configuration_t *config) {
+ return config->loglevel;
}
-#ifdef WITH_POLICY
-
-struct iovec *configuration_ConnectionSetPriority(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- connection_set_priority_command *control = request[1].iov_base;
-
- Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid);
- if (!conn)
- return utils_CreateNack(header, control, sizeof(connection_set_priority_command));
-
- connection_SetPriority(conn, control->priority);
-
-#ifdef WITH_MAPME
- /* Hook: connection event */
- forwarder_onConnectionEvent(config->forwarder, conn,
- CONNECTION_EVENT_PRIORITY_CHANGED);
-#endif /* WITH_MAPME */
-
- return utils_CreateAck(header, control, sizeof(connection_set_priority_command));
+void configuration_set_logfile(configuration_t *config, const char *logfile) {
+ config->logfile = logfile;
+ log_conf.log_file = fopen(logfile, "w");
+ config->logfile_fd = fileno(log_conf.log_file);
}
-struct iovec *configuration_ConnectionSetTags(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- connection_set_tags_command *control = request[1].iov_base;
-
- Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid);
- if (!conn)
- return utils_CreateNack(header, control, sizeof(connection_set_tags_command));
-
- connection_SetTags(conn, control->tags);
-
-#ifdef WITH_MAPME
- /* Hook: connection event */
- forwarder_onConnectionEvent(config->forwarder, conn,
- CONNECTION_EVENT_TAGS_CHANGED);
-#endif /* WITH_MAPME */
-
- return utils_CreateAck(header, control, sizeof(connection_set_tags_command));
+const char *configuration_get_logfile(const configuration_t *config) {
+ return config->logfile;
}
-struct iovec *configuration_ProcessPolicyAdd(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- add_policy_command *control = request[1].iov_base;
-
- if (forwarder_AddOrUpdatePolicy(config->forwarder, control)) {
- return utils_CreateAck(header, control, sizeof(add_policy_command));
- } else {
- return utils_CreateNack(header, control, sizeof(add_policy_command));
- }
+int configuration_get_logfile_fd(const configuration_t *config) {
+ return config->logfile_fd;
}
-struct iovec *configuration_ProcessPolicyList(Configuration *config,
- struct iovec *request) {
- FibEntryList *fibList = forwarder_GetFibEntries(config->forwarder);
-
- size_t payloadSize = fibEntryList_Length(fibList);
- struct sockaddr_in tmpAddr;
- struct sockaddr_in6 tmpAddr6;
-
- // allocate payload, cast from void* to uint8_t* = bytes granularity
- uint8_t *payloadResponse =
- parcMemory_AllocateAndClear(sizeof(list_policies_command) * payloadSize);
-
- for (size_t i = 0; i < fibEntryList_Length(fibList); i++) {
- FibEntry *entry = (FibEntry *)fibEntryList_Get(fibList, i);
- NameBitvector *prefix = name_GetContentName(fibEntry_GetPrefix(entry));
-
- list_policies_command *listPoliciesCommand =
- (list_policies_command *)(payloadResponse +
- (i * sizeof(list_policies_command)));
-
- Address *addressEntry = nameBitvector_ToAddress(prefix);
- if (addressGetType(addressEntry) == ADDR_INET) {
- addressGetInet(addressEntry, &tmpAddr);
- listPoliciesCommand->addressType = ADDR_INET;
- listPoliciesCommand->address.v4.as_inaddr = tmpAddr.sin_addr;
- } else if (addressGetType(addressEntry) == ADDR_INET6) {
- addressGetInet6(addressEntry, &tmpAddr6);
- listPoliciesCommand->addressType = ADDR_INET6;
- listPoliciesCommand->address.v6.as_in6addr = tmpAddr6.sin6_addr;
- }
- listPoliciesCommand->len = nameBitvector_GetLength(prefix);
- listPoliciesCommand->policy = fibEntry_GetPolicy(entry);
-
- addressDestroy(&addressEntry);
- }
-
- // send response
- header_control_message *header = request[0].iov_base;
- header->messageType = RESPONSE_LIGHT;
- header->length = (unsigned)payloadSize;
-
- struct iovec *response =
- parcMemory_AllocateAndClear(sizeof(struct iovec) * 2);
-
- response[0].iov_base = header;
- response[0].iov_len = sizeof(header_control_message);
- response[1].iov_base = payloadResponse;
- response[1].iov_len = sizeof(list_policies_command) * payloadSize;
-
- fibEntryList_Destroy(&fibList);
- return response;
+void configuration_set_daemon(configuration_t *config, bool daemon) {
+ config->daemon = daemon;
}
-struct iovec *configuration_ProcessPolicyRemove(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- remove_policy_command *control = request[1].iov_base;
-
- if (forwarder_RemovePolicy(config->forwarder, control))
- return utils_CreateAck(header, control, sizeof(remove_policy_command));
- else
- return utils_CreateNack(header, control, sizeof(remove_policy_command));
+bool configuration_get_daemon(const configuration_t *config) {
+ return config->daemon;
}
-struct iovec *configuration_UpdateConnection(Configuration *config,
- struct iovec *request) {
- header_control_message *header = request[0].iov_base;
- update_connection_command *control = request[1].iov_base;
+void configuration_set_strategy(configuration_t *config, const char *prefix,
+ strategy_type_t strategy_type) {
+ int res;
+ prefix_key_t *prefix_copy = slab_get(prefix_key_t, config->prefix_keys);
+ strcpy_s(prefix_copy->prefix, sizeof(prefix_key_t), prefix);
- Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid);
- if (!conn)
- return utils_CreateNack(header, control, sizeof(update_connection_command));
-
- connection_SetTags(conn, control->tags);
- connection_SetAdminState(conn, control->admin_state);
- if (control->priority > 0)
- connection_SetPriority(conn, control->priority);
-
- return utils_CreateAck(header, control, sizeof(update_connection_command));
+ khiter_t k =
+ kh_put_strategy_map(config->strategy_map, prefix_copy->prefix, &res);
+ kh_value(config->strategy_map, k) = strategy_type;
}
-#endif /* WITH_POLICY */
-
-// ===========================
-// Main functions that deal with receiving commands, executing them, and sending
-// ACK/NACK
-
-struct iovec *configuration_DispatchCommand(Configuration *config,
- command_id command,
- struct iovec *control,
- unsigned ingressId) {
- struct iovec *response = NULL;
- switch (command) {
- case ADD_LISTENER:
- response = configurationListeners_Add(config, control, ingressId);
- break;
-
- case ADD_CONNECTION:
- response = configuration_ProcessCreateTunnel(config, control);
- break;
-
- case LIST_CONNECTIONS:
- response = configuration_ProcessConnectionList(config, control);
- break;
-
- case ADD_ROUTE:
- response =
- configuration_ProcessRegisterHicnPrefix(config, control, ingressId);
- break;
-
- case LIST_ROUTES:
- response = configuration_ProcessRegistrationList(config, control);
- break;
-
- case REMOVE_CONNECTION:
- response = configuration_ProcessRemoveTunnel(config, control, ingressId);
- break;
-
- case REMOVE_LISTENER:
- response = configuration_ProcessRemoveListener(config, control, ingressId);
- break;
-
- case REMOVE_ROUTE:
- response = configuration_ProcessUnregisterHicnPrefix(config, control);
- break;
-
- case CACHE_STORE:
- response = configuration_ProcessCacheStore(config, control);
- break;
-
- case CACHE_SERVE:
- response = configuration_ProcessCacheServe(config, control);
- break;
-
- case CACHE_CLEAR:
- response = configuration_ProcessCacheClear(config, control);
- break;
-
- case SET_STRATEGY:
- response = configuration_SetForwardingStrategy(config, control);
- break;
-
- case SET_WLDR:
- response = configuration_SetWldr(config, control);
- break;
-
- case ADD_PUNTING:
- response = configurationListeners_AddPunting(config, control, ingressId);
- break;
- case LIST_LISTENERS:
- response = configuration_ProcessListenersList(config, control);
- break;
-
- case MAPME_ENABLE:
- response = configuration_MapMeEnable(config, control);
- break;
-
- case MAPME_DISCOVERY:
- response = configuration_MapMeDiscovery(config, control);
- break;
-
- case MAPME_TIMESCALE:
- response = configuration_MapMeTimescale(config, control);
- break;
-
- case MAPME_RETX:
- response = configuration_MapMeRetx(config, control);
- break;
-
- case MAPME_SEND_UPDATE:
- response = configuration_MapMeSendUpdate(config, control, ingressId);
- break;
-
- case CONNECTION_SET_ADMIN_STATE:
- response = configuration_ConnectionSetAdminState(config, control);
- break;
-
-#ifdef WITH_POLICY
- case ADD_POLICY:
- response = configuration_ProcessPolicyAdd(config, control);
- break;
-
- case LIST_POLICIES:
- response = configuration_ProcessPolicyList(config, control);
- break;
-
- case REMOVE_POLICY:
- response = configuration_ProcessPolicyRemove(config, control);
- break;
-
- case UPDATE_CONNECTION:
- response = configuration_UpdateConnection(config, control);
- break;
-
- case CONNECTION_SET_PRIORITY:
- response = configuration_ConnectionSetPriority(config, control);
- break;
-
- case CONNECTION_SET_TAGS:
- response = configuration_ConnectionSetTags(config, control);
- break;
-#endif /* WITH_POLICY */
-
- default:
- break;
- }
-
- return response;
+strategy_type_t configuration_get_strategy(const configuration_t *config,
+ const char *prefix) {
+ khiter_t k = kh_get_strategy_map(config->strategy_map, prefix);
+ if (k == kh_end(config->strategy_map)) return STRATEGY_TYPE_UNDEFINED;
+ return kh_val(config->strategy_map, k);
}
-void configuration_ReceiveCommand(Configuration *config, command_id command,
- struct iovec *request, unsigned ingressId) {
- parcAssertNotNull(config, "Parameter config must be non-null");
- parcAssertNotNull(request, "Parameter request must be non-null");
- struct iovec *response =
- configuration_DispatchCommand(config, command, request, ingressId);
- configuration_SendResponse(config, response, ingressId);
-
- /*
- * The message is originally received by a listener, and will be freed in
- * different parts of the code.
- *
- * For the special case of commands, a iovec is created, eg in
- * udpListener::_readCommand, which has to be freed (it is commented in the
- * listener). On the contrary, the original message is freed.
- *
- * From this function, commands are dispatched to different processing
- * functions, which have two general behaviours:
- *
- * - LIST commands:
- * . a payload for the response is allocated
- * . a iovec for the response is allocated with header = request header,
- * payload = newly allocated payload
- *
- * - Other commands:
- * . a ack/nack packet is generated thanks to utils/utils.cc
- * . this allocates a iovec which reuses the header of the request just
- * updating the messageType field inside.
- */
- parcMemory_Deallocate(&request);
-
- switch (command) {
- case LIST_CONNECTIONS:
- case LIST_ROUTES: // case LIST_INTERFACES: case ETC...:
- case LIST_LISTENERS:
- case LIST_POLICIES:
- /* Deallocate payload */
- parcMemory_Deallocate(&response[1].iov_base);
- break;
- default:
- break;
- }
-
- parcMemory_Deallocate(&response);
+void configuration_flush_log() {
+ if (log_conf.log_file) fclose(log_conf.log_file);
}
diff --git a/hicn-light/src/hicn/config/configuration.h b/hicn-light/src/hicn/config/configuration.h
index 5090f1413..0d1a2b8e7 100644
--- a/hicn-light/src/hicn/config/configuration.h
+++ b/hicn-light/src/hicn/config/configuration.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,17 +23,19 @@
*
*/
-#ifndef configuration_h
-#define configuration_h
+#ifndef HICNLIGHT_CONFIGURATION_H
+#define HICNLIGHT_CONFIGURATION_H
-#include <hicn/core/logger.h>
-#include <hicn/utils/commands.h>
+#include <hicn/util/khash.h>
+#include "../core/msgbuf.h"
+#include "../core/strategy.h"
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/hicn-light.h>
+#include <hicn/interest_manifest.h>
-struct configuration;
-typedef struct configuration Configuration;
+KHASH_MAP_INIT_STR(strategy_map, unsigned);
-struct forwarder;
-typedef struct forwarder Forwarder;
+typedef struct configuration_s configuration_t;
/**
* <#One Line Description#>
@@ -49,7 +51,7 @@ typedef struct forwarder Forwarder;
* <#example#>
* @endcode
*/
-Configuration *configuration_Create(Forwarder *forwarder);
+configuration_t *configuration_create();
/**
* <#One Line Description#>
@@ -65,13 +67,7 @@ Configuration *configuration_Create(Forwarder *forwarder);
* <#example#>
* @endcode
*/
-void configuration_Destroy(Configuration **configPtr);
-
-void configuration_SetupAllListeners(Configuration *config, uint16_t port,
- const char *localPath);
-
-void configuration_ReceiveCommand(Configuration *config, command_id command,
- struct iovec *request, unsigned ingressId);
+void configuration_free(configuration_t *config);
/**
* Returns the configured size of the content store
@@ -87,7 +83,7 @@ void configuration_ReceiveCommand(Configuration *config, command_id command,
* <#example#>
* @endcode
*/
-size_t configuration_GetObjectStoreSize(Configuration *config);
+size_t configuration_get_cs_size(const configuration_t *config);
/**
* Sets the size of the content store (in objects, not bytes)
@@ -101,52 +97,54 @@ size_t configuration_GetObjectStoreSize(Configuration *config);
* <#example#>
* @endcode
*/
-void configuration_SetObjectStoreSize(Configuration *config,
- size_t maximumContentObjectCount);
+void configuration_set_cs_size(configuration_t *config, size_t size);
-strategy_type configuration_GetForwardingStrategy(Configuration *config,
- const char *prefix);
+const char *configuration_get_fn_config(const configuration_t *config);
-/**
- * Returns the Forwarder that owns the Configuration
- *
- * Returns the hicn-light Forwarder. Used primarily by associated classes in
- * the configuration group.
- *
- * @param [in] config An allocated Configuration
- *
- * @return non-null The owning Forwarder
- * @return null An error
- *
- * Example:
- * @code
- * {
- * <#example#>
- * }
- * @endcode
- */
-Forwarder *configuration_GetForwarder(const Configuration *config);
+void configuration_set_fn_config(configuration_t *config,
+ const char *fn_config);
-/**
- * Returns the logger used by the Configuration subsystem
- *
- * Returns the logger specified when the Configuration was created.
- *
- * @param [in] config An allocated Configuration
- *
- * @retval non-null The logger
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-Logger *configuration_GetLogger(const Configuration *config);
+void configuration_set_suffixes_per_split(configuration_t *config,
+ size_t n_suffixes_per_split);
+
+size_t configuration_get_suffixes_per_split(const configuration_t *config);
+
+void configuration_set_split_strategy(
+ configuration_t *config,
+ int_manifest_split_strategy_t n_suffixes_per_split);
+
+int_manifest_split_strategy_t configuration_get_split_strategy(
+ const configuration_t *config);
+
+void configuration_set_port(configuration_t *config, uint16_t port);
+
+uint16_t configuration_get_port(const configuration_t *config);
+
+void configuration_set_configuration_port(configuration_t *config,
+ uint16_t configuration_port);
+
+uint16_t configuration_get_configuration_port(const configuration_t *config);
+
+void configuration_set_loglevel(configuration_t *config, int loglevel);
+
+int configuration_get_loglevel(const configuration_t *config);
+
+void configuration_set_logfile(configuration_t *config, const char *logfile);
+
+const char *configuration_get_logfile(const configuration_t *config);
+
+int configuration_get_logfile_fd(const configuration_t *config);
+
+void configuration_set_daemon(configuration_t *config, bool daemon);
+
+bool configuration_get_daemon(const configuration_t *config);
+
+void configuration_set_strategy(configuration_t *config, const char *prefix,
+ strategy_type_t strategy_type);
+
+strategy_type_t configuration_get_strategy(const configuration_t *config,
+ const char *prefix);
-struct iovec *configuration_DispatchCommand(Configuration *config,
- command_id command,
- struct iovec *control,
- unsigned ingressId);
+void configuration_flush_log();
-#endif // configuration_h
+#endif // HICNLIGHT_CONFIGURATION_H
diff --git a/hicn-light/src/hicn/config/configurationFile.c b/hicn-light/src/hicn/config/configurationFile.c
deleted file mode 100644
index ebf057fa6..000000000
--- a/hicn-light/src/hicn/config/configurationFile.c
+++ /dev/null
@@ -1,314 +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.
- */
-
-#ifndef _WIN32
-#include <unistd.h>
-#endif
-#include <ctype.h>
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_List.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/config/configuration.h>
-#include <hicn/config/configurationFile.h>
-#include <hicn/config/controlRoot.h>
-#include <hicn/config/controlState.h>
-
-struct configuration_file {
- Forwarder *forwarder;
- const char *filename;
- FILE *fh;
-
- size_t linesRead;
-
- // our custom state machine.
- ControlState *controlState;
-};
-
-/*
- * Called by a command to dispatch the correct command
- */
-struct iovec *_writeRead(ControlState *state, struct iovec *msg) {
- ConfigurationFile *configFile =
- (ConfigurationFile *)controlState_GetUserdata(state);
-
- parcAssertNotNull(msg, "Parameter msg must be non-null");
- struct iovec *response = configuration_DispatchCommand(
- forwarder_GetConfiguration(configFile->forwarder),
- ((header_control_message *)msg[0].iov_base)->commandID, msg, 0);
-
- return response;
-}
-
-/**
- * Removes leading whitespace (space + tab).
- *
- * If the string is all whitespace, the return value will point to the
- * terminating '\0'.
- *
- * @param [in] str A null-terminated c-string
- *
- * @retval non-null A pointer in to string of the first non-whitespace
- *
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-static char *_stripLeadingWhitespace(char *str) {
- while (isspace(*str)) {
- str++;
- }
- return str;
-}
-
-/**
- * Removes trailing whitespace
- *
- * Inserts a NULL after the last non-whitespace character, modiyfing the input
- * string.
- *
- * @param [in] str A null-terminated c-string
- *
- * @return non-null A pointer to the input string
- *
- * Example:
- * @code
- * {
- * <#example#>
- * }
- * @endcode
- */
-static char *_stripTrailingWhitespace(char *str) {
- char *p = str + strlen(str) - 1;
- while (p > str && isspace(*p)) {
- p--;
- }
-
- // cap it. If no whitespace, p+1 == str + strlen(str), so will overwrite the
- // current null. If all whitespace p+1 == str+1. For an empty string, p+1 =
- // str.
- *(p + 1) = 0;
-
- // this does not catch the case where the entire string is whitespace
- if (p == str && isspace(*p)) {
- *p = 0;
- }
-
- return str;
-}
-
-/**
- * Removed leading and trailing whitespace
- *
- * Modifies the input string (may add a NULL at the end). Will return
- * a pointer to the first non-whitespace character or the terminating NULL.
- *
- * @param [in] str A null-terminated c-string
- *
- * @return non-null A pointer in to the input string
- *
- * Example:
- * @code
- * {
- * <#example#>
- * }
- * @endcode
- */
-static char *_trim(char *str) {
- return _stripTrailingWhitespace(_stripLeadingWhitespace(str));
-}
-
-/**
- * Parse a string in to a PARCList with one word per element
- *
- * The string passed will be modified by inserting NULLs after each token.
- *
- * @param [in] str A c-string (will be modified)
- *
- * @retval non-null A PARCList where each item is a single word
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-static PARCList *_parseArgs(char *str) {
- PARCList *list =
- parcList(parcArrayList_Create(NULL), PARCArrayListAsPARCList);
-
- const char delimiters[] = " \t";
-
- char *token;
- token = strtok(str, delimiters);
- while (token != NULL) {
- if (strlen(token) > 0) {
- parcList_Add(list, strdup(token));
- }
- token = strtok(NULL, delimiters);
- }
- // while ((token = strsep(&str, delimiters)) != NULL) {
- // parcList_Add(list, token);
- // }
-
- return list;
-}
-
-// =============================================================
-
-static void _destroy(ConfigurationFile **configFilePtr) {
- ConfigurationFile *configFile = *configFilePtr;
- parcMemory_Deallocate((void **)&configFile->filename);
-
- if (configFile->fh != NULL) {
- fclose(configFile->fh);
- }
-
- controlState_Destroy(&configFile->controlState);
-}
-
-parcObject_ExtendPARCObject(ConfigurationFile, _destroy, NULL, NULL, NULL, NULL,
- NULL, NULL);
-
-parcObject_ImplementRelease(configurationFile, ConfigurationFile);
-
-ConfigurationFile *configurationFile_Create(Forwarder *forwarder,
- const char *filename) {
- parcAssertNotNull(forwarder, "Parameter hicn-fwd must be non-null");
- parcAssertNotNull(filename, "Parameter filename must be non-null");
-
- ConfigurationFile *configFile = parcObject_CreateInstance(ConfigurationFile);
-
- if (configFile) {
- configFile->linesRead = 0;
- configFile->forwarder = forwarder;
- configFile->filename =
- parcMemory_StringDuplicate(filename, strlen(filename));
- parcAssertNotNull(configFile->filename, "Could not copy string '%s'",
- filename);
-
- // setup the control state for the command parser: last parameter NULL
- // because
- // writeRead still not implemented from configuration file.
- configFile->controlState =
- controlState_Create(configFile, _writeRead, false,
- SRV_CTRL_IP, SRV_CTRL_PORT);
-
- // we do not register Help commands
- controlState_RegisterCommand(configFile->controlState,
- controlRoot_Create(configFile->controlState));
-
- // open the file and make sure we can read it
- configFile->fh = fopen(configFile->filename, "r");
-
- if (configFile->fh) {
- if (logger_IsLoggable(forwarder_GetLogger(forwarder),
- LoggerFacility_Config, PARCLogLevel_Debug)) {
- logger_Log(forwarder_GetLogger(forwarder), LoggerFacility_Config,
- PARCLogLevel_Debug, __func__, "Open config file %s",
- configFile->filename);
- }
- } else {
- if (logger_IsLoggable(forwarder_GetLogger(forwarder),
- LoggerFacility_Config, PARCLogLevel_Error)) {
- logger_Log(forwarder_GetLogger(forwarder), LoggerFacility_Config,
- PARCLogLevel_Error, __func__,
- "Could not open config file %s: (%d) %s",
- configFile->filename, errno, strerror(errno));
- }
-
- // failure cleanup the object -- this nulls it so final return null be
- // NULL
- configurationFile_Release(&configFile);
- }
- }
- return configFile;
-}
-
-bool configurationFile_Process(ConfigurationFile *configFile) {
- parcAssertNotNull(configFile, "Parameter configFile must be non-null");
-
- // default to a "true" return value and only set to false if we encounter an
- // error.
- bool success = true;
-
-#define BUFFERLEN 2048
- char buffer[BUFFERLEN];
-
- configFile->linesRead = 0;
-
- // always clear errors and fseek to start of file in case we get called
- // multiple times.
- clearerr(configFile->fh);
- rewind(configFile->fh);
-
- while (success && fgets(buffer, BUFFERLEN, configFile->fh) != NULL) {
- configFile->linesRead++;
-
- char *stripedBuffer = _trim(buffer);
- if (strlen(stripedBuffer) > 0) {
- if (stripedBuffer[0] != '#') {
- // not empty and not a comment
-
- // _parseArgs will modify the string
- char *copy =
- parcMemory_StringDuplicate(stripedBuffer, strlen(stripedBuffer));
- PARCList *args = _parseArgs(copy);
- char output[8192];
- CommandReturn result =
- controlState_DispatchCommand(configFile->controlState, args, output, sizeof(output));
-
- // we ignore EXIT from the configuration file
- if (result == CommandReturn_Failure) {
- if (logger_IsLoggable(forwarder_GetLogger(configFile->forwarder),
- LoggerFacility_Config, PARCLogLevel_Error)) {
- logger_Log(forwarder_GetLogger(configFile->forwarder),
- LoggerFacility_Config, PARCLogLevel_Error, __func__,
- "Error on input file %s line %d: %s",
- configFile->filename, configFile->linesRead,
- stripedBuffer);
- }
- success = false;
- }
- for(int i = 0; i < parcList_Size(args); i++){
- free(parcList_GetAtIndex(args, i));
- }
- parcList_Release(&args);
- parcMemory_Deallocate((void **)&copy);
- }
- }
- }
-
- if (ferror(configFile->fh)) {
- if (logger_IsLoggable(forwarder_GetLogger(configFile->forwarder),
- LoggerFacility_Config, PARCLogLevel_Error)) {
- logger_Log(forwarder_GetLogger(configFile->forwarder),
- LoggerFacility_Config, PARCLogLevel_Error, __func__,
- "Error on input file %s line %d: (%d) %s",
- configFile->filename, configFile->linesRead, errno,
- strerror(errno));
- }
- success = false;
- }
-
- return success;
-}
diff --git a/hicn-light/src/hicn/config/configurationFile.h b/hicn-light/src/hicn/config/configurationFile.h
deleted file mode 100644
index b748dfc15..000000000
--- a/hicn-light/src/hicn/config/configurationFile.h
+++ /dev/null
@@ -1,93 +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.
- */
-
-/**
- * @file configurationFile.h
- * @brief Accepts a filename and provides a means to read it into Configuration
- *
- * Reads a configuration file and converts the lines in to configuration
- * commands for use in Configuration.
- *
- * Accepts '#' lines as comments. Skips blank and whitespace-only lines.
- *
- */
-
-#ifndef configurationFile_h
-#define configurationFile_h
-
-#include <hicn/core/forwarder.h>
-
-struct configuration_file;
-typedef struct configuration_file ConfigurationFile;
-
-/**
- * Creates a ConfigurationFile to prepare to process the file
- *
- * Prepares the object and opens the file. Makes sure we can read the file.
- * Does not read the file or process any commands from the file.
- *
- * @param [in] hicn-light An allocated Forwarder to configure with the file
- * @param [in] filename The file to use
- *
- * @retval non-null An allocated ConfigurationFile that is readable
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-ConfigurationFile *configurationFile_Create(Forwarder *forwarder,
- const char *filename);
-
-/**
- * Reads the configuration file line-by-line and issues commands to
- * Configuration
- *
- * Reads the file line by line. Skips '#' and blank lines.
- *
- * Will stop on the first error. Lines already processed will not be un-done.
- *
- * @param [in] configFile An allocated ConfigurationFile
- *
- * @retval true The entire files was processed without error.
- * @retval false There was an error in the file.
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-bool configurationFile_Process(ConfigurationFile *configFile);
-
-// void configurationFile_ProcessForwardingStrategies(Configuration * config,
-// ConfigurationFile * configFile);
-
-/**
- * Closes the underlying file and releases memory
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in,out] configFilePtr An allocated ConfigurationFile that will be
- * NULL'd as output
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void configurationFile_Release(ConfigurationFile **configFilePtr);
-
-#endif /* defined(configurationFile_h) */
diff --git a/hicn-light/src/hicn/config/configurationListeners.c b/hicn-light/src/hicn/config/configurationListeners.c
deleted file mode 100644
index 31a0c4776..000000000
--- a/hicn-light/src/hicn/config/configurationListeners.c
+++ /dev/null
@@ -1,629 +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.
- */
-
-#ifndef _WIN32
-#include <arpa/inet.h>
-#include <unistd.h>
-#endif
-#include <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <hicn/core/system.h>
-#include <hicn/utils/interfaceSet.h>
-#include <hicn/utils/punting.h>
-
-#include <hicn/config/configurationListeners.h>
-#include <hicn/io/hicnListener.h>
-#include <hicn/io/tcpListener.h>
-#include <hicn/io/udpListener.h>
-
-#include <hicn/utils/address.h>
-#include <hicn/utils/addressList.h>
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static bool _setupHicnListenerOnInet4(Forwarder *forwarder,
- const char *symbolic, Address *address) {
- bool success = false;
-#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING)
- ListenerOps *ops =
- hicnListener_CreateInet(forwarder, (char *)symbolic, address);
- if (ops != NULL) {
- success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops);
- parcAssertTrue(success, "Failed to add Hicn listener %s to ListenerSet",
- symbolic);
- }
-#endif /* __APPLE__ _WIN32*/
- return success;
-}
-
-static bool _setupHicnListenerOnInet6(Forwarder *forwarder,
- const char *symbolic, Address *address) {
- bool success = false;
-#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING)
- ListenerOps *ops =
- hicnListener_CreateInet6(forwarder, (char *)symbolic, address);
- if (ops != NULL) {
- success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops);
- parcAssertTrue(success, "Failed to add Hicn listener %s to ListenerSet",
- symbolic);
- }
-#endif /* __APPLE__ _WIN32 */
- return success;
-}
-
-bool configurationListeners_Remove(const Configuration *config) {
- Logger *logger = configuration_GetLogger(config);
- if (logger_IsLoggable(logger, LoggerFacility_Config, PARCLogLevel_Warning)) {
- logger_Log(logger, LoggerFacility_Config, PARCLogLevel_Warning, __func__,
- "Removing a listener not supported: ingress %u control %s");
- }
-
- return false;
-}
-
-bool _AddPuntingInet(const Configuration *config, Punting *punting,
- unsigned ingressId) {
-#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING)
- struct sockaddr *addr = parcNetwork_SockAddress("0.0.0.0", 1234);
- if (addr == NULL) {
- printf("Error creating address\n");
- return false;
- }
-
- Address *fakeAddr = addressCreateFromInet((struct sockaddr_in *)addr);
-
- ListenerOps *listenerOps = listenerSet_Find(
- forwarder_GetListenerSet(configuration_GetForwarder(config)), ENCAP_HICN,
- fakeAddr);
- addressDestroy(&fakeAddr);
-
- if (listenerOps == NULL) {
- printf("the main listener (IPV4) does not exists\n");
- return false;
- }
-
- struct sockaddr_in puntingAddr;
-
- Address *address = puntingGetAddress(punting);
- if (address == NULL) return false;
-
- bool res = addressGetInet(address, &puntingAddr);
- if (!res) {
- printf("unable to read the punting address\n");
- return false;
- }
-
- char prefix[INET_ADDRSTRLEN];
- inet_ntop(AF_INET, &(puntingAddr.sin_addr), prefix, INET_ADDRSTRLEN);
-
- char len[5];
- sprintf(len, "%d", puntingPrefixLen(punting));
-
- char *prefixStr =
- malloc(strlen(prefix) + strlen(len) + 2); //+1 for the zero-terminator
- if (prefixStr == NULL) {
- printf("error while create the prefix string\n");
- return false;
- }
- strcpy(prefixStr, prefix);
- strcat(prefixStr, "/");
- strcat(prefixStr, len);
-
- res = hicnListener_Punting(listenerOps, prefixStr);
- if (!res) {
- printf("error while adding the punting rule\n");
- return false;
- }
-
- return true;
-#else
- return false;
-#endif
-}
-
-bool _AddPuntingInet6(const Configuration *config, Punting *punting,
- unsigned ingressId) {
-#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING)
- struct sockaddr *addr = parcNetwork_SockAddress("0::0", 1234);
- if (addr == NULL) {
- printf("Error creating address\n");
- return false;
- }
-
- Address *fakeAddr = addressCreateFromInet6((struct sockaddr_in6 *)addr);
-
- // comments:
- // EncapType: I use the Hicn encap since the punting is available only for
- // Hicn listeners LocalAddress: The only listern for which we need punting
- // rules is the main one, which has no address
- // so I create a fake empty address. This need to be consistent
- // with the address set at creation time
-
- ListenerOps *listenerOps = listenerSet_Find(
- forwarder_GetListenerSet(configuration_GetForwarder(config)), ENCAP_HICN,
- fakeAddr);
- addressDestroy(&fakeAddr);
-
- if (listenerOps == NULL) {
- printf("the main listener does not exists\n");
- return false;
- }
-
- struct sockaddr_in6 puntingAddr;
- bool res = addressGetInet6(puntingGetAddress(punting), &puntingAddr);
- if (!res) {
- printf("unable to read the punting address\n");
- return false;
- }
-
- char prefix[INET6_ADDRSTRLEN];
- inet_ntop(AF_INET6, &(puntingAddr.sin6_addr), prefix, INET6_ADDRSTRLEN);
-
- char len[5];
- sprintf(len, "%d", puntingPrefixLen(punting));
-
- char *prefixStr =
- malloc(strlen(prefix) + strlen(len) + 2); //+1 for the zero-terminator
- if (prefixStr == NULL) {
- printf("error while create the prefix string\n");
- return false;
- }
- strcpy(prefixStr, prefix);
- strcat(prefixStr, "/");
- strcat(prefixStr, len);
-
- res = hicnListener_Punting(listenerOps, prefixStr);
- if (!res) {
- printf("error while adding the punting rule\n");
- return false;
- }
-
- return true;
-#else
- return false;
-#endif
-}
-
-//============= LIGHT COMMAN ===============
-
-static bool _addEther(Configuration *config, add_listener_command *control,
- unsigned ingressId) {
- // Not implemented
- return false;
-}
-
-/*
- * Create a new IPV4/TCP listener.
- *
- * @param [in,out] forwarder The hicn-light forwarder instance
- * @param [in] listenerName The name of the listener
- * @param [in] addr4 The ipv4 address in network byte order
- * @param [in] port The port number in network byte order
- * @param [in] interfaceName The name of the interface to bind the socket
- *
- * return true if success, false otherwise
- */
-static bool _setupTcpListenerOnInet(Forwarder *forwarder, char *listenerName, ipv4_addr_t *addr4,
- uint16_t *port, char *interfaceName) {
- parcAssertNotNull(listenerName, "Parameter listenerName must be non-null");
-
- bool success = false;
-
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = *port;
- addr.sin_addr.s_addr = *addr4;
-
- ListenerOps *ops = tcpListener_CreateInet(forwarder, listenerName, addr, interfaceName);
- if (ops) {
- success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops);
-#if 0
- parcAssertTrue(success, "Failed to add TCP listener on %s to ListenerSet",
- addressToString(ops->getListenAddress(ops)));
-#endif
- }
- return success;
-}
-
-
-/*
- * Create a new IPV4/UDP listener.
- *
- * @param [in,out] forwarder The hicn-light forwarder instance
- * @param [in] listenerName The name of the listener
- * @param [in] addr4 The ipv4 address in network byte order
- * @param [in] port The port number in network byte order
- * @param [in] interfaceName The name of the interface to bind the socket
- *
- * return true if success, false otherwise
- */
-static bool _setupUdpListenerOnInet(Forwarder *forwarder, char *listenerName, ipv4_addr_t *addr4,
- uint16_t *port, char *interfaceName) {
- bool success = false;
-
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = *port;
- addr.sin_addr.s_addr = *addr4;
-
- ListenerOps *ops = udpListener_CreateInet(forwarder, listenerName, addr, interfaceName);
- if (ops) {
- success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops);
-#if 0
- parcAssertTrue(success, "Failed to add UDP listener on %s to ListenerSet",
- addressToString(ops->getListenAddress(ops)));
-#endif
- }
- return success;
-}
-
-
-/*
- * Create a new IPV6/TCP listener.
- *
- * @param [in,out] forwarder The hicn-light forwarder instance
- * @param [in] addr6 The ipv6 address in network byte order
- * @param [in] port The port number in network byte order
- * @param [in] interfaceName The name of the interface to bind the socket
- *
- * return true if success, false otherwise
- */
-static bool _setupTcpListenerOnInet6Light(Forwarder *forwarder, char *listenerName,
- ipv6_addr_t *addr6, uint16_t *port, char *interfaceName,
- uint32_t scopeId) {
- bool success = false;
-
- struct sockaddr_in6 addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin6_family = AF_INET6;
- addr.sin6_port = *port;
- addr.sin6_addr = *addr6;
- addr.sin6_scope_id = scopeId;
-
- ListenerOps *ops = tcpListener_CreateInet6(forwarder, listenerName, addr, interfaceName);
- if (ops) {
- success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops);
-#if 0
- parcAssertTrue(success, "Failed to add TCP6 listener on %s to ListenerSet",
- addressToString(ops->getListenAddress(ops)));
-#endif
- }
- return success;
-}
-
-
-/*
- * Create a new IPV6/UDP listener.
- *
- * @param [in,out] forwarder The hicn-light forwarder instance
- * @param [in] listenerName The name of the listener
- * @param [in] addr6 The ipv6 address in network byte order
- * @param [in] port The port number in network byte order
- * @param [in] interfaceName The name of the interface to bind the socket
- *
- * return true if success, false otherwise
- */
-static bool _setupUdpListenerOnInet6Light(Forwarder *forwarder, char *listenerName,
- ipv6_addr_t *addr6, uint16_t *port, char *interfaceName) {
- bool success = false;
-
- struct sockaddr_in6 addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin6_family = AF_INET6;
- addr.sin6_port = *port;
- addr.sin6_addr = *addr6;
- addr.sin6_scope_id = 0;
-
- ListenerOps *ops = udpListener_CreateInet6(forwarder, listenerName, addr, interfaceName);
- if (ops) {
- success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops);
-#if 0
- parcAssertTrue(success, "Failed to add UDP6 listener on %s to ListenerSet",
- addressToString(ops->getListenAddress(ops)));
-#endif
- }
- return success;
-}
-
-/*
- * Create a new HICN listener.
- *
- * @param [in] config The configuration
- * @param [in] control The control command
- * @param [in] port The connection id of the command
- *
- * return true if success, false otherwise
- */
-bool _addHicn(Configuration *config, add_listener_command *control,
- unsigned ingressId) {
- bool success = false;
- const char *symbolic = control->symbolic;
- Address *localAddress = NULL;
-
- switch (control->addressType) {
- case ADDR_INET: {
- localAddress =
- addressFromInaddr4Port(&control->address.v4.as_u32, &control->port);
- success = _setupHicnListenerOnInet4(configuration_GetForwarder(config),
- symbolic, localAddress);
- break;
- }
-
- case ADDR_INET6: {
- localAddress =
- addressFromInaddr6Port(&control->address.v6.as_in6addr, &control->port);
- success = _setupHicnListenerOnInet6(configuration_GetForwarder(config),
- symbolic, localAddress);
- break;
- }
-
- default:
- if (logger_IsLoggable(configuration_GetLogger(config),
- LoggerFacility_Config, PARCLogLevel_Warning)) {
- logger_Log(configuration_GetLogger(config), LoggerFacility_Config,
- PARCLogLevel_Warning, __func__,
- "Unsupported address type for HICN (ingress id %u): "
- "must be either IPV4 or IPV6",
- ingressId);
- }
- break;
- }
-
- if (success == true && localAddress != NULL) {
- if (logger_IsLoggable(configuration_GetLogger(config),
- LoggerFacility_Config, PARCLogLevel_Info)) {
- char * str = addressToString(localAddress);
- logger_Log(configuration_GetLogger(config), LoggerFacility_Config,
- PARCLogLevel_Info, __func__,
- "Setup hicn listener on address %s",
- str);
- parcMemory_Deallocate((void **)&str);
- }
- }
-
- addressDestroy(&localAddress);
-
- return success;
-}
-
-bool _addIP(Configuration *config, add_listener_command *control,
- unsigned ingressId) {
- bool success = false;
- char *symbolic = control->symbolic;
-
- switch (control->addressType) {
- case ADDR_INET: {
-
- if (control->connectionType == UDP_CONN) {
- success =
- _setupUdpListenerOnInet(configuration_GetForwarder(config), symbolic,
- &control->address.v4.as_u32, &control->port, control->interfaceName);
- } else if (control->connectionType == TCP_CONN) {
- success =
- _setupTcpListenerOnInet(configuration_GetForwarder(config), symbolic,
- &control->address.v4.as_u32, &control->port, control->interfaceName);
- }
- break;
- }
-
- case ADDR_INET6: {
- if (control->connectionType == UDP_CONN) {
- success = _setupUdpListenerOnInet6Light(
- configuration_GetForwarder(config), symbolic, &control->address.v6.as_in6addr,
- &control->port, control->interfaceName);
- } else if (control->connectionType == TCP_CONN) {
- success = _setupTcpListenerOnInet6Light(
- configuration_GetForwarder(config), symbolic, &control->address.v6.as_in6addr,
- &control->port, control->interfaceName, 0);
- }
- break;
- }
-
- default:
- if (logger_IsLoggable(configuration_GetLogger(config),
- LoggerFacility_Config, PARCLogLevel_Warning)) {
- char *addrStr = utils_CommandAddressToString(
- control->addressType, &control->address, &control->port);
- logger_Log(
- configuration_GetLogger(config), LoggerFacility_Config,
- PARCLogLevel_Warning, __func__,
- "Unsupported address type for IP encapsulation ingress id %u: %s",
- ingressId, addrStr);
- parcMemory_Deallocate((void **)&addrStr);
- }
- break;
- }
-
- if (success) {
- if (logger_IsLoggable(configuration_GetLogger(config),
- LoggerFacility_Config, PARCLogLevel_Info)) {
- char *addrStr = utils_CommandAddressToString(
- control->addressType, &control->address, &control->port);
- logger_Log(configuration_GetLogger(config), LoggerFacility_Config,
- PARCLogLevel_Info, __func__, "Setup listener on address %s",
- addrStr);
- parcMemory_Deallocate((void **)&addrStr);
- }
- }
-
- return success;
-}
-
-struct iovec *configurationListeners_Add(Configuration *config,
- struct iovec *request,
- unsigned ingressId) {
- header_control_message *header = request[0].iov_base;
- add_listener_command *control = request[1].iov_base;
-
- bool success = false;
-
- ListenerSet *listenerSet = forwarder_GetListenerSet(configuration_GetForwarder(config));
- int listenerId = listenerSet_FindIdByListenerName(listenerSet, control->symbolic);
-
- if (listenerId < 0) {
- if (control->listenerMode == ETHER_MODE) {
- parcTrapNotImplemented("Add Ethernet Listener is not supported");
- success = _addEther(config, control, ingressId);
- // it is a failure
- } else if (control->listenerMode == IP_MODE) {
- success = _addIP(config, control, ingressId);
- } else if (control->listenerMode == HICN_MODE) {
- success = _addHicn(config, control, ingressId);
- } else {
- Logger *logger = configuration_GetLogger(config);
- if (logger_IsLoggable(logger, LoggerFacility_Config,
- PARCLogLevel_Warning)) {
- logger_Log(logger, LoggerFacility_Config, PARCLogLevel_Warning, __func__,
- "Unsupported encapsulation mode (ingress id %u)", ingressId);
- }
- }
- }
-
- // generate ACK/NACK
- struct iovec *response;
-
- if (success) { // ACK
- response = utils_CreateAck(header, control, sizeof(add_listener_command));
- } else { // NACK
- response = utils_CreateNack(header, control, sizeof(add_listener_command));
- }
-
- return response;
-}
-
-struct iovec *configurationListeners_AddPunting(Configuration *config,
- struct iovec *request,
- unsigned ingressId) {
- header_control_message *header = request[0].iov_base;
- add_punting_command *control = request[1].iov_base;
-
- const char *symbolicOrConnid = control->symbolicOrConnid;
- uint32_t len = control->len;
- in_port_t port = htons(1234);
- bool success = false;
-
- if (control->addressType == ADDR_INET) {
- Address *address = addressFromInaddr4Port(&control->address.v4.as_u32, &port);
- Punting *punting = puntingCreate(symbolicOrConnid, address, len);
- success = _AddPuntingInet(config, punting, ingressId);
- addressDestroy(&address);
- } else if (control->addressType == ADDR_INET6) {
- Address *address = addressFromInaddr6Port(&control->address.v6.as_in6addr, &port);
- Punting *punting = puntingCreate(symbolicOrConnid, address, len);
- success = _AddPuntingInet6(config, punting, ingressId);
- addressDestroy(&address);
- } else {
- printf("Invalid IP type.\n"); // will generate a Nack
- return utils_CreateNack(header, control, sizeof(add_punting_command));
- }
-
- // generate ACK/NACK
- struct iovec *response;
- if (success) { // ACK
- response = utils_CreateAck(header, control, sizeof(add_punting_command));
- } else { // NACK
- response = utils_CreateNack(header, control, sizeof(add_punting_command));
- }
-
- return response;
-}
-
-//=========================== INITIAL LISTENERS ====================
-
-static void _setupListenersOnAddress(Forwarder *forwarder, char *listenerName,
- const Address *address, uint16_t port,
- char *interfaceName) {
- address_type type = addressGetType(address);
- switch (type) {
- case ADDR_INET: {
- struct sockaddr_in tmp;
- addressGetInet(address, &tmp);
- _setupTcpListenerOnInet(forwarder, listenerName, &tmp.sin_addr.s_addr, &port, interfaceName);
- break;
- }
-
- case ADDR_INET6: {
- struct sockaddr_in6 tmp;
- addressGetInet6(address, &tmp);
- _setupTcpListenerOnInet6Light(forwarder, listenerName, &tmp.sin6_addr, &port, interfaceName,
- tmp.sin6_scope_id);
- break;
- }
-
- case ADDR_LINK:
- // not used
- break;
-
- default:
- // dont' know how to handle this, so no listeners
- break;
- }
-}
-
-void configurationListeners_SetupAll(const Configuration *config, uint16_t port,
- const char *localPath) {
- Forwarder *forwarder = configuration_GetForwarder(config);
- InterfaceSet *set = system_Interfaces(forwarder);
-
- size_t interfaceSetLen = interfaceSetLength(set);
- for (size_t i = 0; i < interfaceSetLen; i++) {
- Interface *iface = interfaceSetGetByOrdinalIndex(set, i);
-
- const AddressList *addresses = interfaceGetAddresses(iface);
- size_t addressListLen = addressListLength(addresses);
-
- for (size_t j = 0; j < addressListLen; j++) {
- const Address *address = addressListGetItem(addresses, j);
-
- // Do not start on link address
- char listenerName[SYMBOLIC_NAME_LEN];
-#if defined(__ANDROID__) || defined(_WIN32)
- snprintf(listenerName, SYMBOLIC_NAME_LEN, "local_%zu", i);
-#else
- snprintf(listenerName, SYMBOLIC_NAME_LEN, "local_%ld", i);
-#endif
- if (addressGetType(address) != ADDR_LINK) {
- _setupListenersOnAddress(forwarder, listenerName, address, port,
- (char *)interfaceGetName(iface));
- }
- }
- }
-
- interfaceSetDestroy(&set);
-}
-
-void configurationListeners_SetutpLocalIPv4(const Configuration *config,
- uint16_t port) {
- Forwarder *forwarder = configuration_GetForwarder(config);
- in_addr_t addr = inet_addr("127.0.0.1");
- uint16_t network_byte_order_port = htons(port);
-
- char listenerNameUdp[SYMBOLIC_NAME_LEN] = "lo_udp";
- char listenerNameTcp[SYMBOLIC_NAME_LEN] = "lo_tcp";
- char *loopback_interface = "lo";
- _setupUdpListenerOnInet(forwarder, listenerNameUdp,(ipv4_addr_t *)&(addr),
- &network_byte_order_port, loopback_interface);
- _setupTcpListenerOnInet(forwarder, listenerNameTcp, (ipv4_addr_t *)&(addr),
- &network_byte_order_port, loopback_interface);
-}
diff --git a/hicn-light/src/hicn/config/configurationListeners.h b/hicn-light/src/hicn/config/configurationListeners.h
deleted file mode 100644
index b09ad5167..000000000
--- a/hicn-light/src/hicn/config/configurationListeners.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file configurationListeners.h
- * @brief Configuration routines related to Listeners
- *
- * Adding and removing listeners.
- *
- */
-
-#ifndef configurationListeners_h
-#define configurationListeners_h
-
-#include <hicn/config/configuration.h>
-#include <hicn/core/forwarder.h>
-
-#include <hicn/utils/address.h>
-
-/**
- * Setup udp, tcp, and local listeners
- *
- * Will bind to all available IP protocols on the given port.
- * Does not add Ethernet listeners.
- *
- * @param port is the UPD and TCP port to use
- * @param localPath is the AF_UNIX path to use, if NULL no AF_UNIX listener is
- * setup
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void configurationListeners_SetupAll(const Configuration *config, uint16_t port,
- const char *localPath);
-
-void configurationListeners_SetutpLocalIPv4(const Configuration *config,
- uint16_t port);
-
-bool configurationListeners_Remove(const Configuration *config);
-
-// light functions
-
-/**
- * Add new listener.
- *
- * @param request The request coming from hicnLightControl or the
- * configuration file. The bytes in the request are
- * ordered following the network byte order convention.
- *
- * @param ingressId The connection id of the incoming request.
- */
-struct iovec *configurationListeners_Add(Configuration *config,
- struct iovec *request,
- unsigned ingressId);
-
-struct iovec *configurationListeners_AddPunting(Configuration *config,
- struct iovec *request,
- unsigned ingressId);
-
-#endif /* defined(configurationListeners_h) */
diff --git a/hicn-light/src/hicn/config/configuration_file.c b/hicn-light/src/hicn/config/configuration_file.c
new file mode 100644
index 000000000..8649e0143
--- /dev/null
+++ b/hicn-light/src/hicn/config/configuration_file.c
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+#include <ctype.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <hicn/ctrl/hicn-light.h>
+#include <hicn/config/configuration_file.h>
+#include <hicn/util/sstrncpy.h>
+
+#include "commands.h"
+#include <hicn/ctrl/parse.h>
+
+#define BUFFERLEN 2048
+
+static char *_trim(char *str) {
+ char *end;
+
+ // Trim leading space
+ while (isspace((unsigned char)*str)) str++;
+
+ if (*str == 0) // All spaces?
+ return str;
+
+ // Trim trailing space
+ end = str + strnlen_s(str, BUFFERLEN) - 1;
+ while (end > str && isspace((unsigned char)*end)) end--;
+
+ // Write new null terminator character
+ end[1] = '\0';
+
+ return str;
+}
+
+bool configuration_file_process(forwarder_t *forwarder, const char *filename) {
+ assert(forwarder);
+ assert(filename);
+
+ int linesRead = 0;
+ FILE *f = fopen(filename, "r");
+ if (!f) {
+ ERROR("Could not open configuration file %s: (%d) %s", filename, errno,
+ strerror(errno));
+ goto ERR_OPEN;
+ }
+ DEBUG("Opening configuration file %s", filename);
+
+ char buffer[BUFFERLEN];
+ bool success = true;
+
+#if 0
+ // TODO(eloparco): We could use a fake socket since we only need the vft
+ hc_sock_t *s = hc_sock_create(FORWARDER_TYPE_HICNLIGHT, NULL);
+ if (!s) {
+ ERROR("Could not create socket");
+ goto ERR_SOCK;
+ }
+#else
+ hc_sock_initialize_module(NULL);
+#endif
+
+ while (success && fgets(buffer, BUFFERLEN, f) != NULL) {
+ linesRead++;
+
+ char *cmd = _trim(buffer);
+ if (strnlen_s(cmd, BUFFERLEN) <= 0) continue;
+ if (cmd[0] == '#') continue;
+
+ INFO("Processing command: %s", cmd);
+ hc_command_t command = {};
+ if (parse(cmd, &command) < 0) {
+ ERROR("Error parsing command : '%s'", cmd);
+ continue;
+ }
+
+ /* Serialize request into message */
+ // hc_msg_t msg;
+ uint8_t msg[1024];
+ ssize_t msg_len = hc_light_command_serialize(
+ command.action, command.object_type, &command.object, msg);
+ switch (msg_len) {
+ case -1:
+ case -2:
+ ERROR("Command '%s' not supported", cmd);
+ continue;
+ case -3:
+ ERROR("Error during command serialization '%s'", cmd);
+ continue;
+ default:
+ break;
+ }
+
+ size_t _unused;
+ command_process(forwarder, (uint8_t *)msg, CONNECTION_ID_UNDEFINED,
+ &_unused);
+ }
+
+#if 0
+ hc_sock_free(s);
+#endif
+
+ if (ferror(f)) {
+ ERROR("Error on input file %s line %d: (%d) %s", filename, linesRead, errno,
+ strerror(errno));
+ goto ERR_READ;
+ }
+ fclose(f);
+ return true;
+
+#if 0
+ERR_SOCK:
+ hc_sock_free(s);
+#endif
+ERR_READ:
+ fclose(f);
+ERR_OPEN:
+ return false;
+}
diff --git a/hicn-light/src/hicn/config/configuration_file.h b/hicn-light/src/hicn/config/configuration_file.h
new file mode 100644
index 000000000..03599d4f4
--- /dev/null
+++ b/hicn-light/src/hicn/config/configuration_file.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file configuration_file.h
+ * @brief Accepts a filename and provides a means to read it into Configuration
+ *
+ * Reads a configuration file and converts the lines in to configuration
+ * commands for use in Configuration.
+ *
+ * Accepts '#' lines as comments. Skips blank and whitespace-only lines.
+ *
+ */
+
+#ifndef configuration_file_h
+#define configuration_file_h
+
+#include <hicn/core/forwarder.h>
+#include <hicn/ctrl/hicn-light.h>
+
+/**
+ * Configure hicn-light by reading a configuration file line-by-line and
+ * issueing commands to the forwarder.
+ *
+ * The configuration file is a set of lines, just like used in hicnLightControl.
+ * You need to have "add listener" lines in the file to receive connections. No
+ * default listeners are configured.
+ *
+ * This function reads the file line by line, skipping '#' and blank lines, and
+ * will stop on the first error. Lines already processed will not be un-done.
+ *
+ * @param[in] forwarder An allocated forwarder_t
+ * @param[in] filename The path to the configuration file
+ *
+ * @retval true The entire files was processed without error.
+ * @retval false There was an error in the file.
+ *
+ * Example:
+ * @code
+ * <#example#>
+ * @endcode
+ */
+bool configuration_file_process(forwarder_t* forwarder, const char* filename);
+
+#endif /* defined(configuration_file_h) */
diff --git a/hicn-light/src/hicn/config/controlAdd.c b/hicn-light/src/hicn/config/controlAdd.c
deleted file mode 100644
index cac8e7913..000000000
--- a/hicn-light/src/hicn/config/controlAdd.c
+++ /dev/null
@@ -1,128 +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/hicn-light/config.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlAdd.h>
-#include <hicn/config/controlAddConnection.h>
-#include <hicn/config/controlAddListener.h>
-#include <hicn/config/controlAddPunting.h>
-#include <hicn/config/controlAddRoute.h>
-#ifdef WITH_POLICY
-#include <hicn/config/controlAddPolicy.h>
-#endif /* WITH_POLICY */
-
-// ===================================================
-
-static void _controlAdd_Init(CommandParser *parser, CommandOps *ops);
-
-static CommandReturn _controlAdd_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static CommandReturn _controlAdd_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-static const char *command_add = "add";
-static const char *help_command_add = "help add";
-
-CommandOps *webControlAdd_Create(ControlState *state) {
- return commandOps_Create(state, command_add, _controlAdd_Init,
- _controlAdd_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlAdd_CreateHelp(ControlState *state) {
- return commandOps_Create(state, help_command_add, NULL,
- _controlAdd_HelpExecute, commandOps_Destroy);
-}
-
-// ===================================================
-
-static CommandReturn _controlAdd_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- CommandOps *ops_add_connection = controlAddConnection_Create(NULL);
- CommandOps *ops_add_route = controlAddRoute_Create(NULL);
- CommandOps *ops_add_punting = controlAddPunting_Create(NULL);
- CommandOps *ops_add_listener = controlAddListener_Create(NULL);
-#ifdef WITH_POLICY
- CommandOps *ops_add_policy = controlAddPolicy_Create(NULL);
-#endif /* WITH_POLICY */
-#ifdef WITH_POLICY
- snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n %s\n %s\n\n",
- ops_add_connection->command,
- ops_add_route->command,
- ops_add_punting->command,
- ops_add_listener->command,
- ops_add_policy->command);
-#else
- snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n %s\n\n",
- ops_add_connection->command,
- ops_add_route->command,
- ops_add_punting->command,
- ops_add_listener->command);
-
-#endif /* WITH_POLICY */
-
- commandOps_Destroy(&ops_add_connection);
- commandOps_Destroy(&ops_add_route);
- commandOps_Destroy(&ops_add_punting);
- commandOps_Destroy(&ops_add_listener);
-#ifdef WITH_POLICY
- commandOps_Destroy(&ops_add_policy);
-#endif /* WITH_POLICY */
- return CommandReturn_Success;
-}
-
-static void _controlAdd_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- controlState_RegisterCommand(state, controlAddListener_HelpCreate(state));
- controlState_RegisterCommand(state, controlAddListener_Create(state));
- controlState_RegisterCommand(state, controlAddConnection_HelpCreate(state));
- controlState_RegisterCommand(state, controlAddRoute_HelpCreate(state));
- controlState_RegisterCommand(state, controlAddConnection_Create(state));
- controlState_RegisterCommand(state, controlAddRoute_Create(state));
- controlState_RegisterCommand(state, controlAddPunting_Create(state));
- controlState_RegisterCommand(state, controlAddPunting_HelpCreate(state));
-#ifdef WITH_POLICY
- controlState_RegisterCommand(state, controlAddPolicy_HelpCreate(state));
- controlState_RegisterCommand(state, controlAddPolicy_Create(state));
-#endif /* WITH_POLICY */
-}
-
-static CommandReturn _controlAdd_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlAdd_HelpExecute(parser, ops, args, output, output_size);
-}
diff --git a/hicn-light/src/hicn/config/controlAddConnection.c b/hicn-light/src/hicn/config/controlAddConnection.c
deleted file mode 100644
index eed37f3ad..000000000
--- a/hicn-light/src/hicn/config/controlAddConnection.c
+++ /dev/null
@@ -1,450 +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/hicn-light/config.h>
-
-#include <ctype.h>
-#include <parc/assert/parc_Assert.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <hicn/config/controlAddConnection.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-// ===================================================
-
-static void _controlAddConnection_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlAddConnection_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddConnection_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-#ifdef __linux__
-static CommandReturn _controlAddConnection_HicnHelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddConnection_HicnExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-#endif
-
-static CommandReturn _controlAddConnection_UdpHelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddConnection_UdpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static CommandReturn _controlAddConnection_TcpHelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddConnection_TcpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-static const char *_commandAddConnection = "add connection";
-#ifdef __linux__
-static const char *_commandAddConnectionHicn = "add connection hicn";
-#endif
-static const char *_commandAddConnectionUdp = "add connection udp";
-static const char *_commandAddConnectionTcp = "add connection tcp";
-static const char *_commandAddConnectionHelp = "help add connection";
-#ifdef __linux__
-static const char *_commandAddConnectionHicnHelp = "help add connection hicn";
-#endif
-static const char *_commandAddConnectionUdpHelp = "help add connection udp";
-static const char *_commandAddConnectionTcpHelp = "help add connection tcp";
-
-// ===================================================
-
-CommandOps *controlAddConnection_Create(ControlState *state) {
- return commandOps_Create(state, _commandAddConnection,
- _controlAddConnection_Init,
- _controlAddConnection_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlAddConnection_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddConnectionHelp, NULL,
- _controlAddConnection_HelpExecute,
- commandOps_Destroy);
-}
-
-// ===================================================
-
-#ifdef __linux__
-static CommandOps *_controlAddConnection_HicnCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddConnectionHicn, NULL,
- _controlAddConnection_HicnExecute,
- commandOps_Destroy);
-}
-#endif
-
-static CommandOps *_controlAddConnection_UdpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddConnectionUdp, NULL,
- _controlAddConnection_UdpExecute,
- commandOps_Destroy);
-}
-
-static CommandOps *_controlAddConnection_TcpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddConnectionTcp, NULL,
- _controlAddConnection_TcpExecute,
- commandOps_Destroy);
-}
-
-// ===================================================
-#ifdef __linux__
-static CommandOps *_controlAddConnection_HicnHelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddConnectionHicnHelp, NULL,
- _controlAddConnection_HicnHelpExecute,
- commandOps_Destroy);
-}
-#endif
-
-static CommandOps *_controlAddConnection_UdpHelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddConnectionUdpHelp, NULL,
- _controlAddConnection_UdpHelpExecute,
- commandOps_Destroy);
-}
-
-static CommandOps *_controlAddConnection_TcpHelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddConnectionTcpHelp, NULL,
- _controlAddConnection_TcpHelpExecute,
- commandOps_Destroy);
-}
-
-// ===================================================
-
-static CommandReturn _controlAddConnection_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
-#ifdef __linux__
- snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n\n",
- _commandAddConnectionHicn,
- _commandAddConnectionUdp,
- _commandAddConnectionTcp);
-#else
- snprintf(output, output_size, "Available commands:\n %s\n %s\n\n",
- _commandAddConnectionUdp,
- _commandAddConnectionTcp);
-#endif
- return CommandReturn_Success;
-}
-
-static void _controlAddConnection_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
-#ifdef __linux__
- controlState_RegisterCommand(state,
- _controlAddConnection_HicnHelpCreate(state));
-#endif
- controlState_RegisterCommand(state,
- _controlAddConnection_UdpHelpCreate(state));
- controlState_RegisterCommand(state,
- _controlAddConnection_TcpHelpCreate(state));
-#ifdef __linux__
- controlState_RegisterCommand(state, _controlAddConnection_HicnCreate(state));
-#endif
- controlState_RegisterCommand(state, _controlAddConnection_UdpCreate(state));
- controlState_RegisterCommand(state, _controlAddConnection_TcpCreate(state));
-}
-
-static CommandReturn _controlAddConnection_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlAddConnection_HelpExecute(parser, ops, args, output, output_size);
-}
-
-// ===================================================
-// functions general to all connection types
-
-/**
- * Create a tunnel in the forwarder based on the addresses
- *
- * Caller retains ownership of memory.
- * The symbolic name will be used to refer to this connection. It must be unqiue
- * otherwise the forwarder will reject this commend.
- *
- * @param [in] parser An allocated CommandParser
- * @param [in] ops Allocated CommandOps (needed to extract ControlState)
- * @param [in] localAddress the local IP and port. The port may be the wildcard
- * value.
- * @param [in] remoteAddress The remote IP and port (both must be specified)
- * @param [in] tunnelType The tunneling protocol
- * @param [in] symbolic The symbolic name for the connection (must be unique)
- * @param [in] output Output buffer
- * @param [in] output_size Output buffer size
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * {
- * struct sockaddr_in *anyAddress = parcNetwork_SockInet4AddressAny();
- * struct sockaddr_in *remote =
- * parcNetwork_SockInet4Address("192.168.1.2", 9695);
- *
- * Address *localAddress = addressCreateFromInet(anyAddress);
- * Address *remoteAddress = addressCreateFromInet(remote);
- *
- * control_CreateTunnel(state, localAddress, remoteAddress, IPTUN_TCP,
- * "conn7");
- *
- * addressDestroy(&localAddress);
- * addressDestroy(&remoteAddress);
- * parcMemory_Deallocate((void **)&remote);
- * parcMemory_Deallocate((void **)&anyAddress);
- * }
- * @endcode
- */
-
-static CommandReturn _controlAddConnection_CreateTunnel(CommandParser *parser,
- CommandOps *ops, const char *local_ip,
- const char *local_port,
- const char *remote_ip,
- const char *remote_port,
- connection_type tunnelType,
- const char *symbolic,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
- // a request like this always has an interface index of 0 [FIELD REMOVED]
- // unsigned int interfaceIndex = 0;
-
- // allocate command payload
- add_connection_command *addConnectionCommand =
- parcMemory_AllocateAndClear(sizeof(add_connection_command));
-
- // check and set IP addresses
- if (inet_pton(AF_INET, remote_ip, &addConnectionCommand->remoteIp.v4.as_u32) ==
- 1 &&
- inet_pton(AF_INET, local_ip, &addConnectionCommand->localIp.v4.as_u32) == 1) {
- addConnectionCommand->ipType = ADDR_INET;
-
- } else if (inet_pton(AF_INET6, remote_ip,
- &addConnectionCommand->remoteIp.v6.as_in6addr) == 1 &&
- inet_pton(AF_INET6, local_ip,
- &addConnectionCommand->localIp.v6.as_in6addr) == 1) {
- addConnectionCommand->ipType = ADDR_INET6;
-
- } else {
- snprintf(output, output_size, "Error: local address %s not same type as remote address %s\n",
- local_ip, remote_ip);
- parcMemory_Deallocate(&addConnectionCommand);
- return CommandReturn_Failure;
- }
-
- // Fill remaining payload fields
- addConnectionCommand->connectionType = tunnelType;
- strcpy(addConnectionCommand->symbolic, symbolic);
- addConnectionCommand->remotePort = htons((uint16_t)atoi(remote_port));
- addConnectionCommand->localPort = htons((uint16_t)atoi(local_port));
-
- // send message and receive response
- struct iovec *response =
- utils_SendRequest(state, ADD_CONNECTION, addConnectionCommand,
- sizeof(add_connection_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddConnection_IpHelp(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- const char *protocol,
- char *output,
- size_t output_size) {
- snprintf(output, output_size,
- #ifdef __linux__
- "add connection hicn <symbolic> <remote_ip> <local_ip>\n"
- #endif
- "add connection udp <symbolic> <remote_ip> <port> <local_ip> <port>\n"
- " <symbolic> : symbolic name, e.g. 'conn1' (must be "
- "unique, start with alpha)\n"
- " <remote_ip> : the IPv4 or IPv6 or hostname of the remote system\n"
- " <local_ip> : optional local IP address to bind to\n"
- "\n");
- return CommandReturn_Success;
-}
-
-#ifdef __linux__
-static CommandReturn _controlAddConnection_HicnHelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- _controlAddConnection_IpHelp(parser, ops, args, "hicn", output, output_size);
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddConnection_HicnExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- static const int _indexSymbolic = 3;
- static const int _indexRemAddr = 4;
- static const int _indexLocAddr = 5;
-
- if (parcList_Size(args) != 6) {
- _controlAddConnection_HicnHelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- char *symbolic = parcList_GetAtIndex(args, _indexSymbolic);
-
- if (!utils_ValidateSymbolicName(symbolic)) {
- snprintf(output, output_size, "Invalid symbolic name. Must begin with alpha and contain only "
- "alphanum.\n");
- return CommandReturn_Failure;
- }
-
- char *remote_ip = parcList_GetAtIndex(args, _indexRemAddr);
- char *local_ip = parcList_GetAtIndex(args, _indexLocAddr);
- char *port = "1234"; // this is a random port number that will be ignored
-
- return _controlAddConnection_CreateTunnel(
- parser, ops, local_ip, port, remote_ip, port, HICN_CONN, symbolic, output, output_size);
-}
-#endif
-
-static CommandReturn _controlAddConnection_UdpHelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- _controlAddConnection_IpHelp(parser, ops, args, "udp", output, output_size);
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddConnection_UdpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- static const int _indexSymbolic = 3;
- static const int _indexRemAddr = 4;
- static const int _indexRemPort = 5;
- static const int _indexLocAddr = 6;
- static const int _indexLocPort = 7;
-
- if (parcList_Size(args) != 8) {
- _controlAddConnection_UdpHelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- char *symbolic = parcList_GetAtIndex(args, _indexSymbolic);
- size_t offset = 0;
- if (!utils_ValidateSymbolicName(symbolic)) {
- snprintf(output, output_size,
- "Invalid symbolic name. Must begin with alpha and contain only "
- "alphanum.\n");
- return CommandReturn_Failure;
- }
-
- char *remote_ip = parcList_GetAtIndex(args, _indexRemAddr);
- char *local_ip = parcList_GetAtIndex(args, _indexLocAddr);
-
- char *remote_port = parcList_GetAtIndex(args, _indexRemPort);
- char *local_port = parcList_GetAtIndex(args, _indexLocPort);
-
- return _controlAddConnection_CreateTunnel(parser, ops, local_ip, local_port,
- remote_ip, remote_port, UDP_CONN,
- symbolic,
- output + offset, output_size - offset);
-}
-
-static CommandReturn _controlAddConnection_TcpHelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- _controlAddConnection_IpHelp(parser, ops, args, "tcp", output, output_size);
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddConnection_TcpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- static const int _indexSymbolic = 3;
- static const int _indexRemAddr = 4;
- static const int _indexRemPort = 5;
- static const int _indexLocAddr = 6;
- static const int _indexLocPort = 7;
-
- if (parcList_Size(args) != 8) {
- _controlAddConnection_UdpHelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- char *symbolic = parcList_GetAtIndex(args, _indexSymbolic);
- if (!utils_ValidateSymbolicName(symbolic)) {
- snprintf(output, output_size, "Invalid symbolic name. Must begin with alpha and contain only "
- "alphanum.\n");
- return CommandReturn_Failure;
- }
-
- char *remote_ip = parcList_GetAtIndex(args, _indexRemAddr);
- char *local_ip = parcList_GetAtIndex(args, _indexLocAddr);
-
- char *remote_port = parcList_GetAtIndex(args, _indexRemPort);
- char *local_port = parcList_GetAtIndex(args, _indexLocPort);
-
- return _controlAddConnection_CreateTunnel(parser, ops, local_ip, local_port,
- remote_ip, remote_port, TCP_CONN,
- symbolic,
- output, output_size);
-}
diff --git a/hicn-light/src/hicn/config/controlAddConnection.h b/hicn-light/src/hicn/config/controlAddConnection.h
deleted file mode 100644
index 546388efc..000000000
--- a/hicn-light/src/hicn/config/controlAddConnection.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.
- */
-
-/**
- * @file control_AddConnection.h
- * @brief Command-line "add connection" node
- *
- * Implements the "add connection" node of the CLI tree
- *
- *
- */
-
-#ifndef controlAddConnection_h
-#define controlAddConnection_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlAddConnection_Create(ControlState *state);
-CommandOps *controlAddConnection_HelpCreate(ControlState *state);
-#endif // controlAddConnection_h
diff --git a/hicn-light/src/hicn/config/controlAddListener.c b/hicn-light/src/hicn/config/controlAddListener.c
deleted file mode 100644
index df84c4691..000000000
--- a/hicn-light/src/hicn/config/controlAddListener.c
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-
-#include <ctype.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <hicn/config/controlAddListener.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlAddListener_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddListener_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *command_add_listener = "add listener";
-static const char *command_help_add_listener = "help add listener";
-
-CommandOps *controlAddListener_Create(ControlState *state) {
- return commandOps_Create(state, command_add_listener, NULL,
- _controlAddListener_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlAddListener_HelpCreate(ControlState *state) {
- return commandOps_Create(state, command_help_add_listener, NULL,
- _controlAddListener_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static const int _indexProtocol = 2;
-static const int _indexSymbolic = 3;
-static const int _indexAddress = 4;
-static const int _indexPort = 5;
-static const int _indexInterfaceName = 6;
-
-static CommandReturn _controlAddListener_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size,
- "commands:\n"
-#ifdef __linux__
- " add listener hicn <symbolic> <localAddress> \n"
-#endif
- " add listener udp <symbolic> <localAddress> <port> <interface>\n"
- " add listener tcp <symbolic> <localAddress> <port> <interface>\n"
- "\n"
- " symbolic: User defined name for listener, must start with "
- "alpha and be alphanum\n"
-#ifdef __linux__
- " protocol: hicn | udp\n"
-#else
- " protocol: udp\n"
-#endif
- " localAddress: IPv4 or IPv6 address (or prefix protocol = hicn) "
- "assigend to the local interface\n"
- " port: Udp port\n"
- " interface: interface\n"
- "\n"
- "Notes:\n"
- " The symblic name must be unique or the source will reject it.\n"
-#ifdef __linux__
- " If protocol = hicn: the address 0::0 indicates the main listern, "
- "for which we can set punting rules.\n"
-#endif
- );
- return CommandReturn_Success;
-}
-
-static CommandReturn _CreateListener(CommandParser *parser, CommandOps *ops,
- const char *symbolic, const char *addr,
- const char *port, char *interfaceName, listener_mode mode,
- connection_type type,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- // allocate command payload
- add_listener_command *addListenerCommand =
- parcMemory_AllocateAndClear(sizeof(add_listener_command));
-
- // check and set IP address
- if (inet_pton(AF_INET, addr, &addListenerCommand->address.v4.as_u32) == 1) {
- addListenerCommand->addressType = ADDR_INET;
-
- } else if (inet_pton(AF_INET6, addr, &addListenerCommand->address.v6.as_in6addr) == 1) {
- addListenerCommand->addressType = ADDR_INET6;
-
- } else {
- snprintf(output, output_size, "Error: %s is not a valid network address \n", addr);
- parcMemory_Deallocate(&addListenerCommand);
- return CommandReturn_Failure;
- }
-
- // Fill remaining payload fields
- size_t name_size = strlen((const char *)interfaceName);
- if(name_size > SYMBOLIC_NAME_LEN){
- //cut the string
- name_size = SYMBOLIC_NAME_LEN;
- }
-
- memcpy(addListenerCommand->interfaceName, interfaceName, name_size);
- addListenerCommand->listenerMode = mode;
- addListenerCommand->connectionType = type;
- addListenerCommand->port = htons((uint16_t)atoi(port));
- strcpy(addListenerCommand->symbolic, symbolic);
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, ADD_LISTENER, addListenerCommand, sizeof(add_listener_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddListener_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 5 && parcList_Size(args) != 7) {
- _controlAddListener_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- CommandReturn result = CommandReturn_Failure;
-
- const char *symbolic = parcList_GetAtIndex(args, _indexSymbolic);
-
- if (!utils_ValidateSymbolicName(symbolic)) {
- snprintf(output, output_size,
- "Error: symbolic name must begin with an alpha and be alphanum "
- "after\n");
- return result;
- }
-
- const char *protocol = parcList_GetAtIndex(args, _indexProtocol);
- const char *host = parcList_GetAtIndex(args, _indexAddress);
- char *interfaceName = parcList_GetAtIndex(args, _indexInterfaceName);
- if ((strcasecmp("hicn", protocol) == 0)) {
- const char *port =
- "1234"; // this is a random port number that will be ignored
-
- // here we discard the prefix len if it exists, since we don't use it in
- // code but we let libhicn to find the right ip address.
- return _CreateListener(parser, ops, symbolic, host, port, "hicn", HICN_MODE,
- HICN_CONN, output, output_size);
- }
- const char *port = parcList_GetAtIndex(args, _indexPort);
-
- if ((strcasecmp("udp", protocol) == 0)) {
- return _CreateListener(parser, ops, symbolic, host, port, interfaceName, IP_MODE,
- UDP_CONN, output, output_size);
- } else if ((strcasecmp("tcp", protocol) == 0)) {
- return _CreateListener(parser, ops, symbolic, host, port, interfaceName, IP_MODE,
- TCP_CONN, output, output_size);
- } else {
- _controlAddListener_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- if (result == CommandReturn_Failure) snprintf(output, output_size, "creation failed\n");
-
- return result;
-}
diff --git a/hicn-light/src/hicn/config/controlAddListener.h b/hicn-light/src/hicn/config/controlAddListener.h
deleted file mode 100644
index 6516d1779..000000000
--- a/hicn-light/src/hicn/config/controlAddListener.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.
- */
-
-/**
- * @file control_AddListener.h
- * @brief Add a listener to an interface
- *
- * <#Detailed Description#>
- *
- */
-
-#ifndef Control_AddListener_h
-#define Control_AddListener_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlAddListener_Create(ControlState *state);
-CommandOps *controlAddListener_HelpCreate(ControlState *state);
-#endif // Control_AddListener_h
diff --git a/hicn-light/src/hicn/config/controlAddPolicy.c b/hicn-light/src/hicn/config/controlAddPolicy.c
deleted file mode 100644
index 66439d29c..000000000
--- a/hicn-light/src/hicn/config/controlAddPolicy.c
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef WITH_POLICY
-
-#include <hicn/hicn-light/config.h>
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <hicn/config/controlAddPolicy.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-#include <hicn/utils/token.h>
-
-static CommandReturn _controlAddPolicy_Execute(CommandParser *parser,
- CommandOps *ops, PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddPolicy_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandAddPolicy = "add policy";
-static const char *_commandAddPolicyHelp = "help add policy";
-
-CommandOps *controlAddPolicy_Create(ControlState *state) {
- return commandOps_Create(state, _commandAddPolicy, NULL,
- _controlAddPolicy_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlAddPolicy_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddPolicyHelp, NULL,
- _controlAddPolicy_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlAddPolicy_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- size_t output_offset = snprintf(output, output_size, "commands:\n"
- " add policy <prefix> <app_name>");
-
- #define _(x, y) output_offset += snprintf(output + output_offset, output_size - output_offset, " FLAG:%s", policy_tag_str[POLICY_TAG_ ## x]);
- foreach_policy_tag
- #undef _
-
- output_offset += snprintf(output + output_offset, output_size - output_offset,"\n");
- printf("\n");
- output_offset += snprintf(output + output_offset, output_size - output_offset,
- " prefix: The hicn name as IPv4 or IPv6 address (e.g 1234::0/64)\n"
- " app_name: The application name associated to this policy\n"
- " FLAG:*: A value among [neutral|require|prefer|avoid|prohibit] with an optional '!' character prefix for disabling changes\n"
- "\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddPolicy_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 11) {
- _controlAddPolicy_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *prefixStr = parcList_GetAtIndex(args, 2);
- char *addr = (char *)malloc((strlen(prefixStr) + 1) * sizeof(char));
-
- // separate address and len
- char *slash;
- uint32_t len = 0;
- strcpy(addr, prefixStr);
- slash = strrchr(addr, '/');
- if (slash != NULL) {
- len = atoi(slash + 1);
- *slash = '\0';
- }
-
- // allocate command payload
- add_policy_command *addPolicyCommand =
- parcMemory_AllocateAndClear(sizeof(add_policy_command));
-
- // check and set IP address
- if (inet_pton(AF_INET, addr, &addPolicyCommand->address.v4.as_u32) == 1) {
- if (len > 32) {
- snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n");
- parcMemory_Deallocate(&addPolicyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- addPolicyCommand->addressType = ADDR_INET;
- } else if (inet_pton(AF_INET6, addr, &addPolicyCommand->address.v6.as_in6addr) == 1) {
- if (len > 128) {
- snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n");
- parcMemory_Deallocate(&addPolicyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- addPolicyCommand->addressType = ADDR_INET6;
- } else {
- snprintf(output, output_size, "Error: %s is not a valid network address \n", addr);
- parcMemory_Deallocate(&addPolicyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
-
- free(addr);
-
- addPolicyCommand->len = len;
-
- hicn_policy_t policy;
- snprintf((char*)policy.app_name, APP_NAME_LEN, "%s", (char*)parcList_GetAtIndex(args, 3));
- for (int i=4; i < 11; i++) {
- const char *tag = parcList_GetAtIndex(args, i);
- policy_tag_state_t tag_state;
- tag_state.disabled = (tag[0] == '!') ? 1 : 0;
- if (strcmp(&tag[tag_state.disabled], "neutral") == 0) {
- tag_state.state = POLICY_STATE_NEUTRAL;
- } else if (strcmp(&tag[tag_state.disabled], "require") == 0) {
- tag_state.state = POLICY_STATE_REQUIRE;
- } else if (strcmp(&tag[tag_state.disabled], "prefer") == 0) {
- tag_state.state = POLICY_STATE_PREFER;
- } else if (strcmp(&tag[tag_state.disabled], "avoid") == 0) {
- tag_state.state = POLICY_STATE_AVOID;
- } else if (strcmp(&tag[tag_state.disabled], "prohibit") == 0) {
- tag_state.state = POLICY_STATE_PROHIBIT;
- } else {
- snprintf(output, output_size, "ERROR: invalid tag value '%s'\n", tag);
- parcMemory_Deallocate(&addPolicyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
-
- policy.tags[i-4] = tag_state;
-
- }
-
- addPolicyCommand->policy = policy;
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, ADD_POLICY, addPolicyCommand,
- sizeof(add_policy_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
-
-#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/config/controlAddPunting.c b/hicn-light/src/hicn/config/controlAddPunting.c
deleted file mode 100644
index 41d846d55..000000000
--- a/hicn-light/src/hicn/config/controlAddPunting.c
+++ /dev/null
@@ -1,159 +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/hicn-light/config.h>
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <hicn/utils/punting.h>
-
-#include <hicn/config/controlAddPunting.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlAddPunting_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddPunting_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandAddPunting = "add punting";
-static const char *_commandAddPuntingHelp = "help add punting";
-
-static const int _indexSymbolic = 2;
-static const int _indexPrefix = 3;
-
-CommandOps *controlAddPunting_Create(ControlState *state) {
- return commandOps_Create(state, _commandAddPunting, NULL,
- _controlAddPunting_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlAddPunting_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddPuntingHelp, NULL,
- _controlAddPunting_HelpExecute, commandOps_Destroy);
-}
-
-// =====================================================
-
-static CommandReturn _controlAddPunting_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "add punting <symbolic> <prefix>\n"
- " <symbolic> : listener symbolic name\n"
- " <address> : prefix to add as a punting rule. (example "
- "1234::0/64)\n"
- "\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddPunting_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 4) {
- _controlAddPunting_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *symbolicOrConnid = parcList_GetAtIndex(args, _indexSymbolic);
-
- if (!utils_ValidateSymbolicName(symbolicOrConnid) &&
- !utils_IsNumber(symbolicOrConnid)) {
- snprintf(output, output_size,
- "ERROR: Invalid symbolic or connid:\n"
- "symbolic name must begin with an alpha followed by alphanum;\nconnid "
- "must be an integer\n");
- return CommandReturn_Failure;
- }
-
- const char *prefixStr = parcList_GetAtIndex(args, _indexPrefix);
- char *addr = (char *)malloc((strlen(prefixStr) + 1) * sizeof(char));
-
- // separate address and len
- char *slash;
- uint32_t len = 0;
- strcpy(addr, prefixStr);
- slash = strrchr(addr, '/');
- if (slash != NULL) {
- len = atoi(slash + 1);
- *slash = '\0';
- }
-
- // allocate command payload
- add_punting_command *addPuntingCommand =
- parcMemory_AllocateAndClear(sizeof(add_punting_command));
-
- // check and set IP address
- if (inet_pton(AF_INET, addr, &addPuntingCommand->address.v4.as_u32) == 1) {
- if (len > 32) {
- snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n");
- parcMemory_Deallocate(&addPuntingCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- addPuntingCommand->addressType = ADDR_INET;
- } else if (inet_pton(AF_INET6, addr, &addPuntingCommand->address.v6.as_in6addr) == 1) {
- if (len > 128) {
- snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n");
- parcMemory_Deallocate(&addPuntingCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- addPuntingCommand->addressType = ADDR_INET6;
- } else {
- snprintf(output, output_size, "Error: %s is not a valid network address \n", addr);
- parcMemory_Deallocate(&addPuntingCommand);
- free(addr);
- return CommandReturn_Failure;
- }
-
- free(addr);
-
- // Fill remaining payload fields
- addPuntingCommand->len = len;
- strcpy(addPuntingCommand->symbolicOrConnid, symbolicOrConnid);
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, ADD_PUNTING, addPuntingCommand, sizeof(add_punting_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
-
-// ======================================================================
diff --git a/hicn-light/src/hicn/config/controlAddRoute.c b/hicn-light/src/hicn/config/controlAddRoute.c
deleted file mode 100644
index 78c0173ea..000000000
--- a/hicn-light/src/hicn/config/controlAddRoute.c
+++ /dev/null
@@ -1,162 +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/hicn-light/config.h>
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <hicn/config/controlAddRoute.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlAddRoute_Execute(CommandParser *parser,
- CommandOps *ops, PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlAddRoute_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandAddRoute = "add route";
-static const char *_commandAddRouteHelp = "help add route";
-
-CommandOps *controlAddRoute_Create(ControlState *state) {
- return commandOps_Create(state, _commandAddRoute, NULL,
- _controlAddRoute_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlAddRoute_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandAddRouteHelp, NULL,
- _controlAddRoute_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlAddRoute_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "commands:\n"
- " add route <symbolic | connid> <prefix> <cost>\n"
- "\n"
- " symbolic: The symbolic name for an exgress\n"
- " connid: The egress connection id (see 'help list connections')\n"
- " prefix: The hicn name as IPv4 or IPv6 address (e.g 1234::0/64)\n"
- " cost: positive integer representing cost\n"
- "\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlAddRoute_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 5) {
- _controlAddRoute_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *symbolicOrConnid = parcList_GetAtIndex(args, 2);
-
- if (!utils_ValidateSymbolicName(symbolicOrConnid) &&
- !utils_IsNumber(symbolicOrConnid)) {
- snprintf(output, output_size, "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an "
- "alpha followed by alphanum;\nconnid must be an integer\n");
- return CommandReturn_Failure;
- }
-
- unsigned cost = atoi(parcList_GetAtIndex(args, 4));
-
- if (cost == 0) {
- snprintf(output, output_size, "ERROR: cost must be positive integer, got %u from '%s'\n", cost,
- (char *)parcList_GetAtIndex(args, 4));
- return CommandReturn_Failure;
- }
-
- const char *prefixStr = parcList_GetAtIndex(args, 3);
- char *addr = (char *)malloc((strlen(prefixStr) + 1) * sizeof(char));
-
- // separate address and len
- char *slash;
- uint32_t len = 0;
- strcpy(addr, prefixStr);
- slash = strrchr(addr, '/');
- if (slash != NULL) {
- len = atoi(slash + 1);
- *slash = '\0';
- }
-
- // allocate command payload
- add_route_command *addRouteCommand =
- parcMemory_AllocateAndClear(sizeof(add_route_command));
-
- // check and set IP address
- if (inet_pton(AF_INET, addr, &addRouteCommand->address.v4.as_u32) == 1) {
- if (len > 32) {
- snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n");
- parcMemory_Deallocate(&addRouteCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- addRouteCommand->addressType = ADDR_INET;
- } else if (inet_pton(AF_INET6, addr, &addRouteCommand->address.v6.as_in6addr) == 1) {
- if (len > 128) {
- snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n");
- parcMemory_Deallocate(&addRouteCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- addRouteCommand->addressType = ADDR_INET6;
- } else {
- snprintf(output, output_size, "Error: %s is not a valid network address \n", addr);
- parcMemory_Deallocate(&addRouteCommand);
- free(addr);
- return CommandReturn_Failure;
- }
-
- free(addr);
-
- // Fill remaining payload fields
- addRouteCommand->len = len;
- addRouteCommand->cost = (uint16_t)cost;
- strcpy(addRouteCommand->symbolicOrConnid, symbolicOrConnid);
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, ADD_ROUTE, addRouteCommand,
- sizeof(add_route_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlAddRoute.h b/hicn-light/src/hicn/config/controlAddRoute.h
deleted file mode 100644
index 9588c0f42..000000000
--- a/hicn-light/src/hicn/config/controlAddRoute.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.
- */
-
-/**
- * @file control_AddRoute.h
- * @brief Add a static route
- *
- * Implements the "add route" node of the CLI tree
- *
- */
-
-#ifndef Control_AddRoute_h
-#define Control_AddRoute_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlAddRoute_Create(ControlState *state);
-CommandOps *controlAddRoute_HelpCreate(ControlState *state);
-#endif // Control_AddRoute_h
diff --git a/hicn-light/src/hicn/config/controlCache.c b/hicn-light/src/hicn/config/controlCache.c
deleted file mode 100644
index b6010fcfd..000000000
--- a/hicn-light/src/hicn/config/controlCache.c
+++ /dev/null
@@ -1,99 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/security/parc_Security.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlCache.h>
-#include <hicn/config/controlCacheClear.h>
-#include <hicn/config/controlCacheServe.h>
-#include <hicn/config/controlCacheStore.h>
-
-static void _controlCache_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlCache_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlCache_HelpExecute(CommandParser *parser,
- CommandOps *ops, PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandCache = "cache";
-static const char *_commandCacheHelp = "help cache";
-
-CommandOps *controlCache_Create(ControlState *state) {
- return commandOps_Create(state, _commandCache, _controlCache_Init,
- _controlCache_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlCache_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandCacheHelp, NULL,
- _controlCache_HelpExecute, commandOps_Destroy);
-}
-
-// =====================================================
-
-static CommandReturn _controlCache_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- CommandOps *ops_cache_serve = controlCacheServe_HelpCreate(NULL);
- CommandOps *ops_cache_store = controlCacheStore_HelpCreate(NULL);
- CommandOps *ops_cache_clear = controlCacheClear_HelpCreate(NULL);
-
- snprintf(output, output_size, "Available commands:\n"
- " %s\n %s\n %s\n\n",
- ops_cache_serve->command,
- ops_cache_store->command,
- ops_cache_clear->command);
- commandOps_Destroy(&ops_cache_serve);
- commandOps_Destroy(&ops_cache_store);
- commandOps_Destroy(&ops_cache_clear);
-
- return CommandReturn_Success;
-}
-
-static void _controlCache_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- controlState_RegisterCommand(state, controlCacheServe_HelpCreate(state));
- controlState_RegisterCommand(state, controlCacheStore_HelpCreate(state));
- controlState_RegisterCommand(state, controlCacheClear_HelpCreate(state));
- controlState_RegisterCommand(state, controlCacheServe_Create(state));
- controlState_RegisterCommand(state, controlCacheStore_Create(state));
- controlState_RegisterCommand(state, controlCacheClear_Create(state));
-}
-
-static CommandReturn _controlCache_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlCache_HelpExecute(parser, ops, args, output, output_size);
-}
-
-// ======================================================================
diff --git a/hicn-light/src/hicn/config/controlCache.h b/hicn-light/src/hicn/config/controlCache.h
deleted file mode 100644
index c2f2402f1..000000000
--- a/hicn-light/src/hicn/config/controlCache.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.
- */
-
-#ifndef controlCache_h
-#define controlCache_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlCache_Create(ControlState *state);
-CommandOps *controlCache_HelpCreate(ControlState *state);
-#endif // controlCache_h
diff --git a/hicn-light/src/hicn/config/controlCacheClear.c b/hicn-light/src/hicn/config/controlCacheClear.c
deleted file mode 100644
index afd8f6fc1..000000000
--- a/hicn-light/src/hicn/config/controlCacheClear.c
+++ /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.
- */
-
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlCacheClear.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlCacheClear_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlCacheClear_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandCacheClear = "cache clear";
-static const char *_commandCacheClearHelp = "help cache clear";
-
-// ====================================================
-
-CommandOps *controlCacheClear_Create(ControlState *state) {
- return commandOps_Create(state, _commandCacheClear, NULL,
- _controlCacheClear_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlCacheClear_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandCacheClearHelp, NULL,
- _controlCacheClear_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlCacheClear_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "cache clear\n\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlCacheClear_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlCacheClear_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- ControlState *state = ops->closure;
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, CACHE_CLEAR, NULL, 0);
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlCacheClear.h b/hicn-light/src/hicn/config/controlCacheClear.h
deleted file mode 100644
index 025758c34..000000000
--- a/hicn-light/src/hicn/config/controlCacheClear.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.
- */
-
-/**
- * @file controlCacheClear.h
- * @brief Clear the cache
- *
- * Removes all the cached data form the local content store (if available)
- *
- */
-
-#ifndef Control_CacheClear_h
-#define Control_CacheClear_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlCacheClear_Create(ControlState *state);
-CommandOps *controlCacheClear_HelpCreate(ControlState *state);
-#endif // Control_CacheClear_h
diff --git a/hicn-light/src/hicn/config/controlCacheServe.c b/hicn-light/src/hicn/config/controlCacheServe.c
deleted file mode 100644
index a4454037d..000000000
--- a/hicn-light/src/hicn/config/controlCacheServe.c
+++ /dev/null
@@ -1,108 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlCacheServe.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlCacheServe_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlCacheServe_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandCacheServe = "cache serve";
-static const char *_commandCacheServeHelp = "help cache serve";
-
-// ====================================================
-
-CommandOps *controlCacheServe_Create(ControlState *state) {
- return commandOps_Create(state, _commandCacheServe, NULL,
- _controlCacheServe_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlCacheServe_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandCacheServeHelp, NULL,
- _controlCacheServe_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlCacheServe_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "cache serve [on|off]\n\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlCacheServe_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 3) {
- _controlCacheServe_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- bool active;
- if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) {
- active = true;
- } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) {
- active = false;
- } else {
- _controlCacheServe_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- cache_serve_command *cacheServeCommand =
- parcMemory_AllocateAndClear(sizeof(cache_serve_command));
- if (active) {
- cacheServeCommand->activate = ACTIVATE_ON;
- } else {
- cacheServeCommand->activate = ACTIVATE_OFF;
- }
-
- ControlState *state = ops->closure;
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, CACHE_SERVE, cacheServeCommand, sizeof(cache_serve_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlCacheServe.h b/hicn-light/src/hicn/config/controlCacheServe.h
deleted file mode 100644
index afebc0601..000000000
--- a/hicn-light/src/hicn/config/controlCacheServe.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.
- */
-
-#ifndef Control_CacheServe_h
-#define Control_CacheServe_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlCacheServe_Create(ControlState *state);
-CommandOps *controlCacheServe_HelpCreate(ControlState *state);
-#endif // Control_CacheServe_h
diff --git a/hicn-light/src/hicn/config/controlCacheStore.c b/hicn-light/src/hicn/config/controlCacheStore.c
deleted file mode 100644
index 9f2a18146..000000000
--- a/hicn-light/src/hicn/config/controlCacheStore.c
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlCacheStore.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlCacheStore_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlCacheStore_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandCacheStore = "cache store";
-static const char *_commandCacheStoreHelp = "help cache store";
-
-// ====================================================
-
-CommandOps *controlCacheStore_Create(ControlState *state) {
- return commandOps_Create(state, _commandCacheStore, NULL,
- _controlCacheStore_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlCacheStore_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandCacheStoreHelp, NULL,
- _controlCacheStore_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlCacheStore_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "cache store [on|off]\n\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlCacheStore_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 3) {
- _controlCacheStore_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- bool active;
- if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) {
- active = true;
- } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) {
- active = false;
- } else {
- _controlCacheStore_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- cache_store_command *cacheStoreCommand =
- parcMemory_AllocateAndClear(sizeof(cache_store_command));
- if (active) {
- cacheStoreCommand->activate = ACTIVATE_ON;
- } else {
- cacheStoreCommand->activate = ACTIVATE_OFF;
- }
-
- ControlState *state = ops->closure;
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, CACHE_STORE, cacheStoreCommand, sizeof(cache_store_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlCacheStore.h b/hicn-light/src/hicn/config/controlCacheStore.h
deleted file mode 100644
index e32bf5663..000000000
--- a/hicn-light/src/hicn/config/controlCacheStore.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.
- */
-
-#ifndef Control_CacheStore_h
-#define Control_CacheStore_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlCacheStore_Create(ControlState *state);
-CommandOps *controlCacheStore_HelpCreate(ControlState *state);
-#endif // Control_CacheStore_h
diff --git a/hicn-light/src/hicn/config/controlList.c b/hicn-light/src/hicn/config/controlList.c
deleted file mode 100644
index 353856c43..000000000
--- a/hicn-light/src/hicn/config/controlList.c
+++ /dev/null
@@ -1,130 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/security/parc_Security.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlList.h>
-#include <hicn/config/controlListConnections.h>
-//#include <hicn/config/controlListInterfaces.h>
-#include <hicn/config/controlListListeners.h>
-#include <hicn/config/controlListRoutes.h>
-#ifdef WITH_POLICY
-#include <hicn/config/controlListPolicies.h>
-#endif /* WITH_POLICY */
-
-static void _controlList_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlList_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlList_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandList = "list";
-static const char *_commandListHelp = "help list";
-
-CommandOps *controlList_Create(ControlState *state) {
- return commandOps_Create(state, _commandList, _controlList_Init,
- _controlList_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlList_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandListHelp, NULL,
- _controlList_HelpExecute, commandOps_Destroy);
-}
-
-// =====================================================
-
-static CommandReturn _controlList_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- CommandOps *ops_list_connections = controlListConnections_HelpCreate(NULL);
- // CommandOps *ops_list_interfaces = controlListInterfaces_HelpCreate(NULL);
- CommandOps *ops_list_routes = controlListRoutes_HelpCreate(NULL);
- CommandOps *ops_list_listeners = controlListListeners_HelpCreate(NULL);
-#ifdef WITH_POLICY
- CommandOps *ops_list_policies = controlListPolicies_HelpCreate(NULL);
-#endif /* WITH_POLICY */
-
- snprintf(output, output_size, "Available commands:\n"
- " %s\n"
- " %s\n"
- " %s\n"
-#ifdef WITH_POLICY
- " %s\n"
-#endif /* WITH_POLICY */
- "\n",
- ops_list_connections->command,
- ops_list_routes->command,
- ops_list_listeners->command
-#ifdef WITH_POLICY
- , ops_list_policies->command
-#endif /* WITH_POLICY */
- );
-
- commandOps_Destroy(&ops_list_connections);
- // commandOps_Destroy(&ops_list_interfaces);
- commandOps_Destroy(&ops_list_routes);
- commandOps_Destroy(&ops_list_listeners);
-#ifdef WITH_POLICY
- commandOps_Destroy(&ops_list_policies);
-#endif /* WITH_POLICY */
-
- return CommandReturn_Success;
-}
-
-static void _controlList_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- controlState_RegisterCommand(state, controlListConnections_HelpCreate(state));
- // controlState_RegisterCommand(state,
- // controlListInterfaces_HelpCreate(state));
- controlState_RegisterCommand(state, controlListListeners_HelpCreate(state));
- controlState_RegisterCommand(state, controlListRoutes_HelpCreate(state));
- controlState_RegisterCommand(state, controlListConnections_Create(state));
- // controlState_RegisterCommand(state, controlListInterfaces_Create(state));
- controlState_RegisterCommand(state, controlListRoutes_Create(state));
- controlState_RegisterCommand(state, controlListListeners_Create(state));
-#ifdef WITH_POLICY
- controlState_RegisterCommand(state, controlListPolicies_HelpCreate(state));
- controlState_RegisterCommand(state, controlListPolicies_Create(state));
-#endif /* WITH_POLICY */
-}
-
-static CommandReturn _controlList_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlList_HelpExecute(parser, ops, args, output, output_size);
-}
-
-// ======================================================================
diff --git a/hicn-light/src/hicn/config/controlList.h b/hicn-light/src/hicn/config/controlList.h
deleted file mode 100644
index d497e5179..000000000
--- a/hicn-light/src/hicn/config/controlList.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.
- */
-
-/**
- * @file control_List.h
- * @brief Root node for the "list" commands
- *
- * Implements the "list" node of the CLI tree.
- *
- */
-
-#ifndef controlList_h
-#define controlList_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlList_Create(ControlState *state);
-CommandOps *controlList_HelpCreate(ControlState *state);
-#endif // controlList_h
diff --git a/hicn-light/src/hicn/config/controlListConnections.c b/hicn-light/src/hicn/config/controlListConnections.c
deleted file mode 100644
index 6406ba8c3..000000000
--- a/hicn-light/src/hicn/config/controlListConnections.c
+++ /dev/null
@@ -1,195 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlListConnections.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlListConnections_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlListConnections_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandListConnections = "list connections";
-static const char *_commandListConnectionsHelp = "help list connections";
-const char *connTypeString[6] = {"GRE", "TCP", "UDP", "MCAST", "L2", "HICN"};
-const char *stateString[3] = {"UP", "DOWN", "UNKNOWN"};
-
-CommandOps *controlListConnections_Create(ControlState *state) {
- return commandOps_Create(state, _commandListConnections, NULL,
- _controlListConnections_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlListConnections_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandListConnectionsHelp, NULL,
- _controlListConnections_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlListConnections_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
-snprintf(output, output_size, "%s", "list connections: displays a 1-line summary of each connection\n"
- "\n"
- "The columns are:\n"
- " connection id : an integer index for the connection\n"
- " state : UP or DOWN\n"
- " local address : the local network address associated with the "
- "connection\n"
- " remote address: the remote network address associated with the "
- "connection\n"
- " protocol : the network protocol (tcp, udp, gre, mcast, "
- "ether)\n"
- "\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlListConnections_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlListConnections_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-#ifdef WITH_POLICY
- char flags_str[POLICY_TAG_N+1];
- char *s;
-#endif /* WITH_POLICY */
-
- ControlState *state = ops->closure;
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, LIST_CONNECTIONS, NULL, 0);
- if (!response) { // get NULL pointer = FAILURE
- return CommandReturn_Failure;
- }
-
- // Process/Print message
- header_control_message *receivedHeader =
- (header_control_message *)response[0].iov_base;
- uint8_t *receivedPayload = (uint8_t *)response[1].iov_base;
-
- char *sourceString = NULL;
- char *destinationString = NULL;
-
- // Allocate output to pass to the main function if the call is not interactive
- char **commandOutputMain = NULL;
- if (!controlState_IsInteractive(state) && receivedHeader->length > 0) {
- commandOutputMain =
- parcMemory_Allocate(sizeof(char *) * receivedHeader->length);
- for (size_t j = 0; j < receivedHeader->length; j++) {
- commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 256);
- }
- }
-size_t output_offset = 0;
-
-#ifdef WITH_POLICY
- output_offset = snprintf(output, output_size, "%5s %10s %12s %6s %40s %40s %5s %s %s\n", "id", "name", "admin_state", "state", "source", "destination", "type", "priority", "flags");
-#else
- output_offset = snprintf(output, output_size, "%5s %10s %12s %6s %40s %40s %5s\n", "id", "name", "admin_state", "state", "source", "destination", "type");
-#endif /* WITH_POLICY */
-
- // Process/Print payload
-
- for (int i = 0; i < receivedHeader->length; i++) {
- list_connections_command *listConnectionsCommand =
- (list_connections_command *)(receivedPayload +
- (i * sizeof(list_connections_command)));
-
- sourceString = utils_CommandAddressToString(
- listConnectionsCommand->connectionData.ipType,
- &listConnectionsCommand->connectionData.localIp,
- &listConnectionsCommand->connectionData.localPort);
-
- destinationString = utils_CommandAddressToString(
- listConnectionsCommand->connectionData.ipType,
- &listConnectionsCommand->connectionData.remoteIp,
- &listConnectionsCommand->connectionData.remotePort);
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
-
-#ifdef WITH_POLICY
-
- s = flags_str;
-#define _(x, y) *s++ = policy_tags_has(listConnectionsCommand->connectionData.tags, POLICY_TAG_ ## x) ? y : '.';
-foreach_policy_tag
-#undef _
- *s = '\0';
-
- parcBufferComposer_Format(
- composer, "%5d %10s %12s %6s %40s %40s %5s [%6d] [%s]", listConnectionsCommand->connid, listConnectionsCommand->connectionName,
- stateString[listConnectionsCommand->connectionData.admin_state],
- stateString[listConnectionsCommand->state], sourceString,
- destinationString,
- connTypeString[listConnectionsCommand->connectionData.connectionType],
- listConnectionsCommand->connectionData.priority,
- flags_str);
-
-#else
- parcBufferComposer_Format(
- composer, "%5d %10s %12s %6s %40s %40s %5s", listConnectionsCommand->connid, listConnectionsCommand->connectionName,
- stateString[listConnectionsCommand->admin_state],
- stateString[listConnectionsCommand->state], sourceString,
- destinationString,
- connTypeString[listConnectionsCommand->connectionData.connectionType]);
-#endif /* WITH_POLICY */
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
-
- if (!controlState_IsInteractive(state)) {
- strcpy(commandOutputMain[i], result);
- }
- output_offset += snprintf(output + output_offset, output_size - output_offset, "%s\n", result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
- }
-
- controlState_SetCommandOutput(state, commandOutputMain);
-
- // DEALLOCATE
- parcMemory_Deallocate((void **)&sourceString);
- parcMemory_Deallocate((void **)&destinationString);
- parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base
- parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base
- parcMemory_Deallocate(&response); // free iovec pointer
-
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlListConnections.h b/hicn-light/src/hicn/config/controlListConnections.h
deleted file mode 100644
index cd5c21cec..000000000
--- a/hicn-light/src/hicn/config/controlListConnections.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.
- */
-
-/**
- * @file control_ListConnections.h
- * @brief List the current connections of hicn-light
- *
- * Implements the "list connections" node of the CLI tree
- *
- */
-
-#ifndef Control_ListConnections_h
-#define Control_ListConnections_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlListConnections_Create(ControlState *state);
-CommandOps *controlListConnections_HelpCreate(ControlState *state);
-#endif // Control_ListConnections_h
diff --git a/hicn-light/src/hicn/config/controlListInterfaces.c b/hicn-light/src/hicn/config/controlListInterfaces.c
deleted file mode 100644
index c632a1d21..000000000
--- a/hicn-light/src/hicn/config/controlListInterfaces.c
+++ /dev/null
@@ -1,81 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlListInterfaces.h>
-
-static CommandReturn _controlListInterfaces_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlListInterfaces_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandListInterfaces = "list interfaces";
-static const char *_commandListInterfacesHelp = "help list interfaces";
-
-// ====================================================
-
-CommandOps *controlListInterfaces_Create(ControlState *state) {
- return commandOps_Create(state, _commandListInterfaces, NULL,
- _controlListInterfaces_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlListInterfaces_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandListInterfacesHelp, NULL,
- _controlListInterfaces_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlListInterfaces_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "list interfaces\n\n")
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlListInterfaces_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlListInterfaces_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- //========================== NOT IMPLEMENTED
- //===========================
-
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlListInterfaces.h b/hicn-light/src/hicn/config/controlListInterfaces.h
deleted file mode 100644
index f885835ed..000000000
--- a/hicn-light/src/hicn/config/controlListInterfaces.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.
- */
-
-/**
- * @file control_ListInterfaces.h
- * @brief List the icn-light interfaces
- *
- * Implements the "list interfaces" and "help list interfaces" nodes of the
- * command tree
- *
- */
-
-#ifndef Control_ListInterfaces_h
-#define Control_ListInterfaces_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlListInterfaces_Create(ControlState *state);
-CommandOps *controlListInterfaces_HelpCreate(ControlState *state);
-#endif // Control_ListInterfaces_h
diff --git a/hicn-light/src/hicn/config/controlListListeners.c b/hicn-light/src/hicn/config/controlListListeners.c
deleted file mode 100644
index c189dfc36..000000000
--- a/hicn-light/src/hicn/config/controlListListeners.c
+++ /dev/null
@@ -1,160 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/config/controlListListeners.h>
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlListListeners_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlListListeners_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandListListeners = "list listeners";
-static const char *_commandListListenersHelp = "help list listeners";
-static const char *listenerType[5] = {"TCP", "UDP", "ETHER", "LOCAL", "HICN"};
-
-// ====================================================
-
-CommandOps *controlListListeners_Create(ControlState *state) {
- return commandOps_Create(state, _commandListListeners, NULL,
- _controlListListeners_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlListListeners_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandListListenersHelp, NULL,
- _controlListListeners_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlListListeners_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "list listeners\n\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlListListeners_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlListListeners_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- ControlState *state = ops->closure;
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, LIST_LISTENERS, NULL, 0);
- if (!response) { // get NULL pointer = FAILURE
- return CommandReturn_Failure;
- }
-
- // Process/Print message
- header_control_message *receivedHeader =
- (header_control_message *)response[0].iov_base;
- uint8_t *receivedPayload = (uint8_t *)response[1].iov_base;
-
- // Allocate output to pass to the main function if the call is not interactive
- char **commandOutputMain = NULL;
- if (!controlState_IsInteractive(state) && receivedHeader->length > 0) {
- commandOutputMain =
- parcMemory_Allocate(sizeof(char *) * receivedHeader->length);
- for (size_t j = 0; j < receivedHeader->length; j++) {
- commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 128);
- }
- }
-
- char *addrString = NULL;
- size_t output_offset = 0;
- if (receivedHeader->length > 0) {
- output_offset = snprintf(output, output_size, "%6.6s %.*s %50.70s %6s %10s\n", "iface", SYMBOLIC_NAME_LEN, "name", "address", "type", "interface");
-
- } else {
- output_offset = snprintf(output, output_size, " --- No entry in the list \n");
- }
-
- for (int i = 0; i < receivedHeader->length; i++) {
- list_listeners_command *listListenersCommand =
- (list_listeners_command *)(receivedPayload +
- (i * sizeof(list_listeners_command)));
-
- addrString = utils_CommandAddressToString(listListenersCommand->addressType,
- &listListenersCommand->address,
- &listListenersCommand->port);
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
-
- if (strcmp(listenerType[listListenersCommand->encapType], "UDP") == 0 ||
- strcmp(listenerType[listListenersCommand->encapType], "TCP") == 0) {
- parcBufferComposer_Format(composer, "%6u %.*s %50.70s %6s %10s",
- listListenersCommand->connid,
- SYMBOLIC_NAME_LEN, listListenersCommand->listenerName,
- addrString,
- listenerType[listListenersCommand->encapType],
- listListenersCommand->interfaceName);
- } else {
- parcBufferComposer_Format(composer, "%6u %.*s %50.70s %6s",
- listListenersCommand->connid,
- SYMBOLIC_NAME_LEN, listListenersCommand->listenerName,
- addrString,
- listenerType[listListenersCommand->encapType]);
- }
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
-
- if (!controlState_IsInteractive(state)) {
- strncpy(commandOutputMain[i], result, 128);
- }
- output_offset += snprintf(output + output_offset, output_size - output_offset, "%s\n", result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
- }
-
- controlState_SetCommandOutput(state, commandOutputMain);
-
- // DEALLOCATE
- parcMemory_Deallocate((void **)&addrString);
- parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base
- parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base
- parcMemory_Deallocate(&response); // free iovec pointer
-
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlListListeners.h b/hicn-light/src/hicn/config/controlListListeners.h
deleted file mode 100644
index 11ec07579..000000000
--- a/hicn-light/src/hicn/config/controlListListeners.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.
- */
-
-/**
- * @file control_ListListeners.h
- * @brief List the icn-light listeners
- *
- * Implements the "list listeners" and "help list listeners" nodes of the
- * command tree
- *
- */
-
-#ifndef Control_ListListeners_h
-#define Control_ListListeners_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlListListeners_Create(ControlState *state);
-CommandOps *controlListListeners_HelpCreate(ControlState *state);
-#endif // Control_ListListeners_h
diff --git a/hicn-light/src/hicn/config/controlListPolicies.c b/hicn-light/src/hicn/config/controlListPolicies.c
deleted file mode 100644
index 8eae6453b..000000000
--- a/hicn-light/src/hicn/config/controlListPolicies.c
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef WITH_POLICY
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Time.h>
-
-#include <hicn/config/controlListPolicies.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlListPolicies_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlListPolicies_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandListPolicies = "list policies";
-static const char *_commandListPoliciesHelp = "help list policies";
-
-// ====================================================
-
-CommandOps *controlListPolicies_Create(ControlState *state) {
- return commandOps_Create(state, _commandListPolicies, NULL,
- _controlListPolicies_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlListPolicies_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandListPoliciesHelp, NULL,
- _controlListPolicies_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlListPolicies_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "command: list policies\n\n");
- return CommandReturn_Success;
-}
-
-#define MAX(x,y) (x > y ? x : y)
-#define MAXSZ_COLUMN MAX(MAXSZ_POLICY_TAG, MAXSZ_POLICY_TAG_STATE)
-
-#define MAXSZ_STR_STAT 10
-#define MAXSZ_APP_NAME 25
-
-typedef struct {
- #define _(x, y) char x[MAXSZ_POLICY_TAG_STATE];
- foreach_policy_tag
- #undef _
-} tag_state_str_t;
-
-static CommandReturn _controlListPolicies_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlListPolicies_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- ControlState *state = ops->closure;
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, LIST_POLICIES, NULL, 0);
- if (!response) { // get NULL pointer = FAILURE
- return CommandReturn_Failure;
- }
-
- // Process/Print message
- header_control_message *receivedHeader =
- (header_control_message *)response[0].iov_base;
- uint8_t *receivedPayload = (uint8_t *)response[1].iov_base;
- if (!receivedPayload) {
- snprintf(output, output_size, "No payload!\n");
- return CommandReturn_Failure;
- }
-
- // Allocate output to pass to the main function if the call is not interactive
- char **commandOutputMain = NULL;
- if (!controlState_IsInteractive(state) && receivedHeader->length > 0) {
- commandOutputMain =
- parcMemory_Allocate(sizeof(char *) * receivedHeader->length);
- for (size_t j = 0; j < receivedHeader->length; j++) {
- commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 128);
- }
- }
-
- char *addrString = NULL;
- in_port_t port = htons(1234); // this is a random port number that is ignored
- size_t output_offset = 0;
- if (receivedHeader->length > 0) {
- output_offset += snprintf(output, output_size, "%*s %*s", MAXSZ_PREFIX, "prefix", MAXSZ_APP_NAME /*APP_NAME_LEN*/, "app_name");
- #define _(x, y) output_offset += snprintf(output + output_offset, output_size - output_offset, " %*s",MAXSZ_COLUMN, policy_tag_str[POLICY_TAG_ ## x]);
- foreach_policy_tag
- #undef _
- output_offset += snprintf(output + output_offset, output_size - output_offset, "\n");
- } else {
- output_offset += snprintf(output, output_size, " --- No entry in the list \n");
- }
-
- tag_state_str_t str;
-
- for (int i = 0; i < receivedHeader->length; i++) {
- list_policies_command *listPoliciesCommand =
- (list_policies_command *)(receivedPayload +
- (i * sizeof(list_policies_command)));
-
-#if 0
- char tag_s[MAXSZ_POLICY_TAG_STATE * POLICY_TAG_N];
-
- policy_tag_state_snprintf((char*)&tag_s[MAXSZ_POLICY_TAG_STATE * POLICY_TAG_ ## x], \
- MAXSZ_POLICY_TAG_STATE, \
- &listPoliciesCommand->policy.tags[POLICY_TAG_ ## x]);
-#endif
-
- #define _(x, y) policy_tag_state_snprintf(str.x, MAXSZ_POLICY_TAG_STATE, &listPoliciesCommand->policy.tags[POLICY_TAG_ ## x]);
- foreach_policy_tag
- #undef _
-
- addrString = utils_CommandAddressToString(
- listPoliciesCommand->addressType, &listPoliciesCommand->address, &port);
-
-#if 0
- PARCBufferComposer *composer = parcBufferComposer_Create();
-
- parcBufferComposer_Format(
- composer, "%*s %*s"
- #define _(x, y) " %*s"
- foreach_policy_tag
- #undef _
- "%s",
- MAXSZ_PREFIX, addrString, APP_NAME_LEN, listPoliciesCommand->policy.app_name,
- #define _(x, y) MAXSZ_COLUMN, str.x,
- foreach_policy_tag
- #undef _
- "");
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
-
- if (!controlState_IsInteractive(state)) {
- strcpy(commandOutputMain[i], result);
- }
-
- puts(result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
-#else
-
- output_offset = snprintf(output + output_offset, output_size - output_offset, "%*s %*s",
- MAXSZ_PREFIX, addrString, MAXSZ_APP_NAME /*APP_NAME_LEN*/, listPoliciesCommand->policy.app_name);
- #define _(x, y) output_offset += snprintf(output + output_offset, output_size - output_offset, " %*s", MAXSZ_COLUMN, str.x);
- foreach_policy_tag
- #undef _
-
- output_offset = snprintf(output + output_offset, output_size - output_offset, "\n");
-
-
- /*printf("%*s %*s"
- #define _(x, y) " %*s"
- foreach_policy_tag
- #undef _
- "%s\n",
- MAXSZ_PREFIX, addrString, MAXSZ_APP_NAME *//*APP_NAME_LEN*//*, listPoliciesCommand->policy.app_name,
- #define _(x, y) MAXSZ_COLUMN, str.x,
- foreach_policy_tag
- #undef _
- "");*/
-
-#endif
- }
-
- output_offset += snprintf(output + output_offset, output_size - output_offset, "\nSTATISTICS\n\n");
- // STATISTICS
- output_offset += snprintf(output + output_offset, output_size - output_offset, "%*s %*s %*s | %*s | %*s | %*s\n",
- MAXSZ_PREFIX, "", MAXSZ_APP_NAME /*APP_NAME_LEN*/, "",
- 3*MAXSZ_STR_STAT+2, "WIRED", 3*MAXSZ_STR_STAT+2, "WIFI", 3*MAXSZ_STR_STAT+2, "CELLULAR", 3*MAXSZ_STR_STAT+2, "ALL");
- output_offset += snprintf(output + output_offset, output_size - output_offset, "%*s %*s %*s %*s %*s | %*s %*s %*s | %*s %*s %*s | %*s %*s %*s\n",
- MAXSZ_PREFIX, "prefix", MAXSZ_APP_NAME /*APP_NAME_LEN*/, "app_name",
- MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate",
- MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate",
- MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate",
- MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate");
- for (int i = 0; i < receivedHeader->length; i++) {
- list_policies_command *listPoliciesCommand =
- (list_policies_command *)(receivedPayload +
- (i * sizeof(list_policies_command)));
- addrString = utils_CommandAddressToString(
- listPoliciesCommand->addressType, &listPoliciesCommand->address, &port);
- output_offset += snprintf(output + output_offset, output_size - output_offset, "%*s %*s %*.2f %*.2f %*.2f | %*.2f %*.2f %*.2f | %*.2f %*.2f %*.2f | %*.2f %*.2f %*.2f\n",
- MAXSZ_PREFIX, addrString, MAXSZ_APP_NAME, listPoliciesCommand->policy.app_name,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wired.throughput,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wired.latency,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wired.loss_rate,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wifi.throughput,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wifi.latency,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wifi.loss_rate,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.cellular.throughput,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.cellular.latency,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.cellular.loss_rate,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.all.throughput,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.all.latency,
- MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.all.loss_rate);
- }
-
- controlState_SetCommandOutput(state, commandOutputMain);
-
- // DEALLOCATE
- parcMemory_Deallocate((void **)&addrString);
- parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base
- parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base
- parcMemory_Deallocate(&response); // free iovec pointer
-
- return CommandReturn_Success;
-}
-
-#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/config/controlListRoutes.c b/hicn-light/src/hicn/config/controlListRoutes.c
deleted file mode 100644
index 395251b94..000000000
--- a/hicn-light/src/hicn/config/controlListRoutes.c
+++ /dev/null
@@ -1,158 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Time.h>
-
-#include <hicn/config/controlListRoutes.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlListRoutes_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlListRoutes_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandListRoutes = "list routes";
-static const char *_commandListRoutesHelp = "help list routes";
-
-// ====================================================
-
-CommandOps *controlListRoutes_Create(ControlState *state) {
- return commandOps_Create(state, _commandListRoutes, NULL,
- _controlListRoutes_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlListRoutes_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandListRoutesHelp, NULL,
- _controlListRoutes_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlListRoutes_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "command: list routes\n"
- "\n"
- "This command will fetch the prefix routing table. For each route, it "
- "will list:\n"
- " iface: interface\n"
- " protocol: the routing protocol, such as STATIC, CONNECTED, etc.\n"
- " type: LMP or EXACT (longest matching prefix or exact match)\n"
- " cost: The route cost, lower being preferred\n"
- " next: List of next hops by interface id\n"
- " prefix: name prefix\n"
- "\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlListRoutes_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlListRoutes_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- ControlState *state = ops->closure;
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, LIST_ROUTES, NULL, 0);
- if (!response) { // get NULL pointer = FAILURE
- return CommandReturn_Failure;
- }
-
- // Process/Print message
- header_control_message *receivedHeader =
- (header_control_message *)response[0].iov_base;
- uint8_t *receivedPayload = (uint8_t *)response[1].iov_base;
-
- // Allocate output to pass to the main function if the call is not interactive
- char **commandOutputMain = NULL;
- if (!controlState_IsInteractive(state) && receivedHeader->length > 0) {
- commandOutputMain =
- parcMemory_Allocate(sizeof(char *) * receivedHeader->length);
- for (size_t j = 0; j < receivedHeader->length; j++) {
- commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 128);
- }
- }
-
- char *addrString = NULL;
- in_port_t port = htons(1234); // this is a random port number that is ignored
- size_t output_offset = 0;
- if (receivedHeader->length > 0) {
- output_offset = snprintf(output, output_size, "%6.6s %8.8s %70.70s %s\n", "iface", "cost", "prefix", "len");
- } else {
- output_offset = snprintf(output, output_size, " --- No entry in the list \n");
- }
-
- for (int i = 0; i < receivedHeader->length; i++) {
- list_routes_command *listRoutesCommand =
- (list_routes_command *)(receivedPayload +
- (i * sizeof(list_routes_command)));
-
- addrString = utils_CommandAddressToString(
- listRoutesCommand->addressType, &listRoutesCommand->address, &port);
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
-
- parcBufferComposer_Format(
- composer, "%6u %8u %70.70s %3d", listRoutesCommand->connid,
- listRoutesCommand->cost, addrString, listRoutesCommand->len);
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
-
- if (!controlState_IsInteractive(state)) {
- strcpy(commandOutputMain[i], result);
- }
-
- output_offset += snprintf(output + output_offset, output_size - output_offset, "%s\n", result);
- parcMemory_Deallocate((void **)&result);
- parcBufferComposer_Release(&composer);
- }
-
- controlState_SetCommandOutput(state, commandOutputMain);
-
- // DEALLOCATE
- parcMemory_Deallocate((void **)&addrString);
- parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base
- parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base
- parcMemory_Deallocate(&response); // free iovec pointer
-
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlMapMe.c b/hicn-light/src/hicn/config/controlMapMe.c
deleted file mode 100644
index b292ee0f0..000000000
--- a/hicn-light/src/hicn/config/controlMapMe.c
+++ /dev/null
@@ -1,104 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/config/controlMapMe.h>
-#include <hicn/config/controlMapMeDiscovery.h>
-#include <hicn/config/controlMapMeEnable.h>
-#include <hicn/config/controlMapMeRetx.h>
-#include <hicn/config/controlMapMeTimescale.h>
-
-static void _controlMapMe_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlMapMe_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlMapMe_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandMapMe = "mapme";
-static const char *_commandMapMeHelp = "help mapme";
-
-CommandOps *controlMapMe_Create(ControlState *state) {
- return commandOps_Create(state, _commandMapMe, _controlMapMe_Init,
- _controlMapMe_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlMapMe_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandMapMeHelp, NULL,
- _controlMapMe_HelpExecute, commandOps_Destroy);
-}
-
-// =====================================================
-
-static CommandReturn _controlMapMe_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- CommandOps *ops_mapme_enable = controlMapMeEnable_HelpCreate(NULL);
- CommandOps *ops_mapme_discovery = controlMapMeDiscovery_HelpCreate(NULL);
- CommandOps *ops_mapme_timescale = controlMapMeTimescale_HelpCreate(NULL);
- CommandOps *ops_mapme_retx = controlMapMeRetx_HelpCreate(NULL);
-
- snprintf(output, output_size, "Available commands:\n"
- " %s\n %s\n %s\n %s\n\n",
- ops_mapme_enable->command,
- ops_mapme_discovery->command,
- ops_mapme_timescale->command,
- ops_mapme_retx->command);
-
- commandOps_Destroy(&ops_mapme_enable);
- commandOps_Destroy(&ops_mapme_discovery);
- commandOps_Destroy(&ops_mapme_timescale);
- commandOps_Destroy(&ops_mapme_retx);
-
- return CommandReturn_Success;
-}
-
-static void _controlMapMe_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- controlState_RegisterCommand(state, controlMapMeEnable_HelpCreate(state));
- controlState_RegisterCommand(state, controlMapMeDiscovery_HelpCreate(state));
- controlState_RegisterCommand(state, controlMapMeTimescale_HelpCreate(state));
- controlState_RegisterCommand(state, controlMapMeRetx_HelpCreate(state));
- controlState_RegisterCommand(state, controlMapMeEnable_Create(state));
- controlState_RegisterCommand(state, controlMapMeDiscovery_Create(state));
- controlState_RegisterCommand(state, controlMapMeTimescale_Create(state));
- controlState_RegisterCommand(state, controlMapMeRetx_Create(state));
-}
-
-static CommandReturn _controlMapMe_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlMapMe_HelpExecute(parser, ops, args, output, output_size);
-}
-
-// ======================================================================
diff --git a/hicn-light/src/hicn/config/controlMapMe.h b/hicn-light/src/hicn/config/controlMapMe.h
deleted file mode 100644
index 3edd78989..000000000
--- a/hicn-light/src/hicn/config/controlMapMe.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.
- */
-
-#ifndef controlMapMe_h
-#define controlMapMe_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlMapMe_Create(ControlState *state);
-CommandOps *controlMapMe_HelpCreate(ControlState *state);
-#endif // controlMapMe_h
diff --git a/hicn-light/src/hicn/config/controlMapMeDiscovery.c b/hicn-light/src/hicn/config/controlMapMeDiscovery.c
deleted file mode 100644
index 6ec941141..000000000
--- a/hicn-light/src/hicn/config/controlMapMeDiscovery.c
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/config/controlMapMeDiscovery.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlMapMeDiscovery_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlMapMeDiscovery_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandMapMeDiscovery = "mapme discovery";
-static const char *_commandMapMeDiscoveryHelp = "help mapme discovery";
-
-// ====================================================
-
-CommandOps *controlMapMeDiscovery_Create(ControlState *state) {
- return commandOps_Create(state, _commandMapMeDiscovery, NULL,
- _controlMapMeDiscovery_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlMapMeDiscovery_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandMapMeDiscoveryHelp, NULL,
- _controlMapMeDiscovery_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlMapMeDiscovery_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "mapme discovery [on|off]\n\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlMapMeDiscovery_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 3) {
- _controlMapMeDiscovery_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- bool active;
- if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) {
- active = true;
- } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) {
- active = false;
- } else {
- _controlMapMeDiscovery_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- mapme_activator_command *mapmeDiscoveryCommand =
- parcMemory_AllocateAndClear(sizeof(mapme_activator_command));
- if (active) {
- mapmeDiscoveryCommand->activate = ACTIVATE_ON;
- } else {
- mapmeDiscoveryCommand->activate = ACTIVATE_OFF;
- }
-
- ControlState *state = ops->closure;
- // send message and receive response
- struct iovec *response =
- utils_SendRequest(state, MAPME_DISCOVERY, mapmeDiscoveryCommand,
- sizeof(mapme_activator_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlMapMeDiscovery.h b/hicn-light/src/hicn/config/controlMapMeDiscovery.h
deleted file mode 100644
index c2832632a..000000000
--- a/hicn-light/src/hicn/config/controlMapMeDiscovery.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.
- */
-
-#ifndef Control_MapMeDiscovery_h
-#define Control_MapMeDiscovery_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlMapMeDiscovery_Create(ControlState *state);
-CommandOps *controlMapMeDiscovery_HelpCreate(ControlState *state);
-#endif // Control_MapMeDiscovery_h
diff --git a/hicn-light/src/hicn/config/controlMapMeEnable.c b/hicn-light/src/hicn/config/controlMapMeEnable.c
deleted file mode 100644
index 0595cc346..000000000
--- a/hicn-light/src/hicn/config/controlMapMeEnable.c
+++ /dev/null
@@ -1,107 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/config/controlMapMeEnable.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlMapMeEnable_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlMapMeEnable_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandMapMeEnable = "mapme enable";
-static const char *_commandMapMeEnableHelp = "help mapme enable";
-
-// ====================================================
-
-CommandOps *controlMapMeEnable_Create(ControlState *state) {
- return commandOps_Create(state, _commandMapMeEnable, NULL,
- _controlMapMeEnable_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlMapMeEnable_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandMapMeEnableHelp, NULL,
- _controlMapMeEnable_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlMapMeEnable_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "mapme enable [on|off]\n\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlMapMeEnable_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 3) {
- _controlMapMeEnable_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- bool active;
- if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) {
- active = true;
- } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) {
- active = false;
- } else {
- _controlMapMeEnable_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- mapme_activator_command *mapmeEnableCommand =
- parcMemory_AllocateAndClear(sizeof(mapme_activator_command));
- if (active) {
- mapmeEnableCommand->activate = ACTIVATE_ON;
- } else {
- mapmeEnableCommand->activate = ACTIVATE_OFF;
- }
-
- ControlState *state = ops->closure;
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, MAPME_ENABLE, mapmeEnableCommand, sizeof(mapme_activator_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlMapMeEnable.h b/hicn-light/src/hicn/config/controlMapMeEnable.h
deleted file mode 100644
index 0ce4970f3..000000000
--- a/hicn-light/src/hicn/config/controlMapMeEnable.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.
- */
-
-#ifndef Control_MapMeEnable_h
-#define Control_MapMeEnable_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlMapMeEnable_Create(ControlState *state);
-CommandOps *controlMapMeEnable_HelpCreate(ControlState *state);
-#endif // Control_MapMeEnable_h
diff --git a/hicn-light/src/hicn/config/controlMapMeRetx.c b/hicn-light/src/hicn/config/controlMapMeRetx.c
deleted file mode 100644
index 9f37ca6f5..000000000
--- a/hicn-light/src/hicn/config/controlMapMeRetx.c
+++ /dev/null
@@ -1,101 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/config/controlMapMeRetx.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlMapMeRetx_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlMapMeRetx_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandMapMeRetx = "mapme retx";
-static const char *_commandMapMeRetxHelp = "help mapme retx";
-
-// ====================================================
-
-CommandOps *controlMapMeRetx_Create(ControlState *state) {
- return commandOps_Create(state, _commandMapMeRetx, NULL,
- _controlMapMeRetx_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlMapMeRetx_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandMapMeRetxHelp, NULL,
- _controlMapMeRetx_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlMapMeRetx_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "mapme retx <milliseconds>\n\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlMapMeRetx_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 3) {
- _controlMapMeRetx_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *rtx = parcList_GetAtIndex(args, 2);
- if (!utils_IsNumber(rtx)) {
- snprintf(output, output_size,
- "ERROR: retransmission value (expressed in ms) must be a positive "
- "integer \n");
- return CommandReturn_Failure;
- }
-
- mapme_timing_command *mapmeRetxCommand =
- parcMemory_AllocateAndClear(sizeof(mapme_timing_command));
- mapmeRetxCommand->timePeriod = (unsigned)strtold(rtx, NULL);
-
- ControlState *state = ops->closure;
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, MAPME_RETX, mapmeRetxCommand, sizeof(mapme_timing_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlMapMeTimescale.c b/hicn-light/src/hicn/config/controlMapMeTimescale.c
deleted file mode 100644
index 51701aa2f..000000000
--- a/hicn-light/src/hicn/config/controlMapMeTimescale.c
+++ /dev/null
@@ -1,102 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/config/controlMapMeTimescale.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlMapMeTimescale_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlMapMeTimescale_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandMapMeTimescale = "mapme timescale";
-static const char *_commandMapMeTimescaleHelp = "help mapme timescale";
-
-// ====================================================
-
-CommandOps *controlMapMeTimescale_Create(ControlState *state) {
- return commandOps_Create(state, _commandMapMeTimescale, NULL,
- _controlMapMeTimescale_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlMapMeTimescale_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandMapMeTimescaleHelp, NULL,
- _controlMapMeTimescale_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlMapMeTimescale_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "mapme timescale <milliseconds>\n\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlMapMeTimescale_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 3) {
- _controlMapMeTimescale_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *ts = parcList_GetAtIndex(args, 2);
- if (!utils_IsNumber(ts)) {
- snprintf(output, output_size,
- "ERROR: timescale value (expressed in ms) must be a positive integer "
- "\n");
- return CommandReturn_Failure;
- }
-
- mapme_timing_command *mapmeTimescaleCommand =
- parcMemory_AllocateAndClear(sizeof(mapme_timing_command));
- mapmeTimescaleCommand->timePeriod = (unsigned)strtold(ts, NULL);
-
- ControlState *state = ops->closure;
- // send message and receive response
- struct iovec *response =
- utils_SendRequest(state, MAPME_TIMESCALE, mapmeTimescaleCommand,
- sizeof(mapme_timing_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlMapMeTimescale.h b/hicn-light/src/hicn/config/controlMapMeTimescale.h
deleted file mode 100644
index 947d00a5d..000000000
--- a/hicn-light/src/hicn/config/controlMapMeTimescale.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.
- */
-
-#ifndef Control_MapMeTimescale_h
-#define Control_MapMeTimescale_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlMapMeTimescale_Create(ControlState *state);
-CommandOps *controlMapMeTimescale_HelpCreate(ControlState *state);
-#endif // Control_MapMeTimescale_h
diff --git a/hicn-light/src/hicn/config/controlQuit.c b/hicn-light/src/hicn/config/controlQuit.c
deleted file mode 100644
index 621880d13..000000000
--- a/hicn-light/src/hicn/config/controlQuit.c
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/security/parc_Security.h>
-
-#include <hicn/config/controlQuit.h>
-
-static CommandReturn _controlQuit_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlQuit_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandQuit = "quit";
-static const char *_commandQuitHelp = "help quit";
-
-// ====================================================
-
-CommandOps *controlQuit_Create(ControlState *state) {
- return commandOps_Create(state, _commandQuit, NULL, _controlQuit_Execute,
- commandOps_Destroy);
-}
-
-CommandOps *controlQuit_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandQuitHelp, NULL,
- _controlQuit_HelpExecute, commandOps_Destroy);
-}
-
-// ==============================================
-
-static CommandReturn _controlQuit_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "Exits the interactive control program\n\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlQuit_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "exiting interactive shell\n");
- return CommandReturn_Exit;
-}
diff --git a/hicn-light/src/hicn/config/controlQuit.h b/hicn-light/src/hicn/config/controlQuit.h
deleted file mode 100644
index b45d5e215..000000000
--- a/hicn-light/src/hicn/config/controlQuit.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.
- */
-
-/**
- * @file control_Quit.h
- * @brief The quit command
- *
- * Implements the "quit" and "help quit" nodes of the command tree
- *
- */
-#ifndef Control_Quit_h
-#define Control_Quit_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlQuit_Create(ControlState *state);
-CommandOps *controlQuit_HelpCreate(ControlState *state);
-#endif // Control_Quit_h
diff --git a/hicn-light/src/hicn/config/controlRemove.c b/hicn-light/src/hicn/config/controlRemove.c
deleted file mode 100644
index b1a88b5c1..000000000
--- a/hicn-light/src/hicn/config/controlRemove.c
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/security/parc_Security.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlRemove.h>
-#include <hicn/config/controlRemoveListener.h>
-#include <hicn/config/controlRemoveConnection.h>
-#include <hicn/config/controlRemovePunting.h>
-#include <hicn/config/controlRemoveRoute.h>
-#ifdef WITH_POLICY
-#include <hicn/config/controlRemovePolicy.h>
-#endif /* WITH_POLICY */
-
-static void _controlRemove_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlRemove_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlRemove_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandRemove = "remove";
-static const char *_commandRemoveHelp = "help remove";
-
-// ====================================================
-
-CommandOps *controlRemove_Create(ControlState *state) {
- return commandOps_Create(state, _commandRemove, _controlRemove_Init,
- _controlRemove_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlRemove_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandRemoveHelp, NULL,
- _controlRemove_HelpExecute, commandOps_Destroy);
-}
-
-// ==============================================
-
-static CommandReturn _controlRemove_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- CommandOps *ops_remove_connection = controlRemoveConnection_Create(NULL);
- CommandOps *ops_remove_listener = controlRemoveListener_Create(NULL);
- CommandOps *ops_remove_route = controlRemoveRoute_Create(NULL);
- CommandOps *ops_remove_punting = controlRemovePunting_Create(NULL);
-#ifdef WITH_POLICY
- CommandOps *ops_remove_policy = controlRemovePolicy_Create(NULL);
-#endif /* WITH_POLICY */
-
- snprintf(output, output_size, "Available commands:\n"
- " %s\n"
- " %s\n"
- " %s\n"
- " %s\n"
-#ifdef WITH_POLICY
- " %s\n"
-#endif /* WITH_POLICY */
- "\n",
- ops_remove_connection->command,
- ops_remove_listener->command,
- ops_remove_route->command,
- ops_remove_punting->command
-#ifdef WITH_POLICY
- , ops_remove_policy->command
-#endif /* WITH_POLICY */
- );
-
- commandOps_Destroy(&ops_remove_connection);
- commandOps_Destroy(&ops_remove_listener);
- commandOps_Destroy(&ops_remove_route);
- commandOps_Destroy(&ops_remove_punting);
-#ifdef WITH_POLICY
- commandOps_Destroy(&ops_remove_policy);
-#endif /* WITH_POLICY */
- return CommandReturn_Success;
-}
-
-static void _controlRemove_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- controlState_RegisterCommand(state,
- controlRemoveConnection_HelpCreate(state));
- controlState_RegisterCommand(state,
- controlRemoveListener_HelpCreate(state));
- controlState_RegisterCommand(state, controlRemoveRoute_HelpCreate(state));
- controlState_RegisterCommand(state, controlRemoveConnection_Create(state));
- controlState_RegisterCommand(state, controlRemoveListener_Create(state));
- controlState_RegisterCommand(state, controlRemoveRoute_Create(state));
- controlState_RegisterCommand(state, controlRemovePunting_Create(state));
- controlState_RegisterCommand(state, controlRemovePunting_HelpCreate(state));
-#ifdef WITH_POLICY
- controlState_RegisterCommand(state, controlRemovePolicy_HelpCreate(state));
- controlState_RegisterCommand(state, controlRemovePolicy_Create(state));
-#endif /* WITH_POLICY */
-}
-
-static CommandReturn _controlRemove_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlRemove_HelpExecute(parser, ops, args, output, output_size);
-}
diff --git a/hicn-light/src/hicn/config/controlRemove.h b/hicn-light/src/hicn/config/controlRemove.h
deleted file mode 100644
index 863555728..000000000
--- a/hicn-light/src/hicn/config/controlRemove.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.
- */
-
-/**
- * @file control_Remove.h
- * @brief Implements the remove node of the CLI tree
- *
- * Implements the "remove" and "help remove" nodes of the command tree
- *
- */
-#ifndef controlRemove_h
-#define controlRemove_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlRemove_Create(ControlState *state);
-CommandOps *controlRemove_HelpCreate(ControlState *state);
-#endif // controlRemove_h
diff --git a/hicn-light/src/hicn/config/controlRemoveConnection.c b/hicn-light/src/hicn/config/controlRemoveConnection.c
deleted file mode 100644
index a6cfae1e5..000000000
--- a/hicn-light/src/hicn/config/controlRemoveConnection.c
+++ /dev/null
@@ -1,122 +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/hicn-light/config.h>
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <hicn/utils/address.h>
-
-#include <hicn/config/controlRemoveConnection.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlRemoveConnection_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlRemoveConnection_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-static const char *_commandRemoveConnection = "remove connection";
-static const char *_commandRemoveConnectionHelp = "help remove connection";
-
-// ====================================================
-
-CommandOps *controlRemoveConnection_Create(ControlState *state) {
- return commandOps_Create(state, _commandRemoveConnection, NULL,
- _controlRemoveConnection_Execute,
- commandOps_Destroy);
-}
-
-CommandOps *controlRemoveConnection_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandRemoveConnectionHelp, NULL,
- _controlRemoveConnection_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlRemoveConnection_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "command:\n"
- " remove connection <symbolic|id>\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlRemoveConnection_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 3) {
- _controlRemoveConnection_HelpExecute(parser, ops, args, output, output_size);
- return false;
- }
-
- if ((strcmp(parcList_GetAtIndex(args, 0), "remove") != 0) ||
- (strcmp(parcList_GetAtIndex(args, 1), "connection") != 0)) {
- _controlRemoveConnection_HelpExecute(parser, ops, args, output, output_size);
- return false;
- }
-
- const char *symbolicOrConnid = parcList_GetAtIndex(args, 2);
-
- if (!utils_ValidateSymbolicName(symbolicOrConnid) &&
- !utils_IsNumber(symbolicOrConnid)) {
- snprintf(output, output_size,
- "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an "
- "alpha followed by alphanum;\nconnid must be an integer\n");
- return CommandReturn_Failure;
- }
-
- // allocate command payload
- remove_connection_command *removeConnectionCommand =
- parcMemory_AllocateAndClear(sizeof(remove_connection_command));
- // fill payload
- strcpy(removeConnectionCommand->symbolicOrConnid, symbolicOrConnid);
-
- // send message and receive response
- struct iovec *response =
- utils_SendRequest(state, REMOVE_CONNECTION, removeConnectionCommand,
- sizeof(remove_connection_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlRemoveConnection.h b/hicn-light/src/hicn/config/controlRemoveConnection.h
deleted file mode 100644
index 51d3a52a8..000000000
--- a/hicn-light/src/hicn/config/controlRemoveConnection.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.
- */
-
-/**
- * @file control_RemoveConnection.h
- * @brief Remove a connection from the connection table
- *
- * Implements the "remove connection" and "help remove connection" nodes of the
- * CLI tree
- *
- */
-
-#ifndef Control_RemoveConnection_h
-#define Control_RemoveConnection_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlRemoveConnection_Create(ControlState *state);
-CommandOps *controlRemoveConnection_HelpCreate(ControlState *state);
-#endif // Control_RemoveConnection_h
diff --git a/hicn-light/src/hicn/config/controlRemoveListener.c b/hicn-light/src/hicn/config/controlRemoveListener.c
deleted file mode 100644
index 7525316f1..000000000
--- a/hicn-light/src/hicn/config/controlRemoveListener.c
+++ /dev/null
@@ -1,123 +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/hicn-light/config.h>
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <hicn/utils/address.h>
-
-#include <hicn/config/controlRemoveListener.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlRemoveListener_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlRemoveListener_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-static const char *_commandRemoveListener = "remove listener";
-static const char *_commandRemoveListenerHelp = "help remove listener";
-
-// ====================================================
-
-CommandOps *controlRemoveListener_Create(ControlState *state) {
- return commandOps_Create(state, _commandRemoveListener, NULL,
- _controlRemoveListener_Execute,
- commandOps_Destroy);
-}
-
-CommandOps *controlRemoveListener_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandRemoveListenerHelp, NULL,
- _controlRemoveListener_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlRemoveListener_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "command:\n"
- " remove listener <symbolic|id>\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlRemoveListener_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 3) {
- _controlRemoveListener_HelpExecute(parser, ops, args, output, output_size);
- return false;
- }
-
- if ((strcmp(parcList_GetAtIndex(args, 0), "remove") != 0) ||
- (strcmp(parcList_GetAtIndex(args, 1), "listener") != 0)) {
- _controlRemoveListener_HelpExecute(parser, ops, args, output, output_size);
- return false;
- }
-
- const char *listenerId = parcList_GetAtIndex(args, 2);
-
-if (!utils_ValidateSymbolicName(listenerId) &&
- !utils_IsNumber(listenerId)) {
- snprintf(output, output_size,
- "ERROR: Invalid symbolic or listenerId:\nsymbolic name must begin with an "
- "alpha followed by alphanum;\nlistenerId must be an integer\n");
- return CommandReturn_Failure;
- }
-
- // allocate command payload
- remove_listener_command *removeListenerCommand =
- parcMemory_AllocateAndClear(sizeof(remove_listener_command));
- // fill payload
- //removeListenerCommand->listenerId = atoi(listenerId);
- snprintf(removeListenerCommand->symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%s", listenerId);
-
- // send message and receive response
- struct iovec *response =
- utils_SendRequest(state, REMOVE_LISTENER, removeListenerCommand,
- sizeof(remove_listener_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlRemoveListener.h b/hicn-light/src/hicn/config/controlRemoveListener.h
deleted file mode 100644
index 794d1e1a9..000000000
--- a/hicn-light/src/hicn/config/controlRemoveListener.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.
- */
-
-/**
- * @file control_RemoveConnection.h
- * @brief Remove a connection from the connection table
- *
- * Implements the "remove connection" and "help remove connection" nodes of the
- * CLI tree
- *
- */
-
-#ifndef Control_RemoveListener_h
-#define Control_RemoveListener_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlRemoveListener_Create(ControlState *state);
-CommandOps *controlRemoveListener_HelpCreate(ControlState *state);
-#endif // Control_RemoveListener_h
diff --git a/hicn-light/src/hicn/config/controlRemovePolicy.c b/hicn-light/src/hicn/config/controlRemovePolicy.c
deleted file mode 100644
index 35741396e..000000000
--- a/hicn-light/src/hicn/config/controlRemovePolicy.c
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef WITH_POLICY
-
-#include <hicn/hicn-light/config.h>
-
-#include <ctype.h>
-#include <parc/algol/parc_List.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <parc/assert/parc_Assert.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <hicn/utils/address.h>
-
-#include <hicn/config/controlRemovePolicy.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlRemovePolicy_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlRemovePolicy_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-static const char *_commandRemovePolicy = "remove policy";
-static const char *_commandRemovePolicyHelp = "help remove policy";
-
-// ====================================================
-
-CommandOps *controlRemovePolicy_Create(ControlState *state) {
- return commandOps_Create(state, _commandRemovePolicy, NULL,
- _controlRemovePolicy_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlRemovePolicy_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandRemovePolicyHelp, NULL,
- _controlRemovePolicy_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlRemovePolicy_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "commands:\n"
- " remove policy <prefix>\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlRemovePolicy_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 3) {
- _controlRemovePolicy_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *prefixStr = parcList_GetAtIndex(args, 2);
- char *addr = (char *)malloc(sizeof(char) * (strlen(prefixStr) + 1));
-
- // separate address and len
- char *slash;
- uint32_t len = 0;
- strcpy(addr, prefixStr);
- slash = strrchr(addr, '/');
- if (slash != NULL) {
- len = atoi(slash + 1);
- *slash = '\0';
- }
-
- // allocate command payload
- remove_policy_command *removePolicyCommand =
- parcMemory_AllocateAndClear(sizeof(remove_policy_command));
-
- // check and set IP address
- if (inet_pton(AF_INET, addr, &removePolicyCommand->address.v4.as_u32) == 1) {
- if (len > 32) {
- snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n");
- parcMemory_Deallocate(&removePolicyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- removePolicyCommand->addressType = ADDR_INET;
- } else if (inet_pton(AF_INET6, addr, &removePolicyCommand->address.v6.as_in6addr) ==
- 1) {
- if (len > 128) {
- snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n");
- parcMemory_Deallocate(&removePolicyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- removePolicyCommand->addressType = ADDR_INET6;
- } else {
- snprintf(output, output_size, "Error: %s is not a valid network address \n", addr);
- parcMemory_Deallocate(&removePolicyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
-
- free(addr);
- // Fill remaining payload fields
- removePolicyCommand->len = len;
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, REMOVE_POLICY, removePolicyCommand, sizeof(remove_policy_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
-
-#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/config/controlRemovePunting.c b/hicn-light/src/hicn/config/controlRemovePunting.c
deleted file mode 100644
index 84d096b81..000000000
--- a/hicn-light/src/hicn/config/controlRemovePunting.c
+++ /dev/null
@@ -1,83 +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/hicn-light/config.h>
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <hicn/utils/address.h>
-
-#include <hicn/config/controlRemovePunting.h>
-
-static CommandReturn _controlRemovePunting_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlRemovePunting_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-static const char *_commandRemovePunting = "remove punting";
-static const char *_commandRemovePuntingHelp = "help punting connection";
-
-// ====================================================
-
-CommandOps *controlRemovePunting_Create(ControlState *state) {
- return commandOps_Create(state, _commandRemovePunting, NULL,
- _controlRemovePunting_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlRemovePunting_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandRemovePuntingHelp, NULL,
- _controlRemovePunting_HelpExecute,
- commandOps_Destroy);
-}
-
-// ====================================================
-
-// ====================================================
-
-static CommandReturn _controlRemovePunting_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "remove punting <symbolic> <prefix>\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlRemovePunting_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "command not implemented\n");
- return _controlRemovePunting_HelpExecute(parser, ops, args, output, output_size);
-}
-
-// ==================================================
diff --git a/hicn-light/src/hicn/config/controlRemoveRoute.c b/hicn-light/src/hicn/config/controlRemoveRoute.c
deleted file mode 100644
index eb5642d98..000000000
--- a/hicn-light/src/hicn/config/controlRemoveRoute.c
+++ /dev/null
@@ -1,154 +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/hicn-light/config.h>
-
-#include <ctype.h>
-#include <parc/algol/parc_List.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <parc/assert/parc_Assert.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <hicn/utils/address.h>
-
-#include <hicn/config/controlRemoveRoute.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlRemoveRoute_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlRemoveRoute_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-// ===================================================
-
-static const char *_commandRemoveRoute = "remove route";
-static const char *_commandRemoveRouteHelp = "help remove route";
-
-// ====================================================
-
-CommandOps *controlRemoveRoute_Create(ControlState *state) {
- return commandOps_Create(state, _commandRemoveRoute, NULL,
- _controlRemoveRoute_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlRemoveRoute_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandRemoveRouteHelp, NULL,
- _controlRemoveRoute_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlRemoveRoute_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "commands:\n"
- " remove route <symbolic | connid> <prefix>\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlRemoveRoute_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 4) {
- _controlRemoveRoute_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *symbolicOrConnid = parcList_GetAtIndex(args, 2);
-
- if (!utils_ValidateSymbolicName(symbolicOrConnid) &&
- !utils_IsNumber(symbolicOrConnid)) {
- snprintf(output, output_size,
- "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an "
- "alpha followed by alphanum;\nconnid must be an integer\n");
- return CommandReturn_Failure;
- }
-
- const char *prefixStr = parcList_GetAtIndex(args, 3);
- char *addr = (char *)malloc(sizeof(char) * (strlen(prefixStr) + 1));
-
- // separate address and len
- char *slash;
- uint32_t len = 0;
- strcpy(addr, prefixStr);
- slash = strrchr(addr, '/');
- if (slash != NULL) {
- len = atoi(slash + 1);
- *slash = '\0';
- }
-
- // allocate command payload
- remove_route_command *removeRouteCommand =
- parcMemory_AllocateAndClear(sizeof(remove_route_command));
-
- // check and set IP address
- if (inet_pton(AF_INET, addr, &removeRouteCommand->address.v4.as_u32) == 1) {
- if (len > 32) {
- snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n");
- parcMemory_Deallocate(&removeRouteCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- removeRouteCommand->addressType = ADDR_INET;
- } else if (inet_pton(AF_INET6, addr, &removeRouteCommand->address.v6.as_in6addr) ==
- 1) {
- if (len > 128) {
- snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n");
- parcMemory_Deallocate(&removeRouteCommand);
- free(addr);
- return CommandReturn_Failure;
- }
- removeRouteCommand->addressType = ADDR_INET6;
- } else {
- snprintf(output, output_size, "Error: %s is not a valid network address \n", addr);
- parcMemory_Deallocate(&removeRouteCommand);
- free(addr);
- return CommandReturn_Failure;
- }
-
- free(addr);
- // Fill remaining payload fields
- removeRouteCommand->len = len;
- strcpy(removeRouteCommand->symbolicOrConnid, symbolicOrConnid);
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, REMOVE_ROUTE, removeRouteCommand, sizeof(remove_route_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlRemoveRoute.h b/hicn-light/src/hicn/config/controlRemoveRoute.h
deleted file mode 100644
index 5e152b2fd..000000000
--- a/hicn-light/src/hicn/config/controlRemoveRoute.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.
- */
-
-/**
- * @file control_RemoveRoute.h
- * @brief Remove a route from the FIB
- *
- * Implements the "remove route" and "help remove route" nodes of the command
- * tree
- *
- */
-
-#ifndef Control_RemoveRoute_h
-#define Control_RemoveRoute_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlRemoveRoute_Create(ControlState *state);
-CommandOps *controlRemoveRoute_HelpCreate(ControlState *state);
-#endif // Control_RemoveRoute_h
diff --git a/hicn-light/src/hicn/config/controlRoot.c b/hicn-light/src/hicn/config/controlRoot.c
deleted file mode 100644
index 39a1fa6b5..000000000
--- a/hicn-light/src/hicn/config/controlRoot.c
+++ /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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/config/controlAdd.h>
-#include <hicn/config/controlCache.h>
-#include <hicn/config/controlList.h>
-#include <hicn/config/controlMapMe.h>
-#include <hicn/config/controlQuit.h>
-#include <hicn/config/controlRemove.h>
-#include <hicn/config/controlRoot.h>
-#include <hicn/config/controlSet.h>
-#include <hicn/config/controlUnset.h>
-#ifdef WITH_POLICY
-#include <hicn/config/controlUpdate.h>
-#endif /* WITH_POLICY */
-
-static void _controlRoot_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlRoot_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlRoot_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandRoot = "";
-static const char *_commandRootHelp = "help";
-
-// ====================================================
-
-CommandOps *controlRoot_Create(ControlState *state) {
- return commandOps_Create(state, _commandRoot, _controlRoot_Init,
- _controlRoot_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlRoot_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandRootHelp, NULL,
- _controlRoot_HelpExecute, commandOps_Destroy);
-}
-
-// ===================================================
-
-static CommandReturn _controlRoot_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- size_t output_offset = snprintf(output, output_size, "Command-line execution:\n"
- " controller [--server <server-ip>] [--port <server-port>] "
- "command\n"
- "\n"
- "Interactive execution:\n"
- " controller [--server <server-ip>] [--port <server-port>]\n"
- "\n"
- "If the keystore is not specified, the default path is used. Keystore "
- "must exist prior to running program.\n"
- "If the password is not specified, the user will be prompted.\n"
- "\n");
-
- CommandOps *ops_help_add = controlAdd_CreateHelp(NULL);
- CommandOps *ops_help_list = controlList_HelpCreate(NULL);
- CommandOps *ops_help_quit = controlQuit_HelpCreate(NULL);
- CommandOps *ops_help_remove = controlRemove_HelpCreate(NULL);
- CommandOps *ops_help_set = controlSet_HelpCreate(NULL);
- CommandOps *ops_help_unset = controlUnset_HelpCreate(NULL);
- CommandOps *ops_help_cache = controlCache_HelpCreate(NULL);
- CommandOps *ops_help_mapme = controlMapMe_HelpCreate(NULL);
-#ifdef WITH_POLICY
- CommandOps *ops_help_update = controlUpdate_HelpCreate(NULL);
-#endif /* WITH_POLICY */
-
- snprintf(output + output_offset, output_size - output_offset,"Available commands:\n"
- " %s\n"
- " %s\n"
- " %s\n"
- " %s\n"
- " %s\n"
- " %s\n"
- " %s\n"
- " %s\n"
-#ifdef WITH_POLICY
- " %s\n"
-#endif /* WITH_POLICY */
- "\n",
- ops_help_add->command,
- ops_help_list->command,
- ops_help_quit->command,
- ops_help_remove->command,
- ops_help_set->command,
- ops_help_unset->command,
- ops_help_cache->command,
- ops_help_mapme->command
-#ifdef WITH_POLICY
- , ops_help_update->command
-#endif /* WITH_POLICY */
- );
-
- commandOps_Destroy(&ops_help_add);
- commandOps_Destroy(&ops_help_list);
- commandOps_Destroy(&ops_help_quit);
- commandOps_Destroy(&ops_help_remove);
- commandOps_Destroy(&ops_help_set);
- commandOps_Destroy(&ops_help_unset);
- commandOps_Destroy(&ops_help_cache);
- commandOps_Destroy(&ops_help_mapme);
-#ifdef WITH_POLICY
- commandOps_Destroy(&ops_help_update);
-#endif /* WITH_POLICY */
-
- return CommandReturn_Success;
-}
-
-static void _controlRoot_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
-
- controlState_RegisterCommand(state, controlAdd_CreateHelp(state));
- controlState_RegisterCommand(state, controlList_HelpCreate(state));
- controlState_RegisterCommand(state, controlQuit_HelpCreate(state));
- controlState_RegisterCommand(state, controlRemove_HelpCreate(state));
- controlState_RegisterCommand(state, controlSet_HelpCreate(state));
- controlState_RegisterCommand(state, controlUnset_HelpCreate(state));
- controlState_RegisterCommand(state, controlCache_HelpCreate(state));
- controlState_RegisterCommand(state, controlMapMe_HelpCreate(state));
-#ifdef WITH_POLICY
- controlState_RegisterCommand(state, controlUpdate_HelpCreate(state));
-#endif /* WITH_POLICY */
-
- controlState_RegisterCommand(state, webControlAdd_Create(state));
- controlState_RegisterCommand(state, controlList_Create(state));
- controlState_RegisterCommand(state, controlQuit_Create(state));
- controlState_RegisterCommand(state, controlRemove_Create(state));
- controlState_RegisterCommand(state, controlSet_Create(state));
- controlState_RegisterCommand(state, controlUnset_Create(state));
- controlState_RegisterCommand(state, controlCache_Create(state));
- controlState_RegisterCommand(state, controlMapMe_Create(state));
-#ifdef WITH_POLICY
- controlState_RegisterCommand(state, controlUpdate_Create(state));
-#endif /* WITH_POLICY */
-}
-
-static CommandReturn _controlRoot_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return CommandReturn_Success;
-}
-
-// ======================================================================
diff --git a/hicn-light/src/hicn/config/controlRoot.h b/hicn-light/src/hicn/config/controlRoot.h
deleted file mode 100644
index 154b81a80..000000000
--- a/hicn-light/src/hicn/config/controlRoot.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.
- */
-
-/**
- * @file control_Root.h
- * @brief Root of the command tree
- *
- * Implements the root of the command tree. This is the one module that
- * needs to be seeded to the control state to build the whole tree.
- *
- */
-
-#ifndef Control_Root_h
-#define Control_Root_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlRoot_Create(ControlState *state);
-CommandOps *controlRoot_HelpCreate(ControlState *state);
-#endif // Control_Root_h
diff --git a/hicn-light/src/hicn/config/controlSet.c b/hicn-light/src/hicn/config/controlSet.c
deleted file mode 100644
index 37d56e593..000000000
--- a/hicn-light/src/hicn/config/controlSet.c
+++ /dev/null
@@ -1,98 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/security/parc_Security.h>
-
-#include <hicn/config/controlSet.h>
-#include <hicn/config/controlSetDebug.h>
-#include <hicn/config/controlSetStrategy.h>
-#include <hicn/config/controlSetWldr.h>
-
-static void _controlSet_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlSet_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlSet_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandSet = "set";
-static const char *_commandSetHelp = "help set";
-
-// ===========================================================
-
-CommandOps *controlSet_Create(ControlState *state) {
- return commandOps_Create(state, _commandSet, _controlSet_Init,
- _controlSet_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlSet_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandSetHelp, NULL,
- _controlSet_HelpExecute, commandOps_Destroy);
-}
-
-// ===========================================================
-
-static void _controlSet_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- controlState_RegisterCommand(state, controlSetDebug_Create(state));
- controlState_RegisterCommand(state, controlSetDebug_HelpCreate(state));
- controlState_RegisterCommand(state, controlSetStrategy_Create(state));
- controlState_RegisterCommand(state, controlSetStrategy_HelpCreate(state));
- controlState_RegisterCommand(state, controlSetWldr_Create(state));
- controlState_RegisterCommand(state, controlSetWldr_HelpCreate(state));
-}
-
-static CommandReturn _controlSet_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- CommandOps *ops_help_set_debug = controlSetDebug_HelpCreate(NULL);
- CommandOps *ops_help_set_strategy = controlSetStrategy_HelpCreate(NULL);
- CommandOps *ops_help_set_wldr = controlSetWldr_HelpCreate(NULL);
-
- snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n\n",
- ops_help_set_debug->command,
- ops_help_set_strategy->command,
- ops_help_set_wldr->command);
-
- commandOps_Destroy(&ops_help_set_debug);
- commandOps_Destroy(&ops_help_set_strategy);
- commandOps_Destroy(&ops_help_set_wldr);
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlSet_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlSet_HelpExecute(parser, ops, args, output, output_size);
-}
diff --git a/hicn-light/src/hicn/config/controlSet.h b/hicn-light/src/hicn/config/controlSet.h
deleted file mode 100644
index abe2a611d..000000000
--- a/hicn-light/src/hicn/config/controlSet.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.
- */
-
-/**
- * @file control_Set.h
- * @brief Implements the set node of the CLI tree
- *
- * Implements the "set" and "help set" nodes of the command tree
- *
- */
-#ifndef Control_Set_h
-#define Control_Set_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlSet_Create(ControlState *state);
-CommandOps *controlSet_HelpCreate(ControlState *state);
-#endif // Control_Set_h
diff --git a/hicn-light/src/hicn/config/controlSetDebug.c b/hicn-light/src/hicn/config/controlSetDebug.c
deleted file mode 100644
index a5dcc89c1..000000000
--- a/hicn-light/src/hicn/config/controlSetDebug.c
+++ /dev/null
@@ -1,81 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlSetDebug.h>
-#include <hicn/core/dispatcher.h>
-#include <hicn/core/forwarder.h>
-
-static CommandReturn _controlSetDebug_Execute(CommandParser *parser,
- CommandOps *ops, PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlSetDebug_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandSetDebug = "set debug";
-static const char *_commandSetDebugHelp = "help set debug";
-
-// ====================================================
-
-CommandOps *controlSetDebug_Create(ControlState *state) {
- return commandOps_Create(state, _commandSetDebug, NULL,
- _controlSetDebug_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlSetDebug_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandSetDebugHelp, NULL,
- _controlSetDebug_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlSetDebug_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "set debug: will enable the debug flag for more verbose output\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlSetDebug_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlSetDebug_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- ControlState *state = ops->closure;
- controlState_SetDebug(state, true);
- snprintf(output, output_size, "Debug flag set\n\n");
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlSetDebug.h b/hicn-light/src/hicn/config/controlSetDebug.h
deleted file mode 100644
index fabeb6952..000000000
--- a/hicn-light/src/hicn/config/controlSetDebug.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.
- */
-
-/**
- * @file control_SetDebug.h
- * @brief Sets the debug flag for more verbose output
- *
- * Implements the "set debug" and "help set debug" nodes of the command tree
- *
- */
-
-#ifndef Control_SetDebug_h
-#define Control_SetDebug_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlSetDebug_Create(ControlState *state);
-CommandOps *controlSetDebug_HelpCreate(ControlState *state);
-#endif // Control_SetDebug_h
diff --git a/hicn-light/src/hicn/config/controlSetStrategy.c b/hicn-light/src/hicn/config/controlSetStrategy.c
deleted file mode 100644
index fe0ba84a0..000000000
--- a/hicn-light/src/hicn/config/controlSetStrategy.c
+++ /dev/null
@@ -1,264 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <hicn/config/controlSetDebug.h>
-#include <hicn/core/dispatcher.h>
-#include <hicn/core/forwarder.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlSetStrategy_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlSetStrategy_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandSetStrategy = "set strategy";
-static const char *_commandSetStrategyHelp = "help set strategy";
-
-static const char *_commandSetStrategyOptions[LAST_STRATEGY_VALUE] = {
- "loadbalancer",
- "random",
- "low_latency",
-};
-
-// ====================================================
-
-CommandOps *controlSetStrategy_Create(ControlState *state) {
- return commandOps_Create(state, _commandSetStrategy, NULL,
- _controlSetStrategy_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlSetStrategy_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandSetStrategyHelp, NULL,
- _controlSetStrategy_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-strategy_type _validStrategy(const char *strategy) {
- strategy_type validStrategy = LAST_STRATEGY_VALUE;
-
- for (int i = 0; i < LAST_STRATEGY_VALUE; i++) {
- if (strcmp(_commandSetStrategyOptions[i], strategy) == 0) {
- validStrategy = i;
- break;
- }
- }
- return validStrategy;
-}
-
-static void _getAddressAndLen(const char * prefixStr, char *addr, uint32_t *len){
- char *slash;
- strcpy(addr, prefixStr);
- slash = strrchr(addr, '/');
- if (slash != NULL) {
- *len = atoi(slash + 1);
- *slash = '\0';
- }
-}
-
-static bool _checkAndSetIp(set_strategy_command * setStrategyCommand,
- int index,
- char * addr,
- uint32_t len,
- char *output,
- size_t output_size){
- // check and set IP address
- int res;
- if(index == -1)
- res = inet_pton(AF_INET, addr, &setStrategyCommand->address.v4.as_u32);
- else
- res = inet_pton(AF_INET, addr,
- &setStrategyCommand->addresses[index].v4.as_u32);
-
- if(res == 1) {
- if (len == UINT32_MAX) {
- snprintf(output, output_size, "Netmask not specified: set to 32 by default\n");
- len = 32;
- } else if (len > 32) {
- snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n");
- return false;
- }
- if(index == -1)
- setStrategyCommand->addressType = ADDR_INET;
- else
- setStrategyCommand->addresses_type[index] = ADDR_INET;
-
- } else {
-
- if(index == -1)
- res = inet_pton(AF_INET6, addr,
- &setStrategyCommand->address.v6.as_in6addr);
- else
- res = inet_pton(AF_INET6, addr,
- &setStrategyCommand->addresses[index].v6.as_in6addr);
-
- if(res == 1) {
- if (len == UINT32_MAX) {
- snprintf(output, output_size, "Netmask not specified: set to 128 by default\n");
- len = 128;
- } else if (len > 128) {
- snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n");
- return false;
- }
-
- if(index == -1)
- setStrategyCommand->addressType = ADDR_INET6;
- else
- setStrategyCommand->addresses_type[index] = ADDR_INET6;
-
- } else {
- snprintf(output, output_size, "Error: %s is not a valid network address \n", addr);
-
- return false;
- }
- }
- return true;
-}
-
-static CommandReturn _controlSetStrategy_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size,
- "set strategy <prefix> <strategy> "
- "[related_prefix1 related_preifx2 ...]\n"
- "prefix: ipv4/ipv6 address (ex: 1234::/64)\n"
- "strategy: strategy identifier\n"
- "optinal: list of related prefixes (max %u)\n"
- "available strategies:\n"
- " random\n"
- " loadbalancer\n"
- " low_latency\n\n",
- MAX_FWD_STRATEGY_RELATED_PREFIXES);
- return CommandReturn_Success;
-}
-
-
-static CommandReturn _controlSetStrategy_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (output) {
- output[0] = '\0';
- }
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) < 4 ||
- parcList_Size(args) > (4 + MAX_FWD_STRATEGY_RELATED_PREFIXES)) {
- _controlSetStrategy_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- if (((strcmp(parcList_GetAtIndex(args, 0), "set") != 0) ||
- (strcmp(parcList_GetAtIndex(args, 1), "strategy") != 0))) {
- _controlSetStrategy_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *prefixStr = parcList_GetAtIndex(args, 2);
- char *addr = (char *)malloc(sizeof(char) * (strlen(prefixStr) + 1));
- uint32_t len = UINT32_MAX;
- _getAddressAndLen(prefixStr, addr, &len);
-
- // allocate command payload
- set_strategy_command *setStrategyCommand =
- parcMemory_AllocateAndClear(sizeof(set_strategy_command));
-
- bool success = _checkAndSetIp(setStrategyCommand, -1, addr, len, output, output_size);
- if(!success){
- parcMemory_Deallocate(&setStrategyCommand);
- free(addr);
- return CommandReturn_Failure;
- }
-
- const char *strategyStr = parcList_GetAtIndex(args, 3);
- // check valid strategy
- strategy_type strategy;
- if ((strategy = _validStrategy(strategyStr)) == LAST_STRATEGY_VALUE) {
- size_t output_offset = strlen(output);
- output_offset += snprintf(output + output_offset, output_size - output_offset, "Error: invalid strategy \n");
-
- parcMemory_Deallocate(&setStrategyCommand);
- _controlSetStrategy_HelpExecute(parser, ops, args, output + output_offset, output_size - output_offset);
- free(addr);
- return CommandReturn_Failure;
- }
-
- free(addr);
-
- // Fill remaining payload fields
- setStrategyCommand->len = len;
- setStrategyCommand->strategyType = strategy;
- size_t output_offset = strlen(output);
- //check additional prefixes
- if(parcList_Size(args) > 4){
- uint32_t index = 4; //first realted prefix
- uint32_t addr_index = 0;
- setStrategyCommand->related_prefixes = (uint8_t)parcList_Size(args) - 4;
- while(index < parcList_Size(args)){
- const char *str = parcList_GetAtIndex(args, index);
- char *rel_addr = (char *)malloc(sizeof(char) * (strlen(str) + 1));
- uint32_t rel_len = UINT32_MAX;
- _getAddressAndLen(str, rel_addr, &rel_len);
- bool success = _checkAndSetIp(setStrategyCommand, addr_index,
- rel_addr, rel_len, output + output_offset, output_size - output_offset);
- if(!success){
- parcMemory_Deallocate(&setStrategyCommand);
- free(rel_addr);
- return CommandReturn_Failure;
- }
- output_offset = strlen(output);
- setStrategyCommand->lens[addr_index] = rel_len;
- free(rel_addr);
- index++;
- addr_index++;
- }
- }else{
- setStrategyCommand->related_prefixes = 0;
- }
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, SET_STRATEGY, setStrategyCommand, sizeof(set_strategy_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlSetStrategy.h b/hicn-light/src/hicn/config/controlSetStrategy.h
deleted file mode 100644
index 7ad56ccba..000000000
--- a/hicn-light/src/hicn/config/controlSetStrategy.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.
- */
-
-#ifndef Control_SetStrategy_h
-#define Control_SetStrategy_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlSetStrategy_Create(ControlState *state);
-CommandOps *controlSetStrategy_HelpCreate(ControlState *state);
-#endif // Control_SetStrategy_h
diff --git a/hicn-light/src/hicn/config/controlSetWldr.c b/hicn-light/src/hicn/config/controlSetWldr.c
deleted file mode 100644
index 0d4a7eca2..000000000
--- a/hicn-light/src/hicn/config/controlSetWldr.c
+++ /dev/null
@@ -1,131 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlSetDebug.h>
-#include <hicn/core/dispatcher.h>
-#include <hicn/core/forwarder.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlSetWldr_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlSetWldr_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandSetWldr = "set wldr";
-static const char *_commandSetWldrHelp = "help set wldr";
-
-// ====================================================
-
-CommandOps *controlSetWldr_Create(ControlState *state) {
- return commandOps_Create(state, _commandSetWldr, NULL,
- _controlSetWldr_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlSetWldr_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandSetWldrHelp, NULL,
- _controlSetWldr_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlSetWldr_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "set wldr <on|off> <connection_id>\n\n");
-
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlSetWldr_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- ControlState *state = ops->closure;
-
- if (parcList_Size(args) != 4) {
- _controlSetWldr_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- if (((strcmp(parcList_GetAtIndex(args, 0), "set") != 0) ||
- (strcmp(parcList_GetAtIndex(args, 1), "wldr") != 0))) {
- _controlSetWldr_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- bool active;
- if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) {
- active = true;
- } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) {
- active = false;
- } else {
- _controlSetWldr_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- // check if valid connid
- const char *symbolicOrConnid = parcList_GetAtIndex(args, 3);
-
- if (!utils_ValidateSymbolicName(symbolicOrConnid) &&
- !utils_IsNumber(symbolicOrConnid)) {
- snprintf(output, output_size,
- "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an "
- "alpha followed by alphanum;\nconnid must be an integer\n");
- return CommandReturn_Failure;
- }
-
- // allocate command payload
- set_wldr_command *setWldrCommand =
- parcMemory_AllocateAndClear(sizeof(set_wldr_command));
- strcpy(setWldrCommand->symbolicOrConnid, symbolicOrConnid);
- if (active) {
- setWldrCommand->activate = ACTIVATE_ON;
- } else {
- setWldrCommand->activate = ACTIVATE_OFF;
- }
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(state, SET_WLDR, setWldrCommand,
- sizeof(set_wldr_command));
-
- if (!response) { // get NULL pointer
- return CommandReturn_Failure;
- }
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlSetWldr.h b/hicn-light/src/hicn/config/controlSetWldr.h
deleted file mode 100644
index 3c01110e4..000000000
--- a/hicn-light/src/hicn/config/controlSetWldr.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.
- */
-
-#ifndef Control_SetWldr_h
-#define Control_SetWldr_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlSetWldr_Create(ControlState *state);
-CommandOps *controlSetWldr_HelpCreate(ControlState *state);
-#endif // Control_SetWldr_h
diff --git a/hicn-light/src/hicn/config/controlState.c b/hicn-light/src/hicn/config/controlState.c
deleted file mode 100644
index acdae9e52..000000000
--- a/hicn-light/src/hicn/config/controlState.c
+++ /dev/null
@@ -1,243 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <string.h>
-
-#include <parc/security/parc_Security.h>
-
-#include <parc/algol/parc_List.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <parc/algol/parc_Time.h>
-#include <parc/algol/parc_TreeRedBlack.h>
-
-#include <hicn/config/commandParser.h>
-#include <hicn/config/controlRoot.h>
-#include <hicn/config/controlState.h>
-
-#include <hicn/utils/commands.h>
-
-struct controller_state {
- CommandParser *parser;
- bool debugFlag;
-
- void *userdata;
- struct iovec *(*writeRead)(ControlState *state, struct iovec *msg);
- int sockfd;
- char **commandOutput;
- bool isInteractive;
-};
-
-int controlState_connectToFwdDeamon(char *server_ip, uint16_t port) {
- int sockfd;
- struct sockaddr_in servaddr;
-
- if ((sockfd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- printf("\nSocket Creation Failed \n");
- return EXIT_FAILURE;
- }
-
- memset(&servaddr, 0, sizeof(servaddr));
-
- // Filling server information
- servaddr.sin_family = AF_INET;
- servaddr.sin_port = htons(port);
- inet_pton(AF_INET, server_ip, &(servaddr.sin_addr.s_addr));
-
- // Establish connection
- if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
- printf("\nConnection Failed: hicn-light Daemon is not running \n");
- return -1;
- }
-
- return sockfd;
-}
-
-ControlState *controlState_Create(
- void *userdata,
- struct iovec *(*writeRead)(ControlState *state, struct iovec *msg),
- bool openControllerConnetion,
- char *server_ip, uint16_t port) {
- ControlState *state = parcMemory_AllocateAndClear(sizeof(ControlState));
- parcAssertNotNull(state, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ControlState));
- state->parser = commandParser_Create();
-
- state->userdata = userdata;
- state->writeRead = writeRead;
- state->debugFlag = false;
- state->commandOutput = NULL;
- state->isInteractive = true;
-
- if (openControllerConnetion) {
- state->sockfd = controlState_connectToFwdDeamon(server_ip, port);
- if (state->sockfd == -1) {
- return NULL;
- }
- } else {
- state->sockfd = 2; // stderr
- }
-
- return state;
-}
-
-void controlState_Destroy(ControlState **statePtr) {
- parcAssertNotNull(statePtr, "Parameter statePtr must be non-null");
- parcAssertNotNull(*statePtr,
- "Parameter statePtr must dereference t non-null");
- ControlState *state = *statePtr;
- // printf("sockid destroyed: %d\n", state->sockfd);
- // close the connection with the fwd deamon
- shutdown(state->sockfd, 2);
-
- commandParser_Destroy(&state->parser);
- parcMemory_Deallocate((void **)&state);
- *statePtr = NULL;
-}
-
-void controlState_SetDebug(ControlState *state, bool debugFlag) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- state->debugFlag = debugFlag;
- commandParser_SetDebug(state->parser, debugFlag);
-}
-
-bool controlState_GetDebug(ControlState *state) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- return state->debugFlag;
-}
-
-void controlState_RegisterCommand(ControlState *state, CommandOps *ops) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- commandParser_RegisterCommand(state->parser, ops);
-}
-
-struct iovec *controlState_WriteRead(ControlState *state, struct iovec *msg) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- parcAssertNotNull(msg, "Parameter msg must be non-null");
-
- return state->writeRead(state, msg);
-}
-
-static PARCList *_controlState_ParseStringIntoTokens(
- const char *originalString) {
- PARCList *list =
- parcList(parcArrayList_Create(parcArrayList_StdlibFreeFunction),
- PARCArrayListAsPARCList);
-
- char *token;
-
- char *tofree =
- parcMemory_StringDuplicate(originalString, strlen(originalString) + 1);
- char *string = tofree;
-
- token = strtok(string, " \t\n");
- while (token != NULL) {
- if (strlen(token) > 0) {
- parcList_Add(list, strdup(token));
- }
- token = strtok(NULL, " \t\n");
- }
-
- parcMemory_Deallocate((void **)&tofree);
-
- return list;
-}
-
-CommandReturn controlState_DispatchCommand(ControlState *state,
- PARCList *args,
- char *output,
- size_t output_size) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- return commandParser_DispatchCommand(state->parser, args, output, output_size);
-}
-
-int controlState_Interactive(ControlState *state) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- char *line = NULL;
- size_t linecap = 0;
- CommandReturn controlReturn = CommandReturn_Success;
- char output[8192];
- while (controlReturn != CommandReturn_Exit && !feof(stdin)) {
- fputs("> ", stdout);
- fflush(stdout);
- ssize_t failure = getline(&line, &linecap, stdin);
- parcAssertTrue(failure > -1, "Error getline");
-
- PARCList *args = _controlState_ParseStringIntoTokens(line);
-
- controlReturn = controlState_DispatchCommand(state, args, output, sizeof(output));
- printf("%s", output);
- // release and get command
- parcList_Release(&args);
- }
- return 0;
-}
-
-void controlState_SetCommandOutput(ControlState *state, char **commandData) {
- state->commandOutput = commandData;
-}
-
-void controlState_ReleaseCommandOutput(ControlState *state, char **commandData,
- size_t commandLenght) {
- for (size_t i = 0; i < commandLenght; i++) {
- parcMemory_Deallocate(&commandData[i]);
- }
- parcMemory_Deallocate(&commandData);
- state->commandOutput = NULL;
-}
-
-char **controlState_GetCommandOutput(ControlState *state) {
- return state->commandOutput;
-}
-
-// size_t
-// controlState_GetCommandLen(ControlState *state){
-
-// }
-
-void controlState_SetInteractiveFlag(ControlState *state, bool interactive) {
- state->isInteractive = interactive;
-}
-
-bool controlState_IsInteractive(ControlState *state) {
- return state->isInteractive;
-}
-
-int controlState_GetSockfd(ControlState *state) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- return state->sockfd;
-}
-
-void *controlState_GetUserdata(ControlState *state) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- return state->userdata;
-}
-
-bool controlState_isConfigFile(ControlState *state) {
- parcAssertNotNull(state, "Parameter state must be non-null");
- if (state->sockfd != 2) {
- return false;
- } else {
- return true;
- }
-}
diff --git a/hicn-light/src/hicn/config/controlState.h b/hicn-light/src/hicn/config/controlState.h
deleted file mode 100644
index 52b1f6655..000000000
--- a/hicn-light/src/hicn/config/controlState.h
+++ /dev/null
@@ -1,242 +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.
- */
-
-/**
- * @file controlState.h
- * @brief A control program for hicn-light using CLI commands
- *
- * Implements the state machine for the control program. It takes a "writeRead"
- * function as part of the constructor. This abstracts out the backend. It
- * could be a Portal from hicnLightControl program down to the forwarder or it
- * could be an internal function within hicn-light.
- *
- */
-
-#ifndef control_h
-#define control_h
-
-#include <parc/algol/parc_List.h>
-#include <hicn/config/commandParser.h>
-
-#include <hicn/utils/commands.h>
-
-#define SRV_CTRL_IP "127.0.0.1"
-#define SRV_CTRL_PORT 9695
-
-struct controller_state;
-typedef struct controller_state ControlState;
-
-/**
- * controlState_Create
- *
- * Creates the global state for the Control program. The user provides the
- * writeRead function for sending and receiving the message wrapping command
- * arguments. For configuration file inside hicn-light, it would make direct
- * calls to Configuration -> Dispatcher.
- *
- * @param [in] userdata A closure passed back to the user when calling
- * writeRead.
- * @param [in] writeRead The function to write then read configuration messages
- * to hicn-light
- *
- * @return non-null The control state
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-
-ControlState *controlState_Create(
- void *userdata,
- struct iovec *(*writeRead)(ControlState *state, struct iovec *msg),
- bool openControllerConnetion,
- char * server_ip, uint16_t port);
-
-/**
- * Destroys the control state, closing all network connections
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void controlState_Destroy(ControlState **statePtr);
-
-/**
- * Registers a CommandOps with the system.
- *
- * Each command has its complete command prefix in the "command" field.
- * RegisterCommand will put these command prefixes in to a tree and then match
- * what a user types against the longest-matching prefix in the tree. If
- * there's a match, it will call the "execute" function.
- *
- * @param [in] state An allocated ControlState
- * @param [in] command The command to register with the system
- *
- * Example:
- * @code
- * static CommandReturn
- * control_Root_Execute(CommandParser *parser, CommandOps *ops, PARCList
- * *args)
- * {
- * printf("Root Command\n");
- * return CommandReturn_Success;
- * }
- *
- * static CommandReturn
- * control_FooBar_Execute(CommandParser *parser, CommandOps *ops, PARCList
- * *args)
- * {
- * printf("Foo Bar Command\n");
- * return CommandReturn_Success;
- * }
- *
- * const CommandOps control_Root = {
- * .command = "", // empty string for root
- * .init = NULL,
- * .execute = control_Root_Execute
- * };
- *
- * const CommandOps control_FooBar = {
- * .command = "foo bar", // empty string for root
- * .init = NULL,
- * .execute = control_FooBar_Execute
- * };
- *
- * void startup(void)
- * {
- * ControlState *state = controlState_Create("happy", "day");
- * controlState_RegisterCommand(state, control_FooBar);
- * controlState_RegisterCommand(state, control_Root);
- *
- * // this executes "root"
- * controlState_DispatchCommand(state, "foo");
- * controlState_Destroy(&state);
- * }
- * @endcode
- */
-void controlState_RegisterCommand(ControlState *state, CommandOps *command);
-
-/**
- * Performs a longest-matching prefix of the args to the command tree
- *
- * The command tree is created with controlState_RegisterCommand.
- *
- * @param [in] state The allocated ControlState
- * @param [in] args Each command_line word parsed to the ordered list
- * @param [in] output Output string
- * @param [in] output_length output string max length
- *
- * @return CommandReturn_Success the command was successful
- * @return CommandReturn_Failure the command failed or was not found
- * @return CommandReturn_Exit the command indicates that the interactive mode
- * should exit
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-CommandReturn controlState_DispatchCommand(ControlState *state,
- PARCList *args,
- char *output,
- size_t output_length);
-
-/**
- * Begin an interactive shell
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-int controlState_Interactive(ControlState *state);
-
-/**
- * Write then Read a command
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-struct iovec *controlState_WriteRead(ControlState *state, struct iovec *msg);
-
-/**
- * Sets the Debug mode, which will print out much more information.
- *
- * Prints out much more diagnostic information about what hicn-light controller
- * is doing. yes, you would make a CommandOps to set and unset this :)
- *
- * @param [in] debugFlag true means to print debug info, false means to turn it
- * off
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void controlState_SetDebug(ControlState *state, bool debugFlag);
-
-/**
- * Returns the debug state of ControlState
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @return <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-bool controlState_GetDebug(ControlState *state);
-#endif // control_h
-
-void controlState_SetCommandOutput(ControlState *state, char **commandData);
-
-void controlState_ReleaseCommandOutput(ControlState *state, char **commandData,
- size_t commandLenght);
-
-char **controlState_GetCommandOutput(ControlState *state);
-
-void controlState_SetInteractiveFlag(ControlState *state, bool interactive);
-
-bool controlState_IsInteractive(ControlState *state);
-
-void *controlState_GetUserdata(ControlState *state);
-
-bool controlState_isConfigFile(ControlState *state);
-
-int controlState_GetSockfd(ControlState *state);
diff --git a/hicn-light/src/hicn/config/controlUnset.c b/hicn-light/src/hicn/config/controlUnset.c
deleted file mode 100644
index e05ba2286..000000000
--- a/hicn-light/src/hicn/config/controlUnset.c
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/security/parc_Security.h>
-
-#include <hicn/config/controlUnset.h>
-#include <hicn/config/controlUnsetDebug.h>
-
-static void _controlUnset_Init(CommandParser *parser, CommandOps *ops);
-
-static CommandReturn _controlUnset_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlUnset_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandUnset = "unset";
-static const char *_commandUnsetHelp = "help unset";
-
-// ===========================================================
-
-CommandOps *controlUnset_Create(ControlState *state) {
- return commandOps_Create(state, _commandUnset, _controlUnset_Init,
- _controlUnset_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlUnset_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandUnsetHelp, NULL,
- _controlUnset_HelpExecute, commandOps_Destroy);
-}
-
-// ===========================================================
-
-static void _controlUnset_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- controlState_RegisterCommand(state, controlUnsetDebug_Create(state));
- controlState_RegisterCommand(state, controlUnsetDebug_HelpCreate(state));
-}
-
-static CommandReturn _controlUnset_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- CommandOps *ops_help_unset_debug = controlUnsetDebug_HelpCreate(NULL);
- snprintf(output, output_size, "Available commands:\n %s\n\n", ops_help_unset_debug->command);
-
- commandOps_Destroy(&ops_help_unset_debug);
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlUnset_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlUnset_HelpExecute(parser, ops, args, output, output_size);
-}
diff --git a/hicn-light/src/hicn/config/controlUnset.h b/hicn-light/src/hicn/config/controlUnset.h
deleted file mode 100644
index 9d9cb5c44..000000000
--- a/hicn-light/src/hicn/config/controlUnset.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.
- */
-
-/**
- * @file control_Unset.h
- * @brief Implements the unset node of the CLI tree
- *
- * Implements the "unset" and "help unset" nodes of the command tree
- *
- */
-#ifndef Control_Unset_h
-#define Control_Unset_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlUnset_Create(ControlState *state);
-CommandOps *controlUnset_HelpCreate(ControlState *state);
-#endif // Control_Unset_h
diff --git a/hicn-light/src/hicn/config/controlUnsetDebug.c b/hicn-light/src/hicn/config/controlUnsetDebug.c
deleted file mode 100644
index ac2a4e028..000000000
--- a/hicn-light/src/hicn/config/controlUnsetDebug.c
+++ /dev/null
@@ -1,83 +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/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlUnsetDebug.h>
-#include <hicn/core/dispatcher.h>
-#include <hicn/core/forwarder.h>
-
-static CommandReturn _controlUnsetDebug_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlUnsetDebug_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandUnsetDebug = "unset debug";
-static const char *_commandUnsetDebugHelp = "help unset debug";
-
-// ====================================================
-
-CommandOps *controlUnsetDebug_Create(ControlState *state) {
- return commandOps_Create(state, _commandUnsetDebug, NULL,
- _controlUnsetDebug_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlUnsetDebug_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandUnsetDebugHelp, NULL,
- _controlUnsetDebug_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static CommandReturn _controlUnsetDebug_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- snprintf(output, output_size, "unset debug: will disable the debug flag\n\n");
- return CommandReturn_Success;
-}
-
-static CommandReturn _controlUnsetDebug_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if (parcList_Size(args) != 2) {
- _controlUnsetDebug_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- ControlState *state = ops->closure;
- controlState_SetDebug(state, false);
- snprintf(output, output_size, "Debug flag cleared\n\n");
-
- return CommandReturn_Success;
-}
diff --git a/hicn-light/src/hicn/config/controlUnsetDebug.h b/hicn-light/src/hicn/config/controlUnsetDebug.h
deleted file mode 100644
index c76ba8c98..000000000
--- a/hicn-light/src/hicn/config/controlUnsetDebug.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.
- */
-
-/**
- * @file control_UnsetDebug.h
- * @brief Unsets the debug flag for more verbose output
- *
- * Implements the "unset debug" and "help unset debug" nodes of the CLI tree
- *
- */
-
-#ifndef Control_UnsetDebug_h
-#define Control_UnsetDebug_h
-
-#include <hicn/config/controlState.h>
-CommandOps *controlUnsetDebug_Create(ControlState *state);
-CommandOps *controlUnsetDebug_HelpCreate(ControlState *state);
-#endif // Control_UnsetDebug_h
diff --git a/hicn-light/src/hicn/config/controlUpdate.c b/hicn-light/src/hicn/config/controlUpdate.c
deleted file mode 100644
index 095bbf01e..000000000
--- a/hicn-light/src/hicn/config/controlUpdate.c
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef WITH_POLICY
-
-#include <hicn/hicn-light/config.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/security/parc_Security.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/config/controlUpdate.h>
-#include <hicn/config/controlUpdateConnection.h>
-
-static void _controlUpdate_Init(CommandParser *parser, CommandOps *ops);
-static CommandReturn _controlUpdate_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlUpdate_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *_commandUpdate = "update";
-static const char *_commandUpdateHelp = "help update";
-
-CommandOps *controlUpdate_Create(ControlState *state) {
- return commandOps_Create(state, _commandUpdate, _controlUpdate_Init,
- _controlUpdate_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlUpdate_HelpCreate(ControlState *state) {
- return commandOps_Create(state, _commandUpdateHelp, NULL,
- _controlUpdate_HelpExecute, commandOps_Destroy);
-}
-
-// =====================================================
-
-static CommandReturn _controlUpdate_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- //CommandOps *ops_update_connections = controlUpdateConnections_HelpCreate(NULL);
- // CommandOps *ops_update_interfaces = controlUpdateInterfaces_HelpCreate(NULL);
- //CommandOps *ops_update_routes = controlUpdateRoutes_HelpCreate(NULL);
- CommandOps *ops_update_listeners = controlUpdateConnection_HelpCreate(NULL);
- snprintf(output, output_size,
- "Available commands:\n %s\n\n",
- ops_update_listeners->command);
-
-
-
- // commandOps_Destroy(&ops_update_connections);
- // commandOps_Destroy(&ops_update_interfaces);
- //commandOps_Destroy(&ops_update_routes);
- commandOps_Destroy(&ops_update_listeners);
-
- return CommandReturn_Success;
-}
-
-static void _controlUpdate_Init(CommandParser *parser, CommandOps *ops) {
- ControlState *state = ops->closure;
- //controlState_RegisterCommand(state, controlUpdateConnections_HelpCreate(state));
- // controlState_RegisterCommand(state,
- // controlUpdateInterfaces_HelpCreate(state));
- controlState_RegisterCommand(state, controlUpdateConnection_HelpCreate(state));
- //controlState_RegisterCommand(state, controlUpdateRoutes_HelpCreate(state));
- //controlState_RegisterCommand(state, controlUpdateConnections_Create(state));
- // controlState_RegisterCommand(state, controlUpdateInterfaces_Create(state));
- //controlState_RegisterCommand(state, controlUpdateRoutes_Create(state));
- controlState_RegisterCommand(state, controlUpdateConnection_Create(state));
-}
-
-static CommandReturn _controlUpdate_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- return _controlUpdate_HelpExecute(parser, ops, args, output, output_size);
-}
-
-#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/config/controlUpdateConnection.c b/hicn-light/src/hicn/config/controlUpdateConnection.c
deleted file mode 100644
index 70a017d4f..000000000
--- a/hicn-light/src/hicn/config/controlUpdateConnection.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef WITH_POLICY
-
-#include <hicn/hicn-light/config.h>
-
-#include <ctype.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <hicn/config/controlUpdateConnection.h>
-
-#include <hicn/policy.h>
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-static CommandReturn _controlUpdateConnection_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-static CommandReturn _controlUpdateConnection_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size);
-
-static const char *command_update_connection = "update connection";
-static const char *command_help_update_connection = "help update connection";
-
-CommandOps *controlUpdateConnection_Create(ControlState *state) {
- return commandOps_Create(state, command_update_connection, NULL,
- _controlUpdateConnection_Execute, commandOps_Destroy);
-}
-
-CommandOps *controlUpdateConnection_HelpCreate(ControlState *state) {
- return commandOps_Create(state, command_help_update_connection, NULL,
- _controlUpdateConnection_HelpExecute, commandOps_Destroy);
-}
-
-// ====================================================
-
-static const int _indexSymbolic = 2;
-static const int _indexTags = 3;
-
-static CommandReturn _controlUpdateConnection_HelpExecute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
-
- snprintf(output, output_size,
- "commands:\n"
- " update connection <symbolic | id> <tags> \n"
- "\n"
- " symbolic: User defined name for connection, must start with "
- "alpha and be alphanum\n"
- " id: Identifier for the connection\n"
- " tags: A string representing tags\n");
- return CommandReturn_Success;
-}
-
-
-static CommandReturn _controlUpdateConnection_Execute(CommandParser *parser,
- CommandOps *ops,
- PARCList *args,
- char *output,
- size_t output_size) {
- if ((parcList_Size(args) != 3) && (parcList_Size(args) != 4)) {
- _controlUpdateConnection_HelpExecute(parser, ops, args, output, output_size);
- return CommandReturn_Failure;
- }
-
- const char *symbolicOrConnid = parcList_GetAtIndex(args, _indexSymbolic);
-
- if (!utils_ValidateSymbolicName(symbolicOrConnid) &&
- !utils_IsNumber(symbolicOrConnid)) {
- snprintf(output, output_size,
- "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an "
- "alpha followed by alphanum;\nconnid must be an integer\n");
- return CommandReturn_Failure;
- }
-
- policy_tags_t tags = POLICY_TAGS_EMPTY;
- if (parcList_Size(args) == 4) {
- const char *str_tags = parcList_GetAtIndex(args, _indexTags);
-
- for (unsigned i = 0; str_tags[i] != 0; i++) {
- switch(tolower(str_tags[i])) {
- case 'e':
- policy_tags_add(&tags, POLICY_TAG_WIRED);
- break;
- case 'w':
- policy_tags_add(&tags, POLICY_TAG_WIFI);
- break;
- case 'c':
- policy_tags_add(&tags, POLICY_TAG_CELLULAR);
- break;
- case 'b':
- policy_tags_add(&tags, POLICY_TAG_BEST_EFFORT);
- break;
- case 'r':
- policy_tags_add(&tags, POLICY_TAG_REALTIME);
- break;
- case 'm':
- policy_tags_add(&tags, POLICY_TAG_MULTIPATH);
- break;
- case 't':
- policy_tags_add(&tags, POLICY_TAG_TRUSTED);
- break;
- }
- }
- }
- ControlState *state = ops->closure;
-
- // allocate command payload
- update_connection_command *updateConnectionCommand =
- parcMemory_AllocateAndClear(sizeof(update_connection_command));
- updateConnectionCommand->tags = tags;
- strcpy(updateConnectionCommand->symbolicOrConnid, symbolicOrConnid);
-
- // send message and receive response
- struct iovec *response = utils_SendRequest(
- state, UPDATE_CONNECTION, updateConnectionCommand, sizeof(update_connection_command));
-
- if (!response) // get NULL pointer
- return CommandReturn_Failure;
-
- parcMemory_Deallocate(&response); // free iovec pointer
- return CommandReturn_Success;
-}
-
-#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/config/symbolicNameTable.c b/hicn-light/src/hicn/config/symbolicNameTable.c
deleted file mode 100644
index e5ae81d3e..000000000
--- a/hicn-light/src/hicn/config/symbolicNameTable.c
+++ /dev/null
@@ -1,191 +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 <ctype.h>
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_HashCodeTable.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/config/symbolicNameTable.h>
-
-struct symblic_name_table {
- PARCHashCodeTable *symbolicNameTable;
- PARCHashCodeTable *indexToNameTable;
-};
-
-// ========================================================================================
-// symbolic name table functions
-
-static bool _symbolicNameEquals(const void *keyA, const void *keyB) {
- return (strcasecmp((const char *)keyA, (const char *)keyB) == 0);
-}
-
-static HashCodeType _symbolicNameHash(const void *keyA) {
- const char *str = (const char *)keyA;
- size_t length = strlen(str);
- return parcHash32_Data(str, length);
-}
-
-static bool _connectionIdEquals(const void *keyA, const void *keyB) {
- unsigned idA = *((unsigned *)keyA);
- unsigned idB = *((unsigned *)keyB);
- return (idA == idB);
-}
-
-static HashCodeType _connectionIdHash(const void *keyA) {
- unsigned idA = *((unsigned *)keyA);
- return parcHash32_Int32(idA);
-}
-
-// ========================================================================================
-
-SymbolicNameTable *symbolicNameTable_Create(void) {
- SymbolicNameTable *table = parcMemory_Allocate(sizeof(SymbolicNameTable));
-
- if (table) {
- // key = char *
- // value = uint32_t *
- table->symbolicNameTable = parcHashCodeTable_Create(
- _symbolicNameEquals, _symbolicNameHash, parcMemory_DeallocateImpl,
- parcMemory_DeallocateImpl);
- table->indexToNameTable = parcHashCodeTable_Create(
- _connectionIdEquals, _connectionIdHash, parcMemory_DeallocateImpl,
- parcMemory_DeallocateImpl);
- }
-
- return table;
-}
-
-void symbolicNameTable_Destroy(SymbolicNameTable **tablePtr) {
- SymbolicNameTable *table = *tablePtr;
- parcHashCodeTable_Destroy(&table->symbolicNameTable);
- parcHashCodeTable_Destroy(&table->indexToNameTable);
- parcMemory_Deallocate((void **)&table);
- *tablePtr = NULL;
-}
-
-static char *_createKey(const char *symbolicName) {
- char *key = parcMemory_StringDuplicate(symbolicName, strlen(symbolicName));
-
- // convert key to upper case
- char *p = key;
-
- // keeps looping until the first null
- while ((*p = toupper(*p))) {
- p++;
- }
- return key;
-}
-
-bool symbolicNameTable_Exists(SymbolicNameTable *table,
- const char *symbolicName) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null");
-
- char *key = _createKey(symbolicName);
- bool found = (parcHashCodeTable_Get(table->symbolicNameTable, key) != NULL);
- parcMemory_Deallocate((void **)&key);
- return found;
-}
-
-void symbolicNameTable_Remove(SymbolicNameTable *table,
- const char *symbolicName) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null");
-
- char *key = _createKey(symbolicName);
-
- unsigned id = symbolicNameTable_Get(table, symbolicName);
- uint32_t *value = parcMemory_Allocate(sizeof(uint32_t));
- *value = id;
-
- parcHashCodeTable_Del(table->symbolicNameTable, key);
- parcHashCodeTable_Del(table->indexToNameTable, value);
- parcMemory_Deallocate((void **)&key);
- parcMemory_Deallocate((void **)&value);
-}
-
-bool symbolicNameTable_Add(SymbolicNameTable *table, const char *symbolicName,
- unsigned connid) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null");
- parcAssertTrue(connid < UINT32_MAX, "Parameter connid must be less than %u",
- UINT32_MAX);
-
- char *key1 = _createKey(symbolicName);
-
- uint32_t *value1 = parcMemory_Allocate(sizeof(uint32_t));
- *value1 = connid;
-
- bool success = parcHashCodeTable_Add(table->symbolicNameTable, key1, value1);
- if (!success)
- goto ERR_NAME;
-
- char *key2 = _createKey(symbolicName);
-
- uint32_t *value2 = parcMemory_Allocate(sizeof(uint32_t));
- *value2 = connid;
-
- success = parcHashCodeTable_Add(table->indexToNameTable, value2, key2);
- if (!success)
- goto ERR_INDEX;
-
- goto END;
-
-ERR_INDEX:
- parcMemory_Deallocate((void **)&key2);
- parcMemory_Deallocate((void **)&value2);
- parcHashCodeTable_Del(table->symbolicNameTable, key1);
-ERR_NAME:
- parcMemory_Deallocate((void **)&key1);
- parcMemory_Deallocate((void **)&value1);
-END:
- return success;
-
-}
-
-unsigned symbolicNameTable_Get(SymbolicNameTable *table,
- const char *symbolicName) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null");
-
- unsigned connid = UINT32_MAX;
-
- char *key = _createKey(symbolicName);
-
- uint32_t *value = parcHashCodeTable_Get(table->symbolicNameTable, key);
- if (value)
- connid = *value;
-
- parcMemory_Deallocate((void **)&key);
- return connid;
-}
-
-const char *symbolicNameTable_GetNameByIndex(SymbolicNameTable *table,
- unsigned id) {
- parcAssertNotNull(table, "Parameter table must be non-null");
-
- uint32_t *value = parcMemory_Allocate(sizeof(uint32_t));
- *value = id;
-
- const char *name = parcHashCodeTable_Get(table->indexToNameTable, value);
- if (name == NULL) name = "";
-
- parcMemory_Deallocate((void **)&value);
- return name;
-}
diff --git a/hicn-light/src/hicn/config/symbolicNameTable.h b/hicn-light/src/hicn/config/symbolicNameTable.h
deleted file mode 100644
index 69919cf00..000000000
--- a/hicn-light/src/hicn/config/symbolicNameTable.h
+++ /dev/null
@@ -1,131 +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.
- */
-
-/**
- * @file symbolicNameTable.h
- * @brief The symbolic name table maps a string name to a connection id
- *
- * When configuring tunnels/connections, the user provides a string name
- * (symbolic name) that they will use to refer to that connection. The symblic
- * name table translates that symbolic name to a connection id.
- *
- */
-
-#ifndef symbolicNameTable_h
-#define symbolicNameTable_h
-
-struct symblic_name_table;
-typedef struct symblic_name_table SymbolicNameTable;
-
-#include <stdbool.h>
-
-/**
- * Creates a symbolic name table
- *
- * Allocates a SymbolicNameTable, which will store the symbolic names
- * in a hash table.
- *
- * @retval non-null An allocated SymbolicNameTable
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-SymbolicNameTable *symbolicNameTable_Create(void);
-
-/**
- * Destroys a name table
- *
- * All keys and data are released.
- *
- * @param [in,out] tablePtr A pointer to a SymbolicNameTable, which will be
- * NULL'd
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void symbolicNameTable_Destroy(SymbolicNameTable **tablePtr);
-
-/**
- * Checks if the name (case insensitive) is in the table
- *
- * Does a case-insensitive match to see if the name is in the table
- *
- * @param [in] table An allocated SymbolicNameTable
- * @param [in] symbolicName The name to check for
- *
- * @retval true The name is in the table
- * @retval false The name is not in the talbe
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-bool symbolicNameTable_Exists(SymbolicNameTable *table,
- const char *symbolicName);
-
-/**
- * Adds a (name, connid) pair to the table.
- *
- * The name is stored case insensitive. The value UINT_MAX is used to indicate
- * a non-existent key, so it should not be stored as a value in the table.
- *
- * @param [in] table An allocated SymbolicNameTable
- * @param [in] symbolicName The name to save (will make a copy)
- * @param [in] connid The connection id to associate with the name
- *
- * @retval true The pair was added
- * @retval false The pair was not added (likely duplicate key)
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-bool symbolicNameTable_Add(SymbolicNameTable *table, const char *symbolicName,
- unsigned connid);
-
-/**
- * Returns the connection id associated with the symbolic name
- *
- * This function will look for the given name (case insensitive) and return the
- * corresponding connid. If the name is not in the table, the function will
- * return UINT_MAX.
- *
- * @param [in] table An allocated SymbolicNameTable
- * @param [in] symbolicName The name to retrieve
- *
- * @retval UINT_MAX symbolicName not found
- * @retval number the corresponding connid.
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-unsigned symbolicNameTable_Get(SymbolicNameTable *table,
- const char *symbolicName);
-
-void symbolicNameTable_Remove(SymbolicNameTable *table,
- const char *symbolicName);
-const char *symbolicNameTable_GetNameByIndex(SymbolicNameTable *table,
- unsigned id);
-
-#endif /* defined(symbolicNameTable_h) */
diff --git a/hicn-light/src/hicn/content_store/CMakeLists.txt b/hicn-light/src/hicn/content_store/CMakeLists.txt
index aaf256118..f7cfc26b6 100644
--- a/hicn-light/src/hicn/content_store/CMakeLists.txt
+++ b/hicn-light/src/hicn/content_store/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -12,20 +12,12 @@
# limitations under the License.
list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/contentStoreEntry.h
- ${CMAKE_CURRENT_SOURCE_DIR}/contentStoreInterface.h
- ${CMAKE_CURRENT_SOURCE_DIR}/contentStoreLRU.h
- ${CMAKE_CURRENT_SOURCE_DIR}/listTimeOrdered.h
- ${CMAKE_CURRENT_SOURCE_DIR}/listLRU.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/lru.h
)
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/contentStoreInterface.c
- ${CMAKE_CURRENT_SOURCE_DIR}/contentStoreLRU.c
- ${CMAKE_CURRENT_SOURCE_DIR}/listLRU.c
- ${CMAKE_CURRENT_SOURCE_DIR}/listTimeOrdered.c
- ${CMAKE_CURRENT_SOURCE_DIR}/contentStoreEntry.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/lru.c
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
-set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE) \ No newline at end of file
+set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
diff --git a/hicn-light/src/hicn/content_store/contentStoreEntry.c b/hicn-light/src/hicn/content_store/contentStoreEntry.c
deleted file mode 100644
index 45f98881e..000000000
--- a/hicn-light/src/hicn/content_store/contentStoreEntry.c
+++ /dev/null
@@ -1,136 +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/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <hicn/content_store/contentStoreEntry.h>
-
-#include <parc/assert/parc_Assert.h>
-
-const uint64_t contentStoreEntry_MaxExpiryTime = UINT64_MAX;
-
-struct contentstore_entry {
- Message *message;
- ListLruEntry *lruEntry;
- unsigned refcount;
- bool hasExpiryTimeTicks;
- uint64_t expiryTimeTicks;
-};
-
-ContentStoreEntry *contentStoreEntry_Create(Message *contentMessage,
- ListLru *listLRU) {
- parcAssertNotNull(contentMessage, "Parameter objectMessage must be non-null");
-
- ContentStoreEntry *entry =
- parcMemory_AllocateAndClear(sizeof(ContentStoreEntry));
- parcAssertNotNull(entry, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ContentStoreEntry));
- entry->message = message_Acquire(contentMessage);
- entry->refcount = 1;
-
- if (listLRU != NULL) {
- entry->lruEntry = listLRU_NewHeadEntry(listLRU, entry);
- }
-
- entry->hasExpiryTimeTicks = message_HasContentExpiryTime(contentMessage);
-
- if (entry->hasExpiryTimeTicks) {
- entry->expiryTimeTicks = message_GetContentExpiryTimeTicks(contentMessage);
- }
-
- return entry;
-}
-
-ContentStoreEntry *contentStoreEntry_Acquire(
- const ContentStoreEntry *original) {
- parcAssertNotNull(original, "Parameter must be non-null");
- ((ContentStoreEntry *)original)->refcount++;
- return (ContentStoreEntry *)original;
-}
-
-void contentStoreEntry_Release(ContentStoreEntry **entryPtr) {
- parcAssertNotNull(entryPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*entryPtr,
- "Parameter must dereference to non-null pointer");
-
- ContentStoreEntry *entry = *entryPtr;
- parcAssertTrue(entry->refcount > 0, "Illegal state: has refcount of 0");
-
- entry->refcount--;
- if (entry->refcount == 0) {
- if (entry->lruEntry) {
- listLRU_EntryDestroy(&entry->lruEntry);
- }
- message_Release(&entry->message);
- parcMemory_Deallocate((void **)&entry);
- }
- *entryPtr = NULL;
-}
-
-Message *contentStoreEntry_GetMessage(const ContentStoreEntry *storeEntry) {
- parcAssertNotNull(storeEntry, "Parameter must be non-null");
- return storeEntry->message;
-}
-
-bool contentStoreEntry_HasExpiryTimeTicks(const ContentStoreEntry *storeEntry) {
- parcAssertNotNull(storeEntry, "Parameter must be non-null");
- return storeEntry->hasExpiryTimeTicks;
-}
-
-uint64_t contentStoreEntry_GetExpiryTimeTicks(
- const ContentStoreEntry *storeEntry) {
- parcAssertNotNull(storeEntry, "Parameter must be non-null");
- parcAssertTrue(storeEntry->hasExpiryTimeTicks,
- "storeEntry has no ExpiryTimeTicks. Did you call "
- "contentStoreEntry_HasExpiryTimeTicks() first?");
- return storeEntry->expiryTimeTicks;
-}
-
-int contentStoreEntry_CompareExpiryTime(const ContentStoreEntry *value1,
- const ContentStoreEntry *value2) {
- // A signum comparison. negative if key 1 is smaller, 0 if key1 == key2,
- // greater than 0 if key1 is bigger.
-
- ContentStoreEntry *v1 = (ContentStoreEntry *)value1;
- ContentStoreEntry *v2 = (ContentStoreEntry *)value2;
-
- if (v1->expiryTimeTicks < v2->expiryTimeTicks) {
- return -1;
- } else if (v1->expiryTimeTicks > v2->expiryTimeTicks) {
- return +1;
- } else {
- // At this point, the times are the same. Use the address of the message as
- // the decider. This allows us to store multiple messages with the same
- // expiry/cache time.
- if (v1->message < v2->message) {
- return -1;
- } else if (v1->message > v2->message) {
- return +1;
- }
- }
-
- return 0; // The same message has been encountered.
-}
-
-void contentStoreEntry_MoveToHead(ContentStoreEntry *storeEntry) {
- parcAssertNotNull(storeEntry, "Parameter must be non-null");
- parcAssertNotNull(storeEntry->lruEntry,
- "ContentStoreEntry is not attached to an ListLru");
- if (storeEntry->lruEntry) {
- listLRU_EntryMoveToHead(storeEntry->lruEntry);
- }
-}
diff --git a/hicn-light/src/hicn/content_store/contentStoreEntry.h b/hicn-light/src/hicn/content_store/contentStoreEntry.h
deleted file mode 100644
index 4f0fd19c1..000000000
--- a/hicn-light/src/hicn/content_store/contentStoreEntry.h
+++ /dev/null
@@ -1,146 +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.
- */
-
-#ifndef contentStoreEntry_h
-#define contentStoreEntry_h
-
-#include <hicn/content_store/listLRU.h>
-#include <hicn/core/message.h>
-
-struct contentstore_entry;
-typedef struct contentstore_entry ContentStoreEntry;
-
-/**
- * The max time allowed for an ExpiryTime. Will never be exceeded.
- */
-extern const uint64_t contentStoreEntry_MaxExpiryTime;
-
-/**
- * Creates a new `ContentStoreEntry` instance, acquiring a reference to the
- * supplied `Message`.
- *
- * @param message the message to store
- * @param listLRU the LRU list that this entry will be stored in.
- * @return A newly created `ContentStoreEntry` instance that must eventually be
- * released by calling
- * {@link contentStoreEntry_Release}.
- *
- * @see contentStoreEntry_Release
- */
-ContentStoreEntry *contentStoreEntry_Create(Message *objectMessage,
- ListLru *listLRU);
-
-/**
- * Returns a reference counted copy of the supplied `ContentStoreEntry`.
- *
- * @param original the ContentStoreEntry to return a reference to.
- * @return Reference counted copy, must call
- * <code>contentStoreEntry_Destroy()</code> on it.
- */
-ContentStoreEntry *contentStoreEntry_Acquire(const ContentStoreEntry *original);
-
-/**
- * Releases one reference count and destroys object when reaches zero
- *
- * @param [in,out] entryPtr A pointer to an allocated ContentStoreEntry
- *
- */
-void contentStoreEntry_Release(ContentStoreEntry **entryPtr);
-
-/**
- * Returns a pointer to the contained {@link Message}.
- * The caller must called {@link message_Acquire()} if they want to keep a
- * reference to the returned message.
- *
- * @param storeEntry the ContentStoreEntry from which to retrieve the `Message`
- * pointer.
- * @return the address of the `Message` contained in the storeEntry.
- * @see message_Acquire
- */
-Message *contentStoreEntry_GetMessage(const ContentStoreEntry *storeEntry);
-
-/**
- * Return true if the message stored in this `ContentStoreEntry` has an
- * ExpiryTime.
- *
- * @param storeEntry the ContentStoreEntry containing the message.
- * @return true if the referenced message has an ExpiryTime. False, otherwise.
- */
-bool contentStoreEntry_HasExpiryTimeTicks(const ContentStoreEntry *storeEntry);
-
-/**
- * Return the ExpiryTime stored in this `ContentStoreEntry`.
- *
- * @param storeEntry the ContentStoreEntry from which to retrieve the `Message`
- * pointer.
- * @return the address of the `Message` contained in the storeEntry.
- */
-uint64_t contentStoreEntry_GetExpiryTimeTicks(
- const ContentStoreEntry *storeEntry);
-
-/**
- * A signum function comparing two `ContentStoreEntry` instances, using their
- * ExpiryTime and, if necessary, the addresses of the referenced Message. In
- * other words, if two ContentStoreEntries have the same ExpiryTime, the
- * comparison will then be made on the memory addresses of the Messages
- * referenced by the ContentStoreEntrys. So, the only way two ContentStoreEntrys
- * will compare equally (0) is if they both have the same ExpiryTime and
- * reference the same Message.
- *
- * Used to determine the ordering relationship of two `ContentStoreEntry`
- * instances. This is used by the {@link ListTimeOrdered} to keep a list of
- * ContentStoreEntrys, sorted by ExpiryTime.
- *
- * @param [in] storeEntry1 A pointer to a `ContentStoreEntry` instance.
- * @param [in] storeEntry2 A pointer to a `ContentStoreEntry` instance to be
- * compared to `storeEntry1`.
- *
- * @return 0 if `storeEntry1` and `storeEntry2` are equivalent
- * @return < 0 if `storeEntry1` < `storeEntry2`
- * @return > 0 if `storeEntry1` > `storeEntry2`
- *
- * Example:
- * @code
- * {
- * ContentStoreEntry *entry1 = contentStoreEntry_Create(...);
- * ContentStoreEntry *entry2 = contentStoreEntry_Create(...);
- *
- * int val = contentStoreEntry_CompareExpiryTime(entry1, entry2);
- * if (val < 0) {
- * // entry1 has a lower ExpiryTime, or the same ExpiryTime as entry2
- * and a different message. } else if (val > 0) {
- * // entry2 has a lower ExpiryTime, or the same ExpiryTime as entry1
- * and a different message. } else {
- * // entry1 and entry2 have the same ExpiryTime AND the same message.
- * }
- *
- * contentStoreEntry_Release(&entry1);
- * contentStoreEntry_Release(&entry2);
- *
- * }
- * @endcode
- */
-int contentStoreEntry_CompareExpiryTime(const ContentStoreEntry *storeEntry1,
- const ContentStoreEntry *storeEntry2);
-
-/**
- * Move this entry to the head of the LRU list
- *
- * Moves the entry to the head of the LRU list it was created with
- *
- * @param [in] storeEntry An allocated ContenstoreEntry
- */
-void contentStoreEntry_MoveToHead(ContentStoreEntry *storeEntry);
-#endif // contentStoreEntry_h
diff --git a/hicn-light/src/hicn/content_store/contentStoreInterface.c b/hicn-light/src/hicn/content_store/contentStoreInterface.c
deleted file mode 100644
index 2f5ddb8c2..000000000
--- a/hicn-light/src/hicn/content_store/contentStoreInterface.c
+++ /dev/null
@@ -1,57 +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/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/content_store/contentStoreInterface.h>
-
-void contentStoreInterface_Release(ContentStoreInterface **storeImplPtr) {
- (*storeImplPtr)->release(storeImplPtr);
-}
-
-bool contentStoreInterface_PutContent(ContentStoreInterface *storeImpl,
- Message *content,
- uint64_t currentTimeTicks) {
- return storeImpl->putContent(storeImpl, content, currentTimeTicks);
-}
-
-bool contentStoreInterface_RemoveContent(ContentStoreInterface *storeImpl,
- Message *content) {
- return storeImpl->removeContent(storeImpl, content);
-}
-
-Message *contentStoreInterface_MatchInterest(ContentStoreInterface *storeImpl,
- Message *interest,
- uint64_t currentTimeTicks) {
- return storeImpl->matchInterest(storeImpl, interest, currentTimeTicks);
-}
-
-size_t contentStoreInterface_GetObjectCapacity(
- ContentStoreInterface *storeImpl) {
- return storeImpl->getObjectCapacity(storeImpl);
-}
-
-size_t contentStoreInterface_GetObjectCount(ContentStoreInterface *storeImpl) {
- return storeImpl->getObjectCount(storeImpl);
-}
-
-void contentStoreInterface_Log(ContentStoreInterface *storeImpl) {
- storeImpl->log(storeImpl);
-}
-
-void *contentStoreInterface_GetPrivateData(ContentStoreInterface *storeImpl) {
- return storeImpl->_privateData;
-}
diff --git a/hicn-light/src/hicn/content_store/contentStoreInterface.h b/hicn-light/src/hicn/content_store/contentStoreInterface.h
deleted file mode 100644
index b2bc3f919..000000000
--- a/hicn-light/src/hicn/content_store/contentStoreInterface.h
+++ /dev/null
@@ -1,211 +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.
- */
-
-#ifndef contentStoreInterface_h
-#define contentStoreInterface_h
-
-#include <stdio.h>
-
-#include <hicn/core/message.h>
-
-typedef struct contentstore_config {
- size_t objectCapacity;
-} ContentStoreConfig;
-
-typedef struct contentstore_interface ContentStoreInterface;
-
-struct contentstore_interface {
- /**
- * Place a Message representing a ContentObject into the ContentStore. If
- * necessary to make room, remove expired content or content that has exceeded
- * the Recommended Cache Time.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- * @param content - a pointer to a `Message` to place in the store.
- * @param currentTimeTicks - the current time, in hicn-light ticks, since the
- * UTC epoch.
- */
- bool (*putContent)(ContentStoreInterface *storeImpl, Message *content,
- uint64_t currentTimeTicks);
-
- /**
- * The function to call to remove content from the ContentStore.
- * It will Release any references that were created when the content was
- * placed into the ContentStore.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- * @param content - a pointer to a `Message` to remove from the store.
- */
- bool (*removeContent)(ContentStoreInterface *storeImpl, Message *content);
-
- /**
- * Given a Message that represents and Interest, try to find a matching
- * ContentObject.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- * @param interest - a pointer to a `Message` representing the Interest to
- * match.
- *
- * @return a pointer to a Message containing the matching ContentObject
- * @return NULL if no matching ContentObject was found
- */
- Message *(*matchInterest)(ContentStoreInterface *storeImpl, Message *interest,
- uint64_t currentTimeTicks);
-
- /**
- * Return the maximum number of ContentObjects that can be stored in this
- * ContentStore. This is a raw count, not based on memory size.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- *
- * @return the maximum number of ContentObjects that can be stored
- */
- size_t (*getObjectCapacity)(ContentStoreInterface *storeImpl);
-
- /**
- * Return the number of ContentObjects currently stored in the ContentStore.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- *
- * @return the current number of ContentObjects in the ContentStore
- */
- size_t (*getObjectCount)(ContentStoreInterface *storeImpl);
-
- /**
- * Log a ContentStore implementation specific version of store-related
- * information.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- */
- void (*log)(ContentStoreInterface *storeImpl);
-
- /**
- * Acquire a new reference to the specified ContentStore instance. This
- * reference will eventually need to be released by calling {@link
- * contentStoreInterface_Release}.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- */
- ContentStoreInterface *(*acquire)(const ContentStoreInterface *storeImpl);
-
- /**
- * Release the ContentStore, which will also Release any references held by
- * it.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- */
- void (*release)(ContentStoreInterface **storeImpl);
-
- /**
- * A pointer to opaque private data used by the ContentStore instance
- * represented by this instance of ContentStoreInterface.
- */
- void *_privateData;
-};
-
-/**
- * Place a Message representing a ContentObject into the ContentStore. If
- * necessary to make room, remove expired content or content that has exceeded
- * the Recommended Cache Time.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- * @param content - a pointer to a `Message` to place in the store.
- *
- * @param currentTimeTicks - the current time, in hicn-light ticks, since the
- * UTC epoch.
- */
-bool contentStoreInterface_PutContent(ContentStoreInterface *storeImpl,
- Message *content,
- uint64_t currentTimeTicks);
-
-/**
- * The function to call to remove content from the ContentStore.
- * It will Release any references that were created when the content was placed
- * into the ContentStore.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- * @param content - a pointer to a `Message` to remove from the store.
- */
-bool contentStoreInterface_RemoveContent(ContentStoreInterface *storeImpl,
- Message *content);
-
-/**
- * Given a Message that represents and Interest, try to find a matching
- * ContentObject.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- * @param interest - a pointer to a `Message` representing the Interest to
- * match.
- *
- * @return a pointer to a Message containing the matching ContentObject
- * @return NULL if no matching ContentObject was found
- */
-Message *contentStoreInterface_MatchInterest(ContentStoreInterface *storeImpl,
- Message *interest,
- uint64_t currentTimeTicks);
-
-/**
- * Return the maximum number of ContentObjects that can be stored in this
- * ContentStore. This is a raw count, not based on memory size.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- *
- * @return the maximum number of ContentObjects that can be stored
- */
-size_t contentStoreInterface_GetObjectCapacity(
- ContentStoreInterface *storeImpl);
-
-/**
- * Return the number of ContentObjects currently stored in the ContentStore.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- *
- * @return the current number of ContentObjects in the ContentStore
- */
-size_t contentStoreInterface_GetObjectCount(ContentStoreInterface *storeImpl);
-
-/**
- * Loga ContentStore implementation specific version of store-related
- * information.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- */
-void contentStoreInterface_Log(ContentStoreInterface *storeImpl);
-
-/**
- * Acquire a new reference to the specified ContentStore instance. This
- * reference will eventually need to be released by calling {@link
- * contentStoreInterface_Release}.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- */
-ContentStoreInterface *contentStoreInterface_Aquire(
- const ContentStoreInterface *storeImpl);
-
-/**
- * Release the ContentStore, which will also Release any references held by it.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- */
-void contentStoreInterface_Release(ContentStoreInterface **storeImplPtr);
-
-/**
- * Return a pointer to the data private to this implementation of the
- * ContentStore interface.
- *
- * @param storeImpl - a pointer to this ContentStoreInterface instance.
- */
-void *contentStoreInterface_GetPrivateData(ContentStoreInterface *storeImpl);
-#endif // contentStoreInterface_h
diff --git a/hicn-light/src/hicn/content_store/contentStoreLRU.c b/hicn-light/src/hicn/content_store/contentStoreLRU.c
deleted file mode 100644
index 76a2c8659..000000000
--- a/hicn-light/src/hicn/content_store/contentStoreLRU.c
+++ /dev/null
@@ -1,462 +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.
- */
-
-#ifndef _WIN32
-#include <sys/queue.h>
-#endif
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_DisplayIndented.h>
-#include <parc/algol/parc_HashCodeTable.h>
-#include <parc/algol/parc_Object.h>
-
-#include <hicn/core/logger.h>
-
-#include <hicn/content_store/contentStoreLRU.h>
-
-#include <hicn/content_store/contentStoreEntry.h>
-#include <hicn/content_store/contentStoreInterface.h>
-#include <hicn/content_store/listLRU.h>
-#include <hicn/content_store/listTimeOrdered.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <hicn/processor/hashTableFunction.h>
-
-typedef struct contentstore_stats {
- uint64_t countExpiryEvictions;
- uint64_t countRCTEvictions;
- uint64_t countLruEvictions;
- uint64_t countAdds;
- uint64_t countHits;
- uint64_t countMisses;
-} _ContentStoreLRUStats;
-
-typedef struct contentstore_lru_data {
- size_t objectCapacity;
- size_t objectCount;
-
- Logger *logger;
-
- // This LRU is just for keeping track of insertion and access order.
- ListLru *lru;
-
- ListTimeOrdered *indexByExpirationTime;
-
- PARCHashCodeTable *storageByName;
-
- _ContentStoreLRUStats stats;
-} _ContentStoreLRU;
-
-static void _destroyIndexes(_ContentStoreLRU *store) {
- if (store->indexByExpirationTime != NULL) {
- listTimeOrdered_Release(&(store->indexByExpirationTime));
- }
-
- if (store->storageByName != NULL) {
- parcHashCodeTable_Destroy(&(store->storageByName));
- }
-
- if (store->lru != NULL) {
- listLRU_Destroy(&(store->lru));
- }
-}
-
-static void _contentStoreInterface_Destroy(
- ContentStoreInterface **storeImplPtr) {
- _ContentStoreLRU *store = contentStoreInterface_GetPrivateData(*storeImplPtr);
-
- parcObject_Release((PARCObject **)&store);
-}
-
-static bool _contentStoreLRU_Destructor(_ContentStoreLRU **storePtr) {
- _ContentStoreLRU *store = *storePtr;
-
- _destroyIndexes(store);
- logger_Release(&store->logger);
-
- return true;
-}
-
-parcObject_Override(_ContentStoreLRU, PARCObject,
- .destructor = (PARCObjectDestructor *)
- _contentStoreLRU_Destructor);
-
-parcObject_ExtendPARCObject(ContentStoreInterface,
- _contentStoreInterface_Destroy, NULL, NULL, NULL,
- NULL, NULL, NULL);
-
-static parcObject_ImplementAcquire(_contentStoreLRU, ContentStoreInterface);
-static parcObject_ImplementRelease(_contentStoreLRU, ContentStoreInterface);
-
-static void _hashTableFunction_ContentStoreEntryDestroyer(void **dataPtr) {
- contentStoreEntry_Release((ContentStoreEntry **)dataPtr);
-}
-
-static bool _contentStoreLRU_Init(_ContentStoreLRU *store,
- ContentStoreConfig *config, Logger *logger) {
- bool result = false;
-
- store->logger = logger_Acquire(logger);
-
- size_t initialSize = config->objectCapacity * 2;
- memset(&store->stats, 0, sizeof(_ContentStoreLRUStats));
-
- store->objectCapacity = config->objectCapacity;
- store->objectCount = 0;
-
- // initial size must be at least 1 or else the data structures break.
- initialSize = (initialSize == 0) ? 1 : initialSize;
-
- store->indexByExpirationTime = listTimeOrdered_Create(
- (TimeOrderList_KeyCompare *)contentStoreEntry_CompareExpiryTime);
-
- store->storageByName = parcHashCodeTable_Create_Size(
- hashTableFunction_MessageNameEquals,
- hashTableFunction_MessageNameHashCode, NULL,
- _hashTableFunction_ContentStoreEntryDestroyer, initialSize);
-
- store->lru = listLRU_Create();
-
- // If any of the index tables couldn't be allocated, we can't continue.
- if ((store->indexByExpirationTime == NULL) ||
- (store->storageByName == NULL) || (store->lru == NULL)) {
- if (logger_IsLoggable(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Error)) {
- logger_Log(store->logger, LoggerFacility_Processor, PARCLogLevel_Error,
- __func__,
- "ContentStoreLRU could not be created. Could not allocate all "
- "index tables.",
- (void *)store, store->objectCapacity);
- }
-
- _destroyIndexes(store);
- result = false;
- } else {
- result = true;
- }
- return result;
-}
-
-/**
- * Remove a ContentStoreEntry from all tables and indices.
- */
-static void _contentStoreLRU_PurgeStoreEntry(_ContentStoreLRU *store,
- ContentStoreEntry *entryToPurge) {
- if (contentStoreEntry_HasExpiryTimeTicks(entryToPurge)) {
- listTimeOrdered_Remove(store->indexByExpirationTime, entryToPurge);
- }
-
- Message *content = contentStoreEntry_GetMessage(entryToPurge);
-
- // This _Del call will call the Release/Destroy on the ContentStoreEntry,
- // which will remove it from the LRU as well.
- parcHashCodeTable_Del(store->storageByName, content);
-
- store->objectCount--;
-}
-
-static bool _contentStoreLRU_RemoveLeastUsed(_ContentStoreLRU *store) {
- bool result = false;
-
- if (store->objectCount > 0) {
- ListLruEntry *lruEntry = listLRU_PopTail(store->lru);
- ContentStoreEntry *storeEntry =
- (ContentStoreEntry *)listLRU_EntryGetData(lruEntry);
-
- if (logger_IsLoggable(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(
- store->logger, LoggerFacility_Processor, PARCLogLevel_Debug, __func__,
- "ContentStore %p evict message %p by LRU (LRU evictions %" PRIu64 ")",
- (void *)store, (void *)contentStoreEntry_GetMessage(storeEntry),
- store->stats.countLruEvictions);
- }
-
- _contentStoreLRU_PurgeStoreEntry(store, storeEntry);
-
- result = true;
- }
- return result;
-}
-
-static void _evictByStorePolicy(_ContentStoreLRU *store,
- uint64_t currentTimeInTicks) {
- // We need to make room. Here's the plan:
- // 1) Check to see if anything has expired. If so, remove it and we're done.
- // If not, 2) Remove the least recently used item.
-
- ContentStoreEntry *entry =
- listTimeOrdered_GetOldest(store->indexByExpirationTime);
- if (entry && contentStoreEntry_HasExpiryTimeTicks(entry) &&
- (currentTimeInTicks > contentStoreEntry_GetExpiryTimeTicks(entry))) {
- // Found an expired entry. Remove it, and we're done.
-
- store->stats.countExpiryEvictions++;
- if (logger_IsLoggable(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(store->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__,
- "ContentStore %p evict message %p by ExpiryTime (ExpiryTime "
- "evictions %" PRIu64 ")",
- (void *)store, (void *)contentStoreEntry_GetMessage(entry),
- store->stats.countExpiryEvictions);
- }
-
- _contentStoreLRU_PurgeStoreEntry(store, entry);
- } else {
- store->stats.countLruEvictions++;
- _contentStoreLRU_RemoveLeastUsed(store);
- }
-}
-
-static bool _contentStoreLRU_PutContent(ContentStoreInterface *storeImpl,
- Message *content,
- uint64_t currentTimeTicks)
-
-{
- bool result = false;
- _ContentStoreLRU *store =
- (_ContentStoreLRU *)contentStoreInterface_GetPrivateData(storeImpl);
- parcAssertNotNull(store, "Parameter store must be non-null");
- parcAssertNotNull(content, "Parameter objectMessage must be non-null");
-
- parcAssertTrue(message_GetType(content) == MessagePacketType_ContentObject,
- "Parameter objectMessage must be a Content Object");
-
- if (store->objectCapacity == 0) {
- return false;
- }
-
- ContentStoreEntry *storeEntry = parcHashCodeTable_Get(store->storageByName, content);
- if(storeEntry){
- _contentStoreLRU_PurgeStoreEntry(store, storeEntry);
- }
-
- uint64_t expiryTimeTicks = contentStoreEntry_MaxExpiryTime;
-
- if (message_HasContentExpiryTime(content)) {
- expiryTimeTicks = message_GetContentExpiryTimeTicks(content);
- }
- // Don't add anything that's already expired or has exceeded RCT.
- if (currentTimeTicks >= expiryTimeTicks) {
- return false;
- }
-
- if (store->objectCount >= store->objectCapacity) {
- // Store is full. Need to make room.
- _evictByStorePolicy(store, currentTimeTicks);
- }
-
- // And now add a new entry to the head of the LRU.
-
- ContentStoreEntry *entry = contentStoreEntry_Create(content, store->lru);
-
- if (entry != NULL) {
- if (parcHashCodeTable_Add(store->storageByName, content, entry)) {
- if (contentStoreEntry_HasExpiryTimeTicks(entry)) {
- listTimeOrdered_Add(store->indexByExpirationTime, entry);
- }
-
- store->objectCount++;
- store->stats.countAdds++;
-
- if (logger_IsLoggable(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(store->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__,
- "ContentStoreLRU %p saved message %p (object count %" PRIu64
- ")",
- (void *)store, (void *)content, store->objectCount);
- }
-
- result = true;
- } else {
- // Free what we just created, but did not add. 'entry' has ownership of
- // 'copy', and so will call _Release() on it
- contentStoreEntry_Release(&entry);
-
- if (logger_IsLoggable(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Warning)) {
- logger_Log(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Warning, __func__,
- "ContentStoreLRU %p failed to add message %p to hash table",
- (void *)store, (void *)content);
- }
- }
- }
-
- return result;
-}
-
-static Message *_contentStoreLRU_MatchInterest(ContentStoreInterface *storeImpl,
- Message *interest,
- uint64_t currentTimeTicks) {
- Message *result = NULL;
-
- _ContentStoreLRU *store =
- (_ContentStoreLRU *)contentStoreInterface_GetPrivateData(storeImpl);
-
- parcAssertNotNull(store, "Parameter store must be non-null");
- parcAssertNotNull(interest, "Parameter interestMessage must be non-null");
- parcAssertTrue(message_GetType(interest) == MessagePacketType_Interest,
- "Parameter interestMessage must be an Interest");
-
- PARCHashCodeTable *table;
- table = store->storageByName;
-
- ContentStoreEntry *storeEntry = parcHashCodeTable_Get(table, interest);
-
- bool foundEntry = false;
-
- if (storeEntry) {
- if (contentStoreEntry_HasExpiryTimeTicks(storeEntry) &&
- contentStoreEntry_GetExpiryTimeTicks(storeEntry) < currentTimeTicks) {
- // the entry is expired, we can remove it
- _contentStoreLRU_PurgeStoreEntry(store, storeEntry);
- } else {
- foundEntry = true;
- }
- }
-
- if (foundEntry) {
- contentStoreEntry_MoveToHead(storeEntry);
- result = contentStoreEntry_GetMessage(storeEntry);
-
- store->stats.countHits++;
-
- if (logger_IsLoggable(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(store->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__,
- "ContentStoreLRU %p matched interest %p (hits %" PRIu64
- ", misses %" PRIu64 ")",
- (void *)store, (void *)interest, store->stats.countHits,
- store->stats.countMisses);
- }
- } else {
- store->stats.countMisses++;
-
- if (logger_IsLoggable(store->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(store->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__,
- "ContentStoreLRU %p missed interest %p (hits %" PRIu64
- ", misses %" PRIu64 ")",
- (void *)store, (void *)interest, store->stats.countHits,
- store->stats.countMisses);
- }
- }
-
- return result;
-}
-
-static bool _contentStoreLRU_RemoveContent(ContentStoreInterface *storeImpl,
- Message *content) {
- bool result = false;
- _ContentStoreLRU *store =
- (_ContentStoreLRU *)contentStoreInterface_GetPrivateData(storeImpl);
-
- ContentStoreEntry *storeEntry =
- parcHashCodeTable_Get(store->storageByName, content);
-
- if (storeEntry != NULL) {
- _contentStoreLRU_PurgeStoreEntry(store, storeEntry);
- result = true;
- }
-
- return result;
-}
-
-static void _contentStoreLRU_Log(ContentStoreInterface *storeImpl) {
- _ContentStoreLRU *store =
- (_ContentStoreLRU *)contentStoreInterface_GetPrivateData(storeImpl);
-
- logger_Log(store->logger, LoggerFacility_Processor, PARCLogLevel_All,
- __func__,
- "ContentStoreLRU @%p {count = %zu, capacity = %zu {"
- "stats = @%p {adds = %" PRIu64 ", hits = %" PRIu64
- ", misses = %" PRIu64 ", LRUEvictons = %" PRIu64
- ", ExpiryEvictions = %" PRIu64 ", RCTEvictions = %" PRIu64 "} }",
- store, store->objectCount, store->objectCapacity, &store->stats,
- store->stats.countAdds, store->stats.countHits,
- store->stats.countMisses, store->stats.countLruEvictions,
- store->stats.countExpiryEvictions, store->stats.countRCTEvictions);
-}
-
-static size_t _contentStoreLRU_GetObjectCapacity(
- ContentStoreInterface *storeImpl) {
- _ContentStoreLRU *store =
- (_ContentStoreLRU *)contentStoreInterface_GetPrivateData(storeImpl);
- return store->objectCapacity;
-}
-
-static size_t _contentStoreLRU_GetObjectCount(
- ContentStoreInterface *storeImpl) {
- _ContentStoreLRU *store =
- (_ContentStoreLRU *)contentStoreInterface_GetPrivateData(storeImpl);
- return store->objectCount;
-}
-
-static size_t _contentStoreLRU_SetObjectCapacity(
- ContentStoreInterface *storeImpl, size_t newCapacity) {
- _ContentStoreLRU *store =
- (_ContentStoreLRU *)contentStoreInterface_GetPrivateData(storeImpl);
- return store->objectCapacity = newCapacity;
-}
-
-ContentStoreInterface *contentStoreLRU_Create(ContentStoreConfig *config,
- Logger *logger) {
- ContentStoreInterface *storeImpl = NULL;
-
- parcAssertNotNull(logger, "ContentStoreLRU requires a non-NULL logger");
-
- storeImpl = parcObject_CreateAndClearInstance(ContentStoreInterface);
-
- if (storeImpl != NULL) {
- storeImpl->_privateData =
- parcObject_CreateAndClearInstance(_ContentStoreLRU);
-
- if (_contentStoreLRU_Init(storeImpl->_privateData, config, logger)) {
- storeImpl->putContent = &_contentStoreLRU_PutContent;
- storeImpl->removeContent = &_contentStoreLRU_RemoveContent;
-
- storeImpl->matchInterest = &_contentStoreLRU_MatchInterest;
-
- storeImpl->getObjectCount = &_contentStoreLRU_GetObjectCount;
- storeImpl->getObjectCapacity = &_contentStoreLRU_GetObjectCapacity;
-
- storeImpl->log = &_contentStoreLRU_Log;
-
- storeImpl->acquire = &_contentStoreLRU_Acquire;
- storeImpl->release = &_contentStoreLRU_Release;
-
- // Initialize from the config passed to us.
- _contentStoreLRU_SetObjectCapacity(storeImpl, config->objectCapacity);
-
- if (logger_IsLoggable(logger, LoggerFacility_Processor,
- PARCLogLevel_Info)) {
- logger_Log(logger, LoggerFacility_Processor, PARCLogLevel_Info,
- __func__, "ContentStoreLRU %p created with capacity %zu",
- (void *)storeImpl,
- contentStoreInterface_GetObjectCapacity(storeImpl));
- }
- }
- } else {
- parcObject_Release((void **)&storeImpl);
- }
-
- return storeImpl;
-}
diff --git a/hicn-light/src/hicn/content_store/contentStoreLRU.h b/hicn-light/src/hicn/content_store/contentStoreLRU.h
deleted file mode 100644
index 94ec4d6b2..000000000
--- a/hicn-light/src/hicn/content_store/contentStoreLRU.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef contentStoreLRU_h
-#define contentStoreLRU_h
-
-#include <hicn/content_store/contentStoreInterface.h>
-#include <hicn/core/logger.h>
-#include <stdio.h>
-
-/**
- * Create and Initialize an instance of contentStoreLRU. A newly allocated
- * {@link ContentStoreInterface} object is initialized and returned. It must
- * eventually be released by calling {@link contentStoreInterface_Release}.
- *
- *
- * @param config An instance of `ContentStoreConfig`, specifying options to be
- * applied by the underlying contentStoreLRU instance.
- * @param logger An instance of a {@link Logger} to use for logging content
- * store events.
- *
- * @return a newly created contentStoreLRU instance.
- *
- */
-ContentStoreInterface *contentStoreLRU_Create(ContentStoreConfig *config,
- Logger *logger);
-#endif // contentStoreLRU_h
diff --git a/hicn-light/src/hicn/content_store/listLRU.c b/hicn-light/src/hicn/content_store/listLRU.c
deleted file mode 100644
index 242af4078..000000000
--- a/hicn-light/src/hicn/content_store/listLRU.c
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _WIN32
-#include <sys/queue.h>
-#endif
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/content_store/listLRU.h>
-
-struct list_lru_entry {
- void *userData;
-
- // always set to the list
- ListLru *parentList;
-
- // indicates if the Entry is currently in the list
- bool inList;
-
- TAILQ_ENTRY(list_lru_entry) list;
-};
-
-// this defines the TAILQ structure so we can access the tail pointer
-TAILQ_HEAD(lru_s, list_lru_entry);
-
-struct list_lru {
- struct lru_s head;
- size_t itemsInList;
-};
-
-void listLRU_EntryDestroy(ListLruEntry **entryPtr) {
- parcAssertNotNull(entryPtr,
- "Parameter entryPtr must be non-null double pointer");
-
- ListLruEntry *entry = *entryPtr;
- if (entry->inList) {
- TAILQ_REMOVE(&entry->parentList->head, entry, list);
- parcAssertTrue(
- entry->parentList->itemsInList > 0,
- "Invalid state, removed entry from list, but itemsInList is 0");
- entry->parentList->itemsInList--;
- }
-
- parcMemory_Deallocate((void **)&entry);
- *entryPtr = NULL;
-}
-
-void listLRU_EntryMoveToHead(ListLruEntry *entry) {
- parcAssertNotNull(entry, "Parameter entry must be non-null");
-
- TAILQ_REMOVE(&entry->parentList->head, entry, list);
- TAILQ_INSERT_HEAD(&entry->parentList->head, entry, list);
-}
-
-void *listLRU_EntryGetData(ListLruEntry *entry) { return entry->userData; }
-
-ListLru *listLRU_Create() {
- ListLru *list = parcMemory_AllocateAndClear(sizeof(ListLru));
- parcAssertNotNull(list, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListLru));
- list->itemsInList = 0;
- TAILQ_INIT(&list->head);
- return list;
-}
-
-void listLRU_Destroy(ListLru **lruPtr) {
- parcAssertNotNull(lruPtr, "Parameter lruPtr must be non-null double pointer");
-
- ListLru *lru = *lruPtr;
-
- ListLruEntry *entry = TAILQ_FIRST(&lru->head);
- while (entry != NULL) {
- ListLruEntry *next = TAILQ_NEXT(entry, list);
- listLRU_EntryDestroy(&entry);
- entry = next;
- }
-
- parcMemory_Deallocate((void **)&lru);
- *lruPtr = NULL;
-}
-
-ListLruEntry *listLRU_NewHeadEntry(ListLru *lru, void *data) {
- parcAssertNotNull(lru, "Parameter lru must be non-null");
- parcAssertNotNull(data, "Parameter data must be non-null");
-
- ListLruEntry *entry = parcMemory_AllocateAndClear(sizeof(ListLruEntry));
- parcAssertNotNull(entry, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListLruEntry));
- entry->userData = data;
- entry->parentList = lru;
- entry->inList = true;
-
- TAILQ_INSERT_HEAD(&lru->head, entry, list);
- lru->itemsInList++;
-
- return entry;
-}
-
-ListLruEntry *listLRU_PopTail(ListLru *lru) {
- parcAssertNotNull(lru, "Parameter lru must be non-null");
-
- ListLruEntry *entry = TAILQ_LAST(&lru->head, lru_s);
-
- if (entry) {
- parcAssertTrue(
- lru->itemsInList > 0,
- "Invalid state, removed entry from list, but itemsInList is 0");
- lru->itemsInList--;
- TAILQ_REMOVE(&lru->head, entry, list);
- entry->inList = false;
- }
-
- return entry;
-}
-
-size_t listLRU_Length(const ListLru *lru) {
- parcAssertNotNull(lru, "Parameter lru must be non-null");
- return lru->itemsInList;
-}
diff --git a/hicn-light/src/hicn/content_store/listLRU.h b/hicn-light/src/hicn/content_store/listLRU.h
deleted file mode 100644
index 75f698b61..000000000
--- a/hicn-light/src/hicn/content_store/listLRU.h
+++ /dev/null
@@ -1,94 +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.
- */
-
-/**
- * @file listLRU.h
- * @brief Maintains an LRU for the content store
- *
- * An LRU list is make up of LRU entries. The entries are bound to the list.
- * The user of the list is reponsible for knowing when there's too many things
- * and wants to remove one. The LRU list will grow without bound otherwise.
- *
- * The LRU list is meant to be used as an auxiliary data structure, not the
- * primary storage of data elements.
- *
- */
-
-#ifndef listLRU_h
-#define listLRU_h
-
-struct list_lru_entry;
-typedef struct list_lru_entry ListLruEntry;
-
-struct list_lru;
-typedef struct list_lru ListLru;
-
-/**
- * @function lruEntry_Destroy
- * @abstract Destroys and element. This will also remove it from the list.
- */
-void listLRU_EntryDestroy(ListLruEntry **entryPtr);
-
-/**
- * @function listLRU_EntryMoveToHead
- * @abstract move an element to head
- */
-void listLRU_EntryMoveToHead(ListLruEntry *entry);
-
-/**
- * @function lruEntry_GetData
- * @abstract Returns the user-supplied opaque data when the entry was created
- */
-void *listLRU_EntryGetData(ListLruEntry *entry);
-
-/**
- * @function listLRU_Create
- * @abstract Creates a new Least-Recently-Used list
- */
-ListLru *listLRU_Create();
-
-/**
- * @function listLRU_Destroy
- * @abstract Destroys a list and frees all the elements in it
- */
-void listLRU_Destroy(ListLru **listPtr);
-
-/**
- * Returns the number of items in the list
- *
- * @param [in] lru An allocated ListLru
- * @retval number The number of items in the LRU list
- */
-size_t listLRU_Length(const ListLru *lru);
-
-/**
- * @function listLRU_NewHeadEntry
- * @abstract Creates a new entry for the list. It is inserted at the head of
- * the list.
- */
-ListLruEntry *listLRU_NewHeadEntry(ListLru *lru, void *data);
-
-/**
- * @function listLRU_PopTail
- * @abstract Removes the tail element from the list and returns it to the user
- * @discussion
- * Pops the tail element. The user should examine its data to destroy their
- * tail object, then call <code>LruEntry_Destroy()</code> to free the
- * LRU entry.
- *
- * @return The tail element, or NULL for an empty list
- */
-ListLruEntry *listLRU_PopTail(ListLru *list);
-#endif // listLRU_h
diff --git a/hicn-light/src/hicn/content_store/listTimeOrdered.c b/hicn-light/src/hicn/content_store/listTimeOrdered.c
deleted file mode 100644
index 690c6e412..000000000
--- a/hicn-light/src/hicn/content_store/listTimeOrdered.c
+++ /dev/null
@@ -1,94 +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 <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <hicn/content_store/listTimeOrdered.h>
-
-#include <parc/algol/parc_Object.h>
-#include <parc/algol/parc_TreeRedBlack.h>
-
-/**
- * A list of ContentStoreEntrys, kept in sorted order by time. The ordering is
- * calculated by a key compare function (e.g. {@link TimeOrderList_KeyCompare}),
- * passed in.
- *
- * This container does not hold references to the objects that it contains. In
- * other words, it does not Acquire() the Messages that are placed in it. That
- * reference count is managed by the owning ContentStore. This is purely an
- * index, and provides an easy to way index Messages based on a specified time
- * value. Typically, that would be the Expiration Time.
- *
- * It maintains a tree, sorted by the time values passed in to the Add()
- * function. It does not manage capacity, and can grow uncontrollably if the
- * owning ContentStore does not manage it. Items are indexed first by time, then
- * address of the Message (just as a distringuishing attribute). This allows us
- * to store multiple items with the same expiration time.
- */
-
-struct list_timeordered {
- PARCTreeRedBlack *timeOrderedTree;
-};
-
-static void _finalRelease(ListTimeOrdered **listP) {
- ListTimeOrdered *list = *listP;
- parcTreeRedBlack_Destroy(&list->timeOrderedTree);
-}
-
-parcObject_ExtendPARCObject(ListTimeOrdered, _finalRelease, NULL, NULL, NULL,
- NULL, NULL, NULL);
-
-parcObject_ImplementAcquire(listTimeOrdered, ListTimeOrdered);
-
-parcObject_ImplementRelease(listTimeOrdered, ListTimeOrdered);
-
-ListTimeOrdered *listTimeOrdered_Create(
- TimeOrderList_KeyCompare *keyCompareFunction) {
- ListTimeOrdered *result = parcObject_CreateInstance(ListTimeOrdered);
- if (NULL != result) {
- result->timeOrderedTree =
- parcTreeRedBlack_Create(keyCompareFunction, // keyCompare
- NULL, // keyFree
- NULL, // keyCopy
- NULL, // valueEquals
- NULL, // valueFree
- NULL); // valueCopy
- }
- return result;
-}
-
-void listTimeOrdered_Add(ListTimeOrdered *list, ContentStoreEntry *entry) {
- parcTreeRedBlack_Insert(list->timeOrderedTree, entry, entry);
-}
-
-ContentStoreEntry *listTimeOrdered_GetOldest(ListTimeOrdered *list) {
- return parcTreeRedBlack_FirstKey(list->timeOrderedTree);
-}
-
-bool listTimeOrdered_Remove(ListTimeOrdered *list,
- ContentStoreEntry *storeEntry) {
- bool result = false;
-
- ContentStoreEntry *entry = (ContentStoreEntry *)parcTreeRedBlack_Remove(
- list->timeOrderedTree, storeEntry);
- if (entry != NULL) {
- result = true;
- }
- return result;
-}
-
-size_t listTimeOrdered_Length(ListTimeOrdered *list) {
- return (size_t)parcTreeRedBlack_Size(list->timeOrderedTree);
-}
diff --git a/hicn-light/src/hicn/content_store/listTimeOrdered.h b/hicn-light/src/hicn/content_store/listTimeOrdered.h
deleted file mode 100644
index 325e7c0d4..000000000
--- a/hicn-light/src/hicn/content_store/listTimeOrdered.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.
- */
-
-#ifndef listTimeOrdered_h
-#define listTimeOrdered_h
-
-#include <parc/algol/parc_TreeRedBlack.h>
-#include <hicn/content_store/contentStoreEntry.h>
-#include <hicn/core/message.h>
-#include <stdio.h>
-
-struct list_timeordered;
-typedef struct list_timeordered ListTimeOrdered;
-
-/**
- * A signum function that takes two instances of ContentStoreEntrys and
- * returns a value based on their relative values.
- */
-typedef PARCTreeRedBlack_KeyCompare TimeOrderList_KeyCompare;
-
-/**
- * Create a new instance of `ListTimeOrdered` that will maintain the order of
- * its list items using the supplied `keyCompareFunction`.
- *
- * The newly created `ListTimeOrdered` must eventually be released by calling
- * {@link listTimeOrdered_Release}.
- *
- * @param keyCompareFunction the signum comparison function to use to sort
- * stored items.
- * @return a new instance of `TimeOrderList`.
- * @return NULL if the new instance couldn't be created.
- *
- */
-ListTimeOrdered *listTimeOrdered_Create(
- TimeOrderList_KeyCompare *keyCompareFunction);
-
-/**
- * Release a previously acquired reference to the specified instance,
- * decrementing the reference count for the instance.
- *
- * The pointer to the instance is set to NULL as a side-effect of this function.
- *
- * If the invocation causes the last reference to the instance to be released,
- * the instance is deallocated and the instance's implementation will perform
- * additional cleanup and release other privately held references.
- *
- */
-void listTimeOrdered_Release(ListTimeOrdered **listP);
-
-/**
- * Add a {@link ContentStoreEntry} instance to the specified list. Note that a
- * new refernece to the specified `storeEntry` is not acquired.
- *
- * @param list the list instance into which to add the specified storeEntry.
- * @param storeEntry the storeEntry instance to add.
- *
- */
-void listTimeOrdered_Add(ListTimeOrdered *list, ContentStoreEntry *storeEntry);
-
-/**
- * Remove a {@link ContentStoreEntry} instance from the specified list.
- *
- * @param list the list instance from which to remove the specified storeEntry.
- * @param storeEntry the storeEntry instance to remove.
- * @return true if the removal was succesful.
- * @return false if the removal was not succesful.
- *
- */
-bool listTimeOrdered_Remove(ListTimeOrdered *list,
- ContentStoreEntry *storeEntry);
-
-/**
- * Return the oldest {@link ContentStoreEntry} instance in this list. That is,
- * the one with the smallest time value.
- *
- * @param list the list instance from which to retrieve the oldest storeEntry.
- * @param the oldest `ContentStoreEntry` in the list
- * @param NULL if no `ContentStoreEntry` was available.
- *
- */
-ContentStoreEntry *listTimeOrdered_GetOldest(ListTimeOrdered *list);
-
-/**
- * Return the number of items currently stored in the list.
- *
- * @param list the `ListTimeOrdered` instance from which to retrieve the count.
- * @return the number of items in the list.
- *
- */
-size_t listTimeOrdered_Length(ListTimeOrdered *list);
-#endif /* defined(listTimeOrdered_h) */
diff --git a/hicn-light/src/hicn/content_store/lru.c b/hicn-light/src/hicn/content_store/lru.c
new file mode 100644
index 000000000..2f1fb9427
--- /dev/null
+++ b/hicn-light/src/hicn/content_store/lru.c
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _WIN32
+#include <sys/queue.h>
+#endif
+
+#include <hicn/util/log.h>
+
+#include <hicn/hicn-light/config.h>
+#include <stdio.h>
+
+#include <hicn/core/packet_cache.h>
+#include "lru.h"
+
+void cs_lru_initialize(cs_t *cs) {
+ /* We start with an empty double-linked list */
+ cs->lru.head = INVALID_ENTRY_ID;
+ cs->lru.tail = INVALID_ENTRY_ID;
+}
+
+void cs_lru_finalize(cs_t *cs) {
+ // Nothing to do
+}
+
+cs_entry_t *_cs_entry_at(pkt_cache_t *pkt_cache, off_t entry_id) {
+ pkt_cache_entry_t *entry = pkt_cache_entry_at(pkt_cache, entry_id);
+ assert(entry->entry_type == PKT_CACHE_CS_TYPE);
+ return &entry->u.cs_entry;
+}
+
+/**
+ * Remove a cs_entry_t from all tables and indices.
+ */
+static int cs_lru_remove_entry(pkt_cache_t *pkt_cache,
+ pkt_cache_entry_t *entry) {
+ assert(pkt_cache);
+ assert(entry);
+
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ cs_entry_t *cs_entry = &entry->u.cs_entry;
+
+ // If node to be deleted is head node
+ if (cs->lru.head == entry_id) cs->lru.head = cs_entry->lru.next;
+
+ // If node to be deleted is tail node
+ if (cs->lru.tail == entry_id) cs->lru.tail = cs_entry->lru.prev;
+
+ // If node to be deleted is not the last node
+ if (cs_entry->lru.next != INVALID_ENTRY_ID) {
+ cs_entry_t *next_cs_entry = _cs_entry_at(pkt_cache, cs_entry->lru.next);
+ assert(next_cs_entry);
+ next_cs_entry->lru.prev = cs_entry->lru.prev;
+ }
+
+ // If node to be deleted is not the first node
+ if (cs_entry->lru.prev != INVALID_ENTRY_ID) {
+ cs_entry_t *prev_entry = _cs_entry_at(pkt_cache, cs_entry->lru.prev);
+ assert(prev_entry);
+ prev_entry->lru.next = cs_entry->lru.next;
+ }
+
+ cs->stats.lru.countLruDeletions++;
+ return LRU_SUCCESS;
+}
+
+/**
+ * @brief LRU processing related to the insertion of a new entry in the content
+ * store (helper).
+ * @param[in] cs Content store.
+ * @param[in] entry_id Identifier of the entry in the content store entry pool.
+ * @param[in] is_update Boolean value to distinguish update from add operations
+ * since an update involves removing an entry and adding it again
+ *
+ * @return int Error code : 0 if succesful, a negative value otherwise.
+ *
+ * NOTE:
+ * - We insert the new element at the head of the double-linked list.
+ */
+int _cs_lru_add_entry(pkt_cache_t *pkt_cache, off_t entry_id, bool is_update) {
+ assert(pkt_cache);
+
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ cs_entry_t *entry = _cs_entry_at(pkt_cache, entry_id);
+ assert(entry);
+
+ // Add at the front of the LRU doubly linked list
+ if (cs->lru.head != INVALID_ENTRY_ID) {
+ cs_entry_t *head_entry = _cs_entry_at(pkt_cache, cs->lru.head);
+ assert(head_entry->lru.prev == INVALID_ENTRY_ID);
+ head_entry->lru.prev = entry_id;
+
+ entry->lru.next = cs->lru.head;
+ entry->lru.prev = INVALID_ENTRY_ID;
+
+ cs->lru.head = entry_id;
+ } else { /* The list is empty */
+ assert(cs->lru.tail == INVALID_ENTRY_ID);
+
+ entry->lru.next = INVALID_ENTRY_ID;
+ entry->lru.prev = INVALID_ENTRY_ID;
+ cs->lru.head = cs->lru.tail = entry_id;
+ }
+ if (!is_update) cs->stats.lru.countAdds++;
+
+ // Handle LRU eviction
+ if (cs->num_entries > cs->max_size) {
+ DEBUG("LRU eviction");
+ cs->stats.lru.countLruEvictions++;
+
+ // Remove from LRU tail
+ pkt_cache_entry_t *tail = pkt_cache_entry_at(pkt_cache, cs->lru.tail);
+ cs_lru_remove_entry(pkt_cache, tail);
+ return LRU_EVICTION;
+ }
+
+ return LRU_SUCCESS;
+}
+
+/**
+ * @brief LRU processing related to the insertion of a new entry in the content
+ * store.
+ * @param[in] cs Content store.
+ * @param[in] entry_id Identifier of the entry in the content store entry pool.
+ *
+ * @return int Error code : 0 if succesful, a negative value otherwise.
+ *
+ * NOTE:
+ * - We insert the new element at the head of the double-linked list.
+ */
+static int cs_lru_add_entry(pkt_cache_t *pkt_cache, off_t entry_id) {
+ return _cs_lru_add_entry(pkt_cache, entry_id, false);
+}
+
+/**
+ * Move a cs_entry_t to the LRU head.
+ */
+static void cs_lru_update_entry(pkt_cache_t *pkt_cache,
+ pkt_cache_entry_t *entry) {
+ assert(pkt_cache);
+ assert(entry);
+
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ cs->stats.lru.countUpdates++;
+
+ // Remove from LRU
+ cs_lru_remove_entry(pkt_cache, entry);
+
+ // Attach at the LRU head
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+ _cs_lru_add_entry(pkt_cache, entry_id, true);
+}
+
+DECLARE_CS(lru);
diff --git a/hicn-light/src/hicn/content_store/lru.h b/hicn-light/src/hicn/content_store/lru.h
new file mode 100644
index 000000000..9e78ce327
--- /dev/null
+++ b/hicn-light/src/hicn/content_store/lru.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HICNLIGHT_CS_LRU_H
+#define HICNLIGHT_CS_LRU_H
+
+#define LRU_FAILURE 0
+#define LRU_SUCCESS 1
+#define LRU_EVICTION 2
+
+typedef struct {
+ off_t prev;
+ off_t next;
+} cs_entry_lru_state_t;
+
+typedef struct {
+ off_t head;
+ off_t tail;
+} cs_lru_state_t;
+
+/**
+ * @brief Count the number of:
+ * - CS matches
+ * - CS misses
+ * - entries added to CS/LRU (upon receiving a data packet)
+ * - entries updated in the LRU
+ * (because an already-existing CS entry has been updated)
+ * - LRU evictions
+ *
+ * 'countExpiryEvictions' is not collected since an entry is never evicted
+ * because of expiration. An expired CS entry is only detected when
+ * a data packet with the same name is received, causing an update
+ * (NOT an actual eviction).
+ */
+typedef struct {
+ uint64_t countHits;
+ uint64_t countMisses;
+ uint64_t countAdds;
+ uint64_t countUpdates;
+ uint64_t countLruDeletions;
+ uint64_t countLruEvictions;
+} cs_lru_stats_t;
+
+#endif /* HICNLIGHT_CS_LRU_H */
diff --git a/hicn-light/src/hicn/core/CMakeLists.txt b/hicn-light/src/hicn/core/CMakeLists.txt
index 1b13be91f..94295bdf1 100644
--- a/hicn-light/src/hicn/core/CMakeLists.txt
+++ b/hicn-light/src/hicn/core/CMakeLists.txt
@@ -1,9 +1,9 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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,
@@ -12,49 +12,59 @@
# limitations under the License.
list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/connectionManager.h
- ${CMAKE_CURRENT_SOURCE_DIR}/connectionState.h
- ${CMAKE_CURRENT_SOURCE_DIR}/ticks.h
- ${CMAKE_CURRENT_SOURCE_DIR}/connectionList.h
- ${CMAKE_CURRENT_SOURCE_DIR}/connectionTable.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/address.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/address_pair.h
${CMAKE_CURRENT_SOURCE_DIR}/connection.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/connection_vft.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/connection_table.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/content_store.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/fib_entry.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/fib.h
${CMAKE_CURRENT_SOURCE_DIR}/forwarder.h
- ${CMAKE_CURRENT_SOURCE_DIR}/logger.h
- ${CMAKE_CURRENT_SOURCE_DIR}/dispatcher.h
- ${CMAKE_CURRENT_SOURCE_DIR}/message.h
- ${CMAKE_CURRENT_SOURCE_DIR}/messagePacketType.h
- ${CMAKE_CURRENT_SOURCE_DIR}/numberSet.h
- ${CMAKE_CURRENT_SOURCE_DIR}/streamBuffer.h
- ${CMAKE_CURRENT_SOURCE_DIR}/system.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/listener.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/listener_table.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/listener_vft.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/msgbuf.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/msgbuf_pool.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/packet_cache.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/pit.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/policy_stats.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy_vft.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/subscription.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/ticks.h
+
+ # ${CMAKE_CURRENT_SOURCE_DIR}/system.h
${CMAKE_CURRENT_SOURCE_DIR}/mapme.h
${CMAKE_CURRENT_SOURCE_DIR}/wldr.h
- ${CMAKE_CURRENT_SOURCE_DIR}/messageHandler.h
- ${CMAKE_CURRENT_SOURCE_DIR}/nameBitvector.h
- ${CMAKE_CURRENT_SOURCE_DIR}/name.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/nexthops.h
)
list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/address.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/address_pair.c
${CMAKE_CURRENT_SOURCE_DIR}/connection.c
- ${CMAKE_CURRENT_SOURCE_DIR}/connectionList.c
- ${CMAKE_CURRENT_SOURCE_DIR}/connectionManager.c
- ${CMAKE_CURRENT_SOURCE_DIR}/connectionTable.c
- ${CMAKE_CURRENT_SOURCE_DIR}/dispatcher.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/connection_table.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/connection_vft.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/content_store.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/fib.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/fib_entry.c
${CMAKE_CURRENT_SOURCE_DIR}/forwarder.c
- ${CMAKE_CURRENT_SOURCE_DIR}/logger.c
- ${CMAKE_CURRENT_SOURCE_DIR}/message.c
- ${CMAKE_CURRENT_SOURCE_DIR}/numberSet.c
- ${CMAKE_CURRENT_SOURCE_DIR}/streamBuffer.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/listener.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/listener_table.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/listener_vft.c
${CMAKE_CURRENT_SOURCE_DIR}/mapme.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/msgbuf.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/msgbuf_pool.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/nexthops.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/packet_cache.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/pit.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/policy_stats.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy_vft.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/subscription.c
${CMAKE_CURRENT_SOURCE_DIR}/wldr.c
- ${CMAKE_CURRENT_SOURCE_DIR}/nameBitvector.c
- ${CMAKE_CURRENT_SOURCE_DIR}/name.c
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
-
-set(TO_INSTALL_HEADER_FILES
- ${TO_INSTALL_HEADER_FILES}
- ${HEADER_FILES}
- PARENT_SCOPE
-)
diff --git a/hicn-light/src/hicn/core/address.c b/hicn-light/src/hicn/core/address.c
new file mode 100644
index 000000000..65664fa17
--- /dev/null
+++ b/hicn-light/src/hicn/core/address.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file address.c
+ * \brief Implementation of Address
+ */
+
+#include <hicn/core/address.h>
+#include <hicn/util/sstrncpy.h>
+
+int address_from_ip_port(address_t *address, int family,
+ hicn_ip_address_t *addr, uint16_t port) {
+ switch (family) {
+ case AF_INET:
+ *address = ADDRESS4(ntohl(addr->v4.as_inaddr.s_addr), ntohs(port));
+ break;
+ case AF_INET6:
+ *address = ADDRESS6(addr->v6.as_in6addr, ntohs(port));
+ break;
+ default:
+ return -1;
+ }
+ return 0;
+}
+
+const char *_address_family_str[] = {
+ [AF_INET] = "AF_INET",
+ [AF_INET6] = "AF_INET6",
+};
+
+int address_to_string(const address_t *address, char *addr_str, int *port) {
+ const int SUCCESS = 0;
+ char port_str[NI_MAXSERV];
+ struct sockaddr_storage addr = address->as_ss;
+ socklen_t addr_len = sizeof(addr);
+
+ int result =
+ getnameinfo((struct sockaddr *)&addr, addr_len, addr_str, NI_MAXHOST,
+ port_str, sizeof(port_str), NI_NUMERICHOST | NI_NUMERICSERV);
+
+ if (result != SUCCESS) {
+ strcpy_s(addr_str, NI_MAXHOST, "N/A");
+ if (port != NULL) *port = -1;
+ return result;
+ }
+
+ if (port != NULL) *port = atoi(port_str);
+ return SUCCESS;
+}
+
+address_t _ADDRESS4_LOCALHOST(uint16_t port) {
+ return ADDRESS4_LOCALHOST(port);
+}
diff --git a/hicn-light/src/hicn/core/address.h b/hicn-light/src/hicn/core/address.h
new file mode 100644
index 000000000..38cd1e87c
--- /dev/null
+++ b/hicn-light/src/hicn/core/address.h
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file address.h
+ * \brief Address
+ */
+
+#ifndef HICNLIGHT_ADDRESS_H
+#define HICNLIGHT_ADDRESS_H
+
+#include <netinet/in.h>
+
+#include <string.h> // memcmp
+#include <hicn/util/ip_address.h>
+#include <netinet/in.h>
+
+typedef union {
+ struct sockaddr_in as_sin;
+ struct sockaddr_in6 as_sin6;
+ struct sockaddr as_sa;
+ struct sockaddr_storage as_ss;
+} address_t;
+
+#define address_equals(a, b) (memcmp(a, b, sizeof(address_t)) == 0)
+
+#define address_family(address) ((address)->as_ss.ss_family)
+
+#define address4(address) ((struct sockaddr_in *)(address))
+#define address6(address) ((struct sockaddr_in6 *)(address))
+#define address_sa(address) ((struct sockaddr *)(address))
+
+#define address4_ip(address) (address4(address)->sin_addr)
+#define address6_ip(address) (address6(address)->sin6_addr)
+#define address6_scope_id(address) (address4_ptr(address)->sin6_scope_id)
+
+#define address_socklen(address) \
+ (((address)->as_ss.ss_family == AF_INET) ? sizeof(struct sockaddr_in) \
+ : sizeof(struct sockaddr_in6))
+
+#define address4_is_local(address) \
+ ((htonl((address4_ip(address)).s_addr) & 0xFF000000) == 0x7F000000)
+
+static inline bool _address6_is_local(struct sockaddr_in6 *sin6) {
+ return IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr);
+}
+
+#define address6_is_local(address) (_address6_is_local(address6(address)))
+
+#define address_is_local(address) \
+ ((address)->as_ss.ss_family == AF_INET) ? address4_is_local(address) \
+ : address6_is_local(address)
+
+int address_from_ip_port(address_t *address, int family,
+ hicn_ip_address_t *addr, uint16_t port);
+
+static inline address_t ADDRESS4(in_addr_t in_addr, int port) {
+ address_t address = {
+ .as_sin =
+ {
+ .sin_family = AF_INET,
+ .sin_port = htons(port),
+ .sin_addr = {.s_addr = htonl(in_addr)},
+ },
+ };
+
+ return address;
+}
+
+#define ADDRESS4_LOCALHOST(port) ADDRESS4(INADDR_LOOPBACK, (port))
+
+/**
+ * @brief Helper function to avoid macro expansion in c++ tests. Wrapper around
+ * 'ADDRESS4_LOCALHOST()'.
+ *
+ * @param port
+ * @return address_t
+ */
+address_t _ADDRESS4_LOCALHOST(uint16_t port);
+
+#define ADDRESS4_ANY(port) ADDRESS4(INADDR_ANY, (port))
+
+static inline address_t ADDRESS6(struct in6_addr in_addr, int port) {
+ address_t address = {
+ .as_sin6 =
+ {
+ .sin6_family = AF_INET6,
+ .sin6_port = htons(port),
+ .sin6_addr = in_addr,
+ },
+ };
+
+ return address;
+}
+
+#define ADDRESS6_LOCALHOST(port) ADDRESS6(in6addr_loopback, (port))
+#define ADDRESS6_ANY(port) ADDRESS6((struct in6_addr)IN6ADDR_ANY_INIT, port)
+
+#define ADDRESS_ANY(family, port) \
+ ((family == AF_INET) ? ADDRESS4_ANY(port) : ADDRESS6_ANY(port))
+
+extern const char *_address_family_str[];
+
+#define address_family_str(address) \
+ (_address_family_str[address_family(address)])
+
+#define address4_empty(address) (address4_ip(address).s_addr == 0)
+#define address6_empty(address) \
+ (memcmp(address6_ip(address).s6_addr, &in6addr_any, \
+ sizeof(struct in6_addr)) == 0)
+#define address_empty(address) \
+ (address_family(address) == AF_INET ? address4_empty(address) \
+ : address6_empty(address))
+
+/**
+ * @brief Return the string representation and the port of the IP address
+ * provided.
+ *
+ * @param[in] address Address to obtain the string representation from.
+ * @param[in, out] buffer String to store the string representation of the
+ * address. It contains "N/A" in case of failure (see return value).
+ * @param[in, out] port Integer to store the the port. It contains -1 in case of
+ * failure (see return value). If NULL, it will not be used to store the port.
+ * @return int 0 if success, failure otherwise.
+ */
+
+int address_to_string(const address_t *address, char *buffer, int *port);
+
+#endif /* HICNLIGHT_ADDRESS_H */
diff --git a/hicn-light/src/hicn/core/address_pair.c b/hicn-light/src/hicn/core/address_pair.c
new file mode 100644
index 000000000..c4f8b397b
--- /dev/null
+++ b/hicn-light/src/hicn/core/address_pair.c
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file address_pair.c
+ * \brief Implementation of Address pair
+ */
+
+#include "address_pair.h"
+
+address_pair_t address_pair_factory(address_t local, address_t remote) {
+ address_pair_t pair;
+ memset(&pair, 0, sizeof(address_pair_t));
+
+ pair.local = local;
+ pair.remote = remote;
+ return pair;
+}
+
+int address_pair_from_ip_port(address_pair_t* pair, int family,
+ hicn_ip_address_t* local_addr,
+ uint16_t local_port,
+ hicn_ip_address_t* remote_addr,
+ uint16_t remote_port) {
+ memset(pair, 0, sizeof(*pair));
+ if (address_from_ip_port(&pair->local, family, local_addr, local_port) < 0)
+ return -1;
+ if (address_from_ip_port(&pair->remote, family, remote_addr, remote_port) < 0)
+ return -1;
+ return 0;
+}
diff --git a/hicn-light/src/hicn/core/address_pair.h b/hicn-light/src/hicn/core/address_pair.h
new file mode 100644
index 000000000..b2872ad35
--- /dev/null
+++ b/hicn-light/src/hicn/core/address_pair.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file address_pair.h
+ * \brief Address pair
+ */
+
+#ifndef HICNLIGHT_ADDRESS_PAIR_H
+#define HICNLIGHT_ADDRESS_PAIR_H
+
+#include <hicn/util/ip_address.h>
+
+#include "address.h"
+
+typedef struct {
+ address_t local;
+ address_t remote;
+} address_pair_t;
+
+/**
+ * @brief Create an address pair starting from local and remote addresses.
+ *
+ * @param local The local address to use in the pair
+ * @param remote The remote address to use in the pair
+ * @return address_pair_t The address pair created
+ */
+address_pair_t address_pair_factory(address_t local, address_t remote);
+
+int address_pair_from_ip_port(address_pair_t* pair, int family,
+ hicn_ip_address_t* local_addr,
+ uint16_t local_port,
+ hicn_ip_address_t* remote_addr,
+ uint16_t remote_port);
+
+static inline int address_pair_equals(const address_pair_t* pair1,
+ const address_pair_t* pair2) {
+ return address_equals(&pair1->local, &pair2->local) &&
+ address_equals(&pair1->remote, &pair2->remote);
+}
+
+#define address_pair_get_local(pair) (&(pair)->local)
+#define address_pair_get_remote(pair) (&(pair)->remote)
+
+#define address_pair_get_local_family(pair) \
+ (address_family(address_pair_get_local(pair)))
+#define address_pair_get_remote_family(pair) \
+ (address_family(address_pair_get_remote(pair)))
+#define address_pair_get_family(pair) address_pair_get_local_family(pair)
+
+#define address_pair_is_valid(pair) \
+ (address_pair_get_local_family(pair) == address_pair_get_remote_family(pair))
+
+#endif /* HICNLIGHT_ADDRESS_PAIR_H */
diff --git a/hicn-light/src/hicn/core/connection.c b/hicn-light/src/hicn/core/connection.c
index c2ac71a5f..a9d632d52 100644
--- a/hicn-light/src/hicn/core/connection.c
+++ b/hicn-light/src/hicn/core/connection.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,347 +13,358 @@
* limitations under the License.
*/
-#include <limits.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
+/**
+ * @file connection.c
+ * @brief Implementation of hICN connections
+ */
-#include <hicn/core/connection.h>
-#include <hicn/core/connectionState.h>
-#include <hicn/core/messageHandler.h>
-#include <hicn/core/ticks.h>
-#include <hicn/core/wldr.h>
-#include <hicn/io/addressPair.h>
-#include <hicn/io/ioOperations.h>
+#include <assert.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#ifdef WITH_POLICY
+#include <hicn/core/forwarder.h>
+#include <hicn/core/listener.h>
+#include <hicn/core/wldr.h>
#include <hicn/policy.h>
-#endif /* WITH_POLICY */
+#include <hicn/util/log.h>
+
+#include "connection.h"
+#include "connection_vft.h"
+
+// This is called by configuration
+connection_t *connection_create(face_type_t type, const char *name,
+ const address_pair_t *pair,
+ const forwarder_t *forwarder) {
+ assert(face_type_is_valid(type));
+ assert(pair);
+ assert(forwarder);
+
+ /* initialized so that gcc-9 does not complain */
+ face_type_t listener_type = FACE_TYPE_UNDEFINED;
+ switch (type) {
+ case FACE_TYPE_UDP:
+ listener_type = FACE_TYPE_UDP_LISTENER;
+ break;
+ case FACE_TYPE_TCP:
+ listener_type = FACE_TYPE_TCP_LISTENER;
+ break;
+ case FACE_TYPE_HICN:
+ return NULL; /* Not implemented */
+ case FACE_TYPE_HICN_LISTENER:
+ case FACE_TYPE_UDP_LISTENER:
+ case FACE_TYPE_TCP_LISTENER:
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_N:
+ return NULL;
+ }
-struct connection {
+ listener_table_t *ltable = forwarder_get_listener_table(forwarder);
+ listener_key_t key = listener_key_factory(pair->local, listener_type);
- const AddressPair *addressPair;
- IoOperations *ops;
+ listener_t *listener = listener_table_get_by_key(ltable, &key);
+ if (!listener) {
+ WITH_ERROR({
+ char addr_str[NI_MAXHOST];
+ int port;
+ address_to_string(&pair->local, addr_str, &port);
+ ERROR("Could not find listener to match address %s:%d", addr_str, port);
+ })
- unsigned refCount;
+ return NULL;
+ }
- unsigned counter;
+ connection_table_t *table =
+ forwarder_get_connection_table(listener->forwarder);
+ unsigned connection_id = listener_create_connection(listener, name, pair);
+ if (!connection_id_is_valid(connection_id)) return NULL;
+ return connection_table_at(table, connection_id);
+}
- bool wldrAutoStart; // if true, wldr can be set automatically
- // by default this value is set to true.
- // if wldr is activated using a command (config
- // file/hicnLightControl) this value is set to false so
- // that a base station can not disable wldr at the client
- Wldr *wldr;
+netdevice_type_t connection_get_netdevice_type(const char *interface_name) {
+ if (strncmp(interface_name, "lo", 2) == 0) {
+ return NETDEVICE_TYPE_LOOPBACK;
+ }
+ if ((strncmp(interface_name, "eth", 3) == 0) ||
+ (strncmp(interface_name, "en", 2) == 0)) {
+ /* eth* en* enx* */
+ return NETDEVICE_TYPE_WIRED;
+ }
+ if (strncmp(interface_name, "wl", 2) == 0) {
+ /* wlan* wlp* wlx* */
+ return NETDEVICE_TYPE_WIFI;
+ }
+ if (strncmp(interface_name, "rmnet_ipa", 9) == 0) {
+ /* Qualcomm IPA driver */
+ return NETDEVICE_TYPE_UNDEFINED;
+ }
+ if ((strncmp(interface_name, "rmnet", 5) == 0) ||
+ (strncmp(interface_name, "rev_rmnet", 9) == 0) ||
+ (strncmp(interface_name, "ccmni", 5) == 0)) {
+ /*
+ * rmnet* (Qualcomm) ccmni* (MediaTek)
+ */
+ return NETDEVICE_TYPE_CELLULAR;
+ }
+ /* usb0 might be cellular (eg Zenfone2) */
+ /* what about tethering */
+ /* tun* dummy* ... */
+ /* bnet* pan* hci* for bluetooth */
+ return NETDEVICE_TYPE_UNDEFINED;
+}
+/**
+ * @brief Initializes a connection
+ *
+ * @param [out] connection - Allocated connection buffer (eg. from pool) to be
+ * initialized.
+ * @param [in] forwarder - forwarder_t to which the connection is associated.
+ * This parameter needs to be non-NULL for connections receiving packets, such
+ * as TCP connections which are very close to UDP listeners, and unlike
+ * bound UDP connections).
+ * @param [in] fd - A fd specific to the connection, or 0 if the connection
+ * should inherit the fd of the listener.
+ * @return 0 if no error, -1 otherwise
+ */
+int connection_initialize(connection_t *connection, face_type_t type,
+ const char *name, const char *interface_name, int fd,
+ const address_pair_t *pair, bool local,
+ unsigned connection_id, listener_t *listener) {
+ int rc;
+
+ assert(connection);
+ /* Interface name can be NULL eg always for TCP connnections */
+ assert(pair);
+ // assert(address_pair_is_valid(pair)); TODO: local addr in the pair is not
+ // initialized for now
+
+ if (fd == 0) WARN("Connection is not connected");
+
+ *connection = (connection_t){
+ .id = connection_id,
+ .name = strdup(name),
+ .type = type,
+ .interface_name = strdup(interface_name),
+ .pair = *pair,
+ .fd = ((fd != 0) ? fd : listener_get_fd(listener)),
+ .connected = (fd != 0),
+ // .up = true,
+ .local = local,
+ // XXX UDP should start UP, TCP DOWN until remove side answer ?
+ .state = FACE_STATE_UNDEFINED,
+ .admin_state = FACE_STATE_UP,
#ifdef WITH_POLICY
- policy_tags_t tags;
+ .priority = 0,
#endif /* WITH_POLICY */
-};
-
-Connection *connection_Create(IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- Connection *conn = parcMemory_AllocateAndClear(sizeof(Connection));
- parcAssertNotNull(conn, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Connection));
- conn->addressPair = ioOperations_GetAddressPair(ops);
- conn->ops = ops;
- conn->refCount = 1;
- conn->wldr = NULL;
+ .listener = listener,
+ .closed = false,
- conn->wldrAutoStart = true;
- conn->counter = 0;
+ /* WLDR */
+ .wldr = NULL,
+ .wldr_autostart = true,
+ };
+ connection->stats.conn_id = connection_id;
- /* By default, a connection will aim at the UP state */
- connection_SetAdminState(conn, CONNECTION_STATE_UP);
+ connection->interface_type =
+ connection_get_netdevice_type(connection->interface_name);
#ifdef WITH_POLICY
- conn->tags = POLICY_TAGS_EMPTY;
-#endif /* WITH_POLICY */
+ connection_clear_tags(connection);
+ switch (connection->interface_type) {
+#if 0
+ case NETDEVICE_TYPE_LOOPBACK:
+ connection_add_tag(connection, POLICY_TAG_LOOPBACK);
+ break;
+#endif
+ case NETDEVICE_TYPE_WIRED:
+ connection_add_tag(connection, POLICY_TAG_WIRED);
+ break;
+ case NETDEVICE_TYPE_WIFI:
+ connection_add_tag(connection, POLICY_TAG_WIFI);
+ break;
+ case NETDEVICE_TYPE_CELLULAR:
+ connection_add_tag(connection, POLICY_TAG_CELLULAR);
+ default:
+ break;
+ }
+#endif
- return conn;
-}
+ connection->data =
+ malloc(connection_vft[get_protocol(connection->type)]->data_size);
+ if (!connection->data) goto ERR_DATA;
-Connection *connection_Acquire(Connection *connection) {
- parcAssertNotNull(connection, "Parameter conn must be non-null");
- connection->refCount++;
- return connection;
-}
+ assert(connection_has_valid_id(connection));
-void connection_Release(Connection **connectionPtr) {
- parcAssertNotNull(connectionPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*connectionPtr,
- "Parameter must dereference to non-null pointer");
- Connection *conn = *connectionPtr;
-
- parcAssertTrue(
- conn->refCount > 0,
- "Invalid state, connection reference count should be positive, got 0.");
- conn->refCount--;
- if (conn->refCount == 0) {
- // don't destroy addressPair, its part of ops.
- ioOperations_Release(&conn->ops);
- if (conn->wldr != NULL) {
- wldr_Destroy(&(conn->wldr));
- }
- parcMemory_Deallocate((void **)&conn);
+ rc = connection_vft[get_protocol(connection->type)]->initialize(connection);
+ if (rc < 0) {
+ goto ERR_VFT;
}
- *connectionPtr = NULL;
-}
-
-bool connection_Send(const Connection *conn, Message *message) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
- if (ioOperations_IsUp(conn->ops)) {
- if (message_GetType(message) == MessagePacketType_ContentObject) {
- uint8_t connectionId = (uint8_t)connection_GetConnectionId(conn);
- message_UpdatePathLabel(message, connectionId);
+ if (connection->connected) {
+ /*
+ * The file descriptor is created by the listener. We assume for now that
+ * all connections get their own fd, and we have to register it.
+ *
+ * TODO the connection has no more read callback, so we call the one from
+ * the listener.
+ */
+ loop_fd_event_create(&connection->event_data, MAIN_LOOP, fd, listener,
+ (fd_callback_t)listener_read_callback, connection->id,
+ NULL);
+
+ if (!connection->event_data) {
+ goto ERR_REGISTER_FD;
}
- if (conn->wldr != NULL) {
- wldr_SetLabel(conn->wldr, message);
- } else {
- message_ResetWldrLabel(message);
+
+ if (loop_fd_event_register(connection->event_data) < 0) {
+ goto ERR_REGISTER_FD;
}
- return ioOperations_Send(conn->ops, NULL, message);
}
- return false;
-}
-
-bool connection_SendIOVBuffer(const Connection *conn, struct iovec *msg,
- size_t size) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- parcAssertNotNull(msg, "Parameter message must be non-null");
-
- return ioOperations_SendIOVBuffer(conn->ops, msg, size);
-}
-bool connection_SendBuffer(const Connection *conn, u8 * buffer, size_t length)
-{
- struct iovec iov[1];
- iov[0].iov_base = buffer;
- iov[0].iov_len = length;
- return connection_SendIOVBuffer(conn, iov, 1);
-}
-
-void connection_Probe(Connection *conn, uint8_t * probe) {
- ioOperations_SendProbe(conn->ops, probe);
-}
-
-void connection_HandleProbe(Connection *conn, uint8_t *probe){
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- parcAssertNotNull(probe, "Parameter pkt must be non-null");
-
- if(messageHandler_IsInterest(probe)){
- messageHandler_CreateProbeReply(probe, HF_INET6_TCP);
- ioOperations_SendProbe(conn->ops, probe);
+ return 0;
+
+ERR_REGISTER_FD:
+#ifndef _WIN32
+ close(fd);
+#else
+ closesocket(fd);
+#endif
+ERR_VFT:
+ free(connection->data);
+ERR_DATA:
+ free(connection->interface_name);
+ free(connection->name);
+ return -1;
+}
+
+int connection_finalize(connection_t *connection) {
+ assert(connection);
+ assert(connection_has_valid_type(connection));
+
+ if (connection->connected) {
+ loop_event_unregister(connection->event_data);
+ loop_event_free(connection->event_data);
}
-}
-
-IoOperations *connection_GetIoOperations(const Connection *conn) {
- return conn->ops;
-}
-
-unsigned connection_GetConnectionId(const Connection *conn) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- return ioOperations_GetConnectionId(conn->ops);
-}
-
-const AddressPair *connection_GetAddressPair(const Connection *conn) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- return ioOperations_GetAddressPair(conn->ops);
-}
-
-bool connection_IsUp(const Connection *conn) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops) return false;
- return ioOperations_IsUp(conn->ops);
-}
-bool connection_IsLocal(const Connection *conn) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- return ioOperations_IsLocal(conn->ops);
-}
+ if (connection->fd != 0) { // Only if connected socket
+#ifndef _WIN32
+ close(connection->fd);
+#else
+ closesocket(connection->fd);
+#endif
+ }
-const void *connection_Class(const Connection *conn) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- return ioOperations_Class(conn->ops);
-}
+ if (connection->wldr) wldr_free(connection->wldr);
-bool connection_ReSend(const Connection *conn, Message *message,
- bool notification) {
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
- bool res = false;
-
- if (connection_IsUp(conn)) {
- // here the wldr header is alreay set: this message is a retransmission or a
- // notification
-
- // we need to recompiute the path lable since we always store a pointer to
- // the same message if this message will be sent again to someonelse, the
- // new path label must be computed starting from the orignal labelorignal
- // label. Notice that we heve the same problem in case of PIT aggregation.
- // That case is handled insied the MessageProcessor. This is specific to
- // WLDR retransmittions. This is done only for data packets
-
- if (message_GetType(message) == MessagePacketType_ContentObject) {
- uint8_t connectionId = (uint8_t)connection_GetConnectionId(conn);
- uint32_t old_path_label = message_GetPathLabel(message);
- message_UpdatePathLabel(message, connectionId);
-
- res = ioOperations_Send(conn->ops, NULL, message);
-
- message_SetPathLabel(message, old_path_label);
- } else {
- res = ioOperations_Send(conn->ops, NULL, message);
- }
- }
+ connection_vft[get_protocol(connection->type)]->finalize(connection);
- if (notification) {
- // the notification is never destroyed
- message_Release(&message);
- }
+ if (connection->data) free(connection->data);
+ connection->data = NULL;
+ if (connection->interface_name) free(connection->interface_name);
+ connection->interface_name = NULL;
+ if (connection->name) free(connection->name);
+ connection->name = NULL;
- return res;
+ return 0;
}
-void connection_AllowWldrAutoStart(Connection *conn, bool allow) {
- conn->wldrAutoStart = allow;
-}
+bool connection_send_packet(const connection_t *connection,
+ const uint8_t *packet, size_t size) {
+ assert(connection);
+ assert(face_type_is_valid(connection->type));
+ assert(packet);
-void connection_EnableWldr(Connection *conn) {
- if (!connection_IsLocal(conn)) {
- if (conn->wldr == NULL) {
- printf("----------------- enable wldr\n");
- conn->wldr = wldr_Init();
- }
- }
+ return connection_vft[get_protocol(connection->type)]->send_packet(
+ connection, packet, size);
}
-void connection_DisableWldr(Connection *conn) {
- if (!connection_IsLocal(conn)) {
- if (conn->wldr != NULL) {
- printf("----------------- disable wldr\n");
- wldr_Destroy(&(conn->wldr));
- conn->wldr = NULL;
- }
- }
+bool _connection_send(connection_t *connection, msgbuf_t *msgbuf, bool queue) {
+ return connection_vft[get_protocol(connection->type)]->send(connection,
+ msgbuf, queue);
}
-bool connection_HasWldr(const Connection *conn) {
- if (conn->wldr == NULL) {
- return false;
- } else {
- return true;
- }
+bool connection_flush(connection_t *connection) {
+ return connection_vft[get_protocol(connection->type)]->flush(connection);
}
-bool connection_WldrAutoStartAllowed(const Connection *conn) {
- return conn->wldrAutoStart;
-}
+bool connection_send(connection_t *connection, off_t msgbuf_id, bool queue) {
+ assert(connection);
+ assert(msgbuf_id_is_valid(msgbuf_id));
-void connection_DetectLosses(Connection *conn, Message *message) {
- if (conn->wldr != NULL) wldr_DetectLosses(conn->wldr, conn, message);
-}
+ // if (!connection_is_up(connection))
+ // return false;
-void connection_HandleWldrNotification(Connection *conn, Message *message) {
- if (conn->wldr != NULL)
- wldr_HandleWldrNotification(conn->wldr, conn, message);
-}
+ const listener_t *listener = connection_get_listener(connection);
+ const forwarder_t *forwarder = listener_get_forwarder(listener);
+ const msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
-connection_state_t connection_GetState(const Connection *conn)
-{
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops)
- return CONNECTION_STATE_UNDEFINED;
- return ioOperations_GetState(conn->ops);
-}
+#if 0
+ if (connection->wldr)
+ wldr_set_label(connection->wldr, msgbuf);
+ else
+ msgbuf_reset_wldr_label(msgbuf);
+#endif
-void connection_SetState(Connection *conn, connection_state_t state)
-{
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops)
- return;
- ioOperations_SetState(conn->ops, state);
+ return _connection_send(connection, msgbuf, queue);
}
-connection_state_t connection_GetAdminState(const Connection *conn)
-{
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops)
- return CONNECTION_STATE_UNDEFINED;
- return ioOperations_GetAdminState(conn->ops);
-}
+/*
+ * here the wldr header is alreay set: this message is a retransmission or a
+ * notification
+ *
+ * we need to recompute the path label since we always store a pointer to
+ * the same message if this message will be sent again to someone else, the
+ * new path label must be computed starting from the orignal label. Note
+ * that we heve the same problem in case of PIT aggregation. That case is
+ * handled inside the MessageProcessor. This is specific to WLDR
+ * retransmittions. This is done only for data packets
+ */
+bool connection_resend(connection_t *connection, msgbuf_t *msgbuf,
+ bool notification) {
+ assert(connection);
+ assert(msgbuf);
-void connection_SetAdminState(Connection *conn, connection_state_t admin_state)
-{
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops)
- return;
- if ((admin_state != CONNECTION_STATE_UP) && (admin_state != CONNECTION_STATE_DOWN))
- return;
- ioOperations_SetAdminState(conn->ops, admin_state);
-}
+ bool ret = false;
-#ifdef WITH_POLICY
-uint32_t connection_GetPriority(const Connection *conn)
-{
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops)
- return 0;
- return ioOperations_GetPriority(conn->ops);
-}
+ if (!connection_is_up(connection)) return ret;
-void connection_SetPriority(Connection *conn, uint32_t priority)
-{
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops)
- return;
- ioOperations_SetPriority(conn->ops, priority);
-}
-#endif /* WITH_POLICY */
+ ret = _connection_send(connection, msgbuf, false); /* no queueing */
-const char * connection_GetInterfaceName(const Connection * conn)
-{
- parcAssertNotNull(conn, "Parameter conn must be non-null");
- if (!conn->ops)
- return NULL;
- return ioOperations_GetInterfaceName(conn->ops);
+ return ret;
}
-#ifdef WITH_POLICY
+/* WLDR */
-void connection_AddTag(Connection *conn, policy_tag_t tag)
-{
- policy_tags_add(&conn->tags, tag);
+void connection_wldr_allow_autostart(connection_t *connection, bool value) {
+ connection->wldr_autostart = value;
}
-void connection_RemoveTag(Connection *conn, policy_tag_t tag)
-{
- policy_tags_remove(&conn->tags, tag);
+bool connection_wldr_autostart_is_allowed(const connection_t *connection) {
+ return connection->wldr_autostart;
}
-policy_tags_t connection_GetTags(const Connection *conn)
-{
- return conn->tags;
+void connection_wldr_enable(connection_t *connection, bool value) {
+ if (connection_is_local(connection)) return;
+ if (value) {
+ if (connection->wldr) return;
+ connection->wldr = wldr_create();
+ } else {
+ if (!connection->wldr) return;
+ wldr_free(connection->wldr);
+ }
}
-void connection_SetTags(Connection *conn, policy_tags_t tags)
-{
- conn->tags = tags;
+bool connection_has_wldr(const connection_t *connection) {
+ return !!connection->wldr;
}
-void connection_ClearTags(Connection *conn)
-{
- conn->tags = POLICY_TAGS_EMPTY;
+void connection_wldr_detect_losses(const connection_t *connection,
+ const msgbuf_t *msgbuf) {
+ if (!connection->wldr) return;
+ wldr_detect_losses(connection->wldr, connection, msgbuf);
}
-int connection_HasTag(const Connection *conn, policy_tag_t tag)
-{
- return policy_tags_has(conn->tags, tag);
+void connection_wldr_handle_notification(const connection_t *connection,
+ const msgbuf_t *msgbuf) {
+ if (!connection->wldr) return;
+ wldr_handle_notification(connection->wldr, connection, msgbuf);
}
-
-#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/core/connection.h b/hicn-light/src/hicn/core/connection.h
index b6513ea1a..e177e2039 100644
--- a/hicn-light/src/hicn/core/connection.h
+++ b/hicn-light/src/hicn/core/connection.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.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,184 +15,230 @@
/**
* @file connection.h
- * @brief Wrapper for different types of connections
- *
- * A connection wraps a specific set of {@link IoOperations}. Those operations
- * allow for input and output. Connections get stored in the Connection Table.
- *
+ * @brief hICN connections
*/
-#ifndef connection_h
-#define connection_h
-#include <hicn/hicn-light/config.h>
-#include <hicn/core/connectionState.h>
-#include <hicn/io/ioOperations.h>
-#include <hicn/utils/address.h>
+#ifndef HICNLIGHT_CONNECTION_H
+#define HICNLIGHT_CONNECTION_H
-#ifdef WITH_MAPME
-typedef enum {
- CONNECTION_EVENT_CREATE,
- CONNECTION_EVENT_DELETE,
- CONNECTION_EVENT_UPDATE,
- CONNECTION_EVENT_SET_UP,
- CONNECTION_EVENT_SET_DOWN,
- CONNECTION_EVENT_PRIORITY_CHANGED,
- CONNECTION_EVENT_TAGS_CHANGED,
-} connection_event_t;
+#include <hicn/face.h>
-#endif /* WITH_MAPME */
+#include "address_pair.h"
+#include "listener.h"
+#include "msgbuf.h"
#ifdef WITH_POLICY
#include <hicn/policy.h>
#endif /* WITH_POLICY */
-struct connection;
-typedef struct connection Connection;
+#define CONNECTION_ID_UNDEFINED INVALID_FACE_ID
-/**
- * Creates a connection object.
- */
-Connection *connection_Create(IoOperations *ops);
+#define foreach_connection_event \
+ _(UNDEFINED) \
+ _(CREATE) \
+ _(DELETE) \
+ _(UPDATE) \
+ _(SET_UP) \
+ _(SET_DOWN) \
+ _(PRIORITY_CHANGED) \
+ _(TAGS_CHANGED) \
+ _(N)
-/**
- * @function connection_Release
- * @abstract Releases a reference count, destroying on last release
- * @discussion
- * Only frees the memory on the final reference count. The pointer will
- * always be NULL'd.
- */
-void connection_Release(Connection **connectionPtr);
+typedef enum {
+#define _(x) CONNECTION_EVENT_##x,
+ foreach_connection_event
+#undef _
+} connection_event_t;
-/**
- * @function connection_Acquire
- * @abstract A reference counted copy.
- * @discussion
- * A shallow copy, they share the same memory.
- */
-Connection *connection_Acquire(Connection *connection);
+struct wldr_s;
+
+typedef struct {
+ unsigned id;
+ char* name;
+ char* interface_name;
+ netdevice_type_t interface_type;
+ face_type_t type;
+ address_pair_t pair;
+ // bool up;
+ bool local;
+ face_state_t state;
+ face_state_t admin_state;
+#ifdef WITH_POLICY
+ policy_tags_t tags;
+ uint32_t priority;
+#endif /* WITH_POLICY */
-/**
- * @function connection_Send
- * @abstract Sends the message on the connection
- * @return true if message sent, false if connection not up
- */
-bool connection_Send(const Connection *conn, Message *message);
+ int fd;
+ bool connected; // true if the connection is connected and has its own fd
+ event_t* event_data;
+
+ void* data;
+
+ listener_t* listener;
+ // struct forwarder_s * forwarder; // recv only
+ bool closed;
+
+ /* WLDR */
+
+ bool wldr_autostart;
+ /*
+ * if true, wldr can be set automatically by default this value is set to
+ * true. if wldr is activated using a command (config file/hicnLightControl)
+ * this value is set to false so that a base station can not disable wldr at
+ * the client.
+ */
+ struct wldr_s* wldr;
+
+ connection_stats_t stats;
+} connection_t;
+
+#if 1
+#define connection_get_id(C) ((C)->id)
+#define connection_id_is_valid(ID) (ID != CONNECTION_ID_UNDEFINED)
+#define connection_get_name(C) ((C)->name)
+#define connection_get_type(C) ((C)->type)
+#define connection_has_valid_id(C) \
+ (connection_id_is_valid(connection_get_id(C)))
+#define connection_has_valid_type(C) \
+ (face_type_is_valid(connection_get_type(C)))
+#define connection_get_pair(C) (&(C)->pair)
+#define connection_get_local(C) (address_pair_get_local(connection_get_pair(C)))
+#define connection_get_remote(C) \
+ (address_pair_get_remote(connection_get_pair(C)))
+#define connection_get_local(C) (address_pair_get_local(connection_get_pair(C)))
+#define connection_get_remote(C) \
+ (address_pair_get_remote(connection_get_pair(C)))
+#define connection_is_up(C) ((C)->state == FACE_STATE_UP)
+#define connection_is_closed(C) ((C)->closed == true)
+#define connection_is_local(C) ((C)->local)
+#define connection_get_state(C) ((C)->state)
+#define connection_set_state(C, STATE) (C)->state = STATE
+#define connection_get_admin_state(C) ((C)->admin_state)
+#define connection_set_admin_state(C, STATE) (C)->admin_state = STATE
+#define connection_get_interface_name(C) ((C)->interface_name)
+#define connection_get_interface_type(C) ((C)->interface_type)
-/**
- * @function connection_SendIOVBuffer
- * @abstract Sends an IOV buffer
- */
-bool connection_SendIOVBuffer(const Connection *conn, struct iovec *msg,
- size_t size);
+#ifdef WITH_POLICY
+#define connection_get_priority(C) ((C)->priority)
+#define connection_set_priority(C, PRIORITY) (C)->priority = PRIORITY
+#define connection_get_tags(C) ((C)->tags)
+#define connection_set_tags(C, TAGS) (C)->tags = TAGS
+#define connection_has_tag(C, TAG) policy_tags_has(connection_get_tags(C), TAG)
+#define connection_add_tag(C, TAG) policy_tags_add(&connection_get_tags(C), TAG)
+#define connection_remove_tag(C, TAG) \
+ do { \
+ policy_tags_t _conn_var(tags); \
+ _conn_var(tags) = connection_get_tags(C); \
+ policy_tags_remove(_conn_var(tags), (TAG)); \
+ connection_set_tags((C), _conn_var(tags)); \
+ } while (0)
+#define connection_clear_tags(C) connection_set_tags(C, POLICY_TAGS_EMPTY)
-/**
- * @function connection_SendBuffer
- * @abstract Sends a buffer
- */
-bool connection_SendBuffer(const Connection *conn, u8 * buffer, size_t length);
+#endif /* WITH_POLICY */
-/**
- * Return the `IoOperations` instance associated with the specified `Connection`
- * instance.
- * @param [in] connection The allocated connection
- * @return a pointer to the IoOperations instance associated by th specified
- * connection.
- */
-IoOperations *connection_GetIoOperations(const Connection *conn);
+#else
-/**
- * Returns the unique identifier of the connection
- * Calls the underlying IoOperations to fetch the connection id
- * @param [in] connection The allocated connection
- * @return unsigned The unique connection id
- */
-unsigned connection_GetConnectionId(const Connection *conn);
+/* Accessors */
+static inline unsigned connection_get_id(const connection_t* connection);
-/**
- * Returns the (remote, local) address pair that describes the connection
- * @param [in] connection The allocated connection
- * @return non-null The connection's remote and local address
- * @return null Should never return NULL
- */
-const AddressPair *connection_GetAddressPair(const Connection *conn);
+#define connection_id_is_valid(id) (id != CONNECTION_ID_UNDEFINED)
+#define connection_has_valid_id(C) (connection_id_is_valid(connection_get_id(C))
-/**
- * Checks if the connection is in the "up" state
- * @param [in] connection The allocated connection
- * @return true The connection is in the "up" state
- * @return false The connection is not in the "up" state
- */
-bool connection_IsUp(const Connection *conn);
+static inline char* connection_get_name(const connection_t* connection);
-/**
- * Checks if the connection is to a Local/Loopback address
- *
- * A local connection is PF_LOCAL (PF_UNIX) and a loopback connection is
- * 127.0.0.0/8 or ::1 for IPv6.
- *
- * @param [in] connection The allocated connection
- *
- * @retval true The connection is local or loopback
- * @retval false The connection is not local or loopback
- */
-bool connection_IsLocal(const Connection *conn);
+static inline face_type_t connection_get_type(const connection_t* connection);
-/**
- * Returns an opaque pointer representing the class of the Io Operations
- *
- * Returns an opaque pointer that an implementation can use to detect if
- * the connection is based on that class.
- *
- * @param [in] conn The Connection to analyze
- *
- * @return non-null An opaque pointer for each concrete implementation
- */
-const void *connection_Class(const Connection *conn);
+static inline address_pair_t* connection_get_pair(
+ const connection_t* connection);
-bool connection_ReSend(const Connection *conn, Message *message,
- bool notification);
+#define connection_get_local(C) (address_pair_get_local(connection_get_pair(C)))
+#define connection_get_remote(C) (address_pair_remote(connection_get_pair(C)))
-void connection_Probe(Connection *conn, uint8_t *probe);
+static inline bool connection_is_up(const connection_t* connection);
-void connection_HandleProbe(Connection *conn, uint8_t *message);
+static inline bool connection_is_local(const connection_t* connection);
-void connection_AllowWldrAutoStart(Connection *conn, bool allow);
+static inline face_state_t connection_get_state(const connection_t* connection);
-void connection_EnableWldr(Connection *conn);
+static inline void connection_set_state(connection_t* connection,
+ face_state_t state);
-void connection_DisableWldr(Connection *conn);
+static inline face_state_t connection_get_admin_state(
+ const connection_t* connection);
-bool connection_HasWldr(const Connection *conn);
+static inline void connection_set_admin_state(connection_t* connection,
+ face_state_t state);
-bool connection_WldrAutoStartAllowed(const Connection *conn);
+static inline const char* connection_get_interface_name(
+ const connection_t* connection);
-void connection_DetectLosses(Connection *conn, Message *message);
+#ifdef WITH_POLICY
-void connection_HandleWldrNotification(Connection *conn, Message *message);
+static inline uint32_t connection_get_priority(const connection_t* connection);
-connection_state_t connection_GetState(const Connection *conn);
+static inline void connection_set_priority(connection_t* connection,
+ uint32_t priority);
-void connection_SetState(Connection *conn, connection_state_t state);
+static inline policy_tags_t connection_get_tags(const connection_t* connection);
-connection_state_t connection_GetAdminState(const Connection *conn);
+static inline void connection_set_tags(connection_t* connection,
+ policy_tags_t tags);
-void connection_SetAdminState(Connection *conn, connection_state_t admin_state);
+#define connection_has_tag(C, TAG) policy_tags_has(connection_get_tags(C), TAG)
-#ifdef WITH_POLICY
-uint32_t connection_GetPriority(const Connection *conn);
+#define connection_add_tag(C, TAG) policy_tags_add(connection_get_tags(X), TAG)
-void connection_SetPriority(Connection *conn, uint32_t priority);
-#endif /* WITH_POLICY */
+#define connection_remove_tag(C, TAG) \
+ do { \
+ policy_tags_t _conn_var(tags); \
+ _conn_var(tags) = connection_get_tags(C); \
+ policy_tags_remove(_conn_var(tags), (TAG)); \
+ connection_set_tags((C), _conn_var(tags)); \
+ } while (0)
-const char * connection_GetInterfaceName(const Connection * conn);
+#define connection_clear_tags(C) connection_set_tags(C, POLICY_TAGS_EMPTY)
-#ifdef WITH_POLICY
-void connection_AddTag(Connection *conn, policy_tag_t tag);
-void connection_RemoveTag(Connection *conn, policy_tag_t tag);
-policy_tags_t connection_GetTags(const Connection *conn);
-void connection_SetTags(Connection *conn, policy_tags_t tags);
-void connection_ClearTags(Connection *conn);
-int connection_HasTag(const Connection *conn, policy_tag_t tag);
#endif /* WITH_POLICY */
-#endif // connection_h
+#endif
+
+connection_t* connection_create(face_type_t type, const char* name,
+ const address_pair_t* pair,
+ const struct forwarder_s* forwarder);
+
+int connection_initialize(connection_t* connection, face_type_t type,
+ const char* name, const char* interface_name, int fd,
+ const address_pair_t* pair, bool local,
+ unsigned connection_id, listener_t* listener);
+
+int connection_finalize(connection_t* connection);
+
+bool connection_send_packet(const connection_t* connection,
+ const uint8_t* packet, size_t size);
+
+bool connection_flush(connection_t* connection);
+
+bool connection_send(connection_t* connection, off_t msgbuf_id, bool queue);
+
+size_t connection_process_buffer(connection_t* connection,
+ const uint8_t* buffer, size_t size);
+
+/* WLDR */
+
+void connection_wldr_allow_autostart(connection_t* connection, bool value);
+
+bool connection_wldr_autostart_is_allowed(const connection_t* connection);
+
+void connection_wldr_enable(connection_t* connection, bool value);
+
+bool connection_has_wldr(const connection_t* connection);
+
+void connection_wldr_detect_losses(const connection_t* connection,
+ const msgbuf_t* msgbuf);
+
+void connection_wldr_handle_notification(const connection_t* connection,
+ const msgbuf_t* msgbuf);
+
+#define connection_get_listener(connection) (connection->listener)
+
+#endif /* HICNLIGHT_CONNECTION_H */
diff --git a/hicn-light/src/hicn/core/connectionList.c b/hicn-light/src/hicn/core/connectionList.c
deleted file mode 100644
index d51a9aad5..000000000
--- a/hicn-light/src/hicn/core/connectionList.c
+++ /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.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Memory.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <hicn/core/connectionList.h>
-
-struct connection_list {
- PARCArrayList *listOfConnections;
-};
-
-static void connectionList_ArrayDestroyer(void **voidPtr) {
- Connection **entryPtr = (Connection **)voidPtr;
- connection_Release(entryPtr);
-}
-
-ConnectionList *connectionList_Create() {
- ConnectionList *list = parcMemory_AllocateAndClear(sizeof(ConnectionList));
- parcAssertNotNull(list, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ConnectionList));
- list->listOfConnections = parcArrayList_Create(connectionList_ArrayDestroyer);
- return list;
-}
-
-void connectionList_Destroy(ConnectionList **listPtr) {
- parcAssertNotNull(listPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*listPtr, "Parameter must dereference to non-null pointer");
- ConnectionList *list = *listPtr;
- parcArrayList_Destroy(&list->listOfConnections);
- parcMemory_Deallocate((void **)&list);
- *listPtr = NULL;
-}
-
-void connectionList_Append(ConnectionList *list, Connection *entry) {
- parcAssertNotNull(list, "Parameter list must be non-null");
- parcAssertNotNull(entry, "Parameter entry must be non-null");
-
- parcArrayList_Add(list->listOfConnections, connection_Acquire(entry));
-}
-
-size_t connectionList_Length(const ConnectionList *list) {
- parcAssertNotNull(list, "Parameter list must be non-null");
- return parcArrayList_Size(list->listOfConnections);
-}
-
-Connection *connectionList_Get(ConnectionList *list, size_t index) {
- parcAssertNotNull(list, "Parameter list must be non-null");
- Connection *original =
- (Connection *)parcArrayList_Get(list->listOfConnections, index);
- return original;
-}
diff --git a/hicn-light/src/hicn/core/connectionList.h b/hicn-light/src/hicn/core/connectionList.h
deleted file mode 100644
index fbba9f6d8..000000000
--- a/hicn-light/src/hicn/core/connectionList.h
+++ /dev/null
@@ -1,70 +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.
- */
-
-/**
- * @file connectionList.h
- * @brief A typesafe list of Connection objects
- *
- * <#Detailed Description#>
- *
- */
-
-#ifndef connectionList_h
-#define connectionList_h
-
-struct connection_list;
-typedef struct connection_list ConnectionList;
-
-#include <hicn/core/connection.h>
-
-/**
- * Creates a lis of Connection
- *
- * @return non-null An allocated list
- * @return null An error
- */
-ConnectionList *connectionList_Create(void);
-
-/**
- * Destroys the list and all objects inside it
- */
-void connectionList_Destroy(ConnectionList **listPtr);
-
-/**
- * @function connectionList_Append
- * @abstract Adds a connection entry to the list.
- * @discussion
- * Acquires a reference to the passed entry and stores it in the list.
- */
-void connectionList_Append(ConnectionList *list, Connection *entry);
-
-/**
- * Returns the number of items on the list
- * @param [in] list The allocated list to check
- * @return number The number of items on the list
- */
-size_t connectionList_Length(const ConnectionList *list);
-
-/**
- * @function connectionList_Get
- * @abstract Returns the connection entry.
- * @discussion
- * Caller must not destroy the returned value. If you will store the
- * entry in your own data structure, you should acquire your own reference.
- * Will assert if you go beyond the end of the list.
- *
- */
-Connection *connectionList_Get(ConnectionList *list, size_t index);
-#endif // connectionList_h
diff --git a/hicn-light/src/hicn/core/connectionManager.c b/hicn-light/src/hicn/core/connectionManager.c
deleted file mode 100644
index 709f0902a..000000000
--- a/hicn-light/src/hicn/core/connectionManager.c
+++ /dev/null
@@ -1,196 +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 Connection Manager sets itself up as a listener to the Messenger so it
- * can take action based on system events.
- *
- * The Connection Manager queues and then processes in a later time slice the
- * messages.
- *
- */
-
-#include <hicn/hicn-light/config.h>
-#include <hicn/core/connectionManager.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/messenger/messenger.h>
-#include <hicn/messenger/messengerRecipient.h>
-#include <hicn/messenger/missiveDeque.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_Memory.h>
-
-#include <parc/assert/parc_Assert.h>
-
-struct connection_manager {
- Forwarder *forwarder;
- Logger *logger;
-
- MessengerRecipient *messengerRecipient;
-
- // we queue missives as they come in to process in our own
- // event timeslice
- MissiveDeque *missiveQueue;
-
- // for deferred queue processing
- PARCEventTimer *timerEvent;
-};
-
-/**
- * Receives missives from the messenger, queues them, and schedules our
- * execution
- *
- * We defer processing of missives to a later time slice
- */
-static void connectionManager_MessengerCallback(MessengerRecipient *recipient,
- Missive *missive);
-
-/**
- * Event callback
- *
- * This is our main run loop to process our queue of messages. It is scheduled
- * in {@link connectionManager_MessengerCallback} when the queue becomes
- * non-empty.
- *
- * When we are called here, we have exclusive use of the system, so we will not
- * create any message loops
- *
- * @param [in] fd unused, required for compliance with function prototype
- * @param [in] which_event unused, required for compliance with function
- * prototype
- * @param [in] connManagerVoidPtr A void* to ConnectionManager
- *
- */
-static void connectionManager_ProcessQueue(int fd, PARCEventType which_event,
- void *connManagerVoidPtr);
-
-static void connectionManager_ProcessClosedMissive(
- ConnectionManager *connManager, const Missive *missive);
-
-// ========================================================
-// Public API
-
-ConnectionManager *connectionManager_Create(Forwarder *forwarder) {
- ConnectionManager *connManager =
- parcMemory_AllocateAndClear(sizeof(ConnectionManager));
- parcAssertNotNull(connManager,
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ConnectionManager));
- connManager->forwarder = forwarder;
- connManager->missiveQueue = missiveDeque_Create();
- connManager->logger = logger_Acquire(forwarder_GetLogger(forwarder));
-
- Messenger *messenger = forwarder_GetMessenger(connManager->forwarder);
-
- // creates the timer, but does not start it
- PARCEventScheduler *base =
- dispatcher_GetEventScheduler(forwarder_GetDispatcher(forwarder));
- connManager->timerEvent = parcEventTimer_Create(
- base, 0, connectionManager_ProcessQueue, connManager);
-
- connManager->messengerRecipient = messengerRecipient_Create(
- connManager, connectionManager_MessengerCallback);
- messenger_Register(messenger, connManager->messengerRecipient);
- return connManager;
-}
-
-void connectionManager_Destroy(ConnectionManager **managerPtr) {
- parcAssertNotNull(managerPtr, "Double pointer must be non-null");
- parcAssertNotNull(*managerPtr, "Double pointer must dereference to non-null");
-
- ConnectionManager *connManager = *managerPtr;
-
- Messenger *messenger = forwarder_GetMessenger(connManager->forwarder);
- parcEventTimer_Destroy(&(connManager->timerEvent));
- messenger_Unregister(messenger, connManager->messengerRecipient);
- messengerRecipient_Destroy(&connManager->messengerRecipient);
- missiveDeque_Release(&connManager->missiveQueue);
- logger_Release(&connManager->logger);
-
- parcMemory_Deallocate((void **)&connManager);
- *managerPtr = NULL;
-}
-
-// ========================================================
-// Internal Functions
-
-static void connectionManager_MessengerCallback(MessengerRecipient *recipient,
- Missive *missive) {
- ConnectionManager *connManager =
- messengerRecipient_GetRecipientContext(recipient);
-
- // we do not release our reference count, we store it until later
- // We are called with our own reference, so we do not need to acquire the
- // missive here.
- missiveDeque_Append(connManager->missiveQueue, missive);
-
- if (missiveDeque_Size(connManager->missiveQueue) == 1) {
- // When it becomes non-empty, schedule {@link
- // connectionManager_ProcessQueue}
- struct timeval immediateTimeout = {0, 0};
- parcEventTimer_Start(connManager->timerEvent, &immediateTimeout);
- }
-}
-
-static void connectionManager_ProcessQueue(int fd, PARCEventType which_event,
- void *connManagerVoidPtr) {
- ConnectionManager *connManager = (ConnectionManager *)connManagerVoidPtr;
-
- Missive *missive;
- while ((missive = missiveDeque_RemoveFirst(connManager->missiveQueue)) !=
- NULL) {
- switch (missive_GetType(missive)) {
- case MissiveType_ConnectionCreate:
- // hook to signal that a new connection was created
- break;
- case MissiveType_ConnectionUp:
- // hook to signal that a new connection is up
- break;
- case MissiveType_ConnectionDown:
- // hook to signal that a connection is down
- break;
- case MissiveType_ConnectionClosed:
- connectionManager_ProcessClosedMissive(connManager, missive);
- break;
- case MissiveType_ConnectionDestroyed:
- // hook to signal that a connection was destroyed
- break;
- default:
- parcTrapUnexpectedState("Missive %p of unknown type: %d",
- (void *)missive, missive_GetType(missive));
- }
- missive_Release(&missive);
- }
-}
-
-static void connectionManager_ProcessClosedMissive(
- ConnectionManager *connManager, const Missive *missive) {
- logger_Log(connManager->logger, LoggerFacility_Core, PARCLogLevel_Debug,
- __func__, "Processing CLOSED message for connid %u",
- missive_GetConnectionId(missive));
-
- ConnectionTable *table = forwarder_GetConnectionTable(connManager->forwarder);
- const Connection *conn =
- connectionTable_FindById(table, missive_GetConnectionId(missive));
-
- if (conn) {
- // this will destroy the connection if its the last reference count
- connectionTable_Remove(table, conn);
-
- // remove from FIB
- forwarder_RemoveConnectionIdFromRoutes(connManager->forwarder,
- missive_GetConnectionId(missive));
- }
-}
diff --git a/hicn-light/src/hicn/core/connectionManager.h b/hicn-light/src/hicn/core/connectionManager.h
deleted file mode 100644
index 34fee8717..000000000
--- a/hicn-light/src/hicn/core/connectionManager.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.
- */
-
-/**
- * @file connectionManager.h
- * @brief The connection manager handles connection events, such as going down
- *
- * The connection manager listens to the event notification system. Based on
- * those events, the connection manager will take specific actions. This is
- * expected to be a singleton instantiated by the forwarder.
- *
- */
-
-#ifndef connectionManager_h
-#define connectionManager_h
-
-#include <hicn/core/forwarder.h>
-
-struct connection_manager;
-typedef struct connection_manager ConnectionManager;
-
-ConnectionManager *connectionManager_Create(Forwarder *forwarder);
-
-void connectionManager_Destroy(ConnectionManager **managerPtr);
-#endif // connectionManager_h
diff --git a/hicn-light/src/hicn/core/connectionTable.c b/hicn-light/src/hicn/core/connectionTable.c
deleted file mode 100644
index f8589c12b..000000000
--- a/hicn-light/src/hicn/core/connectionTable.c
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @header ConnectionTable
- * @abstract Records all the current connections and references to them
- * @discussion
- *
- */
-
-#ifndef _WIN32
-#include <unistd.h>
-#endif
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_HashCodeTable.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_TreeRedBlack.h>
-#include <hicn/core/connectionTable.h>
-#include <hicn/io/addressPair.h>
-
-struct connection_table {
- // The main storage table that has a Destroy method.
- // The key is an unsigned int pointer. We use an unsigned int pointer
- // because we want to be able to lookup by the id alone, and not have to
- // have the IoOperations everywhere.
- PARCHashCodeTable *storageTableById;
-
- // The key is a AddressPair
- // It does not have a destroy method for the data or key,
- // as they are derived from the storage table.
- PARCHashCodeTable *indexByAddressPair;
-
- // An iterable stucture organized by connection id. The keys and
- // values are the same pointers as in storageTableById, so there
- // are no destructors in the tree.
- // The only reason to keep this tree is so we have an iterable list
- // of connections, which the hash table does not give us.
- PARCTreeRedBlack *listById;
-};
-
-static bool connectionTable_ConnectionIdEquals(const void *keyA,
- const void *keyB) {
- unsigned idA = *((unsigned *)keyA);
- unsigned idB = *((unsigned *)keyB);
- return (idA == idB);
-}
-
-static int connectionTable_ConnectionIdCompare(const void *keyA,
- const void *keyB) {
- unsigned idA = *((unsigned *)keyA);
- unsigned idB = *((unsigned *)keyB);
- if (idA < idB) {
- return -1;
- }
- if (idA > idB) {
- return +1;
- }
- return 0;
-}
-
-static bool connectionTable_AddressPairEquals(const void *keyA,
- const void *keyB) {
- const AddressPair *pairA = (const AddressPair *)keyA;
- const AddressPair *pairB = (const AddressPair *)keyB;
-
- return addressPair_Equals(pairA, pairB);
-}
-
-static HashCodeType connectionTable_ConnectionIdHashCode(const void *keyA) {
- unsigned idA = *((unsigned *)keyA);
- return parcHash32_Int32(idA);
-}
-
-static HashCodeType connectionTable_AddressPairHashCode(const void *keyA) {
- const AddressPair *pairA = (const AddressPair *)keyA;
- return addressPair_HashCode(pairA);
-}
-
-static void connectionTable_ConnectionIdDestroyer(void **dataPtr) {
- unsigned *idA = (unsigned *)*dataPtr;
- parcMemory_Deallocate((void **)&idA);
- *dataPtr = NULL;
-}
-
-static void connectionTable_ConnectionDestroyer(void **dataPtr) {
- connection_Release((Connection **)dataPtr);
-}
-
-ConnectionTable *connectionTable_Create() {
- size_t initialSize = 16384;
-
- ConnectionTable *conntable =
- parcMemory_AllocateAndClear(sizeof(ConnectionTable));
- parcAssertNotNull(conntable, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ConnectionTable));
-
- conntable->storageTableById = parcHashCodeTable_Create_Size(
- connectionTable_ConnectionIdEquals, connectionTable_ConnectionIdHashCode,
- connectionTable_ConnectionIdDestroyer,
- connectionTable_ConnectionDestroyer, initialSize);
-
- // no key or data destroyer, this is an index into storageByid.
- conntable->indexByAddressPair = parcHashCodeTable_Create_Size(
- connectionTable_AddressPairEquals, connectionTable_AddressPairHashCode,
- NULL, NULL, initialSize);
-
- conntable->listById =
- parcTreeRedBlack_Create(connectionTable_ConnectionIdCompare,
- NULL, // key free
- NULL, // key copy
- NULL, // value equals
- NULL, // value free
- NULL); // value copy
-
- return conntable;
-}
-
-void connectionTable_Destroy(ConnectionTable **conntablePtr) {
- parcAssertNotNull(conntablePtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*conntablePtr,
- "Parameter must dereference to non-null pointer");
-
- ConnectionTable *conntable = *conntablePtr;
-
- parcTreeRedBlack_Destroy(&conntable->listById);
- parcHashCodeTable_Destroy(&conntable->indexByAddressPair);
- parcHashCodeTable_Destroy(&conntable->storageTableById);
- parcMemory_Deallocate((void **)&conntable);
- *conntablePtr = NULL;
-}
-
-/**
- * @function connectionTable_Add
- * @abstract Add a connection, takes ownership of memory
- */
-void connectionTable_Add(ConnectionTable *table, Connection *connection) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- parcAssertNotNull(connection, "Parameter connection must be non-null");
-
- unsigned *connectionIdKey = parcMemory_Allocate(sizeof(unsigned));
- parcAssertNotNull(connectionIdKey, "parcMemory_Allocate(%zu) returned NULL",
- sizeof(unsigned));
- *connectionIdKey = connection_GetConnectionId(connection);
-
- if (parcHashCodeTable_Add(table->storageTableById, connectionIdKey,
- connection)) {
- parcHashCodeTable_Add(table->indexByAddressPair,
- (void *)connection_GetAddressPair(connection),
- connection);
- parcTreeRedBlack_Insert(table->listById, connectionIdKey, connection);
- } else {
- parcTrapUnexpectedState(
- "Could not add connection id %u -- is it a duplicate?",
- *connectionIdKey);
- }
-}
-
-/**
- * @function connectionTable_Remove
- * @abstract Removes the connection, calling Destroy on our copy
- */
-void connectionTable_Remove(ConnectionTable *table,
- const Connection *connection) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- parcAssertNotNull(connection, "Parameter connection must be non-null");
-
- unsigned connid = connection_GetConnectionId(connection);
-
- parcTreeRedBlack_Remove(table->listById, &connid);
- parcHashCodeTable_Del(table->indexByAddressPair,
- connection_GetAddressPair(connection));
- parcHashCodeTable_Del(table->storageTableById, &connid);
-}
-
-void connectionTable_RemoveById(ConnectionTable *table, unsigned id) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- const Connection *connection = connectionTable_FindById(table, id);
- if (connection) {
- connectionTable_Remove(table, connection);
- }
-}
-
-const Connection *connectionTable_FindByAddressPair(ConnectionTable *table,
- const AddressPair *pair) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- return (Connection *)parcHashCodeTable_Get(table->indexByAddressPair, pair);
-}
-
-const Connection *connectionTable_FindById(const ConnectionTable *table,
- unsigned id) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- return (Connection *)parcHashCodeTable_Get(table->storageTableById, &id);
-}
-
-ConnectionList *connectionTable_GetEntries(const ConnectionTable *table) {
- parcAssertNotNull(table, "Parameter table must be non-null");
- ConnectionList *list = connectionList_Create();
-
- PARCArrayList *values = parcTreeRedBlack_Values(table->listById);
- for (size_t i = 0; i < parcArrayList_Size(values); i++) {
- Connection *original = parcArrayList_Get(values, i);
- connectionList_Append(list, original);
- }
- parcArrayList_Destroy(&values);
- return list;
-}
diff --git a/hicn-light/src/hicn/core/connectionTable.h b/hicn-light/src/hicn/core/connectionTable.h
deleted file mode 100644
index 548ef8e6e..000000000
--- a/hicn-light/src/hicn/core/connectionTable.h
+++ /dev/null
@@ -1,99 +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.
- */
-
-/**
- */
-
-#ifndef connectionTable_h
-#define connectionTable_h
-
-#include <hicn/core/connection.h>
-#include <hicn/core/connectionList.h>
-#include <hicn/io/addressPair.h>
-#include <hicn/io/ioOperations.h>
-
-struct connection_table;
-typedef struct connection_table ConnectionTable;
-
-/**
- * Creates an empty connection table
- */
-ConnectionTable *connectionTable_Create(void);
-
-/**
- * Destroys the connection table
- * This will release the reference to all connections stored in the connection
- * table.
- * @param [in,out] conntablePtr Pointer to the allocated connection table, will
- * be NULL'd
- */
-void connectionTable_Destroy(ConnectionTable **conntablePtr);
-
-/**
- * @function connectionTable_Add
- * @abstract Add a connection, takes ownership of memory
- */
-void connectionTable_Add(ConnectionTable *table, Connection *connection);
-
-/**
- * @function connectionTable_Remove
- * @abstract Removes the connection, calling Destroy on our copy
- */
-void connectionTable_Remove(ConnectionTable *table,
- const Connection *connection);
-
-/**
- * Removes a connection from the connection table
- *
- * Looks up a connection by its connection ID and removes it from the connection
- * table. Removing the connection will call connection_Release() on the
- * connection object.
- *
- * @param [in] table The allocated connection table
- * @param [in] id The connection ID
- */
-void connectionTable_RemoveById(ConnectionTable *table, unsigned id);
-
-/**
- * Lookup a connection by the (local, remote) addres pair
- *
- * @param [in] table The allocated connection table
- * @param [in] pair The address pair to match, based on the inner values of the
- * local and remote addresses
- *
- * @retval non-null The matched conneciton
- * @retval null No match found or error
- */
-const Connection *connectionTable_FindByAddressPair(ConnectionTable *table,
- const AddressPair *pair);
-
-/**
- * @function connectionTable_FindById
- * @abstract Find a connection by its numeric id.
- * @return NULL if not found
- */
-const Connection *connectionTable_FindById(const ConnectionTable *table, unsigned id);
-
-/**
- * @function connectionTable_GetEntries
- * @abstract Returns a list of connections. They are reference counted copies
- * from the table.
- * @discussion
- * An allocated list of connections in the table. Each list entry is a
- * reference counted copy of the connection in the table, thus they are "live"
- * objects.
- */
-ConnectionList *connectionTable_GetEntries(const ConnectionTable *table);
-#endif // connectionTable_h
diff --git a/hicn-light/src/hicn/core/connection_table.c b/hicn-light/src/hicn/core/connection_table.c
new file mode 100644
index 000000000..a6b114c01
--- /dev/null
+++ b/hicn-light/src/hicn/core/connection_table.c
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file connection_table.c
+ * \brief Implementation of hICN connection table
+ */
+
+#include <hicn/util/log.h>
+#include <hicn/util/sstrncpy.h>
+
+#include "connection.h"
+#include "connection_table.h"
+
+/* This is only used as a hint for first allocation, as the table is resizeable
+ */
+#define DEFAULT_CONNECTION_TABLE_SIZE 64
+
+typedef struct {
+ char name[SYMBOLIC_NAME_LEN];
+} name_key_t;
+
+connection_table_t *_connection_table_create(size_t init_size,
+ size_t max_size) {
+ if (init_size == 0) init_size = DEFAULT_CONNECTION_TABLE_SIZE;
+
+ connection_table_t *table = malloc(sizeof(connection_table_t));
+ if (!table) return NULL;
+
+ table->max_size = max_size;
+
+ /* Initialize indices */
+ table->id_by_pair = kh_init_ct_pair();
+ table->pair_keys = slab_create(address_pair_t, SLAB_INIT_SIZE);
+ table->id_by_name = kh_init_ct_name();
+ table->name_keys = slab_create(name_key_t, SLAB_INIT_SIZE);
+
+ /*
+ * We start by allocating a reasonably-sized pool, as this will eventually
+ * be resized if needed.
+ */
+ pool_init(table->connections, init_size, 0);
+
+ return table;
+}
+
+void connection_table_free(connection_table_t *table) {
+ unsigned conn_id;
+ kh_foreach_value(table->id_by_name, conn_id, {
+ connection_t *connection = connection_table_get_by_id(table, conn_id);
+ const char *name = connection_get_name(connection);
+
+ INFO("Removing connection %s [%d]", name, connection->fd);
+ connection_finalize(connection);
+ });
+
+ kh_destroy_ct_pair(table->id_by_pair);
+ slab_free(table->pair_keys);
+ kh_destroy_ct_name(table->id_by_name);
+ slab_free(table->name_keys);
+
+ pool_free(table->connections);
+ free(table);
+}
+
+connection_t *connection_table_allocate(const connection_table_t *table,
+ const address_pair_t *pair,
+ const char *name) {
+ connection_t *conn = NULL;
+ pool_get(table->connections, conn);
+ if (!conn) return NULL;
+
+#ifdef __APPLE__
+ // set __uint8_t sin_len to 0
+ uint8_t *ptr = (uint8_t *)address_pair_get_local(pair);
+ *ptr = 0x0;
+ ptr = (uint8_t *)address_pair_get_remote(pair);
+ *ptr = 0x0;
+#endif /* __APPLE__ */
+
+ off_t id = conn - table->connections;
+ int rc;
+
+ // Add in name hash table
+ name_key_t *name_copy = slab_get(name_key_t, table->name_keys);
+ strcpy_s(name_copy->name, sizeof(name_key_t), name);
+
+ khiter_t k = kh_put_ct_name(table->id_by_name, name_copy->name, &rc);
+ assert(rc == KH_ADDED || rc == KH_RESET);
+ kh_value(table->id_by_name, k) = (unsigned int)id;
+
+ // Add in pair hash table
+ address_pair_t *pair_copy = slab_get(address_pair_t, table->pair_keys);
+ memcpy(pair_copy, pair, sizeof(address_pair_t));
+
+ k = kh_put_ct_pair(table->id_by_pair, pair_copy, &rc);
+ assert(rc == KH_ADDED || rc == KH_RESET);
+ kh_value(table->id_by_pair, k) = (unsigned int)id;
+
+ assert(kh_size(table->id_by_name) == kh_size(table->id_by_pair));
+ return conn;
+}
+
+void connection_table_deallocate(const connection_table_t *table,
+ const connection_t *conn) {
+ const char *name = connection_get_name(conn);
+ const address_pair_t *pair = connection_get_pair(conn);
+
+#ifdef __APPLE__
+ // set __uint8_t sin_len to 0
+ uint8_t *ptr = (uint8_t *)address_pair_get_local(pair);
+ *ptr = 0x0;
+ ptr = (uint8_t *)address_pair_get_remote(pair);
+ *ptr = 0x0;
+#endif /* __APPLE__ */
+
+ // Remove from name hash table
+ khiter_t k = kh_get_ct_name(table->id_by_name, name);
+ assert(k != kh_end(table->id_by_name));
+ kh_del_ct_name(table->id_by_name, k);
+ slab_put(table->name_keys, kh_key(table->id_by_name, k));
+
+ // Remove from pair hash table
+ k = kh_get_ct_pair(table->id_by_pair, pair);
+ assert(k != kh_end(table->id_by_pair));
+ kh_del_ct_pair(table->id_by_pair, k);
+ slab_put(table->pair_keys, kh_key(table->id_by_pair, k));
+
+ assert(kh_size(table->id_by_name) == kh_size(table->id_by_pair));
+ pool_put(table->connections, conn);
+}
+
+connection_t *connection_table_get_by_pair(const connection_table_t *table,
+ const address_pair_t *pair) {
+#ifdef __APPLE__
+ // set __uint8_t sin_len to 0
+ uint8_t *ptr = (uint8_t *)address_pair_get_local(pair);
+ *ptr = 0x0;
+ ptr = (uint8_t *)address_pair_get_remote(pair);
+ *ptr = 0x0;
+#endif /* __APPLE__ */
+
+ khiter_t k = kh_get_ct_pair(table->id_by_pair, pair);
+ if (k == kh_end(table->id_by_pair)) return NULL;
+ return table->connections + kh_val(table->id_by_pair, k);
+}
+
+off_t connection_table_get_id_by_name(const connection_table_t *table,
+ const char *name) {
+ khiter_t k = kh_get_ct_name(table->id_by_name, name);
+ if (k == kh_end(table->id_by_name)) return CONNECTION_ID_UNDEFINED;
+ return kh_val(table->id_by_name, k);
+}
+
+connection_t *connection_table_get_by_name(const connection_table_t *table,
+ const char *name) {
+ unsigned conn_id = (unsigned int)connection_table_get_id_by_name(table, name);
+ if (!connection_id_is_valid(conn_id)) return NULL;
+ return connection_table_at(table, conn_id);
+}
+
+void connection_table_remove_by_id(connection_table_t *table, off_t id) {
+ connection_t *connection = connection_table_at(table, id);
+ INFO("Removing connection %d (%s)", id, connection_get_name(connection));
+
+ connection_table_deallocate(table, connection);
+}
+
+void connection_table_print_by_pair(const connection_table_t *table) {
+ const address_pair_t *k;
+ unsigned v;
+
+ char local_addr_str[NI_MAXHOST], remote_addr_str[NI_MAXHOST];
+ int local_port, remote_port;
+ connection_t *connection;
+ const char *name;
+
+ INFO("*** Connection table ***");
+ kh_foreach(table->id_by_pair, k, v, {
+ address_to_string(&(k->local), local_addr_str, &local_port);
+ address_to_string(&(k->remote), remote_addr_str, &remote_port);
+ connection = connection_table_get_by_id(table, v);
+ name = connection_get_name(connection);
+ INFO("(%s:%d - %s:%d)\t\t\t(%u, %s)", local_addr_str, local_port,
+ remote_addr_str, remote_port, v, name);
+ })
+}
+
+void connection_table_print_by_name(const connection_table_t *table) {
+ const char *k;
+ unsigned v;
+
+ connection_t *connection;
+ const char *name;
+
+ INFO("*** Connection table ***");
+ kh_foreach(table->id_by_name, k, v, {
+ connection = connection_table_get_by_id(table, v);
+ name = connection_get_name(connection);
+ INFO("(%s)\t\t\t(%u, %s)", k, v, name);
+ })
+}
+
+connection_t *_connection_table_get_by_id(connection_table_t *table, off_t id) {
+ return connection_table_get_by_id(table, id);
+}
+
+static inline u16 RAND16() { return rand() & 0xFFFF; }
+
+int connection_table_get_random_name(const connection_table_t *table,
+ char *name) {
+ int i, n_attempts = 2 * USHRT_MAX;
+ for (i = 0; i < n_attempts; i++) {
+ int rc = snprintf(name, SYMBOLIC_NAME_LEN, "conn%u", RAND16());
+ if (rc < 0 || rc >= SYMBOLIC_NAME_LEN) continue;
+
+ // Check if generated connection name is a duplicate
+ khiter_t k = kh_get_ct_name(table->id_by_name, name);
+ if (k == kh_end(table->id_by_name)) break;
+ }
+
+ if (i == n_attempts) {
+ ERROR("Unable to generate new unique connection name");
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/hicn-light/src/hicn/core/connection_table.h b/hicn-light/src/hicn/core/connection_table.h
new file mode 100644
index 000000000..dcfb1e1dd
--- /dev/null
+++ b/hicn-light/src/hicn/core/connection_table.h
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file connection_table.h
+ * \brief hICN connection_table
+ *
+ * The connection table is composed of :
+ * - a pool of connections allowing access through their id in constant time;
+ * - a set of indices in the form of hash table for efficient index lookups:
+ * . by name
+ * . by address pair
+ *
+ * For efficient index retrieval, the header will be prepended and the
+ * resulting pointer will directly point to the connection pool.
+ */
+
+#ifndef HICNLIGHT_CONNECTION_TABLE_H
+#define HICNLIGHT_CONNECTION_TABLE_H
+
+#include <hicn/util/khash.h>
+#include <hicn/util/hash.h>
+#include <hicn/util/slab.h>
+#include "address_pair.h"
+#include "connection.h"
+#include <hicn/util/pool.h>
+
+/* Hash functions for indices. */
+#define address_pair_hash(pair) (hash_struct(pair))
+
+/* Hash table types for indices. */
+KHASH_INIT(ct_pair, const address_pair_t *, unsigned, 1, address_pair_hash,
+ address_pair_equals);
+KHASH_MAP_INIT_STR(ct_name, unsigned);
+
+typedef struct {
+ size_t max_size;
+
+ kh_ct_pair_t *id_by_pair;
+ slab_t *pair_keys;
+ kh_ct_name_t *id_by_name;
+ slab_t *name_keys;
+
+ connection_t *connections; // pool
+} connection_table_t;
+
+/**
+ * @brief Allocate a connection from the connection table.
+ *
+ * @param[in] table The connection table from which to allocate a connection.
+ * @param[out] connection The pointer that will hold the allocated connection.
+ * @param[in] pair The address pair associated to the connection (to update
+ * index).
+ * @param[in] name The name associated to the connection (to update index).
+ *
+ * NOTE:
+ * - This function updates all indices from the connection table if the
+ * allocation is successful.
+ * - You should always check that the returned connection is not NULL, which
+ * would signal that the pool is exhausted and could not be extended.
+ */
+connection_t *connection_table_allocate(const connection_table_t *table,
+ const address_pair_t *pair,
+ const char *name);
+/**
+ * @brief Deallocate a connection and return it to the connection table pool.
+ *
+ * @param[in] table The connection table to which the connection is returned.
+ * @param[in] conn The connection that is returned to the pool.
+ *
+ * NOTE:
+ * - Upon returning a connection to the pool, all indices pointing to that
+ * connection are also cleared.
+ */
+void connection_table_deallocate(const connection_table_t *table,
+ const connection_t *conn);
+
+/**
+ * @brief Returns the length of the connection table, the number of active
+ * connections.
+ *
+ * @param[in] table The connection table for which we retrieve the length.
+ *
+ * @return size_t The length of the connection table.
+ *
+ * NOTE:
+ * - The length of the connection table, that is the number of currently active
+ * connections.
+ */
+#define connection_table_len(table) (pool_len(table->connections))
+
+/**
+ * @brief Validate an index in the connection table.
+ *
+ * @param[in] table The connection table in which to validate an index.
+ * @param[in] id The index of the connection to validate.
+ *
+ * @return bool A flag indicating whether the connection index is valid or not.
+ */
+#define connection_table_validate_id(table, id) \
+ pool_validate_id((table)->connections, (id))
+
+/**
+ * @brief Return the connection corresponding to the specified index in the
+ * connection table.
+ *
+ * @param[in] table The connection table for which to retrieve the connection.
+ * @param[in] id The index for which to retrieve the connection.
+ *
+ * @return connection_t * The connection correponding to the specified index in
+ * the connection table.
+ *
+ * @see connection_table_get_by_id
+ *
+ * NOTE:
+ * - In this function, the index is not validated.
+ */
+#define connection_table_at(table, id) ((table)->connections + id)
+
+/**
+ * @brief Return the connection corresponding to the specified and validated
+ * index in the connection table.
+ *
+ * @param[in] table The connection table for which to retrieve the connection.
+ * @param[in] id The index for which to retrieve the connection.
+ *
+ * @return connection_t * The connection correponding to the specified index in
+ * the connection table.
+ *
+ * @see connection_table_get_by_id
+ *
+ * NOTE:
+ * - In this function, the index is validated.
+ */
+#define connection_table_get_by_id(table, id) \
+ connection_table_validate_id(table, id) ? connection_table_at(table, id) \
+ : NULL
+
+/**
+ * @brief Helper function to avoid macro expansion in c++ tests. Wrapper around
+ * 'connection_table_get_by_id'.
+ */
+connection_t *_connection_table_get_by_id(connection_table_t *table, off_t id);
+
+/**
+ * @brief Returns the index of a given connection in the connection table.
+ *
+ * @param[in] table The connection table from which to retrieve the index.
+ * @param[in] conn The connection for which to retrieve the index.
+ *
+ * @return off_t The index of the specified connection in the connection table.
+ */
+#define connection_table_get_connection_id(table, conn) \
+ (unsigned)(conn - table->connections)
+
+#define connection_table_foreach(table, conn, BODY) \
+ pool_foreach(table->connections, (conn), BODY)
+
+#define connection_table_foreach_new(table, CONN, BODY) \
+ pool_foreach_typed(table->connections, connection_t *, CONN, BODY)
+
+#define connection_table_enumerate(table, i, conn, BODY) \
+ pool_enumerate(table->connections, (i), (conn), BODY)
+
+/**
+ * @brief Create a new connection table (extended parameters).
+ *
+ * @param[in] init_size Initially allocated size (hint, 0 = use default value).
+ * @param[in] max_size Maximum size (0 = unlimited).
+ *
+ * @return connection_table_t* The newly created connection table.
+ */
+connection_table_t *_connection_table_create(size_t init_size, size_t max_size);
+
+/**
+ * @brief Create a new connection table (minimal parameters).
+ *
+ * @return connection_table_t* The newly created connection table.
+ */
+#define connection_table_create() _connection_table_create(0, 0)
+
+/**
+ * @brief Free a connection table
+ *
+ * @param[in] table Connection table to free
+ */
+void connection_table_free(connection_table_t *table);
+
+/**
+ * @brief Retrieve a connection from the connection table by address pair.
+ *
+ * @param[in] table The connection table in which to search.
+ * @param[in] pair The address pair to search for.
+ *
+ * @return connection_t * The connection matching the specified address pair, or
+ * NULL if not found.
+ */
+connection_t *connection_table_get_by_pair(const connection_table_t *table,
+ const address_pair_t *pair);
+
+/**
+ * @brief Return a connection index from the connection table by name.
+ *
+ * @param[in] table The connection table in which to search.
+ * @param[in] name The name to search for.
+ *
+ * @return off_t The index of the connection matching the name, or
+ * CONNECTION_ID_UNDEFINED if not found.
+ */
+off_t connection_table_get_id_by_name(const connection_table_t *table,
+ const char *name);
+
+/**
+ * @brief Return a connection from the connection table by name.
+ *
+ * @param[in] table The connection table in which to search.
+ * @param[in] name The name to search for.
+ *
+ * @return connection_t * The connection matching the name, or NULL if not
+ * found.
+ */
+connection_t *connection_table_get_by_name(const connection_table_t *table,
+ const char *name);
+
+/**
+ * @brief Remove a connection from the connection table by its index.
+ *
+ * @param[in] table The connection table from which to delete the connection.
+ * @param[in] id The index of the connection to remove.
+ */
+void connection_table_remove_by_id(connection_table_t *table, off_t id);
+
+/**
+ * @brief Print the connection table content.
+ *
+ * @param[in] table The connection table to print.
+ */
+void connection_table_print_by_pair(const connection_table_t *table);
+
+void connection_table_print_by_name(const connection_table_t *table);
+
+int connection_table_get_random_name(const connection_table_t *table,
+ char *name);
+
+#endif /* HICNLIGHT_CONNECTION_TABLE_H */
diff --git a/libtransport/includes/hicn/transport/utils/move_wrapper.h b/hicn-light/src/hicn/core/connection_vft.c
index 5dc3b461d..fe97096d3 100644
--- a/libtransport/includes/hicn/transport/utils/move_wrapper.h
+++ b/hicn-light/src/hicn/core/connection_vft.c
@@ -1,6 +1,5 @@
/*
* Copyright (c) 2021 Cisco and/or its affiliates.
- *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,25 +13,25 @@
* limitations under the License.
*/
-#pragma once
+/**
+ * @file connection_vft.c
+ * @brief Implementation of connection VFT
+ */
-#include <type_traits>
+#include "connection_vft.h"
-namespace utils {
+#ifdef __linux
+extern connection_ops_t connection_hicn;
+#endif
-template <typename F>
-struct MoveWrapper : F {
- MoveWrapper(F&& f) : F(std::move(f)) {}
+extern connection_ops_t connection_tcp;
+extern connection_ops_t connection_udp;
- MoveWrapper(MoveWrapper&&) = default;
- MoveWrapper& operator=(MoveWrapper&&) = default;
+const connection_ops_t *connection_vft[] = {
+#ifdef __linux
+ [FACE_PROTOCOL_HICN] = &connection_hicn,
+#endif
- MoveWrapper(const MoveWrapper&);
- MoveWrapper& operator=(const MoveWrapper&);
+ [FACE_PROTOCOL_TCP] = &connection_tcp,
+ [FACE_PROTOCOL_UDP] = &connection_udp,
};
-
-template <typename T>
-auto moveHandler(T&& t) -> MoveWrapper<typename std::decay<T>::type> {
- return std::move(t);
-}
-} // namespace utils \ No newline at end of file
diff --git a/hicn-light/src/hicn/core/connection_vft.h b/hicn-light/src/hicn/core/connection_vft.h
new file mode 100644
index 000000000..cc736905c
--- /dev/null
+++ b/hicn-light/src/hicn/core/connection_vft.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file connection_vft.h
+ * @brief Connection VFT
+ */
+
+#ifndef HICNLIGHT_CONNECTION_VFT_H
+#define HICNLIGHT_CONNECTION_VFT_H
+
+#include "connection.h"
+
+typedef struct {
+ int (*initialize)(connection_t* connection);
+ void (*finalize)(connection_t* connection);
+ int (*get_socket)(const listener_t* listener, const address_t* local,
+ const address_t* remote, const char* interface_name);
+ bool (*flush)(connection_t* connection);
+ bool (*send)(connection_t* connection, msgbuf_t* msgbuf, bool queue);
+ bool (*send_packet)(const connection_t* connection, const uint8_t* packet,
+ size_t size);
+ // void (*read_callback)(connection_t * connection, int fd, void * data);
+ size_t data_size;
+} connection_ops_t;
+
+#define DECLARE_CONNECTION(NAME) \
+ const connection_ops_t connection_##NAME = { \
+ .initialize = connection_##NAME##_initialize, \
+ .finalize = connection_##NAME##_finalize, \
+ .get_socket = listener_##NAME##_get_socket, \
+ .flush = connection_##NAME##_flush, \
+ .send = connection_##NAME##_send, \
+ .send_packet = connection_##NAME##_send_packet, \
+ .data_size = sizeof(connection_##NAME##_data_t), \
+ };
+
+// .read_callback = connection_ ## NAME ## _read_callback,
+
+extern const connection_ops_t* connection_vft[];
+
+#endif /* HICNLIGHT_CONNECTION_VFT_H */
diff --git a/hicn-light/src/hicn/core/content_store.c b/hicn-light/src/hicn/core/content_store.c
new file mode 100644
index 000000000..360e6d333
--- /dev/null
+++ b/hicn-light/src/hicn/core/content_store.c
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file content_store.c
+ * \brief Implementation of hICN content_store
+ */
+
+#include "content_store.h"
+#include "packet_cache.h"
+
+extern const cs_ops_t cs_lru;
+
+const cs_ops_t *const cs_vft[] = {
+ [CS_TYPE_LRU] = &cs_lru,
+};
+
+cs_t *_cs_create(cs_type_t type, size_t max_size) {
+ if (!CS_TYPE_VALID(type)) {
+ ERROR("[cs_create] Invalid content store type");
+ return NULL;
+ }
+
+ if (max_size == 0) max_size = DEFAULT_CS_SIZE;
+
+ cs_t *cs = malloc(sizeof(cs_t));
+ if (!cs) return NULL;
+
+ cs->type = type;
+ cs->num_entries = 0;
+ cs->max_size = max_size;
+ cs_vft[type]->initialize(cs);
+ cs->stats.lru = (cs_lru_stats_t){0};
+
+ return cs;
+}
+
+void cs_free(cs_t *cs) {
+ assert(cs);
+
+ cs_vft[cs->type]->finalize(cs);
+ free(cs);
+}
+
+void _cs_clear(cs_t **cs_ptr) {
+ cs_type_t cs_type = (*cs_ptr)->type;
+ size_t max_size = (*cs_ptr)->max_size;
+
+ // Free and recreate the CS
+ cs_free(*cs_ptr);
+ *cs_ptr = _cs_create(cs_type, max_size);
+}
+
+void cs_hit(cs_t *cs) {
+ cs->stats.lru.countHits++;
+ TRACE("ContentStore hit (hits %u, misses %u)", cs->stats.lru.countHits,
+ cs->stats.lru.countMisses);
+}
+
+void cs_miss(cs_t *cs) {
+ cs->stats.lru.countMisses++;
+ TRACE("ContentStore miss (hits %u, misses %u)", cs->stats.lru.countHits,
+ cs->stats.lru.countMisses);
+}
+
+void cs_log(cs_t *cs) {
+ DEBUG(
+ "Content store: size = %u, capacity = %u, hits = %u, misses = %u, adds = "
+ "%u, updates = %u, deletions = %u (with evictions = %u)",
+ cs->num_entries, cs->max_size, cs->stats.lru.countHits,
+ cs->stats.lru.countMisses, cs->stats.lru.countAdds,
+ cs->stats.lru.countUpdates, cs->stats.lru.countLruDeletions,
+ cs->stats.lru.countLruEvictions);
+}
+
+cs_lru_stats_t cs_get_lru_stats(cs_t *cs) { return cs->stats.lru; }
diff --git a/hicn-light/src/hicn/core/content_store.h b/hicn-light/src/hicn/core/content_store.h
new file mode 100644
index 000000000..ceaf05e6b
--- /dev/null
+++ b/hicn-light/src/hicn/core/content_store.h
@@ -0,0 +1,108 @@
+#ifndef HICNLIGHT_CS_H
+#define HICNLIGHT_CS_H
+
+#include <hicn/util/pool.h>
+#include "../content_store/lru.h"
+#include "msgbuf_pool.h"
+
+#define INVALID_ENTRY_ID ~0ul /* off_t */
+#define DEFAULT_CS_SIZE 256 // Fixed CS size
+
+typedef struct {
+ off_t msgbuf_id;
+ struct {
+ off_t prev;
+ off_t next;
+ } lru;
+} cs_entry_t;
+
+#define cs_entry_get_msgbuf_id(entry) ((entry)->msgbuf_id)
+
+typedef enum {
+ CS_TYPE_UNDEFINED,
+ CS_TYPE_LRU,
+ CS_TYPE_N,
+} cs_type_t;
+
+#define CS_TYPE_VALID(type) (type != CS_TYPE_UNDEFINED) && (type != CS_TYPE_N)
+
+typedef struct {
+ /* The maximum allowed expiry time (will never be exceeded). */
+ uint64_t max_expiry_time; // XXX part of lru ?
+} cs_options_t;
+
+typedef struct {
+ cs_type_t type;
+ int num_entries;
+ size_t max_size;
+ cs_lru_state_t lru;
+ union {
+ cs_lru_stats_t lru;
+ } stats;
+} cs_t;
+
+/**
+ * @brief Create a new content store (extended parameters).
+ *
+ * @param[in] type Content store type
+ * @param[in] max_size Maximum size (0 = use default value)
+ *
+ * @return cs_t* - The newly created content store
+ */
+cs_t *_cs_create(cs_type_t type, size_t max_size);
+
+/**
+ * @brief Create a new content store
+ *
+ * @param[in] size Maximum content store size
+ *
+ * @return cs_t* - The newly created content store
+ */
+#define cs_create(size) _cs_create(CS_TYPE_LRU, (size))
+
+/**
+ * @brief Free a content store data structure.
+ *
+ * @param[in] pool_ptr Pointer to the content store to free
+ */
+void cs_free(cs_t *cs);
+
+/**
+ * @brief Clear the content of the content store (helper).
+ *
+ * @param[in, out] cs Pointer to the content store to clear
+ */
+void _cs_clear(cs_t **cs);
+
+/**
+ * @brief Clear the content of the content store.
+ *
+ * @param[in, out] cs Pointer to the content store to clear
+ */
+#define cs_clear(cs) _cs_clear((cs_t **)&cs);
+
+/**
+ * @brief Update content store statistics upon CS hit event.
+ *
+ * @param[in] cs Pointer to the content store to use
+ */
+void cs_hit(cs_t *cs);
+
+/**
+ * @brief Update content store statistics upon CS miss event.
+ *
+ * @param[in] cs Pointer to the content store to use
+ */
+void cs_miss(cs_t *cs);
+
+/**
+ * @brief Log content store statistics, e.g. the CS current and maximum size,
+ * the number of matches, misses, add operations, update operations, evictions.
+ *
+ * @param cs Pointer to the CS data structure to use
+ */
+void cs_log(cs_t *cs);
+
+cs_lru_stats_t cs_get_lru_stats(cs_t *cs);
+
+#endif /* HICNLIGHT_CS_H */
diff --git a/hicn-light/src/hicn/core/dispatcher.c b/hicn-light/src/hicn/core/dispatcher.c
deleted file mode 100644
index 59951e950..000000000
--- a/hicn-light/src/hicn/core/dispatcher.c
+++ /dev/null
@@ -1,474 +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.
- */
-
-/**
- * @header dispatcher.c
- * @abstract Event dispatcher for hicn-light. Uses parcEvent
- * @discussion
- * Wraps the functions we use in parcEvent, along with StreamBuffer and
- * Message. The dispatcher is the event loop, so it manages things like signals,
- * timers, and network events.
- */
-
-#ifndef _WIN32
-#include <arpa/inet.h>
-#include <sys/socket.h>
-#include <unistd.h>
-#endif
-#include <errno.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <hicn/hicn-light/config.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#include <parc/algol/parc_EventQueue.h>
-#include <parc/algol/parc_EventTimer.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/core/dispatcher.h>
-
-#include <pthread.h>
-
-#ifndef INPORT_ANY
-#define INPORT_ANY 0
-#endif
-
-struct dispatcher {
- PARCEventScheduler *Base;
- Logger *logger;
-};
-
-// ==========================================
-// Public API
-
-PARCEventScheduler *dispatcher_GetEventScheduler(Dispatcher *dispatcher) {
- return dispatcher->Base;
-}
-
-Dispatcher *dispatcher_Create(Logger *logger) {
- Dispatcher *dispatcher = parcMemory_AllocateAndClear(sizeof(Dispatcher));
- parcAssertNotNull(dispatcher,
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Dispatcher));
-
- dispatcher->Base = parcEventScheduler_Create();
- dispatcher->logger = logger_Acquire(logger);
-
- parcAssertNotNull(dispatcher->Base,
- "Got NULL from parcEventScheduler_Create()");
-
- return dispatcher;
-}
-
-void dispatcher_Destroy(Dispatcher **dispatcherPtr) {
- parcAssertNotNull(dispatcherPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*dispatcherPtr,
- "Parameter must dereference to non-null pointer");
- Dispatcher *dispatcher = *dispatcherPtr;
-
- logger_Release(&dispatcher->logger);
- parcEventScheduler_Destroy(&(dispatcher->Base));
- parcMemory_Deallocate((void **)&dispatcher);
- *dispatcherPtr = NULL;
-}
-
-void dispatcher_Stop(Dispatcher *dispatcher) {
- struct timeval delay = {0, 1000};
-
- parcEventScheduler_Stop(dispatcher->Base, &delay);
-}
-
-void dispatcher_Run(Dispatcher *dispatcher) {
- parcAssertNotNull(dispatcher, "Parameter must be non-null");
-
- parcEventScheduler_Start(dispatcher->Base, 0);
-}
-
-void dispatcher_RunDuration(Dispatcher *dispatcher, struct timeval *duration) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(duration, "Parameter duration must be non-null");
-
- parcEventScheduler_Stop(dispatcher->Base, duration);
- parcEventScheduler_Start(dispatcher->Base, 0);
-}
-
-void dispatcher_RunCount(Dispatcher *dispatcher, unsigned count) {
- parcAssertNotNull(dispatcher, "Parameter must be non-null");
-
- for (unsigned i = 0; i < count; i++) {
- parcEventScheduler_Start(dispatcher->Base,
- PARCEventSchedulerDispatchType_LoopOnce);
- }
-}
-
-PARCEventSocket *dispatcher_CreateListener(Dispatcher *dispatcher,
- PARCEventSocket_Callback *callback,
- void *user_data, int backlog,
- const struct sockaddr *sa,
- int socklen) {
- PARCEventSocket *listener = parcEventSocket_Create(
- dispatcher->Base, callback, NULL, user_data, sa, socklen);
- if (listener == NULL) {
- perror("Problem creating listener");
- }
- return listener;
-}
-
-void dispatcher_DestroyListener(Dispatcher *dispatcher,
- PARCEventSocket **listenerPtr) {
- parcAssertNotNull(listenerPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*listenerPtr,
- "Parameter must dereference to non-null pointer");
- parcEventSocket_Destroy(listenerPtr);
-}
-
-PARCEventQueue *dispatcher_CreateStreamBufferFromSocket(Dispatcher *dispatcher,
- SocketType fd) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- PARCEventQueue *buffer = parcEventQueue_Create(
- dispatcher->Base, fd,
- PARCEventQueueOption_CloseOnFree | PARCEventQueueOption_DeferCallbacks);
- parcAssertNotNull(buffer,
- "Got null from parcEventBufver_Create for socket %d", fd);
- return buffer;
-}
-
-PARCEventTimer *dispatcher_CreateTimer(Dispatcher *dispatcher, bool isPeriodic,
- PARCEvent_Callback *callback,
- void *userData) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(callback, "Parameter callback must be non-null");
-
- PARCEventType flags = 0;
- if (isPeriodic) {
- flags |= PARCEventType_Persist;
- }
- PARCEventTimer *event =
- parcEventTimer_Create(dispatcher->Base, flags, callback, userData);
- return event;
-}
-
-void dispatcher_StartTimer(Dispatcher *dispatcher, PARCEventTimer *timerEvent,
- struct timeval *delay) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(timerEvent, "Parameter timerEvent must be non-null");
- int failure = parcEventTimer_Start(timerEvent, delay);
- parcAssertFalse(failure < 0, "Error starting timer event %p: (%d) %s",
- (void *)timerEvent, errno, strerror(errno));
-}
-
-void dispatcher_StopTimer(Dispatcher *dispatcher, PARCEventTimer *event) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(event, "Parameter event must be non-null");
-
- int failure = parcEventTimer_Stop(event);
- parcAssertFalse(failure < 0, "Error stopping signal event %p: (%d) %s",
- (void *)event, errno, strerror(errno));
-}
-
-void dispatcher_DestroyTimerEvent(Dispatcher *dispatcher,
- PARCEventTimer **eventPtr) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(eventPtr,
- "Parameter eventPtr must be non-null double pointer");
- parcAssertNotNull(*eventPtr,
- "Paramter eventPtr must dereference to non-null pointer");
-
- parcEventTimer_Destroy(eventPtr);
- eventPtr = NULL;
-}
-
-PARCEvent *dispatcher_CreateNetworkEvent(Dispatcher *dispatcher,
- bool isPersistent,
- PARCEvent_Callback *callback,
- void *userData, int fd) {
- short flags = PARCEventType_Timeout | PARCEventType_Read;
- if (isPersistent) {
- flags |= PARCEventType_Persist;
- }
-
- PARCEvent *event =
- parcEvent_Create(dispatcher->Base, fd, flags, callback, userData);
- parcAssertNotNull(event, "Got null from parcEvent_Create for socket %d", fd);
- return event;
-}
-
-void dispatcher_DestroyNetworkEvent(Dispatcher *dispatcher,
- PARCEvent **eventPtr) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(eventPtr,
- "Parameter eventPtr must be non-null double pointer");
- parcAssertNotNull(*eventPtr,
- "Paramter eventPtr must dereference to non-null pointer");
-
- parcEvent_Destroy(eventPtr);
- eventPtr = NULL;
-}
-
-void dispatcher_StartNetworkEvent(Dispatcher *dispatcher, PARCEvent *event) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(event, "Parameter event must be non-null");
-
- int failure = parcEvent_Start(event);
- parcAssertFalse(failure < 0, "Error starting signal event %p: (%d) %s",
- (void *)event, errno, strerror(errno));
-}
-
-void dispatcher_StopNetworkEvent(Dispatcher *dispatcher, PARCEvent *event) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(event, "Parameter event must be non-null");
-
- int failure = parcEvent_Stop(event);
- parcAssertFalse(failure < 0, "Error stopping signal event %p: (%d) %s",
- (void *)event, errno, strerror(errno));
-}
-
-PARCEventSignal *dispatcher_CreateSignalEvent(
- Dispatcher *dispatcher, PARCEventSignal_Callback *callback, void *userData,
- int signal) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(callback, "Parameter callback must be non-null");
-
- PARCEventSignal *event = parcEventSignal_Create(
- dispatcher->Base, signal, PARCEventType_Signal | PARCEventType_Persist,
- callback, userData);
- parcAssertNotNull(event,
- "Got null event when creating signal catcher for signal %d",
- signal);
-
- return event;
-}
-
-void dispatcher_DestroySignalEvent(Dispatcher *dispatcher,
- PARCEventSignal **eventPtr) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(eventPtr,
- "Parameter eventPtr must be non-null double pointer");
- parcAssertNotNull(*eventPtr,
- "Paramter eventPtr must dereference to non-null pointer");
-
- parcEventSignal_Destroy(eventPtr);
- eventPtr = NULL;
-}
-
-void dispatcher_StartSignalEvent(Dispatcher *dispatcher,
- PARCEventSignal *event) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(event, "Parameter event must be non-null");
-
- int failure = parcEventSignal_Start(event);
- parcAssertFalse(failure < 0, "Error starting signal event %p: (%d) %s",
- (void *)event, errno, strerror(errno));
-}
-
-void dispatcher_StopSignalEvent(Dispatcher *dispatcher,
- PARCEventSignal *event) {
- parcAssertNotNull(dispatcher, "Parameter dispatcher must be non-null");
- parcAssertNotNull(event, "Parameter event must be non-null");
-
- int failure = parcEventSignal_Stop(event);
- parcAssertFalse(failure < 0, "Error stopping signal event %p: (%d) %s",
- (void *)event, errno, strerror(errno));
-}
-
-/**
- * Bind to a local address/port then connect to peer.
- */
-static bool dispatcher_StreamBufferBindAndConnect(Dispatcher *dispatcher,
- PARCEventQueue *buffer,
- struct sockaddr *localSock,
- socklen_t localSockLength,
- struct sockaddr *remoteSock,
- socklen_t remoteSockLength) {
- // we need to bind, then connect. Special operation, so we make our
- // own fd then pass it off to the buffer event
-
-#ifndef _WIN32
- int fd = socket(localSock->sa_family, SOCK_STREAM, 0);
- if (fd < 0) {
- perror("socket");
- return -1;
- }
-
- // Set non-blocking flag
- int flags = fcntl(fd, F_GETFL, NULL);
- if (flags < 0) {
- perror("F_GETFL");
- close(fd);
- return -1;
- }
- int failure = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
- if (failure) {
- perror("F_SETFL");
- close(fd);
- return -1;
- }
-
- failure = bind(fd, localSock, localSockLength);
- if (failure) {
- perror("bind");
- close(fd);
- return false;
- }
-
- parcEventQueue_SetFileDescriptor(buffer, fd);
-
- failure = parcEventQueue_ConnectSocket(buffer, remoteSock, remoteSockLength);
- if (failure && (errno != EINPROGRESS)) {
- perror("connect");
- close(fd);
- return false;
- }
-#else
- SOCKET fd = socket(localSock->sa_family, SOCK_STREAM, 0);
- if (fd == INVALID_SOCKET) {
- perror("socket");
- return -1;
- }
-
- // Set non-blocking flag
- u_long mode = 1;
- int result = ioctlsocket(fd, FIONBIO, &mode);
- if (result == NO_ERROR) {
- perror("ioctlsocket error");
- closesocket(fd);
- WSACleanup();
- return -1;
- }
-
- int failure = bind(fd, localSock, (int)localSockLength);
- if (failure) {
- perror("bind");
- closesocket(fd);
- WSACleanup();
- return false;
- }
-
- parcEventQueue_SetFileDescriptor(buffer, (int)fd);
-
- failure = parcEventQueue_ConnectSocket(buffer, remoteSock, remoteSockLength);
- if (failure && (errno != EINPROGRESS)) {
- perror("connect");
- closesocket(fd);
- WSACleanup();
- return false;
- }
-#endif
-
- return true;
-}
-
-/**
- * Connect to an INET peer
- * @return NULL on error, otherwise a streambuffer
- */
-static PARCEventQueue *dispatcher_StreamBufferConnect_INET(
- Dispatcher *dispatcher, const Address *localAddress,
- const Address *remoteAddress) {
- struct sockaddr_in localSock, remoteSock;
- addressGetInet(localAddress, &localSock);
- addressGetInet(remoteAddress, &remoteSock);
-
- PARCEventQueue *buffer = parcEventQueue_Create(
- dispatcher->Base, -1, PARCEventQueueOption_CloseOnFree);
- parcAssertNotNull(buffer, "got null buffer from parcEventQueue_Create()");
-
- bool success = dispatcher_StreamBufferBindAndConnect(
- dispatcher, buffer, (struct sockaddr *)&localSock, sizeof(localSock),
- (struct sockaddr *)&remoteSock, sizeof(remoteSock));
- if (!success) {
- parcEventQueue_Destroy(&buffer);
- buffer = NULL;
- }
-
- return buffer;
-}
-
-/**
- * Connect to an INET peer
- * @return NULL on error, otherwise a streambuffer
- */
-static PARCEventQueue *
-// static StreamBuffer *
-dispatcher_StreamBufferConnect_INET6(Dispatcher *dispatcher,
- const Address *localAddress,
- const Address *remoteAddress) {
- struct sockaddr_in6 localSock, remoteSock;
- addressGetInet6(localAddress, &localSock);
- addressGetInet6(remoteAddress, &remoteSock);
-
- PARCEventQueue *buffer = parcEventQueue_Create(
- dispatcher->Base, -1, PARCEventQueueOption_CloseOnFree);
- parcAssertNotNull(buffer, "got null buffer from parcEventQueue_Create()");
-
- bool success = dispatcher_StreamBufferBindAndConnect(
- dispatcher, buffer, (struct sockaddr *)&localSock, sizeof(localSock),
- (struct sockaddr *)&remoteSock, sizeof(remoteSock));
- if (!success) {
- parcEventQueue_Destroy(&buffer);
- buffer = NULL;
- }
-
- return buffer;
-}
-
-PARCEventQueue *dispatcher_StreamBufferConnect(Dispatcher *dispatcher,
- const AddressPair *pair) {
- const Address *localAddress = addressPair_GetLocal(pair);
- const Address *remoteAddress = addressPair_GetRemote(pair);
-
- // they must be of the same address family
- if (addressGetType(localAddress) != addressGetType(remoteAddress)) {
- char message[2048];
- char *localAddressString = addressToString(localAddress);
- char *remoteAddressString = addressToString(remoteAddress);
- snprintf(message, 2048,
- "Remote address not same type as local address, expected %d got "
- "%d\nlocal %s remote %s",
- addressGetType(localAddress), addressGetType(remoteAddress),
- localAddressString, remoteAddressString);
-
- parcMemory_Deallocate((void **)&localAddressString);
- parcMemory_Deallocate((void **)&remoteAddressString);
-
- parcAssertTrue(
- addressGetType(localAddress) == addressGetType(remoteAddress), "%s",
- message);
- }
-
- address_type type = addressGetType(localAddress);
-
- PARCEventQueue *result = NULL;
-
- switch (type) {
- case ADDR_INET:
- return dispatcher_StreamBufferConnect_INET(dispatcher, localAddress,
- remoteAddress);
- break;
- case ADDR_INET6:
- return dispatcher_StreamBufferConnect_INET6(dispatcher, localAddress,
- remoteAddress);
- break;
- default:
- parcTrapIllegalValue(type, "local address unsupported address type: %d",
- type);
- }
- return result;
-}
diff --git a/hicn-light/src/hicn/core/dispatcher.h b/hicn-light/src/hicn/core/dispatcher.h
deleted file mode 100644
index e5c2df336..000000000
--- a/hicn-light/src/hicn/core/dispatcher.h
+++ /dev/null
@@ -1,288 +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.
- */
-
-/**
- * @header hicn-light Dispatcher
- * @abstract The dispatcher is the event loop run by Forwarder.
- * @discussion
- * These functions manage listeners, timers, and network events inside
- * the event loop.
- *
- * Curently, it is a thin wrapper around an event so we don't have to
- * expose that implementation detail to other modules.
- *
- */
-
-#ifndef dispatcher_h
-#define dispatcher_h
-
-#ifndef _WIN32
-#include <sys/socket.h>
-#endif
-#include <stdbool.h>
-
-struct dispatcher;
-typedef struct dispatcher Dispatcher;
-
-#include <parc/algol/parc_Event.h>
-#include <parc/algol/parc_EventQueue.h>
-#include <parc/algol/parc_EventScheduler.h>
-#include <parc/algol/parc_EventSignal.h>
-#include <parc/algol/parc_EventSocket.h>
-#include <parc/algol/parc_EventTimer.h>
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/core/logger.h>
-
-PARCEventScheduler *dispatcher_GetEventScheduler(Dispatcher *dispatcher);
-/**
- * Creates an event dispatcher
- *
- * Event dispatcher based on PARCEvent
- *
- * @return non-null Allocated event dispatcher
- * @return null An error
- */
-Dispatcher *dispatcher_Create(Logger *logger);
-
-/**
- * Destroys event dispatcher
- *
- * Caller is responsible for destroying call events before destroying
- * the event dispatcher.
- */
-void dispatcher_Destroy(Dispatcher **dispatcherPtr);
-
-/**
- * @function dispatcher_Stop
- * @abstract Called from a different thread, tells the dispatcher to stop
- * @discussion
- * Called from a user thread or from an interrupt handler.
- * Does not block. Use <code>dispatcher_WaitForStopped()</code> to
- * block until stopped after calling this.
- */
-void dispatcher_Stop(Dispatcher *dispatcher);
-
-/**
- * @function dispatcher_WaitForStopped
- * @abstract Blocks until dispatcher in stopped state
- * @discussion
- * Used after <code>dispatcher_Stop()</code> to wait for stop.
- */
-void dispatcher_WaitForStopped(Dispatcher *dispatcher);
-
-/**
- * @function dispatcher_Run
- * @abstract Runs the forwarder, blocks.
- */
-void dispatcher_Run(Dispatcher *dispatcher);
-
-/**
- * @function dispatcher_RunDuration
- * @abstract Runs forwarder for at most duration, blocks.
- * @discussion
- * Blocks running the forwarder for a duration. May be called
- * iteratively to keep running. Duration is a minimum, actual
- * runtime may be slightly longer.
- */
-void dispatcher_RunDuration(Dispatcher *dispatcher, struct timeval *duration);
-
-/**
- * @header dispatcher_RunCount
- * @abstract Run the event loop for the given count cycles
- * @discussion
- * Runs the event loop for the given number of cycles, blocking
- * until done. May be called sequentially over and over.
- *
- */
-void dispatcher_RunCount(Dispatcher *dispatcher, unsigned count);
-
-typedef int SocketType;
-
-typedef struct evconnlistener Listener;
-
-/**
- * @typedef ListenerCallback
- * @abstract Callback function typedef for a stream listener
- *
- * @constant listener is the object created by <code>forwarder_NewBind()</code>
- * that received the client connection
- * @constant client_socket is the client socket
- * @constant user_data is the user_data passed to
- * <code>forwarder_NewBind()</code>
- * @constant client_addr is the client address
- * @constant socklen is the length of client_addr
- * @discussion <#Discussion#>
- */
-typedef void(ListenerCallback)(Listener *listener, SocketType client_socket,
- struct sockaddr *client_addr, int socklen,
- void *user_data);
-
-/**
- * @header forwarder_NewBind
- * @abstract Allocate a new stream listener
- * @discussion
- * The server socket will be freed when closed and will be reusable.
- *
- * @param forwarder that owns the event loop
- * @param cb is the callback for a new connection
- * @param user_data is opaque user data passed to the callback
- * @param backlog is the listen() depth, may use -1 for a default value
- * @param sa is the socket address to bind to (INET, INET6, LOCAL)
- * @param socklen is the sizeof the actual sockaddr (e.g. sizeof(sockaddr_un))
- */
-PARCEventSocket *dispatcher_CreateListener(Dispatcher *dispatcher,
- PARCEventSocket_Callback *callback,
- void *user_data, int backlog,
- const struct sockaddr *sa,
- int socklen);
-
-void dispatcher_DestroyListener(Dispatcher *dispatcher,
- PARCEventSocket **listenerPtr);
-
-typedef struct event TimerEvent;
-typedef struct event NetworkEvent;
-typedef struct event SignalEvent;
-
-/**
- * @typedef EventCallback
- * @abstract A network event or a timer callback
- * @constant fd The file descriptor associated with the event, may be -1 for
- * timers
- * @constant which_event is a bitmap of the EventType
- * @constant user_data is the user_data passed to
- * <code>Forwarder_CreateEvent()</code>
- */
-typedef void(EventCallback)(SocketType fd, short which_event, void *user_data);
-
-/**
- * @function dispatcher_CreateTimer
- * @abstract Creates a Event for use as a timer.
- * @discussion
- *
- * When created, the timer is idle and you need to call
- * <code>forwarder_StartTimer()</code>
- *
- * @param isPeriodic means the timer will fire repeatidly, otherwise it is a
- * one-shot and needs to be set again with <code>dispatcher_StartTimer()</code>
- */
-PARCEventTimer *dispatcher_CreateTimer(Dispatcher *dispatcher, bool isPeriodic,
- PARCEvent_Callback *callback,
- void *userData);
-
-/**
- * @function dispatcher_StartTimer
- * @abstract Starts the timer with the given delay.
- * @discussion
- * If the timer is periodic, it will keep firing with the given delay
- */
-void dispatcher_StartTimer(Dispatcher *dispatcher, PARCEventTimer *timerEvent,
- struct timeval *delay);
-
-void dispatcher_StopTimer(Dispatcher *dispatcher, PARCEventTimer *timerEvent);
-
-/**
- * @function dispatcher_DestroyTimerEvent
- * @abstract Cancels the timer and frees the event
- */
-void dispatcher_DestroyTimerEvent(Dispatcher *dispatcher,
- PARCEventTimer **eventPtr);
-
-/**
- * @function dispatcher_CreateNetworkEvent
- * @abstract Creates a network event callback on the socket
- * @discussion
- * May be used on any sort of file descriptor or socket. The event is edge
- * triggered and non-reentrent. This means you need to drain the events off the
- * socket, as the callback will not be called again until a new event arrives.
- *
- * When created, the event is idle and you need to call
- * <code>forwarder_StartNetworkEvent()</code>
- *
- * @param isPersistent means the callback will keep firing with new events,
- * otherwise its a one-shot
- * @param fd is the socket to monitor
- */
-PARCEvent *dispatcher_CreateNetworkEvent(Dispatcher *dispatcher,
- bool isPersistent,
- PARCEvent_Callback *callback,
- void *userData, int fd);
-
-void dispatcher_StartNetworkEvent(Dispatcher *dispatcher, PARCEvent *event);
-void dispatcher_StopNetworkEvent(Dispatcher *dispatcher, PARCEvent *event);
-
-void dispatcher_DestroyNetworkEvent(Dispatcher *dispatcher,
- PARCEvent **eventPtr);
-
-/**
- * @function dispatcher_CreateSignalEvent
- * @abstract Creates a signal trap
- * @discussion
- * May be used on catchable signals. The event is edge triggered and
- * non-reentrent. Signal events are persistent.
- *
- * When created, the signal trap is idle and you need to call
- * <code>forwarder_StartSignalEvent()</code>
- *
- * @param signal is the system signal to monitor (e.g. SIGINT).
- * @return <#return#>
- */
-PARCEventSignal *dispatcher_CreateSignalEvent(
- Dispatcher *dispatcher, PARCEventSignal_Callback *callback, void *userData,
- int signal);
-
-void dispatcher_DestroySignalEvent(Dispatcher *dispatcher,
- PARCEventSignal **eventPtr);
-
-void dispatcher_StartSignalEvent(Dispatcher *dispatcher,
- PARCEventSignal *event);
-void dispatcher_StopSignalEvent(Dispatcher *dispatcher, PARCEventSignal *event);
-
-// =============
-// stream buffers
-
-#include <hicn/core/streamBuffer.h>
-#include <hicn/io/addressPair.h>
-
-/**
- * @function dispatcher_CreateStreamBuffer
- * @abstract Creates a high-function buffer around a stream socket
- */
-PARCEventQueue *dispatcher_CreateStreamBufferFromSocket(Dispatcher *dispatcher,
- SocketType fd);
-
-/**
- * @function dispatcher_StreamBufferConnect
- * @abstract Create a TCP tunnel to a remote peer
- * @discussion
- * For TCP, both address pairs need to be the same address family: both INET
- * or both INET6. The remote address must have the complete socket information
- * (address, port). The local socket could be wildcarded or may specify down to
- * the (address, port) pair.
- *
- * If the local address is IPADDR_ANY and the port is 0, then it is a normal
- * call to "connect" that will use whatever local IP address and whatever local
- * port for the connection. If either the address or port is set, the local
- * socket will first be bound (via bind(2)), and then call connect().
- *
- * It is unlikely that the buffer will be connected by the time the function
- * returns. The eventCallback will fire once the remote system accepts the
- * conneciton.
- *
- * @return NULL on error, otherwise a streambuffer.
- */
-PARCEventQueue *dispatcher_StreamBufferConnect(Dispatcher *dispatcher,
- const AddressPair *pair);
-#endif // dispatcher_h
diff --git a/hicn-light/src/hicn/core/fib.c b/hicn-light/src/hicn/core/fib.c
new file mode 100644
index 000000000..c44d2daf0
--- /dev/null
+++ b/hicn-light/src/hicn/core/fib.c
@@ -0,0 +1,743 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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/hicn-light/config.h>
+#include <stdio.h>
+
+#include <hicn/core/fib.h>
+
+typedef struct fib_node_s {
+ struct fib_node_s *child[2]; /* 0: left, 1: right */
+ fib_entry_t *entry;
+ bool is_used;
+} fib_node_t;
+
+#define ZERO 0
+#define ONE 1
+
+static fib_node_t *fib_node_create(fib_node_t *left, fib_node_t *right,
+ fib_entry_t *entry, bool is_used) {
+ fib_node_t *node = malloc(sizeof(fib_node_t));
+ if (!node) return NULL;
+
+ *node = (fib_node_t){
+ .child = {left, right},
+ .entry = entry,
+ .is_used = is_used,
+ };
+
+ return node;
+}
+
+static void fib_node_free(fib_node_t *node) {
+ if (!node) return;
+
+ fib_node_free(node->child[ZERO]);
+ fib_node_free(node->child[ONE]);
+
+ fib_entry_free(node->entry);
+ free(node);
+}
+
+/******************************************************************************/
+
+struct fib_s {
+ void *forwarder;
+ fib_node_t *root;
+ unsigned size;
+};
+
+fib_t *fib_create(void *forwarder) {
+ fib_t *fib = malloc(sizeof(fib_t));
+ if (!fib) return NULL;
+
+ fib->forwarder = forwarder;
+ fib->root = NULL;
+ fib->size = 0;
+
+ return fib;
+}
+
+void fib_free(fib_t *fib) {
+ assert(fib);
+
+ fib_node_free(fib->root);
+
+ free(fib);
+}
+
+size_t fib_get_size(const fib_t *fib) {
+ assert(fib);
+ return fib->size;
+}
+
+/*
+ * This struct will hold various information related to the returned node such
+ * as its parent and grandparent if any, as well as some already computed
+ * information about the prefix.
+ */
+typedef struct {
+ /* Result node ancestors (NULL if not applicable) */
+ fib_node_t *parent;
+ fib_node_t *gparent;
+ fib_node_t *lpm;
+ /* Information related to the result node */
+ hicn_prefix_t *prefix;
+ uint32_t prefix_len;
+ uint32_t match_len;
+} fib_search_t;
+/*
+ * @brief Search for longest subprefix (helper function)
+ * @param [in] fib - Pointer to the FIB to search
+ * @param [in] prefix - The prefix used for search
+ * @param [out] search - A pointer to a structure that will hold related search
+ * information, that can be NULL if this is not needed.
+ *
+ * @returns The node whose entry corresponds to the longest subprefix of the
+ * prefix passed in parameter, or NULL if not found. The longest prefix match is
+ * thus the resulting node if curr_len == prefix_len, and its parent
+ * otherwise.
+ *
+ * Implementation details:
+ *
+ * This function performs a descent in the tree, following branches
+ * corresponding to the value of the next bit, until reaching past a leaf, or
+ * either the current node prefix:
+ * when one of the two following conditions is met:
+ * - is not a prefix of the searched one (match_len < curr_len), or
+ * - is longer or equal than the inserted one (curr_len >= prefix_len)
+ */
+fib_node_t *fib_search(const fib_t *fib, const hicn_prefix_t *prefix,
+ fib_search_t *search) {
+ uint32_t prefix_len = hicn_prefix_get_len(prefix);
+ uint32_t curr_len;
+ uint32_t match_len;
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HICN_PREFIX];
+ int rc = hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, prefix);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "%s", "(error)");
+ DEBUG("[fib_search] prefix=%s prefix_len=%d\n", buf, prefix_len);
+ });
+
+ fib_node_t *parent = NULL;
+ fib_node_t *gparent = NULL;
+ fib_node_t *lpm = NULL;
+ fib_node_t *curr = fib->root;
+ while (curr) {
+ const hicn_prefix_t *curr_prefix = fib_entry_get_prefix(curr->entry);
+
+ curr_len = hicn_prefix_get_len(curr_prefix);
+ match_len = hicn_prefix_lpm(prefix, curr_prefix);
+
+ // store the lpm
+ if (match_len == curr_len && curr->is_used) lpm = curr;
+
+ // curr_len >= prefix_len l >= L
+ // L is a prefix of l
+ // > means we did not find
+ // = means we could have found
+ if (match_len < curr_len || curr_len >= prefix_len) break;
+
+ gparent = parent;
+ parent = curr;
+
+ /* The following lookup won't fail since curr_len < prefix_len */
+ uint8_t next_bit = hicn_prefix_get_bit(prefix, curr_len);
+ curr = curr->child[next_bit];
+ }
+
+ if (search) {
+ search->parent = parent;
+ search->gparent = gparent;
+ search->lpm = lpm;
+ if (curr) {
+ search->prefix_len = curr_len;
+ search->match_len = match_len;
+ }
+ }
+ return curr;
+}
+
+/*
+ * Helper: insert a new node between parent and child.
+ *
+ * parent == NULL means we set the root of the FIB
+ * child == NULL means our node has no child
+ */
+fib_node_t *_fib_insert(fib_t *fib, fib_entry_t *entry, fib_node_t *parent,
+ fib_node_t *child, bool is_used) {
+ fib_node_t *new_node = fib_node_create(NULL, NULL, entry, is_used);
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(entry);
+
+ if (!parent) {
+ fib->root = new_node;
+ } else {
+ const hicn_prefix_t *parent_prefix = fib_entry_get_prefix(parent->entry);
+ uint32_t parent_prefix_len = hicn_prefix_get_len(parent_prefix);
+ uint8_t next_bit = hicn_prefix_get_bit(prefix, parent_prefix_len);
+ parent->child[next_bit] = new_node;
+ }
+
+ if (child) {
+ const hicn_prefix_t *child_prefix = fib_entry_get_prefix(child->entry);
+ uint32_t match_len = hicn_prefix_lpm(prefix, child_prefix);
+ uint8_t next_bit = hicn_prefix_get_bit(child_prefix, match_len);
+ new_node->child[next_bit] = child;
+ }
+
+ if (is_used) fib->size++;
+ return new_node;
+}
+
+/*
+ * Helper: remove a node from parent
+ */
+void _fib_remove(fib_t *fib, fib_node_t *curr, fib_node_t *parent) {
+ /*
+ * If we remove the node, curr has either 0 or 1 child. In the latter case,
+ * we attach it to parent
+ */
+ fib_node_t *child = curr->child[ZERO] ? curr->child[ZERO] : curr->child[ONE];
+ if (!parent) {
+ fib->root = child;
+ } else {
+ if (parent->child[ZERO] == curr)
+ parent->child[ZERO] = child;
+ else
+ parent->child[ONE] = child;
+ }
+ if (curr->is_used) fib->size--;
+ fib_node_free(curr);
+}
+
+/*
+ * - Stop condition: curr == NULL. This corresponds to:
+ *
+ * (CASE 1) Our parent is a strict prefix and we simply have to create a new
+ * leaf child in the correct branch based on the next bit following the parent
+ * prefix.
+ *
+ * Otherwise, our parent node exist. Based on the stop condition, we
+ * either have:
+ *
+ * - Stop condition 1 : curr_len == match_len AND curr_len >=
+ * prefix_len l == m && l >= L
+ *
+ * 2 sub-cases:
+ * - l = m > L : IMPOSSIBLE L < m since m = LPM(l, L) means L >= m
+ * - l = m = L : insert the current node, either it exists or not
+ *
+ * We thus have:
+ *
+ * (CASE 2) The node already exist. If is not in use we turn it on and we set
+ * the right fib entry.
+ *
+ * The case when it is used should never occur because of the way we add
+ * entries in the FIB... but let's add the nexthops we wish to insert into
+ * the existing FIB entry.
+ *
+ * - Stop condition 2: curr_len != match_len
+ * l != m => l > m
+ *
+ * We have two possibilities:
+ * - Only one is bigger than m (case 3)
+ * - They are both bigger than m (case 4)
+ *
+ * (CASE 3) Only one is bigger than m
+ * L == m => L < l (since l != m and l >= m)
+ * l > L = m
+ *
+ * This means L is a prefix of l.
+ * l'
+ * /
+ * L
+ * /
+ * l
+ *
+ * (CASE 4) They are both bigger than m
+ * - l > L > m
+ * - L > l > m
+ * - L = l > m
+ *
+ * Both share L and l share l' as a common prefix, and this is not l' since
+ * they share the name next bit.
+ *
+ * So this case is impossible and we would have taken the other branch during
+ * the descent:
+ *
+ * l'
+ * / \
+ * l L
+ *
+ * We are in a situation where e need to insert an internal node:
+ *
+ * l'
+ * |
+ * X <------ internal node
+ * / \
+ * l L
+ */
+fib_entry_t *fib_add(fib_t *fib, fib_entry_t *entry) {
+ assert(fib);
+ assert(entry);
+
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(entry);
+ uint32_t prefix_len = hicn_prefix_get_len(prefix);
+
+ fib_search_t search;
+ fib_node_t *curr = fib_search(fib, prefix, &search);
+
+ char buf[MAXSZ_HICN_PREFIX];
+ char buf2[MAXSZ_HICN_PREFIX];
+ int rc;
+
+ rc = hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, prefix);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "%s", "(error)");
+ if (curr) {
+ rc = hicn_prefix_snprintf(buf2, MAXSZ_HICN_PREFIX,
+ fib_entry_get_prefix(curr->entry));
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf2, MAXSZ_HICN_PREFIX, "%s", "(error)");
+ } else {
+ snprintf(buf2, MAXSZ_HICN_PREFIX, "%s", "(null)");
+ search.prefix_len = 0;
+ search.match_len = 0;
+ }
+ DEBUG("fib_search(%s) result: curr=%s, prefix_len=%d; match_len=%d\n", buf,
+ buf2, search.prefix_len, search.match_len);
+
+ /* Case 1 */
+ if (!curr) {
+ _fib_insert(fib, entry, search.parent, NULL, true);
+ goto END;
+ }
+
+ /* Case 2 */
+ if (search.prefix_len == search.match_len && prefix_len == search.match_len) {
+ const nexthops_t *nexthops = fib_entry_get_nexthops(entry);
+ nexthops_foreach(nexthops, nexthop,
+ { fib_entry_nexthops_add(curr->entry, nexthop); });
+ fib_entry_free(entry);
+ entry = curr->entry;
+ curr->is_used = true;
+ goto END;
+ }
+
+ /* Case 3 */
+ if (prefix_len == search.match_len) {
+ _fib_insert(fib, entry, search.parent, curr, true);
+ goto END;
+ }
+
+ /* Case 4 */
+ hicn_prefix_t inner_prefix; /* dup'ed in fib_entry_create */
+ hicn_prefix_copy(&inner_prefix, prefix);
+
+ hicn_prefix_truncate(&inner_prefix, search.match_len);
+
+ fib_entry_t *inner_entry = fib_entry_create(
+ &inner_prefix, STRATEGY_TYPE_UNDEFINED, NULL, fib->forwarder);
+
+ fib_node_t *new_node =
+ _fib_insert(fib, inner_entry, search.parent, curr, false);
+ _fib_insert(fib, entry, new_node, NULL, true);
+
+END:
+#if 0
+ fib_dump(fib);
+#endif
+ return entry;
+}
+
+/*
+ * Implementation details:
+ *
+ * To find whether the fib contains a prefix, we issue a search, and based on
+ * the stopping conditions, we return the fib note if and only if curr
+ * is not NULL, and prefix_len == curr_len (== match_len)
+ */
+fib_node_t *fib_contains_node(const fib_t *fib, const hicn_prefix_t *prefix) {
+ assert(fib);
+ assert(prefix);
+
+ uint32_t prefix_len = hicn_prefix_get_len(prefix);
+
+ fib_search_t search;
+ fib_node_t *curr = fib_search(fib, prefix, &search);
+
+ if (!curr) return NULL;
+ if (search.match_len != prefix_len) return NULL;
+ if (prefix_len != search.prefix_len) return NULL;
+
+ return curr->is_used ? curr : NULL;
+}
+
+fib_entry_t *fib_contains(const fib_t *fib, const hicn_prefix_t *prefix) {
+ fib_node_t *node = fib_contains_node(fib, prefix);
+ if (!node) return NULL;
+ return node->entry;
+}
+
+/*
+ * @brief Remove a prefix (and the associated node) from FIB
+ *
+ * We search for
+ *
+ * Actions depend on N, the number of children of the node to remove
+ * Examples are build using 'left' children only, but the cases with 'right'
+ * children are symmetrical.
+ *
+ * Legend:
+ * (empty) : no children
+ * * : 0 or more children
+ * + : at least one children
+ *
+ * N == 2 - Mark the node as unused
+ *
+ * parent parent
+ * / \ / \
+ * curr ... ==> (curr) ...
+ * / \ / \
+ * L R L R
+ *
+ * N == 1 - Attach the child to the parent node (whether parent is used or not)
+ *
+ * a) curr has no parent (curr is the root)
+ *
+ * curr +
+ * / ==>
+ * +
+ *
+ * b) curr has a parent
+ * parent parent
+ * / \ / \
+ * curr * ==> L *
+ * / \
+ * L
+ *
+ * (parent) (parent)
+ * / \ / \
+ * curr + ==> L +
+ * / \
+ * L
+ *
+ * N == 0
+ *
+ * a) curr has no parent (curr is the root)
+ *
+ * curr
+ * / \ ==>
+ *
+ * b) parent is unused.
+ *
+ * Assuming curr is the left child, then parent must have a
+ * right child, and the grand-parent must be used.
+ *
+ * gp gp gp
+ * / / /
+ * (parent) ==> (parent) ==> +
+ * / \ / \
+ * curr + +
+ * / \
+ *
+ * c) parent is used.
+ *
+ * Assuming curr is the left child, we simply remove it from
+ * parent, leaving parent unchanged whether it has a right child or not.
+ *
+ * parent parent
+ * / \ / \
+ * curr * ==> *
+ * / \
+ *
+ *
+ */
+static void fib_node_remove(fib_t *fib, const hicn_prefix_t *prefix) {
+ assert(fib);
+ assert(prefix);
+
+ uint32_t prefix_len = hicn_prefix_get_len(prefix);
+
+ fib_search_t search;
+ fib_node_t *curr = fib_search(fib, prefix, &search);
+
+ /*
+ * If we reach a NULL, unused node, or a node not matching, that means the
+ * node does not exist
+ */
+ if (!curr || !curr->is_used || (search.prefix_len != prefix_len)) return;
+
+ uint8_t N = 0;
+ if (curr->child[ZERO]) N++;
+ if (curr->child[ONE]) N++;
+
+ switch (N) {
+ case 2:
+ curr->is_used = false;
+ break;
+
+ case 1:
+ _fib_remove(fib, curr, search.parent);
+ break;
+
+ case 0:
+ _fib_remove(fib, curr, search.parent);
+ if (search.parent && !search.parent->is_used)
+ _fib_remove(fib, search.parent, search.gparent);
+ break;
+ }
+}
+
+void fib_remove(fib_t *fib, const hicn_prefix_t *prefix, unsigned conn_id) {
+ assert(fib);
+ assert(prefix);
+
+ fib_node_t *node = fib_contains_node(fib, prefix);
+ if (!node) return;
+
+ fib_entry_nexthops_remove(node->entry, conn_id);
+ if (fib_entry_nexthops_len(node->entry) == 0)
+ /* When using MAP-Me, we keep empty FIB entries but we mark them as unused*/
+#ifdef WITH_MAPME
+ node->is_used = false;
+#else
+ fib_node_remove(fib, name);
+#endif /* WITH_MAPME */
+}
+
+static size_t fib_node_remove_connection_id(fib_node_t *node, unsigned conn_id,
+ fib_entry_t **array, size_t pos) {
+ if (!node) return pos;
+ if (node->is_used) {
+ fib_entry_nexthops_remove(node->entry, conn_id);
+
+ /* When using MAP-Me, we keep empty FIB entries but we mark them as unused*/
+ if (fib_entry_nexthops_len(node->entry) == 0)
+#ifdef WITH_MAPME
+ node->is_used = false;
+#else
+ array[pos++] = node->entry;
+#endif /* WITH_MAPME */
+ }
+ pos = fib_node_remove_connection_id(node->child[ONE], conn_id, array, pos);
+ pos = fib_node_remove_connection_id(node->child[ZERO], conn_id, array, pos);
+ return pos;
+}
+
+void fib_remove_entry(fib_t *fib, fib_entry_t *entry) {
+ fib_node_remove(fib, fib_entry_get_prefix(entry));
+}
+
+void fib_remove_connection(fib_t *fib, unsigned conn_id,
+ fib_entry_t ***removed_entries,
+ size_t *num_removed_entries) {
+ assert(fib);
+
+ fib_entry_t **array = malloc(sizeof(fib_entry_t *) * fib->size);
+
+ size_t pos = 0;
+ pos = fib_node_remove_connection_id(fib->root, conn_id, array, pos);
+
+ if (removed_entries) {
+ /*
+ * The caller is taking charge of releasing entries (as well as the returned
+ * array
+ */
+ assert(num_removed_entries);
+
+ *removed_entries = array;
+ *num_removed_entries = pos;
+
+ } else {
+ for (int i = 0; i < pos; i++)
+ fib_node_remove(fib, fib_entry_get_prefix(array[i]));
+ }
+ free(array);
+}
+
+fib_entry_t *fib_match_msgbuf(const fib_t *fib, const msgbuf_t *msgbuf) {
+ assert(fib);
+ assert(msgbuf);
+
+ return fib_match_name(fib, msgbuf_get_name(msgbuf));
+}
+
+/*
+ * fib_search returns the longest non-strict subprefix.
+ * the LPM is stored in search if it exists
+ */
+fib_entry_t *fib_match_prefix(const fib_t *fib, const hicn_prefix_t *prefix) {
+ assert(fib);
+ assert(prefix);
+
+ fib_search_t search;
+ fib_search(fib, prefix, &search);
+ if (!search.lpm) return NULL;
+ return search.lpm->entry;
+}
+
+fib_entry_t *fib_match_name(const fib_t *fib, const hicn_name_t *name) {
+ hicn_prefix_t prefix;
+ const hicn_name_prefix_t *name_prefix = hicn_name_get_prefix(name);
+ prefix.name = *name_prefix;
+ prefix.len = hicn_name_prefix_get_len_bits(name_prefix);
+ return fib_match_prefix(fib, &prefix);
+}
+
+static size_t fib_node_collect_entries(fib_node_t *node, fib_entry_t **array,
+ size_t pos) {
+ assert(array);
+
+ if (!node) return pos;
+
+ if (node->is_used) array[pos++] = node->entry;
+
+ pos = fib_node_collect_entries(node->child[ONE], array, pos);
+ pos = fib_node_collect_entries(node->child[ZERO], array, pos);
+ return pos;
+}
+
+size_t fib_get_entry_array(const fib_t *fib, fib_entry_t ***array_p) {
+ size_t pos = 0;
+ *array_p = malloc(sizeof(fib_entry_t *) * fib->size);
+ if (!*array_p) return pos;
+ pos = fib_node_collect_entries(fib->root, *array_p, pos);
+ return pos;
+}
+
+bool _fib_is_valid(const fib_node_t *node) {
+ if (!node) return true;
+
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(node->entry);
+ uint32_t prefix_len = hicn_prefix_get_len(prefix);
+
+ for (unsigned i = 0; i < 2; i++) {
+ const fib_node_t *child = node->child[i];
+ if (!child) continue;
+ const hicn_prefix_t *child_prefix = fib_entry_get_prefix(child->entry);
+
+ uint32_t match_len = hicn_prefix_lpm(prefix, child_prefix);
+ if (match_len != prefix_len) return false;
+ if (hicn_prefix_get_bit(child_prefix, match_len) != i) return false;
+ if (!_fib_is_valid(child)) return false;
+ }
+ return true;
+}
+
+/*
+ * @brief Check that the structure of the FIB is correct : prefixes are
+ * correctly nested, 0 are on the left, 1 on the right, and that we have no
+ * more than 1 unused prefix as parents.
+ */
+bool fib_is_valid(const fib_t *fib) { return _fib_is_valid(fib->root); }
+
+/*
+ * Checks whether the preorder traversal of the sub-tree corresponds to the
+ * prefix and used arrays, starting from pos (helper)
+ */
+bool __fib_check_preorder(const fib_node_t *node,
+ const hicn_prefix_t **prefix_array, bool *used_array,
+ size_t size, size_t *pos) {
+ /* Check left subtree... */
+ fib_node_t *left = node->child[ZERO];
+ if (left && !__fib_check_preorder(left, prefix_array, used_array, size, pos))
+ return false;
+
+ /* ... then current node ... */
+ if (*pos > size) {
+ ERROR("size error");
+ return false;
+ }
+
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(node->entry);
+
+ if (!hicn_prefix_equals(prefix, prefix_array[*pos])) {
+ char buf[MAXSZ_HICN_PREFIX];
+ char buf2[MAXSZ_HICN_PREFIX];
+ int rc;
+
+ rc = hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, prefix);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "%s", "(error)");
+ rc = hicn_prefix_snprintf(buf2, MAXSZ_HICN_PREFIX, prefix_array[*pos]);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf2, MAXSZ_HICN_PREFIX, "%s", "(error)");
+ ERROR("Prefix mismatch in position %ld %s != %s", *pos, buf, buf2);
+ return false;
+ }
+
+ (*pos)++;
+
+ /* ... then right subtree */
+ fib_node_t *right = node->child[ONE];
+ if (right &&
+ !__fib_check_preorder(right, prefix_array, used_array, size, pos))
+ return false;
+
+ return true;
+}
+
+/*
+ * Checks whether the preorder traversal of the trie
+ * corresponds to the prefix and used arrays.
+ */
+bool _fib_check_preorder(const fib_t *fib, const hicn_prefix_t **prefix_array,
+ bool *used_array, size_t size) {
+ if (!fib->root) return true;
+ size_t pos = 0;
+ if (!__fib_check_preorder(fib->root, prefix_array, used_array, size, &pos))
+ return false;
+ /* We need to check that we don't miss elements */
+ return pos == size;
+}
+
+// XXX print empty node but not recurse
+void _fib_dump(const fib_node_t *node, int start, int indent, int location) {
+ char buf[MAXSZ_HICN_PREFIX];
+
+ if (node) {
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(node->entry);
+ int rc = hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, prefix);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "%s %d", "(error)", rc);
+ } else {
+ snprintf(buf, MAXSZ_HICN_PREFIX, "%s", "(null)");
+ }
+
+ if (indent > 0) {
+ for (int i = 0; i < start; i++) printf(" ");
+ for (int i = 0; i < indent - start - 1; i++) printf("| ");
+ printf("|_ ");
+ }
+ printf("%s", buf);
+ if (node && !node->is_used) printf(" [inner]");
+ printf("\n");
+
+ if (!node) return;
+
+ if (location == 2) {
+ start++;
+ location = 0;
+ }
+ _fib_dump(node->child[ZERO], start, indent + 1,
+ (location == 0) ? 1 : location);
+ _fib_dump(node->child[ONE], start, indent + 1,
+ (location == 0) ? 2 : location);
+}
+
+void fib_dump(const fib_t *fib) { _fib_dump(fib->root, 0, 0, 0); }
diff --git a/hicn-light/src/hicn/core/fib.h b/hicn-light/src/hicn/core/fib.h
new file mode 100644
index 000000000..4fb5009f5
--- /dev/null
+++ b/hicn-light/src/hicn/core/fib.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+#ifndef HICNLIGHT_FIB_H
+#define HICNLIGHT_FIB_H
+
+#include "fib_entry.h"
+#include "msgbuf.h"
+#include <hicn/name.h>
+
+#define _fib_var(x) _fib_##x
+
+typedef struct fib_s fib_t;
+
+fib_t *fib_create(void *forwarder);
+
+void fib_free(fib_t *fib);
+
+size_t fib_get_size(const fib_t *fib);
+
+fib_entry_t *fib_add(fib_t *fib, fib_entry_t *node);
+
+fib_entry_t *fib_contains(const fib_t *fib, const hicn_prefix_t *prefix);
+
+void fib_remove(fib_t *fib, const hicn_prefix_t *prefix, unsigned conn_id);
+
+void fib_remove_entry_connection(fib_t *fib, fib_entry_t *entry,
+ unsigned conn_id, fib_entry_t **removed_entry);
+
+void fib_remove_name_connection(fib_t *fib, const hicn_prefix_t *prefix,
+ unsigned conn_id);
+
+void fib_remove_entry(fib_t *fib, fib_entry_t *entry);
+
+void fib_remove_connection(fib_t *fib, unsigned conn_id,
+ fib_entry_t ***removed_entries,
+ size_t *num_removed_entries);
+
+fib_entry_t *fib_match_msgbuf(const fib_t *fib, const msgbuf_t *msgbuf);
+
+fib_entry_t *fib_match_prefix(const fib_t *fib, const hicn_prefix_t *prefix);
+
+fib_entry_t *fib_match_name(const fib_t *fib, const hicn_name_t *name);
+
+size_t fib_get_entry_array(const fib_t *fib, fib_entry_t ***array_p);
+
+/*
+ * NOTE : do not use return on the loop body to avoid leaking memory
+ */
+#define fib_foreach_entry(FIB, ENTRY, BODY) \
+ do { \
+ fib_entry_t **_fib_var(array); \
+ size_t _fib_var(n) = fib_get_entry_array((FIB), &_fib_var(array)); \
+ size_t _fib_var(i); \
+ fib_entry_t *ENTRY; \
+ for (_fib_var(i) = 0; _fib_var(i) < _fib_var(n); _fib_var(i)++) { \
+ ENTRY = _fib_var(array)[_fib_var(i)]; \
+ do { \
+ BODY \
+ } while (0); \
+ } \
+ free(_fib_var(array)); \
+ } while (0)
+
+bool fib_is_valid(const fib_t *fib);
+bool _fib_check_preorder(const fib_t *fib, const hicn_prefix_t **prefix_array,
+ bool *used_array, size_t size);
+
+#define fib_check_preorder(F, PA, UA) \
+ _fib_check_preorder(F, PA, UA, sizeof(PA) / sizeof(hicn_prefix_t *))
+
+void fib_dump(const fib_t *fib);
+
+#endif /* HICNLIGHT_FIB_H */
diff --git a/hicn-light/src/hicn/core/fib_entry.c b/hicn-light/src/hicn/core/fib_entry.c
new file mode 100644
index 000000000..b510b68b4
--- /dev/null
+++ b/hicn-light/src/hicn/core/fib_entry.c
@@ -0,0 +1,667 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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 <stdio.h>
+
+#include <hicn/hicn-light/config.h>
+#include <hicn/core/fib_entry.h>
+#include <hicn/core/strategy.h>
+
+#ifdef WITH_MAPME
+#include <hicn/core/ticks.h>
+#endif /* WITH_MAPME */
+
+#ifdef WITH_POLICY
+#include <hicn/core/forwarder.h>
+#include <hicn/policy.h>
+
+#ifdef WITH_MAPME
+#include <hicn/core/mapme.h>
+#endif /* WITH_MAPME */
+
+#endif /* WITH_POLICY */
+
+#ifdef WITH_POLICY_STATS
+#include <hicn/core/policy_stats.h>
+#endif /* WITH_POLICY_STATS */
+
+fib_entry_t *fib_entry_create(const hicn_prefix_t *prefix,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options,
+ const forwarder_t *forwarder) {
+ assert(prefix);
+ /*
+ * For tests, we allow forwarder to be NULL, some
+ * functions cannot be called but otherwise we need a main loop, etc.
+ */
+ // assert(forwarder);
+
+ fib_entry_t *entry = malloc(sizeof(fib_entry_t));
+ if (!entry) goto ERR_MALLOC;
+
+ memset(entry, 0, sizeof(*entry));
+ hicn_prefix_copy(&entry->prefix, prefix);
+ entry->nexthops = NEXTHOPS_EMPTY;
+
+ fib_entry_add_strategy_options(entry, STRATEGY_TYPE_BESTPATH, NULL);
+ fib_entry_add_strategy_options(entry, STRATEGY_TYPE_REPLICATION, NULL);
+ fib_entry_set_strategy(entry, strategy_type, strategy_options);
+
+#ifdef WITH_MAPME
+ entry->user_data = NULL;
+ entry->user_data_release = NULL;
+#endif /* WITH_MAPME */
+
+ entry->forwarder = forwarder;
+
+#ifdef WITH_POLICY
+ entry->policy = POLICY_EMPTY;
+#endif /* WITH_POLICY */
+
+#ifdef WITH_POLICY_STATS
+ entry->policy_stats = POLICY_STATS_EMPTY;
+ entry->policy_counters = POLICY_COUNTERS_EMPTY;
+#endif /* WITH_POLICY_STATS */
+
+ return entry;
+
+ERR_MALLOC:
+ return NULL;
+}
+
+void fib_entry_free(fib_entry_t *entry) {
+ assert(entry);
+#ifdef WITH_MAPME
+ if (entry->user_data) entry->user_data_release(&entry->user_data);
+#endif /* WITH_MAPME */
+ free(entry);
+}
+
+void fib_entry_add_strategy_options(fib_entry_t *entry,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options) {
+ // for the moment only the best path and replication strategies support
+ // strategy options return for the other strategyes
+ if (strategy_type != STRATEGY_TYPE_BESTPATH &&
+ strategy_type != STRATEGY_TYPE_REPLICATION)
+ return;
+
+ if (!strategy_options) {
+ if (strategy_type == STRATEGY_TYPE_BESTPATH) {
+ entry->strategy.options.bestpath.local_prefixes = NULL;
+ } else {
+ entry->strategy.options.replication.local_prefixes = NULL;
+ }
+ return;
+ }
+
+ local_prefixes_t *new_prefixes;
+ local_prefixes_t *curr_prefixes;
+
+ if (strategy_type == STRATEGY_TYPE_BESTPATH) {
+ new_prefixes = strategy_options->bestpath.local_prefixes;
+ curr_prefixes = entry->strategy.options.bestpath.local_prefixes;
+
+ if (!curr_prefixes) {
+ entry->strategy.options.bestpath.local_prefixes = create_local_prefixes();
+ curr_prefixes = entry->strategy.options.bestpath.local_prefixes;
+ }
+ } else {
+ new_prefixes = strategy_options->replication.local_prefixes;
+ curr_prefixes = entry->strategy.options.replication.local_prefixes;
+
+ if (!curr_prefixes) {
+ entry->strategy.options.replication.local_prefixes =
+ create_local_prefixes();
+ curr_prefixes = entry->strategy.options.replication.local_prefixes;
+ }
+ }
+
+ local_prefixes_add_prefixes(curr_prefixes, new_prefixes);
+}
+
+void fib_entry_set_strategy(fib_entry_t *entry, strategy_type_t strategy_type,
+ strategy_options_t *strategy_options) {
+ // Default strategy if undefined
+ if (!STRATEGY_TYPE_VALID(strategy_type)) strategy_type = STRATEGY_TYPE_RANDOM;
+
+ if (entry->strategy.type == strategy_type) { // startegy alredy set
+ if (strategy_type != STRATEGY_TYPE_BESTPATH) {
+ return; // nothing to do
+ } else {
+ strategy_initialize(&entry->strategy, entry->forwarder);
+ return;
+ }
+ }
+
+ entry->strategy.type = strategy_type;
+ if (strategy_options) entry->strategy.options = *strategy_options;
+
+ strategy_initialize(&entry->strategy, entry->forwarder);
+}
+
+/*
+ * Filters the set of nexthops passed as parameters (and not the one stored in
+ * the FIB entry
+ */
+nexthops_t *fib_entry_filter_nexthops(fib_entry_t *entry, nexthops_t *nexthops,
+ unsigned ingress_id, bool prefer_local) {
+ assert(entry);
+ assert(nexthops);
+
+ nexthops_reset(nexthops);
+
+ // DEBUG("[fib_entry_filter_nexthops] num=%d/%d ingress_id=%d",
+ // nexthops_get_curlen(nexthops), nexthops_get_len(nexthops),
+ // ingress_id);
+
+ /* Filter out ingress, down & administrative down faces */
+ const connection_table_t *table =
+ forwarder_get_connection_table(entry->forwarder);
+ connection_t *conn;
+ uint_fast32_t flags;
+
+ hicn_policy_t policy = fib_entry_get_policy(entry);
+
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i, nexthop == ingress_id);
+ nexthops_disable_if(nexthops, i,
+ (connection_get_admin_state(conn) == FACE_STATE_DOWN));
+ nexthops_disable_if(nexthops, i,
+ (connection_get_state(conn) == FACE_STATE_DOWN));
+ });
+
+ // DEBUG("After pruning, num=%d/%d", nexthops_get_curlen(nexthops),
+ // nexthops_get_len(nexthops));
+
+ if (prefer_local) {
+ /* Backup flags and cur_len*/
+ flags = nexthops->flags;
+ size_t cur_len = nexthops_get_curlen(nexthops);
+
+ /* Filter local */
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i, (!connection_is_local(conn)));
+ });
+
+ /* Local faces have priority */
+ if (nexthops_get_curlen(nexthops) > 0) return nexthops;
+
+ nexthops->flags = flags;
+ nexthops->cur_elts = cur_len;
+ }
+
+ /* Filter out local */
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i, (connection_is_local(conn)));
+
+#ifdef WITH_POLICY
+ /* Policy filtering : next hops */
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_REQUIRE) &&
+ (!connection_has_tag(conn, POLICY_TAG_WIRED)));
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_PROHIBIT) &&
+ (connection_has_tag(conn, POLICY_TAG_WIRED)));
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_REQUIRE) &&
+ (!connection_has_tag(conn, POLICY_TAG_WIFI)));
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_PROHIBIT) &&
+ (connection_has_tag(conn, POLICY_TAG_WIFI)));
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_REQUIRE) &&
+ (!connection_has_tag(conn, POLICY_TAG_CELLULAR)));
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_PROHIBIT) &&
+ (connection_has_tag(conn, POLICY_TAG_CELLULAR)));
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_REQUIRE) &&
+ (!connection_has_tag(conn, POLICY_TAG_TRUSTED)));
+ nexthops_disable_if(
+ nexthops, i,
+ (policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_PROHIBIT) &&
+ (connection_has_tag(conn, POLICY_TAG_TRUSTED)));
+#endif /* WITH_POLICY */
+ });
+
+ if (nexthops_get_curlen(nexthops) == 0) {
+ DEBUG("After REQUIRE/PROHIBIT pruning, num=%d/%d",
+ nexthops_get_curlen(nexthops), nexthops_get_len(nexthops));
+ return nexthops;
+ }
+
+ /* We have at least one matching next hop, implement heuristic */
+
+#ifdef WITH_POLICY
+ /*
+ * As VPN connections might trigger duplicate uses of one interface, we start
+ * by filtering out interfaces based on trust status.
+ */
+ flags = nexthops->flags;
+
+ if ((policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_REQUIRE) ||
+ (policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_PREFER)) {
+ /* Try to filter out NON TRUSTED faces */
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ (!connection_has_tag(conn, POLICY_TAG_TRUSTED)));
+ });
+
+ if ((nexthops_get_curlen(nexthops) == 0) &&
+ (policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_REQUIRE)) {
+ return nexthops;
+ }
+
+ } else {
+ /* Try to filter out TRUSTED faces */
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ (connection_has_tag(conn, POLICY_TAG_TRUSTED)));
+ });
+ }
+
+ if (nexthops_get_curlen(nexthops) == 0) nexthops->flags = flags;
+
+ /* Other preferences */
+ if (policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_AVOID) {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ connection_has_tag(conn, POLICY_TAG_WIRED));
+ });
+ if (nexthops_get_curlen(nexthops) == 0) nexthops->flags = flags;
+ }
+ if (policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_AVOID) {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ connection_has_tag(conn, POLICY_TAG_WIFI));
+ });
+ if (nexthops_get_curlen(nexthops) == 0) nexthops->flags = flags;
+ }
+ if (policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_AVOID) {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ connection_has_tag(conn, POLICY_TAG_CELLULAR));
+ });
+ if (nexthops_get_curlen(nexthops) == 0) nexthops->flags = flags;
+ }
+
+ if (policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_PREFER) {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ !connection_has_tag(conn, POLICY_TAG_WIRED));
+ });
+ if (nexthops_get_curlen(nexthops) == 0) nexthops->flags = flags;
+ }
+ if (policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_PREFER) {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ !connection_has_tag(conn, POLICY_TAG_WIFI));
+ });
+ if (nexthops_get_curlen(nexthops) == 0) nexthops->flags = flags;
+ }
+ if (policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_PREFER) {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ !connection_has_tag(conn, POLICY_TAG_CELLULAR));
+ });
+ if (nexthops_get_curlen(nexthops) == 0) nexthops->flags = flags;
+ }
+// XXX backup curlen ???
+#endif /* WITH_POLICY */
+
+ DEBUG("[fib_entry_filter_nexthops] before face priority num=%d/%d",
+ nexthops_get_curlen(nexthops), nexthops_get_len(nexthops));
+
+ /* Priority */
+ uint32_t max_priority = 0;
+ nexthops_foreach(nexthops, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ uint32_t priority = connection_get_priority(conn);
+ if (priority > max_priority) max_priority = priority;
+ });
+ nexthops_enumerate(nexthops, i, nexthop, {
+ conn = connection_table_at(table, nexthop);
+ nexthops_disable_if(nexthops, i,
+ connection_get_priority(conn) < max_priority);
+ });
+
+ DEBUG("[fib_entry_filter_nexthops] result num=%d/%d",
+ nexthops_get_curlen(nexthops), nexthops_get_len(nexthops));
+
+ /* Nexthop priority */
+
+ /*
+ * Filter out nexthops with lowest strategy priority.
+ * Initializing at 0 allows to disable nexthops with a negative priority
+ */
+ max_priority = 0;
+ nexthops_enumerate(nexthops, i, nexthop, {
+ (void)nexthop;
+ int priority = nexthops->state[i].priority;
+ if (priority > max_priority) max_priority = priority;
+ });
+ nexthops_enumerate(nexthops, i, nexthop, {
+ int priority = nexthops->state[i].priority;
+ nexthops_disable_if(nexthops, i, (priority < max_priority));
+ });
+
+ /*
+ * If multipath is disabled, we don't offer much choice to the forwarding
+ * strategy, but still go through it for accounting purposes.
+ */
+ if ((policy.tags[POLICY_TAG_MULTIPATH].state == POLICY_STATE_PROHIBIT) ||
+ (policy.tags[POLICY_TAG_MULTIPATH].state == POLICY_STATE_AVOID)) {
+ DEBUG(
+ "[fib_entry_get_nexthops_from_strategy] select single nexthops due to "
+ "multipath policy");
+ nexthops_select_first(nexthops);
+ }
+
+ return nexthops;
+}
+
+/*
+ * Retrieve all candidate nexthops for sending mapme updates == all non local
+ * connections. We don't apply the policy at this stage.
+ */
+nexthops_t *fib_entry_get_mapme_nexthops(fib_entry_t *entry,
+ nexthops_t *new_nexthops) {
+ assert(new_nexthops);
+
+ const connection_table_t *table =
+ forwarder_get_connection_table(entry->forwarder);
+
+ /* We create a nexthop structure based on connections */
+ // XXX This should be done close to where it is needed
+ connection_t *connection;
+ connection_table_foreach(table, connection, {
+ if (connection_is_local(connection)) continue;
+ new_nexthops->elts[nexthops_get_len(new_nexthops)] =
+ connection_table_get_connection_id(table, connection);
+ nexthops_inc(new_nexthops);
+ });
+
+ return new_nexthops;
+}
+
+/*
+ * Update available next hops following policy update.
+ *
+ * The last nexthop parameter is only used if needed, otherwise the pointer to
+ * fib entry is returned to avoid an useless copy
+ */
+nexthops_t *fib_entry_get_available_nexthops(fib_entry_t *entry,
+ unsigned ingress_id,
+ nexthops_t *new_nexthops) {
+ // DEBUG("[fib_entry_get_available_nexthops]");
+
+ connection_table_t *table = forwarder_get_connection_table(entry->forwarder);
+
+ /*
+ * Give absolute preference to local faces, with no policy, unless
+ * ingress_id == ~0, which means we are searching faces on which to
+ * advertise our prefix
+ */
+ if (ingress_id == ~0) {
+ assert(new_nexthops);
+ /* We create a nexthop structure based on connections */
+ // XXX This should be done close to where it is needed
+ connection_t *connection;
+ connection_table_foreach(table, connection, {
+ if (connection_is_local(connection)) continue;
+ new_nexthops->elts[nexthops_get_len(new_nexthops)] =
+ (unsigned int)connection_table_get_connection_id(table, connection);
+ nexthops_inc(new_nexthops);
+ });
+
+#ifdef WITH_POLICY
+ return fib_entry_filter_nexthops(entry, new_nexthops, ingress_id, false);
+#else
+ return new_nexthops;
+#endif
+ }
+
+#ifdef WITH_POLICY
+ return fib_entry_filter_nexthops(entry, fib_entry_get_nexthops(entry),
+ ingress_id, true);
+#else
+ return fib_entry_get_nexthops(entry);
+#endif
+}
+
+#ifdef WITH_POLICY
+
+hicn_policy_t fib_entry_get_policy(const fib_entry_t *entry) {
+ return entry->policy;
+}
+
+void fib_entry_set_policy(fib_entry_t *entry, hicn_policy_t policy) {
+ INFO("fib_entry_set_policy");
+ entry->policy = policy;
+
+ forwarder_on_route_event(entry->forwarder, entry);
+
+ // XXX generic mechanism to perform a mapme update
+#if 0
+#ifdef WITH_MAPME
+ /*
+ * Skip entries that do not correspond to a producer ( / have a locally
+ * served prefix / have no local connection as next hop)
+ */
+ if (!fib_entry_has_local_nexthop(entry)) return;
+ mapme_t *mapme = forwarder_get_mapme(entry->forwarder);
+#endif /* WITH_MAPME */
+#endif
+}
+
+#endif /* WITH_POLICY */
+
+void fib_entry_nexthops_add(fib_entry_t *entry, unsigned nexthop) {
+ /*
+ * Nexthop is added to both:
+ * - fib_entry: it is added to the nexthops_t struct, in the elts array.
+ * - strategy: only used to eventually initialize internal state, might be
+ * empty like in the random strategy.
+ */
+ off_t id = nexthops_add(&entry->nexthops, nexthop);
+ strategy_add_nexthop(&entry->strategy, &entry->nexthops, id);
+}
+
+void fib_entry_nexthops_remove(fib_entry_t *entry, unsigned nexthop) {
+ off_t id = nexthops_remove(&entry->nexthops, nexthop);
+ strategy_remove_nexthop(&entry->strategy, &entry->nexthops, id);
+}
+
+nexthops_t *fib_entry_get_nexthops_from_strategy(fib_entry_t *entry,
+ const msgbuf_t *msgbuf,
+ bool is_retransmission) {
+ assert(entry);
+ assert(msgbuf);
+
+ // DEBUG("[fib_entry_get_nexthops_from_strategy]");
+
+ const policy_stats_mgr_t *mgr =
+ forwarder_get_policy_stats_mgr(entry->forwarder);
+ assert(mgr);
+
+ /* Filtering */
+ nexthops_t *nexthops = fib_entry_get_available_nexthops(
+ entry, msgbuf_get_connection_id(msgbuf), NULL);
+ if (nexthops_get_curlen(nexthops) == 0) return nexthops;
+
+#ifdef WITH_POLICY_STATS
+ /*
+ * Update statistics about loss rates. We only detect losses upon
+ * retransmissions, and assume for the computation that the candidate set of
+ * output faces is the same as previously (i.e. does not take into account
+ * event such as face up/down, policy update, etc. Otherwise we would need to
+ * know what was the previous choice !
+ */
+ if (is_retransmission)
+ policy_stats_on_retransmission(mgr, &entry->policy_counters, nexthops);
+#endif /* WITH_POLICY_STATS */
+
+ /*
+ * NOTE: We might want to call a forwarding strategy even with no nexthop to
+ * take a fallback decision.
+ */
+ if (nexthops_get_curlen(nexthops) == 0) return nexthops;
+
+#ifdef WITH_POLICY
+
+ /*
+ * Filter out nexthops with lowest strategy priority.
+ * Initializing at 0 allows to disable nexthops with a negative priority
+ */
+ unsigned max_priority = 0;
+ nexthops_enumerate(nexthops, i, nexthop, {
+ int priority = nexthops->state[i].priority;
+ if (priority > max_priority) max_priority = priority;
+ });
+ nexthops_enumerate(nexthops, i, nexthop, {
+ int priority = nexthops->state[i].priority;
+ nexthops_disable_if(nexthops, i, (priority < max_priority));
+ });
+
+ /*
+ * If multipath is disabled, we don't offer much choice to the forwarding
+ * strategy, but still go through it for accounting purposes.
+ */
+ hicn_policy_t policy = fib_entry_get_policy(entry);
+ if ((policy.tags[POLICY_TAG_MULTIPATH].state == POLICY_STATE_PROHIBIT) ||
+ (policy.tags[POLICY_TAG_MULTIPATH].state == POLICY_STATE_AVOID)) {
+ DEBUG(
+ "[fib_entry_get_nexthops_from_strategy] select single nexthops due to "
+ "multipath policy");
+ nexthops_select_first(nexthops);
+ }
+
+#endif /* WITH_POLICY */
+
+ // DEBUG("[fib_entry_get_nexthops_from_strategy] calling lookup_nethops "
+ // "on strategy (num=%d)", nexthops_get_len(nexthops));
+ return strategy_lookup_nexthops(&entry->strategy, nexthops, msgbuf);
+}
+
+void fib_entry_on_data(fib_entry_t *entry, nexthops_t *data_nexthops,
+ const msgbuf_t *msgbuf, Ticks pitEntryCreation,
+ Ticks objReception) {
+ assert(entry);
+ assert(data_nexthops);
+ assert(msgbuf);
+
+#ifdef WITH_POLICY_STATS
+ if (pitEntryCreation != 0) { // if pitEntryCreation we no match in the pit
+ // was found
+ const policy_stats_mgr_t *mgr =
+ forwarder_get_policy_stats_mgr(entry->forwarder);
+ Ticks rtt = objReception - pitEntryCreation;
+ policy_stats_on_data(mgr, &entry->policy_stats, &entry->policy_counters,
+ data_nexthops, msgbuf, rtt);
+ }
+#endif /* WITH_POLICY_STATS */
+
+ if (pitEntryCreation != 0 ||
+ (fib_entry_strategy_type(entry) == STRATEGY_TYPE_BESTPATH)) {
+ strategy_on_data(&entry->strategy, &entry->nexthops, data_nexthops, msgbuf,
+ pitEntryCreation, objReception);
+ }
+}
+
+void fib_entry_on_timeout(fib_entry_t *entry,
+ const nexthops_t *timeout_nexthops) {
+ assert(entry);
+ assert(timeout_nexthops);
+
+#ifdef WITH_POLICY_STATS
+ const policy_stats_mgr_t *mgr =
+ forwarder_get_policy_stats_mgr(entry->forwarder);
+ policy_stats_on_timeout(mgr, &entry->policy_counters, timeout_nexthops);
+#endif /* WITH_POLICY_STATS */
+
+ strategy_on_timeout(&entry->strategy, &entry->nexthops, timeout_nexthops);
+}
+
+const hicn_prefix_t *fib_entry_get_prefix(const fib_entry_t *entry) {
+ assert(entry);
+ return &(entry->prefix);
+}
+
+/*
+ * Return true if we have at least one local connection as next hop
+ */
+bool fib_entry_has_local_nexthop(const fib_entry_t *entry) {
+ connection_table_t *table = forwarder_get_connection_table(entry->forwarder);
+
+ nexthops_foreach(fib_entry_get_nexthops(entry), nexthop, {
+ const connection_t *conn = connection_table_at(table, nexthop);
+ /* Ignore non-local connections */
+ if (!connection_is_local(conn)) continue;
+ return true;
+ });
+ return false;
+}
+
+bool fib_entry_has_all_local_nexthops(const fib_entry_t *entry) {
+ connection_table_t *table = forwarder_get_connection_table(entry->forwarder);
+
+ int count = 0;
+ nexthops_foreach(fib_entry_get_nexthops(entry), nexthop, {
+ const connection_t *conn = connection_table_at(table, nexthop);
+ /* Ignore non-local connections */
+ if (!connection_is_local(conn)) return false;
+ count++;
+ });
+ return (count > 0);
+}
+
+#ifdef WITH_MAPME
+
+void *fib_entry_get_user_data(const fib_entry_t *entry) {
+ assert(entry);
+
+ return entry->user_data;
+}
+
+void fib_entry_set_user_data(fib_entry_t *entry, const void *user_data,
+ void (*user_data_release)(void **)) {
+ assert(entry);
+ assert(user_data);
+ assert(user_data_release);
+
+ entry->user_data = (void *)user_data;
+ entry->user_data_release = user_data_release;
+}
+
+#endif /* WITH_MAPME */
diff --git a/hicn-light/src/hicn/core/fib_entry.h b/hicn-light/src/hicn/core/fib_entry.h
new file mode 100644
index 000000000..e1e48c871
--- /dev/null
+++ b/hicn-light/src/hicn/core/fib_entry.h
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * @file fib_entry.h
+ * @brief A forwarding entry in the FIB table
+ *
+ * A Forwarding Information Base (FIB) entry (fib_entry_t) is a
+ * set of nexthops for a name. It also indicates the forwarding strategy.
+ *
+ * Each nexthop contains the ConnectionId assocaited with it. This could be
+ * something specific like a MAC address or point-to-point tunnel. Or, it
+ * could be something general like a MAC group address or ip multicast overlay.
+ *
+ * See strategy.h for a description of forwarding strategies.
+ * In short, a strategy is the algorithm used to select one or more nexthops
+ * from the set of available nexthops.
+ *
+ * Each nexthop also contains a void* to a forwarding strategy data container.
+ * This allows a strategy to keep proprietary information about each nexthop.
+ *
+ *
+ */
+
+#ifndef fib_entry_h
+#define fib_entry_h
+
+#include <hicn/name.h>
+#include "strategy.h"
+#include "msgbuf.h"
+#include "nexthops.h"
+#include "policy_stats.h"
+
+typedef struct {
+ hicn_prefix_t prefix;
+ unsigned refcount;
+ nexthops_t nexthops;
+
+ /* This is used for producer prefixes only */
+ uint32_t nexthops_hash;
+
+ strategy_entry_t strategy;
+
+ const void *forwarder;
+
+#ifdef WITH_POLICY
+ hicn_policy_t policy;
+#endif /* WITH_POLICY */
+
+ policy_counters_t policy_counters;
+ policy_stats_t policy_stats;
+
+#ifdef WITH_MAPME
+#if 0
+ /* In case of no multipath, this stores the previous decision taken by policy.
+ * As the list of nexthops is not expected to change, we can simply store the
+ * flags */
+ uint_fast32_t prev_nexthops_flags;
+#endif
+ void *user_data;
+ void (*user_data_release)(void **user_data);
+#endif /* WITH_MAPME */
+} fib_entry_t;
+
+#define _fib_entry_var(x) _fib_entry_##x
+
+#define fib_entry_strategy_type(fib_entry) ((fib_entry)->strategy.type)
+
+#define fib_entry_get_nexthops(fib_entry) (&(fib_entry)->nexthops)
+
+#define fib_entry_nexthops_len(fib_entry) \
+ (nexthops_get_len(&(fib_entry)->nexthops))
+#define fib_entry_nexthops_curlen(fib_entry) \
+ (nexthops_curlen(&(fib_entry)->nexthops))
+#define fib_entry_get_nexthop(fib_entry, i) ((fib_entry)->nexthops.elts[i])
+#define fib_entry_foreach_nexthop(fib_entry, nexthop, BODY) \
+ nexthops_foreach(fib_entry->nexthops, BODY)
+
+#define fib_entry_get_nexthops_hash(E) ((E)->nexthops_hash)
+#define fib_entry_set_nexthops_hash(E, H) (E)->nexthops_hash = (H)
+
+static inline void fib_entry_set_nexthops(fib_entry_t *entry,
+ nexthops_t *nexthops) {
+ entry->nexthops = *nexthops;
+}
+
+static inline void fib_entry_initialize_nexthops(fib_entry_t *entry) {
+ entry->nexthops = NEXTHOPS_EMPTY;
+}
+
+static inline bool fib_entry_nexthops_changed(fib_entry_t *entry,
+ nexthops_t *nexthops) {
+ uint32_t old_hash = fib_entry_get_nexthops_hash(entry);
+ uint32_t hash = nexthops_get_hash(nexthops);
+ if (hash != old_hash) {
+ fib_entry_set_nexthops_hash(entry, hash);
+ return true;
+ }
+ return false;
+};
+
+struct forwarder_s;
+
+/*
+ * This does a copy of the name passed as parameter
+ */
+fib_entry_t *fib_entry_create(const hicn_prefix_t *prefix,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options,
+ const struct forwarder_s *table);
+
+void fib_entry_free(fib_entry_t *entry);
+
+void fib_entry_add_strategy_options(fib_entry_t *entry,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options);
+
+void fib_entry_set_strategy(fib_entry_t *fib_entry,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options);
+
+void fib_entry_nexthops_add(fib_entry_t *fib_entry, unsigned nexthop);
+
+void fib_entry_nexthops_remove(fib_entry_t *fib_entry, unsigned nexthop);
+
+/**
+ * @function fib_entry_nexthops_get
+ * @abstract Returns the nexthop set of the FIB entry. You must Acquire if it
+ * will be saved.
+ * @discussion
+ * Returns the next hop set for the FIB entry.
+ */
+const nexthops_t *fib_entry_nexthops_get(const fib_entry_t *fib_entry);
+
+const nexthops_t *fib_entry_nexthops_getFromForwardingStrategy(
+ fib_entry_t *fib_entry, const msgbuf_t *interest_msgbuf,
+ bool is_retransmission);
+
+void fib_entry_on_data(fib_entry_t *fib_entry, nexthops_t *nexthops,
+ const msgbuf_t *object_msgbuf, Ticks pit_entry_creation,
+ Ticks data_reception);
+
+#ifdef WITH_POLICY
+hicn_policy_t fib_entry_get_policy(const fib_entry_t *fib_entry);
+void fib_entry_reconsider_policy(fib_entry_t *fib_entry);
+void fib_entry_set_policy(fib_entry_t *fib_entry, hicn_policy_t policy);
+void fib_entry_update_stats(fib_entry_t *fib_entry, uint64_t now);
+#endif /* WITH_POLICY */
+
+nexthops_t *fib_entry_filter_nexthops(fib_entry_t *entry, nexthops_t *nexthops,
+ unsigned ingress_id, bool prefer_local);
+
+nexthops_t *fib_entry_get_mapme_nexthops(fib_entry_t *entry,
+ nexthops_t *new_nexthops);
+
+nexthops_t *fib_entry_get_available_nexthops(fib_entry_t *fib_entry,
+ unsigned in_connection,
+ nexthops_t *new_nexthops);
+void fib_entry_on_timeout(fib_entry_t *fib_entry, const nexthops_t *egressId);
+nexthops_t *fib_entry_get_nexthops_from_strategy(
+ fib_entry_t *fib_entry, const msgbuf_t *interest_msgbuf,
+ bool is_retransmission);
+
+/**
+ * @function fib_entry_get_prefix
+ * @return The FIB entry prefix
+ */
+const hicn_prefix_t *fib_entry_get_prefix(const fib_entry_t *fib_entry);
+
+bool fib_entry_has_local_nexthop(const fib_entry_t *entry);
+bool fib_entry_has_all_local_nexthops(const fib_entry_t *entry);
+
+#ifdef WITH_MAPME
+
+/**
+ * @function fib_entry_get_user_data
+ * @abstract Returns user data associated to the FIB entry.
+ * @param [in] fib_entry - Pointer to the FIB entry.
+ * @return User data as a void pointer
+ */
+void *fib_entry_get_user_data(const fib_entry_t *fib_entry);
+
+/**
+ * @function fib_entry_get_user_data
+ * @abstract Associates user data and release callback to a FIB entry.
+ * @param [in] fib_entry - Pointer to the FIB entry.
+ * @param [in] user_data - Generic pointer to user data
+ * @param [in@ user_data_release - Callback used to release user data upon
+ * change of FIB entry removal.
+ */
+void fib_entry_set_user_data(fib_entry_t *fib_entry, const void *user_data,
+ void (*user_data_release)(void **));
+
+#endif /* WITH_MAPME */
+
+#endif // fib_entry_h
diff --git a/hicn-light/src/hicn/core/forwarder.c b/hicn-light/src/hicn/core/forwarder.c
index 94e8cc885..8c276bfef 100644
--- a/hicn-light/src/hicn/core/forwarder.c
+++ b/hicn-light/src/hicn/core/forwarder.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,6 +23,20 @@
* the event scheduler
*/
+/* Bypass FIB and send packet one by one */
+//#define BYPASS_FIB 1
+
+/* Send packets one by one : only effective if FIB is not bypassed */
+//#define USE_SEND_PACKET 1
+
+/* Batch sending: only if the previous option is undefined */
+#define USE_QUEUE true
+
+/* Shall we send mapme updates to advertise all local prefixes on newly created
+ * faces
+ */
+//#define ADVERTISE_PREFIXES_ON_NEW_FACES
+
#ifndef _WIN32
#include <arpa/inet.h>
#include <sys/socket.h>
@@ -30,8 +44,7 @@
#endif
#include <errno.h>
#include <fcntl.h>
-#include <signal.h>
-#include <hicn/hicn-light/config.h>
+//#include <hicn/hicn-light/config.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -41,90 +54,71 @@
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-#include <parc/logging/parc_LogReporterTextStdout.h>
-
-#include <hicn/core/connectionManager.h>
-#include <hicn/core/connectionTable.h>
-#include <hicn/core/dispatcher.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/core/messagePacketType.h>
+#include "connection_table.h"
+#include "fib.h"
+#include "forwarder.h"
+#include "listener_table.h"
#ifdef WITH_MAPME
-#include <hicn/core/mapme.h>
+#include "mapme.h"
#endif /* WITH_MAPME */
-#include <hicn/config/configuration.h>
-#include <hicn/config/configurationFile.h>
-#include <hicn/config/configurationListeners.h>
-#include <hicn/processor/messageProcessor.h>
+#include "msgbuf.h"
+#include "msgbuf_pool.h"
+#include "packet_cache.h"
+#include "../config/configuration.h"
+// #include "../config/configuration_file.h"
+#include "../config/commands.h"
+#include "../io/base.h" // MAX_MSG
+
+#ifdef WITH_POLICY_STATS
+#include <hicn/core/policy_stats.h>
+#endif /* WITH_POLICY_STATS */
#include <hicn/core/wldr.h>
+#include <hicn/interest_manifest.h>
+#include <hicn/util/log.h>
-#include <parc/assert/parc_Assert.h>
-
-// the router's clock frequency (we now use the monotonic clock)
-#define HZ 1000
-
-// these will all be a little off because its all integer division
-#define MSEC_PER_TICK (1000 / HZ)
-#define USEC_PER_TICK (1000000 / HZ)
-#define NSEC_PER_TICK ((1000000000ULL) / HZ)
-#define MSEC_TO_TICKS(msec) \
- ((msec < FC_MSEC_PER_TICK) ? 1 : msec / FC_MSEC_PER_TICK)
-#define NSEC_TO_TICKS(nsec) ((nsec < NSEC_PER_TICK) ? 1 : nsec / NSEC_PER_TICK)
+struct forwarder_s {
+ // uint16_t server_port;
-struct forwarder {
- Dispatcher *dispatcher;
-
- uint16_t server_port;
+ // used by seed48 and nrand48
+ unsigned short seed[3];
- PARCEventSignal *signal_int;
- PARCEventSignal *signal_term;
-#ifndef _WIN32
- PARCEventSignal *signal_usr1;
-#endif
- PARCEventTimer *keepalive_event;
+ connection_table_t *connection_table;
+ listener_table_t *listener_table;
+ configuration_t *config;
- // will skew the virtual clock forward. In normal operaiton, it is 0.
- Ticks clockOffset;
+ pkt_cache_t *pkt_cache;
+ fib_t *fib;
+ msgbuf_pool_t *msgbuf_pool;
- unsigned nextConnectionid;
- Messenger *messenger;
- ConnectionManager *connectionManager;
- ConnectionTable *connectionTable;
- ListenerSet *listenerSet;
- Configuration *config;
+#ifdef WITH_MAPME
+ mapme_t *mapme;
+#endif /* WITH_MAPME */
- // we'll eventually want to setup a threadpool of these
- MessageProcessor *processor;
+ bool store_in_cs;
+ bool serve_from_cs;
- Logger *logger;
+ forwarder_stats_t stats;
+#ifdef WITH_POLICY_STATS
+ policy_stats_mgr_t policy_stats_mgr;
+#endif /* WITH_POLICY_STATS */
- PARCClock *clock;
+ /*
+ * The message forwarder has to decide whether to queue incoming packets for
+ * batching, or trigger the transmission on the connection
+ */
+ unsigned *pending_conn;
-#if !defined(__APPLE__)
- hicn_socket_helper_t
- *hicnSocketHelper; // state required to manage hicn connections
-#endif
- // used by seed48 and nrand48
- unsigned short seed[3];
+ subscription_table_t *subscriptions;
-#ifdef WITH_MAPME
- MapMe *mapme;
-#endif /* WITH_MAPME */
+ // Used to store the msgbufs that need to be released
+ off_t *acquired_msgbuf_ids;
};
-// signal traps through the event scheduler
-static void _signal_cb(int, PARCEventType, void *);
-
-// A no-op keepalive to prevent Libevent from exiting the dispatch loop
-static void _keepalive_cb(int, PARCEventType, void *);
-
/**
* Reseed our pseudo-random number generator.
*/
-static void forwarder_Seed(Forwarder *forwarder) {
+static void forwarder_seed(forwarder_t *forwarder) {
#ifndef _WIN32
int fd;
ssize_t res;
@@ -150,452 +144,1533 @@ static void forwarder_Seed(Forwarder *forwarder) {
#endif
}
-Logger *forwarder_GetLogger(const Forwarder *forwarder) {
- return forwarder->logger;
-}
+forwarder_t *forwarder_create(configuration_t *configuration) {
+ forwarder_t *forwarder = malloc(sizeof(forwarder_t));
+ if (!forwarder) goto ERR_MALLOC;
-// ============================================================================
-// Setup and destroy section
+ forwarder_seed(forwarder);
+ srand(forwarder->seed[0] ^ forwarder->seed[1] ^ forwarder->seed[2]);
-Forwarder *forwarder_Create(Logger *logger) {
- Forwarder *forwarder = parcMemory_AllocateAndClear(sizeof(Forwarder));
- parcAssertNotNull(forwarder, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Forwarder));
- memset(forwarder, 0, sizeof(Forwarder));
- forwarder_Seed(forwarder);
+ forwarder->config = configuration;
- forwarder->clock = parcClock_Monotonic();
- forwarder->clockOffset = 0;
+ forwarder->listener_table = listener_table_create();
+ if (!forwarder->listener_table) goto ERR_LISTENER_TABLE;
- if (logger) {
- forwarder->logger = logger_Acquire(logger);
- logger_SetClock(forwarder->logger, forwarder->clock);
- } else {
- PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
- forwarder->logger = logger_Create(reporter, forwarder->clock);
- parcLogReporter_Release(&reporter);
- }
+ forwarder->connection_table = connection_table_create();
+ if (!forwarder->connection_table) goto ERR_CONNECTION_TABLE;
- forwarder->nextConnectionid = 1;
- forwarder->dispatcher = dispatcher_Create(forwarder->logger);
- forwarder->messenger = messenger_Create(forwarder->dispatcher);
- forwarder->connectionManager = connectionManager_Create(forwarder);
- forwarder->connectionTable = connectionTable_Create();
- forwarder->listenerSet = listenerSet_Create();
- forwarder->config = configuration_Create(forwarder);
- forwarder->processor = messageProcessor_Create(forwarder);
-
- forwarder->signal_term = dispatcher_CreateSignalEvent(
- forwarder->dispatcher, _signal_cb, forwarder, SIGTERM);
- dispatcher_StartSignalEvent(forwarder->dispatcher, forwarder->signal_term);
-
- forwarder->signal_int = dispatcher_CreateSignalEvent(
- forwarder->dispatcher, _signal_cb, forwarder, SIGINT);
- dispatcher_StartSignalEvent(forwarder->dispatcher, forwarder->signal_int);
-#ifndef _WIN32
- forwarder->signal_usr1 = dispatcher_CreateSignalEvent(
- forwarder->dispatcher, _signal_cb, forwarder, SIGPIPE);
- dispatcher_StartSignalEvent(forwarder->dispatcher, forwarder->signal_usr1);
-#endif
+ forwarder->fib = fib_create(forwarder);
+ if (!forwarder->fib) goto ERR_FIB;
-#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(_WIN32) && \
- defined(PUNTING)
- forwarder->hicnSocketHelper = hicn_create();
- if (!forwarder->hicnSocketHelper)
- goto ERR_SOCKET;
-#endif /* __APPLE__ */
-
-#ifdef WITH_MAPME
- if (!(mapme_create(&forwarder->mapme, forwarder)))
- goto ERR_MAPME;
-#endif /* WITH_MAPME */
+ forwarder->msgbuf_pool = msgbuf_pool_create();
+ if (!forwarder->msgbuf_pool) goto ERR_PACKET_POOL;
+ size_t objectStoreSize = configuration_get_cs_size(configuration);
+ forwarder->pkt_cache = pkt_cache_create(objectStoreSize);
+ if (!forwarder->pkt_cache) goto ERR_PKT_CACHE;
- /* ignore child */
-#ifndef _WIN32
- signal(SIGCHLD, SIG_IGN);
+ forwarder->subscriptions = subscription_table_create();
+ if (!forwarder->subscriptions) goto ERR_SUBSCRIPTION;
- /* ignore tty signals */
- signal(SIGTSTP, SIG_IGN);
- signal(SIGTTOU, SIG_IGN);
- signal(SIGTTIN, SIG_IGN);
-#endif
+ // the two flags for the cs are set to true by default. If the cs
+ // is active it always work as expected unless the use modifies this
+ // values using controller
+ if (objectStoreSize != 0) {
+ forwarder->store_in_cs = true;
+ forwarder->serve_from_cs = true;
+ }
- // We no longer use this for ticks, but we need to have at least one event
- // schedule to keep Libevent happy.
+#ifdef WITH_MAPME
+ forwarder->mapme = mapme_create(forwarder);
+ if (!forwarder->mapme) goto ERR_MAPME;
+#endif /* WITH_MAPME */
- struct timeval wtnow_timeout;
- timerclear(&wtnow_timeout);
+#ifdef WITH_POLICY_STATS
+ if (policy_stats_mgr_initialize(&forwarder->policy_stats_mgr, forwarder) < 0)
+ goto ERR_MGR;
+#endif /* WITH_POLICY_STATS */
- wtnow_timeout.tv_sec = 0;
- wtnow_timeout.tv_usec = 50000; // 20 Hz keepalive
+ memset(&forwarder->stats, 0, sizeof(forwarder_stats_t));
+ vector_init(forwarder->pending_conn, MAX_MSG, 0);
+ vector_init(forwarder->acquired_msgbuf_ids, MAX_MSG, 0);
- PARCEventScheduler *base =
- dispatcher_GetEventScheduler(forwarder->dispatcher);
- forwarder->keepalive_event = parcEventTimer_Create(
- base, PARCEventType_Persist, _keepalive_cb, (void *)forwarder);
- parcEventTimer_Start(forwarder->keepalive_event, &wtnow_timeout);
+ char *n_suffixes_per_split_str = getenv("N_SUFFIXES_PER_SPLIT");
+ if (n_suffixes_per_split_str)
+ configuration_set_suffixes_per_split(forwarder_get_configuration(forwarder),
+ atoi(n_suffixes_per_split_str));
return forwarder;
+ERR_MGR:
#ifdef WITH_MAPME
ERR_MAPME:
#endif /* WITH_MAPME */
-#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(_WIN32) && \
- defined(PUNTING)
- hicn_free(forwarder->hicnSocketHelper);
-ERR_SOCKET:
-#endif
- listenerSet_Destroy(&(forwarder->listenerSet));
- connectionManager_Destroy(&(forwarder->connectionManager));
- connectionTable_Destroy(&(forwarder->connectionTable));
- messageProcessor_Destroy(&(forwarder->processor));
- configuration_Destroy(&(forwarder->config));
- messenger_Destroy(&(forwarder->messenger));
-
- dispatcher_DestroySignalEvent(forwarder->dispatcher,
- &(forwarder->signal_int));
- dispatcher_DestroySignalEvent(forwarder->dispatcher,
- &(forwarder->signal_term));
-#ifndef _WIN32
- dispatcher_DestroySignalEvent(forwarder->dispatcher,
- &(forwarder->signal_usr1));
-#endif
-
- parcClock_Release(&forwarder->clock);
- logger_Release(&forwarder->logger);
-
- // do the dispatcher last
- dispatcher_Destroy(&(forwarder->dispatcher));
- parcMemory_Deallocate((void **)&forwarder);
+ERR_SUBSCRIPTION:
+ subscription_table_free(forwarder->subscriptions);
+ERR_PKT_CACHE:
+ pkt_cache_free(forwarder->pkt_cache);
+
+ msgbuf_pool_free(forwarder->msgbuf_pool);
+ERR_PACKET_POOL:
+ fib_free(forwarder->fib);
+ERR_FIB:
+ connection_table_free(forwarder->connection_table);
+ERR_CONNECTION_TABLE:
+ listener_table_free(forwarder->listener_table);
+ERR_LISTENER_TABLE:
+ free(forwarder);
+ERR_MALLOC:
return NULL;
}
-void forwarder_Destroy(Forwarder **ptr) {
- parcAssertNotNull(ptr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*ptr, "Parameter must dereference to non-null pointer");
- Forwarder *forwarder = *ptr;
-#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(_WIN32) && \
- defined(PUNTING)
- hicn_free(forwarder->hicnSocketHelper);
-#endif
- parcEventTimer_Destroy(&(forwarder->keepalive_event));
-
- listenerSet_Destroy(&(forwarder->listenerSet));
- connectionManager_Destroy(&(forwarder->connectionManager));
- connectionTable_Destroy(&(forwarder->connectionTable));
- messageProcessor_Destroy(&(forwarder->processor));
- configuration_Destroy(&(forwarder->config));
+void forwarder_free(forwarder_t *forwarder) {
+ assert(forwarder);
- // the messenger is used by many of the other pieces, so destroy it last
- messenger_Destroy(&(forwarder->messenger));
+ policy_stats_mgr_finalize(&forwarder->policy_stats_mgr);
#ifdef WITH_MAPME
mapme_free(forwarder->mapme);
#endif /* WITH_MAPME */
- dispatcher_DestroySignalEvent(forwarder->dispatcher,
- &(forwarder->signal_int));
- dispatcher_DestroySignalEvent(forwarder->dispatcher,
- &(forwarder->signal_term));
-#ifndef _WIN32
- dispatcher_DestroySignalEvent(forwarder->dispatcher,
- &(forwarder->signal_usr1));
-#endif
+ pkt_cache_free(forwarder->pkt_cache);
+ msgbuf_pool_free(forwarder->msgbuf_pool);
+ fib_free(forwarder->fib);
+ connection_table_free(forwarder->connection_table);
+ listener_table_free(forwarder->listener_table);
+ subscription_table_free(forwarder->subscriptions);
+ configuration_free(forwarder->config);
+ vector_free(forwarder->pending_conn);
+ vector_free(forwarder->acquired_msgbuf_ids);
+ free(forwarder);
+}
+
+/*
+ * An event occurred that might trigger an update of the FIB cache. It is
+ * possible that the flags have been reset following a connection add or remote.
+ * The objective of this function is to prepare the cache entry, and to alert of
+ * any change for both consumer and producer prefixes.
+ */
+void forwarder_on_route_event(const forwarder_t *forwarder,
+ fib_entry_t *entry) {
+ commands_notify_route(forwarder, entry);
+
+#ifdef ADVERTISE_PREFIXES_ON_NEW_FACES
+ nexthops_t new_nexthops = NEXTHOPS_EMPTY;
+#endif /* ADVERTISE_PREFIXES_ON_NEW_FACES */
+
+ nexthops_t *nexthops = NULL;
+ char *prefix_type_s;
+
+ const connection_table_t *table =
+ forwarder_get_connection_table(entry->forwarder);
+
+ const hicn_prefix_t *prefix = fib_entry_get_prefix(entry);
+
+ WITH_INFO({
+ char buf[MAXSZ_HICN_PREFIX];
+ hicn_prefix_snprintf(buf, MAXSZ_HICN_NAME, prefix);
+ INFO("fib_entry_on_event: %s", buf);
+ )};
+
+ if (!fib_entry_has_local_nexthop(entry)) {
+ /* Recompute FIB cache, then check whether it has changed based on hash */
+ prefix_type_s = "consumer";
+ nexthops = fib_entry_get_nexthops(entry);
+ nexthops_reset(nexthops);
+ fib_entry_filter_nexthops(entry, nexthops, ~0, false);
+#ifdef ADVERTISE_PREFIXES_ON_NEW_FACES
+ } else {
+ /* Check available non-local connections (on which we would send MAP-Me
+ * updates */
+ prefix_type_s = "producer";
+
+ nexthops = fib_entry_get_mapme_nexthops(entry, &new_nexthops);
+ fib_entry_filter_nexthops(entry, nexthops, ~0, true);
+
+#ifdef WITH_MAPME
+ mapme_set_adjacencies(forwarder->mapme, entry, nexthops, NULL);
+#endif /* WITH_MAPME */
+#endif /* ADVERTISE_PREFIXES_ON_NEW_FACES */
+ }
+
+ if (!nexthops)
+ return;
- parcClock_Release(&forwarder->clock);
- logger_Release(&forwarder->logger);
+ if (!fib_entry_nexthops_changed(entry, nexthops)) return;
- // do the dispatcher last
- dispatcher_Destroy(&(forwarder->dispatcher));
+ /* Send notification */
+ WITH_INFO({
+ char buf[MAXSZ_HICN_PREFIX];
+ hicn_prefix_snprintf(buf, MAXSZ_HICN_NAME, prefix);
+ INFO("Active interfaces changed for %s prefix %s", prefix_type_s, buf);
+ });
- parcMemory_Deallocate((void **)&forwarder);
- *ptr = NULL;
+ netdevice_flags_t flags = NETDEVICE_FLAGS_EMPTY;
+ nexthops_foreach(nexthops, nh, {
+ connection_t *connection = connection_table_get_by_id(table, nh);
+ netdevice_flags_add(flags, connection_get_interface_type(connection));
+ });
+
+ hicn_ip_prefix_t ip_prefix;
+ hicn_prefix_get_ip_prefix(prefix, &ip_prefix);
+ commands_notify_active_interface_update(forwarder, &ip_prefix, flags);
}
-void forwarder_SetupAllListeners(Forwarder *forwarder, uint16_t port,
- const char *localPath) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
+int forwarder_add_connection(const forwarder_t *forwarder,
+ const char *symbolic_name, face_type_t type,
+ address_pair_t *pair, policy_tags_t tags,
+ int priority, face_state_t admin_state) {
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ connection_t *connection = connection_table_get_by_pair(table, pair);
+
+ if (!connection) {
+ connection = connection_create(type, symbolic_name, pair, forwarder);
+ if (!connection) {
+ ERROR("Failed to create %s connection", face_type_str(type));
+ return -1;
+ }
+
+ } else {
+ WARN("Connection already exists");
+ }
+
+#ifdef WITH_POLICY
+ connection_set_tags(connection, tags);
+ connection_set_priority(connection, priority);
+#endif /* WITH_POLICY */
- configurationListeners_SetupAll(forwarder->config, port, localPath);
+ connection_set_admin_state(connection, admin_state);
+ return 0;
}
-void forwarder_SetupLocalListeners(Forwarder *forwarder, uint16_t port) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- configurationListeners_SetutpLocalIPv4(forwarder->config, port);
+int forwarder_remove_connection(const forwarder_t *forwarder,
+ unsigned connection_id, bool finalize) {
+ /* Remove connection from the FIB */
+ forwarder_remove_connection_id_from_routes(forwarder, connection_id);
+
+ /* Remove connection */
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+
+ /* Hook: connection deleted through the control protocol */
+ connection_t *connection = connection_table_at(table, connection_id);
+ forwarder_on_connection_event(forwarder, connection, CONNECTION_EVENT_DELETE);
+
+ connection_table_remove_by_id(table, connection_id);
+ if (finalize) connection_finalize(connection);
+
+ return 0;
}
-void forwarder_SetupFromConfigFile(Forwarder *forwarder, const char *filename) {
- ConfigurationFile *configFile = configurationFile_Create(forwarder, filename);
- if (configFile) {
- configurationFile_Process(configFile);
- configurationFile_Release(&configFile);
- }
+/*
+ * This is currently called from commands.c for every command sent to update
+ * a connection.
+ */
+void forwarder_on_connection_event(const forwarder_t *forwarder,
+ const connection_t *connection,
+ connection_event_t event) {
+ assert(connection);
+
+ commands_notify_connection(forwarder, event, connection);
+
+ unsigned conn_id = connection_get_id(connection);
+
+ /* We need to send a MapMe update on the newly selected connections for
+ * each concerned fib_entry : connection is involved, or no more involved */
+ fib_t *fib = forwarder_get_fib(forwarder);
+ fib_foreach_entry(fib, entry, {
+ const nexthops_t *nexthops = fib_entry_get_nexthops(entry);
+
+ if (!fib_entry_has_local_nexthop(entry)) {
+ /* Consumer prefix */
+ /*
+ * A new connection has no impact until it is added to FIB, which will
+ * be handled in a route event
+ */
+ if (event == CONNECTION_EVENT_CREATE) break;
+
+ /*
+ * For each FIB entry, trigger an event only if the connection is part
+ * of nexthops */
+ // XXX Replace this by a function
+ nexthops_foreach(nexthops, nexthop, {
+ if (nexthop != conn_id) continue;
+ forwarder_on_route_event(forwarder, entry);
+ break;
+ });
+ } else {
+ /* Producer prefix */
+ if (connection_is_local(connection)) break;
+
+ // XXX we could optimize event more
+ forwarder_on_route_event(forwarder, entry);
+ }
+ });
+}
+
+void forwarder_setup_local_listeners(forwarder_t *forwarder, uint16_t port) {
+ assert(forwarder);
+ listener_setup_local(forwarder, port);
}
-Configuration *forwarder_GetConfiguration(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
+configuration_t *forwarder_get_configuration(forwarder_t *forwarder) {
+ assert(forwarder);
return forwarder->config;
}
-// ============================================================================
+subscription_table_t *forwarder_get_subscriptions(
+ const forwarder_t *forwarder) {
+ return forwarder->subscriptions;
+}
+
+connection_table_t *forwarder_get_connection_table(
+ const forwarder_t *forwarder) {
+ assert(forwarder);
+ return forwarder->connection_table;
+}
-unsigned forwarder_GetNextConnectionId(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return forwarder->nextConnectionid++;
+listener_table_t *forwarder_get_listener_table(const forwarder_t *forwarder) {
+ assert(forwarder);
+ return forwarder->listener_table;
}
-Messenger *forwarder_GetMessenger(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return forwarder->messenger;
+pkt_cache_t *forwarder_get_pkt_cache(const forwarder_t *forwarder) {
+ assert(forwarder);
+ return forwarder->pkt_cache;
}
-Dispatcher *forwarder_GetDispatcher(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return forwarder->dispatcher;
+void forwarder_cs_set_store(forwarder_t *forwarder, bool val) {
+ assert(forwarder);
+ forwarder->store_in_cs = val;
}
-#ifdef WITH_POLICY
-ConnectionTable *forwarder_GetConnectionTable(const Forwarder *forwarder) {
-#else
-ConnectionTable *forwarder_GetConnectionTable(Forwarder *forwarder) {
-#endif /* WITH_POLICY */
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return forwarder->connectionTable;
+bool forwarder_cs_get_store(forwarder_t *forwarder) {
+ assert(forwarder);
+ return forwarder->store_in_cs;
}
-ListenerSet *forwarder_GetListenerSet(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return forwarder->listenerSet;
+void forwarder_cs_set_serve(forwarder_t *forwarder, bool val) {
+ assert(forwarder);
+ forwarder->serve_from_cs = val;
}
-void forwarder_SetChacheStoreFlag(Forwarder *forwarder, bool val) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- messageProcessor_SetCacheStoreFlag(forwarder->processor, val);
+bool forwarder_cs_get_serve(forwarder_t *forwarder) {
+ assert(forwarder);
+ return forwarder->serve_from_cs;
}
-bool forwarder_GetChacheStoreFlag(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return messageProcessor_GetCacheStoreFlag(forwarder->processor);
+void forwarder_cs_set_size(forwarder_t *forwarder, size_t size) {
+ assert(forwarder);
+
+ if (pkt_cache_set_cs_size(forwarder->pkt_cache, size) < 0) {
+ ERROR(
+ "Unable to resize the CS: provided maximum size (%u) is smaller than "
+ "the number of elements currently stored in the CS (%u). Clear the "
+ "CS "
+ "and retry.",
+ size, pkt_cache_get_cs_size(forwarder->pkt_cache));
+ }
}
-void forwarder_SetChacheServeFlag(Forwarder *forwarder, bool val) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- messageProcessor_SetCacheServeFlag(forwarder->processor, val);
+size_t forwarder_cs_get_size(forwarder_t *forwarder) {
+ assert(forwarder);
+ return pkt_cache_get_cs_size(forwarder->pkt_cache);
}
-bool forwarder_GetChacheServeFlag(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return messageProcessor_GetCacheServeFlag(forwarder->processor);
+size_t forwarder_cs_get_num_stale_entries(forwarder_t *forwarder) {
+ assert(forwarder);
+ return pkt_cache_get_num_cs_stale_entries(forwarder->pkt_cache);
}
-void forwarder_ReceiveCommand(Forwarder *forwarder, command_id command,
- struct iovec *message, unsigned ingressId) {
- configuration_ReceiveCommand(forwarder->config, command, message, ingressId);
+void forwarder_cs_clear(forwarder_t *forwarder) {
+ assert(forwarder);
+
+ pkt_cache_cs_clear(forwarder->pkt_cache);
}
-void forwarder_Receive(Forwarder *forwarder, Message *message) {
- parcAssertNotNull(forwarder, "Parameter hicn-light must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
+/**
+ * @function forwarder_Drop
+ * @abstract Whenever we "drop" a message, increment counters
+ * @discussion
+ * This is a bookkeeping function. It increments the appropriate counters.
+ *
+ * The default action for a message is to destroy it in
+ * <code>forwarder_Receive()</code>, so this function does not need to do
+ * that.
+ *
+ */
+static ssize_t forwarder_drop(forwarder_t *forwarder, off_t msgbuf_id) {
+ forwarder->stats.countDropped++;
+
+ const msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ const msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
- // this takes ownership of the message, so we're done here
+ switch (msgbuf_get_type(msgbuf)) {
+ case HICN_PACKET_TYPE_INTEREST:
+ forwarder->stats.countInterestsDropped++;
+ break;
- // this are the checks needed to implement WLDR. We set wldr only on the STAs
- // and we let the AP to react according to choise of the client.
- // if the STA enables wldr using the set command, the AP enable wldr as well
- // otherwise, if the STA disable it the AP remove wldr
- // WLDR should be enabled only on the STAs using the command line
- // TODO
- // disable WLDR command line on the AP
- const Connection *conn = connectionTable_FindById(
- forwarder->connectionTable, message_GetIngressConnectionId(message));
+ case HICN_PACKET_TYPE_DATA:
+ forwarder->stats.countObjectsDropped++;
+ break;
+
+ default:
+ forwarder->stats.countOtherDropped++;
+ break;
+ }
+
+ return msgbuf_get_len(msgbuf);
+ // dont destroy message here, its done at end of receive
+}
+
+#ifndef BYPASS_FIB
+/*
+ * If the hoplimit is equal to 0, then we may only forward it to local
+ * applications. Otherwise, we may forward it off the system.
+ *
+ */
+
+static ssize_t forwarder_forward_via_connection(forwarder_t *forwarder,
+ off_t msgbuf_id,
+ unsigned conn_id) {
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+
+ const msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+
+ connection_t *conn = connection_table_get_by_id(table, conn_id);
if (!conn) {
- /*
- * Drop is a static method in messageProcessor which might or might not need
- * to be called for accounting purposes. This call was initially absent so
- * the behaviour was kept like this, as this situation is unlikely. We need
- * to release memory though, as this is not done in Drop anyways.
- */
- //messageProcessor_Drop(forwarder->processor, message);
- message_Release(&message);
- return;
+ forwarder->stats.countDroppedConnectionNotFound++;
+ WARN("forward msgbuf %lu to interface %u not found (count %u)", msgbuf_id,
+ conn_id, forwarder->stats.countDroppedConnectionNotFound);
+ return forwarder_drop(forwarder, msgbuf_id);
}
- if (message_HasWldr(message)) {
- if (connection_HasWldr(conn)) {
+ /* Always queue the packet... */
+ // DEBUG("Queueing packet\n");
+
+#if defined(USE_SEND_PACKET) || !defined(__linux__)
+
+ // Here we need to update the path label of a data packet before send
+ // it. The path label update can be done here because the packet is sent
+ // directly to the socket
+ if (msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA)
+ msgbuf_update_pathlabel(msgbuf, connection_get_id(conn));
+
+ bool success = connection_send_packet(conn, msgbuf_get_packet(msgbuf),
+ msgbuf_get_len(msgbuf));
+#else
+
+ // In this case we cannot update the path label even if it is need because
+ // the packet is not copied and only the packet id is enqueued to the ring
+ // buffer associated the output interface. If the path label is updated here
+ // all data packets get delivered to the next hop with the same label that is
+ // associated to the last connection used. For this reason the path label
+ // update must be done before the packet is actually sent inside the different
+ // IO implementations.
+ bool success = connection_send(conn, msgbuf_id, USE_QUEUE);
+
+#endif
+
+ /* ... and mark the connection as pending if this is not yet the case */
+ if (!vector_contains(forwarder->pending_conn, conn_id))
+ vector_push(forwarder->pending_conn, conn_id);
+
+ if (!success) {
+ forwarder->stats.countSendFailures++;
+
+ DEBUG("forward msgbuf %llu to interface %u send failure (count %u)",
+ msgbuf_id, conn_id, forwarder->stats.countSendFailures);
+ return forwarder_drop(forwarder, msgbuf_id);
+ }
+
+ switch (msgbuf_get_type(msgbuf)) {
+ case HICN_PACKET_TYPE_INTEREST:
+ forwarder->stats.countInterestForwarded++;
+ break;
+
+ case HICN_PACKET_TYPE_DATA:
+ forwarder->stats.countObjectsForwarded++;
+ break;
+
+ default:
+ break;
+ }
+
+ TRACE("forward msgbuf %p (size=%u) to interface %u", msgbuf,
+ msgbuf_get_len(msgbuf), conn_id);
+ return msgbuf_get_len(msgbuf);
+}
+
+/**
+ * @function forwarder_forward_to_nexthops
+ * @abstract Try to forward to each nexthop listed in the NumberSet
+ * @discussion
+ * Will not forward to the ingress connection.
+ *
+ * @return The number of nexthops tried
+ */
+static unsigned forwarder_forward_to_nexthops(forwarder_t *forwarder,
+ off_t msgbuf_id,
+ const nexthops_t *nexthops) {
+ // DEBUG("[forwarder_forward_to_nexthops] num=%d/%d",
+ // nexthops_get_curlen(nexthops), nexthops_get_len(nexthops));
+ unsigned forwardedCopies = 0;
+
+ const msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+ unsigned ingressId = msgbuf_get_connection_id(msgbuf);
+
+ nexthops_foreach(nexthops, nexthop, {
+ // DEBUG("[forwarder_forward_to_nexthops] - nexthop = %d");
+ if (nexthop == ingressId) continue;
+
+ forwardedCopies++;
+ // INFO("[forwarder_forward_to_nexthops] - nexthop = %d OK", nexthop);
+ forwarder_forward_via_connection(forwarder, msgbuf_id, nexthop);
+ });
+
+ return forwardedCopies;
+}
+
+static bool forwarder_forward_via_fib(forwarder_t *forwarder, off_t msgbuf_id,
+ pkt_cache_verdict_t verdict,
+ pkt_cache_entry_t *entry) {
+ assert(forwarder && entry && msgbuf_id_is_valid(msgbuf_id));
+
+ bool ret = true;
+
+ const msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_INTEREST);
+
+ fib_entry_t *fib_entry = fib_match_msgbuf(forwarder->fib, msgbuf);
+ if (!fib_entry) return false;
+
+ nexthops_t *nexthops = fib_entry_get_nexthops(fib_entry);
+
+ /* Backup flags and cur_len*/
+ uint_fast32_t flags = nexthops->flags;
+ size_t cur_len = nexthops_get_curlen(nexthops);
+
+ /* This affects the nexthops */
+ nexthops = strategy_lookup_nexthops(&fib_entry->strategy, nexthops, msgbuf);
+
+ if (nexthops_get_curlen(nexthops) == 0) {
+ ERROR("Message %p returned an empty next hop set", msgbuf);
+ ret = false;
+ goto END;
+ }
+
+ pit_entry_t *pit_entry = &entry->u.pit_entry;
+ if (!pit_entry) {
+ ret = false;
+ goto END;
+ }
+
+ pit_entry_set_fib_entry(pit_entry, fib_entry);
+
+ // this requires some additional checks. It may happen that some of the output
+ // faces selected by the forwarding strategy are not usable. So far all the
+ // forwarding strategy return only valid faces (or an empty list)
+ nexthops_foreach(nexthops, nexthop, {
+ // DEBUG("Adding egress to PIT for nexthop %d", nexthop);
+ pit_entry_egress_add(pit_entry, nexthop);
+ });
+
+ if (forwarder_forward_to_nexthops(forwarder, msgbuf_id, nexthops) <= 0) {
+ ERROR("Error forwarding mMessage %p to next hops", msgbuf);
+ ret = false;
+ }
+
+END:
+ /* Restore flags & curlen */
+ nexthops->flags = flags;
+ nexthops->cur_elts = cur_len;
+
+ return ret;
+}
+
+#endif /* ! BYPASS_FIB */
+
+int _forwarder_forward_upon_interest(
+ forwarder_t *forwarder, msgbuf_pool_t *msgbuf_pool, off_t data_msgbuf_id,
+ off_t interest_msgbuf_id, pkt_cache_entry_t *entry,
+ pkt_cache_verdict_t verdict, bool is_aggregated) {
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, interest_msgbuf_id);
+
+ // - Aggregation can be perfomed, do not forward
+ if (verdict == PKT_CACHE_VERDICT_AGGREGATE_INTEREST) {
+ forwarder_drop(forwarder, interest_msgbuf_id);
+ return (int)msgbuf_get_len(msgbuf);
+ }
+
+ // - Data packet matching the interest was found, forward reply
+ if (verdict == PKT_CACHE_VERDICT_FORWARD_DATA) {
+ assert(forwarder->serve_from_cs == true);
+
+ msgbuf_t *interest_msgbuf = msgbuf_pool_at(msgbuf_pool, interest_msgbuf_id);
+ msgbuf_t *data_msgbuf = msgbuf_pool_at(msgbuf_pool, data_msgbuf_id);
+
+ msgbuf_reset_pathlabel(data_msgbuf);
+ forwarder_forward_via_connection(forwarder, data_msgbuf_id,
+ msgbuf_get_connection_id(interest_msgbuf));
+ return (int)msgbuf_get_len(msgbuf);
+ }
+
+ // - For aggregated interest, the interest forwarding is done in
+ // `_forwarder_forward_aggregated_interest()`
+ if (is_aggregated) return (int)msgbuf_get_len(msgbuf);
+
+ // - Try to forward the interest
+ int rc =
+ forwarder_forward_via_fib(forwarder, interest_msgbuf_id, verdict, entry);
+ if (!rc) {
+ // - Not able to forward, drop the packet
+ forwarder->stats.countDroppedNoRoute++;
+ INFO("Message %lu did not match FIB, no route (count %u)",
+ interest_msgbuf_id, forwarder->stats.countDroppedNoRoute);
+
+ forwarder_drop(forwarder, interest_msgbuf_id);
+ return -1;
+ }
+
+ return (int)msgbuf_get_len(msgbuf);
+}
+
+static void _forwarder_update_interest_stats(forwarder_t *forwarder,
+ pkt_cache_verdict_t verdict,
+ msgbuf_t *msgbuf,
+ bool has_expire_ts,
+ uint64_t expire_ts) {
+ long expiration = has_expire_ts ? expire_ts : -1;
+ switch (verdict) {
+ case PKT_CACHE_VERDICT_FORWARD_INTEREST:
+ DEBUG("Message added to PIT (expiration=%ld)", expiration);
+ break;
+
+ case PKT_CACHE_VERDICT_AGGREGATE_INTEREST:
+ forwarder->stats.countInterestsAggregated++;
+ DEBUG("Message aggregated in PIT (expiration=%ld)", expiration);
+ break;
+
+ case PKT_CACHE_VERDICT_RETRANSMIT_INTEREST:
+ forwarder->stats.countInterestsRetransmitted++;
+ DEBUG("Message retransmitted (expiration=%ld)", expiration);
+ break;
+
+ case PKT_CACHE_VERDICT_FORWARD_DATA:
+ forwarder->stats.countInterestsSatisfiedFromStore++;
+ DEBUG("Message satisfied from content store (expiration=%ld)",
+ expiration);
+ break;
+
+ case PKT_CACHE_VERDICT_INTEREST_EXPIRED_FORWARD_INTEREST:
+ forwarder->stats.countInterestsExpired++;
+ DEBUG("Message replaced expired interest (expiration=%ld)", expiration);
+ break;
+
+ case PKT_CACHE_VERDICT_DATA_EXPIRED_FORWARD_INTEREST:
+ forwarder->stats.countDataExpired++;
+ DEBUG("Message replaced expired data (expiration=%ld)", expiration);
+ break;
+
+ case PKT_CACHE_VERDICT_ERROR:
+ ERROR("Invalid packet cache content");
+ break;
+
+ default:
+ break;
+ }
+}
+
+/**
+ * Return the interest manifest from the interest payload
+ */
+static int _forwarder_get_interest_manifest(
+ msgbuf_t *msgbuf, interest_manifest_header_t **int_manifest_header,
+ size_t *payload_size) {
+ uint8_t *payload;
+
+ hicn_packet_buffer_t *pkbuf = msgbuf_get_pkbuf(msgbuf);
+
+ hicn_payload_type_t payload_type;
+ HICN_UNUSED(int rc) = hicn_packet_get_payload_type(pkbuf, &payload_type);
+ // XXX ASSERT HERE !!!
+ if (rc != HICN_LIB_ERROR_NONE) return -1;
+ // assert(rc == HICN_LIB_ERROR_NONE);
+
+ if (payload_type != HPT_MANIFEST) return -1;
+
+ rc = hicn_packet_get_payload(pkbuf, &payload, payload_size, false);
+ // assert(rc == HICN_LIB_ERROR_NONE);
+ if (rc != HICN_LIB_ERROR_NONE) return -1;
+
+ *int_manifest_header = (interest_manifest_header_t *)payload;
+
+ return 0;
+}
+
+// Manifest is split using splitting strategy, then every
+// sub-manifest is sent using the forwarding strategy defined for the prefix
+int _forwarder_forward_aggregated_interest(
+ forwarder_t *forwarder, interest_manifest_header_t *int_manifest_header,
+ msgbuf_t *msgbuf, off_t msgbuf_id, pkt_cache_entry_t **entries) {
+ assert(msgbuf_id_is_valid(msgbuf_id) &&
+ msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_INTEREST);
+
+ int ret = -1;
+
+ fib_entry_t *fib_entry = fib_match_msgbuf(forwarder->fib, msgbuf);
+ if (!fib_entry) goto END;
+
+ nexthops_t *nexthops = fib_entry_get_nexthops(fib_entry);
+ if (nexthops_get_curlen(nexthops) == 0) {
+ ret = 0;
+ goto END;
+ }
+
+ /* Backup flags and cur_len*/
+ uint_fast32_t flags = nexthops->flags;
+ size_t cur_len = nexthops_get_curlen(nexthops);
+
+ size_t n_suffixes_per_split = configuration_get_suffixes_per_split(
+ forwarder_get_configuration(forwarder));
+ int_manifest_split_strategy_t disaggregation_strategy =
+ configuration_get_split_strategy(forwarder_get_configuration(forwarder));
+ switch (disaggregation_strategy) {
+ case INT_MANIFEST_SPLIT_STRATEGY_NONE:
+ n_suffixes_per_split = int_manifest_header->n_suffixes + 1;
+
+ case INT_MANIFEST_SPLIT_STRATEGY_MAX_N_SUFFIXES: {
+ // Generate sub-manifests: same as original manifest,
+ // but different suffix in the header and different bitmap
+
+ int total_len = 0;
+ // Suffixes in manifest plus the one in the header
+ int total_suffixes = int_manifest_header->n_suffixes + 1;
+
+ // Save copy of original bitmap to use as a reference
+ // to generate bitmaps for sub-manifests
+ hicn_uword original_bitmap[BITMAP_SIZE] = {0};
+ memcpy(&original_bitmap, int_manifest_header->request_bitmap,
+ BITMAP_SIZE * sizeof(hicn_uword));
+
+ size_t suffix_index = 0; // Position of suffix in initial manifest
+ interest_manifest_header_t *manifest = NULL;
+ size_t payload_size;
+ while (suffix_index < total_suffixes) {
+ // If more than one sub-manifest,
+ // clone original interest manifest and update suffix
+ if (suffix_index > 0) {
+ msgbuf_t *clone;
+ off_t clone_id =
+ msgbuf_pool_clone(forwarder->msgbuf_pool, &clone, msgbuf_id);
+ msgbuf_pool_acquire(clone);
+ forwarder_acquired_msgbuf_ids_push(forwarder, clone_id);
+
+ msgbuf_id = clone_id;
+ msgbuf = clone;
+ }
+
+ hicn_uword curr_bitmap[BITMAP_SIZE] = {0};
+ size_t first_suffix_index_in_submanifest = suffix_index;
+ suffix_index = interest_manifest_update_bitmap(
+ original_bitmap, curr_bitmap, suffix_index, total_suffixes,
+ n_suffixes_per_split);
+ size_t first_suffix_index_in_next_submanifest = suffix_index;
+
+ // Update manifest bitmap in current msgbuf
+
+ int ret =
+ _forwarder_get_interest_manifest(msgbuf, &manifest, &payload_size);
+ _ASSERT(ret == 0);
+ memcpy(manifest->request_bitmap, curr_bitmap,
+ BITMAP_SIZE * sizeof(hicn_uword));
+ WITH_TRACE({
+ bitmap_print(manifest->request_bitmap, BITMAP_SIZE);
+ printf("\n");
+ });
+
+ /*
+ * Update PIT entries for suffixes in current sub-manifest.
+ *
+ * Note that strategy lookup affects the nexthops, and we need to
+ *restore the initial state before every lookup
+ */
+ nexthops->flags = flags;
+ nexthops->cur_elts = cur_len;
+ nexthops =
+ strategy_lookup_nexthops(&fib_entry->strategy, nexthops, msgbuf);
+
+ if (nexthops_get_curlen(nexthops) == 0) {
+ ERROR("Message %p returned an empty next hop set", msgbuf);
+ goto RESTORE;
+ }
+
+ for (size_t i = first_suffix_index_in_submanifest;
+ i < first_suffix_index_in_next_submanifest; i++) {
+ if (!bitmap_is_set_no_check(manifest->request_bitmap, i)) continue;
+
+ pit_entry_t *pit_entry = &(entries[i]->u.pit_entry);
+ if (!pit_entry) goto RESTORE;
+
+ pit_entry_set_fib_entry(pit_entry, fib_entry);
+ nexthops_foreach(nexthops, nexthop,
+ { pit_entry_egress_add(pit_entry, nexthop); });
+ }
+
+ // Serialize manifest before sending it
+ interest_manifest_serialize(int_manifest_header);
+
+ if (forwarder_forward_to_nexthops(forwarder, msgbuf_id, nexthops) <=
+ 0) {
+ ERROR("Message %p returned an empty next hop set", msgbuf);
+ continue;
+ }
+
+ total_len += msgbuf_get_len(msgbuf);
+ }
+
+ ret = total_len;
+ goto END;
+ }
+
+ default:
+ break;
+ }
+
+RESTORE:
+ /* Restore flags & curlen */
+ nexthops->flags = flags;
+ nexthops->cur_elts = cur_len;
+
+END:
+ return ret;
+}
+
+static ssize_t forwarder_process_single_interest(forwarder_t *forwarder,
+ msgbuf_pool_t *msgbuf_pool,
+ msgbuf_t *msgbuf,
+ off_t msgbuf_id) {
+ pkt_cache_verdict_t verdict = PKT_CACHE_VERDICT_ERROR;
+ off_t data_msgbuf_id = INVALID_MSGBUF_ID;
+ pkt_cache_entry_t *entry = NULL;
+
+ // Update packet cache
+ pkt_cache_on_interest(forwarder->pkt_cache, msgbuf_pool, msgbuf_id, &verdict,
+ &data_msgbuf_id, &entry, msgbuf_get_name(msgbuf),
+ forwarder->serve_from_cs);
+
+ _forwarder_update_interest_stats(forwarder, verdict, msgbuf,
+ entry->has_expire_ts, entry->expire_ts);
+
+ int rc = _forwarder_forward_upon_interest(
+ forwarder, msgbuf_pool, data_msgbuf_id, msgbuf_id, entry, verdict, false);
+
+ // No route when trying to forward interest, remove from PIT
+ if (rc == -1) pkt_cache_pit_remove_entry(forwarder->pkt_cache, entry);
+
+ return msgbuf_get_len(msgbuf);
+}
+
+static ssize_t forwarder_process_aggregated_interest(
+ forwarder_t *forwarder, interest_manifest_header_t *int_manifest_header,
+ msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf, off_t msgbuf_id) {
+ pkt_cache_verdict_t verdict = PKT_CACHE_VERDICT_ERROR;
+ off_t data_msgbuf_id = INVALID_MSGBUF_ID;
+ pkt_cache_entry_t *entry = NULL;
+ // Save PIT entries to avoid re-doing pkt cache lookup in
+ // `_forwarder_forward_aggregated_interest()`
+ pkt_cache_entry_t *entries[BITMAP_SIZE * WORD_WIDTH];
+
+ int n_suffixes_to_fwd = 0;
+
+ hicn_name_t name_copy = HICN_NAME_EMPTY;
+ hicn_name_copy(&name_copy, msgbuf_get_name(msgbuf));
+
+ // Suffixes in interest manifest also contains suffix in main name. We can
+ // then just iterate the interest manifest and update the suffix in the name
+ // struct
+ hicn_name_suffix_t *suffix;
+ unsigned long pos;
+ interest_manifest_foreach_suffix(int_manifest_header, suffix, pos) {
+ // Update name
+ hicn_name_set_suffix(&name_copy, *suffix);
+
+ // Update packet cache
+ pkt_cache_on_interest(forwarder->pkt_cache, msgbuf_pool, msgbuf_id,
+ &verdict, &data_msgbuf_id, &entry, &name_copy,
+ forwarder->serve_from_cs);
+
+ entries[pos] = entry;
+ _forwarder_update_interest_stats(forwarder, verdict, msgbuf,
+ entry->has_expire_ts, entry->expire_ts);
+
+ // Here only data forwarding is performed, interest forwarding is done
+ // in '_forwarder_forward_aggregated_interest()'
+ int rc =
+ _forwarder_forward_upon_interest(forwarder, msgbuf_pool, data_msgbuf_id,
+ msgbuf_id, entry, verdict, true);
+
+ // No route when trying to forward interest, remove from PIT
+ if (rc == -1) pkt_cache_pit_remove_entry(forwarder->pkt_cache, entry);
+
+ // Unset in bitmap if no interest forwarding needed,
+ // otherwise increase count of suffixes to forward
+ if (rc == -1 || verdict == PKT_CACHE_VERDICT_AGGREGATE_INTEREST ||
+ verdict == PKT_CACHE_VERDICT_FORWARD_DATA) {
+ bitmap_unset_no_check(int_manifest_header->request_bitmap, pos);
+ } else {
+ n_suffixes_to_fwd++;
+ }
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HICN_PREFIX];
+ int rc = hicn_name_snprintf(buf, MAXSZ_HICN_NAME, &name_copy);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "(error)");
+ DEBUG("Next in manifest: %s", buf);
+ });
+ }
+
+ // Return if nothing in the manifest to forward
+ if (n_suffixes_to_fwd == 0) return msgbuf_get_len(msgbuf);
+
+ return _forwarder_forward_aggregated_interest(forwarder, int_manifest_header,
+ msgbuf, msgbuf_id, entries);
+}
+
+/**
+ * @function forwarder_process_interest
+ * @abstract Receive an interest from the network
+ * @discussion
+ * (1) if interest in the PIT, aggregate in PIT
+ * (2) if interest in the ContentStore, reply
+ * (3) if in the FIB, forward
+ * (4) drop
+ *
+ */
+static ssize_t forwarder_process_interest(forwarder_t *forwarder,
+ off_t msgbuf_id) {
+ assert(forwarder);
+ assert(msgbuf_id_is_valid(msgbuf_id));
+
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+ const connection_table_t *table = forwarder_get_connection_table(forwarder);
+ connection_t *conn =
+ connection_table_get_by_id(table, msgbuf_get_connection_id(msgbuf));
+
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_INTEREST);
+
+ u32 n_suffixes = 0;
+ interest_manifest_header_t *int_manifest_header = NULL;
+ size_t payload_size;
+ int ret = _forwarder_get_interest_manifest(msgbuf, &int_manifest_header,
+ &payload_size);
+ if (ret == 0) {
+ // Deserialize intrest manifest
+ interest_manifest_deserialize(int_manifest_header);
+
+ if (!interest_manifest_is_valid(int_manifest_header, payload_size))
+ return -1;
+
+ n_suffixes = int_manifest_header->n_suffixes;
+ }
+
+ // Update stats
+ forwarder->stats.countInterestsReceived++;
+ conn->stats.interests.rx_pkts++;
+ conn->stats.interests.rx_bytes += msgbuf_get_len(msgbuf);
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HICN_PREFIX];
+ int rc = hicn_name_snprintf(buf, MAXSZ_HICN_NAME, msgbuf_get_name(msgbuf));
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "(error)");
+ DEBUG("INTEREST (%s) msgbuf_id=%lu ingress=%u length=%u", buf, msgbuf_id,
+ msgbuf_get_connection_id(msgbuf), msgbuf_get_len(msgbuf));
+ DEBUG("INTEREST (%s) suffixes=%u msgbuf_id=%lu ingress=%u length=%u", buf,
+ n_suffixes, msgbuf_id, msgbuf_get_connection_id(msgbuf),
+ msgbuf_get_len(msgbuf));
+ });
+
+ // Cache suffixes for current prefix to (possibly) avoid double lookups
+ pkt_cache_save_suffixes_for_prefix(
+ forwarder->pkt_cache, hicn_name_get_prefix(msgbuf_get_name(msgbuf)));
+
+ if (ret == -1)
+ return forwarder_process_single_interest(forwarder, msgbuf_pool, msgbuf,
+ msgbuf_id);
+ return forwarder_process_aggregated_interest(forwarder, int_manifest_header,
+ msgbuf_pool, msgbuf, msgbuf_id);
+}
+
+static void _forwarder_log_on_data(forwarder_t *forwarder,
+ pkt_cache_verdict_t verdict) {
+ switch (verdict) {
+ case PKT_CACHE_VERDICT_FORWARD_DATA:
+ DEBUG("Message added to CS from PIT");
+ break;
+ case PKT_CACHE_VERDICT_STORE_DATA:
+ DEBUG(
+ "Message added to CS (expired or no previous interest "
+ "pending)");
+ break;
+ case PKT_CACHE_VERDICT_CLEAR_DATA:
+ break;
+ case PKT_CACHE_VERDICT_UPDATE_DATA:
+ DEBUG("Message updated in CS");
+ break;
+ case PKT_CACHE_VERDICT_IGNORE_DATA:
+ DEBUG("Message not stored in CS");
+ break;
+ case PKT_CACHE_VERDICT_ERROR:
+ ERROR("Invalid packet cache content");
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * @function forwarder_process_data
+ * @abstract Process an in-bound content object
+ * @discussion
+ * (1) If it does not match anything in the PIT, drop it
+ * (2) Add to Content Store
+ * (3) Reverse path forward via PIT entries
+ *
+ * @param <#param1#>
+ */
+static ssize_t forwarder_process_data(forwarder_t *forwarder, off_t msgbuf_id) {
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HICN_PREFIX];
+ int rc = hicn_name_snprintf(buf, MAXSZ_HICN_NAME, msgbuf_get_name(msgbuf));
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "(error)");
+ DEBUG("DATA (%s) msgbuf_id=%lu ingress=%u length=%u", buf, msgbuf_id,
+ msgbuf_get_connection_id(msgbuf), msgbuf_get_len(msgbuf));
+ });
+
+ const connection_table_t *table = forwarder_get_connection_table(forwarder);
+ connection_t *conn =
+ connection_table_get_by_id(table, msgbuf_get_connection_id(msgbuf));
+
+ // Update stats
+ forwarder->stats.countObjectsReceived++;
+ conn->stats.data.rx_pkts++;
+ conn->stats.data.rx_bytes += msgbuf_get_len(msgbuf);
+
+ // Cache suffixes for current prefix to (possibly) avoid double lookups
+ pkt_cache_save_suffixes_for_prefix(
+ forwarder->pkt_cache, hicn_name_get_prefix(msgbuf_get_name(msgbuf)));
+
+ pkt_cache_verdict_t verdict = PKT_CACHE_VERDICT_ERROR;
+ bool wrong_egress;
+ nexthops_t *ingressSetUnion = pkt_cache_on_data(
+ forwarder->pkt_cache, msgbuf_pool, msgbuf_id, forwarder->store_in_cs,
+ connection_is_local(conn), &wrong_egress, &verdict);
+
+ _forwarder_log_on_data(forwarder, verdict);
+
+ if (wrong_egress) { // Interest sent via a connection but received from
+ // another
+ WARN("Data coming from unexpected connection, discarded");
+ } else if (!ingressSetUnion) { // No match in the PIT
+ forwarder->stats.countDroppedNoReversePath++;
+ DEBUG("Message %lu did not match PIT, no reverse path", msgbuf_id);
+
+ // NOTE : probes are not stored in PIT
+ if (msgbuf_is_probe(msgbuf)) {
+ fib_entry_t *entry = fib_match_msgbuf(forwarder->fib, msgbuf);
+ if (entry && fib_entry_strategy_type(entry) == STRATEGY_TYPE_BESTPATH) {
+ nexthops_t probe_nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&probe_nexthops, msgbuf_get_connection_id(msgbuf));
+ fib_entry_on_data(entry, &probe_nexthops, msgbuf, 0, ticks_now());
+ }
+ }
+ forwarder_drop(forwarder, msgbuf_id);
+ } else {
+ // Reverse path forward via PIT entries
+ forwarder_forward_to_nexthops(forwarder, msgbuf_id, ingressSetUnion);
+ free(ingressSetUnion);
+ }
+
+ return msgbuf_get_len(msgbuf);
+}
+
+void forwarder_flush_connections(forwarder_t *forwarder) {
+ // DEBUG("[forwarder_flush_connections]");
+ const connection_table_t *table = forwarder_get_connection_table(forwarder);
+
+ unsigned num_pending_conn = (unsigned)vector_len(forwarder->pending_conn);
+ for (unsigned i = 0; i < num_pending_conn; i++) {
+ unsigned conn_id = forwarder->pending_conn[i];
+ connection_t *conn = connection_table_at(table, conn_id);
+ if (!connection_flush(conn)) {
+ WARN("Could not flush connection queue");
+ // XXX keep track of non flushed connections...
+ }
+ }
+ vector_reset(forwarder->pending_conn);
+ // DEBUG("[forwarder_flush_connections] done");
+}
+
+#if WITH_WLDR
+// XXX move to wldr file, worst case in connection.
+void forwarder_apply_wldr(const forwarder_t *forwarder, const msgbuf_t *msgbuf,
+ connection_t *connection) {
+ // this are the checks needed to implement WLDR. We set wldr only on the
+ // STAs and we let the AP to react according to choice of the client. if
+ // the STA enables wldr using the set command, the AP enable wldr as
+ // well otherwise, if the STA disable it the AP remove wldr WLDR should
+ // be enabled only on the STAs using the command line
+ // TODO
+ // disable WLDR command line on the AP
+ if (msgbuf_has_wldr(msgbuf)) {
+ if (connection_has_wldr(connection)) {
// case 1: WLDR is enabled
- connection_DetectLosses((Connection *)conn, message);
- } else if (!connection_HasWldr(conn) &&
- connection_WldrAutoStartAllowed(conn)) {
+ connection_wldr_detect_losses(connection, msgbuf);
+ } else if (!connection_has_wldr(connection) &&
+ connection_wldr_autostart_is_allowed(connection)) {
// case 2: We are on an AP. We enable WLDR
- connection_EnableWldr((Connection *)conn);
- connection_DetectLosses((Connection *)conn, message);
+ connection_wldr_enable(connection, true);
+ connection_wldr_detect_losses(connection, msgbuf);
}
// case 3: Ignore WLDR
} else {
- if (connection_HasWldr(conn) && connection_WldrAutoStartAllowed(conn)) {
+ if (connection_has_wldr(connection) &&
+ connection_wldr_autostart_is_allowed(connection)) {
// case 1: STA do not use WLDR, we disable it
- connection_DisableWldr((Connection *)conn);
+ connection_wldr_enable(connection, false);
}
}
-
- messageProcessor_Receive(forwarder->processor, message);
}
+#endif
-Ticks forwarder_GetTicks(const Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
- return parcClock_GetTime(forwarder->clock) + forwarder->clockOffset;
-}
+bool forwarder_add_or_update_route(forwarder_t *forwarder,
+ hicn_ip_prefix_t *prefix,
+ unsigned ingress_id) {
+ assert(forwarder);
+ assert(prefix);
-Ticks forwarder_NanosToTicks(uint64_t nanos) { return NSEC_TO_TICKS(nanos); }
+ configuration_t *config = forwarder_get_configuration(forwarder);
-uint64_t forwarder_TicksToNanos(Ticks ticks) {
- return (1000000000ULL) * ticks / HZ;
-}
+ char prefix_s[MAXSZ_IP_PREFIX];
+ int rc = hicn_ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, prefix);
+ assert(rc < MAXSZ_IP_PREFIX);
+ if (rc < 0) return false;
+
+ INFO("Adding prefix=%s for conn_id=%d", prefix_s, ingress_id);
-bool forwarder_AddOrUpdateRoute(Forwarder *forwarder,
- add_route_command *control, unsigned ifidx) {
- parcAssertNotNull(forwarder, "Parameter hicn-light must be non-null");
- parcAssertNotNull(control, "Parameter route must be non-null");
+ strategy_type_t strategy_type = configuration_get_strategy(config, prefix_s);
- // we only have one message processor
- bool res =
- messageProcessor_AddOrUpdateRoute(forwarder->processor, control, ifidx);
+ hicn_prefix_t name_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&prefix->address, prefix->len,
+ &name_prefix);
+ fib_entry_t *entry = fib_contains(forwarder->fib, &name_prefix);
+ if (!entry) {
+ entry = fib_entry_create(&name_prefix, strategy_type, NULL, forwarder);
+ if (ingress_id != INVALID_FACE_ID)
+ fib_entry_nexthops_add(entry, ingress_id);
+ entry = fib_add(forwarder->fib, entry);
- return res;
+ } else {
+ if (ingress_id != INVALID_FACE_ID)
+ fib_entry_nexthops_add(entry, ingress_id);
+ }
+
+ forwarder_on_route_event(forwarder, entry);
+
+ return true;
}
+bool forwarder_remove_route(forwarder_t *forwarder, hicn_ip_prefix_t *prefix,
+ unsigned ingress_id) {
+ assert(forwarder);
+ assert(prefix);
-bool forwarder_RemoveRoute(Forwarder *forwarder, remove_route_command *control,
- unsigned ifidx) {
- parcAssertNotNull(forwarder, "Parameter hicn-light must be non-null");
- parcAssertNotNull(control, "Parameter route must be non-null");
+ hicn_prefix_t name_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&prefix->address, prefix->len,
+ &name_prefix);
+ fib_remove(forwarder->fib, &name_prefix, ingress_id);
- // we only have one message processor
- return messageProcessor_RemoveRoute(forwarder->processor, control, ifidx);
+ return true;
}
#ifdef WITH_POLICY
-bool forwarder_AddOrUpdatePolicy(Forwarder *forwarder,
- add_policy_command *control) {
- parcAssertNotNull(forwarder, "Parameter forwarder must be non-null");
- parcAssertNotNull(control, "Parameter control must be non-null");
+bool forwarder_add_or_update_policy(forwarder_t *forwarder,
+ hicn_ip_prefix_t *prefix,
+ hicn_policy_t *policy) {
+ assert(forwarder);
+ assert(prefix);
+ assert(policy);
+
+ hicn_prefix_t name_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&prefix->address, prefix->len,
+ &name_prefix);
+ fib_entry_t *entry = fib_contains(forwarder->fib, &name_prefix);
+ if (!entry) return false;
- return messageProcessor_AddOrUpdatePolicy(forwarder->processor, control);
+ fib_entry_set_policy(entry, *policy);
+
+ return true;
}
-bool forwarder_RemovePolicy(Forwarder *forwarder, remove_policy_command *control) {
- parcAssertNotNull(forwarder, "Parameter forwarder must be non-null");
- parcAssertNotNull(control, "Parameter control must be non-null");
+bool forwarder_remove_policy(forwarder_t *forwarder, hicn_ip_prefix_t *prefix) {
+ assert(forwarder);
+ assert(prefix);
+
+ hicn_prefix_t name_prefix = HICN_PREFIX_EMPTY;
+ hicn_prefix_create_from_ip_address_len(&prefix->address, prefix->len,
+ &name_prefix);
+ fib_entry_t *entry = fib_contains(forwarder->fib, &name_prefix);
+ if (!entry) return false;
- return messageProcessor_RemovePolicy(forwarder->processor, control);
+ fib_entry_set_policy(entry, POLICY_EMPTY);
+
+ return true;
}
#endif /* WITH_POLICY */
-void forwarder_RemoveConnectionIdFromRoutes(Forwarder *forwarder,
- unsigned connectionId) {
- parcAssertNotNull(forwarder, "Parameter hicn-light must be non-null");
- messageProcessor_RemoveConnectionIdFromRoutes(forwarder->processor,
- connectionId);
+void forwarder_remove_connection_id_from_routes(const forwarder_t *forwarder,
+ unsigned connection_id) {
+ fib_entry_t **removed_entries = NULL;
+ size_t num_removed_entries;
+
+ assert(forwarder);
+
+ fib_remove_connection(forwarder->fib, connection_id, &removed_entries,
+ &num_removed_entries);
+
+ if (num_removed_entries > 0) {
+ assert(removed_entries);
+
+ for (int i = 0; i < num_removed_entries; i++) {
+ fib_entry_t *entry = removed_entries[i];
+ forwarder_on_route_event(forwarder, entry);
+ fib_remove_entry(forwarder->fib, entry);
+ }
+ free(removed_entries);
+ }
}
-void forwarder_SetStrategy(Forwarder *forwarder, Name *prefix,
- strategy_type strategy,
- unsigned related_prefixes_len,
- Name **related_prefixes) {
- parcAssertNotNull(forwarder, "Parameter hicn-light must be non-null");
- parcAssertNotNull(prefix, "Parameter prefix must be non-null");
+void forwarder_add_strategy_options(forwarder_t *forwarder,
+ hicn_prefix_t *name_prefix,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options) {
+ assert(forwarder);
+ assert(name_prefix);
+ assert(strategy_options);
+ assert(STRATEGY_TYPE_VALID(strategy_type));
- processor_SetStrategy(forwarder->processor, prefix, strategy,
- related_prefixes_len, related_prefixes);
+ fib_entry_t *entry = fib_contains(forwarder->fib, name_prefix);
+ if (!entry) return;
+
+ fib_entry_add_strategy_options(entry, strategy_type, strategy_options);
}
-FibEntryList *forwarder_GetFibEntries(Forwarder *forwarder) {
- return messageProcessor_GetFibEntries(forwarder->processor);
+void forwarder_set_strategy(forwarder_t *forwarder, hicn_prefix_t *prefix,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options) {
+ assert(forwarder);
+ assert(prefix);
+ assert(STRATEGY_TYPE_VALID(strategy_type));
+ /* strategy_options might be NULL */
+
+ fib_entry_t *entry = fib_contains(forwarder->fib, prefix);
+ if (!entry) {
+ // there is no exact match. so if the forwarding strategy is not in
+ // the list of strategies that can be set by the transport, return
+ if (strategy_type != STRATEGY_TYPE_BESTPATH &&
+ strategy_type != STRATEGY_TYPE_REPLICATION) {
+ return;
+ }
+
+ // here it may be the transprot that wants to set the strategy, but it has
+ // no knowledge of the length of the prefix. so we apply the strategy at the
+ // matching fib entry, which later will be the one that will be used to send
+ // interests with this name
+ entry = fib_match_prefix(forwarder->fib, prefix);
+ if (!entry) {
+ return; // no fib match, return
+ }
+ }
+
+ fib_entry_set_strategy(entry, strategy_type, strategy_options);
}
-void forwarder_SetContentObjectStoreSize(Forwarder *forwarder,
- size_t maximumContentStoreSize) {
- messageProcessor_SetContentObjectStoreSize(forwarder->processor,
- maximumContentStoreSize);
+cs_t *forwarder_get_cs(const forwarder_t *forwarder) {
+ assert(forwarder);
+
+ return pkt_cache_get_cs(forwarder->pkt_cache);
}
-void forwarder_ClearCache(Forwarder *forwarder) {
- messageProcessor_ClearCache(forwarder->processor);
+// IMPORTANT: Use this function ONLY for read-only operations since a
+// realloc would otherwise modify the returned copy but not the original
+// msgbuf ids vector in the forwarder. This constraint cannot be enforced
+// by returning a (const off_t *) because the vector_t macros still cast
+// to (void **).
+off_t *forwarder_get_acquired_msgbuf_ids(const forwarder_t *forwarder) {
+ return forwarder->acquired_msgbuf_ids;
}
-PARCClock *forwarder_GetClock(const Forwarder *forwarder) {
- return forwarder->clock;
+void forwarder_acquired_msgbuf_ids_reset(const forwarder_t *forwarder) {
+ vector_reset(forwarder->acquired_msgbuf_ids);
}
-#if !defined(__APPLE__)
-hicn_socket_helper_t *forwarder_GetHicnSocketHelper(Forwarder *forwarder) {
- return forwarder->hicnSocketHelper;
+void forwarder_acquired_msgbuf_ids_push(const forwarder_t *forwarder,
+ off_t msgbuf_id) {
+ vector_push(forwarder->acquired_msgbuf_ids, msgbuf_id);
}
-#endif
// =======================================================
-static void _signal_cb(int sig, PARCEventType events, void *user_data) {
- Forwarder *forwarder = (Forwarder *)user_data;
+fib_t *forwarder_get_fib(const forwarder_t *forwarder) {
+ return forwarder->fib;
+}
+
+msgbuf_pool_t *forwarder_get_msgbuf_pool(const forwarder_t *forwarder) {
+ return forwarder->msgbuf_pool;
+}
+
+mapme_t *forwarder_get_mapme(const forwarder_t *forwarder) {
+ return forwarder->mapme;
+}
+
+#ifdef WITH_POLICY_STATS
+const policy_stats_mgr_t *forwarder_get_policy_stats_mgr(
+ const forwarder_t *forwarder) {
+ return &forwarder->policy_stats_mgr;
+}
+#endif /* WITH_POLICY_STATS */
+
+/**
+ * @brief Finalize (i.e. close fd and free internal data structures)
+ * the current connection ("SELF") when the command is received.
+ * The connection cannot be removed inside the command handling
+ * because it is needed to return the ack back.
+ */
+static void _forwarder_finalize_connection_if_self(connection_t *conn,
+ msgbuf_t *msgbuf) {
+ uint8_t *packet = msgbuf_get_packet(msgbuf);
+ msg_connection_remove_t *msg = (msg_connection_remove_t *)packet;
+ cmd_connection_remove_t *control = &msg->payload;
+
+ if (strcmp(control->symbolic_or_connid, "SELF") == 0)
+ connection_finalize(conn);
+}
- logger_Log(forwarder->logger, LoggerFacility_Core, PARCLogLevel_Warning,
- __func__, "signal %d events %d", sig, events);
+ssize_t forwarder_receive(forwarder_t *forwarder, listener_t *listener,
+ off_t msgbuf_id, address_pair_t *pair, Ticks now) {
+ assert(forwarder);
+ /* listener can be NULL */
+ assert(msgbuf_id_is_valid(msgbuf_id));
+ assert(pair);
+
+ hicn_name_t name;
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+ assert(msgbuf);
+
+ size_t size = msgbuf_get_len(msgbuf);
+
+ const connection_table_t *table =
+ forwarder_get_connection_table(listener->forwarder);
+
+ /* Connection lookup */
+ if (msgbuf_get_connection_id(msgbuf) == CONNECTION_ID_UNDEFINED) {
+ connection_t *connection = connection_table_get_by_pair(table, pair);
+ unsigned conn_id =
+ connection
+ ? (unsigned)connection_table_get_connection_id(table, connection)
+ : CONNECTION_ID_UNDEFINED;
+
+ assert((conn_id != CONNECTION_ID_UNDEFINED) || listener);
+ msgbuf->connection_id = conn_id;
+ }
- switch ((int)sig) {
- case SIGTERM:
- logger_Log(forwarder->logger, LoggerFacility_Core, PARCLogLevel_Warning,
- __func__, "Caught an terminate signal; exiting cleanly.");
- dispatcher_Stop(forwarder->dispatcher);
+ forwarder->stats.countReceived++;
+
+ /* Initialize packet buffer stored in msgbuf through libhicn */
+ msgbuf_initialize_from_packet(msgbuf);
+
+ /* Detect packet type */
+ hicn_packet_analyze(msgbuf_get_pkbuf(msgbuf));
+
+ msgbuf->recv_ts = now;
+
+RETRY:
+
+ switch (msgbuf_get_type(msgbuf)) {
+ case HICN_PACKET_TYPE_INTEREST:
+ if (!connection_id_is_valid(msgbuf->connection_id)) {
+ char conn_name[SYMBOLIC_NAME_LEN];
+ int rc = connection_table_get_random_name(table, conn_name);
+ if (rc < 0) {
+ ERROR("Could not create name for new connection");
+ goto DROP;
+ }
+
+ unsigned connection_id =
+ listener_create_connection(listener, conn_name, pair);
+ if (connection_id == CONNECTION_ID_UNDEFINED) {
+ ERROR("Could not create new connection");
+ goto DROP;
+ }
+ msgbuf->connection_id = connection_id;
+ }
+ msgbuf->path_label = 0; // not used for interest packets
+ hicn_interest_get_name(msgbuf_get_pkbuf(msgbuf), &name);
+ msgbuf_set_name(msgbuf, &name);
+#ifdef WITH_WLDR
+ forwarder_apply_wldr(forwarder, msgbuf, connection);
+#endif /* WITH_WLDR */
+ forwarder_process_interest(forwarder, msgbuf_id);
+
+ pkt_cache_log(forwarder->pkt_cache);
break;
- case SIGINT:
- logger_Log(forwarder->logger, LoggerFacility_Core, PARCLogLevel_Warning,
- __func__, "Caught an interrupt signal; exiting cleanly.");
- dispatcher_Stop(forwarder->dispatcher);
+ case HICN_PACKET_TYPE_DATA:
+ /* This include probes */
+ if (!connection_id_is_valid(msgbuf->connection_id)) {
+ ERROR("Invalid connection for data packet");
+ goto DROP;
+ }
+ msgbuf_init_pathlabel(msgbuf);
+ hicn_data_get_name(msgbuf_get_pkbuf(msgbuf), &name);
+ msgbuf_set_name(msgbuf, &name);
+#ifdef WITH_WLDR
+ forwarder_apply_wldr(forwarder, msgbuf, connection);
+#endif /* WITH_WLDR */
+ forwarder_process_data(forwarder, msgbuf_id);
+
+ pkt_cache_log(forwarder->pkt_cache);
break;
-#ifndef _WIN32
- case SIGUSR1:
- // dump stats
+
+#ifdef WITH_WLDR
+ case HICN_PACKET_TYPE_WLDR_NOTIFICATION:
+ if (!connection_id_is_valid(msgbuf->connection_id)) {
+ ERROR("Invalid connection for WLDR packet");
+ goto DROP;
+ }
+ connection_t *connection =
+ connection_table_get_by_id(table, msgbuf->connection_id);
+ connection_wldr_handle_notification(connection, msgbuf);
break;
#endif
- default:
+ case HICN_PACKET_TYPE_MAPME:
+ INFO("Received MAP-Me packet");
+ if (!connection_id_is_valid(msgbuf->connection_id)) {
+ char conn_name[SYMBOLIC_NAME_LEN];
+ int rc = connection_table_get_random_name(table, conn_name);
+ if (rc < 0) {
+ ERROR("Could not create name for new connection");
+ goto DROP;
+ }
+
+ unsigned connection_id =
+ listener_create_connection(listener, conn_name, pair);
+ if (connection_id == CONNECTION_ID_UNDEFINED) {
+ ERROR("Could not create new connection");
+ goto DROP;
+ }
+ INFO("Created connection upon MAP-Me packet");
+ msgbuf->connection_id = connection_id;
+ }
+ mapme_process(forwarder->mapme, msgbuf);
break;
- }
-}
-static void _keepalive_cb(int fd, PARCEventType what, void *user_data) {
- parcAssertTrue(what & PARCEventType_Timeout, "Got unexpected tick_cb: %d",
- what);
- // function is just a keepalive for hicn-light, does not do anything
-}
+ case HICN_PACKET_TYPE_COMMAND:
+ // Create the connection to send the ack back
+ if (!connection_id_is_valid(msgbuf->connection_id)) {
+ char conn_name[SYMBOLIC_NAME_LEN];
+ int rc = connection_table_get_random_name(table, conn_name);
+ if (rc < 0) {
+ ERROR("Could not create name for new connection");
+ goto DROP;
+ }
+
+ unsigned connection_id =
+ listener_create_connection(listener, conn_name, pair);
+ if (connection_id == CONNECTION_ID_UNDEFINED) {
+ ERROR("Could not create new connection");
+ goto DROP;
+ }
+ msgbuf->connection_id = connection_id;
+ }
+
+ msg_header_t *msg = (msg_header_t *)msgbuf_get_packet(msgbuf);
+ msgbuf->command.type = msg->header.command_id;
+ if (!command_type_is_valid(msgbuf->command.type)) {
+ ERROR("Invalid command %d", msgbuf->command.type);
+ goto DROP;
+ }
+
+ /*
+ * We need to retrieve the connection (in case it is useful) before
+ * proceeding through the removal
+ */
+ connection_t *connection =
+ connection_table_get_by_id(table, msgbuf_get_connection_id(msgbuf));
+ size = command_process_msgbuf(forwarder, msgbuf);
+ if (msgbuf->command.type == COMMAND_TYPE_CONNECTION_REMOVE)
+ _forwarder_finalize_connection_if_self(connection, msgbuf);
+ return size;
-#ifdef WITH_MAPME
-FIB *forwarder_getFib(Forwarder *forwarder) {
- return messageProcessor_getFib(forwarder->processor);
-}
+ default:
+ /* Commands are not recognized by the packet parser */
+ if (msgbuf_is_command(msgbuf)) {
+ msgbuf_set_type(msgbuf, HICN_PACKET_TYPE_COMMAND);
+ goto RETRY;
+ }
+ goto DROP;
+ }
-void forwarder_onConnectionEvent(Forwarder *forwarder, const Connection *conn, connection_event_t event) {
-//#ifdef WITH_POLICY
-// messageProcessor_onConnectionEvent(forwarder->processor, conn, event);
-//#else
- mapme_onConnectionEvent(forwarder->mapme, conn, event);
-//#endif /* WITH_POLICY */
-}
+ return size;
-void forwarder_ProcessMapMe(Forwarder *forwarder, const uint8_t *msgBuffer,
- unsigned conn_id) {
- mapme_Process(forwarder->mapme, msgBuffer, conn_id);
+DROP:
+ forwarder_drop(forwarder, msgbuf_id);
+ return 0;
}
-MapMe *
-forwarder_getMapmeInstance(const Forwarder *forwarder) {
- return forwarder->mapme;
+void forwarder_log(forwarder_t *forwarder) {
+ DEBUG(
+ "Forwarder: received = %u (interest = %u, data = %u), dropped = %u "
+ "(interest = %u, data = %u, other = %u), forwarded = { interests = "
+ "%u, "
+ "data = %u }, dropped = { connection_not_found = %u, send_failure "
+ "= "
+ "%u, "
+ "no_route_in_fib = %u }, interest processing = { aggregated = %u, "
+ "retransmitted = %u, satisfied_from_cs = %u, expired_interests = "
+ "%u, "
+ "expired_data = %u }, data processing = { "
+ "no_reverse_path = %u }\n",
+ forwarder->stats.countReceived, forwarder->stats.countInterestsReceived,
+ forwarder->stats.countObjectsReceived, forwarder->stats.countDropped,
+ forwarder->stats.countInterestsDropped,
+ forwarder->stats.countObjectsDropped, forwarder->stats.countOtherDropped,
+ forwarder->stats.countInterestForwarded,
+ forwarder->stats.countObjectsForwarded,
+ forwarder->stats.countDroppedConnectionNotFound,
+ forwarder->stats.countSendFailures, forwarder->stats.countDroppedNoRoute,
+ forwarder->stats.countInterestsAggregated,
+ forwarder->stats.countInterestsRetransmitted,
+ forwarder->stats.countInterestsSatisfiedFromStore,
+ forwarder->stats.countInterestsExpired, forwarder->stats.countDataExpired,
+ forwarder->stats.countDroppedNoReversePath);
}
-#endif /* WITH_MAPME */
+forwarder_stats_t forwarder_get_stats(forwarder_t *forwarder) {
+ return forwarder->stats;
+}
diff --git a/hicn-light/src/hicn/core/forwarder.h b/hicn-light/src/hicn/core/forwarder.h
index d1815b7d4..b7ce5ff4d 100644
--- a/hicn-light/src/hicn/core/forwarder.h
+++ b/hicn-light/src/hicn/core/forwarder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,292 +18,241 @@
* only be called within the forwarders thread of execution.
*/
-#ifndef forwarder_h
-#define forwarder_h
+#ifndef HICNLIGHT_FORWARDER_H
+#define HICNLIGHT_FORWARDER_H
-#ifndef _WIN32
-#include <sys/time.h>
-#endif
-#include <stdlib.h>
-
-#include <hicn/core/connectionTable.h>
-#include <hicn/core/dispatcher.h>
-#include <hicn/messenger/messenger.h>
+//#ifndef _WIN32
+//#include <sys/time.h>
+//#endif
+//
-#include <hicn/core/message.h>
+#include <stdlib.h>
+#include <sys/socket.h> // struct mmsghdr
-#include <hicn/config/configuration.h>
+#include "connection.h"
+#include "connection_table.h"
+#include "packet_cache.h"
+#include "listener_table.h"
+#include "msgbuf.h"
+#include "msgbuf_pool.h"
+#include "../config/configuration.h"
+#include "subscription.h"
#ifdef WITH_MAPME
-#include <hicn/processor/fib.h>
+#include "fib.h"
#endif /* WITH_MAPME */
-#include <hicn/core/logger.h>
-#include <hicn/core/ticks.h>
-#include <hicn/io/listenerSet.h>
-
-#include <hicn/processor/fibEntryList.h>
-
-#include <parc/algol/parc_Clock.h>
-
-#if !defined(__APPLE__)
-#include <hicn/socket/api.h>
-#endif
-
#define PORT_NUMBER 9695
#define PORT_NUMBER_AS_STRING "9695"
-#include <hicn/utils/commands.h>
+//#include <hicn/utils/commands.h>
// ==============================================
-struct forwarder;
-typedef struct forwarder Forwarder;
+typedef struct forwarder_s forwarder_t;
/**
- * @function forwarder_Create
- * @abstract Create the forwarder and use the provided logger for diagnostic
+ * @brief Create the forwarder and use the provided logger for diagnostic
* output
* @discussion
* If the logger is null, hicn-light will create a STDOUT logger.
*
* @param logger may be NULL
*/
-Forwarder *forwarder_Create(Logger *logger);
+forwarder_t *forwarder_create(configuration_t *configuration);
/**
- * @function forwarder_Destroy
- * @abstract Destroys the forwarder, stopping all traffic and freeing all memory
+ * @brief Destroys the forwarder, stopping all traffic and freeing all memory
*/
-void forwarder_Destroy(Forwarder **ptr);
+void forwarder_free(forwarder_t *forwarder);
/**
- * @function forwarder_SetupAllListeners
- * @abstract Setup all listeners (tcp, udp, local, ether, ip multicast) on all
- * interfaces
- * @discussion
- * Sets up all listeners on all running interfaces. This provides a quick and
- * easy startup, rather than providing a configuration file or programmatic
- * commands.
- *
- * @param port is used by TCP and UDP listeners, in host byte order
- * @param localPath is the AF_UNIX path to use, if NULL no AF_UNIX listener is
- * setup
- */
-void forwarder_SetupAllListeners(Forwarder *forwarder, uint16_t port,
- const char *localPath);
-/**
- * @function forwarder_SetupAllListeners
- * @abstract Setup one tcp and one udp listener on address 127.0.0.1 and the
+ * @brief Setup one tcp and one udp listener on address 127.0.0.1 and the
* given port
*/
-void forwarder_SetupLocalListeners(Forwarder *forwarder, uint16_t port);
-
-/**
- * Configure hicn-light via a configuration file
- *
- * The configuration file is a set of lines, just like used in hicnLightControl.
- * You need to have "add listener" lines in the file to receive connections. No
- * default listeners are configured.
- *
- * @param [in] forwarder An alloated Forwarder
- * @param [in] filename The path to the configuration file
- */
-void forwarder_SetupFromConfigFile(Forwarder *forwarder, const char *filename);
-
-/**
- * Returns the logger used by this forwarder
- *
- * If you will store the logger, you should acquire a reference to it.
- *
- * @param [in] forwarder An allocated hicn-light forwarder
- *
- * @retval non-null The logger used by hicn-light
- * @retval null An error
- */
-Logger *forwarder_GetLogger(const Forwarder *forwarder);
-
-/**
- * @function forwarder_SetLogLevel
- * @abstract Sets the minimum level to log
- */
-void forwarder_SetLogLevel(Forwarder *forwarder, PARCLogLevel level);
+void forwarder_setup_local_listeners(forwarder_t *forwarder, uint16_t port);
-/**
- * @function forwarder_GetNextConnectionId
- * @abstract Get the next identifier for a new connection
- */
-unsigned forwarder_GetNextConnectionId(Forwarder *forwarder);
+configuration_t *forwarder_get_configuration(forwarder_t *forwarder);
-Messenger *forwarder_GetMessenger(Forwarder *forwarder);
-
-Dispatcher *forwarder_GetDispatcher(Forwarder *forwarder);
+subscription_table_t *forwarder_get_subscriptions(const forwarder_t *forwarder);
/**
* Returns the set of currently active listeners
*
- * @param [in] forwarder An allocated hicn-light forwarder
+ * @param[in] forwarder An allocated hicn-light forwarder
*
* @retval non-null The set of active listeners
* @retval null An error
*/
-ListenerSet *forwarder_GetListenerSet(Forwarder *forwarder);
+listener_table_t *forwarder_get_listener_table(const forwarder_t *forwarder);
/**
* Returns the forwrder's connection table
*
- * @param [in] forwarder An allocated hicn-light forwarder
+ * @param[in] forwarder An allocated hicn-light forwarder
*
* @retval non-null The connection tabler
* @retval null An error
*
*/
-#ifdef WITH_POLICY
-ConnectionTable *forwarder_GetConnectionTable(const Forwarder *forwarder);
-#else
-ConnectionTable *forwarder_GetConnectionTable(Forwarder *forwarder);
-#endif /* WITH_POLICY */
+connection_table_t *forwarder_get_connection_table(
+ const forwarder_t *forwarder);
-/**
- * Returns a Tick-based clock
- *
- * Runs at approximately 1 msec per tick (see HZ in forwarder.c).
- * Do not Release this clock. If you save a copy of it, create your own
- * reference to it with parcClock_Acquire().
- *
- * @param [in] forwarder An allocated hicn-light forwarder
- *
- * @retval non-null An allocated hicn-light Clock based on the Tick counter
- * @retval null An error
- */
-PARCClock *forwarder_GetClock(const Forwarder *forwarder);
+pkt_cache_t *forwarder_get_pkt_cache(const forwarder_t *forwarder);
-/**
- * Direct call to get the Tick clock
- *
- * Runs at approximately 1 msec per tick (see HZ in forwarder.c)
- *
- * @param [in] forwarder An allocated hicn-light forwarder
- */
-Ticks forwarder_GetTicks(const Forwarder *forwarder);
+void forwarder_cs_set_store(forwarder_t *forwarder, bool val);
+
+bool forwarder_cs_get_store(forwarder_t *forwarder);
+
+void forwarder_cs_set_serve(forwarder_t *forwarder, bool val);
+
+bool forwarder_cs_get_serve(forwarder_t *forwarder);
/**
- * Convert nano seconds to Ticks
+ * Sets the maximum number of content objects in the content store
*
- * Converts nano seconds to Ticks, based on HZ (in forwarder.c)
+ * Implementation dependent - may wipe the cache.
*/
-Ticks forwarder_NanosToTicks(uint64_t nanos);
-
-uint64_t forwarder_TicksToNanos(Ticks ticks);
-
-void forwarder_ReceiveCommand(Forwarder *forwarder, command_id command,
- struct iovec *message, unsigned ingressId);
+void forwarder_cs_set_size(forwarder_t *forwarder, size_t size);
-void forwarder_Receive(Forwarder *forwarder, Message *mesage);
+size_t forwarder_cs_get_size(forwarder_t *forwarder);
+size_t forwarder_cs_get_num_stale_entries(forwarder_t *forwarder);
+void forwarder_cs_clear(forwarder_t *forwarder);
/**
- * @function forwarder_AddOrUpdateRoute
- * @abstract Adds or updates a route on all the message processors
+ * @brief Adds or updates a route on all the message processors
*/
-bool forwarder_AddOrUpdateRoute(Forwarder *forwarder,
- add_route_command *control, unsigned ifidx);
+bool forwarder_add_or_update_route(forwarder_t *forwarder,
+ hicn_ip_prefix_t *prefix,
+ unsigned ingress_id);
/**
- * @function forwarder_RemoveRoute
- * @abstract Removes a route from all the message processors
+ * @brief Removes a route from all the message processors
*/
-bool forwarder_RemoveRoute(Forwarder *forwarder, remove_route_command *control,
- unsigned ifidx);
+bool forwarder_remove_route(forwarder_t *forwarder, hicn_ip_prefix_t *prefix,
+ unsigned ingress_id);
#ifdef WITH_POLICY
/**
- * @function forwarder_AddOrUpdatePolicy
- * @abstract Adds or updates a policy on the message processor
+ * @brief Adds or updates a policy on the message processor
*/
-bool forwarder_AddOrUpdatePolicy(Forwarder *forwarder, add_policy_command *control);
+bool forwarder_add_or_update_policy(forwarder_t *forwarder,
+ hicn_ip_prefix_t *prefix,
+ hicn_policy_t *policy);
/**
- * @function forwarder_RemovePolicy
- * @abstract Removes a policy from the message processor
+ * @brief Removes a policy from the message processor
*/
-bool forwarder_RemovePolicy(Forwarder *forwarder, remove_policy_command *control);
+bool forwarder_remove_policy(forwarder_t *forwarder, hicn_ip_prefix_t *prefix);
+
#endif /* WITH_POLICY */
/**
* Removes a connection id from all routes
*/
-void forwarder_RemoveConnectionIdFromRoutes(Forwarder *forwarder,
- unsigned connectionId);
+void forwarder_remove_connection_id_from_routes(const forwarder_t *forwarder,
+ unsigned connection_id);
-/**
- * @function forwarder_GetConfiguration
- * @abstract The configuration object
- * @discussion
- * The configuration contains all user-issued commands. It does not include
- * dynamic state.
- */
-Configuration *forwarder_GetConfiguration(Forwarder *forwarder);
+void forwarder_add_strategy_options(forwarder_t *forwarder,
+ hicn_prefix_t *name_prefix,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options);
+
+void forwarder_set_strategy(forwarder_t *forwarder, hicn_prefix_t *prefix,
+ strategy_type_t strategy_type,
+ strategy_options_t *strategy_options);
-FibEntryList *forwarder_GetFibEntries(Forwarder *forwarder);
+cs_t *forwarder_get_cs(const forwarder_t *forwarder);
+
+off_t *forwarder_get_acquired_msgbuf_ids(const forwarder_t *forwarder);
/**
- * Sets the maximum number of content objects in the content store
- *
- * Implementation dependent - may wipe the cache.
+ * @note Acquire msgbuf ids vector ONLY for read-only operations.
*/
-void forwarder_SetContentObjectStoreSize(Forwarder *forwarder,
- size_t maximumContentStoreSize);
-
-void forwarder_SetChacheStoreFlag(Forwarder *forwarder, bool val);
+off_t *forwarder_get_acquired_msgbuf_ids(const forwarder_t *forwarder);
-bool forwarder_GetChacheStoreFlag(Forwarder *forwarder);
+void forwarder_acquired_msgbuf_ids_reset(const forwarder_t *forwarder);
-void forwarder_SetChacheServeFlag(Forwarder *forwarder, bool val);
+void forwarder_acquired_msgbuf_ids_push(const forwarder_t *forwarder,
+ off_t msgbuf_id);
-bool forwarder_GetChacheServeFlag(Forwarder *forwarder);
+/**
+ * @brief Returns the forwarder's FIB.
+ * @param[in] forwarder - Pointer to the forwarder.
+ * @returns Pointer to the hICN FIB.
+ */
+fib_t *forwarder_get_fib(const forwarder_t *forwarder);
-void forwarder_ClearCache(Forwarder *forwarder);
+/**
+ * @brief Return the forwarder packet pool.
+ * @param[in] forwarder The forwarder from which to retrieve the packet
+ * pool.
+ * @return msgbuf_pool_t * The forwarder packet pool.
+ */
+msgbuf_pool_t *forwarder_get_msgbuf_pool(const forwarder_t *forwarder);
-void forwarder_SetStrategy(Forwarder *forwarder, Name *prefix,
- strategy_type strategy, unsigned related_prefixes_len,
- Name **related_prefixes);
-#if !defined(__APPLE__)
-hicn_socket_helper_t *forwarder_GetHicnSocketHelper(Forwarder *forwarder);
-#endif
#ifdef WITH_MAPME
-/**
- * @function forwarder_getFib
- * @abstract Returns the hICN forwarder's FIB.
- * @param [in] forwarder - Pointer to the hICN forwarder.
- * @returns Pointer to the hICN FIB.
- */
-FIB *forwarder_getFib(Forwarder *forwarder);
+void forwarder_on_route_event(const forwarder_t *forwarder, fib_entry_t *entry);
+
+int forwarder_add_connection(const forwarder_t *forwarder,
+ const char *symbolic_name, face_type_t type,
+ address_pair_t *pair, policy_tags_t tags,
+ int priority, face_state_t admin_state);
+
+int forwarder_remove_connection(const forwarder_t *forwarder,
+ unsigned connection_id, bool finalize);
/**
- * @function forwarder_onConnectionEvent
- * @abstract Callback fired upon addition of a new connection through the
+ * @brief Callback fired upon addition of a new connection through the
* control protocol.
- * @param [in] forwarder - Pointer to the hICN forwarder.
- * @param [in] conn - Pointer to the newly added connection.
- * @param [in] event - Connection event
+ * @param[in] forwarder - Pointer to the forwarder.
+ * @param[in] conn - Pointer to the newly added connection.
+ * @param[in] event - Connection event
*/
-void forwarder_onConnectionEvent(Forwarder *forwarder, const Connection *conn, connection_event_t event);
+void forwarder_on_connection_event(const forwarder_t *forwarder,
+ const connection_t *connection,
+ connection_event_t event);
/**
- * @function forwarder_ProcessMapMe
- * @abstract Callback fired by an hICN listener upon reception of a MAP-Me
+ * @brief Callback fired by an hICN listener upon reception of a MAP-Me
* message.
- * @param [in] forwarder - Pointer to the hICN forwarder.
- * @param [in] msgBuffer - MAP-Me buffer
- * @param [in] conn_id - Ingress connection id
+ * @param[in] forwarder - Pointer to the forwarder.
+ * @param[in] msgBuffer - MAP-Me buffer
+ * @param[in] conn_id - Ingress connection id
*/
-void forwarder_ProcessMapMe(Forwarder *forwarder, const uint8_t *msgBuffer,
- unsigned conn_id);
+void forwarder_process_mapme(const forwarder_t *forwarder,
+ const uint8_t *packet, unsigned conn_id);
-struct mapme;
-struct mapme * forwarder_getMapmeInstance(const Forwarder *forwarder);
+struct mapme_s *forwarder_get_mapme(const forwarder_t *forwarder);
#endif /* WITH_MAPME */
-#endif // forwarder_h
+#ifdef WITH_POLICY_STATS
+const policy_stats_mgr_t *forwarder_get_policy_stats_mgr(
+ const forwarder_t *forwarder);
+#endif /* WITH_POLICY_STATS */
+
+void forwarder_flush_connections(forwarder_t *forwarder);
+
+/**
+ * @brief Handles a newly received packet from a listener.
+ *
+ * NOTE: the received msgbuf is incomplete and only holds the packet content and
+ * size/
+ */
+ssize_t forwarder_receive(forwarder_t *forwarder, listener_t *listener,
+ off_t msgbuf_id, address_pair_t *pair, Ticks now);
+
+/**
+ * @brief Log forwarder statistics, e.g. info about packets processed, packets
+ * dropped, packets forwarded, errors while forwarding, interest and data
+ * processing results.
+ *
+ * @param forwarder Pointer to the forwarder data structure to use
+ */
+void forwarder_log(forwarder_t *forwarder);
+
+forwarder_stats_t forwarder_get_stats(forwarder_t *forwarder);
+
+#endif // HICNLIGHT_FORWARDER_H
diff --git a/hicn-light/src/hicn/core/listener.c b/hicn-light/src/hicn/core/listener.c
new file mode 100644
index 000000000..d2f547863
--- /dev/null
+++ b/hicn-light/src/hicn/core/listener.c
@@ -0,0 +1,425 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file listener.c
+ * @brief Implementation of hICN listeners
+ */
+
+#include <string.h> // strdup
+
+#include <hicn/util/log.h>
+
+#include "forwarder.h"
+#include "listener_vft.h"
+#include "../io/base.h"
+
+listener_key_t listener_key_factory(address_t address, face_type_t type) {
+ listener_key_t key;
+ memset(&key, 0, sizeof(listener_key_t));
+
+ key.address = address;
+ key.type = type;
+ return key;
+}
+
+listener_t *listener_create(face_type_t type, const address_t *address,
+ const char *interface_name, const char *name,
+ forwarder_t *forwarder) {
+ listener_table_t *table = forwarder_get_listener_table(forwarder);
+
+ listener_key_t key = listener_key_factory(*address, type);
+
+ listener_t *listener = listener_table_allocate(table, &key, name);
+ unsigned listener_id =
+ (unsigned int)listener_table_get_listener_id(table, listener);
+
+ int ret = listener_initialize(listener, type, name, listener_id, address,
+ interface_name, forwarder);
+ if (ret < 0) {
+ listener_table_remove_by_id(table, listener_id);
+ listener_finalize(listener);
+ return NULL;
+ }
+
+ WITH_INFO({
+ char addr_str[NI_MAXHOST];
+ int port;
+ address_to_string(address, addr_str, &port);
+ INFO("LISTENER CREATE (%s) %p created for address %s:%d",
+ face_type_str(listener->type), listener, addr_str, port);
+ listener_table_print_by_key(table);
+ })
+
+ return listener;
+}
+
+int listener_initialize(listener_t *listener, face_type_t type,
+ const char *name, unsigned listener_id,
+ const address_t *address, const char *interface_name,
+ forwarder_t *forwarder) {
+ int rc;
+
+ assert(listener);
+ assert(forwarder);
+
+ *listener = (listener_t){
+ .id = listener_id,
+ .name = strdup(name),
+ .key = listener_key_factory(*address, type),
+ .interface_name = strdup(interface_name),
+ .family = address->as_ss.ss_family,
+ .fd = 0,
+ .forwarder = forwarder,
+ };
+
+ face_protocol_t face_protocol = get_protocol(listener->type);
+ if (face_protocol == FACE_PROTOCOL_UNKNOWN) goto ERR_VFT;
+
+ listener->data = malloc(listener_vft[face_protocol]->data_size);
+ if (!listener->data) goto ERR_DATA;
+
+ assert(listener_has_valid_type(listener));
+
+ rc = listener_vft[face_protocol]->initialize(listener);
+ if (rc < 0) goto ERR_VFT;
+
+ listener->fd = listener_vft[face_protocol]->get_socket(listener, address,
+ NULL, interface_name);
+ if (listener->fd < 0) {
+ char addr_str[NI_MAXHOST];
+ int port;
+ address_to_string(address, addr_str, &port);
+ ERROR("Error creating listener %s fd: (%d) %s", addr_str, errno,
+ strerror(errno));
+ goto ERR_FD;
+ }
+ assert(listener->fd > 0);
+
+ // XXX data should be pre-allocated here
+
+ loop_fd_event_create(&listener->event_data, MAIN_LOOP, listener->fd, listener,
+ (fd_callback_t)listener_read_callback,
+ CONNECTION_ID_UNDEFINED, NULL);
+
+ if (!listener->event_data) {
+ goto ERR_REGISTER_FD;
+ }
+
+ if (loop_fd_event_register(listener->event_data) < 0) {
+ goto ERR_REGISTER_FD;
+ }
+
+ return 0;
+
+ERR_REGISTER_FD:
+#ifndef _WIN32
+ close(listener->fd);
+#else
+ closesocket(listener->fd);
+#endif
+ERR_FD:
+ERR_VFT:
+ERR_DATA:
+ return -1;
+}
+
+int listener_finalize(listener_t *listener) {
+ assert(listener);
+ assert(listener_has_valid_type(listener));
+
+ if (listener->event_data) {
+ loop_event_unregister(listener->event_data);
+ loop_event_free(listener->event_data);
+ }
+
+ if (listener->fd != -1) {
+#ifndef _WIN32
+ close(listener->fd);
+#else
+ closesocket(listener->fd);
+#endif
+ }
+
+ listener_vft[get_protocol(listener->type)]->finalize(listener);
+
+ if (listener->data) free(listener->data);
+ listener->data = NULL;
+ if (listener->interface_name) free(listener->interface_name);
+ listener->interface_name = NULL;
+ if (listener->name) free(listener->name);
+ listener->name = NULL;
+
+ return 0;
+}
+
+int listener_get_socket(const listener_t *listener, const address_t *local,
+ const address_t *remote, const char *interface_name) {
+ assert(listener);
+ assert(listener_has_valid_type(listener));
+ assert(local);
+ // assert(remote); TODO: can it be null?
+
+ // DEBUG("[listener_get_socket]");
+
+ return listener_vft[get_protocol(listener->type)]->get_socket(
+ listener, local, remote, interface_name);
+}
+
+/*
+ * This is called from the forwarder to dynamially create new connections on the
+ * listener, in that case, name is NULL. It is also called from
+ * connection_create, which is itself called from the configuration part.
+ */
+unsigned listener_create_connection(listener_t *listener,
+ const char *connection_name,
+ const address_pair_t *pair) {
+ assert(listener);
+ assert(listener_has_valid_type(listener));
+ assert(pair);
+
+ /* initialized so that gcc-9 does not complain */
+ face_type_t connection_type = FACE_TYPE_UNDEFINED;
+ switch (listener->type) {
+ case FACE_TYPE_UDP_LISTENER:
+ connection_type = FACE_TYPE_UDP;
+ break;
+ case FACE_TYPE_TCP_LISTENER:
+ connection_type = FACE_TYPE_TCP;
+ break;
+ case FACE_TYPE_HICN:
+ case FACE_TYPE_HICN_LISTENER:
+ case FACE_TYPE_UDP:
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_N:
+ return CONNECTION_ID_UNDEFINED;
+ }
+
+#ifdef USE_CONNECTED_SOCKETS
+ /*
+ * We create a connected connection with its own fd, instead of returning
+ * the fd of the listener. This will allow to avoid specifying the
+ * destination address when sending packets, and will increase performance
+ * by avoiding a FIB lookup for each packet.
+ */
+ int fd = listener_get_socket(listener, address_pair_get_local(pair),
+ address_pair_get_remote(pair),
+ listener->interface_name);
+ if (fd < 0) return CONNECTION_ID_UNDEFINED;
+#else
+ int fd = 0; // means listener->fd;
+#endif
+ bool local = address_is_local(address_pair_get_local(pair));
+
+ connection_table_t *table =
+ forwarder_get_connection_table(listener->forwarder);
+ connection_t *connection =
+ connection_table_allocate(table, pair, connection_name);
+ unsigned connection_id =
+ (unsigned int)connection_table_get_connection_id(table, connection);
+
+ int rc = connection_initialize(connection, connection_type, connection_name,
+ listener->interface_name, fd, pair, local,
+ connection_id, listener);
+ if (rc < 0) {
+ connection_table_remove_by_id(table, connection_id);
+ connection_finalize(connection);
+ return CONNECTION_ID_UNDEFINED;
+ }
+
+ WITH_INFO({
+ char local_addr_str[NI_MAXHOST];
+ char remote_addr_str[NI_MAXHOST];
+ int local_port;
+ int remote_port;
+ address_to_string(&(pair->local), local_addr_str, &local_port);
+ address_to_string(&(pair->remote), remote_addr_str, &remote_port);
+ INFO("%s connection %p created for address pair %s:%d (local=%s) - %s:%d",
+ face_type_str(connection->type), connection, local_addr_str,
+ local_port, connection_is_local(connection) ? "true" : "false",
+ remote_addr_str, remote_port);
+ connection_table_print_by_pair(table);
+ })
+
+ forwarder_on_connection_event(listener->forwarder, connection,
+ CONNECTION_EVENT_CREATE);
+
+ return connection_id;
+}
+
+int listener_punt(const listener_t *listener, const char *prefix_s) {
+ assert(listener);
+ assert(listener_get_type(listener) == FACE_TYPE_HICN);
+ assert(prefix_s);
+
+ return listener_vft[get_protocol(listener->type)]->punt(listener, prefix_s);
+}
+
+ssize_t listener_read_single(listener_t *listener, int fd,
+ unsigned connection_id) {
+ assert(listener);
+
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(listener->forwarder);
+
+ // Preapare the msgbuf
+ msgbuf_t *msgbuf = NULL;
+ off_t msgbuf_id = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ if (!msgbuf_id_is_valid(msgbuf_id)) return -1;
+
+ // Prepare the address pair
+ address_pair_t pair;
+ memset(&pair, 0, sizeof(address_pair_t));
+ pair.local = listener->address;
+
+ // Read message and populate the remote address
+ ssize_t n = listener_vft[get_protocol(listener->type)]->read_single(
+ fd, msgbuf, address_pair_get_remote(&pair));
+ if (n <= 0) {
+ msgbuf_pool_put(msgbuf_pool, msgbuf);
+ return -1;
+ }
+
+ msgbuf_pool_acquire(msgbuf);
+ msgbuf_set_connection_id(msgbuf, connection_id);
+
+ // Process received packet
+ size_t processed_bytes = forwarder_receive(listener->forwarder, listener,
+ msgbuf_id, &pair, ticks_now());
+ forwarder_log(listener->forwarder);
+ if (processed_bytes <= 0) ERROR("Unable to handle message");
+
+ /*
+ * The connection on which we went packets might do batching (even without
+ * sendmmsg), and we need to inform the system that we want to proceed to
+ * sending packets.
+ */
+ forwarder_flush_connections(listener->forwarder);
+ msgbuf_pool_release(msgbuf_pool, &msgbuf);
+ return processed_bytes;
+}
+
+ssize_t listener_read_batch(listener_t *listener, int fd,
+ unsigned connection_id) {
+ assert(listener);
+
+ size_t total_processed_bytes = 0;
+ ssize_t num_msg_received = 0;
+
+ forwarder_t *forwarder = listener->forwarder;
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ forwarder_acquired_msgbuf_ids_reset(forwarder);
+
+ /* Receive messages in the loop as long as we manage to fill the buffers */
+ do {
+ /* Prepare the msgbuf and address pair arrays */
+ msgbuf_t *msgbufs[MAX_MSG];
+ if (msgbuf_pool_getn(msgbuf_pool, msgbufs, MAX_MSG) < 0) {
+ ERROR("Unable to get message buffers");
+ break;
+ }
+
+ address_pair_t pair[MAX_MSG];
+ address_t *address_remote[MAX_MSG];
+ memset(&pair, 0, MAX_MSG * sizeof(address_pair_t));
+
+ off_t msgbuf_ids[MAX_MSG];
+ for (unsigned i = 0; i < MAX_MSG; i++) {
+ // Copy the pointers to the remote addresses
+ address_remote[i] = address_pair_get_remote(&pair[i]);
+
+ // Populate local addresses
+ pair[i].local = listener->address;
+
+ // Do NOT rely on msgbuf pointers since a msgbuf pool rezise event may
+ // make them invalid, use msgbuf ids instead
+ msgbuf_ids[i] = msgbuf_pool_get_id(msgbuf_pool, msgbufs[i]);
+ }
+
+ // Read batch and populate remote addresses
+ num_msg_received = listener_vft[get_protocol(listener->type)]->read_batch(
+ fd, msgbufs, address_remote, MAX_MSG);
+
+ for (int i = 0; i < MAX_MSG; i++) {
+ // Release unused msg buffers
+ if (i >= num_msg_received) {
+ msgbuf_pool_put(msgbuf_pool, msgbufs[i]);
+ continue;
+ }
+
+ msgbuf_pool_acquire(msgbufs[i]);
+ msgbuf_set_connection_id(msgbufs[i], connection_id);
+ forwarder_acquired_msgbuf_ids_push(forwarder, msgbuf_ids[i]);
+ }
+
+ if (num_msg_received < 0) break;
+ TRACE("[listener_read_batch] batch size = %d", num_msg_received);
+
+ for (unsigned i = 0; i < num_msg_received; i++) {
+ size_t processed_bytes = forwarder_receive(
+ forwarder, listener, msgbuf_ids[i], &pair[i], ticks_now());
+ forwarder_log(listener->forwarder);
+
+ total_processed_bytes += processed_bytes;
+ }
+ } while (num_msg_received ==
+ MAX_MSG); /* backpressure based on queue size ? */
+
+ /*
+ * Signal to the forwarder that we reached the end of a batch and we need to
+ * flush connections out
+ */
+ forwarder_flush_connections(forwarder);
+
+ const off_t *acquired_msgbuf_ids =
+ forwarder_get_acquired_msgbuf_ids(forwarder);
+ for (int i = 0; i < vector_len(acquired_msgbuf_ids); i++) {
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, acquired_msgbuf_ids[i]);
+ msgbuf_pool_release(msgbuf_pool, &msgbuf);
+ }
+
+ return total_processed_bytes;
+}
+
+/*
+ * This might be called for a connection on the listener too. The listener is
+ * the entity that owns the buffers used for reading.
+ */
+ssize_t listener_read_callback(listener_t *listener, int fd,
+ unsigned connection_id, void *user_data) {
+ assert(listener);
+ assert(!user_data);
+
+ /*
+ * As the listener callback is shared between the listener and the different
+ * connections created on top of it, the fd might be either of them.
+ */
+ // assert(fd == listener->fd);
+
+ if (listener_vft[get_protocol(listener->type)]->read_batch)
+ return listener_read_batch(listener, fd, connection_id);
+
+ return listener_read_single(listener, fd, connection_id);
+}
+
+void listener_setup_local(forwarder_t *forwarder, uint16_t port) {
+ address_t localhost_ipv4_addr = ADDRESS4_LOCALHOST(port);
+ listener_create(FACE_TYPE_UDP_LISTENER, &localhost_ipv4_addr, "lo", "lo_udp4",
+ forwarder);
+
+ address_t localhost_ipv6_addr = ADDRESS6_LOCALHOST(port);
+ listener_create(FACE_TYPE_UDP_LISTENER, &localhost_ipv6_addr, "lo", "lo_udp6",
+ forwarder);
+}
diff --git a/hicn-light/src/hicn/core/listener.h b/hicn-light/src/hicn/core/listener.h
new file mode 100644
index 000000000..76d865c5d
--- /dev/null
+++ b/hicn-light/src/hicn/core/listener.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file listener.h
+ * @brief hICN listeners
+ */
+
+#ifndef HICNLIGHT_LISTENER_H
+#define HICNLIGHT_LISTENER_H
+
+#include <hicn/face.h>
+
+#include "address_pair.h"
+#include "msgbuf.h"
+#include <hicn/base/loop.h>
+
+#define LISTENER_ID_UNDEFINED ~0
+
+struct forwarder_s;
+
+typedef struct {
+ address_t address;
+ face_type_t type;
+} listener_key_t;
+
+static inline int listener_key_equals(const listener_key_t *key1,
+ const listener_key_t *key2) {
+ return address_equals(&key1->address, &key2->address) &&
+ (key1->type == key2->type);
+}
+
+/**
+ * @brief Create a listener key starting from an address and a face type.
+ *
+ * @param address
+ * @param type
+ * @return listener_key_t The listener key created.
+ *
+ * @note The listener key returned is resetted before intializing
+ * the internal fields, to allow a reliable hash generation.
+ */
+listener_key_t listener_key_factory(address_t address, face_type_t type);
+
+/* This structure holds what is in common to all listeners */
+typedef struct {
+ int id;
+ char *name;
+ union {
+ listener_key_t key;
+ struct {
+ address_t address;
+ face_type_t type;
+ };
+ };
+
+ char *interface_name;
+ unsigned family;
+
+ int fd;
+ event_t *event_data;
+
+ void *data; /* Listener specific data */
+ struct forwarder_s *forwarder;
+} listener_t;
+
+#define listener_get_id(L) ((L)->id)
+#define listener_get_name(L) ((L)->name)
+#define listener_get_key(L) (&(L)->key)
+#define listener_get_type(L) ((L)->type)
+#define listener_get_interface_name(L) ((L)->interface_name)
+#define listener_get_address(L) (&(L)->address)
+#define listener_has_valid_type(L) (face_type_is_valid((L)->type))
+#define listener_id_is_valid(ID) (ID != LISTENER_ID_UNDEFINED)
+
+listener_t *listener_create(face_type_t type, const address_t *address,
+ const char *interface_name, const char *symbolic,
+ struct forwarder_s *forwarder);
+
+/**
+ * @brief Helper function used inside 'listener_create' to
+ * setup variables in listener struct.
+ *
+ * @see listener_create
+ */
+int listener_initialize(listener_t *listener, face_type_t type,
+ const char *name, unsigned listener_id,
+ const address_t *address, const char *interface_name,
+ struct forwarder_s *forwarder);
+
+int listener_finalize(listener_t *listener);
+
+int listener_punt(const listener_t *listener, const char *prefix_s);
+
+int listener_get_socket(const listener_t *listener, const address_t *local,
+ const address_t *remote, const char *interface_name);
+
+unsigned listener_create_connection(listener_t *listener, const char *name,
+ const address_pair_t *pair);
+
+void listener_setup_local(struct forwarder_s *forwarder, uint16_t port);
+
+void listener_process_packet(const listener_t *listener, const uint8_t *packet,
+ size_t size);
+
+ssize_t listener_read_single(listener_t *listener, int fd,
+ unsigned connection_id);
+ssize_t listener_read_batch(listener_t *listener, int fd,
+ unsigned connection_id);
+
+/**
+ * @brief Callback helper function for batch reading data from listener fd.
+ *
+ * This function is usually called from the listener read callback to proceed to
+ * actual reading of data from the fd.
+ *
+ * @see listener_read_callback
+ *
+ * NOTE: the function returns size_t as for TCP we might need to know how much
+ * data we can consume from the socket.
+ */
+ssize_t listener_read_callback(listener_t *listener, int fd,
+ unsigned connection_id, void *user_data);
+
+#define listener_get_forwarder(listener) (listener->forwarder)
+#define listener_get_fd(listener) (listener->fd)
+
+#endif /* HICNLIGHT_LISTENER_H */
diff --git a/hicn-light/src/hicn/core/listener_table.c b/hicn-light/src/hicn/core/listener_table.c
new file mode 100644
index 000000000..4a0f74a13
--- /dev/null
+++ b/hicn-light/src/hicn/core/listener_table.c
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file listener_table.c
+ * \brief Implementation of hICN listener table
+ */
+
+#include <hicn/util/log.h>
+#include <hicn/util/sstrncpy.h>
+
+#include "listener_table.h"
+#include "listener.h"
+
+/* This is only used as a hint for first allocation, as the table is resizeable
+ */
+#define DEFAULT_LISTENER_TABLE_SIZE 64
+
+typedef struct {
+ char name[SYMBOLIC_NAME_LEN];
+} name_key_t;
+
+listener_table_t *_listener_table_create(size_t init_size, size_t max_size) {
+ if (init_size == 0) init_size = DEFAULT_LISTENER_TABLE_SIZE;
+
+ listener_table_t *table = malloc(sizeof(listener_table_t));
+ if (!table) return NULL;
+
+ table->max_size = max_size;
+
+ /* Initialize indices */
+ table->id_by_name = kh_init_lt_name();
+ table->name_keys = slab_create(name_key_t, SLAB_INIT_SIZE);
+ table->id_by_key = kh_init_lt_key();
+ table->listener_keys = slab_create(listener_key_t, SLAB_INIT_SIZE);
+
+ /*
+ * We start by allocating a reasonably-sized pool, as this will eventually
+ * be resized if needed.
+ */
+ pool_init(table->listeners, init_size, 0);
+
+ return table;
+}
+
+void listener_table_free(listener_table_t *table) {
+ unsigned listener_id;
+ kh_foreach_value(table->id_by_key, listener_id, {
+ listener_t *listener = listener_table_get_by_id(table, listener_id);
+ const char *name = listener_get_name(listener);
+ INFO("Removing listener %s [%d]", name, listener->fd);
+ listener_finalize(listener);
+ });
+
+ kh_destroy_lt_name(table->id_by_name);
+ slab_free(table->name_keys);
+ kh_destroy_lt_key(table->id_by_key);
+ slab_free(table->listener_keys);
+
+ pool_free(table->listeners);
+ free(table);
+}
+
+listener_t *listener_table_allocate(const listener_table_t *table,
+ const listener_key_t *key,
+ const char *name) {
+ listener_t *listener = NULL;
+ pool_get(table->listeners, listener);
+ if (!listener) return NULL;
+
+ off_t id = listener - table->listeners;
+ int rc;
+
+ // Add in name hash table
+ name_key_t *name_copy = slab_get(name_key_t, table->name_keys);
+ strcpy_s(name_copy->name, sizeof(name_key_t), name);
+
+ khiter_t k = kh_put_lt_name(table->id_by_name, name_copy->name, &rc);
+ assert(rc == KH_ADDED || rc == KH_RESET);
+ kh_value(table->id_by_name, k) = (unsigned int)id;
+
+ // Add in key hash table
+ listener_key_t *key_copy = slab_get(listener_key_t, table->listener_keys);
+ memcpy(key_copy, key, sizeof(listener_key_t));
+
+ k = kh_put_lt_key(table->id_by_key, key_copy, &rc);
+ assert(rc == KH_ADDED || rc == KH_RESET);
+ kh_value(table->id_by_key, k) = (unsigned int)id;
+
+ assert(kh_size(table->id_by_name) == kh_size(table->id_by_key));
+ return listener;
+}
+
+void listener_table_deallocate(const listener_table_t *table,
+ listener_t *listener) {
+ const char *name = listener_get_name(listener);
+ listener_key_t *key = listener_get_key(listener);
+
+ // Remove from name hash table
+ khiter_t k = kh_get_lt_name(table->id_by_name, name);
+ assert(k != kh_end(table->id_by_name));
+ kh_del_lt_name(table->id_by_name, k);
+ slab_put(table->name_keys, kh_key(table->id_by_name, k));
+
+ // Remove from key hash table
+ k = kh_get_lt_key(table->id_by_key, key);
+ assert(k != kh_end(table->id_by_key));
+ kh_del_lt_key(table->id_by_key, k);
+ slab_put(table->listener_keys, kh_key(table->id_by_key, k));
+
+ assert(kh_size(table->id_by_name) == kh_size(table->id_by_key));
+ pool_put(table->listeners, listener);
+}
+
+listener_t *listener_table_get_by_address(listener_table_t *table,
+ face_type_t type,
+ const address_t *address) {
+ listener_key_t key = listener_key_factory(*address, type);
+ khiter_t k = kh_get_lt_key(table->id_by_key, &key);
+ if (k == kh_end(table->id_by_key)) return NULL;
+ return listener_table_at(table, kh_val(table->id_by_key, k));
+}
+
+listener_t *listener_table_get_by_key(listener_table_t *table,
+ const listener_key_t *key) {
+ khiter_t k = kh_get_lt_key(table->id_by_key, key);
+ if (k == kh_end(table->id_by_key)) return NULL;
+ return listener_table_at(table, kh_val(table->id_by_key, k));
+}
+
+void listener_table_remove_by_id(listener_table_t *table, off_t id) {
+ listener_t *listener = listener_table_at(table, id);
+ INFO("Removing listener %d (%s)", id, listener_get_name(listener));
+
+ listener_table_deallocate(table, listener);
+}
+
+off_t listener_table_get_id_by_name(const listener_table_t *table,
+ const char *name) {
+ khiter_t k = kh_get_lt_name(table->id_by_name, name);
+ if (k == kh_end(table->id_by_name)) return LISTENER_ID_UNDEFINED;
+ return kh_val(table->id_by_name, k);
+}
+
+listener_t *listener_table_get_by_name(listener_table_t *table,
+ const char *name) {
+ unsigned listener_id =
+ (unsigned int)listener_table_get_id_by_name(table, name);
+ if (!listener_id_is_valid(listener_id)) return NULL;
+ return listener_table_at(table, listener_id);
+}
+
+listener_t *_listener_table_get_by_id(listener_table_t *table, off_t id) {
+ return listener_table_get_by_id(table, id);
+}
+
+void listener_table_print_by_key(const listener_table_t *table) {
+ const listener_key_t *k;
+ unsigned v;
+
+ char addr_str[NI_MAXHOST];
+ int port;
+ listener_t *listener;
+ const char *name;
+
+ INFO("*** Listener table ***");
+ kh_foreach(table->id_by_key, k, v, {
+ address_to_string(&k->address, addr_str, &port);
+ listener = listener_table_get_by_id(table, v);
+ name = listener_get_name(listener);
+ INFO("%s:%d - %s\t\t\t\t(%u, %s)", addr_str, port, face_type_str(k->type),
+ v, name);
+ })
+}
+
+void listener_table_print_by_name(const listener_table_t *table) {
+ const char *k;
+ unsigned v;
+
+ char addr_str[NI_MAXHOST];
+ int port;
+ listener_t *listener;
+ const listener_key_t *key;
+
+ INFO("*** Listener table ***");
+ kh_foreach(table->id_by_name, k, v, {
+ listener = listener_table_get_by_id(table, v);
+ key = listener_get_key(listener);
+ address_to_string(&key->address, addr_str, &port);
+
+ INFO("%s:%d - %s\t\t\t\t(%u, %s)", addr_str, port, face_type_str(key->type),
+ v, k);
+ })
+}
diff --git a/hicn-light/src/hicn/core/listener_table.h b/hicn-light/src/hicn/core/listener_table.h
new file mode 100644
index 000000000..062d1748e
--- /dev/null
+++ b/hicn-light/src/hicn/core/listener_table.h
@@ -0,0 +1,270 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file listener_table.h
+ * \brief hICN listener table
+ *
+ * The listener table is composed of:
+ * - a pool of listeners allowing access through their index in constant time;
+ * - a set of indices in the form of hash table for efficient index lookups:
+ * . by name
+ * . by key (listener_type, address)
+ *
+ * For efficient index retrieval, the header will be prepended and the
+ * resulting pointer will directly point to the listener pool.
+ */
+
+#ifndef HICNLIGHT_LISTENER_TABLE_H
+#define HICNLIGHT_LISTENER_TABLE_H
+
+#include <hicn/util/khash.h>
+#include <hicn/util/hash.h>
+#include <hicn/util/slab.h>
+#include "address.h"
+#include "listener.h"
+#include <hicn/util/pool.h>
+
+/* Hash functions for indices */
+#define key_hash(key) (hash_struct(key))
+
+/* Hash table types for indices */
+KHASH_MAP_INIT_STR(lt_name, unsigned);
+KHASH_INIT(lt_key, const listener_key_t *, unsigned, 1, key_hash,
+ listener_key_equals);
+
+typedef struct {
+ size_t max_size;
+
+ kh_lt_key_t *id_by_key;
+ slab_t *listener_keys;
+ kh_lt_name_t *id_by_name;
+ slab_t *name_keys;
+
+ listener_t *listeners; // pool
+} listener_table_t;
+
+/**
+ * @brief Allocate a listener from the listener table.
+ *
+ * @param[in] table The listener table from which to allocate a listener.
+ * @param[out] listener The pointer that will hold the allocated listener.
+ * @param[in] pair The address pair associated to the listener (to update index)
+ * @param[in] name The name associated to the listener (to update index)
+ *
+ * NOTE:
+ * - This function updates all indices from the listener table if the
+ * allocation is successful.
+ * - You should always check that the returned listener is not NULL, which
+ * would signal that the pool is exhausted and could not be extended.
+ */
+listener_t *listener_table_allocate(const listener_table_t *table,
+ const listener_key_t *key,
+ const char *name);
+
+/**
+ * @brief Deallocate a listener and return it to the listener table pool.
+ *
+ * @param[in] table The listener table to which the listener is returned.
+ * @param[in] conn The listener that is returned to the pool.
+ *
+ * NOTE:
+ * - Upon returning a listener to the pool, all indices pointing to that
+ * listener are also cleared.
+ */
+void listener_table_deallocate(const listener_table_t *table,
+ listener_t *listener);
+
+/**
+ * @brief Returns the length of the listener table, the number of active
+ * listeners.
+ *
+ * @param[in] table The listener table for which we retrieve the length.
+ *
+ * @return size_t The length of the listener table.
+ *
+ * NOTE:
+ * - The length of the listener table, that is the number of currently active
+ * listeners.
+ */
+#define listener_table_len(table) (pool_len(table->listeners))
+
+/**
+ * @brief Validate an index in the listener table.
+ *
+ * @param[in] table The listener table in which to validate an index.
+ * @param[in] id The index of the listener to validate.
+ *
+ * @return bool A flag indicating whether the listener index is valid or not.
+ */
+#define listener_table_validate_id(table, id) \
+ pool_validate_id(table->listeners, id)
+
+/**
+ * @brief Return the listener corresponding to the specified index in the
+ * listener table.
+ *
+ * @param[in] table The listener table for which to retrieve the listener.
+ * @param[in] id The index for which to retrieve the listener.
+ *
+ * @return listener_t * The listener correponding to the specified index in
+ * the listener table.
+ *
+ * @see listener_table_get_by_id
+ *
+ * NOTE:
+ * - In this function, the index is not validated.
+ */
+#define listener_table_at(table, id) ((table)->listeners + id)
+
+/**
+ * @brief Return the listener corresponding to the specified and validated
+ * index in the listener table.
+ *
+ * @param[in] table The listener table for which to retrieve the listener.
+ * @param[in] id The index for which to retrieve the listener.
+ *
+ * @return listener_t * The listener correponding to the specified index in
+ * the listener table.
+ *
+ * @see listener_table_get_by_id
+ *
+ * NOTE:
+ * - In this function, the index is validated.
+ */
+#define listener_table_get_by_id(table, id) \
+ listener_table_validate_id(table, id) ? listener_table_at(table, id) : NULL
+
+/**
+ * @brief Helper function to avoid macro expansion in c++ tests. Wrapper around
+ * 'listener_table_get_by_id'.
+ */
+listener_t *_listener_table_get_by_id(listener_table_t *table, off_t id);
+
+/**
+ * @brief Returns the index of a given listener in the listener table.
+ *
+ * @param[in] table The listener table from which to retrieve the index.
+ * @param[in] conn The listener for which to retrieve the index.
+ *
+ * @return off_t The index of the specified listener in the listener table.
+ */
+#define listener_table_get_listener_id(table, listener) \
+ (listener - table->listeners)
+
+#define listener_table_foreach(table, listener, BODY) \
+ do { \
+ listener_t *listener; \
+ (void)listener; \
+ pool_foreach( \
+ table->listeners, listener, do { BODY } while (0)); \
+ } while (0)
+
+#define listener_table_enumerate(table, i, conn, BODY) \
+ pool_enumerate(table->listeners, (i), (conn), BODY)
+
+/**
+ * @brief Create a new listener table (extended parameters)
+ *
+ * @param[in] init_size Initially allocated size (hint, 0 = use default value)
+ * @param[in] max_size Maximum size (0 = unlimited)
+ *
+ * @return listener_table_t* - The newly created listener table
+ */
+listener_table_t *_listener_table_create(size_t init_size, size_t max_size);
+
+/**
+ * @brief Create a new listener table (minimal parameters)
+ *
+ * @return listener_table_t* - The newly created listener table
+ */
+#define listener_table_create() _listener_table_create(0, 0)
+
+/**
+ * @brief Free a listener table
+ *
+ * @param[in] table Listener table to free
+ */
+void listener_table_free(listener_table_t *table);
+
+/**
+ * @brief Retrieve a listener from the listener table by address.
+ *
+ * @param[in] table The listener table in which to search.
+ * @param[in] type The face type characterizing the listener to search for.
+ * @param[in] address The address to search for.
+ *
+ * @return listener_t * The listener matching the specified address, or
+ * NULL if not found.
+ */
+listener_t *listener_table_get_by_address(listener_table_t *table,
+ face_type_t type,
+ const address_t *address);
+
+/**
+ * @brief Retrieve a listener from the listener table by listener key (i.e.
+ * address + face type).
+ *
+ * @param[in] table The listener table in which to search.
+ * @param[in] key The listener key characterizing the listener to search for.
+ *
+ * @return listener_t * The listener matching the specified address, or
+ * NULL if not found.
+ */
+listener_t *listener_table_get_by_key(listener_table_t *table,
+ const listener_key_t *key);
+
+/**
+ * @brief Return a listener index from the listener table by name.
+ *
+ * @param[in] table The listener table in which to search.
+ * @param[in] name The name to search for.
+ *
+ * @return off_t The index of the listener matching the name, or
+ * LISTENER_ID_UNDEFINED if not found.
+ */
+off_t listener_table_get_id_by_name(const listener_table_t *table,
+ const char *name);
+
+/**
+ * @brief Return a listener from the listener table by name.
+ *
+ * @param[in] table The listener table in which to search.
+ * @param[in] name The name to search for.
+ *
+ * @return listener_t * The listener matching the name, or NULL if not
+ * found.
+ */
+listener_t *listener_table_get_by_name(listener_table_t *table,
+ const char *name);
+
+/**
+ * @brief Remove a listener from the listener table by its index.
+ *
+ * @param[in] table The listener table from which to delete the listener.
+ * @param[in] id The index of the listener to remove.
+ */
+void listener_table_remove_by_id(listener_table_t *table, off_t id);
+
+/**
+ * @brief Print the listener table content.
+ *
+ * @param[in] table The listener table to print.
+ */
+void listener_table_print_by_key(const listener_table_t *table);
+
+void listener_table_print_by_name(const listener_table_t *table);
+
+#endif /* HICNLIGHT_LISTENER_TABLE_H */
diff --git a/hicn-light/src/hicn/config/controlAddPolicy.h b/hicn-light/src/hicn/core/listener_vft.c
index 273e3a476..600c9482f 100644
--- a/hicn-light/src/hicn/config/controlAddPolicy.h
+++ b/hicn-light/src/hicn/core/listener_vft.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,22 +14,23 @@
*/
/**
- * @file control_AddPolicy.h
- * @brief Add a static policy
- *
- * Implements the "add policy" node of the CLI tree
- *
+ * @file listener_vft.c
+ * @brief Implementation of listener VFT
*/
-#ifndef Control_AddPolicy_h
-#define Control_AddPolicy_h
-
-#ifdef WITH_POLICY
+#include "listener_vft.h"
-#include <hicn/config/controlState.h>
-CommandOps *controlAddPolicy_Create(ControlState *state);
-CommandOps *controlAddPolicy_HelpCreate(ControlState *state);
+#ifdef __linux__
+extern listener_ops_t listener_hicn;
+#endif
+extern listener_ops_t listener_tcp;
+extern listener_ops_t listener_udp;
-#endif /* WITH_POLICY */
+const listener_ops_t* listener_vft[] = {
+#ifdef __linux__
+ [FACE_PROTOCOL_HICN] = &listener_hicn,
+#endif
-#endif // Control_AddPolicy_h
+ [FACE_PROTOCOL_TCP] = &listener_tcp,
+ [FACE_PROTOCOL_UDP] = &listener_udp,
+};
diff --git a/hicn-light/src/hicn/core/listener_vft.h b/hicn-light/src/hicn/core/listener_vft.h
new file mode 100644
index 000000000..97f08778c
--- /dev/null
+++ b/hicn-light/src/hicn/core/listener_vft.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file listener_vft.h
+ * @brief Listener VFT
+ */
+
+#ifndef HICNLIGHT_LISTENER_VFT_H
+#define HICNLIGHT_LISTENER_VFT_H
+
+#include <hicn/core/address_pair.h>
+#include <hicn/core/connection.h>
+#include <hicn/core/listener.h>
+#include <hicn/face.h>
+
+typedef struct {
+ int (*initialize)(listener_t* listener);
+ void (*finalize)(listener_t* listener);
+ int (*punt)(const listener_t* listener, const char* prefix_s);
+ int (*get_socket)(const listener_t* listener, const address_t* local,
+ const address_t* remote, const char* interface_name);
+ int (*send)(const connection_t* connection, const address_t* dummy,
+ msgbuf_t* msgbuf, bool queue);
+ int (*send_packet)(const connection_t* connection, const uint8_t* packet,
+ size_t size);
+ ssize_t (*read_single)(int fd, msgbuf_t* msgbuf, address_t* address);
+ ssize_t (*read_batch)(int fd, msgbuf_t** msgbuf, address_t** address,
+ size_t len);
+ size_t data_size;
+} listener_ops_t;
+
+#define DECLARE_LISTENER(NAME) \
+ const listener_ops_t listener_##NAME = { \
+ .initialize = listener_##NAME##_initialize, \
+ .finalize = listener_##NAME##_finalize, \
+ .punt = listener_##NAME##_punt, \
+ .get_socket = listener_##NAME##_get_socket, \
+ .read_single = listener_##NAME##_read_single, \
+ .read_batch = listener_##NAME##_read_batch, \
+ .data_size = sizeof(listener_##NAME##_data_t), \
+ }
+
+extern const listener_ops_t* listener_vft[];
+
+#endif /* HICNLIGHT_LISTENER_VFT_H */
diff --git a/hicn-light/src/hicn/core/logger.c b/hicn-light/src/hicn/core/logger.c
deleted file mode 100644
index 0b9bb264c..000000000
--- a/hicn-light/src/hicn/core/logger.c
+++ /dev/null
@@ -1,177 +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.
- */
-
-#ifndef _WIN32
-#include <unistd.h>
-#endif
-
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-
-#include <parc/logging/parc_Log.h>
-
-#include <hicn/core/forwarder.h>
-#include <hicn/core/logger.h>
-
-struct logger {
- PARCClock *clock;
-
- PARCLogReporter *reporter;
- PARCLog *loggerArray[LoggerFacility_END];
-};
-
-static const struct facility_to_string {
- LoggerFacility facility;
- const char *string;
-} _facilityToString[] = {
- {.facility = LoggerFacility_Config, .string = "Config"},
- {.facility = LoggerFacility_Core, .string = "Core"},
- {.facility = LoggerFacility_IO, .string = "IO"},
- {.facility = LoggerFacility_Message, .string = "Message"},
- {.facility = LoggerFacility_Processor, .string = "Processor"},
- {.facility = LoggerFacility_Strategy, .string = "Strategy"},
- {.facility = 0, .string = NULL}};
-
-const char *logger_FacilityString(LoggerFacility facility) {
- for (int i = 0; _facilityToString[i].string != NULL; i++) {
- if (_facilityToString[i].facility == facility) {
- return _facilityToString[i].string;
- }
- }
- return "Unknown";
-}
-
-static void _allocateLoggers(Logger *logger, PARCLogReporter *reporter) {
- parcTrapUnexpectedStateIf(
- logger->reporter != NULL,
- "Trying to allocate a reporter when the previous one is not null");
- logger->reporter = parcLogReporter_Acquire(reporter);
-
- char hostname[255];
- int gotHostName = gethostname(hostname, 255);
- if (gotHostName < 0) {
- snprintf(hostname, 255, "unknown");
- }
-
- for (int i = 0; i < LoggerFacility_END; i++) {
- logger->loggerArray[i] = parcLog_Create(hostname, logger_FacilityString(i),
- "forwarder", logger->reporter);
- parcLog_SetLevel(logger->loggerArray[i], PARCLogLevel_Error);
- }
-}
-
-static void _releaseLoggers(Logger *logger) {
- for (int i = 0; i < LoggerFacility_END; i++) {
- parcLog_Release(&logger->loggerArray[i]);
- }
- parcLogReporter_Release(&logger->reporter);
-}
-
-static void _destroyer(Logger **loggerPtr) {
- Logger *logger = *loggerPtr;
- _releaseLoggers(logger);
- parcClock_Release(&(*loggerPtr)->clock);
-}
-
-parcObject_ExtendPARCObject(Logger, _destroyer, NULL, NULL, NULL, NULL, NULL,
- NULL);
-
-parcObject_ImplementAcquire(logger, Logger);
-
-parcObject_ImplementRelease(logger, Logger);
-
-Logger *logger_Create(PARCLogReporter *reporter, const PARCClock *clock) {
- parcAssertNotNull(reporter, "Parameter reporter must be non-null");
- parcAssertNotNull(clock, "Parameter clock must be non-null");
-
- Logger *logger = parcObject_CreateAndClearInstance(Logger);
- if (logger) {
- logger->clock = parcClock_Acquire(clock);
- _allocateLoggers(logger, reporter);
- }
-
- return logger;
-}
-
-void logger_SetReporter(Logger *logger, PARCLogReporter *reporter) {
- parcAssertNotNull(logger, "Parameter logger must be non-null");
-
- // save the log level state
- PARCLogLevel savedLevels[LoggerFacility_END];
- for (int i = 0; i < LoggerFacility_END; i++) {
- savedLevels[i] = parcLog_GetLevel(logger->loggerArray[i]);
- }
-
- _releaseLoggers(logger);
-
- _allocateLoggers(logger, reporter);
-
- // restore log level state
- for (int i = 0; i < LoggerFacility_END; i++) {
- parcLog_SetLevel(logger->loggerArray[i], savedLevels[i]);
- }
-}
-
-void logger_SetClock(Logger *logger, PARCClock *clock) {
- parcAssertNotNull(logger, "Parameter logger must be non-null");
- parcClock_Release(&logger->clock);
- logger->clock = parcClock_Acquire(clock);
-}
-
-static void _assertInvariants(const Logger *logger, LoggerFacility facility) {
- parcAssertNotNull(logger, "Parameter logger must be non-null");
- parcTrapOutOfBoundsIf(facility >= LoggerFacility_END, "Invalid facility %d",
- facility);
-}
-
-void logger_SetLogLevel(Logger *logger, LoggerFacility facility,
- PARCLogLevel minimumLevel) {
- _assertInvariants(logger, facility);
- PARCLog *log = logger->loggerArray[facility];
- parcLog_SetLevel(log, minimumLevel);
-}
-
-bool logger_IsLoggable(const Logger *logger, LoggerFacility facility,
- PARCLogLevel level) {
- _assertInvariants(logger, facility);
- PARCLog *log = logger->loggerArray[facility];
- return parcLog_IsLoggable(log, level);
-}
-
-void logger_Log(Logger *logger, LoggerFacility facility, PARCLogLevel level,
- const char *module, const char *format, ...) {
- if (logger_IsLoggable(logger, facility, level)) {
- // this is logged as the messageid
- uint64_t logtime = parcClock_GetTime(logger->clock);
-
- // logger_IsLoggable asserted invariants so we know facility is in bounds
- PARCLog *log = logger->loggerArray[facility];
-
- va_list va;
- va_start(va, format);
-
- parcLog_MessageVaList(log, level, logtime, format, va);
-
- va_end(va);
- }
-}
diff --git a/hicn-light/src/hicn/core/logger.h b/hicn-light/src/hicn/core/logger.h
deleted file mode 100644
index 8ab741f40..000000000
--- a/hicn-light/src/hicn/core/logger.h
+++ /dev/null
@@ -1,170 +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.
- */
-
-/**
- * @file logger.h
- * @brief Logger for the hicn-light forwarder
- *
- * A facility based logger to allow selective logging from different parts of
- * hicn-light
- *
- */
-
-#ifndef logger_h
-#define logger_h
-
-#ifndef _WIN32
-#include <sys/time.h>
-#endif
-#include <parc/algol/parc_Buffer.h>
-#include <parc/algol/parc_Clock.h>
-#include <parc/logging/parc_LogLevel.h>
-#include <parc/logging/parc_LogReporter.h>
-#include <stdarg.h>
-
-struct logger;
-typedef struct logger Logger;
-
-/**
- * CONFIG faciilty concerns anything in the /config directory
- * CORE concerns anything in the /core directory
- * IO concerns anything in the /io directory (listeners, connectors, tcp,
- * ethernet, etc.) PROCESSOR concerns FIB, PIT, CS MESSAGE concerns message
- * events, like parsing
- */
-typedef enum {
- LoggerFacility_Config,
- LoggerFacility_Core,
- LoggerFacility_IO,
- LoggerFacility_Processor,
- LoggerFacility_Message,
- LoggerFacility_Strategy,
- LoggerFacility_END // sentinel value
-} LoggerFacility;
-
-/**
- * Returns a string representation of a facility
- *
- * Do not free the returned value.
- *
- * @param [in] facility The facility to change to a string
- *
- * @retval string A string representation of the facility
- */
-const char *logger_FacilityString(LoggerFacility facility);
-
-/**
- * Returns a string representation of a log level
- *
- * Do not free the returned value.
- *
- * @param [in] level The level to change to a string
- *
- * @retval string A string representation of the level
- */
-const char *logger_LevelString(PARCLogLevel level);
-
-/**
- * Create a logger that uses a given writer and clock
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] writer The output writer
- * @param [in] clock The clock to use for log messages
- *
- * @retval non-null An allocated logger
- * @retval null An error
- */
-Logger *logger_Create(PARCLogReporter *reporter, const PARCClock *clock);
-
-/**
- * Release logger
- */
-void logger_Release(Logger **loggerPtr);
-
-/**
- * Acquire logger
- */
-Logger *logger_Acquire(const Logger *logger);
-
-/**
- * Sets the minimum log level for a facility
- *
- * The default log level is ERROR. For a message to be logged, it must be of
- * equal or higher log level.
- *
- * @param [in] logger An allocated logger
- * @param [in] facility The facility to set the log level for
- * @param [in] The minimum level to log
- *
- */
-void logger_SetLogLevel(Logger *logger, LoggerFacility facility,
- PARCLogLevel minimumLevel);
-
-/**
- * Tests if the log level would be logged
- *
- * If the facility would log the given level, returns true. May be used as a
- * guard around expensive logging functions.
- *
- * @param [in] logger An allocated logger
- * @param [in] facility The facility to test
- * @param [in] The level to test
- *
- * @retval true The given facility would log the given level
- * @retval false A message of the given level would not be logged
- *
- */
-bool logger_IsLoggable(const Logger *logger, LoggerFacility facility,
- PARCLogLevel level);
-
-/**
- * Log a message
- *
- * The message will only be logged if it is loggable (logger_IsLoggable returns
- * true).
- *
- * @param [in] logger An allocated Logger
- * @param [in] facility The facility to log under
- * @param [in] level The log level of the message
- * @param [in] module The specific module logging the message
- * @param [in] format The message with varargs
- *
- */
-void logger_Log(Logger *logger, LoggerFacility facility, PARCLogLevel level,
- const char *module, const char *format, ...);
-
-/**
- * Switch the logger to a new reporter
- *
- * Will close the old reporter and re-setup the internal loggers to use the new
- * reporter. All current log level settings are preserved.
- *
- * @param [in] logger An allocated Logger
- * @param [in] reporter An allocated PARCLogReporter
- */
-void logger_SetReporter(Logger *logger, PARCLogReporter *reporter);
-
-/**
- * Set a new clock to use with the logger
- *
- * The logger will start getting the time (logged as the messageid) from the
- * specified clock
- *
- * @param [in] logger An allocated Logger
- * @param [in] clock An allocated PARCClock
- */
-void logger_SetClock(Logger *logger, PARCClock *clock);
-#endif // logger_h
diff --git a/hicn-light/src/hicn/core/mapme.c b/hicn-light/src/hicn/core/mapme.c
index 3a1c9777b..acda2b8cd 100644
--- a/hicn-light/src/hicn/core/mapme.c
+++ b/hicn-light/src/hicn/core/mapme.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,98 @@
/**
* @file mapme.c
* @brief MAP-Me : AnchorLess Producer Mobility Management.
+ *
+ * TODO:
+ * - review notification code with to integration of VPP implementation
+ * - reflect changes back in VPP
+ * - implement heuristic for update/notification selection
+ *
+ * MAP-Me hooks in forwarder
+ *
+ * A) Face table changes
+ *
+ * - face added
+ *
+ * * new local/producer face : this is a new prefix that we need to advertise
+ * on existing connections.
+ *
+ * We go over non-local connections an advertise the prefix through an IU
+ * provided that the connection satisfies the policy associated to the FIB
+ * entry. MAP-Me assumes the prefix already exists in the network, and the
+ * IU shall be discarded if the entry does not exist at the next hop. Three
+ * possibilities:
+ * . a bootstrap mechanism
+ * . we allow subprefixes of a prefix that is not empty by duplicating the
+ * FIB entry
+ * . we allow prefix creation in all circumstances : this is problematic
+ * since we might be creating spurious entries in routers for which we
+ * don't expect entries to be created.
+ *
+ * NOTE: because in general we will not allow for FIB entry creation, we
+ * cannot let the forwarder remove FIB entries with no nexthop (for instance
+ * after the producer leaves a point-of-attachment). This might creates
+ * permanent state in router's tables, but we assume it is the role of the
+ * routing plane to take care of routing entries.
+ *
+ * * new non-local face : a new face is available (eg. thanks to the face
+ * manager, after the node has connection to a new WiFi/LTE access point),
+ * and we thus need to advertise all local/producer prefixes onto this
+ * interface.
+ *
+ * For this, we currently scan the FIB for entries that have at least one
+ * local/producer face in nexthops, advertise the prefix on this new
+ * connection provided that it satisfies the associated policy.
+ *
+ * - face removed
+ *
+ * Currently, we take no action when a face is removed. It might however be a
+ * signal that a producer application is no more running at a given node, and
+ * that we can temporarily disable the forwarding towards that path.
+ *
+ * - face up / down
+ *
+ * - face nexthop added
+ *
+ * - face changed priority/tags
+ *
+ * B) Interest and Data forwarder path
+ *
+ * mapme_on_interest
+ *
+ * mapme_on_data
+ *
+ *
+ * EVENTS
+ * NH_SET
+ * NH_ADD
+ * PH_ADD
+ * PH_DEL
+ *
+ * C) Retransmission management
+ *
+ * Data structure
+ *
+ * mapme_on_timeout
+ *
+ *
+ * This allows us to define a convenient API for implementing MAP-Me:
+ *
+ * mapme_on_face_event XXX rename
+ *
+ * mapme_set_all_adjacencies(const mapme_t *mapme, fib_entry_t *entry)
+ * This function is used to update all the adjacencies. It needs to be called
+ * in case of face add/delete/change (priority/tas) and polocy
+ *
+ * mapme_set_adjacencies(const mapme_t *mapme, fib_entry_t *entry,
+ * nexthops_t *nexthops)
+ * This function updates only the nexthops and clear the tfib. It
+ * needs to be called by the forwarding strategy in case of path switch
+ *
+ * mapme_update_adjacencies(const mapme_t *mapme, fib_entry_t *entry,
+ * bool inc_iu_seq)
+ * This function is called to propagate the IU and it propagates the IU using
+ * the nexthops in the tfib. It needs to be used for mapme prcessing, IU
+ * forwarding, NATs and in case of timeouts
*/
#ifdef WITH_MAPME
@@ -24,739 +116,779 @@
#include <hicn/core/mapme.h>
#include <stdio.h> // printf
+#include <hicn/base/loop.h>
#include <hicn/core/connection.h>
-#include <hicn/core/connectionList.h>
#include <hicn/core/forwarder.h>
-#include <hicn/core/logger.h>
-#include <hicn/core/message.h>
-#include <hicn/core/messagePacketType.h> // packet types
+#include <hicn/core/msgbuf.h>
#include <hicn/core/ticks.h>
-#include <hicn/processor/fibEntry.h>
-#include <hicn/processor/pitEntry.h>
-
-#include <parc/algol/parc_HashMap.h>
-#include <parc/algol/parc_Iterator.h>
-#include <parc/algol/parc_Unsigned.h>
-#include <parc/assert/parc_Assert.h>
+#include <hicn/core/fib_entry.h>
+#include <hicn/core/pit.h>
+#include <hicn/base/loop.h>
+#include <hicn/util/log.h>
#define MS2NS(x) x * 1000000
#define T2NS(x) forwarder_TicksToNanos(x)
#define MAPME_DEFAULT_TU 5000 /* ms */
#define MAPME_DEFAULT_RETX 500 /* ms */
-#define MAX_RETX 3
+#define MAPME_DEFAULT_DISCOVERY false
+#define MAPME_DEFAULT_PROTOCOL IPPROTO_IPV6
+#define MAPME_MAX_RETX 3
+#define MTU 1500 // XXX TODO Mutualize this define
-#define NOT_A_NOTIFICATION false
-#define NO_INGRESS 0
+#define DONT_QUEUE false
#define TIMER_NO_REPEAT false
-#define DO_DISCOVERY 1
#define MAPME_INVALID_DICOVERY_SEQ -1
+#define INIT_SEQ 0
-#define LOG_FACILITY LoggerFacility_Core
+#define foreach_mapme_event \
+ _(UNDEFINED) \
+ _(FACE_ADD) \
+ _(FACE_DEL) \
+ _(NH_SET) \
+ _(NH_ADD) \
+ _(PH_ADD) \
+ _(PH_DEL) \
+ _(N)
+
+typedef enum {
+#define _(x) MAPME_EVENT_##x,
+ foreach_mapme_event
+#undef _
+} mapme_event_t;
-#define LOG(mapme, log_level, fmt, ...) \
- do { \
- Logger *logger = forwarder_GetLogger(mapme->forwarder); \
- if (logger_IsLoggable(logger, LOG_FACILITY, log_level)) { \
- logger_Log(logger, LOG_FACILITY, log_level, __func__, fmt, \
- ##__VA_ARGS__); \
- } \
- } while (0)
+/*
+ * We need a retransmission pool holding all necessary information for crafting
+ * special interests, thus including both the DPO and the prefix associated to
+ * it.
+ */
+#define NUM_RETX_ENTRIES 100
+#define NUM_RETX_SLOT 2
-#define WARN(mapme, fmt, ...) \
- LOG(mapme, PARCLogLevel_Warning, fmt, ##__VA_ARGS__)
-#define ERR(mapme, fmt, ...) LOG(mapme, PARCLogLevel_Error, fmt, ##__VA_ARGS__)
-#define INFO(mapme, fmt, ...) LOG(mapme, PARCLogLevel_Info, fmt, ##__VA_ARGS__)
-#define DEBUG(mapme, fmt, ...) \
- LOG(mapme, PARCLogLevel_Debug, fmt, ##__VA_ARGS__)
+typedef struct {
+ hicn_prefix_t prefix;
+ fib_entry_t *entry;
+ uint8_t retx_count; // Number of retransmissions since last tfib addition
+} mapme_retx_t;
/**
* MAP-Me state data structure
*/
-struct mapme {
- uint32_t retx; /* ms */
- uint32_t Tu; /* ms */
- bool removeFibEntries;
+struct mapme_s {
+ /* Options XXX mapme_conf_t ! */
+ uint32_t retx; /* retx timeout (in ms) */
+ uint32_t timescale; /* timescale (in ms) */
+ bool discovery; /* discovery flag */
+ int protocol;
+ bool enabled; /* mapme enabled/disabled */
+
+ /*
+ * Retransmissions
+ * Lite calendar queue with NUM_RETX_SLOT slots
+ */
+ event_t *timer;
+ mapme_retx_t retx_array[NUM_RETX_SLOT][NUM_RETX_ENTRIES];
+ uint8_t retx_len[NUM_RETX_SLOT];
+ uint8_t cur;
+ uint8_t idle;
- Forwarder *forwarder;
+ forwarder_t *forwarder;
};
-static MapMe MapMeDefault = {.retx = MAPME_DEFAULT_RETX,
- .Tu = MAPME_DEFAULT_TU,
- .removeFibEntries = false};
+#define NEXT_SLOT(CUR) (1 - CUR)
+#define CUR mapme->retx_array[mapme->cur]
+#define NXT mapme->retx_array[NEXT_SLOT(mapme->cur)]
+#define CURLEN mapme->retx_len[mapme->cur]
+#define NXTLEN mapme->retx_len[NEXT_SLOT(mapme->cur)]
+
+static mapme_t mapme_default = {
+ .retx = MAPME_DEFAULT_RETX,
+ .timescale = MAPME_DEFAULT_TU,
+ .discovery = MAPME_DEFAULT_DISCOVERY,
+ .protocol = MAPME_DEFAULT_PROTOCOL,
+ .enabled = true,
+ .timer = NULL,
+ // .retx_array = {{ 0 }}, // memset
+ .retx_len = {0},
+ .cur = 0, /* current slot */
+ .idle = 0,
+};
/******************************************************************************/
-bool mapme_create(MapMe **mapme, Forwarder *forwarder) {
- *mapme = malloc(sizeof(MapMe));
- if (!mapme) goto ERR_MALLOC;
+int mapme_on_timeout(void *mapme_arg, int fd, unsigned id, void *data);
- /* Internal state : set default values */
- memcpy(*mapme, &MapMeDefault, sizeof(MapMe));
+mapme_t *mapme_create(void *forwarder) {
+ mapme_t *mapme = malloc(sizeof(mapme_t));
+ if (!mapme) return NULL;
- (*mapme)->forwarder = forwarder;
-
- /* As there is no face table and no related events, we need to install hooks
- * in various places in the forwarder, where both control commands and
- * signalization are processed.
- */
+ /* Internal state : set default values */
+ memcpy(mapme, &mapme_default, sizeof(mapme_t));
+ memset(mapme->retx_array, 0, NUM_RETX_SLOT * NUM_RETX_ENTRIES);
- return true;
+ mapme->forwarder = forwarder;
+ loop_timer_create(&mapme->timer, MAIN_LOOP, mapme, mapme_on_timeout, NULL);
+ if (!mapme->timer) {
+ ERROR("Error allocating mapme timer.");
+ free(mapme);
+ return NULL;
+ }
-ERR_MALLOC:
- return false;
+ return mapme;
}
-void mapme_free(MapMe *mapme)
-{
- free(mapme);
+void mapme_free(mapme_t *mapme) {
+ loop_event_free(mapme->timer);
+ free(mapme);
}
/******************************************************************************
* TFIB
******************************************************************************/
-#define INVALID_SEQ 0
-#define INIT_SEQ 0
-
typedef struct {
+ // XXX We need magic number to know whether the TFIB was initialized or not
+ // ... or merge it inside the real data structure.
+ // NOTE: in VPP we reuse the nexthops in opposite order to gain room
+ // XXX need enough space in user_data !!
uint32_t seq;
- PARCHashMap *nexthops;
+ nexthops_t nexthops; // XXX useless shadow structure
/* Update/Notification heuristic */
- Ticks lastAckedUpdate;
-} MapMeTFIB;
+ Ticks last_acked_update;
+} mapme_tfib_t;
-static MapMeTFIB *mapmeTFIB_Create() {
- MapMeTFIB *tfib;
- tfib = malloc(sizeof(MapMeTFIB));
- if (!tfib) goto ERR_MALLOC;
+#define TFIB(FIB_ENTRY) ((mapme_tfib_t *)fib_entry_get_user_data(FIB_ENTRY))
+
+static mapme_tfib_t *mapme_tfib_create() {
+ mapme_tfib_t *tfib;
+ tfib = malloc(sizeof(mapme_tfib_t));
+ if (!tfib) return NULL;
+
+ // init
tfib->seq = INIT_SEQ;
- tfib->lastAckedUpdate = 0;
- tfib->nexthops = parcHashMap_Create();
- if (!tfib->nexthops) goto ERR_HASHMAP;
+ tfib->last_acked_update = 0;
+ nexthops_set_len(&tfib->nexthops, 0);
return tfib;
-
-ERR_HASHMAP:
- free(tfib);
-ERR_MALLOC:
- return NULL;
}
-static PARCIterator *mapmeTFIB_CreateKeyIterator(const MapMeTFIB *tfib) {
- /*
- * Creating an iterator on an empty HashMap seems to raise an exception
- * due to :
- * parcTrapOutOfMemoryIf(state->listIterator == NULL,
- * "Cannot create parcLinkedList_CreateIterator");
- * in : _parcHashMap_Init
- *
- * All buckets are empty, as they are after creation, and as they should be,
- * but the error is triggered.
- */
- if (parcHashMap_Size(tfib->nexthops) == 0)
- return NULL;
- return parcHashMap_CreateKeyIterator(tfib->nexthops);
+void mapme_release_tfib(mapme_tfib_t **tfibPtr) {
+ mapme_tfib_t *tfib = *tfibPtr;
+ free(tfib);
+ tfibPtr = NULL;
}
-void mapmeTFIB_Release(const MapMe * mapme, MapMeTFIB **tfibPtr);
-
/**
- * @function mapme_CreateTFIB
- * @abstract Associate a new TFIB entry to a FIB entry.
+ * @function mapme_create_tfib
+ * @abstract Associate a new TFIB entry to a FIB entry. If a TFIB already exists
+ * the new one will be used
* @param [in] - Pointer to the FIB entry.
* @return Boolean indicating the success of the operation.
*/
-static void mapme_CreateTFIB(const MapMe * mapme, FibEntry *fibEntry) {
- MapMeTFIB *tfib;
-
- /* Make sure we don't already have an associated TFIB entry */
- tfib = fibEntry_getUserData(fibEntry);
- // assertNull(tfib);
-
- tfib = mapmeTFIB_Create();
- fibEntry_setUserData(fibEntry, mapme, tfib, (void (*)(const void*, void**))mapmeTFIB_Release);
-}
+static void mapme_create_tfib(const mapme_t *mapme, fib_entry_t *entry) {
+ mapme_tfib_t *tfib;
-#define TFIB(fibEntry) ((MapMeTFIB *)fibEntry_getUserData(fibEntry))
-
-static const PARCEventTimer *mapmeTFIB_Get(const MapMeTFIB *tfib,
- unsigned conn_id) {
- const PARCEventTimer *timer;
- const PARCBuffer *buffer;
- PARCUnsigned *cid = parcUnsigned_Create(conn_id);
- buffer = parcHashMap_Get(tfib->nexthops, cid);
- if (!buffer) {
- timer = NULL;
- goto END;
- }
- PARCByteArray *array = parcBuffer_Array(buffer);
- timer = *((PARCEventTimer **)parcByteArray_Array(array));
-END:
- parcUnsigned_Release(&cid);
- return timer;
+ tfib = mapme_tfib_create();
+ fib_entry_set_user_data(entry, tfib, (void (*)(void **))mapme_release_tfib);
}
-static void mapmeTFIB_Put(MapMeTFIB *tfib, unsigned conn_id,
- const PARCEventTimer *timer) {
- /* NOTE: Timers are not objects (the only class not being an object in
- * fact), and as such, we cannot use them as values for the HashMap.
- * Just like for unsigned we needed the PARC wrapper.
- * There is no wrapper for pointers, so we use Arrays, which has an ubly
- * syntax...
- */
- PARCUnsigned *cid = parcUnsigned_Create(conn_id);
- PARCBuffer *buffer = parcBuffer_CreateFromArray(&timer, sizeof(PARCEventTimer *));
- parcHashMap_Put(tfib->nexthops, cid, buffer);
-
- parcUnsigned_Release(&cid);
- parcBuffer_Release(&buffer);
+/**
+ * @brief Update/Notification heuristic:
+ *
+ * NOTE: IN are currently disabled until the proper placeholder is agreed in the
+ * interest header.
+ */
+static hicn_mapme_type_t mapme_get_type_from_heuristic(const mapme_t *mapme,
+ fib_entry_t *entry) {
+#if 0
+ if (!entry) return UPDATE;
+ if (fib_entry_has_local_nexthop(entry))
+ /* We are a producer for this entry, send update */
+ return UPDATE;
+#else /* Always send IU */
+ return UPDATE;
+#endif
}
-static void mapmeTFIB_Remove(const MapMe * mapme, MapMeTFIB *tfib, unsigned conn_id) {
- PARCUnsigned *cid = parcUnsigned_Create(conn_id);
-
- /* Release timer */
- const PARCBuffer *buffer = parcHashMap_Get(tfib->nexthops, cid);
- if (buffer) {
- PARCByteArray *array = parcBuffer_Array(buffer);
- PARCEventTimer * timer = *((PARCEventTimer **)parcByteArray_Array(array));
- if (timer) {
- parcEventTimer_Stop(timer);
- Dispatcher *dispatcher = forwarder_GetDispatcher(mapme->forwarder);
- dispatcher_DestroyTimerEvent(dispatcher, &timer);
- }
+/**
+ *
+ * Here nexthops is not necessarily FIB nexthops as we might advertise given FIB
+ * entries on various other connections.
+ *
+ * prefix can be specified to send an update for a More Specific Prefix (MSP),
+ * or left NULL for the default behaviour. Note there will be no support for
+ * retransmission for MSP.
+ *
+ * NOTES:
+ * - if the face is pending an we receive an IN, maybe we should not cancel the
+ * timer
+ * - this function should never be called for Notifications.
+ */
+int mapme_send_to_nexthops(const mapme_t *mapme, fib_entry_t *entry,
+ const nexthops_t *nexthops,
+ const hicn_prefix_t *prefix) {
+ INFO("mapme send to nexthops");
+ const hicn_prefix_t *mapme_prefix;
+ uint32_t mapme_seq;
+
+ assert(!!prefix ^ !!entry);
+
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return -1;
}
- parcHashMap_Remove(tfib->nexthops, cid);
- parcUnsigned_Release(&cid);
-}
-
-void mapmeTFIB_Release(const MapMe * mapme, MapMeTFIB **tfibPtr) {
- MapMeTFIB *tfib = *tfibPtr;
-
- /* Release all TFIB entries, incl. timers */
- PARCIterator *iterator = mapmeTFIB_CreateKeyIterator(tfib);
- if (iterator) {
- /* No iterator is created if the TFIB is empty */
- while (parcIterator_HasNext(iterator)) {
- PARCUnsigned *cid = parcIterator_Next(iterator);
- unsigned conn_id = parcUnsigned_GetUnsigned(cid);
- mapmeTFIB_Remove(mapme, tfib, conn_id);
+ if (prefix) {
+ INFO("mapme with given prefix");
+ mapme_prefix = prefix;
+ mapme_seq = 1;
+ } else {
+ INFO("mapme wih fib entry prefix");
+ mapme_tfib_t *tfib = TFIB(entry);
+ if (tfib == NULL) {
+ mapme_create_tfib(mapme, entry);
+ tfib = TFIB(entry);
}
- parcIterator_Release(&iterator);
- }
-
- parcHashMap_Release(&tfib->nexthops);
- free(tfib);
- *tfibPtr = NULL;
-}
-
-
-int hicn_prefix_from_name(const Name *name, hicn_prefix_t *prefix) {
- NameBitvector *bv = name_GetContentName(name);
- ip_prefix_t ip_prefix;
- nameBitvector_ToIPAddress(bv, &ip_prefix);
- /* The name length will be equal to ip address' prefix length */
- return hicn_prefix_create_from_ip_prefix(&ip_prefix, prefix);
-}
-
-static Message *mapme_createMessage(const MapMe *mapme, const Name *name,
- mapme_params_t *params) {
- Ticks now = forwarder_GetTicks(mapme->forwarder);
- Logger *logger = forwarder_GetLogger(mapme->forwarder);
-
- INFO(mapme, "[MAP-Me] CreateMessage type=%d seq=%d", params->type,
- params->seq);
-
- hicn_prefix_t prefix;
- int rc = hicn_prefix_from_name(name, &prefix);
- if (rc < 0) {
- ERR(mapme, "[MAP-Me] Failed to create lib's name");
- goto ERR_NAME;
+ mapme_prefix = fib_entry_get_prefix(entry);
+ mapme_seq = tfib->seq;
}
-
- size_t size = (params->protocol == IPPROTO_IPV6) ? HICN_MAPME_V6_HDRLEN
- : HICN_MAPME_V4_HDRLEN;
- uint8_t *icmp_pkt = parcMemory_AllocateAndClear(size);
-
- INFO(mapme, "[MAP-Me] Creating MAP-Me packet");
- size_t len = hicn_mapme_create_packet(icmp_pkt, &prefix, params);
- if (len == 0) {
- ERR(mapme, "[MAP-Me] Failed to create mapme packet through lib");
- goto ERR_CREATE;
+ char prefix_s[MAXSZ_IP_PREFIX];
+ int rc = hicn_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, mapme_prefix);
+ assert(rc < MAXSZ_IP_PREFIX);
+ if (rc < 0) NULL;
+
+ INFO("mapme send to nexthops prefix= %s", prefix_s);
+
+ WITH_INFO({
+ char buf[MAXSZ_HICN_PREFIX];
+ int rc = hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, mapme_prefix);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "(error)");
+ INFO("sending IU/IN for name %s on nexthops", buf);
+ })
+
+ mapme_params_t params = {.protocol = mapme->protocol,
+ .type = mapme_get_type_from_heuristic(mapme, entry),
+ .seq = mapme_seq};
+
+ uint8_t packet[MTU];
+ size_t size = hicn_mapme_create_packet(packet, mapme_prefix, &params);
+ if (size <= 0) {
+ ERROR("Could not create MAP-Me packet");
+ return -1;
}
- // hicn_packet_dump(icmp_pkt, MAPME_HDRLEN);
+ connection_table_t *table = forwarder_get_connection_table(mapme->forwarder);
- return message_CreateFromByteArray(NO_INGRESS, icmp_pkt,
- MessagePacketType_Interest, now, logger);
+ nexthops_foreach(nexthops, nexthop, {
+ const connection_t *conn = connection_table_get_by_id(table, nexthop);
+ assert(!connection_is_local(conn));
+ connection_send_packet(conn, packet, size);
+ });
-ERR_CREATE:
- parcMemory_Deallocate(&icmp_pkt);
-ERR_NAME:
- return NULL;
+ return 0;
}
-static Message *mapme_createAckMessage(const MapMe *mapme,
- const uint8_t *msgBuffer,
- const mapme_params_t *params) {
- Ticks now = forwarder_GetTicks(mapme->forwarder);
- Logger *logger = forwarder_GetLogger(mapme->forwarder);
-
- size_t size = (params->protocol == IPPROTO_IPV6) ? HICN_MAPME_V6_HDRLEN
- : HICN_MAPME_V4_HDRLEN;
- uint8_t *icmp_pkt = parcMemory_AllocateAndClear(size);
- memcpy(icmp_pkt, msgBuffer, size);
-
- size_t len = hicn_mapme_create_ack(icmp_pkt, params);
- if (len != size) {
- ERR(mapme, "[MAP-Me] Failed to create mapme ack packet through lib");
- goto ERR;
+#if 0
+/**
+ *
+ * Here nexthops is not necessarily FIB nexthops as we might advertise given FIB
+ * entries on various other connections.
+ */
+void mapme_maybe_send_to_nexthops(const mapme_t *mapme, fib_entry_t *fib_entry,
+ const nexthops_t *nexthops) {
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return;
}
- return message_CreateFromByteArray(
- NO_INGRESS, icmp_pkt, MessagePacketType_ContentObject, now, logger);
-
-ERR:
- parcMemory_Deallocate(&icmp_pkt);
- return NULL;
-}
-
-struct setFacePendingArgs {
- const MapMe *mapme;
- const Name *name;
- FibEntry *fibEntry;
- unsigned conn_id;
- bool send;
- bool is_producer;
- uint32_t num_retx;
-};
-
-static bool mapme_setFacePending(const MapMe *mapme, const Name *name,
- FibEntry *fibEntry, unsigned conn_id,
- bool send, bool is_producer, bool clear_tfib, uint32_t num_retx);
-
-static void mapme_setFacePendingCallback(int fd, PARCEventType which_event,
- void *data) {
- struct setFacePendingArgs *args = (struct setFacePendingArgs *)data;
-
- parcAssertTrue(which_event & PARCEventType_Timeout,
- "Event incorrect, expecting %X set, got %X",
- PARCEventType_Timeout, which_event);
+ /* Detect change */
+ if (!fib_entry_nexthops_changed(fib_entry)) {
+ INFO("No change in nexthops");
+ return;
+ }
+ fib_entry_set_prev_nexthops(fib_entry);
- INFO(args->mapme, "Timeout during retransmission. Re-sending");
- mapme_setFacePending(args->mapme, args->name, args->fibEntry, args->conn_id,
- args->send, args->is_producer, false, args->num_retx);
- free(args);
+ mapme_send_to_nexthops(mapme, fib_entry, nexthops);
}
-
-/**
- * @brief Update/Notification heuristic:
- *
- * NOTE: IN are currently disabled until the proper placeholder is agreed in the
- * interest header.
- */
-static hicn_mapme_type_t mapme_getTypeFromHeuristic(const MapMe *mapme,
- FibEntry *fibEntry) {
-#if 0 /* interplay of IU/IN */
- if (TFIB(fibEntry)->lastAckedUpdate == 0) {
- return UPDATE;
- } else {
- Ticks interval = now - TFIB(fibEntry)->lastAckedUpdate;
- return (T2NS(interval) > MS2NS(mapme->Tu)) ? UPDATE : NOTIFICATION;
- }
-#else /* Always send IU */
- return UPDATE;
#endif
-}
-static bool mapme_setFacePending(const MapMe *mapme, const Name *name,
- FibEntry *fibEntry, unsigned conn_id,
- bool send, bool is_producer, bool clear_tfib, uint32_t num_retx) {
- int rc;
+/******************************************************************************
+ * MAPME API
+ ******************************************************************************/
- INFO(mapme, "[MAP-Me] SetFacePending connection=%d prefix=XX retx=%d",
- conn_id, num_retx);
+int mapme_set_all_adjacencies(const mapme_t *mapme, fib_entry_t *entry) {
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return -1;
+ }
- /* NOTE: if the face is pending an we receive an IN, maybe we should not
- * cancel the timer
- */
- Dispatcher *dispatcher = forwarder_GetDispatcher(mapme->forwarder);
- PARCEventTimer *timer;
+ /* Apply the policy of the fib_entry over all neighbours */
+ nexthops_t new_nexthops = NEXTHOPS_EMPTY;
+ nexthops_t *nexthops = fib_entry_get_mapme_nexthops(entry, &new_nexthops);
- /* Safeguard during retransmissions */
- if (!TFIB(fibEntry))
- return true;
+ /* We set force to true to avoid overriding the FIB cache */
+ return mapme_set_adjacencies(mapme, entry, nexthops, NULL);
+}
+// XXX this will change with the FIB cache
+// XXX we are sometimes incrementing tfib seq for nothing
+int mapme_set_adjacencies(const mapme_t *mapme, fib_entry_t *entry,
+ nexthops_t *nexthops, const hicn_prefix_t *prefix) {
+ INFO("mapme set adjacenies");
/*
- * On the producer side, we have to clear the TFIB everytime we change the list
- * of adjacencies, otherwise retransmissions will occur to preserve them.
+ * - entry is provided in case of a producer reannouncement
+ * - prefix is provided for control plane triggered updates
*/
- if (clear_tfib) {
- /*
- * It is likely we cannot iterator and remove elements from the hashmap at
- * the same time, so we proceed in two steps
- */
- if (parcHashMap_Size(TFIB(fibEntry)->nexthops) > 0) {
-
- NumberSet * conns = numberSet_Create();
-
- PARCIterator *it = parcHashMap_CreateKeyIterator(TFIB(fibEntry)->nexthops);
- while (parcIterator_HasNext(it)) {
- PARCUnsigned *cid = parcIterator_Next(it);
- unsigned conn_id = parcUnsigned_GetUnsigned(cid);
- numberSet_Add(conns, conn_id);
- }
- parcIterator_Release(&it);
-
- for (size_t i = 0; i < numberSet_Length(conns); i++) {
- unsigned conn_id = numberSet_GetItem(conns, i);
- mapmeTFIB_Remove(mapme, TFIB(fibEntry), conn_id);
- }
+ assert(!!prefix ^ !!entry);
- numberSet_Release(&conns);
- }
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return -1;
}
- // NOTE
- // - at producer, send always true, we always send something reliably so we
- // set the timer.
- // - in the network, we always forward an IU, and never an IN
- //if (is_producer || send) {
- if (send) {
- mapme_params_t params = {
- .protocol = IPPROTO_IPV6,
- .type = is_producer ? mapme_getTypeFromHeuristic(mapme, fibEntry) : UPDATE,
- .seq = TFIB(fibEntry)->seq};
- Message *special_interest = mapme_createMessage(mapme, name, &params);
- if (!special_interest) {
- INFO(mapme, "[MAP-Me] Could not create special interest");
- return false;
- }
+ if (entry) {
+ /* Check disabled, we need to be able to send an update for a larger prefix
+ * that the one being served.
+ */
+ // if (!fib_entry_has_local_nexthop(entry)) return -1;
- const ConnectionTable *table =
- forwarder_GetConnectionTable(mapme->forwarder);
- const Connection *conn =
- connectionTable_FindById((ConnectionTable *)table, conn_id);
- if (conn) {
- const Name * name = message_GetName(special_interest);
- char * name_str = name_ToString(name);
- INFO(mapme, "[MAP-Me] Sending MAP-Me packet name=%s seq=%d conn=%d",
- name_str, params.seq, conn_id);
- free(name_str);
- connection_ReSend(conn, special_interest, NOT_A_NOTIFICATION);
- } else {
- INFO(mapme, "[MAP-Me] Stopped retransmissions as face went down");
- }
- message_Release(&special_interest);
-
- if (num_retx < MAX_RETX) {
- INFO(mapme, "[MAP-Me] - Scheduling retransmission\n");
- /* Schedule retransmission */
- struct setFacePendingArgs *args =
- malloc(sizeof(struct setFacePendingArgs));
- if (!args)
- goto ERR_MALLOC;
- args->mapme = mapme;
- args->name = name;
- args->fibEntry = fibEntry;
- args->conn_id = conn_id;
- args->send = send;
- args->is_producer = is_producer;
- args->num_retx = num_retx + 1;
-
- timer = dispatcher_CreateTimer(dispatcher, TIMER_NO_REPEAT,
- mapme_setFacePendingCallback, args);
- struct timeval timeout = {mapme->retx / 1000,
- (mapme->retx % 1000) * 1000};
- rc = parcEventTimer_Start(timer, &timeout);
- if (rc < 0) {
- free(args);
- goto ERR_TIMER;
- }
- } else {
- INFO(mapme, "[MAP-Me] Last retransmission.");
- timer = NULL;
+ mapme_tfib_t *tfib = TFIB(entry);
+ if (tfib == NULL) {
+ mapme_create_tfib(mapme, entry);
+ tfib = TFIB(entry);
}
- } else {
- INFO(mapme, "[MAP-Me] - not forwarding as send is False");
- timer = NULL;
- }
- mapmeTFIB_Remove(mapme, TFIB(fibEntry), conn_id);
- mapmeTFIB_Put(TFIB(fibEntry), conn_id, timer);
+ /*
+ * We need to prevent pending updates to recreate a link which does not make
+ * since anymore since we edit the graph here.
+ */
+ nexthops_clear(&tfib->nexthops);
- return true;
+ /* We update the sequence number in all cases otherwise this won't allow
+ * repetition
+ */
+ tfib->seq++;
+ }
-ERR_TIMER:
- dispatcher_DestroyTimerEvent(dispatcher, &timer);
-ERR_MALLOC:
- return false;
+ INFO("calling send to nh");
+ mapme_send_to_nexthops(mapme, entry, nexthops, prefix);
+ return 0;
}
-/*------------------------------------------------------------------------------
- * Event handling
- *----------------------------------------------------------------------------*/
+int mapme_set_adjacency(const mapme_t *mapme, fib_entry_t *entry,
+ nexthop_t nexthop, const hicn_prefix_t *prefix) {
+ nexthops_t nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, nexthop);
-/*
- * Return true if we have at least one local connection as next hop
- */
-static bool mapme_hasLocalNextHops(const MapMe *mapme,
- const FibEntry *fibEntry) {
- const NumberSet *nexthops = fibEntry_GetNexthops(fibEntry);
- const ConnectionTable *table = forwarder_GetConnectionTable(mapme->forwarder);
-
- for (size_t j = 0; j < fibEntry_NexthopCount(fibEntry); j++) {
- /* Retrieve Nexthop #j */
- unsigned conn_id = numberSet_GetItem(nexthops, j);
- const Connection *conn =
- connectionTable_FindById((ConnectionTable *)table, conn_id);
-
- /* Ignore non-local connections */
- if (!connection_IsLocal(conn)) continue;
- /* We don't need to test against conn_added since we don't
- * expect it to have any entry in the FIB */
-
- return true;
- }
- return false;
+ return mapme_set_adjacencies(mapme, entry, &nexthops, prefix);
}
-void
-mapme_send_updates(const MapMe * mapme, FibEntry * fibEntry, const NumberSet * nexthops)
-{
- if (!TFIB(fibEntry)) /* Create TFIB associated to FIB entry */
- mapme_CreateTFIB(mapme, fibEntry);
- TFIB(fibEntry)->seq++;
-
- const Name *name = fibEntry_GetPrefix(fibEntry);
- char *name_str = name_ToString(name);
- bool clear_tfib = true;
-
- INFO(mapme, "[MAP-Me] Candidate next hops changed");
- for (size_t j = 0; j < numberSet_Length(nexthops); j++) {
- unsigned nexthop_id = numberSet_GetItem(nexthops, j);
-
- /* We extract the nexthop type based on tags */
- const char * nexthop_type;
- ConnectionTable * table = forwarder_GetConnectionTable(mapme->forwarder);
- const Connection * conn = connectionTable_FindById(table, nexthop_id);
- if (connection_HasTag(conn, POLICY_TAG_WIRED)) {
- nexthop_type = "WIRED";
- } else if (connection_HasTag(conn, POLICY_TAG_WIFI)) {
- nexthop_type = "WIFI";
- } else if (connection_HasTag(conn, POLICY_TAG_CELLULAR)) {
- nexthop_type = "CELLULAR";
- } else {
- nexthop_type = "UNKNOWN";
- }
-
- INFO(mapme, "[MAP-Me] sending IU/IN for name %s on connection %d - %s (%s)", name_str,
- nexthop_id, connection_GetInterfaceName(conn), nexthop_type);
- mapme_setFacePending(mapme, name, fibEntry, nexthop_id, true, true, clear_tfib, 0);
- clear_tfib = false;
+int mapme_update_adjacencies(const mapme_t *mapme, fib_entry_t *entry,
+ bool inc_iu_seq) {
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return -1;
}
- INFO(mapme, "[MAP-Me] Done sending MAP-Me update");
- free(name_str);
-}
-
-void
-mapme_maybe_send_updates(const MapMe * mapme, FibEntry * fibEntry, const NumberSet * nexthops)
-{
- /* Detect change */
- NumberSet * previous_nexthops = fibEntry_GetPreviousNextHops(fibEntry);
- if (numberSet_Equals(nexthops, previous_nexthops)) {
- INFO(mapme, "[MAP-Me] No change in nexthops");
- return;
+ mapme_tfib_t *tfib = TFIB(entry);
+ if (tfib == NULL) {
+ mapme_create_tfib(mapme, entry);
+ tfib = TFIB(entry);
}
- fibEntry_SetPreviousNextHops(fibEntry, nexthops);
- mapme_send_updates(mapme, fibEntry, nexthops);
-}
+ if (inc_iu_seq) tfib->seq++;
-void
-mapme_reconsiderFibEntry(const MapMe *mapme, FibEntry * fibEntry)
-{
- /*
- * Skip entries that do not correspond to a producer ( / have a locally
- * served prefix / have no local connection as next hop)
- */
- if (!mapme_hasLocalNextHops(mapme, fibEntry))
- return;
+ mapme_send_to_nexthops(mapme, entry, &tfib->nexthops, NULL);
+ return 0;
+}
- /* Apply the policy of the fibEntry over all neighbours */
- NumberSet * available_nexthops = fibEntry_GetAvailableNextHops(fibEntry, ~0);
+int mapme_send_to_nexthop(const mapme_t *mapme, fib_entry_t *entry,
+ unsigned nexthop) {
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return -1;
+ }
- /* Advertise prefix on all available next hops (if needed) */
- mapme_send_updates(mapme, fibEntry, available_nexthops);
+ nexthops_t nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, nexthop);
- numberSet_Release(&available_nexthops);
+ return mapme_send_to_nexthops(mapme, entry, &nexthops, NULL);
}
+#if 0
/*
* Callback called everytime a new connection is created by the control protocol
*/
-void
-mapme_onConnectionEvent(const MapMe *mapme, const Connection *conn_added, connection_event_t event) {
+void mapme_on_connection_event(const mapme_t *mapme,
+ const connection_t *conn_added,
+ connection_event_t event) {
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return;
+ }
+
/* Does the priority change impacts the default route selection; if so,
* advertise the prefix on this default route. If there are many default
* routes, either v4 v6, or many connections as next hops on this default
* route, then send to all.
*/
if (conn_added) {
- if (connection_IsLocal(conn_added))
- return;
+ if (connection_is_local(conn_added)) return;
- unsigned conn_added_id = connection_GetConnectionId(conn_added);
- switch(event) {
+ unsigned conn_added_id = connection_get_id(conn_added);
+ switch (event) {
case CONNECTION_EVENT_CREATE:
- INFO(mapme, "[MAP-Me] Connection %d got created", conn_added_id);
- break;
+ INFO("Connection %d got created", conn_added_id);
+ break;
case CONNECTION_EVENT_DELETE:
- INFO(mapme, "[MAP-Me] Connection %d got deleted", conn_added_id);
- break;
+ INFO("Connection %d got deleted", conn_added_id);
+ break;
case CONNECTION_EVENT_UPDATE:
- INFO(mapme, "[MAP-Me] Connection %d got updated", conn_added_id);
- break;
+ INFO("Connection %d got updated", conn_added_id);
+ break;
case CONNECTION_EVENT_SET_UP:
- INFO(mapme, "[MAP-Me] Connection %d went up", conn_added_id);
- break;
+ INFO("Connection %d went up", conn_added_id);
+ break;
case CONNECTION_EVENT_SET_DOWN:
- INFO(mapme, "[MAP-Me] Connection %d went down", conn_added_id);
- break;
+ INFO("Connection %d went down", conn_added_id);
+ break;
case CONNECTION_EVENT_TAGS_CHANGED:
- INFO(mapme, "[MAP-Me] Connection %d changed tags", conn_added_id);
- break;
+ INFO("Connection %d changed tags", conn_added_id);
+ break;
case CONNECTION_EVENT_PRIORITY_CHANGED:
- INFO(mapme, "[MAP-Me] Connection %d changed priority to %d",
- conn_added_id, connection_GetPriority(conn_added));
- break;
+ INFO("Connection %d changed priority to %d", conn_added_id,
+ connection_get_priority(conn_added));
+ break;
}
}
/* We need to send a MapMe update on the newly selected connections for
- * each concerned fibEntry : connection is involved, or no more involved */
- FibEntryList *fiblist = forwarder_GetFibEntries(mapme->forwarder);
-
- /* Iterate a first time on the FIB to get the locally served prefixes */
- for (size_t i = 0; i < fibEntryList_Length(fiblist); i++) {
- FibEntry *fibEntry = (FibEntry *)fibEntryList_Get(fiblist, i);
- mapme_reconsiderFibEntry(mapme, fibEntry);
- }
-
- fibEntryList_Destroy(&fiblist);
-
- INFO(mapme, "[MAP-Me] Done");
+ * each concerned fib_entry : connection is involved, or no more involved */
+ const fib_t *fib = forwarder_get_fib(mapme->forwarder);
+ fib_foreach_entry(fib, entry, { mapme_set_all_adjacencies(mapme, entry); });
}
+#endif
/*------------------------------------------------------------------------------
* Special Interest handling
*----------------------------------------------------------------------------*/
-/**
- * @discussion This function is way too long and should be cut out
- */
-static bool mapme_onSpecialInterest(const MapMe *mapme,
- const uint8_t *msgBuffer,
- unsigned conn_in_id, hicn_prefix_t *prefix,
- mapme_params_t *params) {
- const ConnectionTable *table = forwarder_GetConnectionTable(mapme->forwarder);
- /* The cast is needed since connectionTable_FindById miss the
- * const qualifier for the first parameter */
- const Connection *conn_in =
- connectionTable_FindById((ConnectionTable *)table, conn_in_id);
- seq_t fibSeq, seq = params->seq;
- bool send = (params->type == UPDATE);
- bool rv;
-
- Name *name = name_CreateFromPacket(msgBuffer, MessagePacketType_Interest);
- name_setLen(name, prefix->len);
- char *name_str = name_ToString(name);
- INFO(mapme,
- "[MAP-Me] Ack'ed Special Interest on connection %d - prefix=%s type=XX "
- "seq=%d",
- conn_in_id, name_str, seq);
- free(name_str);
+#ifdef HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY
+fib_entry_t *mapme_create_fib_entry(const mapme_t *mapme,
+ const hicn_prefix_t *prefix,
+ unsigned ingress_id) {
+ INFO(" - creating FIB entry with next hop on connection %d", ingress_id);
/*
- * Immediately send an acknowledgement back on the ingress connection
- * We always ack, even duplicates.
+ * This might happen for a node hosting a producer which has moved.
+ * Destroying the face has led to removing all corresponding FIB
+ * entries. In that case, we need to correctly restore the FIB entries.
+ * Also in case we have an intermediate node with just a less specific prefix
+ * (eg. a default route), and thus an announcement with a more specific
+ * prefix. In that case we need to perform a FIB lookup to find the next hops
+ * to which the message should be propagated (before adding).
*/
- Message *ack = mapme_createAckMessage(mapme, msgBuffer, params);
- if (!ack) {
- name_Release(&name);
- return false;
- }
- rv = connection_ReSend(conn_in, ack, NOT_A_NOTIFICATION);
- message_Release(&ack);
+ forwarder_t *forwarder = mapme->forwarder;
+
+ fib_t *fib = forwarder_get_fib(forwarder);
+ configuration_t *config = forwarder_get_configuration(forwarder);
+
+ char prefix_s[MAXSZ_IP_PREFIX];
+ int rc = hicn_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, prefix);
+ assert(rc < MAXSZ_IP_PREFIX);
+ if (rc < 0) NULL;
+
+ INFO("creating FIB entry for prefix %s", prefix_s);
- if (!rv) {
- name_Release(&name);
- return false;
+ strategy_type_t strategy_type = configuration_get_strategy(config, prefix_s);
+ fib_entry_t *entry = fib_entry_create(prefix, strategy_type, NULL, forwarder);
+ mapme_create_tfib(mapme, entry);
+
+ fib_entry_t *lpm = fib_match_prefix(fib, prefix);
+
+ // Keep this after the LPM lookup
+ fib_add(fib, entry);
+
+ if (!lpm) {
+ TFIB(entry)->seq = 0;
+ if (ingress_id != INVALID_FACE_ID)
+ fib_entry_nexthops_add(entry, ingress_id);
+ return entry;
}
- /* EPM on FIB */
- /* only the processor has access to the FIB */
- FIB *fib = forwarder_getFib(mapme->forwarder);
+ /*
+ * We make a clone of the FIB entry (zero'ing the sequence number ?) with
+ * the more specific name, and proceed as usual. Worst case we clone the
+ * default route...
+ */
+ const nexthops_t *lpm_nexthops = fib_entry_get_nexthops(lpm);
+ nexthops_foreach(lpm_nexthops, nh, { fib_entry_nexthops_add(entry, nh); });
+ return entry;
+}
+#endif
- FibEntry *fibEntry = fib_Contains(fib, name);
+int mapme_on_timeout(void *mapme_arg, int fd, unsigned id, void *data) {
+ mapme_t *mapme = mapme_arg;
+ assert(mapme);
+ assert(id == 0);
+ assert(!data);
+ /* Timeout occurred, we have to retransmit IUs for all pending
+ * prefixes having entries in TFIB
+ *
+ * timeouts are slotted
+ * | | | |
+ *
+ * ^
+ * +- event occurred
+ * new face, wait for the second next
+ * (having two arrays and swapping cur and next)
+ * retx : put in next
+ */
+ mapme->idle += 1;
- name_Release(&name);
+ for (uint8_t pos = 0; pos < CURLEN; pos++) {
+ mapme_retx_t *retx = &CUR[pos];
- if (!fibEntry) {
- INFO(mapme, "Ignored update with no FIB entry");
- return 0;
-#if 0
- INFO(mapme,
- "[MAP-Me] - Re-creating FIB entry with next hop on connection %d",
- conn_in_id);
- /*
- * This might happen for a node hosting a producer which has moved.
- * Destroying the face has led to removing all corresponding FIB
- * entries. In that case, we need to correctly restore the FIB entries.
- */
- strategy_type fwdStrategy = LAST_STRATEGY_VALUE;
+ if (!retx->entry) /* deleted entry */
+ continue;
- /*
- * It might also be due to the announcement of a more specific prefix. In
- * that case we need to perform a FIB lookup to find the next hops to which
- * the message should be propagated.
+ mapme_tfib_t *tfib = TFIB(retx->entry);
+ assert(tfib);
+
+ /* Re-send interest for all entries */
+ mapme_update_adjacencies(mapme, retx->entry, false);
+
+ retx->retx_count++;
+ /* If we exceed the numver of retransmittion it means that all tfib
+ * entries have seens at least HICN_PARAM_RETX_MAX of retransmission
*/
-#ifdef WITH_POLICY
- fibEntry = fibEntry_Create(name, fwdStrategy, mapme->forwarder);
-#else
- fibEntry = fibEntry_Create(name, fwdStrategy);
-#endif /* WITH_POLICY */
- FibEntry *lpm = fib_MatchName(fib, name);
- mapme_CreateTFIB(mapme, fibEntry);
- fib_Add(fib, fibEntry);
- if (!lpm) {
- TFIB(fibEntry)->seq = seq;
- fibEntry_AddNexthop(fibEntry, conn_in_id);
- return true;
+ if (retx->retx_count < MAPME_MAX_RETX) {
+ /*
+ * We did some retransmissions, so let's reschedule a check in the
+ * next slot
+ */
+ NXT[NXTLEN++] = CUR[pos];
+ mapme->idle = 0;
+ } else {
+ WARN("Maximum retransmissions exceeded");
+ /* If we exceed the numver of retransmission it means that all TFIB
+ * entries have seens at least HICN_PARAM_RTX_MAX retransmissions.
+ * (Deletion might be slightly late).
+ *
+ * XXX document: when adding an entry in TFIB, we might exceed max
+ * retransmissions for previous entries that started retransmitting
+ * beforehand.
+ */
+ nexthops_clear(&tfib->nexthops);
}
+ }
- /*
- * We make a clone of the FIB entry (zero'ing the sequence number ?) with
- * the more specific name, and proceed as usual. Worst case we clone the
- * default route...
- */
- const NumberSet *lpm_nexthops = fibEntry_GetNexthops(lpm);
- for (size_t i = 0; i < numberSet_Length(lpm_nexthops); i++) {
- fibEntry_AddNexthop(fibEntry, numberSet_GetItem(lpm_nexthops, i));
+ /* Reset events in this slot and prepare for next one */
+ CURLEN = 0;
+ mapme->cur = NEXT_SLOT(mapme->cur);
+
+ /* After two empty slots, we disable the timer */
+ if (mapme->idle > 1) {
+ loop_event_unregister(mapme->timer);
+ }
+
+ return 0;
+}
+
+static void mapme_on_event(mapme_t *mapme, mapme_event_t event,
+ fib_entry_t *entry, unsigned ingress_id) {
+ switch (event) {
+#if 0
+ case HICN_MAPME_EVENT_FACE_ADD:
+ {
+ /*
+ * A face has been added:
+ * - In case of a local app face, we need to advertise a new prefix
+ * - For another local face type, we need to advertise local
+ * prefixes and schedule retransmissions
+ */
+ mapme_retx_t *retx_events = event_data;
+ for (uint8_t i = 0; i < vec_len (retx_events); i++) {
+ hicn_mapme_on_face_added(mapme, retx_events[i].dpo);
+ }
+
+ if (mapme->timer_fd == -1)
+ mapme->timer_fd = loop_register_timer(MAIN_LOOP,
+ mapme->retx, mapme, mapme_on_timeout, NULL);
+ mapme->idle = 0;
+ break;
+ }
+ case HICN_MAPME_EVENT_FACE_DEL:
+ if (mapme->timer_fd == -1)
+ mapme->timer_fd = loop_register_timer(MAIN_LOOP,
+ DEFAULT_TIMEOUT, mapme, mapme_on_timeout, NULL);
+ mapme->idle = 0;
+ break;
+#endif
+
+ case MAPME_EVENT_NH_SET:
+ /*
+ * An hICN FIB entry has been modified. All operations so far
+ * have been procedded in the nodes. Here we need to track
+ * retransmissions upon timeout: we mark the FIB entry as pending in
+ * the second-to-next slot
+ */
+
+ /*
+ * XXX Move this in doc
+ *
+ * The FIB entry has a new next hop, and its TFIB section has:
+ * - eventually previous prev hops for which a IU with a
+ * lower seqno has been sent
+ * - the prev hops that have just been added.
+ *
+ * We don't distinguish any and just send an updated IU to all
+ * of them. The retransmission of the latest IU to all
+ * facilitates the matching of ACKs to a single seqno which is
+ * the one stored in the FIB.
+ *
+ * Since we retransmit to all prev hops, we can remove this
+ * (T)FIB entry for the check at the end of the current slot.
+ */
+
+ /* Mark FIB entry as pending for second-to-next slot */
+ /*
+ * Transmit IU for all TFIB entries with latest seqno (we have
+ * at least one for sure!)
+ */
+ mapme_update_adjacencies(mapme, entry, false);
+
+ /* Delete entry_id from retransmissions in the current slot (if present)
+ * ... */
+ /* ... and schedule it for next slot (if not already) */
+ uint8_t j;
+ for (j = 0; j < CURLEN; j++) {
+ if (CUR[j].entry == entry) CUR[j].entry = NULL; /* sufficient */
+ }
+ for (j = 0; j < NXTLEN; j++) {
+ if (NXT[j].entry == entry) break;
+ }
+ if (j == NXTLEN) /* not found */
+ NXT[NXTLEN++] = (mapme_retx_t){
+ .entry = entry,
+ .retx_count = 0,
+ };
+
+ if (!loop_timer_is_enabled(mapme->timer)) {
+ if (loop_timer_register(mapme->timer, mapme->retx) < 0) {
+ ERROR("Error setting mapme timer.");
+ break;
+ }
+ }
+ mapme->idle = 0;
+ break;
+
+ case MAPME_EVENT_NH_ADD:
+ /*
+ * XXX move this in doc
+ *
+ * As per the description of states, this event should add the face
+ * to the list of next hops, and eventually remove it from TFIB.
+ * This corresponds to the multipath case.
+ *
+ * In all cases, we assume the propagation was already done when the first
+ * interest with the same sequence number was received, so we stop here
+ * No change in TFIB = no IU to send
+ *
+ * No change in timers.
+ */
+
+ // XXX useless
+#if 0
+ /* Add ingress face as next hop */
+ idle = 0;
+#endif
+ break;
+
+ case MAPME_EVENT_PH_ADD:
+ /* Back-propagation, interesting even for IN (desync) */
+ mapme_send_to_nexthop(mapme, entry, ingress_id);
+
+ mapme->idle = 0;
+ if (!loop_timer_is_enabled(mapme->timer))
+ loop_timer_register(mapme->timer, mapme->retx);
+ break;
+
+ case MAPME_EVENT_PH_DEL:
+ /* Ack : remove an element from TFIB */
+ break;
+
+ case MAPME_EVENT_FACE_ADD:
+ case MAPME_EVENT_FACE_DEL:
+
+ case MAPME_EVENT_UNDEFINED:
+ case MAPME_EVENT_N:
+ ERROR("Unexpected event");
+ break;
+ }
+}
+
+static void mapme_on_interest(mapme_t *mapme, msgbuf_t *msgbuf,
+ unsigned ingress_id, hicn_prefix_t *prefix,
+ mapme_params_t *params) {
+ connection_table_t *table = forwarder_get_connection_table(mapme->forwarder);
+
+ /* The cast is needed since connectionTable_FindById miss the
+ * const qualifier for the first parameter */
+ const connection_t *conn_in = connection_table_get_by_id(table, ingress_id);
+
+ /*
+ * Immediately send an acknowledgement back on the ingress connection
+ * We always ack, even duplicates. Clone mgsbuf to avoid to overwrite the
+ * received message
+ */
+ msgbuf_t *ack;
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(mapme->forwarder);
+ off_t interest_offset = msgbuf_pool_get_id(msgbuf_pool, (msgbuf_t *)msgbuf);
+ msgbuf_pool_clone(msgbuf_pool, &ack, interest_offset);
+
+ uint8_t *ack_packet = msgbuf_get_packet(ack);
+ size_t size = hicn_mapme_create_ack(ack_packet, params);
+ if (!connection_send_packet(conn_in, ack_packet, size)) {
+ /* We accept the packet knowing we will get a retransmit */
+ ERROR("Failed to send ACK packet");
+ }
+
+ msgbuf_pool_put(msgbuf_pool, ack);
+
+ WITH_INFO({
+ char buf[MAXSZ_HICN_PREFIX];
+ int rc = hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, prefix);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "%s", "(error)");
+ INFO("Ack'ed interest : connection=%d prefix=%s seq=%d", ingress_id, buf,
+ params->seq);
+ });
+
+ /* EPM on FIB */
+ const fib_t *fib = forwarder_get_fib(mapme->forwarder);
+ fib_entry_t *entry = fib_contains(fib, prefix);
+ if (!entry) {
+#ifdef HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY
+ entry = mapme_create_fib_entry(mapme, prefix, ingress_id);
+ if (!entry) {
+ ERROR("Failed to create FIB entry");
+ return;
}
+#else
+ INFO("Ignored update with no FIB entry");
+ return;
#endif
+ }
- } else if (!TFIB(fibEntry)) {
- /* Create TFIB associated to FIB entry */
- INFO(mapme,
- "[MAP-Me] - Creating TFIB entry with default sequence number");
- mapme_CreateTFIB(mapme, fibEntry);
+ mapme_tfib_t *tfib = TFIB(entry);
+ if (tfib == NULL) {
+ mapme_create_tfib(mapme, entry);
+ tfib = TFIB(entry);
}
/*
@@ -767,102 +899,57 @@ static bool mapme_onSpecialInterest(const MapMe *mapme,
* Detection: we receive a message initially sent by ourselves, ie a message
* for which the prefix has a local next hop in the FIB.
*/
- if (mapme_hasLocalNextHops(mapme, fibEntry)) {
- INFO(mapme, "[MAP-Me] - Received original interest... Update complete");
- return true;
- }
+ // XXX NOT IN VPP ?
- fibSeq = TFIB(fibEntry)->seq;
- if (seq > fibSeq) {
- INFO(mapme,
- "[MAP-Me] - Higher sequence number than FIB %d, updating seq and "
- "next hops",
- fibSeq);
- /* This has to be done first to allow processing SpecialInterestAck's */
- TFIB(fibEntry)->seq = seq;
-
- /* Reliably forward the IU on all prevHops */
- INFO(mapme, "[MAP-Me] - (1/3) processing prev hops");
- if (params->type == UPDATE) {
- PARCIterator *iterator = mapmeTFIB_CreateKeyIterator(TFIB(fibEntry));
- if (iterator) {
- /* No iterator is created if the TFIB is empty */
- while (parcIterator_HasNext(iterator)) {
- PARCUnsigned *cid = parcIterator_Next(iterator);
- unsigned conn_id = parcUnsigned_GetUnsigned(cid);
- INFO(mapme, "[MAP-Me] - Re-sending IU to pending connection %d",
- conn_id);
- mapme_setFacePending(mapme, fibEntry_GetPrefix(fibEntry), fibEntry,
- conn_id, false, false, false, 0);
- }
- parcIterator_Release(&iterator);
- }
- }
+ /* Initially we were detecting that the update completed when it returned to
+ * the producer, Because there might be proxies (using local/remote strategy),
+ * we need instead to verify if there is no non-local faces.
+ */
- /* nextHops -> prevHops
- *
- * We add to the list of pendingUpdates the current next hops, and
- * eventually forward them an IU too.
- *
- * Exception: nextHops -> nextHops
- * Because of retransmission issues, it is possible that a second interest
- * (with same of higher sequence number) is receive from a next-hop
- * interface. In that case, the face remains a next hop.
- */
- const NumberSet *nexthops_old = fibEntry_GetNexthops(fibEntry);
+ if (fib_entry_has_all_local_nexthops(entry)) {
+ INFO("Received original interest... Update complete");
+ return;
+ }
- /* We make a copy to be able to send IU _after_ updating next hops */
- NumberSet *nexthops = numberSet_Create();
- numberSet_AddSet(nexthops, nexthops_old);
+ mapme_event_t event = MAPME_EVENT_UNDEFINED;
+ if (params->seq > tfib->seq) {
+ INFO(
+ "MAPME IU seq %d > fib_seq %d, updating seq and next hops, new "
+ "nexthop=%d",
+ params->seq, tfib->seq, ingress_id);
+ /* This has to be done first to allow processing ack */
+ // XXX this should even be done before sending ack, as in VPP.
+ tfib->seq = params->seq;
- /* We are considering : * -> nextHops
- *
- * If inFace was a previous hop, we need to cancel the timer and remove
- * the entry. Also, the face should be added to next hops.
+ /*
+ * Move nexthops to TFIB... but ingress_id that lands in nexthops
*
- * Optimization : nextHops -> nextHops
- * - no next hop to add
- * - we know that inFace was not a previous hop since it was a next hop and
- * this forms a partition. No need for a search
+ * This could might optimized for situations where nothing changes, but
+ * this is very unlikely if not impossible...
*/
-
- INFO(mapme, "[MAP-Me] - (3/3) next hops ~~> prev hops");
- mapmeTFIB_Remove(mapme, TFIB(fibEntry), conn_in_id);
-
- /* Remove all next hops */
- for (size_t k = 0; k < numberSet_Length(nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(nexthops, k);
- INFO(mapme, "[MAP-Me] - Replaced next hops by connection %d", conn_id);
- fibEntry_RemoveNexthopByConnectionId(fibEntry, conn_id);
- }
- fibEntry_AddNexthop(fibEntry, conn_in_id);
-
- INFO(mapme, "[MAP-Me] - (2/3) processing next hops");
- bool complete = true;
- for (size_t k = 0; k < numberSet_Length(nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(nexthops, k);
- INFO(mapme, " - Next hop connection %d", conn_id);
- if (conn_id == conn_in_id) {
- INFO(mapme, " . Ignored this next hop since equal to ingress face");
- continue;
+ nexthops_t nexthops_keep = NEXTHOPS_EMPTY;
+ nexthops_foreach(&entry->nexthops, prevhop, {
+ const connection_t *conn = connection_table_get_by_id(table, prevhop);
+ /* Preserve local connections, migrate others to TFIB */
+ if (connection_is_local(conn)) {
+ nexthops_add(&nexthops_keep, prevhop);
+ } else {
+ nexthops_add(&tfib->nexthops, prevhop);
}
+ });
- INFO(mapme, "[MAP-Me] - Sending IU on current next hop connection %d",
- conn_id);
- mapme_setFacePending(mapme, fibEntry_GetPrefix(fibEntry), fibEntry,
- conn_id, send, false, false, 0);
- complete = false;
- }
+ nexthops_remove(&tfib->nexthops, ingress_id);
- /*
- * The update is completed when the IU could not be sent to any
- * other next hop.
- */
- if (complete) INFO(mapme, "[MAP-Me] - Update completed !");
+ nexthops_clear(&entry->nexthops);
+ nexthops_add(&entry->nexthops, ingress_id);
+ nexthops_foreach(&nexthops_keep, nh,
+ { nexthops_add(&entry->nexthops, nh); });
+
+ event = MAPME_EVENT_NH_SET;
- numberSet_Release(&nexthops);
+ // XXX tell things are complete if we have no IU to send
- } else if (seq == fibSeq) {
+ } else if (params->seq == tfib->seq) {
/*
* Multipath, multihoming, multiple producers or duplicate interest
*
@@ -873,142 +960,77 @@ static bool mapme_onSpecialInterest(const MapMe *mapme,
* producer and that we received back our own IU. In that case, we just
* need to Ack and ignore it.
*/
-#if 0
- if (mapme_hasLocalNextHops(mapme, fibEntry)) {
- INFO(mapme, "[MAP-Me] - Received original interest... Update complete");
- return true;
- }
-#endif
+ DEBUG("params.seq %d == fib_seq %d, adding nethop %d", params->seq,
+ tfib->seq, ingress_id);
- INFO(mapme, "[MAP-Me] - Adding multipath next hop on connection %d",
- conn_in_id);
- fibEntry_AddNexthop(fibEntry, conn_in_id);
+ /* Move ingress to nexthops (and eventually remove it from TFIB) */
+ nexthops_add(&entry->nexthops, ingress_id);
+ nexthops_remove(&tfib->nexthops, ingress_id);
- } else { // seq < fibSeq
+ event = MAPME_EVENT_NH_ADD;
+
+ } else { // params->seq < tfib->seq
/*
* Face is propagating outdated information, we can just
* consider it as a prevHops. Send the special interest backwards with
* the new sequence number to reconciliate this outdated part of the
* arborescence.
*/
- INFO(
- mapme,
- "[MAP-Me] - Update interest %d -> %d sent backwards on connection %d",
- seq, fibSeq, conn_in_id);
- mapme_setFacePending(mapme, fibEntry_GetPrefix(fibEntry), fibEntry,
- conn_in_id, send, false, false, 0);
- }
-
- return true;
-}
-
-void mapme_onSpecialInterestAck(const MapMe *mapme, const uint8_t *msgBuffer,
- unsigned conn_in_id, hicn_prefix_t *prefix,
- mapme_params_t *params) {
- INFO(mapme, "[MAP-Me] Receive IU/IN Ack on connection %d", conn_in_id);
+ if (nexthops_contains(&entry->nexthops, ingress_id)) {
+ INFO("Ignored seq %d < fib_seq %d from current nexthop on face %d",
+ params->seq, tfib->seq, ingress_id);
+ return;
+ } else {
+ INFO("Received seq %d < fib_seq %d, sending backwards on face %d",
+ params->seq, tfib->seq, ingress_id);
+ nexthops_add(&tfib->nexthops, ingress_id);
+ }
- Name * name =
- name_CreateFromPacket(msgBuffer, MessagePacketType_ContentObject);
- name_setLen((Name*) name, prefix->len);
- char * name_str = name_ToString(name);
- INFO(mapme, "[MAP-Me] Received ack for name prefix=%s seq=%d on conn id=%d",
- name_str, params->seq, conn_in_id);
- free(name_str);
+ event = MAPME_EVENT_PH_ADD;
+ }
- FIB *fib = forwarder_getFib(mapme->forwarder);
- FibEntry *fibEntry = fib_Contains(fib, name);
+ /* Don't trigger events for notification unless we need to send interests
+ * backwards */
+ if ((params->type != UPDATE) && (event != MAPME_EVENT_PH_ADD)) return;
- name_Release(&name);
+ mapme_on_event(mapme, event, entry, ingress_id);
+}
- if (!fibEntry) {
+static void mapme_on_data(mapme_t *mapme, msgbuf_t *msgbuf, unsigned ingress_id,
+ hicn_prefix_t *prefix, mapme_params_t *params) {
+ WITH_INFO({
+ char buf[MAXSZ_HICN_PREFIX];
+ int rc = hicn_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, prefix);
+ if (rc < 0 || rc >= MAXSZ_HICN_PREFIX)
+ snprintf(buf, MAXSZ_HICN_PREFIX, "(error)");
+ INFO("Received ack for name prefix=%s seq=%d on conn id=%d", buf,
+ params->seq, ingress_id);
+ })
+
+ const fib_t *fib = forwarder_get_fib(mapme->forwarder);
+ fib_entry_t *entry = fib_contains(fib, prefix);
+ if (!entry) {
+ INFO("Ignored ACK with no corresponding FIB entry");
return;
}
- parcAssertNotNull(fibEntry,
- "No corresponding FIB entry for name contained in IU Ack");
-
- /* Test if the latest pending update has been ack'ed, otherwise just ignore */
- seq_t seq = params->seq;
- if (seq != INVALID_SEQ) {
- seq_t fibSeq = TFIB(fibEntry)->seq;
-
- if (seq < fibSeq) {
-
- /* If we receive an old ack:
- * - either the connection is still a next hop and we have to ignore
- * the ack until we receive a further update with higher seqno
- * - or the connection is no more to be informed and the ack is
- * sufficient and we can remove future retransmissions
- */
-
- INFO(mapme,
- "[MAP-Me] - Ignored special interest Ack with seq=%u, expected %u",
- seq, fibSeq);
- return;
- }
- }
+ mapme_tfib_t *tfib = TFIB(entry);
/*
- * Ignore the Ack if no TFIB is present, or it has no corresponding entry
- * with the ingress face.
- * Note: previously, we were creating the TFIB entry
+ * As we always retransmit IU with the latest seq, we are not interested in
+ * ACKs with inferior seq
*/
- if (!TFIB(fibEntry)) {
- INFO(mapme, "[MAP-Me] - Ignored ACK for prefix with no TFIB entry");
- return;
- }
-
- PARCEventTimer *timer =
- (PARCEventTimer *)mapmeTFIB_Get(TFIB(fibEntry), conn_in_id);
- if (!timer) {
- INFO(mapme,
- "[MAP-Me] - Ignored ACK for prefix not having the Connection in "
- "TFIB entry. Possible duplicate ?");
+ if (params->seq < tfib->seq) {
+ INFO("Ignored ACK with seq %d < %d", params->seq, tfib->seq);
return;
}
- /* Stop timer and remove entry from TFIB */
- mapmeTFIB_Remove(mapme, TFIB(fibEntry), conn_in_id);
-
- INFO(mapme, "[MAP-Me] - Removing TFIB entry for ack on connection %d",
- conn_in_id);
+ nexthops_remove(&tfib->nexthops, ingress_id);
+ mapme_on_event(mapme, MAPME_EVENT_PH_DEL, entry, ingress_id);
/* We need to update the timestamp only for IU Acks, not for IN Acks */
if (params->type == UPDATE_ACK) {
- INFO(mapme, "[MAP-Me] - Updating LastAckedUpdate");
- TFIB(fibEntry)->lastAckedUpdate = forwarder_GetTicks(mapme->forwarder);
- }
-}
-
-/*-----------------------------------------------------------------------------
- * Overloaded functions
- *----------------------------------------------------------------------------*/
-
-/*
- * @abstract returns where to forward a normal interests(nexthops) defined by
- * mapme, it also set the sequnence number properly if needed
- */
-
-/******************************************************************************
- * Public functions (exposed in the .h)
- ******************************************************************************/
-
-/*
- * Returns true iif the message corresponds to a MAP-Me packet
- */
-bool mapme_isMapMe(const uint8_t *packet) {
- hicn_mapme_header_t * mapme = (hicn_mapme_header_t*)packet;
-
- switch(HICN_IP_VERSION(packet)) {
- case 4:
- if (mapme->v4.ip.protocol != IPPROTO_ICMP)
- return false;
- return HICN_IS_MAPME(mapme->v4.icmp_rd.type, mapme->v4.icmp_rd.code);
- case 6:
- if (mapme->v6.ip.nxt != IPPROTO_ICMPV6)
- return false;
- return HICN_IS_MAPME(mapme->v6.icmp_rd.type, mapme->v6.icmp_rd.code);
- default:
- return false;
+ INFO(" - Updating LastAckedUpdate");
+ tfib->last_acked_update = ticks_now();
}
}
@@ -1023,25 +1045,70 @@ bool mapme_isMapMe(const uint8_t *packet) {
* MAP-Me (eg. ICMP packets) and return higher level messages that can be
* processed by MAP-Me core.
*/
-void mapme_Process(const MapMe *mapme, const uint8_t *msgBuffer,
- unsigned conn_id) {
+void mapme_process(mapme_t *mapme, msgbuf_t *msgbuf) {
+ if (mapme->enabled == false) {
+ WARN("MAP-Me is NOT enabled");
+ return;
+ }
+
hicn_prefix_t prefix;
mapme_params_t params;
- hicn_mapme_parse_packet(msgBuffer, &prefix, &params);
+ uint8_t *packet = msgbuf_get_packet(msgbuf);
+ unsigned conn_id = msgbuf_get_connection_id(msgbuf);
+
+ int rc = hicn_mapme_parse_packet(packet, &prefix, &params);
+ if (rc < 0) return;
+
+ // XXX TYPE STR
+ INFO("Received interest type: %d seq: %d len:%d", params.type, params.seq,
+ prefix.len);
+
+ // XXX RENAME TYPES
switch (params.type) {
case UPDATE:
case NOTIFICATION:
- mapme_onSpecialInterest(mapme, msgBuffer, conn_id, &prefix, &params);
+ mapme_on_interest(mapme, msgbuf, conn_id, &prefix, &params);
break;
case UPDATE_ACK:
case NOTIFICATION_ACK:
- mapme_onSpecialInterestAck(mapme, msgBuffer, conn_id, &prefix, &params);
+ mapme_on_data(mapme, msgbuf, conn_id, &prefix, &params);
break;
default:
- ERR(mapme, "[MAP-Me] Unknown message");
+ ERROR("Unknown message");
break;
}
}
+#if 0
+/*
+ * Returns true iif the message corresponds to a MAP-Me packet
+ */
+bool mapme_match_packet(const uint8_t *packet) {
+ hicn_mapme_header_t *mapme = (hicn_mapme_header_t *)packet;
+
+ switch (HICN_IP_VERSION(packet)) {
+ case 4:
+ if (mapme->v4.ip.protocol != IPPROTO_ICMP) return false;
+ return HICN_IS_MAPME(mapme->v4.icmp_rd.type, mapme->v4.icmp_rd.code);
+ case 6:
+ if (mapme->v6.ip.nxt != IPPROTO_ICMPV6) return false;
+ return HICN_IS_MAPME(mapme->v6.icmp_rd.type, mapme->v6.icmp_rd.code);
+ default:
+ return false;
+ }
+}
+#endif
+
+void mapme_set_enable(mapme_t *mapme, bool enable) { mapme->enabled = enable; }
+void mapme_set_discovery(mapme_t *mapme, bool enable) {
+ mapme->discovery = enable;
+}
+void mapme_set_timescale(mapme_t *mapme, uint32_t time) {
+ mapme->timescale = time;
+}
+void mapme_set_retransmision(mapme_t *mapme, uint32_t time) {
+ mapme->retx = time;
+}
+
#endif /* WITH_MAPME */
diff --git a/hicn-light/src/hicn/core/mapme.h b/hicn-light/src/hicn/core/mapme.h
index 72f8d536a..9ece8a090 100644
--- a/hicn-light/src/hicn/core/mapme.h
+++ b/hicn-light/src/hicn/core/mapme.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,29 +26,34 @@
#include <stdbool.h>
#include <stdint.h>
+#include <hicn/ctrl/hicn-light.h>
#include <hicn/hicn.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/core/connection.h>
-#include <hicn/utils/commands.h>
-struct mapme;
-typedef struct mapme MapMe;
+#include "connection.h"
+#include "fib_entry.h"
+#include "msgbuf.h"
+
+// Allow processing of MAP-Me requests when no FIB entry is present.
+// An alternative would be to perform a LPM
+#define HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY
+
+typedef struct mapme_s mapme_t;
/**
* @function mapme_create
* @abstract Initializes MAP-Me state in the forwarder.
* @return bool - Boolean informing about the success of MAP-Me initialization.
*/
-bool mapme_create(MapMe **mapme, Forwarder *Forwarder);
+mapme_t *mapme_create(void *Forwarder);
/**
* @function mapme_free
* @abstract Free MAP-Me state in the forwarder.
*/
-void mapme_free(MapMe *mapme);
+void mapme_free(mapme_t *mapme);
/**
- * @function messageHandler_isMapMe
+ * @function messageHandler_is_mapme
* @abstract Identifies MAP-Me messages
* @discussion This function can be used by the forwarder to dispatch MAP-Me
* message to the appropriate processing function. Ideally this would be
@@ -56,48 +61,68 @@ void mapme_free(MapMe *mapme);
* @param [in] msgBuffer - The buffer to match
* @return A boolean indicating whether message is a MAP-Me control message.
*/
-bool mapme_isMapMe(const uint8_t *msgBuffer);
+bool mapme_match_packet(const uint8_t *msgBuffer);
/**
- * @function mapme_handleMapMeMessage
+ * @function mapme_handlemapme_tMessage
* @abstract Process a MAP-Me message.
* @param [in] mapme - Pointer to the MAP-Me data structure.
* @param [in] message - MAP-Me buffer
* @param [in] conn_id - Ingress connection id
*/
-void mapme_Process(const MapMe *mapme, const uint8_t *msgBuffer,
- unsigned conn_id);
+void mapme_process(mapme_t *mapme, msgbuf_t *msgbuf);
+/* mapme API */
/**
* @function mapme_send_updates
- * @abstract Trigger (if needed) the update for specified FIB entry and nexthops
+ * @abstract sends an update to all adjacencies. Used for face
+ * add/delete/changes (priority.tag) and policy
* @param [in] mapme - Pointer to the MAP-Me data structure.
- * @param [in] fibEntry - The FIB entry to consider
- * @param [in] nexthops - NumberSet holding the next hops on which to send the
- * update.
+ * @param [in] fib_entry - The FIB entry to consider
*/
-void mapme_send_updates(const MapMe * mapme, FibEntry * fibEntry, const NumberSet * nexthops);
+int mapme_set_all_adjacencies(const mapme_t *mapme, fib_entry_t *entry);
/**
- * @function mapme_send_updates
- * @abstract Trigger the update for specified FIB entry and nexthops, only if needed
+ * @function mapme_set_adjacencies
+ * @abstract sends an update to the specified adjacencies. Used by forwarding
+ * strategies
* @param [in] mapme - Pointer to the MAP-Me data structure.
- * @param [in] fibEntry - The FIB entry to consider
- * @param [in] nexthops - NumberSet holding the next hops on which to send the
- * update.
+ * @param [in] fib_entry - The FIB entry to consider
+ * @param [in] nexthops - next hops on which to send the update.
+ * @param [in] prefix - A more specific prefix (special use with no retx), or
+ * NULL
*/
-void mapme_maybe_send_updates(const MapMe * mapme, FibEntry * fibEntry, const NumberSet * nexthops);
+int mapme_set_adjacencies(const mapme_t *mapme, fib_entry_t *entry,
+ nexthops_t *nexthops, const hicn_prefix_t *prefix);
/**
- * @function mapme_reconsiderFibEntry
- * @abstract Process a fib entry for changes that might trigger new updates
+ * @function mapme_set_adjacencies
+ * @abstract sends an update to the specified adjacency. Used by control plane
+ * commands.
* @param [in] mapme - Pointer to the MAP-Me data structure.
- * @param [in] fibEntry - The FIB entry to consider
+ * @param [in] fib_entry - The FIB entry to consider
+ * @param [in] nexthop - nexthop on which to send the update.
+ * @param [in] prefix - A more specific prefix (special use with no retx), or
+ * NULL
*/
-void mapme_reconsiderFibEntry(const MapMe *mapme, FibEntry * fibEntry);
+int mapme_set_adjacency(const mapme_t *mapme, fib_entry_t *entry,
+ nexthop_t nexthop, const hicn_prefix_t *prefix);
/**
- * @function mapme_onConnectionEvent
+ * @function mapme_update_adjacencies
+ * @abstract sends an update on previuos adjacencies. Used for IU forwarding,
+ * NAT and timeouts
+ * strategies
+ * @param [in] mapme - Pointer to the MAP-Me data structure.
+ * @param [in] fib_entry - The FIB entry to consider
+ * @param [in] inc_iu_seq - if true, the seq number of the tfib/mapme iu will be
+ * increased by one
+ */
+int mapme_update_adjacencies(const mapme_t *mapme, fib_entry_t *entry,
+ bool inc_iu_seq);
+
+/**
+ * @function mapme_on_connection_event
* @abstract Callback following the addition of the face though the control
* protocol.
* @discussion This callback triggers the sending of control packets by MAP-Me.
@@ -105,19 +130,27 @@ void mapme_reconsiderFibEntry(const MapMe *mapme, FibEntry * fibEntry);
* @param [in] conn - The newly added connection.
* @param [in] event - Connection event
*/
-void mapme_onConnectionEvent(const MapMe *mapme, const Connection *conn, connection_event_t event);
+void mapme_on_connection_event(const mapme_t *mapme, const connection_t *conn,
+ connection_event_t event);
/**
- * @function mapme_getNextHops
+ * @function mapme_get_nexthops
* @abstract return the nexthops to forward interests defined by mapme, it
* covers also the case where local discovery mechanisms are trriggered.
*/
-NumberSet *mapme_getNextHops(const MapMe *mapme, FibEntry *fibEntry,
- const Message *interest);
-
-hicn_mapme_type_t mapme_PktType_To_LibHicnPktType(MessagePacketType type);
-
-MessagePacketType mapme_LibHicnPktType_To_PktType(hicn_mapme_type_t type);
+// nexthops_t * mapme_get_nexthops(const mapme_t *mapme, fib_entry_t *fib_entry,
+// const msgbuf_t *interest);
+
+#ifdef HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY
+fib_entry_t *mapme_create_fib_entry(const mapme_t *mapme,
+ const hicn_prefix_t *prefix,
+ unsigned ingress_id);
+#endif /* HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY */
+
+void mapme_set_enable(mapme_t *mapme, bool enable);
+void mapme_set_discovery(mapme_t *mapme, bool enable);
+void mapme_set_timescale(mapme_t *mapme, uint32_t time);
+void mapme_set_retransmision(mapme_t *mapme, uint32_t time);
#endif /* WITH_MAPME */
diff --git a/hicn-light/src/hicn/core/message.c b/hicn-light/src/hicn/core/message.c
deleted file mode 100644
index c28938320..000000000
--- a/hicn-light/src/hicn/core/message.c
+++ /dev/null
@@ -1,299 +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 <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <hicn/core/forwarder.h>
-#include <hicn/core/message.h>
-#include <hicn/core/wldr.h>
-
-#include <hicn/core/messageHandler.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-#include <hicn/core/messagePacketType.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_EventBuffer.h>
-
-struct message {
- Logger *logger;
-
- Ticks receiveTime;
- unsigned ingressConnectionId;
-
- Name *name;
-
- uint8_t *messageHead;
-
- unsigned length;
-
- uint8_t packetType;
-
- unsigned refcount;
-};
-
-Message *message_Acquire(const Message *message) {
- Message *copy = (Message *)message;
- copy->refcount++;
- return copy;
-}
-
-Message *message_CreateFromEventBuffer(PARCEventBuffer *data, size_t dataLength,
- unsigned ingressConnectionId,
- Ticks receiveTime, Logger *logger) {
- // used by applications, we can get only interest or data packets
- Message *message = parcMemory_AllocateAndClear(sizeof(Message));
- parcAssertNotNull(message, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Message));
-
- message->logger = logger_Acquire(logger);
- message->receiveTime = receiveTime;
- message->ingressConnectionId = ingressConnectionId;
- message->length = (unsigned int)dataLength;
-
- message->messageHead = parcMemory_AllocateAndClear(dataLength);
- parcAssertNotNull(message->messageHead,
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- dataLength);
-
- // copy the data because *data is destroyed in the connection.
- int res = parcEventBuffer_Read(data, message->messageHead, dataLength);
- if (res == -1) {
- return NULL;
- }
-
- if (messageHandler_IsInterest(message->messageHead)) {
- message->packetType = MessagePacketType_Interest;
- } else if (messageHandler_IsData(message->messageHead)) {
- message->packetType = MessagePacketType_ContentObject;
- } else {
- printf("Got a packet that is not a data nor an interest, drop it!\n");
- return NULL;
- }
- message->name =
- name_CreateFromPacket(message->messageHead, message->packetType);
-
- message->refcount = 1;
-
- return message;
-}
-
-Message *message_CreateFromByteArray(unsigned connid, uint8_t *pckt,
- MessagePacketType type, Ticks receiveTime,
- Logger *logger) {
- Message *message = parcMemory_AllocateAndClear(sizeof(Message));
- parcAssertNotNull(message, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Message));
-
- message->logger = logger_Acquire(logger);
- message->receiveTime = receiveTime;
- message->ingressConnectionId = connid;
- message->messageHead = pckt;
- message->length = messageHandler_GetTotalPacketLength(pckt);
- message->packetType = type;
-
- if (messageHandler_IsWldrNotification(pckt)) {
- message->name = NULL;
- } else {
- message->name =
- name_CreateFromPacket(message->messageHead, message->packetType);
- }
-
- message->refcount = 1;
-
- return message;
-}
-
-void message_Release(Message **messagePtr) {
- parcAssertNotNull(messagePtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*messagePtr,
- "Parameter must dereference to non-null pointer");
-
- Message *message = *messagePtr;
- parcAssertTrue(
- message->refcount > 0,
- "Invalid state: message_Release called on message with 0 references %p",
- (void *)message);
-
- message->refcount--;
- if (message->refcount == 0) {
- if (logger_IsLoggable(message->logger, LoggerFacility_Message,
- PARCLogLevel_Debug)) {
- logger_Log(message->logger, LoggerFacility_Message, PARCLogLevel_Debug,
- __func__, "Message %p destroyed", (void *)message);
- }
-
- logger_Release(&message->logger);
- if (message->name != NULL) name_Release(&message->name);
- parcMemory_Deallocate((void **)&message->messageHead);
- parcMemory_Deallocate((void **)&message);
- }
- *messagePtr = NULL;
-}
-
-bool message_Write(PARCEventQueue *parcEventQueue, const Message *message) {
- parcAssertNotNull(message, "Message parameter must be non-null");
- parcAssertNotNull(parcEventQueue, "Buffer parameter must be non-null");
-
- return parcEventQueue_Write(parcEventQueue, message->messageHead,
- message_Length(message));
-}
-
-size_t message_Length(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return message->length;
-}
-
-bool message_HasWldr(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return messageHandler_HasWldr(message->messageHead);
-}
-
-bool message_IsWldrNotification(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return messageHandler_IsWldrNotification(message->messageHead);
-}
-
-void message_ResetWldrLabel(Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- messageHandler_ResetWldrLabel(message->messageHead);
-}
-
-unsigned message_GetWldrLabel(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return messageHandler_GetWldrLabel(message->messageHead);
-}
-
-unsigned message_GetWldrExpectedLabel(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return messageHandler_GetExpectedWldrLabel(message->messageHead);
-}
-
-unsigned message_GetWldrLastReceived(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return messageHandler_GetWldrLastReceived(message->messageHead);
-}
-
-void message_SetWldrLabel(Message *message, uint16_t label) {
- parcAssertNotNull(message, "Parameter must be non-null");
- messageHandler_SetWldrLabel(message->messageHead, label);
-}
-
-Message *message_CreateWldrNotification(Message *original, uint16_t expected,
- uint16_t lastReceived) {
- parcAssertNotNull(original, "Parameter original must be non-null");
- Message *message = parcMemory_AllocateAndClear(sizeof(Message));
- parcAssertNotNull(message, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Message));
- message->receiveTime = original->receiveTime;
- message->ingressConnectionId = original->ingressConnectionId;
- message->refcount = 1;
- message->logger = logger_Acquire(original->logger);
-
- message->length = (unsigned int)messageHandler_GetICMPPacketSize(
- messageHandler_GetIPPacketType(original->messageHead));
- message->messageHead = parcMemory_AllocateAndClear(message->length);
- parcAssertNotNull(message->messageHead,
- "parcMemory_AllocateAndClear returned NULL");
-
- message->packetType = MessagePacketType_WldrNotification;
- message->name = NULL; // nobody will use the name in a notification packet,
- // so we can simply set it to NULL
-
- // set notification stuff.
- messageHandler_SetWldrNotification(
- message->messageHead, original->messageHead, expected, lastReceived);
- return message;
-}
-
-unsigned message_GetIngressConnectionId(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return message->ingressConnectionId;
-}
-
-void message_SetIngressConnectionId(Message *message, unsigned conn) {
- parcAssertNotNull(message, "Parameter must be non-null");
- message->ingressConnectionId = conn;
-}
-
-Ticks message_GetReceiveTime(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return message->receiveTime;
-}
-
-uint32_t message_GetPathLabel(const Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- return messageHandler_GetPathLabel(message->messageHead);
-}
-
-void message_SetPathLabel(Message *message, uint32_t label) {
- parcAssertNotNull(message, "Parameter must be non-null");
- messageHandler_SetPathLabel(message->messageHead,
- messageHandler_GetPathLabel(message->messageHead), label);
-}
-
-void message_UpdatePathLabel(Message *message, uint8_t outFace) {
- parcAssertNotNull(message, "Parameter must be non-null");
- messageHandler_UpdatePathLabel(message->messageHead, outFace);
-}
-
-void message_ResetPathLabel(Message *message) {
- parcAssertNotNull(message, "Parameter must be non-null");
- messageHandler_ResetPathLabel(message->messageHead);
-}
-
-MessagePacketType message_GetType(const Message *message) {
- parcAssertNotNull(message, "Parameter message must be non-null");
- return message->packetType;
-}
-
-Name *message_GetName(const Message *message) {
- parcAssertNotNull(message, "Parameter message must be non-null");
- return message->name;
-}
-
-bool message_HasInterestLifetime(const Message *message) {
- parcAssertNotNull(message, "Parameter message must be non-null");
- return messageHandler_HasInterestLifetime(message->messageHead);
-}
-
-uint64_t message_GetInterestLifetimeTicks(const Message *message) {
- parcAssertNotNull(message, "Parameter message must be non-null");
- uint64_t lifetime = messageHandler_GetInterestLifetime(message->messageHead);
- return forwarder_NanosToTicks(lifetime * 1000000ULL);
-}
-
-bool message_HasContentExpiryTime(const Message *message) {
- parcAssertNotNull(message, "Parameter message must be non-null");
- return messageHandler_HasContentExpiryTime(message->messageHead);
-}
-
-uint64_t message_GetContentExpiryTimeTicks(const Message *message) {
- parcAssertNotNull(message, "Parameter message must be non-null");
- uint64_t expire = messageHandler_GetContentExpiryTime(message->messageHead);
- if(expire == 0)
- return message->receiveTime;
- return message->receiveTime + forwarder_NanosToTicks(expire * 1000000ULL);
-}
-
-const uint8_t *message_FixedHeader(const Message *message) {
- parcAssertNotNull(message, "Parameter message must be non-null");
- return message->messageHead;
-}
diff --git a/hicn-light/src/hicn/core/message.h b/hicn-light/src/hicn/core/message.h
deleted file mode 100644
index e77dab2b5..000000000
--- a/hicn-light/src/hicn/core/message.h
+++ /dev/null
@@ -1,180 +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.
- */
-
-/**
- * @file message.h
- * @brief Message is the unit of forwarding, i.e. the packets being switched
- *
- */
-#ifndef message_h
-#define message_h
-
-#include <hicn/hicn-light/config.h>
-#include <hicn/core/logger.h>
-#include <hicn/core/messagePacketType.h>
-#include <hicn/core/streamBuffer.h>
-
-#include <hicn/core/name.h>
-
-#include <parc/algol/parc_EventBuffer.h>
-#include <parc/algol/parc_EventQueue.h>
-
-#include <hicn/utils/address.h>
-
-#include <hicn/core/ticks.h>
-
-struct message;
-typedef struct message Message;
-
-/**
- * @function message_CreateFromBuffer
- * @abstract Takes ownership of the input buffer, which comprises one complete
- * message
- */
-
-Message *message_CreateFromEventBuffer(PARCEventBuffer *data, size_t dataLength,
- unsigned ingressConnectionId,
- Ticks receiveTime, Logger *logger);
-
-/**
- * @function message_CreateFromByteArray
- * @abstract create a message from a byte array
- */
-
-Message *message_CreateFromByteArray(unsigned connid, uint8_t *pckt,
- MessagePacketType type, Ticks receiveTime,
- Logger *logger);
-
-/**
- * @function message_Copy
- * @abstract Get a reference counted copy
- */
-
-Message *message_Acquire(const Message *message);
-
-/**
- * Releases the message and frees the memory
- */
-void message_Release(Message **messagePtr);
-
-/**
- * Writes the message to the queue
- */
-
-bool message_Write(PARCEventQueue *parcEventQueue, const Message *message);
-
-/**
- * Returns the total byte length of the message
- */
-size_t message_Length(const Message *message);
-
-bool message_HasWldr(const Message *message);
-
-bool message_IsWldrNotification(const Message *message);
-
-void message_ResetWldrLabel(Message *message);
-
-unsigned message_GetWldrLabel(const Message *message);
-
-unsigned message_GetWldrExpectedLabel(const Message *message);
-
-unsigned message_GetWldrLastReceived(const Message *message);
-
-void message_SetWldrLabel(Message *message, uint16_t label);
-
-Message *message_CreateWldrNotification(Message *original, uint16_t expected,
- uint16_t lastReceived);
-/**
- * Returns the connection id of the packet input
- */
-unsigned message_GetIngressConnectionId(const Message *message);
-
-void message_SetIngressConnectionId(Message *message, unsigned conn);
-
-/**
- * Returns the receive time (in router ticks) of the message
- */
-Ticks message_GetReceiveTime(const Message *message);
-
-/**
- * Returns the PacketType
- */
-MessagePacketType message_GetType(const Message *message);
-
-uint32_t message_GetPathLabel(const Message *message);
-void message_SetPathLabel(Message *message, uint32_t label);
-void message_UpdatePathLabel(Message *message, uint8_t outFace);
-void message_ResetPathLabel(Message *message);
-
-// ===========================================================
-// Accessors used to index and compare messages
-
-/**
- * @function message_GetName
- * @abstract The name in the message
- * @discussion
- * The name of the Interest or Content Object. If the caller will store the
- * name, he should make a reference counted copy.
- * @return The name as stored in the message object.
- */
-
-Name *message_GetName(const Message *message);
-
-/**
- * Determines if the message has an Interest Lifetime parameter
- *
- * @param [in] message An allocated and parsed Message
- *
- * @retval true If an Intrerest Lifetime field exists
- * @retval false If no Interest Lifetime exists
- */
-
-bool message_HasInterestLifetime(const Message *message);
-
-/**
- * Returns the Interest lifetime in hicn-light Ticks
- *
- * the interest expires after now + returned ticks
- *
- * @param [in] message An allocated and parsed Message
- *
- * @retval integer Lifetime in forwarder Ticks
- *
- */
-
-uint64_t message_GetInterestLifetimeTicks(const Message *message);
-
-/**
- * checks if the expiry time is set inside the content object
- */
-bool message_HasContentExpiryTime(const Message *message);
-
-/**
- * returns the moment (in hicn-light ticks) when the content object will expire
- */
-uint64_t message_GetContentExpiryTimeTicks(const Message *message);
-
-/**
- * Returns a pointer to the beginning of the FixedHeader
- *
- * @param [in] message An allocated and parsed Message
- *
- * @return non-null The fixed header memory
- * @return null No fixed header or an error
- */
-
-const uint8_t *message_FixedHeader(const Message *message);
-
-#endif // message_h
diff --git a/hicn-light/src/hicn/core/messageHandler.h b/hicn-light/src/hicn/core/messageHandler.h
deleted file mode 100644
index b41c9a7f0..000000000
--- a/hicn-light/src/hicn/core/messageHandler.h
+++ /dev/null
@@ -1,758 +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.
- */
-
-#ifndef messageHandler
-#define messageHandler
-
-#include <stdlib.h>
-#ifndef _WIN32
-#include <unistd.h> // close
-#endif
-
-#include <hicn/hicn.h>
-#include <hicn/core/messagePacketType.h>
-
-#define H(packet) ((hicn_header_t *)packet)
-#define H6(packet) (H(packet)->v6.ip)
-#define H6T(packet) (H(packet)->v6.tcp)
-#define H4(packet) (H(packet)->v4.ip)
-#define H4T(packet) (H(packet)->v4.tcp)
-
-#define HICN_V6_LEN(packet) (H6(packet).len)
-#define HICN_V4_LEN(packet) (H4(packet).len)
-
-/*** codes and types ***/
-#define IPv6_TYPE 6
-#define IPv4_TYPE 4
-#define ICMP_WLDR_TYPE 42
-#define ICMP_WLDR_CODE 0
-#define ICMP_LB_TYPE 43
-
-/*** masks and constants ***/
-#define PATH_LABEL_MASK 0x8000 // 1000 0000 0000 0000
-#define NOT_PATH_LABEL_MASK 0x7fff // 0111 0000 0000 0000
-#define UINT16_T_MASK 0x0000ffff // 1111 1111 1111 1111
-
-/*** HICN ALLOWED PORTS ***/
-#define CONTROL_PORT 9695
-#define HTTP_PORT 8080
-
-#define IPV6_DEFAULT_VERSION 6
-#define IPV6_DEFAULT_TRAFFIC_CLASS 0
-#define IPV6_DEFAULT_FLOW_LABEL 0
-
-#define expected_lbl wldr_notification_lbl.expected_lbl
-#define received_lbl wldr_notification_lbl.received_lbl
-
-#include <hicn/core/forwarder.h>
-
-#ifdef WITH_MAPME
-#include <hicn/core/mapme.h>
-#include <hicn/socket/api.h>
-#endif /* WITH_MAPME */
-
-#define CONNECTION_ID_UNDEFINED -1
-
-#define BFD_PORT 3784
-
-static inline uint8_t messageHandler_GetIPPacketType(const uint8_t *message) {
- return HICN_IP_VERSION(message);
-}
-
-static inline void messageHandler_UpdateTCPCheckSum(uint8_t *message,
- uint16_t *old_val,
- uint16_t *new_val,
- uint8_t size) {
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv4_TYPE:
- for (uint8_t i = 0; i < size; i++) {
- uint16_t old_csum = ~(H4T(message).csum);
- uint16_t not_old_val = ~(*old_val);
- uint32_t sum = (uint32_t)old_csum + not_old_val + *new_val;
-
- while (sum >> 16) {
- sum = (sum >> 16) + (sum & UINT16_T_MASK);
- }
-
- H4T(message).csum = ~sum;
- ++old_val;
- ++new_val;
- }
- break;
- case IPv6_TYPE:
- for (uint8_t i = 0; i < size; i++) {
- uint16_t old_csum = ~(H6T(message).csum);
- uint16_t not_old_val = ~(*old_val);
- uint32_t sum = (uint32_t)old_csum + not_old_val + *new_val;
-
- while (sum >> 16) {
- sum = (sum >> 16) + (sum & UINT16_T_MASK);
- }
-
- H6T(message).csum = ~sum;
- ++old_val;
- ++new_val;
- }
- break;
- default:
- return;
- }
-}
-
-static inline void messageHandler_UpdateIPv4CheckSum(uint8_t *message,
- uint16_t *old_val,
- uint16_t *new_val,
- uint8_t size) {
- for (uint8_t i = 0; i < size; i++) {
- uint16_t old_csum = ~(H4(message).csum);
- uint16_t not_old_val = ~(*old_val);
- uint32_t sum = (uint32_t)old_csum + not_old_val + *new_val;
-
- while (sum >> 16) {
- sum = (sum >> 16) + (sum & UINT16_T_MASK);
- }
-
- H4(message).csum = ~sum;
- ++old_val;
- ++new_val;
- }
-}
-
-static inline size_t messageHandler_GetEmptyTCPPacketSize(unsigned ipVersion) {
- if (ipVersion == IPv4_TYPE)
- return IPV4_HDRLEN + TCP_HDRLEN;
- else if (ipVersion == IPv6_TYPE)
- return IPV6_HDRLEN + TCP_HDRLEN;
- else
- return 0;
-}
-
-static inline size_t messageHandler_GetICMPPacketSize(unsigned ipVersion) {
- if (ipVersion == IPv4_TYPE)
- return IPV4_HDRLEN + ICMP_HDRLEN;
- else if (ipVersion == IPv6_TYPE)
- return IPV6_HDRLEN + ICMP_HDRLEN;
- else
- return 0;
-}
-
-static inline size_t messageHandler_GetIPHeaderLength(unsigned ipVersion) {
- if (ipVersion == IPv4_TYPE)
- return IPV4_HDRLEN;
- else if (ipVersion == IPv6_TYPE)
- return IPV6_HDRLEN;
- else
- return 0;
-}
-
-static inline bool messageHandler_IsValidHicnPacket(const uint8_t *message) {
- uint8_t version = messageHandler_GetIPPacketType(message);
- if (version == IPv6_TYPE || version == IPv4_TYPE) {
- return true;
- }
- return false;
-}
-
-static inline uint8_t messageHandler_NextHeaderType(const uint8_t *message) {
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- return (uint8_t)H6(message).nxt;
- case IPv4_TYPE:
- return (uint8_t)H4(message).protocol;
- default:
- return 0;
- }
-}
-
-/* Forward declarations */
-static inline void * messageHandler_GetSource(const uint8_t *message);
-static inline void *messageHandler_GetDestination(const uint8_t *message);
-
-static const
-AddressPair *
-_createRecvAddressPairFromPacket(const uint8_t *msgBuffer) {
- Address *packetSrcAddr = NULL; /* This one is in the packet */
- Address *localAddr = NULL; /* This one is to be determined */
-
- if (messageHandler_GetIPPacketType(msgBuffer) == IPv6_TYPE) {
- struct sockaddr_in6 addr_in6;
- addr_in6.sin6_family = AF_INET6;
- addr_in6.sin6_port = htons(1234);
- addr_in6.sin6_flowinfo = 0;
- addr_in6.sin6_scope_id = 0;
- memcpy(&addr_in6.sin6_addr,
- (struct in6_addr *)messageHandler_GetSource(msgBuffer), 16);
- packetSrcAddr = addressCreateFromInet6(&addr_in6);
-
- /* We now determine the local address used to reach the packet src address */
- int sock = (int)socket (AF_INET6, SOCK_DGRAM, 0);
- if (sock < 0)
- goto ERR;
-
- struct sockaddr_in6 remote, local;
- memset(&remote, 0, sizeof(remote));
- remote.sin6_family = AF_INET6;
- remote.sin6_addr = addr_in6.sin6_addr;
- remote.sin6_port = htons(1234);
-
- socklen_t locallen = sizeof(local);
- if (connect(sock, (const struct sockaddr*)&remote, sizeof(remote)) == -1)
- goto ERR;
- if (getsockname(sock, (struct sockaddr*) &local, &locallen) == -1)
- goto ERR;
-
- local.sin6_port = htons(1234);
- localAddr = addressCreateFromInet6(&local);
-
- close(sock);
-
- } else if (messageHandler_GetIPPacketType(msgBuffer) == IPv4_TYPE) {
- struct sockaddr_in addr_in;
- addr_in.sin_family = AF_INET;
- addr_in.sin_port = htons(1234);
- memcpy(&addr_in.sin_addr,
- (struct in_addr *)messageHandler_GetSource(msgBuffer), 4);
- packetSrcAddr = addressCreateFromInet(&addr_in);
-
- /* We now determine the local address used to reach the packet src address */
-
- int sock = (int)socket (AF_INET, SOCK_DGRAM, 0);
- if (sock < 0) {
- perror("Socket error");
- goto ERR;
- }
-
- struct sockaddr_in remote, local;
- memset(&remote, 0, sizeof(remote));
- remote.sin_family = AF_INET;
- remote.sin_addr = addr_in.sin_addr;
- remote.sin_port = htons(1234);
-
- socklen_t locallen = sizeof(local);
- if (connect(sock, (const struct sockaddr*)&remote, sizeof(remote)) == -1)
- goto ERR;
- if (getsockname(sock, (struct sockaddr*) &local, &locallen) == -1)
- goto ERR;
-
- local.sin_port = htons(1234);
- localAddr = addressCreateFromInet(&local);
-
- close(sock);
- }
- /* As this is a receive pair, we swap src and dst */
- return addressPair_Create(localAddr, packetSrcAddr);
-
-ERR:
- perror("Socket error");
- return NULL;
-}
-
-/* Main hook handler */
-
-/**
- * \brief Handle incoming messages
- * \param [in] forwarder - Reference to the Forwarder instance
- * \param [in] packet - Packet buffer
- * \param [in] conn_id - A hint on the connection ID on which the packet
- * was received
- * \return Flag indicating whether the packet matched a hook and was
- * (successfully or not) processed.
- */
-static inline bool messageHandler_handleHooks(Forwarder * forwarder,
- const uint8_t * packet, ListenerOps * listener, int fd, AddressPair * pair)
-{
- bool is_matched = false;
-
- /* BEGIN Match */
-
-#ifdef WITH_MAPME
- bool is_mapme = mapme_isMapMe(packet);
- is_matched |= is_mapme;
-#endif /* WITH_MAPME */
-
- /* ... */
-
- /* END Match */
-
- if (!is_matched)
- return false;
-
- /*
- * Find existing connection or create a new one (we assume all processing
- * requires a valid connection.
- */
-
- if (!pair) {
- /* The hICN listener does not provide any address pair while UDP does */
- const AddressPair * pair = _createRecvAddressPairFromPacket(packet);
- if (!pair)
- return false;
- }
-
- /* Find connection and eventually create it */
- const Connection * conn = connectionTable_FindByAddressPair(
- forwarder_GetConnectionTable(forwarder), pair);
- unsigned conn_id;
- if (conn == NULL) {
- conn_id = listener->createConnection(listener, fd, pair);
- } else {
- conn_id = connection_GetConnectionId(conn);
- }
-
- /* BEGIN Process */
-
-#ifdef WITH_MAPME
- if (mapme_isMapMe(packet))
- forwarder_ProcessMapMe(forwarder, packet, conn_id);
-#endif /* WITH_MAPME */
-
- /* ... */
-
- /* END Process */
- parcMemory_Deallocate((void **)&packet);
- return true;
-}
-
-static inline bool messageHandler_IsTCP(const uint8_t *message) {
- if (messageHandler_NextHeaderType(message) != IPPROTO_TCP) return false;
- return true;
-}
-
-static inline bool messageHandler_IsInterest(const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return false;
-
- bool flag;
- hicn_packet_test_ece(HF_INET6_TCP, (hicn_header_t *)message,
- &flag); // ECE flag is set to 0 in interest packets
- if (flag == false) return true;
- return false;
-}
-
-static inline bool messageHandler_IsData(const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return false;
-
- bool flag;
- hicn_packet_test_ece(HF_INET6_TCP, (hicn_header_t *)message,
- &flag); // ECE flag is set to 1 in data packets
- if (flag == true) return true;
- return false;
-}
-
-static inline bool messageHandler_IsWldrNotification(const uint8_t *message) {
- // this function returns true only if the packet is an ICMP packet in Wldr
- // form. type must be equal to ICMP_WLDR_TYPE and code equal to ICMP_WLDR_CODE
- uint8_t next_header = messageHandler_NextHeaderType(message);
-
- const uint8_t *icmp_ptr;
- if (next_header == IPPROTO_ICMP) {
- icmp_ptr = message + IPV4_HDRLEN;
- } else if (next_header == IPPROTO_ICMPV6) {
- icmp_ptr = message + IPV6_HDRLEN;
- } else {
- return false;
- }
-
- uint8_t type = ((_icmp_header_t *)icmp_ptr)->type;
- uint8_t code = ((_icmp_header_t *)icmp_ptr)->code;
- if (type == ICMP_WLDR_TYPE && code == ICMP_WLDR_CODE) {
- return true;
- }
-
- return false;
-}
-
-static inline bool messageHandler_IsLoadBalancerProbe(const uint8_t *message) {
- uint8_t next_header = messageHandler_NextHeaderType(message);
-
- const uint8_t *icmp_ptr;
- if (next_header == IPPROTO_ICMP) {
- icmp_ptr = message + IPV4_HDRLEN;
- } else if (next_header == IPPROTO_ICMPV6) {
- icmp_ptr = message + IPV6_HDRLEN;
- } else {
- return false;
- }
-
- uint8_t type = ((_icmp_header_t *)icmp_ptr)->type;
- if (type == ICMP_LB_TYPE) {
- return true;
- }
-
- return false;
-}
-
-static inline uint16_t messageHandler_GetTotalPacketLength(
- const uint8_t *message) {
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- return ntohs((uint16_t)HICN_V6_LEN(message)) + IPV6_HDRLEN;
- case IPv4_TYPE:
- return ntohs((uint16_t)HICN_V4_LEN(message));
- default:
- return 0;
- }
-}
-
-static inline uint32_t messageHandler_GetSegment(const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return 0;
-
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- return ntohl((uint32_t)H6T(message).seq);
- case IPv4_TYPE:
- return ntohl((uint32_t)H4T(message).seq);
- default:
- return 0;
- }
-}
-
-static inline uint16_t messageHandler_GetExpectedWldrLabel(
- const uint8_t *message) {
- const uint8_t *icmp_ptr;
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- icmp_ptr = message + IPV6_HDRLEN;
- break;
- case IPv4_TYPE:
- icmp_ptr = message + IPV4_HDRLEN;
- break;
- default:
- return 0;
- }
-
- return ntohs(((_icmp_wldr_header_t *)icmp_ptr)->expected_lbl);
-}
-
-static inline uint16_t messageHandler_GetWldrLastReceived(
- const uint8_t *message) {
- const uint8_t *icmp_ptr;
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- icmp_ptr = message + IPV6_HDRLEN;
- break;
- case IPv4_TYPE:
- icmp_ptr = message + IPV4_HDRLEN;
- break;
- default:
- return 0;
- }
-
- return ntohs(((_icmp_wldr_header_t *)icmp_ptr)->received_lbl);
-}
-
-static inline uint16_t messageHandler_GetWldrLabel(const uint8_t *message) {
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- return ntohs((uint16_t)H6T(message).window);
- case IPv4_TYPE:
- return ntohs((uint16_t)H4T(message).window);
- default:
- return 0;
- }
-}
-
-static inline void messageHandler_SetWldrLabel(uint8_t *message,
- uint16_t label) {
- uint16_t old_val = messageHandler_GetWldrLabel(message);
-
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- H6T(message).window = htons(label);
- break;
- case IPv4_TYPE:
- H4T(message).window = htons(label);
- break;
- default:
- break;
- }
-
- messageHandler_UpdateTCPCheckSum(message, &old_val, &label, 1);
-}
-
-static inline void messageHandler_ResetWldrLabel(uint8_t *message) {
- messageHandler_SetWldrLabel(message, 0);
-}
-
-static inline bool messageHandler_HasWldr(const uint8_t *message) {
- if (messageHandler_IsTCP(message)) {
- uint16_t lbl = messageHandler_GetWldrLabel(message);
- if (lbl != 0) {
- return true;
- }
- }
- return false;
-}
-
-static inline uint32_t messageHandler_GetPathLabel(const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return 0;
-
- uint32_t path_label;
- int res = hicn_data_get_path_label((hicn_header_t *)message, &path_label);
- if (res < 0) return 0;
- return path_label;
-}
-
-static inline void messageHandler_SetPathLabel(uint8_t *message,
- uint32_t old_path_label,
- uint32_t new_path_label) {
- if (!messageHandler_IsTCP(message)) return;
-
- hicn_data_set_path_label((hicn_header_t *)message, new_path_label);
-
- messageHandler_UpdateTCPCheckSum(message, (uint16_t *)&old_path_label,
- (uint16_t *)&new_path_label, 2);
-}
-
-static inline void messageHandler_UpdatePathLabel(uint8_t *message,
- uint8_t outFace) {
- if (!messageHandler_IsTCP(message)) return;
-
- uint32_t pl_old_32bit = messageHandler_GetPathLabel(message);
- uint8_t pl_old_8bit = (uint8_t)(pl_old_32bit >> 24UL);
- uint32_t pl_new_32bit =
- (uint32_t)((((pl_old_8bit << 1) | (pl_old_8bit >> 7)) ^ outFace) << 24UL);
-
- messageHandler_SetPathLabel(message, pl_old_32bit, pl_new_32bit);
-}
-
-static inline void messageHandler_ResetPathLabel(uint8_t *message) {
- messageHandler_SetPathLabel(message, messageHandler_GetPathLabel(message), 0);
-}
-
-static inline uint16_t messageHandler_GetInterestLifetime(
- const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return 0;
-
- hicn_lifetime_t lifetime;
- int res = hicn_interest_get_lifetime((hicn_header_t *)message, &lifetime);
- if (res < 0) return 0;
- return lifetime;
-}
-
-static inline bool messageHandler_HasInterestLifetime(const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return false;
-
- if (messageHandler_GetInterestLifetime(message) == 0) return false;
- return true;
-}
-
-static inline uint32_t messageHandler_GetContentExpiryTime(
- const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return 0;
-
- uint32_t expirationTime;
- int res =
- hicn_data_get_expiry_time((hicn_header_t *)message, &expirationTime);
- if (res < 0) return 0;
- return expirationTime;
-}
-
-static inline bool messageHandler_HasContentExpiryTime(const uint8_t *message) {
- if (!messageHandler_IsTCP(message)) return 0;
-
- uint32_t expirationTime;
- int res =
- hicn_data_get_expiry_time((hicn_header_t *)message, &expirationTime);
- if (res < 0) return false;
-
- if (expirationTime == HICN_MAX_LIFETIME) return false;
-
- return true;
-}
-
-static inline void *messageHandler_GetSource(const uint8_t *message) {
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- return &H6(message).saddr;
- break;
- case IPv4_TYPE:
- return &H4(message).saddr;
- break;
- default:
- return NULL;
- }
-}
-
-static inline void *messageHandler_GetDestination(const uint8_t *message) {
- switch (messageHandler_GetIPPacketType(message)) {
- case IPv6_TYPE:
- return &H6(message).daddr;
- break;
- case IPv4_TYPE:
- return &H4(message).daddr;
- break;
- default:
- return NULL;
- }
-}
-
-static inline void messageHandler_SetSource_IPv6(uint8_t *message,
- struct in6_addr *address) {
- if (messageHandler_IsTCP(message)) {
- uint16_t *old_src = (uint16_t *)messageHandler_GetSource(message);
- messageHandler_UpdateTCPCheckSum(message, old_src, (uint16_t *)address, 8);
- }
- H6(message).saddr.as_in6addr = *address;
-}
-
-static inline void messageHandler_SetDestination_IPv6(
- uint8_t *message, struct in6_addr *address) {
- if (messageHandler_IsTCP(message)) {
- uint16_t *old_dst = (uint16_t *)messageHandler_GetDestination(message);
- messageHandler_UpdateTCPCheckSum(message, old_dst, (uint16_t *)address, 8);
- }
- H6(message).daddr.as_in6addr = *address;
-}
-
-static inline void messageHandler_SetSource_IPv4(uint8_t *message,
- uint32_t *address) {
- // update tcp checksum
- uint16_t *old_src = (uint16_t *)messageHandler_GetSource(message);
- if (messageHandler_IsTCP(message)) {
- messageHandler_UpdateTCPCheckSum(message, old_src, (uint16_t *)address, 2);
- }
- // update IPv4 cheksum
- // the IPv4 checksum is not part of the psudo header for TCP checksum
- // calculation we can update them separetelly
- messageHandler_UpdateIPv4CheckSum(message, old_src, (uint16_t *)address, 2);
-
- H4(message).saddr.as_u32 = *address;
-}
-
-static inline void messageHandler_SetDestination_IPv4(uint8_t *message,
- uint32_t *address) {
- uint16_t *old_dst = (uint16_t *)messageHandler_GetDestination(message);
- if (messageHandler_IsTCP(message)) {
- messageHandler_UpdateTCPCheckSum(message, old_dst, (uint16_t *)address, 2);
- }
- messageHandler_UpdateIPv4CheckSum(message, old_dst, (uint16_t *)address, 2);
- H4(message).daddr.as_u32 = *address;
-}
-
-static inline void messageHandler_SetWldrNotification(uint8_t *notification,
- uint8_t *original,
- uint16_t expected,
- uint16_t received) {
- hicn_header_t *h = (hicn_header_t *)notification;
- switch (messageHandler_GetIPPacketType(original)) {
- case IPv6_TYPE: {
- *h = (hicn_header_t){.v6 = {
- .ip =
- {
- .version_class_flow = htonl(
- (IPV6_DEFAULT_VERSION << 28) |
- (IPV6_DEFAULT_TRAFFIC_CLASS << 20) |
- (IPV6_DEFAULT_FLOW_LABEL & 0xfffff)),
- .len = htons(ICMP_HDRLEN),
- .nxt = IPPROTO_ICMPV6,
- .hlim = 5,
- },
- .wldr =
- {
- .type = ICMP_WLDR_TYPE,
- .code = ICMP_WLDR_CODE,
- .expected_lbl = htons(expected),
- .received_lbl = htons(received),
- },
- }};
- messageHandler_SetSource_IPv6(
- notification,
- (struct in6_addr *)messageHandler_GetDestination(original));
- messageHandler_SetDestination_IPv6(
- notification, (struct in6_addr *)messageHandler_GetSource(original));
- break;
- }
- case IPv4_TYPE: {
- break;
- }
- default:
- break;
- }
-}
-
-static inline uint8_t * messageHandler_CreateProbePacket(hicn_format_t format,
- uint32_t probe_lifetime){
- size_t header_length;
- hicn_packet_get_header_length_from_format(format, &header_length);
-
- uint8_t *pkt = parcMemory_AllocateAndClear(header_length);
-
- hicn_packet_init_header(format, (hicn_header_t *) pkt);
-
- hicn_packet_set_dst_port(format, (hicn_header_t *) pkt, BFD_PORT);
- hicn_interest_set_lifetime ((hicn_header_t *) pkt, probe_lifetime);
-
- return pkt;
-}
-
-static inline void messageHandler_CreateProbeReply(uint8_t * probe,
- hicn_format_t format){
-
- hicn_name_t probe_name;
- hicn_interest_get_name (format,
- (const hicn_header_t *) probe, &probe_name);
- ip_address_t probe_locator;
- hicn_interest_get_locator (format,
- (const hicn_header_t *) probe, &probe_locator);
-
- uint16_t src_prt;
- uint16_t dst_prt;
- hicn_packet_get_src_port(format, (const hicn_header_t *) probe, &src_prt);
- hicn_packet_get_dst_port(format, (const hicn_header_t *) probe, &dst_prt);
- hicn_packet_set_src_port(format, (hicn_header_t *) probe, dst_prt);
- hicn_packet_set_dst_port(format, (hicn_header_t *) probe, src_prt);
-
- hicn_data_set_name (format, (hicn_header_t *) probe, &probe_name);
- hicn_data_set_locator (format, (hicn_header_t *) probe, &probe_locator);
- hicn_data_set_expiry_time ((hicn_header_t *) probe, 0);
-}
-
-static inline hicn_name_t * messageHandler_CreateProbeName(const ip_prefix_t *address){
- hicn_name_t * name = parcMemory_AllocateAndClear(sizeof(hicn_name_t));
- hicn_name_create_from_ip_prefix(address, 0, name);
- return name;
-}
-
-static inline void messageHandler_SetProbeName(uint8_t * probe, hicn_format_t format,
- hicn_name_t * name, uint32_t seq){
- hicn_name_set_seq_number (name, seq);
- hicn_interest_set_name(format, (hicn_header_t *) probe, name);
-}
-
-static inline bool messageHandler_IsAProbe(const uint8_t *packet){
- uint16_t src_prt;
- uint16_t dst_prt;
- hicn_packet_get_src_port (HF_INET6_TCP, (const hicn_header_t *) packet, &src_prt);
- hicn_packet_get_dst_port (HF_INET6_TCP, (const hicn_header_t *) packet, &dst_prt);
-
- if(dst_prt == BFD_PORT){
- //interest probe
- return true;
- }
-
- if(src_prt == BFD_PORT){
- //data (could be a probe)
- uint32_t expiry_time;
- hicn_data_get_expiry_time ((const hicn_header_t *) packet, &expiry_time);
- if(expiry_time == 0){
- //this is a probe
- return true;
- }
- }
-
- return false;
-}
-
-#endif // Metis_metis_MessageHandler
diff --git a/hicn-light/src/hicn/core/messagePacketType.h b/hicn-light/src/hicn/core/messagePacketType.h
deleted file mode 100644
index dfbb12342..000000000
--- a/hicn-light/src/hicn/core/messagePacketType.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.
- */
-
-/**
- * @file message_packet_type_h
- * @brief Defines the packet type for a HICN message
- *
- */
-
-#ifndef message_packet_type_h
-#define message_packet_type_h
-
-typedef enum message_type {
- MessagePacketType_Unknown,
- MessagePacketType_Interest,
- MessagePacketType_ContentObject,
- MessagePacketType_WldrNotification
-} MessagePacketType;
-
-#endif // message_packet_type_h
diff --git a/hicn-light/src/hicn/core/msgbuf.c b/hicn-light/src/hicn/core/msgbuf.c
new file mode 100644
index 000000000..c58f7a7dc
--- /dev/null
+++ b/hicn-light/src/hicn/core/msgbuf.c
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file msgbuf.c
+ * \brief Implementation hICN message buffer
+ */
+
+#include "msgbuf.h"
+#include "../strategies/probe_generator.h"
+
+int msgbuf_initialize(msgbuf_t *msgbuf) {
+ /*
+ * We define the format and the storage area of the packet buffer we
+ * manipulate
+ */
+ hicn_packet_buffer_t *pkbuf = msgbuf_get_pkbuf(msgbuf);
+ hicn_packet_set_buffer(pkbuf, msgbuf->packet, MTU, 0);
+ hicn_packet_init_header(pkbuf, 0);
+ return 0;
+}
+
+int msgbuf_initialize_from_packet(msgbuf_t *msgbuf) {
+ hicn_packet_set_buffer(msgbuf_get_pkbuf(msgbuf), msgbuf->packet, MTU,
+ msgbuf_get_len(msgbuf));
+ return 0;
+}
+
+bool msgbuf_is_command(const msgbuf_t *msgbuf) {
+ return (*msgbuf->packet == REQUEST_LIGHT);
+}
+
+bool msgbuf_is_probe(const msgbuf_t *msgbuf) {
+ hicn_name_t name;
+ hicn_name_suffix_t suffix;
+
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA);
+
+ const hicn_packet_buffer_t *pkbuf = msgbuf_get_pkbuf(msgbuf);
+ hicn_data_get_name(pkbuf, &name);
+ suffix = hicn_name_get_suffix(&name);
+ return (suffix >= MIN_PROBE_SUFFIX && suffix <= MAX_PROBE_SUFFIX);
+}
diff --git a/hicn-light/src/hicn/core/msgbuf.h b/hicn-light/src/hicn/core/msgbuf.h
new file mode 100644
index 000000000..7a35929f4
--- /dev/null
+++ b/hicn-light/src/hicn/core/msgbuf.h
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+/**
+ * \file msgbuf.h
+ * \brief hICN message buffer
+ */
+
+#ifndef HICNLIGHT_MSGBUF
+#define HICNLIGHT_MSGBUF
+
+#include <hicn/name.h>
+#include "ticks.h"
+#include <hicn/hicn.h>
+#include <hicn/ctrl/hicn-light.h>
+
+#define MTU 1500
+#define INVALID_MSGBUF_ID ~0ul
+
+#define msgbuf_id_is_valid(msgbuf_id) \
+ ((unsigned long)msgbuf_id != INVALID_MSGBUF_ID)
+
+typedef struct {
+ hicn_packet_buffer_t pkbuf;
+ unsigned connection_id; // ingress
+ Ticks recv_ts; // timestamp
+ unsigned refs; // refcount
+ unsigned path_label; // original path label of the received message. used
+ // as a base for the path label computation when the
+ // same data packet needs to be forwarded on multiple
+ // face.
+
+ // XXX Cache storage
+ union {
+ /* Interest or data packet */
+ struct {
+ hicn_name_t name;
+ u32 name_hash; // XXX should be always populate when name is assigned
+ } id;
+ /* Command packet */
+ struct {
+ command_type_t type;
+ } command;
+ };
+ uint8_t packet[MTU];
+} msgbuf_t;
+
+int msgbuf_initialize(msgbuf_t *msgbuf);
+int msgbuf_initialize_from_packet(msgbuf_t *msgbuf);
+
+#define msgbuf_get_pkbuf(M) (&(M)->pkbuf)
+
+static inline hicn_packet_type_t msgbuf_get_type(const msgbuf_t *msgbuf) {
+ return hicn_packet_get_type(msgbuf_get_pkbuf(msgbuf));
+}
+
+static inline void msgbuf_set_type(msgbuf_t *msgbuf, hicn_packet_type_t type) {
+ hicn_packet_set_type(msgbuf_get_pkbuf(msgbuf), type);
+}
+
+static inline const hicn_name_t *msgbuf_get_name(const msgbuf_t *msgbuf) {
+ hicn_packet_type_t type = msgbuf_get_type(msgbuf);
+ assert(type == HICN_PACKET_TYPE_INTEREST || type == HICN_PACKET_TYPE_DATA);
+ (void)type;
+
+ return &msgbuf->id.name;
+}
+
+#define msgbuf_get_connection_id(M) ((M)->connection_id)
+#define msgbuf_set_connection_id(M, ID) (M)->connection_id = (ID)
+#define msgbuf_get_packet(M) ((M)->packet)
+#define msgbuf_get_command_type(M) ((M)->command.type)
+#if WITH_WLDR
+#define msgbuf_has_wldr(M) (messageHandler_HasWldr((M)->packet))
+#endif
+
+static inline void msgbuf_set_name(msgbuf_t *msgbuf, const hicn_name_t *name) {
+ msgbuf->id.name = *name;
+}
+
+static inline size_t msgbuf_get_len(const msgbuf_t *msgbuf) {
+ return hicn_packet_get_len(msgbuf_get_pkbuf(msgbuf));
+}
+
+static inline void msgbuf_set_len(msgbuf_t *msgbuf, size_t len) {
+ int rc = hicn_packet_set_len(msgbuf_get_pkbuf(msgbuf), len);
+ assert(rc == HICN_LIB_ERROR_NONE); // XXX
+ _unused(rc);
+}
+
+static inline u32 msgbuf_get_name_hash(const msgbuf_t *msgbuf) {
+ hicn_packet_type_t type = msgbuf_get_type(msgbuf);
+ assert(type == HICN_PACKET_TYPE_INTEREST || type == HICN_PACKET_TYPE_DATA);
+ _unused(type);
+ return msgbuf->id.name_hash;
+}
+
+// Lifetimes/expiry times in milliseconds
+static inline u32 msgbuf_get_interest_lifetime(const msgbuf_t *msgbuf) {
+ u32 lifetime;
+ int rc = hicn_interest_get_lifetime(msgbuf_get_pkbuf(msgbuf), &lifetime);
+ if (rc != HICN_LIB_ERROR_NONE) return 0;
+ return lifetime;
+}
+
+//#define msgbuf_get_lifetime(M)
+// (NSEC_TO_TICKS(messageHandler_GetInterestLifetime((M)->packet) *
+// 1000000ULL))
+#define msgbuf_get_lifetime msgbuf_get_interest_lifetime
+
+static inline bool msgbuf_set_interest_lifetime(msgbuf_t *msgbuf,
+ u32 lifetime) {
+ int rc = hicn_interest_set_lifetime(msgbuf_get_pkbuf(msgbuf), lifetime);
+ return (rc == HICN_LIB_ERROR_NONE);
+}
+
+static inline u32 msgbuf_get_data_expiry_time(const msgbuf_t *msgbuf) {
+ u32 lifetime;
+ int rc = hicn_data_get_expiry_time(msgbuf_get_pkbuf(msgbuf), &lifetime);
+ if (rc != HICN_LIB_ERROR_NONE) return 0;
+ return lifetime;
+}
+
+static inline bool msgbuf_set_data_expiry_time(msgbuf_t *msgbuf, u32 lifetime) {
+ int rc = hicn_data_set_expiry_time(msgbuf_get_pkbuf(msgbuf), lifetime);
+ return (rc == HICN_LIB_ERROR_NONE);
+}
+
+/* Path label */
+
+static inline void msgbuf_init_pathlabel(msgbuf_t *msgbuf) {
+ hicn_path_label_t pl;
+ int rc = hicn_data_get_path_label(msgbuf_get_pkbuf(msgbuf), &pl);
+ assert(rc == HICN_LIB_ERROR_NONE);
+ _unused(rc);
+ msgbuf->path_label = pl;
+}
+
+static inline int msgbuf_get_path_label(const msgbuf_t *msgbuf,
+ hicn_path_label_t *pl) {
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA);
+ return hicn_data_get_path_label(msgbuf_get_pkbuf(msgbuf), pl);
+}
+
+static inline int msgbuf_set_path_label(msgbuf_t *msgbuf,
+ hicn_path_label_t pl) {
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA);
+ return hicn_data_set_path_label(msgbuf_get_pkbuf(msgbuf), pl);
+}
+
+static inline int msgbuf_update_pathlabel(msgbuf_t *msgbuf,
+ hicn_faceid_t outface) {
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA);
+
+ hicn_path_label_t pl, newpl;
+ if (msgbuf_get_path_label(msgbuf, &pl) < 0) return -1;
+
+ update_path_label(pl, outface, &newpl);
+
+ return msgbuf_set_path_label(msgbuf, newpl);
+}
+
+static inline void msgbuf_reset_pathlabel(msgbuf_t *msgbuf) {
+ msgbuf->path_label = 0;
+ hicn_data_set_path_label(msgbuf_get_pkbuf(msgbuf), 0);
+ // ERROR ?
+}
+
+static inline void msgbuf_modify_suffix(msgbuf_t *msgbuf, uint32_t new_suffix) {
+ hicn_name_t name;
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_INTEREST);
+ hicn_interest_get_name(msgbuf_get_pkbuf(msgbuf), &name);
+ hicn_name_set_suffix(&name, new_suffix);
+ hicn_interest_set_name(msgbuf_get_pkbuf(msgbuf), &name);
+}
+
+bool msgbuf_is_command(const msgbuf_t *msgbuf);
+bool msgbuf_is_probe(const msgbuf_t *msgbuf);
+
+/* WLDR */
+
+#if 0
+#define msgbuf_reset_wldr_label(M) (messageHandler_ResetWldrLabel((M)->packet))
+#define msgbuf_get_wldr_label(M) (messageHandler_GetWldrLabel((M)->packet))
+#define msgbuf_get_wldr_expected_label(M) \
+ (messageHandler_GetWldrExpectedLabel((M)->packet))
+#define msgbuf_get_wldr_last_received(M) \
+ (messageHandler_GetWldrLastReceived((M)->packet))
+#define msgbuf_set_wldr_label(M, label) \
+ (messageHandler_GetWldrLabel((M)->packet, label))
+#endif
+
+#endif /* HICNLIGHT_MSGBUF */
diff --git a/hicn-light/src/hicn/core/msgbuf_pool.c b/hicn-light/src/hicn/core/msgbuf_pool.c
new file mode 100644
index 000000000..892bd59a1
--- /dev/null
+++ b/hicn-light/src/hicn/core/msgbuf_pool.c
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * @file msgbuf_pool.c
+ * @brief Implementation of hICN packet pool.
+ */
+
+#include <hicn/util/pool.h>
+#include <hicn/util/log.h>
+#include "msgbuf_pool.h"
+
+msgbuf_pool_t *_msgbuf_pool_create(size_t init_size, size_t max_size) {
+ msgbuf_pool_t *msgbuf_pool = malloc(sizeof(msgbuf_pool_t));
+
+ if (init_size == 0) init_size = PACKET_POOL_DEFAULT_INIT_SIZE;
+
+ pool_init(msgbuf_pool->buffers, init_size, 0);
+
+ return msgbuf_pool;
+}
+
+void msgbuf_pool_free(msgbuf_pool_t *msgbuf_pool) {
+ pool_free(msgbuf_pool->buffers);
+ free(msgbuf_pool);
+}
+
+off_t msgbuf_pool_get(msgbuf_pool_t *msgbuf_pool, msgbuf_t **msgbuf) {
+ off_t id = pool_get(msgbuf_pool->buffers, *msgbuf);
+ (*msgbuf)->refs = 0;
+ return id;
+}
+
+void msgbuf_pool_put(msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf) {
+ pool_put(msgbuf_pool->buffers, msgbuf);
+}
+
+int msgbuf_pool_getn(msgbuf_pool_t *msgbuf_pool, msgbuf_t **msgbuf, size_t n) {
+ // CAVEAT: Resize at the beginning otherwise the resize can be
+ // triggered by an intermediate msgbuf_pool_put, making the
+ // buffers previously retrieved invalid
+ uint64_t remaining_pool_space =
+ pool_get_free_indices_size(msgbuf_pool->buffers);
+ while (remaining_pool_space < n) {
+ _pool_resize((void **)&(msgbuf_pool->buffers), sizeof(msgbuf_t));
+
+ remaining_pool_space = pool_get_free_indices_size(msgbuf_pool->buffers);
+ }
+
+ for (unsigned i = 0; i < n; i++) {
+ // If not able to get the msgbuf
+ if (msgbuf_pool_get(msgbuf_pool, &msgbuf[i]) < 0) {
+ // Release all the msgbufs retrieved so far
+ for (unsigned j = 0; j < i; j++) {
+ msgbuf_pool_put(msgbuf_pool, msgbuf[j]);
+ }
+ return -1;
+ }
+ }
+ return 0;
+}
+
+off_t msgbuf_pool_get_id(msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf) {
+ return msgbuf - msgbuf_pool->buffers;
+}
+
+msgbuf_t *msgbuf_pool_at(const msgbuf_pool_t *msgbuf_pool, off_t id) {
+ assert(msgbuf_id_is_valid(id));
+ return msgbuf_pool->buffers + id;
+}
+
+void msgbuf_pool_acquire(msgbuf_t *msgbuf) { msgbuf->refs++; };
+
+void msgbuf_pool_release(msgbuf_pool_t *msgbuf_pool, msgbuf_t **msgbuf_ptr) {
+ msgbuf_t *msgbuf = *msgbuf_ptr;
+ assert(msgbuf->refs > 0);
+ msgbuf->refs--;
+
+ if (msgbuf->refs == 0) {
+ WITH_TRACE({
+ off_t msgbuf_id = msgbuf_pool_get_id(msgbuf_pool, msgbuf);
+ if (msgbuf_get_type(msgbuf) != HICN_PACKET_TYPE_INTEREST &&
+ msgbuf_get_type(msgbuf) != HICN_PACKET_TYPE_DATA) {
+ TRACE("Msgbuf %d (%p) - put to msgbuf pool", msgbuf_id, msgbuf);
+ } else {
+ char buf[MAXSZ_HICN_NAME];
+ int rc =
+ hicn_name_snprintf(buf, MAXSZ_HICN_NAME, msgbuf_get_name(msgbuf));
+ if (rc < 0 || rc >= MAXSZ_HICN_NAME)
+ snprintf(buf, MAXSZ_HICN_NAME, "%s", "(error)");
+ const char *msgbuf_type_str =
+ msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_INTEREST ? "interest"
+ : "data";
+ TRACE("Msgbuf %d (%p) - %s (%s) put to msgbuf pool", msgbuf_id, msgbuf,
+ buf, msgbuf_type_str);
+ }
+ })
+
+ msgbuf_pool_put(msgbuf_pool, msgbuf);
+ *msgbuf_ptr = NULL;
+ }
+};
+
+off_t msgbuf_pool_clone(msgbuf_pool_t *msgbuf_pool, msgbuf_t **new_msgbuf,
+ off_t orginal_msg_id) {
+ msgbuf_t *original_msgbuf = msgbuf_pool_at(msgbuf_pool, orginal_msg_id);
+ off_t offset = pool_get(msgbuf_pool->buffers, *new_msgbuf);
+ memcpy(*new_msgbuf, original_msgbuf, sizeof(msgbuf_t));
+ (*new_msgbuf)->refs = 0;
+ return offset;
+}
diff --git a/hicn-light/src/hicn/core/msgbuf_pool.h b/hicn-light/src/hicn/core/msgbuf_pool.h
new file mode 100644
index 000000000..b8a15fd84
--- /dev/null
+++ b/hicn-light/src/hicn/core/msgbuf_pool.h
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file msgbuf_pool.h
+ * @brief hICN msgbuf pool.
+ *
+ * The msgbuf pool is used to store packet payloads while the packets are in
+ * transit, as well as holding them into the packet cache (PIT, CSS), WLDR,
+ * mapme, etc.
+ *
+ * Control packets might receive a special treatment in that they are eventually
+ * transformed into a ack/nack, but this should not affect any part of this
+ * design.
+ *
+ * Do we need a reference count, or simply a lock ?
+ * What about weak references ?
+ * We need to be sure that a pool element is never referenced ever again after
+ * it is deleted from the pool as its ID might be reaffected.
+ *
+ * It might even be better to store references to msgbuf's as they might hold
+ * additional information of interest about the packet... a bit like a skbuff in
+ * linux. Is this relevant for the packet cache ?
+ */
+
+#ifndef HICNLIGHT_MSGBUF_POOL_H
+#define HICNLIGHT_MSGBUF_POOL_H
+
+#include "msgbuf.h"
+
+#define MTU 1500
+#define PACKET_POOL_DEFAULT_INIT_SIZE 1024
+
+typedef struct {
+ msgbuf_t *buffers;
+} msgbuf_pool_t;
+
+/**
+ * @brief Allocate and initialize a msgbuf pool structure (helper).
+ *
+ * @param[in] init_size Number of buffers that can be stored in msgbuf pool.
+ * @param[in] max_size Maximum size.
+ * @return msgbuf_pool_t* Pointer to the msgbuf pool created.
+ *
+ * @note
+ * - 0 for init size means a default value (of 1024)
+ * - 0 for max_size means no limit
+ */
+msgbuf_pool_t *_msgbuf_pool_create(size_t init_size, size_t max_size);
+
+/**
+ * @brief Allocate and initialize a msgbuf pool data structure.
+ *
+ * @return msgbuf_pool_t* Pointer to the msgbuf pool created.
+ */
+#define msgbuf_pool_create() _msgbuf_pool_create(0, 0)
+
+/**
+ * @brief Free a msgbuf pool data structure.
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to free.
+ */
+void msgbuf_pool_free(msgbuf_pool_t *msgbuf_pool);
+
+/**
+ * @brief Get a free msgbuf from the msgbuf pool data structure.
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use.
+ * @param[in, out] msgbuf Empty msgbuf that will be used to return the
+ * allocated one from the msgbuf pool.
+ * @return off_t ID of the msgbuf requested.
+ */
+off_t msgbuf_pool_get(msgbuf_pool_t *msgbuf_pool, msgbuf_t **msgbuf);
+
+/**
+ * @brief Release a msgbuf previously obtained, making it available to the
+ * msgbuf pool.
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use.
+ * @param[in] msgbuf Pointer to the msgbuf to release.
+ */
+void msgbuf_pool_put(msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf);
+
+/**
+ * @brief Get multiple free msgbufs from the msgbuf pool data structure.
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use.
+ * @param[in, out] msgbuf Pointer to the first empty msgbuf that will be used to
+ * allocate the msgbufs.
+ * @param[in] n Number of msgbufs requested.
+ * @retval 0 Success.
+ * @retval -1 Error.
+ */
+int msgbuf_pool_getn(msgbuf_pool_t *msgbuf_pool, msgbuf_t **msgbuf, size_t n);
+
+/**
+ * @brief Get the ID corresponding to the msgbuf requested.
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use.
+ * @param[in] msgbuf Pointer to the msgbuf to retrieve the ID for.
+ * @return off_t ID of the msgbuf requested.
+ */
+off_t msgbuf_pool_get_id(msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf);
+
+/**
+ * @brief Get the msgbuf corresponding to the ID requested.
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use.
+ * @param[in] id Index of the msgbuf to retrieve.
+ * @return msgbuf_t* Pointer to the msgbuf corresponding to the ID requested.
+ */
+msgbuf_t *msgbuf_pool_at(const msgbuf_pool_t *msgbuf_pool, off_t id);
+
+/**
+ * @brief Acquire a buffer (by increasing its reference count).
+ *
+ * @param[in] msgbuf Pointer to the msgbuf to acquire
+ */
+void msgbuf_pool_acquire(msgbuf_t *msgbuf);
+
+/**
+ * @brief Release a buffer. The buffer is also put back into the msgbuf
+ * pool if everyone who acquired it has released its possession.
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use
+ * @param[in, out] msgbuf Pointer that holds the pointer to the msgbuf
+ * to release; the double indirection is used to set the msgbuf pointer
+ * to NULL in case it is put into the msgbuf pool.
+ */
+void msgbuf_pool_release(msgbuf_pool_t *msgbuf_pool, msgbuf_t **msgbuf_ptr);
+
+/**
+ * @brief Copy the original msgbuf in new msgbuf taken from the pool. The ref
+ * count on new msgbuf is set to 0
+ *
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use
+ * @param[in,out] new__msgbuf Pointer that holds the replicatate msgbuf
+ * @param[in] original_msgbuf id. use id instead of the pointer becasue the
+ * pointer may becose invalid if the msgbuf_pool requires a resize
+ * @return off_t ID of the msgbuf requested.
+ */
+off_t msgbuf_pool_clone(msgbuf_pool_t *msgbuf_pool, msgbuf_t **new_msgbuf,
+ off_t orginal_msg_id);
+
+#endif /* HICNLIGHT_MSGBUF_POOL_H */
diff --git a/hicn-light/src/hicn/core/name.c b/hicn-light/src/hicn/core/name.c
deleted file mode 100644
index b4a5e8d1b..000000000
--- a/hicn-light/src/hicn/core/name.c
+++ /dev/null
@@ -1,264 +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 <limits.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <parc/algol/parc_BufferComposer.h>
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/core/messageHandler.h>
-#include <hicn/core/name.h>
-
-#include <parc/algol/parc_Hash.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#define IPv6_TYPE 6
-#define IPv4_TYPE 4
-
-// assumption: the IPv6 address is the name, the TCP segment number is the ICN
-// segment
-
-struct name {
- NameBitvector *content_name;
- uint32_t segment;
- uint32_t name_hash;
- // the refcount is shared between all copies
- unsigned *refCountPtr;
-};
-
-// =====================================================
-
-static unsigned _getRefCount(const Name *name) { return *name->refCountPtr; }
-
-static void _incrementRefCount(Name *name) {
- parcAssertTrue(*name->refCountPtr > 0,
- "Illegal State: Trying to increment a 0 refcount!");
- (*name->refCountPtr)++;
-}
-
-static void _decrementRefCount(Name *name) {
- parcAssertTrue(*name->refCountPtr > 0,
- "Illegal State: Trying to decrement a 0 refcount!");
- (*name->refCountPtr)--;
-}
-
-static uint32_t _computeHash(Name *name) {
- parcAssertNotNull(name, "Parameter must be non-null pointer");
-
- uint32_t hash1 = nameBitvector_GetHash32(name->content_name);
- return parcHash32_Data_Cumulative((const uint8_t *)&name->segment, 4, hash1);
-}
-
-// ============================================================================
-
-Name *name_CreateFromPacket(const uint8_t *packet, MessagePacketType type) {
- Name *name = parcMemory_AllocateAndClear(sizeof(Name));
- parcAssertNotNull(name, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Name));
-
- if (messageHandler_GetIPPacketType(packet) == IPv6_TYPE) {
- if (type == MessagePacketType_Interest) {
- name->content_name = nameBitvector_CreateFromIn6Addr(
- (struct in6_addr *)messageHandler_GetDestination(packet), 128);
- } else if (type == MessagePacketType_ContentObject) {
- name->content_name = nameBitvector_CreateFromIn6Addr(
- (struct in6_addr *)messageHandler_GetSource(packet), 128);
- } else {
- parcMemory_Deallocate((void **)&name);
- return NULL;
- }
- } else if (messageHandler_GetIPPacketType(packet) == IPv4_TYPE) {
- if (type == MessagePacketType_Interest) {
- name->content_name = nameBitvector_CreateFromInAddr(
- *((uint32_t *)messageHandler_GetDestination(packet)), 32);
- } else if (type == MessagePacketType_ContentObject) {
- name->content_name = nameBitvector_CreateFromInAddr(
- *((uint32_t *)messageHandler_GetSource(packet)), 32);
- } else {
- parcMemory_Deallocate((void **)&name);
- return NULL;
- }
- } else {
- printf("Error: unknown message type\n");
- parcMemory_Deallocate((void **)&name);
- return NULL;
- }
-
- name->segment = messageHandler_GetSegment(packet);
- name->name_hash = _computeHash(name);
-
- name->refCountPtr = parcMemory_Allocate(sizeof(unsigned));
- parcAssertNotNull(name->refCountPtr, "parcMemory_Allocate(%zu) returned NULL",
- sizeof(unsigned));
- *name->refCountPtr = 1;
- return name;
-}
-
-Name *name_CreateFromAddress(address_type addressType, ip_address_t addr,
- uint8_t len) {
- Name *name = parcMemory_AllocateAndClear(sizeof(Name));
- parcAssertNotNull(name, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Name));
- if (addressType == ADDR_INET) {
- name->content_name = nameBitvector_CreateFromInAddr(addr.v4.as_u32, len);
- } else if (addressType == ADDR_INET6) {
- name->content_name = nameBitvector_CreateFromIn6Addr(&addr.v6.as_in6addr, len);
- } else {
- parcTrapNotImplemented("Unkown packet type");
- }
-
- name->segment = 0;
- name->name_hash = _computeHash(name);
-
- name->refCountPtr = parcMemory_Allocate(sizeof(unsigned));
- parcAssertNotNull(name->refCountPtr, "parcMemory_Allocate(%zu) returned NULL",
- sizeof(unsigned));
- *name->refCountPtr = 1;
-
- return name;
-}
-
-void name_Release(Name **namePtr) {
- parcAssertNotNull(namePtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*namePtr, "Parameter must dereference to non-null pointer");
-
- Name *name = *namePtr;
- _decrementRefCount(name);
- if (_getRefCount(name) == 0) {
- parcMemory_Deallocate((void **)&(name->refCountPtr));
- nameBitvector_Destroy(&(name->content_name));
- }
- parcMemory_Deallocate((void **)&name);
- *namePtr = NULL;
-}
-
-Name *name_Acquire(const Name *original) {
- parcAssertNotNull(original, "Parameter must be non-null");
- Name *copy = parcMemory_AllocateAndClear(sizeof(Name));
- parcAssertNotNull(copy, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Name));
-
- memcpy(copy, original, sizeof(Name));
- _incrementRefCount(copy);
-
- return copy;
-}
-
-Name *name_Copy(const Name *original) {
- parcAssertNotNull(original, "Parameter must be non-null");
- Name *copy = parcMemory_AllocateAndClear(sizeof(Name));
- parcAssertNotNull(copy, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Name));
-
- copy->content_name = nameBitvector_Copy(original->content_name);
- copy->segment = original->segment;
- copy->name_hash = original->name_hash;
-
- copy->refCountPtr = parcMemory_Allocate(sizeof(unsigned));
- parcAssertNotNull(copy->refCountPtr, "parcMemory_Allocate(%zu) returned NULL",
- sizeof(unsigned));
- *copy->refCountPtr = 1;
-
- return copy;
-}
-
-uint32_t name_HashCode(const Name *name) {
- parcAssertNotNull(name, "Parameter must be non-null");
- return name->name_hash;
-}
-
-NameBitvector *name_GetContentName(const Name *name) {
- parcAssertNotNull(name, "Parameter must be non-null");
- return name->content_name;
-}
-
-bool name_Equals(const Name *a, const Name *b) {
- parcAssertNotNull(a, "Parameter a must be non-null");
- parcAssertNotNull(b, "Parameter b must be non-null");
-
- /* BEGIN: Workaround for HICN-400 */
- if ((!a->content_name) || (!b->content_name))
- return false;
- /* END: Workaround for HICN-400 */
-
- if ((nameBitvector_Equals(a->content_name, b->content_name) &&
- a->segment == b->segment))
- return true;
- return false;
-}
-
-int name_Compare(const Name *a, const Name *b) {
- parcAssertNotNull(a, "Parameter a must be non-null");
- parcAssertNotNull(b, "Parameter b must be non-null");
-
- if (a == NULL && b == NULL) {
- return 0;
- }
- if (a == NULL) {
- return -1;
- }
- if (b == NULL) {
- return +1;
- }
-
- int res = nameBitvector_Compare(a->content_name, b->content_name);
-
- if (res != 0) {
- return res;
- } else {
- if (a->segment < b->segment) {
- return -1;
- } else if (a->segment > b->segment) {
- return +1;
- } else {
- return 0;
- }
- }
-}
-
-char *name_ToString(const Name *name) {
- char *output = malloc(128);
-
- Address *packetAddr = nameBitvector_ToAddress(name_GetContentName(name));
-
- char * address_str = addressToString(packetAddr);
- sprintf(output, "name: %s seq: %u", address_str, name->segment);
- parcMemory_Deallocate((void **)&address_str);
-
- addressDestroy(&packetAddr);
-
- return output;
-}
-
-void name_setLen(Name *name, uint8_t len) {
- nameBitvector_setLen(name->content_name, len);
- name->name_hash = _computeHash(name);
-}
-
-#ifdef WITH_POLICY
-uint32_t name_GetSuffix(const Name * name) {
- return name->segment;
-}
-
-uint8_t name_GetLen(const Name * name) {
- return nameBitvector_GetLength(name->content_name);
-}
-#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/core/name.h b/hicn-light/src/hicn/core/name.h
deleted file mode 100644
index db9438150..000000000
--- a/hicn-light/src/hicn/core/name.h
+++ /dev/null
@@ -1,104 +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.
- */
-
-#ifndef name_h
-#define name_h
-
-#include <stdbool.h>
-#include <stdlib.h>
-
-#include <hicn/core/messagePacketType.h>
-#include <hicn/core/nameBitvector.h>
-#include <hicn/utils/address.h>
-
-#include <hicn/utils/commands.h>
-
-struct name;
-typedef struct name Name;
-
-/**
- * Creates a name from packet
- *
- */
-Name *name_CreateFromPacket(const uint8_t *memory, MessagePacketType type);
-
-/**
- * Releases one reference count, and frees memory after last reference
- */
-void name_Release(Name **namePtr);
-
-/**
- * Acquires a reference to the name so that a reference count increments.
- * Notice however that this * function is used only when a new fib entry is
- * created (mostly configuration time) probably here performance are not
- * critical.
- */
-Name *name_Acquire(const Name *original);
-
-/**
- * returns a copy of the name
- */
-Name *name_Copy(const Name *original);
-
-/**
- * A hash value for use in hash tables
- *
- */
-uint32_t name_HashCode(const Name *name);
-
-/**
- * Returns the content name without the segment value
- *
- */
-NameBitvector *name_GetContentName(const Name *name);
-
-/**
- * Determine if two HicnName instances are equal.
- */
-bool name_Equals(const Name *a, const Name *b);
-
-/**
- * Compares two names and returns their ordering
- *
- */
-int name_Compare(const Name *a, const Name *b);
-
-/**
- * return the name in string format (bitvector + segment number)
- *
- */
-char *name_ToString(const Name *name);
-
-/**
- * @function message_setNameLen
- * @abstract Sets a message name length
- * @param [in] message - Interest message
- * @param [in] len - Name length
- */
-void name_setLen(Name *name, uint8_t len);
-
-/**
- * Creates a name from a Address
- *
- */
-Name *name_CreateFromAddress(address_type addressType, ip_address_t addr,
- uint8_t len);
-
-#ifdef WITH_POLICY
-uint32_t name_GetSuffix(const Name * name);
-uint8_t name_GetLen(const Name * name);
-#endif /* WITH_POLICY */
-
-#endif // name_h
diff --git a/hicn-light/src/hicn/core/nameBitvector.c b/hicn-light/src/hicn/core/nameBitvector.c
deleted file mode 100644
index 653560750..000000000
--- a/hicn-light/src/hicn/core/nameBitvector.c
+++ /dev/null
@@ -1,364 +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 <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/core/messageHandler.h>
-#include <hicn/core/nameBitvector.h>
-
-#include <parc/algol/parc_Hash.h>
-
-#include <hicn/utils/commands.h>
-
-#define NAME_LEN 2
-
-const uint64_t BV_SIZE = 64;
-const uint64_t WIDTH = 128;
-const uint64_t ONE = 0x1;
-
-// address b000:0000:0000:0001:c000:0000:0000:0001 is encodend as follow
-// [bits[0] uint64_t ] [bits[1] unit64_t ]
-// ^ ^ ^ ^
-// 63 0 127 64
-// [1000 0000 ... 0000 1101] [1000 0000 ... 0000 0011] //binary
-// 1 b 1 c //hex
-
-struct name_bitvector {
- uint64_t bits[NAME_LEN];
- uint8_t len;
- uint8_t IPversion;
-};
-
-NameBitvector *nameBitvector_CreateFromInAddr(uint32_t addr, uint8_t len) {
- NameBitvector *bitvector = parcMemory_AllocateAndClear(sizeof(NameBitvector));
- parcAssertNotNull(bitvector, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(NameBitvector));
-
- bitvector->bits[0] = 0;
- bitvector->bits[1] = 0;
-
- uint8_t addr_1 = (addr & 0xff000000) >> 24;
- uint8_t addr_2 = (addr & 0x00ff0000) >> 16;
- uint8_t addr_3 = (addr & 0x0000ff00) >> 8;
- uint8_t addr_4 = (addr & 0x000000ff);
-
- bitvector->bits[0] = (bitvector->bits[0] | addr_4) << 8;
- bitvector->bits[0] = (bitvector->bits[0] | addr_3) << 8;
- bitvector->bits[0] = (bitvector->bits[0] | addr_2) << 8;
- bitvector->bits[0] = (bitvector->bits[0] | addr_1);
- bitvector->bits[0] = bitvector->bits[0] << 32;
-
- bitvector->len = len;
-
- bitvector->IPversion = IPv4_TYPE;
-
- return bitvector;
-}
-
-NameBitvector *nameBitvector_CreateFromIn6Addr(struct in6_addr *addr,
- uint8_t len) {
- parcAssertNotNull(addr, "addr cannot be null");
-
- NameBitvector *bitvector = parcMemory_AllocateAndClear(sizeof(NameBitvector));
- parcAssertNotNull(bitvector, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(NameBitvector));
-
- bitvector->bits[0] = 0;
- bitvector->bits[1] = 0;
-
- for (int i = 0; i < 8; ++i) {
- bitvector->bits[0] = (bitvector->bits[0] << 8) | addr->s6_addr[i];
- }
-
- for (int i = 8; i < 16; ++i) {
- bitvector->bits[1] = (bitvector->bits[1] << 8) | addr->s6_addr[i];
- }
-
- bitvector->len = len;
-
- bitvector->IPversion = IPv6_TYPE;
-
- return bitvector;
-}
-
-NameBitvector *nameBitvector_CreateFromAddress(const Address *prefix,
- uint8_t len) {
- parcAssertNotNull(prefix, "prefix cannot be null");
-
- NameBitvector *bitvector = NULL;
- switch (addressGetType(prefix)) {
- case ADDR_INET: {
- struct sockaddr_in addr;
- addressGetInet(prefix, &addr);
- bitvector = nameBitvector_CreateFromInAddr(addr.sin_addr.s_addr, len);
- break;
- }
- case ADDR_INET6: {
- struct sockaddr_in6 addr;
- addressGetInet6(prefix, &addr);
- bitvector = nameBitvector_CreateFromIn6Addr(&addr.sin6_addr, len);
- break;
- }
- default:
- parcTrapNotImplemented("Unkown packet type");
- break;
- }
-
- return bitvector;
-}
-
-NameBitvector *nameBitvector_Copy(const NameBitvector *original) {
- parcAssertNotNull(original, "original cannot be null");
-
- NameBitvector *copy = parcMemory_AllocateAndClear(sizeof(NameBitvector));
- parcAssertNotNull(copy, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(NameBitvector));
-
- copy->bits[0] = original->bits[0];
- copy->bits[1] = original->bits[1];
- copy->len = original->len;
-
- return copy;
-}
-
-void nameBitvector_Destroy(NameBitvector **bitvectorPtr) {
- parcAssertNotNull(bitvectorPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*bitvectorPtr,
- "Parameter must dereference to non-null pointer");
-
- NameBitvector *bv = *bitvectorPtr;
- parcMemory_Deallocate((void **)&(bv));
- *bitvectorPtr = NULL;
-}
-
-uint8_t nameBitvector_GetLength(const NameBitvector *name) { return name->len; }
-
-uint32_t nameBitvector_GetHash32(const NameBitvector *name) {
- return parcHash32_Data_Cumulative((const uint8_t *)name->bits, 16, 0);
-}
-
-bool nameBitvector_Equals(const NameBitvector *a, const NameBitvector *b) {
- if (a->bits[0] == b->bits[0] && a->bits[1] == b->bits[1] && a->len == b->len)
- return true;
- return false;
-}
-
-int nameBitvector_Compare(const NameBitvector *a, const NameBitvector *b) {
- if (a == NULL && b == NULL) {
- return 0;
- }
- if (a == NULL) {
- return -1;
- }
- if (b == NULL) {
- return +1;
- }
-
- if (a->bits[0] < b->bits[0]) {
- return -1;
- } else if (a->bits[0] > b->bits[0]) {
- return +1;
- } else if (a->bits[1] < b->bits[1]) {
- return -1;
- } else if (a->bits[1] > b->bits[1]) {
- return +1;
- } else if (a->len < b->len) {
- return -1;
- } else if (a->len > b->len) {
- return +1;
- } else {
- return 0;
- }
-}
-
-int nameBitvector_testBit(const NameBitvector *name, uint8_t pos, bool *bit) {
- if(pos >= name->len || pos > (WIDTH -1))
- return -1;
-
- *bit = (name->bits[pos / BV_SIZE] & (ONE << ((BV_SIZE - 1) - (pos % BV_SIZE))));
-
- return 0;
-}
-
-uint64_t _diff_bit_log2(uint64_t val) {
- // base 2 log of an uint64_t. This is the same as get the position of
- // the highest bit set (or most significant bit set, MSB)
- uint64_t result = 0;
-
- if (val & 0xFFFFFFFF00000000) {
- val = val >> 32;
- result = result | 32;
- }
- if (val & 0xFFFF0000) {
- val = val >> 16;
- result = result | 16;
- }
- if (val & 0xFF00) {
- val = val >> 8;
- result = result | 8;
- }
- if (val & 0xF0) {
- val = val >> 4;
- result = result | 4;
- }
- if (val & 0xC) {
- val = val >> 2;
- result = result | 2;
- }
- if (val & 0x2) {
- val = val >> 1;
- result = result | 1;
- }
- return result;
-}
-
-uint32_t nameBitvector_lpm(const NameBitvector *a,
- const NameBitvector *b) {
- uint32_t limit;
- uint32_t prefix_len;
- if (a->len < b->len)
- limit = a->len;
- else
- limit = b->len;
-
- uint64_t diff = a->bits[0] ^ b->bits[0];
- if(diff){
- prefix_len = (uint32_t)(BV_SIZE - (_diff_bit_log2(diff) + 1));
- //printf("if 1 diff = %lu plen = %d\n", diff, prefix_len);
- }else{
- prefix_len = (uint32_t)BV_SIZE;
- diff = a->bits[1] ^ b->bits[1];
- if(diff){
- prefix_len += (uint32_t)(BV_SIZE - (_diff_bit_log2(diff) + 1));
- //printf("if 2 diff = %lu plen = %d\n", diff, prefix_len);
- }else{
- prefix_len += (uint32_t)BV_SIZE;
- }
- }
-
- if(prefix_len < limit)
- return prefix_len;
- return limit;
-}
-
-void nameBitvector_clear(NameBitvector *a, uint8_t start_from){
- for(uint8_t pos = start_from; pos < WIDTH; pos++)
- a->bits[pos / BV_SIZE] &= ~(ONE << ((BV_SIZE - 1) - (pos % BV_SIZE)));
-}
-
-int nameBitvector_ToIPAddress(const NameBitvector *name,
- ip_prefix_t *prefix) {
- if (name->IPversion == IPv4_TYPE) {
- struct in_addr *addr = (struct in_addr *)(&prefix->address.v4.buffer);
- prefix->family = AF_INET;
- prefix->len = IPV4_ADDR_LEN_BITS;
-
- uint32_t tmp_addr = name->bits[0] >> 32ULL;
- uint8_t addr_1 = (tmp_addr & 0xff000000) >> 24;
- uint8_t addr_2 = (tmp_addr & 0x00ff0000) >> 16;
- uint8_t addr_3 = (tmp_addr & 0x0000ff00) >> 8;
- uint8_t addr_4 = (tmp_addr & 0x000000ff);
-
- addr->s_addr = 0;
- addr->s_addr = (addr->s_addr | addr_4) << 8;
- addr->s_addr = (addr->s_addr | addr_3) << 8;
- addr->s_addr = (addr->s_addr | addr_2) << 8;
- addr->s_addr = (addr->s_addr | addr_1);
-
- } else {
- struct in6_addr *addr = (struct in6_addr *)(&prefix->address.v6.buffer);
- prefix->family = AF_INET6;
- prefix->len = name->len; // IPV6_ADDR_LEN_BITS;
-
- for (int i = 0; i < 8; i++) {
- addr->s6_addr[i] = (uint8_t)((name->bits[0] >> 8 * (7 - i)) & 0xFF);
- }
-
- int x = 0;
- for (int i = 8; i < 16; ++i) {
- addr->s6_addr[i] = (uint8_t)((name->bits[1] >> 8 * (7 - x)) & 0xFF);
- x++;
- }
- }
- return true;
-}
-
-void nameBitvector_setLen(NameBitvector *name, uint8_t len) { name->len = len; }
-
-Address *nameBitvector_ToAddress(const NameBitvector *name) {
- if (name->IPversion == IPv4_TYPE) {
- struct sockaddr_in addr;
- addr.sin_family = AF_INET;
- addr.sin_port = htons(1234);
-
- uint32_t tmp_addr = name->bits[0] >> 32ULL;
- uint8_t addr_1 = (tmp_addr & 0xff000000) >> 24;
- uint8_t addr_2 = (tmp_addr & 0x00ff0000) >> 16;
- uint8_t addr_3 = (tmp_addr & 0x0000ff00) >> 8;
- uint8_t addr_4 = (tmp_addr & 0x000000ff);
-
- addr.sin_addr.s_addr = 0;
- addr.sin_addr.s_addr = (addr.sin_addr.s_addr | addr_4) << 8;
- addr.sin_addr.s_addr = (addr.sin_addr.s_addr | addr_3) << 8;
- addr.sin_addr.s_addr = (addr.sin_addr.s_addr | addr_2) << 8;
- addr.sin_addr.s_addr = (addr.sin_addr.s_addr | addr_1);
-
- Address *packetAddr = addressCreateFromInet(&addr);
-
- return packetAddr;
-
- } else {
- struct sockaddr_in6 addr;
- addr.sin6_family = AF_INET6;
- addr.sin6_port = htons(1234);
- addr.sin6_scope_id = 0;
- addr.sin6_flowinfo = 0;
-
- for (int i = 0; i < 8; i++) {
- addr.sin6_addr.s6_addr[i] =
- (uint8_t)((name->bits[0] >> 8 * (7 - i)) & 0xFF);
- }
-
- int x = 0;
- for (int i = 8; i < 16; ++i) {
- addr.sin6_addr.s6_addr[i] =
- (uint8_t)((name->bits[1] >> 8 * (7 - x)) & 0xFF);
- x++;
- }
-
- Address *packetAddr = addressCreateFromInet6(&addr);
-
- return packetAddr;
- }
-}
-
-char *nameBitvector_ToString(const NameBitvector *name) {
- char *output = malloc(WIDTH);
-
- Address *packetAddr = nameBitvector_ToAddress(name);
-
- char * str = addressToString(packetAddr);
- sprintf(output, "prefix: %s len: %u", str, name->len);
- parcMemory_Deallocate((void **)&str);
-
- addressDestroy(&packetAddr);
-
- return output;
-}
diff --git a/hicn-light/src/hicn/core/nameBitvector.h b/hicn-light/src/hicn/core/nameBitvector.h
deleted file mode 100644
index 19944778c..000000000
--- a/hicn-light/src/hicn/core/nameBitvector.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef name_bitvector_h
-#define name_bitvector_h
-
-#include <hicn/hicn.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-#include <hicn/utils/address.h>
-
-struct name_bitvector;
-typedef struct name_bitvector NameBitvector;
-
-NameBitvector *nameBitvector_CreateFromInAddr(uint32_t addr, uint8_t len);
-
-NameBitvector *nameBitvector_CreateFromIn6Addr(struct in6_addr *addr,
- uint8_t len);
-
-NameBitvector *nameBitvector_Copy(const NameBitvector *original);
-
-void nameBitvector_Destroy(NameBitvector **bitvectorPtr);
-
-uint8_t nameBitvector_GetLength(const NameBitvector *name);
-
-uint32_t nameBitvector_GetHash32(const NameBitvector *name);
-
-bool nameBitvector_Equals(const NameBitvector *a, const NameBitvector *b);
-
-int nameBitvector_Compare(const NameBitvector *a, const NameBitvector *b);
-
-int nameBitvector_testBit(const NameBitvector *name, uint8_t pos, bool *bit);
-
-uint32_t nameBitvector_lpm(const NameBitvector *a, const NameBitvector *b);
-
-void nameBitvector_clear(NameBitvector *a, uint8_t start_from);
-
-int nameBitvector_ToIPAddress(const NameBitvector *name, ip_prefix_t *prefix);
-void nameBitvector_setLen(NameBitvector *name, uint8_t len);
-
-Address *nameBitvector_ToAddress(const NameBitvector *name);
-
-char *nameBitvector_ToString(const NameBitvector *name);
-
-#endif // name_bitvector_h
diff --git a/hicn-light/src/hicn/core/nexthops.c b/hicn-light/src/hicn/core/nexthops.c
new file mode 100644
index 000000000..1a6096777
--- /dev/null
+++ b/hicn-light/src/hicn/core/nexthops.c
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file nexthops.c
+ * \brief Nexthops implementation
+ */
+
+#include <hicn/util/hash.h>
+
+#include "nexthops.h"
+
+int nexthops_disable(nexthops_t *nexthops, off_t offset) {
+ if (offset >= nexthops->num_elts) return -1;
+ nexthops->flags |= (1 << offset);
+ nexthops->cur_elts--;
+ return 0;
+}
+
+int nexthops_disable_all(nexthops_t *nexthops) {
+ nexthops->flags = ~0;
+ nexthops->cur_elts = 0;
+ return 0;
+}
+
+void nexthops_reset(nexthops_t *nexthops) {
+ nexthops->flags = 0;
+ nexthops->cur_elts = nexthops->num_elts;
+}
+
+off_t nexthops_add(nexthops_t *nexthops, nexthop_t nexthop) {
+ off_t id;
+ nexthops_enumerate(nexthops, i, n, {
+ if (n == nexthop) return i;
+ });
+ id = nexthops->num_elts++;
+ nexthops->elts[id] = nexthop;
+ nexthops_reset(nexthops);
+ return id;
+}
+
+off_t nexthops_remove(nexthops_t *nexthops, nexthop_t nexthop) {
+ nexthops_enumerate(nexthops, i, n, {
+ if (n == nexthop) {
+ nexthops->num_elts--;
+ nexthops->elts[i] = nexthops->elts[nexthops->num_elts];
+ nexthops->state[i] = nexthops->state[nexthops->num_elts];
+ nexthops_reset(nexthops);
+ return i;
+ }
+ });
+ return INVALID_NEXTHOP;
+}
+
+bool nexthops_contains(nexthops_t *nexthops, unsigned nexthop) {
+ nexthops_foreach(nexthops, n, {
+ if (n == nexthop) return true;
+ });
+ return false;
+}
+
+off_t nexthops_find(nexthops_t *nexthops, unsigned nexthop) {
+ nexthops_enumerate(nexthops, i, n, {
+ if (n == nexthop) return i;
+ });
+ return INVALID_NEXTHOP;
+}
+
+unsigned nexthops_get_one(nexthops_t *nexthops) {
+ nexthops_foreach(nexthops, n, { return n; });
+ return INVALID_NEXTHOP;
+}
+
+int nexthops_select(nexthops_t *nexthops, off_t i) {
+ if (i >= nexthops->num_elts) return -1;
+ nexthops->flags = ~0; /* all 1, could be limited to num_elts */
+ nexthops->flags &= ~(1 << (i));
+ nexthops->cur_elts = 1;
+ return 0;
+}
+
+#ifdef WITH_POLICY
+
+void nexthops_set_priority(nexthops_t *nexthops, nexthop_t nexthop,
+ int priority) {
+ nexthops_enumerate(nexthops, i, nh, {
+ if (nexthop == nh) nexthops_set_priority_by_id(nexthops, i, priority);
+ });
+}
+
+void nexthops_set_priority_by_id(nexthops_t *nexthops, off_t i, int priority) {
+ nexthops->state[i].priority = priority;
+}
+
+void nexthops_reset_priority(nexthops_t *nexthops, nexthop_t nexthop) {
+ nexthops_set_priority(nexthops, nexthop, DEFAULT_PRIORITY);
+}
+
+void nexthops_reset_priority_by_id(nexthops_t *nexthops, off_t i) {
+ nexthops_set_priority_by_id(nexthops, i, DEFAULT_PRIORITY);
+}
+
+void nexthops_reset_priorities(nexthops_t *nexthops) {
+ nexthops_enumerate(nexthops, i, nh, {
+ (void)nh;
+ nexthops_reset_priority(nexthops, i);
+ });
+}
+
+bool nexthops_equal(nexthops_t *a, nexthops_t *b) {
+ if (nexthops_get_len(a) != nexthops_get_len(b)) return false;
+ nexthops_foreach(a, n, {
+ if (!nexthops_contains(b, n)) return false;
+ });
+ return true;
+}
+
+void nexthops_copy(nexthops_t *src, nexthops_t *dst) {
+ for (unsigned i = 0; i < MAX_NEXTHOPS; i++) {
+ dst->elts[i] = src->elts[i];
+ dst->state[i] = src->state[i];
+ }
+ dst->num_elts = src->num_elts;
+ dst->flags = src->flags;
+ dst->cur_elts = src->cur_elts;
+}
+
+/* Adapted from Jenkins hash (commutative) */
+uint32_t nexthops_get_hash(nexthops_t *nexthops) {
+ uint32_t hash = 0;
+
+ nexthops_foreach(nexthops, nh, {
+ hash += nh;
+ hash += hash << 10;
+ hash ^= hash >> 6;
+ });
+ hash += hash << 3;
+ hash ^= hash >> 11;
+ hash += hash << 15;
+ return hash;
+}
+
+#endif /* WITH_POLICY */
diff --git a/hicn-light/src/hicn/core/nexthops.h b/hicn-light/src/hicn/core/nexthops.h
new file mode 100644
index 000000000..232c74388
--- /dev/null
+++ b/hicn-light/src/hicn/core/nexthops.h
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file nexthops.h
+ * \brief Nexthops
+ *
+ * An implementation of the nexthop data structure for the FIB entry.
+ *
+ * Note that the position of nexthops in this structure can be reordered. This
+ * is not an issue for the strategy state since the state if bound to the
+ * nexthop information, but an external module should not keep any reference to
+ * the offset of the nexthop.
+ */
+
+#ifndef HICNLIGHT_NEXTHOPS_H
+#define HICNLIGHT_NEXTHOPS_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <stdlib.h>
+
+#include <hicn/util/log.h>
+
+#include "connection.h"
+#include "strategy_vft.h"
+
+#define _nexthops_var(x) _nexthops_##x
+
+typedef unsigned nexthop_t;
+#define NEXTHOP(x) ((nexthop_t)x)
+
+#define INVALID_NEXTHOP NEXTHOP(CONNECTION_ID_UNDEFINED)
+
+/*
+ * This allows storage within a single integer
+ * 32 or 64 nexthops should be sufficient
+ * Eventually replace this with a resizeable vector
+ */
+#define MAX_NEXTHOPS (sizeof(uint_fast32_t) * 8)
+
+typedef struct nexthops_s {
+ unsigned elts[MAX_NEXTHOPS];
+ strategy_nexthop_state_t state[MAX_NEXTHOPS];
+ size_t num_elts;
+
+ /*
+ * flags is used during the processing of nexthops by the policy framework,
+ * and its meaning is local to the related functions.
+ * It is a mask where a bit set to 1 in position N indicates that the Nth
+ * elements in the elts array (elts[N]) is disabled.
+ * The number of enabled next hops is reflected in cur_elts, and it is equal
+ * to num_elts if no nexthop is disabled. This could be replaced by an
+ * efficient function counting the number of 1 bits in flags.
+ */
+ uint_fast32_t flags;
+ size_t cur_elts;
+} nexthops_t;
+
+#define NEXTHOPS_EMPTY \
+ (nexthops_t) { \
+ .elts = {0}, .state = {STRATEGY_NEXTHOP_STATE_EMPTY}, .num_elts = 0, \
+ .flags = 0, .cur_elts = 0, \
+ }
+
+#define nexthops_state(NH, i) ((NH)->state[(i)])
+
+#define nexthops_get_len(NH) ((NH)->num_elts)
+
+#define nexthops_set_len(NH, LEN) \
+ do { \
+ (NH)->num_elts = LEN; \
+ (NH)->cur_elts = LEN; \
+ } while (0)
+
+#define nexthops_get_curlen(NH) ((NH)->cur_elts)
+
+#define nexthops_inc(NH) \
+ do { \
+ (NH)->num_elts++; \
+ (NH)->cur_elts++; \
+ } while (0)
+
+int nexthops_disable(nexthops_t *nexthops, off_t offset);
+int nexthops_disable_all(nexthops_t *nexthops);
+
+#define nexthops_disable_if(NH, i, condition) \
+ do { \
+ if (condition) { \
+ nexthops_disable((NH), (i)); \
+ } \
+ } while (0)
+
+#define nexthops_is_disabled(NH, i) ((NH)->flags & (1 << (i)))
+
+void nexthops_reset(nexthops_t *nexthops);
+
+#define nexthops_enumerate(NH, I, X, BODY) \
+ do { \
+ nexthop_t X; \
+ (void)X; \
+ unsigned I; \
+ (void)I; \
+ for ((I) = 0; (I) < nexthops_get_len(NH); (I)++) { \
+ if (nexthops_is_disabled((NH), (I))) continue; \
+ X = (NH)->elts[(I)]; \
+ do { \
+ BODY \
+ } while (0); \
+ } \
+ } while (0)
+
+#define nexthops_foreach(NH, X, BODY) \
+ do { \
+ nexthops_enumerate((NH), _nexthops_var(i), X, {BODY}); \
+ } while (0)
+
+off_t nexthops_add(nexthops_t *nexthops, nexthop_t nexthop);
+
+off_t nexthops_remove(nexthops_t *nexthops, nexthop_t nexthop);
+
+#define nexthops_clear(NH) \
+ do { \
+ nexthops_set_len(NH, 0); \
+ (NH)->flags = 0; \
+ } while (0)
+
+bool nexthops_contains(nexthops_t *nexthops, unsigned nexthop);
+
+off_t nexthops_find(nexthops_t *nexthops, unsigned nexthop);
+
+unsigned nexthops_get_one(nexthops_t *nexthops);
+
+int nexthops_select(nexthops_t *nexthops, off_t i);
+
+/*
+ * This selects the first available element, irrespective of the current state
+ * of flags
+ */
+#define nexthops_select_first(NH) nexthops_select((NH), 0)
+
+#ifdef WITH_POLICY
+
+#define DEFAULT_PRIORITY 0
+#define DISABLED_PRIORITY -1
+
+void nexthops_set_priority(nexthops_t *nexthops, nexthop_t nexthop,
+ int priority);
+
+void nexthops_set_priority_by_id(nexthops_t *nexthops, off_t i, int priority);
+
+void nexthops_reset_priority_by_id(nexthops_t *nexthops, off_t i);
+
+void nexthops_reset_priority(nexthops_t *nexthops, nexthop_t nexthop);
+
+void nexthops_reset_priorities(nexthops_t *nexthops);
+
+/*
+ * returns true if the list of next hops contained in a is the same of b
+ * returns false otherwise
+ */
+bool nexthops_equal(nexthops_t *a, nexthops_t *b);
+
+void nexthops_copy(nexthops_t *src, nexthops_t *dst);
+
+#endif /* WITH_POLICY */
+
+uint32_t nexthops_get_hash(nexthops_t *nexthops);
+
+#endif /* HICNLIGHT_NEXTHOPS_H */
diff --git a/hicn-light/src/hicn/core/numberSet.c b/hicn-light/src/hicn/core/numberSet.c
deleted file mode 100644
index 106e13be6..000000000
--- a/hicn-light/src/hicn/core/numberSet.c
+++ /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.
- */
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Memory.h>
-#include <hicn/hicn-light/config.h>
-#include <hicn/core/numberSet.h>
-#include <stdio.h>
-
-#include <parc/assert/parc_Assert.h>
-
-struct number_set {
- Number *arrayOfNumbers;
- size_t length;
- size_t limit;
- unsigned refcount;
-};
-
-static void numberSet_Expand(NumberSet *set);
-
-NumberSet *numberSet_Create() {
- NumberSet *set = parcMemory_AllocateAndClear(sizeof(NumberSet));
- parcAssertNotNull(set, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(NumberSet));
- set->arrayOfNumbers = parcMemory_AllocateAndClear(sizeof(Number) * 16);
- parcAssertNotNull((set->arrayOfNumbers),
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Number) * 16);
- set->length = 0;
- set->limit = 16;
- set->refcount = 1;
- return set;
-}
-
-NumberSet *numberSet_Acquire(const NumberSet *original) {
- parcAssertNotNull(original, "Parameter original must be non-null");
- NumberSet *copy = (NumberSet *)original;
- copy->refcount++;
- return copy;
-}
-
-void numberSet_Release(NumberSet **setPtr) {
- parcAssertNotNull(setPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*setPtr, "Parameter must dereference to non-null pointer");
-
- NumberSet *set = *setPtr;
- parcAssertTrue(
- set->refcount > 0,
- "Invalid state: calling destroy on an object with 0 reference count");
- set->refcount--;
-
- if (set->refcount == 0) {
- parcMemory_Deallocate((void **)&(set->arrayOfNumbers));
- parcMemory_Deallocate((void **)&set);
- *setPtr = NULL;
- }
-}
-
-/**
- * @function numberSet_AddNoChecks
- * @abstract Add a number we know is not already in the set
- * @discussion
- * Used by other functions that already know the number is unique in the set,
- * Does not do the expensive Contains check.
- */
-static void numberSet_AddNoChecks(NumberSet *set, Number number) {
- if (set->length == set->limit) {
- numberSet_Expand(set);
- }
-
- set->arrayOfNumbers[set->length] = number;
- set->length++;
-}
-
-bool numberSet_Add(NumberSet *set, Number number) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- if (numberSet_Contains(set, number)) {
- return false;
- }
-
- numberSet_AddNoChecks(set, number);
- return true;
-}
-
-size_t numberSet_Length(const NumberSet *set) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- return set->length;
-}
-
-Number numberSet_GetItem(const NumberSet *set, size_t ordinalIndex) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- parcAssertTrue(ordinalIndex < set->length,
- "Limit beyond end of set, length %zu got %zu", set->length,
- ordinalIndex);
-
- return set->arrayOfNumbers[ordinalIndex];
-}
-
-bool numberSet_Contains(const NumberSet *set, Number number) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- for (size_t i = 0; i < set->length; i++) {
- if (set->arrayOfNumbers[i] == number) {
- return true;
- }
- }
- return false;
-}
-
-void numberSet_AddSet(NumberSet *destinationSet, const NumberSet *setToAdd) {
- parcAssertNotNull(destinationSet,
- "Parameter destinationSet must be non-null");
- parcAssertNotNull(setToAdd, "Parameter setToAdd must be non-null");
-
- for (size_t i = 0; i < setToAdd->length; i++) {
- numberSet_Add(destinationSet, setToAdd->arrayOfNumbers[i]);
- }
-}
-
-NumberSet *numberSet_Subtract(const NumberSet *minuend,
- const NumberSet *subtrahend) {
- // because the underlying ADT is not sorted, this is pretty ineffient, could
- // be O(n^2).
-
- NumberSet *difference = numberSet_Create();
-
- for (size_t i = 0; i < minuend->length; i++) {
- bool unique = true;
- for (size_t j = 0; j < subtrahend->length && unique; j++) {
- if (minuend->arrayOfNumbers[i] == subtrahend->arrayOfNumbers[j]) {
- unique = false;
- }
- }
-
- if (unique) {
- numberSet_AddNoChecks(difference, minuend->arrayOfNumbers[i]);
- }
- }
- return difference;
-}
-
-bool numberSet_Equals(const NumberSet *a, const NumberSet *b) {
- if (a == NULL && b == NULL) {
- return true;
- }
-
- if (a == NULL || b == NULL) {
- return false;
- }
-
- if (a->length == b->length) {
- for (size_t i = 0; i < a->length; i++) {
- bool found = false;
- for (size_t j = 0; j < b->length && !found; j++) {
- if (a->arrayOfNumbers[i] == b->arrayOfNumbers[j]) {
- found = true;
- }
- }
- if (!found) {
- return false;
- }
- }
- return true;
- }
-
- return false;
-}
-
-void numberSet_Remove(NumberSet *set, Number number) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- for (size_t i = 0; i < set->length; i++) {
- if (set->arrayOfNumbers[i] == number) {
- set->length--;
- if (set->length > 0) {
- // move the last element to the removed element to keep the array
- // packed.
- set->arrayOfNumbers[i] = set->arrayOfNumbers[set->length];
- }
- return;
- }
- }
-}
-
-// =====================================================
-
-static void numberSet_Expand(NumberSet *set) {
- size_t newlimit = set->limit * 2;
- size_t newbytes = newlimit * sizeof(Number);
-
- set->arrayOfNumbers = parcMemory_Reallocate(set->arrayOfNumbers, newbytes);
- set->limit = newlimit;
-}
diff --git a/hicn-light/src/hicn/core/numberSet.h b/hicn-light/src/hicn/core/numberSet.h
deleted file mode 100644
index 91a965d7b..000000000
--- a/hicn-light/src/hicn/core/numberSet.h
+++ /dev/null
@@ -1,157 +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.
- */
-
-/**
- * @brief Stores a set of numbers.
- *
- * Useful for things like the reverse path of a PIT
- * or the forward paths of a FIB. Does not allow duplicates.
- *
- */
-
-#ifndef numberSet_h
-#define numberSet_h
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-struct number_set;
-typedef struct number_set NumberSet;
-
-typedef uint32_t Number;
-
-/**
- * @function numberList_Create
- * @abstract A new list of numbers
- */
-NumberSet *numberSet_Create(void);
-
-/**
- * Obtains a reference counted copy of the original
- * The reference count is increased by one. It must be released with
- * NumberSet_Release().
- * @param [in] original An allocated NumberSet
- * @return non-null The reference counted copy
- */
-NumberSet *numberSet_Acquire(const NumberSet *original);
-
-/**
- * Releases one reference count and destroys the memory after last release
- * The pointer will be NULLed after release regardless if the memory was
- * destroyed.
- * @param [in,out] setPtr A pointer to a NumberSet. Will be NULL'd after
- * release.
- */
-void numberSet_Release(NumberSet **setPtr);
-
-/**
- * @function numberList_Append
- * @abstract Add a number to the end of the list
- * @discussion
- * No check for duplicates is done
- * @return true if added, false if a duplicate
- */
-bool numberSet_Add(NumberSet *set, Number number);
-
-/**
- * @function numberList_Length
- * @abstract The count of numbers in the list
- */
-size_t numberSet_Length(const NumberSet *set);
-
-/**
- * @function numberSet_GetItem
- * @abstract Retrieves an item based on the ordinal index
- * @discussion
- * Will assert if the ordinalIndex is out of bounds.
- */
-Number numberSet_GetItem(const NumberSet *set, size_t ordinalIndex);
-
-/**
- * @function numberSet_Contains
- * @abstract Checks for set membership
- * @return true if the set contains the number, false otherwise
- */
-bool numberSet_Contains(const NumberSet *set, Number number);
-
-/**
- * @function numberSet_AddSet
- * @abstract Adds one set to another set
- * @discussion
- * Adds <code>setToAdd</code> to <code>destinationSet</code>
- * @return true if the set contains the number, false otherwise
- */
-void numberSet_AddSet(NumberSet *destinationSet, const NumberSet *setToAdd);
-
-/**
- * @function numberSet_Subtract
- * @abstract Computes set difference <code>difference = minuend -
- * subtrahend</code>, returns a new number set.
- * @discussion
- * <code>minuend</code> and <code>subtrahend</code> are not modified. A new
- * difference set is created.
- *
- * Returns the elements in <code>minuend</code> that are not in
- * <code>subtrahend</code>.
- *
- * @param minuend The set from which to subtract
- * @param subrahend The set begin removed from minuend
- * @return The set difference. May be empty, but will not be NULL.
- */
-NumberSet *numberSet_Subtract(const NumberSet *minuend,
- const NumberSet *subtrahend);
-
-/**
- * Determine if two NumberSet instances are equal.
- *
- * Two NumberSet instances are equal if, and only if,
- * they are the same size and contain the same elements. Empty sets are
- * equal. NULL equals NULL, but does not equal non-NULL.
- *
- * The following equivalence relations on non-null `NumberSet` instances are
- * maintained:
- *
- * * It is reflexive: for any non-null reference value x, `NumberSet_Equals(x,
- * x)` must return true.
- *
- * * It is symmetric: for any non-null reference values x and y,
- * `numberSet_Equals(x, y)` must return true if and only if
- * `numberSet_Equals(y, x)` returns true.
- *
- * * It is transitive: for any non-null reference values x, y, and z, if
- * `numberSet_Equals(x, y)` returns true and
- * `numberSet_Equals(y, z)` returns true,
- * then `numberSet_Equals(x, z)` must return true.
- *
- * * It is consistent: for any non-null reference values x and y, multiple
- * invocations of `numberSet_Equals(x, y)` consistently return true or
- * consistently return false.
- *
- * * For any non-null reference value x, `numberSet_Equals(x, NULL)` must
- * return false.
- *
- * @param a A pointer to a `NumberSet` instance.
- * @param b A pointer to a `NumberSet` instance.
- * @return true if the two `NumberSet` instances are equal.
- */
-bool numberSet_Equals(const NumberSet *a, const NumberSet *b);
-
-/**
- * @function numberSet_Remove
- * @abstract Removes the number from the set
- */
-void numberSet_Remove(NumberSet *set, Number number);
-#endif // numberSet_h
diff --git a/hicn-light/src/hicn/core/packet_cache.c b/hicn-light/src/hicn/core/packet_cache.c
new file mode 100644
index 000000000..937b0480b
--- /dev/null
+++ b/hicn-light/src/hicn/core/packet_cache.c
@@ -0,0 +1,884 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file packet_cache.c
+ * \brief Implementation of hICN packet cache
+ *
+ * _get_suffixes : first level lookup to return the suffixes
+ *
+ * _remove_suffix : Remove suffix from the two level packet cache structure
+ *
+ * __add_suffix : Add a packet cache entry in the second level of the
+ * two-level data structure _add_suffix : Add a packet cache entry in the both
+ * the first and second level of the two-level data tructure (helper)
+ *
+ * __get_suffix : Lookup in the second level of the packet cache
+ *
+ * _get_suffix : Lookup in both the first and second levels of the packet cache
+ *
+ * ----
+ *
+ * pkt_cache_save_suffixes_for_prefix : always done at packet reception to keep
+ * the latest suffixes
+ *
+ * pkt_cache_reset_suffixes_for_prefix
+ *
+ * ----
+ *
+ * pkt_cache_allocate
+ *
+ * pkt_cache_add_to_index
+ *
+ * pkt_cache_remove_from_index
+ *
+ * pkt_cache_pit_remove_entry
+ *
+ * pkt_cache_cs_remove_entry
+ *
+ * pkt_cache_add_to_pit
+ * pkt_cache_add_to_cs
+ *
+ * _pkt_cache_add_to_pit
+ * used by pkt_cache_add_to_pit
+ * plt_cache_update_pit
+ * _pkt_cache_add_to_cs
+ *
+ * pkt_cache_pit_to_cs
+ * pkt_cache_cs_to_pit
+ *
+ * pkt_cache_update_pit : when an interest expired
+ * pkt_cache_update_cs
+ *
+ * pkt_cache_try_aggregate_in_pit
+ *
+ *
+ *
+ */
+
+#include <hicn/core/forwarder.h>
+#include "packet_cache.h"
+
+const char *_pkt_cache_verdict_str[] = {
+#define _(x) [PKT_CACHE_VERDICT_##x] = #x,
+ foreach_kh_verdict
+#undef _
+};
+
+/******************************************************************************
+ * Low-level operations on the hash table
+ ******************************************************************************/
+
+/**
+ * Free the two level packet cache structure (helper)
+ */
+void _prefix_map_free(kh_pkt_cache_prefix_t *prefix_to_suffixes) {
+ kh_pkt_cache_suffix_t *suffix;
+ kh_foreach_value(prefix_to_suffixes, suffix,
+ { kh_destroy_pkt_cache_suffix(suffix); });
+ kh_destroy_pkt_cache_prefix(prefix_to_suffixes);
+}
+
+/**
+ * Perform the first level lookup to return the suffixes (helper)
+ */
+kh_pkt_cache_suffix_t *_get_suffixes(kh_pkt_cache_prefix_t *prefix_to_suffixes,
+ const hicn_name_prefix_t *prefix,
+ bool create, slab_t *prefix_keys) {
+ khiter_t k = kh_get_pkt_cache_prefix(prefix_to_suffixes, prefix);
+
+ /* Return suffixes if found... */
+ if (k != kh_end(prefix_to_suffixes)) {
+ kh_pkt_cache_suffix_t *suffixes = kh_val(prefix_to_suffixes, k);
+ return suffixes;
+ }
+
+ if (!create) return NULL;
+
+ /* ... otherwise populate the first level and return the newly added entry.
+ */
+ kh_pkt_cache_suffix_t *suffixes = kh_init_pkt_cache_suffix();
+
+ hicn_name_prefix_t *prefix_copy = slab_get(hicn_name_prefix_t, prefix_keys);
+ memcpy(prefix_copy, prefix, sizeof(hicn_name_prefix_t));
+
+ int rc;
+ k = kh_put_pkt_cache_prefix(prefix_to_suffixes, prefix_copy, &rc);
+ assert(rc == KH_ADDED || rc == KH_RESET);
+ kh_value(prefix_to_suffixes, k) = suffixes;
+ return suffixes;
+}
+
+/**
+ * Remove suffix from the two level packet cache structure (helper)
+ */
+void _remove_suffix(kh_pkt_cache_prefix_t *prefixes,
+ const hicn_name_prefix_t *prefix,
+ const hicn_name_suffix_t suffix, slab_t *prefix_keys) {
+ kh_pkt_cache_suffix_t *suffixes =
+ _get_suffixes(prefixes, prefix, false, prefix_keys);
+ assert(suffixes != NULL);
+
+ khiter_t k = kh_get_pkt_cache_suffix(suffixes, suffix);
+ assert(k != kh_end(suffixes));
+ kh_del_pkt_cache_suffix(suffixes, k);
+
+ // TODO(eloparco): Remove prefix if no associated suffixes?
+}
+
+/**
+ * Add a packet cache entry in the second level of the two-level data structure
+ * (helper)
+ */
+void __add_suffix(kh_pkt_cache_suffix_t *suffixes, hicn_name_suffix_t suffix,
+ unsigned val) {
+ // INFO("suffix add suffixes=%p suffix=%d val=%d", suffixes, suffix, val);
+ int rc;
+ khiter_t k = kh_put_pkt_cache_suffix(suffixes, suffix, &rc);
+ assert(rc == KH_ADDED || rc == KH_RESET);
+ kh_value(suffixes, k) = val;
+}
+
+/**
+ * Add a packet cache entry in the both the first and second level of the
+ * two-level data tructure (helper)
+ */
+void _add_suffix(kh_pkt_cache_prefix_t *prefixes,
+ const hicn_name_prefix_t *prefix,
+ const hicn_name_suffix_t suffix, unsigned val,
+ slab_t *prefix_keys) {
+ kh_pkt_cache_suffix_t *suffixes =
+ _get_suffixes(prefixes, prefix, true, prefix_keys);
+ assert(suffixes != NULL);
+
+ __add_suffix(suffixes, suffix, val);
+}
+
+/**
+ * Lookup in the second level of the packet cache (helper)
+ */
+unsigned __get_suffix(kh_pkt_cache_suffix_t *suffixes,
+ hicn_name_suffix_t suffix) {
+ khiter_t k = kh_get_pkt_cache_suffix(suffixes, suffix);
+
+ // Not Found
+ if (k == kh_end(suffixes)) {
+ return HICN_INVALID_SUFFIX;
+ }
+
+ unsigned index = kh_val(suffixes, k);
+ return index;
+}
+
+unsigned _get_suffix(kh_pkt_cache_prefix_t *prefixes,
+ const hicn_name_prefix_t *prefix,
+ hicn_name_suffix_t suffix, slab_t *prefix_keys) {
+ /* create is false as this function is always called by lookup */
+ kh_pkt_cache_suffix_t *suffixes =
+ _get_suffixes(prefixes, prefix, false, prefix_keys);
+ if (!suffixes) {
+ return HICN_INVALID_SUFFIX;
+ }
+ return __get_suffix(suffixes, suffix);
+}
+
+/**
+ * Lookup in both the first and second levels of the packet cache (helper)
+ */
+unsigned _get_suffix_from_name(kh_pkt_cache_prefix_t *prefixes,
+ const hicn_name_t *name, slab_t *prefix_keys) {
+ const hicn_name_prefix_t *prefix = hicn_name_get_prefix(name);
+ const hicn_name_suffix_t suffix = hicn_name_get_suffix(name);
+
+ return _get_suffix(prefixes, prefix, suffix, prefix_keys);
+}
+
+void pkt_cache_save_suffixes_for_prefix(pkt_cache_t *pkt_cache,
+ const hicn_name_prefix_t *prefix) {
+ // Cached prefix matches the current one
+ if (hicn_name_prefix_equals(&pkt_cache->cached_prefix, prefix)) return;
+
+ char buf[MAXSZ_HICN_PREFIX];
+ hicn_name_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, &pkt_cache->cached_prefix);
+ hicn_name_prefix_snprintf(buf, MAXSZ_HICN_PREFIX, prefix);
+
+ // Update cached prefix information
+ pkt_cache->cached_prefix = *prefix;
+ pkt_cache->cached_suffixes =
+ _get_suffixes(pkt_cache->prefix_to_suffixes, prefix, true,
+ pkt_cache->prefix_keys); // XXX
+ //
+}
+
+void pkt_cache_reset_suffixes_for_prefix(pkt_cache_t *pkt_cache) {
+ pkt_cache->cached_suffixes = NULL;
+}
+
+/******************************************************************************
+ * Public API
+ ******************************************************************************/
+
+pkt_cache_t *pkt_cache_create(size_t cs_size) {
+ pkt_cache_t *pkt_cache = (pkt_cache_t *)malloc(sizeof(pkt_cache_t));
+
+ pkt_cache->pit = pit_create();
+ if (!pkt_cache->pit) return NULL;
+ pkt_cache->cs = cs_create(cs_size);
+ if (!pkt_cache->cs) return NULL;
+
+ pkt_cache->prefix_to_suffixes = kh_init_pkt_cache_prefix();
+ pkt_cache->prefix_keys = slab_create(hicn_name_prefix_t, SLAB_INIT_SIZE);
+ pool_init(pkt_cache->entries, DEFAULT_PKT_CACHE_SIZE, 0);
+
+ pkt_cache->cached_prefix = HICN_NAME_PREFIX_EMPTY;
+ pkt_cache->cached_suffixes = NULL;
+
+ return pkt_cache;
+}
+
+void pkt_cache_free(pkt_cache_t *pkt_cache) {
+ assert(pkt_cache);
+
+ // Free prefix hash table and pool
+ _prefix_map_free(pkt_cache->prefix_to_suffixes);
+ slab_free(pkt_cache->prefix_keys);
+ pool_free(pkt_cache->entries);
+
+ // Free PIT and CS
+ pit_free(pkt_cache->pit);
+ cs_free(pkt_cache->cs);
+
+ free(pkt_cache);
+}
+
+kh_pkt_cache_suffix_t *pkt_cache_get_suffixes(const pkt_cache_t *pkt_cache,
+ const hicn_name_prefix_t *prefix,
+ bool create,
+ slab_t *prefix_keys) {
+ return _get_suffixes(pkt_cache->prefix_to_suffixes, prefix, create,
+ prefix_keys);
+}
+
+pkt_cache_entry_t *pkt_cache_allocate(pkt_cache_t *pkt_cache) {
+ pkt_cache_entry_t *entry = NULL;
+ pool_get(pkt_cache->entries, entry);
+ assert(entry);
+ return entry;
+}
+
+void pkt_cache_add_to_index(const pkt_cache_t *pkt_cache,
+ const pkt_cache_entry_t *entry) {
+ off_t id = entry - pkt_cache->entries;
+
+ /* It is important that the name used for the index is the one in the packet
+ * cache entry, which is common for PIT and CS
+ */
+ const hicn_name_t *name = &entry->name;
+
+ if (pkt_cache->cached_suffixes) {
+ __add_suffix(pkt_cache->cached_suffixes, hicn_name_get_suffix(name),
+ (unsigned int)id);
+ } else {
+ _add_suffix(pkt_cache->prefix_to_suffixes, hicn_name_get_prefix(name),
+ hicn_name_get_suffix(name), (unsigned int)id,
+ pkt_cache->prefix_keys);
+ }
+}
+
+/**
+ * Remove a name pointer to the packet cache index (helper)
+ */
+void pkt_cache_remove_from_index(const pkt_cache_t *pkt_cache,
+ const hicn_name_t *name) {
+ _remove_suffix(pkt_cache->prefix_to_suffixes, hicn_name_get_prefix(name),
+ hicn_name_get_suffix(name), pkt_cache->prefix_keys);
+
+// TODO
+#if 0
+ khiter_t k = kh_get_pkt_cache_name(pkt_cache->index_by_name, name);
+ assert(k != kh_end(pkt_cache->index_by_name));
+ kh_del(pkt_cache_name, pkt_cache->index_by_name, k);
+#endif
+}
+
+pit_t *pkt_cache_get_pit(pkt_cache_t *pkt_cache) { return pkt_cache->pit; }
+
+cs_t *pkt_cache_get_cs(pkt_cache_t *pkt_cache) { return pkt_cache->cs; }
+
+pkt_cache_entry_t *pkt_cache_lookup(pkt_cache_t *pkt_cache,
+ const hicn_name_t *name,
+ msgbuf_pool_t *msgbuf_pool,
+ pkt_cache_lookup_t *lookup_result,
+ off_t *entry_id,
+ bool is_serve_from_cs_enabled) {
+ unsigned index = HICN_INVALID_SUFFIX;
+ if (pkt_cache->cached_suffixes) {
+ index =
+ __get_suffix(pkt_cache->cached_suffixes, hicn_name_get_suffix(name));
+ } else {
+ index = _get_suffix_from_name(pkt_cache->prefix_to_suffixes, name,
+ pkt_cache->prefix_keys);
+ }
+
+ if (index == HICN_INVALID_SUFFIX) {
+ *lookup_result = PKT_CACHE_LU_NONE;
+ return NULL;
+ }
+
+ pkt_cache_entry_t *entry = pkt_cache_at(pkt_cache, index);
+ assert(entry);
+ bool expired = false;
+ if (entry->has_expire_ts && ticks_now() >= entry->expire_ts) {
+ expired = true;
+ }
+
+ if (entry->entry_type == PKT_CACHE_CS_TYPE) {
+ if (expired)
+ *lookup_result = PKT_CACHE_LU_DATA_EXPIRED;
+ else
+ *lookup_result = PKT_CACHE_LU_DATA_NOT_EXPIRED;
+ } else { // PKT_CACHE_PIT_TYPE
+ if (expired)
+ *lookup_result = PKT_CACHE_LU_INTEREST_EXPIRED;
+ else
+ *lookup_result = PKT_CACHE_LU_INTEREST_NOT_EXPIRED;
+ }
+
+ *entry_id = index;
+ return entry;
+}
+
+void pkt_cache_cs_remove_entry(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ msgbuf_pool_t *msgbuf_pool, bool is_evicted) {
+ assert(pkt_cache);
+ assert(entry);
+ assert(entry->entry_type == PKT_CACHE_CS_TYPE);
+
+ off_t msgbuf_id = entry->u.cs_entry.msgbuf_id;
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+
+ // XXX const hicn_name_t *name = msgbuf_get_name(msgbuf);
+ _remove_suffix(pkt_cache->prefix_to_suffixes,
+ hicn_name_get_prefix(&entry->name),
+ hicn_name_get_suffix(&entry->name), pkt_cache->prefix_keys);
+
+ // Do not update the LRU cache for evicted entries
+ if (!is_evicted) cs_vft[pkt_cache->cs->type]->remove_entry(pkt_cache, entry);
+
+ pkt_cache->cs->num_entries--;
+ pool_put(pkt_cache->entries, entry);
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HICN_NAME];
+ int rc = hicn_name_snprintf(buf, MAXSZ_HICN_NAME, &entry->name);
+ if (rc < 0 || rc >= MAXSZ_HICN_NAME)
+ snprintf(buf, MAXSZ_HICN_NAME, "%s", "(error)");
+ DEBUG("Packet %s removed from CS", buf);
+ })
+
+ msgbuf_pool_release(msgbuf_pool, &msgbuf);
+}
+
+void pkt_cache_pit_remove_entry(pkt_cache_t *pkt_cache,
+ pkt_cache_entry_t *entry) {
+ assert(pkt_cache);
+ assert(entry);
+ assert(entry->entry_type == PKT_CACHE_PIT_TYPE);
+
+ const hicn_name_t *name = &entry->name;
+ _remove_suffix(pkt_cache->prefix_to_suffixes, hicn_name_get_prefix(name),
+ hicn_name_get_suffix(name), pkt_cache->prefix_keys);
+
+ pool_put(pkt_cache->entries, entry);
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HICN_NAME];
+ int rc = hicn_name_snprintf(buf, MAXSZ_HICN_NAME, name);
+ if (rc < 0 || rc >= MAXSZ_HICN_NAME)
+ snprintf(buf, MAXSZ_HICN_NAME, "%s", "(error)");
+ DEBUG("Packet %s removed from PIT", buf);
+ })
+}
+
+void _pkt_cache_add_to_cs(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf,
+ off_t msgbuf_id, off_t entry_id) {
+ entry->u.cs_entry =
+ (cs_entry_t){.msgbuf_id = msgbuf_id,
+ .lru = {.prev = INVALID_ENTRY_ID, .next = INVALID_ENTRY_ID}};
+ Ticks now = ticks_now();
+ entry->create_ts = now;
+ entry->expire_ts = now + msgbuf_get_data_expiry_time(msgbuf);
+ entry->has_expire_ts = true;
+ entry->entry_type = PKT_CACHE_CS_TYPE;
+
+ pkt_cache->cs->num_entries++;
+
+ int tail_id = (int)(pkt_cache->cs->lru.tail);
+ int result = cs_vft[pkt_cache->cs->type]->add_entry(pkt_cache, entry_id);
+ if (result == LRU_EVICTION) {
+ // Remove tail (already removed from LRU cache)
+ pkt_cache_entry_t *tail = pkt_cache_entry_at(pkt_cache, tail_id);
+ assert(tail->entry_type == PKT_CACHE_CS_TYPE);
+ pkt_cache_cs_remove_entry(pkt_cache, tail, msgbuf_pool, true);
+ }
+
+ // Acquired by CS
+ msgbuf_pool_acquire(msgbuf);
+}
+
+void pkt_cache_pit_to_cs(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf,
+ off_t msgbuf_id, off_t entry_id) {
+ assert(pkt_cache);
+ assert(entry);
+ assert(entry->entry_type == PKT_CACHE_PIT_TYPE);
+
+ _pkt_cache_add_to_cs(pkt_cache, entry, msgbuf_pool, msgbuf, msgbuf_id,
+ entry_id);
+}
+
+/**
+ * entry : newly allocated cache entry
+ * msgbuf : used for name, ingress connection id and lifetime
+ */
+void _pkt_cache_add_to_pit(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ const msgbuf_t *msgbuf) {
+ entry->u.pit_entry = (pit_entry_t){
+ .ingressIdSet = NEXTHOPS_EMPTY,
+ .egressIdSet = NEXTHOPS_EMPTY,
+ .fib_entry = NULL,
+ };
+ pit_entry_ingress_add(&entry->u.pit_entry, msgbuf_get_connection_id(msgbuf));
+
+ entry->create_ts = ticks_now();
+ entry->expire_ts = ticks_now() + msgbuf_get_interest_lifetime(msgbuf);
+ entry->has_expire_ts = true;
+ entry->entry_type = PKT_CACHE_PIT_TYPE;
+}
+
+void pkt_cache_cs_to_pit(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ msgbuf_pool_t *msgbuf_pool, const msgbuf_t *msgbuf,
+ off_t msgbuf_id, off_t entry_id) {
+ assert(pkt_cache);
+ assert(entry);
+ assert(entry->entry_type == PKT_CACHE_CS_TYPE);
+
+ // Release data associated with expired CS entry
+ off_t cs_entry_msgbuf_id = entry->u.cs_entry.msgbuf_id;
+ msgbuf_t *cs_entry_msgbuf = msgbuf_pool_at(msgbuf_pool, cs_entry_msgbuf_id);
+ msgbuf_pool_release(msgbuf_pool, &cs_entry_msgbuf);
+
+ cs_vft[pkt_cache->cs->type]->remove_entry(pkt_cache, entry);
+ _pkt_cache_add_to_pit(pkt_cache, entry, msgbuf);
+ pkt_cache->cs->num_entries--;
+}
+
+void pkt_cache_update_cs(pkt_cache_t *pkt_cache, msgbuf_pool_t *msgbuf_pool,
+ pkt_cache_entry_t *entry, msgbuf_t *msgbuf,
+ off_t msgbuf_id) {
+ assert(pkt_cache);
+ assert(entry);
+ assert(entry->entry_type == PKT_CACHE_CS_TYPE);
+
+ // Release previous msgbuf and acquire new one
+ msgbuf_t *prev_msgbuf =
+ msgbuf_pool_at(msgbuf_pool, entry->u.cs_entry.msgbuf_id);
+ msgbuf_pool_release(msgbuf_pool, &prev_msgbuf);
+ msgbuf_pool_acquire(msgbuf);
+
+ entry->u.cs_entry.msgbuf_id = msgbuf_id;
+ entry->create_ts = ticks_now();
+ entry->expire_ts = ticks_now() + msgbuf_get_data_expiry_time(msgbuf);
+ entry->has_expire_ts = true;
+
+ cs_vft[pkt_cache->cs->type]->update_entry(pkt_cache, entry);
+}
+
+pkt_cache_entry_t *pkt_cache_add_to_pit(pkt_cache_t *pkt_cache,
+ const msgbuf_t *msgbuf,
+ const hicn_name_t *name) {
+ assert(pkt_cache);
+
+ pkt_cache_entry_t *entry = pkt_cache_allocate(pkt_cache);
+ entry->name = *name;
+ _pkt_cache_add_to_pit(pkt_cache, entry, msgbuf);
+ pkt_cache_add_to_index(pkt_cache, entry);
+ return entry;
+}
+
+pkt_cache_entry_t *pkt_cache_add_to_cs(pkt_cache_t *pkt_cache,
+ msgbuf_pool_t *msgbuf_pool,
+ msgbuf_t *msgbuf, off_t msgbuf_id) {
+ assert(pkt_cache);
+
+ pkt_cache_entry_t *entry = pkt_cache_allocate(pkt_cache);
+ const hicn_name_t *name = msgbuf_get_name(msgbuf);
+ entry->name = *name;
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+ _pkt_cache_add_to_cs(pkt_cache, entry, msgbuf_pool, msgbuf, msgbuf_id,
+ entry_id);
+ pkt_cache_add_to_index(pkt_cache, entry);
+ return entry;
+}
+
+void pkt_cache_update_pit(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ const msgbuf_t *msgbuf) {
+ assert(pkt_cache);
+ assert(entry);
+ assert(entry->entry_type == PKT_CACHE_PIT_TYPE);
+
+ pit_entry_t *pit_entry = &entry->u.pit_entry;
+ fib_entry_t *fib_entry = pit_entry_get_fib_entry(pit_entry);
+ if (fib_entry)
+ fib_entry_on_timeout(fib_entry, pit_entry_get_egress(pit_entry));
+
+ _pkt_cache_add_to_pit(pkt_cache, entry, msgbuf);
+}
+
+bool pkt_cache_try_aggregate_in_pit(pkt_cache_t *pkt_cache,
+ pkt_cache_entry_t *entry,
+ const msgbuf_t *msgbuf,
+ const hicn_name_t *name) {
+ assert(pkt_cache);
+ assert(entry);
+ assert(entry->entry_type == PKT_CACHE_PIT_TYPE);
+
+ pit_entry_t *pit_entry = &entry->u.pit_entry;
+
+ // Extend entry lifetime
+ Ticks expire_ts = ticks_now() + msgbuf_get_interest_lifetime(msgbuf);
+ if (expire_ts > entry->expire_ts) entry->expire_ts = expire_ts;
+
+ // Check if the reverse path is already present
+ // in the PIT entry (i.e. it is a retransmission)
+ unsigned connection_id = msgbuf_get_connection_id(msgbuf);
+ bool is_aggregated = !pit_entry_ingress_contains(pit_entry, connection_id);
+
+ // If the strategy to use for this packet is STRATEGY_TYPE_LOCAL_REMOTE we may
+ // want to forward the packet even if it should be aggregated. This is useful
+ // when a local consumer socket and a remote one are asking for the same
+ // content. If the interest coming from the remote socket is received before
+ // the one from the local socket, the second interest is aggregated in the PIT
+ // and no interest is satisfied (IRIS app).
+ // Forward the interest if: 1) the strategy in the fib_entry stored in the pit
+ // entry is STRATEGY_TYPE_LOCAL_REMOTE 2) the ingress connection of the
+ // interest if a local connection 3) the ingress list of pit entry has no
+ // other local ingress connection if all these conditions are satisfied, send
+ // the interest. if is_aggregated = false avoid the check (it will be useless)
+
+ if (is_aggregated) {
+ fib_entry_t *fib_entry = pit_entry_get_fib_entry(pit_entry);
+ if (fib_entry &&
+ (fib_entry_strategy_type(fib_entry) == STRATEGY_TYPE_LOCAL_REMOTE)) {
+ // the strategy is STRATEGY_TYPE_LOCAL_REMOTE, check the input face
+ connection_table_t *table =
+ forwarder_get_connection_table(fib_entry->forwarder);
+ if (table) {
+ connection_t *msg_conn =
+ connection_table_get_by_id(table, connection_id);
+ if (msg_conn && connection_is_local(msg_conn)) {
+ // The face is local, check that no other input face is local. With
+ // this check only the first local consumer is able to send
+ // the interest, while the other interests will be aggregated
+ // (however this is quite inefficient)
+ nexthops_t *ingressIdSet = pit_entry_get_ingress(pit_entry);
+ bool in_local_connextion_exists = false;
+ nexthops_enumerate(ingressIdSet, i, nexthop, {
+ connection_t *in_conn = connection_table_get_by_id(table, nexthop);
+ if (in_conn && connection_is_local(in_conn)) {
+ in_local_connextion_exists = true;
+ break;
+ }
+ });
+ if (!in_local_connextion_exists) is_aggregated = false;
+ }
+ }
+ }
+ }
+
+ if (is_aggregated) pit_entry_ingress_add(pit_entry, connection_id);
+
+ WITH_DEBUG({
+ char buf[MAXSZ_HICN_NAME];
+ int rc = hicn_name_snprintf(buf, MAXSZ_HICN_NAME, msgbuf_get_name(msgbuf));
+ if (rc < 0 || rc >= MAXSZ_HICN_NAME)
+ snprintf(buf, MAXSZ_HICN_NAME, "%s", "(error)");
+ if (is_aggregated) {
+ DEBUG("Interest %s already existing (expiry %lu): aggregate", buf,
+ entry->expire_ts);
+ } else {
+ DEBUG("Interest %s already existing (expiry %lu): retransmit", buf,
+ entry->expire_ts);
+ }
+ })
+
+ return is_aggregated;
+}
+
+nexthops_t *pkt_cache_on_data(pkt_cache_t *pkt_cache,
+ msgbuf_pool_t *msgbuf_pool, off_t msgbuf_id,
+ bool is_cs_store_enabled,
+ bool is_connection_local, bool *wrong_egress,
+ pkt_cache_verdict_t *verdict) {
+ assert(pkt_cache);
+ assert(msgbuf_id_is_valid(msgbuf_id));
+
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA);
+
+ *wrong_egress = false;
+ off_t entry_id;
+ pkt_cache_lookup_t lookup_result;
+ pkt_cache_entry_t *entry =
+ pkt_cache_lookup(pkt_cache, msgbuf_get_name(msgbuf), msgbuf_pool,
+ &lookup_result, &entry_id, true);
+
+ pit_entry_t *pit_entry;
+ fib_entry_t *fib_entry;
+ nexthops_t *nexthops = NULL;
+ nexthops_t *nexthops_copy;
+ switch (lookup_result) {
+ case PKT_CACHE_LU_INTEREST_NOT_EXPIRED:
+ pit_entry = &entry->u.pit_entry;
+ fib_entry = pit_entry_get_fib_entry(pit_entry);
+ if (fib_entry)
+ fib_entry_on_data(fib_entry, pit_entry_get_egress(pit_entry), msgbuf,
+ entry->create_ts, ticks_now());
+
+ // Check if the data is coming from the exepected connection
+ nexthops_t *egressIdSet = pit_entry_get_egress(pit_entry);
+ unsigned egress_connection = msgbuf_get_connection_id(msgbuf);
+ if (!nexthops_contains(egressIdSet, egress_connection)) {
+ *wrong_egress = true;
+ return NULL;
+ }
+
+ // XXX TODO : be sure nexthops are valid b/c pit entry is removed
+ // XXX TODO eventually pass holding structure as parameter
+ nexthops = pit_entry_get_ingress(pit_entry);
+ assert(nexthops);
+
+ nexthops_copy = (nexthops_t *)malloc(sizeof(*nexthops_copy));
+ *nexthops_copy = *nexthops;
+
+ if (is_cs_store_enabled) {
+ pkt_cache_pit_to_cs(pkt_cache, entry, msgbuf_pool, msgbuf, msgbuf_id,
+ entry_id);
+ *verdict = PKT_CACHE_VERDICT_FORWARD_DATA;
+ } else {
+ pkt_cache_pit_remove_entry(pkt_cache, entry);
+ *verdict = PKT_CACHE_VERDICT_CLEAR_DATA;
+ }
+
+ return nexthops_copy;
+
+ // Data packets are stored in the content store even in the case
+ // where there is no match in the PIT, to allow applications to push
+ // content to the forwarder's CS. This behavior is allowed only for
+ // local faces.
+ case PKT_CACHE_LU_INTEREST_EXPIRED:
+ if (is_cs_store_enabled && is_connection_local) {
+ pkt_cache_pit_to_cs(pkt_cache, entry, msgbuf_pool, msgbuf, msgbuf_id,
+ entry_id);
+ *verdict = PKT_CACHE_VERDICT_STORE_DATA;
+ } else {
+ pkt_cache_pit_remove_entry(pkt_cache, entry);
+ *verdict = PKT_CACHE_VERDICT_CLEAR_DATA;
+ }
+ return NULL;
+
+ case PKT_CACHE_LU_NONE:
+ *verdict = PKT_CACHE_VERDICT_IGNORE_DATA;
+ if (is_cs_store_enabled && is_connection_local) {
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, msgbuf_id);
+ *verdict = PKT_CACHE_VERDICT_STORE_DATA;
+ }
+ return NULL;
+
+ case PKT_CACHE_LU_DATA_EXPIRED:
+ if (is_cs_store_enabled && is_connection_local) {
+ pkt_cache_update_cs(pkt_cache, msgbuf_pool, entry, msgbuf, msgbuf_id);
+ *verdict = PKT_CACHE_VERDICT_UPDATE_DATA;
+ } else {
+ pkt_cache_cs_remove_entry(pkt_cache, entry, msgbuf_pool, false);
+ *verdict = PKT_CACHE_VERDICT_CLEAR_DATA;
+ }
+ return NULL;
+
+ case PKT_CACHE_LU_DATA_NOT_EXPIRED:
+ *verdict = PKT_CACHE_VERDICT_IGNORE_DATA;
+ if (is_cs_store_enabled && is_connection_local) {
+ pkt_cache_update_cs(pkt_cache, msgbuf_pool, entry, msgbuf, msgbuf_id);
+ *verdict = PKT_CACHE_VERDICT_UPDATE_DATA;
+ }
+ return NULL;
+
+ default:
+ ERROR("Invalid packet cache content");
+ return NULL;
+ }
+}
+
+void pkt_cache_on_interest(pkt_cache_t *pkt_cache, msgbuf_pool_t *msgbuf_pool,
+ off_t msgbuf_id, pkt_cache_verdict_t *verdict,
+ off_t *data_msgbuf_id, pkt_cache_entry_t **entry_ptr,
+ const hicn_name_t *name,
+ bool is_serve_from_cs_enabled) {
+ assert(pkt_cache);
+ assert(msgbuf_id_is_valid(msgbuf_id));
+
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+ assert(msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_INTEREST);
+
+ off_t entry_id;
+ pkt_cache_lookup_t lookup_result;
+ pkt_cache_entry_t *entry =
+ pkt_cache_lookup(pkt_cache, name, msgbuf_pool, &lookup_result, &entry_id,
+ is_serve_from_cs_enabled);
+ *entry_ptr = entry;
+
+ cs_entry_t *cs_entry = NULL;
+ bool is_cs_miss = true;
+ bool is_aggregated;
+ switch (lookup_result) {
+ case PKT_CACHE_LU_NONE:
+ entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, name);
+ *entry_ptr = entry;
+
+ *verdict = PKT_CACHE_VERDICT_FORWARD_INTEREST;
+ break;
+
+ case PKT_CACHE_LU_DATA_NOT_EXPIRED:
+ if (!is_serve_from_cs_enabled) goto PKT_CACHE_LU_DATA_EXPIRED;
+
+ cs_entry = &entry->u.cs_entry;
+ *data_msgbuf_id = cs_entry->msgbuf_id;
+
+ *verdict = PKT_CACHE_VERDICT_FORWARD_DATA;
+ is_cs_miss = false;
+ break;
+
+ case PKT_CACHE_LU_INTEREST_NOT_EXPIRED:
+ is_aggregated =
+ pkt_cache_try_aggregate_in_pit(pkt_cache, entry, msgbuf, name);
+
+ *verdict = is_aggregated ? PKT_CACHE_VERDICT_AGGREGATE_INTEREST
+ : PKT_CACHE_VERDICT_RETRANSMIT_INTEREST;
+ break;
+
+ case PKT_CACHE_LU_INTEREST_EXPIRED:
+ pkt_cache_update_pit(pkt_cache, entry, msgbuf);
+
+ *verdict = PKT_CACHE_VERDICT_INTEREST_EXPIRED_FORWARD_INTEREST;
+ break;
+
+ case PKT_CACHE_LU_DATA_EXPIRED:
+ PKT_CACHE_LU_DATA_EXPIRED:
+ pkt_cache_cs_to_pit(pkt_cache, entry, msgbuf_pool, msgbuf, msgbuf_id,
+ entry_id);
+
+ *verdict = PKT_CACHE_VERDICT_DATA_EXPIRED_FORWARD_INTEREST;
+ break;
+
+ default:
+ *verdict = PKT_CACHE_VERDICT_ERROR;
+ }
+ is_cs_miss ? cs_miss(pkt_cache->cs) : cs_hit(pkt_cache->cs);
+}
+
+void pkt_cache_cs_clear(pkt_cache_t *pkt_cache) {
+ assert(pkt_cache);
+
+ kh_pkt_cache_suffix_t *v_suffixes;
+ u32 k_suffix;
+ u32 v_pkt_cache_entry_id;
+ kh_foreach_value(pkt_cache->prefix_to_suffixes, v_suffixes, {
+ kh_foreach(v_suffixes, k_suffix, v_pkt_cache_entry_id, {
+ pkt_cache_entry_t *entry = pkt_cache_at(pkt_cache, v_pkt_cache_entry_id);
+ if (entry->entry_type == PKT_CACHE_CS_TYPE) {
+ // Remove from hash table
+ khiter_t k = kh_get_pkt_cache_suffix(v_suffixes, k_suffix);
+ assert(k != kh_end(v_suffixes));
+ kh_del_pkt_cache_suffix(v_suffixes, k);
+
+ // Remove from pool
+ pool_put(pkt_cache->entries, entry);
+ }
+ });
+ });
+
+ // Reset cached prefix
+ pkt_cache->cached_prefix = HICN_NAME_PREFIX_EMPTY;
+ pkt_cache->cached_suffixes = NULL;
+
+ // Re-create CS
+ cs_clear(pkt_cache->cs);
+}
+
+size_t pkt_cache_get_num_cs_stale_entries(pkt_cache_t *pkt_cache) {
+ size_t num_stale_entries = 0;
+ Ticks now = ticks_now();
+ pkt_cache_entry_t *entry;
+
+ pool_foreach(pkt_cache->entries, entry, {
+ if (entry->entry_type == PKT_CACHE_CS_TYPE && entry->has_expire_ts &&
+ now >= entry->expire_ts) {
+ num_stale_entries++;
+ }
+ });
+
+ return num_stale_entries;
+}
+
+int pkt_cache_set_cs_size(pkt_cache_t *pkt_cache, size_t size) {
+ if (pkt_cache->cs->num_entries > size) return -1;
+
+ pkt_cache->cs->max_size = size;
+ return 0;
+}
+
+size_t pkt_cache_get_size(pkt_cache_t *pkt_cache) {
+ return pool_len(pkt_cache->entries);
+}
+
+size_t pkt_cache_get_cs_size(pkt_cache_t *pkt_cache) {
+ return pkt_cache->cs->num_entries;
+}
+
+size_t pkt_cache_get_pit_size(pkt_cache_t *pkt_cache) {
+ uint64_t pkt_cache_size = pkt_cache_get_size(pkt_cache);
+ uint64_t pit_size = pkt_cache_size - pkt_cache_get_cs_size(pkt_cache);
+ return pit_size;
+}
+
+void pkt_cache_log(pkt_cache_t *pkt_cache) {
+ DEBUG("Packet cache: total size = %lu, PIT size = %lu, CS size = %u",
+ pkt_cache_get_size(pkt_cache), pkt_cache_get_pit_size(pkt_cache),
+ pkt_cache_get_cs_size(pkt_cache));
+
+ cs_log(pkt_cache->cs);
+}
+
+pkt_cache_stats_t pkt_cache_get_stats(pkt_cache_t *pkt_cache) {
+ cs_lru_stats_t lru_stats = cs_get_lru_stats(pkt_cache_get_cs(pkt_cache));
+ pkt_cache_stats_t stats = {
+ .n_pit_entries = (uint32_t)pkt_cache_get_pit_size(pkt_cache),
+ .n_cs_entries = (uint32_t)pkt_cache_get_cs_size(pkt_cache),
+ .n_lru_evictions = (uint32_t)lru_stats.countLruEvictions,
+ };
+
+ return stats;
+}
diff --git a/hicn-light/src/hicn/core/packet_cache.h b/hicn-light/src/hicn/core/packet_cache.h
new file mode 100644
index 000000000..1abdc57c2
--- /dev/null
+++ b/hicn-light/src/hicn/core/packet_cache.h
@@ -0,0 +1,502 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file packet_cache.h
+ * \brief hICN packet cache
+ *
+ * The packet cache is a data structure that merges together the PIT and the CS,
+ * to which it holds a reference.
+ * It contains PIT and CS entries, indexed in a two-level hash table.
+ *
+ * Each entry has shared fields, e.g. entry type (PIT or CS) and timestamps,
+ * which are used by both PIT and CS entries. In addition, a C union holds
+ * the PIT or CS specific fields.
+ *
+ * Having a single entry that can hold PIT or CS entries allows to reduce
+ * the number of lookups.
+ *
+ * A prefix hash table <prefix, suffix_hashtable> stores the suffixes associated
+ * to each prefix, where each value in the map points to a separate hash
+ * table <suffix, packet_cache_reference> that can be used to retrieved the
+ * packet cache entry.
+ * When an interest/data packet is received, the prefix and the associated
+ * suffixes are saved; if the next packet cache operation involves the same
+ * prefix, no additional lookups in the prefix hash hashtable are needed.
+ */
+
+#ifndef HICNLIGHT_PACKET_CACHE_H
+#define HICNLIGHT_PACKET_CACHE_H
+
+#include <hicn/util/khash.h>
+#include <hicn/util/slab.h>
+#include "content_store.h"
+#include "pit.h"
+#include "msgbuf_pool.h"
+#include "../content_store/lru.h"
+
+#define DEFAULT_PKT_CACHE_SIZE 2048
+
+typedef enum { PKT_CACHE_PIT_TYPE, PKT_CACHE_CS_TYPE } pkt_cache_entry_type_t;
+
+#define foreach_kh_verdict \
+ _(FORWARD_INTEREST) \
+ _(AGGREGATE_INTEREST) \
+ _(RETRANSMIT_INTEREST) \
+ _(FORWARD_DATA) \
+ _(INTEREST_EXPIRED_FORWARD_INTEREST) \
+ _(DATA_EXPIRED_FORWARD_INTEREST) \
+ _(STORE_DATA) \
+ _(CLEAR_DATA) \
+ _(UPDATE_DATA) \
+ _(IGNORE_DATA) \
+ _(ERROR)
+
+typedef enum {
+#define _(x) PKT_CACHE_VERDICT_##x,
+ foreach_kh_verdict
+#undef _
+} pkt_cache_verdict_t;
+
+extern const char *_pkt_cache_verdict_str[];
+
+#define pkt_cache_verdict_str(x) _pkt_cache_verdict_str[x]
+
+#define foreach_kh_lookup \
+ _(INTEREST_NOT_EXPIRED) \
+ _(INTEREST_EXPIRED) \
+ _(DATA_NOT_EXPIRED) \
+ _(DATA_EXPIRED) \
+ _(NONE)
+
+typedef enum {
+#define _(x) PKT_CACHE_LU_##x,
+ foreach_kh_lookup
+#undef _
+} pkt_cache_lookup_t;
+
+KHASH_MAP_INIT_INT(pkt_cache_suffix, unsigned);
+KHASH_INIT(pkt_cache_prefix, const hicn_name_prefix_t *,
+ kh_pkt_cache_suffix_t *, 1, hicn_name_prefix_get_hash,
+ hicn_name_prefix_equals);
+
+typedef struct {
+ hicn_name_t name;
+ pkt_cache_entry_type_t entry_type;
+
+ Ticks create_ts;
+ Ticks expire_ts;
+ // TODO(eloparco): Is it necessary?
+ // Now it is always set to true
+ bool has_expire_ts;
+
+ union {
+ pit_entry_t pit_entry;
+ cs_entry_t cs_entry;
+ } u;
+} pkt_cache_entry_t;
+
+typedef struct {
+ pit_t *pit;
+ cs_t *cs;
+ pkt_cache_entry_t *entries;
+ kh_pkt_cache_prefix_t *prefix_to_suffixes;
+ slab_t *prefix_keys;
+
+ // Cached prefix info to avoid double lookups,
+ // used for both single interest speculation and interest manifest
+ hicn_name_prefix_t cached_prefix;
+ kh_pkt_cache_suffix_t *cached_suffixes;
+} pkt_cache_t;
+
+/**
+ * @brief Create a new packet cache.
+ *
+ * @return pkt_cache_t* The newly created packet cache
+ */
+pkt_cache_t *pkt_cache_create(size_t cs_size);
+
+/**
+ * @brief Add an entry with the specified name to the packet cache.
+ *
+ * @param[in] pkt_cache Pointer to the pool data structure to use.
+ * @param[in, out] entry Empty entry that will be used to return the
+ * allocated one from the msgbuf pool.
+ * @param[in] name hicn_name_t to use
+ *
+ * NOTE: unlike other pools, PIT and CS entries allocation does not update the
+ * index as the key is a hicn_name_t * which should point to :
+ * - the name inside the PIT entry (which is thus not set during allocation),
+ * - the name inside the msgbuf_t in the CS entry, which is always available
+ * during the lifetime of the cache entry.
+ *
+ * The index is therefore updated in pkt_cache_add_to_pit and
+ * pkt_cache_add_to_cs functions.
+ *
+ *
+ */
+pkt_cache_entry_t *pkt_cache_allocate(pkt_cache_t *pkt_cache);
+
+void pkt_cache_add_to_index(const pkt_cache_t *pkt_cache,
+ const pkt_cache_entry_t *entry);
+
+void pkt_cache_remove_from_index(const pkt_cache_t *pkt_cache,
+ const hicn_name_t *name);
+
+/**
+ * @brief Free a packet cache data structure.
+ *
+ * @param[in] pkt_cache Pointer to packet cache data structure to free.
+ */
+void pkt_cache_free(pkt_cache_t *pkt_cache);
+
+/**
+ * @brief Get a reference to the PIT data structure contained in the packet
+ * cache.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to get the
+ * PIT from.
+ */
+pit_t *pkt_cache_get_pit(pkt_cache_t *pkt_cache);
+
+/**
+ * @brief Get a reference to the CS data structure contained in the packet
+ * cache.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to get the
+ * CS from.
+ */
+cs_t *pkt_cache_get_cs(pkt_cache_t *pkt_cache);
+
+/**
+ * @brief Return the total packet cache size (i.e. PIT + CS).
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ */
+size_t pkt_cache_get_size(pkt_cache_t *pkt_cache);
+
+/**
+ * @brief Return the number of stale entries (i.e. expired) in the CS.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ */
+size_t pkt_cache_get_num_cs_stale_entries(pkt_cache_t *pkt_cache);
+
+/**
+ * @brief Change the maximum capacity of the content store (LRU eviction will
+ * be used after reaching the provided size)
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in] size Maximum size of the content store
+ * @return int 0 if success, -1 if the provided maximum size is smaller than
+ * the number of elements currently stored in the CS
+ */
+int pkt_cache_set_cs_size(pkt_cache_t *pkt_cache, size_t size);
+
+/**
+ * @brief Return the content store size.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ */
+size_t pkt_cache_get_cs_size(pkt_cache_t *pkt_cache);
+
+/**
+ * @brief Return the PIT size.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ */
+size_t pkt_cache_get_pit_size(pkt_cache_t *pkt_cache);
+
+#define pkt_cache_entry_get_create_ts(E) ((E)->create_ts)
+#define pkt_cache_entry_get_expire_ts(E) ((E)->expire_ts)
+#define pkt_cache_entry_set_expire_ts(E, EXPIRY_TIME) \
+ (entry)->expire_ts = EXPIRY_TIME
+#define pkt_cache_get_entry_id(pkt_cache, entry) (entry - pkt_cache->entries)
+#define pkt_cache_entry_at(pkt_cache, id) (&(pkt_cache)->entries[id])
+#define pkt_cache_at(pkt_cache, i) (pkt_cache->entries + i)
+
+/**
+ * @brief Retrieve from the packet cache the entry associated with the
+ * specified name.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to retrieve
+ * the entry from
+ * @param[in] name Packet name to use for the lookup
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use
+ * @param[in, out] lookup_result Pointer to store the result of the lookup
+ * @param[in, out] entry_id Pointer to store the entry_id in case of a lookup
+ * match
+ * @param[in] is_serve_from_cs_enabled Boolean to specify if the forwarder is
+ * allowed to serve contents from the CS
+ * @return pkt_cache_entry_t* Entry retrieved, NULL if none found
+ */
+pkt_cache_entry_t *pkt_cache_lookup(pkt_cache_t *pkt_cache,
+ const hicn_name_t *name,
+ msgbuf_pool_t *msgbuf_pool,
+ pkt_cache_lookup_t *lookup_result,
+ off_t *entry_id,
+ bool is_serve_from_cs_enabled);
+
+/**
+ * @brief Clear the content of the CS (PIT entries are left unmodified).
+ *
+ * @param pkt_cache Pointer to the packet cache data structure to use
+ */
+void pkt_cache_cs_clear(pkt_cache_t *pkt_cache);
+
+/**
+ * @brief Log packet cache statistics.
+ *
+ * @param pkt_cache Pointer to the packet cache data structure to use
+ */
+void pkt_cache_log(pkt_cache_t *pkt_cache);
+
+pkt_cache_stats_t pkt_cache_get_stats(pkt_cache_t *pkt_cache);
+
+// TODO(eloparco): To implement
+void pkt_cache_print(const pkt_cache_t *pkt_cache);
+
+/************** Packet cache entry operations *************/
+
+/**
+ * @brief Remove a content store entry from the packet cache.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in] entry Pointer to the content store entry to remove
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use
+ * @param[in] is_evicted Boolean to specify if the content store entry has
+ * already been evicted from the LRU cache
+ */
+void pkt_cache_cs_remove_entry(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ msgbuf_pool_t *msgbuf_pool, bool is_evicted);
+
+/**
+ * @brief Remove a PIT entry from the packet cache.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in] entry Pointer to the PIT entry to remove
+ */
+void pkt_cache_pit_remove_entry(pkt_cache_t *pkt_cache,
+ pkt_cache_entry_t *entry);
+
+/**
+ * @brief Convert a PIT entry to a CS entry.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in, out] entry Pointer to the PIT entry to replace
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use
+ * @param[in] msgbuf Pointer to the msgbuf associated with the CS entry to
+ * insert
+ * @param[in] msgbuf_id Msgbuf ID (i.e. ID in the msgbuf pool) associated with
+ * the CS entry to insert
+ * @param[in] entry_id Entry ID (i.e. ID in the packet cache pool of entries)
+ * associated with the PIT entry to replace
+ */
+void pkt_cache_pit_to_cs(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ msgbuf_pool_t *msgbuf_pool, msgbuf_t *msgbuf,
+ off_t msgbuf_id, off_t entry_id);
+
+/**
+ * @brief Convert a CS entry to a PIT entry.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in, out] entry Pointer to the CS entry to replace
+ * @param[in] msgbuf Pointer to the msgbuf associated with the PIT entry to
+ * insert
+ * @param[in] msgbuf_id Msgbuf ID (i.e. ID in the msgbuf pool) associated with
+ * the PIT entry to insert
+ * @param[in] entry_id Entry ID (i.e. ID in the packet cache pool of entries)
+ * associated with the CS entry to replace
+ */
+void pkt_cache_cs_to_pit(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ msgbuf_pool_t *msgbuf_pool, const msgbuf_t *msgbuf,
+ off_t msgbuf_id, off_t entry_id);
+
+/**
+ * @brief Add PIT entry to the packet cache.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in] msgbuf Pointer to the msgbuf associated with the PIT entry to
+ * insert
+ * @param[in] name Interest name to use; in case of aggregated interests, it is
+ * different from the name stored in the msgbuf
+ * @return pkt_cache_entry_t* Pointer to the packet cache (PIT) entry created
+ */
+pkt_cache_entry_t *pkt_cache_add_to_pit(pkt_cache_t *pkt_cache,
+ const msgbuf_t *msgbuf,
+ const hicn_name_t *name);
+
+/**
+ * @brief Add CS entry to the packet cache.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use
+ * @param[in] msgbuf Pointer to the msgbuf associated with the CS entry to
+ * insert
+ * @param[in] msgbuf_id Msgbuf ID (i.e. ID in the msgbuf pool) associated with
+ * the CS entry to insert
+ * @return pkt_cache_entry_t* Pointer to the packet cache (CS) entry created
+ */
+pkt_cache_entry_t *pkt_cache_add_to_cs(pkt_cache_t *pkt_cache,
+ msgbuf_pool_t *msgbuf_pool,
+ msgbuf_t *msgbuf, off_t msgbuf_id);
+
+/**
+ * @brief Update PIT entry in the packet cache in case of an expired PIT
+ * entry.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in, out] entry Pointer to the PIT entry to update
+ * @param[in] msgbuf Pointer to the msgbuf associated with the PIT entry to
+ * update
+ */
+void pkt_cache_update_pit(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry,
+ const msgbuf_t *msgbuf);
+
+/**
+ * @brief Update CS entry in the packet cache.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in] msgbuf_pool Pointer to the msgbuf pool data structure to use
+ * @param[in, out] entry Pointer to the CS entry to update
+ * @param[in] msgbuf Pointer to the msgbuf associated with the CS entry to
+ * update
+ * @param msgbuf_id Msgbuf ID (i.e. ID in the msgbuf pool) associated with the
+ * CS entry to update
+ */
+void pkt_cache_update_cs(pkt_cache_t *pkt_cache, msgbuf_pool_t *msgbuf_pool,
+ pkt_cache_entry_t *entry, msgbuf_t *msgbuf,
+ off_t msgbuf_id);
+
+/**
+ * @brief Update PIT entry in the packet cache in case of retransmission or
+ * aggregation.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in, out] entry Pointer to the PIT entry to update
+ * @param[in] msgbuf Pointer to the msgbuf associated with the PIT entry to
+ * update
+ * @param[in] name Interest name to use; in case of aggregated interests, it is
+ * different from the name stored in the msgbuf
+ * @return true If aggregation (interest sent from a connection not stored in
+ * the PIT entry)
+ * @return false If retransmission (interest sent from a connection already
+ * stored in the PIT entry)
+ */
+bool pkt_cache_try_aggregate_in_pit(pkt_cache_t *pkt_cache,
+ pkt_cache_entry_t *entry,
+ const msgbuf_t *msgbuf,
+ const hicn_name_t *name);
+
+/**
+ * @brief Cache prefix info (prefix + associated suffixes) to speed up lookups.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ * @param[in] prefix Name prefix to cache
+ */
+void pkt_cache_save_suffixes_for_prefix(pkt_cache_t *pkt_cache,
+ const hicn_name_prefix_t *prefix);
+
+/**
+ * @brief Reset cached prefix info to force double lookups.
+ *
+ * @param[in] pkt_cache Pointer to the packet cache data structure to use
+ */
+void pkt_cache_reset_suffixes_for_prefix(pkt_cache_t *pkt_cache);
+
+/************ Handle data/interest packets received *******/
+
+/**
+ * @brief Handle data packet reception.
+ * @details Perform packet cache lookup and execute operations based on it.
+ * If:
+ * - INTEREST not expired: Convert PIT entry to CS entry; return the
+ * nexthops (that can be used to forward the data
+ * packet now stored in the CS)
+ * - INTEREST expired: Convert PIT entry to CS entry
+ * - DATA expired/not expired: Update the CS
+ * - No match: Add data packet to CS
+ */
+nexthops_t *pkt_cache_on_data(pkt_cache_t *pkt_cache,
+ msgbuf_pool_t *msgbuf_pool, off_t msgbuf_id,
+ bool is_cs_store_enabled,
+ bool is_connection_local, bool *wrong_egress,
+ pkt_cache_verdict_t *verdict);
+
+/**
+ * @brief Handle interest packet reception.
+ * @details Perform packet cache lookup and execute operations based on it.
+ * If:
+ * - No match: Do nothing
+ * - DATA not expired: get data message from CS
+ * - INTEREST not expired: Aggregate or retransmit the interest received;
+ * - INTEREST expired: Update the PIT;
+ * - DATA expired: Convert CS entry to PIT entry;
+ */
+void pkt_cache_on_interest(pkt_cache_t *pkt_cache, msgbuf_pool_t *msgbuf_pool,
+ off_t msgbuf_id, pkt_cache_verdict_t *verdict,
+ off_t *data_msgbuf_id, pkt_cache_entry_t **entry_ptr,
+ const hicn_name_t *name,
+ bool is_serve_from_cs_enabled);
+
+/********* Low-level operations on the hash table *********/
+#ifdef WITH_TESTS
+unsigned __get_suffix(kh_pkt_cache_suffix_t *suffixes,
+ hicn_name_suffix_t suffix);
+unsigned _get_suffix(kh_pkt_cache_prefix_t *prefixes,
+ const hicn_name_prefix_t *prefix,
+ hicn_name_suffix_t suffix, slab_t *prefix_keys);
+void __add_suffix(kh_pkt_cache_suffix_t *suffixes, hicn_name_suffix_t suffix,
+ unsigned val);
+void _add_suffix(kh_pkt_cache_prefix_t *prefixes,
+ const hicn_name_prefix_t *prefix,
+ const hicn_name_suffix_t suffix, unsigned val, slab_t *slab);
+void _remove_suffix(kh_pkt_cache_prefix_t *prefixes,
+ const hicn_name_prefix_t *prefix, hicn_name_suffix_t suffix,
+ slab_t *slab);
+void _prefix_map_free(kh_pkt_cache_prefix_t *prefix_to_suffixes);
+kh_pkt_cache_suffix_t *_get_suffixes(kh_pkt_cache_prefix_t *prefix_to_suffixes,
+ const hicn_name_prefix_t *prefix,
+ bool create, slab_t *prefix_keys);
+#endif
+
+/************** Content Store *****************************/
+
+typedef struct {
+ const char *name;
+ void (*initialize)(cs_t *cs);
+ void (*finalize)(cs_t *cs);
+ int (*add_entry)(pkt_cache_t *pkt_cache, off_t entry_id);
+ void (*update_entry)(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry);
+ int (*remove_entry)(pkt_cache_t *pkt_cache, pkt_cache_entry_t *entry);
+} cs_ops_t;
+extern const cs_ops_t *const cs_vft[];
+
+/**
+ * @brief Initialize the virtual function table used for the
+ * CS cache strategy (e.g. LRU).
+ *
+ */
+#define DECLARE_CS(NAME) \
+ const cs_ops_t cs_##NAME = { \
+ .name = #NAME, \
+ .initialize = cs_##NAME##_initialize, \
+ .finalize = cs_##NAME##_finalize, \
+ .add_entry = cs_##NAME##_add_entry, \
+ .update_entry = cs_##NAME##_update_entry, \
+ .remove_entry = cs_##NAME##_remove_entry, \
+ }
+
+#endif /* HICNLIGHT_PACKET_CACHE_H */
diff --git a/hicn-light/src/hicn/core/pit.c b/hicn-light/src/hicn/core/pit.c
new file mode 100644
index 000000000..322e53674
--- /dev/null
+++ b/hicn-light/src/hicn/core/pit.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The pending interest table.
+ *
+ * Interest aggregation strategy:
+ * - The first Interest for a name is forwarded
+ * - A second Interest for a name from a different reverse path may be
+ * aggregated
+ * - A second Interest for a name from an existing Interest is forwarded
+ * - The Interest Lifetime is like a subscription time. A reverse path entry is
+ * removed once the lifetime is exceeded.
+ * - Whan an Interest arrives or is aggregated, the Lifetime for that reverse
+ * hop is extended. As a simplification, we only keep a single lifetime not per
+ * reverse hop.
+ *
+ */
+
+#include "pit.h"
+
+Ticks pit_calculate_lifetime(pit_t* pit, const msgbuf_t* msgbuf) {
+ uint64_t lifetime = msgbuf_get_lifetime(msgbuf);
+ if (lifetime == 0) lifetime = NSEC_TO_TICKS(DEFAULT_INTEREST_LIFETIME);
+
+ return ticks_now() + lifetime;
+}
+
+/* This is only used as a hint for first allocation, as the table is resizeable
+ */
+#define DEFAULT_PIT_SIZE 65535
+
+pit_t* _pit_create(size_t init_size, size_t max_size) {
+ pit_t* pit = malloc(sizeof(pit_t));
+ if (!pit) return NULL;
+
+ if (init_size == 0) init_size = DEFAULT_PIT_SIZE;
+
+ pit->max_size = max_size;
+ return pit;
+}
+
+void pit_free(pit_t* pit) {
+ assert(pit);
+ free(pit);
+}
+
+// void pit_print(const pit_t *pit) {
+// const Name *k;
+// unsigned v;
+// pit_entry_t * entry;
+// Ticks expire_ts;
+
+// printf("*** PIT ***\n");
+// kh_foreach(pit->index_by_name, k, v, {
+// char *name_str = name_ToString(k);
+// entry = pit_at(pit, v);
+// expire_ts = pit_entry_get_expire_ts(entry);
+// printf("%s\t\t\texpire=%lu\n", name_str, expire_ts);
+// free(name_str);
+// })
+// }
diff --git a/hicn-light/src/hicn/core/pit.h b/hicn-light/src/hicn/core/pit.h
new file mode 100644
index 000000000..f2e901490
--- /dev/null
+++ b/hicn-light/src/hicn/core/pit.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file pit.h
+ * @brief hICN Pending Interest Table (PIT)
+ */
+
+#ifndef HICNLIGHT_PIT_H
+#define HICNLIGHT_PIT_H
+
+#include <hicn/core/fib.h>
+
+typedef struct {
+ nexthops_t ingressIdSet;
+ nexthops_t egressIdSet;
+ fib_entry_t* fib_entry;
+} pit_entry_t;
+
+#define pit_entry_get_ingress(E) (&((E)->ingressIdSet))
+#define pit_entry_get_egress(E) (&((E)->egressIdSet))
+#define pit_entry_get_fib_entry(E) ((E)->fib_entry)
+#define pit_entry_set_fib_entry(E, FIB_ENTRY) ((E)->fib_entry = FIB_ENTRY)
+
+#define pit_entry_ingress_add(E, NH) \
+ nexthops_add(pit_entry_get_ingress(E), (NH))
+
+#define pit_entry_ingress_contains(E, NH) \
+ nexthops_contains(pit_entry_get_ingress(E), (NH))
+
+#define pit_entry_egress_add(E, NH) nexthops_add(pit_entry_get_egress(E), (NH))
+
+typedef struct {
+ // TODO(eloparco): How to handle PIT size?
+ size_t max_size;
+} pit_t;
+
+#define DEFAULT_INTEREST_LIFETIME 4000000000ULL
+
+Ticks pit_calculate_lifetime(pit_t* pit, const msgbuf_t* msgbuf);
+
+/**
+ * @brief Allocate a new PIT data structure (extended parameters)
+ *
+ * @param init_size Initial size (0 = default)
+ * @param max_size Maximum size (0 = unbounded)
+ *
+ * @return pit_t* Newly allocated PIT data structure
+ */
+pit_t* _pit_create(size_t init_size, size_t max_size);
+
+/**
+ * @brief Allocate a new PIT data structure
+ *
+ * @return pit_t* Newly allocated PIT data structure
+ */
+#define pit_create() _pit_create(0, 0)
+
+void pit_free(pit_t* pit);
+
+#endif /* HICNLIGHT_PIT_H */
diff --git a/hicn-light/src/hicn/core/policy_stats.c b/hicn-light/src/hicn/core/policy_stats.c
new file mode 100644
index 000000000..8706a9244
--- /dev/null
+++ b/hicn-light/src/hicn/core/policy_stats.c
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifdef WITH_POLICY_STATS
+
+// This has to be included first because of _GNU_SOURCE
+#include <hicn/core/forwarder.h>
+
+#include <hicn/core/connection_table.h>
+#include <hicn/base/loop.h>
+#include <hicn/util/log.h>
+#include <hicn/core/ticks.h>
+#include <hicn/policy.h>
+#include <hicn/core/fib.h>
+
+#include "policy_stats.h"
+
+#define ALPHA 0.9
+#define STATS_INTERVAL 1000 /* ms */
+
+static int policy_stats_mgr_tick(void* mgr_arg, int fd, unsigned id,
+ void* data) {
+ policy_stats_mgr_t* mgr = mgr_arg;
+ assert(mgr);
+ assert(id == 0);
+ assert(!data);
+
+ uint64_t now = ticks_now();
+
+ /* Loop over FIB entries to compute statistics from counters */
+ const fib_t* fib = forwarder_get_fib(mgr->forwarder);
+
+ fib_foreach_entry(fib, entry, {
+ policy_stats_update(&entry->policy_stats, &entry->policy_counters, now);
+ });
+
+ return 0;
+}
+
+int policy_stats_mgr_initialize(policy_stats_mgr_t* mgr, void* forwarder) {
+ mgr->forwarder = forwarder;
+
+ loop_timer_create(&mgr->timer, MAIN_LOOP, mgr, policy_stats_mgr_tick, NULL);
+ if (!mgr->timer) {
+ ERROR("Error allocating prefix stats mgr timer.");
+ return -1;
+ }
+
+ if (loop_timer_register(mgr->timer, STATS_INTERVAL) < 0) {
+ ERROR("Error registering prefix stats mgr timer.");
+ return -1;
+ }
+
+ return 0;
+}
+
+void policy_stats_mgr_finalize(policy_stats_mgr_t* mgr) {
+ loop_event_unregister(mgr->timer);
+ loop_event_free(mgr->timer);
+}
+
+void policy_stats_on_retransmission(const policy_stats_mgr_t* mgr,
+ policy_counters_t* counters,
+ const nexthops_t* nexthops) {
+ connection_table_t* table = forwarder_get_connection_table(mgr->forwarder);
+ nexthops_foreach(nexthops, nexthop, {
+#ifdef WITH_POLICY
+ const connection_t* conn = connection_table_at(table, nexthop);
+
+ if (connection_has_tag(conn, POLICY_TAG_WIRED))
+ counters->wired.num_losses++;
+ if (connection_has_tag(conn, POLICY_TAG_WIFI)) counters->wifi.num_losses++;
+ if (connection_has_tag(conn, POLICY_TAG_CELLULAR))
+ counters->cellular.num_losses++;
+#endif /* WITH_POLICY */
+ counters->all.num_losses++;
+ });
+}
+
+#define UPDATE_TAG_STATS(TAG, NAME) \
+ do { \
+ if (connection_has_tag(conn, TAG)) { \
+ counters->NAME.num_packets++; \
+ counters->NAME.num_bytes += msg_size; \
+ stats->NAME.latency = \
+ ALPHA * stats->NAME.latency + (1 - ALPHA) * (double)rtt; \
+ counters->NAME.latency_idle = 0; \
+ } \
+ } while (0)
+
+/* Update statistic counters upon Data packet reception */
+void policy_stats_on_data(const policy_stats_mgr_t* mgr, policy_stats_t* stats,
+ policy_counters_t* counters,
+ const nexthops_t* nexthops, const msgbuf_t* msgbuf,
+ Ticks rtt) {
+#ifdef WITH_POLICY
+ forwarder_t* forwarder = mgr->forwarder;
+ connection_table_t* table = forwarder_get_connection_table(forwarder);
+#endif /* WITH_POLICY */
+
+ size_t msg_size = msgbuf_get_len(msgbuf);
+
+ nexthops_foreach(nexthops, nexthop, {
+#ifdef WITH_POLICY
+ const connection_t* conn = connection_table_at(table, nexthop);
+ if (!conn) continue;
+
+ UPDATE_TAG_STATS(POLICY_TAG_WIRED, wired);
+ UPDATE_TAG_STATS(POLICY_TAG_WIFI, wifi);
+ UPDATE_TAG_STATS(POLICY_TAG_CELLULAR, cellular);
+#endif /* WITH_POLICY */
+ });
+
+ stats->all.latency = ALPHA * stats->all.latency + (1 - ALPHA) * (double)rtt;
+ counters->all.latency_idle = 0;
+ counters->all.num_packets++;
+ counters->all.num_bytes += msg_size;
+}
+
+void policy_stats_on_timeout(const policy_stats_mgr_t* mgr,
+ policy_counters_t* counters,
+ const nexthops_t* nexthops) {
+#ifdef WITH_POLICY
+ connection_table_t* table = forwarder_get_connection_table(mgr->forwarder);
+
+ nexthops_foreach(nexthops, nexthop, {
+ const connection_t* conn = connection_table_at(table, nexthop);
+ if (!conn) continue;
+ if (connection_has_tag(conn, POLICY_TAG_WIRED))
+ counters->wired.num_losses++;
+ if (connection_has_tag(conn, POLICY_TAG_WIFI)) counters->wifi.num_losses++;
+ if (connection_has_tag(conn, POLICY_TAG_CELLULAR))
+ counters->cellular.num_losses++;
+ });
+#endif /* WITH_POLICY */
+
+ counters->all.num_losses++;
+}
+
+#define UPDATE_TYPE(TYPE) \
+ do { \
+ /* (a) throughput */ \
+ if (counters->TYPE.num_bytes > 0) { \
+ throughput = counters->TYPE.num_bytes / (now - counters->last_update); \
+ throughput = throughput * 8 / 1024; \
+ if (throughput < 0) throughput = 0; \
+ } else { \
+ throughput = 0; \
+ } \
+ stats->TYPE.throughput = \
+ ALPHA * stats->TYPE.throughput + (1 - ALPHA) * throughput; \
+ \
+ /* (b) loss rate */ \
+ if ((counters->TYPE.num_losses > 0) && (counters->TYPE.num_packets > 0)) { \
+ loss_rate = counters->TYPE.num_losses / counters->TYPE.num_packets; \
+ loss_rate *= 100; \
+ } else { \
+ loss_rate = 0; \
+ } \
+ stats->TYPE.loss_rate = \
+ ALPHA * stats->TYPE.loss_rate + (1 - ALPHA) * loss_rate; \
+ \
+ /* (c) latency */ \
+ counters->TYPE.latency_idle++; \
+ if (counters->TYPE.latency_idle > 1) stats->TYPE.latency = 0; \
+ \
+ /* (d) Reset counters */ \
+ counters->TYPE.num_bytes = 0; \
+ counters->TYPE.num_losses = 0; \
+ counters->TYPE.num_packets = 0; \
+ } while (0)
+
+void policy_stats_update(policy_stats_t* stats, policy_counters_t* counters,
+ uint64_t now) {
+ double throughput;
+ double loss_rate;
+
+ if (now == counters->last_update) return;
+
+#ifdef WITH_POLICY
+ UPDATE_TYPE(wired);
+ UPDATE_TYPE(wifi);
+ UPDATE_TYPE(cellular);
+#endif /* WITH_POLICY */
+ UPDATE_TYPE(all);
+
+ counters->last_update = now;
+}
+
+#endif /* WITH_POLICY_STATS */
diff --git a/hicn-light/src/hicn/core/policy_stats.h b/hicn-light/src/hicn/core/policy_stats.h
new file mode 100644
index 000000000..aee68e515
--- /dev/null
+++ b/hicn-light/src/hicn/core/policy_stats.h
@@ -0,0 +1,92 @@
+
+#ifndef HICNLIGHT_POLICY_STATS_H
+#define HICNLIGHT_POLICY_STATS_H
+
+#ifdef WITH_POLICY_STATS
+
+#include <hicn/policy.h>
+
+typedef struct policy_stats_mgr_s {
+ void* forwarder;
+ event_t* timer;
+} policy_stats_mgr_t;
+
+#if 0
+
+/* PER-INTERFACE POLICY STATS */
+
+typedef struct {
+ float throughput;
+ float latency;
+ float loss_rate;
+} interface_stats_t;
+
+/* POLICY STATS */
+
+typedef struct {
+ interface_stats_t wired;
+ interface_stats_t wifi;
+ interface_stats_t cellular;
+ interface_stats_t all;
+} policy_stats_t;
+
+typedef struct {
+ uint32_t num_packets;
+ uint32_t num_bytes;
+ uint32_t num_losses;
+ uint32_t latency_idle;
+} interface_counters_t;
+
+typedef struct {
+ interface_counters_t wired;
+ interface_counters_t wifi;
+ interface_counters_t cellular;
+ interface_counters_t all;
+ uint64_t last_update;
+} policy_counters_t;
+
+#define INTERFACE_STATS_EMPTY \
+ (interface_stats_t) { .throughput = 0, .latency = 0, .loss_rate = 0, }
+
+#define POLICY_STATS_EMPTY \
+ (policy_stats_t) { \
+ .wired = INTERFACE_STATS_EMPTY, .wifi = INTERFACE_STATS_EMPTY, \
+ .cellular = INTERFACE_STATS_EMPTY, .all = INTERFACE_STATS_EMPTY, \
+ }
+
+#define INTERFACE_COUNTERS_EMPTY \
+ (interface_counters_t) { \
+ .num_packets = 0, .num_bytes = 0, .num_losses = 0, .latency_idle = 0, \
+ }
+
+#define POLICY_COUNTERS_EMPTY \
+ (policy_counters_t) { \
+ .wired = INTERFACE_COUNTERS_EMPTY, .wifi = INTERFACE_COUNTERS_EMPTY, \
+ .cellular = INTERFACE_COUNTERS_EMPTY, .all = INTERFACE_COUNTERS_EMPTY, \
+ .last_update = 0, \
+ }
+#endif
+
+int policy_stats_mgr_initialize(policy_stats_mgr_t* mgr, void* forwarder);
+
+void policy_stats_mgr_finalize(policy_stats_mgr_t* mgr);
+
+void policy_stats_on_retransmission(const policy_stats_mgr_t* mgr,
+ policy_counters_t* countrs,
+ const nexthops_t* nexthops);
+
+void policy_stats_on_data(const policy_stats_mgr_t* mgr, policy_stats_t* stats,
+ policy_counters_t* counters,
+ const nexthops_t* nexthops, const msgbuf_t* msgbuf,
+ Ticks rtt);
+
+void policy_stats_on_timeout(const policy_stats_mgr_t* mgr,
+ policy_counters_t* counters,
+ const nexthops_t* nexthops);
+
+void policy_stats_update(policy_stats_t* stats, policy_counters_t* counters,
+ uint64_t now);
+
+#endif /* WITH_POLICY_STATS */
+
+#endif /* HICNLIGHT_POLICY_STATS_H */
diff --git a/hicn-light/src/hicn/core/strategy.c b/hicn-light/src/hicn/core/strategy.c
new file mode 100644
index 000000000..46c83ef02
--- /dev/null
+++ b/hicn-light/src/hicn/core/strategy.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file strategy.c
+ * \brief Implementation of hICN forwarding strategy
+ */
+
+#include "nexthops.h"
+#include "strategy.h"
+#include "strategy_vft.h"
+
+int strategy_initialize(strategy_entry_t *entry, const void *forwarder) {
+ return strategy_vft[entry->type]->initialize(entry, forwarder);
+}
+
+int strategy_finalize(strategy_entry_t *entry) {
+ return strategy_vft[entry->type]->finalize(entry);
+}
+
+nexthops_t *strategy_lookup_nexthops(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const msgbuf_t *msgbuf) {
+ return strategy_vft[entry->type]->lookup_nexthops(entry, nexthops, msgbuf);
+}
+
+int strategy_add_nexthop(strategy_entry_t *entry, nexthops_t *nexthops,
+ off_t offset) {
+ return strategy_vft[entry->type]->add_nexthop(entry, nexthops, offset);
+}
+
+int strategy_remove_nexthop(strategy_entry_t *entry, nexthops_t *nexthops,
+ off_t offset) {
+ return strategy_vft[entry->type]->remove_nexthop(entry, nexthops, offset);
+}
+
+int strategy_on_data(strategy_entry_t *entry, nexthops_t *nexthops,
+ const nexthops_t *data_nexthops, const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation, Ticks objReception) {
+ return strategy_vft[entry->type]->on_data(
+ entry, nexthops, data_nexthops, msgbuf, pitEntryCreation, objReception);
+}
+
+int strategy_on_timeout(strategy_entry_t *entry, nexthops_t *nexthops,
+ const nexthops_t *timeout_nexthops) {
+ return strategy_vft[entry->type]->on_timeout(entry, nexthops,
+ timeout_nexthops);
+}
diff --git a/hicn-light/src/hicn/core/strategy.h b/hicn-light/src/hicn/core/strategy.h
new file mode 100644
index 000000000..9f1a7dac7
--- /dev/null
+++ b/hicn-light/src/hicn/core/strategy.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file strategy.h
+ * \brief hICN forwarding strategy
+ */
+#ifndef HICNLIGHT_STRATEGY_H
+#define HICNLIGHT_STRATEGY_H
+
+/*
+ * Forwarding strategy
+ *
+ * The forwarding strategy decides to elect one or several next hops among those
+ * available in the FIB entry, after an eventual application of the policy. This
+ * means it should be aware of the different flags set in the nexthops_t data
+ * structure by previous forwarding steps, that might have excluded certain
+ * nexthops.
+ *
+ * A strategy is defined by its type and comes with :
+ * - options, initialized at setup and that might eventually be updated (this
+ * is allowed on a per-strategy basis.
+ * - a state (eventually) empty, that is used to inform its decisions, and
+ * might be updated for each interest sent (lookup_nexthops), data received
+ * (on_data) or timeout event (on_timeout).
+ *
+ * All this information (type, options, state) is made available through a
+ * strategy_entry_t which is stored together with nexthops in the FIB entry.
+ *
+ * Per-nexthop strategy informaton is stored in the nexthops table itself. As it
+ * would be difficult and suboptimal to provide a correct strategy-dependent
+ * initialization in the FIB nad nexthops data structures, it is thus the
+ * responsibility of the forwarding strategy to initialize its state and nexthop
+ * related state when appropriate (eg. at initialization, or when a nexthop is
+ * added).
+ */
+
+#include "nexthops.h"
+#include "strategy_vft.h"
+
+typedef struct strategy_entry_s {
+ const void *forwarder;
+ strategy_type_t type;
+ strategy_options_t options;
+ strategy_state_t state;
+} strategy_entry_t;
+
+int strategy_initialize(strategy_entry_t *entry, const void *forwarder);
+
+int strategy_finalize(strategy_entry_t *entry);
+
+nexthops_t *strategy_lookup_nexthops(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const msgbuf_t *msgbuf);
+
+int strategy_add_nexthop(strategy_entry_t *entry, nexthops_t *nexthops,
+ off_t offset);
+
+int strategy_remove_nexthop(strategy_entry_t *entry, nexthops_t *nexthops,
+ off_t offset);
+
+int strategy_on_data(strategy_entry_t *entry, nexthops_t *nexthops,
+ const nexthops_t *data_nexthops, const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation, Ticks objReception);
+
+int strategy_on_timeout(strategy_entry_t *entry, nexthops_t *nexthops,
+ const nexthops_t *timeout_nexthops);
+
+#endif /* HICNLIGHT_STRATEGY_H */
diff --git a/hicn-light/src/hicn/core/strategy_vft.c b/hicn-light/src/hicn/core/strategy_vft.c
new file mode 100644
index 000000000..0af035c88
--- /dev/null
+++ b/hicn-light/src/hicn/core/strategy_vft.c
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file strategy_vft.c
+ * \brief Implementation of hICN forwarding strategy VFT
+ */
+
+#include "strategy_vft.h"
+
+extern const strategy_ops_t strategy_load_balancer;
+extern const strategy_ops_t strategy_random;
+extern const strategy_ops_t strategy_replication;
+extern const strategy_ops_t strategy_bestpath;
+extern const strategy_ops_t strategy_low_latency;
+extern const strategy_ops_t strategy_local_remote;
+
+const strategy_ops_t *const strategy_vft[] = {
+ [STRATEGY_TYPE_LOADBALANCER] = &strategy_load_balancer,
+ [STRATEGY_TYPE_RANDOM] = &strategy_random,
+ [STRATEGY_TYPE_REPLICATION] = &strategy_replication,
+ [STRATEGY_TYPE_BESTPATH] = &strategy_bestpath,
+ [STRATEGY_TYPE_LOCAL_REMOTE] = &strategy_local_remote,
+#if 0
+ [STRATEGY_TYPE_LOW_LATENCY] = &strategy_low_latency,
+#endif
+};
diff --git a/hicn-light/src/hicn/core/strategy_vft.h b/hicn-light/src/hicn/core/strategy_vft.h
new file mode 100644
index 000000000..55e61db17
--- /dev/null
+++ b/hicn-light/src/hicn/core/strategy_vft.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * \file strategy_vft.h
+ * \brief hICN forwarding strategy VFT
+ */
+#ifndef HICNLIGHT_STRATEGY_VFT_H
+#define HICNLIGHT_STRATEGY_VFT_H
+
+#include "msgbuf.h"
+
+#include "../strategies/best_path.h"
+#include "../strategies/load_balancer.h"
+#include "../strategies/random.h"
+#include "../strategies/replication.h"
+
+typedef union {
+ strategy_load_balancer_options_t load_balancer;
+ strategy_random_options_t random;
+ strategy_replication_options_t replication;
+ strategy_bestpath_options_t bestpath;
+} strategy_options_t;
+
+typedef struct {
+#ifdef WITH_POLICY
+ int priority;
+#endif /* WITH_POLICY */
+ union {
+ strategy_load_balancer_nexthop_state_t load_balancer;
+ strategy_random_nexthop_state_t random;
+ strategy_replication_nexthop_state_t replication;
+ strategy_bestpath_nexthop_state_t bestpath;
+ };
+} strategy_nexthop_state_t;
+
+#define STRATEGY_NEXTHOP_STATE_EMPTY \
+ { \
+ 0, { \
+ { 0 } \
+ } \
+ }
+
+typedef union {
+ strategy_load_balancer_state_t load_balancer;
+ strategy_random_state_t random;
+ strategy_replication_state_t replication;
+ strategy_bestpath_state_t bestpath;
+} strategy_state_t;
+// XXX This has to be merged with nexthops
+// XXX How to avoid errors due to pool id reuse (eg on_data) ?
+
+/**
+ * @typedef strategy_ops_t
+ * @abstract Forwarding strategy implementation
+ * @constant receiveObject is called when we receive an object and have a
+ * measured round trip time. This allows a strategy to update its performance
+ * data.
+ * @constant lookupNexthop Find the set of nexthops to use for the Interest.
+ * May be empty, should not be NULL. Must be destroyed.
+ * @constant addNexthop Add a nexthop to the list of available nexthops with a
+ * routing protocol-specific cost.
+ * @constant destroy cleans up the strategy, freeing all memory and state. A
+ * strategy is reference counted, so the final destruction only happens after
+ * the last reference is released.
+ * @discussion <#Discussion#>
+ */
+
+struct strategy_entry_s;
+struct nexthops_s;
+
+typedef struct {
+ const char *name;
+
+ int (*initialize)(struct strategy_entry_s *entry, const void *forwarder);
+
+ int (*finalize)(struct strategy_entry_s *entry);
+
+ struct nexthops_s *(*lookup_nexthops)(struct strategy_entry_s *entry,
+ struct nexthops_s *nexthops,
+ const msgbuf_t *msgbuf);
+
+ int (*add_nexthop)(struct strategy_entry_s *strategy,
+ struct nexthops_s *nexthops, off_t offset);
+
+ int (*remove_nexthop)(struct strategy_entry_s *entry,
+ struct nexthops_s *nexthops, off_t offset);
+
+ int (*on_data)(struct strategy_entry_s *entry, struct nexthops_s *nexthops,
+ const struct nexthops_s *data_nexthops, const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation, Ticks objReception);
+
+ int (*on_timeout)(struct strategy_entry_s *entry, struct nexthops_s *nexthops,
+ const struct nexthops_s *timeout_nexthops);
+
+} strategy_ops_t;
+
+extern const strategy_ops_t *const strategy_vft[];
+
+#define DECLARE_STRATEGY(NAME) \
+ const strategy_ops_t strategy_##NAME = { \
+ .name = #NAME, \
+ .initialize = strategy_##NAME##_initialize, \
+ .finalize = strategy_##NAME##_finalize, \
+ .add_nexthop = strategy_##NAME##_add_nexthop, \
+ .remove_nexthop = strategy_##NAME##_remove_nexthop, \
+ .lookup_nexthops = strategy_##NAME##_lookup_nexthops, \
+ .on_data = strategy_##NAME##_on_data, \
+ .on_timeout = strategy_##NAME##_on_timeout, \
+ }
+
+#endif /* HICNLIGHT_STRATEGY_VFT_H */
diff --git a/hicn-light/src/hicn/core/streamBuffer.c b/hicn-light/src/hicn/core/streamBuffer.c
index c30139498..401b7c873 100644
--- a/hicn-light/src/hicn/core/streamBuffer.c
+++ b/hicn-light/src/hicn/core/streamBuffer.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-light/src/hicn/core/streamBuffer.h b/hicn-light/src/hicn/core/streamBuffer.h
index 27e793176..0caa10bea 100644
--- a/hicn-light/src/hicn/core/streamBuffer.h
+++ b/hicn-light/src/hicn/core/streamBuffer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-light/src/hicn/core/subscription.c b/hicn-light/src/hicn/core/subscription.c
new file mode 100644
index 000000000..fb954a245
--- /dev/null
+++ b/hicn-light/src/hicn/core/subscription.c
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ */
+
+#include "subscription.h"
+#include <hicn/util/vector.h>
+#include <hicn/util/log.h>
+
+/*----------------------------------------------------------------------------*
+ * Topics and events
+ *----------------------------------------------------------------------------*/
+
+bool topics_contains(hc_topics_t topic_list, hc_topic_t topic) {
+ return ((topic_list) & (topic));
+}
+
+#define topic_is_set(topic_list, topic_index) \
+ ((topic_list) & (1 << (topic_index)))
+
+/*----------------------------------------------------------------------------*
+ * Subscriptions
+ *----------------------------------------------------------------------------*/
+
+struct subscription_table_s {
+ unsigned *table[TOPIC_N];
+};
+
+subscription_table_t *subscription_table_create() {
+ subscription_table_t *subscriptions = malloc(sizeof(subscription_table_t));
+ for (int i = 0; i < NUM_TOPICS; i++)
+ vector_init(subscriptions->table[i], 0, 0);
+
+ return subscriptions;
+}
+
+void subscription_table_free(subscription_table_t *subscriptions) {
+ for (int i = 0; i < NUM_TOPICS; i++) vector_free(subscriptions->table[i]);
+ free(subscriptions);
+}
+
+int subscription_table_add_topics_for_connection(
+ subscription_table_t *subscriptions, hc_topics_t topics,
+ unsigned connection_id) {
+ bool is_subscription_already_present = false;
+ for (int topic_index = 0; topic_index < NUM_TOPICS; topic_index++) {
+ if (topic_is_set(topics, topic_index)) {
+ int num_duplicates = vector_remove_unordered(
+ subscriptions->table[topic_index], connection_id);
+
+ int ret = vector_push(subscriptions->table[topic_index], connection_id);
+ if (ret < 0) {
+ ERROR("Unable to perform subscription for connection %d, topic %s",
+ connection_id, object_type_str(topic_index));
+ return -1;
+ }
+
+ if (num_duplicates > 0) {
+ DEBUG("Connection %d had already a subscription for topic %s",
+ connection_id, object_type_str(topic_index));
+ is_subscription_already_present = true;
+ }
+ }
+ }
+ return is_subscription_already_present ? -2 : 0;
+}
+
+int subscription_table_remove_topics_for_connection(
+ subscription_table_t *subscriptions, hc_topics_t topics,
+ unsigned connection_id) {
+ int num_subscriptions_removed = 0;
+ for (int topic_index = 0; topic_index < NUM_TOPICS; topic_index++) {
+ if (topic_is_set(topics, topic_index)) {
+ int num_duplicates = vector_remove_unordered(
+ subscriptions->table[topic_index], connection_id);
+ if (num_duplicates <= 0) {
+ continue;
+ }
+ num_subscriptions_removed++;
+ }
+ }
+ return num_subscriptions_removed;
+}
+
+hc_topics_t subscription_table_get_topics_for_connection(
+ subscription_table_t *subscriptions, unsigned connection_id) {
+ hc_topics_t topics = 0;
+ for (int topic_index = 0; topic_index < NUM_TOPICS; topic_index++) {
+ unsigned *conn_id;
+ bool found = false;
+ vector_foreach(subscriptions->table[topic_index], conn_id, {
+ if (*conn_id == connection_id) {
+ found = true;
+ break;
+ }
+ });
+ if (found) topics |= (1 << topic_index);
+ }
+ return topics;
+}
+
+unsigned *subscription_table_get_connections_for_topic(
+ subscription_table_t *subscriptions, hc_topic_t topic) {
+ int topic_index = object_from_topic(topic);
+ return subscriptions->table[topic_index];
+}
+
+void subscription_table_print(subscription_table_t *subscriptions) {
+ for (int topic_index = OBJECT_TYPE_UNDEFINED + 1; topic_index < NUM_TOPICS;
+ topic_index++) {
+ printf("topic %s (%lu subscription/s) from connection/s: [ ",
+ object_type_str(topic_index),
+ (unsigned long)vector_len(subscriptions->table[topic_index]));
+ unsigned *connection_id;
+ vector_foreach(subscriptions->table[topic_index], connection_id,
+ { printf("%d ", *connection_id); });
+ printf("]\n");
+ }
+}
diff --git a/hicn-light/src/hicn/core/subscription.h b/hicn-light/src/hicn/core/subscription.h
new file mode 100644
index 000000000..74ddd9e18
--- /dev/null
+++ b/hicn-light/src/hicn/core/subscription.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ */
+
+#ifndef HICNLIGHT_SUBSCRIPTION_H
+#define HICNLIGHT_SUBSCRIPTION_H
+
+#include <hicn/ctrl/api.h>
+#include <stddef.h>
+
+/*----------------------------------------------------------------------------*
+ * Topics
+ *----------------------------------------------------------------------------*/
+
+bool topics_contains(hc_topics_t topic_list, hc_topic_t topic);
+
+/*----------------------------------------------------------------------------*
+ * Subscriptions
+ *----------------------------------------------------------------------------*/
+
+typedef struct subscription_table_s subscription_table_t;
+
+subscription_table_t *subscription_table_create();
+
+void subscription_table_free(subscription_table_t *subscriptions);
+
+/**
+ * @brief Add topic subscriptions for a connection.
+ *
+ * @param subscriptions The pointer to the subscription table
+ * @param topics Topics the connection wants to subscribe to
+ * @param connection_id Identifier of the connection
+ * @return int 0 for success, -1 for error, -2 if already esisting subscription
+ * for at least one of the topic for
+ */
+int subscription_table_add_topics_for_connection(
+ subscription_table_t *subscriptions, hc_topics_t topics,
+ unsigned connection_id);
+
+/**
+ * @brief Remove topic subscriptions for a connection.
+ *
+ * @param subscriptions The pointer to the subscription table
+ * @param topics Topics the connection wants to unsubscribe to
+ * @param connection_id Identifier of the connection
+ * @return int Number of removed subscriptions
+ */
+int subscription_table_remove_topics_for_connection(
+ subscription_table_t *subscriptions, hc_topics_t topics,
+ unsigned connection_id);
+
+/**
+ * @brief Get the topics a connection has subscribed to.
+ *
+ * @param subscriptions The pointer to the subscription table
+ * @param connection_id Identifier of the connection
+ * @return hc_topics_t
+ */
+hc_topics_t subscription_table_get_topics_for_connection(
+ subscription_table_t *subscriptions, unsigned connection_id);
+
+/**
+ * @brief Get the connections that have a subscription for the specified topic.
+ *
+ * @param subscriptions The pointer to the subscription table
+ * @param topic Topic to retrieve the subscriptions for
+ * @return unsigned* Array containing the connection ids associated with the
+ * specified topic
+ */
+unsigned *subscription_table_get_connections_for_topic(
+ subscription_table_t *subscriptions, hc_topic_t topic);
+
+/**
+ * @brief Print the subscription table containing, for each topic, the list
+ * of connections with a subsctiption.
+ *
+ * @param subscriptions The pointer to the subscription table
+ */
+void subscription_table_print(subscription_table_t *subscriptions);
+
+#endif // HICNLIGHT_SUBSCRIPTION_H \ No newline at end of file
diff --git a/hicn-light/src/hicn/core/system.h b/hicn-light/src/hicn/core/system.h
index be6c3e7cf..860133dd3 100644
--- a/hicn-light/src/hicn/core/system.h
+++ b/hicn-light/src/hicn/core/system.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,13 +25,12 @@
#define system_h
#include <hicn/core/forwarder.h>
-#include <hicn/utils/interfaceSet.h>
/**
* @function system_Interfaces
* @abstract The system network interfaces
*/
-InterfaceSet *system_Interfaces(Forwarder *forwarder);
+InterfaceSet *system_Interfaces(forwarder_t *forwarder);
/**
* Returns the MTU of the named interface
@@ -43,7 +42,7 @@ InterfaceSet *system_Interfaces(Forwarder *forwarder);
* @return positive the MTU the kernel reports
*
*/
-unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName);
+unsigned system_InterfaceMtu(forwarder_t *forwarder, const char *interfaceName);
/**
* Returns the LINK address of the specified interface
@@ -55,6 +54,6 @@ unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName);
* @retval null The interface does not exist
*
*/
-Address *system_GetMacAddressByName(Forwarder *forwarder,
+Address *system_GetMacAddressByName(forwarder_t *forwarder,
const char *interfaceName);
#endif
diff --git a/hicn-light/src/hicn/core/ticks.h b/hicn-light/src/hicn/core/ticks.h
index 8750abde5..0955569df 100644
--- a/hicn-light/src/hicn/core/ticks.h
+++ b/hicn-light/src/hicn/core/ticks.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,7 +25,42 @@
#define __STDC_FORMAT_MACROS
#include <stdint.h>
+#include <time.h>
+
+#include <sys/param.h> // HZ
+
+#ifdef __APPLE__
+#include <mach/clock.h>
+#include <mach/mach.h>
+#define HZ 1000
+#endif
typedef uint64_t Ticks;
+// these will all be a little off because its all integer division
+#define NSEC_PER_TICK ((1000000000ULL) / HZ)
+#define NSEC_TO_TICKS(nsec) ((nsec < NSEC_PER_TICK) ? 1 : nsec / NSEC_PER_TICK)
+
+#define TICKS_TO_NSEC(ticks) ((1000000000ULL) * ticks / HZ)
+
+static inline Ticks ticks_now() {
+#if __linux__
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
+ return ts.tv_sec * 1000 + ts.tv_nsec / 1e6;
+#elif _WIN32
+ struct timespec ts;
+ _clock_gettime(TIME_UTC, &ts);
+ return ts.tv_sec * 1000 + ts.tv_nsec / 1e6;
+#else
+ clock_serv_t clockService;
+ mach_timespec_t ts;
+ host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clockService);
+ clock_get_time(clockService, &ts);
+ mach_port_deallocate(mach_task_self(), clockService);
+#endif
+
+ return ts.tv_sec * 1000 + ts.tv_nsec / 1e6;
+}
+
#endif // ticks_h
diff --git a/hicn-light/src/hicn/core/wldr.c b/hicn-light/src/hicn/core/wldr.c
index ad3663d0d..aa1dbf4f9 100644
--- a/hicn-light/src/hicn/core/wldr.c
+++ b/hicn-light/src/hicn/core/wldr.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,93 +13,100 @@
* limitations under the License.
*/
-#include <parc/assert/parc_Assert.h>
-#include <parc/logging/parc_LogReporterTextStdout.h>
#include <hicn/core/connection.h>
#include <hicn/core/forwarder.h>
#include <hicn/core/wldr.h>
#include <stdint.h>
#include <stdio.h>
-struct wldr_buffer {
- Message *message;
+typedef struct {
+ msgbuf_t *msgbuf;
uint8_t rtx_counter;
-};
-
-typedef struct wldr_buffer WldrBuffer;
+} wldr_buffer_t;
-struct wldr_state {
+struct wldr_s {
uint16_t expected_label;
uint16_t next_label;
- WldrBuffer *buffer[BUFFER_SIZE];
+ wldr_buffer_t *buffer[BUFFER_SIZE];
};
-Wldr *wldr_Init() {
- Wldr *wldr = parcMemory_AllocateAndClear(sizeof(Wldr));
+wldr_t *wldr_create() {
+#if 0
+ wldr_t * wldr = parcMemory_AllocateAndClear(sizeof(Wldr));
parcAssertNotNull(wldr, "parcMemory_AllocateAndClear(%zu) returned NULL",
sizeof(Wldr));
wldr->expected_label = 1;
wldr->next_label = 1;
for (int i = 0; i < BUFFER_SIZE; i++) {
- WldrBuffer *entry = parcMemory_AllocateAndClear(sizeof(WldrBuffer));
+ wldr_buffer_t *entry = parcMemory_AllocateAndClear(sizeof(wldr_buffer_t));
parcAssertNotNull(
entry,
- "WldrBuffer init: parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(WldrBuffer));
- entry->message = NULL;
+ "wldr_buffer_t init: parcMemory_AllocateAndClear(%zu) returned NULL",
+ sizeof(wldr_buffer_t));
+ entry->msgbuf = NULL;
entry->rtx_counter = 0;
wldr->buffer[i] = entry;
}
return wldr;
+#else
+ return NULL;
+#endif
}
-void wldr_ResetState(Wldr *wldr) {
+void wldr_resset_state(wldr_t *wldr) {
+#if 0
wldr->expected_label = 1;
wldr->next_label = 1;
for (int i = 0; i < BUFFER_SIZE; i++) {
- wldr->buffer[i]->message = NULL;
+ wldr->buffer[i]->msgbuf = NULL;
wldr->buffer[i]->rtx_counter = 0;
}
+#endif
}
-void wldr_Destroy(Wldr **wldrPtr) {
- Wldr *wldr = *wldrPtr;
+void wldr_free(wldr_t *wldr) {
+#if 0
+ wldr_t * wldr = *wldrPtr;
for (unsigned i = 0; i < BUFFER_SIZE; i++) {
- if (wldr->buffer[i]->message != NULL) {
- message_Release(&(wldr->buffer[i]->message));
+ if (wldr->buffer[i]->msgbuf != NULL) {
+ message_Release(&(wldr->buffer[i]->msgbuf));
parcMemory_Deallocate((void **)&(wldr->buffer[i]));
}
}
parcMemory_Deallocate((void **)&wldr);
*wldrPtr = NULL;
+#endif
}
-static void _wldr_RetransmitPacket(Wldr *wldr, const Connection *conn,
+#if 0
+static void _wldr_RetransmitPacket(wldr_t * wldr, const connection_t * conn,
uint16_t label) {
- if (wldr->buffer[label % BUFFER_SIZE]->message == NULL) {
+ if (wldr->buffer[label % BUFFER_SIZE]->msgbuf == NULL) {
// the required message for retransmission is not in the buffer
return;
}
if (wldr->buffer[label % BUFFER_SIZE]->rtx_counter < MAX_RTX) {
- Message *msg = wldr->buffer[label % BUFFER_SIZE]->message;
+ msgbuf_t *msg = wldr->buffer[label % BUFFER_SIZE]->msgbuf;
message_SetWldrLabel(msg, wldr->next_label);
- if (wldr->buffer[wldr->next_label % BUFFER_SIZE]->message != NULL) {
- message_Release(&(wldr->buffer[wldr->next_label % BUFFER_SIZE]->message));
+ if (wldr->buffer[wldr->next_label % BUFFER_SIZE]->msgbuf != NULL) {
+ msgbuf_Release(&(wldr->buffer[wldr->next_label % BUFFER_SIZE]->msgbuf));
}
- wldr->buffer[wldr->next_label % BUFFER_SIZE]->message = msg;
+ wldr->buffer[wldr->next_label % BUFFER_SIZE]->msgbuf = msg;
wldr->buffer[wldr->next_label % BUFFER_SIZE]->rtx_counter =
wldr->buffer[label % BUFFER_SIZE]->rtx_counter + 1;
- message_Acquire(wldr->buffer[wldr->next_label % BUFFER_SIZE]->message);
+ message_Acquire(wldr->buffer[wldr->next_label % BUFFER_SIZE]->msgbuf);
wldr->next_label++;
connection_ReSend(conn, msg, false);
}
}
+#endif
-static void _wldr_SendWldrNotificaiton(Wldr *wldr, const Connection *conn,
- Message *message, uint16_t expected_lbl,
+#if 0
+static void _wldr_SendWldrNotification(wldr_t * wldr, const connection_t * conn,
+ msgbuf_t *msgbuf, uint16_t expected_lbl,
uint16_t received_lbl) {
// here we need to create a new packet that is used to send the wldr
// notification to the prevoius hop. the destionation address of the
@@ -113,38 +120,43 @@ static void _wldr_SendWldrNotificaiton(Wldr *wldr, const Connection *conn,
// this way the notification packet will be dispaced to the right connection
// at the next hop.
- Message *notification =
- message_CreateWldrNotification(message, expected_lbl, received_lbl);
+ msgbuf_t *notification =
+ message_CreateWldrNotification(msgbuf, expected_lbl, received_lbl);
parcAssertNotNull(notification, "Got null from CreateWldrNotification");
connection_ReSend(conn, notification, true);
}
+#endif
-void wldr_SetLabel(Wldr *wldr, Message *message) {
+void wldr_set_label(wldr_t *wldr, msgbuf_t *msgbuf) {
+#if 0
// in this function we send the packet for the first time
// 1) we set the wldr label
- message_SetWldrLabel(message, wldr->next_label);
+ message_SetWldrLabel(msgbuf, wldr->next_label);
// 2) we store the pointer to packet in the buffer
- if (wldr->buffer[wldr->next_label % BUFFER_SIZE]->message != NULL) {
+ if (wldr->buffer[wldr->next_label % BUFFER_SIZE]->msgbuf != NULL) {
// release an old message if necessary
- message_Release(&(wldr->buffer[wldr->next_label % BUFFER_SIZE]->message));
+ message_Release(&(wldr->buffer[wldr->next_label % BUFFER_SIZE]->msgbuf));
}
// we need to acquire the message to avoid that it gets destroyed
- message_Acquire(message);
+ message_Acquire(msgbuf);
- wldr->buffer[wldr->next_label % BUFFER_SIZE]->message = message;
+ wldr->buffer[wldr->next_label % BUFFER_SIZE]->msgbuf = msgbuf;
wldr->buffer[wldr->next_label % BUFFER_SIZE]->rtx_counter = 0;
wldr->next_label++;
if (wldr->next_label ==
0) // we alwasy skip label 0 beacause it means that wldr is not active
wldr->next_label++;
+#endif
}
-void wldr_DetectLosses(Wldr *wldr, const Connection *conn, Message *message) {
- if (message_HasWldr(message)) {
+void wldr_detect_losses(wldr_t *wldr, const connection_t *connection,
+ const msgbuf_t *msgbuf) {
+#if 0
+ if (message_HasWldr(msgbuf)) {
// this is a normal wldr packet
- uint16_t pkt_lbl = (uint16_t)message_GetWldrLabel(message);
+ uint16_t pkt_lbl = (uint16_t)message_GetWldrLabel(msgbuf);
if (pkt_lbl != wldr->expected_label) {
// if the received packet label is 1 and the expected packet label >
// pkt_lbl usually we are in the case where a remote note disconnected for
@@ -153,7 +165,7 @@ void wldr_DetectLosses(Wldr *wldr, const Connection *conn, Message *message) {
// synch the labels
if ((pkt_lbl != 1) || (wldr->expected_label < pkt_lbl)) {
- _wldr_SendWldrNotificaiton(wldr, conn, message, wldr->expected_label,
+ _wldr_SendWldrNotificaiton(wldr, conn, msgbuf, wldr->expected_label,
pkt_lbl);
}
@@ -165,12 +177,14 @@ void wldr_DetectLosses(Wldr *wldr, const Connection *conn, Message *message) {
wldr->expected_label++; // for the next_label we want to skip 0
}
}
+#endif
}
-void wldr_HandleWldrNotification(Wldr *wldr, const Connection *conn,
- Message *message) {
- uint16_t expected_lbl = (uint16_t)message_GetWldrExpectedLabel(message);
- uint16_t received_lbl = (uint16_t)message_GetWldrLastReceived(message);
+void wldr_handle_notification(wldr_t *wldr, const connection_t *connection,
+ const msgbuf_t *msgbuf) {
+#if 0
+ uint16_t expected_lbl = (uint16_t)message_GetWldrExpectedLabel(msgbuf);
+ uint16_t received_lbl = (uint16_t)message_GetWldrLastReceived(msgbuf);
if ((wldr->next_label - expected_lbl) > BUFFER_SIZE) {
// the packets are not in the buffer anymore
return;
@@ -179,4 +193,5 @@ void wldr_HandleWldrNotification(Wldr *wldr, const Connection *conn,
_wldr_RetransmitPacket(wldr, conn, expected_lbl);
expected_lbl++;
}
+#endif
}
diff --git a/hicn-light/src/hicn/core/wldr.h b/hicn-light/src/hicn/core/wldr.h
index e21889f63..7eccf39cd 100644
--- a/hicn-light/src/hicn/core/wldr.h
+++ b/hicn-light/src/hicn/core/wldr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,7 +18,7 @@
#include <hicn/hicn-light/config.h>
#include <hicn/core/connection.h>
-#include <hicn/core/message.h>
+#include <hicn/core/msgbuf.h>
#define BUFFER_SIZE 8192
#define MAX_RTX 3
@@ -34,19 +34,19 @@
// ATTENTION!!! in order to detect a notificaiton the
// source and destination ports must be set to 0
-struct wldr_state;
-typedef struct wldr_state Wldr;
+typedef struct wldr_s wldr_t;
-Wldr *wldr_Init();
+wldr_t *wldr_create();
-void wldr_Destroy(Wldr **wldrPtr);
+void wldr_free(wldr_t *wldr);
-void wldr_ResetState(Wldr *wldr);
+void wldr_reset_state(wldr_t *wldr);
-void wldr_SetLabel(Wldr *wldr, Message *message);
+void wldr_set_label(wldr_t *wldr, msgbuf_t *msgbuf);
-void wldr_DetectLosses(Wldr *wldr, const Connection *conn, Message *message);
+void wldr_detect_losses(wldr_t *wldr, const connection_t *connection,
+ const msgbuf_t *msgbuf);
-void wldr_HandleWldrNotification(Wldr *wldr, const Connection *conn,
- Message *message);
+void wldr_handle_notification(wldr_t *wldr, const connection_t *connection,
+ const msgbuf_t *msgbuf);
#endif // wldr_h
diff --git a/hicn-light/src/hicn/io/CMakeLists.txt b/hicn-light/src/hicn/io/CMakeLists.txt
index cc4f7371f..1a04aad75 100644
--- a/hicn-light/src/hicn/io/CMakeLists.txt
+++ b/hicn-light/src/hicn/io/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -12,46 +12,14 @@
# limitations under the License.
list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/addressPair.h
- ${CMAKE_CURRENT_SOURCE_DIR}/ioOperations.h
- ${CMAKE_CURRENT_SOURCE_DIR}/listener.h
- ${CMAKE_CURRENT_SOURCE_DIR}/listenerSet.h
- ${CMAKE_CURRENT_SOURCE_DIR}/tcpListener.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicnListener.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udpTunnel.h
- ${CMAKE_CURRENT_SOURCE_DIR}/tcpTunnel.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udpConnection.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udpListener.h
- ${CMAKE_CURRENT_SOURCE_DIR}/streamConnection.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicnTunnel.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicnConnection.h
)
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/addressPair.c
- ${CMAKE_CURRENT_SOURCE_DIR}/ioOperations.c
- ${CMAKE_CURRENT_SOURCE_DIR}/listenerSet.c
- ${CMAKE_CURRENT_SOURCE_DIR}/streamConnection.c
- ${CMAKE_CURRENT_SOURCE_DIR}/tcpListener.c
- ${CMAKE_CURRENT_SOURCE_DIR}/tcpTunnel.c
- ${CMAKE_CURRENT_SOURCE_DIR}/udpConnection.c
- ${CMAKE_CURRENT_SOURCE_DIR}/udpListener.c
- ${CMAKE_CURRENT_SOURCE_DIR}/udpTunnel.c
-)
-
-if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
- list(APPEND SOURCE_FILES
- io/hicnTunnel.c
- io/hicnConnection.c
- io/hicnListener.c
- )
-endif()
-
-set(TO_INSTALL_HEADER_FILES
- ${TO_INSTALL_HEADER_FILES}
- ${HEADER_FILES}
- PARENT_SCOPE
+ ${CMAKE_CURRENT_SOURCE_DIR}/base.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/tcp.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp.c
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
-set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE) \ No newline at end of file
+set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
diff --git a/hicn-light/src/hicn/io/addressPair.c b/hicn-light/src/hicn/io/addressPair.c
deleted file mode 100644
index f9451f900..000000000
--- a/hicn-light/src/hicn/io/addressPair.c
+++ /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.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/io/addressPair.h>
-
-struct address_pair {
- Address *local;
- Address *remote;
-};
-
-static void _addressPair_Destroy(AddressPair **addressPairPtr) {
- AddressPair *pair = *addressPairPtr;
-
- addressDestroy(&pair->local);
- addressDestroy(&pair->remote);
-}
-
-parcObject_ExtendPARCObject(AddressPair, _addressPair_Destroy, NULL,
- addressPair_ToString, addressPair_Equals, NULL,
- addressPair_HashCode, NULL);
-
-parcObject_ImplementAcquire(addressPair, AddressPair);
-
-parcObject_ImplementRelease(addressPair, AddressPair);
-
-AddressPair *addressPair_Create(const Address *local, const Address *remote) {
- parcAssertNotNull(local, "Parameter local must be non-null");
- parcAssertNotNull(remote, "Parameter remote must be non-null");
-
- AddressPair *pair = parcObject_CreateInstance(AddressPair);
- parcAssertNotNull(pair, "Got null from parcObject_Create()");
-
- pair->local = addressCopy(local);
- pair->remote = addressCopy(remote);
-
- return pair;
-}
-
-bool addressPair_Equals(const AddressPair *a, const AddressPair *b) {
- if (a == b) {
- return true;
- }
- if (a == NULL || b == NULL) {
- return false;
- }
-
- if (addressEquals(a->local, b->local)) {
- if (addressEquals(a->remote, b->remote)) {
- return true;
- }
- }
-
- return false;
-}
-
-bool addressPair_EqualsAddresses(const AddressPair *a, const Address *local,
- const Address *remote) {
- if (a == NULL || local == NULL || remote == NULL) {
- return false;
- }
-
- if (addressEquals(a->local, local)) {
- if (addressEquals(a->remote, remote)) {
- return true;
- }
- }
-
- return false;
-}
-
-char *addressPair_ToString(const AddressPair *pair) {
- parcAssertNotNull(pair, "Parameter pair must be non-null");
-
- char *local = addressToString(pair->local);
- char *remote = addressToString(pair->remote);
-
- char *output;
- int failure = asprintf(&output, "{ .local=%s, .remote=%s }", local, remote);
- parcAssertTrue(failure > -1, "Error on asprintf");
-
- parcMemory_Deallocate((void **)&local);
- parcMemory_Deallocate((void **)&remote);
-
- return output;
-}
-
-const Address *addressPair_GetLocal(const AddressPair *pair) {
- parcAssertNotNull(pair, "Parameter pair must be non-null");
- return pair->local;
-}
-
-const Address *addressPair_GetRemote(const AddressPair *pair) {
- parcAssertNotNull(pair, "Parameter pair must be non-null");
- return pair->remote;
-}
-
-/**
- * @function addressPair_HashCode
- * @abstract Hash useful for tables. Consistent with Equals.
- * @discussion
- * Returns a non-cryptographic hash that is consistent with equals. That is,
- * if a == b, then hash(a) == hash(b).
- *
- */
-PARCHashCode addressPair_HashCode(const AddressPair *pair) {
- PARCHashCode hashpair[2];
- hashpair[0] = addressHashCode(pair->local);
- hashpair[1] = addressHashCode(pair->remote);
- return parcHashCode_Hash((const uint8_t *)hashpair, sizeof(hashpair));
-}
diff --git a/hicn-light/src/hicn/io/addressPair.h b/hicn-light/src/hicn/io/addressPair.h
deleted file mode 100644
index f1b72e0dc..000000000
--- a/hicn-light/src/hicn/io/addressPair.h
+++ /dev/null
@@ -1,128 +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.
- */
-
-/**
- * Used to identify a connection between a specific local address and
- * a specific remote address.
- */
-
-#ifndef address_Pair_h
-#define address_Pair_h
-
-#include <hicn/utils/address.h>
-
-struct address_pair;
-typedef struct address_pair AddressPair;
-
-/**
- * @function addressPair_Create
- * @abstract Creates and address pair. There is no restriction on the address
- * types.
- * @discussion
- * Creates an ordered pair of addresses, where the first is considered the
- * "local" address and the second is the "remote" address. Those designations
- * are purely a convention used to name them, and does not imply any specifici
- * types of operations.
- *
- * The two addresses may be of any address types (e.g. IPv4, IPv6, Local,
- * Ethernet). However, some functions that use an AddressPair may require that
- * the local and remote addresses be the same type.
- *
- */
-AddressPair *addressPair_Create(const Address *local, const Address *remote);
-
-/**
- * Returns a reference counted copy of the address pair
- *
- * Increments the reference count and returns the same address pair
- *
- * @param [in] addressPair An allocated address pair
- *
- * @retval non-null A reference counted copy
- * @retval null An error
- */
-AddressPair *addressPair_Acquire(const AddressPair *addressPair);
-
-/**
- * Releases a reference count to the object
- *
- * Decrements the reference count and destroys the object when it reaches 0.
- */
-void addressPair_Release(AddressPair **pairPtr);
-
-/**
- * Determine if two AddressPair instances are equal.
- *
- * Two AddressPair instances are equal if, and only if, the local and remote
- * addresses are identical. Equality is determined by addressEquals(a->local,
- * b->local) and Adress_Equals(a->remote, b->remote).
- *
- * The following equivalence relations on non-null `AddressPair` instances are
- * maintained:
- *
- * * It is reflexive: for any non-null reference value x,
- * `AddressPair_Equals(x, x)` must return true.
- *
- * * It is symmetric: for any non-null reference values x and y,
- * `addressPair_Equals(x, y)` must return true if and only if
- * `addressPair_Equals(y, x)` returns true.
- *
- * * It is transitive: for any non-null reference values x, y, and z, if
- * `addressPair_Equals(x, y)` returns true and
- * `addressPair_Equals(y, z)` returns true,
- * then `addressPair_Equals(x, z)` must return true.
- *
- * * It is consistent: for any non-null reference values x and y, multiple
- * invocations of `addressPair_Equals(x, y)` consistently return true or
- * consistently return false.
- *
- * * For any non-null reference value x, `addressPair_Equals(x, NULL)` must
- * return false.
- *
- * @param a A pointer to a `AddressPair` instance.
- * @param b A pointer to a `AddressPair` instance.
- * @return true if the two `AddressPair` instances are equal.
- */
-bool addressPair_Equals(const AddressPair *a, const AddressPair *b);
-
-/**
- * @function addressPair_EqualsAddresses
- * @abstract As AddressEquals, but "b" is broken out
- * @discussion
- * Equality is determined by addressEquals(a->local, local) and
- * Adress_Equals(a->remote, remote).
- */
-bool addressPair_EqualsAddresses(const AddressPair *a, const Address *local,
- const Address *remote);
-
-const Address *addressPair_GetLocal(const AddressPair *pair);
-
-const Address *addressPair_GetRemote(const AddressPair *pair);
-
-/**
- * @function addressPair_HashCode
- * @abstract Hash useful for tables. Consistent with Equals.
- * @discussion
- * Returns a non-cryptographic hash that is consistent with equals. That is,
- * if a == b, then hash(a) == hash(b).
- */
-PARCHashCode addressPair_HashCode(const AddressPair *pair);
-
-/**
- * @function addressPair_ToString
- * @abstract Human readable string representation. Caller must use free(3).
- */
-char *addressPair_ToString(const AddressPair *pair);
-#endif // address_Pair_h
diff --git a/hicn-light/src/hicn/io/base.c b/hicn-light/src/hicn/io/base.c
new file mode 100644
index 000000000..38d36efbe
--- /dev/null
+++ b/hicn-light/src/hicn/io/base.c
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * @file base.c
+ * #brief Implementation of base IO functions.
+ */
+
+#include <hicn/util/log.h>
+
+#include "base.h"
+
+/**
+ * @brief Helper function for listener to read a single packet on a socket
+ */
+ssize_t io_read_single_fd(int fd, msgbuf_t *msgbuf, address_t *address) {
+ uint8_t *packet = msgbuf_get_packet(msgbuf);
+ size_t size = msgbuf_get_len(msgbuf);
+
+ for (;;) {
+ ssize_t n = read(fd, packet, size);
+ if (n == 0) return n;
+ if (n < 0) {
+ if (errno == EINTR) continue; // XXX was break;
+
+ /* ICMP unreachable due to closing the remote end of a connection */
+ if (errno == ECONNREFUSED) continue;
+
+ ERROR("read failed %d: (%d) %s", fd, errno, strerror(errno));
+ return -1;
+ }
+
+ msgbuf_set_len(msgbuf, (size_t)n);
+ *address = ADDRESS_ANY(AF_UNSPEC, 0); // XXX placeholder, see hicn.c
+ }
+
+ return 1;
+}
+
+ssize_t io_read_single_socket(int fd, msgbuf_t *msgbuf, address_t *address) {
+ struct sockaddr *sa = &(address->as_sa);
+ socklen_t sa_len = sizeof(sa);
+ uint8_t *packet = msgbuf_get_packet(msgbuf);
+
+ ssize_t n = recvfrom(fd, packet, MTU, 0, (struct sockaddr *)sa, &sa_len);
+ msgbuf_set_len(msgbuf, (size_t)n);
+
+#ifdef __APPLE__
+ // set __uint8_t sin_len to 0
+ uint8_t *ptr = (uint8_t *)sa;
+ *ptr = 0x0;
+#endif /* __APPLE__ */
+
+ return n;
+}
+
+#ifdef __linux__
+ssize_t io_read_batch_socket(int fd, msgbuf_t **msgbuf, address_t **address,
+ size_t batch_size) {
+ struct mmsghdr msghdr[batch_size];
+ struct iovec iovecs[batch_size];
+ struct sockaddr_storage addrs[batch_size];
+
+ /* Prepare the mmghdr struct for recvmmsg */
+ for (unsigned i = 0; i < MAX_MSG; i++) {
+ struct mmsghdr *msg = &msghdr[i];
+ *msg = (struct mmsghdr){
+ .msg_hdr =
+ {
+ .msg_iov = &iovecs[i],
+ .msg_iovlen = 1,
+ .msg_name = &addrs[i],
+ .msg_namelen = sizeof(struct sockaddr_storage),
+ .msg_control = NULL,
+ .msg_controllen = 0,
+ },
+ };
+
+ iovecs[i] = (struct iovec){
+ .iov_base = msgbuf_get_packet(msgbuf[i]),
+ .iov_len = MTU,
+ };
+ }
+
+ int n;
+ for (;;) {
+ n = recvmmsg(fd, msghdr, batch_size, /* flags */ 0,
+ /* timeout */ NULL);
+ // INFO("Got n=%d messages", n);
+ if (n == 0) return 0;
+ if (n < 0) {
+ if (errno == EINTR) continue; // XXX was break;
+
+ /* ICMP unreachable due to closing the remote end of a connection */
+ if (errno == ECONNREFUSED) break;
+ if (errno == EAGAIN) return n; // Nothing to read
+
+ ERROR("read failed %d: (%d) %s", fd, errno, strerror(errno));
+ return (ssize_t)n;
+ }
+
+ /*
+ * Assign size to msgbuf, and put the source address into the array
+ * received in parameters, which corresponds to the remote parts of the
+ * connection (local part is setup in the listener itself, eg.
+ * listener_read_batch).
+ */
+ for (int i = 0; i < n; i++) {
+ struct mmsghdr *msg = &msghdr[i];
+ msgbuf_set_len(msgbuf[i], msg->msg_len);
+
+ memcpy(address[i], msg->msg_hdr.msg_name, msg->msg_hdr.msg_namelen);
+ }
+ break;
+ }
+
+ return n;
+}
+#endif /* __linux__ */
diff --git a/hicn-light/src/hicn/io/base.h b/hicn-light/src/hicn/io/base.h
new file mode 100644
index 000000000..3463c6760
--- /dev/null
+++ b/hicn-light/src/hicn/io/base.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file base.h
+ * #brief Base IO functions.
+ */
+
+#ifndef HICNLIGHT_IO_BASE
+#define HICNLIGHT_IO_BASE
+
+#include "../core/address_pair.h"
+#include "../core/msgbuf.h"
+
+#define MAX_MSG 128 // 64 //16 //32
+#define USE_CONNECTED_SOCKETS 1
+
+ssize_t io_read_single_fd(int fd, msgbuf_t* msgbuf, address_t* address);
+
+ssize_t io_read_single_socket(int fd, msgbuf_t* msgbuf, address_t* address);
+
+ssize_t io_read_batch_socket(int fd, msgbuf_t** msgbuf, address_t** address,
+ size_t n);
+
+#endif /* HICNLIGHT_IO_BASE */
diff --git a/hicn-light/src/hicn/io/hicn.c b/hicn-light/src/hicn/io/hicn.c
new file mode 100644
index 000000000..c5859fbe3
--- /dev/null
+++ b/hicn-light/src/hicn/io/hicn.c
@@ -0,0 +1,448 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file hicn.c
+ * @brief Implementation of hicn face
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <hicn/hicn-light/config.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <hicn/util/log.h>
+
+#include "base.h"
+#include "../core/listener.h"
+#include "../core/listener_vft.h"
+#include "../core/connection.h"
+#include "../core/connection_vft.h"
+#include "../core/connection_table.h"
+#include "../core/forwarder.h"
+#include "../core/mapme.h"
+#include "../socket/api.h"
+
+#ifdef __linux__
+#include "../socket/error.h"
+
+#define IPv6 6
+#define IPv4 4
+#define MTU_SIZE 1500 // bytes
+#define MAX_HICN_RETRY 5
+#define DEFAULT_PORT 1234
+
+// XXX #if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(_WIN32) &&
+// defined(PUNTING)
+
+// XXX the socket helper should be moved here as we can have a single hicn
+// listener
+
+#if 0
+static
+const
+address_pair_t *
+_createRecvAddressPairFromPacket(const uint8_t *msgBuffer) {
+ address_t * packetSrcAddr = NULL; /* This one is in the packet */
+ address_t * localAddr = NULL; /* This one is to be determined */
+
+ if (messageHandler_GetIPPacketType(msgBuffer) == IPv6_TYPE) {
+ struct sockaddr_in6 addr_in6;
+ addr_in6.sin6_family = AF_INET6;
+ addr_in6.sin6_port = htons(DEFAULT_PORT);
+ addr_in6.sin6_flowinfo = 0;
+ addr_in6.sin6_scope_id = 0;
+ memcpy(&addr_in6.sin6_addr,
+ (struct in6_addr *)messageHandler_GetSource(msgBuffer), 16);
+ packetSrcAddr = addressCreateFromInet6(&addr_in6);
+
+ /* We now determine the local address used to reach the packet src address */
+#ifndef _WIN32
+ int sock = socket (AF_INET6, SOCK_DGRAM, 0);
+#else
+ int sock = (int)socket (AF_INET6, SOCK_DGRAM, 0);
+#endif /* _WIN32 */
+ if (sock < 0)
+ goto ERR;
+
+ struct sockaddr_in6 remote, local;
+ memset(&remote, 0, sizeof(remote));
+ remote.sin6_family = AF_INET6;
+ remote.sin6_addr = addr_in6.sin6_addr;
+ remote.sin6_port = htons(DEFAULT_PORT);
+
+ socklen_t locallen = sizeof(local);
+ if (connect(sock, (const struct sockaddr*)&remote, sizeof(remote)) == -1)
+ goto ERR;
+ if (getsockname(sock, (struct sockaddr*) &local, &locallen) == -1)
+ goto ERR;
+
+ local.sin6_port = htons(DEFAULT_PORT);
+ localAddr = addressCreateFromInet6(&local);
+
+ close(sock);
+
+ } else if (messageHandler_GetIPPacketType(msgBuffer) == IPv4_TYPE) {
+ struct sockaddr_in addr_in;
+ addr_in.sin_family = AF_INET;
+ addr_in.sin_port = htons(DEFAULT_PORT);
+ memcpy(&addr_in.sin_addr,
+ (struct in_addr *)messageHandler_GetSource(msgBuffer), 4);
+ packetSrcAddr = addressCreateFromInet(&addr_in);
+
+ /* We now determine the local address used to reach the packet src address */
+
+#ifndef _WIN32
+ int sock = socket (AF_INET, SOCK_DGRAM, 0);
+#else
+ int sock = (int)socket (AF_INET, SOCK_DGRAM, 0);
+#endif /* _WIN32 */
+ if (sock < 0) {
+ perror("Socket error");
+ goto ERR;
+ }
+
+ struct sockaddr_in remote, local;
+ memset(&remote, 0, sizeof(remote));
+ remote.sin_family = AF_INET;
+ remote.sin_addr = addr_in.sin_addr;
+ remote.sin_port = htons(DEFAULT_PORT);
+
+ socklen_t locallen = sizeof(local);
+ if (connect(sock, (const struct sockaddr*)&remote, sizeof(remote)) == -1)
+ goto ERR;
+ if (getsockname(sock, (struct sockaddr*) &local, &locallen) == -1)
+ goto ERR;
+
+ local.sin_port = htons(DEFAULT_PORT);
+ localAddr = addressCreateFromInet(&local);
+
+ close(sock);
+ }
+ /* As this is a receive pair, we swap src and dst */
+ return addressPair_Create(localAddr, packetSrcAddr);
+
+ERR:
+ perror("Socket error");
+ return NULL;
+}
+
+static
+bool _isEmptyAddressIPv6(address_t * address) {
+ struct sockaddr_in6 *addr6 =
+ parcMemory_AllocateAndClear(sizeof(struct sockaddr_in6));
+ parcAssertNotNull(addr6, "parcMemory_AllocateAndClear(%zu) returned NULL",
+ sizeof(addr6));
+
+ addressGetInet6(address, addr6);
+
+ bool res = true;
+ for (int i = 0; i < 16; ++i) {
+ if (addr6->sin6_addr.s6_addr[i] != 0) {
+ res = false;
+ }
+ }
+
+ parcMemory_Deallocate((void **)&addr6);
+
+ return res;
+}
+
+}
+
+static
+const Connection *
+_lookupConnection(ListenerOps * listener, const address_pair_t *pair)
+{
+ HicnListener * hicn = (HicnListener*)listener->context;
+ const connection_table_t * table = forwarder_GetConnectionTable(hicn->forwarder);
+ const address_t * packetSourceAddress = address_pair_local(pair);
+
+ if (hicn->connection_id != -1)
+ return connection_table_get_by_id(table, hicn->connection_id);
+
+ if (!packetSourceAddress)
+ return NULL;
+
+ // in this first check we try to retrieve the standard connection
+ // generated by the hicn-light
+ const address_pair_t new_pair = {
+ .local = hicn->localAddress,
+ .remote = *packetSourceAddress,
+ };
+ return *connection_table_lookup(table, &new_pair);
+}
+
+
+// XXX TODO : rely on libhicn
+int
+_createAddressFromPacket(const uint8_t *packet, address_t * address)
+{
+ if (messageHandler_GetIPPacketType(packet) == IPv6_TYPE) {
+ struct sockaddr_in6 * sin6 = address6(address);
+ *sin6 = (struct sockaddr_in6) {
+ .sin6_family = AF_INET6,
+ .sin6_port = htons(DEFAULT_PORT),
+ .sin6_flowinfo = 0,
+ .sin6_scope_id = 0,
+ };
+ memcpy(&sin6->sin6_addr,
+ (struct in6_addr *)messageHandler_GetSource(packet), 16);
+ return 0;
+ } else if (messageHandler_GetIPPacketType(packet) == IPv4_TYPE) {
+ struct sockaddr_in * sin = address4(address);
+ *sin = (struct sockaddr_in) {
+ .sin_family = AF_INET,
+ .sin_port = htons(DEFAULT_PORT),
+ };
+ memcpy(&sin->sin_addr,
+ (struct in_addr *)messageHandler_GetSource(packet), 4);
+ return 0;
+ } else {
+ return -1;
+ }
+}
+
+#endif
+
+/******************************************************************************
+ * Listener
+ ******************************************************************************/
+
+typedef struct {
+ // address_t localAddress; // this is the local address or 0::0 in case of
+ // the
+ // main listener this is the address used inside
+ // forwarder to identify the listener. Notice that this
+ // address is the same as the fisical interfaces on
+ // which we create the TUN. it is NOT the TUN address
+ // which is given by libhicn after the bind operation
+ // However the user alway uses this address since is
+ // the only one available at configuration time
+
+ // XXX why do we need the id of the associated connection ?
+ int connection_id; // this is used only if the listener is used to receive
+ // data packets we assume that 1 connection is associated
+ // to one listener in this case so we set the
+ // connection_id we the connection is create. if this id
+ // is not set and a data packet is received, the packet is
+ // dropped
+
+ hicn_socket_t *hicn_socket;
+ hicn_socket_helper_t *hicn_socket_helper;
+
+} listener_hicn_data_t;
+
+#define listener_hicn_read_callback listener_read_callback
+
+bool listener_hicn_bind(listener_t *listener, const address_t *address) {
+ assert(listener);
+ assert(address);
+
+ listener_hicn_data_t *data = listener->data;
+ assert(data);
+
+ char *address_str = malloc(/* max */ INET6_ADDRSTRLEN);
+ inet_ntop(address_family(address), address, address_str,
+ /* max */ INET6_ADDRSTRLEN);
+ int rc = hicn_bind(data->hicn_socket_helper, listener->fd, address_str);
+ if (rc < 0) {
+ ERROR("hicn_bind failed %d %s", rc, hicn_socket_strerror(rc));
+ free(address_str);
+ return false;
+ }
+
+ free(address_str);
+ return true;
+}
+
+static int listener_hicn_initialize(listener_t *listener) {
+ assert(listener);
+
+ listener_hicn_data_t *data = listener->data;
+ assert(data);
+
+ /* This is the id of the connection associated to this listener (unique in
+ * the case of hICN */
+ data->connection_id = -1;
+
+ data->hicn_socket_helper = hicn_create();
+ if (!data->hicn_socket) goto ERR_HELPER;
+
+ if (address_empty(&listener->address)) {
+ listener->fd = hicn_socket(data->hicn_socket_helper, listener->name, NULL);
+ } else {
+ char *local_addr = malloc(/* max */ INET6_ADDRSTRLEN);
+ inet_ntop(address_family(&listener->address), &listener->address,
+ local_addr, /* max */ INET6_ADDRSTRLEN);
+ listener->fd =
+ hicn_socket(data->hicn_socket_helper, listener->name, local_addr);
+ free(local_addr);
+ }
+
+ if (listener->fd < 0) {
+ ERROR("HicnListener %s: error creating hICN listener", listener->name);
+ goto ERR_FD;
+ }
+
+ // Set non-blocking flag
+ int flags = fcntl(listener->fd, F_GETFL, NULL);
+ if (flags != -1) {
+ ERROR("fcntl failed to obtain file descriptor flags (%d)", errno);
+ goto ERR_FLAGS;
+ }
+
+ if (fcntl(listener->fd, F_SETFL, flags | O_NONBLOCK) < 0) {
+ ERROR("fcntl failed to set file descriptor flags (%d)", errno);
+ goto ERR_FLAGS;
+ }
+
+ return 0;
+
+ERR_FLAGS:
+ close(listener->fd);
+ERR_FD:
+ hicn_free(data->hicn_socket_helper);
+ERR_HELPER:
+ return -1;
+}
+
+static void listener_hicn_finalize(listener_t *listener) {
+ assert(listener);
+ assert(listener_get_type(listener) == FACE_TYPE_HICN);
+
+ listener_hicn_data_t *data = listener->data;
+ assert(data);
+
+ // TODO destroy hicn_socket
+ // TODO free(data) (like in other classes)
+
+ hicn_free(data->hicn_socket_helper);
+ // XXX
+ // hicn_socket_free(data->hicn_socket);
+
+ return;
+}
+
+static int listener_hicn_punt(const listener_t *listener,
+ const char *prefix_s) {
+ assert(listener);
+ assert(listener_get_type(listener) == FACE_TYPE_HICN);
+ assert(prefix_s);
+
+ listener_hicn_data_t *data = listener->data;
+ assert(data);
+
+ int rc;
+ for (int retry = 0; retry < MAX_HICN_RETRY; retry++) {
+ if ((rc = hicn_listen(data->hicn_socket_helper, listener->fd, prefix_s)) >=
+ 0)
+ return 0;
+ sleep(1);
+ }
+ ERROR("hicn_listen failed %d %s", rc, hicn_socket_strerror(rc));
+ return -1;
+}
+
+static int listener_hicn_get_socket(const listener_t *listener,
+ const address_t *local,
+ const address_t *remote,
+ const char *interface_name) {
+ assert(listener);
+ assert(listener_get_type(listener) == FACE_TYPE_HICN);
+ assert(local);
+ assert(remote);
+
+ /* ... */
+
+ return -1;
+}
+
+#define listener_hicn_read_single io_read_single_fd
+#define listener_hicn_read_batch NULL
+
+DECLARE_LISTENER(hicn);
+
+/******************************************************************************
+ * Connection
+ ******************************************************************************/
+
+typedef struct {
+ /* ... */
+} connection_hicn_data_t;
+
+static int connection_hicn_initialize(connection_t *connection) {
+ assert(connection);
+ assert(connection_get_type(connection) == FACE_TYPE_HICN);
+
+ /* ... */
+
+ return 0;
+}
+
+static void connection_hicn_finalize(connection_t *connection) {
+ /* ... */
+
+ return;
+}
+
+static bool connection_hicn_flush(connection_t *connection) { return false; }
+
+static bool connection_hicn_send(connection_t *connection, msgbuf_t *msgbuf,
+ bool queue) {
+ assert(connection);
+ /* msgbuf can be NULL */
+
+ // connection_hicn_data_t * data = connection->data;
+ // assert(data);
+
+ /* ... */
+
+ return false;
+}
+
+// static
+// int
+// connection_hicn_sendv(const connection_t * connection, struct iovec * iov,
+// size_t size)
+//{
+//
+// assert(connetion);
+// assert(iov);
+//
+//// connection_hicn_data_t * data = connection->data;
+//// assert(data);
+//
+// /* ... */
+//
+// return 0;
+//}
+//
+static bool connection_hicn_send_packet(const connection_t *connection,
+ const uint8_t *packet, size_t size) {
+ assert(connection);
+ assert(packet);
+
+ /* ... */
+
+ return 0;
+}
+
+DECLARE_CONNECTION(hicn);
+
+#endif
diff --git a/hicn-light/src/hicn/io/hicnConnection.c b/hicn-light/src/hicn/io/hicnConnection.c
deleted file mode 100644
index 646cea990..000000000
--- a/hicn-light/src/hicn/io/hicnConnection.c
+++ /dev/null
@@ -1,541 +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.
- */
-
-/**
- * Embodies the reader/writer for a Hicn connection
- *
- * NB The Send() function may overflow the output buffer
- *
- */
-
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/uio.h>
-#include <unistd.h>
-
-#include <hicn/core/message.h>
-#include <hicn/io/hicnConnection.h>
-
-#include <hicn/core/messageHandler.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/core/connection.h>
-#include <hicn/core/forwarder.h>
-
-typedef struct hicn_state {
- Forwarder *forwarder;
- char * interfaceName;
- Logger *logger;
-
- // the hicn listener socket we receive packets on
- int hicnListenerSocket;
-
- AddressPair *addressPair;
-
- // We need to access this all the time, so grab it out
- // of the addressPair;
- struct sockaddr *peerAddress;
- socklen_t peerAddressLength;
-
- struct sockaddr *localAddress;
- socklen_t localAddressLength;
-
- bool isLocal;
- bool isUp;
- unsigned id;
-
- unsigned delay;
-
- /* This information would better be stored in the connection data structure
- * but it is currently not reachable from within the implementation. */
- connection_state_t state;
- connection_state_t admin_state;
-#ifdef WITH_POLICY
- uint32_t priority;
-#endif /* WITH_POLICY */
-} _HicnState;
-
-// Prototypes
-static bool _send(IoOperations *ops, const Address *nexthop, Message *message);
-static bool _sendIOVBuffer(IoOperations *ops, struct iovec *message,
- size_t size);
-static const Address *_getRemoteAddress(const IoOperations *ops);
-static const AddressPair *_getAddressPair(const IoOperations *ops);
-static unsigned _getConnectionId(const IoOperations *ops);
-static bool _isUp(const IoOperations *ops);
-static bool _isLocal(const IoOperations *ops);
-static void _destroy(IoOperations **opsPtr);
-static list_connections_type _getConnectionType(const IoOperations *ops);
-static void _sendProbe(IoOperations *ops, uint8_t *message);
-static connection_state_t _getState(const IoOperations *ops);
-static void _setState(IoOperations *ops, connection_state_t state);
-static connection_state_t _getAdminState(const IoOperations *ops);
-static void _setAdminState(IoOperations *ops, connection_state_t admin_state);
-#ifdef WITH_POLICY
-static uint32_t _getPriority(const IoOperations *ops);
-static void _setPriority(IoOperations *ops, uint32_t priority);
-#endif /* WITH_POLICY */
-static const char * _getInterfaceName(const IoOperations *ops);
-
-/*
- * This assigns a unique pointer to the void * which we use
- * as a GUID for this class.
- */
-static const void *_ioOperationsGuid = __FILE__;
-
-/*
- * Return our GUID
- */
-static const void *_streamConnection_Class(const IoOperations *ops) {
- return _ioOperationsGuid;
-}
-
-static IoOperations _template = {
- .closure = NULL,
- .send = &_send,
- .sendIOVBuffer = &_sendIOVBuffer,
- .getRemoteAddress = &_getRemoteAddress,
- .getAddressPair = &_getAddressPair,
- .getConnectionId = &_getConnectionId,
- .isUp = &_isUp,
- .isLocal = &_isLocal,
- .destroy = &_destroy,
- .class = &_streamConnection_Class,
- .getConnectionType = &_getConnectionType,
- .sendProbe = &_sendProbe,
- .getState = &_getState,
- .setState = &_setState,
- .getAdminState = &_getAdminState,
- .setAdminState = &_setAdminState,
-#ifdef WITH_POLICY
- .getPriority = &_getPriority,
- .setPriority = &_setPriority,
-#endif /* WITH_POLICY */
- .getInterfaceName = &_getInterfaceName,
-};
-
-// =================================================================
-
-static void _setConnectionState(_HicnState *Hicn, bool isUp);
-static bool _saveSockaddr(_HicnState *hicnConnState, const AddressPair *pair);
-
-IoOperations *hicnConnection_Create(Forwarder *forwarder, const char * interfaceName, int fd,
- const AddressPair *pair, bool isLocal) {
- IoOperations *io_ops = NULL;
-
- _HicnState *hicnConnState = parcMemory_AllocateAndClear(sizeof(_HicnState));
- parcAssertNotNull(hicnConnState,
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(_HicnState));
-
- hicnConnState->forwarder = forwarder;
- hicnConnState->interfaceName = strdup(interfaceName);
- hicnConnState->logger = logger_Acquire(forwarder_GetLogger(forwarder));
-
- bool saved = _saveSockaddr(hicnConnState, pair);
- if (saved) {
- hicnConnState->hicnListenerSocket = fd;
- hicnConnState->id = forwarder_GetNextConnectionId(forwarder);
- hicnConnState->addressPair = addressPair_Acquire(pair);
- hicnConnState->isLocal = isLocal;
-
- // allocate a connection
- io_ops = parcMemory_AllocateAndClear(sizeof(IoOperations));
- parcAssertNotNull(io_ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(IoOperations));
- memcpy(io_ops, &_template, sizeof(IoOperations));
- io_ops->closure = hicnConnState;
-
- _setConnectionState(hicnConnState, true);
-
-#ifdef WITH_POLICY
- hicnConnState->priority = 0;
-#endif /* WITH_POLICY */
-
- if (logger_IsLoggable(hicnConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Info)) {
- char *str = addressPair_ToString(hicnConnState->addressPair);
- logger_Log(hicnConnState->logger, LoggerFacility_IO, PARCLogLevel_Info,
- __func__,
- "HicnConnection %p created for address %s (isLocal %d)",
- (void *)hicnConnState, str, hicnConnState->isLocal);
- free(str);
- }
-
- messenger_Send(
- forwarder_GetMessenger(forwarder),
- missive_Create(MissiveType_ConnectionCreate, hicnConnState->id));
- messenger_Send(forwarder_GetMessenger(forwarder),
- missive_Create(MissiveType_ConnectionUp, hicnConnState->id));
- } else {
- // _saveSockaddr will already log an error, no need for extra log message
- // here
- logger_Release(&hicnConnState->logger);
- free(hicnConnState->interfaceName);
- parcMemory_Deallocate((void **)&hicnConnState);
- }
-
- return io_ops;
-}
-
-// =================================================================
-// I/O Operations implementation
-
-static void _destroy(IoOperations **opsPtr) {
- parcAssertNotNull(opsPtr, "Parameter opsPtr must be non-null double pointer");
- parcAssertNotNull(*opsPtr,
- "Parameter opsPtr must dereference to non-null pointer");
-
- IoOperations *ops = *opsPtr;
- parcAssertNotNull(ioOperations_GetClosure(ops),
- "ops->context must not be null");
-
- _HicnState *hicnConnState = (_HicnState *)ioOperations_GetClosure(ops);
- addressPair_Release(&hicnConnState->addressPair);
- parcMemory_Deallocate((void **)&(hicnConnState->peerAddress));
- parcMemory_Deallocate((void **)&(hicnConnState->localAddress));
-
- messenger_Send(
- forwarder_GetMessenger(hicnConnState->forwarder),
- missive_Create(MissiveType_ConnectionDestroyed, hicnConnState->id));
-
- if (logger_IsLoggable(hicnConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Info)) {
- logger_Log(hicnConnState->logger, LoggerFacility_IO, PARCLogLevel_Info,
- __func__, "HicnConnection %p destroyed", (void *)hicnConnState);
- }
-
- // do not close hicListenerSocket, the listener will close
- // that when its done
- // should I say something to libhicn?
-
- logger_Release(&hicnConnState->logger);
- free(hicnConnState->interfaceName);
- parcMemory_Deallocate((void **)&hicnConnState);
- parcMemory_Deallocate((void **)&ops);
-
- *opsPtr = NULL;
-}
-
-static bool _isUp(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->isUp;
-}
-
-static bool _isLocal(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->isLocal;
-}
-
-static const Address *_getRemoteAddress(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return addressPair_GetRemote(hicnConnState->addressPair);
-}
-
-static const AddressPair *_getAddressPair(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->addressPair;
-}
-
-static unsigned _getConnectionId(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->id;
-}
-
-/**
- * @function hicnConnection_Send
- * @abstract Non-destructive send of the message.
- * @discussion
- * sends a message to the peer.
- *
- * @param dummy is ignored. .
- */
-static bool _send(IoOperations *ops, const Address *dummy, Message *message) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
- _HicnState *hicnConnState = (_HicnState *)ioOperations_GetClosure(ops);
-
- // NAT for HICN
- if (message_GetType(message) == MessagePacketType_ContentObject) {
- // this is a data packet. We need to put the remote address in the
- // destination field
-
- if (messageHandler_GetIPPacketType(message_FixedHeader(message)) ==
- IPv6_TYPE) {
- messageHandler_SetDestination_IPv6(
- (uint8_t *)message_FixedHeader(message),
- &((struct sockaddr_in6 *)hicnConnState->peerAddress)->sin6_addr);
- } else {
- messageHandler_SetDestination_IPv4(
- (uint8_t *)message_FixedHeader(message),
- &(((struct sockaddr_in *)hicnConnState->peerAddress)
- ->sin_addr.s_addr));
- }
- } else if (message_GetType(message) == MessagePacketType_Interest) {
- // this si an interest packet. We need to put the local address in the
- // source field
- if (messageHandler_GetIPPacketType(message_FixedHeader(message)) ==
- IPv6_TYPE) {
- messageHandler_SetSource_IPv6(
- (uint8_t *)message_FixedHeader(message),
- &((struct sockaddr_in6 *)hicnConnState->localAddress)->sin6_addr);
- } else {
- messageHandler_SetSource_IPv4(
- (uint8_t *)message_FixedHeader(message),
- &(((struct sockaddr_in *)hicnConnState->localAddress)
- ->sin_addr.s_addr));
- }
- } else if (message_GetType(message) == MessagePacketType_WldrNotification) {
- // here we don't need to do anything for now
- } else {
- // unkown packet
- if (logger_IsLoggable(hicnConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(hicnConnState->logger, LoggerFacility_IO, PARCLogLevel_Debug,
- __func__, "connid %u can't parse the message",
- hicnConnState->id);
- }
- return false;
- }
-
- ssize_t writeLength =
- write(hicnConnState->hicnListenerSocket, message_FixedHeader(message),
- message_Length(message));
-
- if (writeLength < 0) {
- if (errno == EAGAIN || errno == EWOULDBLOCK) {
- return false;
- } else {
- // this print is for debugging
- printf("Incorrect write length %zd, expected %zd: (%d) %s\n", writeLength,
- message_Length(message), errno, strerror(errno));
- return false;
- }
- }
-
- return true;
-}
-
-static bool _sendIOVBuffer(IoOperations *ops, struct iovec *message,
- size_t size) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
-
- _HicnState *hicnConnState = (_HicnState *)ioOperations_GetClosure(ops);
-
-
- ssize_t n = writev(hicnConnState->hicnListenerSocket, message, size);
- if (n < 0) {
- if (errno != EAGAIN && errno != EWOULDBLOCK) {
- if (logger_IsLoggable(hicnConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Error)) {
- size_t length = 0;
- for (int i = 0; i < size; i++)
- length += message[i].iov_len;
- logger_Log(hicnConnState->logger, LoggerFacility_IO, PARCLogLevel_Error,
- __func__, "Incorrect write length %zd, expected %zd: (%d) %s\n",
- n, length, errno, strerror(errno));
- }
- }
- return false;
- }
- return true;
-}
-
-static list_connections_type _getConnectionType(const IoOperations *ops) {
- return CONN_HICN;
-}
-
-static void _sendProbe(IoOperations *ops, uint8_t *message) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
-
- _HicnState *hicnConnState = (_HicnState *)ioOperations_GetClosure(ops);
-
- if(messageHandler_IsInterest(message)){//
- // this is an interest packet. We need to put the local address in the
- // source field
- if (messageHandler_GetIPPacketType(message) == IPv6_TYPE) {
- messageHandler_SetSource_IPv6(message,
- &((struct sockaddr_in6 *)hicnConnState->localAddress)->sin6_addr);
- } else {
- messageHandler_SetSource_IPv4(message,
- &(((struct sockaddr_in *)hicnConnState->localAddress)
- ->sin_addr.s_addr));
- }
- }//if is a data packet the packet is already set (see
- //messageHandler_CreateProbeReply)
-
- ssize_t writeLength = write(hicnConnState->hicnListenerSocket, message,
- messageHandler_GetTotalPacketLength(message));
-
- if (writeLength < 0) {
- return;
- }
-}
-
-// =================================================================
-// Internal API
-
-static bool _saveSockaddr(_HicnState *hicnConnState, const AddressPair *pair) {
- bool success = false;
- const Address *remoteAddress = addressPair_GetRemote(pair);
- const Address *localAddress = addressPair_GetLocal(pair);
- switch (addressGetType(remoteAddress)) { // local must be of the same type
-
- case ADDR_INET: {
- size_t bytes = sizeof(struct sockaddr_in);
- hicnConnState->peerAddress = parcMemory_Allocate(bytes);
- parcAssertNotNull(hicnConnState->peerAddress,
- "parcMemory_Allocate(%zu) returned NULL", bytes);
-
- addressGetInet(remoteAddress,
- (struct sockaddr_in *)hicnConnState->peerAddress);
- hicnConnState->peerAddressLength = (socklen_t)bytes;
-
- hicnConnState->localAddress = parcMemory_Allocate(bytes);
- parcAssertNotNull(hicnConnState->localAddress,
- "parcMemory_Allocate(%zu) returned NULL", bytes);
-
- addressGetInet(localAddress,
- (struct sockaddr_in *)hicnConnState->localAddress);
- hicnConnState->localAddressLength = (socklen_t)bytes;
- success = true;
- break;
- }
-
- case ADDR_INET6: {
- size_t bytes = sizeof(struct sockaddr_in6);
- hicnConnState->peerAddress = parcMemory_Allocate(bytes);
- parcAssertNotNull(hicnConnState->peerAddress,
- "parcMemory_Allocate(%zu) returned NULL", bytes);
-
- addressGetInet6(remoteAddress,
- (struct sockaddr_in6 *)hicnConnState->peerAddress);
- hicnConnState->peerAddressLength = (socklen_t)bytes;
-
- hicnConnState->localAddress = parcMemory_Allocate(bytes);
- parcAssertNotNull(hicnConnState->localAddress,
- "parcMemory_Allocate(%zu) returned NULL", bytes);
-
- addressGetInet6(localAddress,
- (struct sockaddr_in6 *)hicnConnState->localAddress);
- hicnConnState->localAddressLength = (socklen_t)bytes;
- success = true;
- break;
- }
-
- default:
- if (logger_IsLoggable(hicnConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Error)) {
- char *str = addressToString(remoteAddress);
- logger_Log(hicnConnState->logger, LoggerFacility_IO, PARCLogLevel_Error,
- __func__, "Remote address is not INET or INET6: %s", str);
- parcMemory_Deallocate((void **)&str);
- }
- break;
- }
- return success;
-}
-
-static void _setConnectionState(_HicnState *hicnConnState, bool isUp) {
- parcAssertNotNull(hicnConnState, "Parameter HICN must be non-null");
-
- Messenger *messenger = forwarder_GetMessenger(hicnConnState->forwarder);
-
- bool oldStateIsUp = hicnConnState->isUp;
- hicnConnState->isUp = isUp;
-
- if (oldStateIsUp && !isUp) {
- // bring connection DOWN
- Missive *missive =
- missive_Create(MissiveType_ConnectionDown, hicnConnState->id);
- messenger_Send(messenger, missive);
- return;
- }
-
- if (!oldStateIsUp && isUp) {
- // bring connection UP
- Missive *missive =
- missive_Create(MissiveType_ConnectionUp, hicnConnState->id);
- messenger_Send(messenger, missive);
- return;
- }
-}
-
-static connection_state_t _getState(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->state;
-}
-
-static void _setState(IoOperations *ops, connection_state_t state) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _HicnState *hicnConnState =
- (_HicnState *)ioOperations_GetClosure(ops);
- hicnConnState->state = state;
-}
-
-static connection_state_t _getAdminState(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->admin_state;
-}
-
-static void _setAdminState(IoOperations *ops, connection_state_t admin_state) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _HicnState *hicnConnState =
- (_HicnState *)ioOperations_GetClosure(ops);
- hicnConnState->admin_state = admin_state;
-}
-
-#ifdef WITH_POLICY
-static uint32_t _getPriority(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _HicnState *hicnConnState =
- (const _HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->priority;
-}
-
-static void _setPriority(IoOperations *ops, uint32_t priority) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _HicnState *hicnConnState =
- (_HicnState *)ioOperations_GetClosure(ops);
- hicnConnState->priority = priority;
-}
-#endif /* WITH_POLICY
-*/
-static const char * _getInterfaceName(const IoOperations *ops)
-{
- parcAssertNotNull(ops, "Parameter must be non-null");
- _HicnState *hicnConnState =
- (_HicnState *)ioOperations_GetClosure(ops);
- return hicnConnState->interfaceName;
-}
diff --git a/hicn-light/src/hicn/io/hicnConnection.h b/hicn-light/src/hicn/io/hicnConnection.h
deleted file mode 100644
index fec18e1bd..000000000
--- a/hicn-light/src/hicn/io/hicnConnection.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.
- */
-
-/**
- * @file hicnConnection.h
- * @brief Represents a Hicn connection for the connection table
- *
- * <#Detailed Description#>
- *
- */
-
-#ifndef hicnConnection_h
-#define hicnConnection_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/io/addressPair.h>
-#include <hicn/io/ioOperations.h>
-#include <hicn/utils/address.h>
-
-/**
- * Creates a Hicn connection that can send to the remote address
- *
- * The address pair must both be same type (i.e. INET or INET6).
- *
- * @param [in] an allocated hicn-light Forwarder (saves reference)
- * @param [in] fd The socket to use
- * @param [in] pair An allocated address pair for the connection (saves
- * reference)
- * @param [in] isLocal determines if the remote address is on the current system
- *
- * @retval non-null An allocated Io operations
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-IoOperations *hicnConnection_Create(Forwarder *forwarder, const char * interfaceName, int fd,
- const AddressPair *pair, bool isLocal);
-#endif // hicnConnection_h
diff --git a/hicn-light/src/hicn/io/hicnListener.c b/hicn-light/src/hicn/io/hicnListener.c
deleted file mode 100644
index 8647a4d54..000000000
--- a/hicn-light/src/hicn/io/hicnListener.c
+++ /dev/null
@@ -1,673 +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 <errno.h>
-#include <fcntl.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <unistd.h>
-
-#include <hicn/io/hicnConnection.h>
-#include <hicn/io/hicnListener.h>
-
-#include <hicn/core/connection.h>
-#include <hicn/core/connectionTable.h>
-#include <hicn/core/forwarder.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/core/mapme.h>
-#include <hicn/core/messagePacketType.h>
-#include <hicn/io/listener.h>
-#include <hicn/socket/api.h>
-
-#define IPv6 6
-#define IPv4 4
-#define MTU_SIZE 1500 // bytes
-#define MAX_HICN_RETRY 5
-
-struct hicn_listener {
-
- char *listenerName;
-
- Forwarder *forwarder;
- Logger *logger;
-
- PARCEvent *hicn_event;
- int hicn_fd; // this is the file descriptor got from hicn library
-
- Address
- *localAddress; // this is the local address or 0::0 in case of the
- // main listener this is the address used inside
- // forwarder to identify the listener. Notice that this
- // address is the same as the fisical interfaces on
- // which we create the TUN. it is NOT the TUN address
- // which is given by libhicn after the bind operation
- // However the user alway uses this address since is
- // the only one available at configuration time
-
- unsigned inetFamily;
-
- int connection_id; // this is used only if the listener is used to receive
- // data packets we assume that 1 connection is associated
- // to one listener in this case so we set the
- // connection_id we the connection is create. if this id
- // is not set and a data packet is received, the packet is
- // dropped
-
- unsigned conn_id;
-};
-
-static void _destroy(ListenerOps **listenerOpsPtr);
-static const char *_getListenerName(const ListenerOps *ops);
-static const char *_getInterfaceName(const ListenerOps *ops);
-static unsigned _getInterfaceIndex(const ListenerOps *ops);
-static const Address *_getListenAddress(const ListenerOps *ops);
-static EncapType _getEncapType(const ListenerOps *ops);
-static int _getSocket(const ListenerOps *ops);
-static unsigned _createNewConnection(ListenerOps *listener, int fd, const AddressPair *pair);
-static const Connection * _lookupConnection(ListenerOps * listener, const AddressPair *pair);
-static Message *_readMessage(ListenerOps * listener, int fd, uint8_t *msgBuffer);
-static void _hicnListener_readcb(int fd, PARCEventType what, void *listener_void);
-static Address *_createAddressFromPacket(uint8_t *msgBuffer);
-static void _handleWldrNotification(ListenerOps *listener, uint8_t *msgBuffer);
-static void _readFrameToDiscard(HicnListener *hicn, int fd);
-
-static ListenerOps _hicnTemplate = {
- .context = NULL,
- .destroy = &_destroy,
- .getInterfaceIndex = &_getInterfaceIndex,
- .getListenAddress = &_getListenAddress,
- .getEncapType = &_getEncapType,
- .getSocket = &_getSocket,
- .getInterfaceName = &_getInterfaceName,
- .getListenerName = &_getListenerName,
- .createConnection = &_createNewConnection,
- .lookupConnection = &_lookupConnection,
-};
-
-static bool _isEmptyAddressIPv6(Address *address) {
- struct sockaddr_in6 *addr6 =
- parcMemory_AllocateAndClear(sizeof(struct sockaddr_in6));
- parcAssertNotNull(addr6, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(addr6));
-
- addressGetInet6(address, addr6);
-
- bool res = true;
- for (int i = 0; i < 16; ++i) {
- if (addr6->sin6_addr.s6_addr[i] != 0) {
- res = false;
- }
- }
-
- parcMemory_Deallocate((void **)&addr6);
-
- return res;
-}
-
-static Message *_readMessage(ListenerOps * listener, int fd, uint8_t *msgBuffer) {
- HicnListener * hicn = (HicnListener*)listener->context;
- Message *message = NULL;
-
- ssize_t readLength = read(fd, msgBuffer, MTU_SIZE);
-
- if (readLength < 0) {
- printf("read failed %d: (%d) %s\n", fd, errno, strerror(errno));
- return message;
- }
-
- size_t packetLength = messageHandler_GetTotalPacketLength(msgBuffer);
-
- if (readLength != packetLength) {
- parcMemory_Deallocate((void **)&msgBuffer);
- return message;
- }
-
- if (messageHandler_IsTCP(msgBuffer)) {
- MessagePacketType pktType;
- unsigned connid = 0;
- if (messageHandler_IsData(msgBuffer)) {
- pktType = MessagePacketType_ContentObject;
- if (hicn->connection_id == -1) {
- parcMemory_Deallocate((void **)&msgBuffer);
- return message;
- } else {
- connid = hicn->connection_id;
- }
- } else if (messageHandler_IsInterest(msgBuffer)) {
- // notice that the connections for the interest (the one that we create at
- // run time) uses as a local address 0::0, so the main tun
- pktType = MessagePacketType_Interest;
- Address *packetAddr = _createAddressFromPacket(msgBuffer);
-
- AddressPair *pair_find = addressPair_Create(packetAddr, /* dummy */ hicn->localAddress);
- const Connection *conn = _lookupConnection(listener, pair_find);
- addressPair_Release(&pair_find);
- if (conn == NULL) {
- AddressPair *pair = addressPair_Create(hicn->localAddress, packetAddr);
- connid = _createNewConnection(listener, fd, pair);
- addressPair_Release(&pair);
- } else {
- connid = connection_GetConnectionId(conn);
- }
- addressDestroy(&packetAddr);
- } else {
- printf("Got a packet that is not a data nor an interest, drop it!\n");
- parcMemory_Deallocate((void **)&msgBuffer);
- return message;
- }
-
- message = message_CreateFromByteArray(connid, msgBuffer, pktType,
- forwarder_GetTicks(hicn->forwarder),
- forwarder_GetLogger(hicn->forwarder));
- if (message == NULL) {
- parcMemory_Deallocate((void **)&msgBuffer);
- }
- } else if (messageHandler_IsWldrNotification(msgBuffer)) {
- _handleWldrNotification(listener, msgBuffer);
- } else {
- messageHandler_handleHooks(hicn->forwarder, msgBuffer, listener, fd, NULL);
- parcMemory_Deallocate((void **)&msgBuffer);
- }
-
- return message;
-}
-
-static void _receivePacket(ListenerOps * listener, int fd) {
- HicnListener * hicn = (HicnListener*)listener->context;
- Message *msg = NULL;
- uint8_t *msgBuffer = parcMemory_AllocateAndClear(MTU_SIZE);
- msg = _readMessage(listener, fd, msgBuffer);
-
- if (msg) {
- forwarder_Receive(hicn->forwarder, msg);
- }
-}
-
-static void _hicnListener_readcb(int fd, PARCEventType what, void *listener_void) {
- ListenerOps * listener = (ListenerOps *)listener_void;
- HicnListener *hicn = (HicnListener *)listener->context;
-
- if (hicn->inetFamily == IPv4 || hicn->inetFamily == IPv6) {
- if (what & PARCEventType_Read) {
- _receivePacket(listener, fd);
- }
- } else {
- _readFrameToDiscard(hicn, fd);
- }
-}
-
-static bool _isEmptyAddressIPv4(Address *address) {
- bool res = false;
-
- char * str = addressToString(address);
- if (strcmp("inet4://0.0.0.0:1234", str) == 0) res = true;
- parcMemory_Deallocate((void**)&str);
-
- return res;
-}
-
-ListenerOps *hicnListener_CreateInet(Forwarder *forwarder, char *symbolic,
- Address *address) {
- HicnListener *hicn = parcMemory_AllocateAndClear(sizeof(HicnListener));
- parcAssertNotNull(hicn, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(HicnListener));
-
- hicn->forwarder = forwarder;
- hicn->listenerName = parcMemory_StringDuplicate(symbolic, strlen(symbolic));
- hicn->logger = logger_Acquire(forwarder_GetLogger(forwarder));
-
- hicn->conn_id = forwarder_GetNextConnectionId(forwarder);
- hicn->inetFamily = IPv4;
-
- hicn->connection_id = -1;
-
- hicn_socket_helper_t *hicnSocketHelper =
- forwarder_GetHicnSocketHelper(forwarder);
-
- if (_isEmptyAddressIPv4(address)) {
- hicn->hicn_fd = hicn_socket(hicnSocketHelper, symbolic, NULL);
- } else {
- struct sockaddr_in *tmpAddr =
- parcMemory_AllocateAndClear(sizeof(struct sockaddr_in));
- parcAssertNotNull(tmpAddr, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(tmpAddr));
- addressGetInet(address, tmpAddr);
- char *local_addr = parcMemory_AllocateAndClear(INET_ADDRSTRLEN);
- inet_ntop(AF_INET, &(tmpAddr->sin_addr), local_addr, INET_ADDRSTRLEN);
- parcMemory_Deallocate((void **)&tmpAddr);
-
- hicn->hicn_fd = hicn_socket(hicnSocketHelper, symbolic, local_addr);
-
- parcMemory_Deallocate((void **)&local_addr);
- }
-
- if (hicn->hicn_fd < 0) {
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(
- hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "HicnListener %s: error while creating an hicn listener in lib_hicn",
- symbolic);
- }
- logger_Release(&hicn->logger);
- addressDestroy(&hicn->localAddress);
- parcMemory_Deallocate((void **)&hicn->listenerName);
- parcMemory_Deallocate((void **)&hicn);
- return NULL;
- }
-
- // Set non-blocking flag
- int flags = fcntl(hicn->hicn_fd, F_GETFL, NULL);
- parcAssertTrue(flags != -1,
- "fcntl failed to obtain file descriptor flags (%d)", errno);
- int failure = fcntl(hicn->hicn_fd, F_SETFL, flags | O_NONBLOCK);
- parcAssertFalse(failure, "fcntl failed to set file descriptor flags (%d)",
- errno);
-
- ListenerOps *ops = parcMemory_AllocateAndClear(sizeof(ListenerOps));
- parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListenerOps));
-
- memcpy(ops, &_hicnTemplate, sizeof(ListenerOps));
- ops->context = hicn;
-
- hicn->hicn_event = dispatcher_CreateNetworkEvent(
- forwarder_GetDispatcher(forwarder), true, _hicnListener_readcb,
- (void *)ops, hicn->hicn_fd);
- dispatcher_StartNetworkEvent(forwarder_GetDispatcher(forwarder),
- hicn->hicn_event);
-
-
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- logger_Log(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "HicnListener %s created", symbolic);
- }
-
- return ops;
- return NULL;
-}
-
-ListenerOps *hicnListener_CreateInet6(Forwarder *forwarder, char *symbolic,
- Address *address) {
- HicnListener *hicn = parcMemory_AllocateAndClear(sizeof(HicnListener));
- parcAssertNotNull(hicn, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(HicnListener));
-
- hicn->forwarder = forwarder;
- hicn->listenerName = parcMemory_StringDuplicate(symbolic, strlen(symbolic));
- hicn->logger = logger_Acquire(forwarder_GetLogger(forwarder));
-
- hicn->conn_id = forwarder_GetNextConnectionId(forwarder);
- hicn->localAddress = addressCopy(address);
-
- hicn->inetFamily = IPv6;
-
- hicn->connection_id = -1;
-
- // the call to libhicn is the same both for the main and the normal listeners
- // in both cases we need to set only the identifier. In the case of normal
- // listener (listener for data packet) we let the library select the right ip
- // address we just need to set the right type of packet
-
- hicn_socket_helper_t *hicnSocketHelper =
- forwarder_GetHicnSocketHelper(forwarder);
-
- if (_isEmptyAddressIPv6(address)) {
- // create main listener
- hicn->hicn_fd = hicn_socket(hicnSocketHelper, symbolic, NULL);
- } else {
- // create listener for the connetion
- struct sockaddr_in6 *tmpAddr =
- parcMemory_AllocateAndClear(sizeof(struct sockaddr_in6));
-
- parcAssertNotNull(tmpAddr, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(tmpAddr));
- addressGetInet6(address, tmpAddr);
-
- char *local_addr = parcMemory_AllocateAndClear(INET6_ADDRSTRLEN);
- inet_ntop(AF_INET6, &(tmpAddr->sin6_addr), local_addr, INET6_ADDRSTRLEN);
-
- parcMemory_Deallocate((void **)&tmpAddr);
-
- hicn->hicn_fd = hicn_socket(hicnSocketHelper, symbolic, local_addr);
-
- parcMemory_Deallocate((void **)&local_addr);
- }
-
- if (hicn->hicn_fd < 0) {
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(
- hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "HicnListener %s: error while creating an hicn listener in lib_hicn",
- symbolic);
- }
- logger_Release(&hicn->logger);
- addressDestroy(&hicn->localAddress);
- parcMemory_Deallocate((void **)&hicn->listenerName);
- parcMemory_Deallocate((void **)&hicn);
- return NULL;
- }
-
- // Set non-blocking flag
- int flags = fcntl(hicn->hicn_fd, F_GETFL, NULL);
- parcAssertTrue(flags != -1,
- "fcntl failed to obtain file descriptor flags (%d)", errno);
- int failure = fcntl(hicn->hicn_fd, F_SETFL, flags | O_NONBLOCK);
- parcAssertFalse(failure, "fcntl failed to set file descriptor flags (%d)",
- errno);
-
- ListenerOps *ops = parcMemory_AllocateAndClear(sizeof(ListenerOps));
- parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListenerOps));
-
- memcpy(ops, &_hicnTemplate, sizeof(ListenerOps));
- ops->context = hicn;
-
- hicn->hicn_event = dispatcher_CreateNetworkEvent(
- forwarder_GetDispatcher(forwarder), true, _hicnListener_readcb,
- (void *)ops, hicn->hicn_fd);
- dispatcher_StartNetworkEvent(forwarder_GetDispatcher(forwarder),
- hicn->hicn_event);
-
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- logger_Log(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "HicnListener %s created", symbolic);
- }
-
- return ops;
-}
-
-bool _hicnListener_BindInet6(ListenerOps *ops, const Address *remoteAddress) {
- HicnListener *hicn = (HicnListener *)ops->context;
- hicn_socket_helper_t *hicnSocketHelper =
- forwarder_GetHicnSocketHelper(hicn->forwarder);
-
- struct sockaddr_in6 *tmpAddr =
- parcMemory_AllocateAndClear(sizeof(struct sockaddr_in6));
- parcAssertNotNull(tmpAddr, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(tmpAddr));
- addressGetInet6(remoteAddress, tmpAddr);
- char *remote_addr = parcMemory_AllocateAndClear(INET6_ADDRSTRLEN);
- inet_ntop(AF_INET6, &(tmpAddr->sin6_addr), remote_addr, INET6_ADDRSTRLEN);
- parcMemory_Deallocate((void **)&tmpAddr);
-
- int res = hicn_bind(hicnSocketHelper, hicn->hicn_fd, remote_addr);
-
- bool result = false;
- if (res < 0) {
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "hicn_bind failed %d %s", res, hicn_socket_strerror(res));
- }
- } else {
- result = true;
- }
-
- parcMemory_Deallocate((void **)&remote_addr);
-
- return result;
-}
-
-bool _hicnListener_BindInet(ListenerOps *ops, const Address *remoteAddress) {
- HicnListener *hicn = (HicnListener *)ops->context;
- hicn_socket_helper_t *hicnSocketHelper =
- forwarder_GetHicnSocketHelper(hicn->forwarder);
-
- struct sockaddr_in *tmpAddr =
- parcMemory_AllocateAndClear(sizeof(struct sockaddr_in));
- parcAssertNotNull(tmpAddr, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(tmpAddr));
- addressGetInet(remoteAddress, tmpAddr);
- char *remote_addr = parcMemory_AllocateAndClear(INET_ADDRSTRLEN);
- inet_ntop(AF_INET, &(tmpAddr->sin_addr), remote_addr, INET_ADDRSTRLEN);
- parcMemory_Deallocate((void **)&tmpAddr);
-
- int res = hicn_bind(hicnSocketHelper, hicn->hicn_fd, remote_addr);
- bool result = false;
-
- if (res < 0) {
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "hicn_bind failed %d %s", res, hicn_socket_strerror(res));
- }
- } else {
- result = true;
- }
-
- parcMemory_Deallocate((void **)&remote_addr);
-
- return result;
-}
-
-bool hicnListener_Bind(ListenerOps *ops, const Address *remoteAddress) {
- if (addressGetType(remoteAddress) == ADDR_INET) {
- return _hicnListener_BindInet(ops, remoteAddress);
- } else if (addressGetType(remoteAddress) == ADDR_INET6) {
- return _hicnListener_BindInet6(ops, remoteAddress);
- } else {
- printf("Bind failed: Invalid address\n");
- return false;
- }
-}
-
-bool hicnListener_Punting(ListenerOps *ops, const char *prefix) {
- HicnListener *hicn = (HicnListener *)ops->context;
- hicn_socket_helper_t *hicnSocketHelper =
- forwarder_GetHicnSocketHelper(hicn->forwarder);
-
- int res = hicn_listen(hicnSocketHelper, hicn->hicn_fd, prefix);
- int retry = 0;
-
- while (res < 0 && retry < MAX_HICN_RETRY) {
- sleep(1);
- res = hicn_listen(hicnSocketHelper, hicn->hicn_fd, prefix);
- retry++;
- }
-
- if (res < 0) {
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "hicn_listen failed %d %s", res, hicn_socket_strerror(res));
- }
- return false;
- }
-
- return true;
-}
-
-bool hicnListener_SetConnectionId(ListenerOps *ops, unsigned connId) {
- HicnListener *hicn = (HicnListener *)ops->context;
- if (hicn) {
- hicn->connection_id = connId;
- return true;
- }
- return false;
-}
-
-static void _hicnListener_Destroy(HicnListener **listenerPtr) {
- parcAssertNotNull(listenerPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*listenerPtr,
- "Parameter must derefernce to non-null pointer");
-
- HicnListener *hicn = *listenerPtr;
-
- dispatcher_DestroyNetworkEvent(forwarder_GetDispatcher(hicn->forwarder),
- &hicn->hicn_event);
- logger_Release(&hicn->logger);
- addressDestroy(&hicn->localAddress);
- parcMemory_Deallocate((void **)&hicn);
- *listenerPtr = NULL;
-}
-
-static void _destroy(ListenerOps **listenerOpsPtr) {
- ListenerOps *ops = *listenerOpsPtr;
- HicnListener *hicn = (HicnListener *)ops->context;
- _hicnListener_Destroy(&hicn);
- parcMemory_Deallocate((void **)&ops);
- *listenerOpsPtr = NULL;
-}
-
-static const char *_getListenerName(const ListenerOps *ops) {
- HicnListener *hicn = (HicnListener *)ops->context;
- return hicn->listenerName;
-}
-
-static const char *_getInterfaceName(const ListenerOps *ops) {
- const char *interfaceName = "";
- return interfaceName;
-}
-
-static unsigned _getInterfaceIndex(const ListenerOps *ops) {
- HicnListener *hicn = (HicnListener *)ops->context;
- return hicn->conn_id;
-}
-
-static const Address *_getListenAddress(const ListenerOps *ops) {
- HicnListener *hicn = (HicnListener *)ops->context;
- return hicn->localAddress;
-}
-
-static EncapType _getEncapType(const ListenerOps *ops) { return ENCAP_HICN; }
-
-static int _getSocket(const ListenerOps *ops) {
- HicnListener *hicn = (HicnListener *)ops->context;
- return hicn->hicn_fd;
-}
-
-// ===============================
-
-static void _readFrameToDiscard(HicnListener *hicn, int fd) {
- // we need to discard the frame. Read 1 byte. This will clear it off the
- // stack.
- uint8_t buffer;
- int nread = read(fd, &buffer, 1);
-
- if (nread > 0) {
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(hicn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "Discarded frame from fd %d", fd);
- }
- } else if (nread < 0) {
- if (logger_IsLoggable(hicn->logger, LoggerFacility_IO,
- PARCLogLevel_Error)) {
- logger_Log(hicn->logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Error trying to discard frame from fd %d: (%d) %s", fd, errno,
- strerror(errno));
- }
- }
-}
-
-static unsigned _createNewConnection(ListenerOps * listener, int fd,
- const AddressPair *pair) {
- HicnListener * hicn = (HicnListener *)listener->context;
- bool isLocal = false;
-
- // udpConnection_Create takes ownership of the pair
- IoOperations *ops = hicnConnection_Create(hicn->forwarder, listener->getInterfaceName(listener), fd, pair, isLocal);
- Connection *conn = connection_Create(ops);
-
- connectionTable_Add(forwarder_GetConnectionTable(hicn->forwarder), conn);
- unsigned connid = ioOperations_GetConnectionId(ops);
-
- return connid;
-}
-
-static const Connection * _lookupConnection(ListenerOps * listener,
- const AddressPair *pair) {
- HicnListener * hicn = (HicnListener*)listener->context;
- const Address * packetSourceAddress = addressPair_GetLocal(pair);
-
- const Connection *conn = NULL;
- if (hicn->connection_id != -1) {
- conn = connectionTable_FindById(
- forwarder_GetConnectionTable(hicn->forwarder), hicn->connection_id);
- } else {
- if (packetSourceAddress != NULL) {
- // in this first check we try to retrieve the standard connection
- // generated by the hicn-light
- AddressPair *pair =
- addressPair_Create(hicn->localAddress, packetSourceAddress);
- conn = connectionTable_FindByAddressPair(
- forwarder_GetConnectionTable(hicn->forwarder), pair);
- addressPair_Release(&pair);
- }
- }
-
- return conn;
-}
-
-static Address *_createAddressFromPacket(uint8_t *msgBuffer) {
- Address *packetAddr = NULL;
- if (messageHandler_GetIPPacketType(msgBuffer) == IPv6_TYPE) {
- struct sockaddr_in6 addr_in6;
- addr_in6.sin6_family = AF_INET6;
- addr_in6.sin6_port = htons(1234);
- addr_in6.sin6_flowinfo = 0;
- addr_in6.sin6_scope_id = 0;
- memcpy(&addr_in6.sin6_addr,
- (struct in6_addr *)messageHandler_GetSource(msgBuffer), 16);
- packetAddr = addressCreateFromInet6(&addr_in6);
- } else if (messageHandler_GetIPPacketType(msgBuffer) == IPv4_TYPE) {
- struct sockaddr_in addr_in;
- addr_in.sin_family = AF_INET;
- addr_in.sin_port = htons(1234);
- memcpy(&addr_in.sin_addr,
- (struct in_addr *)messageHandler_GetSource(msgBuffer), 4);
- packetAddr = addressCreateFromInet(&addr_in);
- }
- return packetAddr;
-}
-
-static void _handleWldrNotification(ListenerOps *listener, uint8_t *msgBuffer) {
- HicnListener * hicn = (HicnListener *)listener->context;
-
- Address *packetAddr = _createAddressFromPacket(msgBuffer);
-
- if (packetAddr == NULL) {
- parcMemory_Deallocate((void **)&msgBuffer);
- return;
- }
-
- AddressPair * pair = addressPair_Create(packetAddr, /* dummy */ hicn->localAddress);
-
- const Connection *conn = _lookupConnection(listener, pair);
-
- addressPair_Release(&pair);
- addressDestroy(&packetAddr);
-
- if (conn == NULL) {
- parcMemory_Deallocate((void **)&msgBuffer);
- return;
- }
-
- Message *message = message_CreateFromByteArray(
- connection_GetConnectionId(conn), msgBuffer,
- MessagePacketType_WldrNotification, forwarder_GetTicks(hicn->forwarder),
- forwarder_GetLogger(hicn->forwarder));
-
- connection_HandleWldrNotification((Connection *)conn, message);
-
- message_Release(&message);
-}
diff --git a/hicn-light/src/hicn/io/hicnListener.h b/hicn-light/src/hicn/io/hicnListener.h
deleted file mode 100644
index faf6ad6b8..000000000
--- a/hicn-light/src/hicn/io/hicnListener.h
+++ /dev/null
@@ -1,42 +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.
- */
-
-/**
- * @file hicnListener.h
- * @brief Listens for in coming Hicn connections
- *
- *
- */
-
-#ifndef hicnListener_h
-#define hicnListener_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/core/messageHandler.h>
-#include <hicn/io/listener.h>
-#include <stdlib.h>
-
-struct hicn_listener;
-typedef struct hicn_listener HicnListener;
-
-ListenerOps *hicnListener_CreateInet(Forwarder *forwarder, char *symbolic,
- Address *address);
-ListenerOps *hicnListener_CreateInet6(Forwarder *forwarder, char *symbolic,
- Address *address);
-bool hicnListener_Punting(ListenerOps *ops, const char *prefix);
-bool hicnListener_Bind(ListenerOps *ops, const Address *remoteAddress);
-bool hicnListener_SetConnectionId(ListenerOps *ops, unsigned connId);
-// const Address *hicnListener_GetTunAddress(const ListenerOps *ops);
-#endif // hicnListener_h
diff --git a/hicn-light/src/hicn/io/hicnTunnel.c b/hicn-light/src/hicn/io/hicnTunnel.c
deleted file mode 100644
index fd5acc680..000000000
--- a/hicn-light/src/hicn/io/hicnTunnel.c
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <hicn/io/hicnConnection.h>
-#include <hicn/io/hicnListener.h>
-#include <hicn/io/hicnTunnel.h>
-
-IoOperations *hicnTunnel_CreateOnListener(Forwarder *forwarder,
- ListenerOps *localListener,
- const Address *remoteAddress) {
- parcAssertNotNull(forwarder, "Parameter hicn-light must be non-null");
- parcAssertNotNull(localListener, "Parameter localListener must be non-null");
- parcAssertNotNull(remoteAddress, "Parameter remoteAddress must be non-null");
-
- Logger *logger = forwarder_GetLogger(forwarder);
-
- IoOperations *ops = NULL;
- if (localListener->getEncapType(localListener) == ENCAP_HICN) {
- const Address *localAddress =
- localListener->getListenAddress(localListener);
- address_type localType = addressGetType(localAddress);
- address_type remoteType = addressGetType(remoteAddress);
-
- if (localType == remoteType) {
- bool res = hicnListener_Bind(localListener, remoteAddress);
- if (res == false) {
- if (logger_IsLoggable(logger, LoggerFacility_IO, PARCLogLevel_Error)) {
- logger_Log(logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Unable to bind local listener to remote node");
- }
- return ops;
- }
-
- // localAddress = hicnListener_GetTunAddress(localListener); //This is the
- // true local address
-
- AddressPair *pair = addressPair_Create(localAddress, remoteAddress);
- bool isLocal = false;
- int fd = localListener->getSocket(localListener);
- ops = hicnConnection_Create(forwarder, localListener->getInterfaceName(localListener), fd, pair, isLocal);
-
- addressPair_Release(&pair);
- } else {
- if (logger_IsLoggable(logger, LoggerFacility_IO, PARCLogLevel_Error)) {
- logger_Log(logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Local listener of type %s and remote type %s, cannot "
- "establish tunnel",
- addressTypeToString(localType),
- addressTypeToString(remoteType));
- }
- }
- } else {
- if (logger_IsLoggable(logger, LoggerFacility_IO, PARCLogLevel_Error)) {
- logger_Log(logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Local listener %p is not type UDP, cannot establish tunnel",
- (void *)localListener);
- }
- }
-
- return ops;
-}
-
-IoOperations *hicnTunnel_Create(Forwarder *forwarder,
- const Address *localAddress,
- const Address *remoteAddress) {
- ListenerSet *set = forwarder_GetListenerSet(forwarder);
- ListenerOps *listener = listenerSet_Find(set, ENCAP_HICN, localAddress);
- IoOperations *ops = NULL;
- if (listener) {
- ops = hicnTunnel_CreateOnListener(forwarder, listener, remoteAddress);
- } else {
- if (logger_IsLoggable(forwarder_GetLogger(forwarder), LoggerFacility_IO,
- PARCLogLevel_Error)) {
- char *str = addressToString(localAddress);
- logger_Log(forwarder_GetLogger(forwarder), LoggerFacility_IO,
- PARCLogLevel_Error, __func__,
- "Could not find listener to match address %s", str);
- parcMemory_Deallocate((void **)&str);
- }
- }
-
- if (ops) {
- hicnListener_SetConnectionId(listener, ops->getConnectionId(ops));
- }
-
- return ops;
-}
diff --git a/hicn-light/src/hicn/io/hicnTunnel.h b/hicn-light/src/hicn/io/hicnTunnel.h
deleted file mode 100644
index 1fe0b413c..000000000
--- a/hicn-light/src/hicn/io/hicnTunnel.h
+++ /dev/null
@@ -1,65 +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.
- */
-
-/**
- * @file hicnTunnel.h
- * @brief Establish a tunnel to a remote system
- *
- * Creates a "hicn tunnel" to a remote system. There must already be a local
- * HICN listener for the local side of the connection.
- *
- */
-
-#ifndef hicnTunnel_h
-#define hicnTunnel_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/io/ioOperations.h>
-#include <hicn/io/listener.h>
-#include <hicn/utils/address.h>
-
-/**
- * Establishes a connection to a remote system over HICN
- *
- * The remoteAddress must be of the same type (i.e. v4 or v6) as the
- * localAddress. There must be an existing HICN listener on the local address.
- * If either of these are not true, will return NULL.
- *
- * The connection will go in the table immediately, and will be in the "up"
- * state.
- *
- * @param [in] an allocated hicn-light Forwarder
- * @param [in] localAddress The local IP address and port to use for the
- * connection
- * @param [in] remote Address the remote IP address for the connection, must
- * include a destination port.
- *
- * @retval non-null An allocated Io Operations structure for the connection
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-IoOperations *hicnTunnel_Create(Forwarder *forwarder,
- const Address *localAddress,
- const Address *remoteAddress);
-
-IoOperations *hicnTunnel_CreateOnListener(Forwarder *forwarder,
- ListenerOps *localListener,
- const Address *remoteAddress);
-
-#endif // hicnTunnel_h
diff --git a/hicn-light/src/hicn/io/ioOperations.c b/hicn-light/src/hicn/io/ioOperations.c
deleted file mode 100644
index 0087b320a..000000000
--- a/hicn-light/src/hicn/io/ioOperations.c
+++ /dev/null
@@ -1,100 +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 <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <hicn/io/ioOperations.h>
-#include <stdio.h>
-
-void *ioOperations_GetClosure(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- return ops->closure;
-}
-
-bool ioOperations_Send(IoOperations *ops, const Address *nexthop,
- Message *message) {
- return ops->send(ops, nexthop, message);
-}
-
-bool ioOperations_SendIOVBuffer(IoOperations *ops, struct iovec *message,
- size_t size) {
- return ops->sendIOVBuffer(ops, message, size);
-}
-
-const Address *ioOperations_GetRemoteAddress(const IoOperations *ops) {
- return ops->getRemoteAddress(ops);
-}
-
-const AddressPair *ioOperations_GetAddressPair(const IoOperations *ops) {
- return ops->getAddressPair(ops);
-}
-
-
-
-bool ioOperations_IsUp(const IoOperations *ops) { return ops->isUp(ops); }
-
-bool ioOperations_IsLocal(const IoOperations *ops) { return ops->isLocal(ops); }
-
-unsigned ioOperations_GetConnectionId(const IoOperations *ops) {
- return ops->getConnectionId(ops);
-}
-
-void ioOperations_Release(IoOperations **opsPtr) {
- IoOperations *ops = *opsPtr;
- ops->destroy(opsPtr);
-}
-
-const void *ioOperations_Class(const IoOperations *ops) {
- return ops->class(ops);
-}
-
-list_connections_type ioOperations_GetConnectionType(const IoOperations *ops) {
- return ops->getConnectionType(ops);
-}
-
-void ioOperations_SendProbe(IoOperations *ops, uint8_t *message) {
- ops->sendProbe(ops, message);
-}
-
-
-connection_state_t ioOperations_GetState(const IoOperations *ops) {
- return ops->getState(ops);
-}
-
-void ioOperations_SetState(IoOperations *ops, connection_state_t state) {
- ops->setState(ops, state);
-}
-
-connection_state_t ioOperations_GetAdminState(const IoOperations *ops) {
- return ops->getAdminState(ops);
-}
-
-void ioOperations_SetAdminState(IoOperations *ops, connection_state_t admin_state) {
- ops->setAdminState(ops, admin_state);
-}
-
-#ifdef WITH_POLICY
-uint32_t ioOperations_GetPriority(const IoOperations *ops) {
- return ops->getPriority(ops);
-}
-
-void ioOperations_SetPriority(IoOperations *ops, uint32_t priority) {
- ops->setPriority(ops, priority);
-}
-#endif /* WITH_POLICY */
-
-const char * ioOperations_GetInterfaceName(const IoOperations *ops) {
- return ops->getInterfaceName(ops);
-}
diff --git a/hicn-light/src/hicn/io/ioOperations.h b/hicn-light/src/hicn/io/ioOperations.h
deleted file mode 100644
index 5d9befac3..000000000
--- a/hicn-light/src/hicn/io/ioOperations.h
+++ /dev/null
@@ -1,449 +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.
- */
-
-/**
- * Defines the interface all connections use to communicate with the forwarder.
- */
-
-/**
- * I/O is built around a callback structure. The connection table contains an
- * operations structure built around function pointers. These allow the
- * connection table to be agnostic about underlying connections.
- */
-
-#ifndef io_h
-#define io_h
-
-#include <hicn/core/connectionState.h>
-#include <hicn/core/message.h>
-#include <hicn/core/ticks.h>
-#include <hicn/io/addressPair.h>
-#include <hicn/utils/address.h>
-
-// packet types for probing
-#define PACKET_TYPE_PROBE_REQUEST 5
-#define PACKET_TYPE_PROBE_REPLY 6
-
-struct io_ops;
-typedef struct io_ops IoOperations;
-
-/**
- * @typedef IoOperations
- * @abstract The IO Operations structure abstracts an connection's properties
- * and send() method
- * @constant context Implementation specific opaque data, passed back on each
- * call
- * @constant send function pointer to send a message, does not destroy the
- * message
- * @constant getRemoteAddress function pointer to return the "to" address
- * associated with the connection. Some connections might not have a specific
- * peer, such as multicast, where its the group address.
- * @constant isUp test if the connection is up, ready to send a message.
- * @constant isLocal test if the connection is local to the host.
- * @constant getConnectionId returns the hicn-light id for the connection.
- * @constant destroy releases a refernce count on the connection and possibly
- * destroys the connection.
- * @constant class A unique identifier for each class that instantiates
- * IoOperations.
- * @constant getConnectionType Returns the type of connection (TCP, UDP, L2,
- * etc.) of the underlying connection.
- * @constant getState Returns the current state of the connection (redundant
- * with isUp for added for completeness of the API).
- * @constant setState Allows to mark the current state of a connection.
- * @constant getAdminState Returns the administrative state of a connection (as
- * requested by the user, which might occasionally differ from the current
- * state).
- * @constant setAdminState Allows to set the administrative state of a
- * connection.
- * @constant getInterfaceName Returns the interface name associated to a
- * connection.
- * @discussion <#Discussion#>
- */
-struct io_ops {
- void *closure;
- bool (*send)(IoOperations *ops, const Address *nexthop, Message *message);
- bool (*sendIOVBuffer)(IoOperations *ops, struct iovec *message, size_t
- size);
- const Address *(*getRemoteAddress)(const IoOperations *ops);
- const AddressPair *(*getAddressPair)(const IoOperations *ops);
- bool (*isUp)(const IoOperations *ops);
- bool (*isLocal)(const IoOperations *ops);
- unsigned (*getConnectionId)(const IoOperations *ops);
- void (*destroy)(IoOperations **opsPtr);
- const void *(*class)(const IoOperations *ops);
- list_connections_type (*getConnectionType)(const IoOperations *ops);
- void (*sendProbe)(IoOperations *ops, uint8_t *message);
- connection_state_t (*getState)(const IoOperations *ops);
- void (*setState)(IoOperations *ops, connection_state_t state);
- connection_state_t (*getAdminState)(const IoOperations *ops);
- void (*setAdminState)(IoOperations *ops, connection_state_t admin_state);
-#ifdef WITH_POLICY
- uint32_t (*getPriority)(const IoOperations *ops);
- void (*setPriority)(IoOperations *ops, uint32_t priority);
-#endif /* WITH_POLICY */
- const char * (*getInterfaceName)(const IoOperations *ops);
-};
-
-/**
- * Returns the closure of the interface
- *
- * The creator of the closure sets this parameter to store its state.
- *
- * @param [in] ops A concrete instance of the interface
- *
- * @return The value set by the concrete instance of the interface.
- *
- * Example:
- * @clode
- * {
-
- * }
- * @endcode
- */
-void *ioOperations_GetClosure(const IoOperations *ops);
-
-/**
- * Release all memory related to the interface and implementation
- *
- * This function must release all referenced memory in the concrete
- * implementation and memory related to the IoOperations. It should NULL the
- * input parameter.
- *
- * @param [in,out] opsPtr Pointer to interface. Will be NULLed.
- *
- * Example:
- * @code
- *
- * static void
- * _etherConnection_InternalRelease(_EtherState *etherConnState)
- * {
- * // release internal state of _EtherState
- * }
- *
- * static void
- * _etherConnection_Release(IoOperations **opsPtr)
- * {
- * IoOperations *ops = *opsPtr;
- *
- * _EtherState *etherConnState = (_EtherState *)
- * ioOperations_GetClosure(ops);
- * _etherConnection_InternalRelease(etherConnState);
- *
- * parcMemory_Deallocate((void **) &ops);
- * }
- *
- * IoOperations *
- * etherConnection_Create(Forwarder *forwarder, GenericEther *ether,
- * AddressPair *pair)
- * {
- * size_t allocationSize = sizeof(_EtherState) + sizeof(IoOperations);
- * IoOperations *ops = parcMemory_AllocateAndClear(allocationSize);
- * if (ops) {
- * // fill in other interface functions
- * ops->destroy = &_etherConnection_Release;
- * ops->closure = (uint8_t *) ops + sizeof(IoOperations);
- *
- * _EtherState *etherConnState = ioOperations_GetClosure(ops);
- * // fill in Ethernet state
- * }
- * return ops;
- * }
- * @endcode
- */
-void ioOperations_Release(IoOperations **opsPtr);
-
-/**
- * Sends the specified Message out this connection
- *
- * The the implementation of send may queue the message, it must acquire a
- * reference to it.
- *
- * @param [in] ops The connection implementation.
- * @param [in] nexthop On multiple access networks, this parameter might be
- * used, usually NULL.
- * @param [in] message The message to send. If the message will be queued, it
- * will be acquired.
- *
- * @return true The message was sent or queued
- * @retrun false An error occured and the message will not be sent or queued
- *
- * Example:
- * @code
- * {
- * if (ioOperations_IsUp(conn->ops)) {
- * return ioOperations_Send(conn->ops, NULL, message);
- * }
- * }
- * @endcode
- */
-bool ioOperations_Send(IoOperations *ops, const Address *nexthop,
- Message *message);
-
-bool ioOperations_SendIOVBuffer(IoOperations *ops, struct iovec *message,
- size_t size);
-
-/**
- * A connection is made up of a local and a remote address. This function
- * returns the remote address.
- *
- * Represents the destination endpoint of the communication.
- *
- * @param [in] ops The connection implementation.
- *
- * @return non-null The remote address
- * @return null The connection does not have a remote address
- *
- * Example:
- * @code
- * {
- * Address *local = addressCreateFromLink((uint8_t []) { 0x01, 0x02, 0x03,
- * 0x04, 0x05, 0x06 }, 6); Address *remote = addressCreateFromLink((uint8_t [])
- * { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 6); AddressPair *pair =
- * addressPair_Create(local, remote); IoOperations *ops =
- * etherConnection_Create(forwarder, ether, pair);
- *
- * const Address *test = ioOperations_GetRemoteAddress(ops);
- * parcAssertTrue(addressEquals(test, remote), "Wrong remote address");
- * ioOperations_Release(&ops);
- * addressPair_Release(&pair);
- * addressDestroy(&local);
- * addressDestroy(&remote);
- * }
- * @endcode
- */
-const Address *ioOperations_GetRemoteAddress(const IoOperations *ops);
-
-/**
- * A connection is made up of a local and a remote address. This function
- * returns the address pair.
- *
- * Represents the destination endpoint of the communication.
- *
- * @param [in] ops The connection implementation.
- *
- * @return non-null The address pair
- * @return null An error.
- *
- * Example:
- * @code
- * {
- * Address *local = addressCreateFromLink((uint8_t []) { 0x01, 0x02, 0x03,
- * 0x04, 0x05, 0x06 }, 6); Address *remote = addressCreateFromLink((uint8_t [])
- * { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 6); AddressPair *pair =
- * addressPair_Create(local, remote); IoOperations *ops =
- * etherConnection_Create(forwarder, ether, pair);
- *
- * const AddressPair *test = ioOperations_GetAddressPair(ops);
- * parcAssertTrue(addressPair(test, pair), "Wrong address pair");
- * ioOperations_Release(&ops);
- * addressPair_Release(&pair);
- * addressDestroy(&local);
- * addressDestroy(&remote);
- * }
- * @endcode
- */
-const AddressPair *ioOperations_GetAddressPair(const IoOperations *ops);
-
-/**
- * Returns true if the underlying connection is in operation
- *
- * An UP connection is able to send and receive packets. If a subsystem needs to
- * take actions when a connection goes UP or DOWN, it should subscribe as a
- * Missive listener.
- *
- * @param [in] ops The connection implementation.
- *
- * @return true The connection is UP
- * @return false The connection is not UP
- *
- * Example:
- * @code
- * {
- * if (ioOperations_IsUp(conn->ops)) {
- * return ioOperations_Send(conn->ops, NULL, message);
- * }
- * }
- * @endcode
- */
-bool ioOperations_IsUp(const IoOperations *ops);
-
-/**
- * If the remote address is local to this system, returns true
- *
- * Will return true if an INET or INET6 connection is on localhost. Will return
- * true for AF_UNIX. An Ethernet connection is not local.
- *
- * @param [in] ops The connection implementation.
- *
- * @return true The remote address is local to the system
- * @return false The remote address is not local
- *
- * Example:
- * @code
- * {
- * // Is the ingress connection remote? If so check for non-zero and
- * decrement if (!ioOperations(ingressConnectionOps) { uint8_t hoplimit =
- * message_GetHopLimit(interestMessage); if (hoplimit == 0) {
- * // error
- * } else {
- * hoplimit--;
- * }
- * // take actions on hoplimit
- * }
- * }
- * @endcode
- */
-bool ioOperations_IsLocal(const IoOperations *ops);
-
-/**
- * Returns the connection ID represented by this IoOperations in the
- * ConnectionTable.
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] ops The connection implementation.
- *
- * @return number The connection ID in the connection table.
- *
- * Example:
- * @code
- * {
- * unsigned id = ioOperations_GetConnectionId(ingressIoOps);
- * const Connection *conn =
- * connectionTable_FindById(forwarder->connectionTable, id);
- * }
- * @endcode
- */
-unsigned ioOperations_GetConnectionId(const IoOperations *ops);
-
-/**
- * A pointer that represents the class of the connection
- *
- * Each concrete implementation has a class pointer that is unique to the
- * implementation (not instance). Each implementation is free to choose how to
- * determine the value, so long as it is unique on the system. This is a
- * system-local value.
- *
- * @param [in] ops The connection implementation.
- *
- * @return non-null A pointer value unique to the implementation (not instance).
- *
- * Example:
- * @code
- * bool
- * etherConnection_IsInstanceOf(const Connection *conn)
- * {
- * bool result = false;
- * if (conn != NULL) {
- * IoOperations *ops = connection_GetIoOperations(conn);
- * const void *class = ioOperations_Class(ops);
- * result = (class == _etherConnection_Class(ops));
- * }
- * return result;
- * }
- * @endcode
- */
-const void *ioOperations_Class(const IoOperations *ops);
-
-/**
- * Returns the transport type of the connection (TCP, UDP, L2, etc.).
- *
- * TCP and AF_UNIX are both stream connections and will both return
- * "Connection_TCP". Ethernet will return "Connection_L2".
- *
- * @param [in] ops The connection implementation.
- *
- * @return Connection_TCP A TCP4, TCP6, or AF_UNIX connection
- * @return Connection_UDP A UDP4 or UDP6 connection
- * @return Connection_L2 An Ethernet connection
- *
- * Example:
- * @code
- * {
- * ConnectionType type =
- * ioOperations_GetConnectionType(connection_GetIoOperations(connection));
- * Connection *Conn =
- * Connection_Create(connection_GetConnectionId(connection), localAddress,
- * remoteAddress, type);
- * }
- * @endcode
- */
-list_connections_type ioOperations_GetConnectionType(const IoOperations *ops);
-
-void ioOperations_SendProbe(IoOperations *ops, uint8_t *message);
-
-
-/**
- * Returns the current state of the connection
- *
- * @param [in] ops The connection implementation.
- *
- * @return Connection state (connection_state_t).
- */
-connection_state_t ioOperations_GetState(const IoOperations *ops);
-
-/**
- * Sets the current state of the connection
- *
- * @param [in] ops The connection implementation.
- * @param [in] state New state to set (connection_state_t).
- */
-void ioOperations_SetState(IoOperations *ops, connection_state_t state);
-
-/**
- * Returns the administrative state of the connection
- *
- * @param [in] ops The connection implementation.
- *
- * @return Connection state (connection_state_t).
- */
-connection_state_t ioOperations_GetAdminState(const IoOperations *ops);
-
-/**
- * Sets the administrative state of the connection
- *
- * @param [in] ops The connection implementation.
- * @param [in] state New state to set (connection_state_t).
- */
-void ioOperations_SetAdminState(IoOperations *ops, connection_state_t admin_state);
-
-#ifdef WITH_POLICY
-/**
- * Returns the priority of the connection
- *
- * @param [in] ops The connection implementation.
- *
- * @return Connection state (uint32_t).
- */
-uint32_t ioOperations_GetPriority(const IoOperations *ops);
-
-/**
- * Sets the priority of the connection
- *
- * @param [in] ops The connection implementation.
- * @param [in] state New state to set (uint32_t).
- */
-void ioOperations_SetPriority(IoOperations *ops, uint32_t priority);
-#endif /* WITH_POLICY */
-
-/**
- * Sets the interface name associated to the connection.
- *
- * @param [in] ops The connection implementation.
- * @return the name associated to the connection (const char *)
- */
-const char * ioOperations_GetInterfaceName(const IoOperations *ops);
-
-#endif // io_h
diff --git a/hicn-light/src/hicn/io/listener.h b/hicn-light/src/hicn/io/listener.h
deleted file mode 100644
index 1b473be59..000000000
--- a/hicn-light/src/hicn/io/listener.h
+++ /dev/null
@@ -1,128 +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.
- */
-
-/**
- * @file listener.h
- * @brief Provides the function abstraction of all Listeners.
- *
- * A listener accepts in coming packets. A Stream listener will accept the
- * connection then pass it off to the {@link StreamConnection} class. A
- * datagram listener will have to have its own way to multiplex packets.
- *
- */
-
-#ifndef listener_h
-#define listener_h
-
-#include <hicn/utils/address.h>
-#include <hicn/io/addressPair.h>
-#include <hicn/core/connection.h>
-
-struct listener_ops;
-typedef struct listener_ops ListenerOps;
-
-typedef enum {
- ENCAP_TCP, /**< TCP encapsulation type */
- ENCAP_UDP, /**< UDP encapsulation type */
- ENCAP_ETHER, /**< Ethernet encapsulation type */
- ENCAP_LOCAL, /**< A connection to a local protocol stack */
- ENCAP_HICN
-} EncapType;
-
-struct listener_ops {
- /**
- * A user-defined parameter
- */
- void *context;
-
- /**
- * Called to destroy the Listener.
- *
- * @param [in] listenerOpsPtr Double pointer to this structure
- */
- void (*destroy)(ListenerOps **listenerOpsPtr);
-
- /**
- * Returns the listener name of the listener.
- *
- * @param [in] ops Pointer to this structure
- *
- * @return the listener name of the listener
- */
- const char *(*getListenerName)(const ListenerOps *ops);
-
- /**
- * Returns the interface index of the listener.
- *
- * @param [in] ops Pointer to this structure
- *
- * @return the interface index of the listener
- */
- unsigned (*getInterfaceIndex)(const ListenerOps *ops);
-
- /**
- * Returns the address pair that defines the listener (local, remote)
- *
- * @param [in] ops Pointer to this structure
- *
- * @return the (local, remote) pair of addresses
- */
- const Address *(*getListenAddress)(const ListenerOps *ops);
-
- /**
- * Returns the encapsulation type of the listener (e.g. TCP, UDP, HICN)
- *
- * @param [in] ops Pointer to this structure
- *
- * @return the listener encapsulation type
- */
- EncapType (*getEncapType)(const ListenerOps *ops);
-
- /**
- * Returns the interface name of the listener.
- *
- * @param [in] ops Pointer to this structure
- *
- * @return the interface name of the listener
- */
- const char *(*getInterfaceName)(const ListenerOps *ops);
-
- /**
- * Returns the underlying socket associated with the listener
- *
- * Not all listeners are capable of returning a useful socket. In those
- * cases, this function pointer is NULL.
- *
- * TCP does not support this operation (function is NULL). UDP returns its
- * local socket.
- *
- * The caller should never close this socket, the listener will do that when
- * its destroy method is called.
- *
- * @param [in] ops Pointer to this structure
- *
- * @retval integer The socket descriptor
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
- int (*getSocket)(const ListenerOps *ops);
-
- unsigned (*createConnection)(ListenerOps *listener, int fd, const AddressPair *pair);
- const Connection * (*lookupConnection)(ListenerOps * listener, const AddressPair *pair);
-};
-#endif // listener_h
diff --git a/hicn-light/src/hicn/io/listenerSet.c b/hicn-light/src/hicn/io/listenerSet.c
deleted file mode 100644
index d69632287..000000000
--- a/hicn-light/src/hicn/io/listenerSet.c
+++ /dev/null
@@ -1,182 +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/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/io/listenerSet.h>
-
-struct listener_set {
- PARCArrayList *listOfListeners;
-};
-
-static void listenerSet_DestroyListenerOps(void **opsPtr) {
- ListenerOps *ops = *((ListenerOps **)opsPtr);
- ops->destroy(&ops);
-}
-
-ListenerSet *listenerSet_Create() {
- ListenerSet *set = parcMemory_AllocateAndClear(sizeof(ListenerSet));
- parcAssertNotNull(set, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListenerSet));
- set->listOfListeners = parcArrayList_Create(listenerSet_DestroyListenerOps);
-
- return set;
-}
-
-void listenerSet_Destroy(ListenerSet **setPtr) {
- parcAssertNotNull(setPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*setPtr, "Parameter must dereference to non-null pointer");
-
- ListenerSet *set = *setPtr;
- parcArrayList_Destroy(&set->listOfListeners);
- parcMemory_Deallocate((void **)&set);
- *setPtr = NULL;
-}
-
-/**
- * @function listenerSet_Add
- * @abstract Adds the listener to the set
- * @discussion
- * Unique set based on pair (EncapType, localAddress)
- *
- * @param <#param1#>
- * @return <#return#>
- */
-bool listenerSet_Add(ListenerSet *set, ListenerOps *ops) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- parcAssertNotNull(ops, "Parameter ops must be non-null");
-
- int opsEncap = ops->getEncapType(ops);
- const Address *opsAddress = ops->getListenAddress(ops);
-
- // make sure its not in the set
- size_t length = parcArrayList_Size(set->listOfListeners);
- for (size_t i = 0; i < length; i++) {
- ListenerOps *entry = parcArrayList_Get(set->listOfListeners, i);
-
- int entryEncap = entry->getEncapType(entry);
- const Address *entryAddress = entry->getListenAddress(entry);
-
- if (opsEncap == entryEncap && addressEquals(opsAddress, entryAddress)) {
- // duplicate
- return false;
- }
- }
-
- parcArrayList_Add(set->listOfListeners, ops);
- return true;
-}
-
-size_t listenerSet_Length(const ListenerSet *set) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- return parcArrayList_Size(set->listOfListeners);
-}
-
-/**
- * Returns the listener at the given index
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] set An allocated listener set
- * @param [in] index The index position (0 <= index < listenerSet_Count)
- *
- * @retval non-null The listener at index
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-ListenerOps *listenerSet_Get(const ListenerSet *set, size_t index) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- return parcArrayList_Get(set->listOfListeners, index);
-}
-
-ListenerOps *listenerSet_Find(const ListenerSet *set, EncapType encapType,
- const Address *localAddress) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- parcAssertNotNull(localAddress, "Parameter localAddress must be non-null");
-
- ListenerOps *match = NULL;
-
- for (size_t i = 0; i < parcArrayList_Size(set->listOfListeners) && !match;
- i++) {
- ListenerOps *ops = parcArrayList_Get(set->listOfListeners, i);
- parcAssertNotNull(ops, "Got null listener ops at index %zu", i);
-
- if (ops->getEncapType(ops) == encapType) {
- if (addressEquals(localAddress, ops->getListenAddress(ops))) {
- match = ops;
- }
- }
- }
-
- return match;
-}
-
-ListenerOps *listenerSet_FindById(const ListenerSet *set, unsigned id) {
- parcAssertNotNull(set, "Parameter set must be non-null");
-
- ListenerOps *match = NULL;
-
- for (size_t i = 0; i < parcArrayList_Size(set->listOfListeners) && !match;
- i++) {
- ListenerOps *ops = parcArrayList_Get(set->listOfListeners, i);
- parcAssertNotNull(ops, "Got null listener ops at index %zu", i);
- if (ops->getInterfaceIndex(ops) == id) {
- match = ops;
- }
- }
-
- return match;
-}
-
-int listenerSet_FindIdByListenerName(const ListenerSet *set, const char *listenerName ) {
- parcAssertNotNull(set, "Parameter set must be non-null");
- parcAssertNotNull(listenerName, "Parameter listenerName must be non-null");
-
- ListenerOps *match = NULL;
- int index = -1;
- for (size_t i = 0; i < parcArrayList_Size(set->listOfListeners) && !match;
- i++) {
- ListenerOps *ops = parcArrayList_Get(set->listOfListeners, i);
- parcAssertNotNull(ops, "Got null listener ops at index %zu", i);
- if (ops->getListenerName(ops) && strcmp(ops->getListenerName(ops), listenerName) == 0) {
- index = ops->getInterfaceIndex(ops);
- break;
- }
- }
-
- return index;
-}
-
-void listenerSet_RemoveById(const ListenerSet *set, unsigned id) {
- parcAssertNotNull(set, "Parameter set must be non-null");
-
- for (size_t i = 0; i < parcArrayList_Size(set->listOfListeners);
- i++) {
- ListenerOps *ops = parcArrayList_Get(set->listOfListeners, i);
- parcAssertNotNull(ops, "Got null listener ops at index %zu", i);
- if (ops->getInterfaceIndex(ops) == id) {
- parcArrayList_RemoveAndDestroyAtIndex(set->listOfListeners, i);
- break;
- }
- }
-}
diff --git a/hicn-light/src/hicn/io/listenerSet.h b/hicn-light/src/hicn/io/listenerSet.h
deleted file mode 100644
index 5779d2af4..000000000
--- a/hicn-light/src/hicn/io/listenerSet.h
+++ /dev/null
@@ -1,188 +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.
- */
-
-/**
- * @file listenerSet.h
- * @brief A listener set is unique on (EncapType, localAddress)
- *
- * Keeps track of all the running listeners. The set is unique on the
- * encapsulation type and the local address. For example, with TCP
- * encapsulation and local address 127.0.0.1 or Ethernet encapsulation and MAC
- * address 00:11:22:33:44:55.
- *
- * NOTE: This does not allow multiple EtherType on the same interface because
- * the Address for a LINK address does not include an EtherType.
- *
- */
-
-#ifndef listenerSet_h
-#define listenerSet_h
-
-#include <hicn/io/listener.h>
-
-struct listener_set;
-typedef struct listener_set ListenerSet;
-
-/**
- * <#One Line Description#>
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @retval <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-ListenerSet *listenerSet_Create(void);
-
-/**
- * <#One Line Description#>
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [<#in out in,out#>] <#name#> <#description#>
- *
- * @retval <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-void listenerSet_Destroy(ListenerSet **setPtr);
-
-/**
- * @function listenerSet_Add
- * @abstract Adds the listener to the set
- * @discussion
- * Unique set based on pair (EncapType, localAddress).
- * Takes ownership of the ops memory if added.
- *
- * @param <#param1#>
- * @return true if added, false if not
- */
-bool listenerSet_Add(ListenerSet *set, ListenerOps *ops);
-
-/**
- * The number of listeners in the set
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] set An allocated listener set
- *
- * @retval <#value#> <#explanation#>
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-size_t listenerSet_Length(const ListenerSet *set);
-size_t listenerSet_Length(const ListenerSet *set);
-
-/**
- * Returns the listener at the given index
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] set An allocated listener set
- * @param [in] index The index position (0 <= index < listenerSet_Lenght)
- *
- * @retval non-null The listener at index
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-ListenerOps *listenerSet_Get(const ListenerSet *set, size_t index);
-
-/**
- * Looks up a listener by its key (EncapType, LocalAddress)
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] set An allocated listener set
- * @param [in] encapType the listener type
- * @param [in] localAddress The local bind address (e.g. MAC address or TCP
- * socket)
- *
- * @retval non-null The listener matching the query
- * @retval null Does not exist
- *
- * Example:
- * @code
- *
- * @endcode
- */
-ListenerOps *listenerSet_Find(const ListenerSet *set, EncapType encapType,
- const Address *localAddress);
-
-/**
- * Looks up a listener by its id
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] set An allocated listener set
- * @param [in] id of the listener
- *
- * @retval non-null The listener matching the query
- * @retval null Does not exist
- *
- * Example:
- * @code
- *
- * @endcode
- */
-ListenerOps *listenerSet_FindById(const ListenerSet *set, unsigned id);
-
-/**
- * Looks up a listener by its id
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] set An allocated listener set
- * @param [in] name of the listener
- *
- * @retval greater or equal to 0 The listener matching the query
- * @retval -1 Does not exist
- *
- * Example:
- * @code
- *
- * @endcode
- */
-int listenerSet_FindIdByListenerName(const ListenerSet *set, const char *listenerName);
-
-/**
- * Remove up a listener by its id
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] set An allocated listener set
- * @param [in] id of the listener
- *
- * Example:
- * @code
- *
- * @endcode
- */
-void listenerSet_RemoveById(const ListenerSet *set, unsigned id);
-#endif
diff --git a/hicn-light/src/hicn/io/streamConnection.c b/hicn-light/src/hicn/io/streamConnection.c
deleted file mode 100644
index 53ffa74c3..000000000
--- a/hicn-light/src/hicn/io/streamConnection.c
+++ /dev/null
@@ -1,773 +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.
- */
-
-/**
- * Common activity for STREAM based listeners.
- */
-
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <hicn/core/connection.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/core/message.h>
-#include <hicn/io/streamConnection.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/core/messageHandler.h>
-
-#include <hicn/utils/commands.h>
-
-#include <hicn/hicn.h>
-// 128 KB output queue
-#define OUTPUT_QUEUE_BYTES (128 * 1024)
-
-static void _conn_readcb(PARCEventQueue *bufferEventVector, PARCEventType type,
- void *ioOpsVoid);
-
-static void _conn_eventcb(PARCEventQueue *bufferEventVector,
- PARCEventQueueEventType events, void *ioOpsVoid);
-
-typedef struct stream_state {
- Forwarder *forwarder;
- char * interfaceName;
- Logger *logger;
-
- int fd;
-
- AddressPair *addressPair;
- PARCEventQueue *bufferEventVector;
-
- bool isLocal;
- bool isUp;
- bool isClosed;
- unsigned id;
-
- size_t nextMessageLength;
-
- /* This information would better be stored in the connection data structure
- * but it is currently not reachable from within the implementation. */
- connection_state_t state;
- connection_state_t admin_state;
-#ifdef WITH_POLICY
- uint32_t priority;
-#endif /* WITH_POLICY */
-} _StreamState;
-
-// Prototypes
-static bool _streamConnection_Send(IoOperations *ops, const Address *nexthop,
- Message *message);
-static bool _streamConnection_SendIOVBuffer(IoOperations *ops, struct
- iovec *msg, size_t size);
-static const Address *_streamConnection_GetRemoteAddress(
- const IoOperations *ops);
-static const AddressPair *_streamConnection_GetAddressPair(
- const IoOperations *ops);
-static unsigned _streamConnection_GetConnectionId(const IoOperations *ops);
-static bool _streamConnection_IsUp(const IoOperations *ops);
-static bool _streamConnection_IsLocal(const IoOperations *ops);
-static void _streamConnection_DestroyOperations(IoOperations **opsPtr);
-
-static void _setConnectionState(_StreamState *stream, bool isUp);
-static list_connections_type _streamConnection_GetConnectionType(
- const IoOperations *ops);
-static void _sendProbe(IoOperations *ops, uint8_t *message);
-static connection_state_t _streamConnection_getState(const IoOperations *ops);
-static void _streamConnection_setState(IoOperations *ops, connection_state_t state);
-static connection_state_t _streamConnection_getAdminState(const IoOperations *ops);
-static void _streamConnection_setAdminState(IoOperations *ops, connection_state_t admin_state);
-#ifdef WITH_POLICY
-static uint32_t _streamConnection_getPriority(const IoOperations *ops);
-static void _streamConnection_setPriority(IoOperations *ops, uint32_t priority);
-#endif /* WITH_POLICY */
-static const char * _streamConnection_getInterfaceName(const IoOperations *ops);
-
-/*
- * This assigns a unique pointer to the void * which we use
- * as a GUID for this class.
- */
-static const void *_ioOperationsGuid = __FILE__;
-
-/*
- * Return our GUID
- */
-static const void *_streamConnection_Class(const IoOperations *ops) {
- return _ioOperationsGuid;
-}
-
-static IoOperations _template = {
- .closure = NULL,
- .send = &_streamConnection_Send,
- .sendIOVBuffer = &_streamConnection_SendIOVBuffer,
- .getRemoteAddress = &_streamConnection_GetRemoteAddress,
- .getAddressPair = &_streamConnection_GetAddressPair,
- .getConnectionId = &_streamConnection_GetConnectionId,
- .isUp = &_streamConnection_IsUp,
- .isLocal = &_streamConnection_IsLocal,
- .destroy = &_streamConnection_DestroyOperations,
- .class = &_streamConnection_Class,
- .getConnectionType = &_streamConnection_GetConnectionType,
- .sendProbe = &_sendProbe,
- .getState = &_streamConnection_getState,
- .setState = &_streamConnection_setState,
- .getAdminState = &_streamConnection_getAdminState,
- .setAdminState = &_streamConnection_setAdminState,
-#ifdef WITH_POLICY
- .getPriority = &_streamConnection_getPriority,
- .setPriority = &_streamConnection_setPriority,
-#endif /* WITH_POLICY */
- .getInterfaceName = &_streamConnection_getInterfaceName,
-};
-
-IoOperations *streamConnection_AcceptConnection(Forwarder *forwarder, int fd,
- AddressPair *pair,
- bool isLocal) {
- _StreamState *stream = parcMemory_AllocateAndClear(sizeof(_StreamState));
- parcAssertNotNull(stream, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(_StreamState));
-
- Dispatcher *dispatcher = forwarder_GetDispatcher(forwarder);
- PARCEventScheduler *eventBase = dispatcher_GetEventScheduler(dispatcher);
- stream->bufferEventVector = parcEventQueue_Create(
- eventBase, fd,
- PARCEventQueueOption_CloseOnFree | PARCEventQueueOption_DeferCallbacks);
-
- stream->forwarder = forwarder;
- stream->interfaceName = NULL;
- stream->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- stream->fd = fd;
- stream->id = forwarder_GetNextConnectionId(forwarder);
- stream->addressPair = pair;
- stream->isClosed = false;
-
-#ifdef WITH_POLICY
- stream->priority = 0;
-#endif /* WITH_POLICY */
-
- // allocate a connection
- IoOperations *io_ops = parcMemory_AllocateAndClear(sizeof(IoOperations));
- parcAssertNotNull(io_ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(IoOperations));
- memcpy(io_ops, &_template, sizeof(IoOperations));
- io_ops->closure = stream;
- stream->isLocal = isLocal;
-
- parcEventQueue_SetCallbacks(stream->bufferEventVector, _conn_readcb, NULL,
- _conn_eventcb, (void *)io_ops);
- parcEventQueue_Enable(stream->bufferEventVector, PARCEventType_Read);
-
- messenger_Send(forwarder_GetMessenger(stream->forwarder),
- missive_Create(MissiveType_ConnectionCreate, stream->id));
-
- // As we are acceting a connection, we begin in the UP state
- _setConnectionState(stream, true);
-
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- char *pair_str = addressPair_ToString(pair);
- logger_Log(stream->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "StreamConnection %p accept for address pair %s", (void *)stream,
- pair_str);
- free(pair_str);
- }
-
- return io_ops;
-}
-
-IoOperations *streamConnection_OpenConnection(Forwarder *forwarder,
- AddressPair *pair, bool isLocal) {
- parcAssertNotNull(forwarder, "Parameter hicn-light must be non-null");
- parcAssertNotNull(pair, "Parameter pair must be non-null");
-
- // if there's an error on the bind or connect, will return NULL
- PARCEventQueue *bufferEventVector =
- dispatcher_StreamBufferConnect(forwarder_GetDispatcher(forwarder), pair);
- if (bufferEventVector == NULL) {
- // error opening connection
- return NULL;
- }
-
- _StreamState *stream = parcMemory_AllocateAndClear(sizeof(_StreamState));
- parcAssertNotNull(stream, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(_StreamState));
-
- stream->forwarder = forwarder;
- stream->interfaceName = NULL;
- stream->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- stream->fd = parcEventQueue_GetFileDescriptor(bufferEventVector);
- stream->bufferEventVector = bufferEventVector;
- stream->id = forwarder_GetNextConnectionId(forwarder);
- stream->addressPair = pair;
- stream->isClosed = false;
-
- // allocate a connection
- IoOperations *io_ops = parcMemory_AllocateAndClear(sizeof(IoOperations));
- parcAssertNotNull(io_ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(IoOperations));
- memcpy(io_ops, &_template, sizeof(IoOperations));
- io_ops->closure = stream;
- stream->isLocal = isLocal;
-
- parcEventQueue_SetCallbacks(stream->bufferEventVector, _conn_readcb, NULL,
- _conn_eventcb, (void *)io_ops);
- parcEventQueue_Enable(stream->bufferEventVector, PARCEventType_Read);
-
- // we start in DOWN state, until remote side answers
- messenger_Send(forwarder_GetMessenger(stream->forwarder),
- missive_Create(MissiveType_ConnectionCreate, stream->id));
- _setConnectionState(stream, false);
-
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO, PARCLogLevel_Info)) {
- char *pair_str = addressPair_ToString(pair);
- logger_Log(stream->logger, LoggerFacility_IO, PARCLogLevel_Info, __func__,
- "StreamConnection %p connect for address pair %s",
- (void *)stream, pair_str);
- free(pair_str);
- }
-
- return io_ops;
-}
-
-static void _streamConnection_DestroyOperations(IoOperations **opsPtr) {
- parcAssertNotNull(opsPtr, "Parameter opsPtr must be non-null double pointer");
- parcAssertNotNull(*opsPtr,
- "Parameter opsPtr must dereference to non-null pointer");
-
- IoOperations *ops = *opsPtr;
- parcAssertNotNull(ioOperations_GetClosure(ops),
- "ops->context must not be null");
-
- _StreamState *stream = (_StreamState *)ioOperations_GetClosure(ops);
-
- parcEventQueue_Destroy(&stream->bufferEventVector);
-
- addressPair_Release(&stream->addressPair);
-
- if (!stream->isClosed) {
- stream->isClosed = true;
- messenger_Send(forwarder_GetMessenger(stream->forwarder),
- missive_Create(MissiveType_ConnectionClosed, stream->id));
- }
-
- messenger_Send(forwarder_GetMessenger(stream->forwarder),
- missive_Create(MissiveType_ConnectionDestroyed, stream->id));
-
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO, PARCLogLevel_Info)) {
- logger_Log(stream->logger, LoggerFacility_IO, PARCLogLevel_Info, __func__,
- "StreamConnection %p destroyed", (void *)stream);
- }
-
- logger_Release(&stream->logger);
- parcMemory_Deallocate((void **)&stream);
- parcMemory_Deallocate((void **)&ops);
-
- *opsPtr = NULL;
-}
-
-static bool _streamConnection_IsUp(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return stream->isUp;
-}
-
-static bool _streamConnection_IsLocal(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return stream->isLocal;
-}
-
-static const Address *_streamConnection_GetRemoteAddress(
- const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return addressPair_GetRemote(stream->addressPair);
-}
-
-static const AddressPair *_streamConnection_GetAddressPair(
- const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return stream->addressPair;
-}
-
-static unsigned _streamConnection_GetConnectionId(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return stream->id;
-}
-
-bool _streamConnection_SendIOVBuffer(IoOperations *ops,
- struct iovec * message, size_t size) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
-
- _StreamState *conn = (_StreamState *)ioOperations_GetClosure(ops);
-
- if (!conn->isUp) {
- if (logger_IsLoggable(conn->logger, LoggerFacility_IO,
- PARCLogLevel_Error)) {
- logger_Log(
- conn->logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "connid %u tried to send to down connection (isUp %d isClosed %d)",
- conn->id, conn->isUp, conn->isClosed);
- }
- return false;
- }
-
- PARCEventBuffer *buffer =
- parcEventBuffer_GetQueueBufferOutput(conn->bufferEventVector);
- size_t buffer_backlog = parcEventBuffer_GetLength(buffer);
- parcEventBuffer_Destroy(&buffer);
-
- if (buffer_backlog >= OUTPUT_QUEUE_BYTES) {
- if (logger_IsLoggable(conn->logger, LoggerFacility_IO,
- PARCLogLevel_Warning)) {
- logger_Log(conn->logger, LoggerFacility_IO, PARCLogLevel_Warning,
- __func__,
- "connid %u Writing to buffer backlog %zu bytes DROP MESSAGE",
- conn->id, buffer_backlog);
- }
- return false;
- }
-
- if (logger_IsLoggable(conn->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- size_t length = 0;
- for (int i = 0; i < size; i++)
- length += message[i].iov_len;
-
- logger_Log( conn->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "connid %u Writing %zu bytes to buffer with backlog %zu bytes",
- conn->id, length, buffer_backlog);
- }
-
- /* Write directly into the parcEventQueue without passing through message */
- for (int i = 0; i < size; i++) {
- if (parcEventQueue_Write(conn->bufferEventVector, message[i].iov_base,
- message[i].iov_len) != 0)
- return false;
- }
-
- return true;
-}
-
-/**
- * @function streamConnection_Send
- * @abstract Non-destructive send of the message.
- * @discussion
- * Send uses message_CopyToStreamBuffer, which is a non-destructive write.
- * The send may fail if there's no buffer space in the output queue.
- *
- * @param dummy is ignored. A stream has only one peer.
- * @return <#return#>
- */
-static bool _streamConnection_Send(IoOperations *ops, const Address *dummy,
- Message *message) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
- _StreamState *stream = (_StreamState *)ioOperations_GetClosure(ops);
-
- bool success = false;
- if (stream->isUp) {
- PARCEventBuffer *buffer =
- parcEventBuffer_GetQueueBufferOutput(stream->bufferEventVector);
- size_t buffer_backlog = parcEventBuffer_GetLength(buffer);
- parcEventBuffer_Destroy(&buffer);
-
- if (buffer_backlog < OUTPUT_QUEUE_BYTES) {
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO,
- PARCLogLevel_Debug)) {
- logger_Log(
- stream->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "connid %u Writing %zu bytes to buffer with backlog %zu bytes",
- stream->id, message_Length(message), buffer_backlog);
- }
-
- int failure = message_Write(stream->bufferEventVector, message);
- if (failure == 0) {
- success = true;
- }
- } else {
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO,
- PARCLogLevel_Warning)) {
- logger_Log(stream->logger, LoggerFacility_IO, PARCLogLevel_Warning,
- __func__,
- "connid %u Writing to buffer backlog %zu bytes DROP MESSAGE",
- stream->id, buffer_backlog);
- }
- }
- } else {
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO,
- PARCLogLevel_Error)) {
- logger_Log(
- stream->logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "connid %u tried to send to down connection (isUp %d isClosed %d)",
- stream->id, stream->isUp, stream->isClosed);
- }
- }
-
- return success;
-}
-
-list_connections_type _streamConnection_GetConnectionType(
- const IoOperations *ops) {
- return CONN_TCP;
-}
-
-static void _sendProbe(IoOperations *ops, uint8_t *message) {
- // we don't need to implemet this here, it is a local connection
-}
-
-// =================================================================
-// the actual I/O functions
-
-int _isACommand(PARCEventBuffer *input) {
- size_t bytesAvailable = parcEventBuffer_GetLength(input);
- parcAssertTrue(bytesAvailable >= sizeof(header_control_message),
- "Called with too short an input: %zu", bytesAvailable);
-
- uint8_t *msg = parcEventBuffer_Pullup(input, bytesAvailable);
- // read first byte of the header
-
- // first byte: must be a REQUEST_LIGHT
- if (msg[0] != REQUEST_LIGHT) {
- return LAST_COMMAND_VALUE;
- }
-
- // second byte: must be a command_id
- if (msg[1] < 0 || msg[1] >= LAST_COMMAND_VALUE) {
- return LAST_COMMAND_VALUE;
- }
-
- return msg[1];
-}
-
-PARCEventBuffer *_tryReadControlMessage(_StreamState *stream,
- PARCEventBuffer *input,
- command_id command,
- struct iovec **request) {
- size_t bytesAvailable = parcEventBuffer_GetLength(input);
-
- if (stream->nextMessageLength == 0) {
- stream->nextMessageLength =
- sizeof(header_control_message) +
- payloadLengthDaemon(command); // consider the whole packet.
- }
-
- if (bytesAvailable >= stream->nextMessageLength) {
- PARCEventBuffer *message = parcEventBuffer_Create();
- int bytesRead = parcEventBuffer_ReadIntoBuffer(input, message,
- stream->nextMessageLength);
- parcAssertTrue(bytesRead == stream->nextMessageLength,
- "Partial read, expected %zu got %d",
- stream->nextMessageLength, bytesRead);
-
- uint8_t *control =
- parcEventBuffer_Pullup(message, stream->nextMessageLength);
- if (!(*request = (struct iovec *)parcMemory_AllocateAndClear(
- sizeof(struct iovec) * 2))) {
- return NULL;
- }
- (*request)[0].iov_base = control; // header
- (*request)[0].iov_len = sizeof(header_control_message);
- if (payloadLengthDaemon(command) > 0) {
- (*request)[1].iov_base =
- control + sizeof(header_control_message); // payload
- } else {
- (*request)[1].iov_base = NULL;
- }
- (*request)[1].iov_len = payloadLengthDaemon(command);
- // now reset message length for next packet
-
- stream->nextMessageLength = 0;
-
- return message;
- }
-
- return NULL;
-}
-
-static bool _isAnHicnPacket(PARCEventBuffer *input) {
- size_t bytesAvailable = parcEventBuffer_GetLength(input);
- parcAssertTrue(bytesAvailable >= sizeof(header_control_message),
- "Called with too short an input: %zu", bytesAvailable);
-
- uint8_t *fh = parcEventBuffer_Pullup(input, sizeof(header_control_message));
- return messageHandler_IsValidHicnPacket(fh);
-}
-
-static Message *_readMessage(_StreamState *stream, Ticks time,
- PARCEventBuffer *input) {
- Message *message = message_CreateFromEventBuffer(
- input, stream->nextMessageLength, stream->id, time, stream->logger);
-
- return message;
-}
-
-static void _startNewMessage(_StreamState *stream, PARCEventBuffer *input,
- size_t inputBytesAvailable) {
- parcAssertTrue(stream->nextMessageLength == 0,
- "Invalid state, nextMessageLength not zero: %zu",
- stream->nextMessageLength);
- parcAssertTrue(inputBytesAvailable >= sizeof(header_control_message),
- "read_length not a whole fixed header!: %zd",
- inputBytesAvailable);
-
- // this linearizes the first messageHandler_GetIPv6HeaderLength() bytes of the
- // input buffer's iovecs and returns a pointer to it.
- uint8_t *fh = parcEventBuffer_Pullup(input, sizeof(header_control_message));
-
- // Calculate the total message size based on the fixed header
- stream->nextMessageLength = messageHandler_GetTotalPacketLength(fh);
-}
-
-static Message *_tryReadMessage(PARCEventBuffer *input, _StreamState *stream) {
- size_t bytesAvailable = parcEventBuffer_GetLength(input);
- parcAssertTrue(bytesAvailable >= sizeof(header_control_message),
- "Called with too short an input: %zu", bytesAvailable);
-
- if (stream->nextMessageLength == 0) {
- _startNewMessage(stream, input, bytesAvailable);
- }
-
- // This is not an ELSE statement. We can both start a new message then
- // check if there's enough bytes to read the whole thing.
-
- if (bytesAvailable >= stream->nextMessageLength) {
- Message *message =
- _readMessage(stream, forwarder_GetTicks(stream->forwarder), input);
-
- // now reset message length for next packet
- stream->nextMessageLength = 0;
-
- return message;
- }
-
- return NULL;
-}
-
-/**
- * @function conn_readcb
- * @abstract Event callback for reads
- * @discussion
- * Will read messages off the input. Continues reading as long as we
- * can get a header to determine the next message length or as long as we
- * can read a complete message.
- *
- * This function manipulates the read low water mark. (1) read a fixed header
- * plus complete message, then set the low water mark to FIXED_HEADER_LEN. (2)
- * read a fixed header, but not a complete message, then set low water mark to
- * the total mesage length. Using the low water mark like this means the buffer
- * event will only trigger on meaningful byte boundaries when we can get actual
- * work done.
- *
- * @param <#param1#>
- * @return <#return#>
- */
-static void _conn_readcb(PARCEventQueue *event, PARCEventType type,
- void *ioOpsVoid) {
- command_id command;
- IoOperations *ops = (IoOperations *)ioOpsVoid;
- _StreamState *stream = (_StreamState *)ioOperations_GetClosure(ops);
-
- PARCEventBuffer *input = parcEventBuffer_GetQueueBufferInput(event);
-
- // drain the input buffer
-
- // notice that we always try to read at least 8 bytes
- // (sizeof(header_control_message)). This is enough to read the length of all
- // kind of packets
- while (parcEventBuffer_GetLength(input) >= sizeof(header_control_message) &&
- parcEventBuffer_GetLength(input) >= stream->nextMessageLength) {
-
- if ((command = _isACommand(input)) != LAST_COMMAND_VALUE) {
- struct iovec *rx;
- // Get message from the stream and set the stream->nextMessageLength
- PARCEventBuffer *message =
- _tryReadControlMessage(stream, input, command, &rx);
- // If received correctly the whole message, send to dispatcher
- if (message) {
- forwarder_ReceiveCommand(stream->forwarder, command, rx, stream->id);
- //parcMemory_Deallocate((void **)&rx);
- parcEventBuffer_Destroy(&message);
- }
-
- } else if (_isAnHicnPacket(input)) {
- // this is an Hicn packet (here we should distinguish between IPv4 and
- // IPv6 tryReadMessage may set nextMessageLength
- Message *message = _tryReadMessage(input, stream);
-
- if (message) {
- forwarder_Receive(stream->forwarder, message);
- }
-
- } else {
- parcAssertTrue(false,
- "(Local stream connection) malformed packet received");
- }
- }
-
- if (stream->nextMessageLength == 0) {
- // we don't have the next header, so set it to the header length
- streamBuffer_SetWatermark(event, true, false,
- sizeof(header_control_message), 0);
- } else {
- // set it to the packet length
- streamBuffer_SetWatermark(event, true, false, stream->nextMessageLength, 0);
- }
- parcEventBuffer_Destroy(&input);
-}
-
-static void _setConnectionState(_StreamState *stream, bool isUp) {
- parcAssertNotNull(stream, "Parameter stream must be non-null");
-
- Messenger *messenger = forwarder_GetMessenger(stream->forwarder);
-
- bool oldStateIsUp = stream->isUp;
- stream->isUp = isUp;
-
- if (oldStateIsUp && !isUp) {
- // bring connection DOWN
- Missive *missive = missive_Create(MissiveType_ConnectionDown, stream->id);
- messenger_Send(messenger, missive);
- return;
- }
-
- if (!oldStateIsUp && isUp) {
- // bring connection UP
- Missive *missive = missive_Create(MissiveType_ConnectionUp, stream->id);
- messenger_Send(messenger, missive);
- return;
- }
-}
-
-static void _conn_eventcb(PARCEventQueue *event, PARCEventQueueEventType events,
- void *ioOpsVoid) {
- IoOperations *ops = (IoOperations *)ioOpsVoid;
- _StreamState *stream = (_StreamState *)ioOperations_GetClosure(ops);
-
- if (events & PARCEventQueueEventType_Connected) {
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO,
- PARCLogLevel_Info)) {
- logger_Log(stream->logger, LoggerFacility_IO, PARCLogLevel_Info, __func__,
- "Connection %u is connected", stream->id);
- }
-
- // if the stream was closed, do not transition to an UP state
- if (!stream->isClosed) {
- _setConnectionState(stream, true);
- }
- } else if (events & PARCEventQueueEventType_EOF) {
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO,
- PARCLogLevel_Info)) {
- logger_Log(stream->logger, LoggerFacility_IO, PARCLogLevel_Info, __func__,
- "connid %u closed.", stream->id);
- }
-
- parcEventQueue_Disable(stream->bufferEventVector, PARCEventType_Read);
-
- _setConnectionState(stream, false);
-
- if (!stream->isClosed) {
- stream->isClosed = true;
- // this will cause the connection manager to destroy the connection later
- messenger_Send(forwarder_GetMessenger(stream->forwarder),
- missive_Create(MissiveType_ConnectionClosed, stream->id));
- }
- } else if (events & PARCEventQueueEventType_Error) {
- if (logger_IsLoggable(stream->logger, LoggerFacility_IO,
- PARCLogLevel_Error)) {
- logger_Log(stream->logger, LoggerFacility_IO, PARCLogLevel_Error,
- __func__, "Got an error on the connection %u: %s", stream->id,
- strerror(errno));
- }
-
- parcEventQueue_Disable(stream->bufferEventVector,
- PARCEventType_Read | PARCEventType_Write);
-
- _setConnectionState(stream, false);
-
- if (!stream->isClosed) {
- stream->isClosed = true;
- // this will cause the connection manager to destroy the connection later
- messenger_Send(forwarder_GetMessenger(stream->forwarder),
- missive_Create(MissiveType_ConnectionClosed, stream->id));
- }
- }
- /* None of the other events can happen here, since we haven't enabled
- * timeouts */
-}
-
-static connection_state_t _streamConnection_getState(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return stream->state;
-}
-
-static void _streamConnection_setState(IoOperations *ops, connection_state_t state) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _StreamState *stream =
- (_StreamState *)ioOperations_GetClosure(ops);
- stream->state = state;
-}
-
-static connection_state_t _streamConnection_getAdminState(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return stream->admin_state;
-}
-
-static void _streamConnection_setAdminState(IoOperations *ops, connection_state_t admin_state) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _StreamState *stream =
- (_StreamState *)ioOperations_GetClosure(ops);
- stream->admin_state = admin_state;
-}
-
-#ifdef WITH_POLICY
-static uint32_t _streamConnection_getPriority(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _StreamState *stream =
- (const _StreamState *)ioOperations_GetClosure(ops);
- return stream->priority;
-}
-
-static void _streamConnection_setPriority(IoOperations *ops, uint32_t priority) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _StreamState *stream =
- (_StreamState *)ioOperations_GetClosure(ops);
- stream->priority = priority;
-}
-#endif /* WITH_POLICY */
-
-static const char * _streamConnection_getInterfaceName(const IoOperations *ops)
-{
- parcAssertNotNull(ops, "Parameter must be non-null");
- _StreamState *stream =
- (_StreamState *)ioOperations_GetClosure(ops);
- return stream->interfaceName;
-}
diff --git a/hicn-light/src/hicn/io/streamConnection.h b/hicn-light/src/hicn/io/streamConnection.h
deleted file mode 100644
index f483d0b82..000000000
--- a/hicn-light/src/hicn/io/streamConnection.h
+++ /dev/null
@@ -1,76 +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.
- */
-
-/**
- * Methods common to TCP and PF_LOCAL stream-based listeners
- */
-
-#ifndef streamConnection_h
-#define streamConnection_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/core/messagePacketType.h>
-#include <hicn/io/addressPair.h>
-#include <hicn/io/ioOperations.h>
-#include <hicn/utils/address.h>
-
-/**
- * @function streamConnection_AcceptConnection
- * @abstract Receive a connection from a remote peer
- * @discussion
- * We are the "server side" of the stream connection, so we need to accept the
- * client connection and setup state for her.
- *
- * @param <#param1#>
- * @return <#return#>
- */
-IoOperations *streamConnection_AcceptConnection(Forwarder *forwarder, int fd,
- AddressPair *pair,
- bool isLocal);
-
-/**
- * @function streamConnection_OpenConnection
- * @abstract Initiate a connection to a remote peer
- * @discussion
- * We are the "client side" of the stream connection. We'll create state for
- * the peer, but it will be in the "down" state until the connection
- * establishes.
- *
- * For TCP, both address pairs need to be the same address family: both INET
- * or both INET6. The remote address must have the complete socket information
- * (address, port). The local socket could be wildcarded or may specify down to
- * the (address, port) pair.
- *
- * If the local address is IPADDR_ANY and the port is 0, then it is a normal
- * call to "connect" that will use whatever local IP address and whatever local
- * port for the connection. If either the address or port is set, the local
- * socket will first be bound (via bind(2)), and then call connect().
- *
- * AF_UNIX is not yet supported
- *
- * If there's an error binding to the specified address or connecting to the
- * remote address, will return NULL.
- *
- * @param pair (takes ownership of this) is the complete socket pair of
- * (address, port) for each end, if INET or INET6.
- * @return NULL on error, otherwise the connections IO operations.
- */
-IoOperations *streamConnection_OpenConnection(Forwarder *forwarder,
- AddressPair *pair, bool isLocal);
-
-bool streamState_SendIOVBuffer(IoOperations *ops, struct iovec *response,
- size_t size);
-
-#endif // streamConnection_h
diff --git a/hicn-light/src/hicn/io/tcp.c b/hicn-light/src/hicn/io/tcp.c
new file mode 100644
index 000000000..a924b6330
--- /dev/null
+++ b/hicn-light/src/hicn/io/tcp.c
@@ -0,0 +1,532 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * Common activity for STREAM based listeners.
+ */
+
+#include <errno.h>
+#ifndef _WIN32
+#include <unistd.h> // fcntl
+#endif /* _WIN32 */
+#include <fcntl.h> // fcntl
+#include <hicn/hicn-light/config.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <hicn/hicn.h>
+#include <hicn/util/log.h>
+
+#include "base.h"
+#include "../core/connection.h"
+#include "../core/connection_vft.h"
+#include "../core/listener.h"
+#include "../core/listener_vft.h"
+#include "../core/msgbuf.h"
+#include "../core/forwarder.h"
+
+// 128 KB output queue
+#define OUTPUT_QUEUE_BYTES (128 * 1024)
+
+#define TCP_RECV_BUFLEN 8192
+//#define MTU 1500
+
+/******************************************************************************
+ * Listener
+ ******************************************************************************/
+
+typedef struct {
+ void *_;
+} listener_tcp_data_t;
+
+static int listener_tcp_initialize(listener_t *listener) {
+ ERROR("[listener_tcp_initialize] Not implemented");
+
+ return 0;
+}
+
+static void listener_tcp_finalize(listener_t *listener) {
+ ERROR("[listener_tcp_finalize] Not implemented");
+}
+
+static int listener_tcp_punt(const listener_t *listener, const char *prefix_s) {
+ ERROR("[listener_tcp_punt] Not implemented");
+ return -1;
+}
+
+static int listener_tcp_get_socket(const listener_t *listener,
+ const address_t *local,
+ const address_t *remote,
+ const char *interface_name) {
+ ERROR("[listener_tcp_get_socket] Not implemented");
+ return -1;
+}
+
+#define listener_tcp_read_single io_read_single_socket
+#define listener_tcp_read_batch NULL
+
+DECLARE_LISTENER(tcp);
+
+/******************************************************************************
+ * Connection
+ ******************************************************************************/
+
+typedef struct {
+ /* Partial receive buffer */
+ u8 buf[TCP_RECV_BUFLEN];
+ size_t roff; /**< Read offset */
+ size_t woff; /**< Write offset */
+
+ // XXX this should be initialized with the header length, and tells what we
+ // expect to receive next...
+ size_t next_len;
+ struct bufferevent *bufferevent;
+} connection_tcp_data_t;
+
+// XXX This seems more a listener code !
+// XXX we must have accept to the connection table to spawn new ones !!
+// XXX equivalent to initialize
+int connection_tcp_accept(connection_t *connection, listener_t *listener,
+ int fd, address_pair_t *pair, bool local,
+ unsigned connection_id) {
+ assert(connection);
+ assert(listener);
+
+ *connection = (connection_t){
+ .id = connection_id,
+ .interface_name = NULL,
+ .type = FACE_TYPE_TCP,
+ .pair = *pair,
+ .fd = fd,
+ .local = local,
+ // As we are accepting a connection, we begin in the UP state
+ .state = FACE_STATE_UP,
+ .admin_state = FACE_STATE_UP,
+#ifdef WITH_POLICY
+ .priority = 0,
+#endif /* WITH_POLICY */
+
+ .listener = listener,
+ .closed = false,
+ };
+
+ WITH_INFO({
+ char addr_str[NI_MAXHOST];
+ int port;
+ address_to_string(&(pair->local), addr_str, &port);
+ INFO("%s connection %p created for address %s:%d (local=%s)",
+ face_type_str(connection->type), connection, addr_str, port,
+ connection_is_local(connection) ? "true" : "false");
+ })
+
+ return 0;
+}
+
+int make_socket(address_pair_t *pair) {
+#ifndef _WIN32
+ int fd = socket(address_family(&pair->local), SOCK_STREAM, 0);
+ if (fd < 0) {
+ perror("socket");
+ goto ERR_SOCKET;
+ }
+#else
+ SOCKET fd = socket(address_family(&pair->local), SOCK_STREAM, 0);
+ if (fd == INVALID_SOCKET) {
+ perror("socket");
+ goto ERR_SOCKET;
+ }
+#endif /* _WIN32 */
+
+ /* Set non-blocking flag */
+#ifndef _WIN32
+ int flags = fcntl(fd, F_GETFL, NULL);
+ if (flags == -1) {
+ perror("F_GETFL");
+ goto ERR;
+ }
+ if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
+ perror("F_SETFL");
+ goto ERR;
+ }
+#else
+ if (ioctlsocket(fd, FIONBIO, &(u_long){1}) != NO_ERROR) {
+ perror("ioctlsocket");
+ goto ERR;
+ }
+#endif /* _WIN32 */
+
+ if (bind(fd, address_sa(&pair->local), address_socklen(&pair->local)) == -1) {
+ perror("bind");
+ goto ERR;
+ }
+
+ if (connect(fd, address_sa(&pair->remote), address_socklen(&pair->remote)) <
+ 0) {
+ perror("connect");
+ goto ERR;
+ }
+
+ return 0;
+
+ERR:
+#ifndef _WIN32
+ close(fd);
+#else
+ closesocket(fd);
+#endif
+
+ERR_SOCKET:
+ return -1;
+}
+
+static int connection_tcp_initialize(connection_t *connection) {
+ assert(connection);
+ assert(connection->type == FACE_TYPE_TCP);
+
+ connection_tcp_data_t *data = connection->data;
+ assert(data);
+
+ data->roff = 0;
+ data->woff = 0;
+
+ connection->fd = make_socket(connection_get_pair(connection));
+ if (connection->fd < 0) {
+ ERROR("Error creating TCP socket");
+ return -1;
+ }
+
+ WITH_INFO({
+ char local_addr_str[NI_MAXHOST];
+ char remote_addr_str[NI_MAXHOST];
+ int local_port;
+ int remote_port;
+ address_to_string(&(connection->pair.local), local_addr_str, &local_port);
+ address_to_string(&(connection->pair.remote), remote_addr_str,
+ &remote_port);
+ INFO("%s connection %p connect for address pair %s:%d (local=%s) - %s:%d",
+ face_type_str(connection->type), connection, local_addr_str,
+ local_port, connection_is_local(connection) ? "true" : "false",
+ remote_addr_str, remote_port);
+ })
+
+ return 0;
+}
+
+// XXX a part needs to be handled in the connection.c
+static void connection_tcp_finalize(connection_t *connection) {
+ if (!connection->closed) {
+ connection->closed = true;
+ // XXX need to delete the connection like previously in the connection
+ // manager
+ }
+
+ INFO("%s connection %p destroyed", face_type_str(connection->type),
+ connection);
+ // XXX need to release the "connection"
+}
+
+#if 0
+static
+bool
+connection_tcp_sendv(connnection_t * connection, struct iovec * iov,
+ size_t size)
+{
+ assert(connection);
+ assert(iov);
+
+ if (!connection_is_up(connection)) {
+ ERROR("Connection #%u tried to send to down connection (up=%d closed=%d)",
+ connection_get_id(connection),
+ connection_get_up(connection) ? "true" : "false",
+ connection_get_closed(connection) ? "true" : "false");
+ return false;
+ }
+
+ PARCEventBuffer *buffer =
+ parcEventBuffer_GetQueueBufferOutput(connection->events);
+ size_t buffer_backlog = parcEventBuffer_GetLength(buffer);
+ parcEventBuffer_Destroy(&buffer);
+
+ if (buffer_backlog >= OUTPUT_QUEUE_BYTES) {
+ WARN("Connection #%u Writing to buffer backlog %zu bytes DROP MESSAGE",
+ connection_get_id(connection), buffer_backlog);
+ return false;
+ }
+
+#if 0
+ /* DEBUG */
+ size_t length = 0;
+ for (int i = 0; i < size; i++)
+ length += message[i].iov_len;
+ DEBUG("Connection #%u writing %zu bytes to buffer with backlog %zu bytes",
+ connection_get_id(connection), length, buffer_backlog);
+#endif
+
+ /* Write directly into the parcEventQueue without passing through message */
+ for (int i = 0; i < size; i++) {
+ if (parcEventQueue_Write(conn->events, iov[i].iov_base,
+ iov[i].iov_len) != 0)
+ return false;
+ }
+
+ return true;
+}
+#endif
+
+static bool connection_tcp_flush(connection_t *connection) { return true; }
+
+/**
+ * @function streamConnection_Send
+ * @abstract Non-destructive send of the message.
+ * @discussion
+ * Send uses message_CopyToStreamBuffer, which is a non-destructive write.
+ * The send may fail if there's no buffer space in the output queue.
+ *
+ * @param dummy is ignored. A stream has only one peer.
+ * @return <#return#>
+ */
+// XXX address not used anywhere
+// XXX too much repeated code with sendv here
+static bool connection_tcp_send(connection_t *connection, msgbuf_t *msgbuf,
+ bool queue) {
+ assert(connection);
+ assert(msgbuf);
+
+ if (!connection_is_up(connection)) {
+ ERROR("Connection #%u tried to send to down connection (up=%d closed=%d)",
+ connection_get_id(connection),
+ connection_is_up(connection) ? "true" : "false",
+ connection_is_closed(connection) ? "true" : "false");
+ return false;
+ }
+
+ // XXX TODO write to fd
+#if 0
+ PARCEventBuffer *buffer =
+ parcEventBuffer_GetQueueBufferOutput(connection->events);
+ size_t buffer_backlog = parcEventBuffer_GetLength(buffer);
+ parcEventBuffer_Destroy(&buffer);
+
+ if (buffer_backlog >= OUTPUT_QUEUE_BYTES) {
+ WARN("Connection #%u Writing to buffer backlog %zu bytes DROP MESSAGE",
+ connection_get_id(connection), buffer_backlog);
+ return false;
+ }
+
+ DEBUG("Connection #%u Writing %zu bytes to buffer with backlog %zu bytes",
+ connection_get_id(connection), msgbuf_len(message), buffer_backlog);
+
+ return (parcEventQueue_Write(connection->events, msgbuf_packet(message),
+ msgbuf_len(message)) == 0);
+#endif
+ return true;
+}
+
+static bool connection_tcp_send_packet(const connection_t *connection,
+ const uint8_t *packet, size_t size) {
+ /* Not implemented for local connections */
+ // XXX shall we set the pointer to NULL and add a check ?
+
+ ERROR("[connection_tcp_send_packet] Not implemented");
+
+ return -1;
+}
+
+// =================================================================
+// the actual I/O functions
+
+// not needed anymore ?
+#if 0
+// XXX this is called iif there is sufficient data to read, otherwise it raises
+// an assertion error. This was a problem before I guess
+static
+int
+connection_tcp_read_message(connection_t * connection, msgbuf_t * msgbuf)
+{
+ assert(connection);
+ assert(msgbuf);
+
+ connection_tcp_data_t * data = connection->data;
+ assert(data);
+
+ size_t n = evbuffer_get_length(data->evbuffer);
+ // XXX this check was wrong
+ // parcAssertTrue(n >= sizeof(cmd_header_t),
+ "Called with too short an input: %zu", n);
+
+ // XXX WTF
+ if (stream->next_len == 0) {
+ // this linearizes the first messageHandler_GetIPv6HeaderLength() bytes of the
+ // input buffer's iovecs and returns a pointer to it.
+ uint8_t *fh = parcEventBuffer_Pullup(data->evbuffer, sizeof(cmd_header_t));
+
+ // Calculate the total message size based on the fixed header
+ stream->next_len = messageHandler_GetTotalPacketLength(fh);
+ }
+ // This is not an ELSE statement. We can both start a new message then
+ // check if there's enough bytes to read the whole thing.
+
+ if (n < stream->next_len)
+ return -1;
+
+ uint8_t packet_type;
+ if (messageHandler_IsInterest(packet)) {
+ packet_type = MESSAGE_TYPE_INTEREST;
+ } else if (messageHandler_IsData(packet)) {
+ packet_type = MESSAGE_TYPE_DATA;
+ } else {
+ ERROR("Dropped packet that is not interest nor data");
+ goto ERR;
+ }
+
+ if (evbuffer_remove(data->evbuffer, data->packet, data->next_len) < 0)
+ return -1;
+
+ msgbuf_from_packet(msgbuf, data->packet, packet_type, stream->id,
+ ticks_now());
+
+ // now reset message length for next packet
+ data->next_len = 0;
+ return 0;
+
+ERR:
+ evbuffer_drain(data->evbuffer, data->next_len);
+ return -1;
+}
+#endif
+
+/**
+ * @function conn_readcb
+ * @abstract Event callback for reads
+ * @discussion
+ * Will read messages off the input. Continues reading as long as we
+ * can get a header to determine the next message length or as long as we
+ * can read a complete message.
+ *
+ * This function manipulates the read low water mark. (1) read a fixed header
+ * plus complete message, then set the low water mark to FIXED_HEADER_LEN. (2)
+ * read a fixed header, but not a complete message, then set low water mark to
+ * the total mesage length. Using the low water mark like this means the buffer
+ * event will only trigger on meaningful byte boundaries when we can get actual
+ * work done.
+ *
+ * @param <#param1#>
+ * @return <#return#>
+ */
+#if 0
+static
+void
+connection_tcp_read_callback(connection_t * connection, int fd, void * user_data)
+{
+ assert(connection);
+ /* user_data can be NULL */
+
+ connection_tcp_data_t * data = connection->data;
+ assert(TCP_RECV_BUFLEN - data->woff > MTU);
+
+ /* No batching here as code is not expected to receive much throughput */
+ for (;;) {
+ ssize_t n = recv(connection->fd, data->buf + data->woff,
+ TCP_RECV_BUFLEN - data->woff, 0);
+ if (n == 0) /* EOF */
+ return; // XXX close connection
+ if (n < 0) {
+ if (errno == EWOULDBLOCK)
+ break;
+ perror("recv");
+ return; // XXX close connection
+ }
+ data->woff += n;
+
+ /* Process */
+ uint8_t * packet = data->buf + data->roff;
+ size_t size = data->woff - data->roff; /* > 0 */
+
+ ssize_t used = listener_read_callback(NULL, fd,
+ address_pair_get_local(&connection->pair), packet, size);
+ if (used < 0)
+ return; // XXX close connection ?
+ if (used == 0)
+ break; /* We would have received more if there was still packets to be read */
+ data->roff += used;
+ assert(data->roff <= data->woff);
+
+ if (data->roff == data->woff) {
+ /* Reset state whenever possible to avoid memcpy's */
+ data->roff = 0;
+ data->woff = 0;
+ return;
+ }
+ }
+
+ /* Make sure there is enough remaining space in the buffer */
+ if (TCP_RECV_BUFLEN - data->woff < MTU) {
+ /*
+ * There should be no overlap provided a sufficiently large BUFLEN, but
+ * who knows.
+ */
+ memmove(data->buf, data->buf + data->roff, data->woff - data->roff);
+ data->woff -= data->roff;
+ data->roff = 0;
+ }
+
+ return;
+}
+#endif
+
+#if 0
+static
+void
+connection_tcp_callback(connection_t * connection, int fd, void * user_data)
+{
+ if (events & PARCEventQueueEventType_Connected) {
+ INFO("Connection %u is connected", stream->id);
+
+ // if the stream was closed, do not transition to an UP state
+ if (!stream->isClosed) {
+ _setConnectionState(stream, true);
+ }
+ } else if (events & PARCEventQueueEventType_EOF) {
+ INFO("connid %u closed.", stream->id);
+
+ parcEventQueue_Disable(stream->events, PARCEventType_Read);
+
+ _setConnectionState(stream, false);
+
+ if (!stream->isClosed) {
+ stream->isClosed = true;
+ // XXX TODO destroy the connection
+ }
+ } else if (events & PARCEventQueueEventType_Error) {
+ ERROR("Got an error on the connection %u: %s", stream->id,
+ strerror(errno));
+
+ parcEventQueue_Disable(stream->events,
+ PARCEventType_Read | PARCEventType_Write);
+
+ _setConnectionState(stream, false);
+
+ if (!stream->isClosed) {
+ stream->isClosed = true;
+ // XXX TODO destroy the connection
+ }
+ }
+ /* None of the other events can happen here, since we haven't enabled
+ * timeouts */
+}
+#endif
+
+DECLARE_CONNECTION(tcp)
diff --git a/hicn-light/src/hicn/io/tcpListener.c b/hicn-light/src/hicn/io/tcpListener.c
deleted file mode 100644
index e2b80c215..000000000
--- a/hicn-light/src/hicn/io/tcpListener.c
+++ /dev/null
@@ -1,262 +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 <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <hicn/core/connectionTable.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/io/listener.h>
-#include <hicn/io/streamConnection.h>
-#include <hicn/io/tcpListener.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <parc/assert/parc_Assert.h>
-
-typedef struct tcp_listener {
- char *listenerName;
- Forwarder *forwarder;
- Logger *logger;
-
- PARCEventSocket *listener;
-
- Address *localAddress;
-
- unsigned id;
- char *interfaceName;
-
- // is the localAddress as 127.0.0.0 address?
- bool isLocalAddressLocal;
-} _TcpListener;
-
-static void _tcpListener_Destroy(_TcpListener **listenerPtr);
-
-static void _tcpListener_OpsDestroy(ListenerOps **listenerOpsPtr);
-
-static const char *_tcpListener_ListenerName(const ListenerOps *ops);
-
-static unsigned _tcpListener_OpsGetInterfaceIndex(const ListenerOps *ops);
-
-static const Address *_tcpListener_OpsGetListenAddress(const ListenerOps *ops);
-
-static const char *_tcpListener_InterfaceName(const ListenerOps *ops);
-
-static EncapType _tcpListener_OpsGetEncapType(const ListenerOps *ops);
-
-static ListenerOps _tcpTemplate = {
- .context = NULL,
- .destroy = &_tcpListener_OpsDestroy,
- .getListenerName = &_tcpListener_ListenerName,
- .getInterfaceIndex = &_tcpListener_OpsGetInterfaceIndex,
- .getListenAddress = &_tcpListener_OpsGetListenAddress,
- .getEncapType = &_tcpListener_OpsGetEncapType,
- .getInterfaceName = &_tcpListener_InterfaceName,
- .getSocket = NULL};
-
-// STREAM daemon listener callback
-static void _tcpListener_Listen(int, struct sockaddr *, int socklen,
- void *tcpVoid);
-
-ListenerOps *tcpListener_CreateInet6(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in6 sin6, char *interfaceName) {
-
- _TcpListener *tcp = parcMemory_AllocateAndClear(sizeof(_TcpListener));
- parcAssertNotNull(tcp, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(_TcpListener));
-
- tcp->forwarder = forwarder;
- tcp->listenerName = parcMemory_StringDuplicate(listenerName, strlen(listenerName));
- tcp->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- tcp->interfaceName = parcMemory_StringDuplicate(interfaceName, strlen(interfaceName));
-
- tcp->listener = dispatcher_CreateListener(
- forwarder_GetDispatcher(forwarder), _tcpListener_Listen, (void *)tcp, -1,
- (struct sockaddr *)&sin6, sizeof(sin6));
-
- if (tcp->listener == NULL) {
- logger_Log(tcp->logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "dispatcher_CreateListener failed to create listener (%d) %s",
- errno, strerror(errno));
- logger_Release(&tcp->logger);
- parcMemory_Deallocate((void **)&tcp);
- return NULL;
- }
-
- tcp->localAddress = addressCreateFromInet6(&sin6);
- tcp->id = forwarder_GetNextConnectionId(forwarder);
- tcp->isLocalAddressLocal =
- parcNetwork_IsSocketLocal((struct sockaddr *)&sin6);
-
- ListenerOps *ops = parcMemory_AllocateAndClear(sizeof(ListenerOps));
- parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListenerOps));
-
- memcpy(ops, &_tcpTemplate, sizeof(ListenerOps));
- ops->context = tcp;
-
- if (logger_IsLoggable(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- char *str = addressToString(tcp->localAddress);
- logger_Log(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "TcpListener %p created for address %s (isLocal %d)",
- (void *)tcp, str, tcp->isLocalAddressLocal);
- parcMemory_Deallocate((void **)&str);
- }
-
- return ops;
-}
-
-ListenerOps *tcpListener_CreateInet(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in sin, char *interfaceName) {
- _TcpListener *tcp = parcMemory_AllocateAndClear(sizeof(_TcpListener));
- parcAssertNotNull(tcp, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(_TcpListener));
-
- tcp->forwarder = forwarder;
- tcp->listenerName = parcMemory_StringDuplicate(listenerName, strlen(listenerName));
- tcp->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- tcp->interfaceName = parcMemory_StringDuplicate(interfaceName, strlen(interfaceName));
-
- tcp->listener = dispatcher_CreateListener(
- forwarder_GetDispatcher(forwarder), _tcpListener_Listen, (void *)tcp, -1,
- (struct sockaddr *)&sin, sizeof(sin));
-
- if (tcp->listener == NULL) {
- logger_Log(tcp->logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "dispatcher_CreateListener failed to create listener (%d) %s",
- errno, strerror(errno));
-
- logger_Release(&tcp->logger);
- parcMemory_Deallocate((void **)&tcp);
- return NULL;
- }
-
- tcp->localAddress = addressCreateFromInet(&sin);
- tcp->id = forwarder_GetNextConnectionId(forwarder);
- tcp->isLocalAddressLocal = parcNetwork_IsSocketLocal((struct sockaddr *)&sin);
-
- ListenerOps *ops = parcMemory_AllocateAndClear(sizeof(ListenerOps));
- parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListenerOps));
-
- memcpy(ops, &_tcpTemplate, sizeof(ListenerOps));
- ops->context = tcp;
-
- if (logger_IsLoggable(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- char *str = addressToString(tcp->localAddress);
- logger_Log(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "TcpListener %p created for address %s (isLocal %d)",
- (void *)tcp, str, tcp->isLocalAddressLocal);
- parcMemory_Deallocate((void **)&str);
- }
-
- return ops;
-}
-
-static void _tcpListener_Destroy(_TcpListener **listenerPtr) {
- parcAssertNotNull(listenerPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*listenerPtr,
- "Parameter must derefernce to non-null pointer");
- _TcpListener *tcp = *listenerPtr;
-
- if (logger_IsLoggable(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- char *str = addressToString(tcp->localAddress);
- logger_Log(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "TcpListener %p destroyed", (void *)tcp);
- parcMemory_Deallocate((void **)&str);
- }
-
- parcMemory_Deallocate((void **)&tcp->listenerName);
- parcMemory_Deallocate((void **)&tcp->interfaceName);
- logger_Release(&tcp->logger);
- dispatcher_DestroyListener(forwarder_GetDispatcher(tcp->forwarder),
- &tcp->listener);
- addressDestroy(&tcp->localAddress);
- parcMemory_Deallocate((void **)&tcp);
- *listenerPtr = NULL;
-}
-
-// ==================================================
-
-static const char *_tcpListener_ListenerName(const ListenerOps *ops) {
- _TcpListener *tcp = (_TcpListener *)ops->context;
- return tcp->listenerName;
-}
-
-static const char *_tcpListener_InterfaceName(const ListenerOps *ops) {
- _TcpListener *tcp = (_TcpListener *)ops->context;
- return tcp->interfaceName;
-}
-
-static void _tcpListener_Listen(int fd, struct sockaddr *sa, int socklen,
- void *tcpVoid) {
- _TcpListener *tcp = (_TcpListener *)tcpVoid;
-
- Address *remote;
-
- switch (sa->sa_family) {
- case AF_INET:
- remote = addressCreateFromInet((struct sockaddr_in *)sa);
- break;
-
- case AF_INET6:
- remote = addressCreateFromInet6((struct sockaddr_in6 *)sa);
- break;
-
- default:
- parcTrapIllegalValue(sa, "Expected INET or INET6, got %d", sa->sa_family);
- abort();
- }
-
- AddressPair *pair = addressPair_Create(tcp->localAddress, remote);
-
- IoOperations *ops = streamConnection_AcceptConnection(
- tcp->forwarder, fd, pair, tcp->isLocalAddressLocal);
- Connection *conn = connection_Create(ops);
-
- connectionTable_Add(forwarder_GetConnectionTable(tcp->forwarder), conn);
-
- if (logger_IsLoggable(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- logger_Log(tcp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "TcpListener %p listen started", (void *)tcp);
- }
-
- addressDestroy(&remote);
-}
-
-static void _tcpListener_OpsDestroy(ListenerOps **listenerOpsPtr) {
- ListenerOps *ops = *listenerOpsPtr;
- _TcpListener *tcp = (_TcpListener *)ops->context;
- _tcpListener_Destroy(&tcp);
- parcMemory_Deallocate((void **)&ops);
- *listenerOpsPtr = NULL;
-}
-
-static unsigned _tcpListener_OpsGetInterfaceIndex(const ListenerOps *ops) {
- _TcpListener *tcp = (_TcpListener *)ops->context;
- return tcp->id;
-}
-
-static const Address *_tcpListener_OpsGetListenAddress(const ListenerOps *ops) {
- _TcpListener *tcp = (_TcpListener *)ops->context;
- return tcp->localAddress;
-}
-
-static EncapType _tcpListener_OpsGetEncapType(const ListenerOps *ops) {
- return ENCAP_TCP;
-}
diff --git a/hicn-light/src/hicn/io/tcpListener.h b/hicn-light/src/hicn/io/tcpListener.h
deleted file mode 100644
index a841738e5..000000000
--- a/hicn-light/src/hicn/io/tcpListener.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file tcpListener.h
- * @brief Listens for in coming TCP connections
- *
- * This is the "server socket" of hicn-light for TCP connections. The actual
- * I/O is handled by {@link StreamConnection}.
- *
- */
-
-#ifndef tcpListener_h
-#define tcpListener_h
-
-#ifndef _WIN32
-#include <netinet/in.h>
-#endif
-
-#include <hicn/core/forwarder.h>
-#include <hicn/io/listener.h>
-#include <stdlib.h>
-
-ListenerOps *tcpListener_CreateInet6(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in6 sin6, char *interfaceName);
-ListenerOps *tcpListener_CreateInet(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in sin, char *interfaceName);
-#endif // tcpListener_h
diff --git a/hicn-light/src/hicn/io/tcpTunnel.c b/hicn-light/src/hicn/io/tcpTunnel.c
deleted file mode 100644
index 7a04a4222..000000000
--- a/hicn-light/src/hicn/io/tcpTunnel.c
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <hicn/io/streamConnection.h>
-#include <hicn/io/tcpListener.h>
-#include <hicn/io/tcpTunnel.h>
-
-IoOperations *tcpTunnel_Create(Forwarder *forwarder,
- const Address *localAddress,
- const Address *remoteAddress) {
- IoOperations *ops = NULL;
-
- address_type localType = addressGetType(localAddress);
- address_type remoteType = addressGetType(remoteAddress);
-
- if (localType == remoteType) {
- AddressPair *pair = addressPair_Create(localAddress, remoteAddress);
- bool isLocal = false;
-
- ops = streamConnection_OpenConnection(forwarder, pair, isLocal);
- }
-
- return ops;
-}
diff --git a/hicn-light/src/hicn/io/tcpTunnel.h b/hicn-light/src/hicn/io/tcpTunnel.h
deleted file mode 100644
index d1d2a8524..000000000
--- a/hicn-light/src/hicn/io/tcpTunnel.h
+++ /dev/null
@@ -1,42 +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.
- */
-
-/**
- * @file tcpTunnel.h
- * @brief Establish a tunnel to a remote system
- *
- */
-
-#ifndef tcpTunnel_h
-#define tcpTunnel_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/io/ioOperations.h>
-#include <hicn/io/listener.h>
-#include <hicn/utils/address.h>
-
-/**
- */
-// IoOperations *tcpTunnel_CreateOnListener(Forwarder *forwarder,
-// ListenerOps *localListener,
-// const Address *remoteAddress);
-
-/**
- */
-IoOperations *tcpTunnel_Create(Forwarder *forwarder,
- const Address *localAddress,
- const Address *remoteAddress);
-
-#endif // tcpTunnel_h
diff --git a/hicn-light/src/hicn/io/udp.c b/hicn-light/src/hicn/io/udp.c
new file mode 100644
index 000000000..d881b4b01
--- /dev/null
+++ b/hicn-light/src/hicn/io/udp.c
@@ -0,0 +1,565 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * @file udp.c
+ * #brief Implementation of the native UDP face leveraging the new packet format
+ * to avoid encapsulation.
+ *
+ */
+
+/* This has to be included early as other modules are including socket.h */
+
+#ifndef _WIN32
+#include <arpa/inet.h>
+#endif
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifndef _WIN32
+#include <sys/uio.h>
+#include <unistd.h>
+#endif
+#include <sys/socket.h>
+
+#ifdef WITH_GSO
+#include <netinet/if_ether.h> // ETH_DATA_LEN
+#include <linux/ipv6.h> // struct ipv6hdr
+#include <netinet/udp.h> // struct udphdr, SOL_UDP
+//#include <linux/udp.h> // UDP_GRO
+#define UDP_GRO 104
+#endif /* WITH_GSO */
+
+#include <hicn/util/log.h>
+#include <hicn/util/sstrncpy.h>
+#include <hicn/util/ring.h>
+
+#include "base.h"
+#include "../core/address_pair.h"
+#include "../core/connection.h"
+#include "../core/connection_vft.h"
+#include "../core/forwarder.h"
+#include "../core/listener.h"
+#include "../core/listener_vft.h"
+#include "../core/msgbuf.h"
+
+#define BATCH_SOCKET_BUFFER 512 * 1024 /* 256k */
+
+/******************************************************************************
+ * Listener
+ ******************************************************************************/
+
+typedef struct {
+ uint16_t port; // in address ?
+} listener_udp_data_t;
+
+#ifdef __ANDROID__
+extern int bindSocket(int sock, const char *interface_name);
+#endif
+
+#if 0
+#include <arpa/inet.h>
+char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen) {
+ switch (sa->sa_family) {
+ case AF_INET:
+ inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), s, maxlen);
+ break;
+
+ case AF_INET6:
+ inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), s, maxlen);
+ break;
+
+ default:
+ strncpy(s, "Unknown AF", maxlen);
+ return NULL;
+ }
+
+ return s;
+}
+#endif
+
+/* socket options */
+int socket_set_options(int fd) {
+#ifndef _WIN32
+ // Set non-blocking flag
+ int flags = fcntl(fd, F_GETFL, NULL);
+ if (flags < 0) {
+ perror("fcntl");
+ return -1;
+ }
+
+ if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
+ perror("fcntl");
+ return -1;
+ }
+#else
+ // Set non-blocking flag
+ int result = ioctlsocket(fd, FIONBIO, &(int){1});
+ if (result != NO_ERROR) {
+ perror("ioctlsocket");
+ return -1;
+ }
+#endif
+
+ // don't hang onto address after listener has closed
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &(int){1}, sizeof(int)) < 0) {
+ perror("setsockopt");
+ return -1;
+ }
+
+#ifdef WITH_GSO
+ int gso_size = ETH_DATA_LEN - sizeof(struct ipv6hdr) - sizeof(struct udphdr);
+ if (setsockopt(fd, SOL_UDP, UDP_SEGMENT, &gso_size, sizeof(gso_size)) < 0) {
+ perror("setsockopt");
+ return -1;
+ }
+#endif /* WITH_GSO */
+
+#ifdef WITH_GRO
+ if (setsockopt(fd, IPPROTO_UDP, UDP_GRO, &(int){1}, sizeof(int)) < 0) {
+ perror("setsockopt");
+ return -1;
+ }
+#endif /* WITH_GRO */
+
+#ifdef WITH_ZEROCOPY
+ if (setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY, &(int){1}, sizeof(int))) {
+ perror("setsockopt");
+ return -1;
+ }
+#endif /* WITH_ZEROCOPY */
+
+ if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &(int){BATCH_SOCKET_BUFFER},
+ sizeof(int)) < 0) {
+ perror("setsockopt");
+ return -1;
+ }
+ if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &(int){BATCH_SOCKET_BUFFER},
+ sizeof(int)) < 0) {
+ perror("setsockopt");
+ return -1;
+ }
+ return 0;
+}
+
+#ifdef __linux__
+/* bind to device */
+int socket_bind_to_device(int fd, const char *interface_name) {
+ if (strncmp("lo", interface_name, 2) == 0) return 0;
+
+ if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, interface_name,
+ strnlen_s(interface_name, IFNAMSIZ)) < 0) {
+ perror("setsockopt");
+ goto ERR_BIND_TO_DEVICE;
+ }
+
+ return 0;
+
+ERR_BIND_TO_DEVICE:
+#ifdef __ANDROID__
+ if (bindSocket(fd, interface_name) < 0) return -1;
+ return 0;
+#else
+ return -1;
+#endif /* __ANDROID__ */
+}
+#endif /* __linux__ */
+
+static int listener_udp_initialize(listener_t *listener) {
+ assert(listener);
+
+#if 0
+ listener_udp_data_t * data = listener->data;
+ assert(data);
+#endif
+ return 0;
+}
+
+static void listener_udp_finalize(listener_t *listener) {
+ assert(listener);
+ assert(listener->type == FACE_TYPE_UDP_LISTENER);
+
+ return;
+}
+
+static int listener_udp_punt(const listener_t *listener, const char *prefix_s) {
+ return -1;
+}
+
+static int listener_udp_get_socket(const listener_t *listener,
+ const address_t *local,
+ const address_t *remote,
+ const char *interface_name) {
+ int fd = socket(address_family(local), SOCK_DGRAM, 0);
+ if (fd < 0) goto ERR_SOCKET;
+
+ if (socket_set_options(fd) < 0) {
+ goto ERR;
+ }
+
+ if (bind(fd, address_sa(local), address_socklen(local)) < 0) {
+ perror("bind");
+ goto ERR;
+ }
+
+#ifdef __linux__
+ if (socket_bind_to_device(fd, interface_name) < 0) {
+ goto ERR;
+ }
+#endif /* __linux__ */
+
+ // DEBUG("UDP remote ?");
+ if (remote) {
+ // DEBUG("UDP connected socket ");
+ if (connect(fd, address_sa(remote), address_socklen(remote)) < 0) {
+ perror("connect");
+ goto ERR;
+ }
+ }
+
+ return fd;
+
+ERR:
+#ifndef _WIN32
+ close(fd);
+#else
+ closesocket(fd);
+#endif
+ERR_SOCKET:
+ return -1;
+}
+
+#define listener_udp_read_single io_read_single_socket
+
+#ifdef __linux__
+#define listener_udp_read_batch io_read_batch_socket
+#else
+#define listener_udp_read_batch NULL
+#endif /* __linux__ */
+
+DECLARE_LISTENER(udp);
+
+/******************************************************************************
+ * Connection
+ ******************************************************************************/
+
+#define RING_LEN 5 * MAX_MSG
+
+typedef struct {
+#ifdef __linux__
+ /* Ring buffer */
+ off_t *ring;
+
+ struct mmsghdr msghdr[MAX_MSG];
+ struct iovec iovecs[MAX_MSG];
+#endif /* __linux__ */
+} connection_udp_data_t;
+
+static int connection_udp_initialize(connection_t *connection) {
+ assert(connection);
+ assert(connection->type == FACE_TYPE_UDP);
+ assert(connection->interface_name);
+
+#ifdef __linux__
+ connection_udp_data_t *data = connection->data;
+ assert(data);
+
+ ring_init(data->ring, RING_LEN);
+
+ void *name = NULL;
+ int namelen = 0;
+
+ /*
+ * If the connection does not use a connected socket, we need to set the
+ * different destination addresses
+ */
+ if (!connection->connected) {
+ const address_t *remote = connection_get_remote(connection);
+ name = address_sa(remote);
+ namelen = address_socklen(remote);
+ }
+
+ memset(data->msghdr, 0, MAX_MSG * sizeof(struct mmsghdr));
+ for (unsigned i = 0; i < MAX_MSG; i++) {
+ struct mmsghdr *msg = &data->msghdr[i];
+ *msg = (struct mmsghdr){
+ .msg_hdr =
+ {
+ .msg_iov = &data->iovecs[i],
+ .msg_iovlen = 1,
+ .msg_name = name,
+ .msg_namelen = namelen,
+#if 0
+ .msg_control = NULL,
+ .msg_controllen = 0,
+ .msg_flags = 0,
+#endif
+ },
+ };
+ }
+#endif /* __linux__ */
+
+ return 0;
+}
+
+static void connection_udp_finalize(connection_t *connection) {
+ assert(connection);
+ assert(connection->type == FACE_TYPE_UDP);
+#ifdef __linux__
+ connection_udp_data_t *data = connection->data;
+ assert(data);
+
+ ring_free(data->ring);
+#endif /* __linux__ */
+}
+
+static bool connection_udp_flush(connection_t *connection) {
+#ifdef __linux__
+ int retry = 0;
+ off_t msgbuf_id = 0;
+ unsigned cpt;
+ size_t i;
+ int n;
+
+ assert(connection);
+ forwarder_t *forwarder = listener_get_forwarder(connection->listener);
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ connection_udp_data_t *data = connection->data;
+ assert(data);
+
+ TRACE("[connection_udp_send] Flushing connection queue");
+
+ /* Flush operation */
+#ifdef WITH_ZEROCOPY
+ int flags = MSG_ZEROCOPY;
+#else
+ int flags = 0;
+#endif /* WITH_ZEROCOPY */
+
+SEND:
+ /* Consume up to MSG_MSG packets in ring buffer */
+ cpt = 0;
+
+ ring_enumerate_n(data->ring, i, &msgbuf_id, MAX_MSG, {
+ msgbuf_t *msgbuf = msgbuf_pool_at(msgbuf_pool, msgbuf_id);
+
+ // update path label
+ if (msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA) {
+ msgbuf_update_pathlabel(msgbuf, connection_get_id(connection));
+
+ connection->stats.data.tx_pkts++;
+ connection->stats.data.tx_bytes += msgbuf_get_len(msgbuf);
+ } else {
+ connection->stats.interests.tx_pkts++;
+ connection->stats.interests.tx_bytes += msgbuf_get_len(msgbuf);
+ }
+
+ data->iovecs[i].iov_base = msgbuf_get_packet(msgbuf);
+ data->iovecs[i].iov_len = msgbuf_get_len(msgbuf);
+ cpt++;
+ });
+
+SENDMMSG:
+ n = sendmmsg(connection->fd, data->msghdr, cpt, flags);
+ if (n == -1) {
+ /* man(2)sendmmsg / BUGS
+ *
+ * If an error occurs after at least one message has been sent, the call
+ * succeeds, and returns the number of messages sent. The error code is
+ * lost. The caller can retry the transmission, starting at the first
+ * failed message, but there is no guarantee that, if an error is
+ * returned, it will be the same as the one that was lost on the previous
+ * call.
+ */
+ WARN("sendmmsg failed %s", strerror(errno));
+ if (retry < 1) {
+ retry++;
+ goto SENDMMSG;
+ }
+ return false;
+ }
+
+ ring_advance(data->ring, n);
+
+ if (n < cpt) {
+ WARN("Unknown error after sending n=%d packets...", n);
+ if (retry < 1) {
+ retry++;
+ goto SEND;
+ }
+ }
+
+ if (ring_get_size(data->ring) > 0) {
+ retry = 0;
+ goto SEND;
+ }
+#endif /* __linux__ */
+ return true;
+}
+
+/**
+ * @function metisUdpConnection_Send
+ * @abstract Non-destructive send of the message.
+ * @discussion
+ * sends a message to the peer.
+ *
+ * @param dummy is ignored. A udp connection has only one peer.
+ * @return <#return#>
+ */
+static bool connection_udp_send(connection_t *connection, msgbuf_t *msgbuf,
+ bool queue) {
+ assert(connection);
+ assert(msgbuf);
+
+#ifdef __linux__
+ connection_udp_data_t *data = connection->data;
+ assert(data);
+
+ forwarder_t *forwarder = listener_get_forwarder(connection->listener);
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+
+ /* Queue packet ? */
+ if (queue) {
+ off_t msgbuf_id;
+ if (ring_is_full(data->ring)) connection_udp_flush(connection);
+
+ msgbuf_id = msgbuf_pool_get_id(msgbuf_pool, msgbuf);
+ ring_add(data->ring, &msgbuf_id);
+
+ } else {
+#endif /* __linux__ */
+ /* Send one */
+ // update the path label befor send the packet
+ if (msgbuf_get_type(msgbuf) == HICN_PACKET_TYPE_DATA) {
+ msgbuf_update_pathlabel(msgbuf, connection_get_id(connection));
+
+ connection->stats.data.tx_pkts++;
+ connection->stats.data.tx_bytes += msgbuf_get_len(msgbuf);
+ } else {
+ connection->stats.interests.tx_pkts++;
+ connection->stats.interests.tx_bytes += msgbuf_get_len(msgbuf);
+ }
+
+ ssize_t writeLength = write(connection->fd, msgbuf_get_packet(msgbuf),
+ msgbuf_get_len(msgbuf));
+
+ if (writeLength < 0) {
+ if (errno == EAGAIN || errno == EWOULDBLOCK) {
+ return false;
+ } else {
+ // this print is for debugging
+ printf("Incorrect write length %zd, expected %lu: (%d) %s\n",
+ writeLength, (long unsigned int)msgbuf_get_len(msgbuf), errno,
+ strerror(errno));
+ return false;
+ }
+ }
+#ifdef __linux__
+ }
+#endif /* __linux__ */
+
+ return true;
+}
+
+#if 0
+static
+bool
+connection_udp_sendv(const connection_t * connection, struct iovec * iov,
+ size_t size)
+{
+
+ assert(connetion);
+ assert(iov);
+
+ connection_udp_data_t * data = connection->data;
+ assert(data);
+
+#ifndef _WIN32
+ // Perform connect before to establish association between this peer and
+ // the remote peer. This is required to use writev.
+ // Connection association can be changed at any time.
+
+ if (writev(connection->fd, iov, (int)size) < 0)
+ return false;
+#else
+ WSABUF *buf = (WSABUF *) malloc(size * sizeof(WSABUF));
+
+ DWORD bytes_sent = 0;
+
+ for (int i = 0; i < size; i++) {
+ buf[i].buf = iov[i].iov_base;
+ buf[i].len = (ULONG)iov[i].iov_len;
+ }
+
+ int rc = WSASendTo(udp->fd, buf, size, &bytes_sent, 0,
+ (SOCKADDR *)address_sa(address_pair_remote(&udp->pair)),
+ address_socklen(address_pair_remote(&udp->pair)), NULL, NULL);
+ free(dataBuf);
+ if (rc == SOCKET_ERROR)
+ return false;
+#endif
+
+ return true;
+}
+#endif
+
+static bool connection_udp_send_packet(const connection_t *connection,
+ const uint8_t *packet, size_t size) {
+ assert(connection);
+ assert(packet);
+
+ // XXX: in case of two connections this functions may have wrong behaviour. We
+ // noticed that the packet is sent by the forwarder on the right socket (fd)
+ // but from tcpdump we see that the packet goes on the other connection. In
+ // other cases the packet is sent twice, first on the wrong socket and later
+ // on the right one, even if we log a single send from the forwarder. The
+ // same behaviour was observed with the write executed in the function
+ // connection_udp_send with the queue flag set to false. A workaround that
+ // seems to solve the problem is to use connection_udp_send with queue = true
+ // and force the flush of the connection if needed.
+
+ // TODO: commented otherwise unable to do tests locally
+ // if(connection_is_local(connection))
+ // return -1;
+
+#ifdef USE_CONNECTED_SOCKETS
+ ssize_t n = send(connection->fd, packet, size, 0);
+ if (n < 0) {
+ perror("sendto");
+ return false;
+ }
+#else
+ const address_t *remote = connection_get_remote(connection);
+ ssize_t n = sendto(connection->fd, packet, size, 0, address_sa(remote),
+ address_socklen(remote));
+ if (n < 0) return false;
+#endif
+
+ return true;
+}
+
+#define connection_udp_read_single \
+ listener_read_batch_socket listener_single_socket
+
+#ifdef __linux__
+#define connection_udp_read_batch listener_read_batch_socket
+#else
+#define connection_udp_read_batch NULL
+#endif /* __linux__ */
+
+DECLARE_CONNECTION(udp);
diff --git a/hicn-light/src/hicn/io/udpConnection.c b/hicn-light/src/hicn/io/udpConnection.c
deleted file mode 100644
index 2747b7ef4..000000000
--- a/hicn-light/src/hicn/io/udpConnection.c
+++ /dev/null
@@ -1,495 +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.
- */
-
-/**
- * Embodies the reader/writer for a UDP connection
- *
- * NB The Send() function may overflow the output buffer
- *
- */
-
-#ifndef _WIN32
-#include <sys/uio.h>
-#endif
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <hicn/core/messageHandler.h>
-#include <hicn/io/udpConnection.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/core/connection.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/core/message.h>
-
-typedef struct udp_state {
- Forwarder *forwarder;
- char * interfaceName;
- Logger *logger;
-
- // the udp listener socket we receive packets on
- int udpListenerSocket;
-
- AddressPair *addressPair;
-
- // We need to access this all the time, so grab it out
- // of the addressPair;
- struct sockaddr *peerAddress;
- socklen_t peerAddressLength;
-
- bool isLocal;
- bool isUp;
- unsigned id;
-
- unsigned delay;
-
- /* This information would better be stored in the connection data structure
- * but it is currently not reachable from within the implementation. */
- connection_state_t state;
- connection_state_t admin_state;
-#ifdef WITH_POLICY
- uint32_t priority;
-#endif /* WITH_POLICY */
-} _UdpState;
-
-// Prototypes
-static bool _send(IoOperations *ops, const Address *nexthop, Message *message);
-static bool _sendIOVBuffer(IoOperations *ops, struct iovec *message,
- size_t size);
-static const Address *_getRemoteAddress(const IoOperations *ops);
-static const AddressPair *_getAddressPair(const IoOperations *ops);
-static unsigned _getConnectionId(const IoOperations *ops);
-static bool _isUp(const IoOperations *ops);
-static bool _isLocal(const IoOperations *ops);
-static void _destroy(IoOperations **opsPtr);
-static list_connections_type _getConnectionType(const IoOperations *ops);
-static void _sendProbe(IoOperations *ops, uint8_t *message);
-static connection_state_t _getState(const IoOperations *ops);
-static void _setState(IoOperations *ops, connection_state_t state);
-static connection_state_t _getAdminState(const IoOperations *ops);
-static void _setAdminState(IoOperations *ops, connection_state_t admin_state);
-#ifdef WITH_POLICY
-static uint32_t _getPriority(const IoOperations *ops);
-static void _setPriority(IoOperations *ops, uint32_t priority);
-#endif /* WITH_POLICY */
-static const char * _getInterfaceName(const IoOperations *ops);
-
-/*
- * This assigns a unique pointer to the void * which we use
- * as a GUID for this class.
- */
-static const void *_IoOperationsGuid = __FILE__;
-
-/*
- * Return our GUID
- */
-static const void *_streamConnection_Class(const IoOperations *ops) {
- return _IoOperationsGuid;
-}
-
-static IoOperations _template = {
- .closure = NULL,
- .send = &_send,
- .sendIOVBuffer = &_sendIOVBuffer,
- .getRemoteAddress = &_getRemoteAddress,
- .getAddressPair = &_getAddressPair,
- .getConnectionId = &_getConnectionId,
- .isUp = &_isUp,
- .isLocal = &_isLocal,
- .destroy = &_destroy,
- .class = &_streamConnection_Class,
- .getConnectionType = &_getConnectionType,
- .sendProbe = &_sendProbe,
- .getState = &_getState,
- .setState = &_setState,
- .getAdminState = &_getAdminState,
- .setAdminState = &_setAdminState,
-#ifdef WITH_POLICY
- .getPriority = &_getPriority,
- .setPriority = &_setPriority,
-#endif /* WITH_POLICY */
- .getInterfaceName = &_getInterfaceName,
-};
-
-// =================================================================
-
-static void _setConnectionState(_UdpState *Udp, bool isUp);
-static bool _saveSockaddr(_UdpState *udpConnState, const AddressPair *pair);
-
-IoOperations *udpConnection_Create(Forwarder *forwarder, const char * interfaceName, int fd,
- const AddressPair *pair, bool isLocal) {
- IoOperations *io_ops = NULL;
-
- _UdpState *udpConnState = parcMemory_AllocateAndClear(sizeof(_UdpState));
- parcAssertNotNull(udpConnState,
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(_UdpState));
-
- udpConnState->forwarder = forwarder;
- udpConnState->interfaceName = strdup(interfaceName);
- udpConnState->logger = logger_Acquire(forwarder_GetLogger(forwarder));
-
- bool saved = _saveSockaddr(udpConnState, pair);
- if (saved) {
- udpConnState->udpListenerSocket = fd;
- udpConnState->id = forwarder_GetNextConnectionId(forwarder);
- udpConnState->addressPair = addressPair_Acquire(pair);
- udpConnState->isLocal = isLocal;
-
- // allocate a connection
- io_ops = parcMemory_AllocateAndClear(sizeof(IoOperations));
- parcAssertNotNull(io_ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(IoOperations));
- memcpy(io_ops, &_template, sizeof(IoOperations));
- io_ops->closure = udpConnState;
-
- _setConnectionState(udpConnState, true);
-
-#ifdef WITH_POLICY
- udpConnState->priority = 0;
-#endif /* WITH_POLICY */
-
- if (logger_IsLoggable(udpConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Info)) {
- char *str = addressPair_ToString(udpConnState->addressPair);
- logger_Log(udpConnState->logger, LoggerFacility_IO, PARCLogLevel_Info,
- __func__,
- "UdpConnection %p created for address %s (isLocal %d)",
- (void *)udpConnState, str, udpConnState->isLocal);
- free(str);
- }
-
- messenger_Send(
- forwarder_GetMessenger(forwarder),
- missive_Create(MissiveType_ConnectionCreate, udpConnState->id));
- messenger_Send(forwarder_GetMessenger(forwarder),
- missive_Create(MissiveType_ConnectionUp, udpConnState->id));
- } else {
- // _saveSockaddr will already log an error, no need for extra log message
- // here
- logger_Release(&udpConnState->logger);
-
- free(udpConnState->interfaceName);
- parcMemory_Deallocate((void **)&udpConnState);
- }
-
- return io_ops;
-}
-
-// =================================================================
-// I/O Operations implementation
-
-static void _destroy(IoOperations **opsPtr) {
- parcAssertNotNull(opsPtr, "Parameter opsPtr must be non-null double pointer");
- parcAssertNotNull(*opsPtr,
- "Parameter opsPtr must dereference to non-null pointer");
-
- IoOperations *ops = *opsPtr;
- parcAssertNotNull(ioOperations_GetClosure(ops),
- "ops->context must not be null");
-
- _UdpState *udpConnState = (_UdpState *)ioOperations_GetClosure(ops);
- addressPair_Release(&udpConnState->addressPair);
- parcMemory_Deallocate((void **)&(udpConnState->peerAddress));
-
- messenger_Send(
- forwarder_GetMessenger(udpConnState->forwarder),
- missive_Create(MissiveType_ConnectionDestroyed, udpConnState->id));
-
- if (logger_IsLoggable(udpConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Info)) {
- logger_Log(udpConnState->logger, LoggerFacility_IO, PARCLogLevel_Info,
- __func__, "UdpConnection %p destroyed", (void *)udpConnState);
- }
-
- // do not close udp->udpListenerSocket, the listener will close
- // that when its done
-
- logger_Release(&udpConnState->logger);
- free(udpConnState->interfaceName);
- parcMemory_Deallocate((void **)&udpConnState);
- parcMemory_Deallocate((void **)&ops);
-
- *opsPtr = NULL;
-}
-
-static bool _isUp(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->isUp;
-}
-
-static bool _isLocal(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->isLocal;
-}
-
-static const Address *_getRemoteAddress(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return addressPair_GetRemote(udpConnState->addressPair);
-}
-
-static const AddressPair *_getAddressPair(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->addressPair;
-}
-
-static unsigned _getConnectionId(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->id;
-}
-
-/**
- * @function metisUdpConnection_Send
- * @abstract Non-destructive send of the message.
- * @discussion
- * sends a message to the peer.
- *
- * @param dummy is ignored. A udp connection has only one peer.
- * @return <#return#>
- */
-static bool _send(IoOperations *ops, const Address *dummy, Message *message) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
- _UdpState *udpConnState = (_UdpState *)ioOperations_GetClosure(ops);
-
- // NAT for HICN
- // in this particular connection we don't need natting beacause we send the
- // packet to the next hop using upd connection
-
- ssize_t writeLength =
- sendto(udpConnState->udpListenerSocket, message_FixedHeader(message),
- (int)message_Length(message), 0, udpConnState->peerAddress,
- udpConnState->peerAddressLength);
-
- if (writeLength < 0) {
- if (errno == EAGAIN || errno == EWOULDBLOCK) {
- return false;
- } else {
- // this print is for debugging
- printf("Incorrect write length %zd, expected %zd: (%d) %s\n", writeLength,
- message_Length(message), errno, strerror(errno));
- return false;
- }
- }
-
- return true;
-}
-
-static bool _sendIOVBuffer(IoOperations *ops, struct iovec *message,
- size_t size) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
- _UdpState *udpConnState = (_UdpState *)ioOperations_GetClosure(ops);
-
-#ifndef _WIN32
- // Perform connect before to establish association between this peer and
- // the remote peer. This is required to use writev.
- // Connection association can be changed at any time.
- connect(udpConnState->udpListenerSocket,
- udpConnState->peerAddress,
- udpConnState->peerAddressLength);
-
- ssize_t writeLength = writev(udpConnState->udpListenerSocket, message, (int)size);
-
- struct sockaddr any_address = {0};
- any_address.sa_family = AF_UNSPEC;
- connect(udpConnState->udpListenerSocket,
- &any_address, (socklen_t)sizeof(any_address));
-
- if (writeLength < 0) {
- return false;
- }
-#else
-
- WSABUF *dataBuf = (WSABUF *) malloc(size * sizeof (dataBuf));
- DWORD BytesSent = 0;
-
- for (int i = 0; i < size; i++) {
- dataBuf[i].buf = message[i].iov_base;
- dataBuf[i].len = (ULONG)message[i].iov_len;
- }
-
- int rc = WSASendTo(udpConnState->udpListenerSocket, dataBuf, (DWORD)size,
- &BytesSent, 0, (SOCKADDR *)udpConnState->peerAddress,
- udpConnState->peerAddressLength, NULL, NULL);
- free(dataBuf);
- if (rc == SOCKET_ERROR) {
- return false;
- }
-#endif
- return true;
-}
-
-static list_connections_type _getConnectionType(const IoOperations *ops) {
- return CONN_UDP;
-}
-
-static void _sendProbe(IoOperations *ops, uint8_t *message) {
- parcAssertNotNull(ops, "Parameter ops must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
- _UdpState *udpConnState = (_UdpState *)ioOperations_GetClosure(ops);
-
- if(udpConnState->isLocal)
- return;
-
- ssize_t writeLength =
- sendto(udpConnState->udpListenerSocket, message,
- messageHandler_GetTotalPacketLength(message), 0, udpConnState->peerAddress,
- udpConnState->peerAddressLength);
-
- if (writeLength < 0) {
- return;
- }
-}
-
-// =================================================================
-// Internal API
-
-static bool _saveSockaddr(_UdpState *udpConnState, const AddressPair *pair) {
- bool success = false;
- const Address *remoteAddress = addressPair_GetRemote(pair);
-
- switch (addressGetType(remoteAddress)) {
- case ADDR_INET: {
- size_t bytes = sizeof(struct sockaddr_in);
- udpConnState->peerAddress = parcMemory_Allocate(bytes);
- parcAssertNotNull(udpConnState->peerAddress,
- "parcMemory_Allocate(%zu) returned NULL", bytes);
-
- addressGetInet(remoteAddress,
- (struct sockaddr_in *)udpConnState->peerAddress);
- udpConnState->peerAddressLength = (socklen_t)bytes;
-
- success = true;
- break;
- }
-
- case ADDR_INET6: {
- size_t bytes = sizeof(struct sockaddr_in6);
- udpConnState->peerAddress = parcMemory_Allocate(bytes);
- parcAssertNotNull(udpConnState->peerAddress,
- "parcMemory_Allocate(%zu) returned NULL", bytes);
-
- addressGetInet6(remoteAddress,
- (struct sockaddr_in6 *)udpConnState->peerAddress);
- udpConnState->peerAddressLength = (socklen_t)bytes;
-
- success = true;
- break;
- }
-
- default:
- if (logger_IsLoggable(udpConnState->logger, LoggerFacility_IO,
- PARCLogLevel_Error)) {
- char *str = addressToString(remoteAddress);
- logger_Log(udpConnState->logger, LoggerFacility_IO, PARCLogLevel_Error,
- __func__, "Remote address is not INET or INET6: %s", str);
- parcMemory_Deallocate((void **)&str);
- }
- break;
- }
- return success;
-}
-
-static void _setConnectionState(_UdpState *udpConnState, bool isUp) {
- parcAssertNotNull(udpConnState, "Parameter Udp must be non-null");
-
- Messenger *messenger = forwarder_GetMessenger(udpConnState->forwarder);
-
- bool oldStateIsUp = udpConnState->isUp;
- udpConnState->isUp = isUp;
-
- if (oldStateIsUp && !isUp) {
- // bring connection DOWN
- Missive *missive =
- missive_Create(MissiveType_ConnectionDown, udpConnState->id);
- messenger_Send(messenger, missive);
- return;
- }
-
- if (!oldStateIsUp && isUp) {
- // bring connection UP
- Missive *missive =
- missive_Create(MissiveType_ConnectionUp, udpConnState->id);
- messenger_Send(messenger, missive);
- return;
- }
-}
-
-static connection_state_t _getState(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->state;
-}
-
-static void _setState(IoOperations *ops, connection_state_t state) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _UdpState *udpConnState =
- (_UdpState *)ioOperations_GetClosure(ops);
- udpConnState->state = state;
-}
-
-static connection_state_t _getAdminState(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->admin_state;
-}
-
-static void _setAdminState(IoOperations *ops, connection_state_t admin_state) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _UdpState *udpConnState =
- (_UdpState *)ioOperations_GetClosure(ops);
- udpConnState->admin_state = admin_state;
-}
-
-#ifdef WITH_POLICY
-static uint32_t _getPriority(const IoOperations *ops) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- const _UdpState *udpConnState =
- (const _UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->priority;
-}
-
-static void _setPriority(IoOperations *ops, uint32_t priority) {
- parcAssertNotNull(ops, "Parameter must be non-null");
- _UdpState *udpConnState =
- (_UdpState *)ioOperations_GetClosure(ops);
- udpConnState->priority = priority;
-}
-#endif /* WITH_POLICY */
-
-static const char * _getInterfaceName(const IoOperations *ops)
-{
- parcAssertNotNull(ops, "Parameter must be non-null");
- _UdpState *udpConnState =
- (_UdpState *)ioOperations_GetClosure(ops);
- return udpConnState->interfaceName;
-}
diff --git a/hicn-light/src/hicn/io/udpConnection.h b/hicn-light/src/hicn/io/udpConnection.h
deleted file mode 100644
index 9fbc5348b..000000000
--- a/hicn-light/src/hicn/io/udpConnection.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.
- */
-
-/**
- * @file udpConnection.h
- * @brief Represents a UDP connection (socket) for the connection table
- *
- * <#Detailed Description#>
- *
- */
-
-#ifndef udpConnection_h
-#define udpConnection_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/io/addressPair.h>
-#include <hicn/io/ioOperations.h>
-#include <hicn/utils/address.h>
-
-/**
- * Creates a UDP connection that can send to the remote address
- *
- * The address pair must both be same type (i.e. INET or INET6).
- *
- * @param [in] metis An allocated MetisForwarder (saves reference)
- * @param [in] fd The socket to use
- * @param [in] pair An allocated address pair for the connection (saves
- * reference)
- * @param [in] isLocal determines if the remote address is on the current system
- *
- * @retval non-null An allocated Io operations
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-IoOperations *udpConnection_Create(Forwarder *forwarder, const char * interfaceName, int fd,
- const AddressPair *pair, bool isLocal);
-#endif // udpConnection_h
diff --git a/hicn-light/src/hicn/io/udpListener.c b/hicn-light/src/hicn/io/udpListener.c
deleted file mode 100644
index 3b318c500..000000000
--- a/hicn-light/src/hicn/io/udpListener.c
+++ /dev/null
@@ -1,653 +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.
- */
-
-#ifndef _WIN32
-#include <arpa/inet.h>
-#include <unistd.h>
-#endif
-#include <errno.h>
-#include <fcntl.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <hicn/core/messageHandler.h>
-
-#include <hicn/io/udpConnection.h>
-#include <hicn/io/udpListener.h>
-
-#include <parc/algol/parc_Network.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/core/connection.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/core/messagePacketType.h>
-
-#define IPv4 4
-#define IPv6 6
-
-struct udp_listener {
- char *listenerName;
- Forwarder *forwarder;
- Logger *logger;
-
- PARCEvent *udp_event;
- SocketType udp_socket;
- uint16_t port;
-
- unsigned id;
- char *interfaceName;
- Address *localAddress;
-};
-
-static void _destroy(ListenerOps **listenerOpsPtr);
-static const char *_getListenerName(const ListenerOps *ops);
-static unsigned _getInterfaceIndex(const ListenerOps *ops);
-static const Address *_getListenAddress(const ListenerOps *ops);
-static EncapType _getEncapType(const ListenerOps *ops);
-static const char *_getInterfaceName(const ListenerOps *ops);
-static int _getSocket(const ListenerOps *ops);
-static unsigned _createNewConnection(ListenerOps *listener, int fd, const AddressPair *pair);
-static const Connection * _lookupConnection(ListenerOps * listener, const AddressPair *pair);
-
-static ListenerOps udpTemplate = {
- .context = NULL,
- .destroy = &_destroy,
- .getInterfaceIndex = &_getInterfaceIndex,
- .getListenAddress = &_getListenAddress,
- .getEncapType = &_getEncapType,
- .getSocket = &_getSocket,
- .getListenerName = &_getListenerName,
- .createConnection = &_createNewConnection,
- .lookupConnection = &_lookupConnection,
- .getInterfaceName = &_getInterfaceName,
-};
-
-
-static void _readcb(int fd, PARCEventType what, void * listener_void);
-
-#ifdef __ANDROID__
-extern int bindSocket(int sock, const char* ifname);
-#endif
-
-ListenerOps *udpListener_CreateInet6(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in6 sin6, const char *interfaceName) {
- ListenerOps *ops = NULL;
-
- UdpListener *udp = parcMemory_AllocateAndClear(sizeof(UdpListener));
- parcAssertNotNull(udp, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(UdpListener));
- udp->forwarder = forwarder;
- udp->listenerName = parcMemory_StringDuplicate(listenerName, strlen(listenerName));
- udp->interfaceName = parcMemory_StringDuplicate(interfaceName, strlen(interfaceName));
- udp->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- udp->localAddress = addressCreateFromInet6(&sin6);
- udp->id = forwarder_GetNextConnectionId(forwarder);
-
- udp->udp_socket = (SocketType)socket(AF_INET6, SOCK_DGRAM, 0);
- parcAssertFalse(udp->udp_socket < 0, "Error opening UDP socket: (%d) %s",
- errno, strerror(errno));
-
- int failure = 0;
-#ifndef _WIN32
- // Set non-blocking flag
- int flags = fcntl(udp->udp_socket, F_GETFL, NULL);
- parcAssertTrue(flags != -1,
- "fcntl failed to obtain file descriptor flags (%d)", errno);
- failure = fcntl(udp->udp_socket, F_SETFL, flags | O_NONBLOCK);
- parcAssertFalse(failure, "fcntl failed to set file descriptor flags (%d)",
- errno);
-#else
- // Set non-blocking flag
- u_long mode = 1;
- int result = ioctlsocket(udp->udp_socket, FIONBIO, &mode);
- if (result != NO_ERROR) {
- parcAssertTrue(result != NO_ERROR,
- "ioctlsocket failed to set file descriptor");
- }
-#endif
-
- int one = 1;
- // don't hang onto address after listener has closed
- failure = setsockopt(udp->udp_socket, SOL_SOCKET, SO_REUSEADDR, (void *)&one,
- (socklen_t)sizeof(one));
- parcAssertFalse(failure, "failed to set REUSEADDR on socket(%d)", errno);
-
- failure = bind(udp->udp_socket, (struct sockaddr *)&sin6, sizeof(sin6));
-
- if (failure == 0) {
-#ifdef __linux__
- if (strncmp("lo", interfaceName, 2) != 0) {
- int ret = setsockopt(udp->udp_socket, SOL_SOCKET, SO_BINDTODEVICE,
- interfaceName, strlen(interfaceName) + 1);
- if (ret < 0) {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "setsockopt(%d, SO_BINDTODEVICE, %s) failed (%d) %s",
- udp->udp_socket, interfaceName, errno, strerror(errno));
-#ifdef __ANDROID__
- ret = bindSocket(udp->udp_socket, interfaceName);
- if (ret < 0) {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "bindSocket(%d, %s) failed", udp->udp_socket, interfaceName);
- close(udp->udp_socket);
- addressDestroy(&udp->localAddress);
- logger_Release(&udp->logger);
- parcMemory_Deallocate((void **)&udp);
- return NULL;
- } else {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "bindSocket(%d, %s) success", udp->udp_socket, interfaceName);
- }
-#else
- close(udp->udp_socket);
- addressDestroy(&udp->localAddress);
- logger_Release(&udp->logger);
- parcMemory_Deallocate((void **)&udp);
- return NULL;
-#endif
- }
- }
-#endif
-
- ops = parcMemory_AllocateAndClear(sizeof(ListenerOps));
- parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListenerOps));
- memcpy(ops, &udpTemplate, sizeof(ListenerOps));
- ops->context = udp;
-
- udp->udp_event =
- dispatcher_CreateNetworkEvent(forwarder_GetDispatcher(forwarder), true,
- _readcb, (void*)ops, udp->udp_socket);
- dispatcher_StartNetworkEvent(forwarder_GetDispatcher(forwarder),
- udp->udp_event);
-
- if (logger_IsLoggable(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- char *str = addressToString(udp->localAddress);
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "UdpListener %p created for address %s", (void *)udp, str);
- parcMemory_Deallocate((void **)&str);
- }
- } else {
- if (logger_IsLoggable(udp->logger, LoggerFacility_IO, PARCLogLevel_Error)) {
- int myerrno = errno;
- char *str = addressToString(udp->localAddress);
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Error binding UDP socket to address %s: (%d) %s", str,
- myerrno, strerror(myerrno));
- parcMemory_Deallocate((void **)&str);
- }
- parcMemory_Deallocate((void **)&udp->listenerName);
- parcMemory_Deallocate((void **)&udp->interfaceName);
-#ifndef _WIN32
- close(udp->udp_socket);
-#else
- closesocket(udp->udp_socket);
-#endif
- addressDestroy(&udp->localAddress);
- logger_Release(&udp->logger);
- parcMemory_Deallocate((void **)&udp);
- }
-
- return ops;
-}
-
-ListenerOps *udpListener_CreateInet(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in sin, const char *interfaceName) {
- ListenerOps *ops = NULL;
-
- UdpListener *udp = parcMemory_AllocateAndClear(sizeof(UdpListener));
- parcAssertNotNull(udp, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(UdpListener));
- udp->forwarder = forwarder;
- udp->listenerName = parcMemory_StringDuplicate(listenerName, strlen(listenerName));
- udp->interfaceName = parcMemory_StringDuplicate(interfaceName, strlen(interfaceName));
- udp->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- udp->localAddress = addressCreateFromInet(&sin);
- udp->id = forwarder_GetNextConnectionId(forwarder);
-
- udp->udp_socket = (SocketType)socket(AF_INET, SOCK_DGRAM, 0);
- parcAssertFalse(udp->udp_socket < 0, "Error opening UDP socket: (%d) %s",
- errno, strerror(errno));
-
- int failure = 0;
-#ifndef _WIN32
- // Set non-blocking flag
- int flags = fcntl(udp->udp_socket, F_GETFL, NULL);
- parcAssertTrue(flags != -1,
- "fcntl failed to obtain file descriptor flags (%d)", errno);
- failure = fcntl(udp->udp_socket, F_SETFL, flags | O_NONBLOCK);
- parcAssertFalse(failure, "fcntl failed to set file descriptor flags (%d)",
- errno);
-#else
- u_long mode = 1;
- int result = ioctlsocket(udp->udp_socket, FIONBIO, &mode);
- if (result != NO_ERROR) {
- parcAssertTrue(result != NO_ERROR,
- "ioctlsocket failed to set file descriptor");
- }
-#endif
-
- int one = 1;
- // don't hang onto address after listener has closed
- failure = setsockopt(udp->udp_socket, SOL_SOCKET, SO_REUSEADDR, (void *)&one,
- (socklen_t)sizeof(one));
- parcAssertFalse(failure, "failed to set REUSEADDR on socket(%d)", errno);
-
- failure = bind(udp->udp_socket, (struct sockaddr *)&sin, sizeof(sin));
- if (failure == 0) {
-#ifdef __linux__
- if (strncmp("lo", interfaceName, 2) != 0) {
- int ret = setsockopt(udp->udp_socket, SOL_SOCKET, SO_BINDTODEVICE,
- interfaceName, strlen(interfaceName) + 1);
- if (ret < 0) {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "setsockopt(%d, SO_BINDTODEVICE, %s) failed (%d) %s",
- udp->udp_socket, interfaceName, errno, strerror(errno));
-#ifdef __ANDROID__
- ret = bindSocket(udp->udp_socket, interfaceName);
- if (ret < 0) {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "bindSocket(%d, %s) failed", udp->udp_socket, interfaceName);
- close(udp->udp_socket);
- addressDestroy(&udp->localAddress);
- logger_Release(&udp->logger);
- parcMemory_Deallocate((void **)&udp);
- return NULL;
- } else {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "bindSocket(%d, %s) success", udp->udp_socket, interfaceName);
- }
-#else
- close(udp->udp_socket);
- addressDestroy(&udp->localAddress);
- logger_Release(&udp->logger);
- parcMemory_Deallocate((void **)&udp);
- return NULL;
-#endif
- }
- }
-#endif
- ops = parcMemory_AllocateAndClear(sizeof(ListenerOps));
- parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(ListenerOps));
- memcpy(ops, &udpTemplate, sizeof(ListenerOps));
- ops->context = udp;
-
- udp->udp_event =
- dispatcher_CreateNetworkEvent(forwarder_GetDispatcher(forwarder), true,
- _readcb, (void *)ops, udp->udp_socket);
- dispatcher_StartNetworkEvent(forwarder_GetDispatcher(forwarder),
- udp->udp_event);
-
-
- if (logger_IsLoggable(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- char *str = addressToString(udp->localAddress);
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "UdpListener %p created for address %s", (void *)udp, str);
- parcMemory_Deallocate((void **)&str);
- }
- } else {
- if (logger_IsLoggable(udp->logger, LoggerFacility_IO, PARCLogLevel_Error)) {
- int myerrno = errno;
- char *str = addressToString(udp->localAddress);
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Error binding UDP socket to address %s: (%d) %s", str,
- myerrno, strerror(myerrno));
- parcMemory_Deallocate((void **)&str);
- }
- parcMemory_Deallocate((void **)&udp->listenerName);
- parcMemory_Deallocate((void **)&udp->interfaceName);
-#ifndef _WIN32
- close(udp->udp_socket);
-#else
- closesocket(udp->udp_socket);
-#endif
- addressDestroy(&udp->localAddress);
- logger_Release(&udp->logger);
- parcMemory_Deallocate((void **)&udp);
- }
-
- return ops;
-}
-
-static void udpListener_Destroy(UdpListener **listenerPtr) {
- parcAssertNotNull(listenerPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*listenerPtr,
- "Parameter must derefernce to non-null pointer");
-
- UdpListener *udp = *listenerPtr;
-
- if (logger_IsLoggable(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "UdpListener %p destroyed", (void *)udp);
- }
-
- parcMemory_Deallocate((void **)&udp->listenerName);
- parcMemory_Deallocate((void **)&udp->interfaceName);
-#ifndef _WIN32
- close(udp->udp_socket);
-#else
- closesocket(udp->udp_socket);
-#endif
-
- addressDestroy(&udp->localAddress);
- dispatcher_DestroyNetworkEvent(forwarder_GetDispatcher(udp->forwarder),
- &udp->udp_event);
- logger_Release(&udp->logger);
- parcMemory_Deallocate((void **)&udp);
- *listenerPtr = NULL;
-}
-
-static const char *_getListenerName(const ListenerOps *ops) {
- UdpListener *udp = (UdpListener *)ops->context;
- return udp->listenerName;
-}
-
-static const char *_getInterfaceName(const ListenerOps *ops) {
- UdpListener *udp = (UdpListener *)ops->context;
- return udp->interfaceName;
-}
-
-static void _destroy(ListenerOps **listenerOpsPtr) {
- ListenerOps *ops = *listenerOpsPtr;
- UdpListener *udp = (UdpListener *)ops->context;
- udpListener_Destroy(&udp);
- parcMemory_Deallocate((void **)&ops);
- *listenerOpsPtr = NULL;
-}
-
-static unsigned _getInterfaceIndex(const ListenerOps *ops) {
- UdpListener *udp = (UdpListener *)ops->context;
- return udp->id;
-}
-
-static const Address *_getListenAddress(const ListenerOps *ops) {
- UdpListener *udp = (UdpListener *)ops->context;
- return udp->localAddress;
-}
-
-static EncapType _getEncapType(const ListenerOps *ops) { return ENCAP_UDP; }
-
-static int _getSocket(const ListenerOps *ops) {
- UdpListener *udp = (UdpListener *)ops->context;
- return (int)udp->udp_socket;
-}
-
-// =====================================================================
-
-/**
- * @function _constructAddressPair
- * @abstract Creates the address pair that uniquely identifies the connection
- * @discussion
- * The peerIpAddress must be of AF_INET or AF_INET6 family.
- *
- * @param <#param1#>
- * @return Allocated MetisAddressPair, must be destroyed
- */
-static AddressPair *_constructAddressPair(UdpListener *udp,
- struct sockaddr *peerIpAddress,
- socklen_t peerIpAddressLength) {
- Address *remoteAddress;
-
- switch (peerIpAddress->sa_family) {
- case AF_INET:
- remoteAddress =
- addressCreateFromInet((struct sockaddr_in *)peerIpAddress);
- break;
-
- case AF_INET6:
- remoteAddress =
- addressCreateFromInet6((struct sockaddr_in6 *)peerIpAddress);
- break;
-
- default:
- parcTrapIllegalValue(peerIpAddress,
- "Peer address unrecognized family for IP: %d",
- peerIpAddress->sa_family);
- }
-
- AddressPair *pair = addressPair_Create(udp->localAddress, remoteAddress);
- addressDestroy(&remoteAddress);
-
- return pair;
-}
-
-static const Connection * _lookupConnection(ListenerOps * listener,
- const AddressPair *pair) {
- UdpListener * udp = (UdpListener *)listener->context;
- ConnectionTable *connTable = forwarder_GetConnectionTable(udp->forwarder);
- return connectionTable_FindByAddressPair(connTable, pair);
-
-}
-
-/**
- * @function _createNewConnection
- * @abstract Creates a new Metis connection for the peer
- * @discussion
- * PRECONDITION: you know there's not an existing connection with the address
- * pair
- *
- * Creates a new connection and adds it to the connection table.
- *
- * @param <#param1#>
- * @return The connection id for the new connection
- */
-
-static unsigned _createNewConnection(ListenerOps * listener, int fd,
- const AddressPair *pair) {
- UdpListener * udp = (UdpListener *)listener->context;
-
- //check it the connection is local
- bool isLocal = false;
- const Address *localAddress = addressPair_GetLocal(pair);
- if(addressGetType(localAddress) == ADDR_INET){
- struct sockaddr_in tmpAddr;
- addressGetInet(localAddress, &tmpAddr);
- if(parcNetwork_IsSocketLocal((struct sockaddr *)&tmpAddr))
- isLocal = true;
- }else{
- struct sockaddr_in6 tmpAddr6;
- addressGetInet6(localAddress, &tmpAddr6);
- if(parcNetwork_IsSocketLocal((struct sockaddr *)&tmpAddr6))
- isLocal = true;
- }
-
- // metisUdpConnection_Create takes ownership of the pair
- IoOperations *ops = udpConnection_Create(udp->forwarder, udp->interfaceName, fd, pair, isLocal);
- Connection *conn = connection_Create(ops);
- // connection_AllowWldrAutoStart(conn);
-
- connectionTable_Add(forwarder_GetConnectionTable(udp->forwarder), conn);
- unsigned connid = ioOperations_GetConnectionId(ops);
-
- return connid;
-}
-
-static void _handleWldrNotification(UdpListener *udp, unsigned connId,
- uint8_t *msgBuffer) {
- const Connection *conn = connectionTable_FindById(
- forwarder_GetConnectionTable(udp->forwarder), connId);
- if (conn == NULL) {
- parcMemory_Deallocate((void **)&msgBuffer);
- return;
- }
-
- Message *message = message_CreateFromByteArray(
- connId, msgBuffer, MessagePacketType_WldrNotification,
- forwarder_GetTicks(udp->forwarder), forwarder_GetLogger(udp->forwarder));
-
- connection_HandleWldrNotification((Connection *)conn, message);
-
- message_Release(&message);
-}
-
-static Message *_readMessage(ListenerOps * listener, int fd,
- AddressPair *pair, uint8_t * packet, bool * processed) {
- UdpListener * udp = (UdpListener *)listener->context;
-
- Message *message = NULL;
-
- unsigned connid;
- bool foundConnection;
-
- const Connection *conn = _lookupConnection(listener, pair);
- if (conn) {
- connid = connection_GetConnectionId(conn);
- foundConnection = true;
- } else {
- connid = 0;
- foundConnection = false;
- }
-
- if (messageHandler_IsTCP(packet)) {
- *processed = true;
- MessagePacketType pktType;
-
- if (messageHandler_IsData(packet)) {
- pktType = MessagePacketType_ContentObject;
- if (!foundConnection) {
- parcMemory_Deallocate((void **)&packet);
- return message;
- }
- } else if (messageHandler_IsInterest(packet)) {
- pktType = MessagePacketType_Interest;
- if (!foundConnection) {
- connid = _createNewConnection(listener, fd, pair);
- }
- } else {
- printf("Got a packet that is not a data nor an interest, drop it!\n");
- parcMemory_Deallocate((void **)&packet);
- return message;
- }
-
- message = message_CreateFromByteArray(
- connid, packet, pktType, forwarder_GetTicks(udp->forwarder),
- forwarder_GetLogger(udp->forwarder));
-
- if (message == NULL) {
- parcMemory_Deallocate((void **)&packet);
- }
- } else if (messageHandler_IsWldrNotification(packet)) {
- *processed = true;
- _handleWldrNotification(udp, connid, packet);
- } else {
-
- *processed = messageHandler_handleHooks(udp->forwarder, packet, listener, fd, pair);
- }
-
- return message;
-}
-
-static void _readCommand(ListenerOps * listener, int fd,
- AddressPair *pair, uint8_t * command) {
- UdpListener * udp = (UdpListener *)listener->context;
-
- if (*command != REQUEST_LIGHT){
- printf("the message received is not a command, drop\n");
- parcMemory_Deallocate((void **) &command);
- return;
- }
-
- command_id id = *(command + 1);
-
- if (id >= LAST_COMMAND_VALUE){
- printf("the message received is not a valid command, drop\n");
- parcMemory_Deallocate((void **) &command);
- return;
- }
-
- unsigned connid;
-
- const Connection *conn = _lookupConnection(listener, pair);
- if (conn) {
- connid = connection_GetConnectionId(conn);
- } else {
- connid = _createNewConnection(listener, fd, pair);
- }
-
- struct iovec *request;
- if (!(request = (struct iovec *) parcMemory_AllocateAndClear(
- sizeof(struct iovec) * 2))) {
- return;
- }
-
- request[0].iov_base = command;
- request[0].iov_len = sizeof(header_control_message);
- request[1].iov_base = command + sizeof(header_control_message);
- request[1].iov_len = payloadLengthDaemon(id);
-
- forwarder_ReceiveCommand(udp->forwarder, id, request, connid);
- parcMemory_Deallocate((void **) &command);
- //parcMemory_Deallocate((void **) &request);
-}
-
-
-static bool _receivePacket(ListenerOps * listener, int fd,
- AddressPair *pair,
- uint8_t * packet) {
- UdpListener * udp = (UdpListener *)listener->context;
- bool processed = false;
- Message *message = _readMessage(listener, fd, pair,
- packet, &processed);
- if (message) {
- forwarder_Receive(udp->forwarder, message);
- }
- return processed;
-}
-
-static void _readcb(int fd, PARCEventType what, void * listener_void) {
- ListenerOps * listener = (ListenerOps *)listener_void;
- UdpListener * udp = (UdpListener *)listener->context;
-
- if (logger_IsLoggable(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- logger_Log(udp->logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "%s socket %d what %s%s%s%s data %p", __func__, fd,
- (what & PARCEventType_Timeout) ? " timeout" : "",
- (what & PARCEventType_Read) ? " read" : "",
- (what & PARCEventType_Write) ? " write" : "",
- (what & PARCEventType_Signal) ? " signal" : "", udp);
- }
-
- if (what & PARCEventType_Read) {
- struct sockaddr_storage peerIpAddress;
- socklen_t peerIpAddressLength = sizeof(peerIpAddress);
-
- //packet it deallocated by _receivePacket or _readCommand
- uint8_t * packet = parcMemory_AllocateAndClear(1500); //max MTU
- ssize_t readLength = recvfrom(fd, packet, 1500, 0,
- (struct sockaddr *)&peerIpAddress, &peerIpAddressLength);
-
-#ifdef __APPLE__
- peerIpAddress.ss_len = 0x00;
-#endif
-
- if(readLength < 0) {
- printf("unable to read the message\n");
- parcMemory_Deallocate(packet);
- return;
- }
-
- AddressPair *pair = _constructAddressPair(
- udp, (struct sockaddr *)&peerIpAddress, peerIpAddressLength);
-
- bool done = _receivePacket(listener, fd, pair, packet);
- if(!done){
- _readCommand(listener, fd, pair, packet);
- }
-
- addressPair_Release(&pair);
- }
-}
diff --git a/hicn-light/src/hicn/io/udpListener.h b/hicn-light/src/hicn/io/udpListener.h
deleted file mode 100644
index 62c09e4db..000000000
--- a/hicn-light/src/hicn/io/udpListener.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.
- */
-
-#ifndef udpListener_h
-#define udpListener_h
-
-#ifndef _WIN32
-#include <netinet/in.h>
-#endif
-
-#include <hicn/core/forwarder.h>
-#include <hicn/io/listener.h>
-#include <stdlib.h>
-
-struct udp_listener;
-typedef struct udp_listener UdpListener;
-
-ListenerOps *udpListener_CreateInet6(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in6 sin6, const char *if_bind);
-ListenerOps *udpListener_CreateInet(Forwarder *forwarder, char *listenerName,
- struct sockaddr_in sin, const char *if_bind);
-// void udpListener_SetPacketType(ListenerOps *ops, MessagePacketType type);
-#endif // udpListener_h
diff --git a/hicn-light/src/hicn/io/udpTunnel.c b/hicn-light/src/hicn/io/udpTunnel.c
deleted file mode 100644
index 9f5249e3c..000000000
--- a/hicn-light/src/hicn/io/udpTunnel.c
+++ /dev/null
@@ -1,105 +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 <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <parc/algol/parc_Network.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/io/udpConnection.h>
-#include <hicn/io/udpListener.h>
-#include <hicn/io/udpTunnel.h>
-
-IoOperations *udpTunnel_CreateOnListener(Forwarder *forwarder,
- ListenerOps *localListener,
- const Address *remoteAddress) {
- parcAssertNotNull(forwarder, "Parameter metis must be non-null");
- parcAssertNotNull(localListener, "Parameter localListener must be non-null");
- parcAssertNotNull(remoteAddress, "Parameter remoteAddress must be non-null");
-
- Logger *logger = forwarder_GetLogger(forwarder);
-
- IoOperations *ops = NULL;
- if (localListener->getEncapType(localListener) == ENCAP_UDP) {
- const Address *localAddress =
- localListener->getListenAddress(localListener);
- address_type localType = addressGetType(localAddress);
- address_type remoteType = addressGetType(remoteAddress);
-
- if (localType == remoteType) {
- AddressPair *pair = addressPair_Create(localAddress, remoteAddress);
-
- //check it the connection is local
- bool isLocal = false;
- if(localType == ADDR_INET){
- struct sockaddr_in tmpAddr;
- addressGetInet(localAddress, &tmpAddr);
- if(parcNetwork_IsSocketLocal((struct sockaddr *)&tmpAddr))
- isLocal = true;
- }else{
- struct sockaddr_in6 tmpAddr6;
- addressGetInet6(localAddress, &tmpAddr6);
- if(parcNetwork_IsSocketLocal((struct sockaddr *)&tmpAddr6))
- isLocal = true;
- }
- int fd = localListener->getSocket(localListener);
- // udpListener_SetPacketType(localListener,
- // MessagePacketType_ContentObject);
- ops = udpConnection_Create(forwarder, localListener->getInterfaceName(localListener), fd, pair, isLocal);
-
- addressPair_Release(&pair);
- } else {
- if (logger_IsLoggable(logger, LoggerFacility_IO, PARCLogLevel_Error)) {
- logger_Log(logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Local listener of type %s and remote type %s, cannot "
- "establish tunnel",
- addressTypeToString(localType),
- addressTypeToString(remoteType));
- }
- }
- } else {
- if (logger_IsLoggable(logger, LoggerFacility_IO, PARCLogLevel_Error)) {
- logger_Log(logger, LoggerFacility_IO, PARCLogLevel_Error, __func__,
- "Local listener %p is not type UDP, cannot establish tunnel",
- (void *)localListener);
- }
- }
-
- return ops;
-}
-
-IoOperations *udpTunnel_Create(Forwarder *forwarder,
- const Address *localAddress,
- const Address *remoteAddress) {
- ListenerSet *set = forwarder_GetListenerSet(forwarder);
- ListenerOps *listener = listenerSet_Find(set, ENCAP_UDP, localAddress);
- IoOperations *ops = NULL;
- if (listener) {
- ops = udpTunnel_CreateOnListener(forwarder, listener, remoteAddress);
- } else {
- if (logger_IsLoggable(forwarder_GetLogger(forwarder), LoggerFacility_IO,
- PARCLogLevel_Error)) {
- char *str = addressToString(localAddress);
- logger_Log(forwarder_GetLogger(forwarder), LoggerFacility_IO,
- PARCLogLevel_Error, __func__,
- "Could not find listener to match address %s", str);
- parcMemory_Deallocate((void **)&str);
- }
- }
- return ops;
-}
diff --git a/hicn-light/src/hicn/io/udpTunnel.h b/hicn-light/src/hicn/io/udpTunnel.h
deleted file mode 100644
index dacfdbb01..000000000
--- a/hicn-light/src/hicn/io/udpTunnel.h
+++ /dev/null
@@ -1,42 +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.
- */
-
-/**
- * @file udpTunnel.h
- * @brief Establish a tunnel to a remote system
- *
- */
-
-#ifndef udpTunnel_h
-#define udpTunnel_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/io/ioOperations.h>
-#include <hicn/io/listener.h>
-#include <hicn/utils/address.h>
-
-/**
- */
-IoOperations *udpTunnel_CreateOnListener(Forwarder *forwarder,
- ListenerOps *localListener,
- const Address *remoteAddress);
-
-/**
- */
-IoOperations *udpTunnel_Create(Forwarder *forwarder,
- const Address *localAddress,
- const Address *remoteAddress);
-
-#endif // udpTunnel_h
diff --git a/hicn-light/src/hicn/messenger/CMakeLists.txt b/hicn-light/src/hicn/messenger/CMakeLists.txt
deleted file mode 100644
index 69a6c32d1..000000000
--- a/hicn-light/src/hicn/messenger/CMakeLists.txt
+++ /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.
-
-list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/missiveDeque.h
- ${CMAKE_CURRENT_SOURCE_DIR}/missive.h
- ${CMAKE_CURRENT_SOURCE_DIR}/missiveType.h
- ${CMAKE_CURRENT_SOURCE_DIR}/messenger.h
- ${CMAKE_CURRENT_SOURCE_DIR}/messengerRecipient.h
-)
-
-list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/messenger.c
- ${CMAKE_CURRENT_SOURCE_DIR}/messengerRecipient.c
- ${CMAKE_CURRENT_SOURCE_DIR}/missive.c
- ${CMAKE_CURRENT_SOURCE_DIR}/missiveDeque.c
-)
-
-set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
-set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE) \ No newline at end of file
diff --git a/hicn-light/src/hicn/messenger/messenger.c b/hicn-light/src/hicn/messenger/messenger.c
deleted file mode 100644
index 45437539d..000000000
--- a/hicn-light/src/hicn/messenger/messenger.c
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- *
- * The messenger is contructued with a reference to the forwarder's dispatcher
- * so it can schedule future events. When someone calls messenger_Send(...), it
- * will put the message on a queue. If the queue was empty, it will scheudle
- * itself to be run. By running the queue in a future dispatcher slice, it
- * guarantees that there will be no re-entrant behavior between callers and
- * message listeners.
- *
- * A recipient will receive a reference counted copy of the missive, so it must
- * call
- * {@link missive_Release} on it.
- *
- */
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Event.h>
-#include <parc/algol/parc_EventScheduler.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/messenger/messenger.h>
-#include <hicn/messenger/missiveDeque.h>
-
-struct messenger {
- PARCArrayList *callbacklist;
- Dispatcher *dispatcher;
- MissiveDeque *eventQueue;
-
- PARCEventTimer *timerEvent;
-};
-
-static void messenger_Dequeue(int fd, PARCEventType which_event,
- void *messengerVoidPtr);
-
-// =========================================
-// Public API
-
-Messenger *messenger_Create(Dispatcher *dispatcher) {
- Messenger *messenger = parcMemory_AllocateAndClear(sizeof(Messenger));
- parcAssertNotNull(messenger, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Messenger));
-
- // NULL destroyer because we're storing structures owned by the caller
- messenger->dispatcher = dispatcher;
- messenger->callbacklist = parcArrayList_Create(NULL);
- messenger->eventQueue = missiveDeque_Create();
-
- // creates the timer, but does not start it
- messenger->timerEvent =
- dispatcher_CreateTimer(dispatcher, false, messenger_Dequeue, messenger);
-
- return messenger;
-}
-
-void messenger_Destroy(Messenger **messengerPtr) {
- parcAssertNotNull(messengerPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*messengerPtr,
- "Parameter must dereference to non-null pointer");
-
- Messenger *messenger = *messengerPtr;
- parcArrayList_Destroy(&messenger->callbacklist);
- missiveDeque_Release(&messenger->eventQueue);
- dispatcher_DestroyTimerEvent(messenger->dispatcher, &messenger->timerEvent);
- parcMemory_Deallocate((void **)&messenger);
- *messengerPtr = NULL;
-}
-
-void messenger_Send(Messenger *messenger, Missive *missive) {
- parcAssertNotNull(messenger, "Parameter messenger must be non-null");
- parcAssertNotNull(missive, "Parameter event must be non-null");
-
- missiveDeque_Append(messenger->eventQueue, missive);
- if (missiveDeque_Size(messenger->eventQueue) == 1) {
- // We need to scheudle ourself when an event is added to an empty queue
-
- // precondition: timer should not be running.
- struct timeval immediateTimeout = {0, 0};
- dispatcher_StartTimer(messenger->dispatcher, messenger->timerEvent,
- &immediateTimeout);
- }
-}
-
-static void removeRecipient(Messenger *messenger,
- const MessengerRecipient *recipient) {
- // don't increment i in the loop
- for (size_t i = 0; i < parcArrayList_Size(messenger->callbacklist);) {
- const void *p = parcArrayList_Get(messenger->callbacklist, i);
- if (p == recipient) {
- // removing will compact the list, so next element will also be at i.
- parcArrayList_RemoveAndDestroyAtIndex(messenger->callbacklist, i);
- } else {
- i++;
- }
- }
-}
-
-/**
- * @function eventMessenger_Register
- * @abstract Receive all event messages
- */
-void messenger_Register(Messenger *messenger,
- const MessengerRecipient *recipient) {
- parcAssertNotNull(messenger, "Parameter messenger must be non-null");
- parcAssertNotNull(recipient, "Parameter recipient must be non-null");
-
- // do not allow duplicates
- removeRecipient(messenger, recipient);
-
- parcArrayList_Add(messenger->callbacklist, recipient);
-}
-
-/**
- * @function eventMessenger_Unregister
- * @abstract Stop receiving event messages
- */
-void messenger_Unregister(Messenger *messenger,
- const MessengerRecipient *recipient) {
- parcAssertNotNull(messenger, "Parameter messenger must be non-null");
- parcAssertNotNull(recipient, "Parameter recipient must be non-null");
-
- removeRecipient(messenger, recipient);
-}
-
-/**
- * Called by event scheduler to give us a slice in which to dequeue events
- *
- * Called inside an event callback, so we now have exclusive access to the
- * system. Dequeues all pending events and calls all the listeners for each one.
- *
- * @param [in] fd unused, required for compliance with function prototype
- * @param [in] which_event unused, required for compliance with function
- * prototype
- * @param [in] messengerVoidPtr A void* to Messenger
- */
-static void messenger_Dequeue(int fd, PARCEventType which_event,
- void *messengerVoidPtr) {
- Messenger *messenger = (Messenger *)messengerVoidPtr;
- parcAssertNotNull(messenger, "Called with null messenger pointer");
-
- Missive *missive;
- while ((missive = missiveDeque_RemoveFirst(messenger->eventQueue)) != NULL) {
- for (size_t i = 0; i < parcArrayList_Size(messenger->callbacklist); i++) {
- MessengerRecipient *recipient =
- parcArrayList_Get(messenger->callbacklist, i);
- parcAssertTrue(recipient, "Recipient is null at index %zu", i);
-
- messengerRecipient_Deliver(recipient, missive_Acquire(missive));
- }
-
- // now let go of our reference to the missive
- missive_Release(&missive);
- }
-}
diff --git a/hicn-light/src/hicn/messenger/messenger.h b/hicn-light/src/hicn/messenger/messenger.h
deleted file mode 100644
index 79d65cda6..000000000
--- a/hicn-light/src/hicn/messenger/messenger.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.
- */
-
-/**
- * The EventMessenger is the system that messages events between
- * producers and consumers.
- *
- * Events are delivered in a deferred event cycle to avoid event callbacks
- * firing when the event generator is still running.
- */
-
-#ifndef messenger_h
-#define messenger_h
-
-#include <hicn/core/dispatcher.h>
-#include <hicn/messenger/messengerRecipient.h>
-#include <hicn/messenger/missive.h>
-
-struct messenger;
-typedef struct messenger Messenger;
-
-/**
- * @function eventmessenger_Create
- * @abstract Creates an event notification system
- * @discussion
- * Typically there's only one of these managed by forwarder.
- *
- * @param dispatcher is the event dispatcher to use to schedule events.
- */
-Messenger *messenger_Create(Dispatcher *dispatcher);
-
-/**
- * @function eventMessenger_Destroy
- * @abstract Destroys the messenger system, no notification is sent
- */
-void messenger_Destroy(Messenger **messengerPtr);
-
-/**
- * @function eventMessenger_Send
- * @abstract Send an event message, takes ownership of the event memory
- */
-void messenger_Send(Messenger *messenger, Missive *missive);
-
-/**
- * @function eventMessenger_Register
- * @abstract Receive all event messages
- */
-void messenger_Register(Messenger *messenger,
- const MessengerRecipient *recipient);
-
-/**
- * @function eventMessenger_Unregister
- * @abstract Stop receiving event messages
- */
-void messenger_Unregister(Messenger *messenger,
- const MessengerRecipient *recipient);
-#endif // messenger_h
diff --git a/hicn-light/src/hicn/messenger/messengerRecipient.c b/hicn-light/src/hicn/messenger/messengerRecipient.c
deleted file mode 100644
index 17407030a..000000000
--- a/hicn-light/src/hicn/messenger/messengerRecipient.c
+++ /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.
- */
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/messenger/messenger.h>
-#include <hicn/messenger/messengerRecipient.h>
-
-struct messenger_recipient {
- void *context;
- MessengerRecipientCallback *notify;
-};
-
-MessengerRecipient *messengerRecipient_Create(
- void *recipientContext, MessengerRecipientCallback *recipientCallback) {
- parcAssertNotNull(recipientCallback,
- "Parameter recipientCallback must be non-null");
-
- MessengerRecipient *recipient =
- parcMemory_AllocateAndClear(sizeof(MessengerRecipient));
- parcAssertNotNull(recipient, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(MessengerRecipient));
- recipient->context = recipientContext;
- recipient->notify = recipientCallback;
- return recipient;
-}
-
-void messengerRecipient_Destroy(MessengerRecipient **recipientPtr) {
- parcAssertNotNull(recipientPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*recipientPtr,
- "Parameter must dereference to non-null pointer");
-
- parcMemory_Deallocate((void **)recipientPtr);
- *recipientPtr = NULL;
-}
-
-void *messengerRecipient_GetRecipientContext(MessengerRecipient *recipient) {
- parcAssertNotNull(recipient, "Parameter must be non-null");
-
- return recipient->context;
-}
-
-void messengerRecipient_Deliver(MessengerRecipient *recipient,
- Missive *missive) {
- parcAssertNotNull(recipient, "Parameter must be non-null");
- recipient->notify(recipient, missive);
-}
diff --git a/hicn-light/src/hicn/messenger/messengerRecipient.h b/hicn-light/src/hicn/messenger/messengerRecipient.h
deleted file mode 100644
index cb5705b3a..000000000
--- a/hicn-light/src/hicn/messenger/messengerRecipient.h
+++ /dev/null
@@ -1,104 +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.
- */
-
-/**
- * @file messengerRecipient.h
- * @brief A recipient represents the entity that will recieve a Missive from the
- * Messenger.
- *
- * A recipient is identified by the pair (contenxt, callback). The context is
- * the recipients context, such as it's object pointer. The callback is the
- * function the recipient uses to receive a Missive.
- *
- * If the receiver is going to do a lot of work or potentially send other
- * missives, the receiver should queue the received notifications and process
- * them in its own slice.
- *
- * A recipient will receive a reference counted copy of the missive, so it must
- * call
- * {@link missive_Release} on it.
- *
- *
- */
-
-#ifndef messengerRecipient_h
-#define messengerRecipient_h
-
-#include <hicn/messenger/missive.h>
-
-struct messenger_recipient;
-typedef struct messenger_recipient MessengerRecipient;
-
-/**
- * @typedef MessengerRecipientCallback
- * @abstract A recipient implements a callback to receive Missives.
- * @constant recipient The recipient to recieve the missive
- * @constant missive The missive, recipient must call {@link missive_Release} on
- * it
- */
-typedef void(MessengerRecipientCallback)(MessengerRecipient *recipient,
- Missive *missive);
-
-/**
- * Creates a Recipient, which represents a reciever of missives.
- *
- * Creates a Recipient that can be registerd with the Messenger using {@link
- * messenger_Register}.
- *
- * @param [in] recipientContext This pointer will be passed back to the
- * recipient with each missive, may be NULL
- * @param [in] recipientCallback The function that receives the missive, must be
- * non-NULL.
- *
- * @return non-null A recipient object
- */
-MessengerRecipient *messengerRecipient_Create(
- void *recipientContext, MessengerRecipientCallback *recipientCallback);
-
-/**
- * Destroys a recipient. You should unregister it first.
- *
- * Destroying a recipient does not unregister it, so be sure to call
- * {@link messenger_Unregister} first.
- *
- * @param [in,out] recipientPtr Double pointer to the recipient to destroy, will
- * be NULL'd.
- */
-void messengerRecipient_Destroy(MessengerRecipient **recipientPtr);
-
-/**
- * Returns the recipient context passed on Create
- *
- * @param [in] recipient The recipient object
- *
- * @return pointer The context pointer used to create the object, maybe NULL
- */
-void *messengerRecipient_GetRecipientContext(MessengerRecipient *recipient);
-
-/**
- * Delivers a Missive to the recipient
- *
- * Passes the missive to the recipients callback.
- *
- * A recipient will receive a reference counted copy of the missive, so it must
- * call
- * {@link missive_Release} on it.
- *
- * @param [in] recipient The receiver
- * @param [in] missive The message to send
- */
-void messengerRecipient_Deliver(MessengerRecipient *recipient,
- Missive *missive);
-#endif // messengerRecipient_h
diff --git a/hicn-light/src/hicn/messenger/missive.c b/hicn-light/src/hicn/messenger/missive.c
deleted file mode 100644
index 5162e683d..000000000
--- a/hicn-light/src/hicn/messenger/missive.c
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/messenger/missive.h>
-
-struct missive {
- MissiveType missiveType;
- unsigned connectionid;
-};
-
-parcObject_Override(Missive, PARCObject, .isLockable = false);
-
-Missive *missive_Create(MissiveType missiveType, unsigned connectionid) {
- Missive *missive = parcObject_CreateInstance(Missive);
- missive->missiveType = missiveType;
- missive->connectionid = connectionid;
- return missive;
-}
-
-Missive *missive_Acquire(const Missive *missive) {
- return parcObject_Acquire(missive);
-}
-
-void missive_Release(Missive **missivePtr) {
- parcObject_Release((void **)missivePtr);
-}
-
-MissiveType missive_GetType(const Missive *missive) {
- parcAssertNotNull(missive, "Parameter missive must be non-null");
- return missive->missiveType;
-}
-
-unsigned missive_GetConnectionId(const Missive *missive) {
- parcAssertNotNull(missive, "Parameter missive must be non-null");
- return missive->connectionid;
-}
diff --git a/hicn-light/src/hicn/messenger/missive.h b/hicn-light/src/hicn/messenger/missive.h
deleted file mode 100644
index fdeddce83..000000000
--- a/hicn-light/src/hicn/messenger/missive.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.
- */
-
-/**
- * @file missive.h
- * @brief A Missive is a status message sent over a broadcast channel inside
- * hicn-light
- *
- * Recipients use {@link messenger_Register} to receive missives. They are
- * broadcast to all recipients.
- *
- */
-#ifndef missive_h
-#define missive_h
-
-#include <hicn/messenger/missiveType.h>
-
-struct missive;
-typedef struct missive Missive;
-
-/**
- * Creates a Missive and sets the reference count to 1
- *
- * A Missive may be sent to listeners of the Messenger to inform them of events
- * on a connection id.
- *
- * @param [in] MissiveType The event type
- * @param [in] connectionid The relevant conneciton id
- *
- * @return non-null A message
- * @retrun null An error
- */
-Missive *missive_Create(MissiveType missiveType, unsigned connectionid);
-
-/**
- * Acquire a reference counted copy
- *
- * Increases the reference count by 1 and returns the original object.
- *
- * @param [in] missive An allocated missive
- *
- * @return non-null The original missive with increased reference count
- */
-Missive *missive_Acquire(const Missive *missive);
-
-/**
- * Releases a reference counted copy.
- *
- * If it is the last reference, the missive is freed.
- *
- * @param [in,out] missivePtr Double pointer to a missive, will be nulled.
- */
-void missive_Release(Missive **missivePtr);
-
-/**
- * Returns the type of the missive
- *
- * Returns the type of event the missive represents
- *
- * @param [in] missive An allocated missive
- *
- * @return MissiveType The event type
- */
-MissiveType missive_GetType(const Missive *missive);
-
-/**
- * Returns the connection ID of the missive
- *
- * An event is usually associated with a connection id (i.e. the I/O channel
- * that originaged the event).
- *
- * @param [in] missive An allocated missive
- *
- * @return number The relevant connection id.
- */
-unsigned missive_GetConnectionId(const Missive *missive);
-#endif // missive_h
diff --git a/hicn-light/src/hicn/messenger/missiveDeque.c b/hicn-light/src/hicn/messenger/missiveDeque.c
deleted file mode 100644
index ab94a4f18..000000000
--- a/hicn-light/src/hicn/messenger/missiveDeque.c
+++ /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.
- */
-
-/**
- * A type-safe wrapper for Missives around a {@link PARCDeque}. We only
- * implement the subset of functions used.
- *
- */
-
-#include <parc/algol/parc_Deque.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/messenger/missive.h>
-#include <hicn/messenger/missiveDeque.h>
-
-struct missive_deque {
- PARCDeque *queue;
-};
-
-MissiveDeque *missiveDeque_Create(void) {
- MissiveDeque *missiveDeque =
- parcMemory_AllocateAndClear(sizeof(MissiveDeque));
- parcAssertNotNull(missiveDeque,
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(MissiveDeque));
- missiveDeque->queue = parcDeque_Create();
- return missiveDeque;
-}
-
-void missiveDeque_Release(MissiveDeque **dequePtr) {
- parcAssertNotNull(dequePtr, "Double pointer must be non-null");
- parcAssertNotNull(*dequePtr, "Double pointer must dereference to non-null");
- MissiveDeque *missiveDeque = *dequePtr;
-
- // flush the queue
- while (!parcDeque_IsEmpty(missiveDeque->queue)) {
- Missive *missive = missiveDeque_RemoveFirst(missiveDeque);
- missive_Release(&missive);
- }
-
- parcDeque_Release(&missiveDeque->queue);
- parcMemory_Deallocate((void **)&missiveDeque);
- *dequePtr = NULL;
-}
-
-MissiveDeque *missiveDeque_Append(MissiveDeque *deque, Missive *missive) {
- parcAssertNotNull(deque, "Parameter deque must be non-null");
- parcAssertNotNull(missive, "Parameter missive must be non-null");
-
- parcDeque_Append(deque->queue, missive);
- return deque;
-}
-
-Missive *missiveDeque_RemoveFirst(MissiveDeque *deque) {
- parcAssertNotNull(deque, "Parameter deque must be non-null");
- return (Missive *)parcDeque_RemoveFirst(deque->queue);
-}
-
-size_t missiveDeque_Size(const MissiveDeque *deque) {
- parcAssertNotNull(deque, "Parameter deque must be non-null");
- return parcDeque_Size(deque->queue);
-}
diff --git a/hicn-light/src/hicn/messenger/missiveDeque.h b/hicn-light/src/hicn/messenger/missiveDeque.h
deleted file mode 100644
index c6f955ce0..000000000
--- a/hicn-light/src/hicn/messenger/missiveDeque.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.
- */
-
-/**
- * @file missiveDeque
- * @brief Double ended queue of Missives
- *
- * Used to queue Missives. This is a type-safe wrapper around {@link PARCDeque}
- *
- */
-
-#ifndef missiveDeque_h
-#define missiveDeque_h
-
-struct missive_deque;
-
-typedef struct missive_deque MissiveDeque;
-
-/**
- * Create a `PARCDeque` instance with the default element equals function.
- *
- * The queue is created with no elements.
- *
- * The default element equals function is used by the `parcDeque_Equals`
- * function and simply compares the values using the `==` operator. Users that
- * need more sophisticated comparisons of the elements need to supply their own
- * function via the `parcDeque_CreateCustom` function.
- *
- * @return non-NULL A pointer to a PARCDeque instance.
- */
-MissiveDeque *missiveDeque_Create(void);
-
-void missiveDeque_Release(MissiveDeque **dequePtr);
-
-/**
- * Appends the missive to the queue, taking ownership of the memory
- */
-MissiveDeque *missiveDeque_Append(MissiveDeque *deque, Missive *missive);
-
-Missive *missiveDeque_RemoveFirst(MissiveDeque *deque);
-
-size_t missiveDeque_Size(const MissiveDeque *deque);
-#endif // missiveDeque_h
diff --git a/hicn-light/src/hicn/messenger/missiveType.h b/hicn-light/src/hicn/messenger/missiveType.h
deleted file mode 100644
index b0d9c7704..000000000
--- a/hicn-light/src/hicn/messenger/missiveType.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.
- */
-
-/**
- * @file missiveType
- * @brief Defines what a Missive represents
- *
- * Currently, missives only carry information about the state of a connection
- * (created, up, down, closed, destroyed).
- *
- */
-
-#ifndef missiveType_h
-#define missiveType_h
-
-/**
- * @typedef Represents the state of a connection
- * @abstract CREATE is the initial state. UP & DOWN are recurrent states.
- * CLOSED is transient. DESTROYED is the terminal state.
- * @constant MissiveType_ConnectionCreate Connection created (new)
- * @constant MissiveType_ConnectionUp Connection is active and passing
- * data
- * @constant MissiveType_ConnectionDown Connection is inactive and cannot
- * pass data
- * @constant MissiveType_ConnectionClosed Connection closed and will be
- * destroyed
- * @constant MissiveType_ConnectionDestroyed Connection destroyed
- * @discussion State transitions:
- * initial -> CREATE
- * CREATE -> (UP | DOWN)
- * UP -> (DOWN | DESTROYED)
- * DOWN -> (UP | CLOSED | DESTROYED)
- * CLOSED -> DESTROYED
- * DESTROYED -> terminal
- */
-typedef enum {
- MissiveType_ConnectionCreate,
- MissiveType_ConnectionUp,
- MissiveType_ConnectionDown,
- MissiveType_ConnectionClosed,
- MissiveType_ConnectionDestroyed
-} MissiveType;
-#endif // missiveType_h
diff --git a/hicn-light/src/hicn/platforms/CMakeLists.txt b/hicn-light/src/hicn/platforms/CMakeLists.txt
index 4073e0558..14237c976 100644
--- a/hicn-light/src/hicn/platforms/CMakeLists.txt
+++ b/hicn-light/src/hicn/platforms/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/hicn-light/src/hicn/platforms/README.txt b/hicn-light/src/hicn/platforms/README.txt
index a1293944c..18c63a5f9 100644
--- a/hicn-light/src/hicn/platforms/README.txt
+++ b/hicn-light/src/hicn/platforms/README.txt
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,4 +14,3 @@
*/
Operating system dependent modules.
-
diff --git a/hicn-light/src/hicn/platforms/android/system.c b/hicn-light/src/hicn/platforms/android/system.c
index ba91748a0..80ca864ea 100644
--- a/hicn-light/src/hicn/platforms/android/system.c
+++ b/hicn-light/src/hicn/platforms/android/system.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,6 +13,7 @@
* limitations under the License.
*/
+#if 0
#include <errno.h>
#include <hicn/hicn-light/config.h>
#include <stdio.h>
@@ -181,3 +182,4 @@ unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName) {
return mtu;
}
+#endif \ No newline at end of file
diff --git a/hicn-light/src/hicn/platforms/darwin/system.c b/hicn-light/src/hicn/platforms/darwin/system.c
index d817248a8..b80fa9b69 100644
--- a/hicn-light/src/hicn/platforms/darwin/system.c
+++ b/hicn-light/src/hicn/platforms/darwin/system.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,6 +13,8 @@
* limitations under the License.
*/
+#if 0
+
#include <errno.h>
#include <ifaddrs.h>
#include <hicn/hicn-light/config.h>
@@ -144,3 +146,5 @@ unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName) {
}
return mtu;
}
+
+#endif
diff --git a/hicn-light/src/hicn/platforms/linux/system.c b/hicn-light/src/hicn/platforms/linux/system.c
index 3bf23cf57..4c14271a7 100644
--- a/hicn-light/src/hicn/platforms/linux/system.c
+++ b/hicn-light/src/hicn/platforms/linux/system.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,6 +13,8 @@
* limitations under the License.
*/
+#if 0
+
#include <errno.h>
#include <ifaddrs.h>
#include <hicn/hicn-light/config.h>
@@ -37,8 +39,6 @@
#include <parc/assert/parc_Assert.h>
-#include <hicn/utils/addressList.h>
-
/**
* Returns the MTU for a named interface
*
@@ -66,11 +66,9 @@ static int getMtu(const char *ifname) {
return ifr.ifr_mtu;
}
-InterfaceSet *system_Interfaces(Forwarder *forwarder) {
+InterfaceSet *system_Interfaces(forwarder_t * forwarder) {
InterfaceSet *set = interfaceSetCreate();
- Logger *logger = forwarder_GetLogger(forwarder);
-
// this is the dynamically allocated head of the list
struct ifaddrs *ifaddr;
int failure = getifaddrs(&ifaddr);
@@ -93,60 +91,18 @@ InterfaceSet *system_Interfaces(Forwarder *forwarder) {
interfaceSetAdd(set, iface);
}
- int family = next->ifa_addr->sa_family;
- switch (family) {
- case AF_INET: {
- Address *address =
- addressCreateFromInet((struct sockaddr_in *)next->ifa_addr);
- interfaceAddAddress(iface, address);
- break;
- }
-
- case AF_INET6: {
- Address *address =
- addressCreateFromInet6((struct sockaddr_in6 *)next->ifa_addr);
- interfaceAddAddress(iface, address);
- break;
- }
-
- case AF_PACKET: {
- struct sockaddr_ll *addr_ll = (struct sockaddr_ll *)next->ifa_addr;
-
- if (logger_IsLoggable(logger, LoggerFacility_IO, PARCLogLevel_Debug)) {
- logger_Log(logger, LoggerFacility_IO, PARCLogLevel_Debug, __func__,
- "sockaddr_ll family %d proto %d ifindex %d hatype %d "
- "pkttype %d halen %d",
- addr_ll->sll_family, addr_ll->sll_protocol,
- addr_ll->sll_ifindex, addr_ll->sll_hatype,
- addr_ll->sll_pkttype, addr_ll->sll_halen);
- }
-
- switch (addr_ll->sll_hatype) {
- // list of the ARP hatypes we can extract a MAC address from
- case ARPHRD_ETHER:
- // fallthrough
- case ARPHRD_IEEE802: {
- Address *address = addressCreateFromLink(
- (uint8_t *)addr_ll->sll_addr, addr_ll->sll_halen);
- interfaceAddAddress(iface, address);
- break;
- }
- default:
- break;
- }
-
- break;
- }
- }
+ address_t * address = (address_t *)next->ifa_addr;
+ interfaceAddAddress(iface, address);
}
freeifaddrs(ifaddr);
return set;
}
-Address *system_GetMacAddressByName(Forwarder *forwarder,
+#if 0
+address_t *system_GetMacAddressByName(Forwarder *forwarder,
const char *interfaceName) {
- Address *linkAddress = NULL;
+ address_t *linkAddress = NULL;
InterfaceSet *interfaceSet = system_Interfaces(forwarder);
Interface *interface = interfaceSetGetByName(interfaceSet, interfaceName);
@@ -156,7 +112,7 @@ Address *system_GetMacAddressByName(Forwarder *forwarder,
size_t length = addressListLength(addressList);
for (size_t i = 0; i < length && !linkAddress; i++) {
- const Address *a = addressListGetItem(addressList, i);
+ const address_t *a = addressListGetItem(addressList, i);
if (addressGetType(a) == ADDR_LINK) {
linkAddress = addressCopy(a);
}
@@ -167,6 +123,7 @@ Address *system_GetMacAddressByName(Forwarder *forwarder,
return linkAddress;
}
+#endif
unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName) {
unsigned mtu = 0;
@@ -182,3 +139,5 @@ unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName) {
return mtu;
}
+
+#endif
diff --git a/hicn-light/src/hicn/platforms/windows/system.c b/hicn-light/src/hicn/platforms/windows/system.c
index 55d89f63a..6bd36a372 100644
--- a/hicn-light/src/hicn/platforms/windows/system.c
+++ b/hicn-light/src/hicn/platforms/windows/system.c
@@ -1,223 +1,223 @@
-/*
- * Copyright (c) 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 <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <sys/types.h>
-
-#include <errno.h>
-#include <string.h>
-
-#define WORKING_BUFFER_SIZE 15000
-#define MAX_TRIES 3
-
-#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
-#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
-
-#include <hicn/core/forwarder.h>
-#include <hicn/utils/interfaceSet.h>
-
-#include <hicn/utils/addressList.h>
-
-/**
- * Returns the MTU for a named interface
- *
- * On linux, we get the MTU by opening a socket and reading SIOCGIFMTU
- *
- * @param [in] ifname Interface name (e.g. "eth0")
- *
- * @retval number The MTU in bytes
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-static int getMtu(const char *ifname) {
- PIP_ADAPTER_ADDRESSES pAddresses = NULL;
- PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
- ULONG outBufLen = 0;
- ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
- ULONG family = AF_UNSPEC;
-
- DWORD dwSize = 0;
- DWORD dwRetVal = 0;
- ULONG Iterations = 0;
- do {
- pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
- if (pAddresses == NULL) {
- printf("Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n");
- exit(1);
- }
-
- dwRetVal =
- GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
-
- if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
- FREE(pAddresses);
- pAddresses = NULL;
- } else {
- break;
- }
-
- Iterations++;
-
- } while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));
-
- if (dwRetVal == NO_ERROR) {
- pCurrAddresses = pAddresses;
- while (pCurrAddresses) {
- if (strcmp(pCurrAddresses->AdapterName, ifname)) {
- int mtu = pCurrAddresses->Mtu;
- if (pAddresses) {
- FREE(pAddresses);
- }
- return mtu;
- }
- pCurrAddresses = pCurrAddresses->Next;
- }
- }
-
- if (pAddresses) {
- FREE(pAddresses);
- }
- return -1;
-}
-
-InterfaceSet *system_Interfaces(Forwarder *forwarder) {
- InterfaceSet *set = interfaceSetCreate();
-
- Logger *logger = forwarder_GetLogger(forwarder);
-
- DWORD dwSize = 0;
- DWORD dwRetVal = 0;
- unsigned int i = 0;
- // Set the flags to pass to GetAdaptersAddresses
- ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
-
- // default to unspecified address family (both)
- ULONG family = AF_UNSPEC;
-
- LPVOID lpMsgBuf = NULL;
-
- PIP_ADAPTER_ADDRESSES pAddresses = NULL;
- ULONG outBufLen = 0;
- ULONG Iterations = 0;
-
- PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
- PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
- PIP_ADAPTER_ANYCAST_ADDRESS pAnycast = NULL;
- PIP_ADAPTER_MULTICAST_ADDRESS pMulticast = NULL;
- IP_ADAPTER_DNS_SERVER_ADDRESS *pDnServer = NULL;
- IP_ADAPTER_PREFIX *pPrefix = NULL;
-
- outBufLen = WORKING_BUFFER_SIZE;
-
- do {
- pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
- parcAssertNotNull(
- pAddresses,
- "Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n");
- dwRetVal =
- GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
-
- if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
- FREE(pAddresses);
- pAddresses = NULL;
- } else {
- break;
- }
-
- Iterations++;
-
- } while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));
- if (dwRetVal == NO_ERROR) {
- // If successful, output some information from the data we received
- pCurrAddresses = pAddresses;
- while (pCurrAddresses) {
- if (pCurrAddresses->OperStatus == IfOperStatusUp) {
- Interface *iface =
- interfaceSetGetByName(set, pCurrAddresses->AdapterName);
- if (iface == NULL) {
- pMulticast = pCurrAddresses->FirstMulticastAddress;
- if (pMulticast) {
- for (i = 0; pMulticast != NULL; i++) pMulticast = pMulticast->Next;
- }
-
- iface = interfaceCreate(
- pCurrAddresses->AdapterName,
- forwarder_GetNextConnectionId(forwarder),
- pCurrAddresses->IfType == IF_TYPE_SOFTWARE_LOOPBACK, i > 0,
- pCurrAddresses->Mtu);
-
- interfaceSetAdd(set, iface);
- for (pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != NULL;
- pUnicast = pUnicast->Next) {
- int family = pUnicast->Address.lpSockaddr->sa_family;
-
- switch (family) {
- case AF_INET: {
- char *ip = inet_ntoa(
- ((struct sockaddr_in *)(pUnicast->Address.lpSockaddr))
- ->sin_addr);
- Address *address = addressCreateFromInet(
- (struct sockaddr_in *)(pUnicast->Address.lpSockaddr));
- interfaceAddAddress(iface, address);
- break;
- }
-
- case AF_INET6: {
- char str[INET6_ADDRSTRLEN];
- inet_ntop(
- AF_INET6,
- &((struct sockaddr_in6 *)(pUnicast->Address.lpSockaddr))
- ->sin6_addr,
- str, INET6_ADDRSTRLEN);
- Address *address = addressCreateFromInet6(
- (struct sockaddr_in6 *)(pUnicast->Address.lpSockaddr));
- interfaceAddAddress(iface, address);
- break;
- }
-
- default:
- break;
- }
- }
- }
- }
- pCurrAddresses = pCurrAddresses->Next;
- }
- }
-
- if (pAddresses) {
- FREE(pAddresses);
- }
- return set;
-}
-
-Address *system_GetMacAddressByName(Forwarder *forwarder,
- const char *interfaceName) {
- return NULL;
-}
-
-unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName) {
- unsigned mtu = 0;
-
- return mtu;
-}
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <parc/assert/parc_Assert.h>
+#include <hicn/hicn-light/config.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sys/types.h>
+
+#include <errno.h>
+#include <string.h>
+
+#define WORKING_BUFFER_SIZE 15000
+#define MAX_TRIES 3
+
+#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
+#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
+
+#include <hicn/core/forwarder.h>
+#include <hicn/utils/interfaceSet.h>
+
+#include <hicn/utils/addressList.h>
+
+/**
+ * Returns the MTU for a named interface
+ *
+ * On linux, we get the MTU by opening a socket and reading SIOCGIFMTU
+ *
+ * @param [in] ifname Interface name (e.g. "eth0")
+ *
+ * @retval number The MTU in bytes
+ *
+ * Example:
+ * @code
+ * <#example#>
+ * @endcode
+ */
+static int getMtu(const char *ifname) {
+ PIP_ADAPTER_ADDRESSES pAddresses = NULL;
+ PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
+ ULONG outBufLen = 0;
+ ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
+ ULONG family = AF_UNSPEC;
+
+ DWORD dwSize = 0;
+ DWORD dwRetVal = 0;
+ ULONG Iterations = 0;
+ do {
+ pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
+ if (pAddresses == NULL) {
+ printf("Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n");
+ exit(1);
+ }
+
+ dwRetVal =
+ GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
+
+ if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
+ FREE(pAddresses);
+ pAddresses = NULL;
+ } else {
+ break;
+ }
+
+ Iterations++;
+
+ } while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));
+
+ if (dwRetVal == NO_ERROR) {
+ pCurrAddresses = pAddresses;
+ while (pCurrAddresses) {
+ if (strcmp(pCurrAddresses->AdapterName, ifname)) {
+ int mtu = pCurrAddresses->Mtu;
+ if (pAddresses) {
+ FREE(pAddresses);
+ }
+ return mtu;
+ }
+ pCurrAddresses = pCurrAddresses->Next;
+ }
+ }
+
+ if (pAddresses) {
+ FREE(pAddresses);
+ }
+ return -1;
+}
+
+InterfaceSet *system_Interfaces(Forwarder *forwarder) {
+ InterfaceSet *set = interfaceSetCreate();
+
+ Logger *logger = forwarder_GetLogger(forwarder);
+
+ DWORD dwSize = 0;
+ DWORD dwRetVal = 0;
+ unsigned int i = 0;
+ // Set the flags to pass to GetAdaptersAddresses
+ ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
+
+ // default to unspecified address family (both)
+ ULONG family = AF_UNSPEC;
+
+ LPVOID lpMsgBuf = NULL;
+
+ PIP_ADAPTER_ADDRESSES pAddresses = NULL;
+ ULONG outBufLen = 0;
+ ULONG Iterations = 0;
+
+ PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
+ PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
+ PIP_ADAPTER_ANYCAST_ADDRESS pAnycast = NULL;
+ PIP_ADAPTER_MULTICAST_ADDRESS pMulticast = NULL;
+ IP_ADAPTER_DNS_SERVER_ADDRESS *pDnServer = NULL;
+ IP_ADAPTER_PREFIX *pPrefix = NULL;
+
+ outBufLen = WORKING_BUFFER_SIZE;
+
+ do {
+ pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
+ parcAssertNotNull(
+ pAddresses,
+ "Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n");
+ dwRetVal =
+ GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
+
+ if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
+ FREE(pAddresses);
+ pAddresses = NULL;
+ } else {
+ break;
+ }
+
+ Iterations++;
+
+ } while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));
+ if (dwRetVal == NO_ERROR) {
+ // If successful, output some information from the data we received
+ pCurrAddresses = pAddresses;
+ while (pCurrAddresses) {
+ if (pCurrAddresses->OperStatus == IfOperStatusUp) {
+ Interface *iface =
+ interfaceSetGetByName(set, pCurrAddresses->AdapterName);
+ if (iface == NULL) {
+ pMulticast = pCurrAddresses->FirstMulticastAddress;
+ if (pMulticast) {
+ for (i = 0; pMulticast != NULL; i++) pMulticast = pMulticast->Next;
+ }
+
+ iface = interfaceCreate(
+ pCurrAddresses->AdapterName,
+ forwarder_GetNextConnectionId(forwarder),
+ pCurrAddresses->IfType == IF_TYPE_SOFTWARE_LOOPBACK, i > 0,
+ pCurrAddresses->Mtu);
+
+ interfaceSetAdd(set, iface);
+ for (pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != NULL;
+ pUnicast = pUnicast->Next) {
+ int family = pUnicast->Address.lpSockaddr->sa_family;
+
+ switch (family) {
+ case AF_INET: {
+ char *ip = inet_ntoa(
+ ((struct sockaddr_in *)(pUnicast->Address.lpSockaddr))
+ ->sin_addr);
+ Address *address = addressCreateFromInet(
+ (struct sockaddr_in *)(pUnicast->Address.lpSockaddr));
+ interfaceAddAddress(iface, address);
+ break;
+ }
+
+ case AF_INET6: {
+ char str[INET6_ADDRSTRLEN];
+ inet_ntop(
+ AF_INET6,
+ &((struct sockaddr_in6 *)(pUnicast->Address.lpSockaddr))
+ ->sin6_addr,
+ str, INET6_ADDRSTRLEN);
+ Address *address = addressCreateFromInet6(
+ (struct sockaddr_in6 *)(pUnicast->Address.lpSockaddr));
+ interfaceAddAddress(iface, address);
+ break;
+ }
+
+ default:
+ break;
+ }
+ }
+ }
+ }
+ pCurrAddresses = pCurrAddresses->Next;
+ }
+ }
+
+ if (pAddresses) {
+ FREE(pAddresses);
+ }
+ return set;
+}
+
+Address *system_GetMacAddressByName(Forwarder *forwarder,
+ const char *interfaceName) {
+ return NULL;
+}
+
+unsigned system_InterfaceMtu(Forwarder *forwarder, const char *interfaceName) {
+ unsigned mtu = 0;
+
+ return mtu;
+}
diff --git a/hicn-light/src/hicn/platforms/windows/win_portability.c b/hicn-light/src/hicn/platforms/windows/win_portability.c
index 3138640dd..e063cec24 100644
--- a/hicn-light/src/hicn/platforms/windows/win_portability.c
+++ b/hicn-light/src/hicn/platforms/windows/win_portability.c
@@ -1,50 +1,54 @@
-/*
- * Copyright (c) 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/platforms/windows/win_portability.h>
-
-int getline(char **lineptr, size_t *n, FILE *stream) {
- static char line[256];
- char *ptr;
- unsigned int len;
-
- if (lineptr == NULL || n == NULL) {
- errno = EINVAL;
- return -1;
- }
-
- if (ferror(stream)) return -1;
-
- if (feof(stream)) return -1;
-
- fgets(line, 256, stream);
-
- ptr = strchr(line, '\n');
- if (ptr) *ptr = '\0';
-
- len = (unsigned int)strlen(line);
-
- if ((len + 1) < 256) {
- ptr = (char *)realloc(*lineptr, 256);
- if (ptr == NULL) return (-1);
- *lineptr = ptr;
- *n = 256;
- }
-
- strcpy(*lineptr, line);
- return (len);
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <hicn/platforms/windows/win_portability.h>
+#include <hicn/util/sstrncpy.h>
+
+int getline(char **lineptr, size_t *n, FILE *stream) {
+ static char line[256];
+ char *ptr;
+ unsigned int len;
+ int rc;
+
+ if (lineptr == NULL || n == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (ferror(stream)) return -1;
+
+ if (feof(stream)) return -1;
+
+ fgets(line, 256, stream);
+
+ ptr = strchr(line, '\n');
+ if (ptr) *ptr = '\0';
+
+ len = (unsigned int)strlen(line);
+
+ if ((len + 1) < 256) {
+ ptr = (char *)realloc(*lineptr, 256);
+ if (ptr == NULL) return (-1);
+ *lineptr = ptr;
+ *n = 256;
+ }
+
+ rc = strcpy_s(*lineptr, 256, line);
+ if (rc != EOK) return -1;
+
+ return (len);
} \ No newline at end of file
diff --git a/hicn-light/src/hicn/platforms/windows/win_portability.h b/hicn-light/src/hicn/platforms/windows/win_portability.h
index 5c25f4bb2..f42bf9d53 100644
--- a/hicn-light/src/hicn/platforms/windows/win_portability.h
+++ b/hicn-light/src/hicn/platforms/windows/win_portability.h
@@ -1,45 +1,45 @@
-/*
- * Copyright (c) 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 <parc/windows/parc_Utils.h>
-#include <afunix.h>
-#include <io.h>
-#include <iphlpapi.h>
-#include <process.h>
-#include <stdio.h>
-#pragma comment(lib, "IPHLPAPI.lib")
-
-#ifndef in_port_t
-#define in_port_t uint16_t
-#endif
-
-#ifndef in_addr_t
-#define in_addr_t uint32_t
-#endif
-
-#ifndef strncasecmp
-#define strncasecmp _strnicmp
-#endif
-
-#ifndef strcasecmp
-#define strcasecmp _stricmp
-#endif
-
-#define HAVE_STRUCT_TIMESPEC
-
-#ifndef getline
-int getline(char **lineptr, size_t *n, FILE *stream);
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <parc/windows/parc_Utils.h>
+#include <afunix.h>
+#include <io.h>
+#include <iphlpapi.h>
+#include <process.h>
+#include <stdio.h>
+#pragma comment(lib, "IPHLPAPI.lib")
+
+#ifndef in_port_t
+#define in_port_t uint16_t
+#endif
+
+#ifndef in_addr_t
+#define in_addr_t uint32_t
+#endif
+
+#ifndef strncasecmp
+#define strncasecmp _strnicmp
+#endif
+
+#ifndef strcasecmp
+#define strcasecmp _stricmp
+#endif
+
+#define HAVE_STRUCT_TIMESPEC
+
+#ifndef getline
+int getline(char **lineptr, size_t *n, FILE *stream);
#endif \ No newline at end of file
diff --git a/hicn-light/src/hicn/processor/CMakeLists.txt b/hicn-light/src/hicn/processor/CMakeLists.txt
deleted file mode 100644
index 17c3b1f88..000000000
--- a/hicn-light/src/hicn/processor/CMakeLists.txt
+++ /dev/null
@@ -1,38 +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.
-
-list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/fibEntry.h
- ${CMAKE_CURRENT_SOURCE_DIR}/fibEntryList.h
- ${CMAKE_CURRENT_SOURCE_DIR}/messageProcessor.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hashTableFunction.h
- ${CMAKE_CURRENT_SOURCE_DIR}/pit.h
- ${CMAKE_CURRENT_SOURCE_DIR}/fib.h
- ${CMAKE_CURRENT_SOURCE_DIR}/pitEntry.h
- ${CMAKE_CURRENT_SOURCE_DIR}/pitVerdict.h
- ${CMAKE_CURRENT_SOURCE_DIR}/pitStandard.h
-)
-
-list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hashTableFunction.c
- ${CMAKE_CURRENT_SOURCE_DIR}/fib.c
- ${CMAKE_CURRENT_SOURCE_DIR}/fibEntry.c
- ${CMAKE_CURRENT_SOURCE_DIR}/fibEntryList.c
- ${CMAKE_CURRENT_SOURCE_DIR}/messageProcessor.c
- ${CMAKE_CURRENT_SOURCE_DIR}/pit.c
- ${CMAKE_CURRENT_SOURCE_DIR}/pitEntry.c
- ${CMAKE_CURRENT_SOURCE_DIR}/pitStandard.c
-)
-
-set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
-set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
diff --git a/hicn-light/src/hicn/processor/fib.c b/hicn-light/src/hicn/processor/fib.c
deleted file mode 100644
index de0d1e2ef..000000000
--- a/hicn-light/src/hicn/processor/fib.c
+++ /dev/null
@@ -1,553 +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/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/core/forwarder.h>
-#include <hicn/processor/fib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-
-#include <parc/assert/parc_Assert.h>
-
-struct node;
-typedef struct node FibNode;
-
-struct node {
- FibNode *left;
- FibNode *right;
- FibEntry *entry;
- bool is_used;
-};
-
-struct fib {
- Forwarder *forwarder;
- FibNode *root;
- unsigned size;
-};
-
-// =====================================================
-// Public API
-
-FibNode *_createNode(FibNode *left, FibNode *right, FibEntry *entry,
- bool is_used) {
- FibNode *n = parcMemory_AllocateAndClear(sizeof(FibNode));
- parcAssertNotNull(n, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(FibNode));
-
- n->left = left;
- n->right = right;
- n->entry = entry;
- n->is_used = is_used;
-
- return n;
-}
-
-FIB *fib_Create(Forwarder *forwarder) {
- FIB *hicnFib = parcMemory_AllocateAndClear(sizeof(FIB));
- parcAssertNotNull(hicnFib, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(FIB));
-
- hicnFib->forwarder = forwarder;
- hicnFib->root = NULL;
- hicnFib->size = 0;
-
- return hicnFib;
-}
-
-void _destroyNode(FibNode *n) {
- fibEntry_Release(&n->entry);
- parcMemory_Deallocate((void **)&n);
- n = NULL;
-}
-
-void _destroyFib(FibNode *n) {
- if(n != NULL){
- _destroyFib(n->right);
- _destroyFib(n->left);
- _destroyNode(n);
- }
-}
-
-void fib_Destroy(FIB **fibPtr) {
- parcAssertNotNull(fibPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*fibPtr, "Parameter must dereference to non-null pointer");
-
- FIB *fib = *fibPtr;
- _destroyFib(fib->root);
-
- parcMemory_Deallocate((void **)&fib);
- *fibPtr = NULL;
-}
-
-void fib_Add(FIB *fib, FibEntry *entry) {
- parcAssertNotNull(fib, "Parameter must be non-null");
- parcAssertNotNull(entry, "Parameter must be non-null");
-
- NameBitvector *new_prefix = name_GetContentName(fibEntry_GetPrefix(entry));
- uint32_t new_prefix_len = nameBitvector_GetLength(new_prefix);
- FibNode * curr = fib->root;
- FibNode * last = NULL;
-
- NameBitvector *curr_name;
- uint32_t curr_prefix_len;
- uint32_t match_len;
-
- while(curr != NULL){
- curr_name = name_GetContentName(fibEntry_GetPrefix(curr->entry));
-
- match_len = nameBitvector_lpm(new_prefix, curr_name);
- curr_prefix_len = nameBitvector_GetLength(curr_name);
-
- if(curr_prefix_len != match_len || //the new entry does not match the curr
- curr_prefix_len >= new_prefix_len) //in this case we cannot procede anymore
- break;
-
- last = curr;
- bool bit;
- int res = nameBitvector_testBit(new_prefix, curr_prefix_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_add)");
- if(bit)
- curr = curr->right;
- else
- curr = curr->left;
- }
-
- //this is the root (empty trie) or an empty child
- if(curr == NULL){
- FibNode * new_node = _createNode(NULL, NULL, entry, true);
- if(last == NULL){
- fib->root = new_node;
- }else{
- uint32_t last_prefix_len = nameBitvector_GetLength(
- name_GetContentName(fibEntry_GetPrefix(last->entry)));
- bool bit;
- int res = nameBitvector_testBit(new_prefix, last_prefix_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_add)");
- if(bit)
- last->right = new_node;
- else
- last->left = new_node;
- }
- fib->size++;
- return;
- }
-
- //curr is not null
-
- //the node already exist
- //if is not in use we turn it on and we set the rigth fib entry
- if(curr_prefix_len == match_len && new_prefix_len == match_len){
- if(!curr->is_used){
- curr->is_used = true;
- curr->entry = entry;
- fib->size++;
- return;
- }else{
- //this case should never happen beacuse of the way we add
- //entries in the fib
- const NumberSet * next_hops = fibEntry_GetNexthops(entry);
- unsigned size = (unsigned)fibEntry_NexthopCount(entry);
- for(unsigned i = 0; i < size; i++)
- fibEntry_AddNexthop(curr->entry,numberSet_GetItem(next_hops, i));
- }
- }
-
- //key is prefix of the curr node (so new_prefix_len < curr_prefix_len)
- if(new_prefix_len == match_len){
- FibNode * new_node = _createNode(NULL, NULL, entry, true);
- if(last == NULL){
- fib->root = new_node;
- }else{
- uint32_t last_prefix_len = nameBitvector_GetLength(
- name_GetContentName(fibEntry_GetPrefix(last->entry)));
-
- bool bit;
- int res = nameBitvector_testBit(new_prefix, last_prefix_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_add)");
- if(bit)
- last->right = new_node;
- else
- last->left = new_node;
- }
- bool bit;
- int res = nameBitvector_testBit(curr_name, match_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_add)");
- if(bit)
- new_node->right = curr;
- else
- new_node->left = curr;
- fib->size++;
- return;
- }
-
- //in the last case we need to add an inner node
- Name * inner_prefix = name_Copy(fibEntry_GetPrefix(entry));
- nameBitvector_clear(name_GetContentName(inner_prefix), match_len);
- name_setLen(inner_prefix, match_len);
-
- //this is an inner node, we don't want an acctive strategy
- //like low_latency that sends probes in this node
- FibEntry * inner_entry = fibEntry_Create(inner_prefix,
- SET_STRATEGY_LOADBALANCER, fib->forwarder);
-
- FibNode * inner_node = _createNode(NULL, NULL, inner_entry, false);
- FibNode * new_node = _createNode(NULL, NULL, entry, true);
-
- if(last == NULL){
- //we need to place the inner_node at the root
- fib->root = inner_node;
- }else{
- uint32_t last_prefix_len = nameBitvector_GetLength(
- name_GetContentName(fibEntry_GetPrefix(last->entry)));
- bool bit;
- int res = nameBitvector_testBit(name_GetContentName(inner_prefix),
- last_prefix_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_add)");
- if(bit)
- last->right = inner_node;
- else
- last->left = inner_node;
- }
-
- bool bit;
- int res = nameBitvector_testBit(new_prefix, match_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_add)");
-
- if(bit){
- inner_node -> left = curr;
- inner_node ->right = new_node;
- }else{
- inner_node -> left = new_node;
- inner_node ->right = curr;
- }
- fib->size ++;
-
- name_Release(&inner_prefix);
-}
-
-FibEntry *fib_Contains(const FIB *fib, const Name *prefix) {
- parcAssertNotNull(fib, "Parameter must be non-null");
- parcAssertNotNull(prefix, "Parameter must be non-null");
-
- NameBitvector *key_name = name_GetContentName(prefix);
- uint32_t key_prefix_len = nameBitvector_GetLength(key_name);
-
- FibNode * curr = fib->root;
-
- while(curr != NULL){
- NameBitvector *curr_name =
- name_GetContentName(fibEntry_GetPrefix(curr->entry));
- uint32_t match_len = nameBitvector_lpm(key_name, curr_name);
- uint32_t curr_prefix_len = nameBitvector_GetLength(curr_name);
-
- if(match_len < curr_prefix_len){
- //the current node does not match completelly the key, so
- //the key is not in the trie
- //this implies curr_prefix_len > key_prefix_len
- return NULL;
- }
-
- if(curr_prefix_len == key_prefix_len){ //== match_len
- //this is an exact match
- if(curr->is_used){
- //we found the key
- return curr->entry;
- }else{
- //the key does not exists
- return NULL;
- }
- }
-
- bool bit;
- int res = nameBitvector_testBit(key_name, curr_prefix_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_contains)");
-
- if(bit)
- curr = curr->right;
- else
- curr = curr->left;
- }
-
- return NULL;
-}
-
-void _removeNode(FIB *fib, const Name *prefix){
- parcAssertNotNull(fib, "Parameter must be non-null");
- parcAssertNotNull(prefix, "Parameter must be non-null");
-
- NameBitvector *key_name = name_GetContentName(prefix);
- uint32_t key_prefix_len = nameBitvector_GetLength(key_name);
-
- FibNode * curr = fib->root;
- FibNode * parent = NULL;
- FibNode * grandpa = NULL;
-
- uint32_t match_len;
- uint32_t curr_prefix_len;
- while(curr != NULL){
- NameBitvector *curr_name =
- name_GetContentName(fibEntry_GetPrefix(curr->entry));
- match_len = nameBitvector_lpm(key_name, curr_name);
- curr_prefix_len = nameBitvector_GetLength(curr_name);
-
- if(match_len < curr_prefix_len ||
- curr_prefix_len == key_prefix_len){
- break;
- }
-
- grandpa = parent;
- parent = curr;
-
- bool bit;
- int res = nameBitvector_testBit(key_name, curr_prefix_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (_removeNode)");
-
- if(bit)
- curr = curr->right;
- else
- curr = curr->left;
- }
-
- if(curr == NULL ||
- !curr->is_used ||
- (curr_prefix_len != key_prefix_len)){
- //the node does not exists
- return;
- }
-
- //curr has 2 children, leave it there and mark it as inner
- if(curr->right != NULL && curr->left != NULL){
- curr->is_used = false;
- fib->size--;
- return;
- }
-
- //curr has no children
- if(curr->right == NULL && curr->left == NULL){
- if (parent == NULL){
- //curr is the root and is the only node in the fib
- fib->root = NULL;
- fib->size--;
- _destroyNode(curr);
- return;
- }
- if(grandpa == NULL){
- //parent is the root
- if(fib->root->left == curr)
- fib->root->left = NULL;
- else
- fib->root->right = NULL;
- fib->size--;
- _destroyNode(curr);
- return;
- }
- if(!parent->is_used){
- //parent is an inner node
- //remove curr and inner_node (parent), connect the other child
- //of the parent to the grandpa
- FibNode * tmp;
- if(parent->right == curr)
- tmp = parent->left;
- else
- tmp = parent->right;
-
- if(grandpa->right == parent)
- grandpa->right = tmp;
- else
- grandpa->left = tmp;
-
- fib->size--;
- _destroyNode(curr);
- _destroyNode(parent);
- return;
- }
- //parent is node not an inner_node
- //just remove curr the node
- if(parent->right == curr)
- parent->right = NULL;
- else
- parent->left = NULL;
- fib->size--;
- _destroyNode(curr);
- return;
- }
-
- //curr has one child
- if(curr->right != NULL || curr->left != NULL){
- if(parent == NULL){
- //curr is the root
- if(fib->root->right != NULL)
- fib->root = fib->root->right;
- else
- fib->root = fib->root->left;
- fib->size--;
- _destroyNode(curr);
- return;
- }
- //attach the child of curr to parent
- FibNode * tmp;
- if(curr->right != NULL)
- tmp = curr->right;
- else
- tmp = curr->left;
-
- if(parent->right == curr)
- parent->right = tmp;
- else
- parent->left = tmp;
-
- fib->size--;
- _destroyNode(curr);
- return;
- }
-}
-
-void fib_Remove(FIB *fib, const Name *name, unsigned connId) {
- parcAssertNotNull(fib, "Parameter must be non-null");
- parcAssertNotNull(name, "Parameter must be non-null");
-
- FibEntry *entry = fib_Contains(fib, name);
-
- if (entry == NULL) {
- return;
- }
-
- fibEntry_RemoveNexthopByConnectionId(entry, connId);
-#ifndef WITH_MAPME
- if (fibEntry_NexthopCount(entry) == 0)
- _removeNode(fib, name);
-#endif /* WITH_MAPME */
-
- // XXX We never release the FIB entry here it seems, including the inner
- // prefix
-
-}
-
-void _removeConnectionId(FibNode *n, unsigned connectionId,
- FibEntryList *list) {
- if(n != NULL){
- if(n->is_used){
- fibEntry_RemoveNexthopByConnectionId(n->entry, connectionId);
-#ifndef WITH_MAPME
- if (fibEntry_NexthopCount(n->entry) == 0) {
- fibEntryList_Append(list, n->entry);
- }
-#endif /* WITH_MAPME */
- }
- _removeConnectionId(n->right, connectionId, list);
- _removeConnectionId(n->left, connectionId, list);
- }
-}
-
-void fib_RemoveConnectionId(FIB *fib, unsigned connectionId) {
- parcAssertNotNull(fib, "Parameter must be non-null");
-
- FibEntryList *list = fibEntryList_Create();
- _removeConnectionId(fib->root, connectionId, list);
-
- for (int i = 0; i < fibEntryList_Length(list); i++) {
- _removeNode(fib, fibEntry_GetPrefix(fibEntryList_Get(list, i)));
- }
-
- fibEntryList_Destroy(&list);
-}
-
-size_t fib_Length(const FIB *fib) {
- parcAssertNotNull(fib, "Parameter must be non-null");
- return fib->size;
-}
-
-FibEntry *fib_MatchMessage(const FIB *fib, const Message *interestMessage) {
- parcAssertNotNull(fib, "Parameter must be non-null");
- parcAssertNotNull(interestMessage, "Parameter must be non-null");
- return fib_MatchBitvector(fib, name_GetContentName(
- message_GetName(interestMessage)));
-}
-
-FibEntry *fib_MatchName(const FIB *fib, const Name *name) {
- parcAssertNotNull(fib, "Parameter must be non-null");
- parcAssertNotNull(name, "Parameter must be non-null");
- return fib_MatchBitvector(fib, name_GetContentName(name));
-}
-
-
-FibEntry *fib_MatchBitvector(const FIB *fib, const NameBitvector *name){
- parcAssertNotNull(fib, "Parameter must be non-null");
- parcAssertNotNull(name, "Parameter must be non-null");
-
- uint32_t key_prefix_len = nameBitvector_GetLength(name);
-
- FibNode * curr = fib->root;
- FibNode * candidate = NULL;
-
- while(curr != NULL){
- NameBitvector *curr_name =
- name_GetContentName(fibEntry_GetPrefix(curr->entry));
- uint32_t match_len = nameBitvector_lpm(name, curr_name);
- uint32_t curr_prefix_len = nameBitvector_GetLength(curr_name);
-
- if(match_len < curr_prefix_len){
- //the current node does not match completelly the key, so
- //return the parent of this node (saved in candidate)
- break;
- }
-
- if(curr->is_used)
- candidate = curr;
-
- //if we are here match_len == curr_prefix_len (can't be larger)
- //so this node is actually a good candidate for a match
- if(curr_prefix_len == key_prefix_len){
- //this an exact match, do not continue
- break;
- }
-
- bool bit;
- int res = nameBitvector_testBit(name, curr_prefix_len, &bit);
- parcAssertFalse(res < 0, "error testing name bit (fib_MatchBitvector)");
-
- if(bit)
- curr = curr->right;
- else
- curr = curr->left;
- }
-
- if(candidate != NULL){
- return candidate->entry;
- }
-
- return NULL;
-}
-
-void _collectFibEntries(FibNode *n, FibEntryList *list){
- if(n != NULL){
- if(n->is_used)
- fibEntryList_Append(list, n->entry);
- _collectFibEntries(n->right, list);
- _collectFibEntries(n->left, list);
- }
-}
-
-FibEntryList *fib_GetEntries(const FIB *fib) {
- parcAssertNotNull(fib, "Parameter must be non-null");
- FibEntryList *list = fibEntryList_Create();
-
- _collectFibEntries(fib->root, list);
-
- return list;
-}
diff --git a/hicn-light/src/hicn/processor/fib.h b/hicn-light/src/hicn/processor/fib.h
deleted file mode 100644
index ef9e121b8..000000000
--- a/hicn-light/src/hicn/processor/fib.h
+++ /dev/null
@@ -1,45 +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.
- */
-#ifndef fib_h
-#define fib_h
-
-#include <hicn/core/message.h>
-#include <hicn/core/name.h>
-#include <hicn/processor/fibEntry.h>
-#include <hicn/processor/fibEntryList.h>
-
-struct fib;
-typedef struct fib FIB;
-
-FIB *fib_Create(Forwarder *forwarder);
-
-void fib_Destroy(FIB **fibPtr);
-
-void fib_Add(FIB *fib, FibEntry *node);
-
-FibEntry *fib_Contains(const FIB *fib, const Name *prefix);
-
-void fib_Remove(FIB *fib, const Name *prefix, unsigned connId);
-
-void fib_RemoveConnectionId(FIB *fib, unsigned connectionId);
-
-FibEntry *fib_MatchMessage(const FIB *fib, const Message *interestMessage);
-FibEntry *fib_MatchName(const FIB *fib, const Name *name);
-FibEntry *fib_MatchBitvector(const FIB *fib, const NameBitvector *name);
-
-size_t fib_Length(const FIB *fib);
-
-FibEntryList *fib_GetEntries(const FIB *fib);
-#endif // fib_h
diff --git a/hicn-light/src/hicn/processor/fibEntry.c b/hicn-light/src/hicn/processor/fibEntry.c
deleted file mode 100644
index 00e8dfa11..000000000
--- a/hicn-light/src/hicn/processor/fibEntry.c
+++ /dev/null
@@ -1,894 +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/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/core/numberSet.h>
-#include <hicn/processor/fibEntry.h>
-
-#include <hicn/core/nameBitvector.h>
-
-#include <hicn/strategies/loadBalancer.h>
-#include <hicn/strategies/lowLatency.h>
-#include <hicn/strategies/rnd.h>
-#include <hicn/strategies/strategyImpl.h>
-#ifdef WITH_MAPME
-#include <parc/algol/parc_HashMap.h>
-#include <hicn/core/ticks.h>
-#endif /* WITH_MAPME */
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/core/connectionState.h>
-
-#ifdef WITH_POLICY
-#include <hicn/core/forwarder.h>
-#include <hicn/policy.h>
-
-#ifdef WITH_MAPME
-#include <hicn/core/mapme.h>
-#endif /* WITH_MAPME */
-
-#define ALPHA 0.5
-
-#endif /* WITH_POLICY */
-
-struct fib_entry {
- Name *name;
- unsigned refcount;
- StrategyImpl *fwdStrategy;
-#ifdef WITH_POLICY
- NumberSet *nexthops;
- const Forwarder * forwarder;
- hicn_policy_t policy;
- policy_counters_t policy_counters;
-// NumberSet *available_nexthops;
-#ifdef WITH_MAPME
- /* In case of no multipath, this stores the previous decision taken by policy */
-#endif /* WITH_MAPME */
-#endif /* WITH_POLICY */
-#ifdef WITH_MAPME
- NumberSet * previous_nexthops;
- const void *userDataOwner;
- void *userData;
- void (*userDataRelease)(const void *owner, void **userData);
-#endif /* WITH_MAPME */
-};
-
-#ifdef WITH_POLICY
-FibEntry *fibEntry_Create(Name *name, strategy_type fwdStrategy, const Forwarder * forwarder) {
-#else
-FibEntry *fibEntry_Create(Name *name, strategy_type fwdStrategy) {
-#endif /* WITH_POLICY */
- FibEntry *fibEntry = parcMemory_AllocateAndClear(sizeof(FibEntry));
- parcAssertNotNull(fibEntry, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(FibEntry));
- fibEntry->name = name_Acquire(name);
-
- switch (fwdStrategy) {
- case SET_STRATEGY_LOADBALANCER:
- fibEntry->fwdStrategy = strategyLoadBalancer_Create();
- break;
-
- case SET_STRATEGY_RANDOM:
- fibEntry->fwdStrategy = strategyRnd_Create();
-
- case SET_STRATEGY_LOW_LATENCY:
- fibEntry->fwdStrategy = strategyLowLatency_Create();
- break;
-
- default:
- // LB is the default strategy
- fwdStrategy = SET_STRATEGY_LOADBALANCER;
- fibEntry->fwdStrategy = strategyLoadBalancer_Create();
- break;
- }
-
- fibEntry->refcount = 1;
-
-#ifdef WITH_MAPME
- fibEntry->userDataOwner = NULL;
- fibEntry->userData = NULL;
- fibEntry->userDataRelease = NULL;
-#endif /* WITH_MAPME */
-
-#ifdef WITH_POLICY
- fibEntry->nexthops = numberSet_Create();
- fibEntry->forwarder = forwarder;
- fibEntry->policy = POLICY_NONE;
- fibEntry->policy_counters = POLICY_COUNTERS_NONE;
-#endif /* WITH_POLICY */
-
- if(fwdStrategy == SET_STRATEGY_LOW_LATENCY){
- strategyLowLatency_SetStrategy(fibEntry->fwdStrategy,
- fibEntry->forwarder, fibEntry,
- 0, NULL);
- }
- return fibEntry;
-}
-
-FibEntry *fibEntry_Acquire(const FibEntry *fibEntry) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
- FibEntry *copy = (FibEntry *)fibEntry;
- copy->refcount++;
- return copy;
-}
-
-void fibEntry_Release(FibEntry **fibEntryPtr) {
- FibEntry *fibEntry = *fibEntryPtr;
- parcAssertTrue(fibEntry->refcount > 0, "Illegal state: refcount is 0");
- fibEntry->refcount--;
- if (fibEntry->refcount == 0) {
- name_Release(&fibEntry->name);
- fibEntry->fwdStrategy->destroy(&(fibEntry->fwdStrategy));
-#ifdef WITH_MAPME
- if (fibEntry->userData) {
- fibEntry->userDataRelease(fibEntry->userDataOwner, &fibEntry->userData);
- }
-#endif /* WITH_MAPME */
-#ifdef WITH_POLICY
- numberSet_Release(&fibEntry->nexthops);
-#endif /* WITH_POLICY */
- parcMemory_Deallocate((void **)&fibEntry);
- }
- *fibEntryPtr = NULL;
-}
-
-void fibEntry_SetStrategy(FibEntry *fibEntry, strategy_type strategy,
- unsigned related_prefixes_len,
- Name **related_prefixes) {
- StrategyImpl *fwdStrategyImpl;
-
- switch (strategy) {
- case SET_STRATEGY_LOADBALANCER:
- fwdStrategyImpl = strategyLoadBalancer_Create();
- break;
-
- case SET_STRATEGY_RANDOM:
- fwdStrategyImpl = strategyRnd_Create();
- break;
-
- case SET_STRATEGY_LOW_LATENCY:
- fwdStrategyImpl = strategyLowLatency_Create();
- break;
-
- default:
- // LB is the default strategy
- strategy = SET_STRATEGY_LOADBALANCER;
- fwdStrategyImpl = strategyLoadBalancer_Create();
- break;
- }
-
- if(strategy == SET_STRATEGY_LOW_LATENCY){
- strategyLowLatency_SetStrategy(fwdStrategyImpl,
- fibEntry->forwarder, fibEntry,
- related_prefixes_len, related_prefixes);
- }
-
- const NumberSet *nexthops = fibEntry_GetNexthops(fibEntry);
- unsigned size = (unsigned)fibEntry_NexthopCount(fibEntry);
- for (unsigned i = 0; i < size; i++) {
- fwdStrategyImpl->addNexthop(fwdStrategyImpl,
- numberSet_GetItem(nexthops, i));
- }
- fibEntry->fwdStrategy->destroy(&(fibEntry->fwdStrategy));
- fibEntry->fwdStrategy = fwdStrategyImpl;
-}
-
-#ifdef WITH_POLICY
-
-/*
- * Update available next hops following policy update.
- */
-NumberSet *
-fibEntry_GetAvailableNextHops(const FibEntry *fibEntry, unsigned in_connection) {
- ConnectionTable * table = forwarder_GetConnectionTable(fibEntry->forwarder);
- NumberSet * nexthops;
- bool dealloc_nexthops = false;
- hicn_policy_t policy = fibEntry_GetPolicy(fibEntry);
-
- /* Reset available next hops and start filtering */
- NumberSet * available_nexthops = numberSet_Create();
-
- /*
- * Give absolute preference to local faces, with no policy, unless
- * in_connection == ~0, which means we are searching faces on which to
- * advertise our prefix
- */
- if (in_connection == ~0) {
- /* We might advertise among all available up connections */
- nexthops = numberSet_Create();
- dealloc_nexthops = true;
-
- ConnectionList * list = connectionTable_GetEntries(table);
- for (size_t i = 0; i < connectionList_Length(list); i++) {
- Connection *conn = connectionList_Get(list, i);
- if (connection_IsLocal(conn))
- continue;
- if (connection_GetAdminState(conn) == CONNECTION_STATE_DOWN)
- continue;
- if (connection_GetState(conn) == CONNECTION_STATE_DOWN)
- continue;
- numberSet_Add(nexthops, connection_GetConnectionId(conn));
- }
- connectionList_Destroy(&list);
- } else {
- nexthops = (NumberSet*)fibEntry_GetNexthops(fibEntry);
- for (size_t k = 0; k < numberSet_Length(nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(nexthops, k);
- /* Filtering out ingress face */
- if (conn_id == in_connection)
- continue;
- /* Filtering out DOWN faces */
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (!conn)
- continue;
- if (connection_GetAdminState(conn) == CONNECTION_STATE_DOWN)
- continue;
- if (connection_GetState(conn) == CONNECTION_STATE_DOWN)
- continue;
- if (!connection_IsLocal(conn))
- continue;
- numberSet_Add(available_nexthops, conn_id);
- }
-
- /* Terminate selection if there are any local face available */
- if (numberSet_Length(available_nexthops) > 0){
- if(dealloc_nexthops){
- numberSet_Release(&nexthops);
- }
- /* No filtering as all local faces are considered equivalent */
- return available_nexthops;
- }
- }
-
- for (size_t k = 0; k < numberSet_Length(nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(nexthops, k);
- const Connection * conn;
-
- /* Filtering out ingress face */
- if (conn_id == in_connection)
- continue;
-
- /* Filtering out DOWN faces */
- conn = connectionTable_FindById(table, conn_id);
- if (!conn)
- continue;
- if (connection_GetAdminState(conn) == CONNECTION_STATE_DOWN)
- continue;
- if (connection_GetState(conn) == CONNECTION_STATE_DOWN)
- continue;
-
- /* Policy filtering : next hops */
- if ((policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_REQUIRE) &&
- (!connection_HasTag(conn, POLICY_TAG_WIRED)))
- continue;
- if ((policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_PROHIBIT) &&
- (connection_HasTag(conn, POLICY_TAG_WIRED)))
- continue;
- if ((policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_REQUIRE) &&
- (!connection_HasTag(conn, POLICY_TAG_WIFI)))
- continue;
- if ((policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_PROHIBIT) &&
- (connection_HasTag(conn, POLICY_TAG_WIFI)))
- continue;
- if ((policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_REQUIRE) &&
- (!connection_HasTag(conn, POLICY_TAG_CELLULAR)))
- continue;
- if ((policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_PROHIBIT) &&
- (connection_HasTag(conn, POLICY_TAG_CELLULAR)))
- continue;
- if ((policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_REQUIRE) &&
- (!connection_HasTag(conn, POLICY_TAG_TRUSTED)))
- continue;
- if ((policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_PROHIBIT) &&
- (connection_HasTag(conn, POLICY_TAG_TRUSTED)))
- continue;
-
- numberSet_Add(available_nexthops, conn_id);
- }
-
- if(dealloc_nexthops)
- numberSet_Release(&nexthops);
-
- if (numberSet_Length(available_nexthops) == 0)
- return available_nexthops;
-
- /* We have at least one matching next hop, implement heuristic */
-
- /*
- * As VPN connections might trigger duplicate uses of one interface, we start
- * by filtering out interfaces based on trust status.
- */
- NumberSet * filtered_nexthops = numberSet_Create();
- if ((policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_REQUIRE) ||
- (policy.tags[POLICY_TAG_TRUSTED].state == POLICY_STATE_PREFER)) {
- /* Try to filter out NON TRUSTED faces */
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (!connection_HasTag(conn, POLICY_TAG_TRUSTED))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- } else {
- /* Try to filter out TRUSTED faces */
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (connection_HasTag(conn, POLICY_TAG_TRUSTED))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- }
- if (numberSet_Length(filtered_nexthops) > 0) {
- numberSet_Release(&available_nexthops);
- available_nexthops = numberSet_Create();
- numberSet_AddSet(available_nexthops, filtered_nexthops);
- }
- numberSet_Release(&filtered_nexthops);
-
- /* Other preferences */
- if (policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_AVOID) {
- filtered_nexthops = numberSet_Create();
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (connection_HasTag(conn, POLICY_TAG_WIRED))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- if (numberSet_Length(filtered_nexthops) > 0) {
- numberSet_Release(&available_nexthops);
- available_nexthops = numberSet_Create();
- numberSet_AddSet(available_nexthops, filtered_nexthops);
- }
- numberSet_Release(&filtered_nexthops);
- }
- if (policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_AVOID) {
- filtered_nexthops = numberSet_Create();
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (connection_HasTag(conn, POLICY_TAG_WIFI))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- if (numberSet_Length(filtered_nexthops) > 0) {
- numberSet_Release(&available_nexthops);
- available_nexthops = numberSet_Create();
- numberSet_AddSet(available_nexthops, filtered_nexthops);
- }
- numberSet_Release(&filtered_nexthops);
- }
- if (policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_AVOID) {
- filtered_nexthops = numberSet_Create();
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (connection_HasTag(conn, POLICY_TAG_CELLULAR))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- if (numberSet_Length(filtered_nexthops) > 0) {
- numberSet_Release(&available_nexthops);
- available_nexthops = numberSet_Create();
- numberSet_AddSet(available_nexthops, filtered_nexthops);
- }
- numberSet_Release(&filtered_nexthops);
- }
-
- if (policy.tags[POLICY_TAG_WIRED].state == POLICY_STATE_PREFER) {
- filtered_nexthops = numberSet_Create();
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (!connection_HasTag(conn, POLICY_TAG_WIRED))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- if (numberSet_Length(filtered_nexthops) > 0) {
- numberSet_Release(&available_nexthops);
- available_nexthops = numberSet_Create();
- numberSet_AddSet(available_nexthops, filtered_nexthops);
- }
- numberSet_Release(&filtered_nexthops);
- }
- if (policy.tags[POLICY_TAG_WIFI].state == POLICY_STATE_PREFER) {
- filtered_nexthops = numberSet_Create();
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (!connection_HasTag(conn, POLICY_TAG_WIFI))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- if (numberSet_Length(filtered_nexthops) > 0) {
- numberSet_Release(&available_nexthops);
- available_nexthops = numberSet_Create();
- numberSet_AddSet(available_nexthops, filtered_nexthops);
- }
- numberSet_Release(&filtered_nexthops);
- }
- if (policy.tags[POLICY_TAG_CELLULAR].state == POLICY_STATE_PREFER) {
- filtered_nexthops = numberSet_Create();
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (!connection_HasTag(conn, POLICY_TAG_CELLULAR))
- continue;
- numberSet_Add(filtered_nexthops, conn_id);
- }
- if (numberSet_Length(filtered_nexthops) > 0) {
- numberSet_Release(&available_nexthops);
- available_nexthops = numberSet_Create();
- numberSet_AddSet(available_nexthops, filtered_nexthops);
- }
- numberSet_Release(&filtered_nexthops);
- }
-
- /* Priority */
- NumberSet * priority_nexthops = numberSet_Create();
-
- uint32_t max_priority = 0;
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- uint32_t priority = connection_GetPriority(conn);
- if (priority < max_priority) {
- continue;
- } else if (priority == max_priority) {
- numberSet_Add(priority_nexthops, conn_id);
- } else { /* priority > max_priority */
- numberSet_Release(&priority_nexthops);
- priority_nexthops = numberSet_Create();
- numberSet_Add(priority_nexthops, conn_id);
- max_priority = priority;
- }
- }
-
- numberSet_Release(&available_nexthops);
-
- return priority_nexthops;
-}
-
-hicn_policy_t fibEntry_GetPolicy(const FibEntry *fibEntry) {
- return fibEntry->policy;
-}
-
-void fibEntry_SetPolicy(FibEntry *fibEntry, hicn_policy_t policy) {
- fibEntry->policy = policy;
- mapme_reconsiderFibEntry(forwarder_getMapmeInstance(fibEntry->forwarder), fibEntry);
-}
-
-NumberSet *
-fibEntry_GetPreviousNextHops(const FibEntry *fibEntry)
-{
- return fibEntry->previous_nexthops;
-}
-#endif /* WITH_POLICY */
-
-void
-fibEntry_SetPreviousNextHops(FibEntry *fibEntry, const NumberSet * nexthops)
-{
- if (fibEntry->previous_nexthops)
- numberSet_Release(&fibEntry->previous_nexthops);
- fibEntry->previous_nexthops = numberSet_Create();
- numberSet_AddSet(fibEntry->previous_nexthops, nexthops);
-}
-
-
-void fibEntry_AddNexthop(FibEntry *fibEntry, unsigned connectionId) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
-#ifdef WITH_POLICY
- if (!numberSet_Contains(fibEntry->nexthops, connectionId)) {
- numberSet_Add(fibEntry->nexthops, connectionId);
- }
-#endif /* WITH_POLICY */
- fibEntry->fwdStrategy->addNexthop(fibEntry->fwdStrategy, connectionId);
-}
-
-void fibEntry_RemoveNexthopByConnectionId(FibEntry *fibEntry,
- unsigned connectionId) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
-#ifdef WITH_POLICY
- if (numberSet_Contains(fibEntry->nexthops, connectionId)) {
- numberSet_Remove(fibEntry->nexthops, connectionId);
- }
-#endif /* WITH_POLICY */
- fibEntry->fwdStrategy->removeNexthop(fibEntry->fwdStrategy, connectionId);
-}
-
-size_t fibEntry_NexthopCount(const FibEntry *fibEntry) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
-#ifdef WITH_POLICY
- return numberSet_Length(fibEntry->nexthops);
-#else
- return fibEntry->fwdStrategy->countNexthops(fibEntry->fwdStrategy);
-#endif /* WITH_POLICY */
-}
-
-const NumberSet *fibEntry_GetNexthops(const FibEntry *fibEntry) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
-#ifdef WITH_POLICY
- return fibEntry->nexthops;
-#else
- return fibEntry->fwdStrategy->returnNexthops(fibEntry->fwdStrategy);
-#endif /* WITH_POLICY */
-}
-
-const NumberSet *fibEntry_GetNexthopsFromForwardingStrategy(
-#ifdef WITH_POLICY
- FibEntry *fibEntry, const Message *interestMessage, bool is_retransmission) {
-#else
- const FibEntry *fibEntry, const Message *interestMessage) {
-#endif /* WITH_POLICY */
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
-#ifdef WITH_POLICY
- ConnectionTable * table = forwarder_GetConnectionTable(fibEntry->forwarder);
- unsigned in_connection = message_GetIngressConnectionId(interestMessage);
-
- hicn_policy_t policy = fibEntry_GetPolicy(fibEntry);
-
- NumberSet * out;
-
- /* Filtering */
- NumberSet * available_nexthops = fibEntry_GetAvailableNextHops(fibEntry, in_connection);
- if (numberSet_Length(available_nexthops) == 0) {
- numberSet_Release(&available_nexthops);
- out = numberSet_Create();
- return out;
- }
-
- /*
- * Update statistics about loss rates. We only detect losses upon
- * retransmissions, and assume for the computation that the candidate set of
- * output faces is the same as previously (i.e. does not take into account
- * event such as face up/down, policy update, etc. Otherwise we would need to
- * know what was the previous choice !
- */
- if (is_retransmission) {
- for (size_t k = 0; k < numberSet_Length(available_nexthops); k++) {
- unsigned conn_id = numberSet_GetItem(available_nexthops, k);
- const Connection * conn = connectionTable_FindById(table, conn_id);
-
- if (connection_HasTag(conn, POLICY_TAG_WIRED))
- fibEntry->policy_counters.wired.num_losses++;
- if (connection_HasTag(conn, POLICY_TAG_WIFI))
- fibEntry->policy_counters.wifi.num_losses++;
- if (connection_HasTag(conn, POLICY_TAG_CELLULAR))
- fibEntry->policy_counters.cellular.num_losses++;
- fibEntry->policy_counters.all.num_losses++;
- }
- }
-
- /*
- * NOTE: We might want to call a forwarding strategy even with no nexthop to
- * take a fallback decision.
- */
- if (numberSet_Length(available_nexthops) == 0) {
- out = numberSet_Create();
- } else {
- /* Multipath */
- if ((policy.tags[POLICY_TAG_MULTIPATH].state != POLICY_STATE_PROHIBIT) &&
- (policy.tags[POLICY_TAG_MULTIPATH].state != POLICY_STATE_AVOID)) {
- out = fibEntry->fwdStrategy->lookupNexthop(fibEntry->fwdStrategy, available_nexthops,
- interestMessage);
- } else {
- unsigned nexthop = numberSet_GetItem(available_nexthops, 0);
- out = numberSet_Create();
- numberSet_Add(out, nexthop);
- }
- }
-
- numberSet_Release(&available_nexthops);
-
- return out;
-#else
- return fibEntry->fwdStrategy->lookupNexthop(fibEntry->fwdStrategy,
- interestMessage);
-#endif /* WITH_POLICY */
-}
-
-#ifdef WITH_POLICY
-void fibEntry_ReceiveObjectMessage(FibEntry *fibEntry,
-#else
-void fibEntry_ReceiveObjectMessage(const FibEntry *fibEntry,
-#endif /* WITH_POLICY */
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
-
-#ifdef WITH_POLICY
- ConnectionTable * table = forwarder_GetConnectionTable(fibEntry->forwarder);
-
- /* Update statistic counters : */
-
- size_t msg_size = message_Length(objectMessage);
- Ticks rtt = objReception - pitEntryCreation;
-
- for (unsigned i = 0; i < numberSet_Length(egressId); i++) {
- unsigned conn_id = numberSet_GetItem(egressId, i);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (!conn)
- continue;
- if (connection_HasTag(conn, POLICY_TAG_WIRED)) {
- fibEntry->policy_counters.wired.num_packets++;
- fibEntry->policy_counters.wired.num_bytes += (uint32_t)msg_size;
- fibEntry->policy.stats.wired.latency = (float) (\
- ALPHA * fibEntry->policy.stats.wired.latency + \
- (1 - ALPHA) * (double)rtt);
- fibEntry->policy_counters.wired.latency_idle = 0;
- }
- if (connection_HasTag(conn, POLICY_TAG_WIFI)) {
- fibEntry->policy_counters.wifi.num_packets++;
- fibEntry->policy_counters.wifi.num_bytes += (uint32_t)msg_size;
- fibEntry->policy.stats.wifi.latency = (float)(\
- ALPHA * fibEntry->policy.stats.wifi.latency + \
- (1 - ALPHA) * (double)rtt);
- fibEntry->policy_counters.wifi.latency_idle = 0;
-
- }
- if (connection_HasTag(conn, POLICY_TAG_CELLULAR)) {
- fibEntry->policy_counters.cellular.num_packets++;
- fibEntry->policy_counters.cellular.num_bytes += (uint32_t)msg_size;
- fibEntry->policy.stats.cellular.latency = (float)(\
- ALPHA * fibEntry->policy.stats.cellular.latency + \
- (1 - ALPHA) * (double)rtt);
- fibEntry->policy_counters.cellular.latency_idle = 0;
- }
- }
-
- fibEntry->policy.stats.all.latency = (float)(\
- ALPHA * fibEntry->policy.stats.all.latency + \
- (1 - ALPHA) * (double)rtt);
- fibEntry->policy_counters.all.latency_idle = 0;
-
- fibEntry->policy_counters.all.num_packets++;
- fibEntry->policy_counters.all.num_bytes += (uint32_t)msg_size;
-
-#endif /* WITH_POLICY */
-
- fibEntry->fwdStrategy->receiveObject(fibEntry->fwdStrategy, egressId,
- objectMessage, pitEntryCreation, objReception);
-}
-
-#ifdef WITH_POLICY
-void fibEntry_OnTimeout(FibEntry *fibEntry, const NumberSet *egressId) {
-#else
-void fibEntry_OnTimeout(const FibEntry *fibEntry, const NumberSet *egressId) {
-#endif /* WITH_POLICY */
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
-
-#ifdef WITH_POLICY
-
- ConnectionTable * table = forwarder_GetConnectionTable(fibEntry->forwarder);
-
- for (unsigned i = 0; i < numberSet_Length(egressId); i++) {
- unsigned conn_id = numberSet_GetItem(egressId, i);
- const Connection * conn = connectionTable_FindById(table, conn_id);
- if (!conn)
- continue;
- if (connection_HasTag(conn, POLICY_TAG_WIRED)) {
- fibEntry->policy_counters.wired.num_losses++;
- }
- if (connection_HasTag(conn, POLICY_TAG_WIFI)) {
- fibEntry->policy_counters.wifi.num_losses++;
- }
- if (connection_HasTag(conn, POLICY_TAG_CELLULAR)) {
- fibEntry->policy_counters.cellular.num_losses++;
- }
- }
-
- fibEntry->policy_counters.all.num_losses++;
-
-#endif /* WITH_POLICY */
-
- fibEntry->fwdStrategy->onTimeout(fibEntry->fwdStrategy, egressId);
-}
-
-#ifdef WITH_POLICY
-void fibEntry_UpdateStats(FibEntry *fibEntry, uint64_t now) {
- double throughput;
- double loss_rate;
-
- if (now == fibEntry->policy_counters.last_update)
- return ;
-
- /* WIRED */
-
- /* a) throughput */
- if (fibEntry->policy_counters.wired.num_bytes > 0) {
- throughput = (float)(fibEntry->policy_counters.wired.num_bytes / \
- (now - fibEntry->policy_counters.last_update)) ;
- throughput = throughput * 8 / 1024;
- if (throughput < 0)
- throughput = 0;
- } else {
- throughput = 0;
- }
- fibEntry->policy.stats.wired.throughput = (float)(\
- ALPHA * fibEntry->policy.stats.wired.throughput + \
- (1-ALPHA) * throughput);
-
- /* b) loss rate */
- if ((fibEntry->policy_counters.wired.num_losses > 0) && \
- (fibEntry->policy_counters.wired.num_packets > 0)){
- loss_rate = fibEntry->policy_counters.wired.num_losses / \
- fibEntry->policy_counters.wired.num_packets;
- loss_rate *= 100;
- } else {
- loss_rate = 0;
- }
- fibEntry->policy.stats.wired.loss_rate = (float)(\
- ALPHA * fibEntry->policy.stats.wired.loss_rate + \
- (1-ALPHA) * loss_rate);
-
- /* Latency */
- fibEntry->policy_counters.wired.latency_idle++;
- if (fibEntry->policy_counters.wired.latency_idle > 1)
- fibEntry->policy.stats.wired.latency = 0;
- fibEntry->policy_counters.wifi.latency_idle++;
- if (fibEntry->policy_counters.wifi.latency_idle > 1)
- fibEntry->policy.stats.wifi.latency = 0;
- fibEntry->policy_counters.cellular.latency_idle++;
- if (fibEntry->policy_counters.cellular.latency_idle > 1)
- fibEntry->policy.stats.cellular.latency = 0;
- fibEntry->policy_counters.all.latency_idle++;
- if (fibEntry->policy_counters.all.latency_idle > 1)
- fibEntry->policy.stats.all.latency = 0;
-
- fibEntry->policy_counters.wired.num_bytes = 0;
- fibEntry->policy_counters.wired.num_losses = 0;
- fibEntry->policy_counters.wired.num_packets = 0;
-
- /* WIFI */
-
- /* a) throughput */
- if (fibEntry->policy_counters.wifi.num_bytes > 0) {
- throughput = (float)(fibEntry->policy_counters.wifi.num_bytes / \
- (now - fibEntry->policy_counters.last_update));
- throughput = throughput * 8 / 1024;
- if (throughput < 0)
- throughput = 0;
- } else {
- throughput = 0;
- }
- fibEntry->policy.stats.wifi.throughput = (float)( \
- ALPHA * fibEntry->policy.stats.wifi.throughput + \
- (1-ALPHA) * throughput);
-
- /* b) loss rate */
- if ((fibEntry->policy_counters.wifi.num_losses > 0) && \
- (fibEntry->policy_counters.wifi.num_packets > 0)) {
- loss_rate = fibEntry->policy_counters.wifi.num_losses / \
- fibEntry->policy_counters.wifi.num_packets;
- loss_rate *= 100;
- } else {
- loss_rate = 0;
- }
- fibEntry->policy.stats.wifi.loss_rate = (float)(\
- ALPHA * fibEntry->policy.stats.wifi.loss_rate + \
- (1-ALPHA) * loss_rate);
-
- fibEntry->policy_counters.wifi.num_bytes = 0;
- fibEntry->policy_counters.wifi.num_losses = 0;
- fibEntry->policy_counters.wifi.num_packets = 0;
-
- /* CELLULAR */
-
- /* a) throughput */
- if (fibEntry->policy_counters.cellular.num_bytes > 0) {
- throughput = (float)(fibEntry->policy_counters.cellular.num_bytes / \
- (now - fibEntry->policy_counters.last_update)) ;
- throughput = throughput * 8 / 1024;
- if (throughput < 0)
- throughput = 0;
- } else {
- throughput = 0;
- }
- fibEntry->policy.stats.cellular.throughput = (float)( \
- ALPHA * fibEntry->policy.stats.cellular.throughput + \
- (1-ALPHA) * throughput);
-
- /* b) loss rate */
- if ((fibEntry->policy_counters.cellular.num_losses > 0) && \
- (fibEntry->policy_counters.cellular.num_packets > 0)) {
- loss_rate = fibEntry->policy_counters.cellular.num_losses / \
- fibEntry->policy_counters.cellular.num_packets;
- loss_rate *= 100;
- } else {
- loss_rate = 0;
- }
- fibEntry->policy.stats.cellular.loss_rate = (float)( \
- ALPHA * fibEntry->policy.stats.cellular.loss_rate + \
- (1-ALPHA) * loss_rate);
-
- fibEntry->policy_counters.cellular.num_bytes = 0;
- fibEntry->policy_counters.cellular.num_losses = 0;
- fibEntry->policy_counters.cellular.num_packets = 0;
-
- /* ALL */
-
- /* a) throughput */
- if (fibEntry->policy_counters.all.num_bytes > 0) {
- throughput = (float)( fibEntry->policy_counters.all.num_bytes / \
- (now - fibEntry->policy_counters.last_update));
- throughput = throughput * 8 / 1024;
- if (throughput < 0)
- throughput = 0;
- } else {
- throughput = 0;
- }
- fibEntry->policy.stats.all.throughput = (float)(\
- ALPHA * fibEntry->policy.stats.all.throughput + \
- (1-ALPHA) * throughput);
-
- /* b) loss rate */
- if ((fibEntry->policy_counters.all.num_losses > 0) && \
- (fibEntry->policy_counters.all.num_packets > 0)) {
- loss_rate = fibEntry->policy_counters.all.num_losses / \
- fibEntry->policy_counters.all.num_packets;
- loss_rate *= 100;
- } else {
- loss_rate = 0;
- }
- fibEntry->policy.stats.all.loss_rate = (float)(\
- ALPHA * fibEntry->policy.stats.all.loss_rate + \
- (1-ALPHA) * loss_rate);
-
- fibEntry->policy_counters.all.num_bytes = 0;
- fibEntry->policy_counters.all.num_losses = 0;
- fibEntry->policy_counters.all.num_packets = 0;
-
- fibEntry->policy_counters.last_update = now;
-}
-#endif /* WITH_POLICY */
-
-Name *fibEntry_GetPrefix(const FibEntry *fibEntry) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
- return fibEntry->name;
- // return metisName_Acquire(fibEntry->name);
-}
-
-strategy_type fibEntry_GetFwdStrategyType(const FibEntry *fibEntry) {
- return fibEntry->fwdStrategy->getStrategy(fibEntry->fwdStrategy);
-}
-
-StrategyImpl *fibEntry_GetFwdStrategy(const FibEntry *fibEntry) {
- return fibEntry->fwdStrategy;
-}
-
-#ifdef WITH_MAPME
-
-void *fibEntry_getUserData(const FibEntry *fibEntry) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
- return fibEntry->userData;
-}
-
-void fibEntry_setUserData(FibEntry *fibEntry, const void *userDataOwner, const
- void *userData, void (*userDataRelease)(const void *, void **)) {
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
- fibEntry->userDataOwner = userDataOwner;
- fibEntry->userData = (void *)userData;
- fibEntry->userDataRelease = userDataRelease;
-}
-
-#endif /* WITH_MAPME */
diff --git a/hicn-light/src/hicn/processor/fibEntry.h b/hicn-light/src/hicn/processor/fibEntry.h
deleted file mode 100644
index cf267d6a6..000000000
--- a/hicn-light/src/hicn/processor/fibEntry.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file fibEntry.h
- * @brief A forwarding entry in the FIB table
- *
- * A Forwarding Information Base (FIB) entry (FibEntry) is a
- * set of nexthops for a name. It also indicates the forwarding strategy.
- *
- * Each nexthop contains the ConnectionId assocaited with it. This could be
- * something specific like a MAC address or point-to-point tunnel. Or, it
- * could be something general like a MAC group address or ip multicast overlay.
- *
- * See strategy.h for a description of forwarding strategies.
- * In short, a strategy is the algorithm used to select one or more nexthops
- * from the set of available nexthops.
- *
- * Each nexthop also contains a void* to a forwarding strategy data container.
- * This allows a strategy to keep proprietary information about each nexthop.
- *
- *
- */
-
-#ifndef fibEntry_h
-#define fibEntry_h
-
-#include <hicn/core/name.h>
-#include <hicn/strategies/strategyImpl.h>
-
-#ifdef WITH_POLICY
-#include <hicn/core/connectionTable.h>
-#endif /* WITH_POLICY */
-
-#ifdef WITH_MAPME
-#include <parc/algol/parc_EventTimer.h>
-#include <parc/algol/parc_Iterator.h>
-#endif /* WITH_MAPME */
-
-struct fib_entry;
-typedef struct fib_entry FibEntry;
-
-#ifdef WITH_POLICY
-struct forwarder;
-FibEntry *fibEntry_Create(Name *name, strategy_type fwdStrategy, const struct forwarder * table);
-#else
-FibEntry *fibEntry_Create(Name *name, strategy_type fwdStrategy);
-#endif
-
-/**
- * Decrements the reference count by one, and destroys the memory after last
- * release
- *
- */
-void fibEntry_Release(FibEntry **fibEntryPtr);
-
-/**
- * Returns a reference counted copy of the fib entry
- *
- * The reference count is increased by one. The returned value must be
- * released via fibEnty_Release().
- *
- * @param [in] fibEntry An allocated FibEntry
- *
- * @return non-null A reference counted copy of the fibEntry
- *
- */
-FibEntry *fibEntry_Acquire(const FibEntry *fibEntry);
-
-void fibEntry_SetStrategy(FibEntry *fibEntry, strategy_type strategy,
- unsigned related_prefixes_len,
- Name **related_prefixes);
-
-void fibEntry_AddNexthop(FibEntry *fibEntry, unsigned connectionId);
-
-void fibEntry_RemoveNexthopByConnectionId(FibEntry *fibEntry,
- unsigned connectionId);
-
-size_t fibEntry_NexthopCount(const FibEntry *fibEntry);
-
-/**
- * @function fibEntry_GetNexthops
- * @abstract Returns the nexthop set of the FIB entry. You must Acquire if it
- * will be saved.
- * @discussion
- * Returns the next hop set for the FIB entry.
- */
-const NumberSet *fibEntry_GetNexthops(const FibEntry *fibEntry);
-
-#ifdef WITH_POLICY
-void fibEntry_ReceiveObjectMessage(FibEntry *fibEntry,
-#else
-void fibEntry_ReceiveObjectMessage(const FibEntry *fibEntry,
-#endif /* WITH_POLICY */
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception);
-
-#ifdef WITH_POLICY
-hicn_policy_t fibEntry_GetPolicy(const FibEntry *fibEntry);
-void fibEntry_ReconsiderPolicy(FibEntry *fibEntry);
-void fibEntry_SetPolicy(FibEntry *fibEntry, hicn_policy_t policy);
-void fibEntry_UpdateStats(FibEntry *fibEntry, uint64_t now);
-NumberSet * fibEntry_GetAvailableNextHops(const FibEntry *fibEntry, unsigned in_connection);
-NumberSet * fibEntry_GetPreviousNextHops(const FibEntry *fibEntry);
-void fibEntry_SetPreviousNextHops(FibEntry *fibEntry, const NumberSet * nexthops);
-
-void fibEntry_OnTimeout(FibEntry *fibEntry, const NumberSet *egressId);
-const NumberSet *fibEntry_GetNexthopsFromForwardingStrategy(
- FibEntry *fibEntry, const Message *interestMessage, bool is_retransmission);
-
-#else
-void fibEntry_OnTimeout(const FibEntry *fibEntry, const NumberSet *egressId);
-const NumberSet *fibEntry_GetNexthopsFromForwardingStrategy(
- const FibEntry *fibEntry, const Message *interestMessage);
-#endif /* WITH_POLICY */
-
-
-strategy_type fibEntry_GetFwdStrategyType(const FibEntry *fibEntry);
-
-StrategyImpl *fibEntry_GetFwdStrategy(const FibEntry *fibEntry);
-
-/**
- * @function fibEntry_GetPrefix
- * @abstract Returns a copy of the prefix.
- * @return A reference counted copy that you must destroy
- */
-Name *fibEntry_GetPrefix(const FibEntry *fibEntry);
-
-#ifdef WITH_MAPME
-
-/**
- * @function fibEntry_getUserData
- * @abstract Returns user data associated to the FIB entry.
- * @param [in] fibEntry - Pointer to the FIB entry.
- * @return User data as a void pointer
- */
-void *fibEntry_getUserData(const FibEntry *fibEntry);
-
-/**
- * @function fibEntry_getUserData
- * @abstract Associates user data and release callback to a FIB entry.
- * @param [in] fibEntry - Pointer to the FIB entry.
- * @param [in] userData - Generic pointer to user data
- * @param [in@ userDataRelease - Callback used to release user data upon change
- * of FIB entry removal.
- */
-void fibEntry_setUserData(FibEntry *fibEntry, const void *userDataOwner,
- const void *userData, void (*userDataRelease)(const void *, void **));
-
-#endif /* WITH_MAPME */
-
-#endif // fibEntry_h
diff --git a/hicn-light/src/hicn/processor/fibEntryList.c b/hicn-light/src/hicn/processor/fibEntryList.c
deleted file mode 100644
index 56d7b8bea..000000000
--- a/hicn-light/src/hicn/processor/fibEntryList.c
+++ /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.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/assert/parc_Assert.h>
-#include <hicn/processor/fibEntryList.h>
-
-struct fib_entry_list {
- PARCArrayList *listOfFibEntries;
-};
-
-static void fibEntryList_ListDestroyer(void **voidPtr) {
- FibEntry **entryPtr = (FibEntry **)voidPtr;
- fibEntry_Release(entryPtr);
-}
-
-FibEntryList *fibEntryList_Create() {
- FibEntryList *fibEntryList =
- parcMemory_AllocateAndClear(sizeof(FibEntryList));
- parcAssertNotNull(fibEntryList,
- "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(FibEntryList));
- fibEntryList->listOfFibEntries =
- parcArrayList_Create(fibEntryList_ListDestroyer);
- return fibEntryList;
-}
-
-void fibEntryList_Destroy(FibEntryList **listPtr) {
- parcAssertNotNull(listPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*listPtr, "Parameter must dereference to non-null pointer");
-
- FibEntryList *list = *listPtr;
- parcArrayList_Destroy(&list->listOfFibEntries);
- parcMemory_Deallocate((void **)&list);
- listPtr = NULL;
-}
-
-void fibEntryList_Append(FibEntryList *list, FibEntry *fibEntry) {
- parcAssertNotNull(list, "Parameter list must be non-null pointer");
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null pointer");
-
- FibEntry *copy = fibEntry_Acquire(fibEntry);
- parcArrayList_Add(list->listOfFibEntries, copy);
-}
-
-size_t fibEntryList_Length(const FibEntryList *list) {
- parcAssertNotNull(list, "Parameter list must be non-null pointer");
- return parcArrayList_Size(list->listOfFibEntries);
-}
-
-const FibEntry *fibEntryList_Get(const FibEntryList *list, size_t index) {
- parcAssertNotNull(list, "Parameter list must be non-null pointer");
- FibEntry *entry = parcArrayList_Get(list->listOfFibEntries, index);
- return entry;
-}
diff --git a/hicn-light/src/hicn/processor/fibEntryList.h b/hicn-light/src/hicn/processor/fibEntryList.h
deleted file mode 100644
index 072a1b369..000000000
--- a/hicn-light/src/hicn/processor/fibEntryList.h
+++ /dev/null
@@ -1,96 +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.
- */
-
-/**
- * @file fibEntryList.h
- * @brief A typesafe list of FibEntry
- *
- * <#Detailed Description#>
- *
- */
-
-#ifndef fibEntryList_h
-#define fibEntryList_h
-
-#include <hicn/processor/fibEntry.h>
-
-struct fib_entry_list;
-typedef struct fib_entry_list FibEntryList;
-
-/**
- * Creates an emtpy FIB entry list
- *
- * Must be destroyed with fibEntryList_Destroy.
- *
- * @retval non-null An allocated FibEntryList
- * @retval null An error
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-FibEntryList *fibEntryList_Create(void);
-
-/**
- * @function FibEntryList_Detroy
- * @abstract Destroys the list and all entries.
- * @discussion
- * <#Discussion#>
- *
- * @param <#param1#>
- */
-void fibEntryList_Destroy(FibEntryList **listPtr);
-
-/**
- * @function fibEntryList_Append
- * @abstract Will store a reference counted copy of the entry.
- * @discussion
- * Will create and store a reference counted copy. You keep ownership
- * of the parameter <code>fibEntry</code>.
- *
- * @param <#param1#>
- * @return <#return#>
- */
-void fibEntryList_Append(FibEntryList *list, FibEntry *fibEntry);
-
-/**
- * Returns the number of entries in the list
- *
- * <#Paragraphs Of Explanation#>
- *
- * @param [in] list An allocated FibEntryList
- *
- * @retval number The number of entries in the list
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-size_t fibEntryList_Length(const FibEntryList *list);
-
-/**
- * @function fibEntryList_Get
- * @abstract Gets an element. This is the internal reference, do not destroy.
- * @discussion
- * Returns an internal reference from the list. You must not destroy it.
- * Will assert if you go off the end of the list.
- *
- * @param <#param1#>
- * @return <#return#>
- */
-const FibEntry *fibEntryList_Get(const FibEntryList *list, size_t index);
-#endif // fibEntryList_h
diff --git a/hicn-light/src/hicn/processor/hashTableFunction.c b/hicn-light/src/hicn/processor/hashTableFunction.c
deleted file mode 100644
index 98afa1294..000000000
--- a/hicn-light/src/hicn/processor/hashTableFunction.c
+++ /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.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/core/message.h>
-#include <hicn/processor/hashTableFunction.h>
-
-#include <parc/assert/parc_Assert.h>
-
-// ======================================================================
-// Hash table key functions
-// We use a Message as the key data type
-
-bool hashTableFunction_MessageNameEquals(const void *messageA,
- const void *messageB) {
- const Message *a = (const Message *)messageA;
- const Message *b = (const Message *)messageB;
-
- return name_Equals(message_GetName(a), message_GetName(b));
-}
-
-HashCodeType hashTableFunction_MessageNameHashCode(const void *messageA) {
- const Message *message = (const Message *)messageA;
- Name *name = message_GetName(message);
-
- // we want the cumulative hash for the whole name
- uint32_t hash = name_HashCode(name);
-
- return hash;
-} \ No newline at end of file
diff --git a/hicn-light/src/hicn/processor/hashTableFunction.h b/hicn-light/src/hicn/processor/hashTableFunction.h
deleted file mode 100644
index eb9989086..000000000
--- a/hicn-light/src/hicn/processor/hashTableFunction.h
+++ /dev/null
@@ -1,73 +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.
- */
-
-/**
- * @file hashTableFunction.h
- * @brief These functions are used in PARCHashCodeTables by the
- * MatchingRulesTable and ContentStore and PIT. They perform the equality
- * and has generation needed by the PARCHashCodeTable.
- *
- */
-#ifndef hashTableFunction_h
-#define hashTableFunction_h
-
-#include <parc/algol/parc_HashCodeTable.h>
-
-// ==========================================================
-// These functions operate on a message as the key in the HashTable.
-// The functions use void * rather than message instances in the function
-// signature because it is using generic has code tables from PARC Library
-
-/**
- * Determine if the Names of two `message` instances are equal.
- *
- * The following equivalence relations on non-null `message` instances are
- * maintained:
- *
- * * It is reflexive: for any non-null reference value x,
- * `hashTableFunction_MessageNameEquals(x, x)` must return true.
- *
- * * It is symmetric: for any non-null reference values x and y,
- * `message_Equals(x, y)` must return true if and only if
- * `hashTableFunction_MessageNameEquals(y, x)` returns true.
- *
- * * It is transitive: for any non-null reference values x, y, and z, if
- * `hashTableFunction_MessageNameEquals(x, y)` returns true and
- * `hashTableFunction_MessageNameEquals(y, z)` returns true,
- * then `hashTableFunction_MessageNameEquals(x, z)` must return true.
- *
- * * It is consistent: for any non-null reference values x and y, multiple
- * invocations of `hashTableFunction_MessageNameEquals(x, y)` consistently
- * return true or consistently return false.
- *
- * * For any non-null reference value x,
- * `hashTableFunction_MessageNameEquals(x, NULL)` must return false.
- *
- * @param a A pointer to a `message` instance.
- * @param b A pointer to a `message` instance.
- * @return true if the names of the two `message` instances are equal.
- */
-bool hashTableFunction_MessageNameEquals(const void *messageA,
- const void *messageB);
-
-/**
- * @function hashTableFunction_NameHashCode
- * @abstract Computes the hash of the entire name in a message
- *
- * @param messageA is a message
- * @return A non-cryptographic hash of Name
- */
-HashCodeType hashTableFunction_MessageNameHashCode(const void *messageA);
-#endif // hashTableFunction_h \ No newline at end of file
diff --git a/hicn-light/src/hicn/processor/matchingRulesTable.c b/hicn-light/src/hicn/processor/matchingRulesTable.c
deleted file mode 100644
index e57239321..000000000
--- a/hicn-light/src/hicn/processor/matchingRulesTable.c
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <hicn/processor/hashTableFunction.h>
-#include <hicn/processor/matchingRulesTable.h>
-
-struct matching_rules_table {
- // using this wrapper we can manatain multiple hash tables indexed in
- // different ways
- // for now we use only a table indexed by name
-
- PARCHashCodeTable *tableByName;
- PARCHashCodeTable_Destroyer dataDestroyer;
-};
-
-static PARCHashCodeTable *matchingRulesTable_GetTableForMessage(
- const MatchingRulesTable *pit, const Message *interestMessage);
-
-// ======================================================================
-
-MatchingRulesTable *matchingRulesTable_Create(
- PARCHashCodeTable_Destroyer dataDestroyer) {
- size_t initialSize = 65535;
-
- MatchingRulesTable *table =
- parcMemory_AllocateAndClear(sizeof(MatchingRulesTable));
- parcAssertNotNull(table, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(MatchingRulesTable));
- table->dataDestroyer = dataDestroyer;
-
- table->tableByName = parcHashCodeTable_Create_Size(
- hashTableFunction_MessageNameEquals,
- hashTableFunction_MessageNameHashCode, NULL, dataDestroyer, initialSize);
-
- return table;
-}
-
-void matchingRulesTable_Destroy(MatchingRulesTable **tablePtr) {
- parcAssertNotNull(tablePtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*tablePtr,
- "Parameter must dereference to non-null pointer");
-
- MatchingRulesTable *table = *tablePtr;
-
- parcHashCodeTable_Destroy(&table->tableByName);
-
- parcMemory_Deallocate((void **)&table);
- *tablePtr = NULL;
-}
-
-void *matchingRulesTable_Get(const MatchingRulesTable *rulesTable,
- const Message *message) {
- parcAssertNotNull(rulesTable, "Parameter rulesTable must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
-
- PARCHashCodeTable *hashTable =
- matchingRulesTable_GetTableForMessage(rulesTable, message);
- return parcHashCodeTable_Get(hashTable, message);
-}
-
-PARCArrayList *matchingRulesTable_GetUnion(const MatchingRulesTable *table,
- const Message *message) {
- PARCArrayList *list = parcArrayList_Create_Capacity(NULL, NULL, 3);
-
- void *dataByName = parcHashCodeTable_Get(table->tableByName, message);
- if (dataByName) {
- parcArrayList_Add(list, dataByName);
- }
-
- return list;
-}
-
-void matchingRulesTable_RemoveFromBest(MatchingRulesTable *rulesTable,
- const Message *message) {
- parcAssertNotNull(rulesTable, "Parameter rulesTable must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
-
- PARCHashCodeTable *hashTable =
- matchingRulesTable_GetTableForMessage(rulesTable, message);
- parcHashCodeTable_Del(hashTable, message);
-}
-
-void matchingRulesTable_RemoveFromAll(MatchingRulesTable *rulesTable,
- const Message *message) {
- parcAssertNotNull(rulesTable, "Parameter rulesTable must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
-
- parcHashCodeTable_Del(rulesTable->tableByName, message);
-}
-
-bool matchingRulesTable_AddToBestTable(MatchingRulesTable *rulesTable,
- Message *key, void *data) {
- parcAssertNotNull(rulesTable, "Parameter rulesTable must be non-null");
- parcAssertNotNull(key, "Parameter key must be non-null");
- parcAssertNotNull(data, "Parameter data must be non-null");
-
- PARCHashCodeTable *hashTable =
- matchingRulesTable_GetTableForMessage(rulesTable, key);
-
- bool success = parcHashCodeTable_Add(hashTable, key, data);
-
- return success;
-}
-
-// ========================================================================================
-
-static PARCHashCodeTable *matchingRulesTable_GetTableForMessage(
- const MatchingRulesTable *pit, const Message *interestMessage) {
- PARCHashCodeTable *table;
- table = pit->tableByName;
-
- return table;
-}
diff --git a/hicn-light/src/hicn/processor/matchingRulesTable.h b/hicn-light/src/hicn/processor/matchingRulesTable.h
deleted file mode 100644
index 64a57d854..000000000
--- a/hicn-light/src/hicn/processor/matchingRulesTable.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.
- */
-
-/**
- * @header matchingRulesTable
- * @abstract A generic table (void *) that matches a Message
- * @discussion
- * Matching is done based on Name
- *
- * When used in the PIT, one calls
- * <code>matchingRulesTable_AddToBestTable()</code> to add an interest to the
- * "best" (i.e. most restrictive match) table, then calls
- * <code>matchingRulesTable_GetUnion()</code> on a content object to match
- * against all of them.
- *
- * When used in a ContentStore, one calls
- * <code>matchingRulesTable_AddToAllTables()</code> to index a Content Object in
- * all the tables. one then calls <code>matchingRulesTable_Get()</code> with an
- * Interest to do the "best" matching (i.e by hash first, then keyid, then just
- * by name).
- *
- */
-
-#ifndef matchingRulesTable_h
-#define matchingRulesTable_h
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_HashCodeTable.h>
-#include <hicn/core/message.h>
-
-struct matching_rules_table;
-typedef struct matching_rules_table MatchingRulesTable;
-
-/**
- * Creates a MatchigRulesTable and specifies the function to call to de-allocate
- * an entry
- *
- * The datadestroyer will be called when an entry is removed from a table. It
- * may be NULL.
- */
-MatchingRulesTable *matchingRulesTable_Create(
- PARCHashCodeTable_Destroyer dataDestroyer);
-
-/**
- * Destroys the table and removes all stored elements.
- *
- */
-void matchingRulesTable_Destroy(MatchingRulesTable **tablePtr);
-
-/**
- * @function matchingRulesTable_Get
- * @abstract Returns the data item that best matches the message.
- * @discussion
- * Indexed by NameAndContentObjectHash, NameAndKeyId, and Name, in that order.
- *
- * @return NULL if nothing matches, otherwise the stored value
- */
-void *matchingRulesTable_Get(const MatchingRulesTable *table,
- const Message *message);
-
-/**
- * @function matchingRulesTable_GetUnion
- * @abstract Returns matching data items from all index tables.
- * @discussion
- * The PARCArrayList does not have an item destructor, so destroying it will
- * not affect the underlying data.
- *
- * @return Will not be NULL, but may be empty
- */
-PARCArrayList *matchingRulesTable_GetUnion(const MatchingRulesTable *table,
- const Message *message);
-
-/**
- * @function matchingRulesTable_Add
- * @abstract Adds the data to the best table
- * @discussion
- * The key must be derived from the data and destroyed when the data is
- * destroyed. Only the data destroyer is called.
- *
- * No duplicates are allowed, will return false if not added.
- *
- * @return true if unique key and added, false if duplicate and no action taken.
- */
-bool matchingRulesTable_AddToBestTable(MatchingRulesTable *rulesTable,
- Message *key, void *data);
-
-/**
- * @function matchingRulesTable_Remove
- * @abstract Removes the matching entry from the best match table, calling the
- * destroyer on the data.
- */
-void matchingRulesTable_RemoveFromBest(MatchingRulesTable *rulesTable,
- const Message *message);
-
-/**
- * @function matchingRulesTable_RemoveFromAll
- * @abstract Removes the message from all tables
- */
-void matchingRulesTable_RemoveFromAll(MatchingRulesTable *rulesTable,
- const Message *message);
-#endif // matchingRulesTable_h
diff --git a/hicn-light/src/hicn/processor/messageProcessor.c b/hicn-light/src/hicn/processor/messageProcessor.c
deleted file mode 100644
index d3f07cbda..000000000
--- a/hicn-light/src/hicn/processor/messageProcessor.c
+++ /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/hicn-light/config.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Memory.h>
-#ifdef WITH_POLICY
-#include <parc/algol/parc_EventTimer.h>
-#ifdef WITH_MAPME
-#include <hicn/core/connection.h>
-#endif /* WITH_MAPME */
-#endif /* WITH_POLICY */
-#include <hicn/processor/messageProcessor.h>
-
-#include <hicn/processor/fib.h>
-#include <hicn/processor/pitStandard.h>
-
-#include <hicn/content_store/contentStoreInterface.h>
-#include <hicn/content_store/contentStoreLRU.h>
-
-#include <hicn/strategies/loadBalancer.h>
-#include <hicn/strategies/lowLatency.h>
-#include <hicn/strategies/rnd.h>
-#include <hicn/strategies/strategyImpl.h>
-
-#include <hicn/io/streamConnection.h>
-#include <hicn/io/udpListener.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/utils/commands.h>
-#include <hicn/utils/utils.h>
-
-#include <hicn/utils/address.h>
-#include <hicn/core/messageHandler.h>
-
-#ifdef WITH_POLICY
-#define STATS_INTERVAL 1000 /* ms */
-#endif /* WITH_POLICY */
-
-/*
- * 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.
- */
-typedef struct processor_stats {
- uint32_t countReceived;
- uint32_t countInterestsReceived;
- uint32_t countObjectsReceived;
-
- uint32_t countInterestsAggregated;
-
- uint32_t countDropped;
- uint32_t countInterestsDropped;
- uint32_t countDroppedNoRoute;
- uint32_t countDroppedNoReversePath;
-
- uint32_t countDroppedConnectionNotFound;
- uint32_t countObjectsDropped;
-
- uint32_t countSendFailures;
- uint32_t countInterestForwarded;
- uint32_t countObjectsForwarded;
- uint32_t countInterestsSatisfiedFromStore;
-
- uint32_t countDroppedNoHopLimit;
- uint32_t countDroppedZeroHopLimitFromRemote;
- uint32_t countDroppedZeroHopLimitToRemote;
-} _ProcessorStats;
-
-struct message_processor {
- Forwarder *forwarder;
- Logger *logger;
-
- PIT *pit;
- ContentStoreInterface *contentStore;
- FIB *fib;
-
- bool store_in_cache;
- bool serve_from_cache;
-
- _ProcessorStats stats;
-
-#ifdef WITH_POLICY
- void * timer;
-#endif /* WITH_POLICY */
-};
-
-static void messageProcessor_Drop(MessageProcessor *processor,
- Message *message);
-static void messageProcessor_ReceiveInterest(MessageProcessor *processor,
- Message *interestMessage);
-static void messageProcessor_ReceiveContentObject(MessageProcessor *processor,
- Message *objectMessage);
-static unsigned messageProcessor_ForwardToNexthops(MessageProcessor *processor,
- Message *message,
- const NumberSet *nexthops);
-
-static void messageProcessor_ForwardToInterfaceId(MessageProcessor *processor,
- Message *message,
- unsigned interfaceId);
-
-// ============================================================
-// Public API
-
-#ifdef WITH_POLICY
-static void
-messageProcessor_Tick(int fd, PARCEventType type, void *user_data)
-{
- MessageProcessor *processor = (MessageProcessor*)user_data;
- uint64_t now = (uint64_t)forwarder_GetTicks(processor->forwarder);
-
- /* Loop over FIB entries to compute statistics from counters */
- FibEntryList *fibList = forwarder_GetFibEntries(processor->forwarder);
-
- for (size_t i = 0; i < fibEntryList_Length(fibList); i++) {
- FibEntry *entry = (FibEntry *)fibEntryList_Get(fibList, i);
- fibEntry_UpdateStats(entry, now);
- }
-
- fibEntryList_Destroy(&fibList);
-}
-#endif /* WITH_POLICY */
-
-MessageProcessor *messageProcessor_Create(Forwarder *forwarder) {
- size_t objectStoreSize =
- configuration_GetObjectStoreSize(forwarder_GetConfiguration(forwarder));
-
- MessageProcessor *processor =
- parcMemory_AllocateAndClear(sizeof(MessageProcessor));
- parcAssertNotNull(processor, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(MessageProcessor));
- memset(processor, 0, sizeof(MessageProcessor));
-
- processor->forwarder = forwarder;
- processor->logger = logger_Acquire(forwarder_GetLogger(forwarder));
- processor->pit = pitStandard_Create(forwarder);
-
- processor->fib = fib_Create(forwarder);
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "MessageProcessor %p created", (void *)processor);
- }
-
- ContentStoreConfig contentStoreConfig = {
- .objectCapacity = objectStoreSize,
- };
-
- processor->contentStore =
- contentStoreLRU_Create(&contentStoreConfig, processor->logger);
-
- // the two flags for the cache are set to true by default. If the cache
- // is active it always work as expected unless the use modifies this
- // values using controller
- processor->store_in_cache = true;
- processor->serve_from_cache = true;
-
-#ifdef WITH_POLICY
- /* Create statistics timer */
- Dispatcher *dispatcher = forwarder_GetDispatcher(forwarder);
- if (!dispatcher)
- goto ERR;
- processor->timer = dispatcher_CreateTimer(dispatcher, /* repeat */ true,
- messageProcessor_Tick, processor);
- if (!processor->timer)
- goto ERR;
- struct timeval timeout = {STATS_INTERVAL / 1000, (STATS_INTERVAL % 1000) * 1000};
- dispatcher_StartTimer(dispatcher, processor->timer, &timeout);
-ERR:
-#endif /* WITH_POLICY */
-
- return processor;
-}
-
-void messageProcessor_SetContentObjectStoreSize(
- MessageProcessor *processor, size_t maximumContentStoreSize) {
- parcAssertNotNull(processor, "Parameter processor must be non-null");
- contentStoreInterface_Release(&processor->contentStore);
-
- ContentStoreConfig contentStoreConfig = {.objectCapacity =
- maximumContentStoreSize};
-
- processor->contentStore =
- contentStoreLRU_Create(&contentStoreConfig, processor->logger);
-}
-
-void messageProcessor_ClearCache(MessageProcessor *processor) {
- parcAssertNotNull(processor, "Parameter processor must be non-null");
- size_t objectStoreSize = configuration_GetObjectStoreSize(
- forwarder_GetConfiguration(processor->forwarder));
-
- contentStoreInterface_Release(&processor->contentStore);
-
- ContentStoreConfig contentStoreConfig = {
- .objectCapacity = objectStoreSize,
- };
-
- processor->contentStore =
- contentStoreLRU_Create(&contentStoreConfig, processor->logger);
-}
-
-ContentStoreInterface *messageProcessor_GetContentObjectStore(
- const MessageProcessor *processor) {
- parcAssertNotNull(processor, "Parameter processor must be non-null");
- return processor->contentStore;
-}
-
-void messageProcessor_Destroy(MessageProcessor **processorPtr) {
- parcAssertNotNull(processorPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*processorPtr, "Parameter dereference to non-null pointer");
-
- MessageProcessor *processor = *processorPtr;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "MessageProcessor %p destroyed", (void *)processor);
- }
-
- logger_Release(&processor->logger);
- fib_Destroy(&processor->fib);
- contentStoreInterface_Release(&processor->contentStore);
- pit_Release(&processor->pit);
-
-#ifdef WITH_POLICY
- Dispatcher *dispatcher = forwarder_GetDispatcher(processor->forwarder);
- if (!dispatcher)
- goto ERR;
- dispatcher_StopTimer(dispatcher, processor->timer);
- dispatcher_DestroyTimerEvent(dispatcher, (PARCEventTimer**)&processor->timer);
-ERR:
-#endif /* WITH_POLICY */
-
- parcMemory_Deallocate((void **)&processor);
- *processorPtr = NULL;
-}
-
-void messageProcessor_Receive(MessageProcessor *processor, Message *message) {
- parcAssertNotNull(processor, "Parameter processor must be non-null");
- parcAssertNotNull(message, "Parameter message must be non-null");
-
- processor->stats.countReceived++;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- char *nameString = name_ToString(message_GetName(message));
- logger_Log(processor->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "Message %p ingress %3u length %5u received name %s",
- (void *)message, message_GetIngressConnectionId(message),
- message_Length(message), nameString);
- parcMemory_Deallocate((void **)&nameString);
- }
-
- switch (message_GetType(message)) {
- case MessagePacketType_Interest:
- messageProcessor_ReceiveInterest(processor, message);
- break;
-
- case MessagePacketType_ContentObject:
- messageProcessor_ReceiveContentObject(processor, message);
- break;
-
- default:
- messageProcessor_Drop(processor, message);
- break;
- }
-
- // if someone wanted to save it, they made a copy
- message_Release(&message);
-}
-
-bool messageProcessor_AddOrUpdateRoute(MessageProcessor *processor,
- add_route_command *control,
- unsigned ifidx) {
- Configuration *config = forwarder_GetConfiguration(processor->forwarder);
-
- char *prefixStr = (char *) utils_PrefixLenToString(
- control->addressType, &control->address, &control->len);
- strategy_type fwdStrategy =
- configuration_GetForwardingStrategy(config, prefixStr);
-
- Name *prefix = name_CreateFromAddress(control->addressType, control->address,
- control->len);
- FibEntry *entry = fib_Contains(processor->fib, prefix);
- if (entry != NULL) {
- fibEntry_AddNexthop(entry, ifidx);
- } else {
-#ifdef WITH_POLICY
- entry = fibEntry_Create(prefix, fwdStrategy, processor->forwarder);
-#else
- entry = fibEntry_Create(prefix, fwdStrategy);
-#endif /* WITH_POLICY */
- fibEntry_AddNexthop(entry, ifidx);
- fib_Add(processor->fib, entry);
- }
-
- free(prefixStr);
- name_Release(&prefix);
-
- return true;
-}
-
-bool messageProcessor_RemoveRoute(MessageProcessor *processor,
- remove_route_command *control,
- unsigned ifidx) {
- Name *name = name_CreateFromAddress(control->addressType, control->address,
- control->len);
- fib_Remove(processor->fib, name, ifidx);
- name_Release(&name);
-
- return true;
-}
-
-#ifdef WITH_POLICY
-
-bool messageProcessor_AddOrUpdatePolicy(MessageProcessor *processor,
- add_policy_command *control) {
- Configuration *config = forwarder_GetConfiguration(processor->forwarder);
-
- const char *prefixStr = utils_PrefixLenToString(
- control->addressType, &control->address, &control->len);
-
- Name *prefix = name_CreateFromAddress(control->addressType, control->address,
- control->len);
- FibEntry *entry = fib_Contains(processor->fib, prefix);
- if (!entry) {
- strategy_type fwdStrategy =
- configuration_GetForwardingStrategy(config, prefixStr);
- entry = fibEntry_Create(prefix, fwdStrategy, processor->forwarder);
- fib_Add(processor->fib, entry);
- }
- fibEntry_SetPolicy(entry, control->policy);
-
- name_Release(&prefix);
-
- return true;
-}
-
-bool messageProcessor_RemovePolicy(MessageProcessor *processor,
- remove_policy_command *control) {
- Name *prefix = name_CreateFromAddress(control->addressType, control->address,
- control->len);
- FibEntry *entry = fib_Contains(processor->fib, prefix);
- name_Release(&prefix);
-
- if (!entry)
- return false;
-
- fibEntry_SetPolicy(entry, POLICY_NONE);
-
- return true;
-}
-
-#endif /* WITH_POLICY */
-
-void messageProcessor_RemoveConnectionIdFromRoutes(MessageProcessor *processor,
- unsigned connectionId) {
- fib_RemoveConnectionId(processor->fib, connectionId);
-}
-
-void processor_SetStrategy(MessageProcessor *processor, Name *prefix,
- strategy_type strategy,
- unsigned related_prefixes_len,
- Name **related_prefixes){
- FibEntry *entry = fib_Contains(processor->fib, prefix);
- if (entry != NULL) {
- fibEntry_SetStrategy(entry, strategy, related_prefixes_len,
- related_prefixes);
- }
-}
-
-FibEntryList *messageProcessor_GetFibEntries(MessageProcessor *processor) {
- parcAssertNotNull(processor, "Parameter processor must be non-null");
- return fib_GetEntries(processor->fib);
-}
-
-// ============================================================
-// Internal API
-
-/**
- * @function messageProcessor_Drop
- * @abstract Whenever we "drop" a message, increment countes
- * @discussion
- * This is a bookkeeping function. It increments the appropriate counters.
- *
- * The default action for a message is to destroy it in
- * <code>messageProcessor_Receive()</code>, so this function does not need to do
- * that.
- *
- */
-static void messageProcessor_Drop(MessageProcessor *processor,
- Message *message) {
- processor->stats.countDropped++;
-
- switch (message_GetType(message)) {
- case MessagePacketType_Interest:
- processor->stats.countInterestsDropped++;
- break;
-
- case MessagePacketType_ContentObject:
- processor->stats.countObjectsDropped++;
- break;
-
- default:
- break;
- }
-
- // dont destroy message here, its done at end of receive
-}
-
-/**
- * @function messageProcessor_AggregateInterestInPit
- * @abstract Try to aggregate the interest in the PIT
- * @discussion
- * Tries to aggregate the interest with another interest.
- *
- * @return true if interest aggregagted (no more forwarding needed), false if
- * need to keep processing it.
- */
-#ifdef WITH_POLICY
-static PITVerdict messageProcessor_AggregateInterestInPit(MessageProcessor *processor,
- Message *interestMessage) {
-#else
-static bool messageProcessor_AggregateInterestInPit(MessageProcessor *processor,
- Message *interestMessage) {
-#endif /* WITH_POLICY */
- PITVerdict verdict = pit_ReceiveInterest(processor->pit, interestMessage);
-
- if (verdict == PITVerdict_Aggregate) {
- // PIT has it, we're done
- processor->stats.countInterestsAggregated++;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(
- processor->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "Message %p aggregated in PIT (aggregated count %u)",
- (void *)interestMessage, processor->stats.countInterestsAggregated);
- }
-
- return true;
- }
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(
- processor->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "Message %p not aggregated in PIT (aggregated count %u)",
- (void *)interestMessage, processor->stats.countInterestsAggregated);
- }
-
- return false;
-}
-
-static bool _satisfyFromContentStore(MessageProcessor *processor,
- Message *interestMessage) {
- bool result = false;
-
- if (message_GetInterestLifetimeTicks(interestMessage) == 0) {
- return false;
- }
-
- if (!processor->serve_from_cache) {
- return result;
- }
-
- // See if there's a match in the store.
- Message *objectMessage = contentStoreInterface_MatchInterest(
- processor->contentStore, interestMessage,
- forwarder_GetTicks(processor->forwarder));
-
- if (objectMessage != NULL) {
- // Remove it from the PIT. nexthops is allocated, so need to destroy
- NumberSet *nexthops = pit_SatisfyInterest(processor->pit, objectMessage);
- parcAssertNotNull(
- nexthops,
- "Illegal state: got a null nexthops for an interest we just inserted.");
-
- // send message in reply, then done
- processor->stats.countInterestsSatisfiedFromStore++;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug, __func__,
- "Message %p satisfied from content store (satisfied count %u)",
- (void *)interestMessage,
- processor->stats.countInterestsSatisfiedFromStore);
- }
-
- message_ResetPathLabel(objectMessage);
-
- messageProcessor_ForwardToNexthops(processor, objectMessage, nexthops);
- numberSet_Release(&nexthops);
-
- result = true;
- }
-
- return result;
-}
-
-/**
- * @function messageProcessor_ForwardViaFib
- * @abstract Try to forward the interest via the FIB
- * @discussion
- * This calls <code>messageProcessor_ForwardToNexthops()</code>, so if we find
- * any nexthops, the interest will be sent on its way. Depending on the
- * IoOperations of each nexthop, it may be a deferred write and bump up the
- * <code>interestMessage</code> refernce count, or it may copy the data out.
- *
- * A TRUE return means we did our best to forward it via the routes. If those
- * routes are actually down or have errors, we still return TRUE. A FALSE
- * return means there were no routes to try.
- *
- * @return true if we found a route and tried to forward it, false if no route
- */
-#ifdef WITH_POLICY
-static bool messageProcessor_ForwardViaFib(MessageProcessor *processor,
- Message *interestMessage, PITVerdict verdict) {
-#else
-static bool messageProcessor_ForwardViaFib(MessageProcessor *processor,
- Message *interestMessage) {
-#endif /* WITH_POLICY */
- FibEntry *fibEntry = fib_MatchMessage(processor->fib, interestMessage);
- if (fibEntry == NULL) {
- return false;
- }
-
- if(messageHandler_IsAProbe(message_FixedHeader(interestMessage))){
- bool reply_to_probe = false;
- ConnectionTable * ct = forwarder_GetConnectionTable(processor->forwarder);
- const NumberSet * nexthops = fibEntry_GetNexthops(fibEntry);
- unsigned size = (unsigned) numberSet_Length(nexthops);
-
- for (unsigned i = 0; i < size; i++) {
- unsigned nhop = numberSet_GetItem(nexthops, i);
- Connection *conn =
- (Connection *)connectionTable_FindById(ct, nhop);
- if (!conn)
- continue;
- bool isLocal = connection_IsLocal(conn);
- if(isLocal){
- Connection * replyConn =
- (Connection *)connectionTable_FindById(ct,
- message_GetIngressConnectionId(interestMessage));
- connection_HandleProbe(replyConn,
- (uint8_t *) message_FixedHeader(interestMessage));
- reply_to_probe = true;
- break;
- }
- }
- if(reply_to_probe)
- return false;
- }
-
-
- PitEntry *pitEntry = pit_GetPitEntry(processor->pit, interestMessage);
- if (pitEntry == NULL) {
- return false;
- }
-
- pitEntry_AddFibEntry(pitEntry, fibEntry);
-
- NumberSet *nexthops = (NumberSet *)fibEntry_GetNexthopsFromForwardingStrategy(
-#ifdef WITH_POLICY
- fibEntry, interestMessage, verdict);
-#else
- fibEntry, interestMessage);
-#endif /* WITH_POLICY */
-
- // this requires some additional checks. It may happen that some of the output
- // faces selected by the forwarding strategy are not usable. So far all the
- // forwarding strategy return only valid faces (or an empty list)
- for (unsigned i = 0; i < numberSet_Length(nexthops); i++) {
- pitEntry_AddEgressId(pitEntry, numberSet_GetItem(nexthops, i));
- }
-
- // The function GetPitEntry encreases the ref counter in the pit entry
- // we need to decrease it
- pitEntry_Release(&pitEntry);
-
- if (messageProcessor_ForwardToNexthops(processor, interestMessage, nexthops) >
- 0) {
- numberSet_Release(&nexthops);
- return true;
- } else {
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug, __func__,
- "Message %p returned an emtpy next hop set",
- (void *)interestMessage);
- }
- }
-
- numberSet_Release(&nexthops);
- return false;
-}
-
-/**
- * @function messageProcessor_ReceiveInterest
- * @abstract Receive an interest from the network
- * @discussion
- * (1) if interest in the PIT, aggregate in PIT
- * (2) if interest in the ContentStore, reply
- * (3) if in the FIB, forward
- * (4) drop
- *
- */
-static void messageProcessor_ReceiveInterest(MessageProcessor *processor,
- Message *interestMessage) {
- processor->stats.countInterestsReceived++;
-
- // (1) Try to aggregate in PIT
-#ifdef WITH_POLICY
- PITVerdict verdict = messageProcessor_AggregateInterestInPit(processor, interestMessage);
- switch(verdict) {
- case PITVerdict_Aggregate:
- //done
- return;
-
- case PITVerdict_Forward:
- case PITVerdict_Retransmit:
- break;
- }
-#else
- if (messageProcessor_AggregateInterestInPit(processor, interestMessage)) {
- // done
- return;
- }
-#endif /* WITH_POLICY */
-
- // At this point, we just created a PIT entry. If we don't forward the
- // interest, we need to remove the PIT entry.
-
- // (2) Try to satisfy from content store
- if (_satisfyFromContentStore(processor, interestMessage)) {
- // done
- // If we found a content object in the CS,
- // messageProcess_SatisfyFromContentStore already cleared the PIT state
- return;
- }
-
- // (3) Try to forward it
-#ifdef WITH_POLICY
- if (messageProcessor_ForwardViaFib(processor, interestMessage, verdict)) {
-#else
- if (messageProcessor_ForwardViaFib(processor, interestMessage)) {
-#endif /* WITH_POLICY */
- // done
- return;
- }
-
- // Remove the PIT entry?
- processor->stats.countDroppedNoRoute++;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "Message %p did not match FIB, no route (count %u)",
- (void *)interestMessage, processor->stats.countDroppedNoRoute);
- }
-
- messageProcessor_Drop(processor, interestMessage);
-}
-
-/**
- * @function messageProcessor_ReceiveContentObject
- * @abstract Process an in-bound content object
- * @discussion
- * (1) If it does not match anything in the PIT, drop it
- * (2) Add to Content Store
- * (3) Reverse path forward via PIT entries
- *
- * @param <#param1#>
- */
-static void messageProcessor_ReceiveContentObject(MessageProcessor *processor,
- Message *message) {
- processor->stats.countObjectsReceived++;
-
- NumberSet *ingressSetUnion = pit_SatisfyInterest(processor->pit, message);
-
- if (numberSet_Length(ingressSetUnion) == 0) {
- // (1) If it does not match anything in the PIT, drop it
- processor->stats.countDroppedNoReversePath++;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug, __func__,
- "Message %p did not match PIT, no reverse path (count %u)",
- (void *)message, processor->stats.countDroppedNoReversePath);
- }
-
- //if the packet is a probe we need to analyze it
- if(messageHandler_IsAProbe(message_FixedHeader(message))){
- FibEntry *fibEntry = fib_MatchMessage(processor->fib, message);
- if(fibEntry &&
- fibEntry_GetFwdStrategyType(fibEntry) == SET_STRATEGY_LOW_LATENCY){
- unsigned connid = message_GetIngressConnectionId(message);
- NumberSet *outFace = numberSet_Create();
- numberSet_Add(outFace, connid);
- fibEntry_ReceiveObjectMessage(fibEntry, outFace, message, 0,
- forwarder_GetTicks(processor->forwarder));
- numberSet_Release(&(outFace));
- }
- }
-
- // we store the packets in the content store enven in the case where there
- // is no match in the PIT table in this way the applications can push the
- // content in the CS of the forwarder. We allow this only for local faces
- bool isLocal = connection_IsLocal(connectionTable_FindById(
- forwarder_GetConnectionTable(processor->forwarder),
- message_GetIngressConnectionId((const Message *)message)));
- if (processor->store_in_cache && isLocal) {
- uint64_t currentTimeTicks = forwarder_GetTicks(processor->forwarder);
- contentStoreInterface_PutContent(processor->contentStore, message,
- currentTimeTicks);
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug, __func__,
- "Message %p sotred in the CS anyway", (void *)message);
- }
- }
-
- messageProcessor_Drop(processor, message);
- } else {
- // (2) Add to Content Store. Store may remove expired content, if necessary,
- // depending on store policy.
- if (processor->store_in_cache) {
- uint64_t currentTimeTicks = forwarder_GetTicks(processor->forwarder);
- contentStoreInterface_PutContent(processor->contentStore, message,
- currentTimeTicks);
- }
- // (3) Reverse path forward via PIT entries
- messageProcessor_ForwardToNexthops(processor, message, ingressSetUnion);
-
- }
-
- numberSet_Release(&ingressSetUnion);
-}
-
-/**
- * @function messageProcessor_ForwardToNexthops
- * @abstract Try to forward to each nexthop listed in the NumberSet
- * @discussion
- * Will not forward to the ingress connection.
- *
- * @return The number of nexthops tried
- */
-static unsigned messageProcessor_ForwardToNexthops(MessageProcessor *processor,
- Message *message,
- const NumberSet *nexthops) {
- unsigned forwardedCopies = 0;
-
- size_t length = numberSet_Length(nexthops);
-
- unsigned ingressId = message_GetIngressConnectionId(message);
- uint32_t old_path_label = 0;
-
- if (message_GetType(message) == MessagePacketType_ContentObject) {
- old_path_label = message_GetPathLabel(message);
- }
-
- for (size_t i = 0; i < length; i++) {
- unsigned egressId = numberSet_GetItem(nexthops, i);
- if (egressId != ingressId) {
- forwardedCopies++;
- messageProcessor_ForwardToInterfaceId(processor, message, egressId);
-
- if (message_GetType(message) == MessagePacketType_ContentObject) {
- // everytime we send out a message we need to restore the original path
- // label of the message this is important because we keep a single copy
- // of the message (single pointer) and we modify the path label at each
- // send.
- message_SetPathLabel(message, old_path_label);
- }
- }
- }
- return forwardedCopies;
-}
-
-/**
- * caller has checked that the hop limit is ok. Try to send out the connection.
- */
-static void messageProcessor_SendWithGoodHopLimit(MessageProcessor *processor,
- Message *message,
- unsigned interfaceId,
- const Connection *conn) {
- bool success = connection_Send(conn, message);
- if (success) {
- switch (message_GetType(message)) {
- case MessagePacketType_Interest:
- processor->stats.countInterestForwarded++;
- break;
-
- case MessagePacketType_ContentObject:
- processor->stats.countObjectsForwarded++;
- break;
-
- default:
- break;
- }
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(
- processor->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "forward message %p to interface %u (int %u, obj %u)",
- (void *)message, interfaceId, processor->stats.countInterestForwarded,
- processor->stats.countObjectsForwarded);
- }
- } else {
- processor->stats.countSendFailures++;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug, __func__,
- "forward message %p to interface %u send failure (count %u)",
- (void *)message, interfaceId,
- processor->stats.countSendFailures);
- }
- messageProcessor_Drop(processor, message);
- }
-}
-
-/*
- * If the hoplimit is equal to 0, then we may only forward it to local
- * applications. Otherwise, we may forward it off the system.
- *
- */
-static void messageProcessor_ForwardToInterfaceId(MessageProcessor *processor,
- Message *message,
- unsigned interfaceId) {
- ConnectionTable *connectionTable =
- forwarder_GetConnectionTable(processor->forwarder);
- const Connection *conn =
- connectionTable_FindById(connectionTable, interfaceId);
-
- if (conn != NULL) {
- messageProcessor_SendWithGoodHopLimit(processor, message, interfaceId,
- conn);
- } else {
- processor->stats.countDroppedConnectionNotFound++;
-
- if (logger_IsLoggable(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(processor->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug, __func__,
- "forward message %p to interface %u not found (count %u)",
- (void *)message, interfaceId,
- processor->stats.countDroppedConnectionNotFound);
- }
-
- messageProcessor_Drop(processor, message);
- }
-}
-
-void messageProcessor_SetCacheStoreFlag(MessageProcessor *processor, bool val) {
- processor->store_in_cache = val;
-}
-
-bool messageProcessor_GetCacheStoreFlag(MessageProcessor *processor) {
- return processor->store_in_cache;
-}
-
-void messageProcessor_SetCacheServeFlag(MessageProcessor *processor, bool val) {
- processor->serve_from_cache = val;
-}
-
-bool messageProcessor_GetCacheServeFlag(MessageProcessor *processor) {
- return processor->serve_from_cache;
-}
-
-#ifdef WITH_MAPME
-
-FIB *messageProcessor_getFib(MessageProcessor *processor) {
- return processor->fib;
-}
-
-#endif /* WITH_MAPME */
diff --git a/hicn-light/src/hicn/processor/messageProcessor.h b/hicn-light/src/hicn/processor/messageProcessor.h
deleted file mode 100644
index 6a863aa38..000000000
--- a/hicn-light/src/hicn/processor/messageProcessor.h
+++ /dev/null
@@ -1,206 +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.
- */
-
-/**
- * @file messageProcessor.h
- * @brief Executes the set of rules dictated by the PacketType
- *
- * This is a "run-to-completion" handling of a message based on the PacketType.
- *
- * The MessageProcessor also owns the PIT and FIB tables.
- *
- */
-
-#ifndef messageProcessor_h
-#define messageProcessor_h
-
-#include <hicn/content_store/contentStoreInterface.h>
-#include <hicn/core/forwarder.h>
-#include <hicn/core/message.h>
-
-#include <hicn/utils/commands.h>
-
-#ifdef WITH_POLICY
-#ifdef WITH_MAPME
-#include <hicn/core/connection.h>
-#endif /* WITH_MAPME */
-#endif /* WITH_POLICY */
-
-struct message_processor;
-typedef struct message_processor MessageProcessor;
-
-/**
- * Allocates a MessageProcessor along with PIT, FIB and ContentStore tables
- *
- * The hicn-light pointer is primarily used for logging (forwarder_Log), getting
- * the configuration, and accessing the connection table.
- *
- * @param [in] Pointer to owning hicn-light process
- *
- * @retval non-null An allocated message processor
- * @retval null An error
- *
- */
-MessageProcessor *messageProcessor_Create(Forwarder *forwarder);
-
-/**
- * Deallocates a message processor an all internal tables
- *
- * @param [in,out] processorPtr Pointer to message processor to de-allocate,
- * will be NULL'd.
- */
-void messageProcessor_Destroy(MessageProcessor **processorPtr);
-
-/**
- * @function messageProcessor_Receive
- * @abstract Process the message, takes ownership of the memory.
- * @discussion
- * Will call destroy on the memory when done with it, so if the caller wants
- * to keep it, make a reference counted copy.
- *
- * Receive may modify some fields in the message, such as the HopLimit field.
- */
-void messageProcessor_Receive(MessageProcessor *procesor, Message *message);
-
-/**
- * Adds or updates a route in the FIB
- *
- * If the route already exists, it is replaced
- *
- * @param [in] procesor An allocated message processor
- * @param [in] route The route to update
- *
- * @retval true added or updated
- * @retval false An error
- */
-bool messageProcessor_AddOrUpdateRoute(MessageProcessor *processor,
- add_route_command *control,
- unsigned ifidx);
-
-/**
- * Removes a route from the FIB
- *
- * Removes a specific nexthop for a route. If there are no nexthops left after
- * the removal, the entire route is deleted from the FIB.
- *
- * @param [in] procesor An allocated message processor
- * @param [in] route The route to remove
- *
- * @retval true Route completely removed
- * @retval false There is still a nexthop for the route
- */
-
-bool messageProcessor_RemoveRoute(MessageProcessor *processor,
- remove_route_command *control,
- unsigned ifidx);
-
-#ifdef WITH_POLICY
-
-/**
- * Adds or updates a policy in the FIB
- *
- * If the policy is already set, it is replaced
- *
- * @param [in] procesor An allocated message processor
- * @param [in] control Control message
- *
- * @retval true added or updated
- * @retval false An error
- */
-bool messageProcessor_AddOrUpdatePolicy(MessageProcessor *processor,
- add_policy_command *control);
-
-/**
- * Removes a policy from the FIB
- *
- * Reset the policy in the FIB to the default (empty) policy.
- *
- * @param [in] procesor An allocated message processor
- * @param [in] control Control message
- *
- * @retval true Policy completely removed
- * @retval false There is still a nexthop for the policy
- */
-bool messageProcessor_RemovePolicy(MessageProcessor *processor,
- remove_policy_command *control);
-
-#endif /* WITH_POLICY */
-
-/**
- * Removes a given connection id from all FIB entries
- *
- * Iterates the FIB and removes the given connection ID from every route.
- */
-void messageProcessor_RemoveConnectionIdFromRoutes(MessageProcessor *processor,
- unsigned connectionId);
-
-/**
- * Returns a list of all FIB entries
- *
- * You must destroy the list.
- *
- * @retval non-null The list of FIB entries
- * @retval null An error
- */
-FibEntryList *messageProcessor_GetFibEntries(MessageProcessor *processor);
-
-/**
- * Adjusts the ContentStore to the given size.
- *
- * This will destroy and re-create the content store, so any cached objects will
- * be lost.
- *
- */
-void messageProcessor_SetContentObjectStoreSize(MessageProcessor *processor,
- size_t maximumContentStoreSize);
-
-/**
- * Return the interface to the currently instantiated ContentStore, if any.
- *
- * @param [in] processor the `MessageProcessor` from which to return the
- * ContentStoreInterface.
- *
- */
-ContentStoreInterface *messageProcessor_GetContentObjectStore(
- const MessageProcessor *processor);
-
-void messageProcessor_SetCacheStoreFlag(MessageProcessor *processor, bool val);
-
-bool messageProcessor_GetCacheStoreFlag(MessageProcessor *processor);
-
-void messageProcessor_SetCacheServeFlag(MessageProcessor *processor, bool val);
-
-bool messageProcessor_GetCacheServeFlag(MessageProcessor *processor);
-
-void messageProcessor_ClearCache(MessageProcessor *processor);
-
-void processor_SetStrategy(MessageProcessor *processor, Name *prefix,
- strategy_type strategy,
- unsigned related_prefixes_len,
- Name **related_prefixes);
-
-#ifdef WITH_MAPME
-
-/**
- * @function messageProcessor_getFib
- * @abstract Returns the hICN processor's FIB.
- * @param [in] forwarder - Pointer to the hICN processor.
- * @returns Pointer to the hICN FIB.
- */
-FIB *messageProcessor_getFib(MessageProcessor *processor);
-
-#endif /* WITH_MAPME */
-
-#endif // messageProcessor_h
diff --git a/hicn-light/src/hicn/processor/pit.c b/hicn-light/src/hicn/processor/pit.c
deleted file mode 100644
index 66ad85410..000000000
--- a/hicn-light/src/hicn/processor/pit.c
+++ /dev/null
@@ -1,45 +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.
- */
-
-/**
- * Generic interface to PIT table
- *
- */
-
-#include <parc/assert/parc_Assert.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/processor/pit.h>
-
-void *pit_Closure(const PIT *pit) { return pit->closure; }
-
-void pit_Release(PIT **pitPtr) { (*pitPtr)->release(pitPtr); }
-
-PITVerdict pit_ReceiveInterest(PIT *pit, Message *interestMessage) {
- return pit->receiveInterest(pit, interestMessage);
-}
-
-NumberSet *pit_SatisfyInterest(PIT *pit, const Message *objectMessage) {
- return pit->satisfyInterest(pit, objectMessage);
-}
-
-void pit_RemoveInterest(PIT *pit, const Message *interestMessage) {
- pit->removeInterest(pit, interestMessage);
-}
-
-PitEntry *pit_GetPitEntry(const PIT *pit, const Message *interestMessage) {
- return pit->getPitEntry(pit, interestMessage);
-}
diff --git a/hicn-light/src/hicn/processor/pit.h b/hicn-light/src/hicn/processor/pit.h
deleted file mode 100644
index 63a9b20e4..000000000
--- a/hicn-light/src/hicn/processor/pit.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file pit.h
- * @brief The Pending Interest Table interface
- *
- * Interface for implementing a PIT table
- *
- */
-
-#ifndef pit_h
-#define pit_h
-
-#include <hicn/core/forwarder.h>
-#include <hicn/core/message.h>
-#include <hicn/core/numberSet.h>
-#include <hicn/processor/pitEntry.h>
-#include <hicn/processor/pitVerdict.h>
-
-struct pit;
-typedef struct pit PIT;
-
-struct pit {
- void (*release)(PIT **pitPtr);
- PITVerdict (*receiveInterest)(PIT *pit, Message *interestMessage);
- NumberSet *(*satisfyInterest)(PIT *pit, const Message *objectMessage);
- void (*removeInterest)(PIT *pit, const Message *interestMessage);
- PitEntry *(*getPitEntry)(const PIT *pit, const Message *interestMessage);
- void *closure;
-};
-
-void *pit_Closure(const PIT *pit);
-
-/**
- * Destroys the PIT table and all entries contained in it.
- *
- * PIT entries are reference counted, so if the user has stored one outside the
- * PIT table it will still be valid.
- *
- * @param [in,out] pitPtr Double pointer to PIT table, will be NULLed
- */
-void pit_Release(PIT **pitPtr);
-
-/**
- * @function pit_ReceiveInterest
- * @abstract Receives an interest and adds to PIT table
- * @discussion
- * If not present, adds entry to the PIT table and returns
- * PIT_VERDICT_NEW_ENTRY. If present and aggregated, returns
- * PIT_VERDICT_EXISTING_ENTRY.
- *
- * Some aggregated interests may return PIT_VERDICT_NEW_ENTRY if the interest
- * needs to be forwarded again (e.g. the lifetime is extended).
- *
- * If the PIT stores the message in its table, it will store a reference
- * counted copy.
- *
- * @return Verdict of receiving the interest
- */
-PITVerdict pit_ReceiveInterest(PIT *pit, Message *interestMessage);
-
-/**
- * @function pit_SatisfyInterest
- * @abstract Tries to satisfy PIT entries based on the message, returning where
- * to send message
- * @discussion
- * If matching interests are in the PIT, will return the set of reverse
- * paths to use to forward the content object.
- *
- * The return value is allocated and must be destroyed.
- *
- * @return Set of ConnectionTable id's to forward the message, may be empty or
- * NULL. Must be destroyed.
- */
-NumberSet *pit_SatisfyInterest(PIT *pit, const Message *objectMessage);
-
-/**
- * @function pit_RemoveInterest
- * @abstract Unconditionally remove the interest from the PIT
- * @discussion
- * The PIT may store a specific name in several tables. This function will
- * remove the interest from the specific table it lives it. It will not
- * remove PIT entries in different tables with the same name.
- *
- * The different tables index interests based on their matching criteria,
- * such as by name, by name and keyid, etc.
- *
- */
-void pit_RemoveInterest(PIT *pit, const Message *interestMessage);
-
-/**
- * @function pit_GetPitEntry
- * @abstract Retrieve the best matching PIT entry for the message.
- * @discussion
- * Returns a reference counted copy of the entry, must call
- * <code>pitEntry_Destory()</code> on it.
- *
- * @return NULL if not in table, otherwise a reference counted copy of the entry
- */
-PitEntry *pit_GetPitEntry(const PIT *pit, const Message *interestMessage);
-#endif // pit_h
diff --git a/hicn-light/src/hicn/processor/pitEntry.c b/hicn-light/src/hicn/processor/pitEntry.c
deleted file mode 100644
index 99b3f1f2b..000000000
--- a/hicn-light/src/hicn/processor/pitEntry.c
+++ /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.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <hicn/core/numberSet.h>
-#include <hicn/processor/pitEntry.h>
-
-#include <parc/assert/parc_Assert.h>
-
-struct pit_entry {
- Message *message;
- NumberSet *ingressIdSet;
- NumberSet *egressIdSet;
-
- FibEntry *fibEntry;
-
- Ticks creationTime;
- Ticks expiryTime;
-
- unsigned refcount;
-};
-
-PitEntry *pitEntry_Create(Message *message, Ticks expiryTime,
- Ticks creationTime) {
- PitEntry *pitEntry = parcMemory_AllocateAndClear(sizeof(PitEntry));
- parcAssertNotNull(pitEntry, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(PitEntry));
- pitEntry->message = message;
- pitEntry->ingressIdSet = numberSet_Create();
- pitEntry->egressIdSet = numberSet_Create();
- pitEntry->refcount = 1;
-
- // add the message to the reverse path set
- numberSet_Add(pitEntry->ingressIdSet,
- message_GetIngressConnectionId(message));
-
- // hack in a 4-second timeout
- pitEntry->expiryTime = expiryTime;
- pitEntry->fibEntry = NULL;
-
- pitEntry->creationTime = creationTime;
- return pitEntry;
-}
-
-void pitEntry_Release(PitEntry **pitEntryPtr) {
- parcAssertNotNull(pitEntryPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*pitEntryPtr,
- "Parameter must dereference to non-null pointer");
-
- PitEntry *pitEntry = *pitEntryPtr;
- parcTrapIllegalValueIf(pitEntry->refcount == 0,
- "Illegal state: has refcount of 0");
-
- pitEntry->refcount--;
- if (pitEntry->refcount == 0) {
- if (pitEntry->fibEntry != NULL) {
- fibEntry_Release(&pitEntry->fibEntry);
- }
- numberSet_Release(&pitEntry->ingressIdSet);
- numberSet_Release(&pitEntry->egressIdSet);
- message_Release(&pitEntry->message);
- parcMemory_Deallocate((void **)&pitEntry);
- }
- *pitEntryPtr = NULL;
-}
-
-PitEntry *pitEntry_Acquire(PitEntry *original) {
- parcAssertNotNull(original, "Parameter original must be non-null");
- original->refcount++;
- return original;
-}
-
-void pitEntry_AddIngressId(PitEntry *pitEntry, unsigned ingressId) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- numberSet_Add(pitEntry->ingressIdSet, ingressId);
-}
-
-void pitEntry_AddEgressId(PitEntry *pitEntry, unsigned egressId) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- numberSet_Add(pitEntry->egressIdSet, egressId);
-}
-
-void pitEntry_AddFibEntry(PitEntry *pitEntry, FibEntry *fibEntry) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- parcAssertNotNull(fibEntry, "Parameter fibEntry must be non-null");
- // the fibEntry should be always the same for all the interests in the same
- // pitEntry
- if (pitEntry->fibEntry == NULL) {
- fibEntry_Acquire(fibEntry);
- pitEntry->fibEntry = fibEntry;
- }
-}
-
-FibEntry *pitEntry_GetFibEntry(PitEntry *pitEntry) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- return pitEntry->fibEntry;
-}
-
-Ticks pitEntry_GetExpiryTime(const PitEntry *pitEntry) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- return pitEntry->expiryTime;
-}
-
-Ticks pitEntry_GetCreationTime(const PitEntry *pitEntry) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- return pitEntry->creationTime;
-}
-
-void pitEntry_SetExpiryTime(PitEntry *pitEntry, Ticks expiryTime) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- pitEntry->expiryTime = expiryTime;
-}
-
-const NumberSet *pitEntry_GetIngressSet(const PitEntry *pitEntry) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- return pitEntry->ingressIdSet;
-}
-
-const NumberSet *pitEntry_GetEgressSet(const PitEntry *pitEntry) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- return pitEntry->egressIdSet;
-}
-
-Message *pitEntry_GetMessage(const PitEntry *pitEntry) {
- parcAssertNotNull(pitEntry, "Parameter pitEntry must be non-null");
- return message_Acquire(pitEntry->message);
-}
diff --git a/hicn-light/src/hicn/processor/pitEntry.h b/hicn-light/src/hicn/processor/pitEntry.h
deleted file mode 100644
index 3cd5821bc..000000000
--- a/hicn-light/src/hicn/processor/pitEntry.h
+++ /dev/null
@@ -1,164 +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.
- */
-
-/**
- * @file pitEntry.h
- * @brief The embodiment of a PIT entry
- *
- * Embodies a PIT entry
- *
- */
-
-#ifndef pitEntry_h
-#define pitEntry_h
-
-#include <hicn/core/message.h>
-#include <hicn/core/numberSet.h>
-#include <hicn/core/ticks.h>
-#include <hicn/processor/fibEntry.h>
-
-struct pit_entry;
-typedef struct pit_entry PitEntry;
-
-/**
- * @function pitEntry_Create
- * @abstract Takes ownership of the message inside the PitEntry
- * @discussion
- * When the PIT entry is destroyed, will call <code>message_Release()</code>
- * on the message.
- *
- */
-PitEntry *pitEntry_Create(Message *message, Ticks expiryTime,
- Ticks CreationTime);
-
-/**
- * Release a previously acquired reference to the specified instance,
- * decrementing the reference count for the instance.
- *
- * The pointer to the instance is set to NULL as a side-effect of this function.
- *
- * If the invocation causes the last reference to the instance to be released,
- * the instance is deallocated and the instance's implementation will perform
- * additional cleanup and release other privately held references.
- *
- * @param [in,out] pitEntryPtr A pointer to a PitEntry instance pointer, which
- * will be set to zero on return.
- *
- */
-void pitEntry_Release(PitEntry **pitEntryPtr);
-
-/**
- * @function pitEntry_Acquire
- * @abstract Returns a reference counted copy
- * @discussion
- * A reference counted copy that shares the same state as the original.
- * Caller must use <code>pitEntry_Release()</code> on it when done.
- *
- * @return A reference counted copy, use Destroy on it.
- */
-PitEntry *pitEntry_Acquire(PitEntry *original);
-
-/**
- * @function pitEntry_AddIngressId
- * @abstract Add an ingress connection id to the list of reverse paths
- * @discussion
- * A PitEntry has two NumberSets. The first is the set of ingress ports,
- * which make up the reverse path. The second is the set of egress ports, which
- * make up its forward path.
- *
- * This function tracks which reverse paths have sent us the interest.
- *
- * @param ingressId the reverse path
- */
-void pitEntry_AddIngressId(PitEntry *pitEntry, unsigned ingressId);
-
-/**
- * @function pitEntry_AddEgressId
- * @abstract Add an egress connection id to the list of attempted paths
- * @discussion
- * A PitEntry has two NumberSets. The first is the set of ingress ports,
- * which make up the reverse path. The second is the set of egress ports, which
- * make up its forward path.
- *
- * This function tracks which forward paths we've tried for the interest.
- *
- * @param egressId the forwarded path
- */
-void pitEntry_AddEgressId(PitEntry *pitEntry, unsigned egressId);
-
-void pitEntry_AddFibEntry(PitEntry *pitEntry, FibEntry *fibEntry);
-
-FibEntry *pitEntry_GetFibEntry(PitEntry *pitEntry);
-
-/**
- * @function pitEntry_GetIngressSet
- * @abstract The Ingress connection id set
- * @discussion
- * You must acquire a copy of the number set if you will store the result.
- * This is the internal reference.
- *
- * @return May be empty, will not be null. Must be destroyed.
- */
-const NumberSet *pitEntry_GetIngressSet(const PitEntry *pitEntry);
-
-/**
- * @function pitEntry_GetEgressSet
- * @abstract The Egress connection id set
- * @discussion
- * You must acquire a copy of the number set if you will store the result.
- * This is the internal reference.
- *
- * @param <#param1#>
- * @return May be empty, will not be null. Must be destroyed.
- */
-const NumberSet *pitEntry_GetEgressSet(const PitEntry *pitEntry);
-
-/**
- * @function pitEntry_GetMessage
- * @abstract Gets the interest underpinning the PIT entry
- * @discussion
- * A reference counted copy, call <code>Message_Release()</code> on it.
- *
- * @return A reference counted copy, call <code>Message_Release()</code> on it.
- */
-Message *pitEntry_GetMessage(const PitEntry *pitEntry);
-
-/**
- * Returns the time (in ticks) at which the PIT entry is no longer valid
- *
- * The ExpiryTime is computed when the PIT entry is added (or via
- * pitEntry_SetExpiryTime). It is the aboslute time (in Ticks) at which the Pit
- * entry is no longer valid.
- *
- * @param [in] PitEntry An allocated PIT entry
- *
- * @retval number The abosolute time (in Ticks) of the Expiry
- */
-Ticks pitEntry_GetExpiryTime(const PitEntry *pitEntry);
-
-Ticks pitEntry_GetCreationTime(const PitEntry *pitEntry);
-/**
- * Sets the ExpriyTime of the PIT entry to the given value
- *
- * It is probalby an error to set the expiryTime to a smaller value than
- * currently set to, but this is not enforced. PIT entries use lazy delete.
- *
- * @param [in] pitEntry The allocated PIT entry to modify
- * @param [in] expiryTime The new expiryTime (UTC in forwarder Ticks)
- *
- */
-void pitEntry_SetExpiryTime(PitEntry *pitEntry, Ticks expiryTime);
-
-#endif // pitEntry_h
diff --git a/hicn-light/src/hicn/processor/pitStandard.c b/hicn-light/src/hicn/processor/pitStandard.c
deleted file mode 100644
index 04d886261..000000000
--- a/hicn-light/src/hicn/processor/pitStandard.c
+++ /dev/null
@@ -1,305 +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 pending interest table.
- *
- * Interest aggregation strategy:
- * - The first Interest for a name is forwarded
- * - A second Interest for a name from a different reverse path may be
- * aggregated
- * - A second Interest for a name from an existing Interest is forwarded
- * - The Interest Lifetime is like a subscription time. A reverse path entry is
- * removed once the lifetime is exceeded.
- * - Whan an Interest arrives or is aggregated, the Lifetime for that reverse
- * hop is extended. As a simplification, we only keep a single lifetime not per
- * reverse hop.
- *
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#define __STDC_FORMAT_MACROS
-#include <inttypes.h>
-
-#include <hicn/processor/hashTableFunction.h>
-#include <hicn/processor/pit.h>
-
-#include <hicn/core/ticks.h>
-
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_HashCodeTable.h>
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/core/forwarder.h>
-
-#include <parc/assert/parc_Assert.h>
-
-struct standard_pit;
-typedef struct standard_pit StandardPIT;
-
-struct standard_pit {
- Forwarder *forwarder;
- Logger *logger;
- PARCHashCodeTable *table; // PIT indexed by name
-};
-
-static void _pit_StoreInTable(StandardPIT *pit, Message *interestMessage);
-
-static void _pit_PitEntryDestroyer(void **dataPtr) {
- pitEntry_Release((PitEntry **)dataPtr);
-}
-
-static bool _pit_IngressSetContains(PitEntry *pitEntry, unsigned connectionId) {
- const NumberSet *set = pitEntry_GetIngressSet(pitEntry);
- bool numberInSet = numberSet_Contains(set, connectionId);
- return numberInSet;
-}
-
-static Ticks _pit_CalculateLifetime(StandardPIT *pit,
- Message *interestMessage) {
- uint64_t interestLifetimeTicks =
- message_GetInterestLifetimeTicks(interestMessage);
- if (interestLifetimeTicks == 0) {
- interestLifetimeTicks = forwarder_NanosToTicks(4000000000ULL);
- }
-
- Ticks expiryTime = forwarder_GetTicks(pit->forwarder) + interestLifetimeTicks;
- return expiryTime;
-}
-
-static void _pit_StoreInTable(StandardPIT *pit, Message *interestMessage) {
- Message *key = message_Acquire(interestMessage);
-
- Ticks expiryTime = _pit_CalculateLifetime(pit, interestMessage);
-
- PitEntry *pitEntry =
- pitEntry_Create(key, expiryTime, forwarder_GetTicks(pit->forwarder));
-
- parcHashCodeTable_Add(pit->table, key, pitEntry);
-
- if (logger_IsLoggable(pit->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(pit->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__,
- "Message %p added to PIT (expiry %" PRIu64 ") ingress %u",
- (void *)interestMessage, pitEntry_GetExpiryTime(pitEntry),
- message_GetIngressConnectionId(interestMessage));
- }
-}
-
-static void _pit_ExtendLifetime(StandardPIT *pit, PitEntry *pitEntry,
- Message *interestMessage) {
- Ticks expiryTime = _pit_CalculateLifetime(pit, interestMessage);
-
- if (expiryTime > pitEntry_GetExpiryTime(pitEntry))
- pitEntry_SetExpiryTime(pitEntry, expiryTime);
-}
-
-// ======================================================================
-// Interface API
-
-static void _pitStandard_Destroy(PIT **pitPtr) {
- parcAssertNotNull(pitPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*pitPtr, "Parameter must dereference to non-null pointer");
-
- StandardPIT *pit = pit_Closure(*pitPtr);
-
- if (logger_IsLoggable(pit->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(pit->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "PIT %p destroyed", (void *)pit);
- }
-
- parcHashCodeTable_Destroy(&pit->table);
- logger_Release(&pit->logger);
- parcMemory_Deallocate(pitPtr);
-}
-
-static PITVerdict _pitStandard_ReceiveInterest(PIT *generic,
- Message *interestMessage) {
- parcAssertNotNull(generic, "Parameter pit must be non-null");
- parcAssertNotNull(interestMessage,
- "Parameter interestMessage must be non-null");
-
- StandardPIT *pit = pit_Closure(generic);
-
- PitEntry *pitEntry = parcHashCodeTable_Get(pit->table, interestMessage);
-
- if (pitEntry) {
- // has it expired?
- Ticks now = forwarder_GetTicks(pit->forwarder);
- if (now < pitEntry_GetExpiryTime(pitEntry)) {
- _pit_ExtendLifetime(pit, pitEntry, interestMessage);
-
- // Is the reverse path already in the PIT entry?
- if (_pit_IngressSetContains(
- pitEntry, message_GetIngressConnectionId(interestMessage))) {
- // It is already in the PIT entry, so this is a retransmission, so
- // forward it.
-
- if (logger_IsLoggable(pit->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(pit->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__,
- "Message %p existing entry (expiry %" PRIu64
- ") and reverse path, forwarding",
- (void *)interestMessage, pitEntry_GetExpiryTime(pitEntry));
- }
-#ifdef WITH_POLICY
- return PITVerdict_Retransmit;
-#else
- return PITVerdict_Forward;
-#endif /* WITH_POLICY */
- }
-
- // It is in the PIT but this is the first interest for the reverse path
- pitEntry_AddIngressId(pitEntry,
- message_GetIngressConnectionId(interestMessage));
-
- if (logger_IsLoggable(pit->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(pit->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__,
- "Message %p existing entry (expiry %" PRIu64
- ") and reverse path is new, aggregate",
- (void *)interestMessage, pitEntry_GetExpiryTime(pitEntry));
- }
-
- return PITVerdict_Aggregate;
- }
- // this is a timeout....
- FibEntry *fibEntry = pitEntry_GetFibEntry(pitEntry);
- if (fibEntry != NULL) {
- fibEntry_OnTimeout(fibEntry, pitEntry_GetEgressSet(pitEntry));
- }
-
- // it's an old entry, remove it
- parcHashCodeTable_Del(pit->table, interestMessage);
- }
-
- _pit_StoreInTable(pit, interestMessage);
-
- return PITVerdict_Forward;
-}
-
-static NumberSet *_pitStandard_SatisfyInterest(PIT *generic,
- const Message *objectMessage) {
- parcAssertNotNull(generic, "Parameter pit must be non-null");
- parcAssertNotNull(objectMessage, "Parameter objectMessage must be non-null");
-
- StandardPIT *pit = pit_Closure(generic);
-
- NumberSet *ingressSet = numberSet_Create();
-
- PitEntry *pitEntry = parcHashCodeTable_Get(pit->table, objectMessage);
- if (pitEntry) {
- // here we need to check if the PIT entry is expired
- // if so, remove the PIT entry.
- Ticks now = forwarder_GetTicks(pit->forwarder);
- if (now < pitEntry_GetExpiryTime(pitEntry)) {
- // PIT entry is not expired, use it
- FibEntry *fibEntry = pitEntry_GetFibEntry(pitEntry);
- if (fibEntry != NULL) {
- fibEntry_ReceiveObjectMessage(fibEntry, pitEntry_GetEgressSet(pitEntry),
- objectMessage,
- pitEntry_GetCreationTime(pitEntry),
- forwarder_GetTicks(pit->forwarder));
- }
- const NumberSet *is = pitEntry_GetIngressSet(pitEntry);
- numberSet_AddSet(ingressSet, is); // with this we do a copy so we can
- // remove the entry from the PIT
- }
- // remove the entry from the PIT. Key is a reference counted copy of the
- // pit entry message
- Message *key = pitEntry_GetMessage(pitEntry);
- parcHashCodeTable_Del(pit->table, key);
- message_Release(&key);
- }
-
- return ingressSet;
-}
-
-static void _pitStandard_RemoveInterest(PIT *generic,
- const Message *interestMessage) {
- parcAssertNotNull(generic, "Parameter pit must be non-null");
- parcAssertNotNull(interestMessage,
- "Parameter interestMessage must be non-null");
-
- StandardPIT *pit = pit_Closure(generic);
-
- if (logger_IsLoggable(pit->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(pit->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "Message %p removed from PIT",
- (void *)interestMessage);
- }
-
- parcHashCodeTable_Del(pit->table, interestMessage);
-}
-
-static PitEntry *_pitStandard_GetPitEntry(const PIT *generic,
- const Message *interestMessage) {
- parcAssertNotNull(generic, "Parameter pit must be non-null");
- parcAssertNotNull(interestMessage,
- "Parameter interestMessage must be non-null");
-
- StandardPIT *pit = pit_Closure(generic);
-
- PitEntry *entry = parcHashCodeTable_Get(pit->table, interestMessage);
- if (entry) {
- return pitEntry_Acquire(entry);
- }
- return NULL;
-}
-
-// ======================================================================
-// Public API
-
-PIT *pitStandard_Create(Forwarder *forwarder) {
- parcAssertNotNull(forwarder, "Parameter must be non-null");
-
- size_t allocation = sizeof(PIT) + sizeof(StandardPIT);
-
- PIT *generic = parcMemory_AllocateAndClear(allocation);
- parcAssertNotNull(generic, "parcMemory_AllocateAndClear(%zu) returned NULL",
- allocation);
- generic->closure = (uint8_t *)generic + sizeof(PIT);
-
- StandardPIT *pit = pit_Closure(generic);
- pit->forwarder = forwarder;
- pit->logger = logger_Acquire(forwarder_GetLogger(forwarder));
-
- size_t initialSize = 65535;
- pit->table =
- parcHashCodeTable_Create_Size(hashTableFunction_MessageNameEquals,
- hashTableFunction_MessageNameHashCode, NULL,
- _pit_PitEntryDestroyer, initialSize);
-
- if (logger_IsLoggable(pit->logger, LoggerFacility_Processor,
- PARCLogLevel_Debug)) {
- logger_Log(pit->logger, LoggerFacility_Processor, PARCLogLevel_Debug,
- __func__, "PIT %p created", (void *)pit);
- }
-
- generic->getPitEntry = _pitStandard_GetPitEntry;
- generic->receiveInterest = _pitStandard_ReceiveInterest;
- generic->release = _pitStandard_Destroy;
- generic->removeInterest = _pitStandard_RemoveInterest;
- generic->satisfyInterest = _pitStandard_SatisfyInterest;
-
- return generic;
-}
diff --git a/hicn-light/src/hicn/processor/pitVerdict.h b/hicn-light/src/hicn/processor/pitVerdict.h
deleted file mode 100644
index f37242027..000000000
--- a/hicn-light/src/hicn/processor/pitVerdict.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file pitVerdict.h
- * @brief Adding an entry to the PIT will return NEW or EXISTING
- *
- * Adding an entry to the PIT will return NEW or EXISTING
- *
- */
-
-#ifndef pitVerdict_h
-#define pitVerdict_h
-
-/**
- * @typedef PitVerdict
- * @abstract The verdit of the PIT for receiving a message
- * @constant PITVerdict_Forward The message made a new PIT entry, the interest
- * should be forwarded
- * @constant PITVerdict_Aggregate The Interest was aggregated in the PIT, does
- * not need to be forwarded
- */
-#ifdef WITH_POLICY
-typedef enum { PITVerdict_Forward, PITVerdict_Aggregate, PITVerdict_Retransmit } PITVerdict;
-#else
-typedef enum { PITVerdict_Forward, PITVerdict_Aggregate } PITVerdict;
-#endif /* WITH_POLICY */
-#endif // pitVerdict_h
diff --git a/hicn-light/src/hicn/socket/CMakeLists.txt b/hicn-light/src/hicn/socket/CMakeLists.txt
index 8c8a757fb..41dbd2342 100644
--- a/hicn-light/src/hicn/socket/CMakeLists.txt
+++ b/hicn-light/src/hicn/socket/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -25,11 +25,5 @@ if (UNIX AND NOT APPLE)
)
endif()
-set(TO_INSTALL_HEADER_FILES
- ${TO_INSTALL_HEADER_FILES}
- ${HEADER_FILES}
- PARENT_SCOPE
-)
-
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
diff --git a/hicn-light/src/hicn/socket/api.c b/hicn-light/src/hicn/socket/api.c
index 34c0aae54..db377aecd 100644
--- a/hicn-light/src/hicn/socket/api.c
+++ b/hicn-light/src/hicn/socket/api.c
@@ -10,8 +10,12 @@
#include <unistd.h> // close
#include "api.h"
-#include "error.h"
#include "ops.h"
+#include <hicn/util/sstrncpy.h>
+
+#if __linux__
+#include "error.h"
+#endif
#define INET_MAX_ADDRSTRLEN INET6_ADDRSTRLEN
@@ -39,7 +43,7 @@ static hicn_conf_t hicn_default_conf = {
struct ip_rule_state_ {
char tun_name[IF_NAMESIZE];
- ip_prefix_t prefix;
+ hicn_ip_prefix_t prefix;
uint32_t table_id;
uint8_t priority;
uint8_t address_family;
@@ -72,8 +76,7 @@ hicn_socket_helper_t *hicn_create() {
}
hicn->conf = malloc(sizeof(hicn_conf_t));
- if (hicn->conf < 0)
- goto ERR_CONF;
+ if (hicn->conf < 0) goto ERR_CONF;
memcpy(hicn->conf, &hicn_default_conf, sizeof(hicn_conf_t));
/* Initialize socket tree to empty */
@@ -133,20 +136,16 @@ void hicn_destroy() {
/* Restore default rules */
printf("Restoring default configuration.\n");
rc = ops.del_lo_prio_rule(NULL, AF_INET6, LOCAL_PRIORITY);
- if (rc < 0)
- ret = -1;
+ if (rc < 0) ret = -1;
rc = ops.del_lo_prio_rule(NULL, AF_INET, LOCAL_PRIORITY);
- if (rc < 0)
- ret = -1;
+ if (rc < 0) ret = -1;
rc = ops.add_lo_prio_rule(NULL, AF_INET6, 0);
- if (rc < 0)
- ret = -1;
+ if (rc < 0) ret = -1;
rc = ops.add_lo_prio_rule(NULL, AF_INET, 0);
- if (rc < 0)
- ret = -1;
+ if (rc < 0) ret = -1;
for (i = 0; i < rules_counter; i++) {
if (strcmp(rules_to_remove[i].tun_name, "NONE") != 0) {
@@ -158,20 +157,17 @@ void hicn_destroy() {
&rules_to_remove[i].prefix, rules_to_remove[i].address_family,
rules_to_remove[i].priority, rules_to_remove[i].table_id);
}
- if (rc < 0)
- ret = -1;
+ if (rc < 0) ret = -1;
}
for (i = 0; i < routes_counter; i++) {
rc = ops.del_out_route(routes_to_remove[i].remote_ip_address,
routes_to_remove[i].address_family,
routes_to_remove[i].table_id);
- if (rc < 0)
- ret = -1;
+ if (rc < 0) ret = -1;
}
- if (ret < 0)
- printf("Unexpected exit. Some state may not be deleted.\n");
+ if (ret < 0) printf("Unexpected exit. Some state may not be deleted.\n");
}
void hicn_free(hicn_socket_helper_t *hicn) {
@@ -197,7 +193,7 @@ int hicn_socket_cmp(hicn_socket_t *a, hicn_socket_t *b) {
return b->fd - a->fd;
}
-ip_prefix_t *hicn_socket_get_src_ip(hicn_socket_t *socket) {
+hicn_ip_prefix_t *hicn_socket_get_src_ip(hicn_socket_t *socket) {
if (socket->type != HS_CONNECTION) {
return NULL;
}
@@ -245,7 +241,8 @@ int hicn_set_local_endpoint(hicn_socket_t *socket, const char *local_ip_address,
*/
/* Copy the local IP address inside the connection */
- rc = ip_prefix_pton(local_ip_address, &socket->connection.tun_ip_address);
+ rc =
+ hicn_ip_prefix_pton(local_ip_address, &socket->connection.tun_ip_address);
if (rc < 0) {
rc = HICN_SOCKET_ERROR_SOCKET_LOCAL_REPR;
goto end;
@@ -255,14 +252,14 @@ end:
return rc;
}
-int hicn_get_local_address(const ip_prefix_t *remote_address,
- ip_prefix_t *local_address) {
+int hicn_get_local_address(const hicn_ip_prefix_t *remote_address,
+ hicn_ip_prefix_t *local_address) {
int rc = 0;
uint32_t interface_id;
- char remote_address_str[INET_MAX_ADDRSTRLEN + 4 ];
+ char remote_address_str[INET_MAX_ADDRSTRLEN + 4];
- rc = ip_prefix_ntop_short(remote_address, remote_address_str,
- sizeof(remote_address_str));
+ rc = hicn_ip_prefix_ntop_short(remote_address, remote_address_str,
+ sizeof(remote_address_str));
if (rc < 0) {
rc = HICN_SOCKET_ERROR_BIND_REMOTE_REPR;
goto ERR;
@@ -293,7 +290,7 @@ ERR:
int hicn_set_remote_endpoint(hicn_socket_t *socket,
const char *remote_ip_address) {
int af, rc = HICN_SOCKET_ERROR_NONE;
- ip_prefix_t addr;
+ hicn_ip_prefix_t addr;
af = get_addr_family(remote_ip_address);
if ((af != AF_INET6) && (af != AF_INET)) {
@@ -301,7 +298,7 @@ int hicn_set_remote_endpoint(hicn_socket_t *socket,
}
/* Bind local endpoint if not done yet */
- if (ip_prefix_empty(&socket->connection.tun_ip_address)) {
+ if (hicn_ip_prefix_empty(&socket->connection.tun_ip_address)) {
char local_ip_address[INET_MAX_ADDRSTRLEN + 4];
/* Local interface id */
@@ -331,7 +328,8 @@ int hicn_set_remote_endpoint(hicn_socket_t *socket,
/////
/* Convert to representation format */
- rc = ip_prefix_ntop_short(&addr, local_ip_address, sizeof(local_ip_address));
+ rc = hicn_ip_prefix_ntop_short(&addr, local_ip_address,
+ sizeof(local_ip_address));
if (rc < 0) {
rc = HICN_SOCKET_ERROR_BIND_REMOTE_REPR;
goto ERR;
@@ -448,8 +446,8 @@ int hicn_listen(hicn_socket_helper_t *hicn, int fd, const char *prefix) {
return rc;
}
- ip_prefix_t ip_prefix;
- rc = ip_prefix_pton(prefix, &ip_prefix);
+ hicn_ip_prefix_t hicn_ip_prefix;
+ rc = hicn_ip_prefix_pton(prefix, &hicn_ip_prefix);
if (rc < 0) {
return rc;
}
@@ -460,16 +458,18 @@ int hicn_listen(hicn_socket_helper_t *hicn, int fd, const char *prefix) {
if (punting_table_id == -1) punting_table_id = socket->connection.table_id;
- rc = ops.add_prio_rule(&ip_prefix, ip_prefix.family, 0,
+ rc = ops.add_prio_rule(&hicn_ip_prefix, hicn_ip_prefix.family, 0,
socket->connection.table_id);
if (rc < 0) {
return rc;
}
- strcpy(rules_to_remove[rules_counter].tun_name, "NONE");
+ rc = strcpy_s(rules_to_remove[rules_counter].tun_name,
+ sizeof(rules_to_remove[rules_counter].tun_name), "NONE");
+ if (rc != EOK) return -1;
- rules_to_remove[rules_counter].prefix = ip_prefix;
- rules_to_remove[rules_counter].address_family = ip_prefix.family;
+ rules_to_remove[rules_counter].prefix = hicn_ip_prefix;
+ rules_to_remove[rules_counter].address_family = hicn_ip_prefix.family;
rules_to_remove[rules_counter].table_id = socket->connection.table_id;
rules_to_remove[rules_counter].priority = 0;
++rules_counter;
@@ -533,7 +533,10 @@ int hicn_bind(hicn_socket_helper_t *hicn, int fd,
goto ERR;
}
- strcpy(rules_to_remove[rules_counter].tun_name, socket->tun_name);
+ rc = strcpy_s(rules_to_remove[rules_counter].tun_name,
+ sizeof(rules_to_remove[rules_counter].tun_name),
+ socket->tun_name);
+ if (rc != EOK) return -1;
rules_to_remove[rules_counter].address_family = addr_family;
rules_to_remove[rules_counter].table_id = socket->connection.table_id;
++rules_counter;
@@ -563,7 +566,13 @@ int hicn_bind(hicn_socket_helper_t *hicn, int fd,
goto ERR;
}
- strcpy(routes_to_remove[routes_counter].remote_ip_address, remote_ip_address);
+ rc = strcpy_s(routes_to_remove[routes_counter].remote_ip_address,
+ sizeof(rules_to_remove[rules_counter].tun_name),
+ remote_ip_address);
+ if (rc != EOK) {
+ rc = HICN_SOCKET_ERROR_UNSPEC;
+ goto ERR;
+ }
routes_to_remove[routes_counter].table_id = socket->connection.table_id;
routes_to_remove[routes_counter].address_family = (uint8_t)addr_family;
++routes_counter;
diff --git a/hicn-light/src/hicn/socket/api.h b/hicn-light/src/hicn/socket/api.h
index 1a7f5c700..3caf9ef1e 100644
--- a/hicn-light/src/hicn/socket/api.h
+++ b/hicn-light/src/hicn/socket/api.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +29,6 @@
#include <stdlib.h>
#include <hicn/hicn.h>
-#include "error.h"
#define BUFSIZE 4096
#define MAX_CONNECTIONS \
@@ -84,7 +83,7 @@ typedef struct hicn_socket_s {
union {
struct {
- ip_prefix_t tun_ip_address;
+ hicn_ip_prefix_t tun_ip_address;
uint32_t interface_id;
/* ID of the corresponding table : avoid default values of 0, 32766 and
@@ -163,8 +162,8 @@ void hicn_free(hicn_socket_helper_t *hicn);
*
* @return 0 in case of success, -1 otherwise.
*/
-int hicn_get_local_address(const ip_prefix_t *remote_address,
- ip_prefix_t *local_address);
+int hicn_get_local_address(const hicn_ip_prefix_t *remote_address,
+ hicn_ip_prefix_t *local_address);
/* hICN socket */
diff --git a/hicn-light/src/hicn/socket/ops.h b/hicn-light/src/hicn/socket/ops.h
index 1bee7c6f6..854b0c461 100644
--- a/hicn-light/src/hicn/socket/ops.h
+++ b/hicn-light/src/hicn/socket/ops.h
@@ -17,10 +17,10 @@ typedef struct {
int (*get_output_ifid)(const char *ip_address, uint8_t address_family,
uint32_t *interface_id);
int (*get_ip_addr)(uint32_t interface_id, uint8_t address_family,
- ip_prefix_t *ip_address);
- int (*set_ip_addr)(uint32_t interface_id, ip_prefix_t *ip_address);
+ hicn_ip_prefix_t *ip_address);
+ int (*set_ip_addr)(uint32_t interface_id, hicn_ip_prefix_t *ip_address);
int (*up_if)(uint32_t interface_id);
- int (*add_in_route_table)(const ip_prefix_t *prefix,
+ int (*add_in_route_table)(const hicn_ip_prefix_t *prefix,
const uint32_t interface_id,
const uint8_t table_id);
int (*add_in_route_table_s)(const char *prefix, const uint32_t interface_id,
@@ -30,23 +30,23 @@ typedef struct {
const uint8_t table_id, int default_route);
int (*del_out_route)(const char *gateway, const uint8_t address_family,
const uint8_t table_id);
- int (*del_lo_route)(const ip_prefix_t *ip_address);
+ int (*del_lo_route)(const hicn_ip_prefix_t *ip_address);
int (*add_rule)(const char *interface_name, const uint8_t address_family,
const uint8_t table_id);
int (*del_rule)(const char *interface_name, const uint8_t address_family,
const uint8_t table_id);
- int (*add_neigh_proxy)(const ip_prefix_t *ip_address,
+ int (*add_neigh_proxy)(const hicn_ip_prefix_t *ip_address,
const uint32_t interface_id);
- int (*add_prio_rule)(const ip_prefix_t *ip_address,
+ int (*add_prio_rule)(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family, const uint32_t priority,
const uint8_t table_id);
- int (*add_lo_prio_rule)(const ip_prefix_t *ip_address,
+ int (*add_lo_prio_rule)(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family,
const uint32_t priority);
- int (*del_prio_rule)(const ip_prefix_t *ip_address,
+ int (*del_prio_rule)(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family, const uint32_t priority,
const uint8_t table_id);
- int (*del_lo_prio_rule)(const ip_prefix_t *ip_address,
+ int (*del_lo_prio_rule)(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family,
const uint32_t priority);
} hicn_socket_ops_t;
diff --git a/hicn-light/src/hicn/socket/ops_linux.c b/hicn-light/src/hicn/socket/ops_linux.c
index 8bfc438f3..a3675e929 100644
--- a/hicn-light/src/hicn/socket/ops_linux.c
+++ b/hicn-light/src/hicn/socket/ops_linux.c
@@ -24,6 +24,8 @@
#include <stdint.h>
#include <stdlib.h>
+#include <hicn/ctrl/api.h>
+#include <hicn/util/sstrncpy.h>
/* Public interface */
@@ -60,13 +62,13 @@ int _nl_get_output_ifid(const char *ip_address, uint8_t address_family,
* @see getifaddrs
*/
int _nl_get_ip_addr(uint32_t interface_id, uint8_t address_family,
- ip_prefix_t *ip_address);
+ hicn_ip_prefix_t *ip_address);
-int _nl_set_ip_addr(uint32_t interface_id, ip_prefix_t *ip_address);
+int _nl_set_ip_addr(uint32_t interface_id, hicn_ip_prefix_t *ip_address);
int _nl_up_if(uint32_t interface_id);
-int _nl_add_in_route_table(const ip_prefix_t *prefix,
+int _nl_add_in_route_table(const hicn_ip_prefix_t *prefix,
const uint32_t interface_id, const uint8_t table_id);
int _nl_add_in_route_table_s(const char *prefix, const uint32_t interface_id,
const uint8_t table_id);
@@ -77,25 +79,25 @@ int _nl_add_out_route(const char *gateway, const uint8_t address_family,
int _nl_del_out_route(const char *gateway, const uint8_t address_family,
const uint8_t table_id);
-int _nl_del_lo_route(const ip_prefix_t *ip_address);
+int _nl_del_lo_route(const hicn_ip_prefix_t *ip_address);
int _nl_add_rule(const char *interface_name, const uint8_t address_family,
const uint8_t table_id);
int _nl_del_rule(const char *interface_name, const uint8_t address_family,
const uint8_t table_id);
-int _nl_add_neigh_proxy(const ip_prefix_t *ip_address,
+int _nl_add_neigh_proxy(const hicn_ip_prefix_t *ip_address,
const uint32_t interface_id);
-int _nl_add_prio_rule(const ip_prefix_t *ip_address,
+int _nl_add_prio_rule(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family, const uint32_t priority,
const uint8_t table_id);
-int _nl_add_lo_prio_rule(const ip_prefix_t *ip_address,
+int _nl_add_lo_prio_rule(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family, const uint32_t priority);
-int _nl_del_prio_rule(const ip_prefix_t *ip_address,
+int _nl_del_prio_rule(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family, const uint32_t priority,
const uint8_t table_id);
-int _nl_del_lo_prio_rule(const ip_prefix_t *ip_address,
+int _nl_del_lo_prio_rule(const hicn_ip_prefix_t *ip_address,
const uint8_t address_family, const uint32_t priority);
#endif /* HICN_NETLINK_H */
@@ -338,7 +340,8 @@ uint32_t _nl_get_ifid(const char *interface_name) {
struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
size_t n;
int fd;
- size_t len = interface_name ? strlen(interface_name) + 1 : 0;
+ size_t len =
+ interface_name ? strnlen_s(interface_name, INTERFACE_LEN) + 1 : 0;
uint8_t padding[RTA_ALIGNTO] = {0, 0, 0, 0};
if (len == 0) {
@@ -353,8 +356,8 @@ uint32_t _nl_get_ifid(const char *interface_name) {
.hdr.nlmsg_flags = FLAGS_GET,
.payload.ifi_family = AF_UNSPEC,
.payload.ifi_index = 0};
- struct rtattr a_ifname = {RTA_LENGTH(strlen(interface_name) + 1),
- IFLA_IFNAME};
+ struct rtattr a_ifname = {
+ RTA_LENGTH(strnlen_s(interface_name, INTERFACE_LEN) + 1), IFLA_IFNAME};
struct iovec iov[] = {{&msg, sizeof(msg)},
{&a_ifname, sizeof(a_ifname)},
@@ -530,7 +533,7 @@ ERR:
}
int _nl_get_ip_addr(uint32_t interface_id, uint8_t address_family,
- ip_prefix_t *prefix) {
+ hicn_ip_prefix_t *prefix) {
char buffer[BUFSIZE];
struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
size_t n;
@@ -599,7 +602,7 @@ ERR_SOCKET:
return HICN_SOCKET_ERROR_UNSPEC;
}
-int _nl_set_ip_addr(uint32_t interface_id, ip_prefix_t *prefix) {
+int _nl_set_ip_addr(uint32_t interface_id, hicn_ip_prefix_t *prefix) {
char buffer[BUFSIZE];
struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
size_t n;
@@ -619,15 +622,15 @@ int _nl_set_ip_addr(uint32_t interface_id, ip_prefix_t *prefix) {
.payload.ifa_index = interface_id};
/* Set attributes = length/type/value */
- struct rtattr ifa_address = {RTA_LENGTH(ip_address_len(prefix->family)),
+ struct rtattr ifa_address = {RTA_LENGTH(hicn_ip_address_len(prefix->family)),
IFA_ADDRESS};
- const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
- if (!address)
- goto ERR_ADDRESS;
+ const void *address =
+ hicn_ip_address_get_buffer(&prefix->address, prefix->family);
+ if (!address) goto ERR_ADDRESS;
const struct iovec iov[] = {
{&msg, sizeof(msg)},
{&ifa_address, sizeof(ifa_address)},
- {(void*)address, ip_address_len(prefix->family)},
+ {(void *)address, hicn_ip_address_len(prefix->family)},
};
msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));
@@ -965,7 +968,7 @@ ERR_SOCKET:
* ip route del 1:2::2 dev lo table local
*
*/
-int _nl_del_lo_route(const ip_prefix_t *prefix) {
+int _nl_del_lo_route(const hicn_ip_prefix_t *prefix) {
char buffer[BUFSIZE];
struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
size_t n;
@@ -991,16 +994,17 @@ int _nl_del_lo_route(const ip_prefix_t *prefix) {
/* Set attribute = length/type/value */
uint32_t one = 1;
- struct rtattr a_dst = {RTA_LENGTH(ip_address_len(prefix->family)), RTA_DST};
+ struct rtattr a_dst = {RTA_LENGTH(hicn_ip_address_len(prefix->family)),
+ RTA_DST};
struct rtattr a_ifid_lo = {RTA_LENGTH(sizeof(uint32_t)), RTA_OIF};
- const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
- if (!address)
- goto ERR;
+ const void *address =
+ hicn_ip_address_get_buffer(&prefix->address, prefix->family);
+ if (!address) goto ERR;
const struct iovec iov[] = {
{&msg, sizeof(msg)},
/* Ip address */
{&a_dst, sizeof(a_dst)},
- {(void*)address, ip_address_len(prefix->family)},
+ {(void *)address, hicn_ip_address_len(prefix->family)},
/* Interface id */
{&a_ifid_lo, sizeof(a_ifid_lo)},
{&one, sizeof(one)}};
@@ -1048,7 +1052,7 @@ int _nl_add_rule(const char *interface_name, uint8_t address_family,
_nl_payload_rule(table_id, address_family, (uint8_t *)buffer, BUFSIZE);
addAttr(hdr, BUFSIZE, FRA_IIFNAME, (void *)interface_name,
- strlen(interface_name));
+ strnlen_s(interface_name, INTERFACE_LEN));
fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
if (fd < 0) {
@@ -1094,7 +1098,7 @@ int _nl_del_rule(const char *interface_name, uint8_t address_family,
_nl_payload_rule(table_id, address_family, (uint8_t *)buffer, BUFSIZE);
addAttr(hdr, BUFSIZE, FRA_IIFNAME, (void *)interface_name,
- strlen(interface_name));
+ strnlen_s(interface_name, INTERFACE_LEN));
fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
if (fd < 0) {
@@ -1131,7 +1135,7 @@ ERR_SOCKET:
* ip -6 neigh add proxy 1:2::2 dev hicnc-cons-eth0 2>&1 | grep nei
*
*/
-int _nl_add_neigh_proxy(const ip_prefix_t *prefix,
+int _nl_add_neigh_proxy(const hicn_ip_prefix_t *prefix,
const uint32_t interface_id) {
/* Buffer for holding the response, with appropriate casting on the header */
char buffer[BUFSIZE];
@@ -1156,18 +1160,19 @@ int _nl_add_neigh_proxy(const ip_prefix_t *prefix,
};
/* Message attributes = length/type/value */
- struct rtattr a_dst = {RTA_LENGTH(ip_address_len(prefix->family)), NDA_DST};
+ struct rtattr a_dst = {RTA_LENGTH(hicn_ip_address_len(prefix->family)),
+ NDA_DST};
- const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
- if (!address)
- goto ERR;
+ const void *address =
+ hicn_ip_address_get_buffer(&prefix->address, prefix->family);
+ if (!address) goto ERR;
/* Iovec describing the packets */
const struct iovec iov[] = {
{&msg, sizeof(msg)},
/* Ip address */
{&a_dst, sizeof(a_dst)},
- {(void*)address, ip_address_len(prefix->family)},
+ {(void *)address, hicn_ip_address_len(prefix->family)},
};
msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));
@@ -1205,7 +1210,7 @@ ERR:
/* ip -6 route add 0:1::/64 dev hicn-if0 table 100 */
/* ip -6 route add 0:2::/64 dev hicn-if1 table 100 */
-int _nl_add_in_route_table(const ip_prefix_t *prefix,
+int _nl_add_in_route_table(const hicn_ip_prefix_t *prefix,
const uint32_t interface_id,
const uint8_t table_id) {
/* Buffer for holding the response, with appropriate casting on the header */
@@ -1237,19 +1242,20 @@ int _nl_add_in_route_table(const ip_prefix_t *prefix,
};
/* Message attributes = length/type/value */
- struct rtattr a_dst = {RTA_LENGTH(ip_address_len(prefix->family)), RTA_DST};
+ struct rtattr a_dst = {RTA_LENGTH(hicn_ip_address_len(prefix->family)),
+ RTA_DST};
struct rtattr a_oif = {RTA_LENGTH(sizeof(uint32_t)), RTA_OIF};
- const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
- if (!address)
- goto ERR;
+ const void *address =
+ hicn_ip_address_get_buffer(&prefix->address, prefix->family);
+ if (!address) goto ERR;
/* Iovec describing the packets */
const struct iovec iov[] = {
{&msg, sizeof(msg)},
/* Destination prefix / ip address */
{&a_dst, sizeof(a_dst)},
- {(void*)address, ip_address_len(prefix->family)},
+ {(void *)address, hicn_ip_address_len(prefix->family)},
/* Output interface */
{&a_oif, sizeof(a_oif)},
{(void *)&interface_id, sizeof(uint32_t)},
@@ -1293,9 +1299,9 @@ ERR:
int _nl_add_in_route_table_s(const char *prefix, const uint32_t interface_id,
const uint8_t table_id) {
int rc;
- ip_prefix_t ip_address;
+ hicn_ip_prefix_t ip_address;
- rc = ip_prefix_pton(prefix, &ip_address);
+ rc = hicn_ip_prefix_pton(prefix, &ip_address);
if (rc < 0) {
return rc;
}
@@ -1308,7 +1314,7 @@ int _nl_add_in_route_s(const char *prefix, const uint32_t interface_id) {
}
/* ip -6 rule add from b001::/16 prio 0 table 100 */
-int _nl_add_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
+int _nl_add_prio_rule(const hicn_ip_prefix_t *prefix, uint8_t address_family,
const uint32_t priority, const uint8_t table_id) {
/* Buffer for holding the response, with appropriate casting on the header */
char buffer[BUFSIZE];
@@ -1343,18 +1349,19 @@ int _nl_add_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
if (prefix) {
/* Message attributes = length/type/value */
- struct rtattr a_src = {RTA_LENGTH(ip_address_len(prefix->family)), FRA_SRC};
+ struct rtattr a_src = {RTA_LENGTH(hicn_ip_address_len(prefix->family)),
+ FRA_SRC};
struct rtattr a_prio = {RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY};
- const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
- if (!address)
- goto ERR;
+ const void *address =
+ hicn_ip_address_get_buffer(&prefix->address, prefix->family);
+ if (!address) goto ERR;
/* Iovec describing the packets */
const struct iovec iov[] = {
{&msg, sizeof(msg)},
/* Source prefix / prefix */
{&a_src, sizeof(a_src)},
- {(void*)address, ip_address_len(prefix->family)},
+ {(void *)address, hicn_ip_address_len(prefix->family)},
/* Priority */
{&a_prio, sizeof(a_prio)},
{(void *)&priority, sizeof(uint32_t)},
@@ -1405,14 +1412,13 @@ ERR:
return HICN_SOCKET_ERROR_UNSPEC;
}
-int _nl_add_lo_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
+int _nl_add_lo_prio_rule(const hicn_ip_prefix_t *prefix, uint8_t address_family,
const uint32_t priority) {
- return _nl_add_prio_rule(prefix, address_family, priority,
- RT_TABLE_LOCAL);
+ return _nl_add_prio_rule(prefix, address_family, priority, RT_TABLE_LOCAL);
}
/* ip -6 rule del from all prio 0 table local */
-int _nl_del_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
+int _nl_del_prio_rule(const hicn_ip_prefix_t *prefix, uint8_t address_family,
const uint32_t priority, const uint8_t table_id) {
/* Buffer for holding the response, with appropriate casting on the header */
char buffer[BUFSIZE];
@@ -1447,19 +1453,20 @@ int _nl_del_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
/* Message attributes = length/type/value */
if (prefix) {
- struct rtattr a_src = {RTA_LENGTH(ip_address_len(prefix->family)), FRA_SRC};
+ struct rtattr a_src = {RTA_LENGTH(hicn_ip_address_len(prefix->family)),
+ FRA_SRC};
struct rtattr a_prio = {RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY};
- const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
- if (!address)
- goto ERR;
+ const void *address =
+ hicn_ip_address_get_buffer(&prefix->address, prefix->family);
+ if (!address) goto ERR;
/* Iovec describing the packets */
const struct iovec iov[] = {
{&msg, sizeof(msg)},
/* Source prefix / prefix */
{&a_src, sizeof(a_src)},
- {(void*)address, ip_address_len(prefix->family)},
+ {(void *)address, hicn_ip_address_len(prefix->family)},
/* Priority */
{&a_prio, sizeof(a_prio)},
{(void *)&priority, sizeof(uint32_t)},
@@ -1512,8 +1519,8 @@ ERR:
return HICN_SOCKET_ERROR_UNSPEC;
}
-int _nl_del_lo_prio_rule(const ip_prefix_t *ip_address, uint8_t address_family,
- const uint32_t priority) {
+int _nl_del_lo_prio_rule(const hicn_ip_prefix_t *ip_address,
+ uint8_t address_family, const uint32_t priority) {
return _nl_del_prio_rule(ip_address, address_family, priority,
RT_TABLE_LOCAL);
}
@@ -1539,7 +1546,7 @@ int _nl_del_lo_prio_rule(const ip_prefix_t *ip_address, uint8_t address_family,
int tun_alloc(char *dev, int flags) {
struct ifreq ifr;
- int fd, err;
+ int fd, err, rc;
char *clonedev = "/dev/net/tun";
/* Arguments taken by the function:
@@ -1563,7 +1570,8 @@ int tun_alloc(char *dev, int flags) {
/* if a device name was specified, put it in the structure; otherwise,
* the kernel will try to allocate the "next" device of the
* specified type */
- strncpy(ifr.ifr_name, dev, IF_NAMESIZE - 1);
+ rc = strcpy_s(ifr.ifr_name, IF_NAMESIZE - 1, dev);
+ if (rc != EOK) return -1;
}
/* try to create the device */
@@ -1576,7 +1584,8 @@ int tun_alloc(char *dev, int flags) {
* interface to the variable "dev", so the caller can know
* it. Note that the caller MUST reserve space in *dev (see calling
* code below) */
- strcpy(dev, ifr.ifr_name);
+ rc = strcpy_s(dev, IF_NAMESIZE, ifr.ifr_name);
+ if (rc != EOK) return -1;
/* this is the special file descriptor that the caller will use to talk
* with the virtual interface */
diff --git a/hicn-light/src/hicn/strategies/CMakeLists.txt b/hicn-light/src/hicn/strategies/CMakeLists.txt
index 886aa137c..754974ee4 100644
--- a/hicn-light/src/hicn/strategies/CMakeLists.txt
+++ b/hicn-light/src/hicn/strategies/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -12,20 +12,23 @@
# limitations under the License.
list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/strategyImpl.h
- ${CMAKE_CURRENT_SOURCE_DIR}/loadBalancer.h
- ${CMAKE_CURRENT_SOURCE_DIR}/lowLatency.h
- ${CMAKE_CURRENT_SOURCE_DIR}/nexthopState.h
- ${CMAKE_CURRENT_SOURCE_DIR}/nexthopStateLowLatency.h
- ${CMAKE_CURRENT_SOURCE_DIR}/rnd.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/load_balancer.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/random.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/replication.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/best_path.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/local_prefixes.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/probe_generator.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/local_remote.h
)
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/loadBalancer.c
- ${CMAKE_CURRENT_SOURCE_DIR}/lowLatency.c
- ${CMAKE_CURRENT_SOURCE_DIR}/nexthopState.c
- ${CMAKE_CURRENT_SOURCE_DIR}/nexthopStateLowLatency.c
- ${CMAKE_CURRENT_SOURCE_DIR}/rnd.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/load_balancer.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/random.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/replication.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/best_path.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/local_prefixes.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/probe_generator.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/local_remote.c
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
diff --git a/hicn-light/src/hicn/strategies/best_path.c b/hicn-light/src/hicn/strategies/best_path.c
new file mode 100644
index 000000000..9223cc8ac
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/best_path.c
@@ -0,0 +1,353 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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 <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <hicn/hicn-light/config.h>
+
+#include <hicn/core/forwarder.h>
+#include <hicn/core/nexthops.h>
+#include <hicn/core/strategy.h>
+#include <hicn/core/strategy_vft.h>
+
+#include "best_path.h"
+
+#define MAX_NEXTHOP_COST 100
+#define MAX_RTT_ALLOWED 300.0 // ms
+#define MAX_LOSSES_ALLOWED 0.4 // 40%
+
+#define MAX_PROBING_DURATION 5000 // ticks (= ms)
+#define PROBES_WAINTING_TIME 500 // ticks (= ms)
+#define MAX_PROBES 50
+
+/* Shorthand */
+#define nexthop_state_t strategy_bestpath_nexthop_state_t
+#define strategy_state_t strategy_bestpath_state_t
+#define nexthop_state(nexthops, i) (&nexthops->state[i].bestpath)
+
+// nexthop state functions
+
+static const nexthop_state_t NEXTHOP_STATE_INIT = {
+ .sent_probes = 0,
+ .recv_probes = 0,
+ .rtt_sum = 0,
+};
+
+static inline unsigned int get_sent_probes(nexthop_state_t *state) {
+ return state->sent_probes;
+}
+
+static inline unsigned int inc_sent_probes(nexthop_state_t *state) {
+ state->sent_probes++;
+ return state->sent_probes;
+}
+
+static inline void add_rtt_sample(nexthop_state_t *state, Ticks rtt) {
+ state->recv_probes++;
+ state->rtt_sum += rtt;
+}
+
+static inline unsigned int get_nexthop_cost(nexthop_state_t *state) {
+ if (state->recv_probes == 0)
+ return 100; // we have no info for this nexthop, return max cost
+
+ assert(state->recv_probes <= state->sent_probes);
+
+ double rtt = (double)state->rtt_sum / (double)state->recv_probes;
+ double delay_cost = rtt / MAX_RTT_ALLOWED;
+ if (delay_cost > 1) delay_cost = 1;
+
+ double loss_rate = (double)(state->sent_probes - state->recv_probes) /
+ (double)state->sent_probes;
+ double loss_cost = loss_rate / MAX_LOSSES_ALLOWED;
+ if (loss_cost > 1) loss_cost = 1;
+
+ double total_cost = delay_cost * 0.5 + loss_cost * 0.5;
+ return round(total_cost * 100);
+}
+
+// options functions
+static void bestpath_update_remote_node(strategy_entry_t *entry,
+ nexthops_t *nexthops) {
+ strategy_state_t *state = &entry->state.bestpath;
+ strategy_bestpath_options_t *options = &entry->options.bestpath;
+ off_t offset = nexthops_find(nexthops, state->best_nexthop);
+
+ /* Backup flags and cur_len: because our code is called from
+ * strategy_on_data / check_stop_probing / stop_probing
+ * which does not expect the nexthop flags to be modified.
+ */
+ uint_fast32_t flags = nexthops->flags;
+ size_t cur_len = nexthops_get_curlen(nexthops);
+
+ nexthops_select(nexthops, offset);
+ update_remote_node_paths(nexthops, entry->forwarder, options->local_prefixes);
+
+ /* Restore flags & curlen */
+ nexthops->flags = flags;
+ nexthops->cur_elts = cur_len;
+}
+
+// probing functions
+
+static void start_probing(strategy_entry_t *entry) {
+ strategy_state_t *state = &entry->state.bestpath;
+ if (state->probing_state == PROBING_OFF) {
+ state->probing_state = PROBING_ON;
+ state->probing_time = ticks_now();
+ }
+}
+
+static void stop_probing(strategy_entry_t *entry, nexthops_t *nexthops) {
+ strategy_state_t *state = &entry->state.bestpath;
+ nexthop_t best_nexthop;
+ best_nexthop = state->best_nexthop;
+ unsigned int min_cost = ~0;
+ unsigned current_nexthop_cost = ~0;
+
+ nexthops_enumerate(nexthops, i, nexthop, {
+ unsigned int cost = get_nexthop_cost(nexthop_state(nexthops, i));
+ if (cost < min_cost) {
+ min_cost = cost;
+ best_nexthop = nexthop;
+ }
+ if (nexthop == state->best_nexthop) current_nexthop_cost = cost;
+
+ nexthops->state[i].bestpath = NEXTHOP_STATE_INIT;
+ });
+
+ if (best_nexthop != state->best_nexthop) {
+ if (current_nexthop_cost > min_cost) {
+ // update best face
+ state->best_nexthop = best_nexthop;
+ }
+ }
+
+ // always update remote node
+ bestpath_update_remote_node(entry, nexthops);
+
+ state->probing_state = PROBING_OFF;
+ delete_all_probes(state->pg);
+}
+
+static void check_stop_probing(strategy_entry_t *entry, nexthops_t *nexthops) {
+ strategy_state_t *state = &entry->state.bestpath;
+ if (state->probing_state == PROBING_OFF) return;
+
+ if (state->probing_state == PROBING_ON) {
+ Ticks probing_duration = ticks_now() - state->probing_time;
+ if (probing_duration >= MAX_PROBING_DURATION) {
+ state->probing_state = PROBING_ENDING;
+ state->probing_time = ticks_now();
+ }
+ return;
+ }
+
+ if (state->probing_state == SENT_MAX_PROBES) {
+ state->probing_state = PROBING_ENDING;
+ state->probing_time = ticks_now();
+ return;
+ }
+
+ if (state->probing_state == PROBING_ENDING) {
+ Ticks ending_duration = ticks_now() - state->probing_time;
+ if (ending_duration >= PROBES_WAINTING_TIME) stop_probing(entry, nexthops);
+ }
+}
+
+static void send_probes(strategy_entry_t *entry, nexthops_t *nexthops,
+ const msgbuf_t *msgbuf) {
+ strategy_state_t *state = &entry->state.bestpath;
+
+ bool sent_max_probes = false;
+ nexthops_enumerate(nexthops, i, nexthop, {
+ if (get_sent_probes(nexthop_state(nexthops, i)) < MAX_PROBES) {
+ int res = generate_probe(state->pg, msgbuf, entry->forwarder, nexthop);
+ if (res >= 0) inc_sent_probes(nexthop_state(nexthops, i));
+ } else {
+ sent_max_probes = true;
+ }
+ });
+
+ if (sent_max_probes) {
+ state->probing_state = SENT_MAX_PROBES;
+ check_stop_probing(entry, nexthops);
+ }
+}
+
+static void init_strategy_state(strategy_state_t *state) {
+ state->best_nexthop = ~0;
+ state->probing_state = PROBING_OFF;
+ state->pg = create_probe_generator();
+}
+
+// strategy functions
+static int strategy_bestpath_initialize(strategy_entry_t *entry,
+ const void *forwarder) {
+ if (entry->forwarder == NULL) {
+ srand((unsigned int)time(NULL));
+ entry->forwarder = forwarder;
+ init_strategy_state(&entry->state.bestpath);
+ } else {
+ strategy_state_t *state = &entry->state.bestpath;
+ if (!state->pg) {
+ // the previous strategy was a different one
+ init_strategy_state(state);
+ } else {
+ // all set, start probing
+ start_probing(entry);
+ }
+ }
+ return 0;
+}
+
+static int strategy_bestpath_finalize(strategy_entry_t *entry) {
+ strategy_state_t *state = &entry->state.bestpath;
+ free_local_prefixes(entry->options.bestpath.local_prefixes);
+ destroy_probe_generator(state->pg);
+ return 0;
+}
+
+static int strategy_bestpath_add_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops, off_t offset) {
+ // reset the strategy state
+ nexthops->state[offset].bestpath = NEXTHOP_STATE_INIT;
+ return 0;
+}
+
+static int strategy_bestpath_remove_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ off_t offset) {
+ /* Nothing to do */
+ return 0;
+}
+
+static nexthops_t *strategy_bestpath_lookup_nexthops(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const msgbuf_t *msgbuf) {
+ size_t nexthops_len = nexthops_get_curlen(nexthops);
+ if (nexthops_len == 0) {
+ // nexthops is empty, return
+ return nexthops;
+ }
+
+ strategy_state_t *state = &entry->state.bestpath;
+ off_t best_nexthop_offset = nexthops_find(nexthops, state->best_nexthop);
+
+ // TODO explain the purpose of this test
+ if (nexthops_len == 1) {
+ nexthop_t nh = nexthops_get_one(nexthops);
+ if (state->best_nexthop != nh) {
+ state->best_nexthop = nh;
+ bestpath_update_remote_node(entry, nexthops);
+ }
+ return nexthops;
+ }
+
+ if (state->best_nexthop == ~0 || best_nexthop_offset == INVALID_NEXTHOP) {
+ state->best_nexthop = nexthops_get_one(nexthops);
+ best_nexthop_offset = nexthops_find(nexthops, state->best_nexthop);
+ bestpath_update_remote_node(entry, nexthops);
+ // we have probe only in case the number of face is > 1
+ start_probing(entry);
+ // bestpath_update_remote_node sets the nexthops. in case of probing we want
+ // to send the packets on all faces, so we reset the nexthops here
+ nexthops_reset(nexthops);
+ }
+
+ if (state->probing_state == PROBING_ON) {
+ // send a probe for each interest received
+ send_probes(entry, nexthops, msgbuf);
+
+ uint32_t suffix = hicn_name_get_suffix(msgbuf_get_name(msgbuf));
+ if (suffix >= MIN_PROBE_SUFFIX && suffix <= MAX_PROBE_SUFFIX) {
+ // this packet is a probe from the transport, so register it
+ Ticks time = get_probe_send_time(state->pg, suffix);
+ if (time == 0) {
+ // a probe with the same seq number is not pending, send the packet
+ // the stats for this probe will be collected by the transport
+ register_probe(state->pg, suffix);
+ } else {
+ // this probe is already pending. avoid duplicates and drop it
+ nexthops->flags = ~0;
+ nexthops->cur_elts = 0;
+ }
+ }
+ } else {
+ // we are not probing anymore. if in probing ending state (wait for probes
+ // to come back) keep replicating traffic, otherwise and on best path
+ if (state->probing_state != PROBING_ENDING)
+ nexthops_select(nexthops, best_nexthop_offset);
+ }
+
+ // in case we are still probing send all interest on all paths
+ // so do not select any next hop.
+ // XXX in this transition phase should we replicate also at the
+ // server side?
+ return nexthops;
+}
+
+static int strategy_bestpath_on_data(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *data_nexthops,
+ const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation,
+ Ticks objReception) {
+ strategy_state_t *state = &entry->state.bestpath;
+ if (state->probing_state == PROBING_OFF) return 0;
+
+ uint32_t seq = hicn_name_get_suffix(msgbuf_get_name(msgbuf));
+ if (seq >= MIN_PROBE_SUFFIX && seq <= MAX_PROBE_SUFFIX) {
+ if (pitEntryCreation != 0) {
+ // this is not a probe sent by the forwader. do not use it in the probing
+ // statisitcs but remove it from the map if it exists
+ delete_probe(state->pg, seq);
+ return 0;
+ }
+
+ Ticks send_time = get_probe_send_time(state->pg, seq);
+ if (send_time != 0) {
+ Ticks rtt = ticks_now() - send_time;
+ delete_probe(state->pg, seq);
+ nexthops_enumerate(data_nexthops, i, nexthop, {
+ off_t pos = nexthops_find(nexthops, nexthop);
+ add_rtt_sample(nexthop_state(nexthops, pos), rtt);
+ });
+ }
+ }
+
+ check_stop_probing(entry, nexthops);
+
+ return 0;
+}
+
+static int strategy_bestpath_on_timeout(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *timeout_nexthops) {
+ /* Nothing to do */
+ return 0;
+}
+
+#undef nexthop_state_t
+#undef strategy_state_t
+
+DECLARE_STRATEGY(bestpath);
+
+#undef nexthop_state_t
+#undef strategy_state_t
diff --git a/hicn-light/src/hicn/strategies/best_path.h b/hicn-light/src/hicn/strategies/best_path.h
new file mode 100644
index 000000000..206214579
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/best_path.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Forward on a single path. Every time the strategy is reset with a command the
+ * forwarder starts to probe the available paths matching the probes on the
+ * original flow. if after the probing phase a better path exists (lower
+ * latency, less losses) the forwarder switch path, otherwise does nothing
+ */
+
+#ifndef HICNLIGHT_STRATEGY_BESTPATH_H
+#define HICNLIGHT_STRATEGY_BESTPATH_H
+
+#include "probe_generator.h"
+#include "local_prefixes.h"
+
+typedef enum {
+ PROBING_OFF,
+ PROBING_ON,
+ SENT_MAX_PROBES,
+ PROBING_ENDING, // waiting for probes to come back
+ UNKWNOWN,
+} probing_state_t;
+
+typedef struct {
+ // number or probes sent during a probing phase
+ unsigned int sent_probes;
+ // number or probes received during a probing phase
+ unsigned int recv_probes;
+ // sum of all rtt collected
+ Ticks rtt_sum;
+} strategy_bestpath_nexthop_state_t;
+
+typedef struct {
+ unsigned best_nexthop;
+ Ticks probing_time;
+ probing_state_t probing_state;
+ probe_generator_t *pg;
+} strategy_bestpath_state_t;
+
+typedef struct {
+ local_prefixes_t *local_prefixes;
+} strategy_bestpath_options_t;
+
+#endif /* HICNLIGHT_STRATEGY_BESTPATH_H */
diff --git a/hicn-light/src/hicn/strategies/loadBalancer.c b/hicn-light/src/hicn/strategies/loadBalancer.c
deleted file mode 100644
index 82b5a6103..000000000
--- a/hicn-light/src/hicn/strategies/loadBalancer.c
+++ /dev/null
@@ -1,369 +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/hicn-light/config.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_HashMap.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-#include <parc/algol/parc_Unsigned.h>
-
-#include <hicn/strategies/loadBalancer.h>
-#include <hicn/strategies/nexthopState.h>
-
-static void _strategyLoadBalancer_ReceiveObject(StrategyImpl *strategy,
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception);
-static void _strategyLoadBalancer_OnTimeout(StrategyImpl *strategy,
- const NumberSet *egressId);
-static NumberSet *_strategyLoadBalancer_LookupNexthop(
- StrategyImpl *strategy,
-#ifdef WITH_POLICY
- NumberSet * nexthops,
-#endif /* WITH_POLICY */
- const Message *interestMessage);
-#ifndef WITH_POLICY
-static NumberSet *_strategyLoadBalancer_ReturnNexthops(StrategyImpl *strategy);
-static unsigned _strategyLoadBalancer_CountNexthops(StrategyImpl *strategy);
-#endif /* ! WITH_POLICY */
-static void _strategyLoadBalancer_AddNexthop(StrategyImpl *strategy,
- unsigned connectionId);
-static void _strategyLoadBalancer_RemoveNexthop(StrategyImpl *strategy,
- unsigned connectionId);
-static void _strategyLoadBalancer_ImplDestroy(StrategyImpl **strategyPtr);
-static strategy_type _strategyLoadBalancer_GetStrategy(StrategyImpl *strategy);
-
-static StrategyImpl _template = {
- .context = NULL,
- .receiveObject = &_strategyLoadBalancer_ReceiveObject,
- .onTimeout = &_strategyLoadBalancer_OnTimeout,
- .lookupNexthop = &_strategyLoadBalancer_LookupNexthop,
-#ifndef WITH_POLICY
- .returnNexthops = &_strategyLoadBalancer_ReturnNexthops,
- .countNexthops = &_strategyLoadBalancer_CountNexthops,
-#endif /* ! WITH_POLICY */
- .addNexthop = &_strategyLoadBalancer_AddNexthop,
- .removeNexthop = &_strategyLoadBalancer_RemoveNexthop,
- .destroy = &_strategyLoadBalancer_ImplDestroy,
- .getStrategy = &_strategyLoadBalancer_GetStrategy,
-};
-
-struct strategy_load_balancer;
-typedef struct strategy_load_balancer StrategyLoadBalancer;
-
-struct strategy_load_balancer {
-#ifndef WITH_POLICY
- double weights_sum;
-#endif /* ! WITH_POLICY */
- // hash map from connectionId to StrategyNexthopState
- PARCHashMap *strategy_state;
-#ifndef WITH_POLICY
- NumberSet *nexthops;
-#endif /* ! WITH_POLICY */
-};
-
-StrategyImpl *strategyLoadBalancer_Create() {
- StrategyLoadBalancer *strategy =
- parcMemory_AllocateAndClear(sizeof(StrategyLoadBalancer));
- parcAssertNotNull(strategy, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(StrategyLoadBalancer));
-
-#ifndef WITH_POLICY
- strategy->weights_sum = 0.0;
-#endif /* ! WITH_POLICY */
- strategy->strategy_state = parcHashMap_Create();
-#ifndef WITH_POLICY
- strategy->nexthops = numberSet_Create();
-#endif /* ! WITH_POLICY */
- srand((unsigned int)time(NULL));
-
- StrategyImpl *impl = parcMemory_AllocateAndClear(sizeof(StrategyImpl));
- parcAssertNotNull(impl, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(StrategyImpl));
- memcpy(impl, &_template, sizeof(StrategyImpl));
- impl->context = strategy;
-
- return impl;
-}
-
-// =======================================================
-// Dispatch API
-
-strategy_type _strategyLoadBalancer_GetStrategy(StrategyImpl *strategy) {
- return SET_STRATEGY_LOADBALANCER;
-}
-
-static void _update_Stats(StrategyLoadBalancer *strategy,
- StrategyNexthopState *state, bool inc) {
- const double ALPHA = 0.9;
-#ifdef WITH_POLICY
- strategyNexthopState_UpdateState(state, inc, ALPHA);
-#else
- double w = strategyNexthopState_GetWeight(state);
- strategy->weights_sum -= w;
- w = strategyNexthopState_UpdateState(state, inc, ALPHA);
- strategy->weights_sum += w;
-#endif /* WITH_POLICY */
-}
-
-#ifndef WITH_POLICY
-static unsigned _select_Nexthop(StrategyLoadBalancer *strategy) {
- double rnd = (double)rand() / (double)RAND_MAX;
- double start_range = 0.0;
-
- PARCIterator *it = parcHashMap_CreateKeyIterator(strategy->strategy_state);
-
- unsigned nexthop = 100000;
- while (parcIterator_HasNext(it)) {
- PARCUnsigned *cid = parcIterator_Next(it);
- const StrategyNexthopState *elem =
- parcHashMap_Get(strategy->strategy_state, cid);
-
- double w = strategyNexthopState_GetWeight(elem);
-
- double prob = w / strategy->weights_sum;
- if ((rnd >= start_range) && (rnd <= (start_range + prob))) {
- nexthop = parcUnsigned_GetUnsigned(cid);
- break;
- } else {
- start_range += prob;
- }
- }
-
- parcIterator_Release(&it);
-
- // if no face is selected by the algorithm (for example because of a wrong
- // round in the weights) we may always select the last face here. Double check
- // this!
- return nexthop;
-}
-#endif /* ! WITH_POLICY */
-
-static void _strategyLoadBalancer_ReceiveObject(StrategyImpl *strategy,
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception) {
- _strategyLoadBalancer_OnTimeout(strategy, egressId);
-}
-
-static void _strategyLoadBalancer_OnTimeout(StrategyImpl *strategy,
- const NumberSet *egressId) {
- StrategyLoadBalancer *lb = (StrategyLoadBalancer *)strategy->context;
-
- for (unsigned i = 0; i < numberSet_Length(egressId); i++) {
- unsigned outId = numberSet_GetItem(egressId, i);
- PARCUnsigned *cid = parcUnsigned_Create(outId);
-
- const StrategyNexthopState *state =
- parcHashMap_Get(lb->strategy_state, cid);
- if (state != NULL) {
- _update_Stats(lb, (StrategyNexthopState *)state, false);
- } else {
- // this may happen if we remove a face/route while downloading a file
- // we should ignore this timeout
- }
- parcUnsigned_Release(&cid);
- }
-}
-
-static NumberSet *_strategyLoadBalancer_LookupNexthop(
- StrategyImpl *strategy,
-#ifdef WITH_POLICY
- NumberSet * nexthops,
-#endif /* WITH_POLICY */
- const Message *interestMessage) {
- StrategyLoadBalancer *lb = (StrategyLoadBalancer *)strategy->context;
- NumberSet *outList = numberSet_Create();
-
-#ifdef WITH_POLICY
- /* Compute the sum of weights of potential next hops */
- double sum = 0;
- for (unsigned i = 0; i < numberSet_Length(nexthops); i++) {
- PARCUnsigned *cid = parcUnsigned_Create(numberSet_GetItem(nexthops, i));
- const StrategyNexthopState *elem =
- parcHashMap_Get(lb->strategy_state, cid);
- parcUnsigned_Release(&cid);
- if (!elem)
- continue;
- sum += strategyNexthopState_GetWeight(elem);
- }
-
- /* Perform weighted random selection */
- double distance = (double)rand() * sum / ((double)RAND_MAX + 1);
-
- for (unsigned i = 0; i < numberSet_Length(nexthops); i++) {
- PARCUnsigned *cid = parcUnsigned_Create(numberSet_GetItem(nexthops, i));
- const StrategyNexthopState *state =
- parcHashMap_Get(lb->strategy_state, cid);
- if (!state) {
- parcUnsigned_Release(&cid);
- continue;
- }
- distance -= strategyNexthopState_GetWeight(state);
- if (distance < 0) {
- numberSet_Add(outList, parcUnsigned_GetUnsigned(cid));
- _update_Stats(lb, (StrategyNexthopState *)state, true);
- parcUnsigned_Release(&cid);
- break;
- }
- parcUnsigned_Release(&cid);
- }
-#else
- unsigned in_connection = message_GetIngressConnectionId(interestMessage);
- PARCUnsigned *in = parcUnsigned_Create(in_connection);
-
- unsigned mapSize = (unsigned)parcHashMap_Size(lb->strategy_state);
-
- if ((mapSize == 0) ||
- ((mapSize == 1) && parcHashMap_Contains(lb->strategy_state, in))) {
- // there are no output faces or the input face is also the only output face.
- // return null to avoid loops
- parcUnsigned_Release(&in);
- return outList;
- }
-
- unsigned out_connection;
- do {
- out_connection = _select_Nexthop(lb);
- } while (out_connection == in_connection);
-
- PARCUnsigned *out = parcUnsigned_Create(out_connection);
-
- const StrategyNexthopState *state = parcHashMap_Get(lb->strategy_state, out);
- if (state == NULL) {
- // this is an error and should not happen!
- parcTrapNotImplemented(
- "Try to send an interest on a face that does not exists");
- }
-
- _update_Stats(lb, (StrategyNexthopState *)state, true);
-
- parcUnsigned_Release(&in);
- parcUnsigned_Release(&out);
-
- numberSet_Add(outList, out_connection);
-#endif /* WITH_POLICY */
-
- return outList;
-}
-
-#ifndef WITH_POLICY
-static NumberSet *_strategyLoadBalancer_ReturnNexthops(StrategyImpl *strategy) {
- StrategyLoadBalancer *lb = (StrategyLoadBalancer *)strategy->context;
- return lb->nexthops;
-}
-
-unsigned _strategyLoadBalancer_CountNexthops(StrategyImpl *strategy) {
- StrategyLoadBalancer *lb = (StrategyLoadBalancer *)strategy->context;
- return (unsigned)numberSet_Length(lb->nexthops);
-}
-#endif /* ! WITH_POLICY */
-
-static void _strategyLoadBalancer_resetState(StrategyImpl *strategy) {
- StrategyLoadBalancer *lb = (StrategyLoadBalancer *)strategy->context;
-#ifndef WITH_POLICY
- lb->weights_sum = 0.0;
-#endif/* ! WITH_POLICY */
- PARCIterator *it = parcHashMap_CreateKeyIterator(lb->strategy_state);
-
- while (parcIterator_HasNext(it)) {
- PARCUnsigned *cid = parcIterator_Next(it);
- StrategyNexthopState *elem =
- (StrategyNexthopState *)parcHashMap_Get(lb->strategy_state, cid);
-
- strategyNexthopState_Reset(elem);
-#ifndef WITH_POLICY
- lb->weights_sum += strategyNexthopState_GetWeight(elem);
-#endif /* ! WITH_POLICY */
- }
-
- parcIterator_Release(&it);
-}
-
-static void _strategyLoadBalancer_AddNexthop(StrategyImpl *strategy,
- unsigned connectionId) {
-
- PARCUnsigned *cid = parcUnsigned_Create(connectionId);
-
- StrategyLoadBalancer *lb = (StrategyLoadBalancer *)strategy->context;
-
- if (!parcHashMap_Contains(lb->strategy_state, cid)) {
- StrategyNexthopState *state = strategyNexthopState_Create();
- parcHashMap_Put(lb->strategy_state, cid, state);
-#ifndef WITH_POLICY
- numberSet_Add(lb->nexthops, connectionId);
-#endif /* WITH_POLICY */
- _strategyLoadBalancer_resetState(strategy);
- }
- parcUnsigned_Release(&cid);
-}
-
-static void _strategyLoadBalancer_RemoveNexthop(StrategyImpl *strategy,
- unsigned connectionId) {
- StrategyLoadBalancer *lb = (StrategyLoadBalancer *)strategy->context;
-
- PARCUnsigned *cid = parcUnsigned_Create(connectionId);
-
- if (parcHashMap_Contains(lb->strategy_state, cid)) {
- StrategyNexthopState *state =
- (StrategyNexthopState *)parcHashMap_Get(lb->strategy_state, cid);
- parcObject_Release((void**)&state);
-
- parcHashMap_Remove(lb->strategy_state, cid);
-#ifndef WITH_POLICY
- numberSet_Remove(lb->nexthops, connectionId);
-#endif /* WITH_POLICY */
- _strategyLoadBalancer_resetState(strategy);
- }
-
- parcUnsigned_Release(&cid);
-}
-
-static void _strategyLoadBalancer_ImplDestroy(StrategyImpl **strategyPtr) {
- parcAssertNotNull(strategyPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*strategyPtr,
- "Parameter must dereference to non-null pointer");
-
- StrategyImpl *impl = *strategyPtr;
- StrategyLoadBalancer *strategy = (StrategyLoadBalancer *)impl->context;
- if (parcHashMap_Size(strategy->strategy_state) > 0) {
- PARCIterator *it = parcHashMap_CreateKeyIterator(strategy->strategy_state);
- while (parcIterator_HasNext(it)) {
- PARCUnsigned *cid = parcIterator_Next(it);
- StrategyNexthopState *state =
- (StrategyNexthopState *) parcHashMap_Get(strategy->strategy_state, cid);
- parcObject_Release((void **) &state);
- }
- parcIterator_Release(&it);
- }
-
- parcHashMap_Release(&(strategy->strategy_state));
-#ifndef WITH_POLICY
- numberSet_Release(&(strategy->nexthops));
-#endif /* ! WITH_POLICY */
-
- parcMemory_Deallocate((void **) &strategy);
- parcMemory_Deallocate((void **) &impl);
- *strategyPtr = NULL;
-}
diff --git a/hicn-light/src/hicn/strategies/load_balancer.c b/hicn-light/src/hicn/strategies/load_balancer.c
new file mode 100644
index 000000000..0e1a170f7
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/load_balancer.c
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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/hicn-light/config.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <hicn/core/strategy.h>
+#include <hicn/core/strategy_vft.h>
+#include <hicn/core/nexthops.h>
+#include <hicn/core/fib_entry.h>
+
+#include "load_balancer.h"
+
+#define AVG_PI_THRESHOLD 1e-3
+#define AVG_PI_MIN 0.1
+
+#define ALPHA 0.9
+
+/* Shorthand */
+#define nexthop_state_t strategy_load_balancer_nexthop_state_t
+#define nexthop_state(nexthops, i) (&nexthops->state[i].load_balancer)
+
+static const nexthop_state_t NEXTHOP_STATE_INIT = {
+ .pi = 0,
+ .avg_pi = 0.0,
+ .weight = 1,
+};
+
+static inline void update_state(nexthop_state_t *state) {
+ state->avg_pi = (state->avg_pi * ALPHA) + (state->pi * 1 - ALPHA);
+ if (state->avg_pi < AVG_PI_THRESHOLD) state->avg_pi = AVG_PI_MIN;
+ state->weight = 1 / state->avg_pi;
+}
+
+static inline void update_state_inc(nexthop_state_t *state) {
+ state->pi++;
+ update_state(state);
+}
+
+static inline void update_state_dec(nexthop_state_t *state) {
+ if (state->pi > 0) state->pi--;
+ update_state(state);
+}
+
+static inline void reset_all(nexthops_t *nexthops) {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ (void)nexthop;
+ nexthops->state[i].load_balancer = NEXTHOP_STATE_INIT;
+ });
+}
+
+static int strategy_load_balancer_initialize(strategy_entry_t *entry,
+ const void *forwarder) {
+ /* No reset, this will be done when a nexthop is added */
+ entry->forwarder = forwarder;
+ return 0;
+}
+
+static int strategy_load_balancer_finalize(strategy_entry_t *entry) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_load_balancer_add_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ off_t offset) {
+ /* We reset the state of all nexthops */
+ reset_all(nexthops);
+ return 0;
+}
+
+static int strategy_load_balancer_remove_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ off_t offset) {
+ reset_all(nexthops);
+ return 0;
+}
+
+static nexthops_t *strategy_load_balancer_lookup_nexthops(
+ strategy_entry_t *entry, nexthops_t *nexthops, const msgbuf_t *msgbuf) {
+ if (nexthops_get_curlen(nexthops) == 0) return nexthops;
+ /* Compute the sum of weights of potential next hops */
+ double sum = 0;
+ nexthops_enumerate(nexthops, i, nexthop, {
+ (void)nexthop;
+ sum += nexthops_state(nexthops, i).load_balancer.weight;
+ });
+
+ /* Perform weighted random selection */
+ double distance = (double)rand() * sum / ((double)RAND_MAX + 1);
+
+ nexthops_enumerate(nexthops, i, nexthop, {
+ distance -= nexthop_state(nexthops, i)->weight;
+ if (distance < 0) {
+ nexthops_select(nexthops, i);
+ update_state_inc(nexthop_state(nexthops, i));
+ break;
+ }
+ });
+ return nexthops;
+}
+
+static int strategy_load_balancer_on_timeout(
+ strategy_entry_t *entry, nexthops_t *nexthops,
+ const nexthops_t *timeout_nexthops) {
+ /*
+ * As we have few nexthops in FIB entry, and even fewer selected ones in
+ * nexthops, we can allow for linear search that will be very efficient
+ * CPU-wise.
+ */
+ nexthops_foreach(timeout_nexthops, timeout_nexthop, {
+ nexthops_enumerate(nexthops, i, nexthop, {
+ if (nexthop == timeout_nexthop)
+ update_state_dec(nexthop_state(nexthops, i));
+ });
+ });
+ return 0;
+}
+
+static int strategy_load_balancer_on_data(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *data_nexthops,
+ const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation,
+ Ticks objReception) {
+ return strategy_load_balancer_on_timeout(entry, nexthops, data_nexthops);
+}
+
+#undef nexthop_state_t
+
+DECLARE_STRATEGY(load_balancer);
+
+#undef nexthop_state_t
diff --git a/hicn-light/src/hicn/config/controlUpdate.h b/hicn-light/src/hicn/strategies/load_balancer.h
index 0007ab653..f7447d928 100644
--- a/hicn-light/src/hicn/config/controlUpdate.h
+++ b/hicn-light/src/hicn/strategies/load_balancer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,22 +14,24 @@
*/
/**
- * @file control_Update.h
- * @brief Root node for the "update" commands
- *
- * Implements the "update" node of the CLI tree.
- *
+ * Forward on the less loaded path
*/
-#ifndef controlUpdate_h
-#define controlUpdate_h
+#ifndef HICNLIGHT_STRATEGY_LOAD_BALANCER_H
+#define HICNLIGHT_STRATEGY_LOAD_BALANCER_H
-#ifdef WITH_POLICY
+typedef struct {
+ unsigned int pi;
+ double avg_pi;
+ double weight;
+} strategy_load_balancer_nexthop_state_t;
-#include <hicn/config/controlState.h>
-CommandOps *controlUpdate_Create(ControlState *state);
-CommandOps *controlUpdate_HelpCreate(ControlState *state);
+typedef struct {
+ void *_;
+} strategy_load_balancer_state_t;
-#endif /* WITH_POLICY */
+typedef struct {
+ void *_;
+} strategy_load_balancer_options_t;
-#endif // controlUpdate_h
+#endif /* HICNLIGHT_STRATEGY_LOAD_BALANCER_H */
diff --git a/hicn-light/src/hicn/strategies/local_prefixes.c b/hicn-light/src/hicn/strategies/local_prefixes.c
new file mode 100644
index 000000000..fb161ab2a
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/local_prefixes.c
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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 "local_prefixes.h"
+#include <hicn/core/forwarder.h>
+#include <hicn/core/nexthops.h>
+#include <hicn/core/mapme.h>
+
+#define MAX_PREFIXES 10
+
+struct local_prefixes_s {
+ hicn_prefix_t local_prefixes[MAX_PREFIXES];
+ unsigned len;
+};
+
+local_prefixes_t *create_local_prefixes() {
+ local_prefixes_t *lp = calloc(1, sizeof(local_prefixes_t));
+ if (!lp) return NULL;
+ return lp;
+}
+
+void free_local_prefixes(local_prefixes_t *lp) { free(lp); }
+
+unsigned local_prefixes_get_len(local_prefixes_t *prefixes) {
+ return prefixes->len;
+}
+
+bool contain_prefix(const local_prefixes_t *prefixes,
+ const hicn_prefix_t *prefix) {
+ for (unsigned i = 0; i < prefixes->len; i++) {
+ if (hicn_prefix_equals(&(prefixes->local_prefixes[i]), prefix)) return true;
+ }
+ return false;
+}
+
+void local_prefixes_add_prefixes(local_prefixes_t *prefixes,
+ local_prefixes_t *new_prefixes) {
+ // if there is not enough space for the new prefixes they are not added
+ unsigned i = 0;
+ while ((i < new_prefixes->len) && (prefixes->len < MAX_PREFIXES)) {
+ if (!contain_prefix(prefixes, &(new_prefixes->local_prefixes[i]))) {
+ hicn_prefix_copy(&prefixes->local_prefixes[prefixes->len],
+ &new_prefixes->local_prefixes[i]);
+ prefixes->len++;
+ }
+ i++;
+ }
+}
+
+void local_prefixes_add_prefix(local_prefixes_t *prefixes,
+ const hicn_prefix_t *prefix) {
+ if (prefixes->len >= MAX_PREFIXES) return;
+ if (!contain_prefix(prefixes, prefix)) {
+ hicn_prefix_copy(&(prefixes->local_prefixes[prefixes->len]), prefix);
+ prefixes->len++;
+ }
+}
+
+void update_remote_node_paths(const void *nexthops, const void *forwarder,
+ local_prefixes_t *prefixes) {
+ if (!prefixes) return;
+ struct mapme_s *mapme = forwarder_get_mapme((forwarder_t *)forwarder);
+ fib_t *fib = forwarder_get_fib((forwarder_t *)forwarder);
+ for (unsigned i = 0; i < prefixes->len; i++) {
+ fib_entry_t *entry = fib_match_prefix(fib, &prefixes->local_prefixes[i]);
+ if (!entry) continue;
+ // XXX we don't want to force
+ mapme_set_adjacencies(mapme, entry, (nexthops_t *)nexthops, NULL);
+ }
+}
diff --git a/hicn-light/src/hicn/strategies/local_prefixes.h b/hicn-light/src/hicn/strategies/local_prefixes.h
new file mode 100644
index 000000000..9d7d8ec78
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/local_prefixes.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * struct used to store prefixes that are served locally.
+ * these prefixes are used in mapme messages to tell to the server which
+ * path to use to retrive the content produced locally.
+ * using this strategy the path selection done by the client can be
+ * replicated at the server
+ */
+
+#ifndef HICNLIGHT_LOCAL_PREFIXES_H
+#define HICNLIGHT_LOCAL_PREFIXES_H
+
+#include <hicn/name.h>
+
+typedef struct local_prefixes_s local_prefixes_t;
+
+local_prefixes_t* create_local_prefixes();
+
+void free_local_prefixes(local_prefixes_t* lp);
+
+unsigned local_prefixes_get_len(local_prefixes_t* prefixes);
+
+void local_prefixes_add_prefixes(local_prefixes_t* prefixes,
+ local_prefixes_t* new_prefixes);
+
+void local_prefixes_add_prefix(local_prefixes_t* prefixes,
+ const hicn_prefix_t* prefix);
+
+void update_remote_node_paths(const void* nexthops, const void* forwarder,
+ local_prefixes_t* prefixes);
+
+#endif /* HICNLIGHT_LOCAL_PREFIXES */
diff --git a/hicn-light/src/hicn/strategies/local_remote.c b/hicn-light/src/hicn/strategies/local_remote.c
new file mode 100644
index 000000000..7edf62643
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/local_remote.c
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hicn/core/nexthops.h>
+#include <hicn/core/forwarder.h>
+
+#include "local_remote.h"
+
+static int strategy_local_remote_initialize(strategy_entry_t *entry,
+ const void *forwarder) {
+ printf("INIT FWD STRATEGY REMOTE LOCAL\n");
+ srand((unsigned int)time(NULL));
+ entry->forwarder = forwarder;
+ return 0;
+}
+
+static int strategy_local_remote_finalize(strategy_entry_t *entry) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_local_remote_add_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ off_t offset) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_local_remote_remove_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ off_t offset) {
+ /* Nothing to do */
+ return 0;
+}
+
+static nexthops_t *strategy_local_remote_lookup_nexthops(
+ strategy_entry_t *entry, nexthops_t *nexthops, const msgbuf_t *msgbuf) {
+ if (!entry->forwarder) {
+ // the forwarder does not exists, drop packet
+ nexthops_disable_all(nexthops);
+ return nexthops;
+ }
+
+ unsigned cid = msgbuf_get_connection_id(msgbuf);
+ connection_table_t *table = forwarder_get_connection_table(entry->forwarder);
+ if (!table) {
+ // the connection table does not exists, drop packet.
+ nexthops_disable_all(nexthops);
+ return nexthops;
+ }
+
+ connection_t *in = connection_table_get_by_id(table, cid);
+ if (!in) {
+ // the ingress connection does not exists, drop packet.
+ nexthops_disable_all(nexthops);
+ return nexthops;
+ }
+
+ bool in_is_local = connection_is_local(in);
+ nexthops_enumerate(nexthops, i, nexthop, {
+ connection_t *out = connection_table_get_by_id(table, nexthop);
+ if (out) {
+ if (connection_is_local(out) != in_is_local) {
+ // this connection satisfies the requirements, send the intetest here.
+ nexthops_select(nexthops, i);
+ return nexthops;
+ }
+ }
+ });
+
+ // no out connection satisfies the requirements, drop packet.
+ nexthops_disable_all(nexthops);
+ return nexthops;
+}
+
+static int strategy_local_remote_on_data(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *data_nexthops,
+ const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation,
+ Ticks objReception) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_local_remote_on_timeout(
+ strategy_entry_t *entry, nexthops_t *nexthops,
+ const nexthops_t *timeout_nexthops) {
+ /* Nothing to do */
+ return 0;
+}
+
+DECLARE_STRATEGY(local_remote);
diff --git a/hicn-light/src/hicn/strategies/local_remote.h b/hicn-light/src/hicn/strategies/local_remote.h
new file mode 100644
index 000000000..58ca5abc3
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/local_remote.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Forward on a single path. If the incoming interest arrives from a local face,
+ * the interest shuold be forwarded only on a remote face. Viceversa, if the
+ * interest comes from remote it should be sent to a local face. Notice that if
+ * the condition cannot be satified (e.g. an interest comes from a local face
+ * and only an other local face can be satified to send the interest) the
+ * interest is dropped
+ */
+
+#ifndef HICNLIGHT_STRATEGY_LOCAL_REMOTE_H
+#define HICNLIGHT_STRATEGY_LOCAL_REMOTE_H
+
+typedef struct {
+ void *_;
+} strategy_loc_rem_nexthop_state_t;
+
+typedef struct {
+ void *_;
+} strategy_loc_rem_state_t;
+
+typedef struct {
+ void *_;
+} strategy_loc_rem_options_t;
+
+#endif /* HICNLIGHT_STRATEGY_LOCAL_REMOTE_H */
diff --git a/hicn-light/src/hicn/strategies/lowLatency.c b/hicn-light/src/hicn/strategies/lowLatency.c
deleted file mode 100644
index 61bffe243..000000000
--- a/hicn-light/src/hicn/strategies/lowLatency.c
+++ /dev/null
@@ -1,851 +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/hicn-light/config.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <math.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_HashMap.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-#include <parc/algol/parc_Unsigned.h>
-
-#include <hicn/core/messageHandler.h>
-
-#include <hicn/strategies/lowLatency.h>
-#include <hicn/strategies/nexthopStateLowLatency.h>
-
-const unsigned STABILITY_FACTOR = 15;
-const unsigned MAX_SWITCH_TRY = 10;
-const unsigned MAX_LATENCY_DIFF = 10;
-const unsigned MAX_TOLLERATED_LATENCY_DIFF = 15;
-const unsigned MAX_ROUNDS_MP_WITHOUT_CHECK = 2;
-const unsigned MAX_ROUNDS_AVOIDING_MULTIPATH = 40; //about 20 sec
-const unsigned MAX_ROUNDS_WITH_ERROR = 4;
-const unsigned PROBE_LIFETIME = 500; //ms
-
-static void _strategyLowLatency_ReceiveObject(StrategyImpl *strategy,
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception);
-static void _strategyLowLatency_OnTimeout(StrategyImpl *strategy,
- const NumberSet *egressId);
-static NumberSet *_strategyLowLatency_LookupNexthop(
- StrategyImpl *strategy,
-#ifdef WITH_POLICY
- NumberSet * nexthops,
-#endif /* WITH_POLICY */
- const Message *interestMessage);
-#ifndef WITH_POLICY
-static NumberSet *_strategyLowLatency_ReturnNexthops(StrategyImpl *strategy);
-static unsigned _strategyLowLatency_CountNexthops(StrategyImpl *strategy);
-#endif /* ! WITH_POLICY */
-static void _strategyLowLatency_AddNexthop(StrategyImpl *strategy,
- unsigned connectionId);
-static void _strategyLowLatency_RemoveNexthop(StrategyImpl *strategy,
- unsigned connectionId);
-static void _strategyLowLatency_ImplDestroy(StrategyImpl **strategyPtr);
-static strategy_type _strategyLowLatency_GetStrategy(StrategyImpl *strategy);
-
-static StrategyImpl _template = {
- .context = NULL,
- .receiveObject = &_strategyLowLatency_ReceiveObject,
- .onTimeout = &_strategyLowLatency_OnTimeout,
- .lookupNexthop = &_strategyLowLatency_LookupNexthop,
-#ifndef WITH_POLICY
- .returnNexthops = &_strategyLowLatency_ReturnNexthops,
- .countNexthops = &_strategyLowLatency_CountNexthops,
-#endif /* ! WITH_POLICY */
- .addNexthop = &_strategyLowLatency_AddNexthop,
- .removeNexthop = &_strategyLowLatency_RemoveNexthop,
- .destroy = &_strategyLowLatency_ImplDestroy,
- .getStrategy = &_strategyLowLatency_GetStrategy,
-};
-
-struct strategy_low_latency;
-typedef struct strategy_low_latency StrategyLowLatency;
-
-struct strategy_low_latency {
- // hash map from connectionId to StrategyNexthopStateLL
- PARCHashMap *strategy_state;
- //hash map from sequence number to ticks (sent time)
- PARCHashMap *pending_probes_ticks;
- //hash map from sequence number to face id
- PARCHashMap *pending_probes_faces;
- const Forwarder * forwarder;
- PARCEventTimer *sendProbes;
- PARCEventTimer *computeBestFace;
- uint8_t * probe;
- hicn_name_t * name;
- StrategyNexthopStateLL * bestFaces[2];
- unsigned round;
- unsigned rounds_in_multipath;
- unsigned rounds_with_error;
- unsigned rounds_avoiding_multipath;
- bool use2paths;
- bool avoid_multipath;
- unsigned related_prefixes_len;
- Name **related_prefixes;
-#ifndef WITH_POLICY
- NumberSet *nexthops;
-#endif /* ! WITH_POLICY */
-};
-
-static void strategyLowLatency_SendProbesCB(int fd, PARCEventType which_event,
- void *data){
- parcAssertTrue(which_event & PARCEventType_Timeout,
- "Event incorrect, expecting %X set, got %X",
- PARCEventType_Timeout, which_event);
-
- StrategyLowLatency *ll = (StrategyLowLatency *) data;
-
- //delete old pending probes
- if(parcHashMap_Size(ll->pending_probes_ticks) != 0){
- Ticks now = forwarder_GetTicks(ll->forwarder);
- PARCIterator *iterator = parcHashMap_CreateKeyIterator(ll->pending_probes_ticks);
- NumberSet *to_remove = numberSet_Create();
- while(parcIterator_HasNext(iterator)) {
- PARCUnsigned *parc_seq = (PARCUnsigned *) parcIterator_Next(iterator);
- PARCUnsigned *parc_time = (PARCUnsigned *) parcHashMap_Get(ll->pending_probes_ticks, parc_seq);
- Ticks sent_time = parcUnsigned_GetUnsigned(parc_time);
- if((now - sent_time) > PROBE_LIFETIME){
- //probes to delete
- numberSet_Add(to_remove, parcUnsigned_GetUnsigned(parc_seq));
- }
- }
- parcIterator_Release(&iterator);
-
- for(int i = 0; i < numberSet_Length(to_remove); i++){
- PARCUnsigned *prob_seq = parcUnsigned_Create(numberSet_GetItem(to_remove,i));
- PARCUnsigned *cid = (PARCUnsigned *) parcHashMap_Get(ll->pending_probes_faces, prob_seq);
- StrategyNexthopStateLL *state =
- (StrategyNexthopStateLL *) parcHashMap_Get(ll->strategy_state, cid);
- strategyNexthopStateLL_LostProbe(state);
- parcHashMap_Remove(ll->pending_probes_ticks, prob_seq);
- parcHashMap_Remove(ll->pending_probes_faces, prob_seq);
- parcUnsigned_Release(&prob_seq);
- }
- numberSet_Release(&to_remove);
- }
-
- ConnectionTable * ct = forwarder_GetConnectionTable(ll->forwarder);
-
- PARCIterator *iterator = parcHashMap_CreateKeyIterator(ll->strategy_state);
- while(parcIterator_HasNext(iterator)){
- PARCUnsigned *cid = (PARCUnsigned *) parcIterator_Next(iterator);
- Connection *conn =
- (Connection *)connectionTable_FindById(ct,
- parcUnsigned_GetUnsigned(cid));
- if(!conn)
- continue;
-
- StrategyNexthopStateLL *state =
- (StrategyNexthopStateLL *) parcHashMap_Get(ll->strategy_state, cid);
-
- //probe only usable paths
- if(!strategyNexthopStateLL_IsAllowed(state))
- continue;
-
- uint32_t seq = rand();
- messageHandler_SetProbeName(ll->probe, HF_INET6_TCP,
- ll->name, seq);
- connection_Probe(conn, ll->probe);
-
- PARCUnsigned *parc_seq = parcUnsigned_Create(seq);
- Ticks now = forwarder_GetTicks(ll->forwarder);
- PARCUnsigned *parc_time = parcUnsigned_Create((unsigned int)now);
- parcHashMap_Put(ll->pending_probes_ticks, parc_seq, parc_time);
- parcHashMap_Put(ll->pending_probes_faces, parc_seq, cid);
- strategyNexthopStateLL_SentProbe(state);
- parcUnsigned_Release(&parc_seq);
- parcUnsigned_Release(&parc_time);
- }
- parcIterator_Release(&iterator);
-
- struct timeval timeout = {0,50000};
- parcEventTimer_Start(ll->sendProbes, &timeout);
-}
-
-static void strategyLowLatency_SendMapmeUpdate(StrategyLowLatency *ll,
- const NumberSet * nexthops){
- MapMe * mapme = forwarder_getMapmeInstance(ll->forwarder);
- FIB * fib = forwarder_getFib((Forwarder*) ll->forwarder);
- if(fib != NULL){
- for(unsigned i = 0; i < ll->related_prefixes_len; i++){
- FibEntry *fibEntry = fib_MatchName(fib, ll->related_prefixes[i]);
- if(fibEntry != NULL){
- mapme_maybe_send_updates(mapme, fibEntry, nexthops);
- }
- }
- }
-}
-
-static void strategyLowLatency_SelectBestFaces(StrategyLowLatency *ll,
- bool new_round){
-
- StrategyNexthopStateLL * old_faces[2];
- old_faces[0] = ll->bestFaces[0];
- old_faces[1] = ll->bestFaces[1];
-
- if(new_round){
- ll->round++;
- }
-
- if(parcHashMap_Size(ll->strategy_state) == 0){
- ll->bestFaces[0] = NULL;
- ll->bestFaces[1] = NULL;
- ll->use2paths = false;
- goto NEW_ROUND;
- }
-
- if(ll->use2paths && ll->bestFaces[0] != NULL && ll->bestFaces[1] != NULL){
- //multipath case
-
- if(!strategyNexthopStateLL_IsLossy(ll->bestFaces[0])
- && !strategyNexthopStateLL_IsLossy(ll->bestFaces[1])
- && strategyNexthopStateLL_IsAllowed(ll->bestFaces[0])
- && strategyNexthopStateLL_IsAllowed(ll->bestFaces[1])){
-
- if(ll->rounds_in_multipath < MAX_ROUNDS_MP_WITHOUT_CHECK){
- //we are at the first rounds of the multipath let's wait a bit
- //(MAX_ROUNDS_MP_WITHOUT_CHECK) to make the queuing converge
- ll->rounds_in_multipath++;
- goto NEW_ROUND;
- }
-
- //we need to decide if we want ot keep using two paths or not
- ll->rounds_in_multipath++;
- double rtt0 = strategyNexthopStateLL_GetRTTLive(ll->bestFaces[0]);
- double rtt1 = strategyNexthopStateLL_GetRTTLive(ll->bestFaces[1]);
- double diff = fabs(rtt0 - rtt1);
-
- if(diff < MAX_LATENCY_DIFF){
- //everything is working, keep using the two paths
- ll->rounds_with_error = 0;
- goto NEW_ROUND;
- }
-
- //check for how many rounds we had problems
- if(ll->rounds_with_error < MAX_ROUNDS_WITH_ERROR &&
- diff < MAX_TOLLERATED_LATENCY_DIFF){
- //we can tollerate few round with errors
- ll->rounds_with_error++;
- goto NEW_ROUND;
- }
-
- //prevent the usage of multiple paths
- ll->rounds_with_error = 0;
- ll->avoid_multipath = true;
- ll->rounds_avoiding_multipath = 0;
- } //else
- //at least one of the two path is lossy
- //or it is not allowed by the policies.
- //search for a better possibility
- }
-
- ll->bestFaces[0] = NULL;
- ll->bestFaces[1] = NULL;
-
- //check if there is at least one non lossy connection
- PARCIterator *iterator = parcHashMap_CreateKeyIterator(ll->strategy_state);
- bool check_losses = true;
- bool found_good_face = false;
- while(parcIterator_HasNext(iterator) && !found_good_face){
- PARCUnsigned *cid = (PARCUnsigned *) parcIterator_Next(iterator);
- const StrategyNexthopStateLL *state = parcHashMap_Get(ll->strategy_state, cid);
- if(!strategyNexthopStateLL_IsLossy(state) &&
- strategyNexthopStateLL_IsAllowed(state)){
- found_good_face = true;
- }
- }
- parcIterator_Release(&iterator);
- if(!found_good_face){
- // all the available faces are lossy, so we take into account only
- // the latency computed with the probes
- check_losses = false;
- }
-
- if(ll->bestFaces[0] == NULL){
- //try to take a random face
- PARCIterator *iterator = parcHashMap_CreateKeyIterator(ll->strategy_state);
- bool face_found = false;
- while(parcIterator_HasNext(iterator) && !face_found) {
- PARCUnsigned *cid = (PARCUnsigned *) parcIterator_Next(iterator);
- StrategyNexthopStateLL *state = (StrategyNexthopStateLL *)
- parcHashMap_Get(ll->strategy_state, cid);
-
- if((check_losses && strategyNexthopStateLL_IsLossy(state)) ||
- !strategyNexthopStateLL_IsAllowed(state)){
- //skip the face
- continue;
- }
-
- ll->bestFaces[0] = state;
- face_found = true;
- }
- parcIterator_Release(&iterator);
- }
-
- if(ll->bestFaces[0] == NULL){
- //no usable face exists
- ll->bestFaces[0] = NULL;
- ll->bestFaces[1] = NULL;
- ll->use2paths = false;
- goto NEW_ROUND;
- }
-
- double bestRtt = strategyNexthopStateLL_GetRTTLive(ll->bestFaces[0]);
-
- if(ll->avoid_multipath)
- ll->rounds_avoiding_multipath++;
-
- if(ll->rounds_avoiding_multipath > MAX_ROUNDS_AVOIDING_MULTIPATH){
- ll->avoid_multipath = false;
- ll->rounds_avoiding_multipath = 0;
- }
-
- iterator = parcHashMap_CreateKeyIterator(ll->strategy_state);
- while (parcIterator_HasNext(iterator)) {
-
- PARCUnsigned *cid = (PARCUnsigned *) parcIterator_Next(iterator);
- StrategyNexthopStateLL *state = (StrategyNexthopStateLL *)
- parcHashMap_Get(ll->strategy_state, cid);
- double rtt = strategyNexthopStateLL_GetRTTLive(state);
-
- if((check_losses && strategyNexthopStateLL_IsLossy(state)) ||
- !strategyNexthopStateLL_IsAllowed(state)){
- //skip the face
- continue;
- }
-
- if(rtt + STABILITY_FACTOR < bestRtt){
- //maybe we found a better face
- double rttInUse = strategyNexthopStateLL_GetRTTInUse(state);
- unsigned try = strategyNexthopStateLL_GetTryToSwitch(state);
-
- //we check the rtt in use to check if the new face that we found
- //gets congested when we use it to send the traffic
- if(rttInUse < bestRtt || try > MAX_SWITCH_TRY){
- //we have a new best face!
- strategyNexthopStateLL_ResetTryToSwitch((StrategyNexthopStateLL*) state);
- bestRtt = rtt;
- if(ll->bestFaces[0] != NULL)
- strategyNexthopStateLL_SetUnusedFace(ll->bestFaces[0]);
- ll->bestFaces[0] = (StrategyNexthopStateLL*) state;
- }else{
- //in this case we should switch but we wait MAX_SWITCH_TRY
- //before switch to avoid ossillations between different paths
- strategyNexthopStateLL_IncreaseTryToSwitch(
- (StrategyNexthopStateLL*) state, ll->round);
- }
- }
- }
-
- parcIterator_Release(&iterator);
-
- if(ll->bestFaces[0] == NULL){
- //we found no face so return
- ll->bestFaces[0] = NULL;
- ll->bestFaces[1] = NULL;
- ll->use2paths = false;
- goto NEW_ROUND;
- }
-
- if(parcHashMap_Size(ll->strategy_state) == 1 || ll->avoid_multipath){
- //in this case (one face available or avoid multipath) we stop the
- //search here. Just reset face 1 if needed
- if(ll->bestFaces[1] != NULL){
- strategyNexthopStateLL_SetUnusedFace(ll->bestFaces[1]);
- ll->bestFaces[1] = NULL;
- }
- ll->use2paths = false;
- goto NEW_ROUND;
- }
-
- //if we are here we have more than 1 interface, so we search for a second one
- //to use in case of multipath
- iterator = parcHashMap_CreateKeyIterator(ll->strategy_state);
- while (parcIterator_HasNext(iterator)) {
- PARCUnsigned *cid = (PARCUnsigned *) parcIterator_Next(iterator);
- if(parcUnsigned_GetUnsigned(cid) !=
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[0])){
-
- StrategyNexthopStateLL *state = (StrategyNexthopStateLL *)
- parcHashMap_Get(ll->strategy_state, cid);
-
- if((check_losses && strategyNexthopStateLL_IsLossy(state)) ||
- !strategyNexthopStateLL_IsAllowed(state)){
- //skip the face
- continue;
- }
-
- if(ll->bestFaces[1] == NULL){
- //in case of 2 faces we should pass always here
- ll->bestFaces[1] = state;
- }else{
- //TODO this must be tested with more then 2 faces
- double rtt1 = strategyNexthopStateLL_GetRTTLive(ll->bestFaces[1]);
- double rttNewFace = strategyNexthopStateLL_GetRTTLive(state);
- if(rttNewFace + STABILITY_FACTOR < rtt1){
- strategyNexthopStateLL_SetUnusedFace(ll->bestFaces[1]);
- ll->bestFaces[1] = state;
- }
- }
- }
- }
- parcIterator_Release(&iterator);
-
- if(ll->bestFaces[1] != NULL){
- //we are not using the second face yet so we use the normal rtt for comparison
- double rtt0 = strategyNexthopStateLL_GetRTTProbe(ll->bestFaces[0]);
- double rtt1 = strategyNexthopStateLL_GetRTTProbe(ll->bestFaces[1]);
- double diff = fabs(rtt0 - rtt1);
- if(diff < MAX_LATENCY_DIFF) {
- //let's start to use 2 paths
- ll->rounds_with_error = 0;
- ll->use2paths = true;
- ll->rounds_in_multipath = 0;
- }else{
- //we use only one path
- strategyNexthopStateLL_SetUnusedFace(ll->bestFaces[1]);
- ll->bestFaces[1] = NULL;
- ll->use2paths = false;
- }
- }else{
- ll->use2paths = false;
- }
-
- NEW_ROUND:
- {
- Logger * log = forwarder_GetLogger(ll->forwarder);
- if(log != NULL &&
- logger_IsLoggable(log, LoggerFacility_Strategy, PARCLogLevel_Info)){
- if(ll->use2paths){
- logger_Log(log, LoggerFacility_Strategy, PARCLogLevel_Info,
- __func__, "use 2 paths. rtt face %d = %f queue = %f is_lossy = %d,"
- "rtt face %d = %f queue = %f is_lossy = %d\n",
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]),
- strategyNexthopStateLL_GetRTTLive(ll->bestFaces[0]),
- strategyNexthopStateLL_GetQueuing(ll->bestFaces[0]),
- strategyNexthopStateLL_IsLossy(ll->bestFaces[0]),
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[1]),
- strategyNexthopStateLL_GetRTTLive(ll->bestFaces[1]),
- strategyNexthopStateLL_GetQueuing(ll->bestFaces[1]),
- strategyNexthopStateLL_IsLossy(ll->bestFaces[1]));
- }else{
- if(ll->bestFaces[0] != NULL){
- logger_Log(log, LoggerFacility_Strategy,
- PARCLogLevel_Info, __func__,
- "use 1 path. rtt face %d = %f is_lossy = %d, "
- "(avoid multipath = %d)\n",
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]),
- strategyNexthopStateLL_GetRTTLive(ll->bestFaces[0]),
- strategyNexthopStateLL_IsLossy(ll->bestFaces[0]),
- ll->avoid_multipath);
- }else{
- logger_Log(log, LoggerFacility_Strategy, PARCLogLevel_Info,
- __func__, "no face to use!\n");
- }
- }
- }
- }
-
- //update the round only at the end for all the faces
- if(new_round){
- PARCIterator * iterator = parcHashMap_CreateKeyIterator(ll->strategy_state);
- while (parcIterator_HasNext(iterator)) {
- PARCUnsigned *cid = (PARCUnsigned *) parcIterator_Next(iterator);
- strategyNexthopStateLL_StartNewRound((StrategyNexthopStateLL *)
- parcHashMap_Get(ll->strategy_state, cid));
- }
- parcIterator_Release(&iterator);
- }
-
- //mapme updates
- //if ll->bestFaces[0] == NULL we don't have any output faces
- //so don't need to send any updates since we are disconnected
- if(ll->related_prefixes_len != 0){
- if(ll->bestFaces[0] != NULL){
- NumberSet *out = numberSet_Create();
- if(old_faces[0] == NULL ||
- (strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]) !=
- strategyNexthopStateLL_GetFaceId(old_faces[0]))){
- //there is a new face 0 so we need a map me update
- //if ll->bestFaces[1] != NULL we need to send the update
- //even if it is the same as before
- numberSet_Add(out,
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]));
- if(ll->bestFaces[1] != NULL){
- numberSet_Add(out,
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[1]));
- }
- strategyLowLatency_SendMapmeUpdate(ll,out);
- }else{
- if(ll->bestFaces[1] != NULL){
- if(old_faces[1] == NULL ||
- (strategyNexthopStateLL_GetFaceId(ll->bestFaces[1]) !=
- strategyNexthopStateLL_GetFaceId(old_faces[1]))){
- //send a mapme both with face 0 and face 1
- numberSet_Add(out,
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]));
- numberSet_Add(out,
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[1]));
- strategyLowLatency_SendMapmeUpdate(ll,out);
- }
- }else{
- if(old_faces[1] != NULL){
- //in the previuos round we were using two faces, now only one
- //send update with only face 0
- numberSet_Add(out,
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]));
- strategyLowLatency_SendMapmeUpdate(ll,out);
- }
- }
- }
- numberSet_Release(&out);
- }
- }
-}
-
-static void strategyLowLatency_BestFaceCB(int fd, PARCEventType which_event,
- void *data){
- parcAssertTrue(which_event & PARCEventType_Timeout,
- "Event incorrect, expecting %X set, got %X",
- PARCEventType_Timeout, which_event);
-
- StrategyLowLatency * ll = (StrategyLowLatency *) data;
- strategyLowLatency_SelectBestFaces(ll, true);
-
- struct timeval timeout = {0, 500000};
- parcEventTimer_Start(ll->computeBestFace, &timeout);
-}
-
-StrategyImpl *strategyLowLatency_Create() {
- StrategyLowLatency *strategy =
- parcMemory_AllocateAndClear(sizeof(StrategyLowLatency));
- parcAssertNotNull(strategy, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(StrategyLowLatency));
-
- strategy->strategy_state = parcHashMap_Create();
- strategy->pending_probes_ticks = parcHashMap_Create();
- strategy->pending_probes_faces = parcHashMap_Create();
-#ifndef WITH_POLICY
- strategy->nexthops = numberSet_Create();
-#endif /* ! WITH_POLICY */
- srand((unsigned int)time(NULL));
-
- StrategyImpl *impl = parcMemory_AllocateAndClear(sizeof(StrategyImpl));
- parcAssertNotNull(impl, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(StrategyImpl));
- memcpy(impl, &_template, sizeof(StrategyImpl));
- impl->context = strategy;
-
- return impl;
-}
-
-void strategyLowLatency_SetStrategy(StrategyImpl *strategy,
- const Forwarder * forwarder,
- const FibEntry * fibEntry,
- unsigned related_prefixes_len,
- Name **related_prefixes) {
- StrategyLowLatency *ll =
- (StrategyLowLatency *)strategy->context;
- ll->forwarder = forwarder;
-
- //create probe packet
- ll->probe = messageHandler_CreateProbePacket(HF_INET6_TCP, PROBE_LIFETIME);
- ip_prefix_t address;
- nameBitvector_ToIPAddress(name_GetContentName(
- fibEntry_GetPrefix(fibEntry)), &address);
- ll->name = messageHandler_CreateProbeName(&address);
-
-
- Dispatcher *dispatcher = forwarder_GetDispatcher((Forwarder *)ll->forwarder);
- ll->sendProbes = dispatcher_CreateTimer(dispatcher, false,
- strategyLowLatency_SendProbesCB, ll);
-
- ll->round = 0;
- ll->rounds_in_multipath = 0;
- ll->rounds_with_error = 0;
- ll->rounds_avoiding_multipath = 0;
- ll->use2paths = false;
- ll->avoid_multipath = false;
-
- ll->related_prefixes_len = related_prefixes_len;
- ll->related_prefixes = malloc(sizeof(Name *) * ll->related_prefixes_len);
- for(unsigned i = 0; i < ll->related_prefixes_len; i++){
- ll->related_prefixes[i] = name_Copy(related_prefixes[i]);
- }
-
- ll->computeBestFace = dispatcher_CreateTimer(dispatcher, false,
- strategyLowLatency_BestFaceCB, ll);
-}
-
-void _startTimers(StrategyImpl *strategy){
- StrategyLowLatency *ll =
- (StrategyLowLatency *)strategy->context;
-
- struct timeval timeoutProbes = {0,10000};
- parcEventTimer_Start(ll->sendProbes, &timeoutProbes);
- struct timeval timeoutBF = {1,0};
- parcEventTimer_Start(ll->computeBestFace, &timeoutBF);
-}
-
-void _stopTimers(StrategyImpl *strategy){
- StrategyLowLatency *ll =
- (StrategyLowLatency *)strategy->context;
-
- parcEventTimer_Stop(ll->sendProbes);
- parcEventTimer_Stop(ll->computeBestFace);
-}
-
-// =======================================================
-// Dispatch API
-
-strategy_type _strategyLowLatency_GetStrategy(StrategyImpl *strategy) {
- return SET_STRATEGY_LOW_LATENCY;
-}
-
-static void _strategyLowLatency_ReceiveObject(StrategyImpl *strategy,
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception) {
- StrategyLowLatency *ll = (StrategyLowLatency *)strategy->context;
-
- if(!messageHandler_IsAProbe(message_FixedHeader(objectMessage)))
- return;
-
- uint32_t seq = messageHandler_GetSegment(message_FixedHeader(objectMessage));
- PARCUnsigned *parc_seq = parcUnsigned_Create(seq);
- if (!parcHashMap_Contains(ll->pending_probes_ticks, parc_seq)){
- parcUnsigned_Release(&parc_seq);
- return;
- }
-
- //here numberSet_Length(egressId) should be 1
- for (unsigned i = 0; i < numberSet_Length(egressId); i++) {
- unsigned outId = numberSet_GetItem(egressId, i);
- PARCUnsigned *cid = parcUnsigned_Create(outId);
-
- const StrategyNexthopStateLL *state =
- parcHashMap_Get(ll->strategy_state, cid);
- if (state != NULL) {
- Ticks time = parcUnsigned_GetUnsigned(
- parcHashMap_Get(ll->pending_probes_ticks, parc_seq));
- Ticks now = forwarder_GetTicks(ll->forwarder);
- Ticks RTT = now - time;
- if(RTT <= 0)
- RTT = 1;
- strategyNexthopStateLL_AddRttSample(
- (StrategyNexthopStateLL *) state, (unsigned int)RTT);
- parcHashMap_Remove(ll->pending_probes_ticks, parc_seq);
- } else {
- // this may happen if we remove a face/route while downloading a file
- // we should ignore this timeout
- }
- parcUnsigned_Release(&cid);
- }
- parcUnsigned_Release(&parc_seq);
-}
-
-static void _strategyLowLatency_OnTimeout(StrategyImpl *strategy,
- const NumberSet *egressId) {}
-
-static NumberSet *_strategyLowLatency_LookupNexthop(StrategyImpl *strategy,
-#ifdef WITH_POLICY
- NumberSet * nexthops,
-#endif /* WITH_POLICY */
- const Message *interestMessage) {
- //unsigned out_connection;
- NumberSet *out = numberSet_Create();
-
- StrategyLowLatency *ll = (StrategyLowLatency *)strategy->context;
-
- //update is_allowed flag of all the next hops
- PARCIterator *iterator = parcHashMap_CreateKeyIterator(ll->strategy_state);
- while(parcIterator_HasNext(iterator)){
- PARCUnsigned *cid = (PARCUnsigned *) parcIterator_Next(iterator);
- StrategyNexthopStateLL *state =
- (StrategyNexthopStateLL *) parcHashMap_Get(ll->strategy_state, cid);
- if(numberSet_Contains(nexthops, parcUnsigned_GetUnsigned(cid))){
- strategyNexthopStateLL_SetIsAllowed(state,true);
- }else{
- strategyNexthopStateLL_SetIsAllowed(state,false);
- }
- }
- parcIterator_Release(&iterator);
-
- if(ll->bestFaces[0] != NULL &&
- !strategyNexthopStateLL_IsAllowed(ll->bestFaces[0])){
- //if ll->bestFaces[0] is not allowed we need to find a new face
- strategyLowLatency_SelectBestFaces(ll, false);
- }
-
- //at this point ll->bestFaces[0] must be allowed
- //single path case
- if(ll->bestFaces[0] != NULL && (ll->bestFaces[1] == NULL || !ll->use2paths)){
- strategyNexthopStateLL_SendPacket(ll->bestFaces[0]);
- numberSet_Add(out, strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]));
-
- //multipath case
- }else if(ll->bestFaces[0] != NULL && ll->bestFaces[1] != NULL && ll->use2paths){
- //it may happen that ll->bestFaces[1] is not allowed, in that case we send on
- //ll->bestFaces[0] until the next best face selection
- if(!strategyNexthopStateLL_IsAllowed(ll->bestFaces[1])){
- strategyNexthopStateLL_SendPacket(ll->bestFaces[0]);
- numberSet_Add(out, strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]));
- }else{
- double queue0 = strategyNexthopStateLL_GetQueuing(ll->bestFaces[0]);
- double queue1 = strategyNexthopStateLL_GetQueuing(ll->bestFaces[1]);
- double prob0 = 0.5;
- if(queue0 > 1 || queue1 > 1){
- prob0 = 1.0 - (queue0 / (queue0 + queue1));
- }
- double coin = ((double) rand() / (RAND_MAX));
- if(coin < prob0){
- strategyNexthopStateLL_SendPacket(ll->bestFaces[0]);
- numberSet_Add(out, strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]));
- }else{
- strategyNexthopStateLL_SendPacket(ll->bestFaces[1]);
- numberSet_Add(out, strategyNexthopStateLL_GetFaceId(ll->bestFaces[1]));
- }
- }
- }
- return out;
-}
-
-
-#ifndef WITH_POLICY
-static NumberSet *_strategyLowLatency_ReturnNexthops(StrategyImpl *strategy) {
- StrategyLoadBalancerLL *ll = (StrategyLoadBalancerLL *)strategy->context;
- return ll->nexthops;
-}
-
-unsigned _strategyLowLatency_CountNexthops(StrategyImpl *strategy) {
- StrategyLoadBalancerLL *ll = (StrategyLoadBalancerLL *)strategy->context;
- return (unsigned)numberSet_Length(ll->nexthops);
-}
-#endif /* ! WITH_POLICY */
-
-static void _strategyLowLatency_AddNexthop(StrategyImpl *strategy,
- unsigned connectionId) {
- PARCUnsigned *cid = parcUnsigned_Create(connectionId);
-
- StrategyLowLatency *ll = (StrategyLowLatency *)strategy->context;
-
- if (!parcHashMap_Contains(ll->strategy_state, cid)) {
- StrategyNexthopStateLL *state = strategyNexthopStateLL_Create(connectionId);
- parcHashMap_Put(ll->strategy_state, cid, state);
- if(ll->bestFaces[0] == NULL){
- ll->bestFaces[0] = state;
- }
-#ifndef WITH_POLICY
- numberSet_Add(ll->nexthops, connectionId);
-#endif /* WITH_POLICY */
- }
-
- if(parcHashMap_Size(ll->strategy_state) >= 2){
- _startTimers(strategy);
- }
-
- parcUnsigned_Release(&cid);
-}
-
-static void _strategyLowLatency_RemoveNexthop(StrategyImpl *strategy,
- unsigned connectionId) {
- StrategyLowLatency *ll = (StrategyLowLatency *)strategy->context;
-
- bool reset_bestFaces = false;
-
- if((ll->bestFaces[0] != NULL &&
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[0]) == connectionId) ||
- (ll->bestFaces[1] != NULL &&
- strategyNexthopStateLL_GetFaceId(ll->bestFaces[1]) == connectionId)){
- reset_bestFaces = true;
- }
-
- PARCUnsigned *cid = parcUnsigned_Create(connectionId);
-
- if (parcHashMap_Contains(ll->strategy_state, cid)) {
- parcHashMap_Remove(ll->strategy_state, cid);
-#ifndef WITH_POLICY
- numberSet_Remove(lb->nexthops, connectionId);
-#endif /* WITH_POLICY */
- }
-
- if(reset_bestFaces){
- ll->bestFaces[0] = NULL;
- ll->bestFaces[1] = NULL;
- strategyLowLatency_SelectBestFaces(ll, false);
- }
-
- if(parcHashMap_Size(ll->strategy_state) < 2){
- _stopTimers(strategy);
- }
-
- parcUnsigned_Release(&cid);
-}
-
-static void _strategyLowLatency_ImplDestroy(StrategyImpl **strategyPtr) {
- parcAssertNotNull(strategyPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*strategyPtr,
- "Parameter must dereference to non-null pointer");
-
- StrategyImpl *impl = *strategyPtr;
- StrategyLowLatency *strategy = (StrategyLowLatency *)impl->context;
-
- _stopTimers(impl);
-
- parcEventTimer_Destroy(&(strategy->sendProbes));
- parcEventTimer_Destroy(&(strategy->computeBestFace));
-
- if (parcHashMap_Size(strategy->strategy_state) > 0) {
- PARCIterator *it = parcHashMap_CreateKeyIterator(strategy->strategy_state);
- while (parcIterator_HasNext(it)) {
- PARCUnsigned *cid = parcIterator_Next(it);
- StrategyNexthopStateLL *state =
- (StrategyNexthopStateLL *)parcHashMap_Get(strategy->strategy_state, cid);
- parcObject_Release((void**)&state);
- }
- parcIterator_Release(&it);
- }
-
- parcHashMap_Release(&(strategy->strategy_state));
- parcHashMap_Release(&(strategy->pending_probes_ticks));
- parcHashMap_Release(&(strategy->pending_probes_faces));
-
- parcMemory_Deallocate(&(strategy->probe));
- parcMemory_Deallocate(&(strategy->name));
-
- for(unsigned i = 0; i < strategy->related_prefixes_len; i++){
- name_Release(&(strategy->related_prefixes[i]));
- }
- free(strategy->related_prefixes);
-
-#ifndef WITH_POLICY
- numberSet_Release(&(strategy->nexthops));
-#endif /* ! WITH_POLICY */
-
- parcMemory_Deallocate((void **)&strategy);
- parcMemory_Deallocate((void **)&impl);
- *strategyPtr = NULL;
-}
diff --git a/hicn-light/src/hicn/strategies/lowLatency.h b/hicn-light/src/hicn/strategies/lowLatency.h
deleted file mode 100644
index 736c8783d..000000000
--- a/hicn-light/src/hicn/strategies/lowLatency.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * Forward on the path with lowest latency
- */
-
-#ifndef lowLatency_h
-#define lowLatency_h
-
-#include <hicn/strategies/strategyImpl.h>
-#include <hicn/core/forwarder.h>
-
-StrategyImpl *strategyLowLatency_Create();
-
-void strategyLowLatency_SetStrategy(StrategyImpl *strategy,
- const Forwarder * forwarder,
- const FibEntry * fibEntry,
- unsigned related_prefixes_len,
- Name **related_prefixes);
-#endif // lowLatency_h
diff --git a/hicn-light/src/hicn/strategies/nexthopState.c b/hicn-light/src/hicn/strategies/nexthopState.c
deleted file mode 100644
index 40af14832..000000000
--- a/hicn-light/src/hicn/strategies/nexthopState.c
+++ /dev/null
@@ -1,212 +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/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/algol/parc_DisplayIndented.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Object.h>
-
-#include <parc/assert/parc_Assert.h>
-#include <hicn/strategies/nexthopState.h>
-
-#define AVG_PI_THRESHOLD 1e-3
-
-struct strategy_nexthop_state {
- unsigned int pi;
- double avg_pi;
- double weight;
-};
-
-static bool _strategyNexthopState_Destructor(
- StrategyNexthopState **instancePtr) {
- return true;
-}
-
-parcObject_ImplementAcquire(strategyNexthopState, StrategyNexthopState);
-
-parcObject_ImplementRelease(strategyNexthopState, StrategyNexthopState);
-
-parcObject_Override(
- StrategyNexthopState, PARCObject,
- .destructor = (PARCObjectDestructor *)_strategyNexthopState_Destructor,
- .copy = (PARCObjectCopy *)strategyNexthopState_Copy,
- .display = (PARCObjectDisplay *)strategyNexthopState_Display,
- .toString = (PARCObjectToString *)strategyNexthopState_ToString,
- .equals = (PARCObjectEquals *)strategyNexthopState_Equals,
- .compare = (PARCObjectCompare *)strategyNexthopState_Compare,
- .hashCode = (PARCObjectHashCode *)strategyNexthopState_HashCode,
- .display = (PARCObjectDisplay *)strategyNexthopState_Display);
-
-void strategyNexthopState_AssertValid(const StrategyNexthopState *instance) {
- parcAssertTrue(strategyNexthopState_IsValid(instance),
- "StrategyNexthopState is not valid.");
-}
-
-StrategyNexthopState *strategyNexthopState_Create() {
- StrategyNexthopState *result =
- parcObject_CreateInstance(StrategyNexthopState);
- if (result != NULL) {
- result->pi = 0;
- result->avg_pi = 0.0;
- result->weight = 1;
- }
- return result;
-}
-
-void strategyNexthopState_Reset(StrategyNexthopState *x) {
- x->pi = 0;
- x->avg_pi = 0.0;
- x->weight = 1;
-}
-
-int strategyNexthopState_Compare(const StrategyNexthopState *val,
- const StrategyNexthopState *other) {
- if (val == NULL) {
- if (other != NULL) {
- return -1;
- }
- } else if (other == NULL) {
- return 1;
- } else {
- strategyNexthopState_OptionalAssertValid(val);
- strategyNexthopState_OptionalAssertValid(other);
-
- if (val->pi < other->pi) {
- return -1;
- } else if (val->pi > other->pi) {
- return 1;
- }
-
- if (val->avg_pi < other->avg_pi) {
- return -1;
- } else if (val->avg_pi > other->avg_pi) {
- return 1;
- }
-
- if (val->weight < other->weight) {
- return -1;
- } else if (val->weight > other->weight) {
- return 1;
- }
- }
-
- return 0;
-}
-
-StrategyNexthopState *strategyNexthopState_Copy(
- const StrategyNexthopState *original) {
- StrategyNexthopState *result = strategyNexthopState_Create();
- result->pi = original->pi;
- result->avg_pi = original->avg_pi;
- result->weight = original->weight;
-
- return result;
-}
-
-void strategyNexthopState_Display(const StrategyNexthopState *instance,
- int indentation) {
- parcDisplayIndented_PrintLine(indentation, "StrategyNexthopState@%p {",
- instance);
- parcDisplayIndented_PrintLine(indentation + 1, "%d", instance->pi);
- parcDisplayIndented_PrintLine(indentation + 1, "%f", instance->avg_pi);
- parcDisplayIndented_PrintLine(indentation + 1, "%f", instance->weight);
- parcDisplayIndented_PrintLine(indentation, "}");
-}
-
-bool strategyNexthopState_Equals(const StrategyNexthopState *x,
- const StrategyNexthopState *y) {
- bool result = false;
-
- if (x == y) {
- result = true;
- } else if (x == NULL || y == NULL) {
- result = false;
- } else {
- strategyNexthopState_OptionalAssertValid(x);
- strategyNexthopState_OptionalAssertValid(y);
-
- if (strategyNexthopState_Compare(x, y) == 0) {
- result = true;
- }
- }
-
- return result;
-}
-
-PARCHashCode strategyNexthopState_HashCode(const StrategyNexthopState *x) {
- PARCHashCode result = 0;
- char str[128];
- sprintf(str, "PI:%d: AVG_PI:%f: W:%f", x->pi, x->avg_pi, x->weight);
- result = parcHashCode_Hash((uint8_t *)&str, strlen(str));
- return result;
-}
-
-bool strategyNexthopState_IsValid(const StrategyNexthopState *x) {
- bool result = false;
-
- if (x != NULL) {
- result = true;
- }
-
- return result;
-}
-
-char *strategyNexthopState_ToString(const StrategyNexthopState *x) {
- // this is not implemented
- parcTrapNotImplemented("strategyNexthopState_ToString is not implemented");
- return NULL;
-}
-
-unsigned strategyNexthopState_GetPI(const StrategyNexthopState *x) {
- strategyNexthopState_OptionalAssertValid(x);
-
- return x->pi;
-}
-
-double strategyNexthopState_GetAvgPI(const StrategyNexthopState *x) {
- strategyNexthopState_OptionalAssertValid(x);
-
- return x->avg_pi;
-}
-
-double strategyNexthopState_GetWeight(const StrategyNexthopState *x) {
- strategyNexthopState_OptionalAssertValid(x);
-
- return x->weight;
-}
-
-double strategyNexthopState_UpdateState(StrategyNexthopState *x, bool inc,
- double alpha) {
- if (inc) {
- x->pi++;
- } else {
- if (x->pi > 0) {
- x->pi--;
- }
- }
- x->avg_pi = (x->avg_pi * alpha) + (x->pi * (1 - alpha));
-#ifdef WITH_POLICY
- if (x->avg_pi < AVG_PI_THRESHOLD) {
-#else
- if (x->avg_pi == 0.0) {
-#endif /* WITH_POLICY */
- x->avg_pi = 0.1;
- }
- x->weight = 1 / x->avg_pi;
-
- return x->weight;
-}
diff --git a/hicn-light/src/hicn/strategies/nexthopState.h b/hicn-light/src/hicn/strategies/nexthopState.h
deleted file mode 100644
index 35a9f497b..000000000
--- a/hicn-light/src/hicn/strategies/nexthopState.h
+++ /dev/null
@@ -1,94 +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.
- */
-
-#ifndef nexthopstate_h
-#define nexthopstate_h
-
-#include <parc/algol/parc_HashCode.h>
-#include <parc/algol/parc_Object.h>
-
-struct strategy_nexthop_state;
-typedef struct strategy_nexthop_state StrategyNexthopState;
-extern parcObjectDescriptor_Declaration(StrategyNexthopState);
-
-/**
- */
-StrategyNexthopState *strategyNexthopState_Acquire(
- const StrategyNexthopState *instance);
-
-#ifdef PARCLibrary_DISABLE_VALIDATION
-#define strategyNexthopState_OptionalAssertValid(_instance_)
-#else
-#define strategyNexthopState_OptionalAssertValid(_instance_) \
- strategyNexthopState_AssertValid(_instance_)
-#endif
-
-/**
- */
-void strategyNexthopState_AssertValid(const StrategyNexthopState *instance);
-
-/**
- */
-StrategyNexthopState *strategyNexthopState_Create();
-
-void strategyNexthopState_Reset(StrategyNexthopState *x);
-/**
- */
-int strategyNexthopState_Compare(const StrategyNexthopState *instance,
- const StrategyNexthopState *other);
-
-/**
- */
-StrategyNexthopState *strategyNexthopState_Copy(
- const StrategyNexthopState *original);
-
-/**
- */
-void strategyNexthopState_Display(const StrategyNexthopState *instance,
- int indentation);
-
-/**
- */
-bool strategyNexthopState_Equals(const StrategyNexthopState *x,
- const StrategyNexthopState *y);
-
-/**
- */
-PARCHashCode strategyNexthopState_HashCode(
- const StrategyNexthopState *instance);
-
-/**
- */
-bool strategyNexthopState_IsValid(const StrategyNexthopState *instance);
-
-/**
- */
-void strategyNexthopState_Release(StrategyNexthopState **instancePtr);
-
-/**
- */
-char *strategyNexthopState_ToString(const StrategyNexthopState *instance);
-
-/**
- */
-unsigned strategyNexthopState_GetPI(const StrategyNexthopState *x);
-
-double strategyNexthopState_GetAvgPI(const StrategyNexthopState *x);
-
-double strategyNexthopState_GetWeight(const StrategyNexthopState *x);
-
-double strategyNexthopState_UpdateState(StrategyNexthopState *x, bool inc,
- double alpha);
-#endif
diff --git a/hicn-light/src/hicn/strategies/nexthopStateLowLatency.c b/hicn-light/src/hicn/strategies/nexthopStateLowLatency.c
index a3953987f..3caed8130 100644
--- a/hicn-light/src/hicn/strategies/nexthopStateLowLatency.c
+++ b/hicn-light/src/hicn/strategies/nexthopStateLowLatency.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,303 +24,17 @@
#include <parc/assert/parc_Assert.h>
#include <hicn/strategies/nexthopStateLowLatency.h>
-const unsigned MAX_ROUNS_WITHOUT_PROBES = 4;
- //if we do not receives probes for 4 rounds it means
- //that we had no responce from any producer for 2 sec
- //we can say that this interface is daed
-const unsigned MIN_NON_LOSSY_ROUNDS = 10;
- //number of rounds in non lossy mode before switch to
- //no lossy state
-const double MAX_LOSS_RATE = 0.10; //10%
-
-struct strategy_nexthop_state_ll {
- bool in_use;
- bool is_allowed; // the policy may not allow the use of this face
- unsigned face_id;
- unsigned sent_packets;
- //switch metrics
- unsigned last_try_to_switch_round;
- unsigned try_to_switch_counter;
- //probes counters
- unsigned recevied_probes;
- unsigned rounds_without_probes;
- unsigned sent_probes;
- unsigned lost_probes;
- unsigned non_lossy_rounds;
- //avgs
- double avg_rtt;
- double avg_rtt_in_use;
- double avg_queue;
- double avg_loss_rate;
-
-};
-
-static bool _strategyNexthopStateLL_Destructor(
- StrategyNexthopStateLL **instancePtr) {
- return true;
-}
-
-parcObject_ImplementAcquire(strategyNexthopStateLL, StrategyNexthopStateLL);
-
-parcObject_ImplementRelease(strategyNexthopStateLL, StrategyNexthopStateLL);
-
-parcObject_Override(
- StrategyNexthopStateLL, PARCObject,
- .destructor = (PARCObjectDestructor *)_strategyNexthopStateLL_Destructor,
- .copy = (PARCObjectCopy *)strategyNexthopStateLL_Copy,
- .display = (PARCObjectDisplay *)strategyNexthopStateLL_Display,
- .toString = (PARCObjectToString *)strategyNexthopStateLL_ToString,
- .equals = (PARCObjectEquals *)strategyNexthopStateLL_Equals,
- .compare = (PARCObjectCompare *)strategyNexthopStateLL_Compare,
- .hashCode = (PARCObjectHashCode *)strategyNexthopStateLL_HashCode,
- .display = (PARCObjectDisplay *)strategyNexthopStateLL_Display);
-
-void strategyNexthopStateLL_AssertValid(const StrategyNexthopStateLL *instance) {
- parcAssertTrue(strategyNexthopStateLL_IsValid(instance),
- "StrategyNexthopState is not valid.");
-}
-
-StrategyNexthopStateLL *strategyNexthopStateLL_Create(unsigned face_id) {
- StrategyNexthopStateLL *result =
- parcObject_CreateInstance(StrategyNexthopStateLL);
- if (result != NULL) {
- result->in_use = false;
- result->is_allowed = true;
- result->face_id = face_id;
- result->sent_packets = 0;
- result->last_try_to_switch_round = 0;
- result->try_to_switch_counter = 0;
- result->recevied_probes = 0;
- result->rounds_without_probes = 0;
- result->sent_probes = 0;
- result->lost_probes = 0;
- result->non_lossy_rounds = MIN_NON_LOSSY_ROUNDS;
- result->avg_rtt = -1.0;
- result->avg_rtt_in_use = -1.0;
- result->avg_queue = 0.0001;
- result->avg_loss_rate = 0.0;
- }
- return result;
-}
-
-void strategyNexthopStateLL_Reset(StrategyNexthopStateLL *x) {
- x->in_use = false;
- x->is_allowed = true;
- x->sent_packets = 0;
- x->last_try_to_switch_round = 0;
- x->try_to_switch_counter = 0;
- x->recevied_probes = 0;
- x->rounds_without_probes = 0;
- x->sent_probes = 0;
- x->lost_probes = 0;
- x->non_lossy_rounds = MIN_NON_LOSSY_ROUNDS;
- x->avg_rtt = -1.0;
- x->avg_rtt_in_use = -1.0;
- x->avg_queue = 0.0001;
- x->avg_loss_rate = 0.0;
-}
-
-
-int strategyNexthopStateLL_Compare(const StrategyNexthopStateLL *val,
- const StrategyNexthopStateLL *other) {
- if (val == NULL) {
- if (other != NULL) {
- return -1;
- }
- } else if (other == NULL) {
- return 1;
- } else {
- strategyNexthopStateLL_OptionalAssertValid(val);
- strategyNexthopStateLL_OptionalAssertValid(other);
-
- if (val->in_use < other->in_use){
- return -1;
- }else if (val->in_use > other->in_use){
- return 1;
- }
-
- if (val->is_allowed < other->is_allowed){
- return -1;
- }else if (val->is_allowed> other->is_allowed){
- return 1;
- }
-
- if (val->face_id < other->face_id) {
- return -1;
- } else if (val->face_id > other->face_id) {
- return 1;
- }
-
- if (val->sent_packets < other->sent_packets){
- return -1;
- } else if (val->sent_packets > other->sent_packets){
- return 1;
- }
-
- if (val->last_try_to_switch_round <
- other->last_try_to_switch_round) {
- return -1;
- } else if (val->last_try_to_switch_round >
- other->last_try_to_switch_round) {
- return 1;
- }
-
- if (val->try_to_switch_counter <
- other->try_to_switch_counter) {
- return -1;
- } else if (val->try_to_switch_counter >
- other->try_to_switch_counter) {
- return 1;
- }
-
- if (val->recevied_probes < other->recevied_probes) {
- return -1;
- } else if (val->recevied_probes > other->recevied_probes) {
- return 1;
- }
-
- if (val->rounds_without_probes < other->rounds_without_probes) {
- return -1;
- } else if (val->rounds_without_probes > other->rounds_without_probes) {
- return 1;
- }
-
- if (val->sent_probes < other->sent_probes) {
- return -1;
- } else if (val->sent_probes > other->sent_probes) {
- return 1;
- }
-
- if (val->lost_probes < other->lost_probes) {
- return -1;
- } else if (val->lost_probes > other->lost_probes) {
- return 1;
- }
-
- if (val->non_lossy_rounds < other->non_lossy_rounds) {
- return -1;
- } else if (val->non_lossy_rounds > other->non_lossy_rounds) {
- return 1;
- }
-
- if (val->avg_rtt < other->avg_rtt) {
- return -1;
- } else if (val->avg_rtt > other->avg_rtt) {
- return 1;
- }
-
- if (val->avg_rtt_in_use < other->avg_rtt_in_use) {
- return -1;
- } else if (val->avg_rtt_in_use > other->avg_rtt_in_use) {
- return 1;
- }
-
- if (val->avg_queue < other->avg_queue) {
- return -1;
- } else if (val->avg_queue > other->avg_queue) {
- return 1;
- }
-
- if (val->avg_loss_rate < other->avg_loss_rate) {
- return -1;
- } else if (val->avg_loss_rate > other->avg_loss_rate) {
- return 1;
- }
- }
-
- return 0;
-}
-
-StrategyNexthopStateLL *strategyNexthopStateLL_Copy(
- const StrategyNexthopStateLL *original) {
- StrategyNexthopStateLL *result = strategyNexthopStateLL_Create(original->face_id);
- result->in_use = original->in_use;
- result->is_allowed = original->is_allowed;
- result->sent_packets = original->sent_packets;
- result->last_try_to_switch_round = original->last_try_to_switch_round;
- result->try_to_switch_counter = original->try_to_switch_counter;
- result->recevied_probes = original->recevied_probes;
- result->rounds_without_probes = original->rounds_without_probes;
- result->sent_probes = original->sent_probes;
- result->lost_probes = original->lost_probes;
- result->non_lossy_rounds = original->non_lossy_rounds;
- result->avg_rtt = original->avg_rtt;
- result->avg_rtt_in_use = original->avg_rtt_in_use;
- result->avg_queue = original->avg_queue;
- result->avg_loss_rate = original->avg_loss_rate;
- return result;
-}
-
-void strategyNexthopStateLL_Display(const StrategyNexthopStateLL *instance,
- int indentation) {
- parcDisplayIndented_PrintLine(indentation, "StrategyNexthopStateLL@%p {",
- instance);
- parcDisplayIndented_PrintLine(indentation + 1, "%d", instance->face_id);
- parcDisplayIndented_PrintLine(indentation + 1, "%f", instance->avg_rtt);
- parcDisplayIndented_PrintLine(indentation + 1, "%f", instance->avg_rtt_in_use);
- parcDisplayIndented_PrintLine(indentation + 1, "%f", instance->avg_queue);
- parcDisplayIndented_PrintLine(indentation + 1, "%f", instance->avg_loss_rate);
- parcDisplayIndented_PrintLine(indentation, "}");
-}
-
-
-bool strategyNexthopStateLL_Equals(const StrategyNexthopStateLL *x,
- const StrategyNexthopStateLL *y) {
- bool result = false;
-
- if (x == y) {
- result = true;
- } else if (x == NULL || y == NULL) {
- result = false;
- } else {
- strategyNexthopStateLL_OptionalAssertValid(x);
- strategyNexthopStateLL_OptionalAssertValid(y);
-
- if (strategyNexthopStateLL_Compare(x, y) == 0) {
- result = true;
- }
- }
-
- return result;
-}
-
-PARCHashCode strategyNexthopStateLL_HashCode(const StrategyNexthopStateLL *x) {
- PARCHashCode result = 0;
- char str[128];
- sprintf(str, "ID:%d: RTT:%f: RTTUSE:%f: Q:%f L:%f", x->face_id, x->avg_rtt,
- x->avg_rtt_in_use, x->avg_queue, x->avg_loss_rate);
- result = parcHashCode_Hash((uint8_t *)&str, strlen(str));
- return result;
-}
-
-bool strategyNexthopStateLL_IsValid(const StrategyNexthopStateLL *x) {
- bool result = false;
-
- if (x != NULL) {
- result = true;
- }
-
- return result;
-}
-
-char *strategyNexthopStateLL_ToString(const StrategyNexthopStateLL *x) {
- // this is not implemented
- parcTrapNotImplemented("strategyNexthopStateLL_ToString is not implemented");
- return NULL;
-}
-
double strategyNexthopStateLL_GetRTTProbe(StrategyNexthopStateLL *x) {
strategyNexthopStateLL_OptionalAssertValid(x);
- if(x->rounds_without_probes > MAX_ROUNS_WITHOUT_PROBES)
- return DBL_MAX;
+ if (x->rounds_without_probes > MAX_ROUNS_WITHOUT_PROBES) return DBL_MAX;
- if(x->avg_rtt == -1.0){
- if(x->avg_rtt_in_use == -1.0){
+ if (x->avg_rtt == -1.0) {
+ if (x->avg_rtt_in_use == -1.0) {
return 0.0;
- }else{
- //this happens if the face recevied probes only in in_use mode
- //we set the avf_rtt with rtt_in_use
+ } else {
+ // this happens if the face recevied probes only in in_use mode
+ // we set the avf_rtt with rtt_in_use
x->avg_rtt = x->avg_rtt_in_use;
}
}
@@ -331,11 +45,9 @@ double strategyNexthopStateLL_GetRTTProbe(StrategyNexthopStateLL *x) {
double strategyNexthopStateLL_GetRTTInUse(StrategyNexthopStateLL *x) {
strategyNexthopStateLL_OptionalAssertValid(x);
- if(x->rounds_without_probes > MAX_ROUNS_WITHOUT_PROBES)
- return DBL_MAX;
+ if (x->rounds_without_probes > MAX_ROUNS_WITHOUT_PROBES) return DBL_MAX;
- if(x->avg_rtt_in_use == -1.0)
- return strategyNexthopStateLL_GetRTTProbe(x);
+ if (x->avg_rtt_in_use == -1.0) return strategyNexthopStateLL_GetRTTProbe(x);
return x->avg_rtt_in_use;
}
@@ -343,9 +55,9 @@ double strategyNexthopStateLL_GetRTTInUse(StrategyNexthopStateLL *x) {
double strategyNexthopStateLL_GetRTTLive(StrategyNexthopStateLL *x) {
strategyNexthopStateLL_OptionalAssertValid(x);
- if(x->in_use){
+ if (x->in_use) {
return strategyNexthopStateLL_GetRTTInUse(x);
- }else{
+ } else {
return strategyNexthopStateLL_GetRTTProbe(x);
}
}
@@ -353,46 +65,45 @@ double strategyNexthopStateLL_GetRTTLive(StrategyNexthopStateLL *x) {
double strategyNexthopStateLL_GetQueuing(const StrategyNexthopStateLL *x) {
strategyNexthopStateLL_OptionalAssertValid(x);
- if(x->rounds_without_probes > MAX_ROUNS_WITHOUT_PROBES)
- return 0.0;
+ if (x->rounds_without_probes > MAX_ROUNS_WITHOUT_PROBES) return 0.0;
return x->avg_queue;
}
void strategyNexthopStateLL_AddRttSample(StrategyNexthopStateLL *x,
- unsigned int rtt){
+ unsigned int rtt) {
strategyNexthopStateLL_OptionalAssertValid(x);
x->recevied_probes++;
- //form uint to double
+ // form uint to double
double drtt = rtt;
- if(x->in_use){
- if(x->avg_rtt_in_use == -1.0){
+ if (x->in_use) {
+ if (x->avg_rtt_in_use == -1.0) {
x->avg_rtt_in_use = drtt;
- }else{
+ } else {
x->avg_rtt_in_use = (x->avg_rtt_in_use * 0.9) + (drtt * 0.1);
}
- }else{
- if(x->avg_rtt == -1.0){
- x->avg_rtt = drtt;
- }else{
+ } else {
+ if (x->avg_rtt == -1.0) {
+ x->avg_rtt = drtt;
+ } else {
x->avg_rtt = (x->avg_rtt * 0.9) + (drtt * 0.1);
}
}
- if(x->avg_rtt_in_use == -1.0 || x->avg_rtt == -1.0){
+ if (x->avg_rtt_in_use == -1.0 || x->avg_rtt == -1.0) {
x->avg_queue = 0.0001;
- }else{
+ } else {
double queue = x->avg_rtt_in_use - x->avg_rtt;
- if(queue < 0){
+ if (queue < 0) {
queue = 0.0001;
}
x->avg_queue = (x->avg_queue * 0.95) + (0.05 * queue);
}
}
-void strategyNexthopStateLL_SetUnusedFace(StrategyNexthopStateLL *x){
+void strategyNexthopStateLL_SetUnusedFace(StrategyNexthopStateLL *x) {
strategyNexthopStateLL_OptionalAssertValid(x);
x->in_use = false;
}
@@ -403,75 +114,76 @@ unsigned strategyNexthopStateLL_GetFaceId(StrategyNexthopStateLL *x) {
}
void strategyNexthopStateLL_IncreaseTryToSwitch(StrategyNexthopStateLL *x,
- unsigned round){
- if(x->try_to_switch_counter == 0 ||
- round == (x->last_try_to_switch_round + 1)){
+ unsigned round) {
+ if (x->try_to_switch_counter == 0 ||
+ round == (x->last_try_to_switch_round + 1)) {
x->last_try_to_switch_round = round;
x->try_to_switch_counter++;
- }else{
+ } else {
x->try_to_switch_counter = 0;
}
}
-unsigned strategyNexthopStateLL_GetTryToSwitch(const StrategyNexthopStateLL *x){
+unsigned strategyNexthopStateLL_GetTryToSwitch(
+ const StrategyNexthopStateLL *x) {
return x->try_to_switch_counter;
}
-void strategyNexthopStateLL_ResetTryToSwitch(StrategyNexthopStateLL *x){
+void strategyNexthopStateLL_ResetTryToSwitch(StrategyNexthopStateLL *x) {
x->try_to_switch_counter = 0;
}
-void strategyNexthopStateLL_SendPacket(StrategyNexthopStateLL *x){
+void strategyNexthopStateLL_SendPacket(StrategyNexthopStateLL *x) {
x->in_use = true;
x->sent_packets++;
}
-void strategyNexthopStateLL_SentProbe(StrategyNexthopStateLL *x){
+void strategyNexthopStateLL_SentProbe(StrategyNexthopStateLL *x) {
x->sent_probes++;
}
-void strategyNexthopStateLL_LostProbe(StrategyNexthopStateLL *x){
+void strategyNexthopStateLL_LostProbe(StrategyNexthopStateLL *x) {
x->lost_probes++;
}
-bool strategyNexthopStateLL_IsLossy(const StrategyNexthopStateLL *x){
- if(x->non_lossy_rounds < 10 ||
- x->avg_loss_rate > MAX_LOSS_RATE){
+bool strategyNexthopStateLL_IsLossy(const StrategyNexthopStateLL *x) {
+ if (x->non_lossy_rounds < 10 || x->avg_loss_rate > MAX_LOSS_RATE) {
return true;
}
return false;
}
-void strategyNexthopStateLL_SetIsAllowed(StrategyNexthopStateLL *x, bool allowed){
+void strategyNexthopStateLL_SetIsAllowed(StrategyNexthopStateLL *x,
+ bool allowed) {
x->is_allowed = allowed;
}
-bool strategyNexthopStateLL_IsAllowed(const StrategyNexthopStateLL *x){
+bool strategyNexthopStateLL_IsAllowed(const StrategyNexthopStateLL *x) {
return x->is_allowed;
}
-void strategyNexthopStateLL_StartNewRound(StrategyNexthopStateLL *x){
+void strategyNexthopStateLL_StartNewRound(StrategyNexthopStateLL *x) {
strategyNexthopStateLL_OptionalAssertValid(x);
- if(x->sent_packets == 0) //the face was not used in the last round
+ if (x->sent_packets == 0) // the face was not used in the last round
x->in_use = false;
x->sent_packets = 0;
- if(x->recevied_probes == 0){
+ if (x->recevied_probes == 0) {
x->rounds_without_probes++;
- }else{
+ } else {
x->rounds_without_probes = 0;
}
x->recevied_probes = 0;
- //compute losses in this round
- if(x->sent_probes != 0){
- double loss_rate = (double) x->lost_probes / (double) x->sent_probes;
+ // compute losses in this round
+ if (x->sent_probes != 0) {
+ double loss_rate = (double)x->lost_probes / (double)x->sent_probes;
x->avg_loss_rate = x->avg_loss_rate * 0.7 + loss_rate * 0.3;
- if(x->avg_loss_rate > MAX_LOSS_RATE){
+ if (x->avg_loss_rate > MAX_LOSS_RATE) {
x->non_lossy_rounds = 0;
- }else{
+ } else {
x->non_lossy_rounds++;
}
}
diff --git a/hicn-light/src/hicn/strategies/nexthopStateLowLatency.h b/hicn-light/src/hicn/strategies/nexthopStateLowLatency.h
index 34dbb8262..7f4181d44 100644
--- a/hicn-light/src/hicn/strategies/nexthopStateLowLatency.h
+++ b/hicn-light/src/hicn/strategies/nexthopStateLowLatency.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -47,7 +47,7 @@ void strategyNexthopStateLL_Reset(StrategyNexthopStateLL *x);
/**
*/
int strategyNexthopStateLL_Compare(const StrategyNexthopStateLL *instance,
- const StrategyNexthopStateLL *other);
+ const StrategyNexthopStateLL *other);
/**
*/
@@ -57,12 +57,12 @@ StrategyNexthopStateLL *strategyNexthopStateLL_Copy(
/**
*/
void strategyNexthopStateLL_Display(const StrategyNexthopStateLL *instance,
- int indentation);
+ int indentation);
/**
*/
bool strategyNexthopStateLL_Equals(const StrategyNexthopStateLL *x,
- const StrategyNexthopStateLL *y);
+ const StrategyNexthopStateLL *y);
/**
*/
@@ -88,11 +88,10 @@ double strategyNexthopStateLL_GetRTTInUse(StrategyNexthopStateLL *x);
double strategyNexthopStateLL_GetRTTLive(StrategyNexthopStateLL *x);
double strategyNexthopStateLL_GetQueuing(const StrategyNexthopStateLL *x);
void strategyNexthopStateLL_AddRttSample(StrategyNexthopStateLL *x,
- unsigned int rtt);
-
+ unsigned int rtt);
void strategyNexthopStateLL_IncreaseTryToSwitch(StrategyNexthopStateLL *x,
- unsigned round);
+ unsigned round);
unsigned strategyNexthopStateLL_GetTryToSwitch(const StrategyNexthopStateLL *x);
void strategyNexthopStateLL_ResetTryToSwitch(StrategyNexthopStateLL *x);
@@ -108,7 +107,8 @@ void strategyNexthopStateLL_LostProbe(StrategyNexthopStateLL *x);
bool strategyNexthopStateLL_IsLossy(const StrategyNexthopStateLL *x);
-void strategyNexthopStateLL_SetIsAllowed(StrategyNexthopStateLL *x, bool allowed);
+void strategyNexthopStateLL_SetIsAllowed(StrategyNexthopStateLL *x,
+ bool allowed);
bool strategyNexthopStateLL_IsAllowed(const StrategyNexthopStateLL *x);
diff --git a/hicn-light/src/hicn/strategies/probe_generator.c b/hicn-light/src/hicn/strategies/probe_generator.c
new file mode 100644
index 000000000..fd0bf5471
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/probe_generator.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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 "probe_generator.h"
+
+#include <hicn/core/forwarder.h>
+#include <hicn/core/nexthops.h>
+
+// map functions
+static void add_to_map(probe_generator_t *pg, unsigned seq, Ticks now) {
+ khiter_t k;
+ int ret;
+ k = kh_put_bp_map(pg->ticks_by_seq, seq, &ret);
+ kh_value(pg->ticks_by_seq, k) = now;
+}
+
+static Ticks get_from_map(probe_generator_t *pg, unsigned seq) {
+ khiter_t k;
+ k = kh_get_bp_map(pg->ticks_by_seq, seq);
+ if (k == kh_end(pg->ticks_by_seq)) return 0;
+ Ticks t = kh_value(pg->ticks_by_seq, k);
+ return t;
+}
+
+static void remove_from_map(probe_generator_t *pg, unsigned seq) {
+ khiter_t k;
+ k = kh_get_bp_map(pg->ticks_by_seq, seq);
+ if (k != kh_end(pg->ticks_by_seq)) kh_del_bp_map(pg->ticks_by_seq, k);
+}
+
+static void clear_map(probe_generator_t *pg) {
+ kh_clear(bp_map, pg->ticks_by_seq);
+}
+
+// seq number generator
+
+static uint32_t get_seq_number(probe_generator_t *pg) {
+ uint32_t seq = 0;
+ uint32_t try = 0;
+ while (try < 3) { // try up to 3 times
+ seq =
+ (rand() % (MAX_PROBE_SUFFIX - MIN_PROBE_SUFFIX + 1)) + MIN_PROBE_SUFFIX;
+ Ticks time = get_from_map(pg, seq);
+ if (time == 0) return seq; // seq does not exists
+ try++;
+ }
+ return 0;
+}
+
+// probing functions
+
+probe_generator_t *create_probe_generator() {
+ probe_generator_t *pg = calloc(1, sizeof(probe_generator_t));
+ if (!pg) return NULL;
+
+ pg->ticks_by_seq = kh_init_bp_map();
+ return pg;
+}
+
+void destroy_probe_generator(probe_generator_t *pg) {
+ kh_destroy_bp_map(pg->ticks_by_seq);
+ free(pg);
+}
+
+int generate_probe(probe_generator_t *pg, const msgbuf_t *msgbuf,
+ const forwarder_t *forwarder, nexthop_t nexthop) {
+ msgbuf_pool_t *msgbuf_pool = forwarder_get_msgbuf_pool(forwarder);
+ connection_table_t *table = forwarder_get_connection_table(forwarder);
+ connection_t *conn = connection_table_get_by_id(table, nexthop);
+ if (!conn) return -1;
+
+ msgbuf_t *probe;
+ off_t msg_id = msgbuf_pool_get_id(msgbuf_pool, (msgbuf_t *)msgbuf);
+ off_t probe_offset = msgbuf_pool_clone(msgbuf_pool, &probe, msg_id);
+
+ uint32_t seq = get_seq_number(pg);
+ if (seq == 0) return -1;
+ msgbuf_modify_suffix(probe, seq);
+ connection_send(conn, probe_offset, true);
+ connection_flush(conn);
+ add_to_map(pg, seq, ticks_now());
+ msgbuf_pool_put(msgbuf_pool, probe);
+
+ return 0;
+}
+
+Ticks register_probe(probe_generator_t *pg, unsigned seq) {
+ Ticks now = ticks_now();
+ add_to_map(pg, seq, now);
+ return now;
+}
+
+Ticks get_probe_send_time(probe_generator_t *pg, unsigned seq) {
+ return get_from_map(pg, seq);
+}
+
+void delete_probe(probe_generator_t *pg, unsigned seq) {
+ remove_from_map(pg, seq);
+}
+
+void delete_all_probes(probe_generator_t *pg) { clear_map(pg); }
diff --git a/hicn-light/src/hicn/strategies/probe_generator.h b/hicn-light/src/hicn/strategies/probe_generator.h
new file mode 100644
index 000000000..065d824a1
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/probe_generator.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+#ifndef HICNLIGHT_PROBE_GENERATOR
+#define HICNLIGHT_PROBE_GENERATOR
+
+#include <hicn/util/khash.h>
+#include <hicn/core/ticks.h>
+#include <hicn/core/msgbuf.h>
+
+#define MIN_PROBE_SUFFIX 0xefffffff
+#define MAX_PROBE_SUFFIX 0xffffffff - 1
+
+KHASH_MAP_INIT_INT64(bp_map, Ticks);
+
+struct forwarder_s;
+
+typedef struct probe_generator {
+ kh_bp_map_t *ticks_by_seq;
+} probe_generator_t;
+
+probe_generator_t *create_probe_generator();
+
+void destroy_probe_generator(probe_generator_t *pg);
+
+int generate_probe(probe_generator_t *pg, const msgbuf_t *msgbuf,
+ const struct forwarder_s *forwarder, unsigned nexthop);
+
+Ticks register_probe(probe_generator_t *pg, unsigned seq);
+
+Ticks get_probe_send_time(probe_generator_t *pg, unsigned seq);
+
+void delete_probe(probe_generator_t *pg, unsigned seq);
+
+void delete_all_probes(probe_generator_t *pg);
+
+#endif /* HICNLIGHT_PROBE_GENERATOR */
diff --git a/hicn-light/src/hicn/strategies/random.c b/hicn-light/src/hicn/strategies/random.c
new file mode 100644
index 000000000..aabae73bc
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/random.c
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <hicn/hicn-light/config.h>
+
+#include <hicn/core/nexthops.h>
+#include <hicn/core/strategy.h>
+#include <hicn/core/strategy_vft.h>
+
+#include "random.h"
+
+static int strategy_random_initialize(strategy_entry_t *entry,
+ const void *forwarder) {
+ srand((unsigned int)time(NULL));
+ entry->forwarder = forwarder;
+ return 0;
+}
+
+static int strategy_random_finalize(strategy_entry_t *entry) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_random_add_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops, off_t offset) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_random_remove_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops, off_t offset) {
+ /* Nothing to do */
+ return 0;
+}
+
+static nexthops_t *strategy_random_lookup_nexthops(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const msgbuf_t *msgbuf) {
+ if (nexthops_get_curlen(nexthops) == 0) return nexthops;
+ nexthops_select(nexthops, rand() % nexthops_get_len(nexthops));
+ return nexthops;
+}
+
+static int strategy_random_on_data(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *data_nexthops,
+ const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation, Ticks objReception) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_random_on_timeout(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *timeout_nexthops) {
+ /* Nothing to do */
+ return 0;
+}
+
+DECLARE_STRATEGY(random);
diff --git a/hicn-light/src/hicn/strategies/random.h b/hicn-light/src/hicn/strategies/random.h
new file mode 100644
index 000000000..bdea5e4dd
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/random.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Forward randomly
+ */
+
+#ifndef HICNLIGHT_STRATEGY_RANDOM_H
+#define HICNLIGHT_STRATEGY_RANDOM_H
+
+typedef struct {
+ void *_;
+} strategy_random_nexthop_state_t;
+
+typedef struct {
+ void *_;
+} strategy_random_state_t;
+
+typedef struct {
+ void *_;
+} strategy_random_options_t;
+
+#endif /* HICNLIGHT_STRATEGY_RANDOM_H */
diff --git a/hicn-light/src/hicn/strategies/replication.c b/hicn-light/src/hicn/strategies/replication.c
new file mode 100644
index 000000000..86a3e3431
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/replication.c
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <hicn/hicn-light/config.h>
+
+#include <hicn/core/nexthops.h>
+#include <hicn/core/strategy.h>
+#include <hicn/core/strategy_vft.h>
+
+#include "replication.h"
+
+/* Shorthand */
+#define strategy_state_t strategy_replication_state_t
+
+static int strategy_replication_initialize(strategy_entry_t *entry,
+ const void *forwarder) {
+ entry->forwarder = forwarder;
+ strategy_state_t *state = &entry->state.replication;
+ state->prev_nexthops = malloc(sizeof(nexthops_t));
+ *((nexthops_t *)state->prev_nexthops) = NEXTHOPS_EMPTY;
+ return 0;
+}
+
+static int strategy_replication_finalize(strategy_entry_t *entry) {
+ /* Nothing to do */
+ strategy_state_t *state = &entry->state.replication;
+ free(state->prev_nexthops);
+ return 0;
+}
+
+static int strategy_replication_add_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ off_t offset) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_replication_remove_nexthop(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ off_t offset) {
+ /* Nothing to do */
+ return 0;
+}
+
+static nexthops_t *strategy_replication_lookup_nexthops(
+ strategy_entry_t *entry, nexthops_t *nexthops, const msgbuf_t *msgbuf) {
+ // if nexthops is different from prev_nexthops send updates
+ strategy_state_t *state = &entry->state.replication;
+
+ if (!nexthops_equal((nexthops_t *)state->prev_nexthops, nexthops)) {
+ // send updates
+ strategy_replication_options_t *options = &entry->options.replication;
+ update_remote_node_paths(nexthops, entry->forwarder,
+ options->local_prefixes);
+
+ // update next hops
+ nexthops_copy(nexthops, (nexthops_t *)state->prev_nexthops);
+ }
+
+ // Return all next hops
+ return nexthops;
+}
+
+static int strategy_replication_on_data(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *data_nexthops,
+ const msgbuf_t *msgbuf,
+ Ticks pitEntryCreation,
+ Ticks objReception) {
+ /* Nothing to do */
+ return 0;
+}
+
+static int strategy_replication_on_timeout(strategy_entry_t *entry,
+ nexthops_t *nexthops,
+ const nexthops_t *timeout_nexthops) {
+ /* Nothing to do */
+ return 0;
+}
+
+DECLARE_STRATEGY(replication);
diff --git a/hicn-light/src/hicn/strategies/replication.h b/hicn-light/src/hicn/strategies/replication.h
new file mode 100644
index 000000000..753ae4744
--- /dev/null
+++ b/hicn-light/src/hicn/strategies/replication.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Forward replication of the interest on all the paths
+ */
+
+#ifndef HICNLIGHT_STRATEGY_REPLICATION_H
+#define HICNLIGHT_STRATEGY_REPLICATION_H
+
+#include "local_prefixes.h"
+
+typedef struct {
+ void *_;
+} strategy_replication_nexthop_state_t;
+
+typedef struct {
+ void *prev_nexthops;
+} strategy_replication_state_t;
+
+typedef struct {
+ local_prefixes_t *local_prefixes;
+} strategy_replication_options_t;
+
+#endif /* HICNLIGHT_STRATEGY_REPLICATION_H */
diff --git a/hicn-light/src/hicn/strategies/rnd.c b/hicn-light/src/hicn/strategies/rnd.c
deleted file mode 100644
index 064f3965b..000000000
--- a/hicn-light/src/hicn/strategies/rnd.c
+++ /dev/null
@@ -1,211 +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/hicn-light/config.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <parc/algol/parc_HashMap.h>
-#include <parc/algol/parc_Memory.h>
-
-#include <hicn/strategies/rnd.h>
-
-static void _strategyRnd_ReceiveObject(StrategyImpl *strategy,
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception);
-static void _strategyRnd_OnTimeout(StrategyImpl *strategy,
- const NumberSet *egressId);
-
-static NumberSet *_strategyRnd_LookupNexthop(StrategyImpl *strategy,
-#ifdef WITH_POLICY
- NumberSet * nexthops,
-#endif /* WITH_POLICY */
- const Message *interestMessage);
-#ifndef WITH_POLICY
-static NumberSet *_strategyRnd_ReturnNexthops(StrategyImpl *strategy);
-static unsigned _strategyRnd_CountNexthops(StrategyImpl *strategy);
-#endif /* ! WITH_POLICY */
-static void _strategyRnd_AddNexthop(StrategyImpl *strategy,
- unsigned connectionId);
-static void _strategyRnd_RemoveNexthop(StrategyImpl *strategy,
- unsigned connectionId);
-static void _strategyRnd_ImplDestroy(StrategyImpl **strategyPtr);
-static strategy_type _strategyRnd_GetStrategy(StrategyImpl *strategy);
-
-static StrategyImpl _template = {
- .context = NULL,
- .receiveObject = &_strategyRnd_ReceiveObject,
- .onTimeout = &_strategyRnd_OnTimeout,
- .lookupNexthop = &_strategyRnd_LookupNexthop,
-#ifndef WITH_POLICY
- .returnNexthops = &_strategyRnd_ReturnNexthops,
- .countNexthops = &_strategyRnd_CountNexthops,
-#endif /* ! WITH_POLICY */
- .addNexthop = &_strategyRnd_AddNexthop,
- .removeNexthop = &_strategyRnd_RemoveNexthop,
- .destroy = &_strategyRnd_ImplDestroy,
- .getStrategy = &_strategyRnd_GetStrategy,
-};
-
-#ifndef WITH_POLICY
-struct strategy_rnd;
-typedef struct strategy_rnd StrategyRnd;
-
-struct strategy_rnd {
- NumberSet *nexthops;
-};
-#endif /* ! WITH_POLICY */
-
-StrategyImpl *strategyRnd_Create() {
-#ifndef WITH_POLICY
- StrategyRnd *strategy = parcMemory_AllocateAndClear(sizeof(StrategyRnd));
- parcAssertNotNull(strategy, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(StrategyRnd));
-
- strategy->nexthops = numberSet_Create();
-#endif /* ! WITH_POLICY */
- srand((unsigned int)time(NULL));
-
- StrategyImpl *impl = parcMemory_AllocateAndClear(sizeof(StrategyImpl));
- parcAssertNotNull(impl, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(StrategyImpl));
- memcpy(impl, &_template, sizeof(StrategyImpl));
-#ifndef WITH_POLICY
- impl->context = strategy;
-#endif /* ! WITH_POLICY */
- return impl;
-}
-
-// =======================================================
-// Dispatch API
-
-strategy_type _strategyRnd_GetStrategy(StrategyImpl *strategy) {
- return SET_STRATEGY_RANDOM;
-}
-
-#ifndef WITH_POLICY
-static int _select_Nexthop(StrategyRnd *strategy) {
- unsigned len = (unsigned)numberSet_Length(strategy->nexthops);
- if (len == 0) {
- return -1;
- }
-
- int rnd = (rand() % len);
- return numberSet_GetItem(strategy->nexthops, rnd);
-}
-#endif /* ! WITH_POLICY */
-
-static void _strategyRnd_ReceiveObject(StrategyImpl *strategy,
- const NumberSet *egressId,
- const Message *objectMessage,
- Ticks pitEntryCreation,
- Ticks objReception) {}
-
-static void _strategyRnd_OnTimeout(StrategyImpl *strategy,
- const NumberSet *egressId) {}
-
-static NumberSet *_strategyRnd_LookupNexthop(StrategyImpl *strategy,
-#ifdef WITH_POLICY
- NumberSet * nexthops,
-#endif /* WITH_POLICY */
- const Message *interestMessage) {
- unsigned out_connection;
- NumberSet *out = numberSet_Create();
-
-#ifdef WITH_POLICY
- // We return one next hop at random
- out_connection = numberSet_GetItem(nexthops, rand() % numberSet_Length(nexthops));
-
-#else
- StrategyRnd *srnd = (StrategyRnd *)strategy->context;
- unsigned in_connection = message_GetIngressConnectionId(interestMessage);
- unsigned nexthopSize = (unsigned)numberSet_Length(srnd->nexthops);
-
- if ((nexthopSize == 0) ||
- ((nexthopSize == 1) &&
- numberSet_Contains(srnd->nexthops, in_connection))) {
- // there are no output faces or the input face is also the only output face.
- // return null to avoid loops
- return out;
- }
-
- do {
- out_connection = _select_Nexthop(srnd);
- } while (out_connection == in_connection);
-
- if (out_connection == -1) {
- return out;
- }
-#endif /* WITH_POLICY */
-
- numberSet_Add(out, out_connection);
- return out;
-}
-
-#ifndef WITH_POLICY
-static NumberSet *_strategyRnd_ReturnNexthops(StrategyImpl *strategy) {
- StrategyRnd *srnd = (StrategyRnd *)strategy->context;
- return srnd->nexthops;
-}
-
-unsigned _strategyRnd_CountNexthops(StrategyImpl *strategy) {
- StrategyRnd *srnd = (StrategyRnd *)strategy->context;
- return (unsigned)numberSet_Length(srnd->nexthops);
-}
-#endif /* ! WITH_POLICY */
-
-static void _strategyRnd_AddNexthop(StrategyImpl *strategy,
- unsigned connectionId) {
-#ifndef WITH_POLICY
- StrategyRnd *srnd = (StrategyRnd *)strategy->context;
- if (!numberSet_Contains(srnd->nexthops, connectionId)) {
- numberSet_Add(srnd->nexthops, connectionId);
- }
-#endif /* ! WITH_POLICY */
-}
-
-static void _strategyRnd_RemoveNexthop(StrategyImpl *strategy,
- unsigned connectionId) {
-#ifndef WITH_POLICY
- StrategyRnd *srnd = (StrategyRnd *)strategy->context;
-
- if (numberSet_Contains(srnd->nexthops, connectionId)) {
- numberSet_Remove(srnd->nexthops, connectionId);
- }
-#endif /* ! WITH_POLICY */
-}
-
-static void _strategyRnd_ImplDestroy(StrategyImpl **strategyPtr) {
- parcAssertNotNull(strategyPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*strategyPtr,
- "Parameter must dereference to non-null pointer");
-
- StrategyImpl *impl = *strategyPtr;
-
-#ifndef WITH_POLICY
- StrategyRnd *strategy = (StrategyRnd *)impl->context;
- numberSet_Release(&(strategy->nexthops));
- parcMemory_Deallocate((void **)&strategy);
-#endif /* ! WITH_POLICY */
-
- parcMemory_Deallocate((void **)&impl);
- *strategyPtr = NULL;
-}
diff --git a/hicn-light/src/hicn/strategies/strategyImpl.h b/hicn-light/src/hicn/strategies/strategyImpl.h
deleted file mode 100644
index 140da5bf8..000000000
--- a/hicn-light/src/hicn/strategies/strategyImpl.h
+++ /dev/null
@@ -1,73 +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.
- */
-
-/**
- * @file strategyImpl.h
- * @brief Defines the function structure for a Strategy implementation
- *
- * <#Detailed Description#>
- *
- */
-
-/**
- * A dispatch structure for a concrete implementation of a forwarding strategy.
- */
-
-#ifndef strategyImpl_h
-#define strategyImpl_h
-
-#include <hicn/core/message.h>
-#include <hicn/core/numberSet.h>
-
-struct strategy_impl;
-typedef struct strategy_impl StrategyImpl;
-
-/**
- * @typedef StrategyImpl
- * @abstract Forwarding strategy implementation
- * @constant receiveObject is called when we receive an object and have a
- * measured round trip time. This allows a strategy to update its performance
- * data.
- * @constant lookupNexthop Find the set of nexthops to use for the Interest.
- * May be empty, should not be NULL. Must be destroyed.
- * @constant addNexthop Add a nexthop to the list of available nexthops with a
- * routing protocol-specific cost.
- * @constant destroy cleans up the strategy, freeing all memory and state. A
- * strategy is reference counted, so the final destruction only happens after
- * the last reference is released.
- * @discussion <#Discussion#>
- */
-struct strategy_impl {
- void *context;
- void (*receiveObject)(StrategyImpl *strategy, const NumberSet *egressId,
- const Message *objectMessage, Ticks pitEntryCreation,
- Ticks objReception);
- void (*onTimeout)(StrategyImpl *strategy, const NumberSet *egressId);
- NumberSet *(*lookupNexthop)(StrategyImpl *strategy,
-#ifdef WITH_POLICY
- NumberSet * nexthops,
-#endif /* WITH_POLICY */
- const Message *interestMessage);
-#ifndef WITH_POLICY
- NumberSet *(*returnNexthops)(StrategyImpl *strategy);
- unsigned (*countNexthops)(StrategyImpl *strategy);
-#endif /* ! WITH_POLICY */
- void (*addNexthop)(StrategyImpl *strategy, unsigned connectionId);
- void (*removeNexthop)(StrategyImpl *strategy, unsigned connectionId);
- void (*destroy)(StrategyImpl **strategyPtr);
- strategy_type (*getStrategy)(StrategyImpl *strategy);
-};
-
-#endif // strategyImpl_h
diff --git a/hicn-light/src/hicn/test/CMakeLists.txt b/hicn-light/src/hicn/test/CMakeLists.txt
new file mode 100644
index 000000000..395b6e333
--- /dev/null
+++ b/hicn-light/src/hicn/test/CMakeLists.txt
@@ -0,0 +1,40 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+
+include(BuildMacros)
+
+list(APPEND TESTS_SRC
+ test-configuration.cc
+ test-fib.cc
+ test-loop.cc
+ test-parser.cc
+ test-ctrl.cc
+ test-msgbuf_pool.cc
+ test-nexthops.cc
+ test-connection_table.cc
+ test-listener_table.cc
+ test-packet_cache.cc
+ test-strategy-load-balancing.cc
+ test-strategy-random.cc
+ test-strategy-replication.cc
+ test-strategy-best-path.cc
+ test-strategy-local-remote.cc
+ test-subscription.cc
+ test-local_prefixes.cc
+ test-probe_generator.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_listener.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../ctrl/libhicnctrl/src/commands/command_route.c
+ main.cc
+)
+
+build_executable(hicn_light_tests
+ NO_INSTALL
+ SOURCES ${TESTS_SRC}
+ LINK_LIBRARIES ${LIBHICN_LIGHT_STATIC} ${GTEST_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}
+ INCLUDE_DIRS ${HICN_LIGHT_INCLUDE_DIRS} ${GTEST_INCLUDE_DIRS}
+ DEPENDS gtest ${LIBHICNCTRL_STATIC} ${LIBHICN_LIGHT_SHARED}
+ COMPONENT ${HICN_LIGHT}
+ DEFINITIONS "${COMPILER_DEFINITIONS}"
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
+
+add_test_internal(hicn_light_tests)
diff --git a/hicn-light/src/hicn/test/main.cc b/hicn-light/src/hicn/test/main.cc
new file mode 100644
index 000000000..49cc28f66
--- /dev/null
+++ b/hicn-light/src/hicn/test/main.cc
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+int main(int argc, char **argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/hicn-light/src/hicn/test/test-configuration.cc b/hicn-light/src/hicn/test/test-configuration.cc
new file mode 100644
index 000000000..2d3b5329f
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-configuration.cc
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C" {
+#include <hicn/config/configuration.h>
+}
+
+static inline size_t CS_SIZE = 10;
+static inline char CONFIG_FILE[] = "setup.conf";
+static inline int LOG_LEVEL = LOG_DEBUG;
+static inline char LOG_FILE[] = "/dev/null";
+static inline uint16_t PORT = 1234;
+static inline uint16_t CONF_PORT = 5678;
+static inline bool IS_DAEMON_MODE = true;
+static inline char PREFIX[] = "b001::/16";
+static inline char PREFIX_2[] = "c001::/16";
+static inline strategy_type_t STRATEGY_TYPE = STRATEGY_TYPE_BESTPATH;
+
+class ConfigurationTest : public ::testing::Test {
+ protected:
+ ConfigurationTest() {
+ config = configuration_create();
+ log_conf.log_level = LOG_FATAL;
+ log_conf.log_file = NULL;
+ }
+ virtual ~ConfigurationTest() { configuration_free(config); }
+
+ configuration_t *config;
+};
+
+TEST_F(ConfigurationTest, CreateConfiguration) {
+ // Check configuration creation
+ ASSERT_NE(config, nullptr);
+}
+
+TEST_F(ConfigurationTest, SetGeneralParameters) {
+ configuration_set_cs_size(config, CS_SIZE);
+ size_t cs_size = configuration_get_cs_size(config);
+ EXPECT_EQ(cs_size, CS_SIZE);
+
+ configuration_set_fn_config(config, CONFIG_FILE);
+ const char *config_file = configuration_get_fn_config(config);
+ EXPECT_EQ(config_file, CONFIG_FILE);
+
+ configuration_set_port(config, PORT);
+ uint16_t port = configuration_get_port(config);
+ EXPECT_EQ(port, PORT);
+
+ configuration_set_configuration_port(config, CONF_PORT);
+ uint16_t conf_port = configuration_get_configuration_port(config);
+ EXPECT_EQ(conf_port, CONF_PORT);
+
+ configuration_set_daemon(config, IS_DAEMON_MODE);
+ bool is_daemon_mode = configuration_get_daemon(config);
+ EXPECT_EQ(is_daemon_mode, IS_DAEMON_MODE);
+}
+
+TEST_F(ConfigurationTest, SetLogParameters) {
+ configuration_set_loglevel(config, LOG_LEVEL);
+ int log_level = configuration_get_loglevel(config);
+ EXPECT_EQ(log_level, LOG_LEVEL);
+ EXPECT_EQ(log_conf.log_level, LOG_LEVEL);
+
+ configuration_set_logfile(config, LOG_FILE);
+ const char *log_file = configuration_get_logfile(config);
+ EXPECT_EQ(log_file, LOG_FILE);
+ int write_fd = configuration_get_logfile_fd(config);
+ EXPECT_NE(write_fd, -1);
+ configuration_flush_log();
+}
+
+TEST_F(ConfigurationTest, SetStrategyParameter) {
+ configuration_set_strategy(config, PREFIX, STRATEGY_TYPE);
+ strategy_type_t strategy_type = configuration_get_strategy(config, PREFIX);
+ EXPECT_EQ(strategy_type, STRATEGY_TYPE);
+
+ // Check strategy for non-registered prefix
+ strategy_type = configuration_get_strategy(config, PREFIX_2);
+ EXPECT_EQ(strategy_type, STRATEGY_TYPE_UNDEFINED);
+}
diff --git a/hicn-light/src/hicn/test/test-connection_table.cc b/hicn-light/src/hicn/test/test-connection_table.cc
new file mode 100644
index 000000000..6723d0ff1
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-connection_table.cc
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/connection_table.h>
+#include <hicn/util/log.h>
+#include <hicn/validation.h>
+}
+
+#define CONNECTION_NAME "conn_name"
+#define CONNECTION_NAME_2 "conn_name_2"
+
+class ConnectionTableTest : public ::testing::Test {
+ protected:
+ ConnectionTableTest() {
+ assert(is_symbolic_name(CONNECTION_NAME, SYMBOLIC_NAME_LEN));
+ assert(is_symbolic_name(CONNECTION_NAME_2, SYMBOLIC_NAME_LEN));
+
+ log_conf.log_level = LOG_WARN;
+
+ conn_table_ = connection_table_create();
+ pair_ =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(2));
+ }
+ virtual ~ConnectionTableTest() { connection_table_free(conn_table_); }
+
+ connection_table_t *conn_table_;
+ connection_t *connection_;
+ address_pair_t pair_;
+};
+
+TEST_F(ConnectionTableTest, CreateTable) {
+ /* Check connection_table allocation */
+ EXPECT_NE(conn_table_, nullptr);
+
+ /* Check connection_table size */
+ size_t conn_table_size = connection_table_len(conn_table_);
+ EXPECT_EQ(conn_table_size, (size_t)0);
+}
+
+TEST_F(ConnectionTableTest, AddConnection) {
+ // Add connection to connection table
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ size_t conn_table_size = connection_table_len(conn_table_);
+ EXPECT_EQ(conn_table_size, (size_t)1);
+ EXPECT_NE(connection_, nullptr);
+
+ // Get connection by name and by pair
+ khiter_t k_name = kh_get_ct_name(conn_table_->id_by_name, CONNECTION_NAME);
+ EXPECT_NE(k_name, kh_end(conn_table_->id_by_name));
+ khiter_t k_pair = kh_get_ct_pair(conn_table_->id_by_pair, &pair_);
+ EXPECT_NE(k_pair, kh_end(conn_table_->id_by_pair));
+}
+
+TEST_F(ConnectionTableTest, GetConnection) {
+ // Add connection to connection table
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ size_t conn_table_size = connection_table_len(conn_table_);
+ EXPECT_EQ(conn_table_size, (size_t)1);
+ EXPECT_NE(connection_, nullptr);
+
+ // Get connection by name
+ connection_t *connection_retrieved =
+ connection_table_get_by_name(conn_table_, CONNECTION_NAME);
+ ASSERT_NE(connection_retrieved, nullptr);
+ EXPECT_EQ(connection_retrieved, connection_);
+
+ // Get connection by pair
+ connection_retrieved = connection_table_get_by_pair(conn_table_, &pair_);
+ ASSERT_NE(connection_retrieved, nullptr);
+ EXPECT_EQ(connection_retrieved, connection_);
+}
+
+TEST_F(ConnectionTableTest, GetConnectionWithIdOutOfRange) {
+ connection_t *connection = _connection_table_get_by_id(conn_table_, ~0);
+ EXPECT_EQ(connection, nullptr);
+}
+
+TEST_F(ConnectionTableTest, GetConnectionWithInvalidId) {
+ // First connection inserted has always id equal to 0
+ int non_valid_id = 5;
+
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ connection_t *connection_not_found =
+ connection_table_get_by_id(conn_table_, non_valid_id);
+ ASSERT_EQ(connection_not_found, nullptr);
+}
+
+TEST_F(ConnectionTableTest, GetConnectionWithValidId) {
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ int id = connection_table_get_connection_id(conn_table_, connection_);
+ connection_t *connection_found = connection_table_get_by_id(conn_table_, id);
+ ASSERT_EQ(connection_found, connection_);
+}
+
+TEST_F(ConnectionTableTest, GetConnectionIdFromValidName) {
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ int id = connection_table_get_id_by_name(conn_table_, CONNECTION_NAME);
+ ASSERT_TRUE(listener_id_is_valid(id));
+}
+
+TEST_F(ConnectionTableTest, GetConnectionIdFromInvalidName) {
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ int id = connection_table_get_id_by_name(conn_table_, CONNECTION_NAME_2);
+ ASSERT_FALSE(listener_id_is_valid(id));
+}
+
+TEST_F(ConnectionTableTest, RemoveConnection) {
+ // Add connection (connection name and pair must be set)
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ connection_->name = (char *)CONNECTION_NAME;
+ connection_->pair = pair_;
+
+ // Remove connection
+ int id = connection_table_get_connection_id(conn_table_, connection_);
+ connection_table_remove_by_id(conn_table_, id);
+
+ // Check connection table size
+ size_t conn_table_size = connection_table_len(conn_table_);
+ EXPECT_EQ(conn_table_size, (size_t)0);
+
+ // Check that previous connection is not valid anymore
+ connection_t *connection_not_found =
+ connection_table_get_by_id(conn_table_, id);
+ EXPECT_EQ(connection_not_found, nullptr);
+ connection_not_found =
+ connection_table_get_by_name(conn_table_, CONNECTION_NAME);
+ EXPECT_EQ(connection_not_found, nullptr);
+ connection_not_found = connection_table_get_by_pair(conn_table_, &pair_);
+ EXPECT_EQ(connection_not_found, nullptr);
+}
+
+TEST_F(ConnectionTableTest, PrintTable) {
+ // Set verbose log level
+ int old_log_level = log_conf.log_level;
+ log_conf.log_level = LOG_INFO;
+
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ // Insert an additional connection
+ address_pair_t pair_2 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(3), _ADDRESS4_LOCALHOST(4));
+ connection_t *connection_2 =
+ connection_table_allocate(conn_table_, &pair_2, CONNECTION_NAME_2);
+ connection_2->type = FACE_TYPE_TCP;
+
+ testing::internal::CaptureStdout();
+ connection_table_print_by_pair(conn_table_);
+ std::string std_out = testing::internal::GetCapturedStdout();
+
+ ASSERT_NE(std_out, "");
+
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:1"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:2"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:3"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:4"));
+
+ log_conf.log_level = old_log_level; // Restore old log level
+}
+
+TEST_F(ConnectionTableTest, AddMultipleConnections) {
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+
+ // Insert an additional connection
+ address_pair_t pair_2 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(3), _ADDRESS4_LOCALHOST(4));
+ connection_t *connection_2 =
+ connection_table_allocate(conn_table_, &pair_2, CONNECTION_NAME_2);
+ connection_2->type = FACE_TYPE_TCP;
+
+ // Check connection table size
+ size_t conn_table_size = connection_table_len(conn_table_);
+ EXPECT_EQ(conn_table_size, (size_t)2);
+
+ connection_t *c1 = connection_table_get_by_name(conn_table_, CONNECTION_NAME);
+ ASSERT_NE(c1, nullptr);
+ connection_t *c2 =
+ connection_table_get_by_name(conn_table_, CONNECTION_NAME_2);
+ ASSERT_NE(c2, nullptr);
+ EXPECT_NE(c1, c2);
+}
+
+TEST_F(ConnectionTableTest, Iterate) {
+ connection_ = connection_table_allocate(conn_table_, &pair_, CONNECTION_NAME);
+ connection_->type = FACE_TYPE_TCP;
+ connection_->pair = pair_;
+
+ // Insert an additional connection
+ address_pair_t pair_2 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(3), _ADDRESS4_LOCALHOST(4));
+ connection_t *connection_2 =
+ connection_table_allocate(conn_table_, &pair_2, CONNECTION_NAME_2);
+ connection_2->type = FACE_TYPE_TCP;
+ connection_2->pair = pair_2;
+
+ // Iterate over the connection table and count the connections
+ connection_t *c;
+ int count = 0;
+ connection_table_foreach(conn_table_, c, { count++; });
+ EXPECT_EQ(count, 2);
+
+ // Iterate over the connection table and check the connections
+ char local_addr_str[NI_MAXHOST], remote_addr_str[NI_MAXHOST];
+ int local_port, remote_port;
+ testing::internal::CaptureStdout();
+ connection_table_foreach(conn_table_, c, {
+ const address_pair_t *pair = connection_get_pair(c);
+ address_to_string(&pair->local, local_addr_str, &local_port);
+ address_to_string(&pair->remote, remote_addr_str, &remote_port);
+
+ printf("%s:%d\t%s:%d\n", local_addr_str, local_port, remote_addr_str,
+ remote_port);
+ });
+
+ std::string std_out = testing::internal::GetCapturedStdout();
+ ASSERT_NE(std_out, "");
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:1"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:2"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:3"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:4"));
+}
+
+TEST_F(ConnectionTableTest, GenerateConnName) {
+ char conn_name[SYMBOLIC_NAME_LEN];
+ int rc = connection_table_get_random_name(conn_table_, conn_name);
+ EXPECT_EQ(rc, 0);
+
+ connection_ = connection_table_allocate(conn_table_, &pair_, conn_name);
+ connection_->type = FACE_TYPE_TCP;
+ connection_->pair = pair_;
+
+ char conn_name2[SYMBOLIC_NAME_LEN];
+ rc = connection_table_get_random_name(conn_table_, conn_name2);
+ EXPECT_EQ(rc, 0);
+ EXPECT_NE(strncmp(conn_name, conn_name2, SYMBOLIC_NAME_LEN), 0);
+}
+
+TEST_F(ConnectionTableTest, GenerateConnNameExhaustion) {
+ char conn_name[SYMBOLIC_NAME_LEN];
+ bool unable_to_allocate = false;
+
+ // Force name exhaustion
+ int n_connections = 1 + USHRT_MAX;
+ for (int i = 0; i <= n_connections; i++) {
+ int rc = connection_table_get_random_name(conn_table_, conn_name);
+ if (rc < 0) {
+ unable_to_allocate = true;
+ break;
+ }
+
+ address_pair_t pair =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(i));
+ connection_t *conn =
+ connection_table_allocate(conn_table_, &pair, conn_name);
+ memset(conn, 0, sizeof(connection_t));
+ conn->type = FACE_TYPE_TCP;
+ conn->pair = pair;
+ }
+
+ EXPECT_TRUE(unable_to_allocate);
+} \ No newline at end of file
diff --git a/hicn-light/src/hicn/test/test-ctrl.cc b/hicn-light/src/hicn/test/test-ctrl.cc
new file mode 100644
index 000000000..f0d3e7c37
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-ctrl.cc
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C" {
+#include <hicn/util/log.h>
+#include <hicn/ctrl.h>
+#include <hicn/ctrl/parse.h>
+#include <hicn/ctrl/route.h>
+#include <hicn/util/sstrncpy.h>
+}
+
+class CtrlTest : public ::testing::Test {
+ protected:
+ CtrlTest() {
+ log_conf.log_level = LOG_INFO;
+ s_ = hc_sock_create_forwarder(FORWARDER_TYPE_HICNLIGHT);
+ }
+ virtual ~CtrlTest() { hc_sock_free(s_); }
+
+ hc_sock_t *s_ = nullptr;
+ hc_command_t command_ = {};
+};
+
+/**
+ * The parse() function is used to easily create the command.
+ * Here we test the serialization of the commands i.e. from command
+ * to message sent to the forwarder.
+ */
+#if 0
+TEST_F(CtrlTest, AddValidListener) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 9695 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_TRUE(success);
+}
+
+TEST_F(CtrlTest, AddListenerInvalidProtocol) {
+ // Set invalid protocol (icmp)
+ std::string cmd = "add listener icmp udp0 10.0.0.1 9696 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, AddListenerInvalidLocalPort) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 9695 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ // Override with invalid port
+ command_.object.listener.local_port = 0;
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, AddListenerInvalidLocalAddress) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 9695 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ // Override with invalid family
+ command_.object.listener.family = -1;
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_EQ(success, false);
+}
+
+TEST_F(CtrlTest, AddListenerEmptyLocalAddress) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 9695 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ // Override with invalid address
+ command_.object.listener.local_addr = IP_ADDRESS_EMPTY;
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, AddListenerInvalidSymbolicName) {
+ std::string cmd = "add listener udp 0udp 10.0.0.1 9695 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, AddListenerInvalidSymbolicName2) {
+ std::string cmd = "add listener udp udp! 10.0.0.1 9695 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, AddListenerInvalidInterfaceName) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 9695 eth/0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ hc_result_t *result = hc_listener_create_conf(s_, &command_.object.listener);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, AddValidRoute) {
+ std::string cmd = "add route conn0 c001::/64 1";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ hc_result_t *result = hc_route_create_conf(s_, &command_.object.route);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_TRUE(success);
+}
+
+TEST_F(CtrlTest, AddRouteInvalidLength) {
+ std::string cmd = "add route conn0 c001::/64 1";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ // Override with invalid prfix len
+ command_.object.route.len = MAX_IPV6_PREFIX_LEN + 1;
+
+ hc_result_t *result = hc_route_create_conf(s_, &command_.object.route);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, AddRouteInvalidCost) {
+ std::string cmd = "add route conn0 c001::/64 1";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+
+ // Override with invalid cost
+ command_.object.route.cost = MAX_ROUTE_COST + 1;
+
+ hc_result_t *result = hc_route_create_conf(s_, &command_.object.route);
+ bool success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+
+ // Override with invalid cost
+ command_.object.route.cost = MIN_ROUTE_COST - 1;
+
+ result = hc_route_create_conf(s_, &command_.object.route);
+ success = hc_result_get_success(s_, result);
+ EXPECT_FALSE(success);
+}
+
+TEST_F(CtrlTest, RouteNameOrID) {
+ hc_route_t route = {
+ .face_id = (face_id_t)INVALID_FACE_ID,
+ .family = AF_INET6,
+ .remote_addr = IPV6_LOOPBACK,
+ .len = 64,
+ .cost = 1,
+ };
+
+ // At least one between name (symbolic or ID) and face_id
+ // should be set to make the route valid
+
+ // Valid name (symbolic)
+ snprintf(route.name, SYMBOLIC_NAME_LEN, "%s", "test");
+ EXPECT_EQ(hc_route_validate(&route), 0);
+
+ // Valid name (ID)
+ snprintf(route.name, SYMBOLIC_NAME_LEN, "%s", "conn0");
+ EXPECT_EQ(hc_route_validate(&route), 0);
+
+ // Valid face_id
+ route.face_id = 1;
+ snprintf(route.name, SYMBOLIC_NAME_LEN, "%s", "");
+ EXPECT_EQ(hc_route_validate(&route), 0);
+
+ // Invalid name stating with number
+ // (face_id is only checked if empty name)
+ route.face_id = 1;
+ snprintf(route.name, SYMBOLIC_NAME_LEN, "%s", "1test");
+ EXPECT_EQ(hc_route_validate(&route), -1);
+}
+#endif
diff --git a/hicn-light/src/hicn/test/test-fib.cc b/hicn-light/src/hicn/test/test-fib.cc
new file mode 100644
index 000000000..5068b4fa2
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-fib.cc
@@ -0,0 +1,338 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+#include <vector>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/util/ip_address.h>
+#include <hicn/config/configuration.h>
+#include <hicn/core/forwarder.h>
+#include <hicn/core/fib.h>
+}
+
+/*
+ * TODO
+ * - test max_size
+ */
+
+#define DEFAULT_SIZE 10
+#define ARRAY_SIZE(a) ((sizeof(a) / sizeof(*(a))))
+
+class FibTest : public ::testing::Test {
+ protected:
+ FibTest() { fib = fib_create(NULL); }
+ virtual ~FibTest() { fib_free(fib); }
+
+ configuration_t *configuration;
+ forwarder_t *forwarder;
+ fib_t *fib;
+};
+
+fib_entry_t *_fib_add_prefix(fib_t *fib, const hicn_prefix_t *prefix,
+ std::vector<uint32_t> &nexthops) {
+ fib_entry_t *entry =
+ fib_entry_create(prefix, STRATEGY_TYPE_UNDEFINED, NULL, NULL);
+ for (size_t i = 0; i < nexthops.size(); i++)
+ fib_entry_nexthops_add(entry, nexthops[i]);
+ fib_add(fib, entry);
+ return entry;
+}
+
+int compare_str_prefix_to_prefix(char *p1, hicn_prefix_t *p2) {
+ char prefix_s[MAXSZ_IP_PREFIX];
+ hicn_ip_prefix_t ipp;
+ hicn_prefix_get_ip_prefix(p2, &ipp);
+ hicn_ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX,
+ (const hicn_ip_prefix_t *)&ipp);
+ return strcmp(prefix_s, p1);
+}
+
+#define HICN_PREFIX(P, STR) \
+ hicn_prefix_t P; \
+ hicn_ip_prefix_t _##P; \
+ EXPECT_EQ(hicn_ip_prefix_pton(STR, &_##P), 0); \
+ EXPECT_EQ(hicn_prefix_create_from_ip_prefix(&_##P, &P), 0);
+
+/* TEST: Fib allocation and initialization */
+TEST_F(FibTest, FibAddOne) {
+ /* Empty fib should be valid */
+
+ HICN_PREFIX(pfx, "1122:3344:5566:7788:9900:aabb:ccdd:eeff/4");
+
+ const hicn_prefix_t *empty_prefix_array[] = {};
+ bool empty_used_array[] = {};
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, empty_prefix_array, empty_used_array));
+
+ const hicn_prefix_t *prefix_array[] = {&pfx};
+ bool used_array[] = {true};
+
+ std::vector<uint32_t> empty_nexthop;
+ for (unsigned i = 0; i < ARRAY_SIZE(prefix_array); i++) {
+ if (!used_array[i]) continue;
+ _fib_add_prefix(fib, prefix_array[i], empty_nexthop);
+ }
+
+ fib_dump(fib);
+
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array, used_array));
+
+ /* Check that free indices and bitmaps are correctly updated */
+}
+
+TEST_F(FibTest, FibAddTwo) {
+ HICN_PREFIX(b001, "b001::/64");
+ HICN_PREFIX(c001, "c001::/64");
+ HICN_PREFIX(inner_8000_1, "8000::/1");
+
+ const hicn_prefix_t *prefix_array[] = {&b001, &inner_8000_1, &c001};
+ bool used_array[] = {true, false, true};
+
+ std::vector<uint32_t> empty_nexthop;
+ _fib_add_prefix(fib, &b001, empty_nexthop);
+ _fib_add_prefix(fib, &c001, empty_nexthop);
+
+ fib_dump(fib);
+
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array, used_array));
+}
+
+TEST_F(FibTest, FibAddFive) {
+ HICN_PREFIX(b002, "b002::/64");
+ HICN_PREFIX(b002_abcd_0, "b002::abcd:0:0:0/128");
+ HICN_PREFIX(b002_2, "b002::2/128");
+ HICN_PREFIX(b002_abcd_1, "b002::abcd:0:0:1/128");
+ HICN_PREFIX(b002_3, "b002::3/128");
+ HICN_PREFIX(inner_b002_2, "b002::2/127");
+ HICN_PREFIX(inner_b002_abcd_0, "b002::abcd:0:0:0/127");
+
+ const hicn_prefix_t *prefix_array[] = {
+ &b002_2, &inner_b002_2, &b002_3, &b002,
+ &b002_abcd_0, &inner_b002_abcd_0, &b002_abcd_1};
+ bool used_array[] = {true, false, true, true, true, false, true};
+
+ std::vector<uint32_t> empty_nexthop;
+ _fib_add_prefix(fib, &b002, empty_nexthop);
+ _fib_add_prefix(fib, &b002_abcd_0, empty_nexthop);
+ _fib_add_prefix(fib, &b002_2, empty_nexthop);
+ _fib_add_prefix(fib, &b002_abcd_1, empty_nexthop);
+ _fib_add_prefix(fib, &b002_3, empty_nexthop);
+
+ fib_dump(fib);
+
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array, used_array));
+}
+
+TEST_F(FibTest, FibAddRemove) {
+ HICN_PREFIX(b002_64, "b002::/64");
+ HICN_PREFIX(b002_128, "b002::/128");
+
+ const hicn_prefix_t *prefix_array_1[] = {&b002_128};
+ bool used_array_1[] = {true};
+ const hicn_prefix_t *prefix_array_2[] = {};
+ bool used_array_2[] = {};
+ const hicn_prefix_t *prefix_array_3[] = {&b002_64};
+ bool used_array_3[] = {true};
+
+ std::vector<uint32_t> empty_nexthop;
+ fib_entry_t *entry = _fib_add_prefix(fib, &b002_128, empty_nexthop);
+ fib_dump(fib);
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array_1, used_array_1));
+
+ fib_remove_entry(fib, entry);
+ fib_dump(fib);
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array_2, used_array_2));
+
+ entry = _fib_add_prefix(fib, &b002_64, empty_nexthop);
+ fib_dump(fib);
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array_3, used_array_3));
+}
+
+TEST_F(FibTest, FibAddNested) {
+ HICN_PREFIX(b002_64, "b002::/64");
+ HICN_PREFIX(b002_128, "b002::/128");
+
+ const hicn_prefix_t *prefix_array_1[] = {&b002_128};
+ bool used_array_1[] = {true};
+ const hicn_prefix_t *prefix_array_2[] = {&b002_128, &b002_64};
+ bool used_array_2[] = {true, true};
+
+ std::vector<uint32_t> empty_nexthop;
+ _fib_add_prefix(fib, &b002_128, empty_nexthop);
+ fib_dump(fib);
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array_1, used_array_1));
+
+ _fib_add_prefix(fib, &b002_64, empty_nexthop);
+ fib_dump(fib);
+ EXPECT_TRUE(fib_is_valid(fib));
+ EXPECT_TRUE(fib_check_preorder(fib, prefix_array_2, used_array_2));
+}
+
+TEST_F(FibTest, IRIStest) {
+ char p_0_s[] = "b001:0:0:3039::/64";
+ char p_1_3_s[] = "b001::3039:0:1:2:0/128";
+ HICN_PREFIX(p_0, p_0_s);
+
+ HICN_PREFIX(p_1_2, "b001::3039:0:1:0:0/128");
+ HICN_PREFIX(p_1_1, "b001::3039:0:1:0:100/128");
+ HICN_PREFIX(p_1_3, p_1_3_s);
+ HICN_PREFIX(p_1_4, "b001::3039:0:1:0:102/128");
+
+ HICN_PREFIX(p_2_2, "b001::3039:0:2:0:0/128");
+ HICN_PREFIX(p_2_1, "b001::3039:0:2:0:100/128");
+ HICN_PREFIX(p_2_3, "b001::3039:0:2:2:0/128");
+ HICN_PREFIX(p_2_4, "b001::3039:0:2:0:102/128");
+
+ HICN_PREFIX(to_match1, "b001::3039:0:1:0:101/128");
+ HICN_PREFIX(to_match2, "b001:0:0:3039:ffff:ffff::/128");
+ HICN_PREFIX(to_match3, "b001:1::/128");
+ HICN_PREFIX(to_match4, "b001::3039:0:1:2:0/128");
+
+ std::vector<uint32_t> nexthop;
+ nexthop.push_back(2); // add nexthop 2 to the fib entry
+ /*** add ***/
+ _fib_add_prefix(fib, &p_0, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+
+ _fib_add_prefix(fib, &p_1_1, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+
+ _fib_add_prefix(fib, &p_1_2, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+
+ _fib_add_prefix(fib, &p_1_3, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+
+ _fib_add_prefix(fib, &p_1_4, nexthop);
+ fib_dump(fib);
+ EXPECT_TRUE(fib_is_valid(fib));
+
+ /*** match ***/
+ fib_entry_t *entry = fib_match_prefix(fib, &to_match1);
+ // the matching prefix should be p0
+ EXPECT_TRUE(entry != NULL);
+ if (entry) {
+ int ret = compare_str_prefix_to_prefix(p_0_s, &(entry->prefix));
+ EXPECT_EQ(ret, 0);
+ }
+
+ entry = fib_match_prefix(fib, &to_match2);
+ // the matching prefix should be p0
+ EXPECT_TRUE(entry != NULL);
+ if (entry) {
+ int ret = compare_str_prefix_to_prefix(p_0_s, &(entry->prefix));
+ EXPECT_EQ(ret, 0);
+ }
+
+ entry = fib_match_prefix(fib, &to_match3);
+ // we expect no match
+ EXPECT_FALSE(entry != NULL);
+
+ entry = fib_match_prefix(fib, &to_match4);
+ // the matching prefix should be p_1_3
+ EXPECT_TRUE(entry != NULL);
+ if (entry) {
+ int ret = compare_str_prefix_to_prefix(p_1_3_s, &(entry->prefix));
+ EXPECT_EQ(ret, 0);
+ }
+
+ /*** remove ***/
+ fib_remove(fib, &p_0, nexthop[0]);
+ EXPECT_TRUE(fib_is_valid(fib));
+ fib_remove(fib, &p_1_1, nexthop[0]);
+ EXPECT_TRUE(fib_is_valid(fib));
+ fib_remove(fib, &p_1_2, nexthop[0]);
+ EXPECT_TRUE(fib_is_valid(fib));
+ fib_remove(fib, &p_1_3, nexthop[0]);
+ EXPECT_TRUE(fib_is_valid(fib));
+ fib_remove(fib, &p_1_4, nexthop[0]);
+ EXPECT_TRUE(fib_is_valid(fib));
+ fib_dump(fib);
+
+ /*** match ***/
+ entry = fib_match_prefix(fib, &to_match1);
+ // we expect no match
+ EXPECT_FALSE(entry != NULL);
+
+ entry = fib_match_prefix(fib, &to_match2);
+ // we expect no match
+ EXPECT_FALSE(entry != NULL);
+
+ entry = fib_match_prefix(fib, &to_match3);
+ // we expect no match
+ EXPECT_FALSE(entry != NULL);
+
+ entry = fib_match_prefix(fib, &to_match4);
+ // we expect no match
+ EXPECT_FALSE(entry != NULL);
+
+ // add again
+ _fib_add_prefix(fib, &p_0, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+ _fib_add_prefix(fib, &p_2_1, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+ _fib_add_prefix(fib, &p_2_2, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+ _fib_add_prefix(fib, &p_2_3, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+ _fib_add_prefix(fib, &p_2_4, nexthop);
+ EXPECT_TRUE(fib_is_valid(fib));
+ fib_dump(fib);
+
+ entry = fib_match_prefix(fib, &to_match1);
+ // the matching prefix should be p0
+ EXPECT_TRUE(entry != NULL);
+ if (entry) {
+ int ret = compare_str_prefix_to_prefix(p_0_s, &(entry->prefix));
+ EXPECT_EQ(ret, 0);
+ }
+
+ entry = fib_match_prefix(fib, &to_match2);
+ // the matching prefix should be p0
+ EXPECT_TRUE(entry != NULL);
+ if (entry) {
+ int ret = compare_str_prefix_to_prefix(p_0_s, &(entry->prefix));
+ EXPECT_EQ(ret, 0);
+ }
+
+ entry = fib_match_prefix(fib, &to_match3);
+ // we expect no match
+ EXPECT_FALSE(entry != NULL);
+
+ entry = fib_match_prefix(fib, &to_match4);
+ // the matching prefix should be p0
+ EXPECT_TRUE(entry != NULL);
+ if (entry) {
+ int ret = compare_str_prefix_to_prefix(p_0_s, &(entry->prefix));
+ EXPECT_EQ(ret, 0);
+ }
+}
diff --git a/hicn-light/src/hicn/test/test-listener_table.cc b/hicn-light/src/hicn/test/test-listener_table.cc
new file mode 100644
index 000000000..6bd2a6ab7
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-listener_table.cc
@@ -0,0 +1,244 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/listener_table.h>
+#include <hicn/util/log.h>
+#include <hicn/validation.h>
+}
+
+#define LISTENER_NAME "listener_name"
+#define LISTENER_NAME_2 "listener_name_2"
+
+class ListenerTableTest : public ::testing::Test {
+ protected:
+ ListenerTableTest() {
+ assert(is_symbolic_name(LISTENER_NAME, SYMBOLIC_NAME_LEN));
+ assert(is_symbolic_name(LISTENER_NAME_2, SYMBOLIC_NAME_LEN));
+
+ log_conf.log_level = LOG_INFO;
+
+ listener_table_ = listener_table_create();
+ key_ = listener_key_factory(_ADDRESS4_LOCALHOST(1), FACE_TYPE_UDP_LISTENER);
+ }
+ virtual ~ListenerTableTest() { listener_table_free(listener_table_); }
+
+ listener_table_t *listener_table_;
+ listener_t *listener_;
+ listener_key_t key_;
+};
+
+TEST_F(ListenerTableTest, CreateTable) {
+ // Check listener_table allocation
+ EXPECT_NE(listener_table_, nullptr);
+
+ // Check listener_table size
+ size_t listener_table_size = listener_table_len(listener_table_);
+ EXPECT_EQ(listener_table_size, (size_t)0);
+}
+
+TEST_F(ListenerTableTest, AddListener) {
+ // Add listener to listener table
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ size_t listener_table_size = listener_table_len(listener_table_);
+ EXPECT_EQ(listener_table_size, (size_t)1);
+ EXPECT_NE(listener_, nullptr);
+
+ // Get listener by name and by key
+ khiter_t k_name = kh_get_lt_name(listener_table_->id_by_name, LISTENER_NAME);
+ EXPECT_NE(k_name, kh_end(listener_table_->id_by_name));
+ khiter_t k_key = kh_get_lt_key(listener_table_->id_by_key, &key_);
+ EXPECT_NE(k_key, kh_end(listener_table_->id_by_key));
+}
+
+TEST_F(ListenerTableTest, GetListener) {
+ // Add listener to listener table
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ size_t listener_table_size = listener_table_len(listener_table_);
+ EXPECT_EQ(listener_table_size, (size_t)1);
+ ASSERT_NE(listener_, nullptr);
+
+ // Get listener by name
+ listener_t *listener_retrieved =
+ listener_table_get_by_name(listener_table_, LISTENER_NAME);
+ ASSERT_NE(listener_retrieved, nullptr);
+ EXPECT_EQ(listener_retrieved, listener_);
+
+ // Get listener by key
+ listener_retrieved = listener_table_get_by_key(listener_table_, &key_);
+ ASSERT_NE(listener_retrieved, nullptr);
+ EXPECT_EQ(listener_retrieved, listener_);
+}
+
+TEST_F(ListenerTableTest, GetListenerWithIdOutOfRange) {
+ listener_t *listener = _listener_table_get_by_id(listener_table_, ~0);
+ EXPECT_EQ(listener, nullptr);
+}
+
+TEST_F(ListenerTableTest, GetListenerWithInvalidId) {
+ // First listener inserted has always id equal to 0
+ int non_valid_id = 5;
+
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ listener_t *listener_not_found =
+ listener_table_get_by_id(listener_table_, non_valid_id);
+ ASSERT_EQ(listener_not_found, nullptr);
+}
+
+TEST_F(ListenerTableTest, GetListenerWithValidId) {
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ int id = listener_table_get_listener_id(listener_table_, listener_);
+ listener_t *listener_found = listener_table_get_by_id(listener_table_, id);
+ ASSERT_EQ(listener_found, listener_);
+}
+
+TEST_F(ListenerTableTest, GetListenerIdFromValidName) {
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ int id = listener_table_get_id_by_name(listener_table_, LISTENER_NAME);
+ ASSERT_TRUE(listener_id_is_valid(id));
+}
+
+TEST_F(ListenerTableTest, GetListenerIdFromInvalidName) {
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ int id = listener_table_get_id_by_name(listener_table_, LISTENER_NAME_2);
+ ASSERT_FALSE(listener_id_is_valid(id));
+}
+
+TEST_F(ListenerTableTest, RemoveListener) {
+ // Add listener (listerner name and key must be set)
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+ listener_->name = (char *)LISTENER_NAME;
+ listener_->key = key_;
+
+ // Remove listener
+ int id = listener_table_get_listener_id(listener_table_, listener_);
+ listener_table_remove_by_id(listener_table_, id);
+
+ // Check listener table size
+ size_t listener_table_size = listener_table_len(listener_table_);
+ EXPECT_EQ(listener_table_size, (size_t)0);
+
+ // Check that previous listener is not valid anymore
+ listener_t *listener_not_found =
+ listener_table_get_by_id(listener_table_, id);
+ EXPECT_EQ(listener_not_found, nullptr);
+ listener_not_found =
+ listener_table_get_by_name(listener_table_, LISTENER_NAME);
+ EXPECT_EQ(listener_not_found, nullptr);
+ listener_not_found = listener_table_get_by_key(listener_table_, &key_);
+ EXPECT_EQ(listener_not_found, nullptr);
+}
+
+TEST_F(ListenerTableTest, PrintTable) {
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ // Insert an additional listener
+ listener_key_t key_2 =
+ listener_key_factory(_ADDRESS4_LOCALHOST(2), FACE_TYPE_TCP_LISTENER);
+ listener_t *listener_2 =
+ listener_table_allocate(listener_table_, &key_2, LISTENER_NAME_2);
+ listener_2->type = FACE_TYPE_UDP_LISTENER;
+
+ testing::internal::CaptureStdout();
+ listener_table_print_by_key(listener_table_);
+ std::string std_out = testing::internal::GetCapturedStdout();
+
+ ASSERT_NE(std_out, "");
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:1"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:2"));
+}
+
+TEST_F(ListenerTableTest, AddMultipleListeners) {
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+
+ // Insert an additional listener
+ listener_key_t key_2 =
+ listener_key_factory(_ADDRESS4_LOCALHOST(2), FACE_TYPE_TCP_LISTENER);
+ listener_t *listener_2 =
+ listener_table_allocate(listener_table_, &key_2, LISTENER_NAME_2);
+ listener_2->type = FACE_TYPE_UDP_LISTENER;
+
+ // Check listener table size
+ size_t listener_table_size = listener_table_len(listener_table_);
+ EXPECT_EQ(listener_table_size, (size_t)2);
+
+ listener_t *l1 = listener_table_get_by_name(listener_table_, LISTENER_NAME);
+ ASSERT_NE(l1, nullptr);
+ listener_t *l2 = listener_table_get_by_name(listener_table_, LISTENER_NAME_2);
+ ASSERT_NE(l2, nullptr);
+ EXPECT_NE(l1, l2);
+}
+
+TEST_F(ListenerTableTest, Iterate) {
+ listener_ = listener_table_allocate(listener_table_, &key_, LISTENER_NAME);
+ listener_->type = FACE_TYPE_UDP_LISTENER;
+ listener_->key = key_;
+
+ // Insert an additional listener
+ listener_key_t key_2 =
+ listener_key_factory(_ADDRESS4_LOCALHOST(2), FACE_TYPE_TCP_LISTENER);
+ listener_t *listener_2 =
+ listener_table_allocate(listener_table_, &key_2, LISTENER_NAME_2);
+ listener_2->type = FACE_TYPE_UDP_LISTENER;
+ listener_2->key = key_2;
+
+ // Iterate over the listener table and count the listeners
+ int count = 0;
+ listener_table_foreach(listener_table_, l, { count++; });
+ EXPECT_EQ(count, 2);
+
+ // Iterate over the listener table and check the listeners
+ char addr_str[NI_MAXHOST];
+ int port;
+ testing::internal::CaptureStdout();
+ listener_table_foreach(listener_table_, l, {
+ address_to_string(&l->address, addr_str, &port);
+ printf("%s\t%s:%d\n", face_type_str(l->type), addr_str, port);
+ });
+
+ std::string std_out = testing::internal::GetCapturedStdout();
+ ASSERT_NE(std_out, "");
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:1"));
+ EXPECT_THAT(std_out, testing::HasSubstr("127.0.0.1:2"));
+ EXPECT_THAT(std_out, testing::HasSubstr("UDP"));
+ EXPECT_THAT(std_out, testing::HasSubstr("TCP"));
+}
diff --git a/hicn-light/src/hicn/test/test-local_prefixes.cc b/hicn-light/src/hicn/test/test-local_prefixes.cc
new file mode 100644
index 000000000..52b1c746e
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-local_prefixes.cc
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/strategies/local_prefixes.h>
+#include <hicn/core/strategy.h>
+}
+
+const char *name_str1 = "b001::0";
+const char *name_str2 = "b002::0";
+const char *name_str3 = "b003::0";
+const char *name_str4 = "b004::0";
+const char *name_str5 = "b005::0";
+const char *name_str6 = "b006::0";
+const char *name_str7 = "b007::0";
+const char *name_str8 = "b008::0";
+const char *name_str9 = "b009::0";
+const char *name_str10 = "b010::0";
+const char *name_str11 = "b011::0";
+
+class LocalPrefixesTest : public ::testing::Test {
+ protected:
+ LocalPrefixesTest() {}
+
+ virtual ~LocalPrefixesTest() {}
+};
+
+TEST_F(LocalPrefixesTest, LocalPrefixesAddName) {
+ int rc;
+ local_prefixes_t *lp = create_local_prefixes();
+ EXPECT_FALSE(lp == nullptr);
+
+ hicn_ip_address_t result = IP_ADDRESS_EMPTY;
+ hicn_ip_address_pton(name_str1, &result);
+ hicn_prefix_t name1;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name1);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str2, &result);
+ hicn_prefix_t name2;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name2);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str3, &result);
+ hicn_prefix_t name3;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name3);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str4, &result);
+ hicn_prefix_t name4;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name4);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str5, &result);
+ hicn_prefix_t name5;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name5);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str6, &result);
+ hicn_prefix_t name6;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name6);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str7, &result);
+ hicn_prefix_t name7;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name7);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str8, &result);
+ hicn_prefix_t name8;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name8);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str9, &result);
+ hicn_prefix_t name9;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name9);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str10, &result);
+ hicn_prefix_t name10;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name10);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str11, &result);
+ hicn_prefix_t name11;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name11);
+ EXPECT_EQ(rc, 0);
+
+ local_prefixes_add_prefix(lp, &name1);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)1);
+
+ local_prefixes_add_prefix(lp, &name1);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)1);
+
+ local_prefixes_add_prefix(lp, &name2);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)2);
+
+ local_prefixes_add_prefix(lp, &name2);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)2);
+
+ local_prefixes_add_prefix(lp, &name3);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)3);
+
+ local_prefixes_add_prefix(lp, &name4);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)4);
+
+ local_prefixes_add_prefix(lp, &name5);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)5);
+
+ local_prefixes_add_prefix(lp, &name6);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)6);
+
+ local_prefixes_add_prefix(lp, &name7);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)7);
+
+ local_prefixes_add_prefix(lp, &name8);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)8);
+
+ local_prefixes_add_prefix(lp, &name9);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)9);
+
+ local_prefixes_add_prefix(lp, &name10);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)10);
+
+ local_prefixes_add_prefix(lp, &name11);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)10);
+
+ free_local_prefixes(lp);
+}
+
+TEST_F(LocalPrefixesTest, LocalPrefixesAddPrefixes) {
+ int rc;
+ local_prefixes_t *lp = create_local_prefixes();
+ EXPECT_FALSE(lp == nullptr);
+
+ hicn_ip_address_t result;
+
+ local_prefixes_t *lp1 = create_local_prefixes();
+ EXPECT_FALSE(lp1 == nullptr);
+
+ hicn_ip_address_pton(name_str1, &result);
+ hicn_prefix_t name1;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name1);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str2, &result);
+ hicn_prefix_t name2;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name2);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str3, &result);
+ hicn_prefix_t name3;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name3);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str4, &result);
+ hicn_prefix_t name4;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name4);
+ EXPECT_EQ(rc, 0);
+
+ local_prefixes_add_prefix(lp1, &name1);
+ local_prefixes_add_prefix(lp1, &name2);
+ local_prefixes_add_prefix(lp1, &name3);
+ local_prefixes_add_prefix(lp1, &name4);
+
+ EXPECT_EQ(local_prefixes_get_len(lp1), (unsigned)4);
+
+ local_prefixes_add_prefixes(lp, lp1);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)4);
+
+ local_prefixes_add_prefixes(lp, lp1);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)4);
+
+ local_prefixes_t *lp2 = create_local_prefixes();
+ EXPECT_FALSE(lp2 == nullptr);
+
+ hicn_ip_address_pton(name_str5, &result);
+ hicn_prefix_t name5;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name5);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str6, &result);
+ hicn_prefix_t name6;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name6);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str7, &result);
+ hicn_prefix_t name7;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name7);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str8, &result);
+ hicn_prefix_t name8;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name8);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str9, &result);
+ hicn_prefix_t name9;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name9);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str10, &result);
+ hicn_prefix_t name10;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name10);
+ EXPECT_EQ(rc, 0);
+
+ hicn_ip_address_pton(name_str11, &result);
+ hicn_prefix_t name11;
+ rc = hicn_prefix_create_from_ip_address_len(&result, 128, &name11);
+ EXPECT_EQ(rc, 0);
+
+ local_prefixes_add_prefix(lp2, &name5);
+ local_prefixes_add_prefix(lp2, &name6);
+ local_prefixes_add_prefix(lp2, &name7);
+ local_prefixes_add_prefix(lp2, &name8);
+ local_prefixes_add_prefix(lp2, &name9);
+ local_prefixes_add_prefix(lp2, &name10);
+ local_prefixes_add_prefix(lp2, &name11);
+
+ EXPECT_EQ(local_prefixes_get_len(lp2), (unsigned)7);
+
+ local_prefixes_add_prefixes(lp, lp2);
+ EXPECT_EQ(local_prefixes_get_len(lp), (unsigned)10);
+
+ free_local_prefixes(lp);
+ free_local_prefixes(lp1);
+ free_local_prefixes(lp2);
+}
diff --git a/hicn-light/src/hicn/test/test-loop.cc b/hicn-light/src/hicn/test/test-loop.cc
new file mode 100644
index 000000000..71635c929
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-loop.cc
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+#include <fcntl.h>
+
+extern "C" {
+#include <hicn/base/loop.h>
+}
+
+class LoopTest : public ::testing::Test {
+ static constexpr uint16_t BUFFER_SIZE = 1024;
+
+ protected:
+ LoopTest()
+ : server_port_(9191),
+ loop_(nullptr),
+ timer_tick_(2000),
+ connection_socket_(-1),
+ event_(nullptr),
+ timer_(nullptr) {}
+
+ virtual ~LoopTest() {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void SetUp() {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ }
+
+ virtual void TearDown() {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ }
+
+ static int onFirstTimerExpiration(void *owner, int fd, unsigned id,
+ void *arg) {
+ assert(id == 0);
+ std::cout << "This function should never be called" << std::endl;
+ EXPECT_TRUE(false);
+ return -1;
+ }
+
+ static int onSecondTimerExpiration(void *owner, int fd, unsigned id,
+ void *arg) {
+ assert(id == 0);
+ std::cout << "First timer expired. Cancel second timer." << std::endl;
+ LoopTest *test = (LoopTest *)(arg);
+ loop_event_unregister(test->timer_);
+ return 0;
+ }
+
+ static int onTimerExpiration(void *owner, int fd, unsigned id, void *arg) {
+ assert(id == 0);
+ // Create client socket
+ struct sockaddr_in addr;
+ int client_socket;
+ LoopTest *test = (LoopTest *)(arg);
+
+ client_socket = socket(AF_INET, SOCK_STREAM, 0);
+ if (client_socket == -1) {
+ perror("socket");
+ return -1;
+ }
+
+ addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(test->server_port_);
+
+ if (connect(client_socket, (struct sockaddr *)&addr,
+ sizeof(struct sockaddr)) == -1) {
+ perror("connect");
+ return -1;
+ }
+
+ if (send(client_socket, "Hello, world!\n", 14, 0) == -1) {
+ perror("send");
+ return -1;
+ }
+
+ close(client_socket);
+ loop_event_unregister(test->timer_);
+
+ return 0;
+ }
+
+ static int onNewConnection(void *owner, int fd, unsigned id, void *arg) {
+ assert(id == 0);
+ LoopTest *test = (LoopTest *)arg;
+ struct sockaddr_in addr;
+ addr.sin_addr.s_addr = INADDR_ANY;
+ addr.sin_family = AF_INET;
+
+ socklen_t addr_len = sizeof(struct sockaddr_in);
+ int ret;
+
+ int client_fd =
+ accept(test->connection_socket_, (struct sockaddr *)(&addr), &addr_len);
+ if (client_fd == -1) {
+ if (errno != EAGAIN && errno != EWOULDBLOCK) { // NOSONAR
+ fprintf(stderr, "accept failed");
+ }
+
+ perror("accept");
+ return -1;
+ }
+
+ // Read whatever data available and close connection.
+ ret = read(client_fd, test->buffer, BUFFER_SIZE);
+ if (ret < 0) {
+ perror("read");
+ return -1;
+ }
+
+ test->buffer[ret] = '\0';
+ std::cout << "Received: " << (char *)test->buffer << std::endl;
+
+ close(client_fd);
+ loop_event_unregister(test->event_);
+
+ return 0;
+ }
+
+ void createTcpSocketServer() {
+ struct sockaddr_in addr;
+ int ret;
+
+ /* Create local socket. */
+
+ connection_socket_ = socket(AF_INET, SOCK_STREAM, 0);
+ if (connection_socket_ == -1) {
+ perror("socket");
+ return;
+ }
+
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(server_port_);
+ addr.sin_addr.s_addr = htonl(INADDR_ANY);
+
+ ret = bind(connection_socket_, (const struct sockaddr *)&addr,
+ sizeof(struct sockaddr_in));
+ if (ret == -1) {
+ perror("bind");
+ return;
+ }
+
+ ret = listen(connection_socket_, 20);
+ if (ret == -1) {
+ perror("listen");
+ return;
+ }
+ }
+
+ uint16_t server_port_;
+ loop_t *loop_;
+ unsigned timer_tick_;
+ int connection_socket_;
+ event_t *event_;
+ event_t *timer_;
+ char buffer[BUFFER_SIZE];
+};
+
+TEST_F(LoopTest, LoopCreateAndFree) {
+ loop_ = loop_create();
+ EXPECT_TRUE(loop_ != NULL);
+ loop_free(loop_);
+ EXPECT_TRUE(loop_ != NULL);
+}
+
+TEST_F(LoopTest, EventCreateAndFree) {
+ int ret;
+
+ // Fake fd
+ int fd = socket(AF_INET, SOCK_STREAM, 0);
+ loop_ = loop_create();
+
+ ret = loop_fd_event_create(&event_, loop_, fd, nullptr,
+ &LoopTest::onNewConnection, 0, this);
+ EXPECT_TRUE(ret >= 0);
+ EXPECT_TRUE(event_);
+
+ // Register the event
+ ret = loop_fd_event_register(event_);
+ EXPECT_TRUE(ret >= 0);
+
+ // Unregister the event
+ ret = loop_event_free(event_);
+ EXPECT_TRUE(ret >= 0);
+
+ // close fd
+ ret = close(fd);
+ EXPECT_EQ(ret, 0);
+
+ // Free event loop
+ loop_free(loop_);
+}
+
+TEST_F(LoopTest, TimerCreateAndCancel) {
+ int ret;
+ event_t *timer2;
+ loop_ = loop_create();
+
+ ret = loop_timer_create(&timer_, loop_, nullptr,
+ &LoopTest::onFirstTimerExpiration, this);
+ EXPECT_TRUE(ret >= 0);
+ EXPECT_TRUE(timer_);
+
+ ret = loop_timer_create(&timer2, loop_, nullptr,
+ &LoopTest::onSecondTimerExpiration, this);
+ EXPECT_TRUE(ret >= 0);
+ EXPECT_TRUE(timer2);
+
+ // Register the 1st timer
+ ret = loop_timer_register(timer_, timer_tick_);
+ EXPECT_TRUE(ret >= 0);
+
+ // Register the 2nd timer
+ ret = loop_timer_register(timer2, timer_tick_ / 2);
+ EXPECT_TRUE(ret >= 0);
+
+ _loop_dispatch(loop_, 0);
+
+ loop_undispatch(loop_);
+
+ // Unregister the events
+ ret = loop_event_free(timer_);
+ ret += loop_event_free(timer2);
+ EXPECT_TRUE(ret >= 0);
+
+ // Free event loop
+ loop_free(loop_);
+}
+
+TEST_F(LoopTest, LoopDispatch) {
+ int ret;
+
+ // Create new unix socket
+ createTcpSocketServer();
+ loop_ = loop_create();
+
+ ret = loop_fd_event_create(&event_, loop_, connection_socket_, nullptr,
+ &LoopTest::onNewConnection, 0, this);
+ EXPECT_TRUE(ret >= 0);
+ EXPECT_TRUE(event_);
+
+ ret = loop_fd_event_register(event_);
+ EXPECT_TRUE(ret >= 0);
+
+ // Create timer.
+ ret = loop_timer_create(&timer_, loop_, nullptr, &LoopTest::onTimerExpiration,
+ this);
+ EXPECT_TRUE(ret >= 0);
+ EXPECT_TRUE(timer_);
+
+ ret = loop_timer_register(timer_, timer_tick_);
+ EXPECT_TRUE(ret >= 0);
+
+ // Start event dispatching
+ _loop_dispatch(loop_, 0);
+
+ // Stop dispatching
+ loop_undispatch(loop_);
+
+ // Free events
+ loop_event_free(timer_);
+ loop_event_free(event_);
+
+ // Free event loop
+ loop_free(loop_);
+}
diff --git a/hicn-light/src/hicn/test/test-msgbuf_pool.cc b/hicn-light/src/hicn/test/test-msgbuf_pool.cc
new file mode 100644
index 000000000..0a78a7a5d
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-msgbuf_pool.cc
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/msgbuf_pool.h>
+#include <hicn/util/pool.h>
+}
+
+class MsgbufPoolTest : public ::testing::Test {
+ protected:
+ MsgbufPoolTest() { msgbuf_pool = msgbuf_pool_create(); }
+ virtual ~MsgbufPoolTest() { msgbuf_pool_free(msgbuf_pool); }
+
+ msgbuf_pool_t *msgbuf_pool;
+};
+
+TEST_F(MsgbufPoolTest, Create) {
+ /* Check msgbuf_pool allocation */
+ EXPECT_NE(msgbuf_pool, nullptr);
+
+ /* Check msgbuf_pool size */
+ size_t msgbuf_pool_size = pool_hdr(msgbuf_pool->buffers)->alloc_size;
+ EXPECT_EQ(msgbuf_pool_size, (size_t)PACKET_POOL_DEFAULT_INIT_SIZE);
+}
+
+TEST_F(MsgbufPoolTest, GetMsgbuf) {
+ msgbuf_t *msgbuf = NULL;
+
+ /* Get valid msgbuf from msgbuf_pool */
+ off_t msgbuf_id = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_NE(msgbuf_id_is_valid((unsigned long)msgbuf_id), 0);
+
+ /* Check if the returned id is correct */
+ off_t id = msgbuf_pool_get_id(msgbuf_pool, msgbuf);
+ EXPECT_EQ(id, msgbuf_id);
+
+ /* Check if the returned msgbuf is correct */
+ msgbuf_t *msgbuf_retrieved = msgbuf_pool_at(msgbuf_pool, id);
+ EXPECT_EQ(msgbuf_retrieved, msgbuf);
+}
+
+TEST_F(MsgbufPoolTest, PutMsgbuf) {
+ /* Check that asking a msgbuf right after releasing another one
+ returns the same msgbuf */
+
+ msgbuf_t *msgbuf = NULL;
+
+ off_t id1 = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ EXPECT_NE(msgbuf, nullptr);
+
+ msgbuf_pool_put(msgbuf_pool, msgbuf);
+
+ off_t id2 = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ EXPECT_NE(msgbuf, nullptr);
+
+ EXPECT_EQ(id2, id1);
+}
+
+TEST_F(MsgbufPoolTest, GetMultipleMsgbufs) {
+ const int NUM_MSG = 3;
+ msgbuf_t *msgbufs[NUM_MSG];
+
+ /* Check if successful allocation */
+ int ret = msgbuf_pool_getn(msgbuf_pool, msgbufs, NUM_MSG);
+ EXPECT_EQ(ret, 0);
+
+ /* Check if all msgbufs are valid */
+ for (unsigned i = 0; i < NUM_MSG; i++) {
+ msgbuf_pool_get_id(msgbuf_pool, msgbufs[i]);
+ EXPECT_NE(msgbufs[i], nullptr) << "Invalid index: " << i;
+ }
+}
+
+TEST_F(MsgbufPoolTest, AcquireMsgbuf) {
+ msgbuf_t *msgbuf = NULL;
+
+ // Get msgbuf from msgbuf_pool
+ off_t msgbuf_id = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ msgbuf_set_type(msgbuf, HICN_PACKET_TYPE_COMMAND);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_NE(msgbuf_id_is_valid((unsigned long)msgbuf_id), 0);
+
+ // Acquire the msgbuf
+ msgbuf_pool_acquire(msgbuf);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_EQ(msgbuf->refs, 1u);
+
+ msgbuf_pool_acquire(msgbuf);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_EQ(msgbuf->refs, 2u);
+}
+
+TEST_F(MsgbufPoolTest, ReleaseMsgbuf) {
+ msgbuf_t *msgbuf = NULL;
+
+ // Get msgbuf from msgbuf_pool
+ off_t msgbuf_id = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ msgbuf_set_type(msgbuf, HICN_PACKET_TYPE_COMMAND);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_NE(msgbuf_id_is_valid((unsigned long)msgbuf_id), 0);
+
+ // Acquire the msgbuf
+ msgbuf_pool_acquire(msgbuf);
+ EXPECT_EQ(msgbuf->refs, 1u);
+
+ // Release the msgbuf
+ msgbuf_pool_release(msgbuf_pool, &msgbuf);
+ EXPECT_EQ(msgbuf, nullptr);
+}
+
+TEST_F(MsgbufPoolTest, ReleaseNotAcquiredMsgbuf) {
+ msgbuf_t *msgbuf = NULL;
+
+ // Get valid msgbuf from msgbuf_pool
+ off_t msgbuf_id = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ msgbuf_set_type(msgbuf, HICN_PACKET_TYPE_COMMAND);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_NE(msgbuf_id_is_valid((unsigned long)msgbuf_id), 0);
+
+#ifndef NDEBUG
+ // Release the msgbuf even if it is not been acquired
+ ASSERT_DEATH(
+ {
+ msgbuf_pool_release(msgbuf_pool, &msgbuf);
+ ;
+ },
+ ".*Assertion.*");
+#endif
+}
+
+TEST_F(MsgbufPoolTest, MultipleAcquireAndReleaseMsgbuf) {
+ msgbuf_t *msgbuf = NULL;
+
+ // Get msgbuf from msgbuf_pool
+ off_t msgbuf_id = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ msgbuf_set_type(msgbuf, HICN_PACKET_TYPE_COMMAND);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_NE(msgbuf_id_is_valid((unsigned long)msgbuf_id), 0);
+
+ // Acquire the msgbuf multiple times
+ msgbuf_pool_acquire(msgbuf);
+ msgbuf_pool_acquire(msgbuf);
+ EXPECT_EQ(msgbuf->refs, 2u);
+
+ // Release the msgbuf
+ msgbuf_pool_release(msgbuf_pool, &msgbuf);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_EQ(msgbuf->refs, 1u);
+ msgbuf_pool_release(msgbuf_pool, &msgbuf);
+ EXPECT_EQ(msgbuf, nullptr);
+}
+
+TEST_F(MsgbufPoolTest, CloneMsgbuf) {
+ msgbuf_t *msgbuf = NULL;
+ off_t msgbuf_id = msgbuf_pool_get(msgbuf_pool, &msgbuf);
+ msgbuf_set_type(msgbuf, HICN_PACKET_TYPE_COMMAND);
+ EXPECT_NE(msgbuf, nullptr);
+ EXPECT_NE(msgbuf_id_is_valid((unsigned long)msgbuf_id), 0);
+
+ msgbuf_t *new_msgbuf;
+ off_t new_msg_id = msgbuf_pool_clone(msgbuf_pool, &new_msgbuf, msgbuf_id);
+
+ EXPECT_EQ(new_msgbuf, msgbuf_pool_at(msgbuf_pool, new_msg_id));
+ EXPECT_NE(new_msgbuf, msgbuf_pool_at(msgbuf_pool, msgbuf_id));
+ EXPECT_NE(new_msgbuf, msgbuf);
+ EXPECT_TRUE(memcmp(msgbuf, new_msgbuf, sizeof(msgbuf_t)) == 0);
+}
diff --git a/hicn-light/src/hicn/test/test-nexthops.cc b/hicn-light/src/hicn/test/test-nexthops.cc
new file mode 100644
index 000000000..9063298fd
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-nexthops.cc
@@ -0,0 +1,274 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/nexthops.h>
+#include <hicn/core/strategy.h>
+}
+
+#define NEXTHOP1 50
+#define NEXTHOP2 51
+#define NEXTHOP3 52
+
+class NexthopsTest : public ::testing::Test {
+ protected:
+ NexthopsTest() {}
+
+ virtual ~NexthopsTest() {}
+
+ nexthops_t nexthops;
+};
+
+TEST_F(NexthopsTest, NexthopsAdd) {
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, NEXTHOP1);
+
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 1);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+
+ nexthops_add(&nexthops, NEXTHOP2);
+ nexthops_add(&nexthops, NEXTHOP3);
+
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+}
+
+TEST_F(NexthopsTest, NexthopsRemove) {
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP2);
+ nexthops_add(&nexthops, NEXTHOP3);
+
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ nexthops_remove(&nexthops, NEXTHOP2);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 2);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ nexthops_remove(&nexthops, NEXTHOP3);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 1);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ nexthops_remove(&nexthops, NEXTHOP3);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 1);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ nexthops_remove(&nexthops, NEXTHOP1);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 0);
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP3));
+}
+
+TEST_F(NexthopsTest, NexthopsClear) {
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP2);
+ nexthops_add(&nexthops, NEXTHOP3);
+
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ nexthops_clear(&nexthops);
+
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 0);
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP3));
+}
+
+TEST_F(NexthopsTest, NexthopsGetOne) {
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP2);
+ nexthops_add(&nexthops, NEXTHOP3);
+
+ unsigned nexthop = nexthops_get_one(&nexthops);
+
+ EXPECT_TRUE(nexthops_contains(&nexthops, nexthop));
+}
+
+TEST_F(NexthopsTest, NexthopsSelect) {
+ int ret;
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP2);
+ nexthops_add(&nexthops, NEXTHOP3);
+
+ ret = nexthops_select(&nexthops, 2);
+
+ EXPECT_TRUE(ret == 0);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 1);
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ ret = nexthops_select(&nexthops, 0);
+
+ EXPECT_TRUE(ret == 0);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 1);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ nexthops_reset(&nexthops);
+
+ EXPECT_TRUE(ret == 0);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ ret = nexthops_select(&nexthops, 4);
+
+ EXPECT_TRUE(ret == -1);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ ret = nexthops_select(&nexthops, 3);
+
+ EXPECT_TRUE(ret == -1);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+}
+
+TEST_F(NexthopsTest, NexthopsDisable) {
+ int ret;
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP2);
+ nexthops_add(&nexthops, NEXTHOP3);
+
+ ret = nexthops_disable(&nexthops, 0);
+
+ EXPECT_TRUE(ret == 0);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 2);
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ ret = nexthops_disable(&nexthops, 2);
+
+ EXPECT_TRUE(ret == 0);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 1);
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ ret = nexthops_disable(&nexthops, 3);
+ EXPECT_TRUE(ret == -1);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 3);
+ EXPECT_TRUE(nexthops_get_curlen(&nexthops) == 1);
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP3));
+}
+
+TEST_F(NexthopsTest, NexthopsState) {
+ strategy_nexthop_state_t state;
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP2);
+ nexthops_add(&nexthops, NEXTHOP3);
+ nexthops.state[0].load_balancer.pi = 100;
+ nexthops.state[1].load_balancer.pi = 200;
+ nexthops.state[2].load_balancer.pi = 300;
+
+ state = nexthops_state(&nexthops, 0);
+ EXPECT_TRUE(state.load_balancer.pi == 100);
+
+ state = nexthops_state(&nexthops, 1);
+ EXPECT_TRUE(state.load_balancer.pi == 200);
+
+ state = nexthops_state(&nexthops, 2);
+ EXPECT_TRUE(state.load_balancer.pi == 300);
+
+ nexthops_remove(&nexthops, NEXTHOP1);
+ EXPECT_TRUE(nexthops_get_len(&nexthops) == 2);
+ EXPECT_FALSE(nexthops_contains(&nexthops, NEXTHOP1));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP2));
+ EXPECT_TRUE(nexthops_contains(&nexthops, NEXTHOP3));
+
+ state = nexthops_state(&nexthops, 0);
+ EXPECT_TRUE(state.load_balancer.pi == 300);
+
+ state = nexthops_state(&nexthops, 1);
+ EXPECT_TRUE(state.load_balancer.pi == 200);
+}
+
+TEST_F(NexthopsTest, NexthopsEqual) {
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_t nexthops_eq = NEXTHOPS_EMPTY;
+ nexthops_t nexthops_not_eq = NEXTHOPS_EMPTY;
+
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP3);
+ nexthops_add(&nexthops_eq, NEXTHOP1);
+ nexthops_add(&nexthops_eq, NEXTHOP3);
+ nexthops_add(&nexthops_not_eq, NEXTHOP2);
+
+ bool ret = nexthops_equal(&nexthops, &nexthops_eq);
+ EXPECT_TRUE(ret);
+
+ ret = nexthops_equal(&nexthops, &nexthops_not_eq);
+ EXPECT_FALSE(ret);
+}
+
+TEST_F(NexthopsTest, NexthopsCopy) {
+ nexthops = NEXTHOPS_EMPTY;
+ nexthops_t nexthops_eq = NEXTHOPS_EMPTY;
+
+ nexthops_add(&nexthops, NEXTHOP1);
+ nexthops_add(&nexthops, NEXTHOP3);
+ nexthops_copy(&nexthops, &nexthops_eq);
+
+ bool ret = nexthops_equal(&nexthops, &nexthops_eq);
+ EXPECT_TRUE(ret);
+}
diff --git a/hicn-light/src/hicn/test/test-packet_cache.cc b/hicn-light/src/hicn/test/test-packet_cache.cc
new file mode 100644
index 000000000..37f4fe985
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-packet_cache.cc
@@ -0,0 +1,703 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <optional>
+#include <random>
+#include <hicn/test/test-utils.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/packet_cache.h>
+}
+
+static constexpr unsigned CS_SIZE = 100;
+static constexpr unsigned CONN_ID = 0;
+static constexpr unsigned CONN_ID_2 = 1;
+static constexpr unsigned MSGBUF_ID = 0;
+static constexpr unsigned MSGBUF_ID_2 = 1;
+static constexpr unsigned MSGBUF_ID_3 = 2;
+static constexpr unsigned FIVE_SECONDS = 5000;
+
+static constexpr int N_OPS = 50000;
+
+class PacketCacheTest : public ::testing::Test {
+ protected:
+ PacketCacheTest() {
+ pkt_cache = pkt_cache_create(CS_SIZE);
+ int rc = hicn_name_create_from_ip_address(IPV4_ANY, 0, &name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_pool = msgbuf_pool_create();
+ msgbuf = msgbuf_create(msgbuf_pool, CONN_ID, &name);
+ }
+
+ virtual ~PacketCacheTest() {
+ msgbuf_pool_free(msgbuf_pool);
+ pkt_cache_free(pkt_cache);
+ }
+
+ msgbuf_t *msgbuf_create(msgbuf_pool_t *msgbuf_pool, unsigned conn_id,
+ hicn_name_t *name,
+ std::optional<Ticks> lifetime = FIVE_SECONDS) {
+ msgbuf_t *msgbuf;
+ msgbuf_pool_get(msgbuf_pool, &msgbuf);
+
+ msgbuf->connection_id = conn_id;
+ msgbuf_set_name(msgbuf, name);
+
+ hicn_packet_set_format(msgbuf_get_pkbuf(msgbuf),
+ HICN_PACKET_FORMAT_IPV6_TCP);
+ hicn_packet_set_type(msgbuf_get_pkbuf(msgbuf), HICN_PACKET_TYPE_INTEREST);
+
+ hicn_packet_buffer_t *pkbuf = msgbuf_get_pkbuf(msgbuf);
+ hicn_packet_set_buffer(pkbuf, msgbuf->packet, MTU, 0);
+
+ int rc = hicn_packet_init_header(msgbuf_get_pkbuf(msgbuf), 0);
+ EXPECT_EQ(rc, 0);
+
+ // Same as 'msgbuf_set_data_expiry_time',
+ // it would write in the same field
+ msgbuf_set_interest_lifetime(msgbuf, *lifetime);
+
+ return msgbuf;
+ }
+
+ hicn_name_t get_name_from_prefix(const char *prefix_str) {
+ hicn_ip_address_t prefix;
+ inet_pton(AF_INET6, prefix_str, (struct in6_addr *)&prefix);
+
+ hicn_name_t name;
+ int rc = hicn_name_create_from_ip_address(prefix, 0, &name);
+ EXPECT_EQ(rc, 0);
+
+ return name;
+ }
+
+ pkt_cache_t *pkt_cache;
+ pkt_cache_entry_t *entry = nullptr;
+ msgbuf_pool_t *msgbuf_pool;
+ hicn_name_t name;
+ msgbuf_t *msgbuf;
+};
+
+TEST_F(PacketCacheTest, LowLevelOperations) {
+ kh_pkt_cache_prefix_t *prefix_to_suffixes = kh_init_pkt_cache_prefix();
+ const hicn_name_prefix_t *prefix = hicn_name_get_prefix(&name);
+ _add_suffix(prefix_to_suffixes, prefix, 1, 11, pkt_cache->prefix_keys);
+ _add_suffix(prefix_to_suffixes, prefix, 2, 22, pkt_cache->prefix_keys);
+
+ unsigned id =
+ _get_suffix(prefix_to_suffixes, prefix, 1, pkt_cache->prefix_keys);
+ EXPECT_EQ(id, 11UL);
+
+ id = _get_suffix(prefix_to_suffixes, prefix, 2, pkt_cache->prefix_keys);
+ EXPECT_EQ(id, 22UL);
+
+ id = _get_suffix(prefix_to_suffixes, prefix, 5, pkt_cache->prefix_keys);
+ EXPECT_EQ(id, HICN_INVALID_SUFFIX);
+
+ _add_suffix(prefix_to_suffixes, prefix, 5, 55, pkt_cache->prefix_keys);
+ id = _get_suffix(prefix_to_suffixes, prefix, 5, pkt_cache->prefix_keys);
+ EXPECT_EQ(id, 55UL);
+
+ _remove_suffix(prefix_to_suffixes, prefix, 2, pkt_cache->prefix_keys);
+ _add_suffix(prefix_to_suffixes, prefix, 2, 222, pkt_cache->prefix_keys);
+ id = _get_suffix(prefix_to_suffixes, prefix, 2, pkt_cache->prefix_keys);
+ EXPECT_EQ(id, 222UL);
+
+ _prefix_map_free(prefix_to_suffixes);
+}
+
+TEST_F(PacketCacheTest, CreatePacketCache) {
+ // Check packet cache allocation
+ EXPECT_NE(pkt_cache, nullptr);
+ pit_t *pit = pkt_cache_get_pit(pkt_cache);
+ ASSERT_NE(pit, nullptr);
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ ASSERT_NE(cs, nullptr);
+
+ // Check sizes
+ ASSERT_EQ(pkt_cache_get_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+}
+
+TEST_F(PacketCacheTest, AddPacketCacheEntry) {
+ // Add entry to the packet cache
+ entry = pkt_cache_allocate(pkt_cache);
+ EXPECT_NE(entry, nullptr);
+ entry->name = name;
+ ASSERT_EQ(pkt_cache_get_size(pkt_cache), 1u);
+ pkt_cache_add_to_index(pkt_cache, entry);
+
+ // Get entry by name
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_lookup(pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id,
+ true);
+ EXPECT_NE(lookup_result, PKT_CACHE_LU_NONE);
+}
+
+TEST_F(PacketCacheTest, GetCS) {
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ ASSERT_NE(cs, nullptr);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ EXPECT_EQ(cs->type, CS_TYPE_LRU);
+ EXPECT_EQ(cs->num_entries, 0);
+ EXPECT_EQ(cs->lru.head, (off_t)INVALID_ENTRY_ID);
+ EXPECT_EQ(cs->lru.tail, (off_t)INVALID_ENTRY_ID);
+}
+
+TEST_F(PacketCacheTest, GetPIT) {
+ pit_t *pit = pkt_cache_get_pit(pkt_cache);
+ ASSERT_NE(pit, nullptr);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+}
+
+TEST_F(PacketCacheTest, LookupEmpty) {
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_entry_t *entry = pkt_cache_lookup(pkt_cache, &name, msgbuf_pool,
+ &lookup_result, &entry_id, true);
+
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_NONE);
+ EXPECT_EQ(entry, nullptr);
+}
+
+TEST_F(PacketCacheTest, AddEntryAndLookup) {
+ // Add entry to the packet cache
+ entry = pkt_cache_allocate(pkt_cache);
+ entry->name = name;
+ entry->entry_type = PKT_CACHE_PIT_TYPE;
+ ASSERT_NE(entry, nullptr);
+ pkt_cache_add_to_index(pkt_cache, entry);
+
+ // Perform lookup
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+
+ EXPECT_TRUE(lookup_result == PKT_CACHE_LU_INTEREST_NOT_EXPIRED ||
+ lookup_result == PKT_CACHE_LU_INTEREST_EXPIRED);
+ EXPECT_NE(lu_entry, nullptr);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, AddToPIT) {
+ // Check if entry properly created
+ pkt_cache_entry_t *entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, &name);
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_PIT_TYPE);
+ EXPECT_TRUE(pit_entry_ingress_contains(&entry->u.pit_entry, CONN_ID));
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_INTEREST_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, AddToCS) {
+ // Check if entry properly created
+ pkt_cache_entry_t *entry =
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+ cs_entry_t *cs_entry = &entry->u.cs_entry;
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_CS_TYPE);
+ EXPECT_EQ(cs_entry->msgbuf_id, MSGBUF_ID);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 1u);
+
+ // Check if CS properly updated
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+ EXPECT_EQ(cs->num_entries, 1);
+ EXPECT_EQ(cs->lru.head, entry_id);
+ EXPECT_EQ(cs->lru.tail, entry_id);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_DATA_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, PitToCS) {
+ // Prepare PIT entry
+ pkt_cache_entry_t *entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, &name);
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ // Check if entry properly updated
+ pkt_cache_pit_to_cs(pkt_cache, entry, msgbuf_pool, msgbuf, MSGBUF_ID,
+ entry_id);
+ cs_entry_t *cs_entry = &entry->u.cs_entry;
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_CS_TYPE);
+ EXPECT_EQ(cs_entry->msgbuf_id, MSGBUF_ID);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 1u);
+
+ // Check if CS properly updated
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+ EXPECT_EQ(cs->num_entries, 1);
+ EXPECT_EQ(cs->lru.head, entry_id);
+ EXPECT_EQ(cs->lru.tail, entry_id);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_DATA_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, CsToPIT) {
+ // Prepare CS entry
+ pkt_cache_entry_t *entry =
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 1u);
+
+ // Check if entry properly updated
+ pkt_cache_cs_to_pit(pkt_cache, entry, msgbuf_pool, msgbuf, MSGBUF_ID,
+ entry_id);
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_PIT_TYPE);
+ EXPECT_TRUE(pit_entry_ingress_contains(&entry->u.pit_entry, CONN_ID));
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_INTEREST_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, UpdateInPIT) {
+ // Prepare PIT entry
+ pkt_cache_entry_t *entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, &name);
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+
+ hicn_name_t new_name;
+ int rc = hicn_name_create_from_ip_address(IPV4_LOOPBACK, 0, &new_name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *new_msgbuf = msgbuf_create(msgbuf_pool, CONN_ID_2, &new_name);
+
+ // Check if entry properly updated
+ pkt_cache_update_pit(pkt_cache, entry, new_msgbuf);
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_PIT_TYPE);
+ EXPECT_EQ(pit_entry_ingress_contains(&entry->u.pit_entry, CONN_ID_2), true);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_INTEREST_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, UpdateInCS) {
+ // Prepare CS entry
+ pkt_cache_entry_t *entry =
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+ off_t entry_id = pkt_cache_get_entry_id(pkt_cache, entry);
+
+ hicn_name_t new_name;
+ int rc = hicn_name_create_from_ip_address(IPV4_LOOPBACK, 0, &new_name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *new_msgbuf = msgbuf_create(msgbuf_pool, CONN_ID_2, &new_name);
+
+ // Check if entry properly updated
+ pkt_cache_update_cs(pkt_cache, msgbuf_pool, entry, new_msgbuf, MSGBUF_ID_2);
+ cs_entry_t *cs_entry = &entry->u.cs_entry;
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_CS_TYPE);
+ EXPECT_EQ(cs_entry->msgbuf_id, MSGBUF_ID_2);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 1u);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_DATA_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, RemoveFromPIT) {
+ // Prepare PIT entry
+ pkt_cache_entry_t *entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, &name);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ pkt_cache_pit_remove_entry(pkt_cache, entry);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_NONE);
+ EXPECT_EQ(lu_entry, nullptr);
+}
+
+TEST_F(PacketCacheTest, RemoveFromCS) {
+ // Prepare CS entry
+ pkt_cache_entry_t *entry =
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 1u);
+
+ pkt_cache_cs_remove_entry(pkt_cache, entry, msgbuf_pool, false);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+
+ // Check if CS properly updated
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ EXPECT_EQ(cs->num_entries, 0);
+ EXPECT_EQ(cs->lru.head, (off_t)INVALID_ENTRY_ID);
+ EXPECT_EQ(cs->lru.tail, (off_t)INVALID_ENTRY_ID);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_NONE);
+ EXPECT_EQ(lu_entry, nullptr);
+}
+
+TEST_F(PacketCacheTest, AddTwoEntriesToCS) {
+ // Prepare another msgbuf
+ hicn_name_t new_name;
+ int rc = hicn_name_create_from_ip_address(IPV4_LOOPBACK, 0, &new_name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *new_msgbuf = msgbuf_create(msgbuf_pool, CONN_ID_2, &new_name);
+
+ pkt_cache_entry_t *entry_1 =
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+ pkt_cache_entry_t *entry_2 =
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, new_msgbuf, MSGBUF_ID_2);
+ off_t entry_id_1 = pkt_cache_get_entry_id(pkt_cache, entry_1);
+ off_t entry_id_2 = pkt_cache_get_entry_id(pkt_cache, entry_2);
+
+ // Check if the CS and LRU cache are properly updated
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+ EXPECT_EQ(cs->num_entries, 2);
+ EXPECT_EQ(cs->lru.head, entry_id_2);
+ EXPECT_EQ(cs->lru.tail, entry_id_1);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 0u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 2u);
+}
+
+TEST_F(PacketCacheTest, AggregateInPIT) {
+ // Prepare another msgbuf
+ hicn_name_t new_name;
+ int rc = hicn_name_create_from_ip_address(IPV4_LOOPBACK, 0, &new_name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *new_msgbuf = msgbuf_create(msgbuf_pool, CONN_ID_2, &new_name);
+
+ // Check if entry properly created (use sleep to get an updated ts)
+ pkt_cache_entry_t *entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, &name);
+ Ticks old_lifetime = entry->expire_ts;
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ bool is_aggregated =
+ pkt_cache_try_aggregate_in_pit(pkt_cache, entry, new_msgbuf, &name);
+ Ticks new_lifetime = entry->expire_ts;
+
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_PIT_TYPE);
+ EXPECT_GT(new_lifetime, old_lifetime);
+ ASSERT_EQ(is_aggregated, true);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_INTEREST_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, RetransmissionInPIT) {
+ // Prepare another msgbuf (using same connection ID)
+ hicn_name_t new_name;
+ int rc = hicn_name_create_from_ip_address(IPV4_LOOPBACK, 0, &new_name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *new_msgbuf = msgbuf_create(msgbuf_pool, CONN_ID, &new_name);
+
+ // Check if entry properly created (use sleep to get an updated ts)
+ pkt_cache_entry_t *entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, &name);
+ Ticks old_lifetime = entry->expire_ts;
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ bool is_aggregated =
+ pkt_cache_try_aggregate_in_pit(pkt_cache, entry, new_msgbuf, &name);
+ Ticks new_lifetime = entry->expire_ts;
+
+ ASSERT_NE(entry, nullptr);
+ EXPECT_EQ(entry->entry_type, PKT_CACHE_PIT_TYPE);
+ EXPECT_GT(new_lifetime, old_lifetime);
+ ASSERT_EQ(is_aggregated, false);
+
+ // Check if hashtable correctly updated
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_entry_t *lu_entry = pkt_cache_lookup(
+ pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id, true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_INTEREST_NOT_EXPIRED);
+ EXPECT_EQ(lu_entry, entry);
+}
+
+TEST_F(PacketCacheTest, LookupExpiredInterest) {
+ // Prepare msgbuf with 0 as interest lifetime
+ msgbuf_t *msgbuf = msgbuf_create(msgbuf_pool, CONN_ID, &name, 0);
+
+ // Add to PIT
+ pkt_cache_entry_t *entry = pkt_cache_add_to_pit(pkt_cache, msgbuf, &name);
+ ASSERT_NE(entry, nullptr);
+
+ // Wait to make the interest expire
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_lookup(pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id,
+ true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_INTEREST_EXPIRED);
+}
+
+TEST_F(PacketCacheTest, LookupExpiredData) {
+ // Prepare msgbuf with 0 as data expiry time
+ msgbuf_t *msgbuf = msgbuf_create(msgbuf_pool, CONN_ID, &name, 0);
+
+ // Add to CS
+ pkt_cache_entry_t *entry =
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+ ASSERT_NE(entry, nullptr);
+
+ // Wait to make the interest expire
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+
+ pkt_cache_lookup_t lookup_result;
+ off_t entry_id;
+ pkt_cache_lookup(pkt_cache, &name, msgbuf_pool, &lookup_result, &entry_id,
+ true);
+ EXPECT_EQ(lookup_result, PKT_CACHE_LU_DATA_EXPIRED);
+}
+
+TEST_F(PacketCacheTest, GetStaleEntries) {
+ // Add to CS a msgbuf with immediate expiration (i.e. stale)
+ msgbuf_t *msgbuf = msgbuf_create(msgbuf_pool, CONN_ID, &name, 0);
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+
+ // Add to CS another msgbuf with immediate expiration (i.e. stale)
+ hicn_name_t name_2;
+ int rc = hicn_name_create_from_ip_address(IPV4_LOOPBACK, 0, &name_2);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *msgbuf_2 = msgbuf_create(msgbuf_pool, CONN_ID, &name_2, 0);
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf_2, MSGBUF_ID_2);
+
+ // Add to CS a msgbuf with 5-seconds expiration (i.e. not stale)
+ hicn_name_t name_3;
+ rc = hicn_name_create_from_ip_address(IPV6_LOOPBACK, 0, &name_3);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *msgbuf_3 =
+ msgbuf_create(msgbuf_pool, CONN_ID, &name_3, FIVE_SECONDS);
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf_3, MSGBUF_ID_3);
+
+ size_t num_stale_entries = pkt_cache_get_num_cs_stale_entries(pkt_cache);
+ EXPECT_EQ(num_stale_entries, 2u);
+}
+
+TEST_F(PacketCacheTest, GetMultipleStaleEntries) {
+ hicn_ip_address_t addr;
+ char name[30];
+ const int NUM_STALES = 10;
+ int rc;
+
+ // Add to CS multiple msgbufs with immediate expiration (i.e. 0 seconds),
+ // resulting in stale entries
+ for (int i = 0; i < NUM_STALES; i++) {
+ snprintf(name, 30, "b001::%d", i);
+ inet_pton(AF_INET6, name, (struct in6_addr *)&addr);
+ hicn_name_t name;
+ rc = hicn_name_create_from_ip_address(addr, 0, &name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *msgbuf = msgbuf_create(msgbuf_pool, i, &name, 0);
+
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, i);
+ }
+
+ // Add to CS multiple msgbufs with 5-seconds expiration,
+ // resulting in non-stale entries
+ for (int i = NUM_STALES; i < 15; i++) {
+ snprintf(name, 30, "b001::%d", i);
+ inet_pton(AF_INET6, name, (struct in6_addr *)&addr);
+ hicn_name_t name;
+ rc = hicn_name_create_from_ip_address(addr, 0, &name);
+ EXPECT_EQ(rc, 0);
+ msgbuf_t *msgbuf = msgbuf_create(msgbuf_pool, i, &name, FIVE_SECONDS);
+
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, i);
+ }
+
+ size_t num_stale_entries = pkt_cache_get_num_cs_stale_entries(pkt_cache);
+ EXPECT_EQ(num_stale_entries, (size_t)NUM_STALES);
+}
+
+TEST_F(PacketCacheTest, PerformanceDoubleLookup) {
+ hicn_name_t tmp = get_name_from_prefix("b001::0");
+
+ auto elapsed_time_double = get_execution_time([&]() {
+ kh_pkt_cache_prefix_t *prefix_to_suffixes = kh_init_pkt_cache_prefix();
+
+ // Add to hash table
+ for (int seq = 0; seq < N_OPS; seq++) {
+ hicn_name_set_suffix(&tmp, seq);
+ _add_suffix(prefix_to_suffixes, hicn_name_get_prefix(&tmp),
+ hicn_name_get_suffix(&tmp), hicn_name_get_suffix(&tmp),
+ pkt_cache->prefix_keys);
+ }
+
+ // Read from hash table
+ for (int seq = 0; seq < N_OPS; seq++) {
+ hicn_name_set_suffix(&tmp, seq);
+ _get_suffix(prefix_to_suffixes, hicn_name_get_prefix(&tmp), seq,
+ pkt_cache->prefix_keys);
+ }
+
+ _prefix_map_free(prefix_to_suffixes);
+ });
+ std::cout << "Double lookup: " << elapsed_time_double << " ms\n";
+}
+
+TEST_F(PacketCacheTest, PerformanceCachedLookup) {
+ hicn_name_t tmp = get_name_from_prefix("b001::0");
+
+ auto elapsed_time_single = get_execution_time([&]() {
+ kh_pkt_cache_prefix_t *prefix_to_suffixes = kh_init_pkt_cache_prefix();
+ kh_pkt_cache_suffix_t *suffixes =
+ _get_suffixes(prefix_to_suffixes, hicn_name_get_prefix(&tmp), true,
+ pkt_cache->prefix_keys);
+
+ // Add to hash table
+ for (int seq = 0; seq < N_OPS; seq++) {
+ hicn_name_set_suffix(&tmp, seq);
+ __add_suffix(suffixes, hicn_name_get_suffix(&tmp),
+ hicn_name_get_suffix(&tmp));
+ }
+
+ // Read from hash table
+ for (int seq = 0; seq < N_OPS; seq++) {
+ hicn_name_set_suffix(&tmp, seq);
+ __get_suffix(suffixes, hicn_name_get_suffix(&tmp));
+ }
+
+ _prefix_map_free(prefix_to_suffixes);
+ });
+ std::cout << "Cached lookup: " << elapsed_time_single << " ms\n";
+}
+
+TEST_F(PacketCacheTest, PerformanceCachedLookupRandom) {
+ hicn_name_t tmp = get_name_from_prefix("b001::0");
+
+ // Prepare random sequence numbers
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ uint32_t seqs[N_OPS];
+ for (int seq = 0; seq < N_OPS; seq++) seqs[seq] = seq;
+ std::shuffle(std::begin(seqs), std::end(seqs), gen);
+
+ auto elapsed_time_single_rand = get_execution_time([&]() {
+ kh_pkt_cache_prefix_t *prefix_to_suffixes = kh_init_pkt_cache_prefix();
+ kh_pkt_cache_suffix_t *suffixes =
+ _get_suffixes(prefix_to_suffixes, hicn_name_get_prefix(&tmp), true,
+ pkt_cache->prefix_keys);
+
+ // Add to hash table
+ for (int seq = 0; seq < N_OPS; seq++) {
+ hicn_name_set_suffix(&tmp, seqs[seq]);
+ __add_suffix(suffixes, hicn_name_get_suffix(&tmp),
+ hicn_name_get_suffix(&tmp));
+ }
+
+ // Read from hash table
+ for (int seq = 0; seq < N_OPS; seq++) {
+ hicn_name_set_suffix(&tmp, seqs[seq]);
+ __get_suffix(suffixes, hicn_name_get_suffix(&tmp));
+ }
+
+ _prefix_map_free(prefix_to_suffixes);
+ });
+ std::cout << "Cached lookup (rand): " << elapsed_time_single_rand << " ms\n";
+}
+
+TEST_F(PacketCacheTest, Clear) {
+ hicn_name_t tmp_name1, tmp_name2;
+ cs_t *cs = pkt_cache_get_cs(pkt_cache);
+
+ // Create name and add to msgbuf pool
+ hicn_name_copy(&tmp_name1, &name);
+ hicn_name_set_suffix(&tmp_name1, 1);
+ msgbuf_t *tmp_msgbuf1 = msgbuf_create(msgbuf_pool, CONN_ID_2, &tmp_name1);
+
+ // Create (another) name and add to msgbuf pool
+ hicn_name_copy(&tmp_name2, &name);
+ hicn_name_set_suffix(&tmp_name2, 2);
+ msgbuf_t *tmp_msgbuf2 = msgbuf_create(msgbuf_pool, CONN_ID_2, &tmp_name2);
+
+ // Add to packet cache (2 entries in the CS, 1 in the PIT)
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, msgbuf, MSGBUF_ID);
+ pkt_cache_add_to_pit(pkt_cache, tmp_msgbuf1, &tmp_name1);
+ pkt_cache_add_to_cs(pkt_cache, msgbuf_pool, tmp_msgbuf2, MSGBUF_ID_2);
+
+ // Check stats (before clearing the packet cache)
+ ASSERT_EQ(pkt_cache_get_size(pkt_cache), 3u);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 2u);
+ ASSERT_EQ(cs->num_entries, 2);
+ ASSERT_EQ(cs->stats.lru.countAdds, 2u);
+
+ // Clear packet cache (i.e. remove content packets from packet cache):
+ // PIT entry should still be there while CS entries are cleared
+ pkt_cache_cs_clear(pkt_cache);
+ cs = pkt_cache_get_cs(pkt_cache);
+
+ // Check stats (after clearing the packet cache)
+ ASSERT_EQ(pkt_cache_get_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_pit_size(pkt_cache), 1u);
+ ASSERT_EQ(pkt_cache_get_cs_size(pkt_cache), 0u);
+ ASSERT_EQ(cs->num_entries, 0);
+ ASSERT_EQ(cs->stats.lru.countAdds, 0u);
+}
diff --git a/hicn-light/src/hicn/test/test-parser.cc b/hicn-light/src/hicn/test/test-parser.cc
new file mode 100644
index 000000000..2e396b97d
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-parser.cc
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C" {
+#include <hicn/util/log.h>
+#include <hicn/ctrl/parse.h>
+}
+
+class ParserTest : public ::testing::Test {
+ protected:
+ ParserTest() { log_conf.log_level = LOG_INFO; }
+ virtual ~ParserTest() {}
+
+ hc_command_t command_ = {};
+};
+
+TEST_F(ParserTest, AddValidListener) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 9695 eth0";
+
+ ASSERT_EQ(parse(cmd.c_str(), &command_), 0);
+ EXPECT_EQ(command_.object.listener.type, FACE_TYPE_UDP_LISTENER);
+ EXPECT_EQ(std::string(command_.object.listener.name), "udp0");
+ EXPECT_EQ(command_.object.listener.family, AF_INET);
+ EXPECT_EQ(command_.object.listener.local_port, 9695);
+ EXPECT_EQ(std::string(command_.object.listener.interface_name), "eth0");
+}
+
+TEST_F(ParserTest, AddListenerSymbolicOverflow) {
+ std::string cmd =
+ "add listener udp super-long-symbolic-name 10.0.0.1 9696 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), -1);
+}
+
+TEST_F(ParserTest, AddListenerInvalidAddress) {
+ std::string cmd = "add listener udp udp0 10.0.0.0.1 9696 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), -1);
+}
+
+TEST_F(ParserTest, AddListenerInvalidAddressString) {
+ std::string cmd = "add listener udp udp0 invalid-addr 9696 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), -1);
+}
+
+TEST_F(ParserTest, AddListenerInvalidPortOutsideRange) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 0 eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), -1);
+}
+
+TEST_F(ParserTest, AddListenerInvalidPortString) {
+ std::string cmd = "add listener udp udp0 10.0.0.1 invalid-port eth0";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), -1);
+}
+
+TEST_F(ParserTest, UnknownCommnad) {
+ std::string cmd = "add face";
+ ASSERT_EQ(parse(cmd.c_str(), &command_), -1);
+}
diff --git a/hicn-light/src/hicn/test/test-probe_generator.cc b/hicn-light/src/hicn/test/test-probe_generator.cc
new file mode 100644
index 000000000..4d6cfa8f7
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-probe_generator.cc
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/strategies/probe_generator.h>
+}
+
+class ProbeGeneratorTest : public ::testing::Test {
+ protected:
+ ProbeGeneratorTest() {}
+
+ virtual ~ProbeGeneratorTest() {}
+};
+
+TEST_F(ProbeGeneratorTest, ProbeGeneratorRegisterProbe) {
+ probe_generator_t *pg = create_probe_generator();
+ EXPECT_FALSE(pg == nullptr);
+
+ register_probe(pg, 1);
+ register_probe(pg, 2);
+ register_probe(pg, 3);
+ register_probe(pg, 4);
+
+ Ticks t = get_probe_send_time(pg, 1);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 2);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 3);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 4);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 5);
+ EXPECT_FALSE(t != 0);
+
+ destroy_probe_generator(pg);
+}
+
+TEST_F(ProbeGeneratorTest, ProbeGeneratorTime) {
+ probe_generator_t *pg = create_probe_generator();
+ EXPECT_FALSE(pg == nullptr);
+
+ Ticks t1 = register_probe(pg, 1);
+ Ticks t2 = get_probe_send_time(pg, 1);
+
+ EXPECT_TRUE(t2 != 0);
+ EXPECT_TRUE(t1 == t2);
+
+ destroy_probe_generator(pg);
+}
+
+TEST_F(ProbeGeneratorTest, ProbeGeneratorDeleteProbe) {
+ probe_generator_t *pg = create_probe_generator();
+ EXPECT_FALSE(pg == nullptr);
+
+ register_probe(pg, 1);
+ register_probe(pg, 2);
+ register_probe(pg, 3);
+ register_probe(pg, 4);
+
+ Ticks t = get_probe_send_time(pg, 1);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 2);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 3);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 4);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 5);
+ EXPECT_FALSE(t != 0);
+
+ delete_probe(pg, 1);
+ delete_probe(pg, 3);
+
+ t = get_probe_send_time(pg, 1);
+ EXPECT_FALSE(t != 0);
+
+ t = get_probe_send_time(pg, 3);
+ EXPECT_FALSE(t != 0);
+
+ destroy_probe_generator(pg);
+}
+
+TEST_F(ProbeGeneratorTest, ProbeGeneratorDeleteAll) {
+ probe_generator_t *pg = create_probe_generator();
+ EXPECT_FALSE(pg == nullptr);
+
+ register_probe(pg, 1);
+ register_probe(pg, 2);
+ register_probe(pg, 3);
+ register_probe(pg, 4);
+
+ Ticks t = get_probe_send_time(pg, 1);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 2);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 3);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 4);
+ EXPECT_TRUE(t != 0);
+
+ t = get_probe_send_time(pg, 5);
+ EXPECT_FALSE(t != 0);
+
+ delete_all_probes(pg);
+
+ t = get_probe_send_time(pg, 1);
+ EXPECT_FALSE(t != 0);
+
+ t = get_probe_send_time(pg, 2);
+ EXPECT_FALSE(t != 0);
+
+ t = get_probe_send_time(pg, 3);
+ EXPECT_FALSE(t != 0);
+
+ t = get_probe_send_time(pg, 4);
+ EXPECT_FALSE(t != 0);
+
+ destroy_probe_generator(pg);
+}
diff --git a/hicn-light/src/hicn/test/test-strategy-best-path.cc b/hicn-light/src/hicn/test/test-strategy-best-path.cc
new file mode 100644
index 000000000..f909c15f2
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-strategy-best-path.cc
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/strategy.h>
+#include <hicn/strategies/best_path.h>
+}
+
+#define MAX_TESTS 10
+
+#define NEXTHOP_ID1 NEXTHOP(28)
+#define NEXTHOP_ID2 NEXTHOP(29)
+#define UNKNOWN_ID1 NEXTHOP(0)
+#define UNKNOWN_ID2 NEXTHOP(1)
+
+class StrategyBestpathTest : public ::testing::Test {
+ protected:
+ StrategyBestpathTest() {
+ /* Strategy and strategy entry */
+ entry = {
+ .type = STRATEGY_TYPE_BESTPATH,
+ .options =
+ {
+ .bestpath = {},
+ },
+ .state = {.bestpath = {}},
+ };
+
+ strategy_initialize(&entry, nullptr);
+
+ // test init
+ EXPECT_EQ(entry.forwarder, nullptr);
+ EXPECT_EQ(entry.state.bestpath.best_nexthop, (unsigned)~0);
+ EXPECT_EQ(entry.state.bestpath.probing_state, PROBING_OFF);
+
+ /* Available nexthops */
+ available_nexthops_ = NEXTHOPS_EMPTY;
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)0);
+
+ /* Message buffer */
+ msgbuf_ = NULL;
+ ticks_ = ticks_now();
+ }
+
+ virtual ~StrategyBestpathTest() { strategy_finalize(&entry); }
+
+ strategy_entry_t entry;
+ nexthops_t available_nexthops_;
+ msgbuf_t *msgbuf_;
+ Ticks ticks_;
+};
+
+TEST_F(StrategyBestpathTest, emptyNexthop) {
+ nexthops_t *nexthops;
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)0);
+}
+
+TEST_F(StrategyBestpathTest, faceExists) {
+ nexthops_t *nexthops;
+
+ nexthops_add(&available_nexthops_, NEXTHOP_ID1);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ nexthops_add(&available_nexthops_, NEXTHOP_ID2);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)2);
+
+ entry.state.bestpath.probing_state = PROBING_OFF;
+ entry.state.bestpath.best_nexthop = NEXTHOP_ID2;
+
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(nexthops, NEXTHOP_ID2));
+ EXPECT_FALSE(nexthops_contains(nexthops, NEXTHOP_ID1));
+
+ EXPECT_TRUE(entry.state.bestpath.probing_state == PROBING_OFF);
+ EXPECT_EQ(entry.state.bestpath.best_nexthop, NEXTHOP_ID2);
+}
diff --git a/hicn-light/src/hicn/test/test-strategy-load-balancing.cc b/hicn-light/src/hicn/test/test-strategy-load-balancing.cc
new file mode 100644
index 000000000..edac5669f
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-strategy-load-balancing.cc
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/strategy.h>
+#include <hicn/strategies/random.h>
+}
+
+#define MAX_TESTS 10
+
+#define NEXTHOP_ID NEXTHOP(28)
+#define NEXTHOP_ID2 NEXTHOP(29)
+#define UNKNOWN_ID1 NEXTHOP(0)
+#define UNKNOWN_ID2 NEXTHOP(1)
+
+class StrategyLoadBalancing : public ::testing::Test {
+ protected:
+ StrategyLoadBalancing() {
+ /* Strategy and strategy entry */
+ entry = {
+ .type = STRATEGY_TYPE_LOADBALANCER,
+ .options =
+ {
+ .random = {},
+ },
+ .state = {.random = {}},
+ };
+
+ strategy_initialize(&entry, nullptr);
+
+ /* Available nexthops */
+ available_nexthops_ = NEXTHOPS_EMPTY;
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)0);
+
+ /* Message buffer */
+ msgbuf_ = NULL;
+ ticks_ = ticks_now();
+ }
+ virtual ~StrategyLoadBalancing() {}
+
+ strategy_entry_t entry;
+ nexthops_t available_nexthops_;
+ msgbuf_t* msgbuf_;
+ Ticks ticks_;
+};
+
+TEST_F(StrategyLoadBalancing, SingleNexthop) {
+ /* Add a single nexthop */
+ off_t id;
+ id = nexthops_add(&available_nexthops_, NEXTHOP_ID);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ strategy_add_nexthop(&entry, &available_nexthops_, id);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID2));
+
+ /* Lookup */
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(nexthops, NEXTHOP_ID));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID2));
+
+ /* Retrieve candidate */
+
+ unsigned nexthop;
+ for (unsigned i = 0; i < MAX_TESTS; i++) {
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_EQ(nexthop, NEXTHOP_ID);
+ }
+
+ /* Disable (move to nexthop unit tests) */
+ nexthops_disable(nexthops, 0);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)0);
+
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_EQ(nexthop, INVALID_NEXTHOP);
+}
+
+TEST_F(StrategyLoadBalancing, MultipleNexthops) {
+ off_t id, id2;
+ /* Add a single nexthop */
+ id = nexthops_add(&available_nexthops_, NEXTHOP_ID);
+ id2 = nexthops_add(&available_nexthops_, NEXTHOP_ID2);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)2);
+
+ strategy_add_nexthop(&entry, &available_nexthops_, id);
+ strategy_add_nexthop(&entry, &available_nexthops_, id2);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)2);
+
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID));
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID2));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID2));
+
+ /* Lookup */
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+
+ EXPECT_TRUE((nexthops_contains(nexthops, NEXTHOP_ID)) ||
+ (nexthops_contains(nexthops, NEXTHOP_ID2)));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID2));
+
+ /* Retrieve candidate */
+
+ unsigned nexthop;
+ for (unsigned i = 0; i < MAX_TESTS; i++) {
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_TRUE((nexthop == NEXTHOP_ID) || (nexthop == NEXTHOP_ID2));
+ }
+}
diff --git a/hicn-light/src/hicn/test/test-strategy-local-remote.cc b/hicn-light/src/hicn/test/test-strategy-local-remote.cc
new file mode 100644
index 000000000..6693e29c8
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-strategy-local-remote.cc
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/base/loop.h>
+#include <hicn/config/configuration.h>
+#include <hicn/core/forwarder.h>
+#include <hicn/core/listener.h>
+#include <hicn/core/address_pair.h>
+#include <hicn/core/address.h>
+#include <hicn/core/strategy.h>
+#include <hicn/strategies/local_remote.h>
+}
+
+class StrategyLocalRemoteTest : public ::testing::Test {
+ protected:
+ StrategyLocalRemoteTest() {
+ conf_ = configuration_create();
+ MAIN_LOOP = loop_create();
+ fwd_ = forwarder_create(conf_);
+
+ /* Strategy and strategy entry */
+ entry_ = {
+ .type = STRATEGY_TYPE_LOCAL_REMOTE,
+ .options =
+ {
+ .random = {},
+ },
+ .state = {.random = {}},
+ };
+
+ strategy_initialize(&entry_, fwd_);
+ }
+
+ virtual ~StrategyLocalRemoteTest() {
+ INFO("loop stopped");
+ forwarder_free(fwd_);
+ loop_free(MAIN_LOOP);
+ MAIN_LOOP = NULL;
+ strategy_finalize(&entry_);
+ }
+
+ strategy_entry_t entry_;
+ nexthops_t available_nexthops_ = NEXTHOPS_EMPTY;
+ configuration_t* conf_;
+ forwarder_t* fwd_;
+ msgbuf_t msgbuf_;
+};
+
+TEST_F(StrategyLocalRemoteTest, InputLocalOutputLocal) {
+ address_t prod_addr = ADDRESS4_LOCALHOST(12345);
+ address_t cons_addr = ADDRESS4_LOCALHOST(12346);
+ address_t listener_addr = ADDRESS4_LOCALHOST(9596);
+
+ listener_t* listener = listener_create(FACE_TYPE_UDP_LISTENER, &listener_addr,
+ "lo", "lo_udp4", fwd_);
+
+ address_pair_t pair_conn_prod = {
+ .local = listener_addr,
+ .remote = prod_addr,
+ };
+
+ address_pair_t pair_conn_cons = {
+ .local = listener_addr,
+ .remote = cons_addr,
+ };
+
+ unsigned prod_conn_id =
+ listener_create_connection(listener, "conp", &pair_conn_prod);
+ unsigned cons_conn_id =
+ listener_create_connection(listener, "conc", &pair_conn_cons);
+
+ msgbuf_.connection_id = cons_conn_id;
+
+ nexthops_add(&available_nexthops_, prod_conn_id);
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry_, &available_nexthops_, &msgbuf_);
+
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)0);
+}
+
+TEST_F(StrategyLocalRemoteTest, InputRemoteOutputRemote) {
+ address_t prod_addr = ADDRESS4_LOCALHOST(12345);
+ address_t cons_addr = ADDRESS4_LOCALHOST(12346);
+ address_t listener_addr = ADDRESS4_LOCALHOST(9596);
+
+ listener_t* listener = listener_create(FACE_TYPE_UDP_LISTENER, &listener_addr,
+ "lo", "lo_udp4", fwd_);
+
+ address_pair_t pair_conn_prod = {
+ .local = listener_addr,
+ .remote = prod_addr,
+ };
+
+ address_pair_t pair_conn_cons = {
+ .local = listener_addr,
+ .remote = cons_addr,
+ };
+
+ connection_t* conn;
+ unsigned prod_conn_id =
+ listener_create_connection(listener, "conp", &pair_conn_prod);
+ unsigned cons_conn_id =
+ listener_create_connection(listener, "conc", &pair_conn_cons);
+
+ // fake two remote connections
+ conn = connection_table_get_by_id(forwarder_get_connection_table(fwd_),
+ prod_conn_id);
+ ASSERT_TRUE(conn != NULL);
+ conn->local = false;
+
+ conn = connection_table_get_by_id(forwarder_get_connection_table(fwd_),
+ cons_conn_id);
+ ASSERT_TRUE(conn != NULL);
+ conn->local = false;
+
+ msgbuf_.connection_id = cons_conn_id;
+
+ nexthops_add(&available_nexthops_, prod_conn_id);
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry_, &available_nexthops_, &msgbuf_);
+
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)0);
+}
+
+TEST_F(StrategyLocalRemoteTest, InputLocalOutputRemote) {
+ address_t prod_addr = ADDRESS4_LOCALHOST(12345);
+ address_t cons_addr = ADDRESS4_LOCALHOST(12346);
+ address_t listener_addr = ADDRESS4_LOCALHOST(9596);
+
+ listener_t* listener = listener_create(FACE_TYPE_UDP_LISTENER, &listener_addr,
+ "lo", "lo_udp4", fwd_);
+
+ address_pair_t pair_conn_prod = {
+ .local = listener_addr,
+ .remote = prod_addr,
+ };
+
+ address_pair_t pair_conn_cons = {
+ .local = listener_addr,
+ .remote = cons_addr,
+ };
+
+ connection_t* conn;
+ unsigned prod_conn_id =
+ listener_create_connection(listener, "conp", &pair_conn_prod);
+ unsigned cons_conn_id =
+ listener_create_connection(listener, "conc", &pair_conn_cons);
+
+ conn = connection_table_get_by_id(forwarder_get_connection_table(fwd_),
+ prod_conn_id);
+ ASSERT_TRUE(conn != NULL);
+ conn->local = false;
+ conn = connection_table_get_by_id(forwarder_get_connection_table(fwd_),
+ cons_conn_id);
+ ASSERT_TRUE(conn != NULL);
+ conn->local = true;
+
+ msgbuf_.connection_id = cons_conn_id;
+
+ nexthops_add(&available_nexthops_, prod_conn_id);
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry_, &available_nexthops_, &msgbuf_);
+
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+}
+
+TEST_F(StrategyLocalRemoteTest, InputRemoteOutputLocal) {
+ address_t cons_addr = ADDRESS4_LOCALHOST(12345);
+ address_t prod_addr = ADDRESS4_LOCALHOST(12346);
+ address_t listener_addr = ADDRESS4_LOCALHOST(9695);
+
+ listener_t* listener = listener_create(FACE_TYPE_UDP_LISTENER, &listener_addr,
+ "lo", "lo_udp4", fwd_);
+
+ address_pair_t pair_conn_prod = {
+ .local = listener_addr,
+ .remote = prod_addr,
+ };
+
+ address_pair_t pair_conn_cons = {
+ .local = listener_addr,
+ .remote = cons_addr,
+ };
+
+ connection_t* conn;
+ unsigned prod_conn_id =
+ listener_create_connection(listener, "conp", &pair_conn_prod);
+ unsigned cons_conn_id =
+ listener_create_connection(listener, "conc", &pair_conn_cons);
+
+ conn = connection_table_get_by_id(forwarder_get_connection_table(fwd_),
+ prod_conn_id);
+ ASSERT_TRUE(conn != NULL);
+ conn->local = true;
+ conn = connection_table_get_by_id(forwarder_get_connection_table(fwd_),
+ cons_conn_id);
+ ASSERT_TRUE(conn != NULL);
+ conn->local = false;
+
+ msgbuf_.connection_id = cons_conn_id;
+
+ nexthops_add(&available_nexthops_, prod_conn_id);
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry_, &available_nexthops_, &msgbuf_);
+
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+}
diff --git a/hicn-light/src/hicn/test/test-strategy-random.cc b/hicn-light/src/hicn/test/test-strategy-random.cc
new file mode 100644
index 000000000..bd9b70120
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-strategy-random.cc
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/strategy.h>
+#include <hicn/core/strategy_vft.h>
+#include <hicn/strategies/random.h>
+}
+
+#define MAX_TESTS 10
+
+#define NEXTHOP_ID NEXTHOP(28)
+#define UNKNOWN_ID1 NEXTHOP(0)
+#define UNKNOWN_ID2 NEXTHOP(1)
+
+class StrategyRandomTest : public ::testing::Test {
+ protected:
+ StrategyRandomTest() {
+ /* Strategy and strategy entry */
+ entry = {
+ .type = STRATEGY_TYPE_RANDOM,
+ .options =
+ {
+ .random = {},
+ },
+ .state = {.random = {}},
+ };
+
+ strategy_initialize(&entry, nullptr);
+
+ /* Available nexthops */
+ available_nexthops_ = NEXTHOPS_EMPTY;
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)0);
+
+ /* Message buffer */
+ msgbuf_ = NULL;
+ ticks_ = ticks_now();
+ }
+ virtual ~StrategyRandomTest() {}
+
+ strategy_entry_t entry;
+ nexthops_t available_nexthops_;
+ msgbuf_t* msgbuf_;
+ Ticks ticks_;
+};
+
+TEST_F(StrategyRandomTest, SingleNexthop) {
+ off_t id;
+
+ /* Add a single nexthop */
+ id = nexthops_add(&available_nexthops_, NEXTHOP_ID);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ strategy_add_nexthop(&entry, &available_nexthops_, id);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID2));
+
+ /* Lookup */
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(nexthops, NEXTHOP_ID));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID2));
+
+ /* Retrieve candidate */
+
+ unsigned nexthop;
+ for (unsigned i = 0; i < MAX_TESTS; i++) {
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_EQ(nexthop, NEXTHOP_ID);
+ }
+
+ /* Disable (move to nexthop unit tests) */
+ nexthops_disable(nexthops, 0);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)0);
+
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_EQ(nexthop, INVALID_NEXTHOP);
+}
+
+TEST_F(StrategyRandomTest, MultipleNexthops) {
+ off_t id;
+
+ /* Add a single nexthop */
+ id = nexthops_add(&available_nexthops_, NEXTHOP_ID);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ strategy_add_nexthop(&entry, &available_nexthops_, id);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID2));
+
+ /* Lookup */
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(nexthops, NEXTHOP_ID));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID2));
+
+ /* Retrieve candidate */
+
+ unsigned nexthop;
+ for (unsigned i = 0; i < MAX_TESTS; i++) {
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_EQ(nexthop, NEXTHOP_ID);
+ }
+}
diff --git a/hicn-light/src/hicn/test/test-strategy-replication.cc b/hicn-light/src/hicn/test/test-strategy-replication.cc
new file mode 100644
index 000000000..1c4d824b8
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-strategy-replication.cc
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C" {
+#define WITH_TESTS
+#include <hicn/core/strategy.h>
+#include <hicn/strategies/random.h>
+}
+
+#define MAX_TESTS 10
+
+#define NEXTHOP_ID1 NEXTHOP(28)
+#define NEXTHOP_ID2 NEXTHOP(29)
+#define UNKNOWN_ID1 NEXTHOP(0)
+#define UNKNOWN_ID2 NEXTHOP(1)
+
+class StrategyReplicationTest : public ::testing::Test {
+ protected:
+ StrategyReplicationTest() {
+ /* Strategy and strategy entry */
+ entry = {
+ .type = STRATEGY_TYPE_REPLICATION,
+ .options =
+ {
+ .replication = {},
+ },
+ .state = {.replication = {}},
+ };
+
+ strategy_initialize(&entry, nullptr);
+
+ /* Available nexthops */
+ available_nexthops_ = NEXTHOPS_EMPTY;
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)0);
+
+ /* Message buffer */
+ msgbuf_ = NULL;
+ ticks_ = ticks_now();
+ }
+
+ virtual ~StrategyReplicationTest() { strategy_finalize(&entry); }
+
+ strategy_entry_t entry;
+ nexthops_t available_nexthops_;
+ msgbuf_t* msgbuf_;
+ Ticks ticks_;
+};
+
+TEST_F(StrategyReplicationTest, SingleNexthop) {
+ off_t id;
+
+ /* Add a single nexthop */
+ id = nexthops_add(&available_nexthops_, NEXTHOP_ID1);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ strategy_add_nexthop(&entry, &available_nexthops_, id);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID1));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID2));
+
+ /* Lookup */
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)1);
+
+ EXPECT_TRUE(nexthops_contains(nexthops, NEXTHOP_ID1));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID2));
+
+ /* Retrieve candidate */
+
+ unsigned nexthop;
+ for (unsigned i = 0; i < MAX_TESTS; i++) {
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_EQ(nexthop, NEXTHOP_ID1);
+ }
+
+ /* Disable (move to nexthop unit tests) */
+ nexthops_disable(nexthops, 0);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)0);
+
+ nexthop = nexthops_get_one(nexthops);
+ EXPECT_EQ(nexthop, INVALID_NEXTHOP);
+}
+
+TEST_F(StrategyReplicationTest, MultipleNexthops) {
+ off_t id;
+
+ id = nexthops_add(&available_nexthops_, NEXTHOP_ID1);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ strategy_add_nexthop(&entry, &available_nexthops_, id);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)1);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)1);
+
+ id = nexthops_add(&available_nexthops_, NEXTHOP_ID2);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)2);
+
+ strategy_add_nexthop(&entry, &available_nexthops_, id);
+ EXPECT_EQ(nexthops_get_len(&available_nexthops_), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(&available_nexthops_), (size_t)2);
+
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID1));
+ EXPECT_TRUE(nexthops_contains(&available_nexthops_, NEXTHOP_ID2));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(&available_nexthops_, UNKNOWN_ID2));
+
+ /* Lookup */
+ nexthops_t* nexthops;
+ nexthops = strategy_lookup_nexthops(&entry, &available_nexthops_, msgbuf_);
+
+ EXPECT_EQ(nexthops_get_len(nexthops), (size_t)2);
+ EXPECT_EQ(nexthops_get_curlen(nexthops), (size_t)2);
+
+ EXPECT_TRUE(nexthops_contains(nexthops, NEXTHOP_ID1));
+ EXPECT_TRUE(nexthops_contains(nexthops, NEXTHOP_ID2));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID1));
+ EXPECT_FALSE(nexthops_contains(nexthops, UNKNOWN_ID2));
+
+ /* Retrieve candidate */
+
+ unsigned tests = 0;
+ nexthops_foreach(nexthops, nexthop, {
+ EXPECT_TRUE(nexthop == NEXTHOP_ID1 || nexthop == NEXTHOP_ID2);
+ tests++;
+ });
+
+ EXPECT_EQ(tests, (unsigned)2);
+}
diff --git a/hicn-light/src/hicn/test/test-subscription.cc b/hicn-light/src/hicn/test/test-subscription.cc
new file mode 100644
index 000000000..5fd3ab57d
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-subscription.cc
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C" {
+#include <hicn/core/subscription.h>
+#include <hicn/util/vector.h>
+}
+
+static inline unsigned CONN_ID = 1;
+static inline unsigned CONN_ID_2 = 2;
+
+class SubscriptionTest : public ::testing::Test {
+ protected:
+ SubscriptionTest() { subscriptions = subscription_table_create(); }
+ virtual ~SubscriptionTest() { subscription_table_free(subscriptions); }
+
+ subscription_table_t *subscriptions;
+};
+
+TEST_F(SubscriptionTest, CreateSubscriptionTable) {
+ // Check subscription table allocation
+ ASSERT_NE(subscriptions, nullptr);
+}
+
+TEST_F(SubscriptionTest, SetTopic) {
+ hc_topics_t topics = TOPIC_STRATEGY;
+
+ // Check that only the topic desired has been subscribed to
+ for (int topic = TOPIC_UNDEFINED; topic < TOPIC_N; topic <<= 1) {
+ if (topic == TOPIC_STRATEGY) {
+ EXPECT_TRUE(topics_contains(topics, (hc_topic_t)topic));
+ continue;
+ }
+ EXPECT_FALSE(topics_contains(topics, (hc_topic_t)topic));
+ }
+}
+
+TEST_F(SubscriptionTest, GetObjectFromTopic) {
+ hc_object_type_t object_type = object_from_topic(TOPIC_STRATEGY);
+ EXPECT_EQ(object_type, OBJECT_TYPE_STRATEGY);
+
+ object_type = object_from_topic(TOPIC_FACE);
+ EXPECT_EQ(object_type, OBJECT_TYPE_FACE);
+}
+
+TEST_F(SubscriptionTest, AddSubscription) {
+ hc_topics_t topics = TOPIC_STRATEGY;
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, topics);
+}
+
+TEST_F(SubscriptionTest, AddAndRemoveSubscriptionForAllTopics) {
+ hc_topics_t topics = ALL_TOPICS;
+ int ret = subscription_table_add_topics_for_connection(subscriptions,
+ ALL_TOPICS, CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ int num_subscriptions_removed =
+ subscription_table_remove_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(num_subscriptions_removed, NUM_TOPICS);
+
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, 0u);
+}
+
+// Failure while adding subscription cannot be tested since it depends on vector
+// reallocation
+
+TEST_F(SubscriptionTest, AddSubscriptionAlreadyAdded) {
+ hc_topics_t topics = TOPIC_STRATEGY;
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ // Subscribe again to same topic
+ ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, -2); // -2 = already-added subscription
+
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, topics);
+}
+
+TEST_F(SubscriptionTest, GetSubscriptionsForConnectionWithoutSubscriptions) {
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, (hc_topics_t)0);
+}
+
+TEST_F(SubscriptionTest, GetSubscriptionsForConnectionWithMultipleSubs) {
+ hc_topics_t topics = TOPIC_STRATEGY | TOPIC_FACE;
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, topics);
+
+ // Add another subscription
+ ret = subscription_table_add_topics_for_connection(subscriptions, TOPIC_PROBE,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, topics |= TOPIC_PROBE);
+}
+
+TEST_F(SubscriptionTest, RemoveSubscription) {
+ // Add subscriptions
+ hc_topics_t topics = TOPIC_STRATEGY | TOPIC_FACE;
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ // Remove one of the previously added subscriptions
+ int num_subscriptions_removed =
+ subscription_table_remove_topics_for_connection(subscriptions,
+ TOPIC_STRATEGY, CONN_ID);
+ EXPECT_EQ(num_subscriptions_removed, 1);
+
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, TOPIC_FACE);
+}
+
+TEST_F(SubscriptionTest, RemoveMultipleSubscriptions) {
+ // Add subscriptions
+ hc_topics_t topics = TOPIC_STRATEGY | TOPIC_FACE | TOPIC_PROBE;
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ // Remove two of the previously added subscriptions
+ int num_subscriptions_removed =
+ subscription_table_remove_topics_for_connection(
+ subscriptions, TOPIC_STRATEGY | TOPIC_FACE, CONN_ID);
+ EXPECT_EQ(num_subscriptions_removed, 2);
+
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, TOPIC_PROBE);
+}
+
+TEST_F(SubscriptionTest, RemoveNonRegistredSubscription) {
+ // Remove a subscription that is not present
+ int num_subscriptions_removed =
+ subscription_table_remove_topics_for_connection(subscriptions,
+ TOPIC_PROBE, CONN_ID);
+ EXPECT_EQ(num_subscriptions_removed, 0);
+
+ // Add two new subscriptions
+ hc_topics_t topics = TOPIC_STRATEGY | TOPIC_FACE;
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ // Remove subscription that was not registred previously
+ num_subscriptions_removed = subscription_table_remove_topics_for_connection(
+ subscriptions, TOPIC_PROBE, CONN_ID);
+ EXPECT_EQ(num_subscriptions_removed, 0);
+
+ hc_topics_t topics_ret =
+ subscription_table_get_topics_for_connection(subscriptions, CONN_ID);
+ EXPECT_EQ(topics_ret, topics);
+}
+
+TEST_F(SubscriptionTest, GetConnectionsForSubscription) {
+ // Add subscriptions for two connections
+ hc_topics_t topics = TOPIC_STRATEGY | TOPIC_FACE;
+ int ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ topics = TOPIC_STRATEGY;
+ ret = subscription_table_add_topics_for_connection(subscriptions, topics,
+ CONN_ID_2);
+ EXPECT_EQ(ret, 0); // 0 = success
+
+ // Check the connections associated with the strategy topic
+ unsigned *conn_ids = subscription_table_get_connections_for_topic(
+ subscriptions, TOPIC_STRATEGY);
+ EXPECT_EQ(vector_len(conn_ids), 2u);
+ EXPECT_TRUE(conn_ids[0] == CONN_ID || conn_ids[0] == CONN_ID_2);
+ EXPECT_TRUE(conn_ids[1] == CONN_ID || conn_ids[1] == CONN_ID_2);
+
+ // Check the connections associated with the face topic
+ conn_ids =
+ subscription_table_get_connections_for_topic(subscriptions, TOPIC_FACE);
+ EXPECT_EQ(vector_len(conn_ids), 1u);
+ EXPECT_EQ(conn_ids[0], (unsigned)CONN_ID);
+}
diff --git a/hicn-light/src/hicn/test/test-utils.h b/hicn-light/src/hicn/test/test-utils.h
new file mode 100644
index 000000000..577629584
--- /dev/null
+++ b/hicn-light/src/hicn/test/test-utils.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include <vector>
+#include <thread>
+#include <numeric>
+
+static constexpr int N_RUNS = 100;
+
+// Utility function for time execution calculation
+template <typename F, typename... Args>
+double get_execution_time(F func, Args &&...args) {
+ std::vector<float> execution_times;
+
+ for (int i = 0; i < N_RUNS; i++) {
+ auto start = std::chrono::high_resolution_clock::now();
+ func(std::forward<Args>(args)...);
+ auto end = std::chrono::high_resolution_clock::now();
+
+ std::chrono::duration<double, std::milli> ms = end - start;
+ execution_times.emplace_back(ms.count());
+ }
+
+ // Calculate average
+ return std::reduce(execution_times.begin(), execution_times.end()) /
+ execution_times.size();
+} \ No newline at end of file
diff --git a/hicn-light/src/hicn/test/test_hash.cc b/hicn-light/src/hicn/test/test_hash.cc
new file mode 100644
index 000000000..c742aa248
--- /dev/null
+++ b/hicn-light/src/hicn/test/test_hash.cc
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <unordered_set>
+#include <hicn/test/test-utils.h>
+
+extern "C" {
+#include <hicn/util/hash.h>
+#include <hicn/core/address_pair.h>
+#include <hicn/core/listener.h>
+}
+
+static constexpr uint32_t init_val = 2166136261UL;
+static constexpr int N_HASHES = 50000;
+
+TEST(HashTest, MultipleHashesForSameAddrPair) {
+ address_pair_t pair =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(2));
+
+ unsigned h1 = hash_struct(&pair);
+ unsigned h2 = hash_struct(&pair);
+ EXPECT_EQ(h1, h2);
+}
+
+TEST(HashTest, SameAddrPairs) {
+ address_pair_t pair1 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(2));
+ address_pair_t pair2 = pair1;
+
+ unsigned h1 = hash_struct(&pair1);
+ unsigned h2 = hash_struct(&pair2);
+ EXPECT_EQ(h1, h2);
+}
+
+TEST(HashTest, DifferentAddrPairs) {
+ address_pair_t pair1 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(2));
+
+ address_pair_t pair2 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(3), _ADDRESS4_LOCALHOST(4));
+
+ unsigned h1 = hash_struct(&pair1);
+ unsigned h2 = hash_struct(&pair2);
+ EXPECT_NE(h1, h2);
+}
+
+TEST(HashTest, SameLocalDifferentRemote) {
+ address_pair_t pair1 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(2));
+
+ address_pair_t pair2 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(4));
+
+ unsigned h1 = hash_struct(&pair1);
+ unsigned h2 = hash_struct(&pair2);
+ EXPECT_NE(h1, h2);
+}
+
+TEST(HashTest, SameRemoteDifferentLocal) {
+ address_pair_t pair1 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(1), _ADDRESS4_LOCALHOST(2));
+
+ address_pair_t pair2 =
+ address_pair_factory(_ADDRESS4_LOCALHOST(3), _ADDRESS4_LOCALHOST(2));
+
+ unsigned h1 = hash_struct(&pair1);
+ unsigned h2 = hash_struct(&pair2);
+ EXPECT_NE(h1, h2);
+}
+
+TEST(HashTest, SameAddresses) {
+ address_t addr1 = _ADDRESS4_LOCALHOST(1);
+ address_t addr2 = _ADDRESS4_LOCALHOST(1);
+
+ unsigned h1 = hash_struct(&addr1);
+ unsigned h2 = hash_struct(&addr2);
+
+ EXPECT_EQ(h1, h2);
+}
+
+TEST(HashTest, SameListenerKeys) {
+ listener_key_t key1 =
+ listener_key_factory(_ADDRESS4_LOCALHOST(1), FACE_TYPE_UDP_LISTENER);
+ listener_key_t key2 =
+ listener_key_factory(_ADDRESS4_LOCALHOST(1), FACE_TYPE_UDP_LISTENER);
+
+ unsigned h1 = hash_struct(&key1);
+ unsigned h2 = hash_struct(&key2);
+
+ EXPECT_EQ(h1, h2);
+}
+
+TEST(HashTest, Collisions) {
+ std::unordered_set<uint32_t> hashes;
+ int n_collisions = 0;
+ for (int i = 0; i < 50000; i++) {
+ uint32_t seg = i;
+ // u32 h = utils::hash::fnv32_buf(&seg, sizeof(seg));
+ // u32 h = cumulative_hash32(&seg, sizeof(uint32_t), init_val);
+ u32 h = hash(&seg, sizeof(seg));
+
+ if (hashes.find(h) != hashes.end()) n_collisions++;
+ hashes.insert(h);
+ }
+ EXPECT_EQ(n_collisions, 0);
+}
+
+/*** Compare FNV with Jenkins ***/
+
+typedef struct {
+ uint32_t data[6];
+} small_struct_t; // Same size as 'NameBitvector'
+
+typedef struct {
+ uint64_t data[32];
+} big_struct_t; // Same size as 'address_pair_t'
+
+TEST(HashTest, PerformanceComparisonSmallStruct) {
+ small_struct_t small_struct;
+
+ // FNV
+ auto time_fnv = get_execution_time([&]() {
+ for (int i = 0; i < N_HASHES; i++) {
+ small_struct.data[0] = i;
+ cumulative_hash32(&small_struct, sizeof(small_struct_t), init_val);
+ }
+ });
+
+ // Jenkins
+ auto time_jenkins = get_execution_time([&]() {
+ for (int i = 0; i < N_HASHES; i++) {
+ small_struct.data[0] = i;
+ hash(&small_struct, sizeof(small_struct_t));
+ }
+ });
+
+ std::cout << "Small struct (size = " << sizeof(small_struct_t) << " bytes)\n";
+ std::cout << "FNV: " << time_fnv << "ms\n";
+ std::cout << "Jenkins: " << time_jenkins << "ms\n";
+}
+
+TEST(HashTest, PerformanceComparisonBigStruct) {
+ big_struct_t big_struct;
+
+ // FNV
+ auto time_fnv = get_execution_time([&]() {
+ for (int i = 0; i < N_HASHES; i++) {
+ big_struct.data[0] = i;
+ cumulative_hash32(&big_struct, sizeof(big_struct_t), init_val);
+ }
+ });
+
+ // Jenkins
+ auto time_jenkins = get_execution_time([&]() {
+ for (int i = 0; i < N_HASHES; i++) {
+ big_struct.data[0] = i;
+ hash(&big_struct, sizeof(big_struct_t));
+ }
+ });
+
+ std::cout << "Big struct (size = " << sizeof(big_struct_t) << " bytes)\n";
+ std::cout << "FNV: " << time_fnv << "ms\n";
+ std::cout << "Jenkins: " << time_jenkins << "ms\n";
+}
+
+TEST(HashTest, CollisionsComparison) {
+ small_struct_t small_struct = {0};
+ std::unordered_set<uint32_t> hashes;
+ int n_collisions_fnv = 0, n_collisions_jenkins = 0;
+
+ // FNV
+ for (int i = 0; i < 10 * N_HASHES; i++) {
+ small_struct.data[0] = i;
+ uint32_t h =
+ cumulative_hash32(&small_struct, sizeof(small_struct_t), init_val);
+
+ if (hashes.find(h) != hashes.end()) n_collisions_fnv++;
+ hashes.insert(h);
+ }
+
+ hashes.clear();
+
+ // Jenkins
+ for (int i = 0; i < 10 * N_HASHES; i++) {
+ small_struct.data[0] = i;
+ uint32_t h = hash(&small_struct, sizeof(small_struct_t));
+
+ if (hashes.find(h) != hashes.end()) n_collisions_jenkins++;
+ hashes.insert(h);
+ }
+
+ std::cout << "Small struct (size = " << sizeof(small_struct_t) << " bytes)\n";
+ std::cout << "FNV: " << n_collisions_fnv << " collision/s\n";
+ std::cout << "Jenkins: " << n_collisions_jenkins << " collision/s\n";
+} \ No newline at end of file
diff --git a/hicn-light/src/hicn/utils/CMakeLists.txt b/hicn-light/src/hicn/utils/CMakeLists.txt
index c8c9b8487..72a918cac 100644
--- a/hicn-light/src/hicn/utils/CMakeLists.txt
+++ b/hicn-light/src/hicn/utils/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,30 +11,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+# XXX This is installed in hicn/utils...
list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/address.h
- ${CMAKE_CURRENT_SOURCE_DIR}/addressList.h
- ${CMAKE_CURRENT_SOURCE_DIR}/commands.h
- ${CMAKE_CURRENT_SOURCE_DIR}/interface.h
- ${CMAKE_CURRENT_SOURCE_DIR}/interfaceSet.h
+# ${CMAKE_CURRENT_SOURCE_DIR}/commands.h
+# ${CMAKE_CURRENT_SOURCE_DIR}/interface.h
+# ${CMAKE_CURRENT_SOURCE_DIR}/interfaceSet.h
${CMAKE_CURRENT_SOURCE_DIR}/punting.h
${CMAKE_CURRENT_SOURCE_DIR}/token.h
- ${CMAKE_CURRENT_SOURCE_DIR}/utils.h
)
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/address.c
- ${CMAKE_CURRENT_SOURCE_DIR}/addressList.c
- ${CMAKE_CURRENT_SOURCE_DIR}/interface.c
- ${CMAKE_CURRENT_SOURCE_DIR}/interfaceSet.c
+# ${CMAKE_CURRENT_SOURCE_DIR}/interface.c
+# ${CMAKE_CURRENT_SOURCE_DIR}/interfaceSet.c
${CMAKE_CURRENT_SOURCE_DIR}/punting.c
- ${CMAKE_CURRENT_SOURCE_DIR}/utils.c
-)
-
-set(TO_INSTALL_HEADER_FILES
- ${TO_INSTALL_HEADER_FILES}
- ${HEADER_FILES}
- PARENT_SCOPE
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
diff --git a/hicn-light/src/hicn/utils/address.c b/hicn-light/src/hicn/utils/address.c
deleted file mode 100644
index 619097e1d..000000000
--- a/hicn-light/src/hicn/utils/address.c
+++ /dev/null
@@ -1,450 +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.
- */
-
-#ifndef _WIN32
-#include <arpa/inet.h>
-#include <unistd.h>
-#endif
-#include <errno.h>
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <hicn/utils/address.h>
-
-#include <parc/algol/parc_Base64.h>
-#include <parc/algol/parc_BufferComposer.h>
-#include <parc/algol/parc_Hash.h>
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <parc/algol/parc_Object.h>
-
-#include <parc/assert/parc_Assert.h>
-
-struct address {
- address_type addressType;
- PARCBuffer *blob;
-};
-
-static struct address_type_str {
- address_type type;
- const char *str;
-} addressTypeString[] = {
- {.type = ADDR_INET, .str = "INET"}, {.type = ADDR_INET6, .str = "INET6"},
- {.type = ADDR_LINK, .str = "LINK"}, {.type = ADDR_IFACE, .str = "IFACE"},
- {.type = ADDR_UNIX, .str = "UNIX"}, {.type = 0, .str = NULL}};
-
-void addressDestroy(Address **addressPtr) {
- parcAssertNotNull(addressPtr, "Parameter must be non-null double pointer");
- parcAssertNotNull(*addressPtr,
- "Parameter must dereference to non-null pointer");
-
- Address *address = *addressPtr;
- parcBuffer_Release(&address->blob);
- parcMemory_Deallocate((void **)&address);
- *addressPtr = NULL;
-}
-
-void addressAssertValid(const Address *address) {
- parcAssertNotNull(address, "Parameter must be non-null Address *");
-}
-
-const char *addressTypeToString(address_type type) {
- for (int i = 0; addressTypeString[i].str != NULL; i++) {
- if (addressTypeString[i].type == type) {
- return addressTypeString[i].str;
- }
- }
- parcTrapIllegalValue(type, "Unknown value: %d", type);
- const char *result = NULL;
- return result;
-}
-
-address_type addressStringToType(const char *str) {
- for (int i = 0; addressTypeString[i].str != NULL; i++) {
- if (strcasecmp(addressTypeString[i].str, str) == 0) {
- return addressTypeString[i].type;
- }
- }
- parcTrapIllegalValue(str, "Unknown type '%s'", str);
- return 0;
-}
-
-static Address *_addressCreate(address_type addressType, PARCBuffer *buffer) {
- Address *result = parcMemory_AllocateAndClear(sizeof(Address));
-
- parcAssertNotNull(result, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(Address));
- if (result != NULL) {
- result->addressType = addressType;
- result->blob = buffer;
- }
- return result;
-}
-
-Address *addressCreateFromInet(struct sockaddr_in *addr_in) {
- parcAssertNotNull(addr_in, "Parameter must be non-null");
-
- addr_in->sin_family = AF_INET;
-
- PARCBuffer *buffer = parcBuffer_Allocate(sizeof(struct sockaddr_in));
- parcBuffer_PutArray(buffer, sizeof(struct sockaddr_in), (uint8_t *)addr_in);
- parcBuffer_Flip(buffer);
-
- Address *result = _addressCreate(ADDR_INET, buffer);
-
- return result;
-}
-
-Address *addressCreateFromInet6(struct sockaddr_in6 *addr_in6) {
- parcAssertNotNull(addr_in6, "Parameter must be non-null");
-
- PARCBuffer *buffer = parcBuffer_Allocate(sizeof(struct sockaddr_in6));
- parcBuffer_PutArray(buffer, sizeof(struct sockaddr_in6), (uint8_t *)addr_in6);
- parcBuffer_Flip(buffer);
-
- Address *result = _addressCreate(ADDR_INET6, buffer);
-
- return result;
-}
-
-Address *addressFromInaddr4Port(in_addr_t *addr4, in_port_t *port) {
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
-
- // We assume address and port are already written in memory in network byte
- // order
- addr.sin_family = AF_INET;
- addr.sin_port = *port;
- addr.sin_addr.s_addr = *addr4;
-
- Address *result = addressCreateFromInet(&addr);
- return result;
-}
-
-Address *addressFromInaddr6Port(struct in6_addr *addr6, in_port_t *port) {
- struct sockaddr_in6 addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin6_family = AF_INET6;
-
- // We assume address and port are already written in memory in network byte
- // order
- addr.sin6_port = *port;
- addr.sin6_addr = *addr6;
- addr.sin6_scope_id = 0;
- // Other 2 fields: scope_id and flowinfo, do not know what to put inside.
-
- Address *result = addressCreateFromInet6(&addr);
- return result;
-}
-
-Address *addressCreateFromLink(const uint8_t *linkaddr, size_t length) {
- parcAssertNotNull(linkaddr, "Parameter must be non-null");
-
- PARCBuffer *buffer = parcBuffer_Allocate(sizeof(struct sockaddr_in6));
- parcBuffer_PutArray(buffer, length, linkaddr);
- parcBuffer_Flip(buffer);
-
- Address *result = _addressCreate(ADDR_LINK, buffer);
- return result;
-}
-
-Address *addressCreateFromInterface(unsigned interfaceIndex) {
- unsigned netbyteorder = htonl(interfaceIndex);
-
- PARCBuffer *buffer = parcBuffer_Allocate(sizeof(netbyteorder));
- parcBuffer_PutArray(buffer, sizeof(netbyteorder), (uint8_t *)&netbyteorder);
- parcBuffer_Flip(buffer);
-
- Address *result = _addressCreate(ADDR_IFACE, buffer);
- return result;
-}
-
-Address *addressCreateFromUnix(struct sockaddr_un *addr_un) {
- parcAssertNotNull(addr_un, "Parameter must be non-null");
-
- PARCBuffer *buffer = parcBuffer_Allocate(sizeof(struct sockaddr_un));
- parcBuffer_PutArray(buffer, sizeof(struct sockaddr_un), (uint8_t *)addr_un);
- parcBuffer_Flip(buffer);
-
- Address *result = _addressCreate(ADDR_UNIX, buffer);
- return result;
-}
-
-Address *addressCopy(const Address *original) {
- addressAssertValid(original);
-
- Address *result =
- _addressCreate(original->addressType, parcBuffer_Copy(original->blob));
- return result;
-}
-
-bool addressEquals(const Address *a, const Address *b) {
- if (a == b) {
- return true;
- }
-
- if (a == NULL || b == NULL) {
- return false;
- }
-
- if (a->addressType == b->addressType) {
- if (parcBuffer_Equals(a->blob, b->blob)) {
- return true;
- }
- }
-
- return false;
-}
-
-address_type addressGetType(const Address *address) {
- addressAssertValid(address);
-
- return address->addressType;
-}
-
-// The Get functions need better names, what they do (Get from what? Put to
-// what?) is not clear from their names. Case 1028
-bool addressGetInet(const Address *address, struct sockaddr_in *addr_in) {
- addressAssertValid(address);
- parcAssertNotNull(addr_in, "Parameter addr_in must be non-null");
-
- if (address->addressType == ADDR_INET) {
- parcAssertTrue(
- parcBuffer_Remaining(address->blob) == sizeof(struct sockaddr_in),
- "Address corrupted. Expected length %zu, actual length %zu",
- sizeof(struct sockaddr_in), parcBuffer_Remaining(address->blob));
-
- memcpy(addr_in, parcBuffer_Overlay(address->blob, 0),
- sizeof(struct sockaddr_in));
- return true;
- }
- return false;
-}
-
-bool addressGetInet6(const Address *address, struct sockaddr_in6 *addr_in6) {
- addressAssertValid(address);
- parcAssertNotNull(addr_in6, "Parameter addr_in6 must be non-null");
-
- if (address->addressType == ADDR_INET6) {
- parcAssertTrue(
- parcBuffer_Remaining(address->blob) == sizeof(struct sockaddr_in6),
- "Address corrupted. Expected length %zu, actual length %zu",
- sizeof(struct sockaddr_in6), parcBuffer_Remaining(address->blob));
-
- memcpy(addr_in6, parcBuffer_Overlay(address->blob, 0),
- sizeof(struct sockaddr_in6));
- return true;
- }
- return false;
-}
-
-bool addressGetUnix(const Address *address, struct sockaddr_un *addr_un) {
- addressAssertValid(address);
- parcAssertNotNull(addr_un, "Parameter addr_in6 must be non-null");
-
- if (address->addressType == ADDR_UNIX) {
- parcAssertTrue(
- parcBuffer_Remaining(address->blob) == sizeof(struct sockaddr_un),
- "Address corrupted. Expected length %zu, actual length %zu",
- sizeof(struct sockaddr_un), parcBuffer_Remaining(address->blob));
-
- memcpy(addr_un, parcBuffer_Overlay(address->blob, 0),
- sizeof(struct sockaddr_un));
- return true;
- }
- return false;
-}
-
-bool addressGetInterfaceIndex(const Address *address, uint32_t *ifidx) {
- addressAssertValid(address);
- parcAssertNotNull(ifidx, "Parameter ifidx must be non-null");
-
- if (address->addressType == ADDR_IFACE) {
- parcAssertTrue(parcBuffer_Remaining(address->blob) == sizeof(uint32_t),
- "Address corrupted. Expected length %zu, actual length %zu",
- sizeof(uint32_t), parcBuffer_Remaining(address->blob));
-
- uint32_t netbyteorder;
- memcpy(&netbyteorder, parcBuffer_Overlay(address->blob, 0),
- sizeof(uint32_t));
- *ifidx = ntohl(netbyteorder);
- return true;
- }
- return false;
-}
-
-PARCBuffer *addressGetLinkAddress(const Address *address) {
- addressAssertValid(address);
- if (address->addressType == ADDR_LINK) {
- return address->blob;
- }
- return NULL;
-}
-
-static PARCBufferComposer *_Inet_BuildString(const Address *address,
- PARCBufferComposer *composer) {
- addressAssertValid(address);
-
- struct sockaddr_in *saddr =
- (struct sockaddr_in *)parcBuffer_Overlay(address->blob, 0);
- return parcNetwork_SockInet4Address_BuildString(saddr, composer);
-}
-
-static PARCBufferComposer *_Inet6_BuildString(const Address *address,
- PARCBufferComposer *composer) {
- addressAssertValid(address);
-
- struct sockaddr_in6 *saddr =
- (struct sockaddr_in6 *)parcBuffer_Overlay(address->blob, 0);
- return parcNetwork_SockInet6Address_BuildString(saddr, composer);
-}
-
-static PARCBufferComposer *_Link_BuildString(const Address *address,
- PARCBufferComposer *composer) {
- addressAssertValid(address);
-
- const unsigned char *addr = parcBuffer_Overlay(address->blob, 0);
-
- size_t length = parcBuffer_Remaining(address->blob);
-
- return parcNetwork_LinkAddress_BuildString(addr, length, composer);
-}
-
-static ssize_t _UnixToString(char *output, size_t remaining_size,
- const PARCBuffer *addr) {
- parcAssertNotNull(output, "parameter output must be non-null");
- parcBuffer_AssertValid(addr);
-
- parcAssertTrue(parcBuffer_Remaining(addr) == sizeof(struct sockaddr_un),
- "Address corrupted. Expected %zu actual %zu",
- sizeof(struct sockaddr_un), parcBuffer_Remaining(addr));
-
- // sockaddr length for the path, 16 for the ascii stuff, 3 for the length
- // number
- struct sockaddr_un *saddr =
- (struct sockaddr_un *)parcBuffer_Overlay((PARCBuffer *)addr, 0);
- size_t min_remaining = strlen(saddr->sun_path) + 16 + 3;
- parcAssertTrue(remaining_size >= min_remaining,
- "Remaining size too small, need at least %zu", min_remaining);
-
- ssize_t output_length = sprintf(output, "{ .path=%s, .len=%zu }",
- saddr->sun_path, strlen(saddr->sun_path));
- return output_length;
-}
-
-static ssize_t _IfaceToString(char *output, size_t remaining_size,
- const PARCBuffer *addr) {
- parcAssertNotNull(output, "parameter output must be non-null");
- parcBuffer_AssertValid(addr);
-
- parcAssertTrue(parcBuffer_Remaining(addr) == sizeof(uint32_t),
- "Address corrupted. Expected %zu actual %zu", sizeof(uint32_t),
- parcBuffer_Remaining(addr));
-
- uint32_t *ifidx = (uint32_t *)parcBuffer_Overlay((PARCBuffer *)addr, 0);
-
- ssize_t output_length = sprintf(output, "{ .ifidx=%u }", ntohl(*ifidx));
-
- return output_length;
-}
-
-PARCBufferComposer *addressBuildString(const Address *address,
- PARCBufferComposer *composer) {
- if (address != NULL) {
- char *str = addressToString(address);
- parcBufferComposer_PutString(composer, str);
- parcMemory_Deallocate((void **)&str);
- }
- return composer;
-}
-
-char *addressToString(const Address *address) {
- addressAssertValid(address);
-
- char addrstr[256];
-
- switch (address->addressType) {
- case ADDR_INET: {
- PARCBufferComposer *composer = parcBufferComposer_Create();
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(
- _Inet_BuildString(address, composer));
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
- parcBufferComposer_Release(&composer);
- return result;
- } break;
-
- case ADDR_INET6: {
- PARCBufferComposer *composer = parcBufferComposer_Create();
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(
- _Inet6_BuildString(address, composer));
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
-
- parcBufferComposer_Release(&composer);
- return result;
- } break;
-
- case ADDR_LINK:
- _UnixToString(addrstr, 256, address->blob);
- break;
-
- case ADDR_IFACE: {
- PARCBufferComposer *composer = parcBufferComposer_Create();
-
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(
- _Link_BuildString(address, composer));
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
-
- parcBufferComposer_Release(&composer);
- return result;
- } break;
-
- case ADDR_UNIX:
- _IfaceToString(addrstr, 256, address->blob);
- break;
-
- default:
- sprintf(addrstr, "UNKNOWN type = %d", address->addressType);
- break;
- }
-
- ssize_t alloc_size = 1024;
- char *output = parcMemory_Allocate(alloc_size);
- parcAssertNotNull(output, "parcMemory_Allocate(%zu) returned NULL",
- alloc_size);
- ssize_t output_length =
- snprintf(output, alloc_size, "{ .type=%s, .data=%s }",
- addressTypeToString(address->addressType), addrstr);
-
- parcAssertTrue(output_length < alloc_size,
- "allocated size too small, needed %zd", output_length);
- parcAssertFalse(output_length < 0, "snprintf error: (%d) %s", errno,
- strerror(errno));
-
- return output;
-}
-
-PARCHashCode addressHashCode(const Address *address) {
- addressAssertValid(address);
-
- PARCHashCode hash = parcBuffer_HashCode(address->blob);
- hash = parcHashCode_HashImpl((uint8_t *)&address->addressType,
- sizeof(address->addressType), hash);
-
- return hash;
-}
diff --git a/hicn-light/src/hicn/utils/address.h b/hicn-light/src/hicn/utils/address.h
deleted file mode 100644
index 6ca98347a..000000000
--- a/hicn-light/src/hicn/utils/address.h
+++ /dev/null
@@ -1,524 +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.
- */
-
-/**
- * @brief Represents an endpoint address.
- *
- * Represents an endpoint address. May be INET, INET6, or a multi-byte LINK,
- * or an Interface Index.
- *
- * INET and INET6 must contain the .sa_addr member, and other members as needed
- * by the use of the address.
- *
- * The Interface Index address is essentially a pointer to a device.
- *
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-#ifndef address_h
-#define address_h
-
-#ifndef _WIN32
-#include <netinet/in.h>
-#include <sys/un.h>
-#endif
-#include <stdbool.h>
-
-#include <parc/algol/parc_Buffer.h>
-#include <parc/algol/parc_BufferComposer.h>
-#include <hicn/utils/commands.h>
-
-/**
- * Return a string representation of the given `address_type`
- *
- * @param [in] type A valid address_type value.
- *
- * @return NULL An error occurred
- * @return non-NULL A pointer to a static string representation of the
- * `address_type`.
- *
- * Example:
- * @code
- * {
- * const char *typeAsString = addressTypeToString(commandAddrType_INET);
- * }
- * @endcode
- *
- * @see addressStringToType
- */
-const char *addressTypeToString(address_type type);
-
-/**
- * Return a `address_type` from the given nul-terminated C string.
- *
- * @param [in] typeAsString A nul-terminated, C string representation of a
- * `address_type`.
- *
- * @return A address_type
- *
- * Example:
- * @code
- * {
- * address_type type = addressTypeToString("INET");
- * }
- * @endcode
- *
- * @see addressTypeToString
- */
-address_type addressStringToType(const char *typeAsString);
-
-struct address;
-typedef struct address Address;
-
-/**
- * Create a new `Address` instance from an IPv4 IP address, the port is
- * optional.
- *
- * The sockaddr_in should be filled in network byte order. The newly created
- * instance must eventually be destroyed by calling {@link addressDestroy}().
- *
- * @param [in] addr_in The `sockaddr_in` representing the IPv4 IP address with
- * which to initialize the new `Address` instance.
- * @return A new instance of `Address` that must eventually be destroyed by
- * calling {@link addressDestroy}().
- *
- * Example:
- * @code
- * {
- * Address *dest = addressCreateFromInet(
- * &(struct sockaddr_in) {
- * .sa_addr =
- * inet_addr("foo.bar.com"), .sa_port = htons(9695) } ); addressDestroy(&dest);
- * }
- * @endcode
- * @see addressDestroy
- */
-Address *addressCreateFromInet(struct sockaddr_in *addr_in);
-
-/**
- * Create a new `Address` instance from an IPv6 IP address, the port is
- * optional.
- *
- *
- * The sockaddr_in should be filled in network byte order. The newly created
- * instance must eventually be destroyed by calling {@link addressDestroy}().
- *
- * @param [in] addr_in6 A `sockaddr_in6` from which to initialize a new instance
- * of Address
- * @return A new instance of `Address` that must eventually be destroyed by
- * calling {@link addressDestroy}()
- *
- * Example:
- * @code
- * {
- * struct sockaddr_in6 addr_in6;
- * memset(&addr_in6, 0, sizeof(struct sockaddr_in6));
- *
- * inet_pton(AF_INET6, "2001:720:1500:1::a100", &(addr_in6.sin6_addr));
- * addr_in6.sin6_family = AF_INET6;
- * addr_in6.sin6_port = 0x0A0B;
- * addr_in6.sin6_flowinfo = 0x01020304;
- *
- * Address *address = addressCreateFromInet6(&addr_in6);
- *
- * addressDestroy(&address);
- * }
- * @endcode
- * @see addressDestroy
- */
-Address *addressCreateFromInet6(struct sockaddr_in6 *addr_in6);
-
-/**
- * Convert an internet address family (IPv4) to the address format used by the
- * Fwd.
- *
- * @param [in] addr4 IPV4 address in *Network byte order*
- * @param [in] port Port number in *Network byte order*
- *
- * @return A new instance of `Address` that must eventually be destroyed by
- * calling {@link addressDestroy}()
- */
-Address *addressFromInaddr4Port(in_addr_t *addr4, in_port_t *port);
-
-/**
- * Convert an internet address family (IPv6) to the address format used by the
- * Fwd
- *
- * @param [in] addr6 IPV4 address in *Network byte order*
- * @param [in] port Port number in *Network byte order*
- *
- * @return A new instance of `Address` that must eventually be destroyed by
- * calling {@link addressDestroy}()
- */
-Address *addressFromInaddr6Port(struct in6_addr *addr6, in_port_t *port);
-
-/**
- * Create a new `Address` instance, initialized from a Link address.
- *
- * User must know the link address format (i.e. token ring vs ethernet) and have
- * the address in a byte array. The array is encoded in left-to-right order. The
- * newly created instance must eventually be destroyed by calling {@link
- * addressDestroy}().
- *
- * @param [in] linkaddr A byte array containing the link address
- * @param [in] length The length of the link address byte array
- * @return A new instance of `Address` that must eventually be destroyed by
- * calling {@link addressDestroy}()
- *
- * Example:
- * @code
- * {
- * uint8_t mac[] = { 0x14, 0x10, 0x9f, 0xd7, 0x0b, 0x89 };
- * Address *address = addressCreateFromLink(mac, sizeof(mac));
- *
- * addressDestroy(&address);
- * }
- * @endcode
- * @see addressDestroy
- */
-Address *addressCreateFromLink(const uint8_t *linkaddr, size_t length);
-
-/**
- * Create a new `Address` instance from a network interface index.
- *
- * The interfaceIndex should be in host byte order. The newly created instance
- * must eventually be destroyed by calling {@link addressDestroy}().
- *
- * @param [in] interfaceIndex The index of the interface to encode
- * @return A new instance of `Address` that must eventually be destroyed by
- * calling {@link addressDestroy}()
- *
- * Example:
- * @code
- * {
- * Address *address = addressCreateFromInterface(2);
- *
- * addressDestroy(&address);
- * }
- * @endcode
- * @see addressDestroy
- */
-Address *addressCreateFromInterface(uint32_t interfaceIndex);
-
-/**
- * Create a new Address instance from a PF_UNIX address domain.
- *
- * The newly created instance must eventually be destroyed by calling {@link
- * addressDestroy}().
- *
- * @param [in] addr_un The `struct sockaddr_un` specifying the local PF_UNIX
- * socket address
- * @return A new instance of `Address` that must eventually be destroyed by
- * calling {@link addressDestroy}()
- *
- * Example:
- * @code
- * {
- * struct sockaddr_un addr_unix;
- * memset(&addr_unix, 0, sizeof(struct sockaddr_un));
- * char path[] = "/Hello/Cruel/World";
- * strcpy(addr_un.sun_path, path);
- * addr_un.sun_family = AF_UNIX;
- *
- * Address *address = addressCreateFromUnix(&addr_un);
- *
- * addressDestroy(&address);
- * }
- * @endcode
- * @see addressDestroy
- */
-Address *addressCreateFromUnix(struct sockaddr_un *addr_un);
-
-/**
- * Create a deep copy of an instance of a `Address`. A completely new,
- * indedependent instance is created.
- *
- * The newly created instance must eventually be destroyed by calling {@link
- * addressDestroy}().
- *
- * @param [in] original A pointer to a `Address` instance to be copied.
- * @return A new instance of a Address, deep copied from the `original`
- * instance.
- *
- * Example:
- * @code
- * {
- * Address *address = addressCreateFromInterface(2);
- *
- * Address *copy = addressCopy(address);
- *
- * addressDestroy(&address);
- * addressDestroy(&copy);
- * }
- * @endcode
- * @see addressDestroy
- */
-Address *addressCopy(const Address *original);
-
-/**
- * Deallocate an instance of a Address.
- *
- * The Address instance is deallocated, and any referenced data is also
- * deallocated. The referenced pointer is set to NULL upon return.
- *
- * @param [in] addressPtr A pointer to a pointer to an instance of Address.
- *
- * Example:
- * @code
- * {
- * Address *address = addressCreateFromInterface(2);
- *
- * addressDestroy(&address);
- * }
- * @endcode
- */
-void addressDestroy(Address **addressPtr);
-
-/**
- * Determine if two Address instances are equal.
- *
- *
- * The following equivalence relations on non-null `Address` instances are
- * maintained:
- *
- * * It is reflexive: for any non-null reference value x, `addressEquals(x, x)`
- * must return true.
- *
- * * It is symmetric: for any non-null reference values x and y,
- * `addressEquals(x, y)` must return true if and only if
- * `addressEquals(y, x)` returns true.
- *
- * * It is transitive: for any non-null reference values x, y, and z, if
- * `addressEquals(x, y)` returns true and
- * `addressEquals(y, z)` returns true,
- * then `addressEquals(x, z)` must return true.
- *
- * * It is consistent: for any non-null reference values x and y, multiple
- * invocations of `addressEquals(x, y)` consistently return true or
- * consistently return false.
- *
- * * For any non-null reference value x, `addressEquals(x, NULL)` must
- * return false.
- *
- * If one address specifies more information than other,
- * e.g. a is INET with a port and b is not, they are not equal.
- *
- * `a` and `b` may be NULL, and NULL == NULL.
- *
- * @param a A pointer to a Address instance
- * @param b A pointer to a Address instance
- * @return true if the two instances are equal
- * @return false if the two instances are not equal
- *
- * Example:
- * @code
- * {
- * Address *address = addressCreateFromInterface(2);
- * Address *copy = addressCopy(address);
- *
- * if (addressEquals(address, copy)) {
- * // true
- * } else {
- * // false
- * }
- *
- * addressDestroy(&address);
- * addressDestroy(&copy);
- * }
- * @endcode
- */
-bool addressEquals(const Address *a, const Address *b);
-
-/**
- * Return the {@link address_type} from a specified Address.
- *
- * @param [in] A pointer to a Address instance
- *
- * @return the {@link address_type} of the specified Address instance
- *
- * Example:
- * @code
- * {
- * Address *address = addressCreateFromInterface(2);
- *
- * address_type type = addressGetType(address);
- *
- * addressDestroy(&address);
- * }
- * @endcode
- *
- * @see address_type
- */
-address_type addressGetType(const Address *address);
-
-/**
- * Fills in the output parameter with an INET address.
- *
- * @param addr_in must be non-NULL
- * @return true if INET address and output filled in, false otherwise.
- *
- */
-bool addressGetInet(const Address *address, struct sockaddr_in *addr_in);
-
-/**
- * Retrieve the INET6 address associated with a `Address` instance.
- *
- * If the specified Address instance is of type {@link commandAddrType_INET6},
- * then populate the supplied `struct sockaddr_in6` from the Address and return
- * true. If the Address is not of type `commandAddrType_INET6`, this function
- * returns false.
- *
- * @param [in] address A pointer to a `Address` instance of type {@link
- * commandAddrType_INET6}.
- * @param [in] addr_in6 A pointer to a `struct sockaddr_in6`. Must be non-NULL.
- * @return true If the Address instance is of type `commandAddrType_INET6` and
- * `addr_in6` was filled in
- * @return false If the Address instance was not of type `commandAddrType_INET6`
- * or `addr_in6` could not be filled in.
- *
- * @see addressGetType
- */
-bool addressGetInet6(const Address *address, struct sockaddr_in6 *addr_in6);
-
-/**
- * Retrieve the interface index associated with a `Address` instance.
- *
- * If the specified `Address` instance is of type {@link commandAddrType_IFACE},
- * then populate the supplied `uint32_t` from the Address and return true. If
- * the `Address` is not of type `commandAddrType_INET6`, this function returns
- * false.
- *
- * @param [in] address A pointer to a `Address` instance of type {@link
- * commandAddrType_IFACE}.
- * @param [in] interfaceIndex A pointer to a `uint32_t` to fill in. Must be
- * non-NULL.
- * @return true If the Address instance is of type `commandAddrType_IFACE` and
- * `interfaceIndex` was filled in.
- * @return false If the Address instance was not of type `commandAddrType_IFACE`
- * or `interfaceIndex` could not be filled in.
- *
- * @see addressGetType
- */
-bool addressGetInterfaceIndex(const Address *address, uint32_t *interfaceIndex);
-
-/**
- * Retrieve the link address associated with a `Address` instance.
- *
- * If the specified `Address` instance is of type {@link commandAddrType_LINK},
- * then return a pointer to the {@link PARCBuffer} containing the link address.
- * If the `Address` is not of type {@link commandAddrType_LINK}, then return
- * NULL. The returned PARCBuffer pointer points to memory managed by the Address
- * instance, and does not need to be destroyed or released on its own.
- *
- * @param [in] address A pointer to a `Address` instance of type {@link
- * commandAddrType_LINK}.
- * @return A pointer to the {@link PARCBuffer} containing the link address.
- *
- * Example:
- * @code
- * {
- * uint8_t mac[] = { 0x14, 0x10, 0x9f, 0xd7, 0x0b, 0x89 };
- * Address *address = addressCreateFromLink(mac, sizeof(mac));
- *
- * PARCBuffer *macBuffer = addressGetLinkAddress(address);
- *
- * addressDestroy(&address);
- * }
- * @endcode
- * @see addressGetType
- */
-PARCBuffer *addressGetLinkAddress(const Address *address);
-
-/**
- * Append the string representation of a `Address` to a specified
- * `PARCBufferComposer`.
- *
- * @param [in] address A pointer to a `Address` instance.
- * @param [in] composer A pointer to a `PARCBufferComposer` instance to which to
- * append the string.
- *
- * @return The `PARCBufferComposer` instance that was passed in.
- *
- * Example:
- * @code
- * {
- * Address *address = addressCreateFromInterface(1);
- * PARCBufferComposer *composer = addressBuildString(address,
- * parcBufferComposer_Create()); parcBufferComposer_Release(&composer);
- * addressDestroy(&address);
- * }
- * @endcode
- *
- * @see PARCBufferComposer
- */
-PARCBufferComposer *addressBuildString(const Address *address,
- PARCBufferComposer *composer);
-
-/**
- * Produce a nil-terminated string representation of the specified instance.
- *
- * The result must be freed by the caller via {@link parcMemory_Deallocate}.
- *
- * @param [in] interest A pointer to the instance.
- *
- * @return NULL Cannot allocate memory.
- * @return non-NULL A pointer to an allocated, nul-terminated C string that must
- * be deallocated via {@link parcMemory_Deallocate}().
- *
- * Example:
- * @code
- * {
- * Address *address = addressCreateFromInterface(1);
- *
- * char *string = addressToString(address);
- *
- * if (string != NULL) {
- * printf("Address looks like: %s\n", string);
- * parcMemory_Deallocate(string);
- * } else {
- * printf("Cannot allocate memory\n");
- * }
- *
- * addressDestroy(&address);
- * }
- * @endcode
- * @see parcMemory_Deallocate
- * @see addressBuildString
- */
-char *addressToString(const Address *address);
-
-/**
- * Return a non-cryptographic hash code consistent with Equals
- *
- * If commandAddrA == commandAddrB, then addressHashCode(commandAddrA) ==
- * addressHashCode(commandAddrB)
- *
- * @param [in] address A pointer to a Address instance.
- * @return A 32-bit hashcode for the specified Address instance.
- *
- * Example:
- * @code
- * Address *address = addressCreateFromInterface(1);
- *
- * uint32_t hashCode = addressHashCode(address);
- *
- * addressDestroy(&address);
- * @endcode
- */
-PARCHashCode addressHashCode(const Address *address);
-#endif // address_h
diff --git a/hicn-light/src/hicn/utils/addressList.c b/hicn-light/src/hicn/utils/addressList.c
deleted file mode 100644
index a64fd6f9e..000000000
--- a/hicn-light/src/hicn/utils/addressList.c
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/hicn-light/config.h>
-#include <stdio.h>
-
-#include <parc/assert/parc_Assert.h>
-
-#include <hicn/utils/addressList.h>
-
-#include <parc/algol/parc_ArrayList.h>
-#include <parc/algol/parc_Buffer.h>
-#include <parc/algol/parc_Memory.h>
-
-struct address_list {
- PARCArrayList *listOfAddress;
-};
-
-static void _addressListFreeAddress(void **addressVoidPtr) {
- Address **addressPtr = (Address **)addressVoidPtr;
- addressDestroy(addressPtr);
-}
-
-AddressList *addressListCreate() {
- AddressList *list = parcMemory_AllocateAndClear(sizeof(AddressList));
- parcAssertNotNull(list, "parcMemory_AllocateAndClear(%zu) returned NULL",
- sizeof(AddressList));
- list->listOfAddress = parcArrayList_Create(_addressListFreeAddress);
- parcAssertNotNull(list->listOfAddress, "Got null from parcArrayList_Create");
-
- return list;
-}
-
-void addressListDestroy(AddressList **addressListPtr) {
- parcAssertNotNull(addressListPtr,
- "Parameter must be non-null double pointer");
- parcAssertNotNull(*addressListPtr,
- "Parameter must dereference to non-null pointer");
- AddressList *list = *addressListPtr;
-
- parcArrayList_Destroy(&list->listOfAddress);
- parcMemory_Deallocate((void **)&list);
- *addressListPtr = NULL;
-}
-
-AddressList *addressListAppend(AddressList *list, Address *address) {
- parcAssertNotNull(list, "Parameter list must be non-null");
- parcAssertNotNull(address, "Parameter address must be non-null");
-
- parcArrayList_Add(list->listOfAddress, (PARCObject *)address);
- return list;
-}
-
-AddressList *addressListCopy(const AddressList *original) {
- parcAssertNotNull(original, "Parameter must be non-null");
-
- AddressList *copy = addressListCreate();
- for (int i = 0; i < parcArrayList_Size(original->listOfAddress); i++) {
- Address *address = (Address *)parcArrayList_Get(original->listOfAddress, i);
- parcArrayList_Add(copy->listOfAddress, (PARCObject *)addressCopy(address));
- }
-
- return copy;
-}
-
-bool addressListEquals(const AddressList *a, const AddressList *b) {
- parcAssertNotNull(a, "Parameter a must be non-null");
- parcAssertNotNull(b, "Parameter b must be non-null");
-
- if (a == b) {
- return true;
- }
-
- if (parcArrayList_Size(a->listOfAddress) !=
- parcArrayList_Size(b->listOfAddress)) {
- return false;
- }
-
- for (size_t i = 0; i < parcArrayList_Size(a->listOfAddress); i++) {
- const Address *addr_a = (Address *)parcArrayList_Get(a->listOfAddress, i);
- const Address *addr_b = (Address *)parcArrayList_Get(b->listOfAddress, i);
- if (!addressEquals(addr_a, addr_b)) {
- return false;
- }
- }
- return true;
-}
-
-size_t addressListLength(const AddressList *list) {
- parcAssertNotNull(list, "Parameter must be non-null");
- return parcArrayList_Size(list->listOfAddress);
-}
-
-const Address *addressListGetItem(const AddressList *list, size_t item) {
- parcAssertNotNull(list, "Parameter must be non-null");
- parcAssertTrue(item < addressListLength(list),
- "Asked for item %zu beyond end of list %zu", item,
- addressListLength(list));
-
- return (Address *)parcArrayList_Get(list->listOfAddress, item);
-}
-
-char *addressListToString(const AddressList *list) {
- PARCBufferComposer *composer = parcBufferComposer_Create();
-
- for (size_t i = 0; i < addressListLength(list); i++) {
- char *addressString = addressToString(addressListGetItem(list, i));
- parcBufferComposer_PutString(composer, addressString);
- if (i < (addressListLength(list) - 1)) {
- parcBufferComposer_PutString(composer, " ");
- }
- parcMemory_Deallocate((void **)&addressString);
- }
-
- PARCBuffer *buffer = parcBufferComposer_ProduceBuffer(composer);
- char *result = parcBuffer_ToString(buffer);
- parcBuffer_Release(&buffer);
- parcBufferComposer_Release(&composer);
-
- return result;
-}
diff --git a/hicn-light/src/hicn/utils/addressList.h b/hicn-light/src/hicn/utils/addressList.h
deleted file mode 100644
index 823b0c8cb..000000000
--- a/hicn-light/src/hicn/utils/addressList.h
+++ /dev/null
@@ -1,196 +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.
- */
-
-/**
- * @brief A list of Address instances.
- *
- * An AddressList is a list of addresses.
- * It wraps a PARCLinkedList for type saftey with Address.
- *
- */
-#ifndef address_list_h
-#define address_list_h
-
-#include <hicn/utils/address.h>
-
-struct address_list;
-/**
- * @typedef AddressList
- * @abstract A list of Address instance pointers.
- */
-typedef struct address_list AddressList;
-
-/**
- * Create an instance of {@link AddressList}
- *
- * @return NULL An error occurred
- * @return non-NULL A pointer to a valid AddressList instance.
- *
- * Example:
- * @code
- * {
- * AddressList *list = addressListCreate();
- *
- * }
- * @endcode
- *
- * @see addressListDestroy
- */
-AddressList *addressListCreate(void);
-
-/**
- * Dellocate and destroy a AddressList instance.
- *
- * @param [in] addressListPtr A pointer to a pointer to a valid {@link
- * AddressList}.
- *
- *
- * Example:
- * @code
- * {
- * AddressList *list = addressListCreate(void);
- * addressListDestroy(&list);
- * }
- * @endcode
- *
- * @see addressListCreate
- */
-void addressListDestroy(AddressList **addressListPtr);
-
-/**
- * Appends the address, taking ownership of the memory
- *
- * @param list A pointer to a AddressList.
- * @param address must be non-null
- * @return The input list
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-AddressList *addressListAppend(AddressList *list, Address *address);
-
-/**
- * Creates a reference counted copy
- *
- * @param list A pointer to a valid {@link AddressList}.
- *
- * @return An allocated list, you must destroy it.
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-AddressList *addressListCopy(const AddressList *list);
-
-/**
- * Determine if two AddressList instances are equal.
- *
- * Two AddressList instances are equal if, and only if, they have the same
- * length, with the same elements in the same order.
- *
- *
- * The following equivalence relations on non-null `AddressList` instances are
- * maintained:
- *
- * * It is reflexive: for any non-null reference value x,
- * `AddressList_Equals(x, x)` must return true.
- *
- * * It is symmetric: for any non-null reference values x and y,
- * `AddressList_Equals(x, y)` must return true if and only if
- * `addressListEquals(y, x)` returns true.
- *
- * * It is transitive: for any non-null reference values x, y, and z, if
- * `addressListEquals(x, y)` returns true and
- * `addressListEquals(y, z)` returns true,
- * then `addressListEquals(x, z)` must return true.
- *
- * * It is consistent: for any non-null reference values x and y, multiple
- * invocations of `addressListEquals(x, y)` consistently return true or
- * consistently return false.
- *
- * * For any non-null reference value x, `addressListEquals(x, NULL)` must
- * return false.
- *
- * @param a A pointer to a `AddressList` instance.
- * @param b A pointer to a `AddressList` instance.
- * @return true if the two `AddressList` instances are equal.
- *
- * Example:
- * @code
- * {
- * AddressList *a = addressListCreate();
- * AddressList *b = addressListCreate();
- *
- * if (addressListEquals(a, b)) {
- * // true
- * } else {
- * // false
- * }
- * }
- * @endcode
- */
-bool addressListEquals(const AddressList *a, const AddressList *b);
-
-/**
- * Get the number of items in the list
- *
- * @param list A pointer to a {@link AddressList}.
- * @return The number of items in the list.
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-size_t addressListLength(const AddressList *list);
-
-/**
- * Returns a const reference to an item.
- * Use addressCopy if needed.
- *
- * Do not free or modify the returned value.
- * Use addressCopy if you need a mutable instance.
- *
- * @param list A pointer to a AddressList.
- * @param item A value less than the number of items in the given {@link
- * AddressList}.
- * @return Asserts if item off end of list.
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-const Address *addressListGetItem(const AddressList *list, size_t item);
-
-/**
- * Get a nul-terminated, C-string representation of the given {@link
- * AddressList}.
- *
- * @param list A pointer to a valid {@link AddressList} instance.
- *
- * @return An allocate string representation of the {@link AddressList} that
- * must be freed via `parcMemory_Deallocate()`.
- *
- * Example:
- * @code
- * <#example#>
- * @endcode
- */
-char *addressListToString(const AddressList *list);
-#endif // address_list_h
diff --git a/hicn-light/src/hicn/utils/commands.h b/hicn-light/src/hicn/utils/commands.h
deleted file mode 100644
index 3758f0f41..000000000
--- a/hicn-light/src/hicn/utils/commands.h
+++ /dev/null
@@ -1,434 +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.
- */
-
-/*
- * @file commands.h
- * @brief All hicn-light commands: 14 in total.
- *
- * Header and payload in binary format.
- */
-
-#ifndef commands_h
-#define commands_h
-
-#ifndef _WIN32
-#include <netinet/in.h>
-#include <sys/socket.h>
-#endif
-
-#include <stdint.h>
-#include <stdlib.h>
-
-#include <hicn/util/ip_address.h>
-#ifdef WITH_POLICY
-#include <hicn/policy.h>
-#endif /* WITH_POLICY */
-
-#define SYMBOLIC_NAME_LEN 16
-#define MAX_FWD_STRATEGY_RELATED_PREFIXES 10
-
-typedef struct in6_addr ipv6_addr_t;
-typedef uint32_t ipv4_addr_t;
-
-typedef enum {
- REQUEST_LIGHT = 0xc0, // this is a command
- RESPONSE_LIGHT,
- ACK_LIGHT,
- NACK_LIGHT,
- LAST_MSG_TYPE_VALUE
-} message_type;
-
-typedef enum {
- ADD_LISTENER = 0,
- ADD_CONNECTION,
- LIST_CONNECTIONS,
- ADD_ROUTE,
- LIST_ROUTES,
- REMOVE_CONNECTION,
- REMOVE_LISTENER,
- REMOVE_ROUTE,
- CACHE_STORE,
- CACHE_SERVE,
- CACHE_CLEAR,
- SET_STRATEGY,
- SET_WLDR,
- ADD_PUNTING,
- LIST_LISTENERS,
- MAPME_ENABLE,
- MAPME_DISCOVERY,
- MAPME_TIMESCALE,
- MAPME_RETX,
- MAPME_SEND_UPDATE,
- CONNECTION_SET_ADMIN_STATE,
-#ifdef WITH_POLICY
- ADD_POLICY,
- LIST_POLICIES,
- REMOVE_POLICY,
- UPDATE_CONNECTION,
- CONNECTION_SET_PRIORITY,
- CONNECTION_SET_TAGS,
-#endif /* WITH_POLICY */
- LAST_COMMAND_VALUE
-} command_id;
-
-typedef enum {
- ADDR_INET = 1,
- ADDR_INET6,
- ADDR_LINK,
- ADDR_IFACE,
- ADDR_UNIX /* PF_UNIX */
-} address_type;
-
-typedef enum {
- UDP_CONN,
- TCP_CONN,
- GRE_CONN, // not implemented
- HICN_CONN
-} connection_type;
-
-typedef enum { ACTIVATE_ON, ACTIVATE_OFF } activate_type;
-
-//========== HEADER ==========
-
-typedef struct {
- uint8_t messageType;
- uint8_t commandID;
- uint16_t length; // tells the number of structures in the payload
- uint32_t seqNum;
-} header_control_message;
-// for the moment has to be at least 8 bytes
-
-// SIZE=8
-
-//========== [00] ADD LISTENER ==========
-
-typedef enum { ETHER_MODE, IP_MODE, HICN_MODE } listener_mode;
-
-typedef struct {
- char symbolic[SYMBOLIC_NAME_LEN];
- char interfaceName[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint16_t port;
- // uint16_t etherType;
- uint8_t addressType;
- uint8_t listenerMode;
- uint8_t connectionType;
-} add_listener_command;
-
-// SIZE=56
-
-//========== [01] ADD CONNECTION ==========
-
-typedef struct {
- char symbolic[SYMBOLIC_NAME_LEN];
- //char interfaceName[SYMBOLIC_NAME_LEN];
- ip_address_t remoteIp;
- ip_address_t localIp;
- uint16_t remotePort;
- uint16_t localPort;
- uint8_t ipType;
- uint8_t connectionType;
- uint8_t admin_state;
-#ifdef WITH_POLICY
- uint32_t priority;
- policy_tags_t tags;
-#endif /* WITH_POLICY */
-} add_connection_command;
-
-// SIZE=56
-
-//========== [02] LIST CONNECTIONS ==========
-
-typedef enum {
- CONN_GRE,
- CONN_TCP,
- CONN_UDP,
- CONN_MULTICAST,
- CONN_L2,
- CONN_HICN
-} list_connections_type;
-
-typedef enum {
- IFACE_UP = 0,
- IFACE_DOWN = 1,
- IFACE_UNKNOWN = 2 // not used actually
-} connection_state;
-
-typedef struct {
- add_connection_command connectionData;
- uint32_t connid;
- uint8_t state;
- char interfaceName[SYMBOLIC_NAME_LEN];
- char connectionName[SYMBOLIC_NAME_LEN];
-} list_connections_command;
-
-// SIZE=80
-
-//========== [03] ADD ROUTE ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint16_t cost;
- uint8_t addressType;
- uint8_t len;
-} add_route_command;
-
-// SIZE=36
-
-//========== [04] LIST ROUTE ==========
-
-typedef struct {
- ip_address_t address;
- uint32_t connid;
- uint16_t cost;
- uint8_t addressType;
- uint8_t len;
-} list_routes_command;
-
-// SIZE=24
-
-//========== [05] REMOVE CONNECTION ==========
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
-} remove_connection_command;
-
-//========== [06] REMOVE LISTENER ==========
-typedef struct {
- char symbolicOrListenerid[SYMBOLIC_NAME_LEN];
-} remove_listener_command;
-
-// SIZE=16
-
-//========== [07] REMOVE ROUTE ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} remove_route_command;
-
-// SIZE=36
-
-//========== [08] CACHE STORE ==========
-
-typedef struct {
- uint8_t activate;
-} cache_store_command;
-
-// SIZE=1
-
-//========== [09] CACHE SERVE ==========
-
-typedef struct {
- uint8_t activate;
-} cache_serve_command;
-
-// SIZE=1
-
-//========== [10] SET STRATEGY ==========
-
-typedef enum {
- SET_STRATEGY_LOADBALANCER,
- SET_STRATEGY_RANDOM,
- SET_STRATEGY_LOW_LATENCY,
- LAST_STRATEGY_VALUE
-} strategy_type;
-
-typedef struct {
- ip_address_t address;
- uint8_t strategyType;
- uint8_t addressType;
- uint8_t len;
- uint8_t related_prefixes;
- ip_address_t addresses[MAX_FWD_STRATEGY_RELATED_PREFIXES];
- uint8_t lens[MAX_FWD_STRATEGY_RELATED_PREFIXES];
- uint8_t addresses_type[MAX_FWD_STRATEGY_RELATED_PREFIXES];
-} set_strategy_command;
-
-// SIZE=208
-
-//========== [11] SET WLDR ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint8_t activate;
-} set_wldr_command;
-
-// SIZE=17
-
-//========== [12] ADD PUNTING ==========
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} add_punting_command;
-
-// SIZE=36
-
-//========== [13] LIST LISTENER ==========
-
-typedef struct {
- ip_address_t address;
- char listenerName[SYMBOLIC_NAME_LEN];
- char interfaceName[SYMBOLIC_NAME_LEN];
- uint32_t connid;
- uint16_t port;
- uint8_t addressType;
- uint8_t encapType;
-} list_listeners_command;
-
-// SIZE=56
-
-//========== [14] MAPME ==========
-
-// (enable/discovery/timescale/retx)
-
-typedef struct {
- uint8_t activate;
-} mapme_activator_command;
-
-// SIZE=1
-
-typedef struct {
- uint32_t timePeriod;
-} mapme_timing_command;
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} mapme_send_update_command;
-
-// SIZE=1
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint8_t admin_state;
- uint8_t pad8[3];
-} connection_set_admin_state_command;
-
-#ifdef WITH_POLICY
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
- hicn_policy_t policy;
-} add_policy_command;
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
- hicn_policy_t policy;
-} list_policies_command;
-
-typedef struct {
- ip_address_t address;
- uint8_t addressType;
- uint8_t len;
-} remove_policy_command;
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint8_t admin_state;
- uint32_t priority;
- policy_tags_t tags;
-} update_connection_command;
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- uint32_t priority;
-} connection_set_priority_command;
-
-typedef struct {
- char symbolicOrConnid[SYMBOLIC_NAME_LEN];
- policy_tags_t tags;
-} connection_set_tags_command;
-
-#endif /* WITH_POLICY */
-
-//===== size of commands ======
-// REMINDER: when a new_command is added, the following switch has to be
-// updated.
-static inline int payloadLengthDaemon(command_id id) {
- switch (id) {
- case ADD_LISTENER:
- return sizeof(add_listener_command);
- case ADD_CONNECTION:
- return sizeof(add_connection_command);
- case LIST_CONNECTIONS:
- return 0; // list connections: payload always 0
- case ADD_ROUTE:
- return sizeof(add_route_command);
- case LIST_ROUTES:
- return 0; // list routes: payload always 0
- case REMOVE_CONNECTION:
- return sizeof(remove_connection_command);
- case REMOVE_LISTENER:
- return sizeof(remove_listener_command);
- case REMOVE_ROUTE:
- return sizeof(remove_route_command);
- case CACHE_STORE:
- return sizeof(cache_store_command);
- case CACHE_SERVE:
- return sizeof(cache_serve_command);
- case CACHE_CLEAR:
- return 0; // cache clear
- case SET_STRATEGY:
- return sizeof(set_strategy_command);
- case SET_WLDR:
- return sizeof(set_wldr_command);
- case ADD_PUNTING:
- return sizeof(add_punting_command);
- case LIST_LISTENERS:
- return 0; // list listeners: payload always 0
- case MAPME_ENABLE:
- return sizeof(mapme_activator_command);
- case MAPME_DISCOVERY:
- return sizeof(mapme_activator_command);
- case MAPME_TIMESCALE:
- return sizeof(mapme_timing_command);
- case MAPME_RETX:
- return sizeof(mapme_timing_command);
- case MAPME_SEND_UPDATE:
- return sizeof(mapme_send_update_command);
- case CONNECTION_SET_ADMIN_STATE:
- return sizeof(connection_set_admin_state_command);
-#ifdef WITH_POLICY
- case ADD_POLICY:
- return sizeof(add_policy_command);
- case LIST_POLICIES:
- return 0; // list policies: payload always 0
- case REMOVE_POLICY:
- return sizeof(remove_policy_command);
- case UPDATE_CONNECTION:
- return sizeof(update_connection_command);
- case CONNECTION_SET_PRIORITY:
- return sizeof(connection_set_priority_command);
- case CONNECTION_SET_TAGS:
- return sizeof(connection_set_tags_command);
-#endif /* WITH_POLICY */
- case LAST_COMMAND_VALUE:
- return 0;
- default:
- return 0;
- }
-}
-#endif
diff --git a/hicn-light/src/hicn/utils/interface.c b/hicn-light/src/hicn/utils/interface.c
index d8597f3ed..c3f8793a4 100644
--- a/hicn-light/src/hicn/utils/interface.c
+++ b/hicn-light/src/hicn/utils/interface.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,12 +22,14 @@
#include <parc/algol/parc_BufferComposer.h>
#include <parc/algol/parc_Memory.h>
#include <parc/algol/parc_Object.h>
-#include <hicn/utils/addressList.h>
+//#include <hicn/utils/addressList.h>
#include <hicn/utils/interface.h>
#include <parc/assert/parc_Assert.h>
#include <hicn/utils/commands.h>
+#if 0
+
struct interface {
char *name;
unsigned interfaceIndex;
@@ -166,3 +168,5 @@ unsigned interfaceGetMTU(const Interface *iface) {
parcAssertNotNull(iface, "Parameter iface must be non-null");
return iface->mtu;
}
+
+#endif
diff --git a/hicn-light/src/hicn/utils/interface.h b/hicn-light/src/hicn/utils/interface.h
index fd91edb1d..365624e4a 100644
--- a/hicn-light/src/hicn/utils/interface.h
+++ b/hicn-light/src/hicn/utils/interface.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,8 +22,7 @@
#ifndef interface_h
#define interface_h
-#include <hicn/utils/address.h>
-#include <hicn/utils/addressList.h>
+#include <hicn/core/address.h>
struct interface;
typedef struct interface Interface;
@@ -59,7 +58,7 @@ void interfaceDestroy(Interface **interfacePtr);
* <#example#>
* @endcode
*/
-void interfaceAddAddress(Interface *iface, Address *address);
+void interfaceAddAddress(Interface *iface, address_t *address);
/**
* Retrieves a list of interface addresses
@@ -74,7 +73,7 @@ void interfaceAddAddress(Interface *iface, Address *address);
* <#example#>
* @endcode
*/
-const AddressList *interfaceGetAddresses(const Interface *iface);
+const address_t **interfaceGetAddresses(const Interface *iface);
/**
* The interface index
diff --git a/hicn-light/src/hicn/utils/interfaceSet.c b/hicn-light/src/hicn/utils/interfaceSet.c
index 3ae52bb80..e06643fc7 100644
--- a/hicn-light/src/hicn/utils/interfaceSet.c
+++ b/hicn-light/src/hicn/utils/interfaceSet.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-light/src/hicn/utils/interfaceSet.h b/hicn-light/src/hicn/utils/interfaceSet.h
index e43f985fe..6723bc493 100644
--- a/hicn-light/src/hicn/utils/interfaceSet.h
+++ b/hicn-light/src/hicn/utils/interfaceSet.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-light/src/hicn/utils/punting.c b/hicn-light/src/hicn/utils/punting.c
index 8f33cf763..60a8d2355 100644
--- a/hicn-light/src/hicn/utils/punting.c
+++ b/hicn-light/src/hicn/utils/punting.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,6 +13,7 @@
* limitations under the License.
*/
+#if 0
#include <hicn/hicn-light/config.h>
#include <stdio.h>
@@ -23,11 +24,11 @@
struct punting {
char *symbolic;
- Address *prefix;
+ address_t *prefix;
uint32_t len;
};
-Punting *puntingCreate(const char *listenerName, Address *prefix,
+Punting *puntingCreate(const char *listenerName, address_t *prefix,
uint32_t len) {
parcAssertNotNull(listenerName, "Parameter listenerName must be non-null");
parcAssertNotNull(prefix, "Parameter prefix must be non-null");
@@ -87,7 +88,7 @@ const char *puntingGetSymbolicName(const Punting *punting) {
return punting->symbolic;
}
-Address *puntingGetAddress(const Punting *punting) {
+address_t * puntingGetAddress(const Punting *punting) {
parcAssertNotNull(punting, "Parameter listener must be non-null");
return punting->prefix;
}
@@ -96,3 +97,4 @@ uint32_t puntingPrefixLen(const Punting *punting) {
parcAssertNotNull(punting, "Parameter listener must be non-null");
return punting->len;
}
+#endif
diff --git a/hicn-light/src/hicn/utils/punting.h b/hicn-light/src/hicn/utils/punting.h
index 9be1baed4..46cec8a91 100644
--- a/hicn-light/src/hicn/utils/punting.h
+++ b/hicn-light/src/hicn/utils/punting.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,10 +16,21 @@
#ifndef punting_h
#define punting_h
+#include <hicn/core/address.h>
+
+typedef struct {
+ char *symbolic;
+ address_t prefix;
+ uint32_t len;
+} punting_t;
+
+#define punting_address(punting) (&((punting)->prefix))
+#define punting_len(punting) ((punting)->len)
+
+#if 0
struct punting;
typedef struct punting Punting;
-#include <hicn/utils/address.h>
/**
* Creates a Punting object
@@ -36,7 +47,7 @@ typedef struct punting Punting;
* @return null An error
*
*/
-Punting *puntingCreate(const char *symbolic, Address *prefix, uint32_t len);
+Punting *puntingCreate(const char *symbolic, address_t *prefix, uint32_t len);
/**
* Releases a reference count to the object
@@ -66,7 +77,9 @@ const char *puntingGetSymbolicName(const Punting *punting);
* Returns the address (INET or INET6 ip address)
*
*/
-Address *puntingGetAddress(const Punting *punting);
+address_t * puntingGetAddress(const Punting *punting);
uint32_t puntingPrefixLen(const Punting *punting);
+#endif
+
#endif // punting_h
diff --git a/hicn-light/src/hicn/utils/token.h b/hicn-light/src/hicn/utils/token.h
index 43e0a77b2..138916f31 100644
--- a/hicn-light/src/hicn/utils/token.h
+++ b/hicn-light/src/hicn/utils/token.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,7 +19,7 @@
* Concatenate preprocessor tokens A and B without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
-#define PPCAT_NX(A, B) A ## B
+#define PPCAT_NX(A, B) A##B
/*
* Concatenate preprocessor tokens A and B after macro-expanding them.
diff --git a/hicn-light/src/hicn/utils/utils.c b/hicn-light/src/hicn/utils/utils.c
deleted file mode 100644
index 36596f943..000000000
--- a/hicn-light/src/hicn/utils/utils.c
+++ /dev/null
@@ -1,235 +0,0 @@
-// Utility function for commands
-
-#ifndef _WIN32
-#include <netinet/in.h>
-#endif
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <parc/algol/parc_Memory.h>
-#include <parc/algol/parc_Network.h>
-#include <parc/assert/parc_Assert.h>
-#include <pthread.h>
-#include <hicn/utils/utils.h>
-
-// This is the unique sequence number used by all messages and its thread locks
-static pthread_mutex_t nextSequenceNumberMutex = PTHREAD_MUTEX_INITIALIZER;
-static uint32_t nextSequenceNumber = 1;
-
-uint32_t utils_GetNextSequenceNumber(void) {
- uint32_t seqnum;
-
- int result = pthread_mutex_lock(&nextSequenceNumberMutex);
- parcAssertTrue(result == 0, "Got error from pthread_mutex_lock: %d", result);
-
- seqnum = nextSequenceNumber++;
-
- result = pthread_mutex_unlock(&nextSequenceNumberMutex);
- parcAssertTrue(result == 0, "Got error from pthread_mutex_unlock: %d",
- result);
-
- return seqnum;
-}
-
-/**
- * Return true if string is purely an integer
- */
-bool utils_IsNumber(const char *string) {
- size_t len = strlen(string);
- for (size_t i = 0; i < len; i++) {
- if (!isdigit(string[i])) {
- return false;
- }
- }
- return true;
-}
-
-/**
- * A symbolic name must be at least 1 character and must begin with an alpha.
- * The remainder must be an alphanum.
- */
-bool utils_ValidateSymbolicName(const char *symbolic) {
- bool success = false;
- size_t len = strlen(symbolic);
- if (len > 0) {
- if (isalpha(symbolic[0])) {
- success = true;
- for (size_t i = 1; i < len; i++) {
- if (!isalnum(symbolic[i])) {
- success = false;
- break;
- }
- }
- }
- }
- return success;
-}
-
-struct iovec *utils_CreateAck(header_control_message *header, void *payload,
- size_t payloadLen) {
- struct iovec *response =
- parcMemory_AllocateAndClear(sizeof(struct iovec) * 2);
-
- header->messageType = ACK_LIGHT;
-
- response[0].iov_base = header;
- response[0].iov_len = sizeof(header_control_message);
- response[1].iov_base = payload;
- response[1].iov_len = payloadLen;
-
- return response;
-}
-
-struct iovec *utils_CreateNack(header_control_message *header, void *payload,
- size_t payloadLen) {
- struct iovec *response =
- parcMemory_AllocateAndClear(sizeof(struct iovec) * 2);
-
- header->messageType = NACK_LIGHT;
- response[0].iov_base = header;
- response[0].iov_len = sizeof(header_control_message);
- response[1].iov_base = payload;
- response[1].iov_len = payloadLen;
-
- return response;
-}
-
-char *utils_BuildStringFromInet(in_addr_t *addr4, in_port_t *port) {
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = *port;
- addr.sin_addr.s_addr = *addr4;
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(
- parcNetwork_SockInet4Address_BuildString(&addr, composer));
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
- parcBufferComposer_Release(&composer);
- return result;
-}
-
-char *utils_BuildStringFromInet6(struct in6_addr *addr6, in_port_t *port) {
- struct sockaddr_in6 addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin6_family = AF_INET6;
- addr.sin6_port = *port;
- addr.sin6_addr = *addr6;
-
- PARCBufferComposer *composer = parcBufferComposer_Create();
- PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(
- parcNetwork_SockInet6Address_BuildString(&addr, composer));
- char *result = parcBuffer_ToString(tempBuffer);
- parcBuffer_Release(&tempBuffer);
- parcBufferComposer_Release(&composer);
- return result;
-}
-
-char *utils_CommandAddressToString(address_type addressType,
- ip_address_t *address,
- in_port_t *port) {
- char *result;
-
- switch (addressType) {
- case ADDR_INET: {
- result = utils_BuildStringFromInet(&address->v4.as_u32, port);
- break;
- }
-
- case ADDR_INET6: {
- result = utils_BuildStringFromInet6(&address->v6.as_in6addr, port);
- break;
- }
-
- default: {
- char *addrStr = (char *)parcMemory_Allocate(sizeof(char) * 32);
- sprintf(addrStr, "Error: UNKNOWN address type = %d", addressType);
- result = addrStr;
- break;
- }
- }
- return result;
-}
-
-struct iovec *utils_SendRequest(ControlState *state, command_id command,
- void *payload, size_t payloadLen) {
- bool success = false;
-
- // get sequence number for the header
- uint32_t currentSeqNum = utils_GetNextSequenceNumber();
-
- // Allocate and fill the header
- header_control_message *headerControlMessage =
- parcMemory_AllocateAndClear(sizeof(header_control_message));
- headerControlMessage->messageType = REQUEST_LIGHT;
- headerControlMessage->commandID = command;
- headerControlMessage->seqNum = currentSeqNum;
- if (payloadLen > 0) {
- headerControlMessage->length = 1;
- }
-
- struct iovec msg[2];
- msg[0].iov_base = headerControlMessage;
- msg[0].iov_len = sizeof(header_control_message);
- msg[1].iov_base = payload;
- msg[1].iov_len = payloadLen;
-
- struct iovec *response = controlState_WriteRead(state, msg);
-
- header_control_message *receivedHeader =
- (header_control_message *)response[0].iov_base;
- if (receivedHeader->seqNum != currentSeqNum) {
- printf("Seq number is NOT correct: expected %d got %d \n", currentSeqNum,
- receivedHeader->seqNum);
- // failure
- } else {
- if (receivedHeader->messageType == RESPONSE_LIGHT) {
- return response; // command needs both payload and header
- } else {
- if (receivedHeader->messageType == ACK_LIGHT) {
- success = true;
- } else if (receivedHeader->messageType == NACK_LIGHT) {
- success = true;
- } else {
- printf("Error: unrecognized message type"); // failure
- }
- }
- }
-
- // deallocate when payload & header of the response are not needed
- if (receivedHeader->length > 0) {
- parcMemory_Deallocate(&response[1].iov_base); // free received payload
- }
- parcMemory_Deallocate(&response[0].iov_base); // free receivedHeader
-
- // return response
- if (success) {
- return response;
- } else {
- parcMemory_Deallocate(&response); // free iovec pointer
- return NULL; // will generate a failure
- }
-}
-
-const char *utils_PrefixLenToString(address_type addressType,
- ip_address_t *address,
- uint8_t *prefixLen) {
- char len[4]; // max size + 1
- sprintf(len, "%u", (unsigned)*prefixLen);
- in_port_t port = htons(1234); // this is a random port number that is ignored
-
- char *prefix = utils_CommandAddressToString(addressType, address, &port);
- char *prefixStr = malloc(strlen(prefix) + strlen(len) + 2);
- strcpy(prefixStr, prefix);
- strcat(prefixStr, "/");
- strcat(prefixStr, len);
-
- free(prefix);
-
- return prefixStr;
-}
diff --git a/hicn-light/src/hicn/utils/utils.h b/hicn-light/src/hicn/utils/utils.h
deleted file mode 100644
index 1fe88e62c..000000000
--- a/hicn-light/src/hicn/utils/utils.h
+++ /dev/null
@@ -1,70 +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.
- */
-
-#ifndef utils_h
-#define utils_h
-
-#include <hicn/config/controlState.h>
-#include <hicn/utils/address.h>
-#include <hicn/utils/commands.h>
-
-/**
- * Return true if string is purely an integer
- */
-bool utils_IsNumber(const char *string);
-
-/**
- * A symbolic name must be at least 1 character and must begin with an alpha.
- * The remainder must be an alphanum.
- */
-bool utils_ValidateSymbolicName(const char *symbolic);
-
-/**
- *Create an Ack message instance as a response of a control successfully
- *completed.
- */
-struct iovec *utils_CreateAck(header_control_message *header, void *payload,
- size_t payloadLen);
-
-/**
- *Create a Nack message instance as a response of a control unsuccessfully
- *completed.
- */
-struct iovec *utils_CreateNack(header_control_message *header, void *payload,
- size_t payloadLen);
-
-/**
- *Convert IPv4/IPv6 address from binary to text string. `uint8_t *ipAddress` has
- *to be a `in_addr_t * or `a struct in6_addr *.
- */
-char *utils_CommandAddressToString(address_type addressType,
- ip_address_t *address, in_port_t *port);
-
-/**
- *Given a command payload, it generates the header and send the request to the
- *deamon.
- */
-struct iovec *utils_SendRequest(ControlState *state, command_id command,
- void *payload, size_t payloadLen);
-
-/**
- *Convert a IPv4/IPv6 address plus Netmask len from binary to text string in the
- *form [add]:[port]/[len].
- */
-const char *utils_PrefixLenToString(address_type addressType,
- ip_address_t *address,
- uint8_t *prefixLen);
-
-#endif
diff --git a/hicn-plugin/.clang-format b/hicn-plugin/.clang-format
index 351a70e20..781418470 100644
--- a/hicn-plugin/.clang-format
+++ b/hicn-plugin/.clang-format
@@ -18,3 +18,4 @@ ForEachMacros:
- 'vec_foreach_index'
- 'vec_foreach_index_backwards'
- 'vlib_foreach_rx_tx'
+ - 'interest_manifest_foreach_suffix'
diff --git a/hicn-plugin/CMakeLists.txt b/hicn-plugin/CMakeLists.txt
index 9f5553857..2b2600743 100644
--- a/hicn-plugin/CMakeLists.txt
+++ b/hicn-plugin/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2023 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,32 +11,51 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Project and cmake version
+##############################################################
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-
project(hicn-plugin)
-include(GNUInstallDirs)
+##############################################################
+# Cmake modules
+##############################################################
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
- "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules/"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/"
+ ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules/
)
-include(BuildMacros)
-
-set (CMAKE_CXX_STANDARD 11)
-set (CMAKE_C_STANDARD 11)
-# Check for memfd_create syscall
-include(CheckSymbolExists)
-CHECK_SYMBOL_EXISTS ( "__NR_memfd_create" "sys/syscall.h" HAVE_MEMFD_CREATE )
-if ( HAVE_MEMFD_CREATE )
- add_definitions ( -DHAVE_MEMFD_CREATE )
+if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ include(CommonSetup)
endif()
+
+##############################################################
+# Libs and Bins names
+##############################################################
set(HICN_PLUGIN hicn-plugin CACHE INTERNAL "" FORCE)
+set(HICNPLUGIN hicn_plugin CACHE INTERNAL "" FORCE)
+set(HICN_API_TEST_PLUGIN hicn_api_test_plugin CACHE INTERNAL "" FORCE)
+set(HICNPLUGIN_SHARED ${HICNPLUGIN}.shared CACHE INTERNAL "" FORCE)
+set(HICN_API_TEST_PLUGIN_SHARED ${HICN_API_TEST_PLUGIN}.shared CACHE INTERNAL "" FORCE)
-include (Packaging)
-add_subdirectory(src)
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake)
-add_subdirectory(vapi)
+
+##############################################################
+# C Standard
+##############################################################
+set (CMAKE_C_STANDARD 11)
+
+
+##############################################################
+# Subdirectories
+##############################################################
+add_subdirectory(includes/vpp_plugins/hicn)
+add_subdirectory(src)
+add_subdirectory(libvapi-safe)
diff --git a/hicn-plugin/cmake/Modules/Packaging.cmake b/hicn-plugin/cmake/Modules/Packaging.cmake
deleted file mode 100644
index c0176e78f..000000000
--- a/hicn-plugin/cmake/Modules/Packaging.cmake
+++ /dev/null
@@ -1,56 +0,0 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-######################
-# Packages section
-######################
-
-set(${HICN_PLUGIN}_DESCRIPTION
- "A high-performance Hybrid ICN forwarder as a plugin to VPP."
- CACHE STRING "Description for deb/rpm package."
-)
-
-set(${HICN_PLUGIN}_DEB_DEPENDENCIES
- "vpp (>= stable_version-release), vpp (<< next_version-release), vpp-plugin-core (>= stable_version-release), vpp-plugin-core (<< next_version-release)"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${HICN_PLUGIN}-dev_DEB_DEPENDENCIES
- "vpp-dev (>= stable_version-release), vpp-dev (<< next_version-release), libvppinfra-dev (>= stable_version-release), libvppinfra-dev (<< next_version-release)"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${HICN_PLUGIN}_RPM_DEPENDENCIES
- "vpp >= stable_version-release, vpp < next_version-release, vpp-plugins >= stable_version-release, vpp-plugins < next_version-release"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${HICN_PLUGIN}-dev_RPM_DEPENDENCIES
- "vpp-devel >= stable_version-release, vpp-devel < next_version-release"
- CACHE STRING "Dependencies for deb/rpm package."
-)
-
-set(${HICN_PLUGIN}_DEB_PACKAGE_CONTROL_EXTRA
- "${CMAKE_CURRENT_SOURCE_DIR}/scripts/postinst"
- CACHE STRING "Control scripts conffiles, postinst, postrm, prerm."
-)
-
-set(${HICN_PLUGIN}_RPM_POST_INSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_SOURCE_DIR}/scripts/post"
- CACHE STRING "Install script that will be copied in the %post section"
-)
-
-set(${HICN_PLUGIN}_RPM_POST_UNINSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_SOURCE_DIR}/scripts/postun"
- CACHE STRING "Uninstall script that will be copied in the %postun section"
-) \ No newline at end of file
diff --git a/hicn-plugin/cmake/packaging.cmake b/hicn-plugin/cmake/packaging.cmake
new file mode 100644
index 000000000..3e1f89131
--- /dev/null
+++ b/hicn-plugin/cmake/packaging.cmake
@@ -0,0 +1,64 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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.
+
+######################
+# Packages section
+######################
+
+set(${HICN_PLUGIN}_DESCRIPTION
+ "A high-performance Hybrid ICN forwarder as a plugin to VPP."
+ CACHE STRING "Description for deb/rpm package."
+)
+
+string(REGEX REPLACE "([0-9]+).([0-9]+)(.[0-9]+)?" "\\1\\2" VER_NO_DOTS ${VPP_DEFAULT_VERSION})
+
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/scripts/postinst
+"#!/bin/bash
+
+#########################################################
+# Complete VPP config file with hicn configuration
+#########################################################
+
+if [ -e /etc/vpp/startup.conf ]; then
+ RESULTS=$(sed -n '/hicn[ ]*{/p' /etc/vpp/startup.conf | wc -l)
+ if [[ $RESULTS = 0 ]]; then
+ printf '\n hicn {
+ ## Set PIT size. Default is 131072 entries
+ # pit-size 500000
+ #
+ ## Set CS size. Default is 4096
+ # cs-size 50000
+ #
+ ## Set maximum PIT entries lifetime in milliseconds. Assigned to a PIT entry in case an interest carries a bigger lifetime
+ # pit-lifetime-max 20
+ #
+ ## Percentage of CS to reserve for application producer faces
+ # cs-reserved-app 20\n}' >> /etc/vpp/startup.conf
+ fi;
+fi;
+")
+
+set(${HICN_PLUGIN}_DEB_DEPENDENCIES
+ "${LIBHICN_COMPONENT} (= stable_version), vpp (>= ${PREFIX_VERSION}), vpp-plugin-core (>= ${PREFIX_VERSION})"
+ CACHE STRING "Dependencies for deb/rpm package."
+)
+
+set(${HICN_PLUGIN}-dev_DEB_DEPENDENCIES
+ "${LIBHICN_COMPONENT}-dev (= stable_version), vpp-dev (>= ${PREFIX_VERSION}), libvppinfra-dev (>= ${PREFIX_VERSION})"
+ CACHE STRING "Dependencies for deb/rpm package."
+)
+
+set(${HICN_PLUGIN}_DEB_PACKAGE_CONTROL_EXTRA
+ "${CMAKE_CURRENT_BINARY_DIR}/scripts/postinst"
+ CACHE STRING "Control scripts conffiles, postinst, postrm, prerm."
+)
diff --git a/hicn-plugin/includes/vpp_plugins/hicn/CMakeLists.txt b/hicn-plugin/includes/vpp_plugins/hicn/CMakeLists.txt
new file mode 100644
index 000000000..d498f5138
--- /dev/null
+++ b/hicn-plugin/includes/vpp_plugins/hicn/CMakeLists.txt
@@ -0,0 +1,30 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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(GNUInstallDirs)
+
+set(HICNPLUGIN_INCLUDE_DIRS
+ ${CMAKE_CURRENT_SOURCE_DIR}/../..
+ CACHE INTERNAL
+ "" FORCE
+)
+
+set(HICNPLUGIN_TO_INSTALL_HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/error.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_all_api_h.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_enums.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_msg_enum.h ""
+ CACHE INTERNAL
+ "" FORCE
+) \ No newline at end of file
diff --git a/hicn-plugin/includes/vpp_plugins/hicn/error.h b/hicn-plugin/includes/vpp_plugins/hicn/error.h
new file mode 100644
index 000000000..ae5e102e7
--- /dev/null
+++ b/hicn-plugin/includes/vpp_plugins/hicn/error.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+#ifndef __HICN_ERROR_H__
+#define __HICN_ERROR_H__
+
+/**
+ * @file error.h
+ *
+ * Error codes for the hICN plugin.
+ */
+
+#define PREFIX(x) HICN_ERROR_##x
+#define NEXT(x) PREFIX (x) - 1
+
+#define foreach_hicn_error \
+ _ (NONE, 0, "Ok") \
+ _ (UNSPECIFIED, -128, "Unspecified Error") \
+ _ (FACE_NOT_FOUND, NEXT (UNSPECIFIED), "Face not found in Face table") \
+ _ (FACE_NULL, NEXT (FACE_NOT_FOUND), "Face null") \
+ _ (FACE_IP_ADJ_NOT_FOUND, NEXT (FACE_NULL), \
+ "Ip adjacecny for face not found") \
+ _ (FACE_HW_INT_NOT_FOUND, NEXT (FACE_IP_ADJ_NOT_FOUND), \
+ "Hardware interface not found") \
+ _ (FACE_NOMEM, NEXT (FACE_HW_INT_NOT_FOUND), "Face table is full") \
+ _ (FACE_NO_GLOBAL_IP, NEXT (FACE_NOMEM), "No global ip address for face") \
+ _ (FACE_NOT_FOUND_IN_ENTRY, NEXT (FACE_NO_GLOBAL_IP), \
+ "Face not found in entry") \
+ _ (FACE_NOT_VALID, NEXT (FACE_NOT_FOUND_IN_ENTRY), "Face not valid") \
+ _ (FACE_ALREADY_DELETED, NEXT (FACE_NOT_VALID), "Face alredy deleted") \
+ _ (FACE_ALREADY_CREATED, NEXT (FACE_ALREADY_DELETED), \
+ "Face alredy created") \
+ _ (FWD_NOT_ENABLED, NEXT (FACE_ALREADY_CREATED), \
+ "hICN forwarder not enabled") \
+ _ (FWD_ALREADY_ENABLED, NEXT (FWD_NOT_ENABLED), \
+ "hICN forwarder alredy enabled") \
+ _ (PARSER_UNSUPPORTED_PROTO, NEXT (FWD_ALREADY_ENABLED), \
+ "Unsupported protocol") \
+ _ (PARSER_PKT_INVAL, NEXT (PARSER_UNSUPPORTED_PROTO), "Packet null") \
+ _ (PARSER_MAPME_PACKET, NEXT (PARSER_PKT_INVAL), "Packet is mapme") \
+ _ (PIT_CONFIG_MINLT_OOB, NEXT (PARSER_MAPME_PACKET), \
+ "Min lifetime ouf of bounds") \
+ _ (PIT_CONFIG_MAXLT_OOB, NEXT (PIT_CONFIG_MINLT_OOB), \
+ "Max lifetime ouf of bounds") \
+ _ (PIT_CONFIG_MINMAXLT, NEXT (PIT_CONFIG_MAXLT_OOB), \
+ "Min lifetime grater than max lifetime") \
+ _ (PIT_CONFIG_DFTLT_OOB, NEXT (PIT_CONFIG_MINMAXLT), \
+ "Default lifetime ouf of bounds") \
+ _ (PIT_CONFIG_SIZE_OOB, NEXT (PIT_CONFIG_DFTLT_OOB), \
+ "Pit size ouf of bounds") \
+ _ (CS_CONFIG_SIZE_OOB, NEXT (PIT_CONFIG_SIZE_OOB), "CS size ouf of bounds") \
+ _ (CS_CONFIG_RESERVED_OOB, NEXT (CS_CONFIG_SIZE_OOB), \
+ "Reseved CS must be between 0 and 100 (excluded)") \
+ _ (DPO_CTX_NHOPS_NS, NEXT (CS_CONFIG_RESERVED_OOB), \
+ "No space for additional next hop") \
+ _ (DPO_CTX_NHOPS_EXISTS, NEXT (DPO_CTX_NHOPS_NS), \
+ "Next hop already in the route") \
+ _ (DPO_CTX_NOT_FOUND, NEXT (DPO_CTX_NHOPS_EXISTS), "Dpo context not found") \
+ _ (DPO_MGR_ID_NOT_VALID, NEXT (DPO_CTX_NOT_FOUND), \
+ "Dpo id for strategy and context not valid") \
+ _ (HASHTB_HASH_NOT_FOUND, NEXT (DPO_MGR_ID_NOT_VALID), \
+ "Hash not found in hash table") \
+ _ (HASHTB_HASH_INVAL, NEXT (HASHTB_HASH_NOT_FOUND), \
+ "Error while calculating the hash") \
+ _ (HASHTB_NOMEM, NEXT (HASHTB_HASH_INVAL), \
+ "Unable to allocate new buckets or nodes") \
+ _ (HASHTB_INVAL, NEXT (HASHTB_NOMEM), "Invalid argument") \
+ _ (HASHTB_KEY_INVAL, NEXT (HASHTB_INVAL), "Invalid hashtb key") \
+ _ (HASHTB_EXIST, NEXT (HASHTB_KEY_INVAL), "Hash already in hashtable") \
+ _ (ROUTE_INVAL, NEXT (HASHTB_EXIST), "Invalid face id and weight") \
+ _ (ROUTE_NO_LD, NEXT (ROUTE_INVAL), "Expected load balance dpo") \
+ _ (ROUTE_MLT_LD, NEXT (ROUTE_NO_LD), \
+ "Unexpected mulitple buckets in load balance dpo") \
+ _ (ROUTE_NO_INSERT, NEXT (ROUTE_MLT_LD), \
+ "Unable to insert a new FIB entry") \
+ _ (ROUTE_DPO_NO_HICN, NEXT (ROUTE_NO_INSERT), "Dpo is not of type hICN") \
+ _ (ROUTE_NOT_FOUND, NEXT (ROUTE_DPO_NO_HICN), "Route not found in FIB") \
+ _ (ROUTE_NOT_UPDATED, NEXT (ROUTE_NOT_FOUND), "Unable to update route") \
+ _ (ROUTE_ALREADY_EXISTS, NEXT (ROUTE_NOT_UPDATED), "Route already in FIB") \
+ _ (CLI_INVAL, NEXT (ROUTE_ALREADY_EXISTS), "Invalid input") \
+ _ (IPS_ADDR_TYPE_NONUNIFORM, NEXT (CLI_INVAL), \
+ "Src and dst addr have different ip types") \
+ _ (FACE_TYPE_EXISTS, NEXT (IPS_ADDR_TYPE_NONUNIFORM), \
+ "Face type already registered") \
+ _ (NO_BUFFERS, NEXT (FACE_TYPE_EXISTS), \
+ "No vlib_buffer available for packet cloning.") \
+ _ (NOT_IMPLEMENTED, NEXT (NO_BUFFERS), "Function not yet implemented") \
+ _ (IFACE_IP_ADJ_NOT_FOUND, NEXT (NOT_IMPLEMENTED), \
+ "IP adjacency on incomplete face not available") \
+ _ (APPFACE_ALREADY_ENABLED, NEXT (IFACE_IP_ADJ_NOT_FOUND), \
+ "Application face already enabled on interface") \
+ _ (APPFACE_FEATURE, NEXT (APPFACE_ALREADY_ENABLED), \
+ "Error while enabling app face feature") \
+ _ (APPFACE_NOT_FOUND, NEXT (APPFACE_FEATURE), "Application face not found") \
+ _ (APPFACE_PROD_PREFIX_NULL, NEXT (APPFACE_NOT_FOUND), \
+ "Prefix must not be null for producer face") \
+ _ (STRATEGY_NH_NOT_FOUND, NEXT (APPFACE_PROD_PREFIX_NULL), \
+ "Next hop not found") \
+ _ (MW_STRATEGY_SET, NEXT (STRATEGY_NH_NOT_FOUND), \
+ "Error while setting weight for next hop") \
+ _ (STRATEGY_NOT_FOUND, NEXT (MW_STRATEGY_SET), "Strategy not found") \
+ _ (UDP_TUNNEL_NOT_FOUND, NEXT (STRATEGY_NOT_FOUND), "Udp tunnel not found") \
+ _ (UDP_TUNNEL_SRC_DST_TYPE, NEXT (UDP_TUNNEL_NOT_FOUND), \
+ "Src and dst addresses have different type (ipv4 and ipv6)") \
+ _ (MAPME_NEXT_HOP_ADDED, NEXT (UDP_TUNNEL_SRC_DST_TYPE), \
+ "Next hop added to mapme") \
+ _ (MAPME_WRONG_FACE_CREATED, NEXT (MAPME_NEXT_HOP_ADDED), \
+ "Face created does not correspond to the IU input face") \
+ _ (MAPME_NEXT_HOP_NOT_ADDED, NEXT (MAPME_WRONG_FACE_CREATED), \
+ "Next hop added to mapme") \
+ _ (PCS_NOT_FOUND, NEXT (MAPME_NEXT_HOP_NOT_ADDED), \
+ "Hash not found in hash table") \
+ _ (PCS_HASH_INVAL, NEXT (PCS_NOT_FOUND), \
+ "Error while calculating the hash") \
+ _ (PCS_INVAL, NEXT (PCS_HASH_INVAL), "Invalid argument") \
+ _ (PCS_KEY_INVAL, NEXT (PCS_INVAL), "Invalid hashtb key") \
+ _ (PCS_EXIST, NEXT (PCS_KEY_INVAL), "Hash already in hashtable")
+
+typedef enum
+{
+#define _(a, b, c) PREFIX (a) = (b),
+ foreach_hicn_error
+#undef _
+ HICN_N_ERROR,
+} hicn_error_t;
+
+extern const char *HICN_ERROR_STRING[];
+
+#define get_error_string(errno) \
+ (char *) (errno ? HICN_ERROR_STRING[(-errno) - 127] : \
+ HICN_ERROR_STRING[errno])
+
+#endif /* //__HICN_ERROR_H__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables: eval: (c-set-style "gnu") End:
+ */
diff --git a/hicn-plugin/src/hicn_all_api_h.h b/hicn-plugin/includes/vpp_plugins/hicn/hicn_all_api_h.h
index 1263ea4a2..13769dd58 100644
--- a/hicn-plugin/src/hicn_all_api_h.h
+++ b/hicn-plugin/includes/vpp_plugins/hicn/hicn_all_api_h.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,7 +13,7 @@
* limitations under the License.
*/
-#include <hicn/hicn.api.h>
+#include <vpp_plugins/hicn/hicn.api.h>
/*
* fd.io coding-style-patch-verification: ON
diff --git a/hicn-plugin/src/hicn_api.h b/hicn-plugin/includes/vpp_plugins/hicn/hicn_api.h
index e32b785b6..31d5e7736 100644
--- a/hicn-plugin/src/hicn_api.h
+++ b/hicn-plugin/includes/vpp_plugins/hicn/hicn_api.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,12 +20,9 @@
* @file
*/
-#define HICN_STRATEGY_NULL ~0
-#define HICN_FIB_TABLE 10
-
/* define message structures */
#define vl_typedefs
-#include <hicn/hicn_all_api_h.h>
+#include <vpp_plugins/hicn/hicn_all_api_h.h>
#undef vl_typedefs
#endif /* // __HICN_API_H___ */
diff --git a/libtransport/src/protocols/fec_base.cc b/hicn-plugin/includes/vpp_plugins/hicn/hicn_enums.h
index 9252bc473..8ad2e5d46 100644
--- a/libtransport/src/protocols/fec_base.cc
+++ b/hicn-plugin/includes/vpp_plugins/hicn/hicn_enums.h
@@ -13,12 +13,10 @@
* limitations under the License.
*/
-#include <protocols/fec/rs.h>
-#include <protocols/fec_base.h>
+#ifndef __HICN_ENUMS_H__
+#define __HICN_ENUMS_H__
-namespace transport {
-namespace protocol {
+#define HICN_STRATEGY_NULL ~0
+#define HICN_FIB_TABLE 10
-namespace fec {} // namespace fec
-} // namespace protocol
-} // namespace transport \ No newline at end of file
+#endif /* // __HICN_ENUMS_H__ */ \ No newline at end of file
diff --git a/hicn-plugin/src/hicn_msg_enum.h b/hicn-plugin/includes/vpp_plugins/hicn/hicn_msg_enum.h
index fcf2a1e87..903fbf8c0 100644
--- a/hicn-plugin/src/hicn_msg_enum.h
+++ b/hicn-plugin/includes/vpp_plugins/hicn/hicn_msg_enum.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,7 +24,7 @@
#define vl_msg_id(n, h) n,
typedef enum
{
-#include <hicn/hicn_all_api_h.h>
+#include <vpp_plugins/hicn/hicn_all_api_h.h>
/* We'll want to know how many messages IDs we need... */
VL_MSG_FIRST_AVAILABLE,
} vl_msg_id_t;
diff --git a/hicn-plugin/libvapi-safe/CMakeLists.txt b/hicn-plugin/libvapi-safe/CMakeLists.txt
new file mode 100644
index 000000000..ba647aa34
--- /dev/null
+++ b/hicn-plugin/libvapi-safe/CMakeLists.txt
@@ -0,0 +1,128 @@
+# Copyright (c) 2021-2023 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.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.
+
+##############################################################
+# Libs and Bins names
+##############################################################
+set(SAFE_VAPI safevapi CACHE INTERNAL "" FORCE)
+set(SAFE_VAPI_SHARED ${SAFE_VAPI}.shared CACHE INTERNAL "" FORCE)
+set(SAFE_VAPI_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/includes CACHE INTERNAL "" FORCE)
+set(SAFE_VAPI_LIBRARIES ${SAFE_VAPI_SHARED} CACHE INTERNAL "" FORCE)
+
+
+##############################################################
+# C/CXX Standard
+##############################################################
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_C_STANDARD 11)
+
+
+##############################################################
+# Dependencies and third party libs
+##############################################################
+find_package(Vpp ${VPP_DEFAULT_VERSION} EXACT REQUIRED)
+find_package(Asio ${ASIO_DEFAULT_VERSION} REQUIRED)
+
+
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
+if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ include(CommonSetup)
+ find_package(HicnPlugin ${CURRENT_VERSION} EXACT REQUIRED)
+else()
+ list(APPEND DEPENDENCIES
+ ${HICNPLUGIN_SHARED}
+ )
+endif()
+
+
+##############################################################
+# Sources
+##############################################################
+list(APPEND HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/includes/vapi/vapi_safe.h
+)
+
+list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/vapi_safe.cc
+)
+
+
+##############################################################
+# Compiler Options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ ${MARCH_COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Libraries to link
+##############################################################
+set (LIBRARIES
+ ${VPP_LIBRARY_VAPICLIENT}
+)
+
+
+##############################################################
+# Include directories
+##############################################################
+list (APPEND INCLUDE_DIRS
+ PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
+ $<BUILD_INTERFACE:${HICNPLUGIN_INCLUDE_DIRS}>
+ $<BUILD_INTERFACE:${VPP_INCLUDE_DIR}>
+ $<BUILD_INTERFACE:${SAFE_VAPI_INCLUDE_DIRS}>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+)
+
+
+##############################################################
+# Compiler definitions
+##############################################################
+list(APPEND COMPILER_DEFINITIONS
+ PUBLIC "-DASIO_STANDALONE"
+)
+
+
+##############################################################
+# Build library
+##############################################################
+build_library(${SAFE_VAPI}
+ SHARED
+ SOURCES ${SOURCE_FILES} ${HEADER_FILES}
+ INSTALL_HEADERS ${HEADER_FILES}
+ LINK_LIBRARIES PRIVATE ${LIBRARIES}
+ COMPONENT ${HICN_PLUGIN}
+ INCLUDE_DIRS ${INCLUDE_DIRS}
+ HEADER_ROOT_DIR ""
+ DEFINITIONS PRIVATE ${COMPILER_DEFINITIONS}
+ DEPENDS ${DEPENDENCIES}
+ VERSION ${CURRENT_VERSION}
+ EXPORT_NAME "libsafevapi"
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Create cmake configuration
+##############################################################
+create_cmake_config (
+ "libsafevapi"
+ INCLUDE_DIRS ${SAFE_VAPI_INCLUDE_DIRS}
+ VERSION ${CURRENT_VERSION}
+ COMPONENT ${HICN_PLUGIN}
+ NAMESPACE hicn
+)
diff --git a/hicn-light/src/hicn/config/controlAddPunting.h b/hicn-plugin/libvapi-safe/includes/vapi/vapi_safe.h
index 9cab76359..e13e73556 100644
--- a/hicn-light/src/hicn/config/controlAddPunting.h
+++ b/hicn-plugin/libvapi-safe/includes/vapi/vapi_safe.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,10 +13,21 @@
* limitations under the License.
*/
-#ifndef controlAddPunting_h
-#define controlAddPunting_h
+#ifndef __VAPI_SAFE__
+#define __VAPI_SAFE__
+
+#include <vapi/vapi.h>
+#include <pthread.h>
+
+#include <vapi/hicn.api.vapi.h>
+#include <vapi/interface.api.vapi.h>
+#include <vapi/ip.api.vapi.h>
+#include <vapi/memif.api.vapi.h>
+#include <vapi/udp.api.vapi.h>
+
+vapi_error_e vapi_connect_safe (vapi_ctx_t *vapi_ctx_ret, int async);
+vapi_error_e vapi_disconnect_safe ();
+void vapi_lock ();
+void vapi_unlock ();
-#include <hicn/config/controlState.h>
-CommandOps *controlAddPunting_Create(ControlState *state);
-CommandOps *controlAddPunting_HelpCreate(ControlState *state);
#endif
diff --git a/hicn-plugin/libvapi-safe/libsafevapi-config.cmake.in b/hicn-plugin/libvapi-safe/libsafevapi-config.cmake.in
new file mode 100644
index 000000000..feb278c1f
--- /dev/null
+++ b/hicn-plugin/libvapi-safe/libsafevapi-config.cmake.in
@@ -0,0 +1,8 @@
+@PACKAGE_INIT@
+
+set(Libsafevapi_VERSION_MAJOR "@VERSION_MAJOR@")
+set(Libsafevapi_VERSION_MINOR "@VERSION_MINOR@")
+set(Libsafevapi_VERSION_PATCH "@VERSION_PATCH@")
+
+set_and_check(Libsafe_vapi_INCLUDE_DIRS "@PACKAGE_Libsafevapi_INCLUDE_DIRS@")
+include("${CMAKE_CURRENT_LIST_DIR}/libsafevapi-targets.cmake")
diff --git a/hicn-plugin/libvapi-safe/src/vapi_safe.cc b/hicn-plugin/libvapi-safe/src/vapi_safe.cc
new file mode 100644
index 000000000..723a0fa64
--- /dev/null
+++ b/hicn-plugin/libvapi-safe/src/vapi_safe.cc
@@ -0,0 +1,420 @@
+/*
+ * Copyright (c) 2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+extern "C"
+{
+#include <stdio.h>
+#include <stdlib.h>
+#include <vapi/vapi_safe.h>
+}
+
+#include <thread>
+#include <random>
+#include <asio.hpp>
+#include <iostream>
+
+namespace
+{
+class NonCopyable
+{
+protected:
+ NonCopyable () = default;
+ ~NonCopyable () = default;
+
+ NonCopyable (const NonCopyable &) = delete;
+ NonCopyable &operator= (const NonCopyable &) = delete;
+};
+
+template <typename T> class Singleton : NonCopyable
+{
+public:
+ static T &
+ getInstance ()
+ {
+ static T instance;
+ return instance;
+ }
+
+protected:
+ Singleton () {}
+ ~Singleton () {}
+};
+
+template <typename T> class ThreadLocalSingleton : NonCopyable
+{
+public:
+ static T &
+ getInstance ()
+ {
+ static thread_local T instance;
+ return instance;
+ }
+
+protected:
+ ThreadLocalSingleton () {}
+ ~ThreadLocalSingleton () {}
+};
+
+class EventThread
+{
+public:
+ EventThread (asio::io_service &io_service, bool detached = false)
+ : internal_io_service_ (nullptr), io_service_ (std::ref (io_service)),
+ work_guard_ (asio::make_work_guard (io_service_.get ())),
+ thread_ (nullptr), detached_ (detached)
+ {
+ run ();
+ }
+
+ explicit EventThread (bool detached = false)
+ : internal_io_service_ (std::make_unique<asio::io_service> ()),
+ io_service_ (std::ref (*internal_io_service_)),
+ work_guard_ (asio::make_work_guard (io_service_.get ())),
+ thread_ (nullptr), detached_ (detached)
+ {
+ run ();
+ }
+
+ EventThread (const EventThread &) = delete;
+ EventThread &operator= (const EventThread &) = delete;
+
+ EventThread (EventThread &&other) noexcept
+ : internal_io_service_ (std::move (other.internal_io_service_)),
+ io_service_ (std::move (other.io_service_)),
+ work_guard_ (std::move (other.work_guard_)),
+ thread_ (std::move (other.thread_)),
+ detached_ (other.detached_)
+ {
+ }
+
+ ~EventThread () { stop (); }
+
+ void
+ run ()
+ {
+ if (stopped ())
+ {
+ io_service_.get ().stopped ();
+ }
+
+ thread_ =
+ std::make_unique<std::thread> ([this] () { io_service_.get ().run (); });
+
+ if (detached_)
+ {
+ thread_->detach ();
+ }
+ }
+
+ std::thread::id
+ getThreadId () const
+ {
+ if (thread_)
+ {
+ return thread_->get_id ();
+ }
+ else
+ {
+ throw std::runtime_error ("Event thread is not running.");
+ }
+ }
+
+ template <typename Func>
+ void
+ add (Func &&f)
+ {
+ io_service_.get ().post (std::forward<Func> (f));
+ }
+
+ template <typename Func>
+ void
+ tryRunHandlerNow (Func &&f)
+ {
+ io_service_.get ().dispatch (std::forward<Func> (f));
+ }
+
+ template <typename Func>
+ void
+ addAndWaitForExecution (Func &&f) const
+ {
+ auto promise = std::promise<void> ();
+ auto future = promise.get_future ();
+
+ asio::dispatch (io_service_.get (),
+ [&promise, f = std::forward<Func> (f)] () {
+ f ();
+ promise.set_value ();
+ });
+
+ future.wait ();
+ }
+
+ void
+ stop ()
+ {
+ add ([this] () { work_guard_.reset (); });
+
+ if (thread_ && thread_->joinable ())
+ {
+ thread_->join ();
+ }
+
+ thread_.reset ();
+ }
+
+ bool
+ stopped () const
+ {
+ return io_service_.get ().stopped ();
+ }
+
+ asio::io_service &
+ getIoService ()
+ {
+ return io_service_;
+ }
+
+private:
+ std::unique_ptr<asio::io_service> internal_io_service_;
+ std::reference_wrapper<asio::io_service> io_service_;
+ asio::executor_work_guard<asio::io_context::executor_type> work_guard_;
+ std::unique_ptr<std::thread> thread_;
+ bool detached_;
+};
+
+class UUID : public Singleton<UUID>
+{
+ friend class Singleton<UUID>;
+ static inline unsigned char hex_chars[16] = { '0', '1', '2', '3', '4', '5',
+ '6', '7', '8', '9', 'a', 'b',
+ 'c', 'd', 'e', 'f' };
+
+public:
+ static inline constexpr unsigned int UUID_LEN = 64;
+
+ ~UUID () = default;
+ std::string
+ generate ()
+ {
+ return generate_hex (UUID_LEN);
+ }
+
+ std::string
+ generate_hex (const unsigned int len)
+ {
+ std::string ret (len, 0);
+
+ for (auto &c : ret)
+ {
+ c = random_char ();
+ }
+
+ return ret;
+ }
+
+private:
+ UUID () : rd_ (), gen_ (rd_ ()), dis_ (0, sizeof (hex_chars) - 1) {}
+
+ unsigned char
+ random_char ()
+ {
+ return hex_chars[dis_ (gen_)];
+ }
+
+private:
+ std::random_device rd_;
+ std::mt19937 gen_;
+ std::uniform_int_distribution<> dis_;
+};
+
+} // namespace
+
+DEFINE_VAPI_MSG_IDS_HICN_API_JSON
+DEFINE_VAPI_MSG_IDS_INTERFACE_API_JSON
+DEFINE_VAPI_MSG_IDS_IP_API_JSON
+DEFINE_VAPI_MSG_IDS_UDP_API_JSON
+DEFINE_VAPI_MSG_IDS_MEMIF_API_JSON
+
+class VapiGlobalConnection : public Singleton<VapiGlobalConnection>
+{
+ friend class Singleton<VapiGlobalConnection>;
+
+ static inline char kapp_name[] = "hicn_app";
+ static inline char kapi_prefix[] = "";
+ static inline int kresponse_queue_size = 32;
+ static inline int kmax_outstanding_requests = 32;
+ static inline uint32_t ktimeout_seconds = 1;
+
+public:
+ vapi_error_e
+ vapiConnectSafe (vapi_ctx_t *vapi_ctx_ret)
+ {
+ if (isConnected ())
+ {
+ *vapi_ctx_ret = vapi_ctx_;
+ return VAPI_OK;
+ }
+
+ std::unique_lock<std::mutex> lock (vapi_mtx_);
+
+ auto rv = vapi_ctx_alloc (&vapi_ctx_);
+ if (rv != VAPI_OK)
+ {
+ return rv;
+ }
+
+ rv = vapi_connect (vapi_ctx_, app_name_.c_str (), nullptr,
+ max_outstanding_requests_, response_queue_size_,
+ VAPI_MODE_BLOCKING, 1);
+ connected_ = true;
+
+ vapi_set_generic_event_cb (vapi_ctx_, &VapiGlobalConnection::genericCb,
+ nullptr);
+
+ if (rv == VAPI_OK)
+ {
+ // startDispatcher ();
+ *vapi_ctx_ret = vapi_ctx_;
+ }
+
+ return rv;
+ }
+
+ void
+ vapiLock ()
+ {
+ vapi_mtx_.lock ();
+ }
+
+ void
+ vapiUnLock ()
+ {
+ vapi_mtx_.unlock ();
+ }
+
+ bool
+ isConnected ()
+ {
+ return connected_;
+ }
+
+ ~VapiGlobalConnection ()
+ {
+ if (!isConnected ())
+ {
+ return;
+ }
+ std::unique_lock<std::mutex> lock (vapi_mtx_);
+ vapi_disconnect (vapi_ctx_);
+ vapi_ctx_free (vapi_ctx_);
+ try
+ {
+ timer_.cancel ();
+ }
+ catch (asio::system_error &e)
+ {
+ // quit anyway
+ }
+ }
+
+private:
+ VapiGlobalConnection (
+ const std::string &app_name = std::string (kapp_name) + "_" +
+ UUID::getInstance ().generate_hex (5),
+ const std::string &api_prefix = kapi_prefix,
+ int max_outstanding_requests = kmax_outstanding_requests,
+ int response_queue_size = kresponse_queue_size)
+ : app_name_ (app_name), api_prefix_ (api_prefix),
+ max_outstanding_requests_ (max_outstanding_requests),
+ response_queue_size_ (response_queue_size), vapi_mtx_ (),
+ vapi_ctx_ (nullptr), connected_ (false), thread_ (),
+ timer_ (thread_.getIoService ())
+ {
+ }
+
+ void
+ timerHandler (const std::error_code &ec)
+ {
+ if (ec)
+ {
+ // Timer was canceled
+ return;
+ }
+
+ if (!isConnected ())
+ {
+ return;
+ }
+
+ std::unique_lock<std::mutex> lock (vapi_mtx_);
+ auto err = vapi_dispatch (vapi_ctx_);
+ if (err != VAPI_OK)
+ {
+ return;
+ }
+
+ startDispatcher ();
+ }
+
+ void
+ startDispatcher ()
+ {
+ timer_.expires_after (std::chrono::seconds (ktimeout_seconds));
+ timer_.async_wait (std::bind (&VapiGlobalConnection::timerHandler, this,
+ std::placeholders::_1));
+ }
+
+ static vapi_error_e
+ genericCb (vapi_ctx_t ctx, void *callback_ctx, vapi_msg_id_t id, void *msg)
+ {
+ std::cout << "Called" << std::endl;
+ return VAPI_OK;
+ }
+
+private:
+ std::string app_name_;
+ std::string api_prefix_;
+ int max_outstanding_requests_;
+ int response_queue_size_;
+ std::mutex vapi_mtx_;
+ vapi_ctx_t vapi_ctx_;
+ std::atomic_bool connected_;
+ EventThread thread_;
+ asio::steady_timer timer_;
+};
+
+vapi_error_e
+vapi_connect_safe (vapi_ctx_t *vapi_ctx_ret, int async)
+{
+ return VapiGlobalConnection::getInstance ().vapiConnectSafe (vapi_ctx_ret);
+}
+
+vapi_error_e
+vapi_disconnect_safe ()
+{
+ return VAPI_OK;
+}
+
+void
+vapi_lock ()
+{
+ VapiGlobalConnection::getInstance ().vapiLock ();
+}
+
+void
+vapi_unlock ()
+{
+ VapiGlobalConnection::getInstance ().vapiUnLock ();
+}
diff --git a/hicn-plugin/scripts/post b/hicn-plugin/scripts/post
deleted file mode 100644
index dd0a9fbf5..000000000
--- a/hicn-plugin/scripts/post
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-
-if [ -e /etc/vpp/startup.conf ]; then
- RESULTS=$(sed -n '/hicn[ ]*{/p' /etc/vpp/startup.conf | wc -l)
- if [[ $RESULTS = 0 ]]; then
- printf '\n hicn {
- ## Set PIT size. Default is 131 072 entries
- # pit-size 500000
- #
- ## Set CS size. Default is 4096
- # cs-size 50000
- #
- ## Set maximum PIT entries lifetime in milliseconds. Assigned to a PIT entry in case an interest carries a bigger lifetime
- # pit-lifetime-max 20
- #
- ## Percentage of CS to reserve for application producer faces
- # cs-reserved-app 20\n}' >> /etc/vpp/startup.conf
- fi;
-fi;
-ln -s /usr/lib64/vpp_plugins/hicn_plugin.so /usr/lib/vpp_plugins/hicn_plugin.so \ No newline at end of file
diff --git a/hicn-plugin/scripts/postinst b/hicn-plugin/scripts/postinst
deleted file mode 100644
index d6d48509c..000000000
--- a/hicn-plugin/scripts/postinst
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/bash
-
-if [ -e /etc/vpp/startup.conf ]; then
- RESULTS=$(sed -n '/hicn[ ]*{/p' /etc/vpp/startup.conf | wc -l)
- if [[ $RESULTS = 0 ]]; then
- printf '\n hicn {
- ## Set PIT size. Default is 131 072 entries
- # pit-size 500000
- #
- ## Set CS size. Default is 4096
- # cs-size 50000
- #
- ## Set maximum PIT entries lifetime in milliseconds. Assigned to a PIT entry in case an interest carries a bigger lifetime
- # pit-lifetime-max 20
- #
- ## Percentage of CS to reserve for application producer faces
- # cs-reserved-app 20\n}' >> /etc/vpp/startup.conf
- fi;
-fi; \ No newline at end of file
diff --git a/hicn-plugin/scripts/postun b/hicn-plugin/scripts/postun
deleted file mode 100644
index c319f014e..000000000
--- a/hicn-plugin/scripts/postun
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/bash
-
-if [ -L /usr/lib/vpp_plugins/hicn_plugin.so ]; then
- rm /usr/lib/vpp_plugins/hicn_plugin.so
-fi; \ No newline at end of file
diff --git a/hicn-plugin/src/CMakeLists.txt b/hicn-plugin/src/CMakeLists.txt
index 124d9b5cb..b7fa828f3 100644
--- a/hicn-plugin/src/CMakeLists.txt
+++ b/hicn-plugin/src/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2020 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,290 +11,252 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# Dependencies
-find_package(Vpp REQUIRED)
-
-include_directories(${HICN_INCLUDE_DIRS} ${VPP_INCLUDE_DIR})
-
-set(LIBHICN_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/mapme.c
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/name.c
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/ops.c
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/protocol/ah.c
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/protocol/icmp.c
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/protocol/ipv4.c
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/protocol/ipv6.c
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/src/protocol/tcp.c
-)
-
-set(LIBHICN_HEADER_FILES_SRC
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/hicn.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/base.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/common.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/error.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/header.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/name.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/ops.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/mapme.h
-)
-
-set(LIBHICN_HEADER_FILES_PROTOCOL
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol/ah.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol/icmp.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol/icmprd.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol/ipv4.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol/ipv6.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol/tcp.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/protocol/udp.h
-)
+##############################################################
+# Dependencies and third party libs
+##############################################################
+find_package(Vpp ${VPP_DEFAULT_VERSION} EXACT REQUIRED)
+
+if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
+ list(APPEND HICN_LIBRARIES hicn::hicn.${LIBTYPE})
+else()
+ set(LIBHICN_LIBRARIES ${LIBHICN_SHARED})
+ list(APPEND DEPENDENCIES
+ ${LIBHICN_LIBRARIES}
+ )
+endif()
-set(LIBHICN_HEADER_FILES_UTIL
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/util/ip_address.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/util/token.h
- ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/includes/hicn/util/types.h
-)
+##############################################################
+# Source/Header files
+##############################################################
set(HICN_PLUGIN_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn.c
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api.c
- ${CMAKE_CURRENT_SOURCE_DIR}/cli.c
- ${CMAKE_CURRENT_SOURCE_DIR}/hashtb.c
- ${CMAKE_CURRENT_SOURCE_DIR}/mgmt.c
- ${CMAKE_CURRENT_SOURCE_DIR}/pcs.c
- ${CMAKE_CURRENT_SOURCE_DIR}/route.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_ctx.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_manager.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategy_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/interest_pcslookup_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitpit_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitcs_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/data_input_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/data_pcslookup_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/data_fwd_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/error.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_cli.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/face.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/iface_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/address_mgr.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_cons.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_prod.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_prod_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_app_cli.c
- ${CMAKE_CURRENT_SOURCE_DIR}/pg.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_mw.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_mw.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_mw_cli.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_rr.c
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_rr.c
- ${CMAKE_CURRENT_SOURCE_DIR}/cache_policies/cs_lru.c
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ack_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ctrl_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme_eventmgr.c
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnels/udp_decap_node.c
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnels/udp_tunnel.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/cli.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/infra.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/mgmt.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/pcs.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/route.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_ctx.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_manager.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/interest_pcslookup_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitpit_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitcs_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/data_input_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/data_pcslookup_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/data_fwd_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/error.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_cli.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/face.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/iface_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/address_mgr.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_cons.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_prod.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_prod_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_app_cli.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/pg.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/pg_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_mw.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_mw.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_mw_cli.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_rr.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_rr.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_rp.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_lr.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_rp.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_lr.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/cache_policies/cs_lru.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ack_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ctrl_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/mapme_eventmgr.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnels/udp_decap_node.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnels/udp_tunnel.c
)
set(HICN_PLUGIN_HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_all_api_h.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hashtb.h
- ${CMAKE_CURRENT_SOURCE_DIR}/mgmt.h
- ${CMAKE_CURRENT_SOURCE_DIR}/params.h
- ${CMAKE_CURRENT_SOURCE_DIR}/pcs.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn.h
- ${CMAKE_CURRENT_SOURCE_DIR}/state.h
- ${CMAKE_CURRENT_SOURCE_DIR}/infra.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_msg_enum.h
- ${CMAKE_CURRENT_SOURCE_DIR}/parser.h
- ${CMAKE_CURRENT_SOURCE_DIR}/route.h
- ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_ctx.h
- ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_manager.h
- ${CMAKE_CURRENT_SOURCE_DIR}/strategy.h
- ${CMAKE_CURRENT_SOURCE_DIR}/interest_pcslookup.h
- ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitpit.h
- ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitcs.h
- ${CMAKE_CURRENT_SOURCE_DIR}/data_pcslookup.h
- ${CMAKE_CURRENT_SOURCE_DIR}/data_fwd.h
- ${CMAKE_CURRENT_SOURCE_DIR}/error.h
- ${CMAKE_CURRENT_SOURCE_DIR}/face_db.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/face.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_node.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/iface_node.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/inlines.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_dpo.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/address_mgr.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_cons.h
- ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_prod.h
- ${CMAKE_CURRENT_SOURCE_DIR}/pg.h
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_mw.h
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_mw.h
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_rr.h
- ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_rr.h
- ${CMAKE_CURRENT_SOURCE_DIR}/cache_policies/cs_policy.h
- ${CMAKE_CURRENT_SOURCE_DIR}/cache_policies/cs_lru.h
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme.h
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ack.h
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ctrl.h
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme_eventmgr.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnels/udp_tunnel.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_all_api_h.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_logging.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/mgmt.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/params.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/pcs.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_buffer_flags.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/state.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/infra.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_msg_enum.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/parser.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/route.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_ctx.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy_dpo_manager.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/interest_pcslookup.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitpit.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/interest_hitcs.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/data_pcslookup.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/data_fwd.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/error.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/face_db.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/face.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_flags.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_node.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/iface_node.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/inlines.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/face_dpo.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/address_mgr.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_cons.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/faces/app/face_prod.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/pg.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_mw.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_mw.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_rr.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_rr.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_rp.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/dpo_lr.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_rp.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/strategies/strategy_lr.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/cache_policies/cs_policy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/cache_policies/cs_lru.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/mapme.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ack.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/mapme_ctrl.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/mapme_eventmgr.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnels/udp_tunnel.h
)
set(HICN_API_TEST_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api_test.c
- ${CMAKE_CURRENT_SOURCE_DIR}/error.c)
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api_test.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/error.c
+)
set(HICN_API_HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_msg_enum.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_all_api_h.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_api.h
- ${CMAKE_CURRENT_SOURCE_DIR}/error.h)
+ ${HICNPLUGIN_TO_INSTALL_HEADER_FILES}
+)
set(HICN_API_GENERATED_FILES
- ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins/hicn/hicn.api.h
- ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins/hicn/hicn.api_types.h
- ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins/hicn/hicn.api_enum.h
+ ${PROJECT_BINARY_DIR}/vpp_plugins/hicn/hicn.api.h
+ ${PROJECT_BINARY_DIR}/vpp_plugins/hicn/hicn.api_types.h
+ ${PROJECT_BINARY_DIR}/vpp_plugins/hicn/hicn.api_enum.h
)
set(HICN_VAPI_GENERATED_FILES
- ${CMAKE_CURRENT_BINARY_DIR}/vapi/hicn.api.vapi.h
- ${CMAKE_CURRENT_BINARY_DIR}/vapi/hicn.api.vapi.hpp)
+ ${PROJECT_BINARY_DIR}/vapi/hicn.api.vapi.h
+ ${PROJECT_BINARY_DIR}/vapi/hicn.api.vapi.hpp
+)
-set(HICN_VPP_STARTUP_CONF_FILE
- ${CMAKE_BINARY_DIR}/startup.conf)
+##############################################################
+# Assume VPP is installed in standard location
+##############################################################
if (NOT VPP_HOME)
- set(VPP_HOME /usr)
+ set(VPP_HOME /usr)
endif()
-if (NOT CMAKE_BUILD_TYPE)
- set (CMAKE_BUILD_TYPE "Release")
-endif (NOT CMAKE_BUILD_TYPE)
-SET(HICN_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR} CACHE STRING "hicn_install_prefix")
+##############################################################
+# RPath
+##############################################################
+SET(HICN_INSTALL_PREFIX
+ ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}
+)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/hicn)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/vapi)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/vnet/ip)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/vnet/fib)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/vnet/udp)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins)
-file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins/hicn)
-include(Packager)
-extract_version()
+##############################################################
+# Compiler Options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ ${MARCH_COMPILER_OPTIONS}
+ PRIVATE "-Wno-address-of-packed-member"
+)
-# These files are missing from vpp binary distribution
-execute_process(
- COMMAND
- bash -c
- "if [ ! -e ${CMAKE_CURRENT_BINARY_DIR}/vapi_json_parser.py ]; then
- curl https://raw.githubusercontent.com/FDio/vpp/stable/2106/src/vpp-api/vapi/vapi_json_parser.py -o ${CMAKE_CURRENT_BINARY_DIR}/vapi_json_parser.py;
- fi;
- if [ ! -e ${CMAKE_CURRENT_BINARY_DIR}/vapi_c_gen.py ]; then
- curl https://raw.githubusercontent.com/FDio/vpp/stable/2106/src/vpp-api/vapi/vapi_c_gen.py -o ${CMAKE_CURRENT_BINARY_DIR}/vapi_c_gen.py;
- fi;
- if [ ! -e ${CMAKE_CURRENT_BINARY_DIR}/vapi_cpp_gen.py ]; then
- curl https://raw.githubusercontent.com/FDio/vpp/stable/2106/src/vpp-api/vapi/vapi_cpp_gen.py -o ${CMAKE_CURRENT_BINARY_DIR}/vapi_cpp_gen.py;
- fi;
- if [ ! -e ${CMAKE_CURRENT_BINARY_DIR}/vnet/ip/ip_types.api ]; then
- curl https://raw.githubusercontent.com/FDio/vpp/stable/2106/src/vnet/ip/ip_types.api -o ${CMAKE_CURRENT_BINARY_DIR}/vnet/ip/ip_types.api;
- fi;
- if [ ! -e ${CMAKE_CURRENT_BINARY_DIR}/vnet/fib/fib_entry_track.h ]; then
- curl https://raw.githubusercontent.com/FDio/vpp/stable/2106/src/vnet/fib/fib_entry_track.h -o ${CMAKE_CURRENT_BINARY_DIR}/vnet/fib/fib_entry_track.h;
- fi;
- if [ ! -e ${CMAKE_CURRENT_BINARY_DIR}/vnet/udp/udp_encap.h ]; then
- curl https://raw.githubusercontent.com/FDio/vpp/stable/2106/src/vnet/udp/udp_encap.h -o ${CMAKE_CURRENT_BINARY_DIR}/vnet/udp/udp_encap.h;
- fi;
- chmod +x ${CMAKE_CURRENT_BINARY_DIR}/vapi_json_parser.py ${CMAKE_CURRENT_BINARY_DIR}/vapi_c_gen.py ${CMAKE_CURRENT_BINARY_DIR}/vapi_cpp_gen.py"
+##############################################################
+# Compiler Definitions
+##############################################################
+set(COMPILE_DEFINITIONS
+ "-DHICN_VPP_PLUGIN=1"
+ "-DHICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY"
)
+if (${CMAKE_BUILD_TYPE} MATCHES "Debug")
+ list(APPEND COMPILE_DEFINITIONS
+ "-DHICN_DDEBUG"
+ "-DCLIB_DEBUG"
+ )
+endif()
+
+
+##############################################################
+# VPP API Generation
+##############################################################
+file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/vapi)
+file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/vpp_plugins/hicn)
+
execute_process(
- COMMAND ${VPP_HOME}/bin/vppapigen --includedir ${CMAKE_CURRENT_BINARY_DIR} --input ${CMAKE_CURRENT_SOURCE_DIR}/hicn.api --output ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins/hicn/hicn.api.h --outputdir ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins/hicn/
- COMMAND ${VPP_HOME}/bin/vppapigen JSON --includedir ${CMAKE_CURRENT_BINARY_DIR} --input ${CMAKE_CURRENT_SOURCE_DIR}/hicn.api --output ${CMAKE_CURRENT_BINARY_DIR}/vapi/hicn.api.json --outputdir ${CMAKE_CURRENT_BINARY_DIR}/vapi/
+ COMMAND ${VPP_HOME}/bin/vppapigen --includedir ${VPP_HOME}/include --input ${CMAKE_CURRENT_SOURCE_DIR}/hicn.api --output ${PROJECT_BINARY_DIR}/vpp_plugins/hicn/hicn.api.h --outputdir ${PROJECT_BINARY_DIR}/vpp_plugins/hicn/
+ COMMAND ${VPP_HOME}/bin/vppapigen JSON --includedir ${VPP_HOME}/include --input ${CMAKE_CURRENT_SOURCE_DIR}/hicn.api --output ${PROJECT_BINARY_DIR}/vapi/hicn.api.json --outputdir ${PROJECT_BINARY_DIR}/vapi/
)
execute_process(
- COMMAND ${CMAKE_CURRENT_BINARY_DIR}/vapi_c_gen.py ${CMAKE_CURRENT_BINARY_DIR}/vapi/hicn.api.json
- COMMAND ${CMAKE_CURRENT_BINARY_DIR}/vapi_cpp_gen.py ${CMAKE_CURRENT_BINARY_DIR}/vapi/hicn.api.json
+ COMMAND ${VPP_HOME}/bin/vapi_c_gen.py ${PROJECT_BINARY_DIR}/vapi/hicn.api.json
+ COMMAND ${VPP_HOME}/bin/vapi_cpp_gen.py ${PROJECT_BINARY_DIR}/vapi/hicn.api.json
+)
+install(
+ FILES ${PROJECT_BINARY_DIR}/vapi/hicn.api.json
+ DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/vpp/api/plugins
+ COMPONENT ${HICN_PLUGIN}
)
-include_directories(SYSTEM)
-include_directories(${CMAKE_CURRENT_BINARY_DIR})
-
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DHICN_VPP_PLUGIN=1")
-add_library(hicn_plugin SHARED
- ${LIBHICN_FILES}
- ${HICN_PLUGIN_SOURCE_FILES}
- ${HICN_API_GENERATED_FILES}
- ${HICN_VAPI_GENERATED_FILES})
-
-file(COPY ${HICN_API_HEADER_FILES} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins/hicn)
-include_directories(${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins)
-file(COPY ${LIBHICN_HEADER_FILES_SRC} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/hicn)
-file(COPY ${LIBHICN_HEADER_FILES_PROTOCOL} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/hicn/protocol)
-file(COPY ${LIBHICN_HEADER_FILES_UTIL} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/hicn/util)
+##############################################################
+# Include directories
+##############################################################
+set(HICN_PLUGIN_INCLUDE_DIRS_INTERNAL
+ PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${VPP_INCLUDE_DIR}
+ PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
+ $<BUILD_INTERFACE:${HICNPLUGIN_INCLUDE_DIRS}>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+)
-add_library(hicn_api_test_plugin SHARED
- ${HICN_API_TEST_SOURCE_FILES}
- ${HICN_API_GENERATED_FILES})
-set(VPP_INSTALL_PLUGIN ${HICN_INSTALL_PREFIX}/vpp_plugins)
-set(VPP_INSTALL_API_TEST_PLUGIN ${HICN_INSTALL_PREFIX}/vpp_api_test_plugins CACHE STRING "vpp_install_api_test_plugin")
-set(VPP_STARTUP_CONF /etc/vpp/)
+##############################################################
+# Build hicn plugins for VPP
+##############################################################
+build_module(${HICNPLUGIN}
+ SOURCES ${HICN_PLUGIN_SOURCE_FILES}
+ INSTALL_HEADERS ${HICN_API_HEADER_FILES} ${HICN_API_GENERATED_FILES}
+ LINK_LIBRARIES PRIVATE ${LIBHICN_LIBRARIES}
+ DEPENDS ${DEPENDENCIES}
+ COMPONENT ${HICN_PLUGIN}
+ INCLUDE_DIRS ${HICN_PLUGIN_INCLUDE_DIRS_INTERNAL}
+ HEADER_ROOT_DIR "vpp_plugins"
+ LIBRARY_ROOT_DIR "vpp_plugins"
+ DEFINITIONS PUBLIC ${COMPILE_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ INSTALL_RPATH "${VPP_INSTALL_PLUGIN}:${HICN_INSTALL_PREFIX}:${VPP_HOME}/lib"
+)
-set_target_properties(hicn_plugin
- PROPERTIES
- LINKER_LANGUAGE C
- INSTALL_RPATH ${VPP_INSTALL_PLUGIN}
- COMPILE_FLAGS "-march=native -Wno-address-of-packed-member"
- PREFIX "")
-set_target_properties(hicn_api_test_plugin
- PROPERTIES
- LINKER_LANGUAGE C
- COMPILE_FLAGS "-march=native -Wno-address-of-packed-member"
- PREFIX "")
+build_module(${HICN_API_TEST_PLUGIN}
+ SOURCES ${HICN_API_TEST_SOURCE_FILES}
+ INSTALL_HEADERS ${HICN_VAPI_GENERATED_FILES}
+ COMPONENT ${HICN_PLUGIN}
+ INCLUDE_DIRS ${HICN_PLUGIN_INCLUDE_DIRS_INTERNAL}
+ HEADER_ROOT_DIR "vapi"
+ LIBRARY_ROOT_DIR "vpp_api_test_plugins"
+ DEFINITIONS PUBLIC ${COMPILE_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ INSTALL_RPATH "${VPP_INSTALL_PLUGIN}:${HICN_INSTALL_PREFIX}:${VPP_HOME}/lib"
+)
-if (${CMAKE_BUILD_TYPE} MATCHES "Debug")
- target_compile_definitions(hicn_plugin PRIVATE "CLIB_DEBUG")
- target_compile_definitions(hicn_api_test_plugin PRIVATE "CLIB_DEBUG")
+##############################################################
+# Unit tests
+##############################################################
+if (${BUILD_TESTS})
+ add_subdirectory(test)
endif()
-
-message (STATUS "hicn-plugin variable ${HICN_PLUGIN}")
-
-install(DIRECTORY
- DESTINATION ${VPP_INSTALL_PLUGIN}
- COMPONENT ${HICN_PLUGIN})
-install(TARGETS hicn_plugin
- DESTINATION
- ${VPP_INSTALL_PLUGIN}
- COMPONENT ${HICN_PLUGIN})
-
-install(DIRECTORY
- DESTINATION ${VPP_INSTALL_API_TEST_PLUGIN}
- COMPONENT ${HICN_PLUGIN})
-install(TARGETS hicn_api_test_plugin
- DESTINATION ${VPP_INSTALL_API_TEST_PLUGIN}
- COMPONENT ${HICN_PLUGIN})
-
-install(FILES ${HICN_API_HEADER_FILES} ${HICN_API_GENERATED_FILES}
- DESTINATION ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}/vpp_plugins/hicn
- COMPONENT ${HICN_PLUGIN}-dev)
-
-install(FILES ${HICN_API_GENERATED_FILES}
- DESTINATION ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}/vpp_plugins/hicn
- COMPONENT ${HICN_PLUGIN}-dev)
-
-install(FILES ${HICN_VAPI_GENERATED_FILES}
- DESTINATION ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}/vapi
- COMPONENT ${HICN_PLUGIN}-dev)
-
-#Set variables for other project depending on hicn-plugin
-set(HICNPLUGIN_INCLUDE_DIRS
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_BINARY_DIR}/vpp_plugins
- ${VPP_INCLUDE_DIRS}
- CACHE INTERNAL "" FORCE)
-set(HICNPLUGIN_LIBRARIES ${VPP_LIBRARIES} CACHE INTERNAL "" FORCE)
diff --git a/hicn-plugin/src/cache_policies/cs_lru.c b/hicn-plugin/src/cache_policies/cs_lru.c
index 408a6cb49..07c4916fb 100644
--- a/hicn-plugin/src/cache_policies/cs_lru.c
+++ b/hicn-plugin/src/cache_policies/cs_lru.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,7 +13,6 @@
* limitations under the License.
*/
-#include "../hashtb.h"
#include "../strategy_dpo_manager.h"
#include "../error.h"
#include "cs_lru.h"
@@ -32,129 +31,112 @@ hicn_cs_policy_vft_t hicn_cs_lru = {
* Insert a new CS element at the head of the CS LRU
*/
void
-hicn_cs_lru_insert (hicn_pit_cs_t *p, hicn_hash_node_t *node,
- hicn_pcs_entry_t *pcs, hicn_cs_policy_t *policy_state)
+hicn_cs_lru_insert (hicn_cs_policy_t *lru_policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry)
{
- hicn_hash_node_t *lrunode;
hicn_pcs_entry_t *lrupcs;
u32 idx;
- idx = hicn_hashtb_node_idx_from_node (p->pcs_table, node);
+ idx = hicn_pcs_entry_get_index (pcs, pcs_entry);
- if (policy_state->head != 0)
+ if (lru_policy->head != HICN_CS_POLICY_END_OF_CHAIN)
{
- lrunode = hicn_hashtb_node_from_idx (p->pcs_table, policy_state->head);
- lrupcs = hicn_pit_get_data (lrunode);
+ lrupcs = hicn_pcs_entry_get_entry_from_index (pcs, lru_policy->head);
- ASSERT (lrupcs->u.cs.cs_lru_prev == 0);
+ ASSERT (lrupcs->u.cs.cs_lru_prev == HICN_CS_POLICY_END_OF_CHAIN);
lrupcs->u.cs.cs_lru_prev = idx;
- pcs->u.cs.cs_lru_prev = 0;
- pcs->u.cs.cs_lru_next = policy_state->head;
+ pcs_entry->u.cs.cs_lru_prev = HICN_CS_POLICY_END_OF_CHAIN;
+ pcs_entry->u.cs.cs_lru_next = lru_policy->head;
- policy_state->head = idx;
+ lru_policy->head = idx;
}
else
{
- ASSERT (policy_state->tail == 0); /* We think the list is
- * empty */
+ // The list should be empty
+ ASSERT (lru_policy->tail == HICN_CS_POLICY_END_OF_CHAIN);
- policy_state->head = policy_state->tail = idx;
+ lru_policy->head = lru_policy->tail = idx;
- pcs->u.cs.cs_lru_next = pcs->u.cs.cs_lru_prev = 0;
+ pcs_entry->u.cs.cs_lru_next = pcs_entry->u.cs.cs_lru_prev =
+ HICN_CS_POLICY_END_OF_CHAIN;
}
- policy_state->count++;
+ lru_policy->count++;
}
void
-hicn_cs_lru_delete_get (hicn_pit_cs_t *p, hicn_cs_policy_t *policy_state,
- hicn_hash_node_t **nodep, hicn_pcs_entry_t **pcs_entry,
- hicn_hash_entry_t **hash_entry)
+hicn_cs_lru_delete_get (hicn_cs_policy_t *lru_policy, const hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t **pcs_entry)
{
- *nodep = hicn_hashtb_node_from_idx (p->pcs_table, policy_state->tail);
- *pcs_entry = hicn_pit_get_data (*nodep);
-
- *hash_entry = hicn_hashtb_get_entry (
- p->pcs_table, (*nodep)->entry_idx, (*nodep)->bucket_id,
- (*nodep)->hn_flags & HICN_HASH_NODE_OVERFLOW_BUCKET);
+ *pcs_entry = hicn_pcs_entry_get_entry_from_index (pcs, lru_policy->tail);
}
/*
* Dequeue an LRU element, for example when it has expired.
*/
void
-hicn_cs_lru_dequeue (hicn_pit_cs_t *pit, hicn_hash_node_t *pnode,
- hicn_pcs_entry_t *pcs, hicn_cs_policy_t *lru)
+hicn_cs_lru_dequeue (hicn_cs_policy_t *lru_policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry)
{
- hicn_hash_node_t *lrunode;
hicn_pcs_entry_t *lrupcs;
- if (pcs->u.cs.cs_lru_prev != 0)
+ if (pcs_entry->u.cs.cs_lru_prev != HICN_CS_POLICY_END_OF_CHAIN)
{
/* Not already on the head of the LRU */
- lrunode =
- hicn_hashtb_node_from_idx (pit->pcs_table, pcs->u.cs.cs_lru_prev);
- lrupcs = hicn_pit_get_data (lrunode);
+ lrupcs =
+ hicn_pcs_entry_get_entry_from_index (pcs, pcs_entry->u.cs.cs_lru_prev);
- lrupcs->u.cs.cs_lru_next = pcs->u.cs.cs_lru_next;
+ lrupcs->u.cs.cs_lru_next = pcs_entry->u.cs.cs_lru_next;
}
else
{
- ASSERT (lru->head ==
- hicn_hashtb_node_idx_from_node (pit->pcs_table, pnode));
- lru->head = pcs->u.cs.cs_lru_next;
+ ASSERT (lru_policy->head == hicn_pcs_entry_get_index (pcs, pcs_entry));
+ lru_policy->head = pcs_entry->u.cs.cs_lru_next;
}
- if (pcs->u.cs.cs_lru_next != 0)
+ if (pcs_entry->u.cs.cs_lru_next != HICN_CS_POLICY_END_OF_CHAIN)
{
/* Not already the end of the LRU */
- lrunode =
- hicn_hashtb_node_from_idx (pit->pcs_table, pcs->u.cs.cs_lru_next);
- lrupcs = hicn_pit_get_data (lrunode);
+ lrupcs =
+ hicn_pcs_entry_get_entry_from_index (pcs, pcs_entry->u.cs.cs_lru_next);
- lrupcs->u.cs.cs_lru_prev = pcs->u.cs.cs_lru_prev;
+ lrupcs->u.cs.cs_lru_prev = pcs_entry->u.cs.cs_lru_prev;
}
else
{
/* This was the last LRU element */
- ASSERT (lru->tail ==
- hicn_hashtb_node_idx_from_node (pit->pcs_table, pnode));
- lru->tail = pcs->u.cs.cs_lru_prev;
+ ASSERT (lru_policy->tail == hicn_pcs_entry_get_index (pcs, pcs_entry));
+ lru_policy->tail = pcs_entry->u.cs.cs_lru_prev;
}
- pcs->u.cs.cs_lru_next = pcs->u.cs.cs_lru_prev = 0;
- lru->count--;
+ pcs_entry->u.cs.cs_lru_next = pcs_entry->u.cs.cs_lru_prev =
+ HICN_CS_POLICY_END_OF_CHAIN;
+ lru_policy->count--;
}
/*
- * Move a CS LRU element to the head, probably after it's been used.
+ * Move a CS LRU element to the head. The element must be part of the LRU list.
*/
void
-hicn_cs_lru_update_head (hicn_pit_cs_t *pit, hicn_hash_node_t *pnode,
- hicn_pcs_entry_t *pcs, hicn_cs_policy_t *lru)
+hicn_cs_lru_update_head (hicn_cs_policy_t *lru_policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry)
{
- if (pcs->u.cs.cs_lru_prev != 0)
+ if (pcs_entry->u.cs.cs_lru_prev != HICN_CS_POLICY_END_OF_CHAIN)
{
/*
* Not already on the head of the LRU, detach it from its
* current position
*/
- hicn_cs_lru_dequeue (pit, pnode, pcs, lru);
+ hicn_cs_lru_dequeue (lru_policy, pcs, pcs_entry);
/* Now detached from the list; attach at head */
- hicn_cs_lru_insert (pit, pnode, pcs, lru);
+ hicn_cs_lru_insert (lru_policy, pcs, pcs_entry);
}
else
{
- /* The element is already dequeue */
- if (pcs->u.cs.cs_lru_next == 0)
- {
- /* Now detached from the list; attach at head */
- hicn_cs_lru_insert (pit, pnode, pcs, lru);
- }
- ASSERT (lru->head ==
- hicn_hashtb_node_idx_from_node (pit->pcs_table, pnode));
+ // The element must be already at the head of the LRU
+ ASSERT (lru_policy->head == hicn_pcs_entry_get_index (pcs, pcs_entry));
}
}
@@ -164,96 +146,86 @@ hicn_cs_lru_update_head (hicn_pit_cs_t *pit, hicn_hash_node_t *pnode,
* CS's limit. Return the number of removed nodes.
*/
int
-hicn_cs_lru_trim (hicn_pit_cs_t *pit, u32 *node_list, int sz,
- hicn_cs_policy_t *lru)
+hicn_cs_lru_trim (hicn_cs_policy_t *lru_policy, hicn_pit_cs_t *pcs,
+ u32 *node_list, size_t sz)
{
- hicn_hash_node_t *lrunode;
hicn_pcs_entry_t *lrupcs;
u32 idx;
int i;
- idx = lru->tail;
+ idx = lru_policy->tail;
- for (i = 0; i < sz; i++)
+ for (i = 0; i < sz && idx > 0; i++)
{
-
- if (idx == 0)
- {
- break;
- }
- lrunode = hicn_hashtb_node_from_idx (pit->pcs_table, idx);
- lrupcs = hicn_pit_get_data (lrunode);
+ lrupcs = hicn_pcs_entry_get_entry_from_index (pcs, idx);
node_list[i] = idx;
idx = lrupcs->u.cs.cs_lru_prev;
- lrupcs->u.cs.cs_lru_prev = 0;
- lrupcs->u.cs.cs_lru_next = 0;
+ lrupcs->u.cs.cs_lru_prev = HICN_CS_POLICY_END_OF_CHAIN;
+ lrupcs->u.cs.cs_lru_next = HICN_CS_POLICY_END_OF_CHAIN;
}
- lru->count -= i;
+ lru_policy->count -= i;
+ lru_policy->tail = idx;
- lru->tail = idx;
- if (idx != 0)
+ if (idx != HICN_CS_POLICY_END_OF_CHAIN)
{
- lrunode = hicn_hashtb_node_from_idx (pit->pcs_table, idx);
- lrupcs = hicn_pit_get_data (lrunode);
-
- lrupcs->u.cs.cs_lru_next = 0;
+ lrupcs = hicn_pcs_entry_get_entry_from_index (pcs, idx);
+ lrupcs->u.cs.cs_lru_next = HICN_CS_POLICY_END_OF_CHAIN;
}
else
{
/* If the tail is empty, the whole lru is empty */
- lru->head = 0;
+ lru_policy->head = HICN_CS_POLICY_END_OF_CHAIN;
}
- return (i);
+ return i;
}
int
-hicn_cs_lru_flush (vlib_main_t *vm, struct hicn_pit_cs_s *pitcs,
- hicn_cs_policy_t *state)
+hicn_cs_lru_flush (hicn_cs_policy_t *lru_policy, hicn_pit_cs_t *pcs)
{
- if (state->head == 0 && state->tail == 0)
+ if (lru_policy->head == HICN_CS_POLICY_END_OF_CHAIN &&
+ lru_policy->tail == HICN_CS_POLICY_END_OF_CHAIN)
return 0;
- hicn_hash_node_t *lrunode;
- hicn_pcs_entry_t *lrupcs;
+ hicn_pcs_entry_t *pcs_entry;
u32 idx;
int i = 0;
- idx = state->tail;
+ idx = lru_policy->tail;
- while (idx != 0)
+ while (idx != HICN_CS_POLICY_END_OF_CHAIN)
{
- lrunode = hicn_hashtb_node_from_idx (pitcs->pcs_table, idx);
- lrupcs = hicn_pit_get_data (lrunode);
-
- u64 hashval = 0;
- hicn_hashtb_fullhash ((u8 *) &(lrunode->hn_key.ks.key),
- lrunode->hn_keysize, &hashval);
- hicn_hash_bucket_t *bucket = NULL;
- if ((hashval & (pitcs->pcs_table->ht_bucket_count - 1)) ==
- lrunode->bucket_id)
- {
- // The bucket is in the non overflown
- bucket = pitcs->pcs_table->ht_buckets + lrunode->bucket_id;
- }
- else
- {
- bucket = pool_elt_at_index (pitcs->pcs_table->ht_overflow_buckets,
- lrunode->bucket_id);
- }
- hicn_hash_entry_t *hash_entry =
- &(bucket->hb_entries[lrunode->entry_idx]);
- hash_entry->locks++;
- hicn_pcs_cs_delete (vm, pitcs, &lrupcs, &lrunode, hash_entry, NULL,
- NULL);
- idx = state->tail;
+ // Get tail entry
+ pcs_entry = hicn_pcs_entry_get_entry_from_index (pcs, idx);
+
+ // Delete entry from the PCS. This will also update the LRU.
+ hicn_pcs_entry_remove_lock (pcs, pcs_entry);
+
+ // Set index to the new tail (updated in the previous call)
+ idx = lru_policy->tail;
+
+ // Advance counter
i++;
}
- return (i);
+ return i;
+}
+
+hicn_cs_policy_t
+hicn_cs_lru_create (u32 max_elts)
+{
+ hicn_cs_policy_t policy = {
+ .vft = hicn_cs_lru,
+ .head = HICN_CS_POLICY_END_OF_CHAIN,
+ .tail = HICN_CS_POLICY_END_OF_CHAIN,
+ .count = 0,
+ .max = max_elts,
+ };
+
+ return policy;
}
/*
diff --git a/hicn-plugin/src/cache_policies/cs_lru.h b/hicn-plugin/src/cache_policies/cs_lru.h
index c939b45df..1e67cb547 100644
--- a/hicn-plugin/src/cache_policies/cs_lru.h
+++ b/hicn-plugin/src/cache_policies/cs_lru.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,7 +17,6 @@
#define __LRU_H__
#include "../pcs.h"
-#include "../hashtb.h"
#include "cs_policy.h"
/**
@@ -28,39 +27,46 @@
extern hicn_cs_policy_vft_t hicn_cs_lru;
-/*
- * Insert a new CS element at the head of the CS LRU
+/**
+ * @brief Insert a new CS element at the head of the CS LRU
+ *
+ * @param policy the cs insertion/eviction policy - LRU
+ * @param pcs the PCS table
+ * @param pcs_entry the PCS entry to insert
+ * @return 0 on success, -1 on overflow
*/
-void hicn_cs_lru_insert (hicn_pit_cs_t *pcs, hicn_hash_node_t *pnode,
- hicn_pcs_entry_t *entry, hicn_cs_policy_t *lru);
+void hicn_cs_lru_insert (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry);
/*
* Dequeue an LRU element, for example when it has expired.
*/
-void hicn_cs_lru_dequeue (hicn_pit_cs_t *pcs, hicn_hash_node_t *pnode,
- hicn_pcs_entry_t *entry, hicn_cs_policy_t *lru);
+void hicn_cs_lru_dequeue (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry);
/*
* Move a CS LRU element to the head, probably after it's been used.
*/
-void hicn_cs_lru_update_head (hicn_pit_cs_t *pcs, hicn_hash_node_t *pnode,
- hicn_pcs_entry_t *entry, hicn_cs_policy_t *lru);
+void hicn_cs_lru_update_head (hicn_cs_policy_t *lru, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *entry);
-void hicn_cs_lru_delete_get (hicn_pit_cs_t *p, hicn_cs_policy_t *policy,
- hicn_hash_node_t **node, hicn_pcs_entry_t **pcs,
- hicn_hash_entry_t **hash_entry);
+void hicn_cs_lru_delete_get (hicn_cs_policy_t *policy,
+ const hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t **pcs_entry);
/*
* Remove a batch of nodes from the CS LRU, copying their node indexes into
* the caller's array. We expect this is done when the LRU size exceeds the
* CS's limit. Return the number of removed nodes.
*/
-int hicn_cs_lru_trim (hicn_pit_cs_t *pcs, u32 *node_list, int sz,
- hicn_cs_policy_t *lru);
+int hicn_cs_lru_trim (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ u32 *node_list, size_t sz);
+
+int hicn_cs_lru_flush (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs);
+
+hicn_cs_policy_t hicn_cs_lru_create (u32 max_elts);
-int hicn_cs_lru_flush (vlib_main_t *vm, struct hicn_pit_cs_s *pitcs,
- hicn_cs_policy_t *state);
-#endif /* // __LRU_H__ */
+#endif /* __LRU_H__ */
/*
* fd.io coding-style-patch-verification: ON
diff --git a/hicn-plugin/src/cache_policies/cs_policy.h b/hicn-plugin/src/cache_policies/cs_policy.h
index 505138943..5280a59c2 100644
--- a/hicn-plugin/src/cache_policies/cs_policy.h
+++ b/hicn-plugin/src/cache_policies/cs_policy.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,7 +16,9 @@
#ifndef __HICN_CS_POLICY_H__
#define __HICN_CS_POLICY_H__
-#include "../hashtb.h"
+#include <vppinfra/types.h>
+#include <vppinfra/clib.h>
+#include <stddef.h>
/**
* @file cs_policy.h
@@ -24,25 +26,10 @@
* This file provides the needed structures to implement a CS policy
*/
-/*
- * Structure
- */
-typedef struct hicn_cs_policy_s
-{
- u32 max;
- u32 count;
-
- /* Indexes to hashtable nodes forming CS LRU */
- u32 head;
- u32 tail;
-
-} hicn_cs_policy_t;
-
/* Forward declaration */
-struct hicn_pit_cs_s;
-struct hicn_hash_node_s;
-struct hicn_pcs_entry_s;
-struct hicn_cs_policy_s;
+typedef struct hicn_pit_cs_s hicn_pit_cs_t;
+typedef struct hicn_pcs_entry_s hicn_pcs_entry_t;
+typedef struct hicn_cs_policy_s hicn_cs_policy_t;
/**
* @brief Definition of the virtual functin table for a cache policy.
@@ -51,40 +38,143 @@ struct hicn_cs_policy_s;
* - insert: add a new element
* - update: update the position of an existing element
* - dequeue: remove an element from the list
- * - delete_get: return the next element that should be removed trim
+ * - delete_get: return the next element that should be removed
+ * - trim: trim last sz elements from the list
* - flush: clean the cs
*/
typedef struct hicn_cs_policy_vft_s
{
- void (*hicn_cs_insert) (struct hicn_pit_cs_s *p,
- struct hicn_hash_node_s *node,
- struct hicn_pcs_entry_s *pcs,
- hicn_cs_policy_t *policy);
-
- void (*hicn_cs_update) (struct hicn_pit_cs_s *p,
- struct hicn_hash_node_s *node,
- struct hicn_pcs_entry_s *pcs,
- hicn_cs_policy_t *policy);
-
- void (*hicn_cs_dequeue) (struct hicn_pit_cs_s *p,
- struct hicn_hash_node_s *node,
- struct hicn_pcs_entry_s *pcs,
- hicn_cs_policy_t *policy);
-
- void (*hicn_cs_delete_get) (struct hicn_pit_cs_s *p,
- hicn_cs_policy_t *policy,
- struct hicn_hash_node_s **node,
- struct hicn_pcs_entry_s **pcs,
- struct hicn_hash_entry_s **hash_entry);
-
- int (*hicn_cs_trim) (struct hicn_pit_cs_s *p, u32 *node_list, int sz,
- hicn_cs_policy_t *policy);
-
- int (*hicn_cs_flush) (vlib_main_t *vm, struct hicn_pit_cs_s *p,
- hicn_cs_policy_t *policy_state);
+ void (*hicn_cs_insert) (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry);
+
+ void (*hicn_cs_update) (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry);
+
+ void (*hicn_cs_dequeue) (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry);
+
+ void (*hicn_cs_delete_get) (hicn_cs_policy_t *policy,
+ const hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t **pcs_entry);
+
+ int (*hicn_cs_trim) (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ u32 *node_list, size_t sz);
+
+ int (*hicn_cs_flush) (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs);
} hicn_cs_policy_vft_t;
-#endif /* // __HICN_POLICY_H__ */
+/*
+ * CS policy
+ */
+typedef struct hicn_cs_policy_s
+{
+#define HICN_CS_POLICY_END_OF_CHAIN (u32) (~0)
+
+ /*
+ * VFT implementing the CS eviction/insertion policy. This must be the first
+ * element of the structure.
+ */
+ hicn_cs_policy_vft_t vft;
+
+ /*
+ * Max number of element in CS
+ */
+ u32 max;
+
+ /*
+ * Number of element in CS
+ */
+ u32 count;
+
+ /*
+ * Head element of the CS (i.e. the most recent element used for LRU)
+ */
+ u32 head;
+
+ /*
+ * Tail element of the LRU (i.e. the next element to evict for LRU)
+ */
+ u32 tail;
+} hicn_cs_policy_t;
+
+/*
+ * Get the max number of element in the CS
+ */
+always_inline u32
+hicn_cs_policy_get_max (const hicn_cs_policy_t *policy)
+{
+ return policy->max;
+}
+
+/*
+ * Get the number of element in the CS
+ */
+always_inline u32
+hicn_cs_policy_get_count (const hicn_cs_policy_t *policy)
+{
+ return policy->count;
+}
+
+/*
+ * Get the head element of the CS
+ */
+always_inline u32
+hicn_cs_policy_get_head (const hicn_cs_policy_t *policy)
+{
+ return policy->head;
+}
+
+/*
+ * Get the tail element of the CS
+ */
+always_inline u32
+hicn_cs_policy_get_tail (const hicn_cs_policy_t *policy)
+{
+ return policy->tail;
+}
+
+always_inline void
+hicn_cs_policy_insert (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry)
+{
+ return policy->vft.hicn_cs_insert (policy, pcs, pcs_entry);
+}
+
+always_inline void
+hicn_cs_policy_update (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry)
+{
+ return policy->vft.hicn_cs_update (policy, pcs, pcs_entry);
+}
+
+always_inline void
+hicn_cs_policy_dequeue (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t *pcs_entry)
+{
+ return policy->vft.hicn_cs_dequeue (policy, pcs, pcs_entry);
+}
+
+always_inline void
+hicn_cs_policy_delete_get (hicn_cs_policy_t *policy, const hicn_pit_cs_t *pcs,
+ hicn_pcs_entry_t **pcs_entry)
+{
+ return policy->vft.hicn_cs_delete_get (policy, pcs, pcs_entry);
+}
+
+always_inline int
+hicn_cs_policy_trim (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs,
+ u32 *node_list, int sz)
+{
+ return policy->vft.hicn_cs_trim (policy, pcs, node_list, sz);
+}
+
+always_inline int
+hicn_cs_policy_flush (hicn_cs_policy_t *policy, hicn_pit_cs_t *pcs)
+{
+ return policy->vft.hicn_cs_flush (policy, pcs);
+}
+
+#endif /* __HICN_POLICY_H__ */
/*
* fd.io coding-style-patch-verification: ON
diff --git a/hicn-plugin/src/cli.c b/hicn-plugin/src/cli.c
index 8ecbf7a95..64ebf61a4 100644
--- a/hicn-plugin/src/cli.c
+++ b/hicn-plugin/src/cli.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,6 +22,9 @@
#include <vnet/ip/ip6_packet.h> // ip46_address_t
#include <vnet/ip/format.h>
#include <vnet/fib/fib_types.h>
+#include <vnet/pg/pg.h>
+
+#include <vpp_plugins/hicn/hicn_api.h>
#include "hicn.h"
#include "infra.h"
@@ -33,7 +36,7 @@
#include "error.h"
#include "faces/face.h"
#include "route.h"
-#include "hicn_api.h"
+#include "mapme.h"
static vl_api_hicn_api_node_params_set_t node_ctl_params = {
.pit_max_size = -1,
@@ -65,8 +68,8 @@ hicn_cli_node_ctl_start_set_command_fn (vlib_main_t *vm,
get_error_string (ret));
return (ret == HICN_ERROR_NONE) ?
- 0 :
- clib_error_return (0, get_error_string (ret));
+ 0 :
+ clib_error_return (0, get_error_string (ret));
}
/*
@@ -91,7 +94,7 @@ hicn_cli_node_ctl_stop_set_command_fn (vlib_main_t *vm,
{
return (0);
}
- while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
+ if (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
{
return clib_error_return (0, "%s '%U'",
get_error_string (HICN_ERROR_CLI_INVAL),
@@ -103,8 +106,8 @@ hicn_cli_node_ctl_stop_set_command_fn (vlib_main_t *vm,
node_ctl_params.pit_max_lifetime_sec, node_ctl_params.cs_max_size, ~0);
return (ret == HICN_ERROR_NONE) ?
- 0 :
- clib_error_return (0, get_error_string (ret));
+ 0 :
+ clib_error_return (0, get_error_string (ret));
}
#define DFLTD_RANGE_OK(val, min, max) \
@@ -201,8 +204,8 @@ hicn_cli_node_ctl_param_set_command_fn (vlib_main_t *vm,
"compilation time for better performances\n");
return (rv == HICN_ERROR_NONE) ?
- 0 :
- clib_error_return (0, "%s '%U'", get_error_string (rv),
+ 0 :
+ clib_error_return (0, "%s '%U'", get_error_string (rv),
format_unformat_error, line_input);
}
@@ -213,7 +216,7 @@ static clib_error_t *
hicn_cli_show_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
vlib_cli_command_t *cmd)
{
- int face_p = 0, fib_p = 0, all_p, internal_p = 0, strategies_p = 0,
+ int face_p = 0, fib_p = 0, all_p = 0, strategies_p = 0,
ret = HICN_ERROR_NONE;
/* Get a line of input. */
@@ -226,14 +229,6 @@ hicn_cli_show_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
{
face_p = 1;
}
- else if (unformat (line_input, "internal"))
- {
- /*
- * We consider 'internal' a superset, so
- * include 'detail' too
- */
- internal_p = 1;
- }
else if (unformat (line_input, "strategies"))
{
/*
@@ -333,23 +328,86 @@ hicn_cli_show_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
vlib_cli_output (vm, (char *) strbuf);
}
done:
- if (all_p && internal_p && ret == HICN_ERROR_NONE)
- {
- vlib_cli_output (vm, "Plugin features: cs:%d\n", HICN_FEATURE_CS);
- vlib_cli_output (vm,
- "Removed CS entries (and freed vlib buffers) %d, "
- "Removed PIT entries %d\n",
- hicn_main.pitcs.pcs_cs_dealloc,
- hicn_main.pitcs.pcs_pit_dealloc);
- vlib_cli_output (vm,
- "Bucke count %d, Overflow buckets count %d, used %d\n",
- hicn_main.pitcs.pcs_table->ht_bucket_count,
- hicn_main.pitcs.pcs_table->ht_overflow_bucket_count,
- hicn_main.pitcs.pcs_table->ht_overflow_buckets_used);
- }
return (ret == HICN_ERROR_NONE) ?
- 0 :
- clib_error_return (0, "%s\n", get_error_string (ret));
+ 0 :
+ clib_error_return (0, "%s\n", get_error_string (ret));
+}
+
+/*
+ * cli handler for 'mapme'
+ */
+static clib_error_t *
+hicn_cli_mapme_set_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
+ vlib_cli_command_t *cmd)
+{
+ clib_error_t *cl_err = 0;
+ fib_prefix_t prefix;
+
+ /* Get a line of input. */
+ unformat_input_t _line_input, *line_input = &_line_input;
+ if (!unformat_user (main_input, unformat_line_input, line_input))
+ {
+ return (0);
+ }
+ while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (line_input, "default-route %U/%d", unformat_ip46_address,
+ &prefix.fp_addr, IP46_TYPE_ANY, &prefix.fp_len))
+ {
+ ;
+ }
+ else
+ {
+ return clib_error_return (0, "%s '%U'",
+ get_error_string (HICN_ERROR_CLI_INVAL),
+ format_unformat_error, line_input);
+ }
+ }
+
+ prefix.fp_proto = ip46_address_is_ip4 (&prefix.fp_addr) ? FIB_PROTOCOL_IP4 :
+ FIB_PROTOCOL_IP6;
+
+ hicn_mapme_main_t *mapme_main = hicn_mapme_get_main ();
+ mapme_main->default_route = prefix;
+
+ return (cl_err);
+}
+
+static clib_error_t *
+hicn_cli_mapme_get_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
+ vlib_cli_command_t *cmd)
+{
+ hicn_mapme_main_t *mm = hicn_mapme_get_main ();
+ int default_route = 0;
+ clib_error_t *cl_err = 0;
+
+ /* Get a line of input. */
+ unformat_input_t _line_input, *line_input = &_line_input;
+ if (!unformat_user (main_input, unformat_line_input, line_input))
+ {
+ return (0);
+ }
+ while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (line_input, "default-route"))
+ {
+ default_route = 1;
+ }
+ else
+ {
+ return clib_error_return (0, "%s '%U'",
+ get_error_string (HICN_ERROR_CLI_INVAL),
+ format_unformat_error, line_input);
+ }
+ }
+
+ if (default_route)
+ {
+ vlib_cli_output (vm, "Mapme default route: '%U'", format_fib_prefix,
+ &mm->default_route);
+ }
+
+ return cl_err;
}
/*
@@ -408,8 +466,8 @@ hicn_cli_strategy_set_command_fn (vlib_main_t *vm,
rv = hicn_route_set_strategy (&prefix, strategy_id);
cl_err = (rv == HICN_ERROR_NONE) ?
- NULL :
- clib_error_return (0, get_error_string (rv));
+ NULL :
+ clib_error_return (0, get_error_string (rv));
done:
return (cl_err);
@@ -583,13 +641,15 @@ hicn_cli_pgen_server_set_command_fn (vlib_main_t *vm,
unformat_input_t *main_input,
vlib_cli_command_t *cmd)
{
- clib_error_t *cl_err;
- int rv = HICN_ERROR_NONE;
- hicnpg_server_main_t *pg_main = &hicnpg_server_main;
int payload_size = 1440;
u32 sw_if_index = ~0;
vnet_main_t *vnm = vnet_get_main ();
- fib_prefix_t *prefix = calloc (1, sizeof (fib_prefix_t));
+ fib_prefix_t prefix = {};
+ u32 hicnpg_server_index;
+ ip46_address_t locator;
+
+ locator.as_u64[0] = 0;
+ locator.as_u64[1] = 0;
/* Get a line of input. */
unformat_input_t _line_input, *line_input = &_line_input;
@@ -599,7 +659,7 @@ hicn_cli_pgen_server_set_command_fn (vlib_main_t *vm,
while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
{
if (unformat (line_input, "name %U/%d", unformat_ip46_address,
- &prefix->fp_addr, IP46_TYPE_ANY, &prefix->fp_len))
+ &prefix.fp_addr, IP46_TYPE_ANY, &prefix.fp_len))
{
;
}
@@ -616,6 +676,11 @@ hicn_cli_pgen_server_set_command_fn (vlib_main_t *vm,
{
;
}
+ else if (unformat (line_input, "dst %U", unformat_ip46_address,
+ &locator, IP46_TYPE_ANY))
+ {
+ ;
+ }
else
{
return (clib_error_return (0, "Unknown input '%U'",
@@ -626,70 +691,45 @@ hicn_cli_pgen_server_set_command_fn (vlib_main_t *vm,
}
/* Attach our packet-gen node for ip4 udp local traffic */
- if ((prefix->fp_addr.ip6.as_u64[0] == (u64) 0 &&
- prefix->fp_addr.ip6.as_u64[1] == 0) ||
- payload_size == 0 || sw_if_index == ~0)
+ if ((prefix.fp_addr.ip6.as_u64[0] == (u64) 0 &&
+ prefix.fp_addr.ip6.as_u64[1] == 0) ||
+ payload_size == 0 || sw_if_index == ~0 ||
+ ip46_address_is_zero (&locator))
{
- return clib_error_return (0, "Error: must supply local port, payload "
+ return clib_error_return (0, "Error: must supply locator, payload "
"size and incoming hICN prefix");
}
// Remove bits that are out of the subnet
- if (ip46_address_is_ip4 (&prefix->fp_addr))
+ if (ip46_address_is_ip4 (&prefix.fp_addr))
{
ip4_address_t mask;
- ip4_preflen_to_mask (prefix->fp_len, &mask);
- prefix->fp_addr.ip4.as_u32 = prefix->fp_addr.ip4.as_u32 & mask.as_u32;
- prefix->fp_proto = FIB_PROTOCOL_IP4;
+ ip4_preflen_to_mask (prefix.fp_len, &mask);
+ prefix.fp_addr.ip4.as_u32 = prefix.fp_addr.ip4.as_u32 & mask.as_u32;
+ prefix.fp_proto = FIB_PROTOCOL_IP4;
}
else
{
ip6_address_t mask;
- ip6_preflen_to_mask (prefix->fp_len, &mask);
- prefix->fp_addr.ip6.as_u64[0] =
- prefix->fp_addr.ip6.as_u64[0] & mask.as_u64[0];
- prefix->fp_addr.ip6.as_u64[1] =
- prefix->fp_addr.ip6.as_u64[1] & mask.as_u64[1];
- prefix->fp_proto = FIB_PROTOCOL_IP6;
+ ip6_preflen_to_mask (prefix.fp_len, &mask);
+ prefix.fp_addr.ip6.as_u64[0] =
+ prefix.fp_addr.ip6.as_u64[0] & mask.as_u64[0];
+ prefix.fp_addr.ip6.as_u64[1] =
+ prefix.fp_addr.ip6.as_u64[1] & mask.as_u64[1];
+ prefix.fp_proto = FIB_PROTOCOL_IP6;
}
- /* Allocate the buffer with the actual content payload TLV */
- int n_buf = vlib_buffer_alloc (vm, &pg_main->pgen_svr_buffer_idx, 1);
-
- if (n_buf == 0)
+ fib_protocol_t dest_proto =
+ ip46_address_is_ip4 (&locator) ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
+ if (prefix.fp_proto != dest_proto)
{
- return (clib_error_return (0, "Impossible to allocate paylod buffer."));
+ return clib_error_return (0, "Error: prefix and locator must be of the "
+ "same protocol");
}
- vlib_buffer_t *rb = NULL;
- rb = vlib_get_buffer (vm, pg_main->pgen_svr_buffer_idx);
-
- pg_main->pgen_srv_hicn_name = prefix;
-
- /* Initialize the buffer data with zeros */
- memset (rb->data, 0, payload_size);
- rb->current_length = payload_size;
-
- vnet_feature_enable_disable ("ip4-unicast", "hicnpg-server", sw_if_index, 1,
- 0, 0);
- vnet_feature_enable_disable ("ip6-unicast", "hicnpg-server", sw_if_index, 1,
- 0, 0);
-
- switch (rv)
- {
- case 0:
- cl_err = 0;
- break;
-
- case VNET_API_ERROR_UNIMPLEMENTED:
- cl_err = clib_error_return (0, "Unimplemented, NYI");
- break;
-
- default:
- cl_err = clib_error_return (0, "hicn pgen server returned %d", rv);
- }
-
- return cl_err;
+ // Create hicnpg_server
+ return hicnpg_server_add_and_lock (&prefix, &hicnpg_server_index, &locator,
+ payload_size);
}
static clib_error_t *
@@ -727,12 +767,27 @@ hicn_enable_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
goto done;
}
}
- rv = hicn_route_enable (&pfx);
+
+ hicn_face_id_t *vec_faces = NULL;
+ fib_node_index_t hicn_fib_index;
+ rv = hicn_route_enable (&pfx, &hicn_fib_index, &vec_faces);
+
+ if (vec_faces != NULL)
+ {
+ hicn_face_id_t *face_id;
+ u8 *str = 0;
+ vec_foreach (face_id, vec_faces)
+ {
+ str = format (str, " %d", *face_id);
+ }
+ vec_free (vec_faces);
+ vlib_cli_output (vm, "Faces for this prefix: %s", str);
+ }
done:
cl_err = (rv == HICN_ERROR_NONE) ?
- NULL :
- clib_error_return (0, get_error_string (rv));
+ NULL :
+ clib_error_return (0, get_error_string (rv));
return cl_err;
}
@@ -776,11 +831,24 @@ hicn_disable_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
done:
cl_err = (rv == HICN_ERROR_NONE) ?
- NULL :
- clib_error_return (0, get_error_string (rv));
+ NULL :
+ clib_error_return (0, get_error_string (rv));
return cl_err;
}
+/* cli declaration for 'mapme set default_route' */
+VLIB_CLI_COMMAND (hicn_cli_mapme_set_command, static) = {
+ .path = "hicn mapme set",
+ .short_help = "hicn mapme set default-route <prefix>",
+ .function = hicn_cli_mapme_set_command_fn,
+};
+
+VLIB_CLI_COMMAND (hicn_cli_mapme_get_command, static) = {
+ .path = "hicn mapme get",
+ .short_help = "hicn mapme get default-route",
+ .function = hicn_cli_mapme_get_command_fn,
+};
+
/* cli declaration for 'control start' */
VLIB_CLI_COMMAND (hicn_cli_node_ctl_start_set_command, static) = {
.path = "hicn control start",
@@ -840,7 +908,7 @@ VLIB_CLI_COMMAND (hicn_cli_pgen_client_set_command, static) = {
VLIB_CLI_COMMAND (hicn_cli_pgen_server_set_command, static) = {
.path = "hicn pgen server",
.short_help = "hicn pgen server name <prefix> intfc <interest in-interface> "
- "size <payload_size>",
+ "dst <ip_address> size <payload_size>",
.long_help = "Run hicn in packet-gen server mode\n",
.function = hicn_cli_pgen_server_set_command_fn,
};
diff --git a/hicn-plugin/src/data_fwd.h b/hicn-plugin/src/data_fwd.h
index 96d8399e4..4acfdea4d 100644
--- a/hicn-plugin/src/data_fwd.h
+++ b/hicn-plugin/src/data_fwd.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -50,6 +50,7 @@ typedef struct
u32 sw_if_index;
u8 pkt_type;
u8 packet_data[64];
+ u32 face;
} hicn_data_fwd_trace_t;
typedef enum
@@ -62,6 +63,15 @@ typedef enum
HICN_DATA_FWD_N_NEXT,
} hicn_data_fwd_next_t;
+/*
+ * Node context data; we think this is per-thread/instance
+ */
+typedef struct hicn_data_fwd_runtime_s
+{
+ int id;
+ hicn_pit_cs_t *pitcs;
+} hicn_data_fwd_runtime_t;
+
/**
* @brief Create a maximum of 256 clones of buffer and store them
* in the supplied array. Unlike the original function in the vlib
diff --git a/hicn-plugin/src/data_fwd_node.c b/hicn-plugin/src/data_fwd_node.c
index fe79b33fa..e3466c904 100644
--- a/hicn-plugin/src/data_fwd_node.c
+++ b/hicn-plugin/src/data_fwd_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -32,292 +32,6 @@ static char *hicn_data_fwd_error_strings[] = {
};
/* Declarations */
-always_inline void drop_packet (vlib_main_t *vm, u32 bi0, u32 *n_left_to_next,
- u32 *next0, u32 **to_next, u32 *next_index,
- vlib_node_runtime_t *node);
-
-always_inline int
-hicn_satisfy_faces (vlib_main_t *vm, u32 b0, hicn_pcs_entry_t *pitp,
- u32 *n_left_to_next, u32 **to_next, u32 *next_index,
- vlib_node_runtime_t *node, u8 isv6,
- vl_api_hicn_api_node_stats_get_reply_t *stats);
-
-always_inline void
-clone_data_to_cs (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *pitp, hicn_header_t *hicn0, f64 tnow,
- hicn_hash_node_t *nodep, vlib_buffer_t *b0,
- hicn_hash_entry_t *hash_entry, u64 name_hash,
- hicn_buffer_t *hicnb, const hicn_dpo_vft_t *dpo_vft,
- dpo_id_t *hicn_dpo_id, hicn_lifetime_t dmsg_lifetime);
-
-/* packet trace format function */
-always_inline u8 *hicn_data_fwd_format_trace (u8 *s, va_list *args);
-
-vlib_node_registration_t hicn_data_fwd_node;
-
-/*
- * ICN forwarder node for interests: handling of Data delivered based on ACL.
- * - 1 packet at a time - ipv4/tcp ipv6/tcp
- */
-static uword
-hicn_data_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
- vlib_frame_t *frame)
-{
-
- u32 n_left_from, *from, *to_next;
- hicn_data_fwd_next_t next_index;
- hicn_pit_cs_t *pitcs = &hicn_main.pitcs;
- vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
- f64 tnow;
- u32 data_received = 1;
-
- from = vlib_frame_vector_args (frame);
- n_left_from = frame->n_vectors;
- next_index = node->cached_next_index;
-
- /* Capture time in vpp terms */
- tnow = vlib_time_now (vm);
-
- while (n_left_from > 0)
- {
- u32 n_left_to_next;
- vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
-
- while (n_left_from > 0 && n_left_to_next > 0)
- {
- vlib_buffer_t *b0;
- u8 isv6;
- u8 *nameptr;
- u16 namelen;
- u32 bi0;
- u32 next0 = HICN_DATA_FWD_NEXT_ERROR_DROP;
- hicn_name_t name;
- hicn_header_t *hicn0;
- hicn_buffer_t *hicnb0;
- hicn_hash_node_t *node0;
- const hicn_strategy_vft_t *strategy_vft0;
- const hicn_dpo_vft_t *dpo_vft0;
- u8 dpo_ctx_id0;
- hicn_pcs_entry_t *pitp;
- hicn_hash_entry_t *hash_entry0;
- int ret = HICN_ERROR_NONE;
-
- /* Prefetch for next iteration. */
- if (n_left_from > 1)
- {
- vlib_buffer_t *b1;
- b1 = vlib_get_buffer (vm, from[1]);
- CLIB_PREFETCH (b1, 2 * CLIB_CACHE_LINE_BYTES, STORE);
- CLIB_PREFETCH (b1->data, CLIB_CACHE_LINE_BYTES, STORE);
- }
- /* Dequeue a packet buffer */
- /*
- * Do not copy the index in the next buffer, we'll do
- * it later. The packet might be cloned, so the buffer to move
- * to next must be the cloned one
- */
- bi0 = from[0];
- from += 1;
- n_left_from -= 1;
-
- b0 = vlib_get_buffer (vm, bi0);
-
- /* Get hicn buffer and state */
- hicnb0 = hicn_get_buffer (b0);
- hicn_get_internal_state (hicnb0, pitcs, &node0, &strategy_vft0,
- &dpo_vft0, &dpo_ctx_id0, &hash_entry0);
-
- ret = hicn_data_parse_pkt (b0, &name, &namelen, &hicn0, &isv6);
- pitp = hicn_pit_get_data (node0);
- nameptr = (u8 *) (&name);
-
- if (PREDICT_FALSE (
- ret != HICN_ERROR_NONE ||
- !hicn_node_compare (nameptr, namelen, node0) ||
- (hash_entry0->he_flags & HICN_HASH_ENTRY_FLAG_CS_ENTRY)))
- {
- /*
- * Remove the lock acquired from
- * data_pcslookup node
- */
- dpo_id_t hicn_dpo_id0 = { .dpoi_type =
- dpo_vft0->hicn_dpo_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = dpo_ctx_id0 };
- hicn_pcs_remove_lock (pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
-
- drop_packet (vm, bi0, &n_left_to_next, &next0, &to_next,
- &next_index, node);
-
- goto end_processing;
- }
- /*
- * Check if the hit is instead a collision in the
- * hash table. Unlikely to happen.
- */
- /*
- * there is no guarantee that the type of entry has
- * not changed from the lookup.
- */
-
- if (tnow > pitp->shared.expire_time ||
- (hash_entry0->he_flags & HICN_HASH_ENTRY_FLAG_DELETED))
- {
- dpo_id_t hicn_dpo_id0 = { .dpoi_type =
- dpo_vft0->hicn_dpo_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = dpo_ctx_id0 };
- hicn_pcs_delete (pitcs, &pitp, &node0, vm, hash_entry0, dpo_vft0,
- &hicn_dpo_id0);
-
- drop_packet (vm, bi0, &n_left_to_next, &next0, &to_next,
- &next_index, node);
- stats.pit_expired_count++;
-
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
- (b0->flags & VLIB_BUFFER_IS_TRACED)))
- {
- hicn_data_fwd_trace_t *t =
- vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_CONTENT;
- t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- t->next_index = next0;
- clib_memcpy (t->packet_data, vlib_buffer_get_current (b0),
- sizeof (t->packet_data));
- }
- }
- else
- {
- ASSERT ((hash_entry0->he_flags & HICN_HASH_ENTRY_FLAG_DELETED) ==
- 0);
-
- data_received++;
- /*
- * We do not check if the data is coming from
- * the outgoing interest face.
- */
-
- /* Prepare the buffer for the cloning */
- ret =
- hicn_satisfy_faces (vm, bi0, pitp, &n_left_to_next, &to_next,
- &next_index, node, isv6, &stats);
-
- dpo_id_t hicn_dpo_id0 = { .dpoi_type =
- dpo_vft0->hicn_dpo_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = dpo_ctx_id0 };
-
- if (PREDICT_FALSE (ret != HICN_ERROR_NONE))
- {
- hicn_pcs_pit_delete (pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
- continue;
- }
- /*
- * Call the strategy callback since the
- * interest has been satisfied
- */
- strategy_vft0->hicn_receive_data (dpo_ctx_id0,
- pitp->u.pit.pe_txnh);
-
-#if HICN_FEATURE_CS
- hicn_lifetime_t dmsg_lifetime;
-
- hicn_type_t type = hicnb0->type;
- hicn_ops_vft[type.l1]->get_lifetime (type, &hicn0->protocol,
- &dmsg_lifetime);
-
- if (dmsg_lifetime)
- {
- /*
- * Clone data packet in the content store and
- * convert the PIT entry into a CS entry
- */
- clone_data_to_cs (vm, pitcs, pitp, hicn0, tnow, node0, b0,
- hash_entry0, hicnb0->name_hash, hicnb0,
- dpo_vft0, &hicn_dpo_id0, dmsg_lifetime);
-
- hicn_pcs_remove_lock (pitcs, &pitp, &node0, vm, hash_entry0,
- NULL, NULL);
- }
- else
- {
- /*
- * If the packet is copied and not cloned, we need to free
- * the vlib_buffer
- */
- if (hicnb0->flags & HICN_BUFFER_FLAGS_PKT_LESS_TWO_CL)
- {
- vlib_buffer_free_one (vm, bi0);
- }
- else
- {
- /*
- * Remove one reference as the buffer is no
- * longer in any frame. The vlib_buffer will be freed
- * when all its cloned vlib_buffer will be freed.
- */
- b0->ref_count--;
- }
-
- /* Delete the PIT entry */
- hicn_pcs_pit_delete (pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
- }
-#else
- ASSERT (pitp == hicn_pit_get_data (node0));
- /*
- * If the packet is copied and not cloned, we need to free the
- * vlib_buffer
- */
- if (hicnb0->flags & HICN_BUFFER_FLAGS_PKT_LESS_TWO_CL)
- {
- vlib_buffer_free_one (vm, bi0);
- }
- else
- {
- /*
- * Remove one reference as the buffer is no
- * longer in any frame. The vlib_buffer will be freed when
- * all its cloned vlib_buffer will be freed.
- */
- b0->ref_count--;
- }
-
- /* Delete the PIT entry */
- hicn_pcs_pit_delete (pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
-#endif
- }
- end_processing:
-
- /* Incr packet counter */
- stats.pkts_processed += 1;
- }
-
- vlib_put_next_frame (vm, node, next_index, n_left_to_next);
- }
- u32 pit_int_count = hicn_pit_get_int_count (pitcs);
- u32 pit_cs_count = hicn_pit_get_cs_count (pitcs);
-
- vlib_node_increment_counter (vm, hicn_data_fwd_node.index,
- HICNFWD_ERROR_DATAS, stats.pkts_data_count);
-
- update_node_counter (vm, hicn_data_fwd_node.index, HICNFWD_ERROR_INT_COUNT,
- pit_int_count);
- update_node_counter (vm, hicn_data_fwd_node.index, HICNFWD_ERROR_CS_COUNT,
- pit_cs_count);
- update_node_counter (vm, hicn_data_fwd_node.index,
- HICNFWD_ERROR_INTEREST_AGG_ENTRY,
- stats.pkts_data_count / data_received);
-
- return (frame->n_vectors);
-}
-
always_inline void
drop_packet (vlib_main_t *vm, u32 bi0, u32 *n_left_to_next, u32 *next0,
u32 **to_next, u32 *next_index, vlib_node_runtime_t *node)
@@ -340,7 +54,8 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
{
int found = 0;
int ret = HICN_ERROR_NONE;
- u32 *clones = NULL, *header = NULL;
+ u32 inline_clones[HICN_FACE_DB_INLINE_FACES];
+ u32 *clones = inline_clones, *header = NULL;
u32 n_left_from = 0;
u32 next0 = HICN_DATA_FWD_NEXT_ERROR_DROP,
next1 = HICN_DATA_FWD_NEXT_ERROR_DROP;
@@ -355,8 +70,11 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
* need to be careful to clone it only 254 times as the buffer
* already has n_add_reds=1.
*/
- vec_alloc (clones, pitp->u.pit.faces.n_faces);
- header = clones;
+ if (hicn_pcs_entry_pit_get_n_faces (pitp) > HICN_FACE_DB_INLINE_FACES)
+ {
+ vec_alloc (clones, hicn_pcs_entry_pit_get_n_faces (pitp));
+ header = clones;
+ }
/* Clone bi0 */
vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0);
@@ -379,7 +97,7 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
{
/* Add one reference to maintain the buffer in the CS.
* b0->ref_count == 0 has two meaning: it has 1 buffer or no buffer
- * chained to it. vlib_buffer_clone2 add a number of reference equalt to
+ * chained to it. vlib_buffer_clone2 add a number of reference equal to
* pitp->u.pit.faces.n_faces - 1 as vlib_buffer_clone does. So after all
* the packet are forwarded the buffer stored in the CS will have
* ref_count == 0;
@@ -387,17 +105,16 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
b0->ref_count++;
}
- found = n_left_from = vlib_buffer_clone2 (
- vm, bi0, clones, pitp->u.pit.faces.n_faces, buffer_advance);
+ found = n_left_from =
+ vlib_buffer_clone2 (vm, bi0, clones, pitp->u.pit.n_faces, buffer_advance);
- ASSERT (n_left_from == pitp->u.pit.faces.n_faces);
+ ASSERT (n_left_from == hicn_pcs_entry_pit_get_n_faces (pitp));
/* Index to iterate over the faces */
int i = 0;
while (n_left_from > 0)
{
-
// Dual loop, X2
while (n_left_from >= 4 && *n_left_to_next >= 2)
{
@@ -414,8 +131,11 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
CLIB_PREFETCH (h3, 2 * CLIB_CACHE_LINE_BYTES, STORE);
}
- face0 = hicn_face_db_get_dpo_face (i++, &pitp->u.pit.faces);
- face1 = hicn_face_db_get_dpo_face (i++, &pitp->u.pit.faces);
+ face0 = hicn_pcs_entry_pit_get_dpo_face (pitp, i);
+ face1 = hicn_pcs_entry_pit_get_dpo_face (pitp, i + 1);
+
+ // Increment index
+ i += 2;
h0 = vlib_get_buffer (vm, clones[0]);
h1 = vlib_get_buffer (vm, clones[1]);
@@ -428,9 +148,9 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
clones += 2;
next0 = isv6 ? HICN_DATA_FWD_NEXT_IFACE6_OUT :
- HICN_DATA_FWD_NEXT_IFACE4_OUT;
+ HICN_DATA_FWD_NEXT_IFACE4_OUT;
next1 = isv6 ? HICN_DATA_FWD_NEXT_IFACE6_OUT :
- HICN_DATA_FWD_NEXT_IFACE4_OUT;
+ HICN_DATA_FWD_NEXT_IFACE4_OUT;
vnet_buffer (h0)->ip.adj_index[VLIB_TX] = face0;
vnet_buffer (h1)->ip.adj_index[VLIB_TX] = face1;
@@ -442,7 +162,8 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
{
hicn_data_fwd_trace_t *t =
vlib_add_trace (vm, node, h0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_CONTENT;
+ t->face = face0;
+ t->pkt_type = HICN_PACKET_TYPE_DATA;
t->sw_if_index = vnet_buffer (h0)->sw_if_index[VLIB_RX];
t->next_index = next0;
clib_memcpy (t->packet_data, vlib_buffer_get_current (h0),
@@ -453,7 +174,8 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
{
hicn_data_fwd_trace_t *t =
vlib_add_trace (vm, node, h1, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_CONTENT;
+ t->face = face1;
+ t->pkt_type = HICN_PACKET_TYPE_DATA;
t->sw_if_index = vnet_buffer (h1)->sw_if_index[VLIB_RX];
t->next_index = next1;
clib_memcpy (t->packet_data, vlib_buffer_get_current (h1),
@@ -470,7 +192,8 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
u32 hi0;
hicn_face_id_t face0;
- face0 = hicn_face_db_get_dpo_face (i++, &pitp->u.pit.faces);
+ face0 = hicn_pcs_entry_pit_get_dpo_face (pitp, i);
+ i += 1;
h0 = vlib_get_buffer (vm, clones[0]);
@@ -481,7 +204,7 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
clones += 1;
next0 = isv6 ? HICN_DATA_FWD_NEXT_IFACE6_OUT :
- HICN_DATA_FWD_NEXT_IFACE4_OUT;
+ HICN_DATA_FWD_NEXT_IFACE4_OUT;
vnet_buffer (h0)->ip.adj_index[VLIB_TX] = face0;
stats->pkts_data_count++;
@@ -491,7 +214,8 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
{
hicn_data_fwd_trace_t *t =
vlib_add_trace (vm, node, h0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_CONTENT;
+ t->face = face0;
+ t->pkt_type = HICN_PACKET_TYPE_DATA;
t->sw_if_index = vnet_buffer (h0)->sw_if_index[VLIB_RX];
t->next_index = next0;
clib_memcpy (t->packet_data, vlib_buffer_get_current (h0),
@@ -531,39 +255,27 @@ hicn_satisfy_faces (vlib_main_t *vm, u32 bi0, hicn_pcs_entry_t *pitp,
}
always_inline void
-clone_data_to_cs (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *pitp, hicn_header_t *hicn0, f64 tnow,
- hicn_hash_node_t *nodep, vlib_buffer_t *b0,
- hicn_hash_entry_t *hash_entry, u64 name_hash,
- hicn_buffer_t *hicnb, const hicn_dpo_vft_t *dpo_vft,
- dpo_id_t *hicn_dpo_id, hicn_lifetime_t dmsg_lifetime)
+clone_data_to_cs (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *pcs_entry,
+ u32 buffer_index, f64 tnow, hicn_lifetime_t dmsg_lifetime)
{
/*
* At this point we think we're safe to proceed. Store the CS buf in
* the PIT/CS hashtable entry
*/
- /*
- * Start turning the PIT into a CS. Note that we may be stepping on
- * the PIT part of the union as we update the CS part, so don't
- * expect the PIT part to be valid after this point.
- */
- hicn_buffer_t *hicnb0 = hicn_get_buffer (b0);
- hicn_pit_to_cs (vm, pitcs, pitp, hash_entry, nodep, dpo_vft, hicn_dpo_id,
- hicnb->face_id,
- hicnb0->flags & HICN_BUFFER_FLAGS_FACE_IS_APP);
-
- pitp->shared.create_time = tnow;
+ // Start turning the PIT into a CS. Note that we may be stepping on the PIT
+ // part of the union as we update the CS part, so don't expect the PIT part
+ // to be valid after this point.
+ hicn_pit_to_cs (pitcs, pcs_entry, buffer_index);
+ hicn_pcs_entry_set_create_time (pcs_entry, tnow);
if (dmsg_lifetime < HICN_PARAM_CS_LIFETIME_MIN ||
dmsg_lifetime > HICN_PARAM_CS_LIFETIME_MAX)
{
dmsg_lifetime = HICN_PARAM_CS_LIFETIME_DFLT;
}
- pitp->shared.expire_time = hicn_pcs_get_exp_time (tnow, dmsg_lifetime);
-
- /* Store the original packet buffer in the CS node */
- pitp->u.cs.cs_pkt_buf = vlib_get_buffer_index (vm, b0);
+ hicn_pcs_entry_set_expire_time (pcs_entry,
+ hicn_pcs_get_exp_time (tnow, dmsg_lifetime));
}
/* packet trace format function */
@@ -575,14 +287,220 @@ hicn_data_fwd_format_trace (u8 *s, va_list *args)
hicn_data_fwd_trace_t *t = va_arg (*args, hicn_data_fwd_trace_t *);
u32 indent = format_get_indent (s);
- s = format (s, "DATAFWD: pkt: %d, sw_if_index %d, next index %d\n",
- (int) t->pkt_type, t->sw_if_index, t->next_index);
+ s = format (s, "DATAFWD: pkt: %d, sw_if_index %d, next index %d, face %d\n",
+ (int) t->pkt_type, t->sw_if_index, t->next_index, t->face);
s = format (s, "%U%U", format_white_space, indent, format_ip6_header,
t->packet_data, sizeof (t->packet_data));
return (s);
}
+vlib_node_registration_t hicn_data_fwd_node;
+
+/*
+ * ICN forwarder node for interests: handling of Data delivered based on ACL.
+ * - 1 packet at a time - ipv4/tcp ipv6/tcp
+ */
+static uword
+hicn_data_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
+ vlib_frame_t *frame)
+{
+
+ u32 n_left_from, *from, *to_next;
+ hicn_data_fwd_next_t next_index;
+ hicn_data_fwd_runtime_t *rt;
+ vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
+ f64 tnow;
+ u32 data_received = 1;
+ vlib_buffer_t *b0;
+ u8 isv6;
+ u32 bi0;
+ u32 next0 = HICN_DATA_FWD_NEXT_ERROR_DROP;
+ hicn_buffer_t *hicnb0;
+ const hicn_strategy_vft_t *strategy_vft0 = NULL;
+ const hicn_dpo_vft_t *dpo_vft0;
+ u8 dpo_ctx_id0 = ~0;
+ u32 pcs_entry_id;
+ hicn_pcs_entry_t *pcs_entry = NULL;
+ hicn_lifetime_t dmsg_lifetime;
+ int ret = HICN_ERROR_NONE;
+
+ rt = vlib_node_get_runtime_data (vm, node->node_index);
+
+ if (PREDICT_FALSE (rt->pitcs == NULL))
+ {
+ rt->pitcs = &hicn_main.pitcs;
+ }
+
+ from = vlib_frame_vector_args (frame);
+ n_left_from = frame->n_vectors;
+ next_index = node->cached_next_index;
+
+ /* Capture time in vpp terms */
+ tnow = vlib_time_now (vm);
+
+ while (n_left_from > 0)
+ {
+ u32 n_left_to_next;
+ vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+ while (n_left_from > 0 && n_left_to_next > 0)
+ {
+ /* Prefetch for next iteration. */
+ if (n_left_from > 1)
+ {
+ vlib_buffer_t *b1;
+ b1 = vlib_get_buffer (vm, from[1]);
+ CLIB_PREFETCH (b1, 2 * CLIB_CACHE_LINE_BYTES, STORE);
+ }
+
+ // Dequeue a packet buffer. Do not copy the index in the next buffer,
+ // we'll do it later. The packet might be cloned, so the buffer to
+ // move to next must be the cloned one
+ bi0 = from[0];
+ from += 1;
+ n_left_from -= 1;
+
+ b0 = vlib_get_buffer (vm, bi0);
+
+ // Get hicn buffer and state
+ hicnb0 = hicn_get_buffer (b0);
+
+ hicn_get_internal_state (hicnb0, &pcs_entry_id, &strategy_vft0,
+ &dpo_vft0, &dpo_ctx_id0);
+
+ // Get PCS entry
+ pcs_entry =
+ hicn_pcs_entry_get_entry_from_index_safe (rt->pitcs, pcs_entry_id);
+
+ if (PREDICT_FALSE (pcs_entry == NULL))
+ {
+ drop_packet (vm, bi0, &n_left_to_next, &next0, &to_next,
+ &next_index, node);
+
+ goto end_processing;
+ }
+
+ isv6 = hicn_buffer_is_v6 (b0);
+
+ // If PCS entry is CS, drop the packet
+ if (PREDICT_FALSE (hicn_pcs_entry_is_cs (pcs_entry)))
+ {
+ drop_packet (vm, bi0, &n_left_to_next, &next0, &to_next,
+ &next_index, node);
+
+ goto end_processing;
+ }
+
+ // We are sure the entry is a PIT entry. Check whether it is expired.
+ if (tnow > hicn_pcs_entry_get_expire_time (pcs_entry))
+ {
+ // Entry expired. Release lock
+ hicn_pcs_entry_remove_lock (rt->pitcs, pcs_entry);
+
+ // Drop packet
+ drop_packet (vm, bi0, &n_left_to_next, &next0, &to_next,
+ &next_index, node);
+
+ // Update stats
+ stats.pit_expired_count++;
+
+ // Trace
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ hicn_data_fwd_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = HICN_PACKET_TYPE_DATA;
+ t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ t->next_index = next0;
+ clib_memcpy (t->packet_data, vlib_buffer_get_current (b0),
+ sizeof (t->packet_data));
+ }
+ }
+ else
+ {
+ // Update stats
+ data_received++;
+
+ /*
+ * We do not check if the data is coming from
+ * the outgoing interest face.
+ */
+
+ // Prepare the buffer for the cloning
+ ret =
+ hicn_satisfy_faces (vm, bi0, pcs_entry, &n_left_to_next,
+ &to_next, &next_index, node, isv6, &stats);
+
+ if (PREDICT_FALSE (ret != HICN_ERROR_NONE))
+ {
+ hicn_pcs_entry_remove_lock (rt->pitcs, pcs_entry);
+ continue;
+ }
+
+ // Call the strategy callback since the interest has been
+ // satisfied
+ strategy_vft0->hicn_receive_data (
+ dpo_ctx_id0, vnet_buffer (b0)->ip.adj_index[VLIB_RX]);
+
+ dmsg_lifetime = hicn_buffer_get_lifetime (b0);
+
+ if (dmsg_lifetime)
+ {
+ // Clone data packet in the content store and convert the PIT
+ // entry into a CS entry
+ clone_data_to_cs (rt->pitcs, pcs_entry, bi0, tnow,
+ dmsg_lifetime);
+ }
+ else
+ {
+ /*
+ * If the packet is copied and not cloned, we need to free
+ * the vlib_buffer
+ */
+ if (hicnb0->flags & HICN_BUFFER_FLAGS_PKT_LESS_TWO_CL)
+ {
+ vlib_buffer_free_one (vm, bi0);
+ }
+ else
+ {
+ /*
+ * Remove one reference as the buffer is no
+ * longer in any frame. The vlib_buffer will be freed
+ * when all its cloned vlib_buffer will be freed.
+ */
+ b0->ref_count--;
+ }
+ // Delete the PIT entry
+ hicn_pcs_entry_remove_lock (rt->pitcs, pcs_entry);
+ }
+ }
+ end_processing:
+
+ /* Incr packet counter */
+ stats.pkts_processed += 1;
+ }
+
+ vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+ }
+ u32 pit_int_count = hicn_pcs_get_pit_count (rt->pitcs);
+ u32 pit_cs_count = hicn_pcs_get_cs_count (rt->pitcs);
+
+ vlib_node_increment_counter (vm, hicn_data_fwd_node.index,
+ HICNFWD_ERROR_DATAS, stats.pkts_data_count);
+
+ update_node_counter (vm, hicn_data_fwd_node.index, HICNFWD_ERROR_INT_COUNT,
+ pit_int_count);
+ update_node_counter (vm, hicn_data_fwd_node.index, HICNFWD_ERROR_CS_COUNT,
+ pit_cs_count);
+ update_node_counter (vm, hicn_data_fwd_node.index,
+ HICNFWD_ERROR_INTEREST_AGG_ENTRY,
+ stats.pkts_data_count / data_received);
+
+ return (frame->n_vectors);
+}
+
/*
* Node registration for the data forwarder node
*/
diff --git a/hicn-plugin/src/data_input_node.c b/hicn-plugin/src/data_input_node.c
index c94443a6b..a91f9156d 100644
--- a/hicn-plugin/src/data_input_node.c
+++ b/hicn-plugin/src/data_input_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -75,6 +75,35 @@ format_hicn_data_input_trace (u8 *s, va_list *args)
return s;
}
+static void
+hicn_data_input_set_adj_index (vlib_buffer_t *b,
+ const ip46_address_t *dst_addr,
+ const hicn_dpo_ctx_t *dpo_ctx)
+{
+ CLIB_UNUSED (u8 set) = 0;
+ u32 *adj_index = &vnet_buffer (b)->ip.adj_index[VLIB_RX];
+
+ if (*adj_index != ADJ_INDEX_INVALID)
+ {
+ return;
+ }
+
+ for (u8 pos = 0; pos < dpo_ctx->entry_count; pos++)
+ {
+ hicn_face_t *face = hicn_dpoi_get_from_idx (dpo_ctx->next_hops[pos]);
+ assert (face);
+
+ if (ip46_address_cmp (&(face->nat_addr), dst_addr) == 0)
+ {
+ *adj_index = face->dpo.dpoi_index;
+ set = 1;
+ break;
+ }
+ }
+
+ ASSERT (set == 1);
+}
+
static uword
hicn_data_input_ip6_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
vlib_frame_t *frame)
@@ -84,6 +113,15 @@ hicn_data_input_ip6_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
u32 n_left_from, n_left_to_next, *from, *to_next;
ip_lookup_next_t next;
u32 thread_index = vm->thread_index;
+ vlib_buffer_t *p0, *p1;
+ u32 pi0, pi1, lbi0, lbi1, wrong_next;
+ ip_lookup_next_t next0, next1;
+ ip6_header_t *ip0, *ip1;
+ ip6_address_t *src_addr0, *src_addr1;
+ ip46_address_t dst_addr0, dst_addr1;
+ const dpo_id_t *dpo0, *dpo1;
+ const load_balance_t *lb0, *lb1;
+ hicn_buffer_t *hicnb0, *hicnb1;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
@@ -95,14 +133,6 @@ hicn_data_input_ip6_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
while (n_left_from >= 4 && n_left_to_next >= 2)
{
- vlib_buffer_t *p0, *p1;
- u32 pi0, pi1, lbi0, lbi1, wrong_next;
- ip_lookup_next_t next0, next1;
- ip6_header_t *ip0, *ip1;
- ip6_address_t *src_addr0, *src_addr1;
- const dpo_id_t *dpo0, *dpo1;
- const load_balance_t *lb0, *lb1;
-
/* Prefetch next iteration. */
{
vlib_buffer_t *p2, *p3;
@@ -122,12 +152,18 @@ hicn_data_input_ip6_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
p0 = vlib_get_buffer (vm, pi0);
p1 = vlib_get_buffer (vm, pi1);
+ hicnb0 = hicn_get_buffer (p0);
+ hicnb1 = hicn_get_buffer (p1);
+
ip0 = vlib_buffer_get_current (p0);
ip1 = vlib_buffer_get_current (p1);
src_addr0 = &ip0->src_address;
src_addr1 = &ip1->src_address;
+ ip46_address_set_ip6 (&dst_addr0, &ip0->dst_address);
+ ip46_address_set_ip6 (&dst_addr1, &ip1->dst_address);
+
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, p0);
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, p1);
@@ -150,14 +186,24 @@ hicn_data_input_ip6_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
dpo1 = load_balance_get_bucket_i (lb1, 0);
if (dpo_is_hicn (dpo0))
- next0 = HICN_DATA_INPUT_IP6_NEXT_FACE;
+ {
+ next0 = (ip_lookup_next_t) HICN_DATA_INPUT_IP6_NEXT_FACE;
+ hicnb0->dpo_ctx_id = dpo0->dpoi_index;
+ hicn_data_input_set_adj_index (
+ p0, &dst_addr0, hicn_strategy_dpo_ctx_get (dpo0->dpoi_index));
+ }
else
- next0 = HICN_DATA_INPUT_IP6_NEXT_IP6_LOCAL;
+ next0 = (ip_lookup_next_t) HICN_DATA_INPUT_IP6_NEXT_IP6_LOCAL;
if (dpo_is_hicn (dpo1))
- next1 = HICN_DATA_INPUT_IP6_NEXT_FACE;
+ {
+ next1 = (ip_lookup_next_t) HICN_DATA_INPUT_IP6_NEXT_FACE;
+ hicnb1->dpo_ctx_id = dpo1->dpoi_index;
+ hicn_data_input_set_adj_index (
+ p1, &dst_addr1, hicn_strategy_dpo_ctx_get (dpo1->dpoi_index));
+ }
else
- next1 = HICN_DATA_INPUT_IP6_NEXT_IP6_LOCAL;
+ next1 = (ip_lookup_next_t) HICN_DATA_INPUT_IP6_NEXT_IP6_LOCAL;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
(p0->flags & VLIB_BUFFER_IS_TRACED))
@@ -234,15 +280,19 @@ hicn_data_input_ip6_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
u32 pi0, lbi0;
ip_lookup_next_t next0;
load_balance_t *lb0;
+ hicn_buffer_t *hicnb0;
ip6_address_t *src_addr0;
+ ip46_address_t dst_addr0;
const dpo_id_t *dpo0;
pi0 = from[0];
to_next[0] = pi0;
p0 = vlib_get_buffer (vm, pi0);
+ hicnb0 = hicn_get_buffer (p0);
ip0 = vlib_buffer_get_current (p0);
src_addr0 = &ip0->src_address;
+ ip46_address_set_ip6 (&dst_addr0, &ip0->dst_address);
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, p0);
lbi0 = ip6_fib_table_fwding_lookup (vnet_buffer (p0)->ip.fib_index,
src_addr0);
@@ -255,9 +305,14 @@ hicn_data_input_ip6_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
dpo0 = load_balance_get_bucket_i (lb0, 0);
if (dpo_is_hicn (dpo0))
- next0 = HICN_DATA_INPUT_IP6_NEXT_FACE;
+ {
+ next0 = (ip_lookup_next_t) HICN_DATA_INPUT_IP6_NEXT_FACE;
+ hicn_data_input_set_adj_index (
+ p0, &dst_addr0, hicn_strategy_dpo_ctx_get (dpo0->dpoi_index));
+ hicnb0->dpo_ctx_id = dpo0->dpoi_index;
+ }
else
- next0 = HICN_DATA_INPUT_IP6_NEXT_IP6_LOCAL;
+ next0 = (ip_lookup_next_t) HICN_DATA_INPUT_IP6_NEXT_IP6_LOCAL;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
(p0->flags & VLIB_BUFFER_IS_TRACED))
@@ -312,7 +367,7 @@ VLIB_REGISTER_NODE (hicn_data_input_ip6) = {
VNET_FEATURE_INIT (hicn_data_input_ip6_arc, static) = {
.arc_name = "ip6-local",
.node_name = "hicn-data-input-ip6",
- .runs_before = VNET_FEATURES ("ip6-local-end-of-arc"),
+ .runs_before = VNET_FEATURES ("ip6-local-end-of-arc")
};
always_inline uword
@@ -326,6 +381,13 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
vlib_buffer_t *bufs[VLIB_FRAME_SIZE];
vlib_buffer_t **b = bufs;
u16 nexts[VLIB_FRAME_SIZE], *next;
+ ip4_header_t *ip0, *ip1, *ip2, *ip3;
+ const load_balance_t *lb0, *lb1, *lb2, *lb3;
+ ip4_address_t *src_addr0, *src_addr1, *src_addr2, *src_addr3;
+ ip46_address_t dst_addr0, dst_addr1, dst_addr2, dst_addr3;
+ u32 lb_index0, lb_index1, lb_index2, lb_index3;
+ const dpo_id_t *dpo0, *dpo1, *dpo2, *dpo3;
+ hicn_buffer_t *hicnb0, *hicnb1, *hicnb2, *hicnb3;
from = vlib_frame_vector_args (frame);
n_left = frame->n_vectors;
@@ -335,14 +397,6 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
#if (CLIB_N_PREFETCHES >= 8)
while (n_left >= 4)
{
- ip4_header_t *ip0, *ip1, *ip2, *ip3;
- const load_balance_t *lb0, *lb1, *lb2, *lb3;
- ip4_fib_mtrie_t *mtrie0, *mtrie1, *mtrie2, *mtrie3;
- ip4_fib_mtrie_leaf_t leaf0, leaf1, leaf2, leaf3;
- ip4_address_t *src_addr0, *src_addr1, *src_addr2, *src_addr3;
- u32 lb_index0, lb_index1, lb_index2, lb_index3;
- const dpo_id_t *dpo0, *dpo1, *dpo2, *dpo3;
-
/* Prefetch next iteration. */
if (n_left >= 8)
{
@@ -362,40 +416,31 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
ip2 = vlib_buffer_get_current (b[2]);
ip3 = vlib_buffer_get_current (b[3]);
+ hicnb0 = hicn_get_buffer (b[0]);
+ hicnb1 = hicn_get_buffer (b[1]);
+ hicnb2 = hicn_get_buffer (b[2]);
+ hicnb3 = hicn_get_buffer (b[3]);
+
src_addr0 = &ip0->src_address;
src_addr1 = &ip1->src_address;
src_addr2 = &ip2->src_address;
src_addr3 = &ip3->src_address;
+ ip46_address_set_ip4 (&dst_addr0, &ip0->dst_address);
+ ip46_address_set_ip4 (&dst_addr1, &ip1->dst_address);
+ ip46_address_set_ip4 (&dst_addr2, &ip2->dst_address);
+ ip46_address_set_ip4 (&dst_addr3, &ip3->dst_address);
+
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, b[0]);
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, b[1]);
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, b[2]);
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, b[3]);
- mtrie0 = &ip4_fib_get (vnet_buffer (b[0])->ip.fib_index)->mtrie;
- mtrie1 = &ip4_fib_get (vnet_buffer (b[1])->ip.fib_index)->mtrie;
- mtrie2 = &ip4_fib_get (vnet_buffer (b[2])->ip.fib_index)->mtrie;
- mtrie3 = &ip4_fib_get (vnet_buffer (b[3])->ip.fib_index)->mtrie;
-
- leaf0 = ip4_fib_mtrie_lookup_step_one (mtrie0, src_addr0);
- leaf1 = ip4_fib_mtrie_lookup_step_one (mtrie1, src_addr1);
- leaf2 = ip4_fib_mtrie_lookup_step_one (mtrie2, src_addr2);
- leaf3 = ip4_fib_mtrie_lookup_step_one (mtrie3, src_addr3);
-
- leaf0 = ip4_fib_mtrie_lookup_step (mtrie0, leaf0, src_addr0, 2);
- leaf1 = ip4_fib_mtrie_lookup_step (mtrie1, leaf1, src_addr1, 2);
- leaf2 = ip4_fib_mtrie_lookup_step (mtrie2, leaf2, src_addr2, 2);
- leaf3 = ip4_fib_mtrie_lookup_step (mtrie3, leaf3, src_addr3, 2);
-
- leaf0 = ip4_fib_mtrie_lookup_step (mtrie0, leaf0, src_addr0, 3);
- leaf1 = ip4_fib_mtrie_lookup_step (mtrie1, leaf1, src_addr1, 3);
- leaf2 = ip4_fib_mtrie_lookup_step (mtrie2, leaf2, src_addr2, 3);
- leaf3 = ip4_fib_mtrie_lookup_step (mtrie3, leaf3, src_addr3, 3);
-
- lb_index0 = ip4_fib_mtrie_leaf_get_adj_index (leaf0);
- lb_index1 = ip4_fib_mtrie_leaf_get_adj_index (leaf1);
- lb_index2 = ip4_fib_mtrie_leaf_get_adj_index (leaf2);
- lb_index3 = ip4_fib_mtrie_leaf_get_adj_index (leaf3);
+ ip4_fib_forwarding_lookup_x4 (
+ vnet_buffer (b[0])->ip.fib_index, vnet_buffer (b[1])->ip.fib_index,
+ vnet_buffer (b[2])->ip.fib_index, vnet_buffer (b[3])->ip.fib_index,
+ src_addr0, src_addr1, src_addr2, src_addr3, &lb_index0, &lb_index1,
+ &lb_index2, &lb_index3);
ASSERT (lb_index0 && lb_index1 && lb_index2 && lb_index3);
lb0 = load_balance_get (lb_index0);
@@ -418,22 +463,42 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
dpo3 = load_balance_get_bucket_i (lb3, 0);
if (dpo_is_hicn (dpo0))
- next[0] = HICN_DATA_INPUT_IP4_NEXT_FACE;
+ {
+ next[0] = (ip_lookup_next_t) HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
+ hicnb0->dpo_ctx_id = dpo0->dpoi_index;
+ hicn_data_input_set_adj_index (
+ b[0], &dst_addr0, hicn_strategy_dpo_ctx_get (dpo0->dpoi_index));
+ }
else
next[0] = HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
if (dpo_is_hicn (dpo1))
- next[1] = HICN_DATA_INPUT_IP4_NEXT_FACE;
+ {
+ next[1] = (ip_lookup_next_t) HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
+ hicnb1->dpo_ctx_id = dpo1->dpoi_index;
+ hicn_data_input_set_adj_index (
+ b[1], &dst_addr1, hicn_strategy_dpo_ctx_get (dpo1->dpoi_index));
+ }
else
next[1] = HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
if (dpo_is_hicn (dpo2))
- next[2] = HICN_DATA_INPUT_IP4_NEXT_FACE;
+ {
+ next[2] = (ip_lookup_next_t) HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
+ hicnb2->dpo_ctx_id = dpo2->dpoi_index;
+ hicn_data_input_set_adj_index (
+ b[2], &dst_addr2, hicn_strategy_dpo_ctx_get (dpo2->dpoi_index));
+ }
else
next[2] = HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
if (dpo_is_hicn (dpo3))
- next[3] = HICN_DATA_INPUT_IP4_NEXT_FACE;
+ {
+ next[3] = (ip_lookup_next_t) HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
+ hicnb3->dpo_ctx_id = dpo3->dpoi_index;
+ hicn_data_input_set_adj_index (
+ b[3], &dst_addr3, hicn_strategy_dpo_ctx_get (dpo3->dpoi_index));
+ }
else
next[3] = HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
@@ -493,16 +558,6 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
#elif (CLIB_N_PREFETCHES >= 4)
while (n_left >= 4)
{
- ip4_header_t *ip0, *ip1;
- const load_balance_t *lb0, *lb1;
- ip4_fib_mtrie_t *mtrie0, *mtrie1;
- ip4_fib_mtrie_leaf_t leaf0, leaf1;
- ip4_address_t *src_addr0, *src_addr1;
- u32 lb_index0, lb_index1;
- flow_hash_config_t flow_hash_config0, flow_hash_config1;
- u32 hash_c0, hash_c1;
- const dpo_id_t *dpo0, *dpo1;
-
/* Prefetch next iteration. */
{
vlib_prefetch_buffer_header (b[2], LOAD);
@@ -515,26 +570,21 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
ip0 = vlib_buffer_get_current (b[0]);
ip1 = vlib_buffer_get_current (b[1]);
+ hicnb0 = hicn_get_buffer (b[0]);
+ hicnb1 = hicn_get_buffer (b[1]);
+
src_addr0 = &ip0->src_address;
src_addr1 = &ip1->src_address;
+ ip46_address_set_ip4 (&dst_addr0, &ip0->dst_address);
+ ip46_address_set_ip4 (&dst_addr1, &ip1->dst_address);
+
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, b[0]);
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, b[1]);
- mtrie0 = &ip4_fib_get (vnet_buffer (b[0])->ip.fib_index)->mtrie;
- mtrie1 = &ip4_fib_get (vnet_buffer (b[1])->ip.fib_index)->mtrie;
-
- leaf0 = ip4_fib_mtrie_lookup_step_one (mtrie0, src_addr0);
- leaf1 = ip4_fib_mtrie_lookup_step_one (mtrie1, src_addr1);
-
- leaf0 = ip4_fib_mtrie_lookup_step (mtrie0, leaf0, src_addr0, 2);
- leaf1 = ip4_fib_mtrie_lookup_step (mtrie1, leaf1, src_addr1, 2);
-
- leaf0 = ip4_fib_mtrie_lookup_step (mtrie0, leaf0, src_addr0, 3);
- leaf1 = ip4_fib_mtrie_lookup_step (mtrie1, leaf1, src_addr1, 3);
-
- lb_index0 = ip4_fib_mtrie_leaf_get_adj_index (leaf0);
- lb_index1 = ip4_fib_mtrie_leaf_get_adj_index (leaf1);
+ ip4_fib_forwarding_lookup_x2 (
+ vnet_buffer (b[0])->ip.fib_index, vnet_buffer (b[1])->ip.fib_index,
+ src_addr0, src_addr1, &lb_index0, &lb_index1);
ASSERT (lb_index0 && lb_index1);
lb0 = load_balance_get (lb_index0);
@@ -549,12 +599,22 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
dpo1 = load_balance_get_bucket_i (lb1, 0);
if (dpo_is_hicn (dpo0))
- next[0] = HICN_DATA_INPUT_IP4_NEXT_FACE;
+ {
+ next[0] = (ip_lookup_next_t) HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
+ hicnb0->dpo_ctx_id = dpo0->dpoi_index;
+ hicn_data_input_set_adj_index (
+ b[0], &dst_addr0, hicn_strategy_dpo_ctx_get (dpo0->dpoi_index));
+ }
else
next[0] = HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
if (dpo_is_hicn (dpo1))
- next[1] = HICN_DATA_INPUT_IP4_NEXT_FACE;
+ {
+ next[1] = (ip_lookup_next_t) HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
+ hicnb1->dpo_ctx_id = dpo1->dpoi_index;
+ hicn_data_input_set_adj_index (
+ b[1], &dst_addr1, hicn_strategy_dpo_ctx_get (dpo1->dpoi_index));
+ }
else
next[1] = HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
@@ -590,26 +650,17 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
#endif
while (n_left > 0)
{
- ip4_header_t *ip0;
- const load_balance_t *lb0;
- ip4_fib_mtrie_t *mtrie0;
- ip4_fib_mtrie_leaf_t leaf0;
- ip4_address_t *src_addr0;
- u32 lbi0;
- const dpo_id_t *dpo0;
-
ip0 = vlib_buffer_get_current (b[0]);
+ hicnb0 = hicn_get_buffer (b[0]);
src_addr0 = &ip0->src_address;
+ ip46_address_set_ip4 (&dst_addr0, &ip0->dst_address);
ip_lookup_set_buffer_fib_index (im->fib_index_by_sw_if_index, b[0]);
- mtrie0 = &ip4_fib_get (vnet_buffer (b[0])->ip.fib_index)->mtrie;
- leaf0 = ip4_fib_mtrie_lookup_step_one (mtrie0, src_addr0);
- leaf0 = ip4_fib_mtrie_lookup_step (mtrie0, leaf0, src_addr0, 2);
- leaf0 = ip4_fib_mtrie_lookup_step (mtrie0, leaf0, src_addr0, 3);
- lbi0 = ip4_fib_mtrie_leaf_get_adj_index (leaf0);
+ lb_index0 = ip4_fib_forwarding_lookup (vnet_buffer (b[0])->ip.fib_index,
+ src_addr0);
- ASSERT (lbi0);
- lb0 = load_balance_get (lbi0);
+ ASSERT (lb_index0);
+ lb0 = load_balance_get (lb_index0);
ASSERT (lb0->lb_n_buckets > 0);
ASSERT (is_pow2 (lb0->lb_n_buckets));
@@ -617,7 +668,12 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
dpo0 = load_balance_get_bucket_i (lb0, 0);
if (dpo_is_hicn (dpo0))
- next[0] = HICN_DATA_INPUT_IP4_NEXT_FACE;
+ {
+ next[0] = (ip_lookup_next_t) HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
+ hicnb0->dpo_ctx_id = dpo0->dpoi_index;
+ hicn_data_input_set_adj_index (
+ b[0], &dst_addr0, hicn_strategy_dpo_ctx_get (dpo0->dpoi_index));
+ }
else
next[0] = HICN_DATA_INPUT_IP4_NEXT_IP4_LOCAL;
@@ -631,7 +687,7 @@ hicn_data_input_ip4_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
t->isv6 = 0;
}
- vlib_increment_combined_counter (cm, thread_index, lbi0, 1,
+ vlib_increment_combined_counter (cm, thread_index, lb_index0, 1,
vlib_buffer_length_in_chain (vm, b[0]));
b += 1;
@@ -665,4 +721,4 @@ VNET_FEATURE_INIT (hicn_data_input_ip4_arc, static) = {
.arc_name = "ip4-local",
.node_name = "hicn-data-input-ip4",
.runs_before = VNET_FEATURES ("ip4-local-end-of-arc"),
-};
+}; \ No newline at end of file
diff --git a/hicn-plugin/src/data_pcslookup.h b/hicn-plugin/src/data_pcslookup.h
index b548497b6..32fca952a 100644
--- a/hicn-plugin/src/data_pcslookup.h
+++ b/hicn-plugin/src/data_pcslookup.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/data_pcslookup_node.c b/hicn-plugin/src/data_pcslookup_node.c
index 073d06c96..5ae6958f5 100644
--- a/hicn-plugin/src/data_pcslookup_node.c
+++ b/hicn-plugin/src/data_pcslookup_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -44,6 +44,12 @@ hicn_data_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
hicn_data_pcslookup_next_t next_index;
hicn_data_pcslookup_runtime_t *rt;
vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
+ vlib_buffer_t *b0;
+ u32 bi0;
+ u32 next0 = HICN_DATA_PCSLOOKUP_NEXT_ERROR_DROP;
+ hicn_pcs_entry_t *pcs_entry = NULL;
+ hicn_buffer_t *hicnb0;
+ int ret;
rt = vlib_node_get_runtime_data (vm, node->node_index);
@@ -62,25 +68,7 @@ hicn_data_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
while (n_left_from > 0 && n_left_to_next > 0)
{
- vlib_buffer_t *b0;
- u8 isv6;
- u8 *nameptr;
- u16 namelen;
- u32 bi0;
- u32 next0 = HICN_DATA_PCSLOOKUP_NEXT_ERROR_DROP;
- u64 name_hash = 0;
- hicn_name_t name;
- hicn_header_t *hicn0 = NULL;
- u32 node_id0 = 0;
- index_t dpo_ctx_id0 = 0;
- int ret0;
- u8 vft_id0;
- u8 is_cs0;
- u8 hash_entry_id = 0;
- u8 bucket_is_overflown = 0;
- u32 bucket_id = ~0;
-
- /* Prefetch for next iteration. */
+ // Prefetch for next iteration.
if (n_left_from > 1)
{
vlib_buffer_t *b1;
@@ -88,9 +76,9 @@ hicn_data_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
// Prefetch two cache lines-- 128 byte-- so that we load the
// hicn_buffer_t as well
CLIB_PREFETCH (b1, 2 * CLIB_CACHE_LINE_BYTES, STORE);
- CLIB_PREFETCH (b1->data, CLIB_CACHE_LINE_BYTES, LOAD);
}
- /* Dequeue a packet buffer */
+
+ // Dequeue a packet buffer
bi0 = from[0];
from += 1;
n_left_from -= 1;
@@ -99,44 +87,35 @@ hicn_data_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
+ hicnb0 = hicn_get_buffer (b0);
+
+ // By default go to drop
next0 = HICN_DATA_PCSLOOKUP_NEXT_ERROR_DROP;
- /* Incr packet counter */
+ // Increase packet counters
stats.pkts_processed += 1;
+ stats.pkts_data_count += 1;
- ret0 = hicn_data_parse_pkt (b0, &name, &namelen, &hicn0, &isv6);
- nameptr = (u8 *) (&name);
+ // Lookup the name in the PIT
+ hicn_name_t name;
+ hicn_packet_get_name (&hicn_get_buffer (b0)->pkbuf, &name);
+ ret = hicn_pcs_lookup_one (rt->pitcs, &name, &pcs_entry);
- if (PREDICT_TRUE (
- ret0 == HICN_ERROR_NONE &&
- hicn_hashtb_fullhash (nameptr, namelen, &name_hash) ==
- HICN_ERROR_NONE))
+ if (ret == HICN_ERROR_NONE)
{
- int res = hicn_hashtb_lookup_node (
- rt->pitcs->pcs_table, nameptr, namelen, name_hash,
- 1
- /*is_data. Do not take lock if hit CS */
- ,
- &node_id0, &dpo_ctx_id0, &vft_id0, &is_cs0, &hash_entry_id,
- &bucket_id, &bucket_is_overflown);
-
- stats.pkts_data_count += 1;
-
- if (res == HICN_ERROR_NONE)
- {
- /*
- * In case the result of the lookup
- * is a CS entry, the packet is
- * dropped
- */
- next0 = HICN_DATA_PCSLOOKUP_NEXT_DATA_FWD + is_cs0;
- }
+ ret = hicn_store_internal_state (
+ b0, hicn_pcs_entry_get_index (rt->pitcs, pcs_entry),
+ hicnb0->dpo_ctx_id);
+
+ /*
+ * In case the result of the lookup
+ * is a CS entry, the packet is
+ * dropped
+ */
+ next0 = HICN_DATA_PCSLOOKUP_NEXT_DATA_FWD +
+ (hicn_pcs_entry_is_cs (pcs_entry) && !ret);
}
- hicn_store_internal_state (b0, name_hash, node_id0, dpo_ctx_id0,
- vft_id0, hash_entry_id, bucket_id,
- bucket_is_overflown);
-
/*
* Verify speculative enqueue, maybe switch current
* next frame
@@ -154,16 +133,18 @@ hicn_data_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
{
hicn_data_pcslookup_trace_t *t =
vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_CONTENT;
+ t->pkt_type = HICN_PACKET_TYPE_DATA;
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
t->next_index = next0;
}
}
+
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
+
/* Check the CS LRU, and trim if necessary. */
- u32 pit_int_count = hicn_pit_get_int_count (rt->pitcs);
- u32 pit_cs_count = hicn_pit_get_cs_count (rt->pitcs);
+ u32 pit_int_count = hicn_pcs_get_pit_count (rt->pitcs);
+ u32 pit_cs_count = hicn_pcs_get_cs_count (rt->pitcs);
vlib_node_increment_counter (vm, hicn_data_pcslookup_node.index,
HICNFWD_ERROR_PROCESSED, stats.pkts_processed);
@@ -175,6 +156,7 @@ hicn_data_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
HICNFWD_ERROR_INT_COUNT, pit_int_count);
update_node_counter (vm, hicn_data_pcslookup_node.index,
HICNFWD_ERROR_CS_COUNT, pit_cs_count);
+
return (frame->n_vectors);
}
diff --git a/hicn-plugin/src/error.c b/hicn-plugin/src/error.c
index 4c6986999..a64066d67 100644
--- a/hicn-plugin/src/error.c
+++ b/hicn-plugin/src/error.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,7 +13,7 @@
* limitations under the License.
*/
-#include "error.h"
+#include <vpp_plugins/hicn/error.h>
const char *HICN_ERROR_STRING[] = {
#define _(a, b, c) c,
diff --git a/hicn-plugin/src/error.h b/hicn-plugin/src/error.h
deleted file mode 100644
index b33a1b50d..000000000
--- a/hicn-plugin/src/error.h
+++ /dev/null
@@ -1,108 +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.
- */
-
-#ifndef __HICN_ERROR_H__
-#define __HICN_ERROR_H__
-
-/**
- * @file error.h
- *
- * Error codes for the hICN plugin.
- */
-
-#define foreach_hicn_error \
- _ (NONE, 0, "Ok") \
- _ (UNSPECIFIED, -128, "Unspecified Error") \
- _ (FACE_NOT_FOUND, -129, "Face not found in Face table") \
- _ (FACE_NULL, -130, "Face null") \
- _ (FACE_IP_ADJ_NOT_FOUND, -131, "Ip adjacecny for face not found") \
- _ (FACE_HW_INT_NOT_FOUND, -132, "Hardware interface not found") \
- _ (FACE_NOMEM, -133, "Face table is full") \
- _ (FACE_NO_GLOBAL_IP, -134, "No global ip address for face") \
- _ (FACE_NOT_FOUND_IN_ENTRY, -135, "Face not found in entry") \
- _ (FACE_ALREADY_DELETED, -136, "Face alredy deleted") \
- _ (FACE_ALREADY_CREATED, -137, "Face alredy created") \
- _ (FWD_NOT_ENABLED, -138, "hICN forwarder not enabled") \
- _ (FWD_ALREADY_ENABLED, -139, "hICN forwarder alredy enabled") \
- _ (PARSER_UNSUPPORTED_PROTO, -140, "Unsupported protocol") \
- _ (PARSER_PKT_INVAL, -141, "Packet null") \
- _ (PIT_CONFIG_MINLT_OOB, -142, "Min lifetime ouf of bounds") \
- _ (PIT_CONFIG_MAXLT_OOB, -143, "Max lifetime ouf of bounds") \
- _ (PIT_CONFIG_MINMAXLT, -144, "Min lifetime grater than max lifetime") \
- _ (PIT_CONFIG_DFTLT_OOB, -145, "Default lifetime ouf of bounds") \
- _ (PIT_CONFIG_SIZE_OOB, -146, "Pit size ouf of bounds") \
- _ (CS_CONFIG_SIZE_OOB, -147, "CS size ouf of bounds") \
- _ (CS_CONFIG_RESERVED_OOB, -148, \
- "Reseved CS must be between 0 and 100 (excluded)") \
- _ (DPO_CTX_NHOPS_NS, -149, "No space for additional next hop") \
- _ (DPO_CTX_NHOPS_EXISTS, -150, "Next hop already in the route") \
- _ (DPO_CTX_NOT_FOUND, -151, "Dpo context not found") \
- _ (DPO_MGR_ID_NOT_VALID, -152, "Dpo id for strategy and context not valid") \
- _ (HASHTB_HASH_NOT_FOUND, -153, "Hash not found in hash table") \
- _ (HASHTB_HASH_INVAL, -154, "Error while calculating the hash") \
- _ (HASHTB_NOMEM, -155, "Unable to allocate new buckets or nodes") \
- _ (HASHTB_INVAL, -156, "Invalid argument") \
- _ (HASHTB_KEY_INVAL, -157, "Invalid hashtb key") \
- _ (HASHTB_EXIST, -158, "Hash already in hashtable") \
- _ (ROUTE_INVAL, -159, "Invalid face id and weight") \
- _ (ROUTE_NO_LD, -160, "Expected load balance dpo") \
- _ (ROUTE_MLT_LD, -161, "Unexpected mulitple buckets in load balance dpo") \
- _ (ROUTE_NO_INSERT, -162, "Unable to insert a new FIB entry") \
- _ (ROUTE_DPO_NO_HICN, -163, "Dpo is not of type hICN") \
- _ (ROUTE_NOT_FOUND, -164, "Route not found in FIB") \
- _ (ROUTE_NOT_UPDATED, -165, "Unable to update route") \
- _ (ROUTE_ALREADY_EXISTS, -166, "Route already in FIB") \
- _ (CLI_INVAL, -167, "Invalid input") \
- _ (IPS_ADDR_TYPE_NONUNIFORM, -168, \
- "Src and dst addr have different ip types") \
- _ (FACE_TYPE_EXISTS, -169, "Face type already registered") \
- _ (NO_BUFFERS, -170, "No vlib_buffer available for packet cloning.") \
- _ (NOT_IMPLEMENTED, -171, "Function not yet implemented") \
- _ (IFACE_IP_ADJ_NOT_FOUND, -172, \
- "IP adjacency on incomplete face not available") \
- _ (APPFACE_ALREADY_ENABLED, -173, \
- "Application face already enabled on interface") \
- _ (APPFACE_FEATURE, -174, "Error while enabling app face feature") \
- _ (APPFACE_NOT_FOUND, -175, "Application face not found") \
- _ (APPFACE_PROD_PREFIX_NULL, -176, \
- "Prefix must not be null for producer face") \
- _ (STRATEGY_NH_NOT_FOUND, -177, "Next hop not found") \
- _ (MW_STRATEGY_SET, -178, "Error while setting weight for next hop") \
- _ (STRATEGY_NOT_FOUND, -179, "Strategy not found") \
- _ (UDP_TUNNEL_NOT_FOUND, -180, "Udp tunnel not found") \
- _ (UDP_TUNNEL_SRC_DST_TYPE, -181, \
- "Src and dst addresses have different type (ipv4 and ipv6)")
-
-typedef enum
-{
-#define _(a, b, c) HICN_ERROR_##a = (b),
- foreach_hicn_error
-#undef _
- HICN_N_ERROR,
-} hicn_error_t;
-
-extern const char *HICN_ERROR_STRING[];
-
-#define get_error_string(errno) \
- (char *) (errno ? HICN_ERROR_STRING[(-errno) - 127] : \
- HICN_ERROR_STRING[errno])
-
-#endif /* //__HICN_ERROR_H__ */
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables: eval: (c-set-style "gnu") End:
- */
diff --git a/hicn-plugin/src/face_db.h b/hicn-plugin/src/face_db.h
deleted file mode 100644
index 1bc061721..000000000
--- a/hicn-plugin/src/face_db.h
+++ /dev/null
@@ -1,152 +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.
- */
-
-#ifndef __HICN_FACE_DB_H__
-#define __HICN_FACE_DB_H__
-
-#include <vnet/dpo/dpo.h>
-#include "faces/face.h"
-
-/**
- * @file face_db.h
- *
- * Define a face db that is store in every pit entry. A face db containes a
- * list of incoming faces for interest packets that are used to forward data
- * packets on the interests' reverse path
- */
-
-/* Must be power of two */
-#define HICN_FACE_DB_INLINE_FACES 8
-
-#define HICN_PIT_BITMAP_SIZE_BYTE HICN_PARAM_FACES_MAX / 8
-#define HICN_PIT_N_HOP_BITMAP_SIZE HICN_PARAM_FACES_MAX
-
-#define HICN_PIT_N_HOP_BUCKET \
- (HICN_PARAM_PIT_ENTRY_PHOPS_MAX - HICN_FACE_DB_INLINE_FACES)
-
-typedef struct hicn_face_bucket_s
-{
- /* Array of indexes of virtual faces */
- hicn_face_id_t faces[HICN_PIT_N_HOP_BUCKET];
-
- /* Used to check if interests are retransmission */
- u8 bitmap[HICN_PIT_BITMAP_SIZE_BYTE];
-
-} hicn_face_bucket_t;
-
-extern hicn_face_bucket_t *hicn_face_bucket_pool;
-
-typedef struct __attribute__ ((packed)) hicn_face_db_s
-{
- /* 19B + 1B = 20B */
- /* Equal to one or zero */
- u8 is_overflow;
-
- /* Number of faces in the last bucket */
- /* Or next availabe entry for storing a dpo_id_t */
- /* 20B + 4B = 24B */
- u32 n_faces;
-
- /* 24B + 32B (8*4) = 56B */
- /* Array of indexes of virtual faces */
- hicn_face_id_t inline_faces[HICN_FACE_DB_INLINE_FACES];
-
- /* 56B + 4B = 60B */
- u32 next_bucket;
-
- /* 60B + 4B = 64B */
- u32 align;
- // align back to 64
-
-} hicn_face_db_t;
-
-always_inline hicn_face_id_t
-hicn_face_db_get_dpo_face (u32 index, hicn_face_db_t *face_db)
-{
- ASSERT (index < face_db->n_faces);
-
- return index < HICN_FACE_DB_INLINE_FACES ?
- (face_db->inline_faces[index]) :
- (pool_elt_at_index (hicn_face_bucket_pool, face_db->next_bucket)
- ->faces[(index - HICN_FACE_DB_INLINE_FACES) &
- (HICN_PIT_N_HOP_BUCKET - 1)]);
-}
-
-always_inline void
-hicn_face_db_init (int max_element)
-{
- pool_init_fixed (hicn_face_bucket_pool, max_element);
-}
-
-always_inline hicn_face_bucket_t *
-hicn_face_db_get_bucket (u32 bucket_index)
-{
- return pool_elt_at_index (hicn_face_bucket_pool, bucket_index);
-}
-
-always_inline void
-hicn_face_db_add_face (hicn_face_id_t face_id, hicn_face_db_t *face_db)
-{
- // ASSERT (dpo->dpoi_index != ~0);
-
- hicn_face_bucket_t *faces_bkt =
- pool_elt_at_index (hicn_face_bucket_pool, face_db->next_bucket);
-
- hicn_face_id_t *element =
- face_db->n_faces < HICN_FACE_DB_INLINE_FACES ?
- &(face_db->inline_faces[face_db->n_faces]) :
- &(faces_bkt->faces[(face_db->n_faces - HICN_FACE_DB_INLINE_FACES) &
- (HICN_PIT_N_HOP_BUCKET - 1)]);
-
- *element = face_id;
-
- u32 bitmap_index = face_id % HICN_PIT_N_HOP_BITMAP_SIZE;
- u32 position_array = bitmap_index / 8;
- u8 bit_index = (u8) (bitmap_index - position_array * 8);
-
- faces_bkt->bitmap[position_array] |= (0x01 << bit_index);
- face_db->n_faces++;
-}
-
-always_inline u8
-hicn_face_search (hicn_face_id_t index, hicn_face_db_t *face_db)
-{
- hicn_face_bucket_t *faces_bkt =
- pool_elt_at_index (hicn_face_bucket_pool, face_db->next_bucket);
- u32 bitmap_index = index % HICN_PIT_N_HOP_BITMAP_SIZE;
-
- u32 position_array = bitmap_index / 8;
- u8 bit_index = bitmap_index - position_array * 8;
-
- return (faces_bkt->bitmap[position_array] >> bit_index) & 0x01;
-}
-
-always_inline void
-hicn_faces_flush (hicn_face_db_t *face_db)
-{
- hicn_face_bucket_t *faces_bkt =
- pool_elt_at_index (hicn_face_bucket_pool, face_db->next_bucket);
- clib_memset_u8 (&(faces_bkt->bitmap), 0, HICN_PIT_BITMAP_SIZE_BYTE);
- face_db->n_faces = 0;
- pool_put_index (hicn_face_bucket_pool, face_db->next_bucket);
-}
-
-#endif /* // __HICN_FACE_DB_H__ */
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables: eval: (c-set-style "gnu") End:
- */
diff --git a/hicn-plugin/src/faces/app/address_mgr.c b/hicn-plugin/src/faces/app/address_mgr.c
index b5d8ce7cb..44729fd69 100644
--- a/hicn-plugin/src/faces/app/address_mgr.c
+++ b/hicn-plugin/src/faces/app/address_mgr.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,7 +14,7 @@
*/
/*
- * Copyright (c) 2017-2019 by cisco systems inc. All rights reserved.
+ * Copyright (c) 2021 by cisco systems inc. All rights reserved.
*
*/
@@ -31,10 +31,11 @@
#include <vnet/interface.h> //appif_flags
#include <vnet/interface_funcs.h> //vnet_sw_interface_set_flags
+#include <vpp_plugins/hicn/error.h>
+
#include "address_mgr.h"
#include "../../hicn.h"
#include "../../infra.h"
-#include "../../error.h"
#include "../face.h"
#include "../../strategy_dpo_ctx.h"
#include "../../route.h"
diff --git a/hicn-plugin/src/faces/app/address_mgr.h b/hicn-plugin/src/faces/app/address_mgr.h
index bd834f063..32545f8ca 100644
--- a/hicn-plugin/src/faces/app/address_mgr.h
+++ b/hicn-plugin/src/faces/app/address_mgr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/faces/app/face_app_cli.c b/hicn-plugin/src/faces/app/face_app_cli.c
index ccdee4450..50e6ae71b 100644
--- a/hicn-plugin/src/faces/app/face_app_cli.c
+++ b/hicn-plugin/src/faces/app/face_app_cli.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,8 +17,9 @@
#include <vnet/dpo/dpo.h>
#include <vlib/vlib.h>
#include <vnet/ip/ip6_packet.h>
+#include <vnet/ip/format.h>
-//#include "../face_dpo.h"
+#include "../../params.h"
#include "../face.h"
#include "face_prod.h"
#include "face_cons.h"
@@ -114,8 +115,8 @@ hicn_face_app_cli_set_command_fn (vlib_main_t *vm,
if (prod)
{
prefix.fp_proto = ip46_address_is_ip4 (&prefix.fp_addr) ?
- FIB_PROTOCOL_IP4 :
- FIB_PROTOCOL_IP6;
+ FIB_PROTOCOL_IP4 :
+ FIB_PROTOCOL_IP6;
rv = hicn_face_prod_add (&prefix, sw_if, &cs_reserved, &prod_addr,
&face_id1);
if (rv == HICN_ERROR_NONE)
@@ -175,8 +176,8 @@ hicn_face_app_cli_set_command_fn (vlib_main_t *vm,
break;
}
return (rv == HICN_ERROR_NONE) ?
- 0 :
- clib_error_return (0, "%s\n", get_error_string (rv));
+ 0 :
+ clib_error_return (0, "%s\n", get_error_string (rv));
}
/* cli declaration for 'cfg face' */
diff --git a/hicn-plugin/src/faces/app/face_cons.c b/hicn-plugin/src/faces/app/face_cons.c
index 53b955775..edb03387d 100644
--- a/hicn-plugin/src/faces/app/face_cons.c
+++ b/hicn-plugin/src/faces/app/face_cons.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -69,10 +69,10 @@ hicn_face_cons_add (ip4_address_t *nh_addr4, ip6_address_t *nh_addr6, u32 swif,
0 /* is_del */);
ip46_address_t nh_addr = to_ip46 (0, (u8 *) nh_addr6);
- index_t adj_index = adj_nbr_find (FIB_PROTOCOL_IP6, VNET_LINK_IP6, &nh_addr, swif);
+ index_t adj_index =
+ adj_nbr_find (FIB_PROTOCOL_IP6, VNET_LINK_IP6, &nh_addr, swif);
- hicn_iface_add ((ip46_address_t *) nh_addr6, swif, faceid2, DPO_PROTO_IP6,
- adj_index);
+ hicn_iface_add ((ip46_address_t *) nh_addr6, swif, faceid2, adj_index, 0);
hicn_face_t *face = hicn_dpoi_get_from_idx (*faceid2);
face->flags |= HICN_FACE_FLAGS_APPFACE_CONS;
@@ -90,7 +90,7 @@ hicn_face_cons_del (hicn_face_id_t face_id)
if (face->flags & HICN_FACE_FLAGS_APPFACE_CONS)
{
- return hicn_face_del (face_id);
+ return hicn_face_unlock_with_id (face_id);
}
else
{
diff --git a/hicn-plugin/src/faces/app/face_cons.h b/hicn-plugin/src/faces/app/face_cons.h
index 3ff246f4f..9df6f773f 100644
--- a/hicn-plugin/src/faces/app/face_cons.h
+++ b/hicn-plugin/src/faces/app/face_cons.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/faces/app/face_prod.c b/hicn-plugin/src/faces/app/face_prod.c
index 16b6e6158..5d0fa727b 100644
--- a/hicn-plugin/src/faces/app/face_prod.c
+++ b/hicn-plugin/src/faces/app/face_prod.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,6 +17,7 @@
#include <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vnet/interface_funcs.h>
+#include <vppinfra/pool.h>
#include "face_prod.h"
#include "address_mgr.h"
@@ -24,17 +25,15 @@
#include "../../route.h"
#include "../../cache_policies/cs_lru.h"
+#define INITIAL_POOL_SIZE 16
hicn_face_prod_state_t *face_state_vec;
/* used to check if an interface is already in the vector */
u32 *face_state_pool;
static int
-hicn_app_state_create (u32 swif, fib_prefix_t *prefix)
+hicn_app_state_create (u32 swif, index_t adj_index, fib_prefix_t *prefix)
{
- /* Make sure that the pool is not empty */
- pool_validate_index (face_state_pool, 0);
-
u32 *swif_app;
u8 found = 0;
@@ -49,6 +48,7 @@ hicn_app_state_create (u32 swif, fib_prefix_t *prefix)
/* Create the appif and store in the vector */
vec_validate (face_state_vec, swif);
+ face_state_vec[swif].adj_index = adj_index;
clib_memcpy (&(face_state_vec[swif].prefix), prefix, sizeof (fib_prefix_t));
/* Set as busy the element in the vector */
@@ -73,9 +73,6 @@ hicn_app_state_create (u32 swif, fib_prefix_t *prefix)
static int
hicn_app_state_del (u32 swif)
{
- /* Make sure that the pool is not empty */
- pool_validate_index (face_state_pool, 0);
-
u32 *temp;
u32 *swif_app = NULL;
u8 found = 0;
@@ -119,7 +116,7 @@ hicn_face_prod_add (fib_prefix_t *prefix, u32 sw_if, u32 *cs_reserved,
hicn_main_t *hm = &hicn_main;
- ip46_address_t local_app_ip;
+ ip46_address_t local_app_ip = { .as_u64 = { 0, 0 } };
CLIB_UNUSED (ip46_address_t remote_app_ip);
u32 if_flags = 0;
@@ -139,10 +136,11 @@ hicn_face_prod_add (fib_prefix_t *prefix, u32 sw_if, u32 *cs_reserved,
if_flags |= VNET_SW_INTERFACE_FLAG_ADMIN_UP;
vnet_sw_interface_set_flags (vnm, sw_if, if_flags);
+#ifdef HICN_DDEBUG
u8 *s0;
s0 = format (0, "Prefix %U", format_fib_prefix, prefix);
-
- vlib_cli_output (vm, "Received request for %s, swif %d\n", s0, sw_if);
+ HICN_DEBUG ("Received request for %s, swif %d\n", s0, sw_if);
+#endif
if (ip46_address_is_zero (&prefix->fp_addr))
{
@@ -265,18 +263,26 @@ hicn_face_prod_add (fib_prefix_t *prefix, u32 sw_if, u32 *cs_reserved,
}
u32 fib_index = fib_table_find (prefix->fp_proto, 0);
- fib_table_entry_path_add2 (fib_index, prefix, FIB_SOURCE_CLI,
+ fib_table_entry_path_add2 (fib_index, prefix, FIB_SOURCE_API,
FIB_ENTRY_FLAG_NONE, rpaths);
- hicn_route_enable (prefix);
- hicn_app_state_create (sw_if, prefix);
+ HICN_DEBUG ("Calling hicn enable for producer face");
+
+ hicn_face_id_t *vec_faces = NULL;
+ fib_node_index_t hicn_fib_node_index;
+ hicn_route_enable (prefix, &hicn_fib_node_index, &vec_faces);
+ if (vec_faces != NULL)
+ vec_free (vec_faces);
+
+ adj_index =
+ adj_nbr_find (isv6 ? FIB_PROTOCOL_IP6 : FIB_PROTOCOL_IP4,
+ isv6 ? VNET_LINK_IP6 : VNET_LINK_IP4, prod_addr, sw_if);
+
+ hicn_app_state_create (sw_if, adj_index, prefix);
}
- adj_index =
- adj_nbr_find (isv6 ? FIB_PROTOCOL_IP6 : FIB_PROTOCOL_IP4,
- isv6 ? VNET_LINK_IP6 : VNET_LINK_IP4, prod_addr, sw_if);
- face = hicn_face_get (&local_app_ip, sw_if, &hicn_face_hashtb,
- adj_index); // HICN_FACE_FLAGS_APPFACE_PROD);
+ face = hicn_face_get (&local_app_ip, sw_if, &hicn_face_hashtb, adj_index);
+ assert (face);
*faceid = hicn_dpoi_get_index (face);
@@ -289,6 +295,7 @@ hicn_face_prod_add (fib_prefix_t *prefix, u32 sw_if, u32 *cs_reserved,
/* Cleanup in case of something went wrong. */
if (ret)
{
+ HICN_ERROR ("Somethig went wrong while adding producer face. Cleanup.");
hicn_app_state_del (sw_if);
}
return ret;
@@ -304,17 +311,32 @@ hicn_face_prod_del (hicn_face_id_t face_id)
if (face->flags & HICN_FACE_FLAGS_APPFACE_PROD)
{
- /* Remove the face from the fib */
- hicn_route_disable (&(face_state_vec[face->sw_if].prefix));
- // hicn_route_del_nhop (&(face_state_vec[face->sw_if].prefix),
- // face_id);
-
- // int ret = hicn_face_del (face_id);
- return hicn_app_state_del (face->sw_if);
- // ret == HICN_ERROR_NONE ? hicn_app_state_del (face->sw_if) : ret;
+ /* Remove the face from the hicn fib */
+ fib_prefix_t *prefix = &(face_state_vec[face->sw_if].prefix);
+ HICN_DEBUG ("Calling hicn_route_disable from hicn_face_prod_del");
+ int ret = hicn_route_disable (prefix);
+ if (ret)
+ {
+ vlib_main_t *vm = vlib_get_main ();
+ vlib_cli_output (vm, "Error disabling route: %s",
+ get_error_string (ret));
+ }
+ /* Also remove it from main fib, as we sre the owners of this prefix */
+ u32 fib_index = fib_table_find (prefix->fp_proto, 0);
+ fib_table_entry_special_remove (fib_index, prefix, FIB_SOURCE_API);
+ ret = hicn_app_state_del (face->sw_if);
+ if (ret)
+ {
+ vlib_main_t *vm = vlib_get_main ();
+ vlib_cli_output (vm, "Error deelting app state: %s",
+ get_error_string (ret));
+ }
}
else
{
+ vlib_main_t *vm = vlib_get_main ();
+ vlib_cli_output (vm, "APPFACE not found.",
+ get_error_string (HICN_ERROR_APPFACE_NOT_FOUND));
return HICN_ERROR_APPFACE_NOT_FOUND;
}
@@ -332,6 +354,13 @@ format_hicn_face_prod (u8 *s, va_list *args)
return s;
}
+void
+hicn_face_prod_init ()
+{
+ /* Make sure that the pool is not empty */
+ pool_alloc (face_state_pool, INITIAL_POOL_SIZE);
+}
+
VNET_FEATURE_INIT (hicn_prod_app_input_ip6, static) = {
.arc_name = "ip6-unicast",
.node_name = "hicn-face-prod-input",
diff --git a/hicn-plugin/src/faces/app/face_prod.h b/hicn-plugin/src/faces/app/face_prod.h
index 4acf89dfc..46bdf7c24 100644
--- a/hicn-plugin/src/faces/app/face_prod.h
+++ b/hicn-plugin/src/faces/app/face_prod.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -50,6 +50,7 @@
typedef struct
{
fib_prefix_t prefix;
+ index_t adj_index;
} hicn_face_prod_state_t;
extern hicn_face_prod_state_t *face_state_vec;
@@ -95,6 +96,11 @@ int hicn_face_prod_set_lru_max (hicn_face_id_t face_id, u32 *requested_size);
*/
u8 *format_hicn_face_prod (u8 *s, va_list *args);
+/**
+ * @brief Init the producer face module
+ */
+void hicn_face_prod_init ();
+
#endif /* _FACE_PROD_H_ */
/*
diff --git a/hicn-plugin/src/faces/app/face_prod_node.c b/hicn-plugin/src/faces/app/face_prod_node.c
index c4c9edc32..93e80d1ac 100644
--- a/hicn-plugin/src/faces/app/face_prod_node.c
+++ b/hicn-plugin/src/faces/app/face_prod_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,8 +24,8 @@
*/
#include "face_prod.h"
-#include "../../hicn_api.h"
#include "../../mgmt.h"
+#include "../../parser.h"
static __clib_unused char *face_prod_input_error_strings[] = {
#define _(sym, string) string,
@@ -43,12 +43,12 @@ typedef struct
{
u32 next_index;
u32 sw_if_index;
+ hicn_error_t error;
} hicn_face_prod_input_trace_t;
typedef enum
{
- HICN_FACE_PROD_NEXT_DATA_IP4,
- HICN_FACE_PROD_NEXT_DATA_IP6,
+ HICN_FACE_PROD_NEXT_PCS,
HICN_FACE_PROD_NEXT_ERROR_DROP,
HICN_FACE_PROD_N_NEXT,
} hicn_face_prod_next_t;
@@ -66,11 +66,14 @@ format_face_prod_input_trace (u8 *s, va_list *args)
s = format (s, "prod-face: sw_if_index %d next-index %d", t->sw_if_index,
t->next_index);
+
+ if (t->error != HICN_ERROR_NONE)
+ s = format (s, " error %s", get_error_string (t->error));
return s;
}
static_always_inline int
-match_ip4_name (u32 *name, fib_prefix_t *prefix)
+match_ip4_name (u32 *name, const fib_prefix_t *prefix)
{
u32 xor = 0;
@@ -80,7 +83,7 @@ match_ip4_name (u32 *name, fib_prefix_t *prefix)
}
static_always_inline int
-match_ip6_name (u8 *name, fib_prefix_t *prefix)
+match_ip6_name (u8 *name, const fib_prefix_t *prefix)
{
union
{
@@ -97,24 +100,42 @@ match_ip6_name (u8 *name, fib_prefix_t *prefix)
}
static_always_inline u32
-hicn_face_prod_next_from_data_hdr (vlib_node_runtime_t *node, vlib_buffer_t *b,
- fib_prefix_t *prefix)
+hicn_face_prod_next_from_data_hdr (vlib_main_t *vm, vlib_buffer_t *b)
{
- u8 *ptr = vlib_buffer_get_current (b);
- u8 v = *ptr & 0xf0;
+ u8 is_v6;
int match_res = 1;
+ int ret = 0;
+ hicn_name_t name;
+ hicn_face_prod_state_t *prod_face = NULL;
+
+ // 1 - ensure the packet is hicn and its format is correct
+ ret = hicn_data_parse_pkt (b, vlib_buffer_length_in_chain (vm, b));
+ if (PREDICT_FALSE (ret))
+ {
+ return HICN_FACE_PROD_NEXT_ERROR_DROP;
+ }
- if (PREDICT_TRUE (v == 0x40 && ip46_address_is_ip4 (&prefix->fp_addr)))
+ // 2 - make sure the packet refers to a valid producer app state and
+ // retrieve app state information
+ prod_face = &face_state_vec[vnet_buffer (b)->sw_if_index[VLIB_RX]];
+ vnet_buffer (b)->ip.adj_index[VLIB_RX] = prod_face->adj_index;
+
+ // 3 - make sure the address in the packet belongs to the producer prefix
+ // of this face
+ const fib_prefix_t *prefix = &prod_face->prefix;
+ is_v6 = hicn_buffer_is_v6 (b);
+ hicn_packet_get_name (&hicn_get_buffer (b)->pkbuf, &name);
+ if (PREDICT_TRUE (!is_v6 && ip46_address_is_ip4 (&prefix->fp_addr)))
{
- match_res = match_ip4_name ((u32 *) &(ptr[12]), prefix);
+ match_res = match_ip4_name (&name.prefix.v4.as_u32, prefix);
}
- else if (PREDICT_TRUE (v == 0x60 && !ip46_address_is_ip4 (&prefix->fp_addr)))
+ else if (PREDICT_TRUE (is_v6 && !ip46_address_is_ip4 (&prefix->fp_addr)))
{
- match_res = match_ip6_name (&(ptr[8]), prefix);
+ match_res = match_ip6_name (name.prefix.v6.as_u8, prefix);
}
- return match_res ? HICN_FACE_PROD_NEXT_DATA_IP4 + (v == 0x60) :
- HICN_FACE_PROD_NEXT_ERROR_DROP;
+ // 4 - if match found, forward data to next hicn node
+ return match_res ? HICN_FACE_PROD_NEXT_PCS : HICN_FACE_PROD_NEXT_ERROR_DROP;
}
static_always_inline void
@@ -138,6 +159,7 @@ hicn_face_prod_input_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
u32 n_left_from, *from, *to_next;
hicn_face_prod_next_t next_index;
vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
+ u32 thread_index = vm->thread_index;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
@@ -151,23 +173,30 @@ hicn_face_prod_input_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
while (n_left_from >= 8 && n_left_to_next >= 4)
{
vlib_buffer_t *b0, *b1, *b2, *b3;
+ hicn_buffer_t *hicnb0, *hicnb1, *hicnb2, *hicnb3;
u32 bi0, bi1, bi2, bi3;
- hicn_face_prod_state_t *prod_face0 = NULL;
- hicn_face_prod_state_t *prod_face1 = NULL;
- hicn_face_prod_state_t *prod_face2 = NULL;
- hicn_face_prod_state_t *prod_face3 = NULL;
u32 next0, next1, next2, next3;
+ // Prefetch next iteration
{
vlib_buffer_t *b4, *b5, *b6, *b7;
b4 = vlib_get_buffer (vm, from[4]);
b5 = vlib_get_buffer (vm, from[5]);
b6 = vlib_get_buffer (vm, from[6]);
b7 = vlib_get_buffer (vm, from[7]);
- CLIB_PREFETCH (b4, CLIB_CACHE_LINE_BYTES, STORE);
- CLIB_PREFETCH (b5, CLIB_CACHE_LINE_BYTES, STORE);
- CLIB_PREFETCH (b6, CLIB_CACHE_LINE_BYTES, STORE);
- CLIB_PREFETCH (b7, CLIB_CACHE_LINE_BYTES, STORE);
+ CLIB_PREFETCH (b4, 2 * CLIB_CACHE_LINE_BYTES, WRITE);
+ CLIB_PREFETCH (b5, 2 * CLIB_CACHE_LINE_BYTES, WRITE);
+ CLIB_PREFETCH (b6, 2 * CLIB_CACHE_LINE_BYTES, WRITE);
+ CLIB_PREFETCH (b7, 2 * CLIB_CACHE_LINE_BYTES, WRITE);
+
+ CLIB_PREFETCH (vlib_buffer_get_current (b4),
+ 2 * CLIB_CACHE_LINE_BYTES, WRITE);
+ CLIB_PREFETCH (vlib_buffer_get_current (b5),
+ 2 * CLIB_CACHE_LINE_BYTES, WRITE);
+ CLIB_PREFETCH (vlib_buffer_get_current (b6),
+ 2 * CLIB_CACHE_LINE_BYTES, WRITE);
+ CLIB_PREFETCH (vlib_buffer_get_current (b7),
+ 2 * CLIB_CACHE_LINE_BYTES, WRITE);
}
bi0 = from[0];
@@ -190,22 +219,49 @@ hicn_face_prod_input_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
b2 = vlib_get_buffer (vm, bi2);
b3 = vlib_get_buffer (vm, bi3);
- prod_face0 = &face_state_vec[vnet_buffer (b0)->sw_if_index[VLIB_RX]];
- prod_face1 = &face_state_vec[vnet_buffer (b1)->sw_if_index[VLIB_RX]];
- prod_face2 = &face_state_vec[vnet_buffer (b2)->sw_if_index[VLIB_RX]];
- prod_face3 = &face_state_vec[vnet_buffer (b3)->sw_if_index[VLIB_RX]];
-
- next0 =
- hicn_face_prod_next_from_data_hdr (node, b0, &prod_face0->prefix);
- next1 =
- hicn_face_prod_next_from_data_hdr (node, b1, &prod_face1->prefix);
- next2 =
- hicn_face_prod_next_from_data_hdr (node, b2, &prod_face2->prefix);
- next3 =
- hicn_face_prod_next_from_data_hdr (node, b3, &prod_face3->prefix);
+ hicnb0 = hicn_get_buffer (b0);
+ hicnb1 = hicn_get_buffer (b1);
+ hicnb2 = hicn_get_buffer (b2);
+ hicnb3 = hicn_get_buffer (b3);
+
+ hicnb0->flags = HICN_FACE_FLAGS_DEFAULT;
+ hicnb1->flags = HICN_FACE_FLAGS_DEFAULT;
+ hicnb2->flags = HICN_FACE_FLAGS_DEFAULT;
+ hicnb3->flags = HICN_FACE_FLAGS_DEFAULT;
+
+ // parse packets and get next node
+ next0 = hicn_face_prod_next_from_data_hdr (vm, b0);
+ next1 = hicn_face_prod_next_from_data_hdr (vm, b1);
+ next2 = hicn_face_prod_next_from_data_hdr (vm, b2);
+ next3 = hicn_face_prod_next_from_data_hdr (vm, b3);
stats.pkts_data_count += 4;
- /* trace */
+ // counters
+ vlib_increment_combined_counter (
+ &counters[hicnb0->face_id * HICN_N_COUNTER], thread_index,
+ HICN_FACE_COUNTERS_DATA_RX, 1,
+ vlib_buffer_length_in_chain (vm, b0));
+ stats.pkts_data_count += 1;
+
+ vlib_increment_combined_counter (
+ &counters[hicnb1->face_id * HICN_N_COUNTER], thread_index,
+ HICN_FACE_COUNTERS_DATA_RX, 1,
+ vlib_buffer_length_in_chain (vm, b0));
+ stats.pkts_data_count += 1;
+
+ vlib_increment_combined_counter (
+ &counters[hicnb2->face_id * HICN_N_COUNTER], thread_index,
+ HICN_FACE_COUNTERS_DATA_RX, 1,
+ vlib_buffer_length_in_chain (vm, b0));
+ stats.pkts_data_count += 1;
+
+ vlib_increment_combined_counter (
+ &counters[hicnb3->face_id * HICN_N_COUNTER], thread_index,
+ HICN_FACE_COUNTERS_DATA_RX, 1,
+ vlib_buffer_length_in_chain (vm, b0));
+ stats.pkts_data_count += 1;
+
+ // trace
hicn_face_prod_trace_buffer (
vm, node, vnet_buffer (b0)->sw_if_index[VLIB_RX], b0, next0);
hicn_face_prod_trace_buffer (
@@ -215,7 +271,7 @@ hicn_face_prod_input_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
hicn_face_prod_trace_buffer (
vm, node, vnet_buffer (b3)->sw_if_index[VLIB_RX], b3, next3);
- /* enqueue */
+ // enqueue
vlib_validate_buffer_enqueue_x4 (vm, node, next_index, to_next,
n_left_to_next, bi0, bi1, bi2, bi3,
next0, next1, next2, next3);
@@ -226,8 +282,8 @@ hicn_face_prod_input_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
while (n_left_from > 0 && n_left_to_next > 0)
{
vlib_buffer_t *b0;
- u32 bi0, swif;
- hicn_face_prod_state_t *prod_face = NULL;
+ hicn_buffer_t *hicnb0;
+ u32 bi0;
u32 next0;
if (n_left_from > 1)
@@ -245,13 +301,19 @@ hicn_face_prod_input_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
- swif = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- prod_face = &face_state_vec[swif];
+ hicnb0 = hicn_get_buffer (b0);
+ hicnb0->flags = HICN_FACE_FLAGS_DEFAULT;
- next0 =
- hicn_face_prod_next_from_data_hdr (node, b0, &prod_face->prefix);
+ next0 = hicn_face_prod_next_from_data_hdr (vm, b0);
stats.pkts_data_count++;
+ // counters
+ vlib_increment_combined_counter (
+ &counters[hicnb0->face_id * HICN_N_COUNTER], thread_index,
+ HICN_FACE_COUNTERS_DATA_RX, 1,
+ vlib_buffer_length_in_chain (vm, b0));
+ stats.pkts_data_count += 1;
+
/* trace */
hicn_face_prod_trace_buffer (
vm, node, vnet_buffer (b0)->sw_if_index[VLIB_RX], b0, next0);
@@ -286,8 +348,7 @@ VLIB_REGISTER_NODE(hicn_face_prod_input_node) =
.n_next_nodes = HICN_FACE_PROD_N_NEXT,
.next_nodes =
{
- [HICN_FACE_PROD_NEXT_DATA_IP4] = "hicn4-face-input",
- [HICN_FACE_PROD_NEXT_DATA_IP6] = "hicn6-face-input",
+ [HICN_FACE_PROD_NEXT_PCS] = "hicn-data-pcslookup",
[HICN_FACE_PROD_NEXT_ERROR_DROP] = "error-drop",
},
};
diff --git a/hicn-plugin/src/faces/face.c b/hicn-plugin/src/faces/face.c
index d62054365..ce3001ac7 100644
--- a/hicn-plugin/src/faces/face.c
+++ b/hicn-plugin/src/faces/face.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#include <vnet/fib/fib_entry_track.h>
#include "face.h"
+#include "app/face_prod.h"
#include "../hicn.h"
#include "../params.h"
#include "../error.h"
@@ -57,24 +58,17 @@ face_show (u8 *s, int face_id, u32 indent)
return (s);
}
-mhash_t hicn_face_vec_hashtb;
mhash_t hicn_face_hashtb;
-hicn_face_vec_t *hicn_vec_pool;
-
const static char *const hicn_face6_nodes[] = {
- "hicn6-face-output", // this is the name you give your node in
- // VLIB_REGISTER_NODE
- "hicn6-iface-output", // this is the name you give your node in
- // VLIB_REGISTER_NODE
+ "hicn6-face-output", // this is the name you give your node in
+ // VLIB_REGISTER_NODE
NULL,
};
const static char *const hicn_face4_nodes[] = {
- "hicn4-face-output", // this is the name you give your node in
- // VLIB_REGISTER_NODE
- "hicn4-iface-output", // this is the name you give your node in
- // VLIB_REGISTER_NODE
+ "hicn4-face-output", // this is the name you give your node in
+ // VLIB_REGISTER_NODE
NULL,
};
@@ -158,19 +152,13 @@ static const fib_node_vft_t hicn_face_fib_node_vft = {
void
hicn_face_module_init (vlib_main_t *vm)
{
- pool_validate (hicn_dpoi_face_pool);
pool_alloc (hicn_dpoi_face_pool, 1024);
counters = vec_new (vlib_combined_counter_main_t,
HICN_PARAM_FACES_MAX * HICN_N_COUNTER);
- mhash_init (&hicn_face_vec_hashtb,
- sizeof (hicn_face_input_faces_t) /* value */,
- sizeof (hicn_face_key_t) /* key */);
mhash_init (&hicn_face_hashtb, sizeof (hicn_face_id_t) /* value */,
sizeof (hicn_face_key_t) /* key */);
- pool_alloc (hicn_vec_pool, 100);
-
/*
* How much useful is the following registration?
* So far it seems that we need it only for setting the dpo_type.
@@ -182,7 +170,12 @@ hicn_face_module_init (vlib_main_t *vm)
* corresponding to a face is updated
*/
hicn_face_fib_node_type =
- fib_node_register_new_type (&hicn_face_fib_node_vft);
+ fib_node_register_new_type ("hicn_face_fib_node", &hicn_face_fib_node_vft);
+
+ /*
+ * Init producer face module
+ */
+ hicn_face_prod_init ();
}
u8 *
@@ -256,46 +249,11 @@ format_hicn_face_all (u8 *s, int n, ...)
int
hicn_face_del (hicn_face_id_t face_id)
{
- hicn_face_t *face = hicn_dpoi_get_from_idx (face_id);
- hicn_face_key_t key;
- hicn_face_key_t old_key;
- hicn_face_key_t old_key2;
-
- hicn_face_get_key (&(face->nat_addr), face->sw_if, &(face->dpo), &key);
- hicn_face_input_faces_t *in_faces_vec =
- hicn_face_get_vec (&(face->nat_addr), &hicn_face_vec_hashtb);
- if (in_faces_vec != NULL)
- {
- hicn_face_vec_t *vec =
- pool_elt_at_index (hicn_vec_pool, in_faces_vec->vec_id);
- u32 index_face = vec_search (*vec, face_id);
- vec_del1 (*vec, index_face);
-
- if (vec_len (*vec) == 0)
- {
- pool_put_index (hicn_vec_pool, in_faces_vec->vec_id);
- mhash_unset (&hicn_face_vec_hashtb, &key, (uword *) &old_key);
- vec_free (*vec);
- }
- else
- {
- /* Check if the face we are deleting is the preferred one. */
- /* If so, repleace with another. */
- if (in_faces_vec->face_id == face_id)
- {
- in_faces_vec->face_id = (*vec)[0];
- }
- }
-
- mhash_unset (&hicn_face_hashtb, &key, (uword *) &old_key2);
- }
-
int ret = HICN_ERROR_NONE;
if (hicn_dpoi_idx_is_valid (face_id))
{
hicn_face_t *face = hicn_dpoi_get_from_idx (face_id);
- face->locks--;
if (face->locks == 0)
pool_put_index (hicn_dpoi_face_pool, face_id);
else
@@ -308,10 +266,12 @@ hicn_face_del (hicn_face_id_t face_id)
}
static void
-hicn_iface_to_face (hicn_face_t *face, const dpo_id_t *dpo)
+hicn_iface_to_face (hicn_face_t *face, const dpo_id_t *dpo,
+ dpo_proto_t dpo_proto)
{
- dpo_stack (hicn_face_type, dpo->dpoi_proto, &face->dpo, dpo);
+ dpo_stack (hicn_face_type, dpo_proto, &face->dpo, dpo);
+ face->dpo.dpoi_proto = dpo_proto;
face->flags &= ~HICN_FACE_FLAGS_IFACE;
face->flags |= HICN_FACE_FLAGS_FACE;
@@ -320,7 +280,7 @@ hicn_iface_to_face (hicn_face_t *face, const dpo_id_t *dpo)
fib_node_init (&face->fib_node, hicn_face_fib_node_type);
fib_node_lock (&face->fib_node);
- if (dpo->dpoi_type != DPO_ADJACENCY_MIDCHAIN ||
+ if (dpo->dpoi_type != DPO_ADJACENCY_MIDCHAIN &&
dpo->dpoi_type != DPO_ADJACENCY_MCAST_MIDCHAIN)
{
ip_adjacency_t *adj = adj_get (dpo->dpoi_index);
@@ -347,12 +307,9 @@ hicn_iface_to_face (hicn_face_t *face, const dpo_id_t *dpo)
*/
int
hicn_face_add (const dpo_id_t *dpo_nh, ip46_address_t *nat_address, int sw_if,
- hicn_face_id_t *pfaceid, u8 is_app_prod)
+ hicn_face_id_t *pfaceid, dpo_proto_t dpo_proto)
{
- hicn_face_flags_t flags = (hicn_face_flags_t) 0;
- flags |= HICN_FACE_FLAGS_FACE;
-
hicn_face_t *face;
face =
@@ -374,9 +331,7 @@ hicn_face_add (const dpo_id_t *dpo_nh, ip46_address_t *nat_address, int sw_if,
if (face == NULL)
{
-
- hicn_iface_add (nat_address, sw_if, pfaceid, dpo_nh->dpoi_proto,
- dpo_nh->dpoi_index);
+ hicn_iface_add (nat_address, sw_if, pfaceid, dpo_nh->dpoi_index, 0);
face = hicn_dpoi_get_from_idx (*pfaceid);
mhash_set_mem (&hicn_face_hashtb, &key, (uword *) pfaceid, 0);
@@ -391,56 +346,10 @@ hicn_face_add (const dpo_id_t *dpo_nh, ip46_address_t *nat_address, int sw_if,
mhash_set_mem (&hicn_face_hashtb, &key, (uword *) pfaceid, 0);
}
- hicn_iface_to_face (face, dpo_nh);
+ hicn_iface_to_face (face, dpo_nh, dpo_proto);
temp_dpo.dpoi_index = ~0;
- hicn_face_input_faces_t *in_faces =
- hicn_face_get_vec (nat_address, &hicn_face_vec_hashtb);
-
- if (in_faces == NULL)
- {
- hicn_face_input_faces_t in_faces_temp;
- hicn_face_vec_t *vec;
- pool_get (hicn_vec_pool, vec);
- *vec = vec_new (hicn_face_id_t, 0);
- u32 index = vec - hicn_vec_pool;
- in_faces_temp.vec_id = index;
- vec_add1 (*vec, *pfaceid);
-
- in_faces_temp.face_id = *pfaceid;
-
- hicn_face_get_key (nat_address, 0, &temp_dpo, &key);
-
- mhash_set_mem (&hicn_face_vec_hashtb, &key, (uword *) &in_faces_temp, 0);
- }
- else
- {
- hicn_face_vec_t *vec =
- pool_elt_at_index (hicn_vec_pool, in_faces->vec_id);
-
- /* */
- if (vec_search (*vec, *pfaceid) != ~0)
- return HICN_ERROR_FACE_ALREADY_CREATED;
-
- vec_add1 (*vec, *pfaceid);
-
- hicn_iface_to_face (face, dpo_nh);
-
- hicn_face_get_key (nat_address, 0, &temp_dpo, &key);
-
- mhash_set_mem (&hicn_face_vec_hashtb, &key, (uword *) in_faces, 0);
-
- /* If the face is an application producer face, we set it as the
- * preferred incoming face. */
- /* This is required to handle the CS separation, and the push api in a
- * lightway */
- if (is_app_prod)
- {
- in_faces->face_id = *pfaceid;
- }
- }
-
retx_t *retx = vlib_process_signal_event_data (
vlib_get_main (), hicn_mapme_eventmgr_process_node.index,
HICN_MAPME_EVENT_FACE_ADD, 1, sizeof (retx_t));
diff --git a/hicn-plugin/src/faces/face.h b/hicn-plugin/src/faces/face.h
index cb706eeca..43900dd4e 100644
--- a/hicn-plugin/src/faces/face.h
+++ b/hicn-plugin/src/faces/face.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,7 +25,12 @@
#include <vppinfra/bihash_8_8.h>
#include <vnet/adj/adj_midchain.h>
-#include "../error.h"
+#include <vpp_plugins/hicn/error.h>
+
+#include "face_flags.h"
+#include "../hicn_buffer_flags.h"
+#include "../hicn_logging.h"
+
typedef u8 hicn_face_flags_t;
typedef index_t hicn_face_id_t;
@@ -66,12 +71,8 @@ typedef index_t hicn_face_id_t;
* - fib_node, fib_entry_index and fib_sibling are information used to be
* notified of changes in the adjacency pointed by the dpo.
*
- * We maintain two hash tables to retrieve faces and ifaces. In particular one
- * hash table which index faces and ifaces for nat_address, sw_if and dpo. This
- * is used to retrieve existing faces or ifaces when an interest is received
- * and when an new face is created. A second hash table that indexes vectors of
- * faces for nat_address and sw_if. This is used to retrieve a list of possible
- * incoming faces when a data is received.
+ * We maintain one hash tables to retrieve faces and ifaces, which indexes
+ * faces and ifaces for nat_address, sw_if and dpo.
*/
/**
@@ -86,7 +87,7 @@ typedef struct __attribute__ ((packed)) hicn_face_s
hicn_face_flags_t flags;
/* Align the upcoming fields */
- u8 align;
+ u8 iface_next;
/* Path label (2B) */
u16 pl_id;
@@ -117,47 +118,8 @@ typedef struct __attribute__ ((packed)) hicn_face_s
/* Pool of faces */
extern hicn_face_t *hicn_dpoi_face_pool;
-/* Flags */
-/* A face is complete and it stores all the information. A iface lacks of the
- adj index, therefore sending a packet through a iface require a lookup in
- the FIB. */
-#define HICN_FACE_FLAGS_DEFAULT 0x00
-#define HICN_FACE_FLAGS_FACE 0x01
-#define HICN_FACE_FLAGS_IFACE 0x02
-#define HICN_FACE_FLAGS_APPFACE_PROD \
- 0x04 /* Currently only IP face can be appface */
-#define HICN_FACE_FLAGS_APPFACE_CONS \
- 0x08 /* Currently only IP face can be appface */
-#define HICN_FACE_FLAGS_DELETED 0x10
-
#define HICN_FACE_NULL (hicn_face_id_t) ~0
-#define HICN_FACE_FLAGS_APPFACE_PROD_BIT 2
-#define HICN_FACE_FLAGS_APPFACE_CONS_BIT 3
-
-#define HICN_BUFFER_FLAGS_DEFAULT 0x00
-#define HICN_BUFFER_FLAGS_FACE_IS_APP 0x01
-
-STATIC_ASSERT ((1 << HICN_FACE_FLAGS_APPFACE_PROD_BIT) ==
- HICN_FACE_FLAGS_APPFACE_PROD,
- "HICN_FACE_FLAGS_APPFACE_PROD_BIT and "
- "HICN_FACE_FLAGS_APPFACE_PROD must correspond");
-
-STATIC_ASSERT ((1 << HICN_FACE_FLAGS_APPFACE_CONS_BIT) ==
- HICN_FACE_FLAGS_APPFACE_CONS,
- "HICN_FACE_FLAGS_APPFACE_CONS_BIT and "
- "HICN_FACE_FLAGS_APPFACE_CONS must correspond");
-
-STATIC_ASSERT (
- (HICN_FACE_FLAGS_APPFACE_PROD >> HICN_FACE_FLAGS_APPFACE_PROD_BIT) ==
- HICN_BUFFER_FLAGS_FACE_IS_APP,
- "hicn buffer app flag does not correspond to HICN_FACE_FLAGS_APPFACE_PROD");
-
-STATIC_ASSERT (
- (HICN_FACE_FLAGS_APPFACE_CONS >> HICN_FACE_FLAGS_APPFACE_CONS_BIT) ==
- HICN_BUFFER_FLAGS_FACE_IS_APP,
- "hicn buffer app flag does not correspond to HICN_FACE_FLAGS_APPFACE_PROD");
-
/**
* @brief Definition of the virtual functin table for an hICN FACE DPO.
*/
@@ -257,6 +219,15 @@ hicn_dpoi_idx_is_valid (hicn_face_id_t face_id)
}
/**
+ * @brief Delete a face
+ *
+ * @param face_id Id of the face to delete
+ * @return HICN_ERROR_FACE_NOT_FOUND if the face does not exist, otherwise
+ * HICN_ERROR_NONE
+ */
+int hicn_face_del (hicn_face_id_t face_id);
+
+/**
* @brief Add a lock to the face dpo
*
* @param dpo Pointer to the face dpo
@@ -274,12 +245,24 @@ hicn_face_lock_with_id (hicn_face_id_t face_id)
*
* @param dpo Pointer to the face dpo
*/
-always_inline void
+always_inline int
hicn_face_unlock_with_id (hicn_face_id_t face_id)
{
hicn_face_t *face;
face = hicn_dpoi_get_from_idx (face_id);
- face->locks--;
+
+ if (face->locks > 0)
+ {
+ face->locks--;
+
+ if (face->locks == 0)
+ {
+ HICN_DEBUG ("Deleting face %d", face_id);
+ return hicn_face_del (face_id);
+ }
+ }
+
+ return HICN_ERROR_NONE;
}
/**
@@ -324,15 +307,6 @@ u8 *format_hicn_face (u8 *s, va_list *args);
u8 *format_hicn_face_all (u8 *s, int n, ...);
/**
- * @brief Delete a face
- *
- * @param face_id Id of the face to delete
- * @return HICN_ERROR_FACE_NOT_FOUND if the face does not exist, otherwise
- * HICN_ERROR_NONE
- */
-int hicn_face_del (hicn_face_id_t face_id);
-
-/**
* @bried vector of faces used to collect faces having the same local address
*
*/
@@ -355,17 +329,6 @@ typedef struct hicn_input_faces_s_
} hicn_face_input_faces_t;
/**
- * Pool containing the vector of possible incoming faces.
- */
-extern hicn_face_vec_t *hicn_vec_pool;
-
-/**
- * Hash tables that indexes a face by remote address. For fast lookup when an
- * interest arrives.
- */
-extern mhash_t hicn_face_vec_hashtb;
-
-/**
* Key definition for the mhash table. An face is uniquely identified by ip
* address, the interface id and a dpo pointing to the next node in the vlib
* graph. The ip address can correspond to the remote ip address of the next
@@ -437,7 +400,7 @@ hicn_face_get (const ip46_address_t *addr, u32 sw_if, mhash_t *hashtb,
hicn_face_id_t *dpoi_index = (hicn_face_id_t *) mhash_get (hashtb, &key);
- if (dpoi_index != NULL)
+ if (dpoi_index != NULL && hicn_dpoi_idx_is_valid (*dpoi_index))
{
hicn_face_lock_with_id (*dpoi_index);
return hicn_dpoi_get_from_idx (*dpoi_index);
@@ -467,7 +430,7 @@ hicn_face_get_with_dpo (const ip46_address_t *addr, u32 sw_if,
hicn_face_id_t *dpoi_index = (hicn_face_id_t *) mhash_get (hashtb, &key);
- if (dpoi_index != NULL)
+ if (dpoi_index != NULL && hicn_dpoi_idx_is_valid (*dpoi_index))
{
hicn_face_lock_with_id (*dpoi_index);
return hicn_dpoi_get_from_idx (*dpoi_index);
@@ -477,28 +440,6 @@ hicn_face_get_with_dpo (const ip46_address_t *addr, u32 sw_if,
}
/**
- * @brief Get the vector of faces from the ip v4 address. Does not add any
- * lock.
- *
- * @param addr Ip v4 address used to create the key for the hash table.
- * @param sw_if Software interface id used to create the key for the hash
- * table.
- * @param hashtb Hash table (remote or local) where to perform the lookup.
- *
- * @result Pointer to the face.
- */
-always_inline hicn_face_input_faces_t *
-hicn_face_get_vec (const ip46_address_t *addr, mhash_t *hashtb)
-{
- hicn_face_key_t key;
-
- dpo_id_t dpo = DPO_INVALID;
-
- hicn_face_get_key (addr, 0, &dpo, &key);
- return (hicn_face_input_faces_t *) mhash_get (hashtb, &key);
-}
-
-/**
* @brief Create a new face ip. API for other modules (e.g., routing)
*
* @param dpo_nh dpo contained in the face that points to the next node in
@@ -512,7 +453,7 @@ hicn_face_get_vec (const ip46_address_t *addr, mhash_t *hashtb)
* reachable ip address, otherwise HICN_ERROR_NONE
*/
int hicn_face_add (const dpo_id_t *dpo_nh, ip46_address_t *nat_address,
- int sw_if, hicn_face_id_t *pfaceid, u8 is_app_prod);
+ int sw_if, hicn_face_id_t *pfaceid, dpo_proto_t dpo_proto);
/**
* @brief Create a new incomplete face ip. (Meant to be used by the data plane)
@@ -525,8 +466,8 @@ int hicn_face_add (const dpo_id_t *dpo_nh, ip46_address_t *nat_address,
* reachable ip address, otherwise HICN_ERROR_NONE
*/
always_inline void
-hicn_iface_add (ip46_address_t *nat_address, int sw_if,
- hicn_face_id_t *pfaceid, dpo_proto_t proto, u32 adj_index)
+hicn_iface_add (const ip46_address_t *nat_address, int sw_if,
+ hicn_face_id_t *pfaceid, u32 adj_index, u8 flags)
{
hicn_face_t *face;
pool_get (hicn_dpoi_face_pool, face);
@@ -534,16 +475,19 @@ hicn_iface_add (ip46_address_t *nat_address, int sw_if,
clib_memcpy (&(face->nat_addr), nat_address, sizeof (ip46_address_t));
face->sw_if = sw_if;
- face->dpo.dpoi_type = DPO_FIRST;
- face->dpo.dpoi_proto = DPO_PROTO_NONE;
+ face->dpo = (dpo_id_t) DPO_INVALID;
face->dpo.dpoi_index = adj_index;
- face->dpo.dpoi_next_node = 0;
+
+ hicn_face_key_t key;
+ hicn_face_get_key (nat_address, sw_if, &face->dpo, &key);
+
+ face->iface_next = 1;
+
face->pl_id = pl_index++;
face->flags = HICN_FACE_FLAGS_IFACE;
+ face->flags |= flags;
face->locks = 1;
- hicn_face_key_t key;
- hicn_face_get_key (nat_address, sw_if, &face->dpo, &key);
*pfaceid = hicn_dpoi_get_index (face);
mhash_set_mem (&hicn_face_hashtb, &key, (uword *) pfaceid, 0);
@@ -560,91 +504,46 @@ hicn_iface_add (ip46_address_t *nat_address, int sw_if,
* ****/
/**
- * @brief Retrieve a vector of faces from the ip4 local address and returns its
- * index.
- *
- * @param vec: Result of the lookup. If no face exists for the local address
- * vec = NULL
- * @param hicnb_flags: Flags that indicate whether the face is an application
- * face or not
- * @param local_addr: Ip v4 nat address of the face
- * @param sw_if: software interface id of the face
- *
- * @result HICN_ERROR_FACE_NOT_FOUND if the face does not exist, otherwise
- * HICN_ERROR_NONE.
+ * @brief Call back to get the adj of the tunnel
*/
-always_inline int
-hicn_face_ip4_lock (hicn_face_id_t *face_id, u32 *in_faces_vec_id,
- u8 *hicnb_flags, const ip4_address_t *nat_addr)
+static adj_walk_rc_t
+hicn4_iface_adj_walk_cb (adj_index_t ai, void *ctx)
{
- ip46_address_t ip_address = { 0 };
- ip46_address_set_ip4 (&ip_address, nat_addr);
- hicn_face_input_faces_t *in_faces_vec =
- hicn_face_get_vec (&ip_address, &hicn_face_vec_hashtb);
-
- if (PREDICT_FALSE (in_faces_vec == NULL))
- return HICN_ERROR_FACE_NOT_FOUND;
-
- *in_faces_vec_id = in_faces_vec->vec_id;
- hicn_face_t *face = hicn_dpoi_get_from_idx (in_faces_vec->face_id);
- *hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
- *hicnb_flags |= (face->flags & HICN_FACE_FLAGS_APPFACE_PROD) >>
- HICN_FACE_FLAGS_APPFACE_PROD_BIT;
+ hicn_face_t *face = (hicn_face_t *) ctx;
- *face_id = in_faces_vec->face_id;
+ dpo_set (&face->dpo, DPO_ADJACENCY_MIDCHAIN, DPO_PROTO_IP4, ai);
+ adj_nbr_midchain_stack (ai, &face->dpo);
- return HICN_ERROR_NONE;
+ return (ADJ_WALK_RC_CONTINUE);
}
-/**
- * @brief Retrieve a face from the ip6 local address and returns its dpo. This
- * method adds a lock on the face state.
- *
- * @param dpo: Result of the lookup. If the face doesn't exist dpo = NULL
- * @param hicnb_flags: Flags that indicate whether the face is an application
- * face or not
- * @param nat_addr: Ip v6 nat address of the face
- * @param sw_if: software interface id of the face
- *
- * @result HICN_ERROR_FACE_NOT_FOUND if the face does not exist, otherwise
- * HICN_ERROR_NONE.
- */
always_inline int
-hicn_face_ip6_lock (hicn_face_id_t *face_id, u32 *in_faces_vec_id,
- u8 *hicnb_flags, const ip6_address_t *nat_addr)
+hicn_face_ip4_find (hicn_face_id_t *index, u8 *hicnb_flags,
+ const ip4_address_t *nat_addr, u32 sw_if, u32 adj_index,
+ u32 node_index)
{
- hicn_face_input_faces_t *in_faces_vec =
- hicn_face_get_vec ((ip46_address_t *) nat_addr, &hicn_face_vec_hashtb);
-
- if (PREDICT_FALSE (in_faces_vec == NULL))
- return HICN_ERROR_FACE_NOT_FOUND;
-
- *in_faces_vec_id = in_faces_vec->vec_id;
- hicn_face_t *face = hicn_dpoi_get_from_idx (in_faces_vec->face_id);
-
- *hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
- *hicnb_flags |= (face->flags & HICN_FACE_FLAGS_APPFACE_PROD) >>
- HICN_FACE_FLAGS_APPFACE_PROD_BIT;
-
- *face_id = in_faces_vec->face_id;
+ int ret = HICN_ERROR_FACE_NOT_FOUND;
+ hicn_face_id_t face_id;
- return HICN_ERROR_NONE;
-}
+ /*All (complete) faces are indexed by remote addess as well */
+ /* if the face exists, it adds a lock */
+ hicn_face_t *face = hicn_face_get ((const ip46_address_t *) nat_addr, sw_if,
+ &hicn_face_hashtb, adj_index);
-/**
- * @brief Call back to get the adj of the tunnel
- */
-static adj_walk_rc_t
-hicn4_iface_adj_walk_cb (adj_index_t ai, void *ctx)
-{
+ if (face != NULL)
+ {
+ /* unlock the face. We don't take a lock on each interest we receive */
+ face_id = hicn_dpoi_get_index (face);
+ hicn_face_unlock_with_id (face_id);
- hicn_face_t *face = (hicn_face_t *) ctx;
+ *hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
+ *index = face_id;
- dpo_set (&face->dpo, DPO_ADJACENCY_MIDCHAIN, DPO_PROTO_IP4, ai);
- adj_nbr_midchain_stack (ai, &face->dpo);
+ ret = HICN_ERROR_FACE_ALREADY_CREATED;
+ }
- return (ADJ_WALK_RC_CONTINUE);
+ return ret;
}
/**
@@ -658,31 +557,34 @@ hicn4_iface_adj_walk_cb (adj_index_t ai, void *ctx)
* @param sw_if: software interface id of the face
* @param node_index: vlib edge index to use in the packet processing
*/
-always_inline void
-hicn_iface_ip4_add_and_lock (hicn_face_id_t *index, u8 *hicnb_flags,
- const ip4_address_t *nat_addr, u32 sw_if,
- u32 adj_index, u32 node_index)
+always_inline int
+hicn_face_ip4_add_and_lock (hicn_face_id_t *index, u8 *hicnb_flags,
+ const ip4_address_t *nat_addr, u32 sw_if,
+ u32 adj_index, u32 node_index)
{
- /*All (complete) faces are indexed by remote addess as well */
-
- ip46_address_t ip_address = { 0 };
- ip46_address_set_ip4 (&ip_address, nat_addr);
+ int ret = HICN_ERROR_NONE;
+ hicn_face_t *face = NULL;
- /* if the face exists, it adds a lock */
- hicn_face_t *face =
- hicn_face_get (&ip_address, sw_if, &hicn_face_hashtb, adj_index);
+ ret = hicn_face_ip4_find (index, hicnb_flags, nat_addr, sw_if, adj_index,
+ node_index);
- if (face == NULL)
+ if (ret == HICN_ERROR_FACE_NOT_FOUND)
{
+ ip46_address_t ip_address = { 0 };
+ ip46_address_set_ip4 (&ip_address, nat_addr);
+
hicn_face_id_t idx;
- hicn_iface_add (&ip_address, sw_if, &idx, DPO_PROTO_IP4, adj_index);
+ u8 face_flags = *hicnb_flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL ?
+ HICN_FACE_FLAGS_UDP4 :
+ *hicnb_flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL ?
+ HICN_FACE_FLAGS_UDP6 :
+ 0;
+
+ hicn_iface_add (&ip_address, sw_if, &idx, adj_index, face_flags);
face = hicn_dpoi_get_from_idx (idx);
- face->dpo.dpoi_type = DPO_FIRST;
- face->dpo.dpoi_proto = DPO_PROTO_IP4;
- face->dpo.dpoi_index = adj_index;
- face->dpo.dpoi_next_node = node_index;
+ face->iface_next = node_index;
/* if (nat_addr->as_u32 == 0) */
/* { */
@@ -691,23 +593,12 @@ hicn_iface_ip4_add_and_lock (hicn_face_id_t *index, u8 *hicnb_flags,
/* } */
*hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
+ *hicnb_flags |= HICN_BUFFER_FLAGS_NEW_FACE;
*index = idx;
- return;
- }
- else
- {
- /* unlock the face. We don't take a lock on each interest we receive */
- hicn_face_id_t face_id = hicn_dpoi_get_index (face);
- hicn_face_unlock_with_id (face_id);
}
- /* Code replicated on purpose */
- *hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
- *hicnb_flags |= (face->flags & HICN_FACE_FLAGS_APPFACE_PROD) >>
- HICN_FACE_FLAGS_APPFACE_PROD_BIT;
-
- *index = hicn_dpoi_get_index (face);
+ return ret;
}
/**
@@ -723,13 +614,39 @@ hicn6_iface_adj_walk_cb (adj_index_t ai, void *ctx)
if ((adj->lookup_next_index == IP_LOOKUP_NEXT_MIDCHAIN) ||
(adj->lookup_next_index == IP_LOOKUP_NEXT_MCAST_MIDCHAIN))
{
- dpo_set (&face->dpo, DPO_ADJACENCY_MIDCHAIN, adj->ia_nh_proto, ai);
+ dpo_set (&face->dpo, DPO_ADJACENCY_MIDCHAIN,
+ (dpo_proto_t) adj->ia_nh_proto, ai);
adj_nbr_midchain_stack (ai, &face->dpo);
}
return (ADJ_WALK_RC_CONTINUE);
}
+always_inline int
+hicn_face_ip6_find (hicn_face_id_t *index, u8 *hicnb_flags,
+ const ip6_address_t *nat_addr, u32 sw_if, u32 adj_index,
+ u32 node_index)
+{
+ int ret = HICN_ERROR_FACE_NOT_FOUND;
+ hicn_face_id_t face_id;
+
+ hicn_face_t *face = hicn_face_get ((const ip46_address_t *) nat_addr, sw_if,
+ &hicn_face_hashtb, adj_index);
+
+ if (face != NULL)
+ {
+ /* unlock the face. We don't take a lock on each interest we receive */
+ face_id = hicn_dpoi_get_index (face);
+ hicn_face_unlock_with_id (face_id);
+ *hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
+ *index = face_id;
+
+ ret = HICN_ERROR_FACE_ALREADY_CREATED;
+ }
+
+ return ret;
+}
+
/**
* @brief Retrieve, or create if it doesn't exist, a face from the ip6 local
* address and returns its dpo. This method adds a lock on the face state.
@@ -741,51 +658,59 @@ hicn6_iface_adj_walk_cb (adj_index_t ai, void *ctx)
* @param sw_if: software interface id of the face
* @param node_index: vlib edge index to use in the packet processing
*/
-always_inline void
-hicn_iface_ip6_add_and_lock (hicn_face_id_t *index, u8 *hicnb_flags,
- const ip6_address_t *nat_addr, u32 sw_if,
- u32 adj_index, u32 node_index)
+always_inline int
+hicn_face_ip6_add_and_lock (hicn_face_id_t *index, u8 *hicnb_flags,
+ const ip6_address_t *nat_addr, u32 sw_if,
+ u32 adj_index, u32 node_index)
{
- /*All (complete) faces are indexed by remote addess as well */
- /* if the face exists, it adds a lock */
- hicn_face_t *face = hicn_face_get ((ip46_address_t *) nat_addr, sw_if,
- &hicn_face_hashtb, adj_index);
+ int ret = HICN_ERROR_NONE;
+ hicn_face_t *face = NULL;
- if (face == NULL)
+ ret = hicn_face_ip6_find (index, hicnb_flags, nat_addr, sw_if, adj_index,
+ node_index);
+
+ if (ret == HICN_ERROR_FACE_NOT_FOUND)
{
+ ip46_address_t ip_address = { 0 };
+ ip46_address_set_ip6 (&ip_address, nat_addr);
hicn_face_id_t idx;
- hicn_iface_add ((ip46_address_t *) nat_addr, sw_if, &idx, DPO_PROTO_IP6,
- adj_index);
+ u8 face_flags = *hicnb_flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL ?
+ HICN_FACE_FLAGS_UDP4 :
+ *hicnb_flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL ?
+ HICN_FACE_FLAGS_UDP6 :
+ 0;
- face = hicn_dpoi_get_from_idx (idx);
+ hicn_iface_add ((const ip46_address_t *) nat_addr, sw_if, &idx,
+ adj_index, face_flags);
- face->dpo.dpoi_type = DPO_FIRST;
- face->dpo.dpoi_proto = DPO_PROTO_IP6;
- face->dpo.dpoi_index = adj_index;
- face->dpo.dpoi_next_node = node_index;
+ face = hicn_dpoi_get_from_idx (idx);
+ face->iface_next = node_index;
adj_nbr_walk (face->sw_if, FIB_PROTOCOL_IP6, hicn6_iface_adj_walk_cb,
face);
- *hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
-
+ *hicnb_flags = HICN_BUFFER_FLAGS_NEW_FACE;
*index = idx;
-
- return;
- }
- else
- {
- /* unlock the face. We don't take a lock on each interest we receive */
- hicn_face_id_t face_id = hicn_dpoi_get_index (face);
- hicn_face_unlock_with_id (face_id);
}
- /* Code replicated on purpose */
- *hicnb_flags = HICN_BUFFER_FLAGS_DEFAULT;
- *hicnb_flags |= (face->flags & HICN_FACE_FLAGS_APPFACE_PROD) >>
- HICN_FACE_FLAGS_APPFACE_PROD_BIT;
+ return ret;
+}
+
+/**
+ * @brief Check if a face is an application face
+ *
+ * @param face_id: The id of the face
+ * @return 1 if application face, 0 otherwise
+ */
+always_inline int
+hicn_face_is_local (hicn_face_id_t face_id)
+{
+ hicn_face_t *face;
+ face = hicn_dpoi_get_from_idx (face_id);
+ ASSERT (face != NULL);
- *index = hicn_dpoi_get_index (face);
+ return face->flags & HICN_FACE_FLAGS_APPFACE_PROD ||
+ face->flags & HICN_FACE_FLAGS_APPFACE_CONS;
}
#endif // __HICN_FACE_H__
diff --git a/hicn-plugin/src/faces/face_cli.c b/hicn-plugin/src/faces/face_cli.c
index a4092e6f4..1c1501478 100644
--- a/hicn-plugin/src/faces/face_cli.c
+++ b/hicn-plugin/src/faces/face_cli.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -82,12 +82,12 @@ hicn_face_cli_show_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
HICN_FACE_CTRX_STRING[i]);
if (n)
- _vec_len (n) = 0;
+ vec_set_len (n, 0);
n = format (n, "packets");
s = format (s, "%U%-16v%16Ld", format_white_space,
30 - strlen (HICN_FACE_CTRX_STRING[i]), n, v.packets);
- _vec_len (n) = 0;
+ vec_set_len (n, 0);
n = format (n, "bytes");
s = format (s, "\n%U%-16v%16Ld\n", format_white_space, indent + 30,
n, v.bytes);
@@ -120,13 +120,13 @@ hicn_face_cli_show_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
HICN_FACE_CTRX_STRING[i]);
if (n)
- _vec_len (n) = 0;
+ vec_set_len (n, 0);
n = format (n, "packets");
s = format (s, "%U%-16v%16Ld", format_white_space,
30 - strlen (HICN_FACE_CTRX_STRING[i]),
n, v.packets);
- _vec_len (n) = 0;
+ vec_set_len (n, 0);
n = format (n, "bytes");
s =
format (s, "\n%U%-16v%16Ld\n", format_white_space,
@@ -158,13 +158,13 @@ hicn_face_cli_show_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
HICN_FACE_CTRX_STRING[i]);
if (n)
- _vec_len (n) = 0;
+ vec_set_len (n, 0);
n = format (n, "packets");
s = format (s, "%U%-16v%16Ld", format_white_space,
30 - strlen (HICN_FACE_CTRX_STRING[i]), n,
v.packets);
- _vec_len (n) = 0;
+ vec_set_len (n, 0);
n = format (n, "bytes");
s = format (s, "\n%U%-16v%16Ld\n", format_white_space,
indent + 30, n, v.bytes);
diff --git a/hicn-plugin/src/faces/face_flags.h b/hicn-plugin/src/faces/face_flags.h
new file mode 100644
index 000000000..880d3b558
--- /dev/null
+++ b/hicn-plugin/src/faces/face_flags.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __HICN_FACE_FLAGS_H__
+#define __HICN_FACE_FLAGS_H__
+
+/* Flags */
+/* A face is complete and it stores all the information. A iface lacks of the
+ adj index, therefore sending a packet through a iface require a lookup in
+ the FIB. */
+#define foreach_face_flag \
+ _ (0, FACE, "face") \
+ _ (1, IFACE, "iface") \
+ _ (2, APPFACE_PROD, "face is producer face") \
+ _ (3, APPFACE_CONS, "face is consumer face") \
+ _ (4, DELETED, "face is deleted") \
+ _ (5, UDP4, "face is udp4") \
+ _ (6, UDP6, "face is udp6")
+
+enum
+{
+ HICN_FACE_FLAGS_DEFAULT = 0,
+#define _(a, b, c) HICN_FACE_FLAGS_##b = (1 << a),
+ foreach_face_flag
+#undef _
+};
+
+#endif /* __HICN_FACE_FLAGS_H__ */ \ No newline at end of file
diff --git a/hicn-plugin/src/faces/face_node.c b/hicn-plugin/src/faces/face_node.c
index 5fe682bd0..2cfb9c7dc 100644
--- a/hicn-plugin/src/faces/face_node.c
+++ b/hicn-plugin/src/faces/face_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,6 +23,10 @@
#include "../cache_policies/cs_lru.h"
#include "../infra.h"
#include "../hicn.h"
+#include "../parser.h"
+
+#include <hicn/error.h>
+#include <hicn/util/ip_address.h>
/**
* @File
@@ -56,6 +60,7 @@ typedef struct
u32 next_index;
u32 sw_if_index;
u8 pkt_type;
+ hicn_error_t error;
u8 packet_data[60];
} hicn4_face_input_trace_t;
@@ -73,6 +78,7 @@ typedef struct
u32 next_index;
u32 sw_if_index;
u8 pkt_type;
+ hicn_error_t error;
u8 packet_data[60];
} hicn6_face_input_trace_t;
@@ -86,8 +92,9 @@ typedef enum
#define NEXT_MAPME_IP4 HICN4_FACE_INPUT_NEXT_MAPME
#define NEXT_MAPME_IP6 HICN6_FACE_INPUT_NEXT_MAPME
-#define NEXT_DATA_IP4 HICN4_FACE_INPUT_NEXT_DATA
-#define NEXT_DATA_IP6 HICN6_FACE_INPUT_NEXT_DATA
+
+#define NEXT_DATA_IP4 HICN4_FACE_INPUT_NEXT_DATA
+#define NEXT_DATA_IP6 HICN6_FACE_INPUT_NEXT_DATA
#define NEXT_ERROR_DROP_IP4 HICN4_FACE_INPUT_NEXT_ERROR_DROP
#define NEXT_ERROR_DROP_IP6 HICN6_FACE_INPUT_NEXT_ERROR_DROP
@@ -95,9 +102,6 @@ typedef enum
#define IP_HEADER_4 ip4_header_t
#define IP_HEADER_6 ip6_header_t
-#define LOCK_DPO_FACE_IP4 hicn_face_ip4_lock
-#define LOCK_DPO_FACE_IP6 hicn_face_ip6_lock
-
#define TRACE_INPUT_PKT_IP4 hicn4_face_input_trace_t
#define TRACE_INPUT_PKT_IP6 hicn6_face_input_trace_t
@@ -111,11 +115,13 @@ typedef enum
do \
{ \
vlib_buffer_t *b0; \
- u32 bi0; \
+ u32 bi0, sw_if0; \
u32 next0 = NEXT_ERROR_DROP_IP##ipv; \
+ u8 is_mapme0; \
IP_HEADER_##ipv *ip_hdr = NULL; \
hicn_buffer_t *hicnb0; \
- int ret; \
+ int from_tunnel0; \
+ int ret0 = HICN_ERROR_NONE; \
/* Prefetch for next iteration. */ \
if (n_left_from > 1) \
{ \
@@ -136,33 +142,53 @@ typedef enum
hicnb0 = hicn_get_buffer (b0); \
ip_hdr = (IP_HEADER_##ipv *) vlib_buffer_get_current (b0); \
\
- u8 is_icmp = ip_hdr->protocol == IPPROTO_ICMPV##ipv; \
- \
- next0 = \
- is_icmp * NEXT_MAPME_IP##ipv + (1 - is_icmp) * NEXT_DATA_IP##ipv; \
+ /* Parse packet and cache useful info in opaque2 */ \
+ ret0 = hicn_data_parse_pkt (b0, vlib_buffer_length_in_chain (vm, b0)); \
+ is_mapme0 = hicn_packet_get_type (&hicn_get_buffer (b0)->pkbuf) == \
+ HICN_PACKET_TYPE_MAPME; \
\
- ret = LOCK_DPO_FACE_IP##ipv (&(hicnb0->face_id), \
- &(hicnb0->in_faces_vec_id), \
- &hicnb0->flags, &(ip_hdr->dst_address)); \
+ ret0 = (ret0 == HICN_ERROR_NONE) || \
+ (ret0 == HICN_ERROR_PARSER_MAPME_PACKET); \
\
- if (PREDICT_FALSE (ret != HICN_ERROR_NONE)) \
- next0 = NEXT_ERROR_DROP_IP##ipv; \
+ /* If parsing is ok, send packet to next node */ \
+ if (PREDICT_FALSE (!ret0)) \
+ { \
+ next0 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ } \
else \
{ \
- vlib_increment_combined_counter ( \
- &counters[hicnb0->face_id * HICN_N_COUNTER], thread_index, \
- HICN_FACE_COUNTERS_DATA_RX, 1, \
- vlib_buffer_length_in_chain (vm, b0)); \
- stats.pkts_data_count += 1; \
+ next0 = is_mapme0 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme0) * NEXT_DATA_IP##ipv; \
+ from_tunnel0 = \
+ (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL || \
+ hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) > 0; \
+ sw_if0 = \
+ (from_tunnel0) * ~0 + \
+ (1 - from_tunnel0) * vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ ret0 = hicn_face_ip##ipv##_find ( \
+ &hicnb0->face_id, &hicnb0->flags, &ip_hdr->dst_address, sw_if0, \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX], \
+ /* Should not be used */ ~0); \
+ /* Make sure the face is not created here */ \
+ if (PREDICT_FALSE (ret0 == HICN_ERROR_FACE_NOT_FOUND)) \
+ { \
+ next0 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ } \
} \
\
+ vlib_increment_combined_counter ( \
+ &counters[hicnb0->face_id * HICN_N_COUNTER], thread_index, \
+ HICN_FACE_COUNTERS_DATA_RX, 1, vlib_buffer_length_in_chain (vm, b0)); \
+ stats.pkts_data_count += 1; \
+ \
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) && \
(b0->flags & VLIB_BUFFER_IS_TRACED))) \
{ \
TRACE_INPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ t->error = ret0; \
t->next_index = next0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
sizeof (t->packet_data)); \
@@ -178,13 +204,15 @@ typedef enum
do \
{ \
vlib_buffer_t *b0, *b1; \
- u32 bi0, bi1; \
+ u32 bi0, bi1, sw_if0, sw_if1; \
u32 next0 = NEXT_ERROR_DROP_IP##ipv; \
u32 next1 = NEXT_ERROR_DROP_IP##ipv; \
+ u8 is_mapme0, is_mapme1; \
IP_HEADER_##ipv *ip_hdr0 = NULL; \
IP_HEADER_##ipv *ip_hdr1 = NULL; \
hicn_buffer_t *hicnb0; \
hicn_buffer_t *hicnb1; \
+ int from_tunnel0, from_tunnel1; \
int ret0, ret1; \
/* Prefetch for next iteration. */ \
{ \
@@ -213,52 +241,129 @@ typedef enum
ip_hdr0 = (IP_HEADER_##ipv *) vlib_buffer_get_current (b0); \
ip_hdr1 = (IP_HEADER_##ipv *) vlib_buffer_get_current (b1); \
\
- u8 is_icmp0 = ip_hdr0->protocol == IPPROTO_ICMPV##ipv; \
- u8 is_icmp1 = ip_hdr1->protocol == IPPROTO_ICMPV##ipv; \
- \
- next0 = \
- is_icmp0 * NEXT_MAPME_IP##ipv + (1 - is_icmp0) * NEXT_DATA_IP##ipv; \
- \
- next1 = \
- is_icmp1 * NEXT_MAPME_IP##ipv + (1 - is_icmp1) * NEXT_DATA_IP##ipv; \
- \
- ret0 = LOCK_DPO_FACE_IP##ipv (&(hicnb0->face_id), \
- &(hicnb0->in_faces_vec_id), \
- &hicnb0->flags, &(ip_hdr0->dst_address)); \
- \
- ret1 = LOCK_DPO_FACE_IP##ipv (&(hicnb1->face_id), \
- &(hicnb1->in_faces_vec_id), \
- &hicnb1->flags, &(ip_hdr1->dst_address)); \
- \
- if (PREDICT_FALSE (ret0 != HICN_ERROR_NONE)) \
- next0 = NEXT_ERROR_DROP_IP##ipv; \
- else \
+ /* Parse packet and cache useful info in opaque2 */ \
+ ret0 = hicn_data_parse_pkt (b0, vlib_buffer_length_in_chain (vm, b0)); \
+ ret1 = hicn_data_parse_pkt (b1, vlib_buffer_length_in_chain (vm, b1)); \
+ is_mapme0 = hicn_packet_get_type (&hicn_get_buffer (b0)->pkbuf) == \
+ HICN_PACKET_TYPE_MAPME; \
+ is_mapme1 = hicn_packet_get_type (&hicn_get_buffer (b1)->pkbuf) == \
+ HICN_PACKET_TYPE_MAPME; \
+ ret0 = (ret0 == HICN_ERROR_NONE) || \
+ (ret0 == HICN_ERROR_PARSER_MAPME_PACKET); \
+ ret1 = (ret1 == HICN_ERROR_NONE) || \
+ (ret1 == HICN_ERROR_PARSER_MAPME_PACKET); \
+ if (PREDICT_TRUE (ret0 && ret1)) \
{ \
- vlib_increment_combined_counter ( \
- &counters[hicnb0->face_id * HICN_N_COUNTER], thread_index, \
- HICN_FACE_COUNTERS_DATA_RX, 1, \
- vlib_buffer_length_in_chain (vm, b0)); \
- stats.pkts_data_count += 1; \
+ next0 = is_mapme0 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme0) * NEXT_DATA_IP##ipv; \
+ \
+ next1 = is_mapme1 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme1) * NEXT_DATA_IP##ipv; \
+ \
+ from_tunnel0 = \
+ (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL || \
+ hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) > 0; \
+ sw_if0 = \
+ (from_tunnel0) * ~0 + \
+ (1 - from_tunnel0) * vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ ret0 = hicn_face_ip##ipv##_find ( \
+ &hicnb0->face_id, &hicnb0->flags, &ip_hdr0->dst_address, sw_if0, \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX], \
+ /* Should not be used */ ~0); \
+ /* Make sure the face is not created here */ \
+ if (PREDICT_FALSE (ret0 == HICN_ERROR_FACE_NOT_FOUND)) \
+ { \
+ next0 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ } \
+ \
+ from_tunnel1 = \
+ (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL || \
+ hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) > 0; \
+ sw_if1 = \
+ (from_tunnel1) * ~0 + \
+ (1 - from_tunnel1) * vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
+ ret1 = hicn_face_ip##ipv##_find ( \
+ &hicnb1->face_id, &hicnb1->flags, &ip_hdr1->dst_address, sw_if1, \
+ vnet_buffer (b1)->ip.adj_index[VLIB_RX], \
+ /* Should not be used */ ~0); \
+ /* Make sure the face is not created here */ \
+ if (PREDICT_FALSE (ret1 == HICN_ERROR_FACE_NOT_FOUND)) \
+ { \
+ next1 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ } \
+ } \
+ else if (ret0 && !ret1) \
+ { \
+ next1 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ from_tunnel0 = \
+ (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL || \
+ hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) > 0; \
+ sw_if0 = \
+ (from_tunnel0) * ~0 + \
+ (1 - from_tunnel0) * vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ ret0 = hicn_face_ip##ipv##_find ( \
+ &hicnb0->face_id, &hicnb0->flags, &ip_hdr0->dst_address, sw_if0, \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX], \
+ /* Should not be used */ ~0); \
+ /* Make sure the face is not created here */ \
+ if (PREDICT_FALSE (ret0 == HICN_ERROR_FACE_NOT_FOUND)) \
+ { \
+ next0 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ } \
+ else \
+ { \
+ next0 = is_mapme0 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme0) * NEXT_DATA_IP##ipv; \
+ } \
+ } \
+ else if (!ret0 && ret1) \
+ { \
+ next0 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ from_tunnel1 = \
+ (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL || \
+ hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) > 0; \
+ sw_if1 = \
+ (from_tunnel1) * ~0 + \
+ (1 - from_tunnel1) * vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
+ ret1 = hicn_face_ip##ipv##_find ( \
+ &hicnb1->face_id, &hicnb1->flags, &ip_hdr1->dst_address, sw_if1, \
+ vnet_buffer (b1)->ip.adj_index[VLIB_RX], \
+ /* Should not be used */ ~0); \
+ /* Make sure the face is not created here */ \
+ if (PREDICT_FALSE (ret1 == HICN_ERROR_FACE_NOT_FOUND)) \
+ { \
+ next1 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ } \
+ else \
+ { \
+ next1 = is_mapme1 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme1) * NEXT_DATA_IP##ipv; \
+ } \
} \
- \
- if (PREDICT_FALSE (ret1 != HICN_ERROR_NONE)) \
- next1 = NEXT_ERROR_DROP_IP##ipv; \
else \
{ \
- vlib_increment_combined_counter ( \
- &counters[hicnb1->face_id * HICN_N_COUNTER], thread_index, \
- HICN_FACE_COUNTERS_DATA_RX, 1, \
- vlib_buffer_length_in_chain (vm, b1)); \
- stats.pkts_data_count += 1; \
+ next0 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
+ next1 = HICN##ipv##_FACE_INPUT_NEXT_ERROR_DROP; \
} \
\
+ vlib_increment_combined_counter ( \
+ &counters[hicnb0->face_id * HICN_N_COUNTER], thread_index, \
+ HICN_FACE_COUNTERS_DATA_RX, 1, vlib_buffer_length_in_chain (vm, b0)); \
+ stats.pkts_data_count += 1; \
+ \
+ vlib_increment_combined_counter ( \
+ &counters[hicnb1->face_id * HICN_N_COUNTER], thread_index, \
+ HICN_FACE_COUNTERS_DATA_RX, 1, vlib_buffer_length_in_chain (vm, b1)); \
+ stats.pkts_data_count += 1; \
+ \
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) && \
(b0->flags & VLIB_BUFFER_IS_TRACED))) \
{ \
TRACE_INPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ t->error = ret0; \
t->next_index = next0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
sizeof (t->packet_data)); \
@@ -269,8 +374,9 @@ typedef enum
{ \
TRACE_INPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b1, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
+ t->error = ret1; \
t->next_index = next1; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b1), \
sizeof (t->packet_data)); \
@@ -437,6 +543,7 @@ VLIB_REGISTER_NODE(hicn6_face_input_node) =
typedef enum
{
+ HICN4_FACE_OUTPUT_NEXT_ERROR_DROP,
HICN4_FACE_OUTPUT_NEXT_ECHO_REPLY,
HICN4_FACE_OUTPUT_NEXT_UDP4_ENCAP,
HICN4_FACE_OUTPUT_NEXT_UDP6_ENCAP,
@@ -445,86 +552,13 @@ typedef enum
typedef enum
{
+ HICN6_FACE_OUTPUT_NEXT_ERROR_DROP,
HICN6_FACE_OUTPUT_NEXT_ECHO_REPLY,
HICN6_FACE_OUTPUT_NEXT_UDP4_ENCAP,
HICN6_FACE_OUTPUT_NEXT_UDP6_ENCAP,
HICN6_FACE_OUTPUT_N_NEXT,
} hicn6_face_output_next_t;
-/* static_always_inline void */
-/* hicn_reply_probe_v4 (vlib_buffer_t * b, hicn_face_t * face) */
-/* { */
-/* hicn_header_t *h0 = vlib_buffer_get_current (b); */
-/* hicn_face_ip_t * face_ip = (hicn_face_ip_t *)(&face->data); */
-/* h0->v4.ip.saddr = h0->v4.ip.daddr; */
-/* h0->v4.ip.daddr = face_ip->local_addr.ip4; */
-/* vnet_buffer (b)->sw_if_index[VLIB_RX] = face->shared.sw_if; */
-
-/* u16 * dst_port_ptr = (u16 *)(((u8*)h0) + sizeof(ip4_header_t) +
- * sizeof(u16)); */
-/* u16 dst_port = *dst_port_ptr; */
-/* u16 * src_port_ptr = (u16 *)(((u8*)h0) + sizeof(ip4_header_t)); */
-
-/* *dst_port_ptr = *src_port_ptr; */
-/* *src_port_ptr = dst_port; */
-
-/* hicn_type_t type = hicn_get_buffer (b)->type; */
-/* hicn_ops_vft[type.l1]->set_lifetime (type, &h0->protocol, 0); */
-/* } */
-
-/* static_always_inline void */
-/* hicn_reply_probe_v6 (vlib_buffer_t * b, hicn_face_t * face) */
-/* { */
-/* hicn_header_t *h0 = vlib_buffer_get_current (b); */
-/* hicn_face_ip_t * face_ip = (hicn_face_ip_t *)(&face->data); */
-/* h0->v6.ip.saddr = h0->v6.ip.daddr; */
-/* h0->v6.ip.daddr = face_ip->local_addr.ip6; */
-/* vnet_buffer (b)->sw_if_index[VLIB_RX] = face->shared.sw_if; */
-
-/* u16 * dst_port_ptr = (u16 *)(((u8*)h0) + sizeof(ip6_header_t) +
- * sizeof(u16)); */
-/* u16 dst_port = *dst_port_ptr; */
-/* u16 * src_port_ptr = (u16 *)(((u8*)h0) + sizeof(ip6_header_t)); */
-
-/* *dst_port_ptr = *src_port_ptr; */
-/* *src_port_ptr = dst_port; */
-
-/* hicn_type_t type = hicn_get_buffer (b)->type; */
-/* hicn_ops_vft[type.l1]->set_lifetime (type, &h0->protocol, 0); */
-
-/* } */
-
-/* static_always_inline u32 */
-/* hicn_face_match_probe (vlib_buffer_t * b, hicn_face_t * face, u32 * next) */
-/* { */
-
-/* u8 *ptr = vlib_buffer_get_current (b); */
-/* u8 v = *ptr & 0xf0; */
-/* u8 res = 0; */
-
-/* if ( v == 0x40 ) */
-/* { */
-/* u16 * dst_port = (u16 *)(ptr + sizeof(ip4_header_t) + sizeof(u16)); */
-/* if (*dst_port == clib_net_to_host_u16(DEFAULT_PROBING_PORT)) */
-/* { */
-/* hicn_reply_probe_v6(b, face); */
-/* *next = HICN4_FACE_NEXT_ECHO_REPLY; */
-/* res = 1; */
-/* } */
-/* } */
-/* else if ( v == 0x60 ) */
-/* { */
-/* u16 * dst_port = (u16 *)(ptr + sizeof(ip6_header_t) + sizeof(u16)); */
-/* if (*dst_port == clib_net_to_host_u16(DEFAULT_PROBING_PORT)) */
-/* { */
-/* hicn_reply_probe_v6(b, face); */
-/* *next = HICN6_FACE_NEXT_ECHO_REPLY; */
-/* res = 1; */
-/* } */
-/* } */
-/* return res; */
-/* } */
-
static inline void
hicn_face_rewrite_interest (vlib_main_t *vm, vlib_buffer_t *b0,
hicn_face_t *face, u32 *next)
@@ -534,19 +568,20 @@ hicn_face_rewrite_interest (vlib_main_t *vm, vlib_buffer_t *b0,
* hicn_face_match_probe(b0, face, next)) */
/* return; */
- hicn_header_t *hicn = vlib_buffer_get_current (b0);
+ hicn_packet_buffer_t *pkbuf = &hicn_get_buffer (b0)->pkbuf;
- // hicn_face_ip_t *ip_face = (hicn_face_ip_t *) face->data;
+ u8 is_v4 = ip46_address_is_ip4 (&face->nat_addr) &&
+ !ip6_address_is_loopback (&face->nat_addr.ip6);
- ip46_address_t temp_addr;
- ip46_address_reset (&temp_addr);
- hicn_type_t type = hicn_get_buffer (b0)->type;
- int ret = hicn_ops_vft[type.l1]->rewrite_interest (
- type, &hicn->protocol, &face->nat_addr, &temp_addr);
+ // hicn_face_ip_t *ip_face = (hicn_face_ip_t *) face->data;
+ hicn_ip_address_t temp_addr;
+ ip46_address_reset (&(temp_addr.as_ip46));
+ hicn_ip_address_t *face_nat_addr = (hicn_ip_address_t *) &face->nat_addr;
+ int ret = hicn_interest_rewrite (pkbuf, face_nat_addr, &temp_addr);
if (ret == HICN_LIB_ERROR_REWRITE_CKSUM_REQUIRED)
{
- ensure_offload_flags (b0, ip46_address_is_ip4 (&face->nat_addr));
+ ensure_offload_flags (b0, is_v4);
}
ASSERT (face->flags & HICN_FACE_FLAGS_FACE);
@@ -571,6 +606,7 @@ static char *hicn6_face_output_error_strings[] = {
typedef struct
{
u32 next_index;
+ u32 next_node;
u32 sw_if_index;
u8 pkt_type;
u8 packet_data[60];
@@ -580,6 +616,7 @@ typedef struct
typedef struct
{
u32 next_index;
+ u32 next_node;
u32 sw_if_index;
u8 pkt_type;
u8 packet_data[60];
@@ -593,8 +630,8 @@ typedef struct
{ \
vlib_buffer_t *b0; \
u32 bi0; \
- u32 next0 = ~0; \
- hicn_face_t *face; \
+ u32 next0 = HICN##ipv##_FACE_OUTPUT_NEXT_ERROR_DROP; \
+ hicn_face_t *face = NULL; \
\
/* Prefetch for next iteration. */ \
if (n_left_from > 1) \
@@ -615,9 +652,10 @@ typedef struct
b0 = vlib_get_buffer (vm, bi0); \
\
hicn_face_id_t face_id = vnet_buffer (b0)->ip.adj_index[VLIB_TX]; \
- face = hicn_dpoi_get_from_idx (face_id); \
+ if (PREDICT_TRUE (hicn_dpoi_idx_is_valid (face_id))) \
+ face = hicn_dpoi_get_from_idx (face_id); \
\
- if (PREDICT_TRUE (face != NULL)) \
+ if (PREDICT_TRUE (face != NULL) && face->flags & HICN_FACE_FLAGS_FACE) \
{ \
hicn_face_rewrite_interest (vm, b0, face, &next0); \
stats.pkts_interest_count += 1; \
@@ -632,9 +670,10 @@ typedef struct
{ \
TRACE_OUTPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
- t->next_index = next0; \
+ t->next_index = vnet_buffer (b0)->ip.adj_index[VLIB_TX]; \
+ t->next_node = next0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
sizeof (t->packet_data)); \
} \
@@ -650,9 +689,9 @@ typedef struct
{ \
vlib_buffer_t *b0, *b1; \
u32 bi0, bi1; \
- u32 next0 = ~0; \
- u32 next1 = ~0; \
- hicn_face_t *face0, *face1; \
+ u32 next0 = HICN##ipv##_FACE_OUTPUT_NEXT_ERROR_DROP; \
+ u32 next1 = HICN##ipv##_FACE_OUTPUT_NEXT_ERROR_DROP; \
+ hicn_face_t *face0 = NULL, *face1 = NULL; \
\
/* Prefetch for next iteration. */ \
{ \
@@ -679,10 +718,13 @@ typedef struct
\
hicn_face_id_t face_id0 = vnet_buffer (b0)->ip.adj_index[VLIB_TX]; \
hicn_face_id_t face_id1 = vnet_buffer (b1)->ip.adj_index[VLIB_TX]; \
- face0 = hicn_dpoi_get_from_idx (face_id0); \
- face1 = hicn_dpoi_get_from_idx (face_id1); \
+ if (PREDICT_TRUE (hicn_dpoi_idx_is_valid (face_id0))) \
+ face0 = hicn_dpoi_get_from_idx (face_id0); \
+ if (PREDICT_TRUE (hicn_dpoi_idx_is_valid (face_id1))) \
+ face1 = hicn_dpoi_get_from_idx (face_id1); \
\
- if (PREDICT_TRUE (face0 != NULL)) \
+ if (PREDICT_TRUE (face0 != NULL) && \
+ face0->flags & HICN_FACE_FLAGS_FACE) \
{ \
hicn_face_rewrite_interest (vm, b0, face0, &next0); \
stats.pkts_interest_count += 1; \
@@ -692,7 +734,8 @@ typedef struct
vlib_buffer_length_in_chain (vm, b0)); \
} \
\
- if (PREDICT_TRUE (face1 != NULL)) \
+ if (PREDICT_TRUE (face1 != NULL) && \
+ face1->flags & HICN_FACE_FLAGS_FACE) \
{ \
hicn_face_rewrite_interest (vm, b1, face1, &next1); \
stats.pkts_interest_count += 1; \
@@ -707,9 +750,10 @@ typedef struct
{ \
TRACE_OUTPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
- t->next_index = next0; \
+ t->next_index = vnet_buffer (b0)->ip.adj_index[VLIB_TX]; \
+ t->next_node = next0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
sizeof (t->packet_data)); \
} \
@@ -719,13 +763,13 @@ typedef struct
{ \
TRACE_OUTPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b1, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
- t->next_index = next1; \
+ t->next_index = vnet_buffer (b1)->ip.adj_index[VLIB_TX]; \
+ t->next_node = next1; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b1), \
sizeof (t->packet_data)); \
} \
- \
/* Verify speculative enqueue, maybe switch current next frame */ \
vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next, \
n_left_to_next, bi0, bi1, next0, \
@@ -778,8 +822,10 @@ hicn4_face_output_format_trace (u8 *s, va_list *args)
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
hicn4_face_output_trace_t *t = va_arg (*args, hicn4_face_output_trace_t *);
- s = format (s, "FACE_IP4_OUTPUT: pkt: %d, sw_if_index %d, next index %d\n%U",
- (int) t->pkt_type, t->sw_if_index, t->next_index,
+ s = format (s,
+ "FACE_IP4_OUTPUT: pkt: %d, sw_if_index %d, next index %d, next "
+ "node: %d\n%U",
+ (int) t->pkt_type, t->sw_if_index, t->next_index, t->next_node,
format_ip4_header, t->packet_data, sizeof (t->packet_data));
return (s);
}
@@ -795,11 +841,7 @@ VLIB_REGISTER_NODE (hicn4_face_output_node) = {
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN (hicn4_face_output_error_strings),
.error_strings = hicn4_face_output_error_strings,
- .n_next_nodes = HICN4_FACE_OUTPUT_N_NEXT,
- /* Reusing the list of nodes from lookup to be compatible with arp */
- .next_nodes = { [HICN4_FACE_OUTPUT_NEXT_ECHO_REPLY] = "hicn4-face-input",
- [HICN4_FACE_OUTPUT_NEXT_UDP4_ENCAP] = "udp4-encap",
- [HICN4_FACE_OUTPUT_NEXT_UDP6_ENCAP] = "udp6-encap" }
+ .sibling_of = "ip4-lookup",
};
static uword
@@ -847,8 +889,10 @@ hicn6_face_output_format_trace (u8 *s, va_list *args)
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
hicn6_face_output_trace_t *t = va_arg (*args, hicn6_face_output_trace_t *);
- s = format (s, "FACE_IP6_OUTPUT: pkt: %d, sw_if_index %d, next index %d\n%U",
- (int) t->pkt_type, t->sw_if_index, t->next_index,
+ s = format (s,
+ "FACE_IP6_OUTPUT: pkt: %d, sw_if_index %d, next index %d, next "
+ "node: %d\n%U",
+ (int) t->pkt_type, t->sw_if_index, t->next_index, t->next_node,
format_ip6_header, t->packet_data, sizeof (t->packet_data));
return (s);
}
@@ -864,12 +908,7 @@ VLIB_REGISTER_NODE (hicn6_face_output_node) = {
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN (hicn6_face_output_error_strings),
.error_strings = hicn6_face_output_error_strings,
- .n_next_nodes = HICN6_FACE_OUTPUT_N_NEXT,
- /* Reusing the list of nodes from lookup to be compatible with neighbour
- discovery */
- .next_nodes = { [HICN6_FACE_OUTPUT_NEXT_ECHO_REPLY] = "hicn6-face-input",
- [HICN6_FACE_OUTPUT_NEXT_UDP4_ENCAP] = "udp4-encap",
- [HICN6_FACE_OUTPUT_NEXT_UDP6_ENCAP] = "udp6-encap" }
+ .sibling_of = "ip6-lookup",
};
/*
diff --git a/hicn-plugin/src/faces/face_node.h b/hicn-plugin/src/faces/face_node.h
index 3b38e71b3..70daa1393 100644
--- a/hicn-plugin/src/faces/face_node.h
+++ b/hicn-plugin/src/faces/face_node.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/faces/iface_node.c b/hicn-plugin/src/faces/iface_node.c
index bf9c56515..8b74c6c25 100644
--- a/hicn-plugin/src/faces/iface_node.c
+++ b/hicn-plugin/src/faces/iface_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,6 +19,11 @@
#include "../hicn.h"
#include "../infra.h"
#include "../cache_policies/cs_lru.h"
+#include "../parser.h"
+#include "iface_node.h"
+
+#include <hicn/error.h>
+#include <hicn/util/ip_address.h>
/**
* @File
@@ -52,12 +57,14 @@ typedef struct
u32 next_index;
u32 sw_if_index;
u8 pkt_type;
+ hicn_error_t error;
u8 packet_data[60];
} hicn4_iface_input_trace_t;
typedef enum
{
HICN4_IFACE_INPUT_NEXT_INTEREST,
+ HICN4_IFACE_INPUT_NEXT_INTEREST_MANIFEST,
HICN4_IFACE_INPUT_NEXT_MAPME,
HICN4_IFACE_INPUT_NEXT_ERROR_DROP,
HICN4_IFACE_INPUT_N_NEXT,
@@ -69,12 +76,14 @@ typedef struct
u32 next_index;
u32 sw_if_index;
u8 pkt_type;
+ hicn_error_t error;
u8 packet_data[60];
} hicn6_iface_input_trace_t;
typedef enum
{
HICN6_IFACE_INPUT_NEXT_INTEREST,
+ HICN6_IFACE_INPUT_NEXT_INTEREST_MANIFEST,
HICN6_IFACE_INPUT_NEXT_MAPME,
HICN6_IFACE_INPUT_NEXT_ERROR_DROP,
HICN6_IFACE_INPUT_N_NEXT,
@@ -86,32 +95,8 @@ typedef enum
#define NEXT_INTEREST_IP4 HICN4_IFACE_INPUT_NEXT_INTEREST
#define NEXT_INTEREST_IP6 HICN6_IFACE_INPUT_NEXT_INTEREST
-#define ADDRESS_IP4 \
- ip_interface_address_t *ia = 0; \
- ip4_address_t *local_address = \
- ip4_interface_first_address (&ip4_main, swif, &ia)
-#define ADDRESS_IP6 \
- ip6_address_t *local_address = ip6_interface_first_address (&ip6_main, swif)
-
-#define ADDRESSX2_IP4 \
- ip_interface_address_t *ia0, *ia1; \
- ia0 = ia1 = 0; \
- ip4_address_t *local_address0 = \
- ip4_interface_first_address (&ip4_main, swif0, &ia0); \
- ip4_address_t *local_address1 = \
- ip4_interface_first_address (&ip4_main, swif1, &ia1);
-
-#define ADDRESSX2_IP6 \
- ip6_address_t *local_address0 = \
- ip6_interface_first_address (&ip6_main, swif0); \
- ip6_address_t *local_address1 = \
- ip6_interface_first_address (&ip6_main, swif1);
-
-#define DPO_ADD_LOCK_IFACE_IP4 hicn_iface_ip4_add_and_lock
-#define DPO_ADD_LOCK_IFACE_IP6 hicn_iface_ip6_add_and_lock
-
-//#define VLIB_EDGE_IP4 data_fwd_iface_ip4_vlib_edge
-//#define VLIB_EDGE_IP6 data_fwd_iface_ip6_vlib_edge
+#define DPO_ADD_LOCK_FACE_IP4 hicn_face_ip4_add_and_lock
+#define DPO_ADD_LOCK_FACE_IP6 hicn_face_ip6_add_and_lock
#define IP_HEADER_4 ip4_header_t
#define IP_HEADER_6 ip6_header_t
@@ -142,14 +127,6 @@ typedef struct
u8 packet_data[60];
} hicn4_iface_output_trace_t;
-typedef enum
-{
- HICN4_IFACE_OUTPUT_NEXT_LOOKUP,
- HICN4_IFACE_OUTPUT_NEXT_UDP4_ENCAP,
- HICN4_IFACE_OUTPUT_NEXT_UDP6_ENCAP,
- HICN4_IFACE_OUTPUT_N_NEXT,
-} hicn4_iface_output_next_t;
-
/* Trace context struct */
typedef struct
{
@@ -159,14 +136,6 @@ typedef struct
u8 packet_data[60];
} hicn6_iface_output_trace_t;
-typedef enum
-{
- HICN6_IFACE_OUTPUT_NEXT_LOOKUP,
- HICN6_IFACE_OUTPUT_NEXT_UDP4_ENCAP,
- HICN6_IFACE_OUTPUT_NEXT_UDP6_ENCAP,
- HICN6_IFACE_OUTPUT_N_NEXT,
-} hicn6_iface_output_next_t;
-
//#define ERROR_OUTPUT_IP4 HICN4_IFACE_OUTPUT_NEXT_ERROR_DROP
//#define ERROR_OUTPUT_IP6 HICN6_IFACE_OUTPUT_NEXT_ERROR_DROP
@@ -176,6 +145,9 @@ typedef enum
#define NEXT_UDP_ENCAP_IP4 HICN4_IFACE_OUTPUT_NEXT_UDP4_ENCAP
#define NEXT_UDP_ENCAP_IP6 HICN6_IFACE_OUTPUT_NEXT_UDP6_ENCAP
+#define NEXT_PG4 HICN4_IFACE_OUTPUT_NEXT_PG
+#define NEXT_PG6 HICN6_IFACE_OUTPUT_NEXT_PG
+
#define HICN_REWRITE_DATA_IP4 hicn_rewrite_iface_data4
#define HICN_REWRITE_DATA_IP6 hicn_rewrite_iface_data6
@@ -188,9 +160,11 @@ typedef enum
do \
{ \
vlib_buffer_t *b0; \
- u32 bi0, next0, next_iface0; \
+ u32 bi0, next0, next_iface0, sw_if0 = ~0; \
IP_HEADER_##ipv *ip_hdr = NULL; \
hicn_buffer_t *hicnb0; \
+ int ret0 = HICN_ERROR_NONE; \
+ u8 is_mapme0, is_manifest0; \
/* Prefetch for next iteration. */ \
if (n_left_from > 1) \
{ \
@@ -211,33 +185,58 @@ typedef enum
hicnb0 = hicn_get_buffer (b0); \
ip_hdr = (IP_HEADER_##ipv *) vlib_buffer_get_current (b0); \
\
- stats.pkts_interest_count += 1; \
- \
- u8 is_icmp = ip_hdr->protocol == IPPROTO_ICMPV##ipv; \
- \
- next0 = \
- is_icmp * NEXT_MAPME_IP##ipv + (1 - is_icmp) * NEXT_INTEREST_IP##ipv; \
- \
- next_iface0 = NEXT_DATA_LOOKUP_IP##ipv; \
- \
- if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL) \
- next_iface0 = NEXT_UDP_ENCAP_IP4; \
- else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) \
- next_iface0 = NEXT_UDP_ENCAP_IP6; \
- \
- DPO_ADD_LOCK_IFACE_IP##ipv ( \
- &(hicnb0->face_id), &hicnb0->flags, &(ip_hdr->src_address), \
- vnet_buffer (b0)->sw_if_index[VLIB_RX], \
- vnet_buffer (b0)->ip.adj_index[VLIB_RX], next_iface0); \
+ /* Parse packet and cache useful info in opaque2 */ \
+ ret0 = \
+ hicn_interest_parse_pkt (b0, vlib_buffer_length_in_chain (vm, b0)); \
+ is_mapme0 = hicn_packet_get_type (&hicn_get_buffer (b0)->pkbuf) == \
+ HICN_PACKET_TYPE_MAPME; \
+ is_manifest0 = hicnb0->payload_type == HPT_MANIFEST; \
+ ret0 = (ret0 == HICN_ERROR_NONE) || \
+ (ret0 == HICN_ERROR_PARSER_MAPME_PACKET); \
+ if (PREDICT_FALSE (!ret0)) \
+ { \
+ next0 = HICN##ipv##_IFACE_INPUT_NEXT_ERROR_DROP; \
+ } \
+ else \
+ { \
+ next0 = is_mapme0 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme0) * (NEXT_INTEREST_IP##ipv + is_manifest0); \
+ \
+ next_iface0 = NEXT_DATA_LOOKUP_IP##ipv; \
+ sw_if0 = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ \
+ if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL && \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] != ADJ_INDEX_INVALID) \
+ { \
+ next_iface0 = NEXT_UDP_ENCAP_IP4; \
+ sw_if0 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL && \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] != \
+ ADJ_INDEX_INVALID) \
+ { \
+ next_iface0 = NEXT_UDP_ENCAP_IP6; \
+ sw_if0 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_PG) \
+ { \
+ next_iface0 = NEXT_PG##ipv; \
+ } \
+ \
+ DPO_ADD_LOCK_FACE_IP##ipv ( \
+ &(hicnb0->face_id), &hicnb0->flags, &(ip_hdr->src_address), \
+ sw_if0, vnet_buffer (b0)->ip.adj_index[VLIB_RX], next_iface0); \
+ } \
\
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) && \
(b0->flags & VLIB_BUFFER_IS_TRACED))) \
{ \
TRACE_INPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
- t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
+ t->sw_if_index = sw_if0; \
t->next_index = next0; \
+ t->error = ret0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
sizeof (t->packet_data)); \
} \
@@ -257,9 +256,12 @@ typedef enum
do \
{ \
vlib_buffer_t *b0, *b1; \
- u32 bi0, bi1, next0, next1, next_iface0, next_iface1; \
+ u32 bi0, bi1, next0, next1; \
+ u32 next_iface0, next_iface1, sw_if0 = ~0, sw_if1 = ~0; \
+ u8 is_mapme0, is_mapme1, is_manifest0, is_manifest1; \
IP_HEADER_##ipv *ip_hdr0 = NULL; \
IP_HEADER_##ipv *ip_hdr1 = NULL; \
+ int ret0 = HICN_ERROR_NONE, ret1 = HICN_ERROR_NONE; \
hicn_buffer_t *hicnb0, *hicnb1; \
\
/* Prefetch for next iteration. */ \
@@ -290,47 +292,155 @@ typedef enum
\
stats.pkts_interest_count += 2; \
\
- u8 is_icmp0 = ip_hdr0->protocol == IPPROTO_ICMPV##ipv; \
- u8 is_icmp1 = ip_hdr1->protocol == IPPROTO_ICMPV##ipv; \
- \
- next0 = is_icmp0 * NEXT_MAPME_IP##ipv + \
- (1 - is_icmp0) * NEXT_INTEREST_IP##ipv; \
- \
- next1 = is_icmp1 * NEXT_MAPME_IP##ipv + \
- (1 - is_icmp1) * NEXT_INTEREST_IP##ipv; \
- \
- next_iface0 = NEXT_DATA_LOOKUP_IP##ipv; \
- \
- if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL) \
- next_iface0 = NEXT_UDP_ENCAP_IP4; \
- else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) \
- next_iface0 = NEXT_UDP_ENCAP_IP6; \
- \
- next_iface1 = NEXT_DATA_LOOKUP_IP##ipv; \
- \
- if (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL) \
- next_iface1 = NEXT_UDP_ENCAP_IP4; \
- else if (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL) \
- next_iface1 = NEXT_UDP_ENCAP_IP6; \
- \
- DPO_ADD_LOCK_IFACE_IP##ipv ( \
- &(hicnb0->face_id), &hicnb0->flags, &(ip_hdr0->src_address), \
- vnet_buffer (b0)->sw_if_index[VLIB_RX], \
- vnet_buffer (b0)->ip.adj_index[VLIB_RX], next_iface0); \
- \
- DPO_ADD_LOCK_IFACE_IP##ipv ( \
- &(hicnb1->face_id), &hicnb1->flags, &(ip_hdr1->src_address), \
- vnet_buffer (b1)->sw_if_index[VLIB_RX], \
- vnet_buffer (b1)->ip.adj_index[VLIB_RX], next_iface1); \
+ /* Parse packet and cache useful info in opaque2 */ \
+ ret0 = \
+ hicn_interest_parse_pkt (b0, vlib_buffer_length_in_chain (vm, b0)); \
+ ret1 = \
+ hicn_interest_parse_pkt (b1, vlib_buffer_length_in_chain (vm, b1)); \
+ is_mapme0 = hicn_packet_get_type (&hicn_get_buffer (b0)->pkbuf) == \
+ HICN_PACKET_TYPE_MAPME; \
+ is_mapme1 = hicn_packet_get_type (&hicn_get_buffer (b1)->pkbuf) == \
+ HICN_PACKET_TYPE_MAPME; \
+ is_manifest0 = hicnb0->payload_type == HPT_MANIFEST; \
+ is_manifest1 = hicnb1->payload_type == HPT_MANIFEST; \
+ ret0 = (ret0 == HICN_ERROR_NONE) || \
+ (ret0 == HICN_ERROR_PARSER_MAPME_PACKET); \
+ ret1 = (ret1 == HICN_ERROR_NONE) || \
+ (ret1 == HICN_ERROR_PARSER_MAPME_PACKET); \
+ \
+ if (PREDICT_TRUE (ret0 && ret1)) \
+ { \
+ next0 = is_mapme0 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme0) * (NEXT_INTEREST_IP##ipv + is_manifest0); \
+ \
+ next1 = is_mapme1 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme1) * (NEXT_INTEREST_IP##ipv + is_manifest1); \
+ \
+ next_iface0 = NEXT_DATA_LOOKUP_IP##ipv; \
+ sw_if0 = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ \
+ if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL && \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] != ADJ_INDEX_INVALID) \
+ { \
+ next_iface0 = NEXT_UDP_ENCAP_IP4; \
+ sw_if0 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL && \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] != \
+ ADJ_INDEX_INVALID) \
+ { \
+ next_iface0 = NEXT_UDP_ENCAP_IP6; \
+ sw_if0 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_PG) \
+ { \
+ next_iface0 = NEXT_PG##ipv; \
+ } \
+ \
+ next_iface1 = NEXT_DATA_LOOKUP_IP##ipv; \
+ sw_if1 = vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
+ \
+ if (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL && \
+ vnet_buffer (b1)->ip.adj_index[VLIB_RX] != ADJ_INDEX_INVALID) \
+ { \
+ next_iface1 = NEXT_UDP_ENCAP_IP4; \
+ sw_if1 = ~0; \
+ } \
+ else if (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL && \
+ vnet_buffer (b1)->ip.adj_index[VLIB_RX] != \
+ ADJ_INDEX_INVALID) \
+ { \
+ next_iface1 = NEXT_UDP_ENCAP_IP6; \
+ sw_if1 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_PG) \
+ { \
+ next_iface1 = NEXT_PG##ipv; \
+ } \
+ \
+ DPO_ADD_LOCK_FACE_IP##ipv ( \
+ &(hicnb0->face_id), &hicnb0->flags, &(ip_hdr0->src_address), \
+ sw_if0, vnet_buffer (b0)->ip.adj_index[VLIB_RX], next_iface0); \
+ \
+ DPO_ADD_LOCK_FACE_IP##ipv ( \
+ &(hicnb1->face_id), &hicnb1->flags, &(ip_hdr1->src_address), \
+ sw_if1, vnet_buffer (b1)->ip.adj_index[VLIB_RX], next_iface1); \
+ } \
+ else if (ret0 && !ret1) \
+ { \
+ next1 = HICN##ipv##_IFACE_INPUT_NEXT_ERROR_DROP; \
+ next0 = is_mapme0 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme0) * NEXT_INTEREST_IP##ipv; \
+ next_iface0 = NEXT_DATA_LOOKUP_IP##ipv; \
+ sw_if0 = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ \
+ if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL && \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] != ADJ_INDEX_INVALID) \
+ { \
+ next_iface0 = NEXT_UDP_ENCAP_IP4; \
+ sw_if0 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL && \
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] != \
+ ADJ_INDEX_INVALID) \
+ { \
+ next_iface0 = NEXT_UDP_ENCAP_IP6; \
+ sw_if0 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_PG) \
+ { \
+ next_iface0 = NEXT_PG##ipv; \
+ } \
+ \
+ DPO_ADD_LOCK_FACE_IP##ipv ( \
+ &(hicnb0->face_id), &hicnb0->flags, &(ip_hdr0->src_address), \
+ sw_if0, vnet_buffer (b0)->ip.adj_index[VLIB_RX], next_iface0); \
+ } \
+ else if (!ret0 && ret1) \
+ { \
+ next0 = HICN##ipv##_IFACE_INPUT_NEXT_ERROR_DROP; \
+ next_iface1 = NEXT_DATA_LOOKUP_IP##ipv; \
+ sw_if1 = vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
+ next1 = is_mapme1 * NEXT_MAPME_IP##ipv + \
+ (1 - is_mapme1) * NEXT_INTEREST_IP##ipv; \
+ \
+ if (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL && \
+ vnet_buffer (b1)->ip.adj_index[VLIB_RX] != ADJ_INDEX_INVALID) \
+ { \
+ next_iface1 = NEXT_UDP_ENCAP_IP4; \
+ sw_if1 = ~0; \
+ } \
+ else if (hicnb1->flags & HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL && \
+ vnet_buffer (b1)->ip.adj_index[VLIB_RX] != \
+ ADJ_INDEX_INVALID) \
+ { \
+ next_iface1 = NEXT_UDP_ENCAP_IP6; \
+ sw_if1 = ~0; \
+ } \
+ else if (hicnb0->flags & HICN_BUFFER_FLAGS_FROM_PG) \
+ { \
+ next_iface1 = NEXT_PG##ipv; \
+ } \
+ \
+ DPO_ADD_LOCK_FACE_IP##ipv ( \
+ &(hicnb1->face_id), &hicnb1->flags, &(ip_hdr1->src_address), \
+ sw_if1, vnet_buffer (b1)->ip.adj_index[VLIB_RX], next_iface1); \
+ } \
+ else \
+ { \
+ next0 = HICN##ipv##_IFACE_INPUT_NEXT_ERROR_DROP; \
+ next1 = HICN##ipv##_IFACE_INPUT_NEXT_ERROR_DROP; \
+ } \
\
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) && \
(b0->flags & VLIB_BUFFER_IS_TRACED))) \
{ \
TRACE_INPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
- t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
+ t->sw_if_index = sw_if0; \
t->next_index = next0; \
+ t->error = ret0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
sizeof (t->packet_data)); \
} \
@@ -340,9 +450,10 @@ typedef enum
{ \
TRACE_INPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b1, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
- t->sw_if_index = vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
+ t->sw_if_index = sw_if1; \
t->next_index = next1; \
+ t->error = ret1; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b1), \
sizeof (t->packet_data)); \
} \
@@ -409,9 +520,17 @@ hicn4_iface_input_format_trace (u8 *s, va_list *args)
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
hicn4_iface_input_trace_t *t = va_arg (*args, hicn4_iface_input_trace_t *);
- s = format (s, "IFACE_IP4_INPUT: pkt: %d, sw_if_index %d, next index %d\n%U",
- (int) t->pkt_type, t->sw_if_index, t->next_index,
- format_ip4_header, t->packet_data, sizeof (t->packet_data));
+ s = format (s, "IFACE_IP4_INPUT: pkt: %d, sw_if_index %d, next index %d",
+ (int) t->pkt_type, t->sw_if_index, t->next_index);
+
+ if (t->error)
+ {
+ s = format (s, " drop reason: %s", get_error_string (t->error));
+ }
+
+ s = format (s, "\n%U", format_ip4_header, t->packet_data,
+ sizeof (t->packet_data));
+
return (s);
}
@@ -432,6 +551,7 @@ VLIB_REGISTER_NODE (hicn4_iface_input_node) =
.next_nodes =
{
[HICN4_IFACE_INPUT_NEXT_INTEREST] = "hicn-interest-pcslookup",
+ [HICN4_IFACE_INPUT_NEXT_INTEREST_MANIFEST] = "hicn-interest-manifest-pcslookup",
[HICN4_IFACE_INPUT_NEXT_MAPME] = "hicn-mapme-ctrl",
[HICN4_IFACE_INPUT_NEXT_ERROR_DROP] = "error-drop",
},
@@ -506,6 +626,7 @@ VLIB_REGISTER_NODE (hicn6_iface_input_node) =
.next_nodes =
{
[HICN6_IFACE_INPUT_NEXT_INTEREST] = "hicn-interest-pcslookup",
+ [HICN6_IFACE_INPUT_NEXT_INTEREST_MANIFEST] = "hicn-interest-manifest-pcslookup",
[HICN6_IFACE_INPUT_NEXT_MAPME] = "hicn-mapme-ctrl",
[HICN6_IFACE_INPUT_NEXT_ERROR_DROP] = "error-drop",
},
@@ -518,6 +639,7 @@ hicn_rewrite_iface_data4 (vlib_main_t *vm, vlib_buffer_t *b0,
const hicn_face_t *iface, u32 *next)
{
ip4_header_t *ip0;
+ int ret = HICN_ERROR_NONE;
/* Get the pointer to the old ip and tcp header */
ip0 = vlib_buffer_get_current (b0);
@@ -529,17 +651,21 @@ hicn_rewrite_iface_data4 (vlib_main_t *vm, vlib_buffer_t *b0,
ip0->ttl = 254; // FIXME TTL
vnet_buffer (b0)->ip.adj_index[VLIB_TX] = iface->dpo.dpoi_index;
- *next = iface->dpo.dpoi_next_node;
- hicn_header_t *hicn = vlib_buffer_get_current (b0);
+ *next = iface->iface_next;
+
+ hicn_packet_buffer_t *pkbuf = &hicn_get_buffer (b0)->pkbuf;
+
+ hicn_ip_address_t temp_addr;
+ ip46_address_reset (&(temp_addr.as_ip46));
+
+ hicn_ip_address_t *iface_nat_addr = (hicn_ip_address_t *) &(iface->nat_addr);
- ip46_address_t temp_addr;
- ip46_address_reset (&temp_addr);
- hicn_type_t type = hicn_get_buffer (b0)->type;
u8 flags = hicn_get_buffer (b0)->flags;
u8 reset_pl = flags & HICN_BUFFER_FLAGS_FROM_CS;
- int ret = hicn_ops_vft[type.l1]->rewrite_data (
- type, &hicn->protocol, &(iface->nat_addr), &(temp_addr), iface->pl_id,
- reset_pl);
+
+ ret = hicn_data_rewrite (pkbuf, iface_nat_addr, &(temp_addr), iface->pl_id,
+ reset_pl);
+
if (ret == HICN_LIB_ERROR_REWRITE_CKSUM_REQUIRED)
{
ensure_offload_flags (b0, 1 /* is_v4 */);
@@ -551,6 +677,7 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
const hicn_face_t *iface, u32 *next)
{
ip6_header_t *ip0;
+ int ret = HICN_ERROR_NONE;
/* Get the pointer to the old ip and tcp header */
/* Copy the previous ip and tcp header to the new portion of memory */
@@ -563,18 +690,19 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
ip0->hop_limit = HICN_IP6_HOP_LIMIT;
vnet_buffer (b0)->ip.adj_index[VLIB_TX] = iface->dpo.dpoi_index;
- *next = iface->dpo.dpoi_next_node;
+ *next = iface->iface_next;
- hicn_header_t *hicn = vlib_buffer_get_current (b0);
+ hicn_packet_buffer_t *pkbuf = &hicn_get_buffer (b0)->pkbuf;
- ip46_address_t temp_addr;
- ip46_address_reset (&temp_addr);
- hicn_type_t type = hicn_get_buffer (b0)->type;
+ hicn_ip_address_t temp_addr;
+ ip46_address_reset (&(temp_addr.as_ip46));
+
+ hicn_ip_address_t *iface_nat_addr = (hicn_ip_address_t *) &(iface->nat_addr);
u8 flags = hicn_get_buffer (b0)->flags;
u8 reset_pl = flags & HICN_BUFFER_FLAGS_FROM_CS;
- int ret = hicn_ops_vft[type.l1]->rewrite_data (
- type, &hicn->protocol, &(iface->nat_addr), &(temp_addr), iface->pl_id,
- reset_pl);
+
+ ret = hicn_data_rewrite (pkbuf, iface_nat_addr, &(temp_addr), iface->pl_id,
+ reset_pl);
if (ret == HICN_LIB_ERROR_REWRITE_CKSUM_REQUIRED)
{
@@ -588,7 +716,7 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
vlib_buffer_t *b0; \
u32 bi0; \
u32 next0 = next_index; \
- hicn_face_t *face; \
+ hicn_face_t *face = NULL; \
\
/* Prefetch for next iteration. */ \
if (n_left_from > 1) \
@@ -609,7 +737,8 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
b0 = vlib_get_buffer (vm, bi0); \
\
hicn_face_id_t face_id = vnet_buffer (b0)->ip.adj_index[VLIB_TX]; \
- face = hicn_dpoi_get_from_idx (face_id); \
+ if (PREDICT_TRUE (hicn_dpoi_idx_is_valid (face_id))) \
+ face = hicn_dpoi_get_from_idx (face_id); \
\
if (PREDICT_TRUE (face != NULL)) \
{ \
@@ -626,7 +755,7 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
{ \
TRACE_OUTPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
t->next_index = next0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
@@ -646,7 +775,7 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
u32 bi0, bi1; \
u32 next0 = next_index; \
u32 next1 = next_index; \
- hicn_face_t *face0, *face1; \
+ hicn_face_t *face0 = NULL, *face1 = NULL; \
\
/* Prefetch for next iteration. */ \
{ \
@@ -674,8 +803,10 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
\
hicn_face_id_t face_id0 = vnet_buffer (b0)->ip.adj_index[VLIB_TX]; \
hicn_face_id_t face_id1 = vnet_buffer (b1)->ip.adj_index[VLIB_TX]; \
- face0 = hicn_dpoi_get_from_idx (face_id0); \
- face1 = hicn_dpoi_get_from_idx (face_id1); \
+ if (PREDICT_TRUE (hicn_dpoi_idx_is_valid (face_id0))) \
+ face0 = hicn_dpoi_get_from_idx (face_id0); \
+ if (PREDICT_TRUE (hicn_dpoi_idx_is_valid (face_id1))) \
+ face1 = hicn_dpoi_get_from_idx (face_id1); \
\
if (PREDICT_TRUE (face0 != NULL)) \
{ \
@@ -702,7 +833,7 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
{ \
TRACE_OUTPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b0, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX]; \
t->next_index = next0; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b0), \
@@ -714,7 +845,7 @@ hicn_rewrite_iface_data6 (vlib_main_t *vm, vlib_buffer_t *b0,
{ \
TRACE_OUTPUT_PKT_IP##ipv *t = \
vlib_add_trace (vm, node, b1, sizeof (*t)); \
- t->pkt_type = HICN_PKT_TYPE_INTEREST; \
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST; \
t->sw_if_index = vnet_buffer (b1)->sw_if_index[VLIB_RX]; \
t->next_index = next1; \
clib_memcpy_fast (t->packet_data, vlib_buffer_get_current (b1), \
@@ -738,7 +869,7 @@ hicn4_iface_output_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
- next_index = node->cached_next_index;
+ next_index = HICN4_IFACE_OUTPUT_NEXT_DROP;
while (n_left_from > 0)
{
@@ -792,9 +923,11 @@ VLIB_REGISTER_NODE (hicn4_iface_output_node) = {
.error_strings = hicn4_iface_output_error_strings,
.n_next_nodes = HICN4_IFACE_OUTPUT_N_NEXT,
/* edit / add dispositions here */
- .next_nodes = { [HICN4_IFACE_OUTPUT_NEXT_LOOKUP] = "ip4-lookup",
+ .next_nodes = { [HICN4_IFACE_OUTPUT_NEXT_DROP] = "error-drop",
+ [HICN4_IFACE_OUTPUT_NEXT_LOOKUP] = "ip4-lookup",
[HICN4_IFACE_OUTPUT_NEXT_UDP4_ENCAP] = "udp4-encap",
- [HICN4_IFACE_OUTPUT_NEXT_UDP6_ENCAP] = "udp6-encap" },
+ [HICN4_IFACE_OUTPUT_NEXT_UDP6_ENCAP] = "udp6-encap",
+ [HICN4_IFACE_OUTPUT_NEXT_PG] = "hicnpg-data" },
};
static uword
@@ -807,7 +940,7 @@ hicn6_iface_output_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
- next_index = node->cached_next_index;
+ next_index = HICN6_IFACE_OUTPUT_NEXT_DROP;
while (n_left_from > 0)
{
@@ -860,11 +993,11 @@ VLIB_REGISTER_NODE (hicn6_iface_output_node) = {
.error_strings = hicn6_iface_output_error_strings,
.n_next_nodes = HICN6_IFACE_OUTPUT_N_NEXT,
/* edit / add dispositions here */
- .next_nodes = { [HICN6_IFACE_OUTPUT_NEXT_LOOKUP] = "ip6-lookup",
+ .next_nodes = { [HICN6_IFACE_OUTPUT_NEXT_DROP] = "error-drop",
+ [HICN6_IFACE_OUTPUT_NEXT_LOOKUP] = "ip6-lookup",
[HICN6_IFACE_OUTPUT_NEXT_UDP4_ENCAP] = "udp4-encap",
- [HICN6_IFACE_OUTPUT_NEXT_UDP6_ENCAP] = "udp6-encap"
-
- },
+ [HICN6_IFACE_OUTPUT_NEXT_UDP6_ENCAP] = "udp6-encap",
+ [HICN6_IFACE_OUTPUT_NEXT_PG] = "hicnpg-data" },
};
/*
diff --git a/hicn-plugin/src/faces/iface_node.h b/hicn-plugin/src/faces/iface_node.h
index acb3cab0f..d580c9e31 100644
--- a/hicn-plugin/src/faces/iface_node.h
+++ b/hicn-plugin/src/faces/iface_node.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -37,6 +37,26 @@
* one implementing the tunnel encapsulation (udp-encap, mpls, etc).
*/
+typedef enum
+{
+ HICN4_IFACE_OUTPUT_NEXT_DROP,
+ HICN4_IFACE_OUTPUT_NEXT_LOOKUP,
+ HICN4_IFACE_OUTPUT_NEXT_UDP4_ENCAP,
+ HICN4_IFACE_OUTPUT_NEXT_UDP6_ENCAP,
+ HICN4_IFACE_OUTPUT_NEXT_PG,
+ HICN4_IFACE_OUTPUT_N_NEXT,
+} hicn4_iface_output_next_t;
+
+typedef enum
+{
+ HICN6_IFACE_OUTPUT_NEXT_DROP,
+ HICN6_IFACE_OUTPUT_NEXT_LOOKUP,
+ HICN6_IFACE_OUTPUT_NEXT_UDP4_ENCAP,
+ HICN6_IFACE_OUTPUT_NEXT_UDP6_ENCAP,
+ HICN6_IFACE_OUTPUT_NEXT_PG,
+ HICN6_IFACE_OUTPUT_N_NEXT,
+} hicn6_iface_output_next_t;
+
/**
* @brief Initialize the ip iface module
*/
diff --git a/hicn-plugin/src/faces/inlines.h b/hicn-plugin/src/faces/inlines.h
index 95a1c2ad2..ad9e26b62 100644
--- a/hicn-plugin/src/faces/inlines.h
+++ b/hicn-plugin/src/faces/inlines.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,24 +21,19 @@
always_inline void
ensure_offload_flags (vlib_buffer_t *b, int is_v4)
{
- vnet_buffer_offload_flags_set(b, VNET_BUFFER_OFFLOAD_F_TCP_CKSUM);
- vnet_buffer_offload_flags_set(b, is_v4 * VNET_BUFFER_OFFLOAD_F_IP_CKSUM);
+ vnet_buffer_offload_flags_set (b, VNET_BUFFER_OFFLOAD_F_TCP_CKSUM);
+ vnet_buffer_offload_flags_set (b, is_v4 * VNET_BUFFER_OFFLOAD_F_IP_CKSUM);
size_t l3_header_size =
is_v4 * sizeof (ip4_header_t) + (!is_v4) * sizeof (ip6_header_t);
/* Make sure l3_hdr_offset and l4_hdr_offset are set */
- if (!(b->flags & VNET_BUFFER_F_L3_HDR_OFFSET_VALID))
- {
- b->flags |= VNET_BUFFER_F_L3_HDR_OFFSET_VALID;
- vnet_buffer (b)->l3_hdr_offset = b->current_data;
- }
- if (!(b->flags & VNET_BUFFER_F_L4_HDR_OFFSET_VALID))
- {
- b->flags |= VNET_BUFFER_F_L4_HDR_OFFSET_VALID;
- vnet_buffer (b)->l4_hdr_offset =
- vnet_buffer (b)->l3_hdr_offset + l3_header_size;
- }
+ b->flags |= VNET_BUFFER_F_L3_HDR_OFFSET_VALID;
+ vnet_buffer (b)->l3_hdr_offset = b->current_data;
+
+ b->flags |= VNET_BUFFER_F_L4_HDR_OFFSET_VALID;
+ vnet_buffer (b)->l4_hdr_offset =
+ vnet_buffer (b)->l3_hdr_offset + l3_header_size;
}
#endif /* __HICN_FACE_INLINES_H__ */ \ No newline at end of file
diff --git a/hicn-plugin/src/hashtb.c b/hicn-plugin/src/hashtb.c
deleted file mode 100644
index a74353239..000000000
--- a/hicn-plugin/src/hashtb.c
+++ /dev/null
@@ -1,1006 +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 <stdlib.h>
-#include <errno.h>
-#include <assert.h>
-#include <inttypes.h>
-
-#include <vlib/vlib.h>
-#include <vppinfra/pool.h>
-
-#include "pcs.h"
-#include "hashtb.h"
-#include "parser.h"
-#include "error.h"
-
-/* return dvd/dvr, rounded up (intended for integer values) */
-#define CEIL(dvd, dvr) \
- ({ \
- __typeof__ (dvd) _dvd = (dvd); \
- __typeof__ (dvr) _dvr = (dvr); \
- (_dvd + _dvr - 1) / _dvr; \
- })
-
-#ifndef ALIGN8
-#define ALIGN8(p) (((p) + 0x7) & ~(0x7))
-#endif
-
-#ifndef ALIGNPTR8
-#define ALIGNPTR8(p) ((void *) (((u8 *) (p) + 0x7) & ~(0x7)))
-#endif
-
-#ifndef ALIGN64
-#define ALIGN64(p) (((p) + 0x3f) & ~(0x3f))
-#endif
-
-#ifndef TRUE
-#define TRUE 1
-#endif
-
-#ifndef FALSE
-#define FALSE 0
-#endif
-
-/*
- * Offset to aligned start of additional data (PIT/CS, FIB) embedded in each
- * node.
- */
-u32 ht_node_data_offset_aligned;
-
-/* Some support for posix vs vpp mem management */
-#define MEM_ALLOC(x) clib_mem_alloc_aligned ((x), 8)
-#define MEM_FREE(p) clib_mem_free ((p))
-
-/*
- * Internal utilities
- */
-
-/* Allocate an overflow bucket */
-static hicn_hash_bucket_t *
-alloc_overflow_bucket (hicn_hashtb_h h)
-{
- hicn_hash_bucket_t *newbkt = NULL;
-
- if (h->ht_overflow_buckets_used < h->ht_overflow_bucket_count)
- {
- pool_get_aligned (h->ht_overflow_buckets, newbkt, 8);
-
- if (newbkt)
- {
- h->ht_overflow_buckets_used++;
- }
- }
- return (newbkt);
-}
-
-/* Free an overflow bucket; clear caller's pointer */
-static void
-free_overflow_bucket (hicn_hashtb_h h, hicn_hash_bucket_t **pb)
-{
- hicn_hash_bucket_t *bkt = *pb;
-
- ASSERT (h->ht_overflow_buckets_used > 0);
-
- pool_put (h->ht_overflow_buckets, bkt);
- h->ht_overflow_buckets_used--;
- *pb = NULL;
-}
-
-/*
- * Init, allocate a new hashtable
- */
-int
-hicn_hashtb_alloc (hicn_hashtb_h *ph, u32 max_elems, size_t app_data_size)
-{
- int ret = HICN_ERROR_NONE;
- hicn_hashtb_h h = NULL;
- u32 count;
- u32 total_buckets;
- size_t sz;
- hicn_hash_node_t *nodep;
- hicn_hash_bucket_t *bucket;
-
- if (ph == NULL)
- {
- ret = HICN_ERROR_HASHTB_INVAL;
- goto done;
- }
- if (max_elems < HICN_HASHTB_MIN_ENTRIES ||
- max_elems > HICN_HASHTB_MAX_ENTRIES)
- {
- goto done;
- }
- /* Allocate and init main hashtable struct */
- h = MEM_ALLOC (sizeof (hicn_hashtb_t));
- if (h == NULL)
- {
- ret = HICN_ERROR_HASHTB_NOMEM;
- goto done;
- }
- memset (h, 0, sizeof (hicn_hashtb_t));
-
- /* Compute main table bucket (row) count and size, and allocate */
-
- /* Consider the last entry as used for containing the overflow bucket */
- total_buckets = CEIL (max_elems, HICN_HASHTB_BUCKET_ENTRIES - 1);
- count = ALIGN8 (CEIL (total_buckets, HICN_HASHTB_FILL_FACTOR));
-
- h->ht_bucket_count = count;
-
- /* We _really_ expect to have buckets aligned on cache lines ... */
- sz = sizeof (hicn_hash_bucket_t);
- assert (sz == ALIGN64 (sz));
-
- h->ht_buckets = MEM_ALLOC (count * sz);
- if (h->ht_buckets == NULL)
- {
- ret = HICN_ERROR_HASHTB_NOMEM;
- goto done;
- }
- memset (h->ht_buckets, 0, count * sz);
-
- /*
- * First time through, compute offset to aligned extra data start in
- * each node struct it's crucial that both the node struct (that the
- * base hashtable uses) and the extra data area (that's also probably
- * a struct) are aligned.
- */
- if (ht_node_data_offset_aligned == 0)
- {
- count = STRUCT_OFFSET_OF (hicn_hash_node_t, hn_data);
- ht_node_data_offset_aligned = ALIGN8 (count);
- }
- // check app struct fits into space provided(HICN_HASH_NODE_APP_DATA_SIZE)
- u32 ht_node_data_size;
- ht_node_data_size = sizeof (hicn_hash_node_t) - ht_node_data_offset_aligned;
- if (app_data_size > ht_node_data_size)
- {
- clib_error (
- "hicn hashtable: fatal error: requested app data size(%u) > hashtb "
- "node's configured bytes available(%u), sizeof(hicn_shared_t)=%u, "
- "sizeof(hicn_pit_entry_t)=%u, sizeof(hicn_cs_entry_t)=%u",
- app_data_size, ht_node_data_size, sizeof (hicn_pcs_shared_t),
- sizeof (hicn_pit_entry_t), sizeof (hicn_cs_entry_t));
- }
- /*
- * Compute entry node count and size, allocate Allocate/'Hide' the
- * zero-th node so can use zero as an 'empty' value
- */
- pool_alloc_aligned (h->ht_nodes, max_elems, 8);
- if (h->ht_nodes == NULL)
- {
- ret = HICN_ERROR_HASHTB_NOMEM;
- goto done;
- }
- pool_get_aligned (h->ht_nodes, nodep, 8);
- // alloc node 0
- nodep = nodep; /* Silence 'not used' warning */
-
- h->ht_node_count = max_elems;
- h->ht_nodes_used = 1;
-
- /*
- * Compute overflow bucket count and size, allocate
- */
- // count = ALIGN8(CEIL(max_elems, HICN_HASHTB_OVERFLOW_FRACTION));
- count = ALIGN8 (total_buckets - h->ht_bucket_count);
-
- pool_alloc_aligned (h->ht_overflow_buckets, count, 8);
- if (h->ht_overflow_buckets == NULL)
- {
- ret = HICN_ERROR_HASHTB_NOMEM;
- goto done;
- }
- /* 'Hide' the zero-th node so we can use zero as an 'empty' value */
- pool_get_aligned (h->ht_overflow_buckets, bucket, 8);
- bucket = bucket; /* Silence 'not used' warning */
-
- h->ht_overflow_bucket_count = count;
- h->ht_overflow_buckets_used = 1;
-
-done:
-
- if (h)
- {
- if ((ret == HICN_ERROR_NONE) && ph)
- {
- *ph = h;
- }
- else
- {
- hicn_hashtb_free (&h);
- }
- }
- return (ret);
-}
-
-/*
- * Free, de-allocate a hashtable
- */
-int
-hicn_hashtb_free (hicn_hashtb_h *ph)
-{
- int ret = 0;
-
- if (ph)
- {
- if ((*ph)->ht_nodes)
- {
- pool_free ((*ph)->ht_nodes);
- (*ph)->ht_nodes = 0;
- }
- if ((*ph)->ht_overflow_buckets)
- {
- pool_free ((*ph)->ht_overflow_buckets);
- (*ph)->ht_overflow_buckets = 0;
- }
- if ((*ph)->ht_buckets)
- {
- MEM_FREE ((*ph)->ht_buckets);
- (*ph)->ht_buckets = 0;
- }
- MEM_FREE (*ph);
-
- *ph = NULL;
- }
- return (ret);
-}
-
-/*
- * Basic api to lookup a specific hash+key tuple. This does the entire lookup
- * operation, retrieving node structs and comparing keys, so it's not
- * optimized for prefetching or high performance.
- *
- * Returns zero and mails back a node on success, errno otherwise.
- */
-int
-hicn_hashtb_lookup_node (hicn_hashtb_h h, const u8 *key, u32 keylen,
- u64 hashval, u8 is_data, u32 *node_id,
- index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs,
- u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow)
-{
- return (hicn_hashtb_lookup_node_ex (
- h, key, keylen, hashval, is_data, FALSE /* deleted nodes */, node_id,
- dpo_ctx_id, vft_id, is_cs, hash_entry_id, bucket_id, bucket_is_overflow));
-}
-
-/*
- * Extended api to lookup a specific hash+key tuple. The implementation
- * allows the caller to locate nodes that are marked for deletion, which is
- * part of some hashtable applications, such as the FIB.
- *
- * This does the entire lookup operation, retrieving node structs and comparing
- * keys, so it's not optimized for prefetching or high performance.
- *
- * Returns zero and mails back a node on success, errno otherwise.
- */
-int
-hicn_hashtb_lookup_node_ex (hicn_hashtb_h h, const u8 *key, u32 keylen,
- u64 hashval, u8 is_data, int include_deleted_p,
- u32 *node_id, index_t *dpo_ctx_id, u8 *vft_id,
- u8 *is_cs, u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow)
-{
- int i, ret = HICN_ERROR_HASHTB_HASH_NOT_FOUND;
- int found_p = FALSE;
- u32 bidx;
- hicn_hash_bucket_t *bucket;
- u32 current_bucket_id = ~0;
-
- /*
- * Use some bits of the low half of the hash to locate a row/bucket
- * in the table
- */
- current_bucket_id = bidx = (hashval & (h->ht_bucket_count - 1));
-
- bucket = h->ht_buckets + bidx;
-
- *bucket_is_overflow = 0;
- /* Check the entries in the bucket for matching hash value */
-
-loop_buckets:
-
- for (i = 0; i < HICN_HASHTB_BUCKET_ENTRIES && !found_p; i++)
- {
- /*
- * If an entry is marked for deletion, ignore it unless the
- * caller explicitly wants these nodes.
- */
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_DELETED)
- {
- if (!include_deleted_p)
- {
- continue;
- }
- }
- if (bucket->hb_entries[i].he_msb64 == hashval)
- {
- /*
- * Found a candidate - must retrieve the actual node
- * and check the key.
- */
- *node_id = bucket->hb_entries[i].he_node;
- *dpo_ctx_id = bucket->hb_entries[i].dpo_ctx_id;
- *vft_id = bucket->hb_entries[i].vft_id;
- *is_cs =
- bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_CS_ENTRY;
- *hash_entry_id = i;
- *bucket_id = current_bucket_id;
- /*
- * If we are doing lookup for a data, do not take a
- * lock in case of a hit with a CS entry
- */
- if (!(is_data && *is_cs))
- {
- bucket->hb_entries[i].locks++;
- }
- found_p = TRUE;
- ret = HICN_ERROR_NONE;
- goto done;
- }
- }
-
- /*
- * Be prepared to continue to an overflow bucket if necessary. We
- * only expect the last entry in a bucket to refer to an overflow
- * bucket...
- */
- i = HICN_HASHTB_BUCKET_ENTRIES - 1;
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_OVERFLOW)
- {
- current_bucket_id = bucket->hb_entries[i].he_node;
- bucket = pool_elt_at_index (h->ht_overflow_buckets,
- bucket->hb_entries[i].he_node);
- *bucket_is_overflow = 1;
- goto loop_buckets;
- }
-done:
-
- return (ret);
-}
-
-/**
- * This function allows to split the hash verification from the comparison of
- * the entire key. Useful to exploit prefertching.
- * return 1 if equals, 0 otherwise
- */
-int
-hicn_node_compare (const u8 *key, u32 keylen, hicn_hash_node_t *node)
-{
-
- int ret = 0;
-
- if (key && keylen == node->hn_keysize)
- {
- ret = (memcmp (key, node->hn_key.ks.key, keylen) == 0);
- }
- return ret;
-}
-
-/*
- * Utility to init a new entry in a hashtable bucket/row. We use this to add
- * new a node+hash, and to clear out an entry during removal.
- */
-void
-hicn_hashtb_init_entry (hicn_hash_entry_t *entry, u32 nodeidx, u64 hashval,
- u32 locks)
-{
- entry->he_msb64 = hashval;
- entry->he_node = nodeidx;
-
- /* Clear out some other fields in the entry */
- entry->he_flags = 0;
- entry->locks = locks;
- entry->vft_id = 0;
- entry->dpo_ctx_id = 0;
-}
-
-/*
- * Insert a node into the hashtable. We expect the caller has a) computed the
- * hash value to use, b) initialized the node with the hash and key info, and
- * c) filled in its app-specific data portion of the node.
- */
-
-int
-hicn_hashtb_insert (hicn_hashtb_h h, hicn_hash_node_t *node,
- hicn_hash_entry_t **hash_entry, u64 hash, u32 *node_id,
- index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs,
- u8 *hash_entry_id, u32 *bucket_id, u8 *bucket_is_overflow)
-{
- int i, ret = HICN_ERROR_HASHTB_INVAL;
- u32 bidx;
- hicn_hash_bucket_t *bucket, *newbkt;
- int use_seven;
- u32 current_bucket_id = ~0;
- int is_overflow = 0;
-
- *hash_entry = NULL;
-
- if (h == NULL)
- {
- goto done;
- }
- /*
- * Use some bits of the low half of the hash to locate a row/bucket
- * in the table
- */
- current_bucket_id = bidx = (hash & (h->ht_bucket_count - 1));
-
- bucket = h->ht_buckets + bidx;
-
- use_seven = (h->ht_flags & HICN_HASHTB_FLAG_USE_SEVEN);
-
- /* Locate a free entry slot in the bucket */
-
-loop_buckets:
-
- for (i = 0; i < HICN_HASHTB_BUCKET_ENTRIES; i++)
- {
-
- /*
- * If an entry is marked for deletion, ignore it
- */
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_DELETED)
- {
- continue;
- }
- /*
- * Be sure that we are not inserting the same entry twice
- */
- if (bucket->hb_entries[i].he_msb64 == hash)
- {
- /*
- * We hit an existing pit entry. increase lock.
- */
-
- *node_id = bucket->hb_entries[i].he_node;
- *dpo_ctx_id = bucket->hb_entries[i].dpo_ctx_id;
- *vft_id = bucket->hb_entries[i].vft_id;
- *is_cs =
- bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_CS_ENTRY;
- *hash_entry_id = i;
- *bucket_id = current_bucket_id;
- *hash_entry = &(bucket->hb_entries[i]);
- /*
- * If we are doing lookup for a data, do not take a
- * lock in case of a hit with a CS entry
- */
- if (!(*is_cs))
- bucket->hb_entries[i].locks++;
- *bucket_is_overflow = is_overflow;
- ret = HICN_ERROR_HASHTB_EXIST;
- goto done;
- }
- if ((bucket->hb_entries[i].he_msb64 == 0LL) &&
- (bucket->hb_entries[i].he_node == 0))
- {
- /* Found a candidate -- fill it in */
-
- /*
- * Special case if the application asked not to use
- * the last entry in each bucket.
- */
- if ((i != (HICN_HASHTB_BUCKET_ENTRIES - 1)) || use_seven)
- {
- hicn_hashtb_init_entry (&(bucket->hb_entries[i]),
- NODE_IDX_FROM_NODE (node, h), hash, 0);
-
- *hash_entry = &(bucket->hb_entries[i]);
-
- node->bucket_id = current_bucket_id;
- node->entry_idx = i;
- (*hash_entry)->vft_id = *vft_id;
- (*hash_entry)->dpo_ctx_id = *dpo_ctx_id;
- if (is_overflow)
- node->hn_flags |= HICN_HASH_NODE_OVERFLOW_BUCKET;
-
- ret = HICN_ERROR_NONE;
- goto done;
- }
- }
- }
- /*
- * Be prepared to continue to an overflow bucket if necessary, or to
- * add a new overflow bucket. We only expect the last entry in a
- * bucket to refer to an overflow bucket...
- */
- i = HICN_HASHTB_BUCKET_ENTRIES - 1;
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_OVERFLOW)
- {
- /* Existing overflow bucket - re-start the search loop */
- current_bucket_id = bucket->hb_entries[i].he_node;
- bucket = pool_elt_at_index (h->ht_overflow_buckets, current_bucket_id);
- is_overflow = 1;
- goto loop_buckets;
- }
- else
- {
- /*
- * Overflow - reached the end of a bucket without finding a
- * free entry slot. Need to allocate an overflow bucket, and
- * connect it to this bucket.
- */
- newbkt = alloc_overflow_bucket (h);
- if (newbkt == NULL)
- {
- ret = HICN_ERROR_HASHTB_NOMEM;
- goto done;
- }
- /*
- * We're touching some more bytes than we absolutely have to
- * here, but ... that seems ok.
- */
- memset (newbkt, 0, sizeof (hicn_hash_bucket_t));
-
- if (use_seven)
- {
- /*
- * Copy existing entry into new bucket - we really
- * expect these to be properly aligned so they can be
- * treated as int.
- */
- memcpy (&(newbkt->hb_entries[0]), &(bucket->hb_entries[i]),
- sizeof (hicn_hash_entry_t));
-
- /* Update bucket id and entry_idx on the hash node */
- hicn_hash_node_t *node =
- pool_elt_at_index (h->ht_nodes, newbkt->hb_entries[0].he_node);
- node->bucket_id = (newbkt - h->ht_overflow_buckets);
- node->entry_idx = 0;
- node->hn_flags |= HICN_HASH_NODE_OVERFLOW_BUCKET;
- }
- /*
- * Connect original bucket to the index of the new overflow
- * bucket
- */
- bucket->hb_entries[i].he_flags |= HICN_HASH_ENTRY_FLAG_OVERFLOW;
- bucket->hb_entries[i].he_node = (newbkt - h->ht_overflow_buckets);
-
- /* Add new entry to new overflow bucket */
- bucket = newbkt;
-
- /*
- * Use entry [1] in the new bucket _if_ we just copied into
- * entry [zero] above.
- */
- if (use_seven)
- {
-
- hicn_hashtb_init_entry (&(bucket->hb_entries[1]),
- NODE_IDX_FROM_NODE (node, h), hash, 0);
- *hash_entry = &(bucket->hb_entries[1]);
-
- node->bucket_id = (newbkt - h->ht_overflow_buckets);
- node->entry_idx = 1;
- node->hn_flags |= HICN_HASH_NODE_OVERFLOW_BUCKET;
- (*hash_entry)->vft_id = *vft_id;
- (*hash_entry)->dpo_ctx_id = *dpo_ctx_id;
- }
- else
- {
-
- hicn_hashtb_init_entry (&(bucket->hb_entries[0]),
- NODE_IDX_FROM_NODE (node, h), hash, 0);
- *hash_entry = &(bucket->hb_entries[0]);
- node->bucket_id = (newbkt - h->ht_overflow_buckets);
- node->entry_idx = 0;
- node->hn_flags |= HICN_HASH_NODE_OVERFLOW_BUCKET;
- (*hash_entry)->vft_id = *vft_id;
- (*hash_entry)->dpo_ctx_id = *dpo_ctx_id;
- }
- }
-
- /* And we're done with the overflow bucket */
- ret = HICN_ERROR_NONE;
-
-done:
-
- return (ret);
-}
-
-/*
- * Delete a node from a hashtable using the node itself, and delete/free the
- * node. Caller's pointer is cleared on success.
- */
-void
-hicn_hashtb_delete (hicn_hashtb_h h, hicn_hash_node_t **pnode, u64 hashval)
-{
-
- hicn_hashtb_remove_node (h, *pnode, hashval);
- hicn_hashtb_free_node (h, *pnode);
- *pnode = NULL;
-}
-
-/*
- * Delete an entry from a hashtable using the node itself. If the node was
- * stored in an overflow bucket, and the bucket is empty after freeing the
- * node, the bucket is freed as well.
- */
-void
-hicn_hashtb_remove_node (hicn_hashtb_h h, hicn_hash_node_t *node, u64 hashval)
-{
- int i, count;
- u32 bidx, overflow_p;
- hicn_hash_bucket_t *bucket, *parent;
-
- if ((h == NULL) || (node == NULL))
- {
- goto done;
- }
- if (node->hn_flags & HICN_HASH_NODE_OVERFLOW_BUCKET)
- bucket = pool_elt_at_index (h->ht_overflow_buckets, node->bucket_id);
- else
- {
- /*
- * Use some bits of the low half of the hash to locate a
- * row/bucket in the table
- */
- bidx = (hashval & (h->ht_bucket_count - 1));
- ASSERT (bidx == node->bucket_id);
- bucket = h->ht_buckets + node->bucket_id;
- }
-
- overflow_p = node->hn_flags & HICN_HASH_NODE_OVERFLOW_BUCKET;
-
- /* Clear out the entry. */
- hicn_hashtb_init_entry (&(bucket->hb_entries[node->entry_idx]), 0, 0LL, 0);
-
- if (!overflow_p)
- {
- /*
- * And we're done, in the easy case where we didn't change an
- * overflow bucket
- */
- goto done;
- }
- /*
- * The special case: if this is the last remaining entry in an
- * overflow bucket, liberate the bucket. That in turn has a special
- * case if this bucket is in the middle of a chain of overflow
- * buckets.
- *
- * Note that we're not trying aggressively (yet) to condense buckets at
- * every possible opportunity.
- */
-
- /*
- * Reset this flag; we'll set it again if this bucket links to
- * another
- */
- overflow_p = FALSE;
-
- for (i = 0, count = 0; i < HICN_HASHTB_BUCKET_ENTRIES; i++)
- {
- if (bucket->hb_entries[i].he_node != 0)
- {
- count++;
- }
- if (i == (HICN_HASHTB_BUCKET_ENTRIES - 1) &&
- (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_OVERFLOW))
- {
- count--; /* Doesn't count as a 'real' entry */
- overflow_p = TRUE;
- }
- }
-
- if (count > 0)
- {
- /* Still a (real) entry in the row */
- goto done;
- }
- /*
- * Need to locate the predecessor of 'bucket': start at the beginning
- * of the chain of buckets and move forward
- */
- bidx = (hashval & (h->ht_bucket_count - 1));
-
- for (parent = h->ht_buckets + bidx; parent != NULL;)
- {
-
- if ((parent->hb_entries[(HICN_HASHTB_BUCKET_ENTRIES - 1)].he_flags &
- HICN_HASH_ENTRY_FLAG_OVERFLOW) == 0)
- {
- parent = NULL;
- break;
- }
- bidx = parent->hb_entries[(HICN_HASHTB_BUCKET_ENTRIES - 1)].he_node;
-
- if (pool_elt_at_index (h->ht_overflow_buckets, bidx) == bucket)
- {
- /*
- * Found the predecessor of 'bucket'. If 'bucket' has
- * a successor, connect 'parent' to it, and take
- * 'bucket out of the middle.
- */
- if (overflow_p)
- {
- parent->hb_entries[(HICN_HASHTB_BUCKET_ENTRIES - 1)].he_node =
- bucket->hb_entries[(HICN_HASHTB_BUCKET_ENTRIES - 1)].he_node;
- }
- else
- {
- /*
- * Just clear the predecessor entry pointing
- * at 'bucket'
- */
- hicn_hashtb_init_entry (
- &parent->hb_entries[(HICN_HASHTB_BUCKET_ENTRIES - 1)], 0, 0LL,
- 0);
- }
-
- break;
- }
- /*
- * After the first iteration, 'parent' will be an overflow
- * bucket too
- */
- parent = pool_elt_at_index (h->ht_overflow_buckets, bidx);
- }
-
- /* We really expect to have found the predecessor */
- ASSERT (parent != NULL);
-
- /* And now, finally, we can put 'bucket' back on the free list */
- free_overflow_bucket (h, &bucket);
-
-done:
- return;
-}
-
-/*
- * Prepare a hashtable node, supplying the key, and computed hash info.
- */
-void
-hicn_hashtb_init_node (hicn_hashtb_h h, hicn_hash_node_t *node, const u8 *key,
- u32 keylen)
-{
- assert (h != NULL);
- assert (node != NULL);
- assert (keylen <= HICN_PARAM_HICN_NAME_LEN_MAX);
-
- /* Init the node struct */
- node->hn_flags = HICN_HASH_NODE_FLAGS_DEFAULT;
- node->hn_keysize = 0;
- node->hn_keysize = keylen;
- memcpy (node->hn_key.ks.key, key, keylen);
- node->bucket_id = ~0;
- node->entry_idx = ~0;
-}
-
-/*
- * Release a hashtable node back to the free list when an entry is cleared
- */
-void
-hicn_hashtb_free_node (hicn_hashtb_h h, hicn_hash_node_t *node)
-{
- ASSERT (h->ht_nodes_used > 0);
-
- /* Return 'node' to the free list */
- pool_put (h->ht_nodes, node);
- h->ht_nodes_used--;
-}
-
-/*
- * Walk a hashtable, iterating through the nodes, keeping context in 'ctx'.
- */
-int
-hicn_hashtb_next_node (hicn_hashtb_h h, hicn_hash_node_t **pnode, u64 *ctx)
-{
- int i, j, ret = HICN_ERROR_HASHTB_INVAL;
- u32 bidx, entry;
- hicn_hash_bucket_t *bucket;
-
- if ((h == NULL) || (pnode == NULL) || (ctx == NULL))
- {
- goto done;
- }
- /* Special-case for new iteration */
- if (*ctx == HICN_HASH_WALK_CTX_INITIAL)
- {
- bidx = 0;
- bucket = &h->ht_buckets[0];
- entry = 0;
- j = 0;
- i = 0;
- goto search_table;
- }
- /* Convert context to bucket and entry indices */
- bidx = *ctx & 0xffffffffLL;
- entry = *ctx >> 32;
-
- if (bidx >= h->ht_bucket_count)
- {
- ret = HICN_ERROR_HASHTB_HASH_NOT_FOUND;
- goto done;
- }
- bucket = h->ht_buckets + bidx;
-
- /* Init total index into entries (includes fixed bucket and overflow) */
- j = 0;
-
-skip_processed_bucket_chunks:
- /*
- * Figure out where to resume the search for the next entry in the
- * table, by trying to find the last entry returned, from the cookie.
- * Loop walks one (regular or overflow) bucket chunk, label is used
- * for walking chain of chunks. Note that if there was a deletion or
- * an addition that created an overflow, iterator can skip entries or
- * return duplicate entries, for entries that are present from before
- * the walk starts until after it ends.
- */
-
- for (i = 0; i < HICN_HASHTB_BUCKET_ENTRIES; i++, j++)
- {
- if (j > entry)
- {
- /*
- * Start search for next here, use existing 'bucket'
- * and 'i'
- */
- break;
- }
- /*
- * If an entry is marked for deletion, ignore it
- */
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_DELETED)
- {
- continue;
- }
- /*
- * Be prepared to continue to an overflow bucket if
- * necessary. (We only expect the last entry in a bucket to
- * refer to an overflow bucket...)
- */
- if (i == (HICN_HASHTB_BUCKET_ENTRIES - 1))
- {
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_OVERFLOW)
- {
- bucket = pool_elt_at_index (h->ht_overflow_buckets,
- bucket->hb_entries[i].he_node);
-
- /* Increment overall entry counter 'j' */
- j++;
-
- goto skip_processed_bucket_chunks;
- }
- /*
- * end of row (end of fixed bucket plus any
- * overflows)
- */
- i = 0;
- j = 0;
-
- bidx++;
-
- /* Special case - we're at the end */
- if (bidx >= h->ht_bucket_count)
- {
- ret = HICN_ERROR_HASHTB_HASH_NOT_FOUND;
- goto done;
- }
- bucket = h->ht_buckets + bidx;
- break;
- }
- }
-
-search_table:
-
- /*
- * Now we're searching through the table for the next entry that's
- * set
- */
-
- for (; i < HICN_HASHTB_BUCKET_ENTRIES; i++, j++)
- {
- /*
- * If an entry is marked for deletion, ignore it
- */
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_DELETED)
- {
- continue;
- }
- /* Is this entry set? */
- if (bucket->hb_entries[i].he_node != 0)
- {
-
- /* Retrieve the node struct */
- *pnode =
- pool_elt_at_index (h->ht_nodes, bucket->hb_entries[i].he_node);
-
- /*
- * Set 'entry' as we exit, so we can update the
- * cookie
- */
- entry = j;
- ret = HICN_ERROR_NONE;
- break;
- }
- /*
- * Be prepared to continue to an overflow bucket if
- * necessary. (We only expect the last entry in a bucket to
- * refer to an overflow bucket...)
- */
- if (i == (HICN_HASHTB_BUCKET_ENTRIES - 1))
- {
- if (bucket->hb_entries[i].he_flags & HICN_HASH_ENTRY_FLAG_OVERFLOW)
- {
- bucket = pool_elt_at_index (h->ht_overflow_buckets,
- bucket->hb_entries[i].he_node);
- /*
- * Reset per-bucket index 'i', here (not done
- * in iterator)
- */
- i = 0;
- /* Increment overall entry counter 'j' */
- j++;
-
- goto search_table;
- }
- else
- {
- /*
- * Move to next bucket, resetting per-bucket
- * and overall entry indexes
- */
- i = 0;
- j = 0;
-
- bidx++;
-
- /* Special case - we're at the end */
- if (bidx >= h->ht_bucket_count)
- {
- ret = HICN_ERROR_HASHTB_HASH_NOT_FOUND;
- goto done;
- }
- bucket = h->ht_buckets + bidx;
- goto search_table;
- }
- }
- }
-
-done:
-
- if (ret == HICN_ERROR_NONE)
- {
- /* Update context */
- *ctx = bidx;
- *ctx |= ((u64) entry << 32);
- }
- return (ret);
-}
-
-int
-hicn_hashtb_key_to_buf (u8 **vec_res, hicn_hashtb_h h,
- const hicn_hash_node_t *node)
-{
- int ret = HICN_ERROR_NONE;
- u8 *vec = *vec_res;
-
- if (node->hn_keysize <= HICN_HASH_KEY_BYTES)
- {
- vec_add (vec, node->hn_key.ks.key, node->hn_keysize);
- }
- *vec_res = vec;
- return (ret);
-}
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables: eval: (c-set-style "gnu") End:
- */
diff --git a/hicn-plugin/src/hashtb.h b/hicn-plugin/src/hashtb.h
deleted file mode 100644
index 3965ec65d..000000000
--- a/hicn-plugin/src/hashtb.h
+++ /dev/null
@@ -1,536 +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.
- */
-
-#ifndef __HICN_HASHTB_H__
-#define __HICN_HASHTB_H__
-
-#include <stdint.h>
-#include <vppinfra/bihash_8_8.h>
-#include <vppinfra/bihash_24_8.h>
-
-#include "params.h"
-#include "parser.h"
-#include "error.h"
-
-/**
- * @file hashtb.h
- * Lookup is finding a hashtable record whose name matches the name being
- * looked up. Most of the lookup work is based on the hash value of the two
- * names. Note that the intel cache line size is 64 bytes, and some platforms
- * load in 2 cache lines together.
- * - first step is to match a record at the bucket/slot level (htab has an
- * array of htbucket_t/htbc_elmt, where each bucket has 7 slots to hold
- * indices for entries.) Matching at this level implies
- * - the hashes of the lookup name and the record map to the same bucket
- * - the high 32 bits of the hashes (slot bce_hash_msb32s) match. Read
- * cost (on the hash table size, i.e. ignoring reading the name being
- * looked up):
- * - First step normally requires 1 cache line load to pull in the
- * 64-byte htbucket_t with the 7 element slot table holding the
- * hash_msb32s.
- * - In the event (hopefully rare for a hash table with appropriate
- * number of buckets) that more than 7 elements hash to the same bucket,
- * lookup may well need to look not only at the static htbc_elmt_t but at
- * the chain of dynamically allocated htbc_elmt_t's linked to the static
- * htbc_elmt_t, where each of these holds slot entries for additional
- * elements.
- * - Before reaching that point, it is initially required to read in the
- * hash table record fields (ht_bucket_buf, htnode buf, etc) holding
- * pointers to the arrays, but these cache lines are common to all
- * lookups so will likely already be in the cache.
- * - second step is to match at the record level (htnode/htkb level) once a
- * slot-level match happens. Matching at this level implies the following
- * match
- * - the hash values (the full 64 bits vs. bucket+32 msb, above).
- * - the name which, on the hash table side, is stored as a list of htkb_t
- * (key buffers).
- *
- * Some hashtables (for which rare false positives are tolerable) store hash
- * values but no keys. (In ISM NDN forwarder, this was used for dcm_dpf: data
- * cache manager's dataplane filter, where speed was critical and very rare
- * false positives would be detected in the full dcm check.) - No key buffers
- * are used (or even allocated at hash table creation).
- */
-
-/* Handy abbreviations for success status, and for boolean values */
-#ifndef TRUE
-#define TRUE 1
-#endif
-
-#ifndef FALSE
-#define FALSE 0
-#endif
-
-#define HICN_HASH_INVALID_IDX ~0
-/*
- * for hicn_hashtb_next_node() iterator, this otherwise illegal context value
- * indicates first call of iteration. Note: must not be 0, which is a legal
- * context value.
- */
-#define HICN_HASH_WALK_CTX_INITIAL (~((u64) 0))
-
-/*
- * Key memory allocation scheme.
- *
- * The key is the bytestring that a hashtable entry is storing, e.g. a fib
- * prefix or packet name. The hash of the name is used not just to pick the
- * bucket, but also as a surrogate for the actual key value.
- *
- * Client calls pass key/name as contiguous memory for lookup/add/delete but
- * hashable stores its copy of the key/name as a list of one or more hash_key
- * structs. - key memory is managed as a list of keys (cache line
- * sized/aligned buffers). - If (keysize < 128) then use key struct's full
- * 128 bytes - If not, first key struct is head of a linked list of elements
- * where the first bytes are used for the key and the last 4 bytes are the
- * index of the next entry (or an end marker). - key memory is generally the
- * single largest use of memory in the hash table, especially for PIT, as
- * names are bigger than node structs (which is also per name/entry).
- *
- */
-
-/* Compute hash node index from node pointer */
-#define NODE_IDX_FROM_NODE(p, h) (u32) ((p) - ((h)->ht_nodes))
-
-#define HICN_HASH_KEY_BYTES 20
-
-typedef struct
-{
- struct
- {
- u8 key[HICN_HASH_KEY_BYTES];
- } ks; /* Entire key in one block */
-} hicn_hash_key_t;
-
-/*
- * Ratio of extra key blocks to allocate, in case the embedded ones aren't
- * sufficient. This is the fraction of the number of entries allocated.
- */
-#define HICN_HASHTB_KEY_RATIO 8
-
-/*
- * hash node, used to store a hash table entry; indexed by an entry in a
- * bucket. the node contains an embedded key; long keys are stored as chains
- * of keys.
- *
- * The memory block for a node includes space for storing outgoing faces for
- * interests, additional memory located off the end of the htnode data
- * structure.
- *
- */
-
-/* Size this so that we can offer 64B aligned on 64-bits for storing outgoing
- * faces information
- */
-#define HICN_HASH_NODE_APP_DATA_SIZE 64
-
-/* How to align in the right way */
-typedef struct __attribute__ ((packed)) hicn_hash_node_s
-{
- /* Bucket id containing the corresponding hash entry. */
- u32 bucket_id;
-
- /* Hash entry index in the bucket */
- u32 entry_idx;
-
- /* Total size of the key */
- u16 hn_keysize;
-
- /* 1 byte of flags for application use */
- u8 hn_flags;
-
- u8 _hn_reserved1; /* TBD, to align what follows back to
- * 32 */
-
- hicn_hash_key_t hn_key; /* Key value embedded in the node, may chain
- * to more key buffers if necessary */
-
- /* 32B + HICN_HASH_NODE_APP_DATA_SIZE */
- /* Followed by app-specific data (fib or pit or cs entry, e.g.) */
- u8 hn_data[HICN_HASH_NODE_APP_DATA_SIZE];
-
-} hicn_hash_node_t;
-
-#define HICN_HASH_NODE_FLAGS_DEFAULT 0x00
-#define HICN_HASH_NODE_CS_FLAGS 0x01
-#define HICN_HASH_NODE_OVERFLOW_BUCKET 0x02
-
-/*
- * hicn_hash_entry_t Structure holding all or part of a hash value, a node
- * index, and other key pieces of info.
- *
- * - 128 bytes/bucket with 19 bytes/entry gives 6 entries, or 5 entries plus
- * next bucket ptr if overflow Changes in this structure will affect
- * hicn_hash_bucket_t
- */
-typedef struct __attribute__ ((packed)) hicn_hash_entry_s
-{
-
- /* MSB of the hash value */
- u64 he_msb64;
-
- /* Index of node block */
- u32 he_node;
-
- /*
- * Lock to prevent hash_node deletion while there are still interest
- * or data referring to it
- */
- u32 locks;
-
- /* Index of dpo (4B) */
- index_t dpo_ctx_id;
-
- /* A few flags, including 'this points to a chain of buckets' */
- u8 he_flags;
-
- /*
- * Index of the virtual function table corresponding to the dpo_ctx
- * strategy
- */
- u8 vft_id;
-
-} hicn_hash_entry_t; // size 22B
-
-STATIC_ASSERT (sizeof (index_t) <= 4, "sizeof index_t is greater than 4B");
-
-#define HICN_HASH_ENTRY_FLAGS_DEFAULT 0x00
-
-/* If entry is PIT this flag is 0 */
-#define HICN_HASH_ENTRY_FLAG_CS_ENTRY 0x01
-
-/*
- * This entry heads a chain of overflow buckets (we expect to see this only
- * in the last entry in a bucket.) In this case, the index is to an overflow
- * bucket rather than to a single node block.
- */
-#define HICN_HASH_ENTRY_FLAG_OVERFLOW 0x04
-
-/* This entry has been marked for deletion */
-#define HICN_HASH_ENTRY_FLAG_DELETED 0x08
-
-/* Use fast he_timeout units for expiration, slow if not */
-#define HICN_HASH_ENTRY_FLAG_FAST_TIMEOUT 0x10
-
-/*
- * hash bucket: Contains an array of entries. Cache line sized/aligned, so no
- * room for extra fields unless bucket size is increased to 2 cache lines or
- * the entry struct shrinks.
- */
-
-/*
- * Overflow bucket ratio as a fraction of the fixed/configured count; a pool
- * of hash buckets used if a row in the fixed table overflows.
- */
-#define HICN_HASHTB_BUCKET_ENTRIES 5
-
-typedef struct __attribute__ ((packed))
-{
- hicn_hash_entry_t hb_entries[HICN_HASHTB_BUCKET_ENTRIES];
- u64 align1;
- u64 align2;
- u16 align3;
-} hicn_hash_bucket_t;
-
-/* Overall target fill-factor for the hashtable */
-#define HICN_HASHTB_FILL_FACTOR 4
-
-#define HICN_HASHTB_MIN_ENTRIES (1 << 4) // includes dummy node 0 entry
-#define HICN_HASHTB_MAX_ENTRIES (1 << 24)
-
-#define HICN_HASHTB_MIN_BUCKETS (1 << 10)
-
-/*
- * htab_t
- *
- * Hash table main structure.
- *
- * Contains - pointers to dynamically allocated arrays of cache-line
- * sized/aligned structures (buckets, nodes, keys). Put frequently accessed
- * fields in the first cache line.
- */
-typedef struct hicn_hashtb_s
-{
-
- /* 8B - main array of hash buckets */
- hicn_hash_bucket_t *ht_buckets;
-
- /* 8B - just-in-case block of overflow buckets */
- hicn_hash_bucket_t *ht_overflow_buckets;
-
- /* 8B - block of nodes associated with entries in buckets */
- hicn_hash_node_t *ht_nodes;
-
- /* Flags */
- u32 ht_flags;
-
- /* Count of buckets allocated in the main array */
- u32 ht_bucket_count;
-
- /* Count of overflow buckets allocated */
- u32 ht_overflow_bucket_count;
- u32 ht_overflow_buckets_used;
-
- /* Count of nodes allocated */
- u32 ht_node_count;
- u32 ht_nodes_used;
-
- /* Count of overflow key structs allocated */
- u32 ht_key_count;
- u32 ht_keys_used;
-
-} hicn_hashtb_t, *hicn_hashtb_h;
-
-/*
- * Offset to aligned start of additional data (PIT/CS, FIB) embedded in each
- * node.
- */
-extern u32 ht_node_data_offset_aligned;
-
-/* Flags for hashtable */
-
-#define HICN_HASHTB_FLAGS_DEFAULT 0x00
-
-/*
- * Don't use the last entry in each bucket - only use it for overflow. We use
- * this for the FIB, currently, so that we can support in-place FIB changes
- * that would be difficult if there were hash entry copies as part of
- * overflow handling.
- */
-#define HICN_HASHTB_FLAG_USE_SEVEN 0x04
-#define HICN_HASHTB_FLAG_KEY_FMT_PFX 0x08
-#define HICN_HASHTB_FLAG_KEY_FMT_NAME 0x10
-
-/*
- * Max prefix name components we'll support in our incremental hashing;
- * currently used only for LPM in the FIB.
- */
-#define HICN_HASHTB_MAX_NAME_COMPS HICN_PARAM_FIB_ENTRY_PFX_COMPS_MAX
-
-/*
- * APIs and inlines
- */
-
-/* Compute hash node index from node pointer */
-static inline u32
-hicn_hashtb_node_idx_from_node (hicn_hashtb_h h, hicn_hash_node_t *p)
-{
- return (p - h->ht_nodes);
-}
-
-/* Retrieve a hashtable node by node index */
-static inline hicn_hash_node_t *
-hicn_hashtb_node_from_idx (hicn_hashtb_h h, u32 idx)
-{
- return (pool_elt_at_index (h->ht_nodes, idx));
-}
-
-/* Allocate a brand-new hashtable */
-int hicn_hashtb_alloc (hicn_hashtb_h *ph, u32 max_elems, size_t app_data_size);
-
-/* Free a hashtable, including its embedded arrays */
-int hicn_hashtb_free (hicn_hashtb_h *ph);
-
-/* Hash a bytestring, currently using bihash */
-u64 hicn_hashtb_hash_bytestring (const u8 *key, u32 keylen);
-
-always_inline hicn_hash_entry_t *
-hicn_hashtb_get_entry (hicn_hashtb_h h, u32 entry_idx, u32 bucket_id,
- u8 bucket_overflow)
-{
- hicn_hash_bucket_t *bucket;
- if (bucket_overflow)
- bucket = pool_elt_at_index (h->ht_overflow_buckets, bucket_id);
- else
- bucket = (hicn_hash_bucket_t *) (h->ht_buckets + bucket_id);
-
- return &(bucket->hb_entries[entry_idx]);
-}
-
-/* Hash a name, currently using bihash */
-always_inline u64
-hicn_hashtb_hash_name (const u8 *key, u16 keylen)
-{
- if (key != NULL && keylen == HICN_V4_NAME_LEN)
- {
- clib_bihash_kv_8_8_t kv;
- kv.key = ((u64 *) key)[0];
- return clib_bihash_hash_8_8 (&kv);
- }
- else if (key != NULL && keylen == HICN_V6_NAME_LEN)
- {
- clib_bihash_kv_24_8_t kv;
- kv.key[0] = ((u64 *) key)[0];
- kv.key[1] = ((u64 *) key)[1];
- kv.key[2] = ((u32 *) key)[4];
- return clib_bihash_hash_24_8 (&kv);
- }
- else
- {
- return (-1LL);
- }
-}
-
-/*
- * Prepare a hashtable node for insertion, supplying the key and computed
- * hash info. This sets up the node->key relationship, possibly allocating
- * overflow key buffers.
- */
-void hicn_hashtb_init_node (hicn_hashtb_h h, hicn_hash_node_t *node,
- const u8 *key, u32 keylen);
-
-/*
- * Insert a node into the hashtable. We expect the caller has used the init
- * api to set the node key and hash info, and populated the extra data area
- * (if any) - or done the equivalent work itself.
- */
-int hicn_hashtb_insert (hicn_hashtb_h h, hicn_hash_node_t *node,
- hicn_hash_entry_t **hash_entry, u64 hash, u32 *node_id,
- index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs,
- u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow);
-
-/*
- * Basic api to lookup a specific hash+key tuple. This does the entire lookup
- * operation, retrieving node structs and comparing keys, so it's not
- * optimized for prefetching or high performance.
- *
- * Returns zero and mails back a node on success, errno otherwise.
- */
-int hicn_hashtb_lookup_node (hicn_hashtb_h h, const u8 *key, u32 keylen,
- u64 hashval, u8 is_data, u32 *node_id,
- index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs,
- u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow);
-
-/*
- * Extended api to lookup a specific hash+key tuple. The implementation
- * allows the caller to locate nodes that are marked for deletion; this is
- * part of some hashtable applications, such as the FIB.
- *
- * This does the entire lookup operation, retrieving node structs and comparing
- * keys, so it's not optimized for prefetching or high performance.
- *
- * Returns zero and mails back a node on success, errno otherwise.
- */
-int hicn_hashtb_lookup_node_ex (hicn_hashtb_h h, const u8 *key, u32 keylen,
- u64 hashval, u8 is_data, int include_deleted_p,
- u32 *node_id, index_t *dpo_ctx_id, u8 *vft_id,
- u8 *is_cs, u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow);
-
-/**
- * @brief Compares the key in the node with the given key
- *
- * This function allows to split the hash verification from the comparison of
- * the entire key. Useful to exploit prefertching.
- * @result 1 if equals, 0 otherwise
- */
-int hicn_node_compare (const u8 *key, u32 keylen, hicn_hash_node_t *node);
-
-/*
- * Remove a node from a hashtable using the node itself. The internal data
- * structs are cleaned up, but the node struct itself is not: the caller must
- * free the node itself.
- */
-void hicn_hashtb_remove_node (hicn_hashtb_h h, hicn_hash_node_t *node,
- u64 hashval);
-
-/*
- * Delete a node from a hashtable using the node itself, and delete/free the
- * node. Caller's pointer is cleared on success.
- */
-void hicn_hashtb_delete (hicn_hashtb_h h, hicn_hash_node_t **pnode,
- u64 hashval);
-
-/*
- * Utility to init a new entry in a hashtable bucket/row. We use this to add
- * new a node+hash, and to clear out an entry during removal.
- */
-void hicn_hashtb_init_entry (hicn_hash_entry_t *entry, u32 nodeidx,
- u64 hashval, u32 locks);
-
-/*
- * Return data area embedded in a hash node struct. We maintain an 'offset'
- * value in case the common node body struct doesn't leave the data area
- * aligned properly.
- */
-static inline void *
-hicn_hashtb_node_data (hicn_hash_node_t *node)
-{
- return ((u8 *) (node) + ht_node_data_offset_aligned);
-}
-
-/*
- * Use some bits of the low half of the hash to locate a row/bucket in the
- * table
- */
-static inline u32
-hicn_hashtb_bucket_idx (hicn_hashtb_h h, u64 hashval)
-{
- return ((u32) (hashval & (h->ht_bucket_count - 1)));
-}
-
-/*
- * Return a hash node struct from the free list, or NULL. Note that the
- * returned struct is _not_ cleared/zeroed - init is up to the caller.
- */
-static inline hicn_hash_node_t *
-hicn_hashtb_alloc_node (hicn_hashtb_h h)
-{
- hicn_hash_node_t *p = NULL;
-
- if (h->ht_nodes_used < h->ht_node_count)
- {
- pool_get_aligned (h->ht_nodes, p, 8);
- h->ht_nodes_used++;
- }
- return (p);
-}
-
-/*
- * Release a hashtable node back to the free list when an entry is cleared
- */
-void hicn_hashtb_free_node (hicn_hashtb_h h, hicn_hash_node_t *node);
-
-/*
- * Walk a hashtable, iterating through the nodes, keeping context in 'ctx'
- * between calls.
- *
- * Set the context value to HICN_HASH_WALK_CTX_INITIAL to start an iteration.
- */
-int hicn_hashtb_next_node (hicn_hashtb_h h, hicn_hash_node_t **pnode,
- u64 *ctx);
-
-int hicn_hashtb_key_to_str (hicn_hashtb_h h, const hicn_hash_node_t *node,
- char *buf, int bufsize, int must_fit);
-
-/*
- * single hash full name can pass offset for two hashes calculation in case
- * we use CS and PIT in a two steps hashes (prefix + seqno)
- */
-always_inline int
-hicn_hashtb_fullhash (const u8 *name, u16 namelen, u64 *name_hash)
-{
- *name_hash = hicn_hashtb_hash_name (name, namelen);
- return (*name_hash != (-1LL) ? HICN_ERROR_NONE : HICN_ERROR_HASHTB_INVAL);
-}
-
-#endif /* // __HICN_HASHTB_H__ */
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables: eval: (c-set-style "gnu") End:
- */
diff --git a/hicn-plugin/src/hicn.api b/hicn-plugin/src/hicn.api
index 9643f2098..d999e0de5 100644
--- a/hicn-plugin/src/hicn.api
+++ b/hicn-plugin/src/hicn.api
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,6 +22,14 @@ enum hicn_action_type
HICN_ENABLE,
};
+enum hicn_strategy
+{
+ HICN_STRATEGY_MW = 0,
+ HICN_STRATEGY_RR,
+ HICN_STRATEGY_RP,
+ HICN_STRATEGY_LR,
+};
+
typedef hicn_face
{
/* IP local address */
@@ -360,6 +368,33 @@ define hicn_api_routes_dump
u32 context;
};
+define hicn_api_strategy_set
+{
+ /* Client identifier, set from api_main.my_client_index */
+ u32 client_index;
+
+ /* Arbitrary context, so client can match reply to request */
+ u32 context;
+
+ /* Fib prefix for the strategy */
+ vl_api_prefix_t prefix;
+
+ /* ID of the strategy to set for this prefix */
+ vl_api_hicn_strategy_t strategy_id;
+};
+
+define hicn_api_strategy_set_reply
+{
+ /* Client identifier, set from api_main.my_client_index */
+ u32 client_index;
+
+ /* Arbitrary context, so client can match reply to request */
+ u32 context;
+
+ /* Return value, zero means all OK */
+ i32 retval;
+};
+
define hicn_api_strategies_get
{
/* Client identifier, set from api_main.my_client_index */
@@ -381,7 +416,7 @@ define hicn_api_strategies_get_reply
u8 n_strategies;
/* Strategies */
- u32 strategy_id[256];
+ vl_api_hicn_strategy_t strategy_id[256];
/* Return value, zero means all OK */
i32 retval;
@@ -396,7 +431,7 @@ define hicn_api_strategy_get
u32 context;
/* Route prefix */
- u32 strategy_id;
+ vl_api_hicn_strategy_t strategy_id;
};
define hicn_api_strategy_get_reply
@@ -437,8 +472,14 @@ define hicn_api_enable_disable_reply
/* Arbitrary context, so client can match reply to request */
u32 context;
-/* Return value, zero means all OK */
+ /* Return value, zero means all OK */
i32 retval;
+
+ /* Number of faces created */
+ u8 nfaces;
+
+ /* IDs of new faces */
+ u32 faceids[16];
};
define hicn_api_register_prod_app
@@ -457,6 +498,9 @@ define hicn_api_register_prod_app
/* CS memory reserved -- in number of packets */
u32 cs_reserved;
+
+ /* Port identifying producer application */
+ u16 port;
};
define hicn_api_register_prod_app_reply
@@ -499,6 +543,9 @@ define hicn_api_register_cons_app
/* swif */
u32 swif;
+
+ /* src port of consumer packet from this face */
+ u16 port;
};
define hicn_api_register_cons_app_reply
@@ -570,6 +617,48 @@ define hicn_api_udp_tunnel_add_del_reply
u32 uei;
};
+define hicn_api_mapme_default_route_set
+{
+ /* Client identifier, set from api_main.my_client_index */
+ u32 client_index;
+
+ /* Arbitrary context, so client can match reply to request */
+ u32 context;
+
+ /* Fib prefix to be used as default if mapme EPM fails */
+ vl_api_prefix_t prefix;
+};
+
+define hicn_api_mapme_default_route_set_reply
+{
+ /* From the request */
+ u32 context;
+
+ /* Return value, zero means all OK */
+ i32 retval;
+};
+
+define hicn_api_mapme_default_route_get
+{
+ /* Client identifier, set from api_main.my_client_index */
+ u32 client_index;
+
+ /* Arbitrary context, so client can match reply to request */
+ u32 context;
+};
+
+define hicn_api_mapme_default_route_get_reply
+{
+ /* From the request */
+ u32 context;
+
+ /* Return value, zero means all OK */
+ i32 retval;
+
+ /* Fib prefix to be used as default if mapme EPM fails */
+ vl_api_prefix_t prefix;
+};
+
/*
* fd.io coding-style-patch-verification: ON
*
diff --git a/hicn-plugin/src/hicn.c b/hicn-plugin/src/hicn.c
index 9bec91455..d48ef4023 100644
--- a/hicn-plugin/src/hicn.c
+++ b/hicn-plugin/src/hicn.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,22 +25,15 @@
#include "mgmt.h"
#include "error.h"
#include "faces/app/address_mgr.h"
-#include "face_db.h"
#include "udp_tunnels/udp_tunnel.h"
#include "route.h"
+#include "pg.h"
hicn_main_t hicn_main;
/* Module vars */
int hicn_infra_fwdr_initialized = 0;
-/*
- * Global time counters we're trying out for opportunistic hashtable
- * expiration.
- */
-uint16_t hicn_infra_fast_timer; /* Counts at 1 second intervals */
-uint16_t hicn_infra_slow_timer; /* Counts at 1 minute intervals */
-
-hicn_face_bucket_t *hicn_face_bucket_pool;
+// hicn_face_bucket_t *hicn_face_bucket_pool;
/*
* Init hicn forwarder with configurable PIT, CS sizes
@@ -48,29 +41,27 @@ hicn_face_bucket_t *hicn_face_bucket_pool;
static int
hicn_infra_fwdr_init (uint32_t shard_pit_size, uint32_t shard_cs_size)
{
- int ret = 0;
+ int ret = HICN_ERROR_NONE;
if (hicn_infra_fwdr_initialized)
{
ret = HICN_ERROR_FWD_ALREADY_ENABLED;
- goto done;
+ goto DONE;
}
+
/* Init per worker limits */
hicn_infra_pit_size = shard_pit_size;
hicn_infra_cs_size = shard_cs_size;
- /* Init the global time-compression counters */
- hicn_infra_fast_timer = 1;
- hicn_infra_slow_timer = 1;
+ hicn_pit_create (&hicn_main.pitcs, hicn_infra_pit_size, hicn_infra_cs_size);
- ret = hicn_pit_create (&hicn_main.pitcs, hicn_infra_pit_size);
- hicn_pit_set_lru_max (&hicn_main.pitcs, hicn_infra_cs_size);
-done:
+DONE:
if ((ret == HICN_ERROR_NONE) && !hicn_infra_fwdr_initialized)
{
hicn_infra_fwdr_initialized = 1;
}
- return (ret);
+
+ return ret;
}
/*
@@ -149,8 +140,8 @@ hicn_infra_plugin_enable_disable (int enable_disable, int pit_size_req,
// check if CS is bugger tha PIT or bigger than the available
// vlib_buffers
uword cs_buffers = (n_buffers > HICN_PARAM_CS_MIN_MBUF) ?
- n_buffers - HICN_PARAM_CS_MIN_MBUF :
- 0;
+ n_buffers - HICN_PARAM_CS_MIN_MBUF :
+ 0;
if (cs_size_req > (pit_size_req / 2) || cs_size_req > cs_buffers)
{
@@ -165,8 +156,6 @@ hicn_infra_plugin_enable_disable (int enable_disable, int pit_size_req,
ret = hicn_infra_fwdr_init (pit_size, cs_size);
- hicn_face_db_init (pit_size);
-
if (ret != HICN_ERROR_NONE)
{
goto done;
@@ -223,24 +212,29 @@ hicn_init (vlib_main_t *vm)
hicn_main_t *sm = &hicn_main;
- /* Init other elements in the 'main' struct */
+ // Init other elements in the 'main' struct
sm->is_enabled = 0;
error = hicn_api_plugin_hookup (vm);
- /* Init the dpo module */
+ // Init the dpo module
hicn_dpos_init ();
- /* Init the app manager */
+ // Init the app manager
address_mgr_init ();
+ // Init the face module
hicn_face_module_init (vm);
- /* Init the route module */
+ // Init the route module
hicn_route_init ();
+ // Init the UDP tunnels module
udp_tunnel_init ();
+ // Init the packet generator module
+ hicn_pg_init (vm);
+
return error;
}
diff --git a/hicn-plugin/src/hicn.h b/hicn-plugin/src/hicn.h
index 4ff4f6ae6..7231773d7 100644
--- a/hicn-plugin/src/hicn.h
+++ b/hicn-plugin/src/hicn.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,20 +16,7 @@
#ifndef __HICN_H__
#define __HICN_H__
-#define ip_address_t hicn_ip_address_t
-#define ip_address_cmp hicn_ip_address_cmp
-#define ip_prefix_t hicn_ip_prefix_t
-#define ip_prefix_cmp hicn_ip_prefix_cmp
-#undef ip_prefix_len
-#define ip_prefix_len hicn_ip_prefix_len
#include <hicn/hicn.h>
-#undef ip_address_t
-#undef ip_address_cmp
-#undef ip_prefix_t
-#undef ip_prefix_cmp
-#undef ip_prefix_len
-#define ip_prefix_len(_a) (_a)->len
-
#include "faces/face.h"
#include <netinet/in.h>
@@ -57,37 +44,57 @@ typedef u8 weight_t;
#define VLIB_BUFFER_MIN_CHAIN_SEG_SIZE (128)
#endif
-/* vlib_buffer cloning utilities impose that current_lentgh is more that
- * 2*CLIB_CACHE_LINE_BYTES. */
-/* This flag is used to mark packets whose lenght is less that
- * 2*CLIB_CACHE_LINE_BYTES. */
-#define HICN_BUFFER_FLAGS_PKT_LESS_TWO_CL 0x02
-#define HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL 0x04
-#define HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL 0x08
-#define HICN_BUFFER_FLAGS_FROM_CS 0x10
+#define MAX_OUT_FACES 8
/* The following is stored in the opaque2 field in the vlib_buffer_t */
typedef struct
{
- /* hash of the name */
- u64 name_hash;
-
- /* ids to prefetch a PIT/CS entry */
- u32 node_id;
- u32 bucket_id;
- u8 hash_entry_id;
- u8 hash_bucket_flags;
-
+ /**
+ * Cached packet info
+ */
+ hicn_packet_buffer_t pkbuf;
+
+ /**
+ * IDs to prefetch a PIT/CS entry (4)
+ */
+ u32 pcs_entry_id;
+
+ /**
+ * DPO/Stategy VFT ID. This is also the DPO type (4)
+ */
+ dpo_type_t vft_id;
+
+ /**
+ * DPO context ID (4)
+ */
+ u32 dpo_ctx_id;
+
+ /**
+ * Cached packet info
+ */
+ u16 payload_type;
+ hicn_lifetime_t lifetime;
+
+ /**
+ * Ingress face (4)
+ */
+ hicn_face_id_t face_id;
+
+ /**
+ * hICN buffer flags (1)
+ */
u8 flags;
- u8 dpo_ctx_id; /* used for data path */
- u8 vft_id; /* " */
-
- hicn_face_id_t face_id; /* ingress iface, sizeof(u32) */
- u32 in_faces_vec_id; /* vector of possible input face for a data packet */
-
- hicn_type_t type;
} hicn_buffer_t;
+STATIC_ASSERT (offsetof (hicn_buffer_t, pcs_entry_id) == 24, "");
+STATIC_ASSERT (offsetof (hicn_buffer_t, vft_id) == 28, "");
+STATIC_ASSERT (offsetof (hicn_buffer_t, dpo_ctx_id) == 32, "");
+STATIC_ASSERT (offsetof (hicn_buffer_t, payload_type) == 36, "");
+STATIC_ASSERT (offsetof (hicn_buffer_t, lifetime) == 40, "");
+STATIC_ASSERT (offsetof (hicn_buffer_t, face_id) == 44, "");
+STATIC_ASSERT (offsetof (hicn_buffer_t, flags) == 48, "");
+// + name = 16+4 = 20
+// opaque : u32[14] = 56
STATIC_ASSERT (sizeof (hicn_buffer_t) <=
STRUCT_SIZE_OF (vlib_buffer_t, opaque2),
"hICN buffer opaque2 meta-data too large for vlib_buffer");
@@ -98,12 +105,47 @@ hicn_get_buffer (vlib_buffer_t *b0)
return (hicn_buffer_t *) &(b0->opaque2[0]);
}
+#if 0
always_inline u8
hicn_is_v6 (hicn_header_t *pkt_hdr)
{
return ((pkt_hdr->v4.ip.version_ihl >> 4) != 4);
}
+always_inline hicn_name_t *
+hicn_buffer_get_name (vlib_buffer_t *b)
+{
+ return hicn_packet_get_name(&hicn_get_buffer (b)->pkbuf);
+}
+#endif
+
+always_inline u8
+hicn_buffer_is_v6 (vlib_buffer_t *b0)
+{
+ hicn_packet_format_t format =
+ hicn_packet_get_format (&hicn_get_buffer (b0)->pkbuf);
+ return HICN_PACKET_FORMAT_IS_IPV6 (format);
+}
+
+always_inline void
+hicn_buffer_set_flags (vlib_buffer_t *b, u8 flags)
+{
+ hicn_buffer_t *hb = hicn_get_buffer (b);
+ hb->flags |= flags;
+}
+
+always_inline hicn_lifetime_t
+hicn_buffer_get_lifetime (vlib_buffer_t *b)
+{
+ return hicn_get_buffer (b)->lifetime;
+}
+
+always_inline hicn_payload_type_t
+hicn_buffer_get_payload_type (vlib_buffer_t *b)
+{
+ return hicn_get_buffer (b)->payload_type;
+}
+
#endif /* __HICN_H__ */
/*
diff --git a/hicn-plugin/src/hicn_api.c b/hicn-plugin/src/hicn_api.c
index b72675f63..28d993a4a 100644
--- a/hicn-plugin/src/hicn_api.c
+++ b/hicn-plugin/src/hicn_api.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -38,14 +38,15 @@
#include "faces/app/face_prod.h"
#include "faces/app/face_cons.h"
#include "route.h"
+#include "mapme.h"
/* define message IDs */
-#include <hicn/hicn.api_enum.h>
-#include <hicn/hicn.api_types.h>
+#include <vpp_plugins/hicn/hicn.api_enum.h>
+#include <vpp_plugins/hicn/hicn.api_types.h>
/* define generated endian-swappers */
#define vl_endianfun
-#include <hicn/hicn_all_api_h.h>
+#include <vpp_plugins/hicn/hicn_all_api_h.h>
#undef vl_endianfun
#define REPLY_MSG_ID_BASE sm->msg_id_base
@@ -79,8 +80,8 @@ vl_api_hicn_api_node_params_set_t_handler (
f64 pit_max_lifetime_sec = mp->pit_max_lifetime_sec;
pit_max_lifetime_sec = pit_max_lifetime_sec == -1 ?
- HICN_PARAM_PIT_LIFETIME_DFLT_MAX_MS / SEC_MS :
- pit_max_lifetime_sec;
+ HICN_PARAM_PIT_LIFETIME_DFLT_MAX_MS / SEC_MS :
+ pit_max_lifetime_sec;
int cs_max_size = clib_net_to_host_i32 (mp->cs_max_size);
cs_max_size = cs_max_size == -1 ? HICN_PARAM_CS_ENTRIES_DFLT : cs_max_size;
@@ -159,7 +160,7 @@ send_face_details (hicn_face_t *face, vl_api_hicn_face_t *mp)
{
sbuf =
format (0, "%U", format_vnet_sw_interface_name, vnm, sw_interface);
- strcpy ((char *) (mp->if_name), (char *) sbuf);
+ strcpy_s ((char *) (mp->if_name), sizeof (mp->if_name), (char *) sbuf);
}
}
@@ -451,6 +452,28 @@ vl_api_hicn_api_strategies_get_t_handler (vl_api_hicn_api_strategies_get_t *mp)
}
static void
+vl_api_hicn_api_strategy_set_t_handler (vl_api_hicn_api_strategy_set_t *mp)
+{
+ vl_api_hicn_api_strategy_set_reply_t *rmp;
+ int rv = HICN_ERROR_NONE;
+ fib_prefix_t prefix;
+ vl_api_hicn_strategy_t strategy_id;
+
+ hicn_main_t *sm = &hicn_main;
+
+ // Decode prefix
+ ip_prefix_decode (&mp->prefix, &prefix);
+
+ // Decode strategy id
+ strategy_id = clib_net_to_host_u32 (mp->strategy_id);
+
+ // Try to set the strategy
+ rv = hicn_route_set_strategy (&prefix, strategy_id);
+
+ REPLY_MACRO (VL_API_HICN_API_STRATEGY_SET_REPLY);
+}
+
+static void
vl_api_hicn_api_strategy_get_t_handler (vl_api_hicn_api_strategy_get_t *mp)
{
vl_api_hicn_api_strategy_get_reply_t *rmp;
@@ -458,7 +481,7 @@ vl_api_hicn_api_strategy_get_t_handler (vl_api_hicn_api_strategy_get_t *mp)
hicn_main_t *sm = &hicn_main;
- u32 strategy_id = clib_net_to_host_u32 (mp->strategy_id);
+ vl_api_hicn_strategy_t strategy_id = clib_net_to_host_u32 (mp->strategy_id);
rv = hicn_dpo_strategy_id_is_valid (strategy_id);
REPLY_MACRO2 (VL_API_HICN_API_STRATEGY_GET_REPLY /* , rmp, mp, rv */, ({
@@ -472,6 +495,49 @@ vl_api_hicn_api_strategy_get_t_handler (vl_api_hicn_api_strategy_get_t *mp)
}));
}
+/************* MAPME ****************/
+
+static void
+vl_api_hicn_api_mapme_default_route_set_t_handler (
+ vl_api_hicn_api_mapme_default_route_set_t *mp)
+{
+ vl_api_hicn_api_mapme_default_route_set_reply_t *rmp;
+ int rv = HICN_ERROR_NONE;
+ fib_prefix_t prefix;
+
+ hicn_main_t *sm = &hicn_main;
+
+ // Decode prefix
+ ip_prefix_decode (&mp->prefix, &prefix);
+
+ // Set the the prefix
+ hicn_mapme_main_t *mm = hicn_mapme_get_main ();
+ mm->default_route = prefix;
+
+ REPLY_MACRO (VL_API_HICN_API_MAPME_DEFAULT_ROUTE_SET_REPLY);
+}
+
+static void
+vl_api_hicn_api_mapme_default_route_get_t_handler (
+ vl_api_hicn_api_mapme_default_route_get_t *mp)
+{
+ vl_api_hicn_api_mapme_default_route_get_reply_t *rmp;
+ int rv = HICN_ERROR_NONE;
+
+ hicn_main_t *sm = &hicn_main;
+
+ // Get the the prefix
+ hicn_mapme_main_t *mm = hicn_mapme_get_main ();
+
+ REPLY_MACRO2 (
+ VL_API_HICN_API_MAPME_DEFAULT_ROUTE_GET_REPLY /* , rmp, mp, rv */, ({
+ if (rv == HICN_ERROR_NONE)
+ {
+ ip_prefix_encode (&mm->default_route, &rmp->prefix);
+ }
+ }));
+}
+
/************* APP FACE ****************/
static void
@@ -567,17 +633,35 @@ vl_api_hicn_api_enable_disable_t_handler (vl_api_hicn_api_enable_disable_t *mp)
fib_prefix_t prefix;
ip_prefix_decode (&mp->prefix, &prefix);
+ hicn_face_id_t *vec_faces = NULL;
+ fib_node_index_t hicn_fib_index;
+
switch (clib_net_to_host_u32 (mp->enable_disable))
{
case HICN_ENABLE:
- rv = hicn_route_enable (&prefix);
+ HICN_DEBUG ("Calling hicn enable from API.");
+ rv = hicn_route_enable (&prefix, &hicn_fib_index, &vec_faces);
break;
case HICN_DISABLE:
+ HICN_DEBUG ("Calling hicn disable from API.");
rv = hicn_route_disable (&prefix);
break;
}
- REPLY_MACRO (VL_API_HICN_API_ENABLE_DISABLE_REPLY /* , rmp, mp, rv */);
+ REPLY_MACRO2 (VL_API_HICN_API_ENABLE_DISABLE_REPLY, ({
+ rmp->nfaces = 0;
+ if (vec_faces != NULL)
+ {
+ hicn_face_id_t *face;
+ vec_foreach (face, vec_faces)
+ {
+ rmp->faceids[rmp->nfaces++] =
+ clib_host_to_net_u32 (*face);
+ }
+
+ vec_free (vec_faces);
+ }
+ }));
}
/*********************************** UDP TUNNELS
@@ -632,7 +716,7 @@ done:
/************************************************************************************/
-#include <hicn/hicn.api.c>
+#include <vpp_plugins/hicn/hicn.api.c>
/* Set up the API message handling tables */
clib_error_t *
diff --git a/hicn-plugin/src/hicn_api_test.c b/hicn-plugin/src/hicn_api_test.c
index 04e216e38..3ca48d98a 100644
--- a/hicn-plugin/src/hicn_api_test.c
+++ b/hicn-plugin/src/hicn_api_test.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -31,180 +31,12 @@
#include <vpp/api/vpe.api_types.h>
-#include <hicn/hicn_api.h>
-#include "error.h"
+#include <vpp_plugins/hicn/hicn_api.h>
+#include <vpp_plugins/hicn/error.h>
+#include <vpp_plugins/hicn/hicn_enums.h>
/* Declare message IDs */
-#include "hicn_msg_enum.h"
-
-/* SUPPORTING FUNCTIONS NOT LOADED BY VPP_API_TEST */
-uword
-unformat_ip46_address (unformat_input_t *input, va_list *args)
-{
- ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
- ip46_type_t type = va_arg (*args, ip46_type_t);
- if ((type != IP46_TYPE_IP6) &&
- unformat (input, "%U", unformat_ip4_address, &ip46->ip4))
- {
- ip46_address_mask_ip4 (ip46);
- return 1;
- }
- else if ((type != IP46_TYPE_IP4) &&
- unformat (input, "%U", unformat_ip6_address, &ip46->ip6))
- {
- return 1;
- }
- return 0;
-}
-
-static ip46_type_t
-ip_address_union_decode (const vl_api_address_union_t *in,
- vl_api_address_family_t af, ip46_address_t *out)
-{
- ip46_type_t type;
-
- switch (clib_net_to_host_u32 (af))
- {
- case ADDRESS_IP4:
- clib_memset (out, 0, sizeof (*out));
- clib_memcpy (&out->ip4, &in->ip4, sizeof (out->ip4));
- type = IP46_TYPE_IP4;
- break;
- case ADDRESS_IP6:
- clib_memcpy (&out->ip6, &in->ip6, sizeof (out->ip6));
- type = IP46_TYPE_IP6;
- break;
- default:
- ASSERT (!"Unkown address family in API address type");
- type = IP46_TYPE_ANY;
- break;
- }
-
- return type;
-}
-
-void
-ip6_address_encode (const ip6_address_t *in, vl_api_ip6_address_t out)
-{
- clib_memcpy (out, in, sizeof (*in));
-}
-
-void
-ip6_address_decode (const vl_api_ip6_address_t in, ip6_address_t *out)
-{
- clib_memcpy (out, in, sizeof (*out));
-}
-
-void
-ip4_address_encode (const ip4_address_t *in, vl_api_ip4_address_t out)
-{
- clib_memcpy (out, in, sizeof (*in));
-}
-
-void
-ip4_address_decode (const vl_api_ip4_address_t in, ip4_address_t *out)
-{
- clib_memcpy (out, in, sizeof (*out));
-}
-
-static void
-ip_address_union_encode (const ip46_address_t *in, vl_api_address_family_t af,
- vl_api_address_union_t *out)
-{
- if (ADDRESS_IP6 == clib_net_to_host_u32 (af))
- ip6_address_encode (&in->ip6, out->ip6);
- else
- ip4_address_encode (&in->ip4, out->ip4);
-}
-
-ip46_type_t
-ip_address_decode (const vl_api_address_t *in, ip46_address_t *out)
-{
- return (ip_address_union_decode (&in->un, in->af, out));
-}
-
-void
-ip_address_encode (const ip46_address_t *in, ip46_type_t type,
- vl_api_address_t *out)
-{
- switch (type)
- {
- case IP46_TYPE_IP4:
- out->af = clib_net_to_host_u32 (ADDRESS_IP4);
- break;
- case IP46_TYPE_IP6:
- out->af = clib_net_to_host_u32 (ADDRESS_IP6);
- break;
- case IP46_TYPE_ANY:
- if (ip46_address_is_ip4 (in))
- out->af = clib_net_to_host_u32 (ADDRESS_IP4);
- else
- out->af = clib_net_to_host_u32 (ADDRESS_IP6);
- break;
- }
- ip_address_union_encode (in, out->af, &out->un);
-}
-
-fib_protocol_t
-fib_proto_from_ip46 (ip46_type_t iproto)
-{
- switch (iproto)
- {
- case IP46_TYPE_IP4:
- return FIB_PROTOCOL_IP4;
- case IP46_TYPE_IP6:
- return FIB_PROTOCOL_IP6;
- case IP46_TYPE_ANY:
- ASSERT (0);
- return FIB_PROTOCOL_IP4;
- }
-
- ASSERT (0);
- return FIB_PROTOCOL_IP4;
-}
-
-ip46_type_t
-fib_proto_to_ip46 (fib_protocol_t fproto)
-{
- switch (fproto)
- {
- case FIB_PROTOCOL_IP4:
- return (IP46_TYPE_IP4);
- case FIB_PROTOCOL_IP6:
- return (IP46_TYPE_IP6);
- case FIB_PROTOCOL_MPLS:
- return (IP46_TYPE_ANY);
- }
- ASSERT (0);
- return (IP46_TYPE_ANY);
-}
-
-void
-ip_prefix_decode (const vl_api_prefix_t *in, fib_prefix_t *out)
-{
- switch (clib_net_to_host_u32 (in->address.af))
- {
- case ADDRESS_IP4:
- out->fp_proto = FIB_PROTOCOL_IP4;
- break;
- case ADDRESS_IP6:
- out->fp_proto = FIB_PROTOCOL_IP6;
- break;
- }
- out->fp_len = in->len;
- out->___fp___pad = 0;
- ip_address_decode (&in->address, &out->fp_addr);
-}
-
-void
-ip_prefix_encode (const fib_prefix_t *in, vl_api_prefix_t *out)
-{
- out->len = in->fp_len;
- ip_address_encode (&in->fp_addr, fib_proto_to_ip46 (in->fp_proto),
- &out->address);
-}
-
-/////////////////////////////////////////////////////
+#include <vpp_plugins/hicn/hicn_msg_enum.h>
#define HICN_FACE_NULL ~0
@@ -256,9 +88,14 @@ foreach_standard_reply_retval_handler;
_ (HICN_API_ROUTE_GET_REPLY, hicn_api_route_get_reply) \
_ (HICN_API_ROUTES_DETAILS, hicn_api_routes_details) \
_ (HICN_API_STRATEGIES_GET_REPLY, hicn_api_strategies_get_reply) \
+ _ (HICN_API_STRATEGY_SET_REPLY, hicn_api_strategy_set_reply) \
_ (HICN_API_STRATEGY_GET_REPLY, hicn_api_strategy_get_reply) \
_ (HICN_API_ENABLE_DISABLE_REPLY, hicn_api_enable_disable_reply) \
- _ (HICN_API_UDP_TUNNEL_ADD_DEL_REPLY, hicn_api_udp_tunnel_add_del_reply)
+ _ (HICN_API_UDP_TUNNEL_ADD_DEL_REPLY, hicn_api_udp_tunnel_add_del_reply) \
+ _ (HICN_API_MAPME_DEFAULT_ROUTE_SET_REPLY, \
+ hicn_api_mapme_default_route_set_reply) \
+ _ (HICN_API_MAPME_DEFAULT_ROUTE_GET_REPLY, \
+ hicn_api_mapme_default_route_get_reply)
static int
api_hicn_api_node_params_set (vat_main_t *vam)
@@ -900,13 +737,194 @@ vl_api_hicn_api_strategies_get_reply_t_handler (
}
static int
+api_hicn_api_strategy_set (vat_main_t *vam)
+{
+ unformat_input_t *input = vam->input;
+ vl_api_hicn_api_strategy_set_t *mp;
+ int ret;
+ int addpfx = -1;
+ fib_prefix_t fib_prefix;
+ ip46_address_t address;
+ int plen;
+
+ vl_api_hicn_strategy_t strategy_id = HICN_STRATEGY_NULL;
+
+ while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (input, "strategy %d", &strategy_id))
+ {
+ addpfx = 2;
+ }
+ else if (addpfx != -1 &&
+ unformat (input, "prefix %U/%d", unformat_ip46_address,
+ &address, IP46_TYPE_ANY, &plen))
+ {
+ ;
+ }
+ else
+ {
+ clib_warning ("Error parsing input string.");
+ return 1;
+ }
+ }
+
+ if (strategy_id == HICN_STRATEGY_NULL)
+ {
+ clib_warning ("Please specify strategy id...");
+ return 1;
+ }
+
+ // Get fib prefix
+ fib_prefix_from_ip46_addr (&address, &fib_prefix);
+ fib_prefix.fp_len = plen;
+
+ /* Construct the API message */
+ M (HICN_API_STRATEGY_SET, mp);
+ mp->strategy_id = clib_host_to_net_u32 (strategy_id);
+ ip_prefix_encode (&fib_prefix, &mp->prefix);
+
+ /* send it... */
+ S (mp);
+
+ /* Wait for a reply... */
+ W (ret);
+
+ return ret;
+}
+
+static void
+vl_api_hicn_api_mapme_default_route_set_reply_t_handler (
+ vl_api_hicn_api_mapme_default_route_set_reply_t *mp)
+{
+ vat_main_t *vam = hicn_test_main.vat_main;
+ i32 retval = ntohl (mp->retval);
+
+ if (vam->async_mode)
+ {
+ vam->async_errors += (retval < 0);
+ return;
+ }
+
+ vam->retval = retval;
+ vam->result_ready = 1;
+
+ if (vam->retval < 0)
+ {
+ fformat (vam->ofp, " (API call error: %d)\n", vam->retval);
+ }
+}
+
+static void
+vl_api_hicn_api_mapme_default_route_get_reply_t_handler (
+ vl_api_hicn_api_mapme_default_route_get_reply_t *mp)
+{
+ vat_main_t *vam = hicn_test_main.vat_main;
+ i32 retval = ntohl (mp->retval);
+ fib_prefix_t prefix;
+ u8 *sbuf = 0;
+
+ ip_prefix_decode (&mp->prefix, &prefix);
+
+ if (vam->async_mode)
+ {
+ vam->async_errors += (retval < 0);
+ return;
+ }
+
+ vam->retval = retval;
+ vam->result_ready = 1;
+
+ if (vam->retval < 0)
+ {
+ fformat (vam->ofp, " (API call error: %d)\n", vam->retval);
+ return;
+ }
+
+ sbuf = format (sbuf, "Mapme Default Route: %U", format_fib_prefix, &prefix);
+ fformat (vam->ofp, "%s\n", sbuf);
+}
+
+static int
+api_hicn_api_mapme_default_route_set (vat_main_t *vam)
+{
+ unformat_input_t *input = vam->input;
+ vl_api_hicn_api_mapme_default_route_set_t *mp;
+ int ret;
+ fib_prefix_t fib_prefix;
+
+ while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (input, "default_route %U/%d", unformat_ip46_address,
+ &fib_prefix.fp_addr, IP46_TYPE_ANY, &fib_prefix.fp_len))
+ {
+ ;
+ }
+ else
+ {
+ clib_warning ("Please specify valid route.");
+ return 1;
+ }
+ }
+
+ /* Construct the API message */
+ M (HICN_API_MAPME_DEFAULT_ROUTE_SET, mp);
+ ip_prefix_encode (&fib_prefix, &mp->prefix);
+
+ /* send it... */
+ S (mp);
+
+ /* Wait for a reply... */
+ W (ret);
+
+ return ret;
+}
+
+static int
+api_hicn_api_mapme_default_route_get (vat_main_t *vam)
+{
+ unformat_input_t *input = vam->input;
+ vl_api_hicn_api_mapme_default_route_set_t *mp;
+ int ret;
+ int default_route = 0;
+
+ while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (input, "default_route"))
+ {
+ default_route = 1;
+ }
+ else
+ {
+ clib_warning ("Invalid option");
+ return 1;
+ }
+ }
+
+ if (default_route == 0)
+ {
+ return 1;
+ }
+
+ /* Construct the API message */
+ M (HICN_API_MAPME_DEFAULT_ROUTE_GET, mp);
+
+ /* send it... */
+ S (mp);
+
+ /* Wait for a reply... */
+ W (ret);
+
+ return ret;
+}
+
+static int
api_hicn_api_strategy_get (vat_main_t *vam)
{
unformat_input_t *input = vam->input;
vl_api_hicn_api_strategy_get_t *mp;
int ret;
- u32 strategy_id = HICN_STRATEGY_NULL;
+ vl_api_hicn_strategy_t strategy_id = HICN_STRATEGY_NULL;
while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
{
@@ -963,6 +981,28 @@ vl_api_hicn_api_strategy_get_reply_t_handler (
fformat (vam->ofp, "%s", mp->description);
}
+static void
+vl_api_hicn_api_strategy_set_reply_t_handler (
+ vl_api_hicn_api_strategy_set_reply_t *mp)
+{
+ vat_main_t *vam = hicn_test_main.vat_main;
+ i32 retval = ntohl (mp->retval);
+
+ if (vam->async_mode)
+ {
+ vam->async_errors += (retval < 0);
+ return;
+ }
+
+ vam->retval = retval;
+ vam->result_ready = 1;
+
+ if (vam->retval < 0)
+ {
+ fformat (vam->ofp, " (API call error: %d)\n", vam->retval);
+ }
+}
+
static int
api_hicn_api_enable_disable (vat_main_t *vam)
{
@@ -1000,8 +1040,8 @@ api_hicn_api_enable_disable (vat_main_t *vam)
}
prefix.fp_proto = ip46_address_is_ip4 (&(prefix.fp_addr)) ?
- FIB_PROTOCOL_IP4 :
- FIB_PROTOCOL_IP6;
+ FIB_PROTOCOL_IP4 :
+ FIB_PROTOCOL_IP6;
// Construct the API message
M (HICN_API_ENABLE_DISABLE, mp);
@@ -1053,8 +1093,8 @@ api_hicn_api_register_prod_app (vat_main_t *vam)
}
prefix.fp_proto = ip46_address_is_ip4 (&(prefix.fp_addr)) ?
- FIB_PROTOCOL_IP4 :
- FIB_PROTOCOL_IP6;
+ FIB_PROTOCOL_IP4 :
+ FIB_PROTOCOL_IP6;
/* Construct the API message */
M (HICN_API_REGISTER_PROD_APP, mp);
ip_prefix_encode (&prefix, &mp->prefix);
@@ -1310,7 +1350,7 @@ vl_api_hicn_api_udp_tunnel_add_del_reply_t_handler (
fformat (vam->ofp, "udp-encap %d\n", uei);
}
-#include <hicn/hicn.api_test.c>
+#include <vpp_plugins/hicn/hicn.api_test.c>
/*
* fd.io coding-style-patch-verification: ON
diff --git a/hicn-plugin/src/hicn_buffer_flags.h b/hicn-plugin/src/hicn_buffer_flags.h
new file mode 100644
index 000000000..7d99e6d33
--- /dev/null
+++ b/hicn-plugin/src/hicn_buffer_flags.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __HICN_BUFFER_FLAGS_H__
+#define __HICN_BUFFER_FLAGS_H__
+
+#define foreach_hicn_buffer_flag \
+ _ (0, NEW_FACE, "new face") \
+ _ (1, PKT_LESS_TWO_CL, "packet is less that 2 cache lines length") \
+ _ (2, FROM_UDP4_TUNNEL, "packet is from udp4 tunnel") \
+ _ (3, FROM_UDP6_TUNNEL, "packet is from udp6 tunnel") \
+ _ (4, FROM_CS, "packet is from cs") \
+ _ (5, FROM_PG, "packet is from packet generator")
+
+enum
+{
+ HICN_BUFFER_FLAGS_DEFAULT = 0,
+#define _(a, b, c) HICN_BUFFER_FLAGS_##b = (1 << a),
+ foreach_hicn_buffer_flag
+#undef _
+};
+
+#endif /* __HICN_BUFFER_FLAGS_H__ */ \ No newline at end of file
diff --git a/hicn-plugin/src/hicn_logging.h b/hicn-plugin/src/hicn_logging.h
new file mode 100644
index 000000000..2e534e546
--- /dev/null
+++ b/hicn-plugin/src/hicn_logging.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __HICN_DEBUG_H__
+#define __HICN_DEBUG_H__
+
+#ifdef HICN_DDEBUG
+#define HICN_DEBUG(...) \
+ do \
+ { \
+ clib_warning (__VA_ARGS__); \
+ } \
+ while (0)
+#else
+#define HICN_DEBUG(...)
+#endif /* HICN_DEBUG */
+
+#define HICN_ERROR(...) clib_warning (__VA_ARGS__)
+
+#endif /* __HICN_DEBUG_H__ */ \ No newline at end of file
diff --git a/hicn-light/src/hicn/strategies/rnd.h b/hicn-plugin/src/infra.c
index 78fb34758..e0dba5efd 100644
--- a/hicn-light/src/hicn/strategies/rnd.h
+++ b/hicn-plugin/src/infra.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,15 +13,13 @@
* limitations under the License.
*/
+#include "infra.h"
+
/**
- * Forward randomly
+ * @file infra.c
+ *
*/
-#ifndef rnd_h
-#define rnd_h
-
-#include <hicn/strategies/strategyImpl.h>
-
-StrategyImpl* strategyRnd_Create();
-
-#endif // rnd_h
+/* PIT and CS size */
+u32 hicn_infra_pit_size;
+u32 hicn_infra_cs_size;
diff --git a/hicn-plugin/src/infra.h b/hicn-plugin/src/infra.h
index 900ecedde..463617da0 100644
--- a/hicn-plugin/src/infra.h
+++ b/hicn-plugin/src/infra.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -46,7 +46,7 @@ typedef struct hicn_main_s
* Boundaries for the interest lifetime. If greater than
* pit_lifetime_max_ms, pit_lifetime_max_ms is used in the PIT
*/
- u64 pit_lifetime_max_ms;
+ u32 pit_lifetime_max_ms;
vnet_link_t link;
@@ -57,8 +57,8 @@ extern hicn_main_t hicn_main;
extern int hicn_infra_fwdr_initialized;
/* PIT and CS size */
-u32 hicn_infra_pit_size;
-u32 hicn_infra_cs_size;
+extern u32 hicn_infra_pit_size;
+extern u32 hicn_infra_cs_size;
/**
* @brief Enable and disable the hicn plugin
diff --git a/hicn-plugin/src/interest_hitcs.h b/hicn-plugin/src/interest_hitcs.h
index 05a790688..0df987778 100644
--- a/hicn-plugin/src/interest_hitcs.h
+++ b/hicn-plugin/src/interest_hitcs.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/interest_hitcs_node.c b/hicn-plugin/src/interest_hitcs_node.c
index e29b173a9..651b2796a 100644
--- a/hicn-plugin/src/interest_hitcs_node.c
+++ b/hicn-plugin/src/interest_hitcs_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -36,13 +36,14 @@ static char *hicn_interest_hitcs_error_strings[] = {
vlib_node_registration_t hicn_interest_hitcs_node;
-always_inline void drop_packet (u32 *next0);
+// always_inline void drop_packet (u32 *next0);
-always_inline void
-clone_from_cs (vlib_main_t *vm, u32 *bi0_cs, vlib_buffer_t *dest, u8 isv6)
+always_inline u32
+clone_from_cs (vlib_main_t *vm, u32 bi0_cs, vlib_buffer_t *dest, u8 isv6)
{
/* Retrieve the buffer to clone */
- vlib_buffer_t *cs_buf = vlib_get_buffer (vm, *bi0_cs);
+ u32 ret = bi0_cs;
+ vlib_buffer_t *cs_buf = vlib_get_buffer (vm, bi0_cs);
hicn_buffer_t *hicnb = hicn_get_buffer (cs_buf);
word buffer_advance = CLIB_CACHE_LINE_BYTES * 2;
if (hicnb->flags & HICN_BUFFER_FLAGS_PKT_LESS_TWO_CL)
@@ -63,7 +64,7 @@ clone_from_cs (vlib_main_t *vm, u32 *bi0_cs, vlib_buffer_t *dest, u8 isv6)
{
vlib_buffer_t *cs_buf2 = vlib_buffer_copy (vm, cs_buf);
vlib_buffer_advance (cs_buf, buffer_advance);
- *bi0_cs = vlib_get_buffer_index (vm, cs_buf2);
+ ret = vlib_get_buffer_index (vm, cs_buf2);
cs_buf->ref_count--;
cs_buf = cs_buf2;
}
@@ -79,6 +80,8 @@ clone_from_cs (vlib_main_t *vm, u32 *bi0_cs, vlib_buffer_t *dest, u8 isv6)
/* Set fag for packet coming from CS */
hicn_get_buffer (dest)->flags |= HICN_BUFFER_FLAGS_FROM_CS;
+
+ return ret;
}
static uword
@@ -89,8 +92,17 @@ hicn_interest_hitcs_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
hicn_interest_hitcs_next_t next_index;
hicn_interest_hitcs_runtime_t *rt;
vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
+ vlib_buffer_t *b0;
+ u8 isv6;
+ u32 bi0, bi_ret;
+ u32 next0 = HICN_INTEREST_HITCS_NEXT_ERROR_DROP;
+ hicn_buffer_t *hicnb0;
+ u32 pcs_entry_index;
+ hicn_pcs_entry_t *pcs_entry = NULL;
+ const hicn_strategy_vft_t *strategy_vft0;
+ const hicn_dpo_vft_t *dpo_vft0;
+ u8 dpo_ctx_id0;
f64 tnow;
- int ret;
rt = vlib_node_get_runtime_data (vm, hicn_interest_hitcs_node.index);
@@ -110,29 +122,12 @@ hicn_interest_hitcs_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
- vlib_buffer_t *b0;
- u8 isv6;
- u8 *nameptr;
- u16 namelen;
- u32 bi0;
- u32 next0 = HICN_INTEREST_HITCS_NEXT_ERROR_DROP;
- hicn_name_t name;
- hicn_header_t *hicn0;
- hicn_buffer_t *hicnb0;
- hicn_hash_node_t *node0;
- hicn_pcs_entry_t *pitp;
- hicn_hash_entry_t *hash_entry0;
- const hicn_strategy_vft_t *strategy_vft0;
- const hicn_dpo_vft_t *dpo_vft0;
- u8 dpo_ctx_id0;
-
/* Prefetch for next iteration. */
if (n_left_from > 1)
{
vlib_buffer_t *b1;
b1 = vlib_get_buffer (vm, from[1]);
CLIB_PREFETCH (b1, 2 * CLIB_CACHE_LINE_BYTES, STORE);
- CLIB_PREFETCH (b1->data, CLIB_CACHE_LINE_BYTES, STORE);
}
/* Dequeue a packet buffer */
@@ -147,86 +142,64 @@ hicn_interest_hitcs_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
/* Get hicn buffer and state */
hicnb0 = hicn_get_buffer (b0);
- hicn_get_internal_state (hicnb0, rt->pitcs, &node0, &strategy_vft0,
- &dpo_vft0, &dpo_ctx_id0, &hash_entry0);
+ hicn_get_internal_state (hicnb0, &pcs_entry_index, &strategy_vft0,
+ &dpo_vft0, &dpo_ctx_id0);
+ pcs_entry =
+ hicn_pcs_entry_get_entry_from_index (rt->pitcs, pcs_entry_index);
- ret = hicn_interest_parse_pkt (b0, &name, &namelen, &hicn0, &isv6);
- nameptr = (u8 *) (&name);
- pitp = hicn_pit_get_data (node0);
+ isv6 = hicn_buffer_is_v6 (b0);
- dpo_id_t hicn_dpo_id0 = { .dpoi_type =
- dpo_vft0->hicn_dpo_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = dpo_ctx_id0 };
-
- if (PREDICT_FALSE (ret != HICN_ERROR_NONE ||
- !hicn_node_compare (nameptr, namelen, node0)))
- {
- /* Remove lock from the entry */
- hicn_pcs_remove_lock (rt->pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
- drop_packet (&next0);
- goto end_processing;
- }
- if ((tnow > pitp->shared.expire_time))
+ if (tnow > hicn_pcs_entry_get_expire_time (pcs_entry))
{
- /* Delete and clean up expired CS entry */
- hicn_pcs_delete (rt->pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
+ // Delete and clean up expired CS entry
+ hicn_pcs_entry_remove_lock (rt->pitcs, pcs_entry);
+
+ // Update stats
stats.cs_expired_count++;
- /* Forward interest to the strategy node */
+
+ // Forward interest to the strategy node
next0 = HICN_INTEREST_HITCS_NEXT_STRATEGY;
}
else
{
- if (PREDICT_TRUE (
- !(hash_entry0->he_flags & HICN_HASH_ENTRY_FLAG_DELETED)))
- hicn_pcs_cs_update (vm, rt->pitcs, pitp, pitp, node0);
-
- /*
- * Retrieve the incoming iface and forward
- * the data through it
- */
+ // Retrieve the incoming iface and forward
+ // the data through it
next0 = isv6 ? HICN_INTEREST_HITCS_NEXT_IFACE6_OUT :
- HICN_INTEREST_HITCS_NEXT_IFACE4_OUT;
+ HICN_INTEREST_HITCS_NEXT_IFACE4_OUT;
vnet_buffer (b0)->ip.adj_index[VLIB_TX] = hicnb0->face_id;
- clone_from_cs (vm, &pitp->u.cs.cs_pkt_buf, b0, isv6);
+ bi_ret = clone_from_cs (
+ vm, hicn_pcs_entry_cs_get_buffer (pcs_entry), b0, isv6);
+
+ hicn_pcs_entry_cs_set_buffer (pcs_entry, bi_ret);
+ // Update stats
stats.pkts_from_cache_count++;
stats.pkts_data_count++;
- /* Remove lock from the entry */
- hicn_pcs_remove_lock (rt->pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
}
- end_processing:
-
- /* Maybe trace */
+ // Maybe trace
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
(b0->flags & VLIB_BUFFER_IS_TRACED)))
{
hicn_interest_hitcs_trace_t *t =
vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_INTEREST;
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST;
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
t->next_index = next0;
}
- /* Incr packet counter */
+
+ // Increment packet counter
stats.pkts_processed += 1;
- /*
- * Verify speculative enqueue, maybe switch current
- * next frame
- */
+ // Verify speculative enqueue, maybe switch current next frame
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
- u32 pit_int_count = hicn_pit_get_int_count (rt->pitcs);
+ u32 pit_int_count = hicn_pcs_get_pit_count (rt->pitcs);
vlib_node_increment_counter (vm, hicn_interest_hitcs_node.index,
HICNFWD_ERROR_CACHED,
@@ -241,11 +214,13 @@ hicn_interest_hitcs_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
return (frame->n_vectors);
}
+#if 0
always_inline void
drop_packet (u32 *next0)
{
*next0 = HICN_INTEREST_HITCS_NEXT_ERROR_DROP;
}
+#endif
/* packet trace format function */
static u8 *
@@ -285,4 +260,4 @@ VLIB_REGISTER_NODE (hicn_interest_hitcs_node) = {
* fd.io coding-style-patch-verification: ON
*
* Local Variables: eval: (c-set-style "gnu") End:
- */
+ */ \ No newline at end of file
diff --git a/hicn-plugin/src/interest_hitpit.h b/hicn-plugin/src/interest_hitpit.h
index 44cf2c879..46659e67c 100644
--- a/hicn-plugin/src/interest_hitpit.h
+++ b/hicn-plugin/src/interest_hitpit.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -46,7 +46,7 @@ typedef struct
{
u32 next_index;
u32 sw_if_index;
- u8 pkt_type;
+ u32 pkt_type;
} hicn_interest_hitpit_trace_t;
typedef enum
@@ -65,4 +65,4 @@ typedef enum
* fd.io coding-style-patch-verification: ON
*
* Local Variables: eval: (c-set-style "gnu") End:
- */
+ */ \ No newline at end of file
diff --git a/hicn-plugin/src/interest_hitpit_node.c b/hicn-plugin/src/interest_hitpit_node.c
index 837eddca7..7f1b0f449 100644
--- a/hicn-plugin/src/interest_hitpit_node.c
+++ b/hicn-plugin/src/interest_hitpit_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,7 +25,6 @@
#include "strategy_dpo_manager.h"
#include "state.h"
#include "error.h"
-#include "face_db.h"
/* packet trace format function */
static u8 *hicn_interest_hitpit_format_trace (u8 *s, va_list *args);
@@ -39,8 +38,6 @@ static char *hicn_interest_hitpit_error_strings[] = {
vlib_node_registration_t hicn_interest_hitpit_node;
-always_inline void drop_packet (u32 *next0);
-
/*
* hICN forwarder node for interests hitting the PIT
*/
@@ -52,7 +49,17 @@ hicn_interest_hitpit_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
hicn_interest_hitpit_next_t next_index;
hicn_interest_hitpit_runtime_t *rt;
vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
- f64 tnow;
+ u32 n_left_to_next;
+ vlib_buffer_t *b0;
+ u32 bi0;
+ u32 next0 = HICN_INTEREST_HITPIT_NEXT_ERROR_DROP;
+ const hicn_strategy_vft_t *strategy_vft0;
+ const hicn_dpo_vft_t *dpo_vft0;
+ u8 dpo_ctx_id0;
+ u8 forward = 0;
+ u32 pit_entry_index;
+ hicn_pcs_entry_t *pcs_entry = NULL;
+ hicn_buffer_t *hicnb0;
rt = vlib_node_get_runtime_data (vm, hicn_interest_hitpit_node.index);
@@ -64,42 +71,17 @@ hicn_interest_hitpit_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
- /* Capture time in vpp terms */
- tnow = vlib_time_now (vm);
-
while (n_left_from > 0)
{
- u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
- vlib_buffer_t *b0;
- u8 isv6;
- u8 *nameptr;
- u16 namelen;
- u32 bi0;
- u32 next0 = HICN_INTEREST_HITPIT_NEXT_ERROR_DROP;
- hicn_name_t name;
- hicn_header_t *hicn0;
- hicn_hash_node_t *node0;
- const hicn_strategy_vft_t *strategy_vft0;
- const hicn_dpo_vft_t *dpo_vft0;
- hicn_pcs_entry_t *pitp;
- u8 dpo_ctx_id0;
- u8 found = 0;
- int nh_idx;
- hicn_face_id_t outface;
- hicn_hash_entry_t *hash_entry0;
- hicn_buffer_t *hicnb0;
- int ret;
-
/* Prefetch for next iteration. */
if (n_left_from > 1)
{
vlib_buffer_t *b1;
b1 = vlib_get_buffer (vm, from[1]);
CLIB_PREFETCH (b1, CLIB_CACHE_LINE_BYTES, LOAD);
- CLIB_PREFETCH (b1->data, CLIB_CACHE_LINE_BYTES, STORE);
}
/* Dequeue a packet buffer */
@@ -114,96 +96,54 @@ hicn_interest_hitpit_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
/* Get hicn buffer and state */
hicnb0 = hicn_get_buffer (b0);
- hicn_get_internal_state (hicnb0, rt->pitcs, &node0, &strategy_vft0,
- &dpo_vft0, &dpo_ctx_id0, &hash_entry0);
+ hicn_get_internal_state (hicnb0, &pit_entry_index, &strategy_vft0,
+ &dpo_vft0, &dpo_ctx_id0);
- ret = hicn_interest_parse_pkt (b0, &name, &namelen, &hicn0, &isv6);
- nameptr = (u8 *) (&name);
- pitp = hicn_pit_get_data (node0);
- dpo_id_t hicn_dpo_id0 = { .dpoi_type =
- dpo_vft0->hicn_dpo_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = dpo_ctx_id0 };
+ // Retrieve PIT entry
+ pcs_entry =
+ hicn_pcs_entry_get_entry_from_index (rt->pitcs, pit_entry_index);
- /*
- * Check if the hit is instead a collision in the
- * hash table. Unlikely to happen.
- */
- if (PREDICT_FALSE (ret != HICN_ERROR_NONE ||
- !hicn_node_compare (nameptr, namelen, node0)))
- {
- stats.interests_hash_collision++;
- /* Remove lock from the entry */
- hicn_pcs_remove_lock (rt->pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
- drop_packet (&next0);
+ // Increment packet counter
+ stats.pkts_processed += 1;
- goto end_processing;
- }
- /*
- * If the entry is expired, remove it no matter of
- * the possible cases.
- */
- if (tnow > pitp->shared.expire_time)
+ // A data packet may have arrived in the time between the pcs
+ // lookup and now. Check again to make sure the entry is CS or
+ // PIT
+ if (hicn_pcs_entry_is_cs (pcs_entry))
{
- strategy_vft0->hicn_on_interest_timeout (dpo_ctx_id0);
- hicn_pcs_delete (rt->pitcs, &pitp, &node0, vm, hash_entry0,
- dpo_vft0, &hicn_dpo_id0);
- stats.pit_expired_count++;
- next0 = HICN_INTEREST_HITPIT_NEXT_STRATEGY;
+ next0 = HICN_INTEREST_HITPIT_NEXT_INTEREST_HITCS;
}
else
{
- if ((hash_entry0->he_flags & HICN_HASH_ENTRY_FLAG_CS_ENTRY))
+ // Distinguish between aggregation, retransmission and
+ // additionally check if the strategy mandates to always send
+ // the interest
+
+ // Retransmission
+ forward = hicn_pcs_entry_pit_search (pcs_entry, hicnb0->face_id);
+
+ // Strategy mandates to force send after aggregation
+ if (!forward && strategy_vft0->hicn_send_after_aggregation (
+ dpo_ctx_id0, hicnb0->face_id))
{
- next0 = HICN_INTEREST_HITPIT_NEXT_INTEREST_HITCS;
+ forward = true;
+ hicn_pcs_entry_pit_add_face (pcs_entry, hicnb0->face_id);
+ }
+
+ if (forward && hicnb0->payload_type != HPT_MANIFEST)
+ {
+ next0 = HICN_INTEREST_HITPIT_NEXT_STRATEGY;
}
else
{
- /*
- * Distinguish between aggregation or
- * retransmission
- */
-
- found =
- hicn_face_search (hicnb0->face_id, &(pitp->u.pit.faces));
+ // Aggregation
+ hicn_pcs_entry_pit_add_face (pcs_entry, hicnb0->face_id);
- if (found)
- {
- strategy_vft0->hicn_select_next_hop (dpo_ctx_id0,
- &nh_idx, &outface);
- /* Retransmission */
- /*
- * Prepare the packet for the
- * forwarding
- */
- next0 = isv6 ? HICN_INTEREST_HITPIT_NEXT_FACE6_OUTPUT :
- HICN_INTEREST_HITPIT_NEXT_FACE4_OUTPUT;
- vnet_buffer (b0)->ip.adj_index[VLIB_TX] = outface;
+ next0 = HICN_INTEREST_HITPIT_NEXT_ERROR_DROP;
- /*
- * Update the egress face in
- * the PIT
- */
- pitp->u.pit.pe_txnh = nh_idx;
- stats.interests_retx++;
- }
- else
- {
- hicn_face_db_add_face (hicnb0->face_id,
- &pitp->u.pit.faces);
-
- /* Aggregation */
- drop_packet (&next0);
- stats.interests_aggregated++;
- }
- /* Remove lock from the entry */
- hicn_pcs_remove_lock (rt->pitcs, &pitp, &node0, vm,
- hash_entry0, dpo_vft0, &hicn_dpo_id0);
+ stats.interests_aggregated++;
}
}
- end_processing:
/* Maybe trace */
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
@@ -211,12 +151,10 @@ hicn_interest_hitpit_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
{
hicn_interest_hitpit_trace_t *t =
vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_INTEREST;
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST;
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
t->next_index = next0;
}
- /* Incr packet counter */
- stats.pkts_processed += 1;
/*
* Verify speculative enqueue, maybe switch current
@@ -227,7 +165,7 @@ hicn_interest_hitpit_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
- u32 pit_int_count = hicn_pit_get_int_count (rt->pitcs);
+ u32 pit_int_count = hicn_pcs_get_pit_count (rt->pitcs);
vlib_node_increment_counter (vm, hicn_interest_hitpit_node.index,
HICNFWD_ERROR_PROCESSED, stats.pkts_processed);
@@ -264,12 +202,6 @@ hicn_interest_hitpit_format_trace (u8 *s, va_list *args)
return (s);
}
-void
-drop_packet (u32 *next0)
-{
- *next0 = HICN_INTEREST_HITPIT_NEXT_ERROR_DROP;
-}
-
/*
* Node registration for the interest forwarder node
*/
diff --git a/hicn-plugin/src/interest_pcslookup.h b/hicn-plugin/src/interest_pcslookup.h
index 87d093e91..ba0e7651d 100644
--- a/hicn-plugin/src/interest_pcslookup.h
+++ b/hicn-plugin/src/interest_pcslookup.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -58,6 +58,16 @@ typedef enum
HICN_INTEREST_PCSLOOKUP_N_NEXT,
} hicn_interest_pcslookup_next_t;
+typedef enum
+{
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_FACE4,
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_FACE6,
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_INTEREST_HITPIT,
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_INTEREST_HITCS,
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_ERROR_DROP,
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_N_NEXT,
+} hicn_interest_manifest_pcslookup_next_t;
+
#endif /* // __HICN_INTEREST_PCSLOOKUP_H__ */
/*
diff --git a/hicn-plugin/src/interest_pcslookup_node.c b/hicn-plugin/src/interest_pcslookup_node.c
index d3f6c7bca..e8aad4a83 100644
--- a/hicn-plugin/src/interest_pcslookup_node.c
+++ b/hicn-plugin/src/interest_pcslookup_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,6 +23,8 @@
#include "error.h"
#include "state.h"
+#include <hicn/interest_manifest.h>
+
/**
* @FILE This node performs a lookup in the PIT and CS for a received interest
* packet.
@@ -45,19 +47,40 @@ static char *hicn_interest_pcslookup_error_strings[] = {
vlib_node_registration_t hicn_interest_pcslookup_node;
+always_inline void
+drop_packet (vlib_main_t *vm, u32 bi0, u32 *n_left_to_next, u32 *next0,
+ u32 **to_next, u32 *next_index, vlib_node_runtime_t *node)
+{
+ *next0 = HICN_INTEREST_PCSLOOKUP_NEXT_ERROR_DROP;
+
+ (*to_next)[0] = bi0;
+ *to_next += 1;
+ *n_left_to_next -= 1;
+
+ vlib_validate_buffer_enqueue_x1 (vm, node, *next_index, *to_next,
+ *n_left_to_next, bi0, *next0);
+}
+
/*
- * ICN forwarder node for interests: handling of Interests delivered based on
- * ACL. - 1 packet at a time - ipv4/tcp ipv6/tcp
+ * ICN forwarder node for interests.
*/
static uword
-hicn_interest_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
- vlib_frame_t *frame)
+hicn_interest_pcslookup_node_inline (vlib_main_t *vm,
+ vlib_node_runtime_t *node,
+ vlib_frame_t *frame)
{
+ int ret;
u32 n_left_from, *from, *to_next;
hicn_interest_pcslookup_next_t next_index;
hicn_interest_pcslookup_runtime_t *rt;
vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
- int ret;
+ vlib_buffer_t *b0;
+ u32 bi0;
+ u32 next0 = HICN_INTEREST_PCSLOOKUP_NEXT_ERROR_DROP;
+ hicn_pcs_entry_t *pcs_entry = NULL;
+ f64 tnow;
+ hicn_buffer_t *hicnb0;
+ const hicn_strategy_vft_t *strategy;
rt = vlib_node_get_runtime_data (vm, hicn_interest_pcslookup_node.index);
@@ -69,38 +92,23 @@ hicn_interest_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
+ tnow = vlib_time_now (vm);
+
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
- vlib_buffer_t *b0;
- u8 isv6;
- u8 *nameptr;
- u16 namelen;
- u32 bi0;
- u32 next0 = HICN_INTEREST_PCSLOOKUP_NEXT_ERROR_DROP;
- u64 name_hash = 0;
- hicn_name_t name;
- hicn_header_t *hicn0;
- u32 node_id0 = 0;
- index_t dpo_ctx_id0 = 0;
- u8 vft_id0 = 0;
- u8 is_cs0 = 0;
- u8 hash_entry_id = 0;
- u8 bucket_is_overflown = 0;
- u32 bucket_id = ~0;
-
/* Prefetch for next iteration. */
if (n_left_from > 1)
{
vlib_buffer_t *b1;
b1 = vlib_get_buffer (vm, from[1]);
CLIB_PREFETCH (b1, CLIB_CACHE_LINE_BYTES, STORE);
- CLIB_PREFETCH (b1->data, CLIB_CACHE_LINE_BYTES, LOAD);
}
- /* Dequeue a packet buffer */
+
+ // Dequeue a packet buffer
bi0 = from[0];
from += 1;
n_left_from -= 1;
@@ -109,47 +117,104 @@ hicn_interest_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
- ret = hicn_interest_parse_pkt (b0, &name, &namelen, &hicn0, &isv6);
- if (PREDICT_TRUE (ret == HICN_ERROR_NONE))
+ // By default we send the interest to strategy node
+ next0 = HICN_INTEREST_PCSLOOKUP_NEXT_STRATEGY;
+
+ // Update stats
+ stats.pkts_processed++;
+
+ hicnb0 = hicn_get_buffer (b0);
+
+ // Check if the interest is in the PCS already
+ hicn_name_t name;
+ hicn_packet_get_name (&hicnb0->pkbuf, &name);
+ ret = hicn_pcs_lookup_one (rt->pitcs, &name, &pcs_entry);
+
+ if (ret == HICN_ERROR_NONE)
{
- next0 = HICN_INTEREST_PCSLOOKUP_NEXT_STRATEGY;
+ // We found an entry in the PCS.
+ ret = hicn_store_internal_state (
+ b0, hicn_pcs_entry_get_index (rt->pitcs, pcs_entry),
+ vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
+
+ // Make sure the entry is not expired first
+ if (tnow > hicn_pcs_entry_get_expire_time (pcs_entry))
+ {
+ // Notify strategy
+ strategy = hicn_dpo_get_strategy_vft (hicnb0->vft_id);
+ strategy->hicn_on_interest_timeout (
+ vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
+
+ // Release lock on entry - this MUST delete the entry
+ hicn_pcs_entry_remove_lock (rt->pitcs, pcs_entry);
+
+ stats.pit_expired_count++;
+
+ // Forward to strategy node
+ // TODO this can be simplified by checking directly in the
+ // pcslookup node!
+ next0 = HICN_INTEREST_PCSLOOKUP_NEXT_STRATEGY;
+
+ goto newentry;
+ }
+ else
+ {
+ // Next stage for this packet is one of hitpit/cs nodes
+ next0 = HICN_INTEREST_PCSLOOKUP_NEXT_INTEREST_HITPIT +
+ hicn_pcs_entry_is_cs (pcs_entry);
+
+ if (PREDICT_FALSE (ret != HICN_ERROR_NONE))
+ next0 = HICN_INTEREST_PCSLOOKUP_NEXT_ERROR_DROP;
+
+ goto end;
+ }
}
- nameptr = (u8 *) (&name);
- stats.pkts_processed++;
+ newentry:
+ // No entry in PCS. Let's create one now
+ pcs_entry = hicn_pcs_entry_pit_get (rt->pitcs, tnow,
+ hicn_buffer_get_lifetime (b0));
+
+ ret = hicn_pcs_pit_insert (rt->pitcs, pcs_entry, &name);
- if (PREDICT_FALSE (
- ret != HICN_ERROR_NONE ||
- hicn_hashtb_fullhash (nameptr, namelen, &name_hash) !=
- HICN_ERROR_NONE))
+ if (PREDICT_FALSE (ret != HICN_ERROR_NONE))
{
next0 = HICN_INTEREST_PCSLOOKUP_NEXT_ERROR_DROP;
+ goto end;
}
- else
+
+ // Store internal state
+ ret = hicn_store_internal_state (
+ b0, hicn_pcs_entry_get_index (rt->pitcs, pcs_entry),
+ vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
+
+ if (PREDICT_FALSE (ret != HICN_ERROR_NONE))
{
- if (hicn_hashtb_lookup_node (
- rt->pitcs->pcs_table, nameptr, namelen, name_hash,
- 0 /* is_data */, &node_id0, &dpo_ctx_id0, &vft_id0,
- &is_cs0, &hash_entry_id, &bucket_id,
- &bucket_is_overflown) == HICN_ERROR_NONE)
- {
- next0 =
- HICN_INTEREST_PCSLOOKUP_NEXT_INTEREST_HITPIT + is_cs0;
- }
- stats.pkts_interest_count++;
+ hicn_pcs_entry_remove_lock (rt->pitcs, pcs_entry);
+ drop_packet (vm, bi0, &n_left_from, &next0, &to_next,
+ &next_index, node);
+ continue;
}
- hicn_store_internal_state (b0, name_hash, node_id0, dpo_ctx_id0,
- vft_id0, hash_entry_id, bucket_id,
- bucket_is_overflown);
+ // Add face
+ hicn_pcs_entry_pit_add_face (pcs_entry, hicnb0->face_id);
+
+ end:
+ stats.pkts_interest_count++;
+
+ // Interest manifest?
+ if (hicn_buffer_get_payload_type (b0) == HPT_MANIFEST)
+ {
+ ;
+ }
- /* Maybe trace */
+ // Maybe trace
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
(b0->flags & VLIB_BUFFER_IS_TRACED)))
{
hicn_interest_pcslookup_trace_t *t =
vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_INTEREST;
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST;
t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
t->next_index = next0;
}
@@ -162,9 +227,8 @@ hicn_interest_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
- u32 pit_int_count = hicn_pit_get_int_count (rt->pitcs);
- u32 pit_cs_count = hicn_pit_get_cs_count (rt->pitcs);
- u32 pcs_ntw_count = hicn_pcs_get_ntw_count (rt->pitcs);
+ u32 pit_int_count = hicn_pcs_get_pit_count (rt->pitcs);
+ u32 pit_cs_count = hicn_pcs_get_cs_count (rt->pitcs);
vlib_node_increment_counter (vm, hicn_interest_pcslookup_node.index,
HICNFWD_ERROR_PROCESSED, stats.pkts_processed);
@@ -179,8 +243,319 @@ hicn_interest_pcslookup_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
update_node_counter (vm, hicn_interest_pcslookup_node.index,
HICNFWD_ERROR_CS_COUNT, pit_cs_count);
+ return (frame->n_vectors);
+}
+
+/*
+ * ICN forwarder node for interests manifest
+ */
+static uword
+hicn_interest_manifest_pcslookup_node_inline (vlib_main_t *vm,
+ vlib_node_runtime_t *node,
+ vlib_frame_t *frame)
+{
+ int ret;
+ u32 n_left_from, *from, *to_next;
+ hicn_interest_pcslookup_next_t next_index;
+ hicn_interest_pcslookup_runtime_t *rt;
+ vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
+ vlib_buffer_t *b0;
+ hicn_buffer_t *hicnb0;
+ u32 bi0;
+
+ const hicn_dpo_ctx_t *dpo_ctx;
+ const hicn_strategy_vft_t *strategy;
+
+ u16 outfaces_len;
+
+ // For cloning
+ u32 clones[MAX_OUT_FACES];
+ hicn_face_id_t outfaces[MAX_OUT_FACES];
+ u32 next0 = HICN_INTEREST_PCSLOOKUP_NEXT_ERROR_DROP;
+ hicn_pcs_entry_t *pcs_entry = NULL;
+ interest_manifest_header_t *int_manifest_header = NULL;
+ unsigned long pos = 0;
+
+ rt = vlib_node_get_runtime_data (vm, hicn_interest_pcslookup_node.index);
+
+ if (PREDICT_FALSE (rt->pitcs == NULL))
+ {
+ rt->pitcs = &hicn_main.pitcs;
+ }
+ from = vlib_frame_vector_args (frame);
+ n_left_from = frame->n_vectors;
+ next_index = node->cached_next_index;
+ int forward = 0;
+
+ vlib_buffer_t *cloneb;
+
+ // Register now
+ f64 tnow = vlib_time_now (vm);
+
+ while (n_left_from > 0)
+ {
+ u32 n_left_to_next;
+ vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+ while (n_left_from > 0 && n_left_to_next > 0)
+ {
+ /* Prefetch for next iteration. */
+ if (n_left_from > 1)
+ {
+ vlib_buffer_t *b1;
+ b1 = vlib_get_buffer (vm, from[1]);
+ CLIB_PREFETCH (b1, CLIB_CACHE_LINE_BYTES, STORE);
+ }
+
+ // Dequeue a packet buffer
+ bi0 = from[0];
+ from += 1;
+ n_left_from -= 1;
+
+ b0 = vlib_get_buffer (vm, bi0);
+ hicnb0 = hicn_get_buffer (b0);
+
+ // By default we send the interest to drop node
+ next0 = HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_ERROR_DROP;
+
+ // Update stats
+ stats.pkts_processed++;
+
+ // Do not forward by default
+ forward = 0;
+
+ // Check if the interest is in the PCS already
+ hicn_name_t name;
+ hicn_packet_get_name (&hicn_get_buffer (b0)->pkbuf, &name);
+
+ ASSERT (hicn_buffer_get_payload_type (b0) == HPT_MANIFEST);
+
+ // Process interest manifest
+ u8 *payload;
+ size_t payload_size;
+ hicn_interest_get_payload (&hicn_get_buffer (b0)->pkbuf, &payload,
+ &payload_size, 0);
+ int_manifest_header = (interest_manifest_header_t *) (payload);
+
+ // Deserialize interest manifest
+ interest_manifest_deserialize (int_manifest_header);
+
+ hicn_name_suffix_t *suffix;
+ if (interest_manifest_is_valid (int_manifest_header, payload_size))
+ {
+ interest_manifest_foreach_suffix (int_manifest_header, suffix,
+ pos)
+ {
+ name.suffix = *suffix;
+ ret = hicn_pcs_lookup_one (rt->pitcs, &name, &pcs_entry);
+
+ if (ret == HICN_ERROR_NONE)
+ {
+ // Match in PCS. We need to clone a packet for the
+ // interest_hic{pit,cs} nodes.
+
+ next0 = HICN_INTEREST_PCSLOOKUP_NEXT_INTEREST_HITPIT +
+ hicn_pcs_entry_is_cs (pcs_entry);
+
+ vlib_buffer_clone (vm, bi0, clones, 1, 0);
+ cloneb = vlib_get_buffer (vm, clones[0]);
+
+ ret = hicn_store_internal_state (
+ cloneb,
+ hicn_pcs_entry_get_index (rt->pitcs, pcs_entry),
+ vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
+
+ if (PREDICT_FALSE (ret != HICN_ERROR_NONE))
+ next0 = HICN_INTEREST_PCSLOOKUP_NEXT_ERROR_DROP;
+
+ to_next[0] = clones[0];
+ to_next += 1;
+ n_left_to_next -= 1;
+
+ // Distinguish between aggregation or retransmission
+ ret = hicn_pcs_entry_pit_search (
+ pcs_entry, hicn_get_buffer (b0)->face_id);
+ if (!ret)
+ {
+ // Aggregated interest. Unset the corresponding
+ // position in bitmap.
+ bitmap_unset_no_check (
+ int_manifest_header->request_bitmap, pos);
+ }
+ else
+ {
+ // Interest must be forwarded fo face node as it
+ // contains retransmissions
+ forward = 1;
+ }
+
+ // Maybe trace
+ if (PREDICT_FALSE (
+ (node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ hicn_interest_pcslookup_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST;
+ t->sw_if_index =
+ vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ t->next_index = next0;
+ }
+ /*
+ * Verify speculative enqueue, maybe switch current
+ * next frame
+ */
+ vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
+ to_next, n_left_to_next,
+ clones[0], next0);
+ }
+ else
+ {
+ // No match. Create new pcs entry and set interest to be
+ // forwarded
+ pcs_entry = hicn_pcs_entry_pit_get (
+ rt->pitcs, tnow, hicn_buffer_get_lifetime (b0));
+
+ // Add entry to PCS table
+ ret = hicn_pcs_pit_insert (rt->pitcs, pcs_entry, &name);
+
+ // This cannot fail as we just checked if PCS contains
+ // this entry
+ assert (ret == HICN_ERROR_NONE);
+
+ // Store internal state
+ ret = hicn_store_internal_state (
+ b0, hicn_pcs_entry_get_index (rt->pitcs, pcs_entry),
+ vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
+
+ if (PREDICT_FALSE (ret != HICN_ERROR_NONE))
+ {
+ // Remove entry
+ hicn_pcs_entry_remove_lock (rt->pitcs, pcs_entry);
+ // We do not drop the packet as it is an interest
+ // manifest.
+ continue;
+ }
+
+ // Add face
+ hicn_pcs_entry_pit_add_face (
+ pcs_entry, hicn_get_buffer (b0)->face_id);
+
+ forward = 1;
+ }
+ }
+ }
+ else
+ {
+ next0 = HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_ERROR_DROP;
+ }
+
+ // If interest must be forwarded, let's do it now
+ if (forward)
+ {
+ // Serialize interest manifest again
+ interest_manifest_serialize (int_manifest_header);
+
+ // Get the strategy VFT
+ hicnb0->dpo_ctx_id = vnet_buffer (b0)->ip.adj_index[VLIB_TX];
+ dpo_ctx = hicn_strategy_dpo_ctx_get (hicnb0->dpo_ctx_id);
+ hicnb0->vft_id = dpo_ctx->dpo_type;
+ strategy = hicn_dpo_get_strategy_vft (hicnb0->vft_id);
+ strategy->hicn_add_interest (hicnb0->dpo_ctx_id);
+
+ // Check we have at least one next hop for the packet
+ ret = strategy->hicn_select_next_hop (
+ hicnb0->dpo_ctx_id, hicnb0->face_id, outfaces, &outfaces_len);
+ if (ret == HICN_ERROR_NONE && outfaces_len > 0)
+ {
+ next0 = hicn_buffer_is_v6 (b0) ?
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_FACE6 :
+ HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_FACE4;
+
+ // Clone interest if needed
+ if (outfaces_len > 1)
+ {
+ ret =
+ vlib_buffer_clone (vm, bi0, clones, (u16) outfaces_len,
+ CLIB_CACHE_LINE_BYTES * 2);
+ ASSERT (ret == outfaces_len);
+ }
+ else
+ {
+ clones[0] = bi0;
+ }
+
+ // Send interest to next hops
+ for (u32 nh = 0; nh < outfaces_len; nh++)
+ {
+ vlib_buffer_t *local_b0 =
+ vlib_get_buffer (vm, clones[nh]);
+
+ to_next[0] = clones[nh];
+ to_next += 1;
+ n_left_to_next -= 1;
+
+ vnet_buffer (local_b0)->ip.adj_index[VLIB_TX] =
+ outfaces[nh];
+ stats.pkts_interest_count++;
+
+ // Maybe trace
+ if (PREDICT_FALSE (
+ (node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (local_b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ hicn_strategy_trace_t *t =
+ vlib_add_trace (vm, node, local_b0, sizeof (*t));
+ t->pkt_type = HICN_PACKET_TYPE_DATA;
+ t->sw_if_index =
+ vnet_buffer (local_b0)->sw_if_index[VLIB_RX];
+ t->next_index = next0;
+ t->dpo_type = hicnb0->vft_id;
+ }
+
+ /*
+ * Fix in case of a wrong speculation. Needed for
+ * cloning the data in the right frame
+ */
+ vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
+ to_next, n_left_to_next,
+ clones[nh], next0);
+ }
+ }
+ else
+ {
+ next0 = HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_ERROR_DROP;
+
+ to_next[0] = bi0;
+ to_next += 1;
+ n_left_to_next -= 1;
+
+ /*
+ * Fix in case of a wrong speculation. Needed for
+ * cloning the data in the right frame
+ */
+ vlib_validate_buffer_enqueue_x1 (
+ vm, node, next_index, to_next, n_left_to_next, bi0, next0);
+ }
+ }
+ }
+ vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+ }
+
+ u32 pit_int_count = hicn_pcs_get_pit_count (rt->pitcs);
+ u32 pit_cs_count = hicn_pcs_get_cs_count (rt->pitcs);
+
+ vlib_node_increment_counter (vm, hicn_interest_pcslookup_node.index,
+ HICNFWD_ERROR_PROCESSED, stats.pkts_processed);
+
+ vlib_node_increment_counter (vm, hicn_interest_pcslookup_node.index,
+ HICNFWD_ERROR_INTERESTS,
+ stats.pkts_interest_count);
+
+ update_node_counter (vm, hicn_interest_pcslookup_node.index,
+ HICNFWD_ERROR_INT_COUNT, pit_int_count);
+
update_node_counter (vm, hicn_interest_pcslookup_node.index,
- HICNFWD_ERROR_CS_NTW_COUNT, pcs_ntw_count);
+ HICNFWD_ERROR_CS_COUNT, pit_cs_count);
return (frame->n_vectors);
}
@@ -191,7 +566,7 @@ hicn_interest_pcslookup_format_trace (u8 *s, va_list *args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
- hicn_interest_pcslookup_trace_t *t =
+ const hicn_interest_pcslookup_trace_t *t =
va_arg (*args, hicn_interest_pcslookup_trace_t *);
s = format (s, "INTEREST_PCSLOOKUP: pkt: %d, sw_if_index %d, next index %d",
@@ -199,12 +574,23 @@ hicn_interest_pcslookup_format_trace (u8 *s, va_list *args)
return (s);
}
+VLIB_NODE_FN (hicn_interest_pcslookup_node)
+(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
+{
+ return hicn_interest_pcslookup_node_inline (vm, node, frame);
+}
+
+VLIB_NODE_FN (hicn_interest_manifest_pcslookup_node)
+(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
+{
+ return hicn_interest_manifest_pcslookup_node_inline (vm, node, frame);
+}
+
/*
* Node registration for the interest forwarder node
*/
VLIB_REGISTER_NODE(hicn_interest_pcslookup_node) =
{
- .function = hicn_interest_pcslookup_node_fn,
.name = "hicn-interest-pcslookup",
.vector_size = sizeof(u32),
.runtime_data_bytes = sizeof(hicn_interest_pcslookup_runtime_t),
@@ -223,6 +609,29 @@ VLIB_REGISTER_NODE(hicn_interest_pcslookup_node) =
};
/*
+ * Node registration for the interest manifest forwarder node
+ */
+VLIB_REGISTER_NODE(hicn_interest_manifest_pcslookup_node) =
+{
+ .name = "hicn-interest-manifest-pcslookup",
+ .vector_size = sizeof(u32),
+ .runtime_data_bytes = sizeof(hicn_interest_pcslookup_runtime_t),
+ .format_trace = hicn_interest_pcslookup_format_trace,
+ .type = VLIB_NODE_TYPE_INTERNAL,
+ .n_errors = ARRAY_LEN(hicn_interest_pcslookup_error_strings),
+ .error_strings = hicn_interest_pcslookup_error_strings,
+ .n_next_nodes = HICN_INTEREST_MANIFEST_PCSLOOKUP_N_NEXT,
+ .next_nodes =
+ {
+ [HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_FACE4] = "hicn4-face-output",
+ [HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_FACE6] = "hicn6-face-output",
+ [HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_INTEREST_HITPIT] = "hicn-interest-hitpit",
+ [HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_INTEREST_HITCS] = "hicn-interest-hitcs",
+ [HICN_INTEREST_MANIFEST_PCSLOOKUP_NEXT_ERROR_DROP] = "error-drop",
+ },
+};
+
+/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables: eval: (c-set-style "gnu") End:
diff --git a/hicn-plugin/src/mapme.h b/hicn-plugin/src/mapme.h
index 63bd42610..c5567d1d4 100644
--- a/hicn-plugin/src/mapme.h
+++ b/hicn-plugin/src/mapme.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,9 +21,9 @@
#include <hicn/mapme.h>
#include "hicn.h"
-#include "route.h"
#include "strategy_dpo_ctx.h"
#include "strategy_dpo_manager.h" // dpo_is_hicn
+#include "udp_tunnels/udp_tunnel.h"
/**
* @file
@@ -61,11 +61,13 @@ typedef struct hicn_mapme_conf_s
{
hicn_mapme_conf_t conf;
bool remove_dpo; // FIXME used ?
+ fib_prefix_t default_route;
vlib_main_t *vm;
- vlib_log_class_t log_class;
} hicn_mapme_main_t;
+extern hicn_mapme_main_t *hicn_mapme_get_main ();
+
/**
* @brief List of event to signat to the procesing node (eventmgr)
*/
@@ -88,6 +90,21 @@ typedef enum
typedef hicn_dpo_ctx_t hicn_mapme_tfib_t;
+/**
+ * FIB Lookup Type
+ */
+#define foreach_hicn_mapme_fib_lookup_type \
+ _ (EPM) \
+ _ (LPM) \
+ _ (LESSPM)
+
+typedef enum
+{
+#define _(a) HICN_MAPME_FIB_LOOKUP_TYPE_##a,
+ foreach_hicn_mapme_fib_lookup_type
+#undef _
+} hicn_mapme_fib_lookup_type_t;
+
/*
* Ideally we might need to care about alignment, but this struct is only
* used for casting hicn_dpo_ctx_t.
@@ -100,65 +117,43 @@ STATIC_ASSERT (sizeof (hicn_mapme_tfib_t) <= sizeof (hicn_dpo_ctx_t),
#define TFIB(dpo_ctx) ((hicn_mapme_tfib_t *) (dpo_ctx))
-static_always_inline int
-hicn_mapme_nh_set (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
-{
- hicn_dpo_ctx_t *strategy_ctx = (hicn_dpo_ctx_t *) tfib;
- const fib_prefix_t *prefix =
- fib_entry_get_prefix (strategy_ctx->fib_entry_index);
-
- u32 n_entries = tfib->entry_count;
- /* Remove all the existing next hops and set the new one */
- for (int i = 0; i < n_entries; i++)
- {
- hicn_face_t *face = hicn_dpoi_get_from_idx (strategy_ctx->next_hops[0]);
- ip_adjacency_t *adj = adj_get (face->dpo.dpoi_index);
- ip_nh_del_helper (face->dpo.dpoi_proto, prefix,
- &adj->sub_type.nbr.next_hop, face->sw_if);
- }
- hicn_face_t *face = hicn_dpoi_get_from_idx (face_id);
- ip_nh_add_helper (face->dpo.dpoi_proto, prefix, &face->nat_addr,
- face->sw_if);
- return 0;
-}
-
/**
- * @brief Add a next hop iif it is not already a next hops
+ * @brief Check whether a face is already included in the TFIB.
+ *
+ * NOTE: linear scan on a contiguous small array should be the most efficient.
*/
static_always_inline int
-hicn_mapme_nh_add (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
+hicn_mapme_tfib_has (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
{
- for (u8 pos = 0; pos < tfib->entry_count; pos++)
- if (tfib->next_hops[pos] == face_id)
- return 0;
-
- /* Add the next hop in the vrf 0 which will add it to the entry in the hICN
- * vrf */
- hicn_dpo_ctx_t *strategy_ctx = (hicn_dpo_ctx_t *) tfib;
- const fib_prefix_t *prefix =
- fib_entry_get_prefix (strategy_ctx->fib_entry_index);
- hicn_face_t *face = hicn_dpoi_get_from_idx (face_id);
- ip_nh_add_helper (face->dpo.dpoi_proto, prefix, &face->nat_addr,
- face->sw_if);
-
+ u8 pos = HICN_PARAM_FIB_ENTRY_NHOPS_MAX - tfib->tfib_entry_count;
+ for (u8 pos2 = pos; pos2 < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; pos2++)
+ if (tfib->next_hops[pos2] == face_id)
+ return 1;
return 0;
}
/**
* Add a 'previous' hop to the TFIB
- *
- * XXX we should have the for look in the reverse order for simpler code.
*/
static_always_inline int
hicn_mapme_tfib_add (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
{
- u8 pos = HICN_PARAM_FIB_ENTRY_NHOPS_MAX - tfib->tfib_entry_count;
+ // Don't add if it already exists
+ // (eg. an old IU received on a face on which we are retransmitting)
+ if (hicn_mapme_tfib_has (tfib, face_id))
+ {
+ HICN_DEBUG ("Found face %d in tfib.");
+ return 0;
+ }
- // XXX don 't add if it already exist
- // eg.an old IU received on a face on which we are retransmitting
- for (u8 pos2 = pos; pos2 < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; pos2++)
- if (tfib->next_hops[pos2] == face_id)
+ // If local face, do not put in in tfib
+ if (hicn_face_is_local (face_id))
+ {
+ HICN_DEBUG ("Do not add local face %d to TFIB.", face_id);
return 0;
+ }
+
+ u8 pos = HICN_PARAM_FIB_ENTRY_NHOPS_MAX - tfib->tfib_entry_count;
// Make sure we have enough room
if (pos <= tfib->entry_count)
@@ -190,7 +185,6 @@ hicn_mapme_tfib_clear (hicn_mapme_tfib_t *tfib)
{
hicn_face_unlock_with_id (tfib->next_hops[pos]);
tfib->next_hops[pos] = invalid;
- break;
}
tfib->tfib_entry_count = 0;
@@ -208,9 +202,12 @@ hicn_mapme_tfib_del (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
*/
u8 start_pos = HICN_PARAM_FIB_ENTRY_NHOPS_MAX - tfib->tfib_entry_count;
u8 pos = ~0;
+
for (pos = start_pos; pos < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; pos++)
if (tfib->next_hops[pos] == face_id)
{
+ HICN_DEBUG ("Deleted the face_id=%d from TFIB as we received an ack.",
+ face_id);
hicn_face_unlock_with_id (tfib->next_hops[pos]);
tfib->next_hops[pos] = invalid;
break;
@@ -230,30 +227,15 @@ hicn_mapme_tfib_del (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
}
/**
- * @brief Performs an Exact Prefix Match lookup on the FIB
+ * @brief Retrive DPO from fib entry
* @returns the corresponding DPO (hICN or IP LB), or NULL
*/
static_always_inline dpo_id_t *
-fib_epm_lookup (ip46_address_t *addr, u8 plen)
+dpo_from_fib_node_index (fib_node_index_t fib_entry_index)
{
- fib_prefix_t fib_pfx;
- fib_node_index_t fib_entry_index;
- u32 fib_index;
- dpo_id_t *dpo_id;
- load_balance_t *lb;
-
- const dpo_id_t *load_balance_dpo_id;
-
- /* At this point the face exists in the face table */
- fib_prefix_from_ip46_addr (addr, &fib_pfx);
- fib_pfx.fp_len = plen;
-
- /* Check if the route already exist in the fib : EPM */
- fib_index = fib_table_find (fib_pfx.fp_proto, HICN_FIB_TABLE);
-
- fib_entry_index = fib_table_lookup_exact_match (fib_index, &fib_pfx);
- if (fib_entry_index == FIB_NODE_INDEX_INVALID)
- return NULL;
+ const dpo_id_t *load_balance_dpo_id = NULL;
+ load_balance_t *lb = NULL;
+ dpo_id_t *dpo_id = NULL;
load_balance_dpo_id = fib_entry_contribute_ip_forwarding (fib_entry_index);
@@ -285,6 +267,46 @@ fib_epm_lookup (ip46_address_t *addr, u8 plen)
return (dpo_id_t *) load_balance_dpo_id;
}
+/**
+ * @brief Performs an Exact Prefix Match lookup on the FIB
+ * @returns the corresponding DPO (hICN or IP LB), or NULL
+ */
+static_always_inline dpo_id_t *
+fib_lookup (ip46_address_t *addr, u8 plen,
+ hicn_mapme_fib_lookup_type_t lookup_type)
+{
+ fib_prefix_t fib_pfx;
+ fib_node_index_t fib_entry_index;
+ u32 fib_index;
+
+ /* At this point the face exists in the face table */
+ fib_prefix_from_ip46_addr (addr, &fib_pfx);
+ fib_pfx.fp_len = plen;
+
+ /* Check if the route already exist in the fib : EPM */
+ fib_index = fib_table_find (fib_pfx.fp_proto, HICN_FIB_TABLE);
+
+ switch (lookup_type)
+ {
+ case HICN_MAPME_FIB_LOOKUP_TYPE_EPM:
+ fib_entry_index = fib_table_lookup_exact_match (fib_index, &fib_pfx);
+ break;
+ case HICN_MAPME_FIB_LOOKUP_TYPE_LPM:
+ fib_entry_index = fib_table_lookup (fib_index, &fib_pfx);
+ break;
+ case HICN_MAPME_FIB_LOOKUP_TYPE_LESSPM:
+ fib_entry_index = fib_table_get_less_specific (fib_index, &fib_pfx);
+ break;
+ default:
+ return NULL;
+ }
+
+ if (fib_entry_index == FIB_NODE_INDEX_INVALID)
+ return NULL;
+
+ return dpo_from_fib_node_index (fib_entry_index);
+}
+
/* DPO types */
extern dpo_type_t hicn_face_udp_type;
@@ -358,10 +380,6 @@ hicn_mapme_get_dpo_face_node (hicn_face_id_t face_id)
}
}
-#define DEBUG(...) // vlib_log_debug(mapme_main.log_class, __VA_ARGS__)
-#define WARN(...) // vlib_log_warn(mapme_main.log_class, __VA_ARGS__)
-#define ERROR(...) // vlib_log_err(mapme_main.log_class, __VA_ARGS__)
-
#endif /* __HICN_MAPME__ */
/*
diff --git a/hicn-plugin/src/mapme_ack.h b/hicn-plugin/src/mapme_ack.h
index 821baf203..9f47e9188 100644
--- a/hicn-plugin/src/mapme_ack.h
+++ b/hicn-plugin/src/mapme_ack.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,7 +14,7 @@
*/
/*
- * Copyright (c) 2017-2019 by Cisco Systems Inc. All Rights Reserved.
+ * Copyright (c) 2021 by Cisco Systems Inc. All Rights Reserved.
*
*/
@@ -41,6 +41,8 @@ typedef struct
u32 next_index;
u32 sw_if_index;
u8 pkt_type;
+ u32 seq;
+ hicn_prefix_t prefix;
} hicn_mapme_ack_trace_t;
typedef enum
diff --git a/hicn-plugin/src/mapme_ack_node.c b/hicn-plugin/src/mapme_ack_node.c
index fad344b73..e1f4d3889 100644
--- a/hicn-plugin/src/mapme_ack_node.c
+++ b/hicn-plugin/src/mapme_ack_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,6 +14,7 @@
*/
#include <vnet/ip/ip6_packet.h>
+#include <vlib/log.h>
#include "hicn.h"
#include "mapme.h"
@@ -47,29 +48,30 @@ static char *hicn_mapme_ack_error_strings[] = {
*/
bool
hicn_mapme_process_ack (vlib_main_t *vm, vlib_buffer_t *b,
- hicn_face_id_t in_face)
+ hicn_face_id_t in_face, hicn_prefix_t *prefix,
+ u32 *seq)
{
seq_t fib_seq;
const dpo_id_t *dpo;
- hicn_prefix_t prefix;
mapme_params_t params;
int rc;
/* Parse incoming message */
- rc = hicn_mapme_parse_packet (vlib_buffer_get_current (b), &prefix, &params);
+ rc = hicn_mapme_parse_packet (vlib_buffer_get_current (b), prefix, &params);
if (rc < 0)
goto ERR_PARSE;
- /* if (params.seq == INVALID_SEQ) */
- /* { */
- /* DEBUG ("Invalid sequence number found in IU"); */
- /* return true; */
- /* } */
+ *seq = params.seq;
+
+ HICN_DEBUG ("ACK - type:%d seq:%d prefix:%U len:%d", params.type, params.seq,
+ format_ip46_address, &prefix->name, IP46_TYPE_ANY, prefix->len);
- dpo = fib_epm_lookup (&(prefix.name), prefix.len);
+ dpo = fib_lookup (&(prefix->name.as_ip46), prefix->len,
+ HICN_MAPME_FIB_LOOKUP_TYPE_EPM);
if (!dpo)
{
- DEBUG ("Ignored ACK for non-existing FIB entry. Ignored.");
+ HICN_ERROR ("Ignored ACK for non-existing FIB entry %U. Ignored.",
+ format_ip_prefix, prefix);
return true;
}
@@ -80,7 +82,7 @@ hicn_mapme_process_ack (vlib_main_t *vm, vlib_buffer_t *b,
if (tfib == NULL)
{
- WARN ("Unable to get strategy ctx.");
+ HICN_ERROR ("Unable to get strategy ctx.");
return false;
}
@@ -92,11 +94,18 @@ hicn_mapme_process_ack (vlib_main_t *vm, vlib_buffer_t *b,
*/
if (params.seq < fib_seq)
{
- DEBUG ("Ignored ACK for low seq");
+ HICN_ERROR ("MAPME: Ignored ACK for low seq");
return true;
}
- hicn_mapme_tfib_del (tfib, in_face);
+ rc = hicn_mapme_tfib_del (tfib, in_face) != HICN_ERROR_NONE;
+ if (rc != HICN_ERROR_NONE)
+ {
+ HICN_ERROR (
+ "MAPME: Error deleting next hop %d from TFIB for prefix %U/%d",
+ in_face, format_ip46_address, &prefix->name, IP46_TYPE_ANY,
+ prefix->len);
+ }
/*
* Is the ingress face in TFIB ? if so, remove it, otherwise it might be a
@@ -105,7 +114,7 @@ hicn_mapme_process_ack (vlib_main_t *vm, vlib_buffer_t *b,
retx_t *retx = vlib_process_signal_event_data (
vm, hicn_mapme_eventmgr_process_node.index, HICN_MAPME_EVENT_FACE_PH_DEL,
1, sizeof (retx_t));
- *retx = (retx_t){ .prefix = prefix, .dpo = *dpo };
+ *retx = (retx_t){ .prefix = *prefix, .dpo = *dpo };
return true;
@@ -123,6 +132,8 @@ hicn_mapme_ack_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
hicn_mapme_ack_next_t next_index;
u32 n_left_from, *from, *to_next;
n_left_from = frame->n_vectors;
+ hicn_prefix_t prefix;
+ u32 seq;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
@@ -150,7 +161,7 @@ hicn_mapme_ack_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
vlib_cli_output (vm, "Received IUAck");
hb = hicn_get_buffer (b0);
- hicn_mapme_process_ack (vm, b0, hb->face_id);
+ hicn_mapme_process_ack (vm, b0, hb->face_id, &prefix, &seq);
/* Single loop: process 1 packet here */
sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
@@ -162,6 +173,8 @@ hicn_mapme_ack_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
vlib_add_trace (vm, node, b0, sizeof (*t));
t->sw_if_index = sw_if_index0;
t->next_index = next0;
+ t->prefix = prefix;
+ t->seq = seq;
}
/* $$$$$ Done processing 1 packet here $$$$$ */
@@ -184,8 +197,11 @@ hicn_mapme_ack_format_trace (u8 *s, va_list *args)
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
hicn_mapme_ack_trace_t *t = va_arg (*args, hicn_mapme_ack_trace_t *);
- s = format (s, "MAPME_ACK: pkt: %d, sw_if_index %d, next index %d",
- (int) t->pkt_type, t->sw_if_index, t->next_index);
+ s = format (
+ s,
+ "MAPME_ACK: pkt: %d, sw_if_index %d, next index %d, prefix %U/%d, seq %u",
+ (int) t->pkt_type, t->sw_if_index, t->next_index, format_ip46_address,
+ &t->prefix.name, IP46_TYPE_ANY, t->prefix.len, t->seq);
return (s);
}
diff --git a/hicn-plugin/src/mapme_ctrl.h b/hicn-plugin/src/mapme_ctrl.h
index a40a969b0..d3dfb7b69 100644
--- a/hicn-plugin/src/mapme_ctrl.h
+++ b/hicn-plugin/src/mapme_ctrl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,7 +14,7 @@
*/
/*
- * Copyright (c) 2017-2019 by Cisco Systems Inc. All Rights Reserved.
+ * Copyright (c) 2021 by Cisco Systems Inc. All Rights Reserved.
*
*/
@@ -39,8 +39,9 @@ typedef struct hicn_mapme_ctrl_runtime_s
typedef struct
{
u32 next_index;
- u32 sw_if_index;
- u8 pkt_type;
+ u32 seq;
+ hicn_prefix_t prefix;
+ hicn_mapme_type_t type;
} hicn_mapme_ctrl_trace_t;
typedef enum
diff --git a/hicn-plugin/src/mapme_ctrl_node.c b/hicn-plugin/src/mapme_ctrl_node.c
index 613958d9c..cf825a957 100644
--- a/hicn-plugin/src/mapme_ctrl_node.c
+++ b/hicn-plugin/src/mapme_ctrl_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,6 +18,7 @@
*/
#include <vnet/ip/ip6_packet.h>
#include <vnet/dpo/load_balance.h>
+#include <vlib/log.h>
#include "hicn.h"
#include "mapme.h"
@@ -30,6 +31,7 @@
#include "strategy_dpo_ctx.h"
#include "error.h"
#include "state.h"
+#include "route.h"
extern hicn_mapme_main_t mapme_main;
@@ -47,6 +49,184 @@ static char *hicn_mapme_ctrl_error_strings[] = {
#undef _
};
+static_always_inline int
+hicn_mapme_nh_set (hicn_mapme_tfib_t *tfib, hicn_face_id_t in_face_id)
+{
+ hicn_dpo_ctx_t *strategy_ctx = (hicn_dpo_ctx_t *) tfib;
+ const fib_prefix_t *prefix =
+ fib_entry_get_prefix (strategy_ctx->fib_entry_index);
+
+ int ret = 0;
+
+ if ((tfib->entry_count == 1) && (tfib->next_hops[0] == in_face_id))
+ return ret;
+
+ /*
+ * Remove all the existing next hops and set the new one
+ */
+ u32 n_entries = tfib->entry_count;
+ for (int i = 0; i < n_entries; i++)
+ {
+ hicn_face_t *face = hicn_dpoi_get_from_idx (strategy_ctx->next_hops[0]);
+ if (dpo_is_adj (&face->dpo))
+ {
+ ip_adjacency_t *adj = adj_get (face->dpo.dpoi_index);
+ ip_nh_adj_add_del_helper (prefix->fp_proto, prefix,
+ &adj->sub_type.nbr.next_hop, face->sw_if,
+ 0);
+ }
+ else if (dpo_is_udp_encap (&face->dpo))
+ {
+ ip_nh_udp_tunnel_add_del_helper (prefix->fp_proto, prefix,
+ face->dpo.dpoi_index,
+ face->dpo.dpoi_proto, 0);
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ ret = HICN_ERROR_MAPME_NEXT_HOP_ADDED;
+ hicn_face_t *face = hicn_dpoi_get_from_idx (in_face_id);
+ if (dpo_is_udp_encap (&face->dpo))
+ {
+ ip_nh_udp_tunnel_add_del_helper (prefix->fp_proto, prefix,
+ face->dpo.dpoi_index,
+ face->dpo.dpoi_proto, 1);
+ }
+ else if (dpo_is_adj (&face->dpo))
+ {
+ ip_nh_adj_add_del_helper (prefix->fp_proto, prefix, &face->nat_addr,
+ face->sw_if, 1);
+ }
+ else
+ {
+ ret = HICN_ERROR_MAPME_NEXT_HOP_NOT_ADDED;
+ }
+
+ return ret;
+}
+
+/**
+ * @brief Check whether a face is already included in the FIB nexthops.
+ *
+ * NOTE: linear scan on a contiguous small array should be the most efficient.
+ */
+static_always_inline int
+hicn_mapme_nh_has (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
+{
+ for (u8 pos = 0; pos < tfib->entry_count; pos++)
+ if (tfib->next_hops[pos] == face_id)
+ return 1;
+ return 0;
+}
+
+/**
+ * @brief Add a next hop iif it is not already a next hops
+ */
+static_always_inline int
+hicn_mapme_nh_add (hicn_mapme_tfib_t *tfib, hicn_face_id_t face_id)
+{
+ if (hicn_mapme_nh_has (tfib, face_id))
+ return 0;
+
+ /* Add the next hop in the vrf 0 which will add it to the entry in the hICN
+ * vrf */
+ hicn_dpo_ctx_t *strategy_ctx = (hicn_dpo_ctx_t *) tfib;
+ const fib_prefix_t *prefix =
+ fib_entry_get_prefix (strategy_ctx->fib_entry_index);
+ hicn_face_t *face = hicn_dpoi_get_from_idx (face_id);
+
+ if (dpo_is_udp_encap (&face->dpo))
+ {
+ ip_nh_udp_tunnel_add_del_helper ((fib_protocol_t) face->dpo.dpoi_proto,
+ prefix, face->dpo.dpoi_index,
+ face->dpo.dpoi_proto, 1);
+ }
+ else
+ {
+ ip_nh_adj_add_del_helper ((fib_protocol_t) face->dpo.dpoi_proto, prefix,
+ &face->nat_addr, face->sw_if, 1);
+ }
+
+ return 0;
+}
+
+/**
+ * @brief Add a route to the fib.
+ *
+ */
+static_always_inline int
+hicn_mapme_add_fib_entry (const fib_prefix_t *prefix,
+ hicn_face_id_t in_face_id,
+ fib_node_index_t *hicn_fib_node_index)
+{
+ int ret = HICN_ERROR_NONE;
+ dpo_proto_t dpo_proto = DPO_PROTO_NONE;
+
+ hicn_face_t *face = hicn_dpoi_get_from_idx (in_face_id);
+
+ if (face->sw_if == ~0)
+ {
+ // UDP encap case
+ if (face->flags & HICN_FACE_FLAGS_UDP4)
+ {
+ dpo_proto = DPO_PROTO_IP4;
+ }
+ else if (face->flags & HICN_FACE_FLAGS_UDP6)
+ {
+ dpo_proto = DPO_PROTO_IP6;
+ }
+ else
+ {
+ // Invalid
+ return HICN_ERROR_FACE_NOT_VALID;
+ }
+
+ ret = ip_nh_udp_tunnel_add_del_helper (
+ prefix->fp_proto, prefix, face->dpo.dpoi_index, dpo_proto, 1);
+ }
+ else
+ {
+ ret = ip_nh_adj_add_del_helper (prefix->fp_proto, prefix,
+ &face->nat_addr, face->sw_if, 1);
+ }
+
+ if (ret != HICN_ERROR_NONE)
+ {
+ return ret;
+ }
+
+ // Now let's trigger the sync the main table with the hicn table
+ hicn_face_id_t *vec_faces = NULL;
+ ret = hicn_route_enable (prefix, hicn_fib_node_index, &vec_faces);
+
+ if (vec_faces[0] != in_face_id)
+ {
+ HICN_ERROR ("Created new face: new face id: %d, in_face id: %d",
+ vec_faces[0], in_face_id);
+ ret = HICN_ERROR_MAPME_WRONG_FACE_CREATED;
+ }
+
+ return ret;
+}
+
+/**
+ * Convert hicn prefix to fib prefix
+ */
+static_always_inline void
+hicn_prefix_to_fib_prefix (const hicn_prefix_t *prefix_in,
+ fib_prefix_t *prefix_out)
+{
+ clib_memcpy (&prefix_out->fp_addr, &prefix_in->name.as_ip46,
+ sizeof (prefix_out->fp_addr));
+ prefix_out->fp_len = (u16) prefix_in->len;
+ prefix_out->fp_proto = ip46_address_is_ip4 (&prefix_out->fp_addr) ?
+ FIB_PROTOCOL_IP4 :
+ FIB_PROTOCOL_IP6;
+}
+
/*
* @brief Process incoming control messages (Interest Update)
* @param vm vlib main data structure
@@ -61,46 +241,117 @@ static char *hicn_mapme_ctrl_error_strings[] = {
*/
static_always_inline bool
hicn_mapme_process_ctrl (vlib_main_t *vm, vlib_buffer_t *b,
- hicn_face_id_t in_face_id)
+ hicn_face_id_t in_face_id, hicn_prefix_t *prefix,
+ u32 *seq, hicn_mapme_type_t *type)
{
seq_t fib_seq;
- const dpo_id_t *dpo;
- hicn_prefix_t prefix;
+ const dpo_id_t *dpo, *dpo_mapme_default_route;
+ fib_prefix_t fib_prefix;
mapme_params_t params;
+ hicn_mapme_tfib_t *tfib;
int rc;
+ hicn_mapme_main_t *mm;
+#ifdef HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY
+ fib_node_index_t fib_node_index;
+ hicn_mapme_tfib_t *tfib_less_specific;
+#endif
+
+ mm = hicn_mapme_get_main ();
/* Parse incoming message */
- rc = hicn_mapme_parse_packet (vlib_buffer_get_current (b), &prefix, &params);
+ rc = hicn_mapme_parse_packet (vlib_buffer_get_current (b), prefix, &params);
if (rc < 0)
goto ERR_PARSE;
- vlib_cli_output (vm, "IU - type:%d seq:%d len:%d", params.type, params.seq,
- prefix.len);
+ *seq = params.seq;
+ *type = params.type;
- /* if (params.seq == INVALID_SEQ) */
- /* { */
- /* vlib_log_warn (mapme_main.log_class, */
- /* "Invalid sequence number found in IU"); */
-
- /* return true; */
- /* } */
+ HICN_DEBUG ("IU - type:%d seq:%d prefix:%U len:%d", params.type, params.seq,
+ format_ip46_address, &prefix->name, IP46_TYPE_ANY, prefix->len);
/* We forge the ACK which we be the packet forwarded by the node */
hicn_mapme_create_ack (vlib_buffer_get_current (b), &params);
- dpo = fib_epm_lookup (&prefix.name, prefix.len);
+ dpo = fib_lookup (&prefix->name.as_ip46, prefix->len,
+ HICN_MAPME_FIB_LOOKUP_TYPE_EPM);
if (!dpo)
{
#ifdef HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY
- /*
- * This might happen for a node hosting a producer which has moved.
- * Destroying the face has led to removing all corresponding FIB
- * entries. In that case, we need to correctly restore the FIB entries.
- */
- DEBUG ("Re-creating FIB entry with next hop on connection")
-#error "not implemented"
+ // As the EPM failed (but we received the IU), it means we have another
+ // prefix that is either more or less specific to which forward
+ // the IU. We do not update the NHs for this prefix, and we use the
+ // default mapme route to forward ther IU.
+
+ dpo_mapme_default_route =
+ fib_lookup (&mm->default_route.fp_addr, mm->default_route.fp_len,
+ HICN_MAPME_FIB_LOOKUP_TYPE_EPM);
+
+ if (!dpo_mapme_default_route)
+ {
+ // No path for mapme default route.
+ HICN_ERROR (
+ "No path for mapme default route (%U). Giving up IU forwarding.",
+ format_fib_prefix, &mm->default_route);
+ return false;
+ }
+
+ hicn_prefix_to_fib_prefix (prefix, &fib_prefix);
+ HICN_DEBUG ("Re-creating FIB entry with next hop on connection");
+ rc = hicn_mapme_add_fib_entry (&fib_prefix, in_face_id, &fib_node_index);
+
+ if (rc != HICN_ERROR_NONE)
+ {
+ return false;
+ }
+
+ // Get the DPO from the fib node index
+ dpo = dpo_from_fib_node_index (fib_node_index);
+
+ // This cannot fail
+ ASSERT (dpo);
+
+// Make sure DPO is hicn
+#ifdef HICN_MAPME_ALLOW_LOCATORS
+ if (!dpo_is_hicn ((dpo)))
+ {
+ /* We have an IP DPO */
+ HICN_ERROR ("Not implemented yet.");
+ return false;
+ }
+#endif
+
+ u32 hicn_dpo_ctx_index = dpo->dpoi_index;
+ u32 hicn_dpo_ctx_index_less_specific_route =
+ dpo_mapme_default_route->dpoi_index;
+
+ tfib_less_specific = TFIB (
+ hicn_strategy_dpo_ctx_get (hicn_dpo_ctx_index_less_specific_route));
+ tfib = TFIB (hicn_strategy_dpo_ctx_get (hicn_dpo_ctx_index));
+
+ for (u8 pos = 0; pos < tfib_less_specific->entry_count; pos++)
+ {
+ HICN_DEBUG (
+ "Adding nexthop to the tfib, dpo index in_face %d, dpo index "
+ "tfib %d",
+ in_face_id, tfib_less_specific->next_hops[pos]);
+ hicn_mapme_tfib_add (tfib, tfib_less_specific->next_hops[pos]);
+ }
+
+ // Update sequence number
+ tfib->seq = params.seq;
+
+ retx_t *retx = vlib_process_signal_event_data (
+ vm, hicn_mapme_eventmgr_process_node.index,
+ HICN_MAPME_EVENT_FACE_NH_SET, 1, sizeof (retx_t));
+ *retx = (retx_t){ .prefix = *prefix,
+ .dpo = {
+ .dpoi_index = hicn_dpo_ctx_index,
+ .dpoi_type = DPO_FIRST,
+ } };
+
+ return true;
#else
- // ERROR("Received IU for non-existing FIB entry");
+ HICN_ERROR ("Received IU for non-existing FIB entry");
return false;
#endif /* HICN_MAPME_ALLOW_NONEXISTING_FIB_ENTRY */
}
@@ -109,17 +360,17 @@ hicn_mapme_process_ctrl (vlib_main_t *vm, vlib_buffer_t *b,
if (!dpo_is_hicn ((dpo)))
{
/* We have an IP DPO */
- WARN ("Not implemented yet.");
+ HICN_ERROR ("Not implemented yet.");
return false;
}
#endif
/* Process the hICN DPO */
- hicn_mapme_tfib_t *tfib = TFIB (hicn_strategy_dpo_ctx_get (dpo->dpoi_index));
+ tfib = TFIB (hicn_strategy_dpo_ctx_get (dpo->dpoi_index));
if (tfib == NULL)
{
- WARN ("Unable to get strategy ctx.");
+ HICN_ERROR ("Unable to get strategy ctx.");
return false;
}
@@ -127,7 +378,7 @@ hicn_mapme_process_ctrl (vlib_main_t *vm, vlib_buffer_t *b,
if (params.seq > fib_seq)
{
- DEBUG (
+ HICN_DEBUG (
"Higher sequence number than FIB %d > %d, updating seq and next hops",
params.seq, fib_seq);
@@ -139,62 +390,82 @@ hicn_mapme_process_ctrl (vlib_main_t *vm, vlib_buffer_t *b,
/* Remove ingress face from TFIB in case it was present */
hicn_mapme_tfib_del (tfib, in_face_id);
+ HICN_DEBUG ("Locks on face %d: %d", in_face_id,
+ hicn_dpoi_get_from_idx (in_face_id)->locks);
+
/* Move next hops to TFIB... but in_face... */
for (u8 pos = 0; pos < tfib->entry_count; pos++)
{
- hicn_face_t *face = hicn_dpoi_get_from_idx (tfib->next_hops[pos]);
- hicn_face_t *in_face = hicn_dpoi_get_from_idx (in_face_id);
- if (dpo_is_adj (&face->dpo))
- {
- ip_adjacency_t *adj = adj_get (dpo->dpoi_index);
- if (ip46_address_cmp (&(adj->sub_type.nbr.next_hop),
- &(in_face->nat_addr)) == 0)
- break;
- }
- DEBUG ("Adding nexthop to the tfib, dpo index in_face %d, dpo index "
- "tfib %d",
- in_face_id, tfib->next_hops[pos]);
+ if (tfib->next_hops[pos] == in_face_id)
+ continue;
+ HICN_DEBUG (
+ "Adding nexthop to the tfib, dpo index in_face %d, dpo index "
+ "tfib %d",
+ in_face_id, tfib->next_hops[pos]);
hicn_mapme_tfib_add (tfib, tfib->next_hops[pos]);
}
- hicn_mapme_nh_set (tfib, in_face_id);
+ int ret = hicn_mapme_nh_set (tfib, in_face_id);
+ HICN_DEBUG ("Locks on face %d: %d", in_face_id,
+ hicn_dpoi_get_from_idx (in_face_id)->locks);
+ if (ret == HICN_ERROR_MAPME_NEXT_HOP_ADDED &&
+ hicn_get_buffer (b)->flags & HICN_BUFFER_FLAGS_NEW_FACE)
+ {
+ hicn_face_unlock_with_id (in_face_id);
+ }
/* We transmit both the prefix and the full dpo (type will be needed to
* pick the right transmit node */
retx_t *retx = vlib_process_signal_event_data (
vm, hicn_mapme_eventmgr_process_node.index,
HICN_MAPME_EVENT_FACE_NH_SET, 1, sizeof (retx_t));
- *retx = (retx_t){ .prefix = prefix, .dpo = *dpo };
+ *retx = (retx_t){ .prefix = *prefix, .dpo = *dpo };
}
else if (params.seq == fib_seq)
{
- DEBUG ("Same sequence number than FIB %d > %d, adding next hop",
- params.seq, fib_seq);
+ HICN_DEBUG ("Same sequence number than FIB %d > %d, adding next hop",
+ params.seq, fib_seq);
- /* Remove ingress face from TFIB in case it was present */
- hicn_mapme_tfib_del (tfib, in_face_id);
+ /**
+ * Add nh BEFORE removing the face from the tfib, as if the last lock is
+ * held by the tfib, deleting it first would also delete the face,
+ * resulting in a undefined behavior after (Debug mode -> SIGABRT,
+ * Release Mode -> Corrupted memory / SIGSEGV).
+ **/
/* Add ingress face to next hops */
hicn_mapme_nh_add (tfib, in_face_id);
+ /* Remove ingress face from TFIB in case it was present */
+ hicn_mapme_tfib_del (tfib, in_face_id);
+
/* Multipath, multihoming, multiple producers or duplicate interest */
retx_t *retx = vlib_process_signal_event_data (
vm, hicn_mapme_eventmgr_process_node.index,
HICN_MAPME_EVENT_FACE_NH_ADD, 1, sizeof (retx_t));
- *retx = (retx_t){ .prefix = prefix, .dpo = *dpo };
+ *retx = (retx_t){ .prefix = *prefix, .dpo = *dpo };
}
else // params.seq < fib_seq
{
/*
* face is propagating outdated information, we can just consider it as a
- * prevHops
+ * prevHops, unless it is the current nexthop.
*/
+ if (hicn_mapme_nh_has (tfib, in_face_id))
+ {
+ HICN_DEBUG ("Ignored seq %d < fib_seq %d from current nexthop",
+ params.seq, fib_seq);
+ return true;
+ }
+ HICN_DEBUG ("Received seq %d < fib_seq %d, sending backwards",
+ params.seq, fib_seq);
+
hicn_mapme_tfib_add (tfib, in_face_id);
retx_t *retx = vlib_process_signal_event_data (
vm, hicn_mapme_eventmgr_process_node.index,
HICN_MAPME_EVENT_FACE_PH_ADD, 1, sizeof (retx_t));
- *retx = (retx_t){ .prefix = prefix, .dpo = *dpo };
+ *retx = (retx_t){ .prefix = *prefix, .dpo = *dpo };
}
/* We just raise events, the event_mgr is in charge of forging packet. */
@@ -216,7 +487,10 @@ hicn_mapme_ctrl_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
hicn_mapme_ctrl_next_t next_index;
u32 n_left_from, *from, *to_next;
n_left_from = frame->n_vectors;
- // hicn_face_id_t in_face;
+ hicn_prefix_t prefix;
+ u32 seq;
+ hicn_mapme_type_t type = UPDATE;
+ int ret;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
@@ -244,20 +518,39 @@ hicn_mapme_ctrl_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
/* This determines the next node on which the ack will be sent back
*/
- u32 next0 = hicn_mapme_ctrl_get_iface_node (hb->face_id);
+ u32 next0 = HICN_MAPME_CTRL_NEXT_IP6_OUTPUT;
- hicn_mapme_process_ctrl (vm, b0, hb->face_id);
+ ret = hicn_mapme_process_ctrl (vm, b0, hb->face_id, &prefix, &seq,
+ &type);
- vnet_buffer (b0)->ip.adj_index[VLIB_TX] = hb->face_id;
+ if (PREDICT_FALSE (ret == 0))
+ {
+ next0 = HICN_MAPME_CTRL_NEXT_ERROR_DROP;
+ seq = ~0;
+ type = UNKNOWN;
+ }
+ else
+ {
+ vnet_buffer (b0)->ip.adj_index[VLIB_TX] = hb->face_id;
+ }
+
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ hicn_mapme_ctrl_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->prefix = prefix;
+ t->next_index = next0;
+ t->seq = seq;
+ t->type = type;
+ }
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
- // vlib_node_increment_counter (vm, hicn_mapme_ctrl_node.index,
- // HICN_MAPME_CTRL_ERROR_SWAPPED,
- // pkts_swapped);
+
return frame->n_vectors;
}
@@ -269,8 +562,9 @@ hicn_mapme_ctrl_format_trace (u8 *s, va_list *args)
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
hicn_mapme_ctrl_trace_t *t = va_arg (*args, hicn_mapme_ctrl_trace_t *);
- s = format (s, "MAPME_CTRL: pkt: %d, sw_if_index %d, next index %d",
- (int) t->pkt_type, t->sw_if_index, t->next_index);
+ s = format (s, "MAPME_CTRL: prefix: %U/%d, next_index %u, seq %u, type %u",
+ format_ip46_address, &t->prefix.name, IP46_TYPE_ANY,
+ t->prefix.len, t->next_index, t->seq, t->type);
return (s);
}
diff --git a/hicn-plugin/src/mapme_eventmgr.c b/hicn-plugin/src/mapme_eventmgr.c
index 49a9b5c57..bb654edf8 100644
--- a/hicn-plugin/src/mapme_eventmgr.c
+++ b/hicn-plugin/src/mapme_eventmgr.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,8 +22,15 @@
#include <vnet/fib/ip4_fib.h>
#include <vnet/fib/ip6_fib.h>
+#include <hicn/mapme.h>
+
#define DEFAULT_TIMEOUT 1.0 /* s */
+/**
+ * @brief This is a process node reacting to face events.
+ */
+vlib_node_registration_t hicn_mapme_eventmgr_process_node;
+
hicn_mapme_main_t mapme_main;
hicn_prefix_t *retx_pool;
@@ -33,7 +40,14 @@ void
hicn_mapme_init (vlib_main_t *vm)
{
mapme_main.vm = vm;
- mapme_main.log_class = vlib_log_register_class ("hicn_mapme", 0);
+ clib_memset_u8 (&mapme_main.default_route, 0,
+ sizeof (mapme_main.default_route));
+}
+
+hicn_mapme_main_t *
+hicn_mapme_get_main ()
+{
+ return &mapme_main;
}
/* borrowed from vnet/fib/ip4_fib.c */
@@ -77,7 +91,6 @@ hicn_mapme_process_fib_entry (vlib_main_t *vm, hicn_face_id_t face,
const dpo_id_t *load_balance_dpo_id;
load_balance_t *lb;
dpo_id_t *dpo_id;
- fib_entry_t *fib_entry;
load_balance_dpo_id = fib_entry_contribute_ip_forwarding (*fib_entry_index);
@@ -92,12 +105,14 @@ hicn_mapme_process_fib_entry (vlib_main_t *vm, hicn_face_id_t face,
{
/* un-const */
dpo_id = (dpo_id_t *) load_balance_get_bucket_i (lb, i);
-
if (dpo_is_hicn (dpo_id))
{
+#ifdef HICN_DDEBUG
+ fib_entry_t *fib_entry;
fib_entry = fib_entry_get (*fib_entry_index);
- vlib_cli_output (vm, "set face pending %U", format_fib_prefix,
- &fib_entry->fe_prefix);
+ HICN_DEBUG ("set face pending %U", format_fib_prefix,
+ &fib_entry->fe_prefix);
+#endif
}
}
}
@@ -107,16 +122,10 @@ hicn_mapme_process_ip4_fib (vlib_main_t *vm, hicn_face_id_t face)
{
ip4_main_t *im4 = &ip4_main;
fib_table_t *fib_table;
- int table_id = -1, fib_index = ~0;
pool_foreach (fib_table, im4->fibs)
{
- ip4_fib_t *fib = pool_elt_at_index (im4->v4_fibs, fib_table->ft_index);
-
- if (table_id >= 0 && table_id != (int) fib->table_id)
- continue;
- if (fib_index != ~0 && fib_index != (int) fib->index)
- continue;
+ ip4_fib_t *fib = pool_elt_at_index (ip4_fibs, fib_table->ft_index);
fib_node_index_t *fib_entry_index;
ip4_fib_show_walk_ctx_t ctx = {
@@ -195,29 +204,38 @@ hicn_mapme_on_face_added (vlib_main_t *vm, hicn_face_id_t face)
#define CURLEN retx_len[cur]
#define NXTLEN retx_len[NEXT_SLOT (cur)]
-static_always_inline void *
-get_packet_buffer (vlib_main_t *vm, u32 node_index, u32 dpoi_index,
- ip46_address_t *addr, hicn_type_t type)
+static_always_inline bool
+create_mapme_packet_buffer (vlib_main_t *vm, u32 node_index, u32 dpoi_index,
+ const hicn_prefix_t *prefix,
+ const mapme_params_t *params)
{
vlib_frame_t *f;
vlib_buffer_t *b; // for newly created packet
u32 *to_next;
u32 bi;
u8 *buffer;
+ size_t n;
+ hicn_packet_format_t format;
if (vlib_buffer_alloc (vm, &bi, 1) != 1)
{
- clib_warning ("buffer allocation failure");
+ HICN_ERROR ("buffer allocation failure");
return NULL;
}
+ format = (params->protocol == IPPROTO_IPV6) ? HICN_PACKET_FORMAT_IPV6_ICMP :
+ HICN_PACKET_FORMAT_IPV4_ICMP;
+
/* Create a new packet from scratch */
b = vlib_get_buffer (vm, bi);
ASSERT (b->current_data == 0);
/* Face information for next hop node index */
vnet_buffer (b)->ip.adj_index[VLIB_TX] = dpoi_index;
- hicn_get_buffer (b)->type = type;
+
+ hicn_packet_buffer_t *pkbuf = &hicn_get_buffer (b)->pkbuf;
+ hicn_packet_set_format (pkbuf, format);
+ hicn_packet_init_header (pkbuf, 0);
/* Enqueue the packet right now */
f = vlib_get_frame_to_node (vm, node_index);
@@ -228,8 +246,21 @@ get_packet_buffer (vlib_main_t *vm, u32 node_index, u32 dpoi_index,
// pointer to IP layer ? do we need to prepare for ethernet ???
buffer = vlib_buffer_get_current (b);
- b->current_length =
- (type.l1 == IPPROTO_IPV6) ? HICN_MAPME_V6_HDRLEN : HICN_MAPME_V4_HDRLEN;
+ b->current_length = HICN_PACKET_FORMAT_IS_IPV6 (format) ?
+ EXPECTED_MAPME_V6_HDRLEN :
+ EXPECTED_MAPME_V4_HDRLEN;
+
+ n = hicn_mapme_create_packet (buffer, prefix, params);
+
+ if (n <= 0)
+ {
+ HICN_ERROR ("Could not create MAP-Me packet");
+ return false;
+ }
+
+ hicn_packet_set_buffer (pkbuf, vlib_buffer_get_current (b),
+ b->current_length, b->current_length);
+ hicn_packet_analyze (&hicn_get_buffer (b)->pkbuf);
return buffer;
}
@@ -238,11 +269,9 @@ static_always_inline bool
hicn_mapme_send_message (vlib_main_t *vm, const hicn_prefix_t *prefix,
mapme_params_t *params, hicn_face_id_t face)
{
- size_t n;
-
/* This should be retrieved from face information */
- DEBUG ("Retransmission for prefix %U seq=%d", format_ip46_address,
- &prefix->name, IP46_TYPE_ANY, params->seq);
+ HICN_DEBUG ("Retransmission for prefix %U/%d seq=%d", format_ip46_address,
+ &prefix->name, IP46_TYPE_ANY, prefix->len, params->seq);
char *node_name = hicn_mapme_get_dpo_face_node (face);
if (!node_name)
@@ -254,18 +283,7 @@ hicn_mapme_send_message (vlib_main_t *vm, const hicn_prefix_t *prefix,
vlib_node_t *node = vlib_get_node_by_name (vm, (u8 *) node_name);
u32 node_index = node->index;
- u8 *buffer = get_packet_buffer (
- vm, node_index, face, (ip46_address_t *) prefix,
- (params->protocol == IPPROTO_IPV6) ? HICN_TYPE_IPV6_ICMP :
- HICN_TYPE_IPV4_ICMP);
- n = hicn_mapme_create_packet (buffer, prefix, params);
- if (n <= 0)
- {
- clib_warning ("Could not create MAP-Me packet");
- return false;
- }
-
- return true;
+ return create_mapme_packet_buffer (vm, node_index, face, prefix, params);
}
static_always_inline void
@@ -275,7 +293,7 @@ hicn_mapme_send_updates (vlib_main_t *vm, hicn_prefix_t *prefix, dpo_id_t dpo,
hicn_mapme_tfib_t *tfib = TFIB (hicn_strategy_dpo_ctx_get (dpo.dpoi_index));
if (!tfib)
{
- DEBUG ("NULL TFIB entry id=%d", dpo.dpoi_index);
+ HICN_DEBUG ("NULL TFIB entry id=%d", dpo.dpoi_index);
return;
}
@@ -283,14 +301,15 @@ hicn_mapme_send_updates (vlib_main_t *vm, hicn_prefix_t *prefix, dpo_id_t dpo,
mapme_params_t params = {
.protocol =
- ip46_address_is_ip4 (&prefix->name) ? IPPROTO_IP : IPPROTO_IPV6,
+ ip46_address_is_ip4 (&prefix->name.as_ip46) ? IPPROTO_IP : IPPROTO_IPV6,
.type = UPDATE,
.seq = tfib->seq,
};
if (send_all)
{
- for (u8 pos = tfib_last_idx; pos < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; pos++)
+ u8 pos;
+ for (pos = tfib_last_idx; pos < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; pos++)
{
hicn_mapme_send_message (vm, prefix, &params, tfib->next_hops[pos]);
}
@@ -337,7 +356,7 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
* Also, we only run a timer when there are pending retransmissions.
*/
timeout = (due_time > current_time) ? due_time - current_time :
- DEFAULT_TIMEOUT;
+ DEFAULT_TIMEOUT;
due_time = current_time + timeout;
}
else
@@ -359,6 +378,7 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
* - For another local face type, we need to advertise local
* prefixes and schedule retransmissions
*/
+ HICN_DEBUG ("Mapme Event: HICN_MAPME_EVENT_FACE_ADD");
retx_t *retx_events = event_data;
for (u8 i = 0; i < vec_len (retx_events); i++)
{
@@ -374,6 +394,7 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
case HICN_MAPME_EVENT_FACE_NH_SET:
{
+ HICN_DEBUG ("Mapme Event: HICN_MAPME_EVENT_FACE_NH_SET");
/*
* An hICN FIB entry has been modified. All operations so far
* have been procedded in the nodes. Here we need to track
@@ -410,6 +431,7 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
* Transmit IU for all TFIB entries with latest seqno (we have
* at least one for sure!)
*/
+ HICN_DEBUG ("Sending mapme message upon NH_SET event");
hicn_mapme_send_updates (vm, &retx->prefix, retx->dpo, true);
/* Delete entry_id from retransmissions in the current slot (if
@@ -433,6 +455,7 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
break;
case HICN_MAPME_EVENT_FACE_NH_ADD:
+ HICN_DEBUG ("Mapme Event: HICN_MAPME_EVENT_FACE_NH_ADD");
/*
* As per the description of states, this event should add the face
* to the list of next hops, and eventually remove it from TFIB.
@@ -452,6 +475,7 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
break;
case HICN_MAPME_EVENT_FACE_PH_ADD:
+ HICN_DEBUG ("Mapme Event: HICN_MAPME_EVENT_FACE_PH_ADD");
/* Back-propagation, interesting even for IN (desync) */
{
retx_t *retx_events = event_data;
@@ -465,6 +489,7 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
break;
case HICN_MAPME_EVENT_FACE_PH_DEL:
+ HICN_DEBUG ("Mapme Event: HICN_MAPME_EVENT_FACE_PH_DEL");
/* Ack : remove an element from TFIB */
break;
@@ -493,8 +518,8 @@ hicn_mapme_eventmgr_process (vlib_main_t *vm, vlib_node_runtime_t *rt,
TFIB (hicn_strategy_dpo_ctx_get (retx->dpo.dpoi_index));
if (!tfib)
{
- DEBUG ("NULL TFIB entry for dpoi_index=%d",
- retx->dpo.dpoi_index);
+ HICN_ERROR ("NULL TFIB entry for dpoi_index=%d",
+ retx->dpo.dpoi_index);
continue;
}
diff --git a/hicn-plugin/src/mapme_eventmgr.h b/hicn-plugin/src/mapme_eventmgr.h
index 2100a6f90..559ba2e75 100644
--- a/hicn-plugin/src/mapme_eventmgr.h
+++ b/hicn-plugin/src/mapme_eventmgr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -39,8 +39,7 @@ typedef struct
/**
* @brief This is a process node reacting to face events.
*/
-// not static !
-vlib_node_registration_t hicn_mapme_eventmgr_process_node;
+extern vlib_node_registration_t hicn_mapme_eventmgr_process_node;
/**
* @brief Initialize MAP-Me on forwarder
diff --git a/hicn-plugin/src/mgmt.c b/hicn-plugin/src/mgmt.c
index b820a378f..6e9ce9fd8 100644
--- a/hicn-plugin/src/mgmt.c
+++ b/hicn-plugin/src/mgmt.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,7 +21,7 @@
#include "mgmt.h"
/* define message IDs */
-#include "hicn_msg_enum.h"
+#include <vpp_plugins/hicn/hicn_msg_enum.h>
/* shared routine betweeen API and CLI, leveraging API message structure */
int
@@ -46,7 +46,8 @@ hicn_mgmt_node_stats_get (vl_api_hicn_api_node_stats_get_reply_t *rmp)
vlib_error_main_t *em;
vlib_node_t *n;
- foreach_vlib_main() {
+ foreach_vlib_main ()
+ {
em = &this_vlib_main->error_main;
n = vlib_get_node (this_vlib_main, hicn_interest_pcslookup_node.index);
u32 node_cntr_base_idx = n->error_heap_index;
diff --git a/hicn-plugin/src/mgmt.h b/hicn-plugin/src/mgmt.h
index 8eaa18fa8..03e73999f 100644
--- a/hicn-plugin/src/mgmt.h
+++ b/hicn-plugin/src/mgmt.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,7 +18,7 @@
#include <vppinfra/error.h>
#include "faces/face.h"
-#include "hicn_api.h"
+#include <vpp_plugins/hicn/hicn_api.h>
/**
* @file mgmt.h
diff --git a/hicn-plugin/src/params.h b/hicn-plugin/src/params.h
index 7c7850d30..324429abe 100644
--- a/hicn-plugin/src/params.h
+++ b/hicn-plugin/src/params.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -60,9 +60,9 @@ STATIC_ASSERT ((HICN_PARAM_FACES_MAX & (HICN_PARAM_FACES_MAX - 1)) == 0,
// HICN_PARAM_PIT_ENTRY_PHOPS_MAX - 4 must be a power of two
#define HICN_PARAM_PIT_ENTRY_PHOPS_MAX 20
-STATIC_ASSERT ((ceil (log2 ((HICN_PARAM_PIT_ENTRY_PHOPS_MAX - 4)))) ==
- (floor (log2 ((HICN_PARAM_PIT_ENTRY_PHOPS_MAX - 4)))),
- "HICN_PARAM_PIT_ENTRY_PHOPS_MAX - 4 must be a power of two");
+// STATIC_ASSERT ((ceil (log2 ((HICN_PARAM_PIT_ENTRY_PHOPS_MAX - 4)))) ==
+// (floor (log2 ((HICN_PARAM_PIT_ENTRY_PHOPS_MAX - 4)))),
+// "HICN_PARAM_PIT_ENTRY_PHOPS_MAX - 4 must be a power of two");
STATIC_ASSERT (
(HICN_PARAM_PIT_ENTRY_PHOPS_MAX <= HICN_PARAM_FACES_MAX),
@@ -113,7 +113,7 @@ STATIC_ASSERT (
#define IPV6_DEFAULT_VERSION 6
#define IPV6_DEFAULT_TRAFFIC_CLASS 0
#define IPV6_DEFAULT_FLOW_LABEL 0
-#define HCIN_IP6_VERSION_TRAFFIC_FLOW \
+#define HICN_IP6_VERSION_TRAFFIC_FLOW \
(IPV6_DEFAULT_VERSION << 28) | (IPV6_DEFAULT_TRAFFIC_CLASS << 20) | \
(IPV6_DEFAULT_FLOW_LABEL & 0xfffff)
#define HICN_IP6_PROTOCOL IP_PROTOCOL_TCP
diff --git a/hicn-plugin/src/parser.h b/hicn-plugin/src/parser.h
index 5c75ce3bd..e9f709481 100644
--- a/hicn-plugin/src/parser.h
+++ b/hicn-plugin/src/parser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,95 +20,92 @@
#include "hicn.h"
#include "error.h"
+#include "infra.h"
/**
* @file parser.h
*/
-/*
- * Key type codes for header, header tlvs, body tlvs, and child tlvs
- */
-
-// FIXME(reuse lib struct, no more control ?)
-enum hicn_pkt_type_e
+always_inline int
+parse (vlib_buffer_t *pkt, uword size)
{
- HICN_PKT_TYPE_INTEREST = 0,
- HICN_PKT_TYPE_CONTENT = 1,
-};
+ if (pkt == NULL)
+ return HICN_ERROR_PARSER_PKT_INVAL;
+
+ int ret = HICN_ERROR_NONE;
+
+ hicn_lifetime_t *lifetime;
+ hicn_payload_type_t payload_type;
+
+ hicn_packet_buffer_t *pkbuf = &hicn_get_buffer (pkt)->pkbuf;
+
+ hicn_packet_set_buffer (pkbuf, vlib_buffer_get_current (pkt), size, size);
+ hicn_packet_analyze (&hicn_get_buffer (pkt)->pkbuf);
+
+ /* get lifetime*/
+ lifetime = &hicn_get_buffer (pkt)->lifetime;
+ hicn_packet_get_lifetime (pkbuf, lifetime);
+
+ if (*lifetime > hicn_main.pit_lifetime_max_ms)
+ *lifetime = hicn_main.pit_lifetime_max_ms;
+
+ /* get payload type */
+ hicn_packet_get_payload_type (pkbuf, &payload_type);
+ hicn_get_buffer (pkt)->payload_type = (u16) (payload_type);
+ return ret;
+
+#if 0
+ hicn_name_t *name; \
+
+ /* get name and name length*/
+ name = &hicn_get_buffer (pkt)->name;
+ ret = hicn_##PACKET_TYPE##_get_name (pkbuf, name);
+ if (PREDICT_FALSE (ret))
+ {
+ if (type.l2 == IPPROTO_ICMPV4 || type.l2 == IPPROTO_ICMPV6)
+ {
+ return HICN_ERROR_PARSER_MAPME_PACKET;
+ }
+ return HICN_ERROR_PARSER_PKT_INVAL;
+ }
+#endif
+}
/**
- * @brief Parse an interest packet
+ * @brief Parse a interest packet
*
* @param pkt vlib buffer holding the interest
- * @param name return variable that will point to the hicn name
- * @param namelen return valiable that will hold the length of the name
- * @param pkt_hdrp return valiable that will point to the packet header
- * @param isv6 return variable that will be equale to 1 is the header is ipv6
+ * @param name [RETURNED] variable that will point to the hicn name
+ * @param namelen [RETURNED] variable that will hold the length of the name
+ * @param port [RETURNED] variable that will hold the source port of the packet
+ * @param pkt_hdrp [RETURNED] valiable that will point to the packet header
+ * @param isv6 [RETURNED] variable that will be equale to 1 is the header is
+ * ipv6
*/
always_inline int
-hicn_interest_parse_pkt (vlib_buffer_t *pkt, hicn_name_t *name, u16 *namelen,
- hicn_header_t **pkt_hdrp, u8 *isv6)
+hicn_interest_parse_pkt (vlib_buffer_t *pkt, uword size)
{
- if (pkt == NULL)
- return HICN_ERROR_PARSER_PKT_INVAL;
- hicn_header_t *pkt_hdr = vlib_buffer_get_current (pkt);
- *pkt_hdrp = pkt_hdr;
- u8 *ip_pkt = vlib_buffer_get_current (pkt);
- *isv6 = hicn_is_v6 (pkt_hdr);
- u8 ip_proto = (*isv6) * IPPROTO_IPV6;
- u8 next_proto_offset = 6 + (1 - *isv6) * 3;
- // in the ipv6 header the next header field is at byte 6
- // in the ipv4 header the protocol field is at byte 9
- hicn_type_t type = (hicn_type_t){ { .l4 = IPPROTO_NONE,
- .l3 = IPPROTO_NONE,
- .l2 = ip_pkt[next_proto_offset],
- .l1 = ip_proto } };
- hicn_get_buffer (pkt)->type = type;
-
- hicn_ops_vft[type.l1]->get_interest_name (type, &pkt_hdr->protocol, name);
- *namelen = (1 - (*isv6)) * HICN_V4_NAME_LEN + (*isv6) * HICN_V6_NAME_LEN;
-
- return HICN_ERROR_NONE;
+ return parse (pkt, size);
}
/**
* @brief Parse a data packet
*
- * @param pkt vlib buffer holding the interest
- * @param name return variable that will point to the hicn name
- * @param namelen return valiable that will hold the length of the name
- * @param pkt_hdrp return valiable that will point to the packet header
- * @param isv6 return variable that will be equale to 1 is the header is ipv6
+ * @param pkt vlib buffer holding the data
+ * @param name [RETURNED] variable that will point to the hicn name
+ * @param namelen [RETURNED] variable that will hold the length of the name
+ * @param port [RETURNED] variable that will hold the source port of the packet
+ * @param pkt_hdrp [RETURNED] valiable that will point to the packet header
+ * @param isv6 [RETURNED] variable that will be equale to 1 is the header is
+ * ipv6
*/
always_inline int
-hicn_data_parse_pkt (vlib_buffer_t *pkt, hicn_name_t *name, u16 *namelen,
- hicn_header_t **pkt_hdrp, u8 *isv6)
+hicn_data_parse_pkt (vlib_buffer_t *pkt, uword size)
{
- if (pkt == NULL)
- return HICN_ERROR_PARSER_PKT_INVAL;
- hicn_header_t *pkt_hdr = vlib_buffer_get_current (pkt);
- *pkt_hdrp = pkt_hdr;
- *pkt_hdrp = pkt_hdr;
- u8 *ip_pkt = vlib_buffer_get_current (pkt);
- *isv6 = hicn_is_v6 (pkt_hdr);
- u8 ip_proto = (*isv6) * IPPROTO_IPV6;
- /*
- * in the ipv6 header the next header field is at byte 6 in the ipv4
- * header the protocol field is at byte 9
- */
- u8 next_proto_offset = 6 + (1 - *isv6) * 3;
- hicn_type_t type = (hicn_type_t){ { .l4 = IPPROTO_NONE,
- .l3 = IPPROTO_NONE,
- .l2 = ip_pkt[next_proto_offset],
- .l1 = ip_proto } };
- hicn_get_buffer (pkt)->type = type;
- hicn_ops_vft[type.l1]->get_data_name (type, &pkt_hdr->protocol, name);
- *namelen = (1 - (*isv6)) * HICN_V4_NAME_LEN + (*isv6) * HICN_V6_NAME_LEN;
-
- return HICN_ERROR_NONE;
+ return parse (pkt, size);
}
-#endif /* // __HICN_PARSER_H__ */
+#endif /* __HICN_PARSER_H__ */
/*
* fd.io coding-style-patch-verification: ON
diff --git a/hicn-plugin/src/pcs.c b/hicn-plugin/src/pcs.c
index d9e0baf6f..564a435a0 100644
--- a/hicn-plugin/src/pcs.c
+++ b/hicn-plugin/src/pcs.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,33 +16,39 @@
#include <stdlib.h>
#include <vlib/vlib.h>
-#include "hashtb.h"
#include "pcs.h"
#include "cache_policies/cs_lru.h"
-int
-hicn_pit_create (hicn_pit_cs_t *p, u32 num_elems)
+void
+hicn_pit_create (hicn_pit_cs_t *p, u32 max_pit_elt, u32 max_cs_elt)
{
- int ret =
- hicn_hashtb_alloc (&p->pcs_table, num_elems, sizeof (hicn_pcs_entry_t));
- p->pcs_table->ht_flags |= HICN_HASHTB_FLAG_KEY_FMT_NAME;
+ // Allocate PCS hash table. KEY=Name, VALUE=pool_idx
+ clib_bihash_24_8_t *pcs_table = &p->pcs_table;
+ u32 n_elements = max_pit_elt / BIHASH_KVP_PER_PAGE;
+ clib_bihash_init_24_8 (pcs_table, "hicn_pcs_table", n_elements, 512 << 20);
- p->pcs_pit_count = p->pcs_cs_count = 0;
+ // Allocate pool of PIT/CS entries
+ pool_alloc (p->pcs_entries_pool, max_pit_elt);
- p->policy_state.max =
- HICN_PARAM_CS_LRU_DEFAULT -
- (HICN_PARAM_CS_LRU_DEFAULT * HICN_PARAM_CS_RESERVED_APP / 100);
- p->policy_state.count = 0;
- p->policy_state.head = p->policy_state.tail = 0;
+ // Init counters
+ p->max_pit_size = max_pit_elt;
+ p->pcs_pit_count = p->pcs_cs_count = 0;
+ p->policy_state = hicn_cs_lru_create (max_cs_elt);
+ p->pcs_cs_count = 0;
+ p->pcs_pcs_alloc = 0;
+ p->pcs_pcs_dealloc = 0;
+ p->pcs_pit_count = 0;
+}
- p->policy_vft.hicn_cs_insert = hicn_cs_lru.hicn_cs_insert;
- p->policy_vft.hicn_cs_update = hicn_cs_lru.hicn_cs_update;
- p->policy_vft.hicn_cs_dequeue = hicn_cs_lru.hicn_cs_dequeue;
- p->policy_vft.hicn_cs_delete_get = hicn_cs_lru.hicn_cs_delete_get;
- p->policy_vft.hicn_cs_trim = hicn_cs_lru.hicn_cs_trim;
- p->policy_vft.hicn_cs_flush = hicn_cs_lru.hicn_cs_flush;
+void
+hicn_pit_destroy (hicn_pit_cs_t *p)
+{
+ // Deallocate PCS hash table.
+ clib_bihash_24_8_t *pcs_table = &p->pcs_table;
+ clib_bihash_free_24_8 (pcs_table);
- return (ret);
+ // Deallocate pool of PIT/CS entries
+ pool_free (p->pcs_entries_pool);
}
/*
diff --git a/hicn-plugin/src/pcs.h b/hicn-plugin/src/pcs.h
index 083efa901..2019ddb73 100644
--- a/hicn-plugin/src/pcs.h
+++ b/hicn-plugin/src/pcs.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,25 +16,34 @@
#ifndef __HICN_PCS_H__
#define __HICN_PCS_H__
-#include "hashtb.h"
-#include "face_db.h"
#include "strategy_dpo_manager.h"
#include "error.h"
#include "cache_policies/cs_policy.h"
#include "faces/face.h"
+#include <vppinfra/bihash_24_8.h>
+
/**
* @file pcs.h
*
* This file implement the PIT and CS which are collapsed in the same
- * structure, thereore an entry is either a PIT entry of a CS entry.
- * The implementation consist of a hash table where each entry of the
- * hash table contains a PIT or CS entry, some counters to maintain the
- * status of the PIT/CS and the reference to the eviction policy for
- * the CS. The default eviction policy id FIFO.
+ * structure, therefore an entry is either a PIT entry of a CS entry.
+ * The implementation consists of a hash table where each entry of the
+ * hash table contains an index to a pool of PIT/CS entries. Each entry
+ * contains some counters to maintain the status of the PIT/CS and the
+ * reference to the eviction policy for the CS.
+ * The default eviction policy is LRU.
*/
-/* The PIT and CS are stored as a union */
+/*
+ * We need a definition of invalid index. ~0 is reasonable as we don't expect
+ * to reach that many element in the PIT.
+ */
+#define HICN_PCS_INVALID_INDEX ((u32) (~0))
+
+/*
+ * The PIT and CS are stored as a union
+ */
#define HICN_PIT_NULL_TYPE 0
#define HICN_PIT_TYPE 1
#define HICN_CS_TYPE 2
@@ -49,778 +58,769 @@
#define HICN_INFRA_SLOW_TIMER_SECS 60
#define HICN_INFRA_SLOW_TIMER_MSECS (HICN_INFRA_SLOW_TIMER_SECS * SEC_MS)
+#define HICN_CS_ENTRY_OPAQUE_SIZE 32
+
+#define HICN_FACE_DB_INLINE_FACES 8
+
+#define HICN_PIT_BITMAP_SIZE_U64 HICN_PARAM_FACES_MAX / 64
+#define HICN_PIT_N_HOP_BITMAP_SIZE HICN_PARAM_FACES_MAX
+
/*
- * Note that changing this may change alignment within the PIT struct, so be
- * careful.
+ * PCS entry. We expect this to fit in 3 cache lines, with a maximum of 8
+ * output inline faces and a bitmap of 512 bits. If more faces are needed, a
+ * vector will be allocated, but it will endup out of the 3 cache lines.
*/
-typedef struct __attribute__ ((packed)) hicn_pcs_shared_s
+typedef struct hicn_pcs_entry_s
{
+ /*
+ * First cache line - shared data
+ */
+ CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
- /* Installation/creation time (vpp float units, for now) */
+ /*
+ * Installation/creation time (vpp float units, for now).
+ * 8 Bytes
+ */
f64 create_time;
- /* Expiration time (vpp float units, for now) */
+ /*
+ * Expiration time (vpp float units, for now)
+ * 8 Bytes
+ */
f64 expire_time;
- /* Shared 'flags' octet */
- u8 entry_flags;
-
- /* Needed to align for the pit or cs portion */
- u8 padding;
-} hicn_pcs_shared_t;
-
-#define HICN_PCS_ENTRY_CS_FLAG 0x01
+ /*
+ * Name
+ * 24 bytes
+ */
+ hicn_name_t name;
-/*
- * PIT entry, unioned with a CS entry below
- */
-typedef struct __attribute__ ((packed)) hicn_pit_entry_s
-{
+ /*
+ * Cached hash of the name
+ * 8 bytes
+ */
+ u64 name_hash;
- /* Shared size 8 + 8 + 2 = 18B */
+ /*
+ * Shared 'flags' octet
+ * 1 Byte
+ */
+ u16 flags;
/*
- * Egress next hop (containes the egress face) This id refers to the
- * position of the choosen face in the next_hops array of the dpo */
- /* 18B + 1B = 19B */
- u8 pe_txnh;
+ * Number of locks on the PCS entry
+ * 2 Bytes
+ */
+ u16 locks;
- /* Array of incoming ifaces */
- /* 24B + 32B (8B*4) =56B */
- hicn_face_db_t faces;
+ /*
+ * Second cache line - PIT or CS data
+ */
+ CLIB_ALIGN_MARK (second_part, 64);
-} hicn_pit_entry_t;
+ union
+ {
+ struct
+ {
+ /*
+ * Bitmap used to check if interests are retransmission
+ */
+ u64 bitmap[HICN_PIT_BITMAP_SIZE_U64];
-#define HICN_CS_ENTRY_OPAQUE_SIZE HICN_HASH_NODE_APP_DATA_SIZE - 36
+ CLIB_ALIGN_MARK (third_part, 64);
-/*
- * CS entry, unioned with a PIT entry below
- */
-typedef struct __attribute__ ((packed)) hicn_cs_entry_s
-{
- /* 18B + 2B = 20B */
- u16 align;
+ /*
+ * Total number of faces
+ */
+ u32 n_faces;
- /* Packet buffer, if held */
- /* 20B + 4B = 24B */
- u32 cs_pkt_buf;
+ /*
+ * Array of indexes of virtual faces
+ */
+ hicn_face_id_t inline_faces[HICN_FACE_DB_INLINE_FACES];
- /* Ingress face */
- /* 24B + 4B = 28B */
- hicn_face_id_t cs_rxface;
+ /*
+ * VPP vector of indexes of additional virtual faces, allocated iff
+ * needed
+ */
+ hicn_face_id_t *faces;
+ } pit;
+ struct
+ { /*
+ * Packet buffer, if held
+ * 4 Bytes
+ */
+ u32 cs_pkt_buf;
- /* Linkage for LRU, in the form of hashtable node indexes */
- /* 28B + 8B = 36B */
- u32 cs_lru_prev;
- u32 cs_lru_next;
+ /*
+ * Linkage for LRU, in the form of hashtable node indexes
+ * 8 Bytes
+ */
+ u32 cs_lru_prev;
+ u32 cs_lru_next;
+ } cs;
+ } u;
+} hicn_pcs_entry_t;
- /* Reserved for implementing cache policy different than LRU */
- /* 36B + (64 - 36)B = 64B */
- u8 opaque[HICN_CS_ENTRY_OPAQUE_SIZE];
+STATIC_ASSERT (sizeof (hicn_pcs_entry_t) <= 3 * CLIB_CACHE_LINE_BYTES,
+ "hicn_pcs_entry_t does not fit in 3 cache lines.");
+
+STATIC_ASSERT (0 == offsetof (hicn_pcs_entry_t, cacheline0),
+ "Cacheline0 must be at the beginning of hicn_pcs_entry_t");
+STATIC_ASSERT (64 == offsetof (hicn_pcs_entry_t, second_part),
+ "second_part must be at byte 64 of hicn_pcs_entry_t");
+STATIC_ASSERT (64 == offsetof (hicn_pcs_entry_t, u.pit.bitmap),
+ "u.pit.bitmap must be at byte 64 of hicn_pcs_entry_t");
+STATIC_ASSERT (64 == offsetof (hicn_pcs_entry_t, u.pit.bitmap),
+ "cs_pkt_buf must be at byte 64 of hicn_pcs_entry_t");
+STATIC_ASSERT (128 == offsetof (hicn_pcs_entry_t, u.pit.third_part),
+ "third_part must be at byte 128 of hicn_pcs_entry_t");
+STATIC_ASSERT (128 == offsetof (hicn_pcs_entry_t, u.pit.n_faces),
+ "u.pit.n_faces must be at byte 128 of hicn_pcs_entry_t");
-} __attribute__ ((packed)) hicn_cs_entry_t;
+#define HICN_PCS_ENTRY_CS_FLAG 0x01
/*
- * Combined PIT/CS entry data structure, embedded in a hashtable entry after
- * the common hashtable preamble struct. This MUST fit in the available
- * (fixed) space in a hashtable node.
+ * Forward declarations
*/
-typedef struct hicn_pcs_entry_s
-{
+always_inline void hicn_pcs_delete_internal (hicn_pit_cs_t *pitcs,
+ hicn_pcs_entry_t *pcs_entry);
- hicn_pcs_shared_t shared;
-
- union
- {
- hicn_pit_entry_t pit;
- hicn_cs_entry_t cs;
- } u;
-} hicn_pcs_entry_t;
+always_inline void hicn_pcs_entry_remove_lock (hicn_pit_cs_t *pitcs,
+ hicn_pcs_entry_t *pcs_entry);
/*
- * Overall PIT/CS table, based on the common hashtable
+ * Overall PIT/CS table.
*/
typedef struct hicn_pit_cs_s
{
+ // Hash table mapping name to hash entry index
+ clib_bihash_24_8_t pcs_table;
+
+ // Total size of PCS
+ u32 max_pit_size;
- hicn_hashtb_t *pcs_table;
+ // Pool of pcs entries
+ hicn_pcs_entry_t *pcs_entries_pool;
/* Counters for PIT/CS sentries */
u32 pcs_pit_count;
u32 pcs_cs_count;
- u32 pcs_cs_dealloc;
- u32 pcs_pit_dealloc;
-
- /* Total size of PCS */
- u32 pcs_size;
+ u32 pcs_pcs_alloc;
+ u32 pcs_pcs_dealloc;
hicn_cs_policy_t policy_state;
- hicn_cs_policy_vft_t policy_vft;
-
} hicn_pit_cs_t;
-/* Functions declarations */
-int hicn_pit_create (hicn_pit_cs_t *p, u32 num_elems);
-
-always_inline void hicn_pit_to_cs (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *pcs_entry,
- hicn_hash_entry_t *hash_entry,
- hicn_hash_node_t *node,
- const hicn_dpo_vft_t *dpo_vft,
- dpo_id_t *hicn_dpo_id,
- hicn_face_id_t inface_id, u8 is_appface);
-
-always_inline void hicn_pcs_cs_update (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *old_entry,
- hicn_pcs_entry_t *entry,
- hicn_hash_node_t *node);
-
-always_inline void hicn_pcs_cs_delete (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t **pcs_entry,
- hicn_hash_node_t **node,
- hicn_hash_entry_t *hash_entry,
- const hicn_dpo_vft_t *dpo_vft,
- dpo_id_t *hicn_dpo_id);
-
-always_inline int
-hicn_pcs_cs_insert (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *entry, hicn_hash_node_t *node,
- hicn_hash_entry_t **hash_entry, u64 hashval, u32 *node_id,
- index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs,
- u8 *hash_entry_id, u32 *bucket_id, u8 *bucket_is_overflow);
-
-always_inline int hicn_pcs_cs_insert_update (
- vlib_main_t *vm, hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry,
- hicn_hash_node_t *node, hicn_hash_entry_t **hash_entry, u64 hashval,
- u32 *node_id, index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs, u8 *hash_entry_id,
- u32 *bucket_id, u8 *bucket_is_overflow, hicn_face_id_t inface);
-
-always_inline int
-hicn_pcs_pit_insert (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry,
- hicn_hash_node_t *node, hicn_hash_entry_t **hash_entry,
- u64 hashval, u32 *node_id, index_t *dpo_ctx_id,
- u8 *vft_id, u8 *is_cs, u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow);
-
-always_inline void
-hicn_pcs_pit_delete (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_node_t **node, vlib_main_t *vm,
- hicn_hash_entry_t *hash_entry,
- const hicn_dpo_vft_t *dpo_vft, dpo_id_t *hicn_dpo_id);
-
-always_inline int hicn_pcs_insert (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *entry,
- hicn_hash_node_t *node,
- hicn_hash_entry_t **hash_entry, u64 hashval,
- u32 *node_id, index_t *dpo_ctx_id,
- u8 *vft_id, u8 *is_cs, u8 *hash_entry_id,
- u32 *bucket_id, u8 *bucket_is_overflow);
-
-always_inline void hicn_pcs_delete (hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_node_t **node, vlib_main_t *vm,
- hicn_hash_entry_t *hash_entry,
- const hicn_dpo_vft_t *dpo_vft,
- dpo_id_t *hicn_dpo_id);
+/************************************************************************
+ **************************** Create / Destroy **************************
+ ************************************************************************/
-always_inline void
-hicn_pcs_remove_lock (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_node_t **node, vlib_main_t *vm,
- hicn_hash_entry_t *hash_entry,
- const hicn_dpo_vft_t *dpo_vft, dpo_id_t *hicn_dpo_id);
+void hicn_pit_create (hicn_pit_cs_t *p, u32 max_pit_elt, u32 max_cs_elt);
+void hicn_pit_destroy (hicn_pit_cs_t *p);
-always_inline void hicn_cs_delete_trimmed (hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_entry_t *hash_entry,
- hicn_hash_node_t **node,
- vlib_main_t *vm);
+/************************************************************************
+ **************************** Counters getters **************************
+ ************************************************************************/
-/* Function implementation */
-/* Accessor for pit/cs data inside hash table node */
-static inline hicn_pcs_entry_t *
-hicn_pit_get_data (hicn_hash_node_t *node)
+always_inline u32
+hicn_pcs_get_pit_count (const hicn_pit_cs_t *pcs)
{
- return (hicn_pcs_entry_t *) (hicn_hashtb_node_data (node));
+ return pcs->pcs_pit_count;
}
-/* Init pit/cs data block (usually inside hash table node) */
-static inline void
-hicn_pit_init_data (hicn_pcs_entry_t *p)
+always_inline u32
+hicn_pcs_get_cs_count (const hicn_pit_cs_t *pcs)
{
- p->shared.entry_flags = 0;
- p->u.pit.faces.n_faces = 0;
- p->u.pit.faces.is_overflow = 0;
- hicn_face_bucket_t *face_bkt;
- pool_get (hicn_face_bucket_pool, face_bkt);
+ return pcs->pcs_cs_count;
+}
- p->u.pit.faces.next_bucket = face_bkt - hicn_face_bucket_pool;
+always_inline u32
+hicn_pcs_get_pcs_alloc (const hicn_pit_cs_t *pcs)
+{
+ return pcs->pcs_pcs_alloc;
}
-/* Init pit/cs data block (usually inside hash table node) */
-static inline void
-hicn_cs_init_data (hicn_pcs_entry_t *p)
+always_inline u32
+hicn_pcs_get_pcs_dealloc (const hicn_pit_cs_t *pcs)
{
- p->shared.entry_flags = 0;
- p->u.pit.faces.n_faces = 0;
- p->u.pit.faces.is_overflow = 0;
+ return pcs->pcs_pcs_dealloc;
}
-static inline f64
+always_inline f64
hicn_pcs_get_exp_time (f64 cur_time_sec, u64 lifetime_msec)
{
return (cur_time_sec + ((f64) lifetime_msec) / SEC_MS);
}
/*
- * Configure CS LRU limit. Zero is accepted, means 'no limit', probably not a
- * good choice.
+ * Create key from the name struct.
*/
-static inline void
-hicn_pit_set_lru_max (hicn_pit_cs_t *p, u32 limit)
+always_inline void
+hicn_pcs_get_key_from_name (clib_bihash_kv_24_8_t *kv, const hicn_name_t *name)
{
- p->policy_state.max = limit;
+ kv->key[0] = name->prefix.v6.as_u64[0];
+ kv->key[1] = name->prefix.v6.as_u64[1];
+ kv->key[2] = name->suffix;
+}
+
+/************************************************************************
+ **************************** LRU Helpers *******************************
+ ************************************************************************/
+
+always_inline hicn_cs_policy_t *
+hicn_pcs_get_policy_state (hicn_pit_cs_t *pcs)
+{
+ return &pcs->policy_state;
}
/*
- * Accessor for PIT interest counter.
+ * Update the CS LRU, moving this item to the head
*/
-static inline u32
-hicn_pit_get_int_count (const hicn_pit_cs_t *pitcs)
+always_inline void
+hicn_pcs_cs_update_lru (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry)
{
- return (pitcs->pcs_pit_count);
+ hicn_cs_policy_t *policy_state = hicn_pcs_get_policy_state (pitcs);
+ hicn_cs_policy_update (policy_state, pitcs, entry);
}
/*
- * Accessor for PIT cs entries counter.
+ * Update the CS LRU, inserting a new item and checking if we need to evict
*/
-static inline u32
-hicn_pit_get_cs_count (const hicn_pit_cs_t *pitcs)
+always_inline void
+hicn_pcs_cs_insert_lru (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry)
{
- return (pitcs->pcs_cs_count);
+ hicn_cs_policy_t *policy_state = hicn_pcs_get_policy_state (pitcs);
+ hicn_cs_policy_insert (policy_state, pitcs, entry);
+ pitcs->pcs_cs_count++;
+
+ // If we reached the MAX size of the CS, let's evict one
+ if (policy_state->count > policy_state->max)
+ {
+ // We reached the mac number of CS entry. We need to trim one.
+ hicn_pcs_entry_t *pcs_entry;
+ hicn_cs_policy_delete_get (policy_state, pitcs, &pcs_entry);
+
+ // Delete evicted entry from hash table
+ hicn_pcs_entry_remove_lock (pitcs, pcs_entry);
+ }
}
-static inline u32
-hicn_pcs_get_ntw_count (const hicn_pit_cs_t *pitcs)
+/*
+ * Dequeue an entry from the CS LRU
+ */
+always_inline void
+hicn_pcs_cs_dequeue_lru (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry)
{
- return (pitcs->policy_state.count);
+ // Dequeue the CS entry
+ hicn_cs_policy_t *policy_state = hicn_pcs_get_policy_state (pitcs);
+ hicn_cs_policy_dequeue (policy_state, pitcs, entry);
}
-static inline u32
-hicn_pit_get_htb_bucket_count (const hicn_pit_cs_t *pitcs)
+/************************************************************************
+ **************************** PCS Entry APIs ****************************
+ ************************************************************************/
+
+/*
+ * Create new PCS entry
+ */
+always_inline hicn_pcs_entry_t *
+_hicn_pcs_entry_get (hicn_pit_cs_t *pitcs)
{
- return (pitcs->pcs_table->ht_overflow_buckets_used);
+ hicn_pcs_entry_t *e;
+ pool_get (pitcs->pcs_entries_pool, e);
+ pitcs->pcs_pcs_alloc++;
+
+ return e;
}
-static inline int
-hicn_cs_enabled (hicn_pit_cs_t *pit)
+/*
+ * Init pit/cs data block
+ */
+always_inline void
+hicn_pcs_entry_init_data (hicn_pcs_entry_t *p, f64 tnow)
{
- switch (HICN_FEATURE_CS)
- {
- case 0:
- default:
- return (0);
- case 1:
- return (pit->policy_state.max > 0);
- }
+ p->flags = 0;
+ p->u.pit.n_faces = 0;
+ p->locks = 1;
+ p->create_time = tnow;
}
/*
- * Delete a PIT/CS entry from the hashtable, freeing the hash node struct.
- * The caller's pointers are zeroed! If cs_trim is true, entry has already
- * been removed from lru list The main purpose of this wrapper is helping
- * maintain the per-PIT stats.
+ * Free PCS entry
*/
always_inline void
-hicn_pcs_delete_internal (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_entry_t *hash_entry,
- hicn_hash_node_t **node, vlib_main_t *vm,
- const hicn_dpo_vft_t *dpo_vft, dpo_id_t *hicn_dpo_id)
+hicn_pcs_entry_put (hicn_pit_cs_t *pitcs, const hicn_pcs_entry_t *entry)
{
- hicn_pcs_entry_t *pcs = *pcs_entryp;
+ pitcs->pcs_pcs_dealloc++;
+ pool_put (pitcs->pcs_entries_pool, entry);
+}
- ASSERT (pcs == hicn_hashtb_node_data (*node));
+/*
+ * Get index from the entry.
+ */
+always_inline u32
+hicn_pcs_entry_get_index (const hicn_pit_cs_t *pitcs,
+ const hicn_pcs_entry_t *entry)
+{
+ ASSERT (!pool_is_free (pitcs->pcs_entries_pool, entry));
+ return (u32) (entry - pitcs->pcs_entries_pool);
+}
- if (hash_entry->he_flags & HICN_HASH_ENTRY_FLAG_CS_ENTRY)
- {
- pitcs->pcs_cs_dealloc++;
- /* Free any associated packet buffer */
- vlib_buffer_free_one (vm, pcs->u.cs.cs_pkt_buf);
- pcs->u.cs.cs_pkt_buf = ~0;
- ASSERT ((pcs->u.cs.cs_lru_prev == 0) &&
- (pcs->u.cs.cs_lru_prev == pcs->u.cs.cs_lru_next));
- }
- else
- {
- pitcs->pcs_pit_dealloc++;
- hicn_strategy_dpo_ctx_unlock (hicn_dpo_id);
+/*
+ * Get index from the entry.
+ */
+always_inline hicn_pcs_entry_t *
+hicn_pcs_entry_get_entry_from_index (const hicn_pit_cs_t *pitcs, u32 index)
+{
+ ASSERT (!pool_is_free_index (pitcs->pcs_entries_pool, index));
+ return pool_elt_at_index (pitcs->pcs_entries_pool, index);
+}
- /* Flush faces */
- hicn_faces_flush (&(pcs->u.pit.faces));
- }
+always_inline hicn_pcs_entry_t *
+hicn_pcs_entry_get_entry_from_index_safe (const hicn_pit_cs_t *pitcs,
+ u32 index)
+{
+ if (!pool_is_free_index (pitcs->pcs_entries_pool, index))
+ return pool_elt_at_index (pitcs->pcs_entries_pool, index);
- hicn_hashtb_delete (pitcs->pcs_table, node, hash_entry->he_msb64);
- *pcs_entryp = NULL;
+ return NULL;
}
/*
- * Convert a PIT entry into a CS entry (assumes that the entry is already in
- * the hashtable.) This is primarily here to maintain the internal counters.
+ * Check if pcs entry is a content store entry
*/
-always_inline void
-hicn_pit_to_cs (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *pcs_entry, hicn_hash_entry_t *hash_entry,
- hicn_hash_node_t *node, const hicn_dpo_vft_t *dpo_vft,
- dpo_id_t *hicn_dpo_id, hicn_face_id_t inface_id, u8 is_appface)
+always_inline int
+hicn_pcs_entry_is_cs (const hicn_pcs_entry_t *entry)
{
+ ASSERT (entry);
+ return (entry->flags & HICN_PCS_ENTRY_CS_FLAG);
+}
- /*
- * Different from the insert node. In here we don't need to add a new
- * hash entry.
- */
- pitcs->pcs_pit_count--;
- hicn_strategy_dpo_ctx_unlock (hicn_dpo_id);
- /* Flush faces */
- hicn_faces_flush (&(pcs_entry->u.pit.faces));
+/*
+ * Add lock to PIT entry
+ */
+always_inline void
+hicn_pcs_entry_add_lock (hicn_pcs_entry_t *pcs_entry)
+{
+ pcs_entry->locks++;
+}
- hash_entry->he_flags |= HICN_HASH_ENTRY_FLAG_CS_ENTRY;
- node->hn_flags |= HICN_HASH_NODE_CS_FLAGS;
- pcs_entry->shared.entry_flags |= HICN_PCS_ENTRY_CS_FLAG;
+/*
+ * Get/Set expire time from the entry
+ */
+always_inline f64
+hicn_pcs_entry_get_expire_time (hicn_pcs_entry_t *pcs_entry)
+{
+ return pcs_entry->expire_time;
+}
- pcs_entry->u.cs.cs_rxface = inface_id;
+always_inline void
+hicn_pcs_entry_set_expire_time (hicn_pcs_entry_t *pcs_entry, f64 expire_time)
+{
+ pcs_entry->expire_time = expire_time;
+}
- /* Update the CS according to the policy */
- hicn_cs_policy_t *policy_state;
- hicn_cs_policy_vft_t *policy_vft;
+/*
+ * Get/Set create time from the entry
+ */
+always_inline f64
+hicn_pcs_entry_get_create_time (hicn_pcs_entry_t *pcs_entry)
+{
+ return pcs_entry->create_time;
+}
- policy_state = &pitcs->policy_state;
- policy_vft = &pitcs->policy_vft;
+always_inline void
+hicn_pcs_entry_set_create_time (hicn_pcs_entry_t *pcs_entry, f64 create_time)
+{
+ pcs_entry->create_time = create_time;
+}
- policy_vft->hicn_cs_insert (pitcs, node, pcs_entry, policy_state);
- pitcs->pcs_cs_count++;
+/*
+ * Remove a lock in the entry and delete it if there are no pending lock and
+ * the entry is marked as to be deleted
+ */
+always_inline void
+hicn_pcs_entry_remove_lock (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *pcs_entry)
+{
+ // Make sure we are removing a lock on a valid entry
+ ASSERT (pcs_entry->locks > 0);
- if (policy_state->count > policy_state->max)
+ if (--pcs_entry->locks == 0)
{
- hicn_hash_node_t *node;
- hicn_pcs_entry_t *pcs_entry;
- hicn_hash_entry_t *hash_entry;
- policy_vft->hicn_cs_delete_get (pitcs, policy_state, &node, &pcs_entry,
- &hash_entry);
-
- /*
- * We don't have to decrease the lock (therefore we cannot
- * use hicn_pcs_cs_delete function)
- */
- policy_vft->hicn_cs_dequeue (pitcs, node, pcs_entry, policy_state);
-
- hicn_cs_delete_trimmed (pitcs, &pcs_entry, hash_entry, &node, vm);
-
- /* Update the global CS counter */
- pitcs->pcs_cs_count--;
+ hicn_pcs_delete_internal (pitcs, pcs_entry);
}
}
-/* Functions specific for PIT or CS */
+/************************************************************************
+ **************************** CS Entry APIs *****************************
+ ************************************************************************/
-always_inline void
-hicn_pcs_cs_update (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *old_entry, hicn_pcs_entry_t *entry,
- hicn_hash_node_t *node)
+/*
+ * Create new CS entry
+ */
+always_inline hicn_pcs_entry_t *
+hicn_pcs_entry_cs_get (hicn_pit_cs_t *pitcs, f64 tnow, u32 buffer_index)
{
- hicn_cs_policy_t *policy_state;
- hicn_cs_policy_vft_t *policy_vft;
+ hicn_pcs_entry_t *ret = _hicn_pcs_entry_get (pitcs);
+ hicn_pcs_entry_init_data (ret, tnow);
+ ret->flags = HICN_PCS_ENTRY_CS_FLAG;
+ ret->u.cs.cs_lru_next = HICN_CS_POLICY_END_OF_CHAIN;
+ ret->u.cs.cs_lru_prev = HICN_CS_POLICY_END_OF_CHAIN;
- policy_state = &pitcs->policy_state;
- policy_vft = &pitcs->policy_vft;
+ return ret;
+}
- if (entry->u.cs.cs_rxface != old_entry->u.cs.cs_rxface)
- {
- /* Dequeue content from the old queue */
- policy_vft->hicn_cs_dequeue (pitcs, node, old_entry, policy_state);
-
- old_entry->u.cs.cs_rxface = entry->u.cs.cs_rxface;
- policy_state = &pitcs->policy_state;
- policy_vft = &pitcs->policy_vft;
-
- policy_vft->hicn_cs_insert (pitcs, node, old_entry, policy_state);
-
- if (policy_state->count > policy_state->max)
- {
- hicn_hash_node_t *node;
- hicn_pcs_entry_t *pcs_entry;
- hicn_hash_entry_t *hash_entry;
- policy_vft->hicn_cs_delete_get (pitcs, policy_state, &node,
- &pcs_entry, &hash_entry);
-
- /*
- * We don't have to decrease the lock (therefore we cannot
- * use hicn_pcs_cs_delete function)
- */
- policy_vft->hicn_cs_dequeue (pitcs, node, pcs_entry, policy_state);
-
- hicn_cs_delete_trimmed (pitcs, &pcs_entry, hash_entry, &node, vm);
-
- /* Update the global CS counter */
- pitcs->pcs_cs_count--;
- }
- }
- else
- /* Update the CS LRU, moving this item to the head */
- policy_vft->hicn_cs_update (pitcs, node, old_entry, policy_state);
+always_inline u32
+hicn_pcs_entry_cs_get_buffer (hicn_pcs_entry_t *pcs_entry)
+{
+ return pcs_entry->u.cs.cs_pkt_buf;
}
always_inline void
-hicn_pcs_cs_delete (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t **pcs_entryp, hicn_hash_node_t **nodep,
- hicn_hash_entry_t *hash_entry,
- const hicn_dpo_vft_t *dpo_vft, dpo_id_t *hicn_dpo_id)
+hicn_pcs_entry_cs_set_buffer (hicn_pcs_entry_t *pcs_entry, u32 buffer_index)
{
- if (!(hash_entry->he_flags & HICN_HASH_ENTRY_FLAG_DELETED))
- {
- hicn_cs_policy_t *policy_state;
- hicn_cs_policy_vft_t *policy_vft;
+ pcs_entry->u.cs.cs_pkt_buf = buffer_index;
+}
- policy_state = &pitcs->policy_state;
- policy_vft = &pitcs->policy_vft;
+always_inline u32
+hicn_pcs_entry_cs_get_next (hicn_pcs_entry_t *pcs_entry)
+{
+ return pcs_entry->u.cs.cs_lru_next;
+}
- policy_vft->hicn_cs_dequeue (pitcs, (*nodep), (*pcs_entryp),
- policy_state);
+always_inline void
+hicn_pcs_entry_cs_set_next (hicn_pcs_entry_t *pcs_entry, u32 next)
+{
+ pcs_entry->u.cs.cs_lru_next = next;
+}
- /* Update the global CS counter */
- pitcs->pcs_cs_count--;
- }
+always_inline u32
+hicn_pcs_entry_cs_get_prev (hicn_pcs_entry_t *pcs_entry)
+{
+ return pcs_entry->u.cs.cs_lru_prev;
+}
- /* A data could have been inserted in the CS through a push. In this case
- * locks == 0 */
- hash_entry->locks--;
- if (hash_entry->locks == 0)
- {
- hicn_pcs_delete_internal (pitcs, pcs_entryp, hash_entry, nodep, vm,
- dpo_vft, hicn_dpo_id);
- }
- else
- {
- hash_entry->he_flags |= HICN_HASH_ENTRY_FLAG_DELETED;
- }
+always_inline void
+hicn_pcs_entry_cs_set_prev (hicn_pcs_entry_t *pcs_entry, u32 prev)
+{
+ pcs_entry->u.cs.cs_lru_prev = prev;
}
-always_inline int
-hicn_pcs_cs_insert (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *entry, hicn_hash_node_t *node,
- hicn_hash_entry_t **hash_entry, u64 hashval, u32 *node_id,
- index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs,
- u8 *hash_entry_id, u32 *bucket_id, u8 *bucket_is_overflow)
+/* Init pit/cs data block (usually inside hash table node) */
+always_inline void
+hicn_pcs_entry_cs_free_data (hicn_pcs_entry_t *p)
{
- ASSERT (entry == hicn_hashtb_node_data (node));
+ CLIB_UNUSED (u32 bi) = hicn_pcs_entry_cs_get_buffer (p);
- int ret = hicn_hashtb_insert (pitcs->pcs_table, node, hash_entry, hashval,
- node_id, dpo_ctx_id, vft_id, is_cs,
- hash_entry_id, bucket_id, bucket_is_overflow);
+#ifndef HICN_PCS_TESTING
+ // Release buffer
+ vlib_buffer_free_one (vlib_get_main (), bi);
+#endif
- if (PREDICT_TRUE (ret == HICN_ERROR_NONE))
- {
- /* Mark the entry as a CS entry */
- node->hn_flags |= HICN_HASH_NODE_CS_FLAGS;
- entry->shared.entry_flags |= HICN_PCS_ENTRY_CS_FLAG;
- (*hash_entry)->he_flags |= HICN_HASH_ENTRY_FLAG_CS_ENTRY;
-
- hicn_cs_policy_t *policy_state;
- hicn_cs_policy_vft_t *policy_vft;
-
- policy_state = &pitcs->policy_state;
- policy_vft = &pitcs->policy_vft;
-
- policy_vft->hicn_cs_insert (pitcs, node, entry, policy_state);
- pitcs->pcs_cs_count++;
-
- if (policy_state->count > policy_state->max)
- {
- hicn_hash_node_t *node;
- hicn_pcs_entry_t *pcs_entry;
- hicn_hash_entry_t *hash_entry;
- policy_vft->hicn_cs_delete_get (pitcs, policy_state, &node,
- &pcs_entry, &hash_entry);
-
- /*
- * We don't have to decrease the lock (therefore we cannot
- * use hicn_pcs_cs_delete function)
- */
- policy_vft->hicn_cs_dequeue (pitcs, node, pcs_entry, policy_state);
-
- hicn_cs_delete_trimmed (pitcs, &pcs_entry, hash_entry, &node, vm);
-
- /* Update the global CS counter */
- pitcs->pcs_cs_count--;
- }
- }
- return ret;
+ // Reset the vlib_buffer index
+ hicn_pcs_entry_cs_set_buffer (p, ~0);
}
+/************************************************************************
+ **************************** PIT Entry APIs ****************************
+ ************************************************************************/
+
/*
- * Insert CS entry into the hashtable The main purpose of this wrapper is
- * helping maintain the per-PIT stats.
+ * Init pit/cs data block
*/
-always_inline int
-hicn_pcs_cs_insert_update (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *entry, hicn_hash_node_t *node,
- hicn_hash_entry_t **hash_entry, u64 hashval,
- u32 *node_id, index_t *dpo_ctx_id, u8 *vft_id,
- u8 *is_cs, u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow, hicn_face_id_t inface)
+always_inline hicn_pcs_entry_t *
+hicn_pcs_entry_pit_get (hicn_pit_cs_t *pitcs, f64 tnow,
+ hicn_lifetime_t lifetime)
{
- int ret;
-
- ASSERT (entry == hicn_hashtb_node_data (node));
+ hicn_pcs_entry_t *ret = _hicn_pcs_entry_get (pitcs);
+ hicn_pcs_entry_init_data (ret, tnow);
+ clib_memset_u64 (ret->u.pit.bitmap, 0, HICN_PIT_BITMAP_SIZE_U64);
+ ret->u.pit.n_faces = 0;
+ ret->expire_time = hicn_pcs_get_exp_time (tnow, lifetime);
- entry->u.cs.cs_rxface = inface;
- ret = hicn_pcs_cs_insert (vm, pitcs, entry, node, hash_entry, hashval,
- node_id, dpo_ctx_id, vft_id, is_cs, hash_entry_id,
- bucket_id, bucket_is_overflow);
-
- /* A content already exists in CS with the same name */
- if (ret == HICN_ERROR_HASHTB_EXIST && *is_cs)
- {
- /* Update the entry */
- hicn_hash_node_t *existing_node =
- hicn_hashtb_node_from_idx (pitcs->pcs_table, *node_id);
- hicn_pcs_entry_t *pitp = hicn_pit_get_data (existing_node);
-
- /* Free associated packet buffer and update counter */
- pitcs->pcs_cs_dealloc++;
- vlib_buffer_free_one (vm, pitp->u.cs.cs_pkt_buf);
-
- pitp->shared.create_time = entry->shared.create_time;
- pitp->shared.expire_time = entry->shared.expire_time;
- pitp->u.cs.cs_pkt_buf = entry->u.cs.cs_pkt_buf;
+ return ret;
+}
- hicn_pcs_cs_update (vm, pitcs, pitp, entry, existing_node);
- }
+/*
+ * Free pit/cs data block
+ */
+always_inline void
+hicn_pcs_entry_pit_free_data (hicn_pcs_entry_t *p)
+{
+ // Nothing to do for the moment
+}
- return (ret);
+always_inline u32
+hicn_pcs_entry_pit_get_n_faces (hicn_pcs_entry_t *p)
+{
+ return p->u.pit.n_faces;
}
/*
- * Insert PIT entry into the hashtable The main purpose of this wrapper is
- * helping maintain the per-PIT stats.
+ * Get face id at index index
*/
-always_inline int
-hicn_pcs_pit_insert (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry,
- hicn_hash_node_t *node, hicn_hash_entry_t **hash_entry,
- u64 hashval, u32 *node_id, index_t *dpo_ctx_id,
- u8 *vft_id, u8 *is_cs, u8 *hash_entry_id, u32 *bucket_id,
- u8 *bucket_is_overflow)
+always_inline hicn_face_id_t
+hicn_pcs_entry_pit_get_dpo_face (const hicn_pcs_entry_t *pit_entry, u32 index)
{
- ASSERT (entry == hicn_hashtb_node_data (node));
-
- int ret = hicn_hashtb_insert (pitcs->pcs_table, node, hash_entry, hashval,
- node_id, dpo_ctx_id, vft_id, is_cs,
- hash_entry_id, bucket_id, bucket_is_overflow);
+ // Make sure the entry is PIT
+ ASSERT (!hicn_pcs_entry_is_cs (pit_entry));
- if (PREDICT_TRUE (ret == HICN_ERROR_NONE))
- pitcs->pcs_pit_count++;
+ // Make sure the index is valid
+ ASSERT (index < pit_entry->u.pit.n_faces);
- return ret;
+ if (index < HICN_FACE_DB_INLINE_FACES)
+ return pit_entry->u.pit.inline_faces[index];
+ else
+ return pit_entry->u.pit.faces[index - HICN_FACE_DB_INLINE_FACES];
}
always_inline void
-hicn_pcs_pit_delete (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_node_t **node, vlib_main_t *vm,
- hicn_hash_entry_t *hash_entry,
- const hicn_dpo_vft_t *dpo_vft, dpo_id_t *hicn_dpo_id)
+hicn_pcs_entry_pit_add_face (hicn_pcs_entry_t *pit_entry,
+ hicn_face_id_t face_id)
{
- hash_entry->locks--;
- if (hash_entry->locks == 0)
+ ASSERT (face_id < HICN_PARAM_FACES_MAX);
+
+ if (pit_entry->u.pit.n_faces < HICN_FACE_DB_INLINE_FACES)
{
- pitcs->pcs_pit_count--;
- hicn_pcs_delete_internal (pitcs, pcs_entryp, hash_entry, node, vm,
- dpo_vft, hicn_dpo_id);
+ pit_entry->u.pit.inline_faces[pit_entry->u.pit.n_faces] = face_id;
}
else
{
- hash_entry->he_flags |= HICN_HASH_ENTRY_FLAG_DELETED;
+ vec_validate_aligned (pit_entry->u.pit.faces,
+ pit_entry->u.pit.n_faces -
+ HICN_FACE_DB_INLINE_FACES,
+ CLIB_CACHE_LINE_BYTES);
+ pit_entry->u.pit
+ .faces[pit_entry->u.pit.n_faces - HICN_FACE_DB_INLINE_FACES] = face_id;
}
-}
-/* Generic functions for PIT/CS */
+ pit_entry->u.pit.n_faces++;
+
+ clib_bitmap_set_no_check (pit_entry->u.pit.bitmap, face_id, 1);
+}
/*
- * Insert PIT/CS entry into the hashtable The main purpose of this wrapper is
- * helping maintain the per-PIT stats.
+ * Search face in db
+ */
+always_inline u8
+hicn_pcs_entry_pit_search (const hicn_pcs_entry_t *pit_entry,
+ hicn_face_id_t face_id)
+{
+ ASSERT (face_id < HICN_PARAM_FACES_MAX);
+ return clib_bitmap_get_no_check ((uword *) pit_entry->u.pit.bitmap, face_id);
+}
+
+/************************************************************************
+ **************************** Lookup API ********************************
+ ************************************************************************/
+
+/**
+ * @brief Perform one lookup in the PIT/CS table using the provided name.
+ *
+ * @param pitcs the PIT/CS table
+ * @param name the name to lookup
+ * @param pcs_entry [RETURN] if the entry exists, the entry is returned
+ * @return HICN_ERROR_NONE if the entry is found, HICN_ERROR_PCS_NOT_FOUND
+ * otherwise
*/
always_inline int
-hicn_pcs_insert (vlib_main_t *vm, hicn_pit_cs_t *pitcs,
- hicn_pcs_entry_t *entry, hicn_hash_node_t *node,
- hicn_hash_entry_t **hash_entry, u64 hashval, u32 *node_id,
- index_t *dpo_ctx_id, u8 *vft_id, u8 *is_cs, u8 *hash_entry_id,
- u32 *bucket_id, u8 *bucket_is_overflow)
+hicn_pcs_lookup_one (hicn_pit_cs_t *pitcs, const hicn_name_t *name,
+ hicn_pcs_entry_t **pcs_entry)
{
int ret;
- if ((*hash_entry)->he_flags & HICN_HASH_ENTRY_FLAG_CS_ENTRY)
+ // Construct the lookup key
+ clib_bihash_kv_24_8_t kv;
+ hicn_pcs_get_key_from_name (&kv, name);
+
+ // Do a search in the has table
+ ret = clib_bihash_search_inline_24_8 (&pitcs->pcs_table, &kv);
+
+ if (PREDICT_FALSE (ret != 0))
{
- ret = hicn_pcs_cs_insert (vm, pitcs, entry, node, hash_entry, hashval,
- node_id, dpo_ctx_id, vft_id, is_cs,
- hash_entry_id, bucket_id, bucket_is_overflow);
+ *pcs_entry = NULL;
+ return HICN_ERROR_PCS_NOT_FOUND;
}
- else
+
+ // Retrieve entry from pool
+ *pcs_entry = hicn_pcs_entry_get_entry_from_index (pitcs, (u32) (kv.value));
+
+ // If the search is successful, we MUST find the entry in the pool.
+ ALWAYS_ASSERT (pcs_entry);
+
+ // If entry found and it is a CS entry, let's update the LRU
+ if (hicn_pcs_entry_is_cs (*pcs_entry))
{
- ret = hicn_pcs_pit_insert (pitcs, entry, node, hash_entry, hashval,
- node_id, dpo_ctx_id, vft_id, is_cs,
- hash_entry_id, bucket_id, bucket_is_overflow);
+ hicn_pcs_cs_update_lru (pitcs, *pcs_entry);
}
- return (ret);
+ // If the entry is found, return it
+ return HICN_ERROR_NONE;
}
+/************************************************************************
+ **************************** PCS Delete API ****************************
+ ************************************************************************/
+
/*
- * Delete entry if there are no pending lock on the entry, otherwise mark it
- * as to delete.
+ * Delete a PIT/CS entry from the hashtable.
+ * The caller's pointers are zeroed! If cs_trim is true, entry has already
+ * been removed from lru list The main purpose of this wrapper is helping
+ * maintain the per-PIT stats.
*/
always_inline void
-hicn_pcs_delete (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_node_t **nodep, vlib_main_t *vm,
- hicn_hash_entry_t *hash_entry, const hicn_dpo_vft_t *dpo_vft,
- dpo_id_t *hicn_dpo_id)
+hicn_pcs_delete_internal (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *pcs_entry)
{
- /*
- * If the entry has already been marked as deleted, it has already
- * been dequeue
- */
- if (hash_entry->he_flags & HICN_HASH_ENTRY_FLAG_CS_ENTRY)
+ if (pcs_entry->flags & HICN_PCS_ENTRY_CS_FLAG)
{
- hicn_pcs_cs_delete (vm, pitcs, pcs_entryp, nodep, hash_entry, dpo_vft,
- hicn_dpo_id);
- }
- else
- {
- hicn_pcs_pit_delete (pitcs, pcs_entryp, nodep, vm, hash_entry, dpo_vft,
- hicn_dpo_id);
- }
-}
+ // Remove entry from LRU list
+ hicn_pcs_cs_dequeue_lru (pitcs, pcs_entry);
-/*
- * Remove a lock in the entry and delete it if there are no pending lock and
- * the entry is marked as to be deleted
- */
-always_inline void
-hicn_pcs_remove_lock (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_node_t **node, vlib_main_t *vm,
- hicn_hash_entry_t *hash_entry,
- const hicn_dpo_vft_t *dpo_vft, dpo_id_t *hicn_dpo_id)
-{
- hash_entry->locks--;
- if (hash_entry->locks == 0 &&
- (hash_entry->he_flags & HICN_HASH_ENTRY_FLAG_DELETED))
- {
- hicn_pcs_delete_internal (pitcs, pcs_entryp, hash_entry, node, vm,
- dpo_vft, hicn_dpo_id);
- }
-}
+ // Update counters
+ pitcs->pcs_cs_count--;
-/*
- * Delete entry which has already been bulk-removed from lru list
- */
-always_inline void
-hicn_cs_delete_trimmed (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t **pcs_entryp,
- hicn_hash_entry_t *hash_entry, hicn_hash_node_t **node,
- vlib_main_t *vm)
-{
+ // Free data
+ hicn_pcs_entry_cs_free_data (pcs_entry);
- if (hash_entry->locks == 0)
- {
- const hicn_dpo_vft_t *dpo_vft = hicn_dpo_get_vft (hash_entry->vft_id);
- dpo_id_t hicn_dpo_id = { .dpoi_type = dpo_vft->hicn_dpo_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = hash_entry->dpo_ctx_id };
-
- hicn_pcs_delete_internal (pitcs, pcs_entryp, hash_entry, node, vm,
- dpo_vft, &hicn_dpo_id);
+ // Sanity check
+ ASSERT ((pcs_entry->u.cs.cs_lru_prev == HICN_CS_POLICY_END_OF_CHAIN) &&
+ (pcs_entry->u.cs.cs_lru_prev == pcs_entry->u.cs.cs_lru_next));
}
else
{
- hash_entry->he_flags |= HICN_HASH_ENTRY_FLAG_DELETED;
+ // Update counters
+ pitcs->pcs_pit_count--;
+ // Flush faces
+ // hicn_faces_flush (&(pcs_entry->u.pit.faces));
}
-}
-/*
- * wrappable counter math (assumed uint16_t): return sum of addends
- */
-always_inline u16
-hicn_infra_seq16_sum (u16 addend1, u16 addend2)
-{
- return (addend1 + addend2);
+ // Delete entry from hash table
+ clib_bihash_kv_24_8_t kv;
+ hicn_pcs_get_key_from_name (&kv, &pcs_entry->name);
+ clib_bihash_add_del_24_8 (&pitcs->pcs_table, &kv, 0 /* is_add */);
+
+ // Free pool entry
+ hicn_pcs_entry_put (pitcs, pcs_entry);
}
-/*
- * for comparing wrapping numbers, return lt,eq,gt 0 for a lt,eq,gt b
- */
+/************************************************************************
+ **************************** PCS Insert API ****************************
+ ************************************************************************/
+
always_inline int
-hicn_infra_seq16_cmp (u16 a, u16 b)
+hicn_pcs_insert (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry,
+ const hicn_name_t *name)
{
- return ((int16_t) (a - b));
+ clib_bihash_kv_24_8_t kv;
+ u32 index = hicn_pcs_entry_get_index (pitcs, entry);
+
+ // Construct KV pair and try to add it to hash table
+ hicn_pcs_get_key_from_name (&kv, name);
+ kv.value = index;
+
+ // Get name hash
+ entry->name_hash = clib_bihash_hash_24_8 (&kv);
+ entry->name = *name;
+
+ return clib_bihash_add_del_24_8 (&pitcs->pcs_table, &kv,
+ 2 /* add_but_not_replace */);
}
-/*
- * below are wrappers for lt, le, gt, ge seq16 comparators
+/**
+ * @brief Insert a CS entry in the PIT/CS table. This function DOES NOT check
+ * if the KV is already present in the table. It expects the caller to check
+ * this before trying to insert the new entry.
+ *
+ * @param pitcs the PIT/CS table
+ * @param entry the entry to insert
+ * @param name the name to use to compute the key
+ * @return always_inline
*/
always_inline int
-hicn_infra_seq16_lt (u16 a, u16 b)
+hicn_pcs_cs_insert (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry,
+ const hicn_name_t *name)
{
- return (hicn_infra_seq16_cmp (a, b) < 0);
-}
+ // Make sure this is a CS entry
+ ASSERT (hicn_pcs_entry_is_cs (entry));
-always_inline int
-hicn_infra_seq16_le (u16 a, u16 b)
-{
- return (hicn_infra_seq16_cmp (a, b) <= 0);
-}
+ int ret = hicn_pcs_insert (pitcs, entry, name);
-always_inline int
-hicn_infra_seq16_gt (u16 a, u16 b)
-{
- return (hicn_infra_seq16_cmp (a, b) > 0);
+ // Make sure insertion happened
+ ASSERT (ret == 0);
+
+ // New entry, update LRU
+ hicn_pcs_cs_insert_lru (pitcs, entry);
+
+ return HICN_ERROR_NONE;
}
+/**
+ * @brief Insert a PIT entry in the PIT/CS table. This function DOES NOT check
+ * if the KV is already present in the table. It is expected the caller checks
+ * this before trying to insert the new entry.
+ *
+ * @param pitcs
+ * @param name
+ * @param pcs_entry_index
+ * @param dpo_ctx_id
+ * @param vft_id
+ * @param is_cs
+ * @return always_inline
+ */
always_inline int
-hicn_infra_seq16_ge (u16 a, u16 b)
+hicn_pcs_pit_insert (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *entry,
+ const hicn_name_t *name)
{
- return (hicn_infra_seq16_cmp (a, b) >= 0);
-}
+ // Insert entry into hash table
+ int ret = hicn_pcs_insert (pitcs, entry, name);
-extern u16 hicn_infra_fast_timer; /* Counts at 1 second intervals */
-extern u16 hicn_infra_slow_timer; /* Counts at 1 minute intervals */
+ // Make sure insertion happened
+ ASSERT (ret == 0);
-/*
- * Utilities to convert lifetime into expiry time based on compressed clock,
- * suitable for the opportunistic hashtable entry timeout processing.
- */
+ // Increment the number of PIT entries if insertion happened
+ pitcs->pcs_pit_count++;
-// convert time in msec to time in clicks
-always_inline u16
-hicn_infra_ms2clicks (u64 time_ms, u64 ms_per_click)
-{
- f64 time_clicks =
- ((f64) (time_ms + ms_per_click - 1)) / ((f64) ms_per_click);
- return ((u16) time_clicks);
+ return HICN_ERROR_NONE;
}
-always_inline u16
-hicn_infra_get_fast_exp_time (u64 lifetime_ms)
-{
- u16 lifetime_clicks =
- hicn_infra_ms2clicks (lifetime_ms, HICN_INFRA_FAST_TIMER_MSECS);
- return (hicn_infra_seq16_sum (hicn_infra_fast_timer, lifetime_clicks));
-}
+/************************************************************************
+ ************************** PCS Conversion API **************************
+ ************************************************************************/
-always_inline u16
-hicn_infra_get_slow_exp_time (u64 lifetime_ms)
+/**
+ * @brief Convert a PIT entry to a CS entry.
+ *
+ * @param vm
+ * @param pitcs
+ * @param pcs_entry
+ * @param hash_entry
+ * @param node
+ * @param dpo_vft
+ * @param hicn_dpo_id
+ * @return always_inline
+ */
+always_inline void
+hicn_pit_to_cs (hicn_pit_cs_t *pitcs, hicn_pcs_entry_t *pit_entry,
+ u32 buffer_index)
{
- u16 lifetime_clicks =
- hicn_infra_ms2clicks (lifetime_ms, HICN_INFRA_SLOW_TIMER_MSECS);
- return (hicn_infra_seq16_sum (hicn_infra_slow_timer, lifetime_clicks));
+ // Different from the insert node. In here we don't need to add a new
+ // hash entry.
+ pitcs->pcs_pit_count--;
+
+ // Flush faces
+ // hicn_faces_flush (&(pit_entry->u.pit.faces));
+
+ // Set the flags
+ pit_entry->flags = HICN_PCS_ENTRY_CS_FLAG;
+
+ // Set the buffer index
+ pit_entry->u.cs.cs_pkt_buf = buffer_index;
+
+ hicn_pcs_cs_insert_lru (pitcs, pit_entry);
}
-#endif /* // __HICN_PCS_H__ */
+#endif /* __HICN_PCS_H__ */
/*
* fd.io coding-style-patch-verification: ON
diff --git a/hicn-plugin/src/pg.c b/hicn-plugin/src/pg.c
index 2f98e9c16..e3dda0520 100644
--- a/hicn-plugin/src/pg.c
+++ b/hicn-plugin/src/pg.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,57 +18,13 @@
#include <vnet/pg/pg.h>
#include <vnet/ip/ip.h>
#include <vnet/ethernet/ethernet.h>
+#include <vnet/fib/fib_entry_track.h>
#include "hicn.h"
#include "pg.h"
#include "parser.h"
#include "infra.h"
-
-/* Registration struct for a graph node */
-vlib_node_registration_t hicn_pg_interest_node;
-vlib_node_registration_t hicn_pg_data_node;
-
-/* Stats, which end up called "error" even though they aren't... */
-#define foreach_hicnpg_error \
- _ (PROCESSED, "hICN PG packets processed") \
- _ (DROPPED, "hICN PG packets dropped") \
- _ (INTEREST_MSGS_GENERATED, "hICN PG Interests generated") \
- _ (CONTENT_MSGS_RECEIVED, "hICN PG Content msgs received")
-
-typedef enum
-{
-#define _(sym, str) HICNPG_ERROR_##sym,
- foreach_hicnpg_error
-#undef _
- HICNPG_N_ERROR,
-} hicnpg_error_t;
-
-static char *hicnpg_error_strings[] = {
-#define _(sym, string) string,
- foreach_hicnpg_error
-#undef _
-};
-
-/*
- * Next graph nodes, which reference the list in the actual registration
- * block below
- */
-typedef enum
-{
- HICNPG_INTEREST_NEXT_V4_LOOKUP,
- HICNPG_INTEREST_NEXT_V6_LOOKUP,
- HICNPG_INTEREST_NEXT_DROP,
- HICNPG_N_NEXT,
-} hicnpg_interest_next_t;
-
-/* Trace context struct */
-typedef struct
-{
- u32 next_index;
- u32 sw_if_index;
- u8 pkt_type;
- u16 msg_type;
-} hicnpg_trace_t;
+#include "route.h"
hicnpg_main_t hicnpg_main = { .index = (u32) 0,
.index_ifaces = (u32) 1,
@@ -78,307 +34,38 @@ hicnpg_main_t hicnpg_main = { .index = (u32) 0,
.n_ifaces = (u32) 1,
.sw_if = (u32) 0 };
-hicnpg_server_main_t hicnpg_server_main = {
- .node_index = 0,
-};
-
-/* packet trace format function */
-static u8 *
-format_hicnpg_trace (u8 *s, va_list *args)
-{
- CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
- CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
- hicnpg_trace_t *t = va_arg (*args, hicnpg_trace_t *);
-
- s = format (s, "HICNPG: pkt: %d, msg %d, sw_if_index %d, next index %d",
- (int) t->pkt_type, (int) t->msg_type, t->sw_if_index,
- t->next_index);
- return (s);
-}
-
-always_inline void hicn_rewrite_interestv4 (vlib_main_t *vm, vlib_buffer_t *b0,
- u32 seq_number, u16 lifetime,
- u32 next_flow, u32 iface);
-
-always_inline void hicn_rewrite_interestv6 (vlib_main_t *vm, vlib_buffer_t *b0,
- u32 seq_number, u16 lifetime,
- u32 next_flow, u32 iface);
-
-always_inline void convert_interest_to_data_v4 (vlib_main_t *vm,
- vlib_buffer_t *b0,
- vlib_buffer_t *rb, u32 bi0);
-
-always_inline void convert_interest_to_data_v6 (vlib_main_t *vm,
- vlib_buffer_t *b0,
- vlib_buffer_t *rb, u32 bi0);
-
-always_inline void calculate_tcp_checksum_v4 (vlib_main_t *vm,
- vlib_buffer_t *b0);
+/**
+ * Pool of hicnpg_server_t
+ */
+hicnpg_server_t *hicnpg_server_pool;
-always_inline void calculate_tcp_checksum_v6 (vlib_main_t *vm,
- vlib_buffer_t *b0);
/*
- * Node function for the icn packet-generator client. The goal here is to
- * manipulate/tweak a stream of packets that have been injected by the vpp
- * packet generator to generate icn request traffic.
+ * hicnph servrer FIB node type
*/
-static uword
-hicnpg_client_interest_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
- vlib_frame_t *frame)
-{
- u32 n_left_from, *from, *to_next;
- hicnpg_interest_next_t next_index;
- u32 pkts_processed = 0, pkts_dropped = 0;
- u32 interest_msgs_generated = 0;
- u32 bi0, bi1;
- vlib_buffer_t *b0, *b1;
- u8 pkt_type0 = 0, pkt_type1 = 0;
- u16 msg_type0 = 0, msg_type1 = 0;
- hicn_header_t *hicn0 = NULL, *hicn1 = NULL;
- hicn_name_t name0, name1;
- u16 namelen0, namelen1;
- hicnpg_main_t *hpgm = &hicnpg_main;
- int iface = 0;
-
- from = vlib_frame_vector_args (frame);
- n_left_from = frame->n_vectors;
- next_index = node->cached_next_index;
-
- while (n_left_from > 0)
- {
- u32 n_left_to_next;
-
- vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
-
- while (n_left_from >= 4 && n_left_to_next >= 2)
- {
- u32 next0 = HICNPG_INTEREST_NEXT_DROP;
- u32 next1 = HICNPG_INTEREST_NEXT_DROP;
- u32 sw_if_index0 = ~0, sw_if_index1 = ~0;
- u8 isv6_0;
- u8 isv6_1;
-
- /* Prefetch next iteration. */
- {
- vlib_buffer_t *p2, *p3;
-
- p2 = vlib_get_buffer (vm, from[2]);
- p3 = vlib_get_buffer (vm, from[3]);
-
- vlib_prefetch_buffer_header (p2, LOAD);
- vlib_prefetch_buffer_header (p3, LOAD);
-
- CLIB_PREFETCH (p2->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
- CLIB_PREFETCH (p3->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
- }
-
- /*
- * speculatively enqueue b0 and b1 to the current
- * next frame
- */
- to_next[0] = bi0 = from[0];
- to_next[1] = bi1 = from[1];
- from += 2;
- to_next += 2;
- n_left_from -= 2;
- n_left_to_next -= 2;
-
- b0 = vlib_get_buffer (vm, bi0);
- b1 = vlib_get_buffer (vm, bi1);
-
- sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_RX];
- vnet_buffer (b0)->sw_if_index[VLIB_RX] = hpgm->sw_if;
- vnet_buffer (b1)->sw_if_index[VLIB_RX] = hpgm->sw_if;
-
- /* Check icn packets, locate names */
- if (hicn_interest_parse_pkt (b0, &name0, &namelen0, &hicn0,
- &isv6_0) == HICN_ERROR_NONE)
- {
- /* this node grabs only interests */
-
- /* Increment the appropriate message counter */
- interest_msgs_generated++;
-
- iface = (hpgm->index_ifaces % hpgm->n_ifaces);
- /* Rewrite and send */
- isv6_0 ?
- hicn_rewrite_interestv6 (
- vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
- hpgm->interest_lifetime, hpgm->index % hpgm->n_flows,
- iface) :
- hicn_rewrite_interestv4 (
- vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
- hpgm->interest_lifetime, hpgm->index % hpgm->n_flows, iface);
-
- hpgm->index_ifaces++;
- if (iface == (hpgm->n_ifaces - 1))
- hpgm->index++;
-
- next0 = isv6_0 ? HICNPG_INTEREST_NEXT_V6_LOOKUP :
- HICNPG_INTEREST_NEXT_V4_LOOKUP;
- }
- if (hicn_interest_parse_pkt (b1, &name1, &namelen1, &hicn1,
- &isv6_1) == HICN_ERROR_NONE)
- {
- /* this node grabs only interests */
-
- /* Increment the appropriate message counter */
- interest_msgs_generated++;
-
- iface = (hpgm->index_ifaces % hpgm->n_ifaces);
- /* Rewrite and send */
- isv6_1 ?
- hicn_rewrite_interestv6 (
- vm, b1, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
- hpgm->interest_lifetime, hpgm->index % hpgm->n_flows,
- iface) :
- hicn_rewrite_interestv4 (
- vm, b1, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
- hpgm->interest_lifetime, hpgm->index % hpgm->n_flows, iface);
-
- hpgm->index_ifaces++;
- if (iface == (hpgm->n_ifaces - 1))
- hpgm->index++;
-
- next1 = isv6_1 ? HICNPG_INTEREST_NEXT_V6_LOOKUP :
- HICNPG_INTEREST_NEXT_V4_LOOKUP;
- }
- /* Send pkt to next node */
- vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
- vnet_buffer (b1)->sw_if_index[VLIB_TX] = ~0;
-
- pkts_processed += 2;
-
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
- {
- if (b0->flags & VLIB_BUFFER_IS_TRACED)
- {
- hicnpg_trace_t *t =
- vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = pkt_type0;
- t->msg_type = msg_type0;
- t->sw_if_index = sw_if_index0;
- t->next_index = next0;
- }
- if (b1->flags & VLIB_BUFFER_IS_TRACED)
- {
- hicnpg_trace_t *t =
- vlib_add_trace (vm, node, b1, sizeof (*t));
- t->pkt_type = pkt_type1;
- t->msg_type = msg_type1;
- t->sw_if_index = sw_if_index1;
- t->next_index = next1;
- }
- }
- if (next0 == HICNPG_INTEREST_NEXT_DROP)
- {
- pkts_dropped++;
- }
- if (next1 == HICNPG_INTEREST_NEXT_DROP)
- {
- pkts_dropped++;
- }
- /*
- * verify speculative enqueues, maybe switch current
- * next frame
- */
- vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next,
- n_left_to_next, bi0, bi1, next0,
- next1);
- }
-
- while (n_left_from > 0 && n_left_to_next > 0)
- {
- u32 next0 = HICNPG_INTEREST_NEXT_DROP;
- u32 sw_if_index0;
- u8 isv6_0;
-
- /* speculatively enqueue b0 to the current next frame */
- bi0 = from[0];
- to_next[0] = bi0;
- from += 1;
- to_next += 1;
- n_left_from -= 1;
- n_left_to_next -= 1;
-
- b0 = vlib_get_buffer (vm, bi0);
-
- sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- vnet_buffer (b0)->sw_if_index[VLIB_RX] = hpgm->sw_if;
-
- /* Check icn packets, locate names */
- if (hicn_interest_parse_pkt (b0, &name0, &namelen0, &hicn0,
- &isv6_0) == HICN_ERROR_NONE)
- {
- /* this node grabs only interests */
-
- /* Increment the appropriate message counter */
- interest_msgs_generated++;
-
- iface = (hpgm->index_ifaces % hpgm->n_ifaces);
-
- /* Rewrite and send */
- isv6_0 ?
- hicn_rewrite_interestv6 (
- vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
- hpgm->interest_lifetime, hpgm->index % hpgm->n_flows,
- iface) :
- hicn_rewrite_interestv4 (
- vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
- hpgm->interest_lifetime, hpgm->index % hpgm->n_flows, iface);
-
- hpgm->index_ifaces++;
- if (iface == (hpgm->n_ifaces - 1))
- hpgm->index++;
+fib_node_type_t hicnpg_server_fib_node_type;
- next0 = isv6_0 ? HICNPG_INTEREST_NEXT_V6_LOOKUP :
- HICNPG_INTEREST_NEXT_V4_LOOKUP;
- }
- /* Send pkt to ip lookup */
- vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
-
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
- (b0->flags & VLIB_BUFFER_IS_TRACED)))
- {
- hicnpg_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = pkt_type0;
- t->msg_type = msg_type0;
- t->sw_if_index = sw_if_index0;
- t->next_index = next0;
- }
- pkts_processed += 1;
-
- if (next0 == HICNPG_INTEREST_NEXT_DROP)
- {
- pkts_dropped++;
- }
- /*
- * verify speculative enqueue, maybe switch current
- * next frame
- */
- vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
- n_left_to_next, bi0, next0);
- }
-
- vlib_put_next_frame (vm, node, next_index, n_left_to_next);
- }
-
- vlib_node_increment_counter (vm, hicn_pg_interest_node.index,
- HICNPG_ERROR_PROCESSED, pkts_processed);
- vlib_node_increment_counter (vm, hicn_pg_interest_node.index,
- HICNPG_ERROR_DROPPED, pkts_dropped);
- vlib_node_increment_counter (vm, hicn_pg_interest_node.index,
- HICNPG_ERROR_INTEREST_MSGS_GENERATED,
- interest_msgs_generated);
+/**
+ * Registered DPO type.
+ */
+dpo_type_t hicnpg_server_dpo_type;
- return (frame->n_vectors);
+static void
+hicnpg_server_restack (hicnpg_server_t *hicnpg_server)
+{
+ dpo_stack (
+ hicnpg_server_dpo_type, fib_proto_to_dpo (hicnpg_server->prefix.fp_proto),
+ &hicnpg_server->dpo,
+ fib_entry_contribute_ip_forwarding (hicnpg_server->fib_entry_index));
}
-void
-hicn_rewrite_interestv4 (vlib_main_t *vm, vlib_buffer_t *b0, u32 seq_number,
- u16 interest_lifetime, u32 next_flow, u32 iface)
+static hicnpg_server_t *
+hicnpg_server_from_fib_node (fib_node_t *node)
{
+#if 1
+ ASSERT (hicnpg_server_fib_node_type == node->fn_type);
+ return ((hicnpg_server_t *) (((char *) node) -
+ STRUCT_OFFSET_OF (hicnpg_server_t, fib_node)));
+#else
hicn_header_t *h0 = vlib_buffer_get_current (b0);
/* Generate the right src and dst corresponding to flow and iface */
@@ -386,16 +73,17 @@ hicn_rewrite_interestv4 (vlib_main_t *vm, vlib_buffer_t *b0, u32 seq_number,
.ip4 = hicnpg_main.pgen_clt_src_addr.ip4,
};
hicn_name_t dst_name = {
- .ip4.prefix_as_ip4 = hicnpg_main.pgen_clt_hicn_name->fp_addr.ip4,
- .ip4.suffix = seq_number,
+ .prefix.v4.as_u32 = hicnpg_main.pgen_clt_hicn_name->fp_addr.ip4.as_u32,
+ .suffix = seq_number,
};
src_addr.ip4.as_u32 += clib_host_to_net_u32 (iface);
- dst_name.ip4.prefix_as_ip4.as_u32 += clib_net_to_host_u32 (next_flow);
+ dst_name.prefix.v4.as_u32 += clib_net_to_host_u32 (next_flow);
/* Update locator and name */
hicn_type_t type = hicn_get_buffer (b0)->type;
- HICN_OPS4->set_interest_locator (type, &h0->protocol, &src_addr);
+ HICN_OPS4->set_interest_locator (type, &h0->protocol,
+ (hicn_ip_address_t *) &src_addr);
HICN_OPS4->set_interest_name (type, &h0->protocol, &dst_name);
/* Update lifetime (currently L4 checksum is not updated) */
@@ -403,44 +91,38 @@ hicn_rewrite_interestv4 (vlib_main_t *vm, vlib_buffer_t *b0, u32 seq_number,
/* Update checksums */
HICN_OPS4->update_checksums (type, &h0->protocol, 0, 0);
+#endif
}
/**
- * @brief Rewrite the IPv6 header as the next generated packet
- *
- * Set up a name prefix
- * - etiher generate interest in which the name varies only after the prefix
- * (inc : seq_number), then the flow acts on the prefix (CHECK)
- * seq_number => TCP, FLOW =>
- *
- * SRC : pgen_clt_src_addr.ip6 DST = generate name (pgen_clt_hicn_name.ip6)
- * ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff
- * \__/ \__/
- * +iface + flow
- * Source is used to emulate different consumers.
- * FIXME iface is ill-named, better name it consumer id
- * Destination is used to iterate on the content.
+ * Function definition to backwalk a FIB node
*/
-void
-hicn_rewrite_interestv6 (vlib_main_t *vm, vlib_buffer_t *b0, u32 seq_number,
- u16 interest_lifetime, u32 next_flow, u32 iface)
+static fib_node_back_walk_rc_t
+hicnpg_server_fib_back_walk (fib_node_t *node, fib_node_back_walk_ctx_t *ctx)
{
- hicn_header_t *h0 = vlib_buffer_get_current (b0);
+ hicnpg_server_restack (hicnpg_server_from_fib_node (node));
+#if 1
+ return FIB_NODE_BACK_WALK_CONTINUE;
+#else
/* Generate the right src and dst corresponding to flow and iface */
ip46_address_t src_addr = {
.ip6 = hicnpg_main.pgen_clt_src_addr.ip6,
};
hicn_name_t dst_name = {
- .ip6.prefix_as_ip6 = hicnpg_main.pgen_clt_hicn_name->fp_addr.ip6,
- .ip6.suffix = seq_number,
+ .prefix.v6.as_u64 = {
+ hicnpg_main.pgen_clt_hicn_name->fp_addr.ip6.as_u64[0],
+ hicnpg_main.pgen_clt_hicn_name->fp_addr.ip6.as_u64[1],
+ },
+ .suffix = seq_number,
};
src_addr.ip6.as_u32[3] += clib_host_to_net_u32 (iface);
- dst_name.ip6.prefix_as_ip6.as_u32[3] += clib_net_to_host_u32 (next_flow);
+ dst_name.prefix.v6.as_u32[3] += clib_net_to_host_u32 (next_flow);
/* Update locator and name */
hicn_type_t type = hicn_get_buffer (b0)->type;
- HICN_OPS6->set_interest_locator (type, &h0->protocol, &src_addr);
+ HICN_OPS6->set_interest_locator (type, &h0->protocol,
+ (hicn_ip_address_t *) &src_addr);
HICN_OPS6->set_interest_name (type, &h0->protocol, &dst_name);
/* Update lifetime */
@@ -448,811 +130,240 @@ hicn_rewrite_interestv6 (vlib_main_t *vm, vlib_buffer_t *b0, u32 seq_number,
/* Update checksums */
calculate_tcp_checksum_v6 (vm, b0);
+#endif
}
-void
-calculate_tcp_checksum_v4 (vlib_main_t *vm, vlib_buffer_t *b0)
+/**
+ * Function definition to get a FIB node from its index
+ */
+static fib_node_t *
+hicnpg_server_fib_node_get (fib_node_index_t index)
{
- ip4_header_t *ip0;
- tcp_header_t *tcp0;
- ip_csum_t sum0;
- u32 tcp_len0;
+ hicnpg_server_t *hpg_server;
- ip0 = (ip4_header_t *) (vlib_buffer_get_current (b0));
- tcp0 =
- (tcp_header_t *) (vlib_buffer_get_current (b0) + sizeof (ip4_header_t));
- tcp_len0 = clib_net_to_host_u16 (ip0->length) - sizeof (ip4_header_t);
+ hpg_server = pool_elt_at_index (hicnpg_server_pool, index);
- /* Initialize checksum with header. */
- if (BITS (sum0) == 32)
- {
- sum0 = clib_mem_unaligned (&ip0->src_address, u32);
- sum0 =
- ip_csum_with_carry (sum0, clib_mem_unaligned (&ip0->dst_address, u32));
- }
- else
- sum0 = clib_mem_unaligned (&ip0->src_address, u64);
-
- sum0 = ip_csum_with_carry (
- sum0, clib_host_to_net_u32 (tcp_len0 + (ip0->protocol << 16)));
-
- /* Invalidate possibly old checksum. */
- tcp0->checksum = 0;
-
- u32 tcp_offset = sizeof (ip4_header_t);
- sum0 = ip_incremental_checksum_buffer (vm, b0, tcp_offset, tcp_len0, sum0);
-
- tcp0->checksum = ~ip_csum_fold (sum0);
+ return (&hpg_server->fib_node);
}
-void
-calculate_tcp_checksum_v6 (vlib_main_t *vm, vlib_buffer_t *b0)
+/**
+ * Function definition to inform the FIB node that its last lock has gone.
+ */
+static void
+hicnpg_server_fib_last_lock_gone (fib_node_t *node)
{
- ip6_header_t *ip0;
- tcp_header_t *tcp0;
- ip_csum_t sum0;
- u32 tcp_len0;
+ hicnpg_server_t *hpg_server;
- ip0 = (ip6_header_t *) (vlib_buffer_get_current (b0));
- tcp0 =
- (tcp_header_t *) (vlib_buffer_get_current (b0) + sizeof (ip6_header_t));
- tcp_len0 = clib_net_to_host_u16 (ip0->payload_length);
+ hpg_server = hicnpg_server_from_fib_node (node);
- /* Initialize checksum with header. */
- if (BITS (sum0) == 32)
- {
- sum0 = clib_mem_unaligned (&ip0->src_address, u32);
- sum0 =
- ip_csum_with_carry (sum0, clib_mem_unaligned (&ip0->dst_address, u32));
- }
- else
- sum0 = clib_mem_unaligned (&ip0->src_address, u64);
-
- sum0 = ip_csum_with_carry (
- sum0, clib_host_to_net_u32 (tcp_len0 + (ip0->protocol << 16)));
-
- /* Invalidate possibly old checksum. */
- tcp0->checksum = 0;
-
- u32 tcp_offset = sizeof (ip6_header_t);
- sum0 = ip_incremental_checksum_buffer (vm, b0, tcp_offset, tcp_len0, sum0);
+ /**
+ * reset the stacked DPO to unlock it
+ */
+ dpo_reset (&hpg_server->dpo);
- tcp0->checksum = ~ip_csum_fold (sum0);
+ pool_put (hicnpg_server_pool, hpg_server);
}
-VLIB_REGISTER_NODE (hicn_pg_interest_node) = {
- .function = hicnpg_client_interest_node_fn,
- .name = "hicnpg-interest",
- .vector_size = sizeof (u32),
- .format_trace = format_hicnpg_trace,
- .type = VLIB_NODE_TYPE_INTERNAL,
- .n_errors = ARRAY_LEN (hicnpg_error_strings),
- .error_strings = hicnpg_error_strings,
- .n_next_nodes = HICNPG_N_NEXT,
- .next_nodes = { [HICNPG_INTEREST_NEXT_V4_LOOKUP] = "ip4-lookup",
- [HICNPG_INTEREST_NEXT_V6_LOOKUP] = "ip6-lookup",
- [HICNPG_INTEREST_NEXT_DROP] = "error-drop" },
-};
-
-/*
- * Next graph nodes, which reference the list in the actual registration
- * block below
- */
-typedef enum
-{
- HICNPG_DATA_NEXT_DROP,
- HICNPG_DATA_NEXT_LOOKUP4,
- HICNPG_DATA_NEXT_LOOKUP6,
- HICNPG_DATA_N_NEXT,
-} hicnpg_data_next_t;
-
-/* Trace context struct */
-typedef struct
-{
- u32 next_index;
- u32 sw_if_index;
- u8 pkt_type;
- u16 msg_type;
-} icnpg_data_trace_t;
-
-/* packet trace format function */
-static u8 *
-format_hicnpg_data_trace (u8 *s, va_list *args)
+static void
+hicnpg_server_dpo_lock (dpo_id_t *dpo)
{
- CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
- CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
- hicnpg_trace_t *t = va_arg (*args, hicnpg_trace_t *);
-
- s = format (s, "HICNPG: pkt: %d, msg %d, sw_if_index %d, next index %d",
- (int) t->pkt_type, (int) t->msg_type, t->sw_if_index,
- t->next_index);
- return (s);
+ hicnpg_server_t *hpg_server;
+ hpg_server = hicnpg_server_get (dpo->dpoi_index);
+ fib_node_lock (&hpg_server->fib_node);
}
-static_always_inline int
-match_ip4_name (u32 *name, fib_prefix_t *prefix)
+static void
+hicnpg_server_dpo_unlock (dpo_id_t *dpo)
{
- u32 xor = 0;
-
- xor = *name & prefix->fp_addr.ip4.data_u32;
-
- return xor == prefix->fp_addr.ip4.data_u32;
+ hicnpg_server_t *hpg_server;
+ hpg_server = hicnpg_server_get (dpo->dpoi_index);
+ fib_node_unlock (&hpg_server->fib_node);
}
-static_always_inline int
-match_ip6_name (u8 *name, fib_prefix_t *prefix)
+static u8 *
+format_hicnpg_server_i (u8 *s, va_list *args)
{
- union
- {
- u32x4 as_u32x4;
- u64 as_u64[2];
- u32 as_u32[4];
- } xor_sum __attribute__ ((aligned (sizeof (u32x4))));
-
- xor_sum.as_u64[0] = ((u64 *) name)[0] & prefix->fp_addr.ip6.as_u64[0];
- xor_sum.as_u64[1] = ((u64 *) name)[1] & prefix->fp_addr.ip6.as_u64[1];
+ index_t hicnpg_server_i = va_arg (*args, index_t);
+ // u32 indent = va_arg (*args, u32);
+ u32 details = va_arg (*args, u32);
+ // vlib_counter_t to;
+ hicnpg_server_t *hpg;
- return (xor_sum.as_u64[0] == prefix->fp_addr.ip6.as_u64[0]) &&
- (xor_sum.as_u64[1] == prefix->fp_addr.ip6.as_u64[1]);
-}
+ hpg = hicnpg_server_get (hicnpg_server_i);
-/*
- * Return 0,1,2.
- * 0 matches
- * 1 does not match and the prefix is ip4
- * 2 does not match and the prefix is ip6
- */
-static_always_inline u32
-match_data (vlib_buffer_t *b, fib_prefix_t *prefix)
-{
- u8 *ptr = vlib_buffer_get_current (b);
- u8 v = *ptr & 0xf0;
- u32 next = 0;
+ // FIXME
+ s = format (s, "dpo-hicnpg-server:[%d]: ip-fib-index:%d ", hicnpg_server_i,
+ hpg->fib_index);
- if (PREDICT_TRUE (v == 0x40 && ip46_address_is_ip4 (&prefix->fp_addr)))
+ if (FIB_PROTOCOL_IP4 == hpg->prefix.fp_proto)
{
- if (!match_ip4_name ((u32 *) &(ptr[12]), prefix))
- next = 1;
+ s = format (s, "protocol:FIB_PROTOCOL_IP4 prefix: %U",
+ format_fib_prefix, &hpg->prefix);
}
- else if (PREDICT_TRUE (v == 0x60 && !ip46_address_is_ip4 (&prefix->fp_addr)))
+ else
{
- if (!match_ip6_name (&(ptr[8]), prefix))
- next = 2;
+ s = format (s, "protocol:FIB_PROTOCOL_IP6 prefix: %U",
+ format_fib_prefix, &hpg->prefix);
}
- return next;
-}
-
-/*
- * Return 0,1,2.
- * 0 matches
- * 1 does not match and the prefix is ip4
- * 2 does not match and the prefix is ip6
- */
-static_always_inline u32
-match_interest (vlib_buffer_t *b, fib_prefix_t *prefix)
-{
- u8 *ptr = vlib_buffer_get_current (b);
- u8 v = *ptr & 0xf0;
- u32 next = 0;
+#if 0
+ vlib_get_combined_counter (&(udp_encap_counters), uei, &to);
+ s = format (s, " to:[%Ld:%Ld]]", to.packets, to.bytes);s
+#endif
- if (PREDICT_TRUE (v == 0x40 && ip46_address_is_ip4 (&prefix->fp_addr)))
+ if (details)
{
- if (!match_ip4_name ((u32 *) &(ptr[16]), prefix))
- next = 1;
- }
- else if (PREDICT_TRUE (v == 0x60 && !ip46_address_is_ip4 (&prefix->fp_addr)))
- {
- if (!match_ip6_name (&(ptr[24]), prefix))
- next = 2;
+ s = format (s, " locks:%d", hpg->fib_node.fn_locks);
+ // s = format (s, "\n%UStacked on:", format_white_space, indent +
+ // 1); s = format (s, "\n%U%U", format_white_space, indent + 2,
+ // format_dpo_id,
+ // &hpg->dpo, indent + 3);
}
- return next;
+ return s;
}
-/*
- * Node function for the icn packet-generator client. The goal here is to
- * manipulate/tweak a stream of packets that have been injected by the vpp
- * packet generator to generate icn request traffic.
- */
-static uword
-hicnpg_client_data_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
- vlib_frame_t *frame)
+static u8 *
+format_hicnpg_server_dpo (u8 *s, va_list *args)
{
- u32 n_left_from, *from, *to_next;
- hicnpg_data_next_t next_index;
- u32 pkts_processed = 0;
- u32 content_msgs_received = 0;
- u32 bi0, bi1;
- vlib_buffer_t *b0, *b1;
- u8 pkt_type0 = 0, pkt_type1 = 0;
- u16 msg_type0 = 1, msg_type1 = 1;
- hicnpg_main_t *hpgm = &hicnpg_main;
-
- from = vlib_frame_vector_args (frame);
- n_left_from = frame->n_vectors;
- next_index = node->cached_next_index;
-
- while (n_left_from > 0)
- {
- u32 n_left_to_next;
- vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
-
- while (n_left_from >= 4 && n_left_to_next >= 2)
- {
- u32 next0 = HICNPG_DATA_NEXT_DROP;
- u32 next1 = HICNPG_DATA_NEXT_DROP;
- u32 sw_if_index0, sw_if_index1;
-
- /* Prefetch next iteration. */
- {
- vlib_buffer_t *p2, *p3;
-
- p2 = vlib_get_buffer (vm, from[2]);
- p3 = vlib_get_buffer (vm, from[3]);
-
- vlib_prefetch_buffer_header (p2, LOAD);
- vlib_prefetch_buffer_header (p3, LOAD);
-
- CLIB_PREFETCH (p2->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
- CLIB_PREFETCH (p3->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
- }
-
- /*
- * speculatively enqueue b0 and b1 to the current
- * next frame
- */
- to_next[0] = bi0 = from[0];
- to_next[1] = bi1 = from[1];
- from += 2;
- to_next += 2;
- n_left_from -= 2;
- n_left_to_next -= 2;
-
- b0 = vlib_get_buffer (vm, bi0);
- b1 = vlib_get_buffer (vm, bi1);
-
- sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_RX];
-
- next0 =
- HICNPG_DATA_NEXT_DROP + match_data (b0, hpgm->pgen_clt_hicn_name);
- next1 =
- HICNPG_DATA_NEXT_DROP + match_data (b1, hpgm->pgen_clt_hicn_name);
-
- if (PREDICT_FALSE (vnet_get_feature_count (
- vnet_buffer (b0)->feature_arc_index,
- vnet_buffer (b0)->sw_if_index[VLIB_RX]) > 1))
- vnet_feature_next (&next0, b0);
-
- if (PREDICT_FALSE (vnet_get_feature_count (
- vnet_buffer (b1)->feature_arc_index,
- vnet_buffer (b1)->sw_if_index[VLIB_RX]) > 1))
- vnet_feature_next (&next1, b1);
+ index_t hpg_server_i = va_arg (*args, index_t);
+ u32 indent = va_arg (*args, u32);
- if (next0 == HICNPG_DATA_NEXT_DROP)
- {
- /* Increment a counter */
- content_msgs_received++;
- }
-
- if (next1 == HICNPG_DATA_NEXT_DROP)
- {
- /* Increment a counter */
- content_msgs_received++;
- }
-
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
- {
- if (b0->flags & VLIB_BUFFER_IS_TRACED)
- {
- icnpg_data_trace_t *t =
- vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = pkt_type0;
- t->msg_type = msg_type0;
- t->sw_if_index = sw_if_index0;
- t->next_index = next0;
- }
- if (b1->flags & VLIB_BUFFER_IS_TRACED)
- {
- icnpg_data_trace_t *t =
- vlib_add_trace (vm, node, b1, sizeof (*t));
- t->pkt_type = pkt_type1;
- t->msg_type = msg_type1;
- t->sw_if_index = sw_if_index1;
- t->next_index = next1;
- }
- }
-
- vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next,
- n_left_to_next, bi0, bi1, next0,
- next1);
- pkts_processed += 2;
- }
-
- while (n_left_from > 0 && n_left_to_next > 0)
- {
- u32 next0 = HICNPG_DATA_NEXT_DROP;
- u32 sw_if_index0;
-
- /* speculatively enqueue b0 to the current next frame */
- bi0 = from[0];
- to_next[0] = bi0;
- from += 1;
- to_next += 1;
- n_left_from -= 1;
- n_left_to_next -= 1;
-
- b0 = vlib_get_buffer (vm, bi0);
-
- sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
-
- next0 =
- HICNPG_DATA_NEXT_DROP + match_data (b0, hpgm->pgen_clt_hicn_name);
-
- if (PREDICT_FALSE (vnet_get_feature_count (
- vnet_buffer (b0)->feature_arc_index,
- vnet_buffer (b0)->sw_if_index[VLIB_RX]) > 1))
- vnet_feature_next (&next0, b0);
-
- if (next0 == HICNPG_DATA_NEXT_DROP)
- {
- /* Increment a counter */
- content_msgs_received++;
- }
-
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
- (b0->flags & VLIB_BUFFER_IS_TRACED)))
- {
- icnpg_data_trace_t *t =
- vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = pkt_type0;
- t->msg_type = msg_type0;
- t->sw_if_index = sw_if_index0;
- t->next_index = next0;
- }
-
- vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
- n_left_to_next, bi0, next0);
-
- pkts_processed++;
- }
- vlib_put_next_frame (vm, node, next_index, n_left_to_next);
- }
-
- vlib_node_increment_counter (vm, hicn_pg_data_node.index,
- HICNPG_ERROR_PROCESSED, pkts_processed);
- vlib_node_increment_counter (vm, hicn_pg_data_node.index,
- HICNPG_ERROR_CONTENT_MSGS_RECEIVED,
- content_msgs_received);
- return (frame->n_vectors);
+ return (format (s, "%U", format_hicnpg_server_i, hpg_server_i, indent, 1));
}
-VLIB_REGISTER_NODE(hicn_pg_data_node) =
-{
- .function = hicnpg_client_data_node_fn,
- .name = "hicnpg-data",
- .vector_size = sizeof(u32),
- .format_trace = format_hicnpg_data_trace,
- .type = VLIB_NODE_TYPE_INTERNAL,
- .n_errors = ARRAY_LEN(hicnpg_error_strings),
- .error_strings = hicnpg_error_strings,
- .n_next_nodes = HICNPG_DATA_N_NEXT,
- .next_nodes =
- {
- [HICNPG_DATA_NEXT_DROP] = "error-drop",
- [HICNPG_DATA_NEXT_LOOKUP4] = "ip4-lookup",
- [HICNPG_DATA_NEXT_LOOKUP6] = "ip6-lookup",
- },
+/*
+ * Virtual function table registered by hicn pg server
+ * for participation in the FIB object graph.
+ */
+const static fib_node_vft_t hicnpg_server_fib_vft = {
+ .fnv_get = hicnpg_server_fib_node_get,
+ .fnv_last_lock = hicnpg_server_fib_last_lock_gone,
+ .fnv_back_walk = hicnpg_server_fib_back_walk,
};
-VNET_FEATURE_INIT (hicn_data_input_ip4_arc, static) = {
- .arc_name = "ip4-unicast",
- .node_name = "hicnpg-data",
- .runs_before = VNET_FEATURES ("ip4-inacl"),
+const static dpo_vft_t hicnpg_server_dpo_vft = {
+ .dv_lock = hicnpg_server_dpo_lock,
+ .dv_unlock = hicnpg_server_dpo_unlock,
+ .dv_format = format_hicnpg_server_dpo,
};
-VNET_FEATURE_INIT (hicn_data_input_ip6_arc, static) = {
- .arc_name = "ip6-unicast",
- .node_name = "hicnpg-data",
- .runs_before = VNET_FEATURES ("ip6-inacl"),
+const static char *const hicnpg_server_ip4_nodes[] = {
+ "hicnpg-server-4",
+ NULL,
};
-/*
- * End of packet-generator client node
- */
-
-/*
- * Beginning of packet-generation server node
- */
-
-/* Registration struct for a graph node */
-vlib_node_registration_t hicn_pg_server_node;
-
-/* Stats, which end up called "error" even though they aren't... */
-#define foreach_icnpg_server_error \
- _ (PROCESSED, "hICN PG Server packets processed") \
- _ (DROPPED, "hICN PG Server packets dropped")
-
-typedef enum
-{
-#define _(sym, str) HICNPG_SERVER_ERROR_##sym,
- foreach_icnpg_server_error
-#undef _
- HICNPG_SERVER_N_ERROR,
-} icnpg_server_error_t;
-
-static char *icnpg_server_error_strings[] = {
-#define _(sym, string) string,
- foreach_icnpg_server_error
-#undef _
+const static char *const hicnpg_server_ip6_nodes[] = {
+ "hicnpg-server-6",
+ NULL,
};
-/*
- * Next graph nodes, which reference the list in the actual registration
- * block below
- */
-typedef enum
-{
- HICNPG_SERVER_NEXT_V4_LOOKUP,
- HICNPG_SERVER_NEXT_V6_LOOKUP,
- HICNPG_SERVER_NEXT_DROP,
- HICNPG_SERVER_N_NEXT,
-} icnpg_server_next_t;
-
-/* Trace context struct */
-typedef struct
-{
- u32 next_index;
- u32 sw_if_index;
- u8 pkt_type;
- u16 msg_type;
-} hicnpg_server_trace_t;
-
-/* packet trace format function */
-static u8 *
-format_icnpg_server_trace (u8 *s, va_list *args)
-{
- CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
- CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
- hicnpg_server_trace_t *t = va_arg (*args, hicnpg_server_trace_t *);
-
- s = format (
- s, "HICNPG SERVER: pkt: %d, msg %d, sw_if_index %d, next index %d",
- (int) t->pkt_type, (int) t->msg_type, t->sw_if_index, t->next_index);
- return (s);
-}
+const static char *const *const hicnpg_server_nodes[DPO_PROTO_NUM] = {
+ [DPO_PROTO_IP4] = hicnpg_server_ip4_nodes,
+ [DPO_PROTO_IP6] = hicnpg_server_ip6_nodes
+};
-/*
- * Node function for the icn packet-generator server.
- */
-static uword
-hicnpg_node_server_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
- vlib_frame_t *frame)
+clib_error_t *
+hicnpg_server_add_and_lock (fib_prefix_t *prefix, u32 *hicnpg_server_index,
+ ip46_address_t *locator, size_t payload_size)
{
- u32 n_left_from, *from, *to_next;
- icnpg_server_next_t next_index;
- u32 pkts_processed = 0, pkts_dropped = 0;
- u32 bi0, bi1;
- vlib_buffer_t *b0, *b1;
- u8 pkt_type0 = 0, pkt_type1 = 0;
- u16 msg_type0 = 0, msg_type1 = 0;
- hicn_header_t *hicn0 = NULL, *hicn1 = NULL;
- hicn_name_t name0, name1;
- u16 namelen0, namelen1;
-
- hicnpg_server_main_t *hpgsm = &hicnpg_server_main;
+ hicnpg_server_t *hpg;
+ index_t hpgi;
+ u32 fib_index;
+ fib_node_index_t fib_entry_index;
+ u32 buffer_index;
+ vlib_buffer_t *rb = NULL;
- from = vlib_frame_vector_args (frame);
+ // Retrieve hicn fib table
+ fib_index =
+ fib_table_find_or_create_and_lock (prefix->fp_proto, 0, hicn_fib_src);
- n_left_from = frame->n_vectors;
- next_index = node->cached_next_index;
+ // Check the prefix we are adding is not already in the table
+ fib_entry_index = fib_table_lookup_exact_match (fib_index, prefix);
- while (n_left_from > 0)
+ if (fib_entry_index != FIB_NODE_INDEX_INVALID)
{
- u32 n_left_to_next;
-
- vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
-
- while (n_left_from >= 4 && n_left_to_next >= 2)
- {
- u32 next0 = HICNPG_SERVER_NEXT_DROP;
- u32 next1 = HICNPG_SERVER_NEXT_DROP;
- u8 isv6_0 = 0;
- u8 isv6_1 = 0;
- u32 sw_if_index0, sw_if_index1;
-
- /* Prefetch next iteration. */
- {
- vlib_buffer_t *p2, *p3;
-
- p2 = vlib_get_buffer (vm, from[2]);
- p3 = vlib_get_buffer (vm, from[3]);
-
- vlib_prefetch_buffer_header (p2, LOAD);
- vlib_prefetch_buffer_header (p3, LOAD);
-
- CLIB_PREFETCH (p2->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
- CLIB_PREFETCH (p3->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
- }
-
- /*
- * speculatively enqueue b0 and b1 to the current
- * next frame
- */
- to_next[0] = bi0 = from[0];
- to_next[1] = bi1 = from[1];
- from += 2;
- to_next += 2;
- n_left_from -= 2;
- n_left_to_next -= 2;
-
- b0 = vlib_get_buffer (vm, bi0);
- b1 = vlib_get_buffer (vm, bi1);
-
- sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_RX];
-
- vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
- vnet_buffer (b1)->sw_if_index[VLIB_TX] = ~0;
-
- u32 match0 = match_interest (b0, hpgsm->pgen_srv_hicn_name);
- u32 match1 = match_interest (b1, hpgsm->pgen_srv_hicn_name);
-
- if (match0)
- {
- next0 = match0 - 1;
- }
- else if (hicn_interest_parse_pkt (b0, &name0, &namelen0, &hicn0,
- &isv6_0) == HICN_ERROR_NONE)
- {
- /* this node grabs only interests */
- vlib_buffer_t *rb = NULL;
- rb = vlib_get_buffer (vm, hpgsm->pgen_svr_buffer_idx);
-
- isv6_0 ? convert_interest_to_data_v6 (vm, b0, rb, bi0) :
- convert_interest_to_data_v4 (vm, b0, rb, bi0);
-
- next0 = isv6_0 ? HICNPG_SERVER_NEXT_V6_LOOKUP :
- HICNPG_SERVER_NEXT_V4_LOOKUP;
- }
-
- if (match1)
- {
- next1 = match1 - 1;
- }
- else if (hicn_interest_parse_pkt (b1, &name1, &namelen1, &hicn1,
- &isv6_1) == HICN_ERROR_NONE)
- {
- /* this node grabs only interests */
- vlib_buffer_t *rb = NULL;
- rb = vlib_get_buffer (vm, hpgsm->pgen_svr_buffer_idx);
-
- isv6_1 ? convert_interest_to_data_v6 (vm, b1, rb, bi1) :
- convert_interest_to_data_v4 (vm, b1, rb, bi1);
-
- next1 = isv6_1 ? HICNPG_SERVER_NEXT_V6_LOOKUP :
- HICNPG_SERVER_NEXT_V4_LOOKUP;
- }
- pkts_processed += 2;
-
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
- {
- if (b0->flags & VLIB_BUFFER_IS_TRACED)
- {
- hicnpg_server_trace_t *t =
- vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = pkt_type0;
- t->msg_type = msg_type0;
- t->sw_if_index = sw_if_index0;
- t->next_index = next0;
- }
- if (b1->flags & VLIB_BUFFER_IS_TRACED)
- {
- hicnpg_server_trace_t *t =
- vlib_add_trace (vm, node, b1, sizeof (*t));
- t->pkt_type = pkt_type1;
- t->msg_type = msg_type1;
- t->sw_if_index = sw_if_index1;
- t->next_index = next1;
- }
- }
- if (next0 == HICNPG_SERVER_NEXT_DROP)
- {
- pkts_dropped++;
- }
- if (next1 == HICNPG_SERVER_NEXT_DROP)
- {
- pkts_dropped++;
- }
- /*
- * verify speculative enqueues, maybe switch current
- * next frame
- */
- vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next,
- n_left_to_next, bi0, bi1, next0,
- next1);
- }
-
- while (n_left_from > 0 && n_left_to_next > 0)
- {
- u32 next0 = HICNPG_SERVER_NEXT_DROP;
- u32 sw_if_index0 = ~0;
- u8 isv6_0 = 0;
-
- /* speculatively enqueue b0 to the current next frame */
- bi0 = from[0];
- to_next[0] = bi0;
- from += 1;
- to_next += 1;
- n_left_from -= 1;
- n_left_to_next -= 1;
-
- b0 = vlib_get_buffer (vm, bi0);
-
- sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
-
- u32 match0 = match_interest (b0, hpgsm->pgen_srv_hicn_name);
-
- if (match0)
- {
- next0 = match0 - 1;
- }
- else if (hicn_interest_parse_pkt (b0, &name0, &namelen0, &hicn0,
- &isv6_0) == HICN_ERROR_NONE)
- {
- /* this node grabs only interests */
- vlib_buffer_t *rb = NULL;
- rb = vlib_get_buffer (vm, hpgsm->pgen_svr_buffer_idx);
-
- isv6_0 ? convert_interest_to_data_v6 (vm, b0, rb, bi0) :
- convert_interest_to_data_v4 (vm, b0, rb, bi0);
-
- next0 = isv6_0 ? HICNPG_SERVER_NEXT_V6_LOOKUP :
- HICNPG_SERVER_NEXT_V4_LOOKUP;
- }
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
- (b0->flags & VLIB_BUFFER_IS_TRACED)))
- {
- hicnpg_server_trace_t *t =
- vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = pkt_type0;
- t->msg_type = msg_type0;
- t->sw_if_index = sw_if_index0;
- t->next_index = next0;
- }
- pkts_processed += 1;
-
- if (next0 == HICNPG_SERVER_NEXT_DROP)
- {
- pkts_dropped++;
- }
- /*
- * verify speculative enqueue, maybe switch current
- * next frame
- */
- vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
- n_left_to_next, bi0, next0);
- }
-
- vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+ // Route already existing.
+ return clib_error_return (0, "Route exist already.");
}
- vlib_node_increment_counter (vm, hicn_pg_server_node.index,
- HICNPG_SERVER_ERROR_PROCESSED, pkts_processed);
- vlib_node_increment_counter (vm, hicn_pg_server_node.index,
- HICNPG_SERVER_ERROR_DROPPED, pkts_dropped);
+ // Allocate packet buffer
+ int n_buf = vlib_buffer_alloc (vlib_get_main (), &buffer_index, 1);
- return (frame->n_vectors);
-}
-
-void
-convert_interest_to_data_v4 (vlib_main_t *vm, vlib_buffer_t *b0,
- vlib_buffer_t *rb, u32 bi0)
-{
- hicn_header_t *h0 = vlib_buffer_get_current (b0);
-
- /* Get the packet length */
- u16 pkt_len = clib_net_to_host_u16 (h0->v4.ip.len);
-
- /*
- * Rule of thumb: We want the size of the IP packet to be <= 1500 bytes
- */
- u16 bytes_to_copy = rb->current_length;
- if ((bytes_to_copy + pkt_len) > 1500)
+ if (n_buf == 0)
{
- bytes_to_copy = 1500 - pkt_len;
+ return clib_error_return (0, "Impossible to allocate paylod buffer.");
}
- /* Add content to the data packet */
- vlib_buffer_add_data (vm, &bi0, rb->data, bytes_to_copy);
-
- b0 = vlib_get_buffer (vm, bi0);
- h0 = vlib_buffer_get_current (b0);
-
- ip4_address_t src_addr = h0->v4.ip.saddr;
- h0->v4.ip.saddr = h0->v4.ip.daddr;
- h0->v4.ip.daddr = src_addr;
-
- h0->v4.ip.len = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, b0));
- h0->v4.ip.csum = ip4_header_checksum ((ip4_header_t *) &(h0->v4.ip));
- calculate_tcp_checksum_v4 (vm, b0);
+ // Initialize the buffer data with zeros
+ rb = vlib_get_buffer (vlib_get_main (), buffer_index);
+ memset (rb->data, 0, payload_size);
+ rb->current_length = payload_size;
+
+ // We can proceed. Get a new hicnpg_server_t
+ pool_get_aligned_zero (hicnpg_server_pool, hpg, 2 * CLIB_CACHE_LINE_BYTES);
+ hpgi = hpg - hicnpg_server_pool;
+
+ // Set DPO
+ dpo_set (
+ &hpg->dpo, hicnpg_server_dpo_type,
+ (ip46_address_is_ip4 (&prefix->fp_addr) ? DPO_PROTO_IP4 : DPO_PROTO_IP6),
+ hpgi);
+
+ // Add the route via the hicnpg_server_dpo_type. In this way packets will
+ // endup in the hicnpg_server node
+ CLIB_UNUSED (fib_node_index_t new_fib_node_index) =
+ fib_table_entry_special_dpo_add (
+ fib_index, prefix, hicn_fib_src,
+ (FIB_ENTRY_FLAG_EXCLUSIVE | FIB_ENTRY_FLAG_LOOSE_URPF_EXEMPT),
+ &hpg->dpo);
+
+#if 0
+ vlib_validate_combined_counter (&(udp_encap_counters), uei);
+ vlib_zero_combined_counter (&(udp_encap_counters), uei);
+#endif
+
+ // Init remaining struct fields
+ fib_node_init (&hpg->fib_node, hicnpg_server_fib_node_type);
+ fib_node_lock (&hpg->fib_node);
+ hpg->fib_index = fib_index;
+ hpg->prefix = *prefix;
+ hpg->buffer_index = buffer_index;
+ hpg->fib_entry_index = fib_entry_index;
+ hpg->hicn_locator = *locator;
+
+ // track the destination address
+ // hpg->fib_entry_index =
+ // fib_entry_track (fib_index, &hpg->prefix,
+ // hicnpg_server_fib_node_type, hpgi, &hpg->fib_sibling);
+ // hicnpg_server_restack (hpg);
+
+ HICN_DEBUG ("Calling hicn enable for pg-server face");
+
+ hicn_face_id_t *vec_faces = NULL;
+ fib_node_index_t hicn_fib_node_index;
+ hicn_route_enable (prefix, &hicn_fib_node_index, &vec_faces);
+ if (vec_faces != NULL)
+ vec_free (vec_faces);
+
+ // Return the index of the hicnpg_server_t
+ *hicnpg_server_index = hpgi;
+
+ return NULL;
}
-void
-convert_interest_to_data_v6 (vlib_main_t *vm, vlib_buffer_t *b0,
- vlib_buffer_t *rb, u32 bi0)
+clib_error_t *
+hicn_pg_init (vlib_main_t *vm)
{
- hicn_header_t *h0 = vlib_buffer_get_current (b0);
-
- /* Get the packet length */
- uint16_t pkt_len =
- clib_net_to_host_u16 (h0->v6.ip.len) + sizeof (ip6_header_t);
-
- /*
- * Figure out how many bytes we can add to the content
- *
- * Rule of thumb: We want the size of the IP packet to be <= 1400 bytes
- */
- u16 bytes_to_copy = rb->current_length;
- if ((bytes_to_copy + pkt_len) > 1500)
- {
- bytes_to_copy = 1500 - pkt_len;
- }
- /* Add content to the data packet */
- vlib_buffer_add_data (vm, &bi0, rb->data, bytes_to_copy);
-
- b0 = vlib_get_buffer (vm, bi0);
+ hicnpg_server_fib_node_type = fib_node_register_new_type (
+ "hicnpg_server_fib_node", &hicnpg_server_fib_vft);
- h0 = vlib_buffer_get_current (b0);
- ip6_address_t src_addr = h0->v6.ip.saddr;
- h0->v6.ip.saddr = h0->v6.ip.daddr;
- h0->v6.ip.daddr = src_addr;
+ hicnpg_server_dpo_type =
+ dpo_register_new_type (&hicnpg_server_dpo_vft, hicnpg_server_nodes);
- h0->v6.ip.len = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, b0) -
- sizeof (ip6_header_t));
- h0->v6.tcp.data_offset_and_reserved |= 0x0f;
- h0->v6.tcp.urg_ptr = htons (0xffff);
-
- calculate_tcp_checksum_v6 (vm, b0);
+ return NULL;
}
-VLIB_REGISTER_NODE(hicn_pg_server_node) =
-{
- .function = hicnpg_node_server_fn,
- .name = "hicnpg-server",
- .vector_size = sizeof(u32),
- .format_trace = format_icnpg_server_trace,
- .type = VLIB_NODE_TYPE_INTERNAL,
- .n_errors = ARRAY_LEN(icnpg_server_error_strings),
- .error_strings = icnpg_server_error_strings,
- .n_next_nodes = HICNPG_SERVER_N_NEXT,
- /* edit / add dispositions here */
- .next_nodes =
- {
- [HICNPG_SERVER_NEXT_V4_LOOKUP] = "ip4-lookup",
- [HICNPG_SERVER_NEXT_V6_LOOKUP] = "ip6-lookup",
- [HICNPG_SERVER_NEXT_DROP] = "error-drop",
- },
-};
-
-VNET_FEATURE_INIT (hicn_pg_server_ip6, static) = {
- .arc_name = "ip6-unicast",
- .node_name = "hicnpg-server",
- .runs_before = VNET_FEATURES ("ip6-inacl"),
-};
-
-VNET_FEATURE_INIT (hicn_pg_server_ip4, static) = {
- .arc_name = "ip4-unicast",
- .node_name = "hicnpg-server",
- .runs_before = VNET_FEATURES ("ip4-inacl"),
-};
-
-/*
- * End of packet-generator server node
- */
-
/*
* fd.io coding-style-patch-verification: ON
*
diff --git a/hicn-plugin/src/pg.h b/hicn-plugin/src/pg.h
index 059b076fb..deb585714 100644
--- a/hicn-plugin/src/pg.h
+++ b/hicn-plugin/src/pg.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,8 @@
#ifndef __HICN_PG_H__
#define __HICN_PG_H__
+#include <vppinfra/pool.h>
+
/**
* @file pg.h
*
@@ -57,23 +59,58 @@
*/
typedef struct hicnpg_main_s
{
- u32 index; // used to compute the sequence number
- fib_prefix_t *pgen_clt_hicn_name; // hICN name to put in the destiantion
- // addess of an interest
- u32
- index_ifaces; /* used to mimic interests coming from different consumer */
- u32 n_ifaces; /* The source address will change from interest to interest */
- /* index_ifaces is used to keep a global reference to the iface used */
- /* and it is incremented when we want to change "consumer" */
- /* n_ifaces identifies how many consumers to simulate */
- u32 max_seq_number; // Use to limit the max sequence number
- u32 n_flows; // Use to simulate multiple flows (a flow always have the same
- // hICN name)
- ip46_address_t pgen_clt_src_addr; // Source addess base to use in the
- // interest
-
- u16 interest_lifetime; // Interest lifetime
- u32 sw_if; // Interface where to send interest and receives data
+ /*
+ * used to compute the sequence number
+ */
+ u32 index;
+
+ /*
+ * hICN name to put in the destination addess of an interest
+ */
+ fib_prefix_t *pgen_clt_hicn_name;
+
+ /*
+ * Used to mimic interests coming from different consumer. The source address
+ * will change from interest to interest index_ifaces is used to keep a
+ * global reference to the iface used and it is incremented when we want to
+ * change "consumer"
+ */
+ u32 index_ifaces;
+
+ /*
+ * n_ifaces identifies how many consumers to simulate
+ */
+ u32 n_ifaces;
+
+ /*
+ * Use to limit the max sequence number
+ */
+ u32 max_seq_number;
+
+ /*
+ * Use to simulate multiple flows (a flow always have the same hICN name)
+ */
+ u32 n_flows;
+
+ /*
+ * Source addess base to use in the interest
+ */
+ ip46_address_t pgen_clt_src_addr;
+
+ /*
+ * Interest lifetime
+ */
+ u16 interest_lifetime;
+
+ /*
+ * Interface where to send interest and receives data.
+ */
+ u32 sw_if;
+
+ /*
+ * Fib node type
+ */
+ fib_node_type_t hicn_fib_node_type;
} hicnpg_main_t;
extern hicnpg_main_t hicnpg_main;
@@ -83,18 +120,75 @@ extern hicnpg_main_t hicnpg_main;
*
* It stores the configuration and make it availables to the pg server node.
*/
-typedef struct hicnpg_server_main_s
+typedef struct hicnpg_server_s
{
- u32 node_index;
- /* Arbitrary content */
- u32 pgen_svr_buffer_idx;
- fib_prefix_t *pgen_srv_hicn_name;
-} hicnpg_server_main_t;
+ /*
+ * Prefix served by this packet generator server
+ */
+ fib_prefix_t prefix;
+
+ /*
+ * IP address to put in the destination addess of the data
+ */
+ ip46_address_t hicn_locator;
+
+ /*
+ * Buffer index
+ */
+ u32 buffer_index;
+
+ /**
+ * The DPO used to forward to the next node in the VLIB graph
+ */
+ dpo_id_t dpo;
-extern hicnpg_server_main_t hicnpg_server_main;
+ /*
+ * linkage into the FIB graph
+ */
+ fib_node_t fib_node;
+ /*
+ * Tracking information for the IP destination
+ */
+ fib_node_index_t fib_entry_index;
+
+ /*
+ * The FIB index
+ */
+ index_t fib_index;
+} hicnpg_server_t;
+
+STATIC_ASSERT (sizeof (hicnpg_server_t) <= 2 * CLIB_CACHE_LINE_BYTES,
+ "hicnpg_server_t is too large");
+
+extern hicnpg_server_t hicnpg_server_main;
extern vlib_node_registration_t hicn_pg_interest_node;
extern vlib_node_registration_t hicn_pg_data_node;
+extern dpo_type_t hicnpg_server_dpo_type;
+
+/**
+ * Pool of hicnpg_servers
+ */
+extern hicnpg_server_t *hicnpg_server_pool;
+
+always_inline hicnpg_server_t *
+hicnpg_server_get (index_t hpgi)
+{
+ return pool_elt_at_index (hicnpg_server_pool, hpgi);
+}
+
+always_inline u8
+dpo_is_pgserver (const dpo_id_t *dpo)
+{
+ return (dpo->dpoi_type == hicnpg_server_dpo_type);
+}
+
+clib_error_t *hicnpg_server_add_and_lock (fib_prefix_t *prefix,
+ u32 *hicnpg_server_index,
+ ip46_address_t *locator,
+ size_t payload_size);
+
+clib_error_t *hicn_pg_init (vlib_main_t *vm);
#endif // __HICN_PG_H__
diff --git a/hicn-plugin/src/pg_node.c b/hicn-plugin/src/pg_node.c
new file mode 100644
index 000000000..3d94c1cd1
--- /dev/null
+++ b/hicn-plugin/src/pg_node.c
@@ -0,0 +1,1121 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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 <vlib/vlib.h>
+#include <vnet/vnet.h>
+#include <vnet/pg/pg.h>
+#include <vnet/ip/ip.h>
+#include <vnet/ethernet/ethernet.h>
+#include <vnet/ip/ip4_packet.h>
+#include <vnet/ip/ip6_packet.h>
+#include <vnet/tcp/tcp_packet.h>
+
+#include "hicn.h"
+#include "pg.h"
+#include "parser.h"
+#include "infra.h"
+
+/* Registration struct for a graph node */
+vlib_node_registration_t hicn_pg_interest_node;
+vlib_node_registration_t hicn_pg_data_node;
+
+/* Stats, which end up called "error" even though they aren't... */
+#define foreach_hicnpg_error \
+ _ (PROCESSED, "hICN PG packets processed") \
+ _ (DROPPED, "hICN PG packets dropped") \
+ _ (INTEREST_MSGS_GENERATED, "hICN PG Interests generated") \
+ _ (CONTENT_MSGS_RECEIVED, "hICN PG Content msgs received")
+
+typedef enum
+{
+#define _(sym, str) HICNPG_ERROR_##sym,
+ foreach_hicnpg_error
+#undef _
+ HICNPG_N_ERROR,
+} hicnpg_error_t;
+
+static char *hicnpg_error_strings[] = {
+#define _(sym, string) string,
+ foreach_hicnpg_error
+#undef _
+};
+
+/*
+ * Next graph nodes, which reference the list in the actual registration
+ * block below
+ */
+typedef enum
+{
+ HICNPG_INTEREST_NEXT_V4_LOOKUP,
+ HICNPG_INTEREST_NEXT_V6_LOOKUP,
+ HICNPG_INTEREST_NEXT_DROP,
+ HICNPG_N_NEXT,
+} hicnpg_interest_next_t;
+
+/* Trace context struct */
+typedef struct
+{
+ u32 next_index;
+ u32 sw_if_index;
+ u8 pkt_type;
+ u16 msg_type;
+} hicnpg_trace_t;
+
+/* packet trace format function */
+static u8 *
+format_hicnpg_trace (u8 *s, va_list *args)
+{
+ CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+ CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+ hicnpg_trace_t *t = va_arg (*args, hicnpg_trace_t *);
+
+ s = format (s, "HICNPG: pkt: %d, msg %d, sw_if_index %d, next index %d",
+ (int) t->pkt_type, (int) t->msg_type, t->sw_if_index,
+ t->next_index);
+ return (s);
+}
+
+always_inline void hicn_rewrite_interestv4 (vlib_main_t *vm, vlib_buffer_t *b0,
+ u32 seq_number, u16 lifetime,
+ u32 next_flow, u32 iface);
+
+always_inline void hicn_rewrite_interestv6 (vlib_main_t *vm, vlib_buffer_t *b0,
+ u32 seq_number, u16 lifetime,
+ u32 next_flow, u32 iface);
+
+always_inline void convert_interest_to_data_v4 (vlib_main_t *vm,
+ vlib_buffer_t *b0,
+ vlib_buffer_t *rb, u32 bi0);
+
+always_inline void convert_interest_to_data_v6 (vlib_main_t *vm,
+ vlib_buffer_t *b0,
+ vlib_buffer_t *rb, u32 bi0);
+
+always_inline void calculate_tcp_checksum_v4 (vlib_main_t *vm,
+ vlib_buffer_t *b0);
+
+always_inline void calculate_tcp_checksum_v6 (vlib_main_t *vm,
+ vlib_buffer_t *b0);
+/*
+ * Node function for the icn packet-generator client. The goal here is to
+ * manipulate/tweak a stream of packets that have been injected by the vpp
+ * packet generator to generate icn request traffic.
+ */
+static uword
+hicnpg_client_interest_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
+ vlib_frame_t *frame)
+{
+ u32 n_left_from, *from, *to_next;
+ hicnpg_interest_next_t next_index;
+ u32 pkts_processed = 0, pkts_dropped = 0;
+ u32 interest_msgs_generated = 0;
+ u32 bi0, bi1;
+ vlib_buffer_t *b0, *b1;
+ u8 pkt_type0 = 0, pkt_type1 = 0;
+ u16 msg_type0 = 0, msg_type1 = 0;
+ hicnpg_main_t *hpgm = &hicnpg_main;
+ int iface = 0;
+ u32 next0 = HICNPG_INTEREST_NEXT_DROP;
+ u32 next1 = HICNPG_INTEREST_NEXT_DROP;
+ u32 sw_if_index0 = ~0, sw_if_index1 = ~0;
+ u8 isv6_0;
+ u8 isv6_1;
+ u32 n_left_to_next;
+ uword size;
+
+ from = vlib_frame_vector_args (frame);
+ n_left_from = frame->n_vectors;
+ next_index = node->cached_next_index;
+
+ while (n_left_from > 0)
+ {
+ vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+ while (n_left_from >= 4 && n_left_to_next >= 2)
+ {
+ /* Prefetch next iteration. */
+ {
+ vlib_buffer_t *p2, *p3;
+
+ p2 = vlib_get_buffer (vm, from[2]);
+ p3 = vlib_get_buffer (vm, from[3]);
+
+ vlib_prefetch_buffer_header (p2, LOAD);
+ vlib_prefetch_buffer_header (p3, LOAD);
+
+ CLIB_PREFETCH (p2->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
+ CLIB_PREFETCH (p3->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
+ }
+
+ /*
+ * speculatively enqueue b0 and b1 to the current
+ * next frame
+ */
+ to_next[0] = bi0 = from[0];
+ to_next[1] = bi1 = from[1];
+ from += 2;
+ to_next += 2;
+ n_left_from -= 2;
+ n_left_to_next -= 2;
+
+ b0 = vlib_get_buffer (vm, bi0);
+ b1 = vlib_get_buffer (vm, bi1);
+
+ hicn_buffer_set_flags (b0, HICN_BUFFER_FLAGS_FROM_PG);
+ hicn_buffer_set_flags (b1, HICN_BUFFER_FLAGS_FROM_PG);
+
+ sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_RX];
+ vnet_buffer (b0)->sw_if_index[VLIB_RX] = hpgm->sw_if;
+ vnet_buffer (b1)->sw_if_index[VLIB_RX] = hpgm->sw_if;
+
+ /* Check icn packets, locate names */
+ size = vlib_buffer_length_in_chain (vm, b0);
+ if (hicn_interest_parse_pkt (b0, size) == HICN_ERROR_NONE)
+ {
+ /* this node grabs only interests */
+ isv6_0 = hicn_buffer_is_v6 (b0);
+
+ /* Increment the appropriate message counter */
+ interest_msgs_generated++;
+
+ iface = (hpgm->index_ifaces % hpgm->n_ifaces);
+ /* Rewrite and send */
+ isv6_0 ?
+ hicn_rewrite_interestv6 (
+ vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
+ hpgm->interest_lifetime, hpgm->index % hpgm->n_flows,
+ iface) :
+ hicn_rewrite_interestv4 (
+ vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
+ hpgm->interest_lifetime, hpgm->index % hpgm->n_flows, iface);
+
+ hpgm->index_ifaces++;
+ if (iface == (hpgm->n_ifaces - 1))
+ hpgm->index++;
+
+ next0 = isv6_0 ? HICNPG_INTEREST_NEXT_V6_LOOKUP :
+ HICNPG_INTEREST_NEXT_V4_LOOKUP;
+ }
+ size = vlib_buffer_length_in_chain (vm, b1);
+ if (hicn_interest_parse_pkt (b1, size) == HICN_ERROR_NONE)
+ {
+ /* this node grabs only interests */
+ isv6_1 = hicn_buffer_is_v6 (b1);
+
+ /* Increment the appropriate message counter */
+ interest_msgs_generated++;
+
+ iface = (hpgm->index_ifaces % hpgm->n_ifaces);
+ /* Rewrite and send */
+ isv6_1 ?
+ hicn_rewrite_interestv6 (
+ vm, b1, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
+ hpgm->interest_lifetime, hpgm->index % hpgm->n_flows,
+ iface) :
+ hicn_rewrite_interestv4 (
+ vm, b1, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
+ hpgm->interest_lifetime, hpgm->index % hpgm->n_flows, iface);
+
+ hpgm->index_ifaces++;
+ if (iface == (hpgm->n_ifaces - 1))
+ hpgm->index++;
+
+ next1 = isv6_1 ? HICNPG_INTEREST_NEXT_V6_LOOKUP :
+ HICNPG_INTEREST_NEXT_V4_LOOKUP;
+ }
+ /* Send pkt to next node */
+ vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
+ vnet_buffer (b1)->sw_if_index[VLIB_TX] = ~0;
+
+ pkts_processed += 2;
+
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
+ {
+ if (b0->flags & VLIB_BUFFER_IS_TRACED)
+ {
+ hicnpg_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = pkt_type0;
+ t->msg_type = msg_type0;
+ t->sw_if_index = sw_if_index0;
+ t->next_index = next0;
+ }
+ if (b1->flags & VLIB_BUFFER_IS_TRACED)
+ {
+ hicnpg_trace_t *t =
+ vlib_add_trace (vm, node, b1, sizeof (*t));
+ t->pkt_type = pkt_type1;
+ t->msg_type = msg_type1;
+ t->sw_if_index = sw_if_index1;
+ t->next_index = next1;
+ }
+ }
+ if (next0 == HICNPG_INTEREST_NEXT_DROP)
+ {
+ pkts_dropped++;
+ }
+ if (next1 == HICNPG_INTEREST_NEXT_DROP)
+ {
+ pkts_dropped++;
+ }
+ /*
+ * verify speculative enqueues, maybe switch current
+ * next frame
+ */
+ vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next,
+ n_left_to_next, bi0, bi1, next0,
+ next1);
+ }
+
+ while (n_left_from > 0 && n_left_to_next > 0)
+ {
+ /* speculatively enqueue b0 to the current next frame */
+ bi0 = from[0];
+ to_next[0] = bi0;
+ from += 1;
+ to_next += 1;
+ n_left_from -= 1;
+ n_left_to_next -= 1;
+
+ b0 = vlib_get_buffer (vm, bi0);
+
+ hicn_buffer_set_flags (b0, HICN_BUFFER_FLAGS_FROM_PG);
+
+ sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ vnet_buffer (b0)->sw_if_index[VLIB_RX] = hpgm->sw_if;
+
+ /* Check icn packets, locate names */
+ size = vlib_buffer_length_in_chain (vm, b0);
+ if (hicn_interest_parse_pkt (b0, size) == HICN_ERROR_NONE)
+ {
+ /* this node grabs only interests */
+ isv6_0 = hicn_buffer_is_v6 (b0);
+
+ /* Increment the appropriate message counter */
+ interest_msgs_generated++;
+
+ iface = (hpgm->index_ifaces % hpgm->n_ifaces);
+
+ /* Rewrite and send */
+ isv6_0 ?
+ hicn_rewrite_interestv6 (
+ vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
+ hpgm->interest_lifetime, hpgm->index % hpgm->n_flows,
+ iface) :
+ hicn_rewrite_interestv4 (
+ vm, b0, (hpgm->index / hpgm->n_flows) % hpgm->max_seq_number,
+ hpgm->interest_lifetime, hpgm->index % hpgm->n_flows, iface);
+
+ hpgm->index_ifaces++;
+ if (iface == (hpgm->n_ifaces - 1))
+ hpgm->index++;
+
+ next0 = isv6_0 ? HICNPG_INTEREST_NEXT_V6_LOOKUP :
+ HICNPG_INTEREST_NEXT_V4_LOOKUP;
+ }
+ /* Send pkt to ip lookup */
+ vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
+
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ hicnpg_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = pkt_type0;
+ t->msg_type = msg_type0;
+ t->sw_if_index = sw_if_index0;
+ t->next_index = next0;
+ }
+ pkts_processed += 1;
+
+ if (next0 == HICNPG_INTEREST_NEXT_DROP)
+ {
+ pkts_dropped++;
+ }
+ /*
+ * verify speculative enqueue, maybe switch current
+ * next frame
+ */
+ vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+ n_left_to_next, bi0, next0);
+ }
+
+ vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+ }
+
+ vlib_node_increment_counter (vm, hicn_pg_interest_node.index,
+ HICNPG_ERROR_PROCESSED, pkts_processed);
+ vlib_node_increment_counter (vm, hicn_pg_interest_node.index,
+ HICNPG_ERROR_DROPPED, pkts_dropped);
+ vlib_node_increment_counter (vm, hicn_pg_interest_node.index,
+ HICNPG_ERROR_INTEREST_MSGS_GENERATED,
+ interest_msgs_generated);
+
+ return (frame->n_vectors);
+}
+
+void
+hicn_rewrite_interestv4 (vlib_main_t *vm, vlib_buffer_t *b0, u32 seq_number,
+ u16 interest_lifetime, u32 next_flow, u32 iface)
+{
+ hicn_packet_buffer_t *pkbuf = &hicn_get_buffer (b0)->pkbuf;
+ /* Generate the right src and dst corresponding to flow and iface */
+ ip46_address_t src_addr = {
+ .ip4 = hicnpg_main.pgen_clt_src_addr.ip4,
+ };
+ hicn_name_t dst_name = {
+ .prefix.v4.as_u32 = hicnpg_main.pgen_clt_hicn_name->fp_addr.ip4.as_u32,
+ .suffix = seq_number,
+ };
+
+ src_addr.ip4.as_u32 += clib_host_to_net_u32 (iface);
+ dst_name.prefix.v4.as_u32 += clib_net_to_host_u32 (next_flow);
+
+ /* Update locator and name */
+ hicn_interest_set_locator (pkbuf, (hicn_ip_address_t *) &src_addr);
+ hicn_interest_set_name (pkbuf, &dst_name);
+
+ /* Update lifetime (currently L4 checksum is not updated) */
+ hicn_interest_set_lifetime (pkbuf, interest_lifetime);
+
+ /* Update checksums */
+ hicn_packet_compute_checksum (pkbuf);
+}
+
+/**
+ * @brief Rewrite the IPv6 header as the next generated packet
+ *
+ * Set up a name prefix
+ * - etiher generate interest in which the name varies only after the prefix
+ * (inc : seq_number), then the flow acts on the prefix (CHECK)
+ * seq_number => TCP, FLOW =>
+ *
+ * SRC : pgen_clt_src_addr.ip6 DST = generate name (pgen_clt_hicn_name.ip6)
+ * ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff
+ * \__/ \__/
+ * +iface + flow
+ * Source is used to emulate different consumers.
+ * FIXME iface is ill-named, better name it consumer id
+ * Destination is used to iterate on the content.
+ */
+void
+hicn_rewrite_interestv6 (vlib_main_t *vm, vlib_buffer_t *b0, u32 seq_number,
+ u16 interest_lifetime, u32 next_flow, u32 iface)
+{
+ hicn_packet_buffer_t *pkbuf = &hicn_get_buffer (b0)->pkbuf;
+
+ /* Generate the right src and dst corresponding to flow and iface */
+ ip46_address_t src_addr = {
+ .ip6 = hicnpg_main.pgen_clt_src_addr.ip6,
+ };
+ hicn_name_t dst_name = {
+ .prefix = (hicn_ip_address_t) (hicnpg_main.pgen_clt_hicn_name->fp_addr),
+ .suffix = seq_number,
+ };
+ src_addr.ip6.as_u32[3] += clib_host_to_net_u32 (iface);
+ dst_name.prefix.v6.as_u32[3] += clib_net_to_host_u32 (next_flow);
+
+ /* Update locator and name */
+ hicn_interest_set_locator (pkbuf, (hicn_ip_address_t *) &src_addr);
+ hicn_interest_set_name (pkbuf, &dst_name);
+ /* Update lifetime */
+ hicn_interest_set_lifetime (pkbuf, interest_lifetime);
+
+ /* Update checksums */
+ hicn_packet_compute_checksum (pkbuf);
+ calculate_tcp_checksum_v6 (vm, b0);
+}
+
+void
+calculate_tcp_checksum_v4 (vlib_main_t *vm, vlib_buffer_t *b0)
+{
+ ip4_header_t *ip0;
+ tcp_header_t *tcp0;
+ ip_csum_t sum0;
+ u32 tcp_len0;
+
+ ip0 = (ip4_header_t *) (vlib_buffer_get_current (b0));
+ tcp0 =
+ (tcp_header_t *) (vlib_buffer_get_current (b0) + sizeof (ip4_header_t));
+ tcp_len0 = clib_net_to_host_u16 (ip0->length) - sizeof (ip4_header_t);
+
+ /* Initialize checksum with header. */
+ if (BITS (sum0) == 32)
+ {
+ sum0 = clib_mem_unaligned (&ip0->src_address, u32);
+ sum0 =
+ ip_csum_with_carry (sum0, clib_mem_unaligned (&ip0->dst_address, u32));
+ }
+ else
+ sum0 = clib_mem_unaligned (&ip0->src_address, u64);
+
+ sum0 = ip_csum_with_carry (
+ sum0, clib_host_to_net_u32 (tcp_len0 + (ip0->protocol << 16)));
+
+ /* Invalidate possibly old checksum. */
+ tcp0->checksum = 0;
+
+ u32 tcp_offset = sizeof (ip4_header_t);
+ sum0 = ip_incremental_checksum_buffer (vm, b0, tcp_offset, tcp_len0, sum0);
+
+ tcp0->checksum = ~ip_csum_fold (sum0);
+}
+
+void
+calculate_tcp_checksum_v6 (vlib_main_t *vm, vlib_buffer_t *b0)
+{
+ ip6_header_t *ip0;
+ tcp_header_t *tcp0;
+ ip_csum_t sum0;
+ u32 tcp_len0;
+
+ ip0 = (ip6_header_t *) (vlib_buffer_get_current (b0));
+ tcp0 =
+ (tcp_header_t *) (vlib_buffer_get_current (b0) + sizeof (ip6_header_t));
+ tcp_len0 = clib_net_to_host_u16 (ip0->payload_length);
+
+ /* Initialize checksum with header. */
+ if (BITS (sum0) == 32)
+ {
+ sum0 = clib_mem_unaligned (&ip0->src_address, u32);
+ sum0 =
+ ip_csum_with_carry (sum0, clib_mem_unaligned (&ip0->dst_address, u32));
+ }
+ else
+ sum0 = clib_mem_unaligned (&ip0->src_address, u64);
+
+ sum0 = ip_csum_with_carry (
+ sum0, clib_host_to_net_u32 (tcp_len0 + (ip0->protocol << 16)));
+
+ /* Invalidate possibly old checksum. */
+ tcp0->checksum = 0;
+
+ u32 tcp_offset = sizeof (ip6_header_t);
+ sum0 = ip_incremental_checksum_buffer (vm, b0, tcp_offset, tcp_len0, sum0);
+
+ tcp0->checksum = ~ip_csum_fold (sum0);
+}
+
+VLIB_REGISTER_NODE (hicn_pg_interest_node) = {
+ .function = hicnpg_client_interest_node_fn,
+ .name = "hicnpg-interest",
+ .vector_size = sizeof (u32),
+ .format_trace = format_hicnpg_trace,
+ .type = VLIB_NODE_TYPE_INTERNAL,
+ .n_errors = ARRAY_LEN (hicnpg_error_strings),
+ .error_strings = hicnpg_error_strings,
+ .n_next_nodes = HICNPG_N_NEXT,
+ .next_nodes = { [HICNPG_INTEREST_NEXT_V4_LOOKUP] = "ip4-lookup",
+ [HICNPG_INTEREST_NEXT_V6_LOOKUP] = "ip6-lookup",
+ [HICNPG_INTEREST_NEXT_DROP] = "error-drop" },
+};
+
+/*
+ * Next graph nodes, which reference the list in the actual registration
+ * block below
+ */
+typedef enum
+{
+ HICNPG_DATA_NEXT_DROP,
+ HICNPG_DATA_NEXT_LOOKUP4,
+ HICNPG_DATA_NEXT_LOOKUP6,
+ HICNPG_DATA_N_NEXT,
+} hicnpg_data_next_t;
+
+/* Trace context struct */
+typedef struct
+{
+ u32 next_index;
+ u32 sw_if_index;
+ u8 pkt_type;
+ u16 msg_type;
+} icnpg_data_trace_t;
+
+/* packet trace format function */
+static u8 *
+format_hicnpg_data_trace (u8 *s, va_list *args)
+{
+ CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+ CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+ hicnpg_trace_t *t = va_arg (*args, hicnpg_trace_t *);
+
+ s = format (s, "HICNPG: pkt: %d, msg %d, sw_if_index %d, next index %d",
+ (int) t->pkt_type, (int) t->msg_type, t->sw_if_index,
+ t->next_index);
+ return (s);
+}
+
+/*
+ * Node function for the icn packet-generator client. The goal here is to
+ * manipulate/tweak a stream of packets that have been injected by the vpp
+ * packet generator to generate icn request traffic.
+ */
+static uword
+hicnpg_client_data_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
+ vlib_frame_t *frame)
+{
+ u32 n_left_from, *from, *to_next;
+ hicnpg_data_next_t next_index;
+ u32 pkts_processed = 0;
+ u32 content_msgs_received = 0;
+ u32 bi0, bi1;
+ vlib_buffer_t *b0, *b1;
+ u8 pkt_type0 = 0, pkt_type1 = 0;
+ u16 msg_type0 = 1, msg_type1 = 1;
+ u32 next0 = HICNPG_DATA_NEXT_DROP;
+ u32 next1 = HICNPG_DATA_NEXT_DROP;
+ u32 sw_if_index0, sw_if_index1;
+
+ from = vlib_frame_vector_args (frame);
+ n_left_from = frame->n_vectors;
+ next_index = node->cached_next_index;
+
+ while (n_left_from > 0)
+ {
+ u32 n_left_to_next;
+ vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+ while (n_left_from >= 4 && n_left_to_next >= 2)
+ {
+ /* Prefetch next iteration. */
+ {
+ vlib_buffer_t *p2, *p3;
+
+ p2 = vlib_get_buffer (vm, from[2]);
+ p3 = vlib_get_buffer (vm, from[3]);
+
+ vlib_prefetch_buffer_header (p2, LOAD);
+ vlib_prefetch_buffer_header (p3, LOAD);
+
+ CLIB_PREFETCH (p2->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
+ CLIB_PREFETCH (p3->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
+ }
+
+ /*
+ * speculatively enqueue b0 and b1 to the current
+ * next frame
+ */
+ to_next[0] = bi0 = from[0];
+ to_next[1] = bi1 = from[1];
+ from += 2;
+ to_next += 2;
+ n_left_from -= 2;
+ n_left_to_next -= 2;
+
+ b0 = vlib_get_buffer (vm, bi0);
+ b1 = vlib_get_buffer (vm, bi1);
+
+ sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_RX];
+
+ next0 = HICNPG_DATA_NEXT_DROP;
+ next1 = HICNPG_DATA_NEXT_DROP;
+
+ // Increment counter
+ content_msgs_received += 2;
+
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
+ {
+ if (b0->flags & VLIB_BUFFER_IS_TRACED)
+ {
+ icnpg_data_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = pkt_type0;
+ t->msg_type = msg_type0;
+ t->sw_if_index = sw_if_index0;
+ t->next_index = next0;
+ }
+ if (b1->flags & VLIB_BUFFER_IS_TRACED)
+ {
+ icnpg_data_trace_t *t =
+ vlib_add_trace (vm, node, b1, sizeof (*t));
+ t->pkt_type = pkt_type1;
+ t->msg_type = msg_type1;
+ t->sw_if_index = sw_if_index1;
+ t->next_index = next1;
+ }
+ }
+
+ vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next,
+ n_left_to_next, bi0, bi1, next0,
+ next1);
+ pkts_processed += 2;
+ }
+
+ while (n_left_from > 0 && n_left_to_next > 0)
+ {
+ /* speculatively enqueue b0 to the current next frame */
+ bi0 = from[0];
+ to_next[0] = bi0;
+ from += 1;
+ to_next += 1;
+ n_left_from -= 1;
+ n_left_to_next -= 1;
+
+ b0 = vlib_get_buffer (vm, bi0);
+
+ sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+
+ next0 = HICNPG_DATA_NEXT_DROP;
+
+ // Increment a counter
+ content_msgs_received += 1;
+
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ icnpg_data_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = pkt_type0;
+ t->msg_type = msg_type0;
+ t->sw_if_index = sw_if_index0;
+ t->next_index = next0;
+ }
+
+ vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+ n_left_to_next, bi0, next0);
+
+ pkts_processed++;
+ }
+ vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+ }
+
+ vlib_node_increment_counter (vm, hicn_pg_data_node.index,
+ HICNPG_ERROR_PROCESSED, pkts_processed);
+ vlib_node_increment_counter (vm, hicn_pg_data_node.index,
+ HICNPG_ERROR_CONTENT_MSGS_RECEIVED,
+ content_msgs_received);
+ return (frame->n_vectors);
+}
+
+VLIB_REGISTER_NODE(hicn_pg_data_node) =
+{
+ .function = hicnpg_client_data_node_fn,
+ .name = "hicnpg-data",
+ .vector_size = sizeof(u32),
+ .format_trace = format_hicnpg_data_trace,
+ .type = VLIB_NODE_TYPE_INTERNAL,
+ .n_errors = ARRAY_LEN(hicnpg_error_strings),
+ .error_strings = hicnpg_error_strings,
+ .n_next_nodes = HICNPG_DATA_N_NEXT,
+ .next_nodes =
+ {
+ [HICNPG_DATA_NEXT_DROP] = "error-drop",
+ [HICNPG_DATA_NEXT_LOOKUP4] = "ip4-lookup",
+ [HICNPG_DATA_NEXT_LOOKUP6] = "ip6-lookup",
+ },
+};
+
+VNET_FEATURE_INIT (hicn_data_input_ip4_arc, static) = {
+ .arc_name = "ip4-unicast",
+ .node_name = "hicnpg-data",
+ .runs_before = VNET_FEATURES ("ip4-inacl"),
+};
+
+VNET_FEATURE_INIT (hicn_data_input_ip6_arc, static) = {
+ .arc_name = "ip6-unicast",
+ .node_name = "hicnpg-data",
+ .runs_before = VNET_FEATURES ("ip6-inacl"),
+};
+
+/*
+ * End of packet-generator client node
+ */
+
+/*
+ * Beginning of packet-generation server node
+ */
+
+/* Registration struct for a graph node */
+vlib_node_registration_t hicn_pg_server_node;
+
+/* Stats, which end up called "error" even though they aren't... */
+#define foreach_icnpg_server_error \
+ _ (PROCESSED, "hICN PG Server packets processed") \
+ _ (DROPPED, "hICN PG Server packets dropped")
+
+typedef enum
+{
+#define _(sym, str) HICNPG_SERVER_ERROR_##sym,
+ foreach_icnpg_server_error
+#undef _
+ HICNPG_SERVER_N_ERROR,
+} icnpg_server_error_t;
+
+static char *icnpg_server_error_strings[] = {
+#define _(sym, string) string,
+ foreach_icnpg_server_error
+#undef _
+};
+
+/*
+ * Next graph nodes, which reference the list in the actual registration
+ * block below
+ */
+typedef enum
+{
+ HICNPG_SERVER_NEXT_V4_LOOKUP,
+ HICNPG_SERVER_NEXT_V6_LOOKUP,
+ HICNPG_SERVER_NEXT_DROP,
+ HICNPG_SERVER_N_NEXT,
+} icnpg_server_next_t;
+
+/* Trace context struct */
+typedef struct
+{
+ u32 next_index;
+ u32 sw_if_index;
+ u8 pkt_type;
+ u16 msg_type;
+} hicnpg_server_trace_t;
+
+/* packet trace format function */
+static u8 *
+format_icnpg_server_trace (u8 *s, va_list *args)
+{
+ CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+ CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+ hicnpg_server_trace_t *t = va_arg (*args, hicnpg_server_trace_t *);
+
+ s = format (
+ s, "HICNPG SERVER: pkt: %d, msg %d, sw_if_index %d, next index %d",
+ (int) t->pkt_type, (int) t->msg_type, t->sw_if_index, t->next_index);
+ return (s);
+}
+
+/*
+ * Node function for the icn packet-generator server.
+ */
+static uword
+hicnpg_node_server_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
+ vlib_frame_t *frame, int isv6)
+{
+ u32 n_left_from, *from, *to_next;
+ icnpg_server_next_t next_index;
+ u32 pkts_processed = 0, pkts_dropped = 0;
+ u32 bi0, bi1;
+ vlib_buffer_t *b0, *b1;
+ u8 pkt_type0 = 0, pkt_type1 = 0;
+ u16 msg_type0 = 0, msg_type1 = 0;
+ u32 next0 = HICNPG_SERVER_NEXT_DROP;
+ u32 next1 = HICNPG_SERVER_NEXT_DROP;
+ u32 sw_if_index0, sw_if_index1;
+ u32 hpgi0, hpgi1;
+ hicnpg_server_t *hpg0, *hpg1;
+ u32 n_left_to_next;
+ uword size;
+
+ from = vlib_frame_vector_args (frame);
+
+ n_left_from = frame->n_vectors;
+ next_index = node->cached_next_index;
+
+ while (n_left_from > 0)
+ {
+ vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+ while (n_left_from >= 4 && n_left_to_next >= 2)
+ {
+ /* Prefetch next iteration. */
+ {
+ vlib_buffer_t *p2, *p3;
+
+ p2 = vlib_get_buffer (vm, from[2]);
+ p3 = vlib_get_buffer (vm, from[3]);
+
+ vlib_prefetch_buffer_header (p2, LOAD);
+ vlib_prefetch_buffer_header (p3, LOAD);
+
+ CLIB_PREFETCH (p2->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
+ CLIB_PREFETCH (p3->data, (2 * CLIB_CACHE_LINE_BYTES), STORE);
+ }
+
+ /*
+ * speculatively enqueue b0 and b1 to the current
+ * next frame
+ */
+ to_next[0] = bi0 = from[0];
+ to_next[1] = bi1 = from[1];
+ from += 2;
+ to_next += 2;
+ n_left_from -= 2;
+ n_left_to_next -= 2;
+
+ b0 = vlib_get_buffer (vm, bi0);
+ b1 = vlib_get_buffer (vm, bi1);
+
+ sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ sw_if_index1 = vnet_buffer (b1)->sw_if_index[VLIB_RX];
+
+ vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
+ vnet_buffer (b1)->sw_if_index[VLIB_TX] = ~0;
+
+ hpgi0 = vnet_buffer (b0)->ip.adj_index[VLIB_TX];
+ hpgi1 = vnet_buffer (b1)->ip.adj_index[VLIB_TX];
+
+ hpg0 = hicnpg_server_get (hpgi0);
+ hpg1 = hicnpg_server_get (hpgi1);
+
+ size = vlib_buffer_length_in_chain (vm, b0);
+ if (hicn_interest_parse_pkt (b0, size) == HICN_ERROR_NONE)
+ {
+ vlib_buffer_t *rb = NULL;
+ rb = vlib_get_buffer (vm, hpg0->buffer_index);
+
+ isv6 ? convert_interest_to_data_v6 (vm, b0, rb, bi0) :
+ convert_interest_to_data_v4 (vm, b0, rb, bi0);
+
+ next0 = isv6 ? HICNPG_SERVER_NEXT_V6_LOOKUP :
+ HICNPG_SERVER_NEXT_V4_LOOKUP;
+ }
+
+ size = vlib_buffer_length_in_chain (vm, b1);
+ if (hicn_interest_parse_pkt (b1, size) == HICN_ERROR_NONE)
+ {
+ vlib_buffer_t *rb = NULL;
+ rb = vlib_get_buffer (vm, hpg1->buffer_index);
+
+ isv6 ? convert_interest_to_data_v6 (vm, b1, rb, bi1) :
+ convert_interest_to_data_v4 (vm, b1, rb, bi1);
+
+ next1 = isv6 ? HICNPG_SERVER_NEXT_V6_LOOKUP :
+ HICNPG_SERVER_NEXT_V4_LOOKUP;
+ }
+ pkts_processed += 2;
+
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
+ {
+ if (b0->flags & VLIB_BUFFER_IS_TRACED)
+ {
+ hicnpg_server_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = pkt_type0;
+ t->msg_type = msg_type0;
+ t->sw_if_index = sw_if_index0;
+ t->next_index = next0;
+ }
+ if (b1->flags & VLIB_BUFFER_IS_TRACED)
+ {
+ hicnpg_server_trace_t *t =
+ vlib_add_trace (vm, node, b1, sizeof (*t));
+ t->pkt_type = pkt_type1;
+ t->msg_type = msg_type1;
+ t->sw_if_index = sw_if_index1;
+ t->next_index = next1;
+ }
+ }
+ if (next0 == HICNPG_SERVER_NEXT_DROP)
+ {
+ pkts_dropped++;
+ }
+ if (next1 == HICNPG_SERVER_NEXT_DROP)
+ {
+ pkts_dropped++;
+ }
+ /*
+ * verify speculative enqueues, maybe switch current
+ * next frame
+ */
+ vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next,
+ n_left_to_next, bi0, bi1, next0,
+ next1);
+ }
+
+ while (n_left_from > 0 && n_left_to_next > 0)
+ {
+ /* speculatively enqueue b0 to the current next frame */
+ bi0 = from[0];
+ to_next[0] = bi0;
+ from += 1;
+ to_next += 1;
+ n_left_from -= 1;
+ n_left_to_next -= 1;
+
+ b0 = vlib_get_buffer (vm, bi0);
+
+ sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
+
+ hpgi0 = vnet_buffer (b0)->ip.adj_index[VLIB_TX];
+ hpg0 = hicnpg_server_get (hpgi0);
+
+ size = vlib_buffer_length_in_chain (vm, b0);
+ if (hicn_interest_parse_pkt (b0, size) == HICN_ERROR_NONE)
+ {
+ /* this node grabs only interests */
+ vlib_buffer_t *rb = NULL;
+ rb = vlib_get_buffer (vm, hpg0->buffer_index);
+
+ isv6 ? convert_interest_to_data_v6 (vm, b0, rb, bi0) :
+ convert_interest_to_data_v4 (vm, b0, rb, bi0);
+
+ next0 = isv6 ? HICNPG_SERVER_NEXT_V6_LOOKUP :
+ HICNPG_SERVER_NEXT_V4_LOOKUP;
+ }
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ hicnpg_server_trace_t *t =
+ vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = pkt_type0;
+ t->msg_type = msg_type0;
+ t->sw_if_index = sw_if_index0;
+ t->next_index = next0;
+ }
+ pkts_processed += 1;
+
+ if (next0 == HICNPG_SERVER_NEXT_DROP)
+ {
+ pkts_dropped++;
+ }
+ /*
+ * verify speculative enqueue, maybe switch current
+ * next frame
+ */
+ vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+ n_left_to_next, bi0, next0);
+ }
+
+ vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+ }
+
+ vlib_node_increment_counter (vm, hicn_pg_server_node.index,
+ HICNPG_SERVER_ERROR_PROCESSED, pkts_processed);
+ vlib_node_increment_counter (vm, hicn_pg_server_node.index,
+ HICNPG_SERVER_ERROR_DROPPED, pkts_dropped);
+
+ return (frame->n_vectors);
+}
+
+void
+convert_interest_to_data_v4 (vlib_main_t *vm, vlib_buffer_t *b0,
+ vlib_buffer_t *rb, u32 bi0)
+{
+ ip4_header_t *ip4 = vlib_buffer_get_current (b0);
+
+ /* Get the packet length */
+ u16 pkt_len = clib_net_to_host_u16 (ip4->length);
+
+ /*
+ * Rule of thumb: We want the size of the IP packet to be <= 1500 bytes
+ */
+ u16 bytes_to_copy = rb->current_length;
+ if ((bytes_to_copy + pkt_len) > 1500)
+ {
+ bytes_to_copy = 1500 - pkt_len;
+ }
+ /* Add content to the data packet */
+ vlib_buffer_add_data (vm, &bi0, rb->data, bytes_to_copy);
+
+ b0 = vlib_get_buffer (vm, bi0);
+
+ ip4 = vlib_buffer_get_current (b0);
+
+ ip4_address_t src_addr = ip4->src_address;
+ ip4->src_address = ip4->dst_address;
+ ip4->dst_address = src_addr;
+
+ ip4->length = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, b0));
+ ip4->checksum = ip4_header_checksum (ip4);
+ calculate_tcp_checksum_v4 (vm, b0);
+}
+
+void
+convert_interest_to_data_v6 (vlib_main_t *vm, vlib_buffer_t *b0,
+ vlib_buffer_t *rb, u32 bi0)
+{
+ ip6_header_t *ip6 = vlib_buffer_get_current (b0);
+
+ /* Get the packet length */
+ uint16_t pkt_len =
+ clib_net_to_host_u16 (ip6->payload_length) + sizeof (ip6_header_t);
+
+ /*
+ * Figure out how many bytes we can add to the content
+ *
+ * Rule of thumb: We want the size of the IP packet to be <= 1400 bytes
+ */
+ u16 bytes_to_copy = rb->current_length;
+ if ((bytes_to_copy + pkt_len) > 1500)
+ {
+ bytes_to_copy = 1500 - pkt_len;
+ }
+ /* Add content to the data packet */
+ vlib_buffer_add_data (vm, &bi0, rb->data, bytes_to_copy);
+
+ b0 = vlib_get_buffer (vm, bi0);
+
+ ip6 = vlib_buffer_get_current (b0);
+ ip6_address_t src_addr = ip6->src_address;
+ ip6->src_address = ip6->dst_address;
+ ip6->dst_address = src_addr;
+
+ ip6->payload_length = clib_host_to_net_u16 (
+ vlib_buffer_length_in_chain (vm, b0) - sizeof (ip6_header_t));
+
+ tcp_header_t *tcp = (tcp_header_t *) (ip6 + 1);
+ tcp->data_offset_and_reserved |= 0x0f;
+ tcp->urgent_pointer = htons (0xffff);
+
+ calculate_tcp_checksum_v6 (vm, b0);
+}
+
+VLIB_NODE_FN (hicn_pg_server6_node)
+(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
+{
+ return hicnpg_node_server_fn (vm, node, frame, 1 /* is_v6 */);
+}
+
+VLIB_NODE_FN (hicn_pg_server4_node)
+(vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
+{
+ return hicnpg_node_server_fn (vm, node, frame, 0 /* is_v6 */);
+}
+
+VLIB_REGISTER_NODE(hicn_pg_server6_node) =
+{
+ .name = "hicnpg-server-6",
+ .vector_size = sizeof(u32),
+ .format_trace = format_icnpg_server_trace,
+ .type = VLIB_NODE_TYPE_INTERNAL,
+ .n_errors = ARRAY_LEN(icnpg_server_error_strings),
+ .error_strings = icnpg_server_error_strings,
+ .n_next_nodes = HICNPG_SERVER_N_NEXT,
+ /* edit / add dispositions here */
+ .next_nodes =
+ {
+ [HICNPG_SERVER_NEXT_V4_LOOKUP] = "ip4-lookup",
+ [HICNPG_SERVER_NEXT_V6_LOOKUP] = "ip6-lookup",
+ [HICNPG_SERVER_NEXT_DROP] = "error-drop",
+ },
+};
+
+VLIB_REGISTER_NODE(hicn_pg_server4_node) =
+{
+ .name = "hicnpg-server-4",
+ .vector_size = sizeof(u32),
+ .format_trace = format_icnpg_server_trace,
+ .type = VLIB_NODE_TYPE_INTERNAL,
+ .n_errors = ARRAY_LEN(icnpg_server_error_strings),
+ .error_strings = icnpg_server_error_strings,
+ .n_next_nodes = HICNPG_SERVER_N_NEXT,
+ /* edit / add dispositions here */
+ .next_nodes =
+ {
+ [HICNPG_SERVER_NEXT_V4_LOOKUP] = "ip4-lookup",
+ [HICNPG_SERVER_NEXT_V6_LOOKUP] = "ip6-lookup",
+ [HICNPG_SERVER_NEXT_DROP] = "error-drop",
+ },
+};
diff --git a/hicn-plugin/src/route.c b/hicn-plugin/src/route.c
index 34a94936e..fa95f7265 100644
--- a/hicn-plugin/src/route.c
+++ b/hicn-plugin/src/route.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -33,6 +33,8 @@
#include "strategies/dpo_mw.h"
#include "infra.h"
#include "udp_tunnels/udp_tunnel.h"
+#include "mapme.h"
+#include "pg.h"
#define FIB_SOURCE_HICN 0x04 // Right after the FIB_SOURCE_INTERFACE priority
@@ -105,94 +107,76 @@ int
hicn_route_set_strategy (fib_prefix_t *prefix, u8 strategy_id)
{
const dpo_id_t *hicn_dpo_id;
- dpo_id_t new_dpo_id = DPO_INVALID;
int ret;
- hicn_dpo_ctx_t *old_hicn_dpo_ctx;
- const hicn_dpo_vft_t *new_dpo_vft;
- index_t new_hicn_dpo_idx;
+ hicn_dpo_ctx_t *hicn_dpo_ctx;
u32 fib_index;
ret = hicn_route_get_dpo (prefix, &hicn_dpo_id, &fib_index);
if (ret == HICN_ERROR_NONE)
{
- old_hicn_dpo_ctx = hicn_strategy_dpo_ctx_get (hicn_dpo_id->dpoi_index);
+ hicn_dpo_ctx = hicn_strategy_dpo_ctx_get (hicn_dpo_id->dpoi_index);
+ const hicn_dpo_vft_t *dpo_vft = hicn_dpo_get_vft_from_id (strategy_id);
- new_dpo_vft = hicn_dpo_get_vft_from_id (strategy_id);
-
- if (new_dpo_vft == NULL || old_hicn_dpo_ctx == NULL)
+ if (hicn_dpo_ctx == NULL || dpo_vft == NULL)
return HICN_ERROR_STRATEGY_NOT_FOUND;
- /* Create a new dpo for the new strategy */
- new_dpo_vft->hicn_dpo_create (
- hicn_dpo_id->dpoi_proto, old_hicn_dpo_ctx->next_hops,
- old_hicn_dpo_ctx->entry_count, &new_hicn_dpo_idx);
-
- /* the value we got when we registered */
- dpo_set (&new_dpo_id, new_dpo_vft->hicn_dpo_get_type (),
- (ip46_address_is_ip4 (&prefix->fp_addr) ? DPO_PROTO_IP4 :
- DPO_PROTO_IP6),
- new_hicn_dpo_idx);
-
- /* Here is where we create the "via" like route */
- /*
- * For the moment we use the global one the prefix you want
- * to match Neale suggested -- FIB_SOURCE_HICN the client
- * that is adding them -- no easy explanation at this time…
- */
- fib_node_index_t new_fib_node_index =
- fib_table_entry_special_dpo_update (fib_index, prefix, hicn_fib_src,
- FIB_ENTRY_FLAG_EXCLUSIVE,
- &new_dpo_id);
-
- dpo_unlock (&new_dpo_id);
- ret = (new_fib_node_index != FIB_NODE_INDEX_INVALID) ?
- HICN_ERROR_NONE :
- HICN_ERROR_ROUTE_NOT_UPDATED;
+ dpo_vft->hicn_dpo_update_type (hicn_dpo_ctx);
}
// Remember to remove the lock from the table when removing the entry
return ret;
}
-int
-ip_nh_add_helper (fib_protocol_t fib_proto, const fib_prefix_t *rpfx,
- ip46_address_t *nh, u32 sw_if)
+static int
+ip_nh_add_del_helper (fib_protocol_t fib_proto, const fib_prefix_t *rpfx,
+ ip46_address_t *nh, u32 sw_if, u32 udp_encap_id,
+ dpo_proto_t proto, u8 is_add)
{
fib_route_path_t *rpaths = NULL, rpath;
u32 fib_index = fib_table_find (fib_proto, 0);
-
clib_memset (&rpath, 0, sizeof (rpath));
+
+ if (nh)
+ {
+ rpath.frp_addr = *nh;
+ rpath.frp_sw_if_index = sw_if;
+ }
+ else if (udp_encap_id != ~0)
+ {
+ rpath.frp_udp_encap_id = udp_encap_id;
+ rpath.frp_flags |= FIB_ROUTE_PATH_UDP_ENCAP;
+ }
+
rpath.frp_weight = 1;
- rpath.frp_sw_if_index = sw_if;
- rpath.frp_addr = *nh;
- rpath.frp_proto = ip46_address_is_ip4 (nh) ? DPO_PROTO_IP4 : DPO_PROTO_IP6;
+ rpath.frp_proto = proto;
vec_add1 (rpaths, rpath);
- fib_table_entry_path_add2 (fib_index, rpfx, FIB_SOURCE_CLI,
- FIB_ENTRY_FLAG_NONE, rpaths);
+ if (is_add)
+ fib_table_entry_path_add2 (fib_index, rpfx, FIB_SOURCE_API,
+ FIB_ENTRY_FLAG_NONE, rpaths);
+ else
+ fib_table_entry_path_remove2 (fib_index, rpfx, FIB_SOURCE_API, rpaths);
+
return 0;
}
int
-ip_nh_del_helper (fib_protocol_t fib_proto, const fib_prefix_t *rpfx,
- ip46_address_t *nh, u32 sw_if)
+ip_nh_adj_add_del_helper (fib_protocol_t fib_proto, const fib_prefix_t *rpfx,
+ ip46_address_t *nh, u32 sw_if, u8 is_add)
{
- fib_route_path_t *rpaths = NULL, rpath;
-
- u32 fib_index = fib_table_find (fib_proto, 0);
-
- clib_memset (&rpath, 0, sizeof (rpath));
- rpath.frp_weight = 1;
- rpath.frp_sw_if_index = sw_if;
- rpath.frp_addr = *nh;
- rpath.frp_proto = ip46_address_is_ip4 (nh) ? DPO_PROTO_IP4 : DPO_PROTO_IP6;
-
- vec_add1 (rpaths, rpath);
+ return ip_nh_add_del_helper (
+ fib_proto, rpfx, nh, sw_if, ~0,
+ ip46_address_is_ip4 (nh) ? DPO_PROTO_IP4 : DPO_PROTO_IP6, is_add);
+}
- fib_table_entry_path_remove2 (fib_index, rpfx, FIB_SOURCE_CLI, rpaths);
- return 0;
+int
+ip_nh_udp_tunnel_add_del_helper (fib_protocol_t fib_proto,
+ const fib_prefix_t *rpfx, u32 uei,
+ dpo_proto_t proto, u8 is_add)
+{
+ return ip_nh_add_del_helper (fib_proto, rpfx, NULL, ~0, uei, proto, is_add);
}
static ip46_address_t *
@@ -234,23 +218,25 @@ get_address (ip46_address_t *nh, u32 sw_if, fib_protocol_t proto)
}
static void
-sync_hicn_fib_entry (hicn_dpo_ctx_t *fib_entry)
+sync_hicn_fib_entry (hicn_dpo_ctx_t *fib_entry, hicn_face_id_t **pvec_faces)
{
+ hicn_face_id_t *vec_faces = NULL;
const dpo_id_t *dpo_loadbalance =
fib_entry_contribute_ip_forwarding (fib_entry->fib_entry_index);
+ const fib_entry_t *_fib_entry = fib_entry_get (fib_entry->fib_entry_index);
const load_balance_t *lb0 = load_balance_get (dpo_loadbalance->dpoi_index);
index_t hicn_fib_entry_index = hicn_strategy_dpo_ctx_get_index (fib_entry);
- hicn_face_id_t *vec_faces = 0;
dpo_id_t temp = DPO_INVALID;
const dpo_id_t *former_dpo = &temp;
int index = 0;
-#define ADD_FACE(nh) \
+#define ADD_FACE(nh, dpo_proto) \
do \
{ \
/* Careful, this adds a lock on the face if it exists */ \
- hicn_face_add (dpo, nh, sw_if, &face_id, 0); \
+ hicn_face_add (dpo, nh, sw_if, &face_id, dpo_proto); \
+ ASSERT (face_id != HICN_FACE_NULL); \
vec_validate (vec_faces, index); \
vec_faces[index] = face_id; \
(index)++; \
@@ -286,34 +272,37 @@ sync_hicn_fib_entry (hicn_dpo_ctx_t *fib_entry)
sw_if = adj->rewrite_header.sw_if_index;
nh = get_address (&(adj->sub_type.nbr.next_hop), sw_if,
fib_entry->proto);
- ADD_FACE (nh);
+ ADD_FACE (nh, dpo->dpoi_proto);
+ HICN_DEBUG ("Added new HICN face: %d because of route prefix %U",
+ face_id, format_fib_prefix, &_fib_entry->fe_prefix);
}
- else if (dpo->dpoi_type == dpo_type_udp_ip4 ||
- dpo->dpoi_type == dpo_type_udp_ip6)
+ else if (dpo_is_udp_encap (dpo))
{
- u8 proto = dpo->dpoi_type == dpo_type_udp_ip4 ? FIB_PROTOCOL_IP4 :
- FIB_PROTOCOL_IP6;
+ dpo_proto_t proto = dpo_udp_encap_get_proto (dpo);
ip46_address_t _nh = { 0 };
nh = &_nh;
- switch (dpo->dpoi_proto)
+ switch (_fib_entry->fe_prefix.fp_proto)
{
case FIB_PROTOCOL_IP6:
- case FIB_PROTOCOL_IP4:
- /**
- * Independently of the type of tunnel, encapsulated packet
- * can be either v6 or v4, so we need to create 2 faces for each
- * version. Tunneled hicn packet MUST have locator set to the
- * loopback address, so ::1 for IPv6 and 127.0.0.1 for IPv4.
- */
ip46_address_set_ip6 (nh, &localhost6);
- ADD_FACE (nh);
+ ADD_FACE (nh, DPO_PROTO_IP6);
+ break;
+ case FIB_PROTOCOL_IP4:
ip46_address_set_ip4 (nh, &localhost4);
- ADD_FACE (nh);
+ ADD_FACE (nh, DPO_PROTO_IP4);
break;
default:
continue;
}
+ HICN_DEBUG ("Added new UDP face: %d because of route prefix %U",
+ face_id, format_fib_prefix, &_fib_entry->fe_prefix);
udp_tunnel_add_existing (dpo->dpoi_index, proto);
+ udp_tunnel_set_face (face_id, proto == DPO_PROTO_IP4);
+ }
+ else if (dpo_is_pgserver (dpo))
+ {
+ hicnpg_server_t *pg_server = hicnpg_server_get (dpo->dpoi_index);
+ ADD_FACE (&pg_server->hicn_locator, dpo->dpoi_proto);
}
}
@@ -345,7 +334,8 @@ sync_hicn_fib_entry (hicn_dpo_ctx_t *fib_entry)
/* Remove the lock added by hicn_face_add */
hicn_face_unlock_with_id (*face_id);
}
- vec_free (vec_faces);
+
+ *pvec_faces = vec_faces;
}
static void
@@ -380,7 +370,9 @@ disable_data_receiving_rm_fib_entry (vnet_main_t *vnm, vnet_sw_interface_t *si,
}
int
-hicn_route_enable (fib_prefix_t *prefix)
+hicn_route_enable (const fib_prefix_t *prefix,
+ fib_node_index_t *hicn_fib_node_index,
+ hicn_face_id_t **pvec_faces)
{
int ret = HICN_ERROR_NONE;
@@ -408,15 +400,17 @@ hicn_route_enable (fib_prefix_t *prefix)
/* Check if the prefix is already enabled */
u32 fib_hicn_index = fib_table_find (prefix->fp_proto, HICN_FIB_TABLE);
- fib_node_index_t fib_hicn_entry_index =
- fib_table_lookup_exact_match (fib_hicn_index, prefix);
+ *hicn_fib_node_index = fib_table_lookup_exact_match (fib_hicn_index, prefix);
- if (fib_hicn_entry_index == FIB_NODE_INDEX_INVALID)
+ if (*hicn_fib_node_index == FIB_NODE_INDEX_INVALID)
{
+ HICN_DEBUG (
+ "No route found for %U. Creating DPO and tracking fib prefix.",
+ format_fib_prefix, prefix);
dpo_id_t dpo = DPO_INVALID;
- index_t dpo_idx;
- default_dpo.hicn_dpo_create (prefix->fp_proto, 0, NEXT_HOP_INVALID,
- &dpo_idx);
+ index_t dpo_idx = ~0;
+ default_dpo.hicn_dpo_create (prefix->fp_proto, 0, 0, &dpo_idx);
+ HICN_DEBUG ("Created new DPO_MW_CTX_T: %d.", dpo_idx);
/* the value we got when we registered */
/*
@@ -425,8 +419,14 @@ hicn_route_enable (fib_prefix_t *prefix)
*/
dpo_set (&dpo, default_dpo.hicn_dpo_get_type (),
(ip46_address_is_ip4 (&prefix->fp_addr) ? DPO_PROTO_IP4 :
- DPO_PROTO_IP6),
+ DPO_PROTO_IP6),
dpo_idx);
+ HICN_DEBUG (
+ "dpo_set called with parameters: type=%d, proto=%s, index=%d",
+ default_dpo.hicn_dpo_get_type (),
+ ip46_address_is_ip4 (&prefix->fp_addr) ? "DPO_PROTO_IP4" :
+ "DPO_PROTO_IP6",
+ dpo_idx);
hicn_dpo_ctx_t *fib_entry = hicn_strategy_dpo_ctx_get (dpo_idx);
@@ -443,12 +443,12 @@ hicn_route_enable (fib_prefix_t *prefix)
* to match Neale suggested -- FIB_SOURCE_HICN the client
* that is adding them -- no easy explanation at this time…
*/
- CLIB_UNUSED (fib_node_index_t new_fib_node_index) =
- fib_table_entry_special_dpo_add (
- fib_hicn_index, prefix, hicn_fib_src,
- (FIB_ENTRY_FLAG_EXCLUSIVE | FIB_ENTRY_FLAG_LOOSE_URPF_EXEMPT), &dpo);
+ *hicn_fib_node_index = fib_table_entry_special_dpo_add (
+ fib_hicn_index, prefix, hicn_fib_src,
+ (FIB_ENTRY_FLAG_EXCLUSIVE | FIB_ENTRY_FLAG_LOOSE_URPF_EXEMPT), &dpo);
- sync_hicn_fib_entry (fib_entry);
+ HICN_DEBUG ("Calling sync_hicn_fib_entry");
+ sync_hicn_fib_entry (fib_entry, pvec_faces);
/* We added a route, therefore add one lock to the table */
fib_table_lock (fib_index, prefix->fp_proto, hicn_fib_src);
@@ -464,23 +464,26 @@ hicn_route_enable (fib_prefix_t *prefix)
*/
vnet_main_t *vnm = vnet_get_main ();
vnet_sw_interface_walk (vnm, enable_data_receiving_new_fib_entry,
- &(prefix->fp_proto));
+ (void *) (&prefix->fp_proto));
dpo_unlock (&dpo);
}
else
{
+ HICN_DEBUG ("Found a route for %U. Updating DPO.", format_fib_prefix,
+ prefix);
const dpo_id_t *load_balance_dpo_id;
const dpo_id_t *strategy_dpo_id;
/* Route already existing. We need to update the dpo. */
load_balance_dpo_id =
- fib_entry_contribute_ip_forwarding (fib_hicn_entry_index);
+ fib_entry_contribute_ip_forwarding (*hicn_fib_node_index);
/* The dpo is not a load balance dpo as expected */
if (load_balance_dpo_id->dpoi_type != DPO_LOAD_BALANCE)
{
ret = HICN_ERROR_ROUTE_NO_LD;
+ HICN_ERROR ("DPO is not a load balance.");
goto done;
}
else
@@ -493,19 +496,22 @@ hicn_route_enable (fib_prefix_t *prefix)
if (!dpo_is_hicn (strategy_dpo_id))
{
ret = HICN_ERROR_ROUTE_DPO_NO_HICN;
+ HICN_ERROR ("DPO is not hicn.");
goto done;
}
if (lb->lb_n_buckets > 1)
{
ret = HICN_ERROR_ROUTE_MLT_LD;
+ HICN_ERROR ("Too many load balance buckets.");
goto done;
}
hicn_dpo_ctx_t *hicn_fib_entry =
hicn_strategy_dpo_ctx_get (strategy_dpo_id->dpoi_index);
- sync_hicn_fib_entry (hicn_fib_entry);
+ HICN_DEBUG ("Calling sync_hicn_fib_entry");
+ sync_hicn_fib_entry (hicn_fib_entry, pvec_faces);
}
}
@@ -527,7 +533,8 @@ hicn_route_disable (fib_prefix_t *prefix)
if (fib_hicn_entry_index == FIB_NODE_INDEX_INVALID)
{
- return HICN_ERROR_ROUTE_NOT_FOUND;
+ HICN_ERROR ("Route %U not found", format_fib_prefix, prefix);
+ ret = HICN_ERROR_ROUTE_NOT_FOUND;
}
else
{
@@ -542,6 +549,8 @@ hicn_route_disable (fib_prefix_t *prefix)
/* The dpo is not a load balance dpo as expected */
if (load_balance_dpo_id->dpoi_type != DPO_LOAD_BALANCE)
{
+ HICN_ERROR ("DPO for route %U is not a load balance.",
+ format_ip_prefix, prefix);
ret = HICN_ERROR_ROUTE_NO_LD;
goto done;
}
@@ -554,12 +563,16 @@ hicn_route_disable (fib_prefix_t *prefix)
if (!dpo_is_hicn (strategy_dpo_id))
{
+ HICN_ERROR ("ERROR: DPO for route %U is not a hicn.",
+ format_ip_prefix, prefix);
ret = HICN_ERROR_ROUTE_DPO_NO_HICN;
goto done;
}
if (lb->lb_n_buckets > 1)
{
+ HICN_ERROR ("DPO for route %U contains multiple next hops.",
+ format_ip_prefix, prefix);
ret = HICN_ERROR_ROUTE_MLT_LD;
goto done;
}
@@ -567,17 +580,37 @@ hicn_route_disable (fib_prefix_t *prefix)
hicn_fib_entry =
hicn_strategy_dpo_ctx_get (strategy_dpo_id->dpoi_index);
+ HICN_DEBUG ("Found from hicn_strategy_dpo_ctx_get with index %d: %p",
+ strategy_dpo_id->dpoi_index, hicn_fib_entry);
+
+ if (PREDICT_FALSE (!hicn_fib_entry))
+ {
+ HICN_ERROR (
+ "hicn_strategy_dpo_ctx_get for index %d returned NULL",
+ strategy_dpo_id->dpoi_index);
+ ret = HICN_ERROR_ROUTE_DPO_NO_HICN;
+ goto done;
+ }
+
for (int i = 0; i < hicn_fib_entry->entry_count; i++)
{
hicn_strategy_dpo_ctx_del_nh (hicn_fib_entry->next_hops[i],
hicn_fib_entry);
}
+
+ hicn_mapme_tfib_clear ((hicn_mapme_tfib_t *) hicn_fib_entry);
}
+ HICN_DEBUG (
+ "Calling fib_entry_untrack and fib_table_entry_special_remove "
+ "for route %U.",
+ format_fib_prefix, prefix);
+
fib_entry_untrack (hicn_fib_entry->fib_entry_index,
hicn_fib_entry->fib_sibling);
fib_table_entry_special_remove (fib_hicn_index, prefix, hicn_fib_src);
+ fib_node_unlock (&hicn_fib_entry->fib_node);
/* Disable the feature to punt data packet every time we enable a new
* hicn route */
@@ -618,7 +651,11 @@ hicn_fib_back_walk_notify (fib_node_t *node, fib_node_back_walk_ctx_t *ctx)
hicn_dpo_ctx_t *fib_entry = hicn_ctx_from_fib_node (node);
- sync_hicn_fib_entry (fib_entry);
+ hicn_face_id_t *vec_faces = NULL;
+ HICN_DEBUG ("Calling sync_hicn_fib_entry from hicn_fib_back_walk_notify");
+ sync_hicn_fib_entry (fib_entry, &vec_faces);
+ if (vec_faces != NULL)
+ vec_free (vec_faces);
return (FIB_NODE_BACK_WALK_CONTINUE);
}
@@ -661,7 +698,8 @@ enable_data_on_existing_hicn (fib_node_index_t fei, void *ctx)
goto done;
}
- enable_disable_data_receiving (strategy_dpo_id->dpoi_proto, sw_if, 1);
+ enable_disable_data_receiving (
+ (fib_protocol_t) strategy_dpo_id->dpoi_proto, sw_if, 1);
}
done:
@@ -673,18 +711,18 @@ set_table_interface_add_del (vnet_main_t *vnm, u32 sw_if_index, u32 is_add)
{
if (!is_add)
- return HICN_ERROR_NONE;
+ return NULL;
- int rv = ip_table_bind (FIB_PROTOCOL_IP4, sw_if_index, HICN_FIB_TABLE, 1);
+ int rv = ip_table_bind (FIB_PROTOCOL_IP4, sw_if_index, HICN_FIB_TABLE);
if (!rv)
{
- rv = ip_table_bind (FIB_PROTOCOL_IP6, sw_if_index, HICN_FIB_TABLE, 1);
+ rv = ip_table_bind (FIB_PROTOCOL_IP6, sw_if_index, HICN_FIB_TABLE);
if (rv)
{
/* An error occurred. Bind the interface back to the default fib */
- ip_table_bind (FIB_PROTOCOL_IP4, sw_if_index, 0, 1);
+ ip_table_bind (FIB_PROTOCOL_IP4, sw_if_index, 0);
}
}
@@ -707,10 +745,11 @@ set_table_interface_add_del (vnet_main_t *vnm, u32 sw_if_index, u32 is_add)
}
return rv ? clib_error_return (0, "unable to add hicn table to interface") :
- 0;
+ 0;
}
-VNET_SW_INTERFACE_ADD_DEL_FUNCTION (set_table_interface_add_del);
+VNET_SW_INTERFACE_ADD_DEL_FUNCTION_PRIO (set_table_interface_add_del,
+ VNET_ITF_FUNC_PRIORITY_HIGH);
void
hicn_route_init ()
@@ -720,7 +759,8 @@ hicn_route_init ()
hicn_fib_src =
fib_source_allocate ("hicn", FIB_SOURCE_HICN, FIB_SOURCE_BH_API);
- hicn_fib_node_type = fib_node_register_new_type (&hicn_fib_vft);
+ hicn_fib_node_type =
+ fib_node_register_new_type ("hicn_route_fib_node", &hicn_fib_vft);
ip_table_create (FIB_PROTOCOL_IP4, HICN_FIB_TABLE, 1, (const u8 *) "hicn4");
ip_table_create (FIB_PROTOCOL_IP6, HICN_FIB_TABLE, 1, (const u8 *) "hicn6");
diff --git a/hicn-plugin/src/route.h b/hicn-plugin/src/route.h
index 19b18b8c6..4fcb219c8 100644
--- a/hicn-plugin/src/route.h
+++ b/hicn-plugin/src/route.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -73,28 +73,31 @@ int hicn_route_get_dpo (const fib_prefix_t *prefix, const dpo_id_t **hicn_dpo,
int hicn_route_set_strategy (fib_prefix_t *prefix, u32 strategy_id);
/**
- * @Brief Helper to add a nex hop in the vrf 0. If there are no entries in the
- * vrf 0 that matches with the prefix (epm), a new one is created.
+ * @Brief Helper to add an adj nex hop in the vrf 0. If there are no entries in
+ * the vrf 0 that matches with the prefix (epm), a new one is created.
*
* @param fib_proto FIB_PROTOCOL_IP6 or FIB_PROTOCOL_IP4 (mpls not supported)
- * @param pfx Prefix for which to add a next hop
+ * @param rpfx Prefix for which to add a next hop
* @param nh Next hop to add
* @param sw_if Software interface index to add in the next hop
*/
-int ip_nh_add_helper (fib_protocol_t fib_proto, const fib_prefix_t *pfx,
- ip46_address_t *nh, u32 sw_if);
+int ip_nh_adj_add_del_helper (fib_protocol_t fib_proto,
+ const fib_prefix_t *rpfx, ip46_address_t *nh,
+ u32 sw_if, u8 is_add);
/**
- * @Brief Helper to remove a nex hop in the vrf 0. If there are no entries in
- * the vrf 0 nothing happens.
+ * @Brief Helper to add an udp-tunnel nex hop in the vrf 0. If there are no
+ * entries in the vrf 0 that matches with the prefix (epm), a new one is
+ * created.
*
* @param fib_proto FIB_PROTOCOL_IP6 or FIB_PROTOCOL_IP4 (mpls not supported)
- * @param pfx Prefix for which to remove a next hop
- * @param nh Next hop to remove
- * @param sw_if Software interface index in the next hop definition
+ * @param rpfx Prefix for which to add a next hop
+ * @param uei The UDP ENCAP ID
+ * @param proto The payload proto for this encap
*/
-int ip_nh_del_helper (fib_protocol_t fib_proto, const fib_prefix_t *rpfx,
- ip46_address_t *nh, u32 sw_if);
+int ip_nh_udp_tunnel_add_del_helper (fib_protocol_t fib_proto,
+ const fib_prefix_t *rpfx, u32 uei,
+ dpo_proto_t proto, u8 is_add);
/**
* @Brief Enable an hICN for an ip prefix
@@ -106,7 +109,9 @@ int ip_nh_del_helper (fib_protocol_t fib_proto, const fib_prefix_t *rpfx,
* loadbalancer in the vrf HICN already contains a dpo which is not an hICN one
* HICN_ERROR_ROUTE_MLT_LD if there are more than a dpo in the vpp loadbalancer
*/
-int hicn_route_enable (fib_prefix_t *prefix);
+int hicn_route_enable (const fib_prefix_t *prefix,
+ fib_node_index_t *hicn_fib_node_index,
+ hicn_face_id_t **vec_faces);
/**
* @Brief Disable an hICN for an ip prefix. If hICN wasn't enable on the prefix
diff --git a/hicn-plugin/src/state.h b/hicn-plugin/src/state.h
index 561aef2db..e80e81e29 100644
--- a/hicn-plugin/src/state.h
+++ b/hicn-plugin/src/state.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,7 +21,6 @@
#include "hicn.h"
#include "pcs.h"
-#include "hashtb.h"
#include "strategy.h"
#include "strategy_dpo_ctx.h"
#include "strategy_dpo_manager.h"
@@ -51,26 +50,14 @@
* @param hash_entry entry in the hash table referring to the buffer
*/
always_inline void
-hicn_get_internal_state (hicn_buffer_t *hicnb, hicn_pit_cs_t *pitcs,
- hicn_hash_node_t **node,
+hicn_get_internal_state (hicn_buffer_t *hicnb, u32 *pit_entry_index,
const hicn_strategy_vft_t **strategy_vft,
- const hicn_dpo_vft_t **dpo_vft, u8 *dpo_ctx_id,
- hicn_hash_entry_t **hash_entry)
+ const hicn_dpo_vft_t **dpo_vft, u8 *dpo_ctx_id)
{
- *node = pool_elt_at_index (pitcs->pcs_table->ht_nodes, hicnb->node_id);
+ *pit_entry_index = hicnb->pcs_entry_id;
*strategy_vft = hicn_dpo_get_strategy_vft (hicnb->vft_id);
*dpo_vft = hicn_dpo_get_vft (hicnb->vft_id);
*dpo_ctx_id = hicnb->dpo_ctx_id;
-
- hicn_hash_bucket_t *bucket;
- if (hicnb->hash_bucket_flags & HICN_HASH_NODE_OVERFLOW_BUCKET)
- bucket = pool_elt_at_index (pitcs->pcs_table->ht_overflow_buckets,
- hicnb->bucket_id);
- else
- bucket =
- (hicn_hash_bucket_t *) (pitcs->pcs_table->ht_buckets + hicnb->bucket_id);
-
- *hash_entry = &(bucket->hb_entries[hicnb->hash_entry_id]);
}
/*
@@ -83,30 +70,25 @@ hicn_get_internal_state (hicn_buffer_t *hicnb, hicn_pit_cs_t *pitcs,
* @brief Store the hicn state in the hicn buffer
*
* @param b vlib buffer holding the hICN packet
- * @param name_hash hash of the hICN name
- * @param node_id id of the node in the hash table referring to the buffer
- * @param dpo_ctx_id id of the dpo context id corresponding to the buffer
- * @param vft_id id of the strategy vft corresponding to the buffer
- * @param hash_entry_id id of the entry in the hash table referring to the
- * buffer
- * @param bucket_id id of the hasth table bucket that holds the hash entry
- * @param bucket_is_overflow 1 if the bucket is from the ht_overflow_buckets
- * pool 0 if the bucket is from the ht_buckets pool
+ * @param pcs_entry_index index of the PCS entry
*/
-always_inline void
-hicn_store_internal_state (vlib_buffer_t *b, u64 name_hash, u32 node_id,
- u8 dpo_ctx_id, u8 vft_id, u8 hash_entry_id,
- u32 bucket_id, u8 bucket_is_overflow)
+always_inline int
+hicn_store_internal_state (vlib_buffer_t *b, u32 pcs_entry_index,
+ u32 dpo_ctx_id)
{
hicn_buffer_t *hicnb = hicn_get_buffer (b);
- hicnb->name_hash = name_hash;
- hicnb->node_id = node_id;
+
hicnb->dpo_ctx_id = dpo_ctx_id;
- hicnb->vft_id = vft_id;
- hicnb->hash_entry_id = hash_entry_id;
- hicnb->bucket_id = bucket_id;
- hicnb->hash_bucket_flags =
- HICN_HASH_NODE_OVERFLOW_BUCKET * bucket_is_overflow;
+ const hicn_dpo_ctx_t *dpo_ctx =
+ hicn_strategy_dpo_ctx_get (hicnb->dpo_ctx_id);
+
+ if (PREDICT_FALSE (dpo_ctx == NULL))
+ return HICN_ERROR_DPO_CTX_NOT_FOUND;
+
+ hicnb->vft_id = dpo_ctx->dpo_type;
+ hicnb->pcs_entry_id = pcs_entry_index;
+
+ return HICN_ERROR_NONE;
}
#endif /* // __HICN_STATE__ */
diff --git a/hicn-plugin/src/strategies/dpo_lr.c b/hicn-plugin/src/strategies/dpo_lr.c
new file mode 100644
index 000000000..59409e25e
--- /dev/null
+++ b/hicn-plugin/src/strategies/dpo_lr.c
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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 "dpo_lr.h"
+#include "strategy_lr.h"
+#include "../strategy_dpo_manager.h"
+#include "../strategy_dpo_ctx.h"
+
+/**
+ * @brief DPO type value for the lr_strategy
+ */
+static dpo_type_t hicn_dpo_type_lr;
+
+static const hicn_dpo_vft_t hicn_dpo_lr_vft = {
+ .hicn_dpo_is_type = &hicn_dpo_is_type_strategy_lr,
+ .hicn_dpo_get_type = &hicn_dpo_strategy_lr_get_type,
+ .hicn_dpo_module_init = &hicn_dpo_strategy_lr_module_init,
+ .hicn_dpo_create = &hicn_strategy_lr_ctx_create,
+ .hicn_dpo_update_type = &hicn_strategy_lr_update_ctx_type,
+ .hicn_dpo_add_update_nh = &hicn_strategy_lr_ctx_add_nh,
+ .hicn_dpo_del_nh = &hicn_strategy_lr_ctx_del_nh,
+ .hicn_dpo_format = &hicn_dpo_strategy_lr_format
+};
+
+const static dpo_vft_t dpo_strategy_lr_ctx_vft = {
+ .dv_lock = hicn_strategy_dpo_ctx_lock,
+ .dv_unlock = hicn_strategy_dpo_ctx_unlock,
+ .dv_format = hicn_strategy_dpo_format,
+};
+
+int
+hicn_dpo_is_type_strategy_lr (const dpo_id_t *dpo)
+{
+ return dpo->dpoi_type == hicn_dpo_type_lr;
+}
+
+void
+hicn_dpo_strategy_lr_module_init (void)
+{
+ /*
+ * Register our type of dpo
+ */
+ hicn_dpo_type_lr = hicn_dpo_register_new_type (
+ hicn_nodes_strategy, &hicn_dpo_lr_vft, hicn_lr_strategy_get_vft (),
+ &dpo_strategy_lr_ctx_vft);
+}
+
+dpo_type_t
+hicn_dpo_strategy_lr_get_type (void)
+{
+ return hicn_dpo_type_lr;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+u8 *
+hicn_dpo_strategy_lr_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent)
+{
+ int i = 0;
+
+ s = format (s, "hicn-lr");
+
+ for (i = 0; i < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; i++)
+ {
+ u8 *buf = NULL;
+ if (i < dpo_ctx->entry_count)
+ buf = format (NULL, "FIB");
+ else if (i >= HICN_PARAM_FIB_ENTRY_NHOPS_MAX - dpo_ctx->tfib_entry_count)
+ buf = format (NULL, "TFIB");
+ else
+ continue;
+
+ s = format (s, "\n");
+ s = format (s, "%U ", format_hicn_face, dpo_ctx->next_hops[i], indent);
+ s = format (s, " %s", buf);
+ }
+
+ return (s);
+}
+
+void
+hicn_strategy_lr_ctx_create (fib_protocol_t proto,
+ const hicn_face_id_t *next_hop, int nh_len,
+ index_t *dpo_idx)
+{
+ hicn_dpo_ctx_t *hicn_strategy_ctx;
+
+ /* Allocate a hicn_dpo_ctx on the vpp pool and initialize it */
+ hicn_strategy_ctx = hicn_strategy_dpo_ctx_alloc ();
+
+ *dpo_idx = hicn_strategy_dpo_ctx_get_index (hicn_strategy_ctx);
+
+ init_dpo_ctx (hicn_strategy_ctx, next_hop, nh_len, hicn_dpo_type_lr,
+ (dpo_proto_t) proto);
+}
+
+void
+hicn_strategy_lr_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx)
+{
+ hicn_strategy_ctx->dpo_type = hicn_dpo_type_lr;
+ // don't care to reset data, it is not used
+}
+
+int
+hicn_strategy_lr_ctx_add_nh (hicn_face_id_t nh, index_t dpo_idx)
+{
+ hicn_dpo_ctx_t *hicn_strategy_dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
+ u8 pos = 0;
+
+ if (hicn_strategy_dpo_ctx == NULL)
+ {
+ return HICN_ERROR_STRATEGY_NOT_FOUND;
+ }
+
+ hicn_strategy_dpo_ctx_add_nh (nh, hicn_strategy_dpo_ctx, &pos);
+ // nothing else to initialize in this strategy
+ return HICN_ERROR_NONE;
+}
+
+int
+hicn_strategy_lr_ctx_del_nh (hicn_face_id_t face_id, index_t dpo_idx)
+{
+ hicn_dpo_ctx_t *hicn_strategy_dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
+ // No need to change the current_nhop. It will be updated at the next
+ // selection.
+ return hicn_strategy_dpo_ctx_del_nh (face_id, hicn_strategy_dpo_ctx);
+}
diff --git a/hicn-plugin/src/strategies/dpo_lr.h b/hicn-plugin/src/strategies/dpo_lr.h
new file mode 100644
index 000000000..757b96db6
--- /dev/null
+++ b/hicn-plugin/src/strategies/dpo_lr.h
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+#ifndef __HICN_DPO_LR_H__
+#define __HICN_DPO_LR_H__
+
+#include <vnet/dpo/dpo.h>
+#include "../strategy_dpo_ctx.h"
+
+/**
+ * @file dpo_lr.h
+ *
+ * This file implements the strategy vtf (see strategy.h) and
+ * the dpo vft (see strategy_dpo_manager.h) for the strategy
+ * local-remote.
+ */
+
+typedef struct hicn_strategy_lr_ctx_s
+{
+} hicn_strategy_lr_ctx_t;
+
+/**
+ * @brief Format the dpo ctx for a human-readable string
+ *
+ * @param s String to which to append the formatted dpo ctx
+ * @param dpo_ctx DPO context
+ * @param indent Indentation
+ *
+ * @result The string with the formatted dpo ctx
+ */
+u8 *hicn_dpo_strategy_lr_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent);
+
+/**
+ * @brief Retrieve an hicn_strategy_lr_ctx object
+ *
+ * @param indext Index of the hicn_dpo_ctx to retrieve
+ * @return The hicn_dpo_ctx object or NULL
+ */
+hicn_dpo_ctx_t *hicn_strategy_lr_ctx_get (index_t index);
+
+/**
+ * @brief Create a new local-remote ctx
+ *
+ * @param proto The protocol to which the dpo is meant for (see vpp docs)
+ * @param next_hop A list of next hops to be inserted in the dpo ctx
+ * @param nh_len Size of the list
+ * @param dpo_idx index_t that will hold the index of the created dpo ctx
+ * @return HICN_ERROR_NONE if the creation was fine, otherwise EINVAL
+ */
+void hicn_strategy_lr_ctx_create (fib_protocol_t proto,
+ const hicn_face_id_t *next_hop, int nh_len,
+ index_t *dpo_idx);
+
+/**
+ * @brief Update existing ctx setting it to local-remote
+ *
+ * @param hicn_strategy_ctx pointer to the ctx to update
+ */
+void hicn_strategy_lr_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx);
+
+/**
+ * @brief Add or update a next hop in the dpo ctx.
+ *
+ * This function is meant to be used in the control plane and not in the data
+ * plane, as it is not optimized for the latter.
+ *
+ * @param nh Next hop to insert in the dpo ctx
+ * @param dpo_idx Index of the dpo ctx to update with the new or updated next
+ * hop
+ * @return HICN_ERROR_NONE if the update or insert was fine,
+ * otherwise HICN_ERROR_DPO_CTX_NOT_FOUND
+ */
+int hicn_strategy_lr_ctx_add_nh (hicn_face_id_t nh, index_t dpo_idx);
+
+/**
+ * @brief Delete a next hop in the dpo ctx.
+ *
+ * @param face_id Face identifier of the next hop
+ * @param dpo_idx Index of the dpo ctx to update with the new or updated next
+ * hop
+ * @return HICN_ERROR_NONE if the update or insert was fine,
+ * otherwise HICN_ERROR_DPO_CTS_NOT_FOUND
+ */
+int hicn_strategy_lr_ctx_del_nh (hicn_face_id_t face_id, index_t dpo_idx);
+
+/**
+ * @brief Prefetch a dpo
+ *
+ * @param dpo_idx Index of the dpo ctx to prefetch
+ */
+void hicn_strategy_lr_ctx_prefetch (index_t dpo_idx);
+
+/**
+ * @brief Return true if the dpo is of type strategy local-remote
+ *
+ * @param dpo Dpo to check the type
+ */
+int hicn_dpo_is_type_strategy_lr (const dpo_id_t *dpo);
+
+/**
+ * @brief Initialize the local-remote strategy
+ */
+void hicn_dpo_strategy_lr_module_init (void);
+
+/**
+ * @brief Return the dpo type for the local-remote strategy
+ */
+dpo_type_t hicn_dpo_strategy_lr_get_type (void);
+
+#endif // __HICN_DPO_LR_H__
diff --git a/hicn-plugin/src/strategies/dpo_mw.c b/hicn-plugin/src/strategies/dpo_mw.c
index 70ef7d7c9..9283f6a43 100644
--- a/hicn-plugin/src/strategies/dpo_mw.c
+++ b/hicn-plugin/src/strategies/dpo_mw.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,9 +28,16 @@ static const hicn_dpo_vft_t hicn_dpo_mw_vft = {
.hicn_dpo_get_type = &hicn_dpo_strategy_mw_get_type,
.hicn_dpo_module_init = &hicn_dpo_strategy_mw_module_init,
.hicn_dpo_create = &hicn_strategy_mw_ctx_create,
+ .hicn_dpo_update_type = &hicn_strategy_mw_update_ctx_type,
.hicn_dpo_add_update_nh = &hicn_strategy_mw_ctx_add_nh,
.hicn_dpo_del_nh = &hicn_strategy_mw_ctx_del_nh,
- .hicn_dpo_format = &hicn_strategy_mw_format_ctx
+ .hicn_dpo_format = &hicn_dpo_strategy_mw_format
+};
+
+const static dpo_vft_t dpo_strategy_mw_ctx_vft = {
+ .dv_lock = &hicn_strategy_dpo_ctx_lock,
+ .dv_unlock = &hicn_strategy_dpo_ctx_unlock,
+ .dv_format = &hicn_strategy_dpo_format
};
int
@@ -59,27 +66,10 @@ hicn_dpo_strategy_mw_get_type (void)
//////////////////////////////////////////////////////////////////////////////////////////////////
u8 *
-hicn_strategy_mw_format_ctx (u8 *s, int n, ...)
+hicn_dpo_strategy_mw_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent)
{
- va_list args;
- va_start (args, n);
- s = format_hicn_strategy_mw_ctx (s, &args);
- return s;
-}
-
-u8 *
-format_hicn_strategy_mw_ctx (u8 *s, va_list *ap)
-{
- int i = 0;
- index_t index = va_arg (*ap, index_t);
- hicn_dpo_ctx_t *dpo_ctx = NULL;
hicn_strategy_mw_ctx_t *mw_dpo_ctx = NULL;
- u32 indent = va_arg (*ap, u32);
- ;
-
- dpo_ctx = hicn_strategy_dpo_ctx_get (index);
- if (dpo_ctx == NULL)
- return s;
+ int i = 0;
mw_dpo_ctx = (hicn_strategy_mw_ctx_t *) dpo_ctx->data;
@@ -117,8 +107,22 @@ hicn_strategy_mw_ctx_create (fib_protocol_t proto,
*dpo_idx = hicn_strategy_dpo_ctx_get_index (hicn_strategy_ctx);
- init_dpo_ctx (hicn_strategy_ctx, next_hop, nh_len, hicn_dpo_type_mw, proto);
+ HICN_DEBUG ("Successful hicn_strategy_dpo_ctx_alloc with index %d",
+ *dpo_idx);
+
+ init_dpo_ctx (hicn_strategy_ctx, next_hop, nh_len, hicn_dpo_type_mw,
+ (dpo_proto_t) proto);
+
+ memset (hicn_strategy_mw_ctx->weight, 0, HICN_PARAM_FIB_ENTRY_NHOPS_MAX);
+}
+
+void
+hicn_strategy_mw_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx)
+{
+ hicn_strategy_mw_ctx_t *hicn_strategy_mw_ctx;
+ hicn_strategy_mw_ctx = (hicn_strategy_mw_ctx_t *) hicn_strategy_ctx->data;
+ hicn_strategy_ctx->dpo_type = hicn_dpo_type_mw;
memset (hicn_strategy_mw_ctx->weight, 0, HICN_PARAM_FIB_ENTRY_NHOPS_MAX);
}
diff --git a/hicn-plugin/src/strategies/dpo_mw.h b/hicn-plugin/src/strategies/dpo_mw.h
index 1a174631a..f3ccf7e30 100644
--- a/hicn-plugin/src/strategies/dpo_mw.h
+++ b/hicn-plugin/src/strategies/dpo_mw.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -38,17 +38,12 @@ typedef struct hicn_strategy_mw_ctx_s
* @brief Format the dpo ctx for a human-readable string
*
* @param s String to which to append the formatted dpo ctx
- * @param ap List of parameters for the formatting
+ * @param dpo_ctx DPO context
+ * @param indent Indentation
*
* @result The string with the formatted dpo ctx
*/
-u8 *format_hicn_strategy_mw_ctx (u8 *s, va_list *ap);
-
-const static dpo_vft_t dpo_strategy_mw_ctx_vft = {
- .dv_lock = hicn_strategy_dpo_ctx_lock,
- .dv_unlock = hicn_strategy_dpo_ctx_unlock,
- .dv_format = format_hicn_strategy_mw_ctx,
-};
+u8 *hicn_dpo_strategy_mw_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent);
/**
* @brief Retrieve an hicn_strategy_mw_ctx object
@@ -72,6 +67,13 @@ void hicn_strategy_mw_ctx_create (fib_protocol_t proto,
index_t *dpo_idx);
/**
+ * @brief Update existing ctx setting it to mw
+ *
+ * @param hicn_strategy_ctx pointer to the ctx to update
+ */
+void hicn_strategy_mw_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx);
+
+/**
* @brief Add or update a next hop in the dpo ctx.
*
* This function is meant to be used in the control plane and not in the data
@@ -120,23 +122,6 @@ void hicn_dpo_strategy_mw_module_init (void);
*/
dpo_type_t hicn_dpo_strategy_mw_get_type (void);
-/**
- * @brief Format the dpo ctx for the strategy Maximum Weight
- *
- * @param s String to append the formatted dpo ctx
- * @param ap List of arguments to format
- */
-u8 *format_hicn_dpo_strategy_mw (u8 *s, va_list *ap);
-
-/**
- * @brief Format the dpo ctx for the strategy Maximum Weight. To
- * call from other functions
- *
- * @param s String to append the formatted dpo ctx
- * @param ... List of arguments to format
- */
-u8 *hicn_strategy_mw_format_ctx (u8 *s, int n, ...);
-
#endif // __HICN_DPO_MW_H__
/*
diff --git a/hicn-plugin/src/strategies/dpo_rp.c b/hicn-plugin/src/strategies/dpo_rp.c
new file mode 100644
index 000000000..eb32083b9
--- /dev/null
+++ b/hicn-plugin/src/strategies/dpo_rp.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "dpo_rp.h"
+#include "strategy_rp.h"
+#include "../strategy_dpo_manager.h"
+#include "../strategy_dpo_ctx.h"
+
+/**
+ * @brief DPO type value for the rp_strategy
+ */
+static dpo_type_t hicn_dpo_type_rp;
+
+static const hicn_dpo_vft_t hicn_dpo_rp_vft = {
+ .hicn_dpo_is_type = &hicn_dpo_is_type_strategy_rp,
+ .hicn_dpo_get_type = &hicn_dpo_strategy_rp_get_type,
+ .hicn_dpo_module_init = &hicn_dpo_strategy_rp_module_init,
+ .hicn_dpo_create = &hicn_strategy_rp_ctx_create,
+ .hicn_dpo_update_type = &hicn_strategy_rp_update_ctx_type,
+ .hicn_dpo_add_update_nh = &hicn_strategy_rp_ctx_add_nh,
+ .hicn_dpo_del_nh = &hicn_strategy_rp_ctx_del_nh,
+ .hicn_dpo_format = &hicn_dpo_strategy_rp_format
+};
+
+const static dpo_vft_t dpo_strategy_rp_ctx_vft = {
+ .dv_lock = hicn_strategy_dpo_ctx_lock,
+ .dv_unlock = hicn_strategy_dpo_ctx_unlock,
+ .dv_format = hicn_strategy_dpo_format,
+};
+
+int
+hicn_dpo_is_type_strategy_rp (const dpo_id_t *dpo)
+{
+ return dpo->dpoi_type == hicn_dpo_type_rp;
+}
+
+void
+hicn_dpo_strategy_rp_module_init (void)
+{
+ /*
+ * Register our type of dpo
+ */
+ hicn_dpo_type_rp = hicn_dpo_register_new_type (
+ hicn_nodes_strategy, &hicn_dpo_rp_vft, hicn_rp_strategy_get_vft (),
+ &dpo_strategy_rp_ctx_vft);
+}
+
+dpo_type_t
+hicn_dpo_strategy_rp_get_type (void)
+{
+ return hicn_dpo_type_rp;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+u8 *
+hicn_dpo_strategy_rp_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent)
+{
+ int i = 0;
+
+ for (i = 0; i < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; i++)
+ {
+ u8 *buf = NULL;
+ if (i < dpo_ctx->entry_count)
+ buf = format (NULL, "FIB");
+ else if (i >= HICN_PARAM_FIB_ENTRY_NHOPS_MAX - dpo_ctx->tfib_entry_count)
+ buf = format (NULL, "TFIB");
+ else
+ continue;
+
+ s = format (s, "\n");
+ s = format (s, "%U ", format_hicn_face, dpo_ctx->next_hops[i], indent);
+ s = format (s, " %s", buf);
+ }
+
+ return (s);
+}
+
+void
+hicn_strategy_rp_ctx_create (fib_protocol_t proto,
+ const hicn_face_id_t *next_hop, int nh_len,
+ index_t *dpo_idx)
+{
+ hicn_dpo_ctx_t *hicn_strategy_ctx;
+
+ /* Allocate a hicn_dpo_ctx on the vpp pool and initialize it */
+ hicn_strategy_ctx = hicn_strategy_dpo_ctx_alloc ();
+
+ *dpo_idx = hicn_strategy_dpo_ctx_get_index (hicn_strategy_ctx);
+
+ init_dpo_ctx (hicn_strategy_ctx, next_hop, nh_len, hicn_dpo_type_rp,
+ (dpo_proto_t) proto);
+}
+
+void
+hicn_strategy_rp_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx)
+{
+ hicn_strategy_ctx->dpo_type = hicn_dpo_type_rp;
+ // don't care to reset data, it is not used
+}
+
+int
+hicn_strategy_rp_ctx_add_nh (hicn_face_id_t nh, index_t dpo_idx)
+{
+ hicn_dpo_ctx_t *hicn_strategy_dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
+ u8 pos = 0;
+
+ if (hicn_strategy_dpo_ctx == NULL)
+ {
+ return HICN_ERROR_STRATEGY_NOT_FOUND;
+ }
+
+ hicn_strategy_dpo_ctx_add_nh (nh, hicn_strategy_dpo_ctx, &pos);
+ // nothing else to initialize in this strategy
+ return HICN_ERROR_NONE;
+}
+
+int
+hicn_strategy_rp_ctx_del_nh (hicn_face_id_t face_id, index_t dpo_idx)
+{
+ hicn_dpo_ctx_t *hicn_strategy_dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
+ // No need to change the current_nhop. It will be updated at the next
+ // selection.
+ return hicn_strategy_dpo_ctx_del_nh (face_id, hicn_strategy_dpo_ctx);
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/hicn-plugin/src/strategies/dpo_rp.h b/hicn-plugin/src/strategies/dpo_rp.h
new file mode 100644
index 000000000..bc3384b63
--- /dev/null
+++ b/hicn-plugin/src/strategies/dpo_rp.h
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __HICN_DPO_RP_H__
+#define __HICN_DPO_RP_H__
+
+#include <vnet/dpo/dpo.h>
+#include "../strategy_dpo_ctx.h"
+
+/**
+ * @file dpo_rp.h
+ *
+ * This file implements the strategy vtf (see strategy.h) and
+ * the dpo vft (see strategy_dpo_manager.h) for the strategy
+ * replication.
+ */
+
+typedef struct hicn_strategy_rp_ctx_s
+{
+} hicn_strategy_rp_ctx_t;
+
+/**
+ * @brief Format the dpo ctx for a human-readable string
+ *
+ * @param s String to which to append the formatted dpo ctx
+ * @param dpo_ctx DPO context
+ * @param indent Indentation
+ *
+ * @result The string with the formatted dpo ctx
+ */
+u8 *hicn_dpo_strategy_rp_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent);
+
+/**
+ * @brief Retrieve an hicn_strategy_rp_ctx object
+ *
+ * @param indext Index of the hicn_dpo_ctx to retrieve
+ * @return The hicn_dpo_ctx object or NULL
+ */
+hicn_dpo_ctx_t *hicn_strategy_rp_ctx_get (index_t index);
+
+/**
+ * @brief Create a new replication ctx
+ *
+ * @param proto The protocol to which the dpo is meant for (see vpp docs)
+ * @param next_hop A list of next hops to be inserted in the dpo ctx
+ * @param nh_len Size of the list
+ * @param dpo_idx index_t that will hold the index of the created dpo ctx
+ * @return HICN_ERROR_NONE if the creation was fine, otherwise EINVAL
+ */
+void hicn_strategy_rp_ctx_create (fib_protocol_t proto,
+ const hicn_face_id_t *next_hop, int nh_len,
+ index_t *dpo_idx);
+
+/**
+ * @brief Update existing ctx setting it to rp
+ *
+ * @param hicn_strategy_ctx pointer to the ctx to update
+ */
+void hicn_strategy_rp_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx);
+
+/**
+ * @brief Add or update a next hop in the dpo ctx.
+ *
+ * This function is meant to be used in the control plane and not in the data
+ * plane, as it is not optimized for the latter.
+ *
+ * @param nh Next hop to insert in the dpo ctx
+ * @param dpo_idx Index of the dpo ctx to update with the new or updated next
+ * hop
+ * @return HICN_ERROR_NONE if the update or insert was fine,
+ * otherwise HICN_ERROR_DPO_CTX_NOT_FOUND
+ */
+int hicn_strategy_rp_ctx_add_nh (hicn_face_id_t nh, index_t dpo_idx);
+
+/**
+ * @brief Delete a next hop in the dpo ctx.
+ *
+ * @param face_id Face identifier of the next hop
+ * @param dpo_idx Index of the dpo ctx to update with the new or updated next
+ * hop
+ * @return HICN_ERROR_NONE if the update or insert was fine,
+ * otherwise HICN_ERROR_DPO_CTS_NOT_FOUND
+ */
+int hicn_strategy_rp_ctx_del_nh (hicn_face_id_t face_id, index_t dpo_idx);
+
+/**
+ * @brief Prefetch a dpo
+ *
+ * @param dpo_idx Index of the dpo ctx to prefetch
+ */
+void hicn_strategy_rp_ctx_prefetch (index_t dpo_idx);
+
+/**
+ * @brief Return true if the dpo is of type strategy rp
+ *
+ * @param dpo Dpo to check the type
+ */
+int hicn_dpo_is_type_strategy_rp (const dpo_id_t *dpo);
+
+/**
+ * @brief Initialize the Replication strategy
+ */
+void hicn_dpo_strategy_rp_module_init (void);
+
+/**
+ * @brief Return the dpo type for the Replication strategy
+ */
+dpo_type_t hicn_dpo_strategy_rp_get_type (void);
+
+#endif // __HICN_DPO_RP_H__
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/hicn-plugin/src/strategies/dpo_rr.c b/hicn-plugin/src/strategies/dpo_rr.c
index 3fe506bd1..1fb72b953 100644
--- a/hicn-plugin/src/strategies/dpo_rr.c
+++ b/hicn-plugin/src/strategies/dpo_rr.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,9 +28,16 @@ static const hicn_dpo_vft_t hicn_dpo_rr_vft = {
.hicn_dpo_get_type = &hicn_dpo_strategy_rr_get_type,
.hicn_dpo_module_init = &hicn_dpo_strategy_rr_module_init,
.hicn_dpo_create = &hicn_strategy_rr_ctx_create,
+ .hicn_dpo_update_type = &hicn_strategy_rr_update_ctx_type,
.hicn_dpo_add_update_nh = &hicn_strategy_rr_ctx_add_nh,
.hicn_dpo_del_nh = &hicn_strategy_rr_ctx_del_nh,
- .hicn_dpo_format = &hicn_strategy_rr_format_ctx
+ .hicn_dpo_format = &hicn_dpo_strategy_rr_format
+};
+
+const static dpo_vft_t dpo_strategy_rr_ctx_vft = {
+ .dv_lock = hicn_strategy_dpo_ctx_lock,
+ .dv_unlock = hicn_strategy_dpo_ctx_unlock,
+ .dv_format = hicn_strategy_dpo_format,
};
int
@@ -59,26 +66,10 @@ hicn_dpo_strategy_rr_get_type (void)
//////////////////////////////////////////////////////////////////////////////////////////////////
u8 *
-hicn_strategy_rr_format_ctx (u8 *s, int n, ...)
-{
- va_list args;
- va_start (args, n);
- s = format_hicn_strategy_rr_ctx (s, &args);
- return s;
-}
-
-u8 *
-format_hicn_strategy_rr_ctx (u8 *s, va_list *ap)
+hicn_dpo_strategy_rr_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent)
{
int i = 0;
- index_t index = va_arg (*ap, index_t);
- hicn_dpo_ctx_t *dpo_ctx = NULL;
hicn_strategy_rr_ctx_t *rr_dpo_ctx = NULL;
- u32 indent = va_arg (*ap, u32);
-
- dpo_ctx = hicn_strategy_dpo_ctx_get (index);
- if (dpo_ctx == NULL)
- return s;
rr_dpo_ctx = (hicn_strategy_rr_ctx_t *) dpo_ctx->data;
@@ -117,8 +108,19 @@ hicn_strategy_rr_ctx_create (fib_protocol_t proto,
*dpo_idx = hicn_strategy_dpo_ctx_get_index (hicn_strategy_ctx);
- init_dpo_ctx (hicn_strategy_ctx, next_hop, nh_len, hicn_dpo_type_rr, proto);
+ init_dpo_ctx (hicn_strategy_ctx, next_hop, nh_len, hicn_dpo_type_rr,
+ (dpo_proto_t) proto);
+
+ hicn_strategy_rr_ctx->current_nhop = 0;
+}
+
+void
+hicn_strategy_rr_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx)
+{
+ hicn_strategy_rr_ctx_t *hicn_strategy_rr_ctx;
+ hicn_strategy_rr_ctx = (hicn_strategy_rr_ctx_t *) hicn_strategy_ctx->data;
+ hicn_strategy_ctx->dpo_type = hicn_dpo_type_rr;
hicn_strategy_rr_ctx->current_nhop = 0;
}
diff --git a/hicn-plugin/src/strategies/dpo_rr.h b/hicn-plugin/src/strategies/dpo_rr.h
index e68e2917d..363174bb2 100644
--- a/hicn-plugin/src/strategies/dpo_rr.h
+++ b/hicn-plugin/src/strategies/dpo_rr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -40,17 +40,12 @@ typedef struct hicn_strategy_rr_ctx_s
* @brief Format the dpo ctx for a human-readable string
*
* @param s String to which to append the formatted dpo ctx
- * @param ap List of parameters for the formatting
+ * @param dpo_ctx DPO context
+ * @param indent Indentation
*
* @result The string with the formatted dpo ctx
*/
-u8 *format_hicn_strategy_rr_ctx (u8 *s, va_list *ap);
-
-const static dpo_vft_t dpo_strategy_rr_ctx_vft = {
- .dv_lock = hicn_strategy_dpo_ctx_lock,
- .dv_unlock = hicn_strategy_dpo_ctx_unlock,
- .dv_format = format_hicn_strategy_rr_ctx,
-};
+u8 *hicn_dpo_strategy_rr_format (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent);
/**
* @brief Retrieve an hicn_strategy_rr_ctx object
@@ -74,6 +69,13 @@ void hicn_strategy_rr_ctx_create (fib_protocol_t proto,
index_t *dpo_idx);
/**
+ * @brief Update existing ctx setting it to rr
+ *
+ * @param hicn_strategy_ctx pointer to the ctx to update
+ */
+void hicn_strategy_rr_update_ctx_type (hicn_dpo_ctx_t *hicn_strategy_ctx);
+
+/**
* @brief Add or update a next hop in the dpo ctx.
*
* This function is meant to be used in the control plane and not in the data
@@ -122,23 +124,6 @@ void hicn_dpo_strategy_rr_module_init (void);
*/
dpo_type_t hicn_dpo_strategy_rr_get_type (void);
-/**
- * @brief Format the dpo ctx for the strategy Round Robin
- *
- * @param s String to append the formatted dpo ctx
- * @param ap List of arguments to format
- */
-u8 *format_hicn_dpo_strategy_rr (u8 *s, va_list *ap);
-
-/**
- * @brief Format the dpo ctx for the strategy Round Robin. To
- * call from other functions
- *
- * @param s String to append the formatted dpo ctx
- * @param ... List of arguments to format
- */
-u8 *hicn_strategy_rr_format_ctx (u8 *s, int n, ...);
-
#endif // __HICN_DPO_RR_H__
/*
diff --git a/hicn-plugin/src/strategies/strategy_lr.c b/hicn-plugin/src/strategies/strategy_lr.c
new file mode 100644
index 000000000..6bb4097ec
--- /dev/null
+++ b/hicn-plugin/src/strategies/strategy_lr.c
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "dpo_lr.h"
+#include "../strategy.h"
+#include "../strategy_dpo_ctx.h"
+#include "../faces/face.h"
+#include "../strategy_dpo_manager.h"
+
+/* Simple strategy that forwards intertests to all next hops */
+/* It does not require to exend the hicn_dpo */
+void hicn_receive_data_lr (index_t dpo_idx, int nh_idx);
+void hicn_add_interest_lr (index_t dpo_idx);
+int hicn_send_after_aggregation_lr (index_t dpo_idx, hicn_face_id_t in_face);
+void hicn_on_interest_timeout_lr (index_t dpo_idx);
+u32 hicn_select_next_hop_lr (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len);
+u8 *hicn_strategy_format_trace_lr (u8 *s, hicn_strategy_trace_t *t);
+u8 *hicn_strategy_format_lr (u8 *s, va_list *ap);
+
+static hicn_strategy_vft_t hicn_strategy_lr_vft = {
+ .hicn_receive_data = &hicn_receive_data_lr,
+ .hicn_add_interest = &hicn_add_interest_lr,
+ .hicn_send_after_aggregation = &hicn_send_after_aggregation_lr,
+ .hicn_on_interest_timeout = &hicn_on_interest_timeout_lr,
+ .hicn_select_next_hop = &hicn_select_next_hop_lr,
+ .hicn_format_strategy_trace = &hicn_strategy_format_trace_lr,
+ .hicn_format_strategy = &hicn_strategy_format_lr
+};
+
+/*
+ * Return the vft of the strategy.
+ */
+hicn_strategy_vft_t *
+hicn_lr_strategy_get_vft (void)
+{
+ return &hicn_strategy_lr_vft;
+}
+
+/* DPO should be given in input as it containes all the information to
+ * calculate the next hops*/
+u32
+hicn_select_next_hop_lr (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len)
+{
+ hicn_dpo_ctx_t *dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
+
+ *len = 0;
+
+ if (dpo_ctx == NULL || dpo_ctx->entry_count == 0)
+ {
+ return HICN_ERROR_STRATEGY_NOT_FOUND;
+ }
+
+ // Check if input face is local face
+ int in_is_local = hicn_face_is_local (in_face);
+
+ int i = 0;
+ while (i < MAX_OUT_FACES && i < dpo_ctx->entry_count)
+ {
+ if (hicn_face_is_local (dpo_ctx->next_hops[i]) != in_is_local)
+ {
+ outfaces[0] = dpo_ctx->next_hops[i];
+ *len = 1;
+ break;
+ }
+
+ i++;
+ }
+
+ return HICN_ERROR_NONE;
+}
+
+void
+hicn_add_interest_lr (index_t dpo_ctx_idx)
+{
+ /* Nothing to do */
+}
+
+int
+hicn_send_after_aggregation_lr (index_t dpo_idx, hicn_face_id_t in_face)
+{
+ if (hicn_face_is_local (in_face))
+ {
+ return true;
+ }
+
+ return false;
+}
+
+void
+hicn_on_interest_timeout_lr (index_t dpo_idx)
+{
+ /* Nothing to do in the lr strategy when we receive an interest */
+}
+
+void
+hicn_receive_data_lr (index_t dpo_idx, int nh_idx)
+{
+ /* nothing to do */
+}
+
+/* packet trace format function */
+u8 *
+hicn_strategy_format_trace_lr (u8 *s, hicn_strategy_trace_t *t)
+{
+ s = format (s,
+ "Strategy_lr: pkt: %d, sw_if_index %d, next index %d, dpo_type "
+ "%d, out_face %d",
+ (int) t->pkt_type, t->sw_if_index, t->next_index, t->dpo_type,
+ t->out_face);
+ return (s);
+}
+
+u8 *
+hicn_strategy_format_lr (u8 *s, va_list *ap)
+{
+
+ u32 indent = va_arg (*ap, u32);
+ s = format (
+ s, "Local-Remote: send from local face to remote only and viceversa \n",
+ indent);
+ return (s);
+}
diff --git a/hicn-light/src/hicn/processor/pitStandard.h b/hicn-plugin/src/strategies/strategy_lr.h
index 9d7ce6a23..826eb89a0 100644
--- a/hicn-light/src/hicn/processor/pitStandard.h
+++ b/hicn-plugin/src/strategies/strategy_lr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,29 +13,23 @@
* limitations under the License.
*/
+#ifndef __HICN_STRATEGY_LR_H__
+#define __HICN_STRATEGY_LR_H__
+
+#include "../strategy.h"
+
/**
- * @file pitStandard.h
- * @brief The Pending Interest Table
- *
- * Implements the standard Pending Interest Table.
+ * @file strategy_lr.h
*
+ * This file implements the local-remote strategy. In this
+ * strategy, if the interest is received from an application (local)
+ * face, it is then sent to a remote next hop. Viceversa, when an interest
+ * is received from a remote face, it is then sent to a local face.
*/
-#ifndef pitStandard_h
-#define pitStandard_h
-
-#include <hicn/processor/pit.h>
-
/**
- * Creates a PIT table
- *
- * Creates and allocates an emtpy PIT table. The Forwarder reference is
- * used for logging and for time functions.
- *
- * @param [in] hicn-light The releated Forwarder
- *
- * @return non-null a PIT table
- * @return null An error
+ * @brief Return the vft for the local-remote strategy
*/
-PIT *pitStandard_Create(Forwarder *forwarder);
-#endif // pit_h
+hicn_strategy_vft_t *hicn_lr_strategy_get_vft (void);
+
+#endif // __HICN_STRATEGY_LR_H__
diff --git a/hicn-plugin/src/strategies/strategy_mw.c b/hicn-plugin/src/strategies/strategy_mw.c
index 9409ec856..1f0210fbe 100644
--- a/hicn-plugin/src/strategies/strategy_mw.c
+++ b/hicn-plugin/src/strategies/strategy_mw.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,16 +16,16 @@
#include "../strategy.h"
#include "../strategy_dpo_ctx.h"
#include "../faces/face.h"
-#include "../hashtb.h"
#include "../strategy_dpo_manager.h"
/* Simple strategy that chooses the next hop with the maximum weight */
/* It does not require to exend the hicn_dpo */
void hicn_receive_data_mw (index_t dpo_idx, int nh_idx);
-void hicn_add_interest_mw (index_t dpo_idx, hicn_hash_entry_t *pit_entry);
+void hicn_add_interest_mw (index_t dpo_idx);
+int hicn_send_after_aggregation_mw (index_t dpo_idx, hicn_face_id_t in_face);
void hicn_on_interest_timeout_mw (index_t dpo_idx);
-u32 hicn_select_next_hop_mw (index_t dpo_idx, int *nh_idx,
- hicn_face_id_t *outface);
+u32 hicn_select_next_hop_mw (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len);
u32 get_strategy_node_index_mw (void);
u8 *hicn_strategy_format_trace_mw (u8 *s, hicn_strategy_trace_t *t);
u8 *hicn_strategy_format_mw (u8 *s, va_list *ap);
@@ -33,6 +33,7 @@ u8 *hicn_strategy_format_mw (u8 *s, va_list *ap);
static hicn_strategy_vft_t hicn_strategy_mw_vft = {
.hicn_receive_data = &hicn_receive_data_mw,
.hicn_add_interest = &hicn_add_interest_mw,
+ .hicn_send_after_aggregation = &hicn_send_after_aggregation_mw,
.hicn_on_interest_timeout = &hicn_on_interest_timeout_mw,
.hicn_select_next_hop = &hicn_select_next_hop_mw,
.hicn_format_strategy_trace = hicn_strategy_format_trace_mw,
@@ -51,12 +52,16 @@ hicn_mw_strategy_get_vft (void)
/* DPO should be give in input as it containes all the information to calculate
* the next hops*/
u32
-hicn_select_next_hop_mw (index_t dpo_idx, int *nh_idx, hicn_face_id_t *outface)
+hicn_select_next_hop_mw (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len)
{
hicn_dpo_ctx_t *dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
if (dpo_ctx == NULL)
- return HICN_ERROR_STRATEGY_NOT_FOUND;
+ {
+ *len = 0;
+ return HICN_ERROR_STRATEGY_NOT_FOUND;
+ }
hicn_strategy_mw_ctx_t *hicn_strategy_mw_ctx =
(hicn_strategy_mw_ctx_t *) dpo_ctx->data;
@@ -71,21 +76,21 @@ hicn_select_next_hop_mw (index_t dpo_idx, int *nh_idx, hicn_face_id_t *outface)
}
}
- *outface = dpo_ctx->next_hops[next_hop_index];
+ outfaces[0] = dpo_ctx->next_hops[next_hop_index];
+ *len = 1;
return HICN_ERROR_NONE;
}
void
-hicn_add_interest_mw (index_t dpo_ctx_idx, hicn_hash_entry_t *hash_entry)
+hicn_add_interest_mw (index_t dpo_ctx_idx)
+{
+}
+
+int
+hicn_send_after_aggregation_mw (index_t dpo_idx, hicn_face_id_t in_face)
{
- hash_entry->dpo_ctx_id = dpo_ctx_idx;
- dpo_id_t hicn_dpo_id = { .dpoi_type = hicn_dpo_strategy_mw_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = dpo_ctx_idx };
- hicn_strategy_dpo_ctx_lock (&hicn_dpo_id);
- hash_entry->vft_id = hicn_dpo_get_vft_id (&hicn_dpo_id);
+ return false;
}
void
diff --git a/hicn-plugin/src/strategies/strategy_mw.h b/hicn-plugin/src/strategies/strategy_mw.h
index 9e0078b23..186e8c5ab 100644
--- a/hicn-plugin/src/strategies/strategy_mw.h
+++ b/hicn-plugin/src/strategies/strategy_mw.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/strategies/strategy_mw_cli.c b/hicn-plugin/src/strategies/strategy_mw_cli.c
index 6b56e9fd5..4ace68423 100644
--- a/hicn-plugin/src/strategies/strategy_mw_cli.c
+++ b/hicn-plugin/src/strategies/strategy_mw_cli.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -76,7 +76,7 @@ hicn_mw_strategy_cli_set_weight_command_fn (vlib_main_t *vm,
}
prefix.fp_proto = ip46_address_is_ip4 (&prefix.fp_addr) ? FIB_PROTOCOL_IP4 :
- FIB_PROTOCOL_IP6;
+ FIB_PROTOCOL_IP6;
ret = hicn_route_get_dpo (&prefix, &hicn_dpo_id, &fib_index);
if (ret == HICN_ERROR_NONE)
diff --git a/hicn-plugin/src/strategies/strategy_rp.c b/hicn-plugin/src/strategies/strategy_rp.c
new file mode 100644
index 000000000..a44da1323
--- /dev/null
+++ b/hicn-plugin/src/strategies/strategy_rp.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "dpo_rp.h"
+#include "../strategy.h"
+#include "../strategy_dpo_ctx.h"
+#include "../faces/face.h"
+#include "../strategy_dpo_manager.h"
+
+/* Simple strategy that forwards intertests to all next hops */
+/* It does not require to exend the hicn_dpo */
+void hicn_receive_data_rp (index_t dpo_idx, int nh_idx);
+void hicn_add_interest_rp (index_t dpo_idx);
+int hicn_send_after_aggregation_rp (index_t dpo_idx, hicn_face_id_t in_face);
+void hicn_on_interest_timeout_rp (index_t dpo_idx);
+u32 hicn_select_next_hop_rp (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len);
+u8 *hicn_strategy_format_trace_rp (u8 *s, hicn_strategy_trace_t *t);
+u8 *hicn_strategy_format_rp (u8 *s, va_list *ap);
+
+static hicn_strategy_vft_t hicn_strategy_rp_vft = {
+ .hicn_receive_data = &hicn_receive_data_rp,
+ .hicn_add_interest = &hicn_add_interest_rp,
+ .hicn_on_interest_timeout = &hicn_on_interest_timeout_rp,
+ .hicn_select_next_hop = &hicn_select_next_hop_rp,
+ .hicn_format_strategy_trace = &hicn_strategy_format_trace_rp,
+ .hicn_format_strategy = &hicn_strategy_format_rp
+};
+
+/*
+ * Return the vft of the strategy.
+ */
+hicn_strategy_vft_t *
+hicn_rp_strategy_get_vft (void)
+{
+ return &hicn_strategy_rp_vft;
+}
+
+/* DPO should be give in input as it containes all the information to calculate
+ * the next hops*/
+u32
+hicn_select_next_hop_rp (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len)
+{
+ hicn_dpo_ctx_t *dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
+
+ if (dpo_ctx == NULL || dpo_ctx->entry_count == 0)
+ {
+ *len = 0;
+ return HICN_ERROR_STRATEGY_NOT_FOUND;
+ }
+
+ int i = 0;
+ while (i < MAX_OUT_FACES && i < dpo_ctx->entry_count)
+ {
+ outfaces[i] = dpo_ctx->next_hops[i];
+ i++;
+ }
+ *len = i;
+
+ return HICN_ERROR_NONE;
+}
+
+void
+hicn_add_interest_rp (index_t dpo_ctx_idx)
+{
+ /* Nothing to do */
+}
+
+int
+hicn_send_after_aggregation_rp (index_t dpo_idx, hicn_face_id_t in_face)
+{
+ return false;
+}
+
+void
+hicn_on_interest_timeout_rp (index_t dpo_idx)
+{
+ /* Nothing to do in the rp strategy when we receive an interest */
+}
+
+void
+hicn_receive_data_rp (index_t dpo_idx, int nh_idx)
+{
+ /* nothing to do */
+}
+
+/* packet trace format function */
+u8 *
+hicn_strategy_format_trace_rp (u8 *s, hicn_strategy_trace_t *t)
+{
+ s = format (s, "Strategy_rp: pkt: %d, sw_if_index %d, next index %d",
+ (int) t->pkt_type, t->sw_if_index, t->next_index);
+ return (s);
+}
+
+u8 *
+hicn_strategy_format_rp (u8 *s, va_list *ap)
+{
+
+ u32 indent = va_arg (*ap, u32);
+ s = format (s, "Replication: send to all the next hops \n", indent);
+ return (s);
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/hicn-plugin/src/strategies/strategy_rp.h b/hicn-plugin/src/strategies/strategy_rp.h
new file mode 100644
index 000000000..c308497cc
--- /dev/null
+++ b/hicn-plugin/src/strategies/strategy_rp.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __HICN_STRATEGY_RP_H__
+#define __HICN_STRATEGY_RP_H__
+
+#include "../strategy.h"
+
+/**
+ * @file strategy_rp.h
+ *
+ * This file implements the replication strategy. In this
+ * strategy all the next hops are used to send an intertest.
+ */
+
+/**
+ * @brief Return the vft for the Replication strategy
+ */
+hicn_strategy_vft_t *hicn_rp_strategy_get_vft (void);
+
+#endif // __HICN_STRATEGY_RP_H__
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/hicn-plugin/src/strategies/strategy_rr.c b/hicn-plugin/src/strategies/strategy_rr.c
index 9995191b7..af3cb320a 100644
--- a/hicn-plugin/src/strategies/strategy_rr.c
+++ b/hicn-plugin/src/strategies/strategy_rr.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,16 +17,16 @@
#include "../strategy.h"
#include "../strategy_dpo_ctx.h"
#include "../faces/face.h"
-#include "../hashtb.h"
#include "../strategy_dpo_manager.h"
/* Simple strategy that chooses the next hop with the maximum weight */
/* It does not require to exend the hicn_dpo */
void hicn_receive_data_rr (index_t dpo_idx, int nh_idx);
-void hicn_add_interest_rr (index_t dpo_idx, hicn_hash_entry_t *pit_entry);
+void hicn_add_interest_rr (index_t dpo_idx);
+int hicn_send_after_aggregation_rr (index_t dpo_idx, hicn_face_id_t in_face);
void hicn_on_interest_timeout_rr (index_t dpo_idx);
-u32 hicn_select_next_hop_rr (index_t dpo_idx, int *nh_idx,
- hicn_face_id_t *outface);
+u32 hicn_select_next_hop_rr (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len);
u8 *hicn_strategy_format_trace_rr (u8 *s, hicn_strategy_trace_t *t);
u8 *hicn_strategy_format_rr (u8 *s, va_list *ap);
@@ -51,17 +51,22 @@ hicn_rr_strategy_get_vft (void)
/* DPO should be give in input as it containes all the information to calculate
* the next hops*/
u32
-hicn_select_next_hop_rr (index_t dpo_idx, int *nh_idx, hicn_face_id_t *outface)
+hicn_select_next_hop_rr (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len)
{
hicn_dpo_ctx_t *dpo_ctx = hicn_strategy_dpo_ctx_get (dpo_idx);
if (dpo_ctx == NULL)
- return HICN_ERROR_STRATEGY_NOT_FOUND;
+ {
+ *len = 0;
+ return HICN_ERROR_STRATEGY_NOT_FOUND;
+ }
hicn_strategy_rr_ctx_t *hicn_strategy_rr_ctx =
(hicn_strategy_rr_ctx_t *) dpo_ctx->data;
- *outface = dpo_ctx->next_hops[hicn_strategy_rr_ctx->current_nhop];
+ outfaces[0] = dpo_ctx->next_hops[hicn_strategy_rr_ctx->current_nhop];
+ *len = 1;
hicn_strategy_rr_ctx->current_nhop =
(hicn_strategy_rr_ctx->current_nhop + 1) % dpo_ctx->entry_count;
@@ -70,15 +75,14 @@ hicn_select_next_hop_rr (index_t dpo_idx, int *nh_idx, hicn_face_id_t *outface)
}
void
-hicn_add_interest_rr (index_t dpo_ctx_idx, hicn_hash_entry_t *hash_entry)
+hicn_add_interest_rr (index_t dpo_ctx_idx)
{
- hash_entry->dpo_ctx_id = dpo_ctx_idx;
- dpo_id_t hicn_dpo_id = { .dpoi_type = hicn_dpo_strategy_rr_get_type (),
- .dpoi_proto = 0,
- .dpoi_next_node = 0,
- .dpoi_index = dpo_ctx_idx };
- hicn_strategy_dpo_ctx_lock (&hicn_dpo_id);
- hash_entry->vft_id = hicn_dpo_get_vft_id (&hicn_dpo_id);
+}
+
+int
+hicn_send_after_aggregation_rr (index_t dpo_idx, hicn_face_id_t in_face)
+{
+ return false;
}
void
diff --git a/hicn-plugin/src/strategies/strategy_rr.h b/hicn-plugin/src/strategies/strategy_rr.h
index 4dfe76b43..fb7520180 100644
--- a/hicn-plugin/src/strategies/strategy_rr.h
+++ b/hicn-plugin/src/strategies/strategy_rr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/strategy.h b/hicn-plugin/src/strategy.h
index 28af55f01..135aeea7b 100644
--- a/hicn-plugin/src/strategy.h
+++ b/hicn-plugin/src/strategy.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,7 +17,6 @@
#define __HICN_STRATEGY__
#include "hicn.h"
-#include "hashtb.h"
#include "mgmt.h"
#include "faces/face.h"
@@ -45,15 +44,17 @@ typedef struct
u32 sw_if_index;
u8 pkt_type;
dpo_type_t dpo_type;
+ hicn_face_id_t out_face;
} hicn_strategy_trace_t;
typedef struct hicn_strategy_vft_s
{
void (*hicn_receive_data) (index_t dpo_idx, int nh_idx);
void (*hicn_on_interest_timeout) (index_t dpo_idx);
- void (*hicn_add_interest) (index_t dpo_idx, hicn_hash_entry_t *pit_entry);
- u32 (*hicn_select_next_hop) (index_t dpo_idx, int *nh_idx,
- hicn_face_id_t *outface);
+ void (*hicn_add_interest) (index_t dpo_idx);
+ int (*hicn_send_after_aggregation) (index_t dpo_idx, hicn_face_id_t in_face);
+ u32 (*hicn_select_next_hop) (index_t dpo_idx, hicn_face_id_t in_face,
+ hicn_face_id_t *outfaces, u16 *len);
u8 *(*hicn_format_strategy_trace) (u8 *, hicn_strategy_trace_t *);
u8 *(*hicn_format_strategy) (u8 *s, va_list *ap);
/**< Format an hICN dpo*/
diff --git a/hicn-plugin/src/strategy_dpo_ctx.c b/hicn-plugin/src/strategy_dpo_ctx.c
index edfe75aa8..eb4173944 100644
--- a/hicn-plugin/src/strategy_dpo_ctx.c
+++ b/hicn-plugin/src/strategy_dpo_ctx.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,7 +21,8 @@ hicn_dpo_ctx_t *hicn_strategy_dpo_ctx_pool;
void
hicn_strategy_init_dpo_ctx_pool ()
{
- pool_init_fixed (hicn_strategy_dpo_ctx_pool, 256);
+ pool_alloc_aligned (hicn_strategy_dpo_ctx_pool, 256,
+ 2 * CLIB_CACHE_LINE_BYTES);
}
void
@@ -29,9 +30,16 @@ hicn_strategy_dpo_ctx_lock (dpo_id_t *dpo)
{
hicn_dpo_ctx_t *dpo_ctx = hicn_strategy_dpo_ctx_get (dpo->dpoi_index);
- if (dpo_ctx != NULL)
+ if (PREDICT_TRUE (dpo_ctx != NULL))
{
dpo_ctx->locks++;
+ HICN_DEBUG ("Locking DPO CTX with index %d. Lock now: %d",
+ dpo->dpoi_index, dpo_ctx->locks);
+ }
+ else
+ {
+ HICN_ERROR ("Trying to lock NULL spo_ctx with index %d",
+ dpo->dpoi_index);
}
}
@@ -41,31 +49,23 @@ hicn_strategy_dpo_ctx_unlock (dpo_id_t *dpo)
hicn_dpo_ctx_t *hicn_strategy_dpo_ctx =
(hicn_dpo_ctx_t *) hicn_strategy_dpo_ctx_get (dpo->dpoi_index);
- if (hicn_strategy_dpo_ctx != NULL)
+ if (PREDICT_TRUE (hicn_strategy_dpo_ctx != NULL))
{
hicn_strategy_dpo_ctx->locks--;
+ HICN_DEBUG ("Unlcking DPO CTX with index %d. Lock now: %d",
+ dpo->dpoi_index, hicn_strategy_dpo_ctx->locks);
if (0 == hicn_strategy_dpo_ctx->locks)
{
+ HICN_DEBUG ("Releasing DPO CTX %d", dpo->dpoi_index);
pool_put (hicn_strategy_dpo_ctx_pool, hicn_strategy_dpo_ctx);
}
}
-}
-
-u8 *
-hicn_strategy_dpo_format_ctx (u8 *s, va_list *ap)
-{
- index_t index = va_arg (*ap, index_t);
- hicn_dpo_ctx_t *dpo = NULL;
- u32 indent = va_arg (*ap, u32);
-
- dpo = (hicn_dpo_ctx_t *) hicn_strategy_dpo_ctx_get (index);
-
- const hicn_dpo_vft_t *dpo_vft = hicn_dpo_get_vft (dpo->dpo_type);
-
- s = dpo_vft->hicn_dpo_format (s, 2, index, indent);
-
- return (s);
+ else
+ {
+ HICN_ERROR ("Trying to unlock NULL spo_ctx with index %d",
+ dpo->dpoi_index);
+ }
}
index_t
@@ -90,8 +90,11 @@ hicn_strategy_dpo_ctx_get (index_t index)
hicn_dpo_ctx_t *
hicn_strategy_dpo_ctx_alloc ()
{
+ HICN_DEBUG ("Allocating new DPO CTX");
hicn_dpo_ctx_t *dpo_ctx;
- pool_get (hicn_strategy_dpo_ctx_pool, dpo_ctx);
+ pool_get_aligned (hicn_strategy_dpo_ctx_pool, dpo_ctx,
+ 2 * CLIB_CACHE_LINE_BYTES);
+ dpo_ctx->locks = 0;
return dpo_ctx;
}
diff --git a/hicn-plugin/src/strategy_dpo_ctx.h b/hicn-plugin/src/strategy_dpo_ctx.h
index fe63a4258..ae642a350 100644
--- a/hicn-plugin/src/strategy_dpo_ctx.h
+++ b/hicn-plugin/src/strategy_dpo_ctx.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -99,6 +99,7 @@ init_dpo_ctx (hicn_dpo_ctx_t *dpo_ctx, const hicn_face_id_t *next_hop,
int nh_len, dpo_type_t dpo_type, dpo_proto_t proto)
{
hicn_face_id_t invalid = NEXT_HOP_INVALID;
+ int i = 0;
dpo_ctx->entry_count = 0;
dpo_ctx->locks = 0;
@@ -108,15 +109,15 @@ init_dpo_ctx (hicn_dpo_ctx_t *dpo_ctx, const hicn_face_id_t *next_hop,
dpo_ctx->seq = INIT_SEQ;
dpo_ctx->dpo_type = dpo_type;
- dpo_ctx->proto = proto;
+ dpo_ctx->proto = (fib_protocol_t) proto;
- for (int i = 0; i < HICN_PARAM_FIB_ENTRY_NHOPS_MAX && i < nh_len; i++)
+ for (i = 0; i < HICN_PARAM_FIB_ENTRY_NHOPS_MAX && i < nh_len; i++)
{
dpo_ctx->next_hops[i] = next_hop[i];
dpo_ctx->entry_count++;
}
- for (int i = nh_len; i < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; i++)
+ for (; i < HICN_PARAM_FIB_ENTRY_NHOPS_MAX; i++)
{
dpo_ctx->next_hops[i] = invalid;
}
diff --git a/hicn-plugin/src/strategy_dpo_manager.c b/hicn-plugin/src/strategy_dpo_manager.c
index 3c441ccac..1e136b47b 100644
--- a/hicn-plugin/src/strategy_dpo_manager.c
+++ b/hicn-plugin/src/strategy_dpo_manager.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,6 +19,8 @@
#include "strategy_dpo_ctx.h"
#include "strategies/dpo_mw.h"
#include "strategies/dpo_rr.h"
+#include "strategies/dpo_rp.h"
+#include "strategies/dpo_lr.h"
#include "strategy.h"
#include "faces/face.h"
@@ -92,20 +94,31 @@ hicn_dpo_get_strategy_vft_from_id (u8 vfts_id)
return hicn_strategy_vfts[strategies_id[vfts_id]];
}
+u8 *
+hicn_strategy_dpo_format (u8 *s, va_list *ap)
+{
+ index_t index = va_arg (*ap, index_t);
+ hicn_dpo_ctx_t *dpo_ctx = NULL;
+ u32 indent = va_arg (*ap, u32);
+
+ dpo_ctx = hicn_strategy_dpo_ctx_get (index);
+ if (dpo_ctx == NULL)
+ return s;
+
+ return hicn_dpo_vfts[dpo_ctx->dpo_type]->hicn_dpo_format (s, dpo_ctx,
+ indent);
+}
+
void
hicn_dpos_init (void)
{
hicn_strategy_init_dpo_ctx_pool ();
hicn_dpo_strategy_mw_module_init ();
hicn_dpo_strategy_rr_module_init ();
+ hicn_dpo_strategy_rp_module_init ();
+ hicn_dpo_strategy_lr_module_init ();
- default_dpo.hicn_dpo_is_type = &hicn_dpo_is_type_strategy_mw;
- default_dpo.hicn_dpo_get_type = &hicn_dpo_strategy_mw_get_type;
- default_dpo.hicn_dpo_module_init = &hicn_dpo_strategy_mw_module_init;
- default_dpo.hicn_dpo_create = &hicn_strategy_mw_ctx_create;
- default_dpo.hicn_dpo_add_update_nh = &hicn_strategy_mw_ctx_add_nh;
- default_dpo.hicn_dpo_del_nh = &hicn_strategy_mw_ctx_del_nh;
- default_dpo.hicn_dpo_format = &hicn_strategy_mw_format_ctx;
+ default_dpo = *hicn_dpo_vfts[hicn_dpo_strategy_mw_get_type ()];
}
u8 *
@@ -128,12 +141,12 @@ format_hicn_strategy_list (u8 *s, int n, ...)
return (s);
}
-u8
+int
hicn_dpo_strategy_id_is_valid (int strategy_id)
{
return vec_len (strategies_id) > strategy_id ?
- HICN_ERROR_NONE :
- HICN_ERROR_DPO_MGR_ID_NOT_VALID;
+ HICN_ERROR_NONE :
+ HICN_ERROR_DPO_MGR_ID_NOT_VALID;
}
int
diff --git a/hicn-plugin/src/strategy_dpo_manager.h b/hicn-plugin/src/strategy_dpo_manager.h
index 7a2ce3fee..0163cd679 100644
--- a/hicn-plugin/src/strategy_dpo_manager.h
+++ b/hicn-plugin/src/strategy_dpo_manager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -53,11 +53,13 @@ typedef struct hicn_dpo_vft_s
void (*hicn_dpo_create) (
fib_protocol_t proto, const hicn_face_id_t *nh, int nh_len,
index_t *dpo_idx); /**< Create the context of the hICN dpo */
+ void (*hicn_dpo_update_type) (
+ hicn_dpo_ctx_t *hicn_strategy_ctx); /**change dpo type */
int (*hicn_dpo_add_update_nh) (
hicn_face_id_t nh,
index_t dpo_idx); /**< Add a next hop to the hICN dpo context */
int (*hicn_dpo_del_nh) (hicn_face_id_t face_id, index_t dpo_idx);
- u8 *(*hicn_dpo_format) (u8 *s, int, ...);
+ u8 *(*hicn_dpo_format) (u8 *s, hicn_dpo_ctx_t *dpo_ctx, u32 indent);
/**< Format an hICN dpo*/
} hicn_dpo_vft_t;
@@ -171,7 +173,7 @@ u8 *format_hicn_strategy_list (u8 *s, int n, ...);
*
* @result HICN_ERROR_NONE is the id is valid, otherwise EINVAL
*/
-u8 hicn_dpo_strategy_id_is_valid (int strategy_id);
+int hicn_dpo_strategy_id_is_valid (int strategy_id);
/**
* @brief Return the number of available strategies. This number can be used to
@@ -187,6 +189,11 @@ int hicn_strategy_get_all_available (void);
*/
void hicn_dpo_register (const hicn_dpo_vft_t *hicn_dpo);
+/**
+ * @brief Format strategy DPO.
+ */
+u8 *hicn_strategy_dpo_format (u8 *s, va_list *ap);
+
#endif /* // __HICN_STRATEGY_DPO_MANAGER_H__ */
/*
diff --git a/hicn-plugin/src/strategy_node.c b/hicn-plugin/src/strategy_node.c
index ec57d76e2..add5772a4 100644
--- a/hicn-plugin/src/strategy_node.c
+++ b/hicn-plugin/src/strategy_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,11 +20,11 @@
#include "parser.h"
#include "strategy.h"
#include "strategy_dpo_ctx.h"
-#include "face_db.h"
#include "infra.h"
#include "mgmt.h"
#include "pcs.h"
#include "state.h"
+#include "data_fwd.h"
#include "strategies/strategy_mw.h"
/* Registration struct for a graph node */
@@ -60,97 +60,32 @@ hicn_strategy_format_trace (u8 *s, va_list *args)
return vft->hicn_format_strategy_trace (s, t);
}
-always_inline int
-hicn_new_interest (hicn_strategy_runtime_t *rt, vlib_buffer_t *b0, u32 *next,
- f64 tnow, u8 *nameptr, u16 namelen, hicn_face_id_t outface,
- int nh_idx, index_t dpo_ctx_id0,
- const hicn_strategy_vft_t *strategy, dpo_type_t dpo_type,
- u8 isv6, vl_api_hicn_api_node_stats_get_reply_t *stats)
+always_inline void
+drop_packet (vlib_main_t *vm, u32 bi0, u32 *n_left_to_next, u32 *next0,
+ u32 **to_next, u32 *next_index, vlib_node_runtime_t *node)
{
- int ret;
- hicn_hash_node_t *nodep;
- hicn_pcs_entry_t *pitp;
- hicn_header_t *hicn0;
- hicn_main_t *sm = &hicn_main;
- hicn_buffer_t *hicnb0 = hicn_get_buffer (b0);
- u32 node_id0 = 0;
- u8 vft_id0 = dpo_type;
- u8 is_cs0 = 0;
- u8 hash_entry_id = 0;
- u8 bucket_is_overflow = 0;
- u32 bucket_id = ~0;
-
- /* Create PIT node and init PIT entry */
- nodep = hicn_hashtb_alloc_node (rt->pitcs->pcs_table);
- if (PREDICT_FALSE (nodep == NULL))
- {
- /* Nothing we can do - no mem */
- *next = HICN_STRATEGY_NEXT_ERROR_DROP;
- return HICN_ERROR_HASHTB_NOMEM;
- }
- pitp = hicn_pit_get_data (nodep);
- hicn_pit_init_data (pitp);
- pitp->shared.create_time = tnow;
-
- hicn0 = vlib_buffer_get_current (b0);
- hicn_lifetime_t imsg_lifetime;
- hicn_type_t type = hicnb0->type;
- hicn_ops_vft[type.l1]->get_lifetime (type, &hicn0->protocol, &imsg_lifetime);
+ vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0);
- if (imsg_lifetime > sm->pit_lifetime_max_ms)
- {
- imsg_lifetime = sm->pit_lifetime_max_ms;
- }
- pitp->shared.expire_time = hicn_pcs_get_exp_time (tnow, imsg_lifetime);
+ *next0 = HICN_STRATEGY_NEXT_ERROR_DROP;
- /* Set up the hash node and insert it */
- hicn_hash_entry_t *hash_entry;
- hicn_hashtb_init_node (rt->pitcs->pcs_table, nodep, nameptr, namelen);
+ (*to_next)[0] = bi0;
+ *to_next += 1;
+ *n_left_to_next -= 1;
- ret = hicn_pcs_pit_insert (rt->pitcs, pitp, nodep, &hash_entry,
- hicnb0->name_hash, &node_id0, &dpo_ctx_id0,
- &vft_id0, &is_cs0, &hash_entry_id, &bucket_id,
- &bucket_is_overflow);
-
- if (ret == HICN_ERROR_NONE)
+ // Maybe trace
+ if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (b0->flags & VLIB_BUFFER_IS_TRACED)))
{
- strategy->hicn_add_interest (vnet_buffer (b0)->ip.adj_index[VLIB_TX],
- hash_entry);
-
- /* Add face */
- hicn_face_db_add_face (hicnb0->face_id, &(pitp->u.pit.faces));
-
- *next = isv6 ? HICN_STRATEGY_NEXT_INTEREST_FACE6 :
- HICN_STRATEGY_NEXT_INTEREST_FACE4;
-
- vnet_buffer (b0)->ip.adj_index[VLIB_TX] = outface;
- stats->pkts_interest_count++;
- pitp->u.pit.pe_txnh = nh_idx;
- }
- else
- {
- /* Interest aggregate in PIT */
- if (ret == HICN_ERROR_HASHTB_EXIST)
- {
- hicn_store_internal_state (b0, hicnb0->name_hash, node_id0,
- dpo_ctx_id0, vft_id0, hash_entry_id,
- bucket_id, bucket_is_overflow);
- // We need to take a lock as the lock is not taken on the hash
- // entry because it is a CS entry (hash_insert function).
- hash_entry->locks++;
- *next = is_cs0 ? HICN_STRATEGY_NEXT_INTEREST_HITCS :
- HICN_STRATEGY_NEXT_INTEREST_HITPIT;
- }
- else
- {
- /* Send the packet to the interest-hitpit node */
- *next = HICN_STRATEGY_NEXT_ERROR_DROP;
- }
- hicn_faces_flush (&(pitp->u.pit.faces));
- hicn_hashtb_free_node (rt->pitcs->pcs_table, nodep);
+ hicn_strategy_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST;
+ t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
+ t->next_index = *next0;
+ t->dpo_type = hicn_get_buffer (b0)->vft_id;
+ t->out_face = -1;
}
- return (ret);
+ vlib_validate_buffer_enqueue_x1 (vm, node, *next_index, *to_next,
+ *n_left_to_next, bi0, *next0);
}
/*
@@ -162,11 +97,19 @@ hicn_strategy_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
vlib_frame_t *frame)
{
+ int ret;
u32 n_left_from, *from, *to_next, n_left_to_next;
hicn_strategy_next_t next_index;
hicn_strategy_runtime_t *rt = NULL;
vl_api_hicn_api_node_stats_get_reply_t stats = { 0 };
- f64 tnow;
+ vlib_buffer_t *b0;
+ u32 bi0;
+ hicn_face_id_t outfaces[MAX_OUT_FACES];
+ u32 clones[MAX_OUT_FACES];
+ u16 outfaces_len;
+ u32 next0;
+ const hicn_strategy_vft_t *strategy;
+ hicn_buffer_t *hicnb0;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
@@ -174,97 +117,108 @@ hicn_strategy_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
rt = vlib_node_get_runtime_data (vm, hicn_strategy_node.index);
rt->pitcs = &hicn_main.pitcs;
/* Capture time in vpp terms */
- tnow = vlib_time_now (vm);
+ next0 = next_index;
while (n_left_from > 0)
{
-
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
- u8 isv6;
- u8 *nameptr;
- u16 namelen;
- hicn_name_t name;
- hicn_header_t *hicn0;
- vlib_buffer_t *b0;
- u32 bi0;
- hicn_face_id_t outface;
- int nh_idx;
- u32 next0 = next_index;
- int ret;
-
- /* Prefetch for next iteration. */
+ // Prefetch for next iteration
if (n_left_from > 1)
{
vlib_buffer_t *b1;
b1 = vlib_get_buffer (vm, from[1]);
- CLIB_PREFETCH (b1, CLIB_CACHE_LINE_BYTES, LOAD);
- CLIB_PREFETCH (&b1->trace_handle, 2 * CLIB_CACHE_LINE_BYTES,
- STORE);
+ CLIB_PREFETCH (b1, 2 * CLIB_CACHE_LINE_BYTES, LOAD);
}
- /* Dequeue a packet buffer */
+
+ // Dequeue a packet buffer
bi0 = from[0];
from += 1;
n_left_from -= 1;
- to_next[0] = bi0;
- to_next += 1;
- n_left_to_next -= 1;
-
b0 = vlib_get_buffer (vm, bi0);
- next0 = HICN_STRATEGY_NEXT_ERROR_DROP;
- hicn_dpo_ctx_t *dpo_ctx = hicn_strategy_dpo_ctx_get (
- vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
- const hicn_strategy_vft_t *strategy =
- hicn_dpo_get_strategy_vft (dpo_ctx->dpo_type);
+ // Drop by default
+ next0 = HICN_STRATEGY_NEXT_ERROR_DROP;
- ret = hicn_interest_parse_pkt (b0, &name, &namelen, &hicn0, &isv6);
+ // Increment counters
stats.pkts_processed++;
- /* Select next hop */
- /*
- * Double check that the interest has been through
- * the interest-pcslookup node due to misconfiguration in
- * the punting rules.
- */
- if (PREDICT_TRUE (ret == HICN_ERROR_NONE &&
- HICN_IS_NAMEHASH_CACHED (b0) &&
- strategy->hicn_select_next_hop (
- vnet_buffer (b0)->ip.adj_index[VLIB_TX], &nh_idx,
- &outface) == HICN_ERROR_NONE))
+
+ hicnb0 = hicn_get_buffer (b0);
+
+ // Get the strategy VFT
+ strategy = hicn_dpo_get_strategy_vft (hicnb0->vft_id);
+
+ // Check we have at least one next hop for the packet
+ ret = strategy->hicn_select_next_hop (
+ hicnb0->dpo_ctx_id, hicnb0->face_id, outfaces, &outfaces_len);
+
+ if (PREDICT_FALSE (ret != HICN_ERROR_NONE || outfaces_len == 0))
+ {
+ drop_packet (vm, bi0, &n_left_to_next, &next0, &to_next,
+ &next_index, node);
+ continue;
+ }
+
+ // Set next node
+ next0 = hicn_buffer_is_v6 (b0) ? HICN_STRATEGY_NEXT_INTEREST_FACE6 :
+ HICN_STRATEGY_NEXT_INTEREST_FACE4;
+
+ if (PREDICT_TRUE (ret == HICN_ERROR_NONE))
{
- /*
- * No need to check if parsing was successful
- * here. Already checked in the interest_pcslookup
- * node
- */
- nameptr = (u8 *) (&name);
- hicn_new_interest (rt, b0, &next0, tnow, nameptr, namelen,
- outface, nh_idx,
- vnet_buffer (b0)->ip.adj_index[VLIB_TX],
- strategy, dpo_ctx->dpo_type, isv6, &stats);
+ // Clone interest if needed
+ if (outfaces_len > 1)
+ {
+ ret = vlib_buffer_clone (vm, bi0, clones, (u16) outfaces_len,
+ CLIB_CACHE_LINE_BYTES * 2);
+ ASSERT (ret == outfaces_len);
+ }
+ else
+ {
+ clones[0] = bi0;
+ }
+
+ // Send interest to next hops
+ for (u32 nh = 0; nh < outfaces_len; nh++)
+ {
+ vlib_buffer_t *local_b0 = vlib_get_buffer (vm, clones[nh]);
+
+ to_next[0] = clones[nh];
+ to_next += 1;
+ n_left_to_next -= 1;
+
+ vnet_buffer (local_b0)->ip.adj_index[VLIB_TX] = outfaces[nh];
+ stats.pkts_interest_count++;
+
+ // Maybe trace
+ if (PREDICT_FALSE (
+ (node->flags & VLIB_NODE_FLAG_TRACE) &&
+ (local_b0->flags & VLIB_BUFFER_IS_TRACED)))
+ {
+ hicn_strategy_trace_t *t =
+ vlib_add_trace (vm, node, local_b0, sizeof (*t));
+ t->pkt_type = HICN_PACKET_TYPE_INTEREST;
+ t->sw_if_index =
+ vnet_buffer (local_b0)->sw_if_index[VLIB_RX];
+ t->next_index = next0;
+ t->dpo_type = hicnb0->vft_id;
+ t->out_face = outfaces[nh];
+ }
+
+ /*
+ * Fix in case of a wrong speculation. Needed for
+ * cloning the data in the right frame
+ */
+ vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
+ to_next, n_left_to_next,
+ clones[nh], next0);
+ }
}
- /* Maybe trace */
- if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
- (b0->flags & VLIB_BUFFER_IS_TRACED)))
+ else
{
- hicn_strategy_trace_t *t =
- vlib_add_trace (vm, node, b0, sizeof (*t));
- t->pkt_type = HICN_PKT_TYPE_CONTENT;
- t->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
- t->next_index = next0;
- t->dpo_type = dpo_ctx->dpo_type;
+ drop_packet (vm, bi0, &n_left_from, &next0, &to_next,
+ &next_index, node);
}
- /*
- * Verify speculative enqueue, maybe switch current
- * next frame
- */
- /*
- * Fix in case of a wrong speculation. Needed for
- * cloning the data in the right frame
- */
- vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
- n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
diff --git a/hicn-plugin/src/test/CMakeLists.txt b/hicn-plugin/src/test/CMakeLists.txt
new file mode 100644
index 000000000..89ad24fbb
--- /dev/null
+++ b/hicn-plugin/src/test/CMakeLists.txt
@@ -0,0 +1,67 @@
+# Copyright (c) 2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+#############################################################
+# Dependencies
+#############################################################
+
+# We need a pure C test framework for the hicn-plugin.
+include (UnityTestFrameworkImport)
+find_package(Threads REQUIRED)
+
+##############################################################
+# Test sources
+##############################################################
+list(APPEND TESTS_SRC
+ main.c
+ vpp.c
+ test_pcs.c
+)
+
+
+##############################################################
+# Link libraries
+##############################################################
+set(TEST_LIBRARIES
+ ${VPP_LIBRARIES}
+ ${UNITY_LIBRARIES}
+ ${LIBHICN_SHARED}
+ ${HICNPLUGIN_SHARED}
+ Threads::Threads
+)
+
+set (
+ LINK_FLAGS
+ "-Wl,-unresolved-symbols=ignore-all"
+)
+
+
+##############################################################
+# Build single unit test executable and add it to test list
+##############################################################
+build_executable(hicnplugin_tests
+ NO_INSTALL
+ SOURCES ${TESTS_SRC}
+ LINK_LIBRARIES
+ ${TEST_LIBRARIES}
+ INCLUDE_DIRS
+ $<TARGET_PROPERTY:${HICNPLUGIN_SHARED},INCLUDE_DIRECTORIES>
+ ${UNITY_INCLUDE_DIRS}
+ DEPENDS unity ${HICNPLUGIN_SHARED}
+ COMPONENT ${HICN_PLUGIN}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+ LINK_FLAGS ${LINK_FLAGS}
+)
+
+unity_add_test_internal(hicnplugin_tests)
diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.h b/hicn-plugin/src/test/main.c
index 0f6c7f8b4..82caba18a 100644
--- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.h
+++ b/hicn-plugin/src/test/main.c
@@ -1,5 +1,6 @@
+
/*
- * Copyright (c) 2018 HUACHENTEL and/or its affiliates.
+ * Copyright (c) 20022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,11 +14,18 @@
* limitations under the License.
*/
-#ifndef __IETF_INTERFACE_H__
-#define __IETF_INTERFACE_H__
-
-int ietf_subscribe_events(sr_session_ctx_t *session,
- sr_subscription_ctx_t **subscription);
+#include <unity_fixture.h>
+#include "vpp.h"
+static void
+RunAllTests (void)
+{
+ RUN_TEST_GROUP (PCS);
+}
-#endif /* __IETF_INTERFACE_H__ */
+int
+main (int argc, const char *argv[])
+{
+ vpp_init ();
+ return UnityMain (argc, argv, RunAllTests);
+} \ No newline at end of file
diff --git a/hicn-plugin/src/test/test_pcs.c b/hicn-plugin/src/test/test_pcs.c
new file mode 100644
index 000000000..8e7416b8b
--- /dev/null
+++ b/hicn-plugin/src/test/test_pcs.c
@@ -0,0 +1,622 @@
+/*
+ * Copyright (c) 20022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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.
+ */
+
+#define HICN_PCS_TESTING
+#include "vpp.h"
+#include <pcs.h>
+
+#include <unity.h>
+#include <unity_fixture.h>
+
+/*
+ * Global PCS instance common to each test
+ */
+static hicn_pit_cs_t global_pcs;
+
+TEST_GROUP (PCS);
+
+/**
+ * Default PIT elements
+ */
+#define MAX_PIT_ELEMENTS 1000000
+
+/**
+ * Default CS elements
+ */
+#define MAX_CS_ELEMENTS (MAX_PIT_ELEMENTS / 10)
+
+TEST_SETUP (PCS)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+ hicn_pit_create (pcs, MAX_PIT_ELEMENTS, MAX_CS_ELEMENTS);
+}
+
+TEST_TEAR_DOWN (PCS)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+ hicn_pit_destroy (pcs);
+}
+
+TEST (PCS, Create)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ // Check counters
+ TEST_ASSERT_EQUAL (0, pcs->pcs_pit_count);
+ TEST_ASSERT_EQUAL (0, pcs->pcs_cs_count);
+ TEST_ASSERT_EQUAL (0, pcs->pcs_pcs_alloc);
+ TEST_ASSERT_EQUAL (0, pcs->pcs_pcs_dealloc);
+ TEST_ASSERT_EQUAL (MAX_PIT_ELEMENTS, pcs->max_pit_size);
+ TEST_ASSERT_EQUAL (MAX_CS_ELEMENTS, pcs->policy_state.max);
+
+ printf ("PIT entry size: %lu", sizeof (hicn_pcs_entry_t));
+}
+
+TEST (PCS, Destroy)
+{
+ // Global PCS instance
+}
+
+TEST (PCS, LookupEmpty)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ hicn_name_t name;
+ int ret = hicn_name_create ("b001::abcd", 0, &name);
+ TEST_ASSERT_EQUAL (0, ret);
+
+ hicn_pcs_entry_t *pcs_entry;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry);
+
+ TEST_ASSERT_EQUAL (HICN_ERROR_PCS_NOT_FOUND, ret);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry);
+}
+
+TEST (PCS, InsertPITEntryAndLookup)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ // Add entry to the PCS
+ int ret = 0;
+
+ // Allocate name
+ hicn_name_t name;
+ hicn_name_create ("b001::1234", 0, &name);
+
+ // Create PCS entry
+ hicn_pcs_entry_t *pcs_entry;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry);
+
+ // We will not find the entry
+ TEST_ASSERT_EQUAL (ret, HICN_ERROR_PCS_NOT_FOUND);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry);
+
+ // Get a new PIT entry from the pool
+ // TODO Check if the hicn_pcs_entry_pit_get is needed here
+ pcs_entry = hicn_pcs_entry_pit_get (pcs, 0, 0);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_alloc (pcs), 1);
+
+ // Insert PIT entry
+ ret = hicn_pcs_pit_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 0);
+
+ // Lookup PIT entry
+ hicn_pcs_entry_t *pcs_entry_ret = NULL;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_NOT_NULL (pcs_entry_ret);
+ TEST_ASSERT_EQUAL (pcs_entry, pcs_entry_ret);
+
+ // Release PIT entry
+ hicn_pcs_entry_remove_lock (pcs, pcs_entry);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_dealloc (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 0);
+
+ // Lookup PIT entry again, we should not find it
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_PCS_NOT_FOUND, ret);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry_ret);
+}
+
+TEST (PCS, InsertCSEntryAndLookup)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ // Add entry to the PCS
+ int ret = 0;
+
+ // Allocate name
+ hicn_name_t name;
+ hicn_name_create ("b008::5555", 0, &name);
+
+ // Create PCS entry
+ hicn_pcs_entry_t *pcs_entry;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry);
+
+ // We will not find the entry
+ TEST_ASSERT_EQUAL (ret, HICN_ERROR_PCS_NOT_FOUND);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry);
+
+ // Get a buffer
+ u32 buffer_index = 198274;
+
+ // Get a new entry from the pool
+ pcs_entry = hicn_pcs_entry_cs_get (pcs, 0, buffer_index);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (1, hicn_pcs_get_pcs_alloc (pcs));
+
+ // Insert CS entry
+ ret = hicn_pcs_cs_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 1);
+
+ // Lookup CS entry
+ hicn_pcs_entry_t *pcs_entry_ret = NULL;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_TRUE (pcs_entry_ret->flags & HICN_PCS_ENTRY_CS_FLAG);
+ TEST_ASSERT_NOT_NULL (pcs_entry_ret);
+ TEST_ASSERT_EQUAL (pcs_entry, pcs_entry_ret);
+
+ // Release CS entry
+ hicn_pcs_entry_remove_lock (pcs, pcs_entry);
+ TEST_ASSERT_EQUAL (1, hicn_pcs_get_pcs_dealloc (pcs));
+ TEST_ASSERT_EQUAL (0, hicn_pcs_get_pit_count (pcs));
+ TEST_ASSERT_EQUAL (0, hicn_pcs_get_cs_count (pcs));
+
+ // Lookup CS entry again, we should not find it
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_PCS_NOT_FOUND, ret);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry_ret);
+}
+
+TEST (PCS, PitToCS)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ // Add entry to the PCS
+ int ret = 0;
+
+ // Allocate name
+ hicn_name_t name;
+ hicn_name_create ("b001::1234", 0, &name);
+
+ // Create PCS entry
+ hicn_pcs_entry_t *pcs_entry;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry);
+
+ // We will not find the entry
+ TEST_ASSERT_EQUAL (ret, HICN_ERROR_PCS_NOT_FOUND);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry);
+
+ // Get a new entry from the pool
+ // TODO Check if the hicn_pcs_entry_pit_get is needed here
+ pcs_entry = hicn_pcs_entry_pit_get (pcs, 0, 0);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_alloc (pcs), 1);
+
+ // Insert PIT entry
+ ret = hicn_pcs_pit_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 0);
+
+ // Lookup PIT entry
+ hicn_pcs_entry_t *pcs_entry_ret = NULL;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_NOT_NULL (pcs_entry_ret);
+ TEST_ASSERT_EQUAL (pcs_entry, pcs_entry_ret);
+
+ // Found the PIT entry we inserted before.
+ // Double check is not a CS
+ TEST_ASSERT_FALSE (pcs_entry_ret->flags & HICN_PCS_ENTRY_CS_FLAG);
+
+ // Turn the PIT entry into a CS
+ hicn_pit_to_cs (pcs, pcs_entry, /* random buffer index */ 12345);
+
+ // Check counters
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 1);
+
+ // Make sure entry is now a CS
+ TEST_ASSERT_TRUE (pcs_entry_ret->flags & HICN_PCS_ENTRY_CS_FLAG);
+}
+
+TEST (PCS, CheckCSLruConsistency)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ // Add entry to the PCS
+ int ret = 0;
+
+ // Allocate name
+ hicn_name_t name;
+ hicn_name_create ("b001::1234", 0, &name);
+
+ // Create CS entry
+ hicn_pcs_entry_t *pcs_entry;
+ // Get a new entry from the pool
+ // TODO Check if the hicn_pcs_entry_pit_get is needed here
+ pcs_entry = hicn_pcs_entry_cs_get (pcs, 0, 0);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_alloc (pcs), 1);
+
+ // Insert CS entry
+ ret = hicn_pcs_cs_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+
+ // Get pcs_entry index
+ uint32_t pcs_entry_index = hicn_pcs_entry_get_index (pcs, pcs_entry);
+
+ // Check LRU
+ hicn_cs_policy_t *policy_state = hicn_pcs_get_policy_state (pcs);
+
+ // Make sure MAX corresponds to what we set
+ TEST_ASSERT_EQUAL (MAX_CS_ELEMENTS, hicn_cs_policy_get_max (policy_state));
+
+ TEST_ASSERT_EQUAL (pcs_entry_index, hicn_cs_policy_get_head (policy_state));
+ TEST_ASSERT_EQUAL (pcs_entry_index, hicn_cs_policy_get_tail (policy_state));
+ TEST_ASSERT_EQUAL (1, hicn_cs_policy_get_count (policy_state));
+
+ // Check pointers of the entry
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_next (pcs_entry));
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_prev (pcs_entry));
+
+ // Lookup the entry itself
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry);
+
+ // Check again the pointers of the entry
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_next (pcs_entry));
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_prev (pcs_entry));
+
+ // Remove CS entry
+ hicn_pcs_entry_remove_lock (pcs, pcs_entry);
+ TEST_ASSERT_EQUAL (1, hicn_pcs_get_pcs_dealloc (pcs));
+ TEST_ASSERT_EQUAL (0, hicn_pcs_get_pit_count (pcs));
+ TEST_ASSERT_EQUAL (0, hicn_pcs_get_cs_count (pcs));
+
+ // Check again LRU
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_cs_policy_get_head (policy_state));
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_cs_policy_get_tail (policy_state));
+ TEST_ASSERT_EQUAL (0, hicn_cs_policy_get_count (policy_state));
+
+ // Let's insert now 2 entries
+ hicn_pcs_entry_t *pcs_entry0;
+ hicn_pcs_entry_t *pcs_entry1;
+
+ pcs_entry0 = hicn_pcs_entry_cs_get (pcs, 0, 0);
+ TEST_ASSERT_NOT_NULL (pcs_entry0);
+ hicn_name_t name0;
+ hicn_name_create ("b001::abcd", 123, &name0);
+ u32 index0 = hicn_pcs_entry_get_index (pcs, pcs_entry0);
+
+ pcs_entry1 = hicn_pcs_entry_cs_get (pcs, 0, 0);
+ TEST_ASSERT_NOT_NULL (pcs_entry1);
+ hicn_name_t name1;
+ hicn_name_create ("b001::9999", 321, &name1);
+ u32 index1 = hicn_pcs_entry_get_index (pcs, pcs_entry1);
+
+ // Insert CS entry
+ ret = hicn_pcs_cs_insert (pcs, pcs_entry0, &name0);
+ ret = hicn_pcs_cs_insert (pcs, pcs_entry1, &name1);
+
+ // Check LRU. index1 was inserted last, so it should be at the head
+ TEST_ASSERT_EQUAL (index1, hicn_cs_policy_get_head (policy_state));
+ // index0 was inserted first, so it should be at the tail
+ TEST_ASSERT_EQUAL (index0, hicn_cs_policy_get_tail (policy_state));
+ // And count shoould be 2
+ TEST_ASSERT_EQUAL (2, hicn_cs_policy_get_count (policy_state));
+
+ // Check pointers of the entries
+
+ // pcs_entry0 should be at the tail
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_next (pcs_entry0));
+ TEST_ASSERT_EQUAL (index1, hicn_pcs_entry_cs_get_prev (pcs_entry0));
+
+ // pcs_entry1 should be at the head
+ TEST_ASSERT_EQUAL (index0, hicn_pcs_entry_cs_get_next (pcs_entry1));
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_prev (pcs_entry1));
+
+ // Let's lookup for entry 0 and check if the LRU is updated correctly
+ ret = hicn_pcs_lookup_one (pcs, &name0, &pcs_entry);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (index0, hicn_pcs_entry_get_index (pcs, pcs_entry));
+
+ // Check pointers of the entries
+
+ // pcs_entry1 should be at the tail
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_next (pcs_entry1));
+ TEST_ASSERT_EQUAL (index0, hicn_pcs_entry_cs_get_prev (pcs_entry1));
+
+ // pcs_entry0 should be at the head
+ TEST_ASSERT_EQUAL (index1, hicn_pcs_entry_cs_get_next (pcs_entry0));
+ TEST_ASSERT_EQUAL (HICN_CS_POLICY_END_OF_CHAIN,
+ hicn_pcs_entry_cs_get_prev (pcs_entry0));
+
+ // index0 should be now the head
+ TEST_ASSERT_EQUAL (index0, hicn_cs_policy_get_head (policy_state));
+ // index1 should be now the tail
+ TEST_ASSERT_EQUAL (index1, hicn_cs_policy_get_tail (policy_state));
+}
+
+TEST (PCS, CheckCSLruMax)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+ int i, ret = 0;
+ ;
+ u32 pcs_entry_index = 0;
+ u32 pcs_entry_index0 = 0;
+ u32 pcs_entry_index1 = 0;
+ hicn_pcs_entry_t *pcs_entry = NULL;
+ hicn_name_t name;
+
+ const hicn_cs_policy_t *policy_state = hicn_pcs_get_policy_state (pcs);
+
+ for (i = 0; i < MAX_CS_ELEMENTS; i++)
+ {
+ // Allocate name
+ ret = hicn_name_create ("b004::aaaa", i, &name);
+ TEST_ASSERT_EQUAL (0, ret);
+
+ // Create CS entry
+ // Get a new entry from the pool
+ // TODO Check if the hicn_pcs_entry_pit_get is needed here
+ pcs_entry = hicn_pcs_entry_cs_get (pcs, 0, i);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (i + 1, hicn_pcs_get_pcs_alloc (pcs));
+
+ pcs_entry_index = hicn_pcs_entry_get_index (pcs, pcs_entry);
+
+ if (i == 0)
+ {
+ pcs_entry_index0 = pcs_entry_index;
+ }
+
+ if (i == 1)
+ {
+ pcs_entry_index1 = pcs_entry_index;
+ }
+
+ // Insert CS entry
+ ret = hicn_pcs_cs_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), i + 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+
+ // Check LRU
+ TEST_ASSERT_EQUAL (pcs_entry_index,
+ hicn_cs_policy_get_head (policy_state));
+ TEST_ASSERT_EQUAL (pcs_entry_index0,
+ hicn_cs_policy_get_tail (policy_state));
+ TEST_ASSERT_EQUAL (i + 1, hicn_cs_policy_get_count (policy_state));
+ }
+
+ // In this moment the CS should be full
+ TEST_ASSERT_EQUAL (hicn_cs_policy_get_max (policy_state),
+ hicn_cs_policy_get_count (policy_state));
+
+ // Next insertion should:
+ // - evict the tail
+ // - update the head
+ // - make a coffee because I am tired
+ ret = hicn_name_create ("b004::aaaa", i, &name);
+ TEST_ASSERT_EQUAL (0, ret);
+
+ pcs_entry = hicn_pcs_entry_cs_get (pcs, 0, i);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (i + 1, hicn_pcs_get_pcs_alloc (pcs));
+
+ pcs_entry_index = hicn_pcs_entry_get_index (pcs, pcs_entry);
+
+ // Insert CS entry
+ ret = hicn_pcs_cs_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), i);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+
+ // Check LRU
+ TEST_ASSERT_EQUAL (pcs_entry_index, hicn_cs_policy_get_head (policy_state));
+ // pcs_entry_index1 should be have eveicted, and pcs_entry_index1 should be
+ // the tail
+ TEST_ASSERT_EQUAL (pcs_entry_index1, hicn_cs_policy_get_tail (policy_state));
+
+ // Make pcs_entry_index0 was freed.
+ TEST_ASSERT_TRUE (
+ pool_is_free_index (pcs->pcs_entries_pool, pcs_entry_index0));
+}
+
+TEST (PCS, AddIngressFacesToPITEntry)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ // Add entry to the PCS
+ int ret = 0;
+
+ // Allocate name
+ hicn_name_t name;
+ hicn_name_create ("b001::9876", 0, &name);
+
+ // Create PCS entry
+ hicn_pcs_entry_t *pcs_entry;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry);
+
+ // We will not find the entry
+ TEST_ASSERT_EQUAL (ret, HICN_ERROR_PCS_NOT_FOUND);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry);
+
+ // Get a new entry from the pool
+ // TODO Check if the hicn_pcs_entry_pit_get is needed here
+ f64 tnow = 10.0;
+ pcs_entry = hicn_pcs_entry_pit_get (pcs, tnow, 0);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_alloc (pcs), 1);
+
+ const u32 faceid = 20;
+
+ // The face should not be in the PIT entry
+ TEST_ASSERT_EQUAL (0, hicn_pcs_entry_pit_search (pcs_entry, faceid));
+
+ // Add ingress face to pit entry
+ hicn_pcs_entry_pit_add_face (pcs_entry, faceid);
+
+ // Insert PIT entry
+ ret = hicn_pcs_pit_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 0);
+
+ // Lookup PIT entry
+ hicn_pcs_entry_t *pcs_entry_ret = NULL;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_NOT_NULL (pcs_entry_ret);
+ TEST_ASSERT_EQUAL (pcs_entry, pcs_entry_ret);
+
+ // Check everything is fine
+ ret = hicn_pcs_entry_pit_search (pcs_entry_ret, faceid);
+ // Face 20 should be in the entry
+ TEST_ASSERT_EQUAL (ret, 1);
+
+ // Get faces and make sure
+ // - there is only one face
+ // - the face is 20
+ TEST_ASSERT_EQUAL (1, hicn_pcs_entry_pit_get_n_faces (pcs_entry_ret));
+ TEST_ASSERT_EQUAL (20, hicn_pcs_entry_pit_get_dpo_face (pcs_entry_ret, 0));
+
+ // Release PIT entry
+ hicn_pcs_entry_remove_lock (pcs, pcs_entry_ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_dealloc (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 0);
+
+ // Lookup PIT entry again, we should not find it
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_PCS_NOT_FOUND, ret);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry_ret);
+}
+
+TEST (PCS, AddIngressFacesToPitEntryCornerCases)
+{
+ hicn_pit_cs_t *pcs = &global_pcs;
+
+ // Add entry to the PCS
+ int ret = 0;
+
+ // Allocate name
+ hicn_name_t name;
+ hicn_name_create ("b001::9876", 0, &name);
+
+ // Create PCS entry
+ hicn_pcs_entry_t *pcs_entry;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry);
+
+ // We will not find the entry
+ TEST_ASSERT_EQUAL (ret, HICN_ERROR_PCS_NOT_FOUND);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry);
+
+ // Get a new entry from the pool
+ // TODO Check if the hicn_pcs_entry_pit_get is needed here
+ f64 tnow = 10.0;
+ pcs_entry = hicn_pcs_entry_pit_get (pcs, tnow, 0);
+ TEST_ASSERT_NOT_NULL (pcs_entry);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_alloc (pcs), 1);
+
+ // Let's initialize HICN_FACE_DB_INLINE_FACES + 1 face IDs
+ u32 faceids[HICN_FACE_DB_INLINE_FACES + 1];
+ for (u32 i = 0; i < HICN_FACE_DB_INLINE_FACES + 1; i++)
+ faceids[i] = rand () % HICN_PARAM_FACES_MAX;
+
+ // The faces should not be in the PIT entry
+ for (u32 i = 0; i < HICN_FACE_DB_INLINE_FACES + 1; i++)
+ TEST_ASSERT_EQUAL (0, hicn_pcs_entry_pit_search (pcs_entry, faceids[i]));
+
+ // Add ingress faces to pit entry
+ for (u32 i = 0; i < HICN_FACE_DB_INLINE_FACES + 1; i++)
+ hicn_pcs_entry_pit_add_face (pcs_entry, faceids[i]);
+
+ // Insert PIT entry
+ ret = hicn_pcs_pit_insert (pcs, pcs_entry, &name);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 0);
+
+ // Lookup PIT entry
+ hicn_pcs_entry_t *pcs_entry_ret = NULL;
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_NONE, ret);
+ TEST_ASSERT_NOT_NULL (pcs_entry_ret);
+ TEST_ASSERT_EQUAL (pcs_entry, pcs_entry_ret);
+
+ // Check everything is fine
+ for (u32 i = 0; i < HICN_FACE_DB_INLINE_FACES + 1; i++)
+ {
+ ret = hicn_pcs_entry_pit_search (pcs_entry_ret, faceids[i]);
+ // Face 20 should be in the entry
+ TEST_ASSERT_EQUAL (1, ret);
+ }
+
+ // Get faces and make sure
+ // - there are HICN_FACE_DB_INLINE_FACES + 1 faces
+ // - the first HICN_FACE_DB_INLINE_FACES are stored in the PIT entry
+ // - the face HICN_FACE_DB_INLINE_FACES + 1 is stored in the array of
+ // additional faces, so outside PIT entry
+ TEST_ASSERT_EQUAL (HICN_FACE_DB_INLINE_FACES + 1,
+ hicn_pcs_entry_pit_get_n_faces (pcs_entry_ret));
+ for (u32 i = 0; i < HICN_FACE_DB_INLINE_FACES + 1; i++)
+ TEST_ASSERT_EQUAL (faceids[i],
+ hicn_pcs_entry_pit_get_dpo_face (pcs_entry_ret, i));
+
+ // Release PIT entry
+ hicn_pcs_entry_remove_lock (pcs, pcs_entry_ret);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pcs_dealloc (pcs), 1);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_pit_count (pcs), 0);
+ TEST_ASSERT_EQUAL (hicn_pcs_get_cs_count (pcs), 0);
+
+ // Lookup PIT entry again, we should not find it
+ ret = hicn_pcs_lookup_one (pcs, &name, &pcs_entry_ret);
+ TEST_ASSERT_EQUAL (HICN_ERROR_PCS_NOT_FOUND, ret);
+ TEST_ASSERT_EQUAL (NULL, pcs_entry_ret);
+}
+
+TEST_GROUP_RUNNER (PCS)
+{
+ RUN_TEST_CASE (PCS, Create)
+ RUN_TEST_CASE (PCS, Destroy)
+ RUN_TEST_CASE (PCS, LookupEmpty)
+ RUN_TEST_CASE (PCS, InsertPITEntryAndLookup)
+ RUN_TEST_CASE (PCS, InsertCSEntryAndLookup)
+ RUN_TEST_CASE (PCS, PitToCS)
+ RUN_TEST_CASE (PCS, CheckCSLruConsistency)
+ RUN_TEST_CASE (PCS, CheckCSLruMax)
+ RUN_TEST_CASE (PCS, AddIngressFacesToPITEntry)
+ RUN_TEST_CASE (PCS, AddIngressFacesToPitEntryCornerCases)
+}
diff --git a/hicn-plugin/src/test/vpp.c b/hicn-plugin/src/test/vpp.c
new file mode 100644
index 000000000..e1f38e23d
--- /dev/null
+++ b/hicn-plugin/src/test/vpp.c
@@ -0,0 +1,570 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <pthread.h>
+#include <sched.h>
+
+#include <vppinfra/cpu.h>
+#include <vlib/vlib.h>
+#include <vlib/unix/unix.h>
+#include <vlib/threads.h>
+#include <vnet/plugin/plugin.h>
+#include <vnet/ethernet/ethernet.h>
+#include <vpp/vnet/config.h>
+#include <vlibmemory/memclnt.api_enum.h> /* To get the last static message id */
+#include <limits.h>
+
+/*
+ * Load plugins from /usr/lib/vpp_plugins by default
+ */
+char *vlib_plugin_path = NULL;
+char *vat_plugin_path = NULL;
+
+static void
+vpp_find_plugin_path ()
+{
+ extern char *vat_plugin_path;
+ char *p, path[PATH_MAX];
+ int rv;
+ u8 *s;
+
+ /* find executable path */
+ if ((rv = readlink ("/proc/self/exe", path, PATH_MAX - 1)) == -1)
+ return;
+
+ /* readlink doesn't provide null termination */
+ path[rv] = 0;
+
+ /* strip filename */
+ if ((p = strrchr (path, '/')) == 0)
+ return;
+ *p = 0;
+
+ /* strip bin/ */
+ if ((p = strrchr (path, '/')) == 0)
+ return;
+ *p = 0;
+
+ s = format (0, "%s/" CLIB_LIB_DIR "/vpp_plugins", path, path);
+ vec_add1 (s, 0);
+ vlib_plugin_path = (char *) s;
+
+ s = format (0, "%s/" CLIB_LIB_DIR "/vpp_api_test_plugins", path, path);
+ vec_add1 (s, 0);
+ vat_plugin_path = (char *) s;
+}
+
+static void
+vpe_main_init (vlib_main_t *vm)
+{
+#if VPP_API_TEST_BUILTIN > 0
+ void vat_plugin_hash_create (void);
+#endif
+
+ if (CLIB_DEBUG > 0)
+ vlib_unix_cli_set_prompt ("DBGvpp# ");
+ else
+ vlib_unix_cli_set_prompt ("vpp# ");
+
+ /* Turn off network stack components which we don't want */
+ vlib_mark_init_function_complete (vm, srp_init);
+
+ /*
+ * Create the binary api plugin hashes before loading plugins
+ */
+#if VPP_API_TEST_BUILTIN > 0
+ vat_plugin_hash_create ();
+#endif
+
+ if (!vlib_plugin_path)
+ vpp_find_plugin_path ();
+}
+
+/*
+ * Default path for runtime data
+ */
+char *vlib_default_runtime_dir = "vpp";
+
+int
+vpp_init_internal (int argc, char *argv[])
+{
+ int i;
+ void vl_msg_api_set_first_available_msg_id (u16);
+ uword main_heap_size = (1ULL << 30);
+ u8 *sizep;
+ u32 size;
+ clib_mem_page_sz_t main_heap_log2_page_sz = CLIB_MEM_PAGE_SZ_DEFAULT;
+ clib_mem_page_sz_t default_log2_hugepage_sz = CLIB_MEM_PAGE_SZ_UNKNOWN;
+ unformat_input_t input, sub_input;
+ u8 *s = 0, *v = 0;
+ int main_core = 1;
+ cpu_set_t cpuset;
+ void *main_heap;
+
+#if __x86_64__
+ CLIB_UNUSED (const char *msg) =
+ "ERROR: This binary requires CPU with %s extensions.\n";
+#define _(a, b) \
+ if (!clib_cpu_supports_##a ()) \
+ { \
+ fprintf (stderr, msg, b); \
+ exit (1); \
+ }
+
+#if __AVX2__
+ _ (avx2, "AVX2")
+#endif
+#if __AVX__
+ _ (avx, "AVX")
+#endif
+#if __SSE4_2__
+ _ (sse42, "SSE4.2")
+#endif
+#if __SSE4_1__
+ _ (sse41, "SSE4.1")
+#endif
+#if __SSSE3__
+ _ (ssse3, "SSSE3")
+#endif
+#if __SSE3__
+ _ (sse3, "SSE3")
+#endif
+#undef _
+#endif
+ /*
+ * Load startup config from file.
+ * usage: vpp -c /etc/vpp/startup.conf
+ */
+ if ((argc == 3) && !strncmp (argv[1], "-c", 2))
+ {
+ FILE *fp;
+ char inbuf[4096];
+ int argc_ = 1;
+ char **argv_ = NULL;
+ char *arg = NULL;
+ char *p;
+
+ fp = fopen (argv[2], "r");
+ if (fp == NULL)
+ {
+ fprintf (stderr, "open configuration file '%s' failed\n", argv[2]);
+ return 1;
+ }
+ argv_ = calloc (1, sizeof (char *));
+ if (argv_ == NULL)
+ {
+ fclose (fp);
+ return 1;
+ }
+ arg = strndup (argv[0], 1024);
+ if (arg == NULL)
+ {
+ fclose (fp);
+ free (argv_);
+ return 1;
+ }
+ argv_[0] = arg;
+
+ while (1)
+ {
+ if (fgets (inbuf, 4096, fp) == 0)
+ break;
+ p = strtok (inbuf, " \t\n");
+ while (p != NULL)
+ {
+ if (*p == '#')
+ break;
+ argc_++;
+ char **tmp = realloc (argv_, argc_ * sizeof (char *));
+ if (tmp == NULL)
+ {
+ fclose (fp);
+ return 1;
+ }
+ argv_ = tmp;
+ arg = strndup (p, 1024);
+ if (arg == NULL)
+ {
+ free (argv_);
+ fclose (fp);
+ return 1;
+ }
+ argv_[argc_ - 1] = arg;
+ p = strtok (NULL, " \t\n");
+ }
+ }
+
+ fclose (fp);
+
+ char **tmp = realloc (argv_, (argc_ + 1) * sizeof (char *));
+ if (tmp == NULL)
+ {
+ free (argv_);
+ return 1;
+ }
+ argv_ = tmp;
+ argv_[argc_] = NULL;
+
+ argc = argc_;
+ argv = argv_;
+ }
+
+ /*
+ * Look for and parse the "heapsize" config parameter.
+ * Manual since none of the clib infra has been bootstrapped yet.
+ *
+ * Format: heapsize <nn>[mM][gG]
+ */
+
+ for (i = 1; i < (argc - 1); i++)
+ {
+ if (!strncmp (argv[i], "plugin_path", 11))
+ {
+ if (i < (argc - 1))
+ vlib_plugin_path = argv[++i];
+ }
+ if (!strncmp (argv[i], "test_plugin_path", 16))
+ {
+ if (i < (argc - 1))
+ vat_plugin_path = argv[++i];
+ }
+ else if (!strncmp (argv[i], "heapsize", 8))
+ {
+ sizep = (u8 *) argv[i + 1];
+ size = 0;
+ while (sizep && *sizep >= '0' && *sizep <= '9')
+ {
+ size *= 10;
+ size += *sizep++ - '0';
+ }
+ if (size == 0)
+ {
+ fprintf (
+ stderr,
+ "warning: heapsize parse error '%s', use default %lld\n",
+ argv[i], (long long int) main_heap_size);
+ goto defaulted;
+ }
+
+ main_heap_size = size;
+
+ if (*sizep == 'g' || *sizep == 'G')
+ main_heap_size <<= 30;
+ else if (*sizep == 'm' || *sizep == 'M')
+ main_heap_size <<= 20;
+ }
+ else if (!strncmp (argv[i], "main-core", 9))
+ {
+ if (i < (argc - 1))
+ {
+ errno = 0;
+ unsigned long x = strtol (argv[++i], 0, 0);
+ if (errno == 0)
+ main_core = x;
+ }
+ }
+ }
+defaulted:
+
+ /* temporary heap */
+ clib_mem_init (0, 1 << 20);
+ unformat_init_command_line (&input, (char **) argv);
+
+ while (unformat_check_input (&input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (&input, "memory %v", &v))
+ {
+ unformat_init_vector (&sub_input, v);
+ v = 0;
+ while (unformat_check_input (&sub_input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (&sub_input, "main-heap-size %U",
+ unformat_memory_size, &main_heap_size))
+ ;
+ else if (unformat (&sub_input, "main-heap-page-size %U",
+ unformat_log2_page_size,
+ &main_heap_log2_page_sz))
+ ;
+ else if (unformat (&sub_input, "default-hugepage-size %U",
+ unformat_log2_page_size,
+ &default_log2_hugepage_sz))
+ ;
+ else
+ {
+ fformat (stderr, "unknown 'memory' config input '%U'\n",
+ format_unformat_error, &sub_input);
+ exit (1);
+ }
+ }
+ unformat_free (&sub_input);
+ }
+ else if (!unformat (&input, "%s %v", &s, &v))
+ break;
+
+ vec_reset_length (s);
+ vec_reset_length (v);
+ }
+ vec_free (s);
+ vec_free (v);
+
+ unformat_free (&input);
+
+ /* set process affinity for main thread */
+ CPU_ZERO (&cpuset);
+ CPU_SET (main_core, &cpuset);
+ pthread_setaffinity_np (pthread_self (), sizeof (cpu_set_t), &cpuset);
+
+ /* Set up the plugin message ID allocator right now... */
+ vl_msg_api_set_first_available_msg_id (VL_MSG_MEMCLNT_LAST + 1);
+
+ /* destroy temporary heap and create main one */
+ clib_mem_destroy ();
+
+ if ((main_heap = clib_mem_init_with_page_size (main_heap_size,
+ main_heap_log2_page_sz)))
+ {
+ /* Figure out which numa runs the main thread */
+ __os_numa_index = clib_get_current_numa_node ();
+
+ if (default_log2_hugepage_sz != CLIB_MEM_PAGE_SZ_UNKNOWN)
+ clib_mem_set_log2_default_hugepage_size (default_log2_hugepage_sz);
+
+ /* and use the main heap as that numa's numa heap */
+ clib_mem_set_per_numa_heap (main_heap);
+ vlib_main_init ();
+ vpe_main_init (vlib_get_first_main ());
+ return 0;
+ }
+ else
+ {
+ {
+ int rv __attribute__ ((unused)) =
+ write (2, "Main heap allocation failure!\r\n", 31);
+ }
+ return 1;
+ }
+}
+
+static clib_error_t *
+memory_config (vlib_main_t *vm, unformat_input_t *input)
+{
+ return 0;
+}
+
+VLIB_CONFIG_FUNCTION (memory_config, "memory");
+
+static clib_error_t *
+heapsize_config (vlib_main_t *vm, unformat_input_t *input)
+{
+ return 0;
+}
+
+VLIB_CONFIG_FUNCTION (heapsize_config, "heapsize");
+
+static clib_error_t *
+placeholder_path_config (vlib_main_t *vm, unformat_input_t *input)
+{
+ u8 *junk;
+
+ while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+ {
+ if (unformat (input, "%s", &junk))
+ {
+ vec_free (junk);
+ return 0;
+ }
+ else
+ return clib_error_return (0, "unknown input '%U'",
+ format_unformat_error, input);
+ }
+ return 0;
+}
+
+static clib_error_t *
+plugin_path_config (vlib_main_t *vm, unformat_input_t *input)
+{
+ return placeholder_path_config (vm, input);
+}
+
+VLIB_CONFIG_FUNCTION (plugin_path_config, "plugin_path");
+
+static clib_error_t *
+test_plugin_path_config (vlib_main_t *vm, unformat_input_t *input)
+{
+ return placeholder_path_config (vm, input);
+}
+
+VLIB_CONFIG_FUNCTION (test_plugin_path_config, "test_plugin_path");
+
+void vl_msg_api_post_mortem_dump (void);
+void vlib_post_mortem_dump (void);
+
+void
+os_panic (void)
+{
+ vl_msg_api_post_mortem_dump ();
+ vlib_post_mortem_dump ();
+ abort ();
+}
+
+void vhost_user_unmap_all (void) __attribute__ ((weak));
+void
+vhost_user_unmap_all (void)
+{
+}
+
+void
+os_exit (int code)
+{
+ static int recursion_block;
+
+ if (code)
+ {
+ if (recursion_block)
+ abort ();
+
+ recursion_block = 1;
+
+ vl_msg_api_post_mortem_dump ();
+ vlib_post_mortem_dump ();
+ vhost_user_unmap_all ();
+ abort ();
+ }
+ exit (code);
+}
+
+#ifdef BARRIER_TRACING
+void
+vl_msg_api_barrier_trace_context (const char *context)
+{
+ vlib_worker_threads[0].barrier_context = context;
+}
+#endif
+
+void
+vl_msg_api_barrier_sync (void)
+{
+ vlib_worker_thread_barrier_sync (vlib_get_main ());
+}
+
+void
+vl_msg_api_barrier_release (void)
+{
+ vlib_worker_thread_barrier_release (vlib_get_main ());
+}
+
+/* This application needs 1 thread stack for the stats pthread */
+u32
+vlib_app_num_thread_stacks_needed (void)
+{
+ return 1;
+}
+
+/*
+ * Depending on the configuration selected above,
+ * it may be necessary to generate stub graph nodes.
+ * It is never OK to ignore "node 'x' refers to unknown node 'y'
+ * messages!
+ */
+
+#include <vppinfra/bihash_8_8.h>
+
+static clib_error_t *
+show_bihash_command_fn (vlib_main_t *vm, unformat_input_t *input,
+ vlib_cli_command_t *cmd)
+{
+ int i;
+ clib_bihash_8_8_t *h;
+ int verbose = 0;
+
+ if (unformat (input, "verbose"))
+ verbose = 1;
+
+ for (i = 0; i < vec_len (clib_all_bihashes); i++)
+ {
+ h = (clib_bihash_8_8_t *) clib_all_bihashes[i];
+ vlib_cli_output (vm, "\n%U", h->fmt_fn, h, verbose);
+ }
+
+ return 0;
+}
+
+/* *INDENT-OFF* */
+VLIB_CLI_COMMAND (show_bihash_command, static) = {
+ .path = "show bihash",
+ .short_help = "show bihash",
+ .function = show_bihash_command_fn,
+};
+/* *INDENT-ON* */
+
+#ifdef CLIB_SANITIZE_ADDR
+/* default options for Address Sanitizer */
+const char *
+__asan_default_options (void)
+{
+ return VPP_SANITIZE_ADDR_OPTIONS;
+}
+#endif /* CLIB_SANITIZE_ADDR */
+
+/***********************************
+ * Missing Symbol in vpp libraries
+ ***********************************/
+
+typedef struct stat_segment_directory_entry_s stat_segment_directory_entry_t;
+typedef void (*stat_segment_update_fn) (stat_segment_directory_entry_t *e,
+ u32 i);
+clib_error_t *
+stat_segment_register_gauge (u8 *name, stat_segment_update_fn update_fn,
+ u32 caller_index)
+{
+ return NULL;
+}
+
+u8 *
+format_vl_api_address_union (u8 *s, va_list *args)
+{
+ return NULL;
+}
+
+int
+vpp_init ()
+{
+#define N_ARGS 3
+#define BUFFER_LEN 1024
+ // Get executable path
+ char buffer[BUFFER_LEN];
+ int ret = readlink ("/proc/self/exe", buffer, BUFFER_LEN);
+
+ ASSERT (ret < BUFFER_LEN);
+
+ if (ret >= BUFFER_LEN)
+ {
+ return -1;
+ }
+
+ buffer[ret] = '\0';
+
+ char *argv[N_ARGS] = { buffer, "unix { nodaemon }", NULL };
+ return vpp_init_internal (N_ARGS - 1, argv);
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/hicn-plugin/src/test/vpp.h b/hicn-plugin/src/test/vpp.h
new file mode 100644
index 000000000..fe680f6b6
--- /dev/null
+++ b/hicn-plugin/src/test/vpp.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __VPP__
+#define __VPP__
+
+int vpp_init ();
+
+#endif \ No newline at end of file
diff --git a/hicn-plugin/src/udp_tunnels/udp_decap.h b/hicn-plugin/src/udp_tunnels/udp_decap.h
index 9ddb8a73b..7dc13f272 100644
--- a/hicn-plugin/src/udp_tunnels/udp_decap.h
+++ b/hicn-plugin/src/udp_tunnels/udp_decap.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/src/udp_tunnels/udp_decap_node.c b/hicn-plugin/src/udp_tunnels/udp_decap_node.c
index 06eb8da71..2ac1b1ecb 100644
--- a/hicn-plugin/src/udp_tunnels/udp_decap_node.c
+++ b/hicn-plugin/src/udp_tunnels/udp_decap_node.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -223,7 +223,7 @@ udp4_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip4_header_t *) outer_ptr0)->dst_address);
udp0 = (udp_header_t *) (outer_ptr0 + sizeof (ip4_header_t));
next0 = v0 == 0x40 ? UDP4_DECAP_NEXT_LOOKUP_IP4 :
- UDP4_DECAP_NEXT_LOOKUP_IP6;
+ UDP4_DECAP_NEXT_LOOKUP_IP6;
ip46_address_set_ip4 (&src1,
&((ip4_header_t *) outer_ptr1)->src_address);
@@ -231,7 +231,7 @@ udp4_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip4_header_t *) outer_ptr1)->dst_address);
udp1 = (udp_header_t *) (outer_ptr1 + sizeof (ip4_header_t));
next1 = v1 == 0x40 ? UDP4_DECAP_NEXT_LOOKUP_IP4 :
- UDP4_DECAP_NEXT_LOOKUP_IP6;
+ UDP4_DECAP_NEXT_LOOKUP_IP6;
ip46_address_set_ip4 (&src2,
&((ip4_header_t *) outer_ptr2)->src_address);
@@ -239,7 +239,7 @@ udp4_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip4_header_t *) outer_ptr2)->dst_address);
udp2 = (udp_header_t *) (outer_ptr2 + sizeof (ip4_header_t));
next2 = v2 == 0x40 ? UDP4_DECAP_NEXT_LOOKUP_IP4 :
- UDP4_DECAP_NEXT_LOOKUP_IP6;
+ UDP4_DECAP_NEXT_LOOKUP_IP6;
ip46_address_set_ip4 (&src3,
&((ip4_header_t *) outer_ptr3)->src_address);
@@ -247,7 +247,7 @@ udp4_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip4_header_t *) outer_ptr3)->dst_address);
udp3 = (udp_header_t *) (outer_ptr3 + sizeof (ip4_header_t));
next3 = v3 == 0x40 ? UDP4_DECAP_NEXT_LOOKUP_IP4 :
- UDP4_DECAP_NEXT_LOOKUP_IP6;
+ UDP4_DECAP_NEXT_LOOKUP_IP6;
hicn_buffer_t *hicnb0, *hicnb1, *hicnb2, *hicnb3;
hicnb0 = hicn_get_buffer (b0);
@@ -257,34 +257,39 @@ udp4_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
/* Udp encap-decap tunnels have dst and src addresses and port
* swapped */
- vnet_buffer (b0)->ip.adj_index[VLIB_RX] =
- udp_tunnel_get (&dst0, &src0, udp0->dst_port, udp0->src_port);
- vnet_buffer (b1)->ip.adj_index[VLIB_RX] =
- udp_tunnel_get (&dst1, &src1, udp1->dst_port, udp1->src_port);
- vnet_buffer (b2)->ip.adj_index[VLIB_RX] =
- udp_tunnel_get (&dst2, &src2, udp2->dst_port, udp2->src_port);
- vnet_buffer (b3)->ip.adj_index[VLIB_RX] =
- udp_tunnel_get (&dst3, &src3, udp3->dst_port, udp3->src_port);
-
- if (vnet_buffer (b0)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
- hicnb0->flags |=
- (outer_v0 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
-
- if (vnet_buffer (b1)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
- hicnb1->flags |=
- (outer_v1 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
-
- if (vnet_buffer (b2)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
- hicnb2->flags |=
- (outer_v2 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
-
- if (vnet_buffer (b3)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
- hicnb3->flags |=
- (outer_v3 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] = udp_tunnel_get_create (
+ &dst0, &src0, udp0->dst_port, udp0->src_port);
+ vnet_buffer (b1)->ip.adj_index[VLIB_RX] = udp_tunnel_get_create (
+ &dst1, &src1, udp1->dst_port, udp1->src_port);
+ vnet_buffer (b2)->ip.adj_index[VLIB_RX] = udp_tunnel_get_create (
+ &dst2, &src2, udp2->dst_port, udp2->src_port);
+ vnet_buffer (b3)->ip.adj_index[VLIB_RX] = udp_tunnel_get_create (
+ &dst3, &src3, udp3->dst_port, udp3->src_port);
+
+ ASSERT (vnet_buffer (b0)->ip.adj_index[VLIB_RX] !=
+ UDP_TUNNEL_INVALID);
+ ASSERT (vnet_buffer (b1)->ip.adj_index[VLIB_RX] !=
+ UDP_TUNNEL_INVALID);
+ ASSERT (vnet_buffer (b2)->ip.adj_index[VLIB_RX] !=
+ UDP_TUNNEL_INVALID);
+ ASSERT (vnet_buffer (b3)->ip.adj_index[VLIB_RX] !=
+ UDP_TUNNEL_INVALID);
+
+ hicnb0->flags =
+ (outer_v0 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+
+ hicnb1->flags =
+ (outer_v1 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+
+ hicnb2->flags =
+ (outer_v2 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+
+ hicnb3->flags =
+ (outer_v3 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
udp_decap_trace_buffer (vm, node, 1, b0);
udp_decap_trace_buffer (vm, node, 1, b1);
@@ -346,17 +351,19 @@ udp4_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip4_header_t *) outer_ptr0)->dst_address);
udp0 = (udp_header_t *) (outer_ptr0 + sizeof (ip4_header_t));
next0 = v0 == 0x40 ? UDP4_DECAP_NEXT_LOOKUP_IP4 :
- UDP4_DECAP_NEXT_LOOKUP_IP6;
+ UDP4_DECAP_NEXT_LOOKUP_IP6;
hicn_buffer_t *hicnb0 = hicn_get_buffer (b0);
- vnet_buffer (b0)->ip.adj_index[VLIB_RX] =
- udp_tunnel_get (&dst0, &src0, udp0->dst_port, udp0->src_port);
+ vnet_buffer (b0)->ip.adj_index[VLIB_RX] = udp_tunnel_get_create (
+ &dst0, &src0, udp0->dst_port, udp0->src_port);
- if (vnet_buffer (b0)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
- hicnb0->flags |=
- (outer_v0 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+ ASSERT (vnet_buffer (b0)->ip.adj_index[VLIB_RX] !=
+ UDP_TUNNEL_INVALID);
+
+ hicnb0->flags |=
+ (outer_v0 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
udp_decap_trace_buffer (vm, node, 1, b0);
@@ -488,7 +495,7 @@ udp6_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip6_header_t *) outer_ptr0)->dst_address);
udp0 = (udp_header_t *) (outer_ptr0 + sizeof (ip6_header_t));
next0 = v0 == 0x40 ? UDP6_DECAP_NEXT_LOOKUP_IP4 :
- UDP6_DECAP_NEXT_LOOKUP_IP6;
+ UDP6_DECAP_NEXT_LOOKUP_IP6;
ip46_address_set_ip6 (&src1,
&((ip6_header_t *) outer_ptr1)->src_address);
@@ -496,7 +503,7 @@ udp6_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip6_header_t *) outer_ptr1)->dst_address);
udp1 = (udp_header_t *) (outer_ptr1 + sizeof (ip6_header_t));
next1 = v1 == 0x40 ? UDP6_DECAP_NEXT_LOOKUP_IP4 :
- UDP6_DECAP_NEXT_LOOKUP_IP6;
+ UDP6_DECAP_NEXT_LOOKUP_IP6;
ip46_address_set_ip6 (&src2,
&((ip6_header_t *) outer_ptr2)->src_address);
@@ -504,7 +511,7 @@ udp6_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip6_header_t *) outer_ptr2)->dst_address);
udp2 = (udp_header_t *) (outer_ptr2 + sizeof (ip6_header_t));
next2 = v2 == 0x40 ? UDP6_DECAP_NEXT_LOOKUP_IP4 :
- UDP6_DECAP_NEXT_LOOKUP_IP6;
+ UDP6_DECAP_NEXT_LOOKUP_IP6;
ip46_address_set_ip6 (&src3,
&((ip6_header_t *) outer_ptr3)->src_address);
@@ -512,7 +519,7 @@ udp6_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip6_header_t *) outer_ptr3)->dst_address);
udp3 = (udp_header_t *) (outer_ptr3 + sizeof (ip6_header_t));
next3 = v3 == 0x40 ? UDP6_DECAP_NEXT_LOOKUP_IP4 :
- UDP6_DECAP_NEXT_LOOKUP_IP6;
+ UDP6_DECAP_NEXT_LOOKUP_IP6;
hicn_buffer_t *hicnb0, *hicnb1, *hicnb2, *hicnb3;
hicnb0 = hicn_get_buffer (b0);
@@ -534,22 +541,22 @@ udp6_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
if (vnet_buffer (b0)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
hicnb0->flags |=
(outer_v0 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
if (vnet_buffer (b1)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
hicnb1->flags |=
(outer_v1 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
if (vnet_buffer (b2)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
hicnb2->flags |=
(outer_v2 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
if (vnet_buffer (b3)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
hicnb3->flags |=
(outer_v3 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
udp_decap_trace_buffer (vm, node, 0, b0);
udp_decap_trace_buffer (vm, node, 0, b1);
@@ -610,7 +617,7 @@ udp6_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
&((ip6_header_t *) outer_ptr0)->dst_address);
udp0 = (udp_header_t *) (outer_ptr0 + sizeof (ip6_header_t));
next0 = v0 == 0x40 ? UDP6_DECAP_NEXT_LOOKUP_IP4 :
- UDP6_DECAP_NEXT_LOOKUP_IP6;
+ UDP6_DECAP_NEXT_LOOKUP_IP6;
hicn_buffer_t *hicnb0 = hicn_get_buffer (b0);
@@ -620,7 +627,7 @@ udp6_decap_node_fn (vlib_main_t *vm, vlib_node_runtime_t *node,
if (vnet_buffer (b0)->ip.adj_index[VLIB_RX] != UDP_TUNNEL_INVALID)
hicnb0->flags |=
(outer_v0 == 0x40 ? HICN_BUFFER_FLAGS_FROM_UDP4_TUNNEL :
- HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
+ HICN_BUFFER_FLAGS_FROM_UDP6_TUNNEL);
udp_decap_trace_buffer (vm, node, 0, b0);
diff --git a/hicn-plugin/src/udp_tunnels/udp_tunnel.c b/hicn-plugin/src/udp_tunnels/udp_tunnel.c
index 8ea2cb503..5b0c0a9ef 100644
--- a/hicn-plugin/src/udp_tunnels/udp_tunnel.c
+++ b/hicn-plugin/src/udp_tunnels/udp_tunnel.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,6 +17,7 @@
#include <vppinfra/bihash_40_8.h>
#include <vnet/fib/fib_table.h>
#include <vnet/udp/udp_local.h>
+#include "../faces/iface_node.h"
#include "../error.h"
#include "../strategy_dpo_ctx.h"
@@ -156,6 +157,39 @@ udp_tunnel_get (const ip46_address_t *src_ip, const ip46_address_t *dst_ip,
return ret == 0 ? (u32) value.value : UDP_TUNNEL_INVALID;
}
+u32
+udp_tunnel_get_create (const ip46_address_t *src_ip,
+ const ip46_address_t *dst_ip, u16 src_port,
+ u16 dst_port)
+{
+ u32 ret = udp_tunnel_get (src_ip, dst_ip, src_port, dst_port);
+ if (ret == UDP_TUNNEL_INVALID)
+ {
+ fib_protocol_t proto =
+ ip46_address_is_ip4 (src_ip) ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
+
+ index_t fib_index = fib_table_find (proto, HICN_FIB_TABLE);
+
+ ret = udp_tunnel_add (
+ proto, fib_index, src_ip, dst_ip, clib_net_to_host_u16 (src_port),
+ clib_net_to_host_u16 (dst_port), UDP_ENCAP_FIXUP_NONE);
+ }
+
+ return ret;
+}
+
+void
+udp_tunnel_set_face (hicn_face_id_t face_id, int isv4)
+{
+ hicn_face_t *face = NULL;
+ face = hicn_dpoi_get_from_idx (face_id);
+ ASSERT (face);
+ ASSERT (dpo_is_udp_encap (&face->dpo));
+
+ face->iface_next = isv4 ? HICN4_IFACE_OUTPUT_NEXT_UDP4_ENCAP :
+ HICN4_IFACE_OUTPUT_NEXT_UDP6_ENCAP;
+}
+
void
udp_tunnel_init ()
{
@@ -255,8 +289,8 @@ udp_tunnel_command_fn (vlib_main_t *vm, unformat_input_t *main_input,
int ret = udp_tunnel_del (fproto, fib_index, &src_ip, &dst_ip, src_port,
dst_port, UDP_ENCAP_FIXUP_NONE);
error = (ret == HICN_ERROR_NONE) ?
- 0 :
- clib_error_return (0, "%s\n", get_error_string (ret));
+ 0 :
+ clib_error_return (0, "%s\n", get_error_string (ret));
}
else
{
diff --git a/hicn-plugin/src/udp_tunnels/udp_tunnel.h b/hicn-plugin/src/udp_tunnels/udp_tunnel.h
index 2e57b7857..f7865f58a 100644
--- a/hicn-plugin/src/udp_tunnels/udp_tunnel.h
+++ b/hicn-plugin/src/udp_tunnels/udp_tunnel.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,6 +20,8 @@
#include <vppinfra/error.h>
#include <vnet/udp/udp_encap.h>
+#include "../faces/face.h"
+
/**
* @file udp_tunnel.h
*
@@ -70,6 +72,19 @@ u32 udp_tunnel_get (const ip46_address_t *src_ip, const ip46_address_t *dst_ip,
u16 src_port, u16 dst_port);
/**
+ * @brief Get udp tunnel UEI. Creates the tunnel if does not exist already.
+ *
+ * @param src_ip source address of the tunnel
+ * @param dst_ip destination address of the tunnel
+ * @param src_port source port
+ * @param src_port destination port
+ * @return id of the udp tunnel/encap
+ */
+u32 udp_tunnel_get_create (const ip46_address_t *src_ip,
+ const ip46_address_t *dst_ip, u16 src_port,
+ u16 dst_port);
+
+/**
* @brief Delete a udp tunnel
*
* @param proto FIB_PROTOCOL_IP4 or FIB_PROTOCOL_IP6
@@ -96,6 +111,24 @@ int udp_tunnel_del (fib_protocol_t proto, index_t fib_index,
void udp_tunnel_add_existing (index_t uei, dpo_proto_t proto);
/**
+ * @brief Check if DPO is UDP encap
+ */
+always_inline int
+dpo_is_udp_encap (const dpo_id_t *dpo)
+{
+ return dpo->dpoi_type == dpo_type_udp_ip4 ||
+ dpo->dpoi_type == dpo_type_udp_ip6;
+}
+
+always_inline dpo_proto_t
+dpo_udp_encap_get_proto (const dpo_id_t *dpo)
+{
+ return dpo->dpoi_type == dpo_type_udp_ip4 ? DPO_PROTO_IP4 : DPO_PROTO_IP6;
+}
+
+void udp_tunnel_set_face (hicn_face_id_t face_id, int isv4);
+
+/**
* @brief Init the udp tunnel module
*
*/
diff --git a/hicn-plugin/src/utils.h b/hicn-plugin/src/utils.h
index 847f2f388..7a3492732 100644
--- a/hicn-plugin/src/utils.h
+++ b/hicn-plugin/src/utils.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/hicn-plugin/vapi/CMakeLists.txt b/hicn-plugin/vapi/CMakeLists.txt
deleted file mode 100644
index 6c176b9f3..000000000
--- a/hicn-plugin/vapi/CMakeLists.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-# Copyright (c) 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.10 FATAL_ERROR)
-
-set(SAFE_VAPI safe_vapi CACHE INTERNAL "" FORCE)
-set(SAFE_VAPI_SHARED ${SAFE_VAPI}.shared CACHE INTERNAL "" FORCE)
-set(SAFE_VAPI_STATIC ${SAFE_VAPI}.static CACHE INTERNAL "" FORCE)
-
-# Dependencies
-
-find_package(Vpp REQUIRED)
-
-list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/include/vapi/vapi_safe.h
-)
-
-list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/vapi_safe.c
-)
-
-set (LIBRARIES
- ${VPP_LIBRARY_VAPICLIENT})
-
-list (APPEND INCLUDE_DIRS
- ${VPP_INCLUDE_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}/include)
-
-build_library(${SAFE_VAPI}
- SHARED STATIC
- SOURCES ${SOURCE_FILES} ${HEADER_FILES}
- INSTALL_HEADERS ${HEADER_FILES}
- LINK_LIBRARIES ${LIBRARIES}
- COMPONENT ${HICN_PLUGIN}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- HEADER_ROOT_DIR /
- DEFINITIONS ${COMPILER_DEFINITIONS}
- )
-
-set(SAFE_VAPI_INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR}/include
- "" CACHE INTERNAL
- "" FORCE
-)
-
-set(SAFE_VAPI_LIBRARIES
- ${SAFE_VAPI_SHARED}
- "" CACHE INTERNAL
- "" FORCE
-)
-
diff --git a/hicn-plugin/vapi/include/vapi/vapi_safe.h b/hicn-plugin/vapi/include/vapi/vapi_safe.h
deleted file mode 100644
index df1114cde..000000000
--- a/hicn-plugin/vapi/include/vapi/vapi_safe.h
+++ /dev/null
@@ -1,19 +0,0 @@
-#ifndef VAPI_SAFE
-#include <vapi/vapi.h>
-#include <pthread.h>
-
-extern pthread_mutex_t *mutex;
-
-vapi_error_e vapi_connect_safe(vapi_ctx_t * vapi_ctx_ret, int async);
-
-vapi_error_e vapi_disconnect_safe();
-void vapi_lock();
-
-void vapi_unlock();
-
-#define VAPI_SAFE (NAME, res, ...) \
- vapi_lock(); \
- res = ## NAME (__ARGS__); \
- vapi_unlock();
-
-#endif //VAPI_SAFE
diff --git a/hicn-plugin/vapi/vapi_safe.c b/hicn-plugin/vapi/vapi_safe.c
deleted file mode 100644
index e9353497f..000000000
--- a/hicn-plugin/vapi/vapi_safe.c
+++ /dev/null
@@ -1,73 +0,0 @@
-#include <vapi/vapi_safe.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#define APP_NAME "hicn_plugin"
-#define MAX_OUTSTANDING_REQUESTS 4
-#define RESPONSE_QUEUE_SIZE 2
-
-pthread_mutex_t *mutex = NULL;
-vapi_ctx_t g_vapi_ctx_instance = NULL;
-u32 count = 0;
-int lock = 0;
-
-vapi_error_e vapi_connect_safe(vapi_ctx_t *vapi_ctx_ret, int async) {
- vapi_error_e rv = VAPI_OK;
-
- while (!__sync_bool_compare_and_swap(&lock, 0, 1));
-
- if (!g_vapi_ctx_instance && !mutex)
- {
- rv = vapi_ctx_alloc(&g_vapi_ctx_instance);
- if (rv != VAPI_OK)
- goto err;
-
- mutex = malloc(sizeof(pthread_mutex_t));
- if (!mutex)
- goto err_mutex_alloc;
-
- if (pthread_mutex_init(mutex, NULL) != 0) {
- printf("Mutex init failed\n");
- goto err_mutex_init;
- }
- }
-
- if (!count)
- {
- rv = vapi_connect(g_vapi_ctx_instance, APP_NAME, NULL,
- MAX_OUTSTANDING_REQUESTS, RESPONSE_QUEUE_SIZE,
- async ? VAPI_MODE_NONBLOCKING : VAPI_MODE_BLOCKING, true);
-
- if (rv != VAPI_OK)
- goto err;
-
- count++;
- }
-
- *vapi_ctx_ret = g_vapi_ctx_instance;
-
- while (!__sync_bool_compare_and_swap(&lock, 1, 0));
- return rv;
-
- err_mutex_init:
- free(mutex);
- err_mutex_alloc:
- err:
- while (!__sync_bool_compare_and_swap(&lock, 1, 0));
- return VAPI_ENOMEM;
-}
-
-vapi_error_e vapi_disconnect_safe() {
- pthread_mutex_lock(mutex);
- vapi_error_e rv = VAPI_OK;
- pthread_mutex_unlock(mutex);
- return rv;
-}
-
-void vapi_lock() {
- pthread_mutex_lock(mutex);
-}
-
-void vapi_unlock() {
- pthread_mutex_unlock(mutex);
-}
diff --git a/cmake/Modules/IosMacros.cmake b/internal/cmake/Modules/CheckSafeC.cmake
index b1e5cc438..fe0b996bd 100644
--- a/cmake/Modules/IosMacros.cmake
+++ b/internal/cmake/Modules/CheckSafeC.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,14 +11,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-if(COMPILE_FOR_IOS)
- include_directories(iOS)
-endif()
-
-macro(find_package_wrapper)
- if(COMPILE_FOR_IOS)
- find_host_package(${ARGN})
- else()
- find_package(${ARGN})
- endif()
+macro(CheckSafeC)
+ if(INTERNAL_ENVIRONMENT_FOUND)
+ set(SAFEC_DEPENDENCY "ciscosafec")
+ endif()
endmacro() \ No newline at end of file
diff --git a/libtransport/cmake/Modules/Ios.cmake b/internal/cmake/Modules/CheckSsl.cmake
index 1b2aae2bf..bf1b11737 100644
--- a/libtransport/cmake/Modules/Ios.cmake
+++ b/internal/cmake/Modules/CheckSsl.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,10 +11,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-function (configure_ios_environment)
- find_host_package ( OpenSSL REQUIRED )
- include_directories(extras/iOS)
-
- find_host_package(Libhicn REQUIRED)
- include_directories(${HICN_INCLUDE_DIRS})
-endfunction() \ No newline at end of file
+macro(CheckSsl)
+ if("${OPENSSL_INCLUDE_DIR}" MATCHES ".*cisco.*")
+ set(OPENSSL_DEPENDENCY "tk-libssl1.1")
+ set(OPENSSL_DEPENDENCY_DEV "tk-libssl-dev")
+ endif()
+endmacro() \ No newline at end of file
diff --git a/internal/cmake/Modules/FindCiscoSafeC.cmake b/internal/cmake/Modules/FindCiscoSafeC.cmake
new file mode 100644
index 000000000..9f723a018
--- /dev/null
+++ b/internal/cmake/Modules/FindCiscoSafeC.cmake
@@ -0,0 +1,54 @@
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+########################################
+#
+# Find the CiscoSafeC libraries and includes
+# This module sets:
+# CISCOSAFEC_FOUND: True if CiscoSafeC was found
+# CISCOSAFEC_LIBRARY: The CiscoSafeC library
+# CISCOSAFEC_LIBRARIES: The CiscoSafeC library and dependencies
+# CISCOSAFEC_INCLUDE_DIR: The CiscoSafeC include dir
+#
+
+set(CISCOSAFEC_SEARCH_PATH_LIST
+ ${CISCOSAFEC_HOME}
+ $ENV{CISCOSAFEC_HOME}
+ /usr/local
+ /opt
+ /usr
+)
+
+find_path(CISCOSAFEC_INCLUDE_DIR safec_config.h
+ HINTS ${CISCOSAFEC_SEARCH_PATH_LIST}
+ PATH_SUFFIXES include include/safec
+ DOC "Find the CiscoSafeC includes"
+)
+
+find_library(CISCOSAFEC_LIBRARY NAMES ciscosafec
+ HINTS ${CISCOSAFEC_SEARCH_PATH_LIST}
+ PATH_SUFFIXES lib
+ DOC "Find the CiscoSafeC libraries"
+)
+
+set(CISCOSAFEC_LIBRARIES ${CISCOSAFEC_LIBRARY})
+set(CISCOSAFEC_INCLUDE_DIRS ${CISCOSAFEC_INCLUDE_DIR})
+
+include(FindPackageHandleStandardArgs)
+set(CISCOSAFEC_FOUND False)
+
+if (NOT "${CISCOSAFEC_INCLUDE_DIR}" STREQUAL "")
+ set(CISCOSAFEC_FOUND True)
+ find_package_handle_standard_args(CiscoSafeC DEFAULT_MSG CISCOSAFEC_LIBRARY CISCOSAFEC_INCLUDE_DIR)
+ mark_as_advanced(CISCOSAFEC_LIBRARY CISCOSAFEC_INCLUDE_DIR)
+endif ()
diff --git a/libtransport/cmake/Modules/Android.cmake b/internal/cmake/Modules/ImportInternal.cmake
index 78918455a..73cdac1a7 100644
--- a/libtransport/cmake/Modules/Android.cmake
+++ b/internal/cmake/Modules/ImportInternal.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,9 +11,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-function (configure_android_environment)
- set(CMAKE_CXX_FLAGS " -Wall -stdlib=libc++ -DASIO_STANDALONE -pthread -isystem -lm")
-
- #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" PARENT_SCOPE)
- #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${ANDROID_C_FLAGS}" PARENT_SCOPE)
-endfunction() \ No newline at end of file
+macro(ImportInternal)
+ find_package(CiscoSafeC)
+ if (CiscoSafeC_FOUND)
+ list(APPEND COMPILER_DEFINITIONS
+ "-DENABLE_SAFEC"
+ )
+ list(APPEND THIRD_PARTY_LIBRARIES ${CISCOSAFEC_LIBRARY})
+ list(APPEND THIRD_PARTY_INCLUDE_DIRS ${CISCOSAFEC_INCLUDE_DIR})
+ endif()
+endmacro() \ No newline at end of file
diff --git a/internal/cmake/Modules/SetRelyGitRepo.cmake b/internal/cmake/Modules/SetRelyGitRepo.cmake
new file mode 100644
index 000000000..facdc19b9
--- /dev/null
+++ b/internal/cmake/Modules/SetRelyGitRepo.cmake
@@ -0,0 +1,20 @@
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+macro(SetRelyGitRepo)
+ if(DEFINED ENV{BITBUCKET_USERNAME} AND DEFINED ENV{BITBUCKET_PASSWORD})
+ set(GIT_REPO https://$ENV{BITBUCKET_USERNAME}:$ENV{BITBUCKET_PASSWORD}@bitbucket-eng-gpk1.cisco.com/bitbucket/scm/icn/rely.git)
+ else()
+ set(GIT_REPO ssh://git@bitbucket-eng-gpk1.cisco.com:7999/icn/rely.git)
+ endif()
+endmacro() \ No newline at end of file
diff --git a/lib/.clang-format b/lib/.clang-format
index 351a70e20..b4846b63a 100644
--- a/lib/.clang-format
+++ b/lib/.clang-format
@@ -10,11 +10,5 @@ BreakBeforeBinaryOperators: None
ContinuationIndentWidth: 2
ForEachMacros:
- - 'clib_bitmap_foreach'
- - 'pool_foreach'
- - 'pool_foreach_index'
- - 'vec_foreach'
- - 'vec_foreach_backwards'
- - 'vec_foreach_index'
- - 'vec_foreach_index_backwards'
- - 'vlib_foreach_rx_tx'
+ - 'interest_manifest_foreach_suffix'
+
diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt
index 65c1cd4ee..ca845ab48 100644
--- a/lib/CMakeLists.txt
+++ b/lib/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,41 +11,50 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Project and cmake version
+##############################################################
cmake_minimum_required (VERSION 3.10 FATAL_ERROR)
project(libhicn C)
-#include(CTest)
+
+##############################################################
+# Cmake modules
+##############################################################
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
"${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
)
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
+if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ include(CommonSetup)
endif()
+
+##############################################################
+# Libs and Bins names
+##############################################################
set(LIBHICN hicn CACHE INTERNAL "" FORCE)
+set(LIBHICN_COMPONENT lib${LIBHICN} CACHE INTERNAL "" FORCE)
set(LIBHICN_SHARED ${LIBHICN}.shared CACHE INTERNAL "" FORCE)
set(LIBHICN_STATIC ${LIBHICN}.static CACHE INTERNAL "" FORCE)
-set(HICN_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/includes CACHE INTERNAL "" FORCE)
-
-include (Packaging)
-option(CMAKE_BUILD_TEST "Build unit tests" OFF)
+##############################################################
+# Dependencies
+##############################################################
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
+if(INTERNAL_ENVIRONMENT)
+ include(ImportInternal)
+ ImportInternal()
+ set(INTERNAL_ENVIRONMENT_FOUND True CACHE STRING "Internal dependency found")
endif()
-if (NOT WIN32)
- set(CMAKE_C_FLAGS -Wall)
-else ()
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4996")
-endif ()
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
-add_subdirectory(includes)
-add_subdirectory (src)
+add_subdirectory(includes)
+add_subdirectory(src)
diff --git a/lib/cmake/Modules/Packaging.cmake b/lib/cmake/packaging.cmake
index 2ceda1426..5f1691722 100644
--- a/lib/cmake/Modules/Packaging.cmake
+++ b/lib/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -32,11 +32,21 @@ set(lib${LIBHICN}-dev_DESCRIPTION ${${LIBHICN}_DESCRIPTION}
)
set(lib${LIBHICN}-dev_DEB_DEPENDENCIES
- "libhicn (>= stable_version)"
+ "libhicn (= stable_version)"
CACHE STRING "Dependencies for deb/rpm package."
)
+
+if (INTERNAL_ENVIRONMENT)
+ include(CheckSafeC)
+ CheckSafeC()
+ set(lib${LIBHICN}-dev_DEB_DEPENDENCIES
+ "${lib${LIBHICN}-dev_DEB_DEPENDENCIES}, ${SAFEC_DEPENDENCY}"
+ CACHE STRING "Dependencies for deb/rpm package."
+ )
+endif()
+
set(lib${LIBHICN}-dev_RPM_DEPENDENCIES
- "libhicn >= stable_version"
+ "libhicn = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
)
diff --git a/lib/includes/CMakeLists.txt b/lib/includes/CMakeLists.txt
index 6c2c34b86..3c79fb891 100644
--- a/lib/includes/CMakeLists.txt
+++ b/lib/includes/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,8 +11,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-set(HICN_INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR} ""
+##############################################################
+# Public headers directory
+##############################################################
+set(Libhicn_INCLUDE_DIRS
+ ${CMAKE_CURRENT_SOURCE_DIR}
CACHE INTERNAL
"" FORCE
)
@@ -21,38 +24,35 @@ set(LIBHICN_HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/hicn/hicn.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/base.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/common.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/compat.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/error.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/header.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/face.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/mapme.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/name.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/packet.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/policy.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ops.h
- PARENT_SCOPE
-)
-
-set(LIBHICN_HEADER_FILES_PROTOCOL
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol/ah.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol/icmp.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol/icmprd.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol/ipv4.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol/ipv6.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol/tcp.h
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn/protocol/udp.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/strategy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/validation.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/interest_manifest.h
PARENT_SCOPE
)
set(LIBHICN_HEADER_FILES_UTIL
${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/array.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/bitmap.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/hash.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/ip_address.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/khash.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/log.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/map.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/pool.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/ring.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/set.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/slab.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/sstrncpy.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/token.h
${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/types.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn/util/vector.h
PARENT_SCOPE
)
set_property(GLOBAL PROPERTY LIBHICN_HEADER_FILES_UTIL_PROPERTY "${LIBHICN_HEADER_FILES_UTIL}")
-
diff --git a/lib/includes/hicn/base.h b/lib/includes/hicn/base.h
index 1061724ce..dcbe47877 100644
--- a/lib/includes/hicn/base.h
+++ b/lib/includes/hicn/base.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,6 +21,8 @@
#ifndef HICN_BASE_H
#define HICN_BASE_H
+#include <stdio.h>
+#include <stdbool.h>
#include "common.h"
#ifdef _WIN32
#include <Winsock2.h>
@@ -30,20 +32,29 @@
/* Default header fields */
#define HICN_DEFAULT_TTL 254
+#define SYMBOLIC_NAME_LEN 16
+
+/* hICN attribute types */
+
+/* Face id */
+
typedef u32 hicn_faceid_t;
-typedef u8 hicn_pathlabel_t;
+
+/* Lifetime */
+
typedef u32 hicn_lifetime_t;
-#define HICN_MAX_LIFETIME_SCALED 0xFFFF
-#define HICN_MAX_LIFETIME_MULTIPLIER 0x0F /* 4 bits */
-#define HICN_MAX_LIFETIME HICN_MAX_LIFETIME_SCALED << HICN_MAX_LIFETIME_MULTIPLIER
+#define HICN_MAX_LIFETIME_SCALED 0xFFFF
+#define HICN_MAX_LIFETIME_MULTIPLIER 0x0F /* 4 bits */
+#define HICN_MAX_LIFETIME \
+ HICN_MAX_LIFETIME_SCALED << HICN_MAX_LIFETIME_MULTIPLIER
/**
* @brief hICN packet format type
*
- * The hICN type represents the sequence of protocols that we can find in packet
- * headers. They are represented as a quartet of u8 values, correponding to
- * IANA protocol assignment, and read from right to left. This is done to
+ * The hICN type represents the sequence of protocols that we can find in
+ * packet headers. They are represented as a quartet of u8 values, correponding
+ * to IANA protocol assignment, and read from right to left. This is done to
* faciliate decapsulation of packet header by simple shift/mask operations.
*
* For instance, an IPv6/TCP packet will be identified as :
@@ -53,72 +64,168 @@ typedef u32 hicn_lifetime_t;
* currently used by an hypothetical signed MAP-Me update :
* [IPPROTO_ICMPRD, IPPROTO_AH, IPPROTO_ICMP, IPPROTO_IPV6]
*/
-typedef union
-{
- /** protocol layers representation */
- struct
- {
-#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
- u8 l1; /**< First layer */
- u8 l2; /**< Second layer */
- u8 l3; /**< Third layer */
- u8 l4; /**< Fourth layer */
-#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
- u8 l4; /**< Fourth layer */
- u8 l3; /**< Third layer */
- u8 l2; /**< Second layer */
- u8 l1; /**< First layer */
-#elif _WIN32 /* Windows is assumed little-endian */
- u8 l1;
- u8 l2;
- u8 l3;
- u8 l4;
-#else
-#error "Unsupported endianness"
-#endif
- };
- /** u32 representation */
- u32 as_u32;
-} hicn_type_t;
+
+typedef uint32_t hicn_packet_format_t;
/* Common protocol layers */
-/* Common protocol layers */
-#ifndef _WIN32
-#define HICN_TYPE(x,y,z,t) (hicn_type_t) {{ .l1 = x, .l2 = y, .l3 = z, .l4 = t }}
-#else
-inline hicn_type_t
-HICN_TYPE(int x, int y, int z, int t)
-{
- hicn_type_t type;
- type.l1 = x;
- type.l2 = y;
- type.l3 = z;
- type.l4 = t;
- return type;
-}
+#define HICN_PACKET_FORMAT(x, y, z, t) \
+ (uint32_t) (((x) << 24) + ((y) << 16) + ((z) << 8) + (t))
+
+#define HICN_PACKET_FORMAT_SIZE 4
+
+// i = 0..3
+#define HICN_PACKET_FORMAT_GET(format, i) \
+ (i < 0 || i > 3) ? IPPROTO_NONE : ((format >> ((3 - (i)) << 3)) & 0xFF)
+
+#define HICN_PACKET_FORMAT_SET(format, i, val) \
+ format = ((val << ((3 - i) << 3)) | \
+ (format & (0xFFFFFFFF ^ (0xFF << ((3 - i) << 3)))))
+
+#define HICN_PACKET_FORMAT_ENUMERATE(FORMAT, POS, PROTOCOL, BODY) \
+ for (unsigned POS = 0; POS <= HICN_PACKET_FORMAT_SIZE - 1; POS++) \
+ { \
+ uint8_t PROTOCOL = HICN_PACKET_FORMAT_GET (FORMAT, POS); \
+ BODY; \
+ }
+
+#define HICN_PACKET_FORMAT_L1(format) HICN_PACKET_FORMAT_L ((format), 0)
+#define HICN_PACKET_FORMAT_L2(format) HICN_PACKET_FORMAT_L ((format), 1)
+#define HICN_PACKET_FORMAT_L3(format) HICN_PACKET_FORMAT_L ((format), 2)
+#define HICN_PACKET_FORMAT_L4(format) HICN_PACKET_FORMAT_L ((format), 3)
+
+extern const char *const _protocol_str[];
+
+#define protocol_str(x) protocol_str[x]
+
+int hicn_packet_format_snprintf (char *s, size_t size,
+ hicn_packet_format_t format);
+
+#define MAXSZ_HICN_PACKET_FORMAT 4 * 4 + 3 // ICMP/ICMP/ICMP/ICMP
+
+#if !defined(__cplusplus)
+#define constexpr const
#endif
-#define HICN_TYPE_IPV4_TCP HICN_TYPE(IPPROTO_IP, IPPROTO_TCP, IPPROTO_NONE, IPPROTO_NONE)
-#define HICN_TYPE_IPV4_ICMP HICN_TYPE(IPPROTO_IP, IPPROTO_ICMP, IPPROTO_NONE, IPPROTO_NONE)
-#define HICN_TYPE_IPV6_TCP HICN_TYPE(IPPROTO_IPV6, IPPROTO_TCP, IPPROTO_NONE, IPPROTO_NONE)
-#define HICN_TYPE_IPV6_ICMP HICN_TYPE(IPPROTO_IPV6, IPPROTO_ICMPV6, IPPROTO_NONE, IPPROTO_NONE)
-#define HICN_TYPE_IPV4_TCP_AH HICN_TYPE(IPPROTO_IP, IPPROTO_TCP, IPPROTO_AH, IPPROTO_NONE)
-#define HICN_TYPE_IPV4_ICMP_AH HICN_TYPE(IPPROTO_IP, IPPROTO_ICMP, IPPROTO_AH, IPPROTO_NONE)
-#define HICN_TYPE_IPV6_TCP_AH HICN_TYPE(IPPROTO_IPV6, IPPROTO_TCP, IPPROTO_AH, IPPROTO_NONE)
-#define HICN_TYPE_IPV6_ICMP_AH HICN_TYPE(IPPROTO_IPV6, IPPROTO_ICMPV6, IPPROTO_AH, IPPROTO_NONE)
-#define HICN_TYPE_NONE HICN_TYPE(IPPROTO_NONE, IPPROTO_NONE, IPPROTO_NONE, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV4_TCP \
+ HICN_PACKET_FORMAT (IPPROTO_IP, IPPROTO_TCP, IPPROTO_NONE, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV4_ICMP \
+ HICN_PACKET_FORMAT (IPPROTO_IP, IPPROTO_ICMP, IPPROTO_NONE, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV6_TCP \
+ HICN_PACKET_FORMAT (IPPROTO_IPV6, IPPROTO_TCP, IPPROTO_NONE, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV6_ICMP \
+ HICN_PACKET_FORMAT (IPPROTO_IPV6, IPPROTO_ICMPV6, IPPROTO_NONE, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_NEW \
+ HICN_PACKET_FORMAT (IPPROTO_ENCAP, IPPROTO_NONE, IPPROTO_NONE, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV4_UDP \
+ HICN_PACKET_FORMAT (IPPROTO_IP, IPPROTO_UDP, IPPROTO_ENCAP, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV6_UDP \
+ HICN_PACKET_FORMAT (IPPROTO_IPV6, IPPROTO_UDP, IPPROTO_ENCAP, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV4_TCP_AH \
+ HICN_PACKET_FORMAT (IPPROTO_IP, IPPROTO_TCP, IPPROTO_AH, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV4_ICMP_AH \
+ HICN_PACKET_FORMAT (IPPROTO_IP, IPPROTO_ICMP, IPPROTO_AH, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV6_TCP_AH \
+ HICN_PACKET_FORMAT (IPPROTO_IPV6, IPPROTO_TCP, IPPROTO_AH, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV6_ICMP_AH \
+ HICN_PACKET_FORMAT (IPPROTO_IPV6, IPPROTO_ICMPV6, IPPROTO_AH, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_NEW_AH \
+ HICN_PACKET_FORMAT (IPPROTO_ENCAP, IPPROTO_AH, IPPROTO_NONE, IPPROTO_NONE)
+#define HICN_PACKET_FORMAT_IPV6_UDP_AH \
+ HICN_PACKET_FORMAT (IPPROTO_IPV6, IPPROTO_UDP, IPPROTO_ENCAP, IPPROTO_AH)
+#define HICN_PACKET_FORMAT_IPV4_UDP_AH \
+ HICN_PACKET_FORMAT (IPPROTO_IP, IPPROTO_UDP, IPPROTO_ENCAP, IPPROTO_AH)
+#define HICN_PACKET_FORMAT_NONE \
+ HICN_PACKET_FORMAT (IPPROTO_NONE, IPPROTO_NONE, IPPROTO_NONE, IPPROTO_NONE)
+
+/* Default packet format */
+
+#define HICN_PACKET_FORMAT_DEFAULT HICN_PACKET_FORMAT_IPV6_TCP
/**
- * @brief Check if type is none.
- * @return 1 if none, 0 otherwise
+ * @brief Return the hICN format with an additional AH header
+ * @param [in] format - hICN packet format
+ * @return Updated hICN packet format
*/
-always_inline int
-hicn_type_is_none(hicn_type_t type)
+static inline hicn_packet_format_t
+hicn_get_ah_format (hicn_packet_format_t format)
{
- return (type.l1 == IPPROTO_NONE) && (type.l2 == IPPROTO_NONE) &&
- (type.l3 == IPPROTO_NONE) && (type.l4 == IPPROTO_NONE);
+ HICN_PACKET_FORMAT_ENUMERATE (format, i, protocol, {
+ switch (protocol)
+ {
+ {
+ case IPPROTO_AH:
+ return format;
+ case IPPROTO_NONE:
+ HICN_PACKET_FORMAT_SET (format, i, IPPROTO_AH);
+ return format;
+ default:
+ break;
+ }
+ }
+ });
+ return format;
}
+/*
+ * MAX(IPV4_HDRLEN (20), IPV6_HDRLEN (40))
+ * + MAX (TCP_HDRLEN (20), UDP_HDRLEN (8), ICMP_HDRLEN (8), NEW_HDRLEN (32))
+ * + AH_HDRLEN
+ */
+#define HICN_HDRLEN_MAX 72
+
+#define HICN_PACKET_FORMAT_IS_NONE(format) \
+ ((HICN_PACKET_FORMAT_GET (format, 0) == IPPROTO_NONE) && \
+ (HICN_PACKET_FORMAT_GET (format, 1) == IPPROTO_NONE) && \
+ (HICN_PACKET_FORMAT_GET (format, 2) == IPPROTO_NONE) && \
+ (HICN_PACKET_FORMAT_GET (format, 3) == IPPROTO_NONE))
+
+#define HICN_PACKET_FORMAT_IS_AH(format) \
+ ((HICN_PACKET_FORMAT_GET (format, 0) == IPPROTO_AH) || \
+ (HICN_PACKET_FORMAT_GET (format, 1) == IPPROTO_AH) || \
+ (HICN_PACKET_FORMAT_GET (format, 2) == IPPROTO_AH) || \
+ (HICN_PACKET_FORMAT_GET (format, 3) == IPPROTO_AH))
+
+#define HICN_PACKET_FORMAT_IS_IPV4(format) \
+ (HICN_PACKET_FORMAT_GET (format, 0) == IPPROTO_IP)
+#define HICN_PACKET_FORMAT_IS_IPV6(format) \
+ (HICN_PACKET_FORMAT_GET (format, 0) == IPPROTO_IPV6)
+
+/*
+ * @brief hICN packet types
+ *
+ * probes are like normal interest & data but:
+ * - interests use BFD port as the destination
+ * - data use BFD port as the source + expiry time must be 0.
+ * if any of these conditions is not met, the packet is still matched as an
+ * interest or data packet.
+ *
+ */
+
+#define foreach_packet_type \
+ _ (UNDEFINED) \
+ _ (INTEREST) \
+ _ (DATA) \
+ _ (WLDR_NOTIFICATION) \
+ _ (MAPME) \
+ _ (PROBE) \
+ _ (COMMAND) \
+ _ (N)
+
+/**
+ * @brief hICN Packet type
+ */
+typedef enum
+{
+#define _(x) HICN_PACKET_TYPE_##x,
+ foreach_packet_type
+#undef _
+} hicn_packet_type_t;
+#undef foreach_type
+
+extern const char *_hicn_packet_type_str[];
+
+#define hicn_packet_type_str(x) _hicn_packet_type_str[x]
+
/**
* @brief hICN Payload type
*
@@ -132,39 +239,120 @@ typedef enum
HPT_UNSPEC = 999
} hicn_payload_type_t;
+/* Path label */
+
+typedef u8 hicn_path_label_t;
+
+#define INVALID_PATH_LABEL 0
+
/**
* @brief Path label computations
*
- * Path label is computed by accumulating the identifiers of successive output
- * faces as a Data packet is traveling from its producer back to the consumer
- * originating the Interest.
+ * Path label is computed by accumulating the identifiers of successive
+ * output faces as a Data packet is traveling from its producer back to the
+ * consumer originating the Interest.
*
* NOTE: this computation is not (yet) part of the hICN specification.
*/
-#define HICN_PATH_LABEL_MASK 0x000000ff
-#define HICN_PATH_LABEL_SIZE 8
+#define HICN_PATH_LABEL_MASK 0x000000ff
+#define HICN_PATH_LABEL_SIZE_BITS sizeof (hicn_path_label_t) * 8
/**
* @brief Path label update
- * @param [in] current_label Current pathlabel
+ * @param [in] current_label Current path_label
* @param [in] face_id The face identifier to combine into the path label
- * @param [out] new_label Computed pathlabel
+ * @param [out] new_label Computed path_label
*
- * This function updates the current_label based on the new face_id, and returns
+ * This function updates the current_label based on the new face_id, and
+ * returns
*/
-always_inline void
-update_pathlabel (hicn_pathlabel_t current_label, hicn_faceid_t face_id,
- hicn_pathlabel_t * new_label)
+static inline void
+update_path_label (hicn_path_label_t current_label, hicn_faceid_t face_id,
+ hicn_path_label_t *new_label)
{
- hicn_pathlabel_t pl_face_id =
- (hicn_pathlabel_t) (face_id & HICN_PATH_LABEL_MASK);
+ hicn_path_label_t pl_face_id =
+ (hicn_path_label_t) (face_id & HICN_PATH_LABEL_MASK);
- *new_label =
- ((current_label << 1) | (current_label >> (HICN_PATH_LABEL_SIZE - 1))) ^
- pl_face_id;
+ *new_label = ((current_label << 1) |
+ (current_label >> (HICN_PATH_LABEL_SIZE_BITS - 1))) ^
+ pl_face_id;
}
+/***************************************************************
+ * Statistics
+ ***************************************************************/
+
+typedef struct
+{
+ // Packets processed
+ uint32_t countReceived; // Interest and data only
+ uint32_t countInterestsReceived;
+ uint32_t countObjectsReceived;
+
+ // Packets Dropped
+ uint32_t countDropped;
+ uint32_t countInterestsDropped;
+ uint32_t countObjectsDropped;
+ uint32_t countOtherDropped;
+
+ // Forwarding
+ uint32_t countInterestForwarded;
+ uint32_t countObjectsForwarded;
+
+ // Errors while forwarding
+ uint32_t countDroppedConnectionNotFound;
+ uint32_t countSendFailures;
+ uint32_t countDroppedNoRoute;
+
+ // Interest processing
+ uint32_t countInterestsAggregated;
+ uint32_t countInterestsRetransmitted;
+ uint32_t countInterestsSatisfiedFromStore;
+ uint32_t countInterestsExpired;
+
+ // Data processing
+ uint32_t countDroppedNoReversePath;
+ uint32_t countDataExpired;
+
+ // TODO(eloparco): Currently not used
+ // uint32_t countDroppedNoHopLimit;
+ // uint32_t countDroppedZeroHopLimitFromRemote;
+ // uint32_t countDroppedZeroHopLimitToRemote;
+} forwarder_stats_t;
+
+typedef struct
+{
+ uint32_t n_pit_entries;
+ uint32_t n_cs_entries;
+ uint32_t n_lru_evictions;
+} pkt_cache_stats_t;
+
+typedef struct
+{
+ forwarder_stats_t forwarder;
+ pkt_cache_stats_t pkt_cache;
+} hicn_light_stats_t;
+
+typedef struct
+{
+ uint32_t conn_id;
+ struct
+ {
+ uint32_t rx_pkts;
+ uint32_t rx_bytes;
+ uint32_t tx_pkts;
+ uint32_t tx_bytes;
+ } interests;
+ struct
+ {
+ uint32_t rx_pkts;
+ uint32_t rx_bytes;
+ uint32_t tx_pkts;
+ uint32_t tx_bytes;
+ } data;
+} connection_stats_t;
+
#endif /* HICN_BASE_H */
/*
diff --git a/lib/includes/hicn/common.h b/lib/includes/hicn/common.h
index 05f8ad95f..64aca8f1f 100644
--- a/lib/includes/hicn/common.h
+++ b/lib/includes/hicn/common.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -36,59 +36,23 @@
#include <stdint.h>
#include <assert.h>
-/* Concise type definitions */
+#include <hicn/util/types.h>
-typedef uint64_t u64;
-typedef uint32_t u32;
-typedef uint16_t u16;
-typedef uint8_t u8;
+#define HICN_EXPECT_FALSE(x) __builtin_expect ((x), 1)
+#define HICN_EXPECT_TRUE(x) __builtin_expect ((x), 0)
+#define HICN_UNUSED(x) x __attribute__ ((unused))
-/*
- * Code annotations
- *
- * NOTE: these are defined by default in VPP.
- */
-
-#ifndef HICN_VPP_PLUGIN
-
-#define PREDICT_FALSE(x) (x)
-#define PREDICT_TRUE(x) (x)
-#define always_inline static inline
-#define static_always_inline static inline
-#define STRUCT_SIZE_OF(type, member) sizeof(((type *)0)->member)
-#define ASSERT
-
-#define STATIC_ASSERT(x)
-
-/* Architecture-dependent uword size */
-#if INTPTR_MAX == INT64_MAX
-#define log2_uword_bits 6
-#elif INTPTR_MAX == INT32_MAX
-#define log2_uword_bits 5
+#ifndef NDEBUG
+#define _ASSERT(x) assert (x)
#else
-#error "Impossible to detect architecture"
+#define _ASSERT(x) ((void) (x))
#endif
-#define uword_bits (1 << log2_uword_bits)
-
-/* Word types. */
-#if uword_bits == 64
-/* 64 bit word machines. */
-typedef u64 uword;
-#else
-/* 32 bit word machines. */
-typedef u32 uword;
-#endif
-
-typedef uword ip_csum_t;
-
-#endif /* ! HICN_VPP_PLUGIN */
-
/*
- * Windows compilers do not support named initilizers when .h files are included
- * inside C++ files. For readability, we either use the following macro, or
- * duplicate some code, with the intent of preserving those safeguards for
- * non-Windows platforms.
+ * Windows compilers do not support named initilizers when .h files are
+ * included inside C++ files. For readability, we either use the following
+ * macro, or duplicate some code, with the intent of preserving those
+ * safeguards for non-Windows platforms.
*/
#ifndef _WIN32
#define ATTR_INIT(key, value) .key = value
@@ -97,12 +61,12 @@ typedef uword ip_csum_t;
#endif
#ifdef _WIN32
- /* Endianness detection for Windows platforms */
+/* Endianness detection for Windows platforms */
#define __ORDER_LITTLE_ENDIAN__ 0x41424344UL
-#define __ORDER_BIG_ENDIAN__ 0x44434241UL
-#define __BYTE_ORDER__ ('ABCD')
+#define __ORDER_BIG_ENDIAN__ 0x44434241UL
+#define __BYTE_ORDER__ ('ABCD')
- /* Windows compatibility headers */
+/* Windows compatibility headers */
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX
@@ -116,10 +80,10 @@ typedef uword ip_csum_t;
#define strdup _strdup
#define __attribute__(A)
-#ifndef IOVEC
+#ifndef IOVEC
#define IOVEC
#define UIO_MAXIOV 16
-#define IOV_MAX UIO_MAXIOV
+#define IOV_MAX UIO_MAXIOV
struct iovec
{
void *iov_base;
@@ -132,66 +96,20 @@ struct iovec
* Portable attribute packed.
*/
#ifndef _WIN32
-#define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__))
+#define PACKED(__Declaration__) __Declaration__ __attribute__ ((__packed__))
#else
-#define PACKED( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop) )
+#define PACKED(__Declaration__) \
+ __pragma (pack (push, 1)) __Declaration__ __pragma (pack (pop))
#endif
-
/*
* IP address types
*/
-#ifdef HICN_VPP_PLUGIN
-
-#include <vnet/ip/ip4_packet.h> // ip4_address_t
-#include <vnet/ip/ip6_packet.h> // ip6_address_t
-
-#if __GNUC__ >= 9
-#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
-#endif
-
-#include <vnet/ip/ip46_address.h>
-
-#if __GNUC__ >= 9
-#pragma GCC diagnostic pop
-#endif
-
-#else
-
-
#ifndef _WIN32
#include <netinet/in.h>
#endif
-typedef union
-{
- u32 as_u32;
- struct in_addr as_inaddr;
-} ip4_address_t;
-
-typedef union
-{
- u64 as_u64[2];
- u32 as_u32[4];
- u8 as_u8[16];
- struct in6_addr as_in6addr;
-} ip6_address_t;
-
-typedef union
-{
- struct
- {
- u32 pad[3];
- ip4_address_t ip4;
- };
- ip6_address_t ip6;
-} ip46_address_t;
-
-#define ip46_address_is_ip4(ip46) (((ip46)->pad[0] | (ip46)->pad[1] | (ip46)->pad[2]) == 0)
-
-#endif /* ! HICN_VPP_PLUGIN */
-
/**
* @brief Returns the family of an IP address
* @param [in] ip_address - IP address in presentation format
@@ -215,33 +133,33 @@ int get_addr_family (const char *ip_address);
* borrow this code here.
*/
-static_always_inline u16
-ip_csum_fold (ip_csum_t c)
+static inline u16
+ip_csum_fold (hicn_ip_csum_t c)
{
/* Reduce to 16 bits. */
#if uword_bits == 64
- c = (c & (ip_csum_t) 0xffffffff) + (c >> (ip_csum_t) 32);
+ c = (c & (hicn_ip_csum_t) 0xffffffff) + (c >> (hicn_ip_csum_t) 32);
c = (c & 0xffff) + (c >> 16);
#endif
c = (c & 0xffff) + (c >> 16);
c = (c & 0xffff) + (c >> 16);
- return (u16)c;
+ return (u16) c;
}
-static_always_inline ip_csum_t
-ip_csum_with_carry (ip_csum_t sum, ip_csum_t x)
+static inline hicn_ip_csum_t
+ip_csum_with_carry (hicn_ip_csum_t sum, hicn_ip_csum_t x)
{
- ip_csum_t t = sum + x;
+ hicn_ip_csum_t t = sum + x;
return t + (t < x);
}
/* Update checksum changing field at even byte offset from x -> 0. */
-static_always_inline ip_csum_t
-ip_csum_add_even (ip_csum_t c, ip_csum_t x)
+static inline hicn_ip_csum_t
+ip_csum_add_even (hicn_ip_csum_t c, hicn_ip_csum_t x)
{
- ip_csum_t d;
+ hicn_ip_csum_t d;
d = c - x;
@@ -252,19 +170,17 @@ ip_csum_add_even (ip_csum_t c, ip_csum_t x)
}
/* Update checksum changing field at even byte offset from 0 -> x. */
-static_always_inline ip_csum_t
-ip_csum_sub_even (ip_csum_t c, ip_csum_t x)
+static inline hicn_ip_csum_t
+ip_csum_sub_even (hicn_ip_csum_t c, hicn_ip_csum_t x)
{
return ip_csum_with_carry (c, x);
}
+#endif /* ! HICN_VPP_PLUGIN */
+
u32 cumulative_hash32 (const void *data, size_t len, u32 lastValue);
u32 hash32 (const void *data, size_t len);
-u64 cumulative_hash64 (const void *data, size_t len, u64 lastValue);
-u64 hash64 (const void *data, size_t len);
-void hicn_packet_dump (const uint8_t * buffer, size_t len);
-
-#endif /* ! HICN_VPP_PLUGIN */
+void hicn_packet_dump (const uint8_t *buffer, size_t len);
/**
* @brief Computes buffer checksum
@@ -273,7 +189,7 @@ void hicn_packet_dump (const uint8_t * buffer, size_t len);
* @param [in] init - Checksum initial value
* @return Checksum of specified buffer
*/
-always_inline u16
+static inline u16
csum (const void *addr, size_t size, u16 init)
{
u32 sum = init;
@@ -291,7 +207,7 @@ csum (const void *addr, size_t size, u16 init)
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
- return (u16) ~ sum;
+ return (u16) ~sum;
}
/*
@@ -305,19 +221,110 @@ csum (const void *addr, size_t size, u16 init)
* Query IP version from packet (either 4 or 6)
* (version is located as same offsets in both protocol headers)
*/
-#define HICN_IP_VERSION(packet) ((hicn_header_t *)packet)->v4.ip.version
+typedef struct
+{
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+ u8 dummy : 4;
+ u8 version : 4;
+#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+ u8 version : 4;
+ u8 dummy : 4;
+#else
+#error "Unsupported endianness"
+#endif
+} ip_version_t;
+#define HICN_IP_VERSION(packet) ((ip_version_t *) packet)->version
/*
- * ntohll / htonll allows byte swapping for 64 bits integers
+ * Endianess utils
*/
-#ifndef htonll
-#define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32))
+
+#if (__BYTE_ORDER__) == (__ORDER_LITTLE_ENDIAN__)
+#define HICN_LITTLE_ENDIAN_ARCH
+#else
+#define HICN_BIG_ENDIAN_ARCH
#endif
-#ifndef ntohll
-#define ntohll(x) ((1==ntohl(1)) ? (x) : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32))
+static inline u16
+hicn_conditional_swap_u16 (u16 value)
+{
+#ifdef HICN_LITTLE_ENDIAN_ARCH
+ value = __builtin_bswap16 (value);
#endif
+ return value;
+}
+
+static inline u32
+hicn_conditional_swap_u32 (u32 value)
+{
+#ifdef HICN_LITTLE_ENDIAN_ARCH
+ value = __builtin_bswap32 (value);
+#endif
+
+ return value;
+}
+
+static inline u64
+hicn_conditional_swap_u64 (u64 value)
+{
+#ifdef HICN_LITTLE_ENDIAN_ARCH
+ value = __builtin_bswap64 (value);
+#endif
+
+ return value;
+}
+
+#define hicn_net_to_host_16(x) hicn_conditional_swap_u16 ((u16) (x))
+#define hicn_net_to_host_32(x) hicn_conditional_swap_u32 ((u32) (x))
+#define hicn_net_to_host_64(x) hicn_conditional_swap_u64 ((u64) (x))
+
+#define hicn_host_to_net_16(x) hicn_conditional_swap_u16 ((u16) (x))
+#define hicn_host_to_net_32(x) hicn_conditional_swap_u32 ((u32) (x))
+#define hicn_host_to_net_64(x) hicn_conditional_swap_u64 ((u64) (x))
+
+#define hicn_round_pow2(x, pow2) (((x) + (pow2) -1) & ~((pow2) -1))
+
+#define _SIZEOF_ALIGNED(x, size) hicn_round_pow2 (sizeof (x), size)
+#define SIZEOF_ALIGNED(x) _SIZEOF_ALIGNED (x, sizeof (void *))
+
+/* Definitions for builtins unavailable on MSVC */
+#if defined(_MSC_VER) && !defined(__clang__)
+#include <intrin.h>
+
+uint32_t __inline __builtin_ctz (uint32_t value)
+{
+ uint32_t trailing_zero = 0;
+ if (_BitScanForward (&trailing_zero, value))
+ return trailing_zero;
+ else
+ return 32;
+}
+
+uint32_t __inline __builtin_clz (uint32_t value)
+{
+ uint32_t leading_zero = 0;
+ if (_BitScanReverse (&leading_zero, value))
+ return 31 - leading_zero;
+ else
+ return 32;
+}
+
+uint32_t __inline __builtin_clzl2 (uint64_t value)
+{
+ uint32_t leading_zero = 0;
+ if (_BitScanReverse64 (&leading_zero, value))
+ return 63 - leading_zero;
+ else
+ return 64;
+}
+
+#define __builtin_clzl __builtin_clzll
+#endif
+
+#define next_pow2(x) (x <= 1 ? 1 : 1ul << (64 - __builtin_clzl (x - 1)))
+#define _unused(x) ((void) (x))
+
#endif /* HICN_COMMON_H */
/*
diff --git a/lib/includes/hicn/compat.h b/lib/includes/hicn/compat.h
deleted file mode 100644
index 486c82348..000000000
--- a/lib/includes/hicn/compat.h
+++ /dev/null
@@ -1,469 +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.
- */
-
-/**
- * @file compat.h
- * @brief Implementation of the compatibility layer.
- *
- * The structure of the core API has evolved to support operations of a variety
- * of packet formats in addition to IPv4/TCP and IPv6/TCP, namely with the use
- * of ICMP for signalization and AH headers for integrity. The new API format
- * has been designed to scale better with the multiplicity of packet formats,
- * and provide a unified interface on top. We maintain an interface for the
- * former API in this file, which mainly acts as a wrapper on top of new calls.
- */
-#ifndef HICN_COMPAT_H
-#define HICN_COMPAT_H
-
-#include "common.h"
-#include "header.h"
-#include "name.h"
-
-/* HICN format options */
-#define HFO_INET 1 << 0
-#define HFO_INET6 1 << 1
-#define HFO_TCP 1 << 2
-#define HFO_ICMP 1 << 3
-#define HFO_AH 1 << 4
-
-#define _is_ipv4(format) ((format & HFO_INET))
-#define _is_ipv6(format) ((format & HFO_INET6) >> 1)
-#define _is_tcp(format) ((format & HFO_TCP) >> 2)
-#define _is_icmp(format) ((format & HFO_ICMP) >> 3)
-#define _is_ah(format) ((format & HFO_AH) >> 4)
-
-typedef enum
-{
- HF_UNSPEC = 0,
- HF_INET_TCP = HFO_INET | HFO_TCP,
- HF_INET6_TCP = HFO_INET6 | HFO_TCP,
- HF_INET_ICMP = HFO_INET | HFO_ICMP,
- HF_INET6_ICMP = HFO_INET6 | HFO_ICMP,
- HF_INET_TCP_AH = HFO_INET | HFO_TCP | HFO_AH,
- HF_INET6_TCP_AH = HFO_INET6 | HFO_TCP | HFO_AH,
- HF_INET_ICMP_AH = HFO_INET | HFO_ICMP | HFO_AH,
- HF_INET6_ICMP_AH = HFO_INET6 | HFO_ICMP | HFO_AH,
-} hicn_format_t;
-
-/**
- * Minimum required header length to determine the type and length of a
- * supposed hICN packet. This should be equal to the maximum value over all
- * possible hICN packet formats, and less than the minimum possible IP packet
- * size.
- */
-#define HICN_V6_MIN_HDR_LEN 6 /* bytes */
-#define HICN_V4_MIN_HDR_LEN 4 /* bytes */
-
-// #define HICN_MIN_HDR_LEN ((HICN_V6_MIN_HDR_LEN > HICN_V4_MIN_HDR_LEN) ?
-// HICN_V6_MIN_HDR_LEN : HICN_V4_MIN_HDR_LEN)
-#define HICN_MIN_HDR_LEN HICN_V6_MIN_HDR_LEN
-
-/**
- * @brief Parse packet headers and return hICN format
- * @param [in] format - hICN Format
- * @param [in, out] packet - Buffer containing the hICN header to be
- * initialized
- * @return hICN error code
- */
-int hicn_packet_init_header (hicn_format_t format, hicn_header_t *packet);
-
-/**
- * @brief Parse packet headers and return hICN format
- * @param [in] h - hICN header
- * @param [out] format - hICN format
- * @return hICN error code
- */
-int hicn_packet_get_format (const hicn_header_t *packet,
- hicn_format_t *format);
-
-/**
- * @brief Update checksums in packet headers
- * @param [in] format - hICN format
- * @param [in,out] packet - packet header
- * @return hICN error code
- */
-int hicn_packet_compute_checksum (hicn_format_t format, hicn_header_t *packet);
-
-/**
- * @brief compute the checksum of the packet header, adding init_sum to the
- * final value
- * @param [in] format - hICN format
- * @param [in,out] packet - packet header
- * @param [in] init_sum - value to add to the final checksum
- * @return hICN error code
- */
-int hicn_packet_compute_header_checksum (hicn_format_t format,
- hicn_header_t *packet, u16 init_sum);
-
-/**
- * @brief Verify checksums in packet headers
- * @param [in] format - hICN format
- * @param [in,out] packet - packet header
- * @return hICN error code
- */
-int hicn_packet_check_integrity_no_payload (hicn_format_t format,
- hicn_header_t *packet,
- u16 init_sum);
-
-// this is not accounted here
-/**
- * @brief Return total length of hicn headers (but signature payload)
- * @param [in] format - hICN format
- * @param [out] header_length - Total length of headers
- * @return hICN error code
- */
-int hicn_packet_get_header_length_from_format (hicn_format_t format,
- size_t *header_length);
-
-/**
- * @brief Return total length of hicn headers (before payload)
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] header_length - Total length of headers
- * @return hICN error code
- */
-int hicn_packet_get_header_length (hicn_format_t format,
- const hicn_header_t *packet,
- size_t *header_length);
-
-/**
- * @brief Return payload length
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] payload_length - payload length
- * @return hICN error code
- */
-int hicn_packet_get_payload_length (hicn_format_t format,
- const hicn_header_t *packet,
- size_t *payload_length);
-
-/**
- * @brief Sets payload length
- * @param [in] format - hICN format
- * @param [in,out] packet - packet header
- * @param [in] payload_length - payload length
- * @return hICN error code
- */
-int hicn_packet_set_payload_length (hicn_format_t format,
- hicn_header_t *packet,
- const size_t payload_length);
-
-/**
- * @brief Compare two hICN packets
- * @param [in] packet_1 - First packet
- * @param [in] packet_2 - Second packet
- * @return 0 if both packets are considered equal, any other value otherwise.
- */
-int hicn_packet_compare (const hicn_header_t *packet1,
- const hicn_header_t *packet2);
-
-/**
- * @brief Retrieve the name of an interest/data packet
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] name - name holding the result
- * @param [in] is_interest - Flag to determine whether it is an interest (1) or
- * data packet (0)
- * @return hICN error code
- */
-int hicn_packet_get_name (hicn_format_t format, const hicn_header_t *packet,
- hicn_name_t *name, u8 is_interest);
-
-/**
- * @brief Sets the name of an interest/data packet
- * @param [in] format - hICN format
- * @param [in,out] packet - packet header
- * @param [in] name - name to set into packet
- * @param [in] is_interest - Flag to determine whether it is an interest (1) or
- * data packet (0)
- * @return hICN error code
- */
-int hicn_packet_set_name (hicn_format_t format, hicn_header_t *packet,
- const hicn_name_t *name, u8 is_interest);
-
-/**
- * @brief Sets the payload of a packet
- * @param [in] format - hICN format
- * @param [in,out] packet - packet header
- * @param [in] payload - payload to set
- * @param [in] payload_length - size of the payload to set
- * @return hICN error code
- *
- * NOTE:
- * - The buffer holding payload is assumed sufficiently large
- * - This function updates header fields with the new length, but no checksum.
- */
-int hicn_packet_set_payload (hicn_format_t format, hicn_header_t *packet,
- const u8 *payload, u16 payload_length);
-
-/**
- * @brief Retrieves the payload of a packet
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] payload - pointer to buffer for storing the result
- * @param [out] payload_length - size of the retreived payload
- * @param [in] hard_copy - Flag : if true (eg. 1), a copy of the payload is
- * made into the payload buffer, otherwise (0) the pointer is changed to point
- * to the payload offset in the packet.
- * @return hICN error code
- *
- * NOTE:
- * - The buffer holding payload is assumed sufficiently large
- */
-int hicn_packet_get_payload (hicn_format_t format, const hicn_header_t *packet,
- u8 **payload, size_t *payload_size,
- bool hard_copy);
-
-/**
- * @brief Retrieve the locator of an interest / data packet
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] ip_address - retrieved locator
- * @param [in] is_interest - Flag to determine whether it is an interest (1) or
- * data packet (0)
- * @return hICN error code
- */
-int hicn_packet_get_locator (hicn_format_t format, const hicn_header_t *packet,
- ip_address_t *prefix, bool is_interest);
-
-/**
- * @brief Sets the locator of an interest / data packet
- * @param [in] format - hICN format
- * @param [in,out] packet - packet header
- * @param [out] ip_address - retrieved locator
- * @param [in] is_interest - Flag to determine whether it is an interest (1) or
- * data packet (0)
- * @return hICN error code
- */
-int hicn_packet_set_locator (hicn_format_t format, hicn_header_t *packet,
- const ip_address_t *prefix, bool is_interest);
-
-/**
- * @brief Retrieves the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] bytes - Retrieved signature size
- * @return hICN error code
- */
-int hicn_packet_get_signature_size (hicn_format_t format,
- const hicn_header_t *packet,
- size_t *bytes);
-
-/**
- * @brief Sets the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [in] bytes - Retrieved signature size
- * @return hICN error code
- */
-int hicn_packet_set_signature_size (hicn_format_t format,
- hicn_header_t *packet, size_t bytes);
-
-/**
- * @brief Sets the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [in] signature_timestamp - Signature timestamp to set
- * @return hICN error code
- */
-int hicn_packet_set_signature_timestamp (hicn_format_t format,
- hicn_header_t *h,
- uint64_t signature_timestamp);
-
-/**
- * @brief Sets the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] signature_timestamp - Retrieved signature timestamp
- * @return hICN error code
- */
-int hicn_packet_get_signature_timestamp (hicn_format_t format,
- const hicn_header_t *h,
- uint64_t *signature_timestamp);
-
-/**
- * @brief Sets the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [in] validation_algorithm - Validation algorithm to set
- * @return hICN error code
- */
-int hicn_packet_set_validation_algorithm (hicn_format_t format,
- hicn_header_t *h,
- uint8_t validation_algorithm);
-
-/**
- * @brief Sets the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] validation_algorithm - Retrieved validation algorithm
- * @return hICN error code
- */
-int hicn_packet_get_validation_algorithm (hicn_format_t format,
- const hicn_header_t *h,
- uint8_t *validation_algorithm);
-
-/**
- * @brief Sets the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [in] key_id - Key id to set
- * @return hICN error code
- */
-int hicn_packet_set_key_id (hicn_format_t format, hicn_header_t *h,
- uint8_t *key_id);
-
-/**
- * @brief Sets the signature size
- * @param [in] format - hICN format
- * @param [in] packet - packet header
- * @param [out] key_id - Retrieved key id
- * @return hICN error code
- */
-int hicn_packet_get_key_id (hicn_format_t format, hicn_header_t *h,
- uint8_t **key_id, uint8_t *key_id_length);
-
-/**
- * @brief Retrieves the packet hop limit
- * @param [in] packet - packet header
- * @param [out] hops - Retrieved hop limit
- * @return hICN error code
- */
-int hicn_packet_get_hoplimit (const hicn_header_t *packet, u8 *hops);
-
-/**
- * @brief Sets the packet hop limit
- * @param [in] packet - packet header
- * @param [in] hops - Hop limit to set
- * @return hICN error code
- */
-int hicn_packet_set_hoplimit (hicn_header_t *packet, u8 hops);
-
-int hicn_packet_copy_header (hicn_format_t format, const hicn_header_t *packet,
- hicn_header_t *destination, bool copy_ah);
-
-int hicn_packet_get_lifetime (const hicn_header_t *packet, u32 *lifetime);
-int hicn_packet_set_lifetime (hicn_header_t *packet, u32 lifetime);
-int hicn_packet_get_reserved_bits (const hicn_header_t *packet,
- u8 *reserved_bits);
-int hicn_packet_set_reserved_bits (hicn_header_t *packet,
- const u8 reserved_bits);
-int hicn_packet_get_payload_type (const hicn_header_t *packet,
- hicn_payload_type_t *payload_type);
-int hicn_packet_set_payload_type (hicn_header_t *packet,
- const hicn_payload_type_t payload_type);
-
-int hicn_packet_set_syn (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_reset_syn (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_test_syn (hicn_format_t format, const hicn_header_t *packet,
- bool *flag);
-int hicn_packet_set_ack (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_reset_ack (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_test_ack (hicn_format_t format, const hicn_header_t *packet,
- bool *flag);
-int hicn_packet_set_rst (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_reset_rst (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_test_rst (hicn_format_t format, const hicn_header_t *packet,
- bool *flag);
-int hicn_packet_set_fin (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_reset_fin (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_test_fin (hicn_format_t format, const hicn_header_t *packet,
- bool *flag);
-int hicn_packet_set_ece (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_reset_ece (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_test_ece (hicn_format_t format, const hicn_header_t *packet,
- bool *flag);
-
-int hicn_packet_set_src_port (hicn_format_t format, hicn_header_t *packet,
- u16 src_port);
-int hicn_packet_get_src_port (hicn_format_t format,
- const hicn_header_t *packet, u16 *src_port);
-int hicn_packet_set_dst_port (hicn_format_t format, hicn_header_t *packet,
- u16 dst_port);
-int hicn_packet_get_dst_port (hicn_format_t format,
- const hicn_header_t *packet, u16 *dst_port);
-int hicn_packet_get_signature (hicn_format_t format, hicn_header_t *packet,
- uint8_t **sign_buf);
-
-/* Interest */
-int hicn_interest_get_name (hicn_format_t format,
- const hicn_header_t *interest, hicn_name_t *name);
-int hicn_interest_set_name (hicn_format_t format, hicn_header_t *interest,
- const hicn_name_t *name);
-int hicn_interest_get_locator (hicn_format_t format,
- const hicn_header_t *interest,
- ip_address_t *prefix);
-int hicn_interest_set_locator (hicn_format_t format, hicn_header_t *interest,
- const ip_address_t *prefix);
-int hicn_interest_compare (const hicn_header_t *interest_1,
- const hicn_header_t *interest_2);
-int hicn_interest_set_lifetime (hicn_header_t *interest, u32 lifetime);
-int hicn_interest_get_lifetime (const hicn_header_t *interest, u32 *lifetime);
-int hicn_interest_get_header_length (hicn_format_t format,
- const hicn_header_t *interest,
- size_t *header_length);
-int hicn_interest_get_payload_length (hicn_format_t format,
- const hicn_header_t *interest,
- size_t *payload_length);
-int hicn_interest_set_payload (hicn_format_t format, hicn_header_t *interest,
- const u8 *payload, size_t payload_length);
-int hicn_interest_get_payload (hicn_format_t format,
- const hicn_header_t *interest, u8 **payload,
- size_t *payload_size, bool hard_copy);
-int hicn_interest_reset_for_hash (hicn_format_t format, hicn_header_t *packet);
-
-/* Data */
-
-int hicn_data_get_name (hicn_format_t format, const hicn_header_t *data,
- hicn_name_t *name);
-int hicn_data_set_name (hicn_format_t format, hicn_header_t *data,
- const hicn_name_t *name);
-int hicn_data_get_locator (hicn_format_t format, const hicn_header_t *data,
- ip_address_t *prefix);
-int hicn_data_set_locator (hicn_format_t format, hicn_header_t *data,
- const ip_address_t *prefix);
-int hicn_data_compare (const hicn_header_t *data_1,
- const hicn_header_t *data_2);
-int hicn_data_get_expiry_time (const hicn_header_t *data, u32 *expiry_time);
-int hicn_data_set_expiry_time (hicn_header_t *data, u32 expiry_time);
-int hicn_data_get_header_length (hicn_format_t format, hicn_header_t *data,
- size_t *header_length);
-int hicn_data_get_payload_length (hicn_format_t format,
- const hicn_header_t *data,
- size_t *payload_length);
-int hicn_data_get_path_label (const hicn_header_t *data, u32 *path_label);
-int hicn_data_set_path_label (hicn_header_t *data, u32 path_label);
-int hicn_data_get_payload (hicn_format_t format, const hicn_header_t *data,
- u8 **payload, size_t *payload_size, bool hard_copy);
-int hicn_data_set_payload (hicn_format_t format, hicn_header_t *data,
- const u8 *payload, size_t payload_length);
-int hicn_data_get_payload_type (const hicn_header_t *data,
- hicn_payload_type_t *payload_type);
-int hicn_data_set_payload_type (hicn_header_t *data,
- hicn_payload_type_t payload_type);
-int hicn_data_reset_for_hash (hicn_format_t format, hicn_header_t *packet);
-int hicn_packet_get_signature_gap (hicn_format_t format,
- const hicn_header_t *h, uint8_t *bytes);
-int hicn_packet_set_signature_gap (hicn_format_t format, hicn_header_t *h,
- uint8_t bytes);
-#endif /* HICN_COMPAT_H */
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables:
- * eval: (c-set-style "gnu")
- * End:
- */
diff --git a/lib/includes/hicn/error.h b/lib/includes/hicn/error.h
index 9303aeb7e..9926c9cd8 100644
--- a/lib/includes/hicn/error.h
+++ b/lib/includes/hicn/error.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,21 +24,22 @@
* Error definitions
******************************************************************************/
-#define foreach_libhicn_error \
-_(NONE, 0, "OK") \
-_(UNSPECIFIED, 128, "Unspecified Error") \
-_(NOT_IMPLEMENTED, 180, "Function not yet implemented") \
-_(NOT_HICN, 202, "Non hICN packet") \
-_(UNKNOWN_ADDRESS, 210, "Unknown address") \
-_(INVALID_PARAMETER, 220, "Invalid parameter") \
-_(INVALID_IP_ADDRESS, 221, "Invalid IP address") \
-_(CORRUPTED_PACKET, 222, "Corrupted packet ") \
-_(REWRITE_CKSUM_REQUIRED, 223, "Incremental csum calculation error: cksum required.") \
-_(UNEXPECTED, 298, "Unexpected error")
+#define foreach_libhicn_error \
+ _ (NONE, 0, "OK") \
+ _ (UNSPECIFIED, 128, "Unspecified Error") \
+ _ (NOT_IMPLEMENTED, 180, "Function not yet implemented") \
+ _ (NOT_HICN, 202, "Non hICN packet") \
+ _ (UNKNOWN_ADDRESS, 210, "Unknown address") \
+ _ (INVALID_PARAMETER, 220, "Invalid parameter") \
+ _ (INVALID_IP_ADDRESS, 221, "Invalid IP address") \
+ _ (CORRUPTED_PACKET, 222, "Corrupted packet ") \
+ _ (REWRITE_CKSUM_REQUIRED, 223, \
+ "Incremental csum calculation error: cksum required.") \
+ _ (UNEXPECTED, 298, "Unexpected error")
typedef enum
{
-#define _(a,b,c) HICN_LIB_ERROR_##a = (-b),
+#define _(a, b, c) HICN_LIB_ERROR_##a = (-b),
foreach_libhicn_error
#undef _
HICN_LIB_N_ERROR,
@@ -46,7 +47,9 @@ typedef enum
extern const char *HICN_LIB_ERROR_STRING[];
-#define hicn_strerror(errno) (char *)(HICN_LIB_ERROR_STRING[-errno])
+#define HICN_LIB_IS_ERROR(rc) (rc < 0)
+
+#define hicn_strerror(errno) (char *) (HICN_LIB_ERROR_STRING[-errno])
#endif /* HICN_ERROR_H */
diff --git a/lib/includes/hicn/face.h b/lib/includes/hicn/face.h
new file mode 100644
index 000000000..fbdacec5f
--- /dev/null
+++ b/lib/includes/hicn/face.h
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file face.h
+ * \brief Face abstraction
+ */
+#ifndef HICN_FACE_H
+#define HICN_FACE_H
+
+#ifndef SPACES
+#define SPACES(x) x
+#endif
+#ifndef SPACE
+#define SPACE 1
+#endif
+#ifndef NULLTERM
+#define NULLTERM 1
+#endif
+
+#include <hicn/policy.h>
+
+#include <hicn/util/ip_address.h>
+
+/* Netdevice type */
+
+#include <net/if.h> // IFNAMSIZ
+#include "base.h"
+
+#define foreach_netdevice_type \
+ _ (UNDEFINED) \
+ _ (LOOPBACK) \
+ _ (WIRED) \
+ _ (WIFI) \
+ _ (CELLULAR) \
+ _ (VPN) \
+ _ (MEMIF) \
+ _ (N)
+
+#define MAXSZ_NETDEVICE_TYPE_ 9
+#define MAXSZ_NETDEVICE_TYPE MAXSZ_NETDEVICE_TYPE_ + NULLTERM
+
+typedef enum
+{
+#define _(x) NETDEVICE_TYPE_##x,
+ foreach_netdevice_type
+#undef _
+} netdevice_type_t;
+
+typedef uint32_t netdevice_flags_t;
+#define NETDEVICE_FLAGS_EMPTY 0
+#define netdevice_flags_clear(F) (F = 0)
+#define netdevice_flags_add(F, T) ((F) |= 1 << (T))
+#define netdevice_flags_remove(F, T) ((F) &= ~(1 << (T)))
+#define netdevice_flags_has(F, T) ((F) & (1 << (T)))
+
+extern const char *_netdevice_type_str[];
+#define netdevice_type_str(x) _netdevice_type_str[x]
+
+#define INVALID_NETDEVICE_ID ~0
+
+/* Netdevice */
+
+/**
+ * \brief Netdevice type
+ *
+ * NOTE
+ * - This struct cannot be made opaque as it is currently part of face_t
+ * - We recommand using the API as to keep redundant attributes consistent
+ */
+
+typedef struct
+{
+ u32 index;
+ char name[IFNAMSIZ];
+} netdevice_t;
+
+#define NETDEVICE_EMPTY \
+ (netdevice_t) \
+ { \
+ .index = 0, .name = { 0 } \
+ }
+
+netdevice_t *netdevice_create_from_index (u32 index);
+netdevice_t *netdevice_create_from_name (const char *name);
+#define netdevice_initialize_from_index netdevice_set_index
+#define netdevice_initialize_from_name netdevice_set_name
+void netdevice_free (netdevice_t *netdevice);
+int netdevice_get_index (const netdevice_t *netdevice, u32 *index);
+int netdevice_set_index (netdevice_t *netdevice, u32 index);
+int netdevice_get_name (const netdevice_t *netdevice, const char **name);
+int netdevice_set_name (netdevice_t *netdevice, const char *name);
+int netdevice_update_index (netdevice_t *netdevice);
+int netdevice_update_name (netdevice_t *netdevice);
+int netdevice_cmp (const netdevice_t *nd1, const netdevice_t *nd2);
+bool netdevice_is_empty (const netdevice_t *netdevice);
+
+#define NETDEVICE_UNDEFINED_INDEX 0
+
+/* Face state */
+
+#define foreach_face_state \
+ _ (UNDEFINED) \
+ _ (DOWN) \
+ _ (UP) \
+ _ (N)
+
+#define MAXSZ_FACE_STATE_ 9
+#define MAXSZ_FACE_STATE MAXSZ_FACE_STATE_ + 1
+
+typedef enum
+{
+#define _(x) FACE_STATE_##x,
+ foreach_face_state
+#undef _
+} face_state_t;
+
+extern const char *_face_state_str[];
+
+#define face_state_str(x) _face_state_str[x]
+
+/* Face type */
+
+#define foreach_face_type \
+ _ (UNDEFINED) \
+ _ (HICN) \
+ _ (HICN_LISTENER) \
+ _ (TCP) \
+ _ (TCP_LISTENER) \
+ _ (UDP) \
+ _ (UDP_LISTENER) \
+ _ (N)
+
+#define MAXSZ_FACE_TYPE_ 13
+#define MAXSZ_FACE_TYPE MAXSZ_FACE_TYPE_ + 1
+
+typedef enum
+{
+#define _(x) FACE_TYPE_##x,
+ foreach_face_type
+#undef _
+} face_type_t;
+
+typedef enum
+{
+ FACE_PROTOCOL_HICN,
+ FACE_PROTOCOL_UDP,
+ FACE_PROTOCOL_TCP,
+ FACE_PROTOCOL_UNKNOWN,
+} face_protocol_t;
+
+#define face_type_is_valid(face_type) \
+ (((face_type) >= FACE_TYPE_UNDEFINED) && (face_type < FACE_TYPE_N))
+#define face_type_is_defined(face_type) \
+ (((face_type) > FACE_TYPE_UNDEFINED) && (face_type < FACE_TYPE_N))
+
+extern const char *_face_type_str[];
+#define face_type_str(x) _face_type_str[x]
+
+face_type_t face_type_from_str (const char *str);
+
+#ifdef WITH_POLICY
+#define MAXSZ_FACE_ \
+ MAXSZ_FACE_TYPE_ + 2 * MAXSZ_URL_ + 2 * MAXSZ_FACE_STATE_ + \
+ MAXSZ_POLICY_TAGS_ + 7
+#else
+#define MAXSZ_FACE_ \
+ MAXSZ_FACE_TYPE_ + 2 * MAXSZ_URL_ + 2 * MAXSZ_FACE_STATE_ + 4
+#endif /* WITH_POLICY */
+#define MAXSZ_FACE MAXSZ_FACE_ + 1
+
+/* Face */
+
+typedef u32 face_id_t;
+#define INVALID_FACE_ID ~0
+
+typedef struct
+{
+ face_id_t id;
+ char name[SYMBOLIC_NAME_LEN];
+ face_type_t type;
+ face_state_t admin_state;
+ face_state_t state;
+#ifdef WITH_POLICY
+ uint32_t priority;
+ policy_tags_t tags; /**< \see policy_tag_t */
+#endif /* WITH_POLICY */
+
+ /*
+ * Depending on the face type, some of the following fields will be unused
+ */
+ netdevice_t netdevice;
+ int family; /* To access family independently of face type */
+ hicn_ip_address_t local_addr;
+ hicn_ip_address_t remote_addr;
+ u16 local_port;
+ u16 remote_port;
+} face_t;
+
+int face_initialize (face_t *face);
+int face_initialize_udp (face_t *face, const char *interface_name,
+ const hicn_ip_address_t *local_addr, u16 local_port,
+ const hicn_ip_address_t *remote_addr, u16 remote_port,
+ int family);
+int face_initialize_udp_sa (face_t *face, const char *interface_name,
+ const struct sockaddr *local_addr,
+ const struct sockaddr *remote_addr);
+
+face_t *face_create ();
+face_t *face_create_udp (const char *interface_name,
+ const hicn_ip_address_t *local_addr, u16 local_port,
+ const hicn_ip_address_t *remote_addr, u16 remote_port,
+ int family);
+face_t *face_create_udp_sa (const char *interface_name,
+ const struct sockaddr *local_addr,
+ const struct sockaddr *remote_addr);
+
+int face_finalize (face_t *face);
+
+void face_free (face_t *face);
+
+typedef int (*face_cmp_t) (const face_t *f1, const face_t *f2);
+
+int face_cmp (const face_t *f1, const face_t *f2);
+
+size_t face_snprintf (char *s, size_t size, const face_t *face);
+
+policy_tags_t face_get_tags (const face_t *face);
+int face_set_tags (face_t *face, policy_tags_t tags);
+
+face_protocol_t get_protocol (face_type_t face_type);
+
+#endif /* HICN_FACE_H */
diff --git a/lib/includes/hicn/header.h b/lib/includes/hicn/header.h
deleted file mode 100644
index b21fe5c84..000000000
--- a/lib/includes/hicn/header.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.
- */
-
-/**
- * @file header.h
- * @brief hICN header data structures.
- *
- * NOTE: These structures are used as convenient facade for accessing
- * the encapsulated headers. They are not written taking compiler padding
- * into account, then a sizeof() on these struct could not give the expected
- * result. For accessing the size of the hicn headers use the macros at the end of
- * this file.
- */
-
-#ifndef HICN_HEADER_H
-#define HICN_HEADER_H
-
-#include "common.h"
-#include "protocol.h"
-
-typedef struct
-{
- _ipv6_header_t ip;
- union
- {
- _tcp_header_t tcp;
- _icmp_header_t icmp;
- _icmp_wldr_header_t wldr;
- };
-} hicn_v6_hdr_t;
-
-typedef struct
-{
- _ipv6_header_t ip;
- union
- {
- struct
- {
- _tcp_header_t tcp;
- _ah_header_t ah;
- };
- struct
- {
- _icmp_header_t icmp;
- _ah_header_t icmp_ah;
- };
- };
-} hicn_v6ah_hdr_t;
-
-typedef struct
-{
- _ipv4_header_t ip;
- union
- {
- _tcp_header_t tcp;
- _icmp_header_t icmp;
- _icmp_wldr_header_t wldr;
- };
-} hicn_v4_hdr_t;
-
-typedef struct
-{
- _ipv4_header_t ip;
- union
- {
- struct
- {
- _tcp_header_t tcp;
- _ah_header_t ah;
- };
- struct
- {
- _icmp_header_t icmp;
- _ah_header_t icmp_ah;
- };
- };
-} hicn_v4ah_hdr_t;
-
-typedef union
-{
- /* To deprecate as redundant with hicn_type_t */
- hicn_v6_hdr_t v6;
- hicn_v6ah_hdr_t v6ah;
- hicn_v4_hdr_t v4;
- hicn_v4ah_hdr_t v4ah;
-
- hicn_protocol_t protocol;
-} hicn_header_t;
-
-
-#define HICN_V6_TCP_HDRLEN (IPV6_HDRLEN + TCP_HDRLEN)
-#define HICN_V6_ICMP_HDRLEN (IPV6_HDRLEN + ICMP_HDRLEN)
-#define HICN_V6_WLDR_HDRLEN (IPV6_HDRLEN + ICMPWLDR_HDRLEN)
-
-#define HICN_V6_TCP_AH_HDRLEN (HICN_V6_TCP_HDRLEN + AH_HDRLEN)
-#define HICN_V6_ICMP_AH_HDRLEN (HICN_V6_ICMP_HDRLEN + AH_HDRLEN)
-
-
-#define HICN_V4_TCP_HDRLEN (IPV4_HDRLEN + TCP_HDRLEN)
-#define HICN_V4_ICMP_HDRLEN (IPV4_HDRLEN + ICMP_HDRLEN)
-#define HICN_V4_WLDR_HDRLEN (IPV4_HDRLEN + ICMPWLDR_HDRLEN)
-
-#define HICN_V4_TCP_AH_HDRLEN (HICN_V4_TCP_HDRLEN + AH_HDRLEN)
-#define HICN_V4_ICMP_AH_HDRLEN (HICN_V4_ICMP_HDRLEN + AH_HDRLEN)
-
-
-
-
-#endif /* HICN_HEADER_H */
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables:
- * eval: (c-set-style "gnu")
- * End:
- */
diff --git a/lib/includes/hicn/hicn.h b/lib/includes/hicn/hicn.h
index 749fd4247..5e67d83a0 100644
--- a/lib/includes/hicn/hicn.h
+++ b/lib/includes/hicn/hicn.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,17 +29,27 @@
* Recovery (WLDR) [2], Anchorless Mobility Management (hICN-AMM) [3],
* including MAP-Me producer mobility mechanisms [4].
*
+ * Other hICN constructs such as faces, policies and stategies are not included
+ * in this header, but available separately in :
+ * - hicn/face.h
+ * - hicn/policy.h
+ * - hicn/strategy.h
+ *
+ * REFERENCES
+ *
* [1] Hybrid Information-Centric Networking
* L. Muscariello, G. Carofiglio, J. Augé, M. Papalini
- * IETF draft (intarea) @ https://tools.ietf.org/html/draft-muscariello-intarea-hicn
+ * IETF draft (intarea) @
+ * https://tools.ietf.org/html/draft-muscariello-intarea-hicn
*
- * [2] Leveraging ICN in-network control for loss detection and recovery in wireless mobile networks
- * G. Carofiglio, L. Muscariello, M. Papalini, N. Rozhnova, X. Zeng
- * In proc. ICN'2016, Kyoto, JP
+ * [2] Leveraging ICN in-network control for loss detection and recovery in
+ * wireless mobile networks G. Carofiglio, L. Muscariello, M. Papalini, N.
+ * Rozhnova, X. Zeng In proc. ICN'2016, Kyoto, JP
*
* [3] Anchorless mobility through hICN
* J. Augé, G. Carofiglio, L. Muscariello, M. Papalini
- * IETF draft (DMM) @ https://tools.ietf.org/html/draft-auge-dmm-hicn-mobility
+ * IETF draft (DMM) @
+ * https://tools.ietf.org/html/draft-auge-dmm-hicn-mobility
*
*
* [4] MAP-Me : Managing Anchorless Mobility in Content Centric Networking
@@ -50,22 +60,21 @@
#ifndef HICN__H
#define HICN__H
-#ifdef HICN_VPP_PLUGIN
+/* Base data structures */
+#include <hicn/base.h>
-#include <hicn/header.h>
+/* Names */
#include <hicn/name.h>
-#include <hicn/ops.h>
-#include <hicn/mapme.h>
-#else
+/* Packet operations */
+#include <hicn/packet.h>
-#include <hicn/error.h>
-#include <hicn/header.h>
-#include <hicn/name.h>
-#include <hicn/ops.h>
+/* MAP-Me : mobility management operations */
#include <hicn/mapme.h>
-#include <hicn/compat.h>
+/* Error management */
+#ifndef HICN_VPP_PLUGIN
+#include <hicn/error.h>
#endif
#endif /* HICN__H */
diff --git a/lib/includes/hicn/interest_manifest.h b/lib/includes/hicn/interest_manifest.h
new file mode 100644
index 000000000..b6122ce1c
--- /dev/null
+++ b/lib/includes/hicn/interest_manifest.h
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HICNLIGHT_INTEREST_MANIFEST_H
+#define HICNLIGHT_INTEREST_MANIFEST_H
+
+#include <string.h>
+#include <stdbool.h>
+
+#include <hicn/util/bitmap.h>
+#include <hicn/base.h>
+#include <hicn/name.h>
+#include <hicn/common.h>
+
+typedef enum
+{
+ INT_MANIFEST_SPLIT_STRATEGY_NONE,
+ INT_MANIFEST_SPLIT_STRATEGY_MAX_N_SUFFIXES,
+ INT_MANIFEST_SPLIT_N_STRATEGIES,
+} int_manifest_split_strategy_t;
+
+#define MAX_SUFFIXES_IN_MANIFEST 256
+
+#define DEFAULT_DISAGGREGATION_STRATEGY \
+ INT_MANIFEST_SPLIT_STRATEGY_MAX_N_SUFFIXES
+#define DEFAULT_N_SUFFIXES_PER_SPLIT MAX_SUFFIXES_IN_MANIFEST
+
+#define BITMAP_SIZE (MAX_SUFFIXES_IN_MANIFEST / WORD_WIDTH)
+
+typedef struct
+{
+ /* This can be 16 bits, but we use 32 bits for alignment */
+ uint32_t n_suffixes;
+
+ /* First suffix */
+ uint32_t padding;
+
+ hicn_uword request_bitmap[BITMAP_SIZE];
+
+ /* Followed by the list of prefixes to ask */
+ /* ... */
+} interest_manifest_header_t;
+
+static_assert (sizeof (interest_manifest_header_t) == 32 + 4 + 4,
+ "interest_manifest_header_t size must be exactly 40 bytes");
+
+#define _interest_manifest_serialize_deserialize(manifest, first, second, \
+ size, serialize) \
+ do \
+ { \
+ u32 n_suffixes = 0; \
+ if (serialize) \
+ n_suffixes = int_manifest_header->n_suffixes; \
+ \
+ int_manifest_header->n_suffixes = \
+ hicn_##first##_to_##second##_32 (int_manifest_header->n_suffixes); \
+ int_manifest_header->padding = \
+ hicn_##first##_to_##second##_32 (int_manifest_header->padding); \
+ \
+ for (unsigned i = 0; i < BITMAP_SIZE; i++) \
+ { \
+ int_manifest_header->request_bitmap[i] = \
+ hicn_##first##_to_##second##_##size ( \
+ int_manifest_header->request_bitmap[i]); \
+ } \
+ \
+ hicn_name_suffix_t *suffix = \
+ (hicn_name_suffix_t *) (int_manifest_header + 1); \
+ if (!serialize) \
+ n_suffixes = int_manifest_header->n_suffixes; \
+ for (unsigned i = 0; i < n_suffixes; i++) \
+ { \
+ *(suffix + i) = hicn_##first##_to_##second##_32 (*(suffix + i)); \
+ } \
+ } \
+ while (0)
+
+#define _interest_manifest_serialize(manifest, size) \
+ _interest_manifest_serialize_deserialize (manifest, host, net, size, 1)
+
+#define _interest_manifest_deserialize(manifest, size) \
+ _interest_manifest_serialize_deserialize (manifest, net, host, size, 0)
+
+static inline void
+interest_manifest_serialize (interest_manifest_header_t *int_manifest_header)
+{
+ _interest_manifest_serialize (int_manifest_header, hicn_uword_bits);
+}
+
+static inline void
+interest_manifest_deserialize (interest_manifest_header_t *int_manifest_header)
+{
+ u32 n_suffixes = 0;
+
+ int_manifest_header->n_suffixes =
+ hicn_net_to_host_32 (int_manifest_header->n_suffixes);
+ int_manifest_header->padding =
+ hicn_net_to_host_32 (int_manifest_header->padding);
+
+ for (unsigned i = 0; i < BITMAP_SIZE; i++)
+ {
+ int_manifest_header->request_bitmap[i] =
+ hicn_net_to_host_64 (int_manifest_header->request_bitmap[i]);
+ }
+
+ hicn_name_suffix_t *suffix =
+ (hicn_name_suffix_t *) (int_manifest_header + 1);
+
+ n_suffixes = int_manifest_header->n_suffixes;
+ for (unsigned i = 0; i < n_suffixes; i++)
+ {
+ *(suffix + i) = hicn_net_to_host_32 (*(suffix + i));
+ }
+}
+
+static inline bool
+interest_manifest_is_valid (interest_manifest_header_t *int_manifest_header,
+ size_t payload_length)
+{
+ if (int_manifest_header->n_suffixes == 0 ||
+ int_manifest_header->n_suffixes > MAX_SUFFIXES_IN_MANIFEST)
+ {
+ return false;
+ }
+
+ hicn_uword empty_bitmap[BITMAP_SIZE] = { 0 };
+ if (memcmp (empty_bitmap, int_manifest_header->request_bitmap,
+ sizeof (empty_bitmap)) == 0)
+ {
+ return false;
+ }
+
+ if (payload_length - sizeof (interest_manifest_header_t) !=
+ int_manifest_header->n_suffixes * sizeof (u32))
+ {
+ return false;
+ }
+
+ return true;
+}
+
+static inline void
+interest_manifest_add_suffix (interest_manifest_header_t *int_manifest_header,
+ hicn_name_suffix_t suffix)
+{
+ hicn_name_suffix_t *start = (hicn_name_suffix_t *) (int_manifest_header + 1);
+ *(start + int_manifest_header->n_suffixes) = suffix;
+ hicn_uword *request_bitmap = int_manifest_header->request_bitmap;
+ bitmap_set_no_check (request_bitmap, int_manifest_header->n_suffixes);
+ int_manifest_header->n_suffixes++;
+}
+
+static inline void
+interest_manifest_init (interest_manifest_header_t *int_manifest_header,
+ u32 fist_suffix)
+{
+ int_manifest_header->n_suffixes = 0;
+ int_manifest_header->padding = 0;
+ memset (int_manifest_header->request_bitmap, 0,
+ sizeof (int_manifest_header->request_bitmap));
+
+ interest_manifest_add_suffix (int_manifest_header, fist_suffix);
+}
+
+static inline void
+interest_manifest_del_suffix (interest_manifest_header_t *int_manifest_header,
+ hicn_uword pos)
+{
+ bitmap_unset_no_check (int_manifest_header->request_bitmap, pos);
+}
+
+static inline size_t
+interest_manifest_update_bitmap (const hicn_uword *initial_bitmap,
+ hicn_uword *bitmap_to_update, size_t start,
+ size_t n, size_t max_suffixes)
+{
+ size_t i = start, n_ones = 0;
+ while (i < n)
+ {
+ if (bitmap_is_set_no_check (initial_bitmap, i))
+ {
+ bitmap_set_no_check (bitmap_to_update, i);
+ n_ones++;
+ }
+ i++;
+
+ if (n_ones == max_suffixes)
+ break;
+ }
+
+ return i;
+}
+
+#define _FIRST(h) (hicn_name_suffix_t *) (h + 1)
+
+#define interest_manifest_foreach_suffix(header, suffix, pos) \
+ for (suffix = _FIRST (header) + bitmap_first_set_no_check ( \
+ header->request_bitmap, BITMAP_SIZE), \
+ pos = 0; \
+ suffix - _FIRST (header) < header->n_suffixes; \
+ pos = suffix - _FIRST (header) + 1, \
+ suffix = _FIRST (header) + \
+ bitmap_next_set_no_check (header->request_bitmap, \
+ suffix - _FIRST (header) + 1, \
+ BITMAP_SIZE), \
+ pos = suffix - _FIRST (header))
+
+#endif /* HICNLIGHT_INTEREST_MANIFEST_H */
diff --git a/lib/includes/hicn/mapme.h b/lib/includes/hicn/mapme.h
index 8fae44530..b452a5dde 100644
--- a/lib/includes/hicn/mapme.h
+++ b/lib/includes/hicn/mapme.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,28 +20,28 @@
#ifndef HICN_MAPME_H
#define HICN_MAPME_H
-#include <stdint.h> // u32
+#include <stdint.h> // u32
#include <stdbool.h>
+#include <hicn/name.h>
+
#include "common.h"
-#include "protocol.h"
-#include "ops.h"
/**
* @brief MAP-Me configuration options
*/
typedef struct
{
- /** MAP-Me enabled flag (default: false) */
+ /** MAP-Me enabled flag (default: false) */
bool enabled;
- /** timescale (T_U parameter) in ms (default: 0 for no notifications) */
+ /** timescale (T_U parameter) in ms (default: 0 for no notifications) */
u32 timescale;
- /** retransmission timer in ms (default: 50) */
+ /** retransmission timer in ms (default: 50) */
u32 retx;
- /**
- * Discovery enabled flag (default: true, should be true if mandatory is
- * notifications are enabled)
- */
+ /**
+ * Discovery enabled flag (default: true, should be true if mandatory is
+ * notifications are enabled)
+ */
bool discovery;
} hicn_mapme_conf_t;
@@ -74,83 +74,51 @@ typedef struct
seq_t seq;
} mapme_params_t;
-
/* MAP-Me API */
-size_t hicn_mapme_create_packet (u8 * buf, const hicn_prefix_t * prefix,
- const mapme_params_t * params);
-size_t hicn_mapme_create_ack (u8 * buf, const mapme_params_t * params);
-int hicn_mapme_parse_packet (const u8 * packet, hicn_prefix_t * prefix,
- mapme_params_t * params);
+size_t hicn_mapme_create_packet (u8 *buf, const hicn_prefix_t *prefix,
+ const mapme_params_t *params);
+size_t hicn_mapme_create_ack (u8 *buf, const mapme_params_t *params);
+int hicn_mapme_parse_packet (const u8 *packet, hicn_prefix_t *prefix,
+ mapme_params_t *params);
/* Implementation & parsing : ICMP Redirect */
#define HICN_MAPME_ACK_FLAG (0x20 | 0x60)
-#define HICN_MAPME_ICMP_TYPE_IPV4 5
-#define HICN_MAPME_ICMP_TYPE_IPV6 137
-#define HICN_MAPME_ICMP_TYPE_ACK_IPV4 (HICN_MAPME_ICMP_TYPE_IPV4 | HICN_MAPME_ACK_FLAG)
-#define HICN_MAPME_ICMP_TYPE_ACK_IPV6 (HICN_MAPME_ICMP_TYPE_IPV6 | HICN_MAPME_ACK_FLAG)
-#define HICN_MAPME_ICMP_CODE 0 /* Redirect Datagrams for the Network (or subnet) */
-
-#define HICN_MAPME_TYPE_IS_IU(type) ((type == HICN_MAPME_ICMP_TYPE_IPV4) || (type == HICN_MAPME_ICMP_TYPE_IPV6))
-#define HICN_MAPME_TYPE_IS_IU_ACK(type) ((type == HICN_MAPME_ICMP_TYPE_ACK_IPV4) || (type == HICN_MAPME_ICMP_TYPE_ACK_IPV6))
-
-#define HICN_MAPME_IS_IU(type, code) (HICN_MAPME_TYPE_IS_IU(type) && (code == HICN_MAPME_ICMP_CODE))
-#define HICN_MAPME_IS_ACK(type, code) (HICN_MAPME_TYPE_IS_IU_ACK(type) && (code == HICN_MAPME_ICMP_CODE))
-
-#define HICN_IS_MAPME(type, code) (HICN_MAPME_IS_IU(type, code) || HICN_MAPME_IS_ACK(type, code))
+#define HICN_MAPME_ICMP_TYPE_IPV4 5
+#define HICN_MAPME_ICMP_TYPE_IPV6 137
+#define HICN_MAPME_ICMP_TYPE_ACK_IPV4 \
+ (HICN_MAPME_ICMP_TYPE_IPV4 | HICN_MAPME_ACK_FLAG)
+#define HICN_MAPME_ICMP_TYPE_ACK_IPV6 \
+ (HICN_MAPME_ICMP_TYPE_IPV6 | HICN_MAPME_ACK_FLAG)
+#define HICN_MAPME_ICMP_CODE \
+ 0 /* Redirect Datagrams for the Network (or subnet) */
+
+#define HICN_MAPME_TYPE_IS_IU(type) \
+ ((type == HICN_MAPME_ICMP_TYPE_IPV4) || (type == HICN_MAPME_ICMP_TYPE_IPV6))
+#define HICN_MAPME_TYPE_IS_IU_ACK(type) \
+ ((type == HICN_MAPME_ICMP_TYPE_ACK_IPV4) || \
+ (type == HICN_MAPME_ICMP_TYPE_ACK_IPV6))
+
+#define HICN_MAPME_IS_IU(type, code) \
+ (HICN_MAPME_TYPE_IS_IU (type) && (code == HICN_MAPME_ICMP_CODE))
+#define HICN_MAPME_IS_ACK(type, code) \
+ (HICN_MAPME_TYPE_IS_IU_ACK (type) && (code == HICN_MAPME_ICMP_CODE))
+
+#define HICN_IS_MAPME(type, code) \
+ (HICN_MAPME_IS_IU (type, code) || HICN_MAPME_IS_ACK (type, code))
/* Fast check for ACK flag */
#define HICN_MAPME_IS_ACK_FAST(icmp_type) (icmp_type & HICN_MAPME_ACK_FLAG)
/* Default TTL */
-#define HICN_MAPME_TTL 255 // typical for redirect (ref?)
-
-/*
- * The length of the MAPME4 header struct must be 120 bytes.
- */
-#define EXPECTED_MAPME_V4_HDRLEN 120
+#define HICN_MAPME_TTL 255 // typical for redirect (ref?)
-/** @brief MAP-Me packet header for IPv4 */
-typedef struct
-{
- _ipv4_header_t ip;
- _icmprd4_header_t icmp_rd;
- seq_t seq;
- u8 len;
- u8 _pad[3];
-} hicn_mapme_v4_header_t;
+/* Should be moved to mapme.c, but header size still in use in VPP */
-/*
- * The length of the MAPME4 header struct must be bytes.
- */
+#define EXPECTED_MAPME_V4_HDRLEN 120
#define EXPECTED_MAPME_V6_HDRLEN 88
-/** @brief MAP-Me packet header for IPv6 */
-typedef struct
-{
- _ipv6_header_t ip;
- _icmprd_header_t icmp_rd;
- seq_t seq;
- u8 len;
- u8 _pad[3];
-} hicn_mapme_v6_header_t;
-
-/** @brief MAP-Me packet header (IP version agnostic) */
-typedef union
-{
- hicn_mapme_v4_header_t v4;
- hicn_mapme_v6_header_t v6;
-} hicn_mapme_header_t;
-
-#define HICN_MAPME_V4_HDRLEN sizeof(hicn_mapme_v4_header_t)
-#define HICN_MAPME_V6_HDRLEN sizeof(hicn_mapme_v6_header_t)
-
-static_assert (EXPECTED_MAPME_V4_HDRLEN == HICN_MAPME_V4_HDRLEN,
- "Size of MAPME_V4 struct does not match its expected size.");
-static_assert (EXPECTED_MAPME_V6_HDRLEN == HICN_MAPME_V6_HDRLEN,
- "Size of MAPME_V6 struct does not match its expected size.");
-
#endif /* HICN_MAPME_H */
/*
diff --git a/lib/includes/hicn/name.h b/lib/includes/hicn/name.h
index d5202068b..a4e8e02ad 100644
--- a/lib/includes/hicn/name.h
+++ b/lib/includes/hicn/name.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,119 +24,109 @@
#ifndef HICN_NAME_H
#define HICN_NAME_H
+#include <assert.h>
#include <stdbool.h>
+#include <stddef.h>
#ifndef _WIN32
-#include <netinet/in.h> // struct sockadd
+#include <netinet/in.h> // struct sockadd
#endif
+#include <hicn/common.h>
#include <hicn/util/ip_address.h>
-#include "common.h"
/******************************************************************************
* hICN names
******************************************************************************/
-#define TCP_SEQNO_LEN 4 /* bytes */
+#define TCP_SEQNO_LEN 4 /* bytes */
#define HICN_V4_PREFIX_LEN IPV4_ADDR_LEN
#define HICN_V6_PREFIX_LEN IPV6_ADDR_LEN
+
+#if 0
#define HICN_SEGMENT_LEN TCP_SEQNO_LEN
-#define HICN_V6_NAME_LEN (HICN_V6_PREFIX_LEN + HICN_SEGMENT_LEN) /* 20 bytes */
-#define HICN_V4_NAME_LEN (HICN_V4_PREFIX_LEN + HICN_SEGMENT_LEN) /* 8 bytes */
+
+#define HICN_V6_NAME_LEN \
+ (HICN_V6_PREFIX_LEN + HICN_SEGMENT_LEN) /* 20 bytes \
+ */
+#define HICN_V4_NAME_LEN \
+ (HICN_V4_PREFIX_LEN + HICN_SEGMENT_LEN) /* 8 bytes \
+ */
+#endif
+
+#define HICN_INVALID_SUFFIX ((uint32_t) (~0))
/* Prefix */
-typedef u32 hicn_name_suffix_t;
+#define HICN_PREFIX_MAX_LEN IP_ADDRESS_MAX_LEN
typedef struct
{
- ip46_address_t name;
+ hicn_ip_address_t name;
u8 len;
} hicn_prefix_t;
+#define HICN_PREFIX_EMPTY \
+ (hicn_prefix_t) { .name = IP_ADDRESS_EMPTY, .len = 0 }
+
+static inline const hicn_ip_address_t *
+hicn_prefix_get_ip_address (const hicn_prefix_t *prefix)
+{
+ return &prefix->name;
+}
+
+static inline u8
+hicn_prefix_get_len (const hicn_prefix_t *prefix)
+{
+ return prefix->len;
+}
+
+int hicn_prefix_get_ip_prefix (const hicn_prefix_t *prefix,
+ hicn_ip_prefix_t *ip_prefix);
/*
* Name
*
* A name is a prefix + a segment name (suffix)
*/
-typedef union
-{
- struct
- {
- union
- {
- u32 prefix;
- u8 prefix_as_u8[4];
- ip4_address_t prefix_as_ip4;
- };
- hicn_name_suffix_t suffix;
- };
- u8 buffer[HICN_V4_NAME_LEN];
-} hicn_v4_name_t;
-
-typedef union
-{
- struct
- {
- union
- {
- u64 prefix[2];
- u8 prefix_as_u8[16];
- ip6_address_t prefix_as_ip6;
- };
- hicn_name_suffix_t suffix;
- };
- u8 buffer[HICN_V6_NAME_LEN];
-} hicn_v6_name_t;
-
-#ifndef HICN_VPP_PLUGIN
-#define HICN_NAME_COMPONENT_SIZE 2
+typedef hicn_ip_address_t hicn_name_prefix_t;
+typedef uint32_t hicn_name_suffix_t;
+
+#define hicn_name_prefix_cmp hicn_ip_address_cmp
+#define hicn_name_prefix_equals hicn_ip_address_equals
+#define hicn_name_prefix_get_len_bits hicn_ip_address_get_len_bits
+#define hicn_name_prefix_get_hash hicn_ip_address_get_hash
+#define hicn_name_prefix_snprintf hicn_ip_address_snprintf
+#define HICN_NAME_PREFIX_EMPTY IP_ADDRESS_EMPTY
typedef struct
{
- struct iovec buffers[HICN_NAME_COMPONENT_SIZE];
-} hicn_iov_name_t;
+ hicn_name_prefix_t prefix;
+ hicn_name_suffix_t suffix;
+} hicn_name_t;
-#define UNSPEC 1 << 0
-#define HNT_CONTIGUOUS 1 << 1
-#define HNT_IOV 1 << 2
-#define HNT_INET 1 << 3
-#define HNT_INET6 1 << 4
+static_assert (offsetof (hicn_name_t, prefix) == 0, "");
+static_assert (offsetof (hicn_name_t, suffix) == 16, "");
+static_assert (sizeof (hicn_name_t) == 20, "");
-typedef enum
+#define HICN_NAME_EMPTY \
+ (hicn_name_t) { .prefix = HICN_NAME_PREFIX_EMPTY, .suffix = 0, }
+
+static inline const hicn_name_prefix_t *
+hicn_name_get_prefix (const hicn_name_t *name)
{
- HNT_UNSPEC = UNSPEC,
- HNT_CONTIGUOUS_V4 = HNT_CONTIGUOUS | HNT_INET,
- HNT_CONTIGUOUS_V6 = HNT_CONTIGUOUS | HNT_INET6,
- HNT_IOV_V4 = HNT_IOV | HNT_INET,
- HNT_IOV_V6 = HNT_IOV | HNT_INET6,
-} hicn_name_type_t;
-#endif /* HICN_VPP_PLUGIN */
+ return &name->prefix;
+}
-typedef struct
+static inline const hicn_name_suffix_t
+hicn_name_get_suffix (const hicn_name_t *name)
{
-#ifndef HICN_VPP_PLUGIN
- hicn_name_type_t type;
- u8 len;
-#endif /* HICN_VPP_PLUGIN */
- union
- {
- hicn_v4_name_t ip4;
- hicn_v6_name_t ip6;
- ip46_address_t ip46;
-#ifndef HICN_VPP_PLUGIN
- hicn_iov_name_t iov;
- u8 buffer[HICN_V6_NAME_LEN];
-#endif /* HICN_VPP_PLUGIN */
- };
-} hicn_name_t;
+ return name->suffix;
+}
-#ifndef HICN_VPP_PLUGIN
-#define _is_unspec(name) ((name->type & UNSPEC))
-#define _is_contiguous(name) ((name->type & HNT_CONTIGUOUS) >> 1)
-#define _is_iov(name) ((name->type & HNT_IOV) >> 2)
-#define _is_inet4(name) ((name->type & HNT_INET) >> 3)
-#define _is_inet6(name) ((name->type & HNT_INET6) >> 4)
-#endif /* HICN_VPP_PLUGIN */
+#define _is_unspec(name) \
+ (((name)->prefix.pad[0] | (name)->prefix.pad[1] | (name)->prefix.pad[2] | \
+ (name)->prefix.v4.as_u32) == 0)
+#define _is_inet4(name) (hicn_ip_address_is_v4 (&name->prefix))
+#define _is_inet6(name) (!_is_inet4 (name))
/**
* @brief Create an hICN name from IP address in presentation format
@@ -145,37 +135,40 @@ typedef struct
* @param [out] Resulting hICN name
* @return hICN error code
*/
-int hicn_name_create (const char *ip_address, u32 id, hicn_name_t * name);
+int hicn_name_create (const char *ip_address, u32 id, hicn_name_t *name);
/**
* @brief Create an hICN name from IP address
* @param [in] ip_address - IP address
- * @param [in] id Segment - identifier
+ * @param [in] suffix - Name suffix
* @param [out] Resulting - hICN name
* @return hICN error code
*/
-int hicn_name_create_from_ip_prefix (const ip_prefix_t * prefix, u32 id,
- hicn_name_t * name);
+int hicn_name_create_from_ip_address (const hicn_ip_address_t ip_address,
+ u32 suffix, hicn_name_t *name);
/**
- * @brief Returns the length of an hICN name
- * @param [in] name - hICN name
- * @return Name length
+ * @brief Create an hICN name from IP prefix
+ * @param [in] prefix - IP prefix
+ * @param [in] suffix - Name suffix
+ * @param [out] Resulting - hICN name
+ * @return hICN error code
*/
-u8 hicn_name_get_length (const hicn_name_t * name);
+int hicn_name_create_from_ip_prefix (const hicn_ip_prefix_t *prefix, u32 id,
+ hicn_name_t *name);
/**
* @brief Compare two hICN names
* @param [in] name_1 - First name to compare
* @param [in] name_2 - Second name to compare
- * @param [in] consider_segment - Flag indicating whether the segment part has to be
- * considered
+ * @param [in] consider_segment - Flag indicating whether the segment part has
+ * to be considered
* @return An integer less than, equal to, or greater than zero if name_1 is
* found, respectively, to be lest than, to match, or be greater than name_2
* based on numeric order.
*/
-int hicn_name_compare (const hicn_name_t * name_1, const hicn_name_t * name_2,
- bool consider_segment);
+int hicn_name_compare (const hicn_name_t *name_1, const hicn_name_t *name_2,
+ bool consider_segment);
/**
* @brief Provides a 32-bit hash of an hICN name
@@ -184,7 +177,10 @@ int hicn_name_compare (const hicn_name_t * name_1, const hicn_name_t * name_2,
* @param [in] consider_suffix - Consider the suffix in the hash computation
* @return hICN error code
*/
-int hicn_name_hash (const hicn_name_t * name, u32 * hash, bool consider_suffix);
+uint32_t _hicn_name_get_hash (const hicn_name_t *name, bool consider_suffix);
+
+#define hicn_name_get_hash(NAME) _hicn_name_get_hash (NAME, true)
+#define hicn_name_get_prefix_hash(NAME) _hicn_name_get_hash (NAME, false)
/**
* @brief Test whether an hICN name is empty
@@ -192,7 +188,7 @@ int hicn_name_hash (const hicn_name_t * name, u32 * hash, bool consider_suffix);
* @return 0 if the name is empty, any other value otherwise (implementation
* returns 1)
*/
-int hicn_name_empty (hicn_name_t * name);
+int hicn_name_empty (hicn_name_t *name);
/**
* @brief Copy an hICN name
@@ -200,7 +196,7 @@ int hicn_name_empty (hicn_name_t * name);
* @param [in] src - Source name to copy
* @return hICN error code
*/
-int hicn_name_copy (hicn_name_t * dst, const hicn_name_t * src);
+int hicn_name_copy (hicn_name_t *dst, const hicn_name_t *src);
/**
* @brief Copy an hICN name to a buffer
@@ -209,8 +205,7 @@ int hicn_name_copy (hicn_name_t * dst, const hicn_name_t * src);
* @param [in] copy_suffix - Flag indicating whether the suffix has to be
* considered
*/
-int hicn_name_copy_to_destination (u8 * dst, const hicn_name_t * src,
- bool copy_suffix);
+int hicn_name_copy_prefix_to_destination (u8 *dst, const hicn_name_t *src);
/**
* @brief Sets the segment part of an hICN name
@@ -218,7 +213,7 @@ int hicn_name_copy_to_destination (u8 * dst, const hicn_name_t * src,
* @param [in] seq_number - Segment identifier
* @return hICN error code
*/
-int hicn_name_set_seq_number (hicn_name_t * name, u32 seq_number);
+int hicn_name_set_suffix (hicn_name_t *name, hicn_name_suffix_t suffix);
/**
* @brief Retrieves the segment part of an hICN name
@@ -226,7 +221,7 @@ int hicn_name_set_seq_number (hicn_name_t * name, u32 seq_number);
* @param [in] seq_number - Segment identifier
* @return hICN error code
*/
-int hicn_name_get_seq_number (const hicn_name_t * name, u32 * seq_number);
+int hicn_name_get_seq_number (const hicn_name_t *name, u32 *seq_number);
/**
* @brief Convert an hICN name to a socket address
@@ -234,8 +229,8 @@ int hicn_name_get_seq_number (const hicn_name_t * name, u32 * seq_number);
* @param [out] ip_address - Resulting socket address
* @return hICN error code
*/
-int hicn_name_to_sockaddr_address (const hicn_name_t * name,
- struct sockaddr *ip_address);
+int hicn_name_to_sockaddr_address (const hicn_name_t *name,
+ struct sockaddr *ip_address);
/**
* @brief Convert an hICN name to an IP address
@@ -243,8 +238,8 @@ int hicn_name_to_sockaddr_address (const hicn_name_t * name,
* @param [out] ip_address - Resulting IP address
* @return hICN error code
*/
-int hicn_name_to_ip_prefix (const hicn_name_t * name,
- ip_prefix_t * ip_prefix);
+int hicn_name_to_hicn_ip_prefix (const hicn_name_t *name,
+ hicn_ip_prefix_t *hicn_ip_prefix);
/**
* @brief Convert an hICN name to presentation format
@@ -253,7 +248,7 @@ int hicn_name_to_ip_prefix (const hicn_name_t * name,
* @param [in] len - Number of bytes available in the buffer
* @return hICN error code
*/
-int hicn_name_ntop (const hicn_name_t * src, char *dst, size_t len);
+int hicn_name_ntop (const hicn_name_t *src, char *dst, size_t len);
/**
* @brief Convert an hICN name from presentation format
@@ -261,7 +256,7 @@ int hicn_name_ntop (const hicn_name_t * src, char *dst, size_t len);
* @param [out] dst - Resulting name
* @return hICN error code
*/
-int hicn_name_pton (const char *src, hicn_name_t * dst);
+int hicn_name_pton (const char *src, hicn_name_t *dst);
/**
* @brief Returns the IP address family of an hICN name
@@ -269,7 +264,19 @@ int hicn_name_pton (const char *src, hicn_name_t * dst);
* @param [out] family - Resulting IP address family (AF_INET or AF_INET6)
* @return hICN error code
*/
-int hicn_name_get_family (const hicn_name_t * name, int *family);
+int hicn_name_get_family (const hicn_name_t *name, int *family);
+
+bool hicn_name_is_v4 (const hicn_name_t *name);
+
+int hicn_name_snprintf (char *s, size_t size, const hicn_name_t *name);
+
+int hicn_name_no_suffix_snprintf (char *s, size_t size,
+ const hicn_name_t *name);
+
+int hicn_name_cmp (const hicn_name_t *n1, const hicn_name_t *n2);
+bool hicn_name_equals (const hicn_name_t *n1, const hicn_name_t *n2);
+
+#define MAXSZ_HICN_NAME MAXSZ_IP_ADDRESS
/**
* @brief Creates an hICN prefix from an IP address
@@ -277,8 +284,35 @@ int hicn_name_get_family (const hicn_name_t * name, int *family);
* @param [out] prefix - Resulting prefix
* @return hICN error code
*/
-int hicn_prefix_create_from_ip_prefix (const ip_prefix_t * ip_prefix,
- hicn_prefix_t * prefix);
+int hicn_prefix_create_from_ip_prefix (const hicn_ip_prefix_t *hicn_ip_prefix,
+ hicn_prefix_t *prefix);
+
+int
+hicn_prefix_create_from_ip_address_len (const hicn_ip_address_t *ip_address,
+ uint8_t len, hicn_prefix_t *prefix);
+
+hicn_prefix_t *hicn_prefix_dup (const hicn_prefix_t *prefix);
+
+int hicn_prefix_copy (hicn_prefix_t *dst, const hicn_prefix_t *src);
+
+bool hicn_prefix_is_v4 (const hicn_prefix_t *prefix);
+
+uint32_t hicn_prefix_lpm (const hicn_prefix_t *p1, const hicn_prefix_t *p2);
+
+void hicn_prefix_clear (hicn_prefix_t *prefix, uint8_t start_from);
+
+void hicn_prefix_truncate (hicn_prefix_t *prefix, uint8_t len);
+
+int hicn_prefix_cmp (const hicn_prefix_t *p1, const hicn_prefix_t *p2);
+
+bool hicn_prefix_equals (const hicn_prefix_t *p1, const hicn_prefix_t *p2);
+
+int hicn_prefix_snprintf (char *s, size_t size, const hicn_prefix_t *prefix);
+
+uint8_t _hicn_prefix_get_bit (const hicn_prefix_t *prefix, uint8_t pos);
+uint8_t hicn_prefix_get_bit (const hicn_prefix_t *prefix, uint8_t pos);
+
+#define MAXSZ_HICN_PREFIX MAXSZ_IP_PREFIX
#endif /* HICN_NAME_H */
diff --git a/lib/includes/hicn/ops.h b/lib/includes/hicn/ops.h
deleted file mode 100644
index e5b1c088c..000000000
--- a/lib/includes/hicn/ops.h
+++ /dev/null
@@ -1,871 +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.
- */
-
-/**
- * @file base.h
- * @brief Protocol-independent packet operations
- */
-
-#ifndef HICN_OPS_H
-#define HICN_OPS_H
-
-#include <stdlib.h>
-
-#include "error.h"
-#include "header.h"
-#include "name.h"
-
-/*
- * hICN operations on packets
- *
- * All prototypes take an hicn_type_t parameter as their first argument, as
- * this decides the sequence of protocols that are being used by the different
- * operations.
- */
-
-typedef struct hicn_ops_s
-{
- /**
- * @brief Initialize the headers of the hicn packet
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the packet
- */
- int (*init_packet_header) (hicn_type_t type, hicn_protocol_t *h);
-
- /**
- * @brief Retrieves an Interest locator
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Interest packet
- * @param [out] ip_address - Retrieved locator
- * @return hICN error code
- */
- int (*get_interest_locator) (hicn_type_t type, const hicn_protocol_t *h,
- ip46_address_t *ip_address);
-
- /**
- * @brief Sets an Interest locator
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest packet
- * @param [in] ip_address - Locator to set
- * @return hICN error code
- */
- int (*set_interest_locator) (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *ip_address);
-
- /**
- * @brief Retrieves an Interest name
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Interest packet
- * @param [out] name - Retrieved name
- * @return hICN error code
- */
- int (*get_interest_name) (hicn_type_t type, const hicn_protocol_t *h,
- hicn_name_t *name);
-
- /**
- * @brief Sets an Interest name
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest packet
- * @param [in] name - Name to set
- * @return hICN error code
- */
- int (*set_interest_name) (hicn_type_t type, hicn_protocol_t *h,
- const hicn_name_t *name);
-
- /**
- * @brief Retrieves an Interest name suffix
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Interest packet
- * @param [out] suffix - Retrieved name suffix
- * @return hICN error code
- */
- int (*get_interest_name_suffix) (hicn_type_t type, const hicn_protocol_t *h,
- hicn_name_suffix_t *suffix);
-
- /**
- * @brief Sets an Interest name suffix
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest packet
- * @param [in] suffix - Name suffix to set
- * @return hICN error code
- */
- int (*set_interest_name_suffix) (hicn_type_t type, hicn_protocol_t *h,
- const hicn_name_suffix_t *suffix);
-
- /**
- * @brief Set flag to mark current packet as interest
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest packet
- * @return hICN error code
- */
- int (*mark_packet_as_interest) (hicn_type_t type, hicn_protocol_t *h);
-
- /**
- * @brief Set flag to mark current packet as data
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest packet
- * @return hICN error code
- */
- int (*mark_packet_as_data) (hicn_type_t type, hicn_protocol_t *h);
-
- /**
- * @brief Clear the necessary Interest fields in order to hash it
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest packet
- * @return hICN error code
- */
- int (*reset_interest_for_hash) (hicn_type_t type, hicn_protocol_t *h);
-
- /**
- * @brief Retrieves a Data locator
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Data packet
- * @param [out] ip_address - Retrieved locator
- * @return hICN error code
- */
- int (*get_data_locator) (hicn_type_t type, const hicn_protocol_t *h,
- ip46_address_t *ip_address);
-
- /**
- * @brief Sets a Data locator
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Data packet
- * @param [in] ip_address - Locator to set
- * @return hICN error code
- */
- int (*set_data_locator) (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *ip_address);
-
- /**
- * @brief Retrieves a Data name
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Data packet
- * @param [out] name - Retrieved name
- * @return hICN error code
- */
- int (*get_data_name) (hicn_type_t type, const hicn_protocol_t *h,
- hicn_name_t *name);
-
- /**
- * @brief Sets a Data name
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Data packet
- * @param [in] name - Name to set
- * @return hICN error code
- */
- int (*set_data_name) (hicn_type_t type, hicn_protocol_t *h,
- const hicn_name_t *name);
-
- /**
- * @brief Retrieves a Data name suffix
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Data packet
- * @param [out] suffix - Retrieved name suffix
- * @return hICN error code
- */
- int (*get_data_name_suffix) (hicn_type_t type, const hicn_protocol_t *h,
- hicn_name_suffix_t *suffix);
-
- /**
- * @brief Sets a Data name suffix
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Data packet
- * @param [in] suffix - Name suffix to set
- * @return hICN error code
- */
- int (*set_data_name_suffix) (hicn_type_t type, hicn_protocol_t *h,
- const hicn_name_suffix_t *suffix);
-
- /**
- * @brief Retrieves a Data pathlabel
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Data packet
- * @param [out] pathlabel - Retrieved pathlabel
- * @return hICN error code
- */
- int (*get_data_pathlabel) (hicn_type_t type, const hicn_protocol_t *h,
- u32 *pathlabel);
-
- /**
- * @brief Sets a Data pathlabel
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Data packet
- * @param [in] pathlabel - Pathlabel to set
- * @return hICN error code
- */
- int (*set_data_pathlabel) (hicn_type_t type, hicn_protocol_t *h,
- const u32 pathlabel);
-
- /**
- * @brief Update a Data pathlabel with a new face identifier
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Data packet
- * @param [in] pathlabel - Face identifier used to update pathlabel
- * @return hICN error code
- */
- int (*update_data_pathlabel) (hicn_type_t type, hicn_protocol_t *h,
- const hicn_faceid_t face_id);
-
- /**
- * @brief Clear the necessary Data fields in order to hash it
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Data packet
- * @return hICN error code
- */
- int (*reset_data_for_hash) (hicn_type_t type, hicn_protocol_t *h);
-
- /**
- * @brief Retrieves an Interest or Data lifetime
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Interest or Data packet
- * @param [out] pathlabel - Retrieved lifetime
- * @return hICN error code
- */
- int (*get_lifetime) (hicn_type_t type, const hicn_protocol_t *h,
- hicn_lifetime_t *lifetime);
-
- /**
- * @brief Sets an Interest or Data lifetime
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [in] pathlabel - Lifetime to set
- * @return hICN error code
- */
- int (*set_lifetime) (hicn_type_t type, hicn_protocol_t *h,
- const hicn_lifetime_t lifetime);
-
- /**
- * @brief Update all checksums in packet headers
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the packet
- * @param [in] partial_csum - Partial checksum (set to 0, used internally to
- * carry intermediate values from IP pseudo-header)
- * @param [in] payload_length - Payload length (can be set to ~0, retrieved
- * and used internally to carry payload length across protocol headers)
- * @return hICN error code
- */
- int (*update_checksums) (hicn_type_t type, hicn_protocol_t *h,
- u16 partial_csum, size_t payload_length);
-
- /**
- * @brief Validate all checksums in packet headers
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the packet
- * @param [in] partial_csum - Partial checksum, or zero if no partial
- * checksum available
- * @param [in] payload_length - Payload length (can be set to ~0, retrieved
- * and used internally to carry payload length across protocol headers)
- * @return hICN error code
- */
- int (*verify_checksums) (hicn_type_t type, hicn_protocol_t *h,
- u16 partial_csum, size_t payload_length);
-
- /**
- * @brief Rewrite an Interest packet header (locator)
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Interest packet
- * @param [in] addr_new - New locator
- * @param [in] addr_old - Old locator (set to NULL, used internally to
- * compute incremental checksums)
- * @return hICN error code
- */
- int (*rewrite_interest) (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new,
- ip46_address_t *addr_old);
-
- /**
- * @brief Rewrite a Data packet header (locator + pathlabel)
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Data packet
- * @param [in] addr_new - New locator
- * @param [in] addr_old - Old locator (set to NULL, used internally to
- * compute incremental checksums)
- * @param [in] face_id - Face identifier used to update pathlabel
- * @param [in] reset_pl - If not zero, reset the current pathlabel
- * before update it
- * @return hICN error code
- */
- int (*rewrite_data) (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new,
- ip46_address_t *addr_old, const hicn_faceid_t face_id,
- u8 reset_pl);
-
- /**
- * @brief Return the packet length
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the packet
- * @parma [out] length - Returned packet length
- * @return hICN error code
- */
- int (*get_length) (hicn_type_t type, const hicn_protocol_t *h,
- size_t *length);
-
- /**
- * @brief Return the current packet header length
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the packet
- * @parma [out] header_length - Returned packet current header length
- * @return hICN error code
- */
- int (*get_current_header_length) (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length);
-
- /**
- * @brief Return the packet header length
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the packet
- * @parma [out] header_length - Returned packet header length
- * @return hICN error code
- */
- int (*get_header_length) (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length);
-
- /**
- * @brief Return the packet payload length
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the packet
- * @parma [out] payload_length - Returned packet payload length
- * @return hICN error code
- */
- int (*get_payload_length) (hicn_type_t type, const hicn_protocol_t *h,
- size_t *payload_length);
-
- /**
- * @brief Sets the packet paylaod length
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the packet
- * @parma [out] payload_length - Payload length to set
- * @return hICN error code
- */
- int (*set_payload_length) (hicn_type_t type, hicn_protocol_t *h,
- size_t payload_length);
-
- /**
- * @brief Retrieves an Interest or Data signature size
- * @param [in] type - hICN packet type
- * @param [in] h - Buffer holding the Interest or Data packet
- * @param [out] signature_size - Retrieved signature size
- * @return hICN error code
- */
- int (*get_signature_size) (hicn_type_t type, const hicn_protocol_t *h,
- size_t *signature_size);
-
- /**
- * @brief Sets an Interest or Data signature size
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [in] signature_size - Signature size to set
- * @return hICN error code
- */
- int (*set_signature_size) (hicn_type_t type, hicn_protocol_t *h,
- size_t signature_size);
-
- /**
- * @brief Sets an Interest or Data signature gap between maximum size and
- * real size
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [in] signature_size - Signature size to set
- * @return hICN error code
- */
- int (*set_signature_gap) (hicn_type_t type, hicn_protocol_t *h,
- uint8_t signature_gap);
-
- /**
- * @brief gets an Interest or Data signature gap between maximum size and
- * real size
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [in] signature_size - retrieve the gap between maximum size and
- * real size
- * @return hICN error code
- */
- int (*get_signature_gap) (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *signature_gap);
-
- /**
- * @brief Gets the signature timestamp
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [out] signature_timestamp - Retrieved signature timestamp
- * @return hICN error code
- */
- int (*get_signature_timestamp) (hicn_type_t type, const hicn_protocol_t *h,
- uint64_t *signature_timestamp);
-
- /**
- * @brief Sets the signature timestamp
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [in] signature_timestamp - Signature timestamp to set
- * @return hICN error code
- */
- int (*set_signature_timestamp) (hicn_type_t type, hicn_protocol_t *h,
- uint64_t signature_timestamp);
-
- /**
- * @brief Gets the signature validation algorithm
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [out] validation_algorithm - Retrieved validation_algorithm
- * @return hICN error code
- */
- int (*get_validation_algorithm) (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *validation_algorithm);
-
- /**
- * @brief Sets the signature validation algorithm
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [in] validation_algorithm - Validation algorithm enumeration
- * @return hICN error code
- */
- int (*set_validation_algorithm) (hicn_type_t type, hicn_protocol_t *h,
- uint8_t validation_algorithm);
-
- /**
- * @brief Gets the key id
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [out] key_id - Retrieved key id first byte address
- * @return hICN error code
- */
- int (*get_key_id) (hicn_type_t type, hicn_protocol_t *h, uint8_t **key_id,
- uint8_t *key_id_size);
-
- /**
- * @brief Sets the key id
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [in] key_id - Key id first byte address
- * @return hICN error code
- */
- int (*set_key_id) (hicn_type_t type, hicn_protocol_t *h, uint8_t *key_id);
-
- /**
- * @brief Get a pointer to the signature field in the packet
- * @param [in] type - hICN packet type
- * @param [in,out] h - Buffer holding the Interest or Data packet
- * @param [out] signature - Pointer to the memory region holding the
- * signature
- * @return hICN error code
- */
- int (*get_signature) (hicn_type_t type, hicn_protocol_t *h,
- uint8_t **signature);
-} hicn_ops_t;
-
-#define DECLARE_HICN_OPS(protocol) \
- const hicn_ops_t hicn_ops_##protocol = { \
- ATTR_INIT (init_packet_header, protocol##_init_packet_header), \
- ATTR_INIT (get_interest_locator, protocol##_get_interest_locator), \
- ATTR_INIT (set_interest_locator, protocol##_set_interest_locator), \
- ATTR_INIT (get_interest_name, protocol##_get_interest_name), \
- ATTR_INIT (set_interest_name, protocol##_set_interest_name), \
- ATTR_INIT (get_interest_name_suffix, \
- protocol##_get_interest_name_suffix), \
- ATTR_INIT (set_interest_name_suffix, \
- protocol##_set_interest_name_suffix), \
- ATTR_INIT (mark_packet_as_interest, protocol##_mark_packet_as_interest), \
- ATTR_INIT (mark_packet_as_data, protocol##_mark_packet_as_data), \
- ATTR_INIT (reset_interest_for_hash, protocol##_reset_interest_for_hash), \
- ATTR_INIT (get_data_locator, protocol##_get_data_locator), \
- ATTR_INIT (set_data_locator, protocol##_set_data_locator), \
- ATTR_INIT (get_data_name, protocol##_get_data_name), \
- ATTR_INIT (set_data_name, protocol##_set_data_name), \
- ATTR_INIT (get_data_name_suffix, protocol##_get_data_name_suffix), \
- ATTR_INIT (set_data_name_suffix, protocol##_set_data_name_suffix), \
- ATTR_INIT (get_data_pathlabel, protocol##_get_data_pathlabel), \
- ATTR_INIT (set_data_pathlabel, protocol##_set_data_pathlabel), \
- ATTR_INIT (update_data_pathlabel, protocol##_update_data_pathlabel), \
- ATTR_INIT (reset_data_for_hash, protocol##_reset_data_for_hash), \
- ATTR_INIT (get_lifetime, protocol##_get_lifetime), \
- ATTR_INIT (set_lifetime, protocol##_set_lifetime), \
- ATTR_INIT (update_checksums, protocol##_update_checksums), \
- ATTR_INIT (verify_checksums, protocol##_verify_checksums), \
- ATTR_INIT (rewrite_interest, protocol##_rewrite_interest), \
- ATTR_INIT (rewrite_data, protocol##_rewrite_data), \
- ATTR_INIT (get_length, protocol##_get_length), \
- ATTR_INIT (get_current_header_length, \
- protocol##_get_current_header_length), \
- ATTR_INIT (get_header_length, protocol##_get_header_length), \
- ATTR_INIT (get_payload_length, protocol##_get_payload_length), \
- ATTR_INIT (set_payload_length, protocol##_set_payload_length), \
- ATTR_INIT (get_signature_size, protocol##_get_signature_size), \
- ATTR_INIT (get_signature_timestamp, protocol##_get_signature_timestamp), \
- ATTR_INIT (set_signature_timestamp, protocol##_set_signature_timestamp), \
- ATTR_INIT (get_validation_algorithm, \
- protocol##_get_validation_algorithm), \
- ATTR_INIT (set_validation_algorithm, \
- protocol##_set_validation_algorithm), \
- ATTR_INIT (get_key_id, protocol##_get_key_id), \
- ATTR_INIT (set_key_id, protocol##_set_key_id), \
- ATTR_INIT (get_signature, protocol##_get_signature), \
- ATTR_INIT (set_signature_gap, protocol##_set_signature_gap), \
- ATTR_INIT (set_signature_size, protocol##_set_signature_size), \
- ATTR_INIT (get_signature_gap, protocol##_get_signature_gap), \
- }
-
-/**
- * @brief Protocol-independent packet operations VFT
- * NOTE: The following declarations should be kept in order
- */
-extern const hicn_ops_t *const hicn_ops_vft[];
-
-/*
- * Helpers for writing recursive protocol operations on packet headers
- *
- * NOTE : we cannot use a shift operation as IPPROTO_NONE != 0 (and 0 is
- * IPv4...)
- */
-always_inline hicn_type_t
-TYPE_POP (hicn_type_t type)
-{
-#ifndef _WIN32
- return HICN_TYPE (type.l2, type.l3, type.l4, IPPROTO_NONE);
-#else
- hicn_type_t new_type;
- new_type.l1 = type.l2;
- new_type.l2 = type.l3;
- new_type.l3 = type.l4;
- new_type.l4 = IPPROTO_NONE;
- return new_type;
-#endif
-}
-
-always_inline hicn_protocol_t *
-PAYLOAD (hicn_type_t type, const hicn_protocol_t *h)
-{
- size_t header_length;
- int rc =
- hicn_ops_vft[type.l1]->get_current_header_length (type, h, &header_length);
- if (rc < 0)
- return NULL;
- return (hicn_protocol_t *) ((u8 *) h + header_length);
-}
-
-#define CHILD_OPS(f, type, h, ...) \
- (hicn_ops_vft[type.l2]->f (TYPE_POP (type), PAYLOAD (type, h), \
- ##__VA_ARGS__))
-
-/** Shortcuts to entry points in VFT */
-#define HICN_OPS4 hicn_ops_vft[IPPROTO_IP]
-#define HICN_OPS6 hicn_ops_vft[IPPROTO_IPV6]
-
-/* Helpers for simple declarations */
-
-#define DECLARE_init_packet_header(protocol, error) \
- int protocol##_init_packet_header (hicn_type_t type, hicn_protocol_t *h) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_interest_locator(protocol, error) \
- int protocol##_get_interest_locator ( \
- hicn_type_t type, const hicn_protocol_t *h, ip46_address_t *ip_address) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_interest_locator(protocol, error) \
- int protocol##_set_interest_locator (hicn_type_t type, hicn_protocol_t *h, \
- const ip46_address_t *ip_address) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_interest_name(protocol, error) \
- int protocol##_get_interest_name ( \
- hicn_type_t type, const hicn_protocol_t *h, hicn_name_t *name) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_interest_name(protocol, error) \
- int protocol##_set_interest_name (hicn_type_t type, hicn_protocol_t *h, \
- const hicn_name_t *name) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_interest_name_suffix(protocol, error) \
- int protocol##_get_interest_name_suffix ( \
- hicn_type_t type, const hicn_protocol_t *h, hicn_name_suffix_t *suffix) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_interest_name_suffix(protocol, error) \
- int protocol##_set_interest_name_suffix ( \
- hicn_type_t type, hicn_protocol_t *h, const hicn_name_suffix_t *suffix) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_mark_packet_as_interest(protocol, error) \
- int protocol##_mark_packet_as_interest (hicn_type_t type, \
- hicn_protocol_t *h) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_mark_packet_as_data(protocol, error) \
- int protocol##_mark_packet_as_data (hicn_type_t type, hicn_protocol_t *h) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_reset_interest_for_hash(protocol, error) \
- int protocol##_reset_interest_for_hash (hicn_type_t type, \
- hicn_protocol_t *h) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_data_locator(protocol, error) \
- int protocol##_get_data_locator ( \
- hicn_type_t type, const hicn_protocol_t *h, ip46_address_t *ip_address) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_data_locator(protocol, error) \
- int protocol##_set_data_locator (hicn_type_t type, hicn_protocol_t *h, \
- const ip46_address_t *ip_address) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_data_name(protocol, error) \
- int protocol##_get_data_name (hicn_type_t type, const hicn_protocol_t *h, \
- hicn_name_t *name) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_data_name(protocol, error) \
- int protocol##_set_data_name (hicn_type_t type, hicn_protocol_t *h, \
- const hicn_name_t *name) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_data_name_suffix(protocol, error) \
- int protocol##_get_data_name_suffix ( \
- hicn_type_t type, const hicn_protocol_t *h, hicn_name_suffix_t *suffix) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_data_name_suffix(protocol, error) \
- int protocol##_set_data_name_suffix (hicn_type_t type, hicn_protocol_t *h, \
- const hicn_name_suffix_t *suffix) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_data_pathlabel(protocol, error) \
- int protocol##_get_data_pathlabel ( \
- hicn_type_t type, const hicn_protocol_t *h, u32 *pathlabel) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_data_pathlabel(protocol, error) \
- int protocol##_set_data_pathlabel (hicn_type_t type, hicn_protocol_t *h, \
- const u32 pathlabel) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_update_data_pathlabel(protocol, error) \
- int protocol##_update_data_pathlabel (hicn_type_t type, hicn_protocol_t *h, \
- const hicn_faceid_t face_id) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_reset_data_for_hash(protocol, error) \
- int protocol##_reset_data_for_hash (hicn_type_t type, hicn_protocol_t *h) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_lifetime(protocol, error) \
- int protocol##_get_lifetime (hicn_type_t type, const hicn_protocol_t *h, \
- hicn_lifetime_t *lifetime) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_lifetime(protocol, error) \
- int protocol##_set_lifetime (hicn_type_t type, hicn_protocol_t *h, \
- const hicn_lifetime_t lifetime) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_update_checksums(protocol, error) \
- int protocol##_update_checksums (hicn_type_t type, hicn_protocol_t *h, \
- u16 partial_csum, size_t payload_length) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_verify_checksums(protocol, error) \
- int protocol##_verify_checksums (hicn_type_t type, hicn_protocol_t *h, \
- u16 partial_csum, size_t payload_length) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_rewrite_interest(protocol, error) \
- int protocol##_rewrite_interest (hicn_type_t type, hicn_protocol_t *h, \
- const ip46_address_t *addr_new, \
- ip46_address_t *addr_old) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_rewrite_data(protocol, error) \
- int protocol##_rewrite_data ( \
- hicn_type_t type, hicn_protocol_t *h, const ip46_address_t *addr_new, \
- ip46_address_t *addr_old, const hicn_faceid_t face_id, u8 reset_pl) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_length(protocol, error) \
- int protocol##_get_length (hicn_type_t type, const hicn_protocol_t *h, \
- size_t *length) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_current_header_length(protocol, error) \
- int protocol##_get_current_header_length ( \
- hicn_type_t type, const hicn_protocol_t *h, size_t *header_length) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_header_length(protocol, error) \
- int protocol##_get_header_length ( \
- hicn_type_t type, const hicn_protocol_t *h, size_t *header_length) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_payload_length(protocol, error) \
- int protocol##_get_payload_length ( \
- hicn_type_t type, const hicn_protocol_t *h, size_t *payload_length) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_payload_length(protocol, error) \
- int protocol##_set_payload_length (hicn_type_t type, hicn_protocol_t *h, \
- size_t payload_length) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_signature_size(protocol, error) \
- int protocol##_get_signature_size ( \
- hicn_type_t type, const hicn_protocol_t *h, size_t *signature_size) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_signature_size(protocol, error) \
- int protocol##_set_signature_size (hicn_type_t type, hicn_protocol_t *h, \
- size_t signature_size) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_signature_gap(protocol, error) \
- int protocol##_set_signature_gap (hicn_type_t type, hicn_protocol_t *h, \
- uint8_t signature_size) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_signature_gap(protocol, error) \
- int protocol##_get_signature_gap ( \
- hicn_type_t type, const hicn_protocol_t *h, uint8_t *signature_size) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_signature_timestamp(protocol, error) \
- int protocol##_set_signature_timestamp ( \
- hicn_type_t type, hicn_protocol_t *h, uint64_t signature_timestamp) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_signature_timestamp(protocol, error) \
- int protocol##_get_signature_timestamp (hicn_type_t type, \
- const hicn_protocol_t *h, \
- uint64_t *signature_timestamp) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_validation_algorithm(protocol, error) \
- int protocol##_set_validation_algorithm ( \
- hicn_type_t type, hicn_protocol_t *h, uint8_t validation_algorithm) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_validation_algorithm(protocol, error) \
- int protocol##_get_validation_algorithm (hicn_type_t type, \
- const hicn_protocol_t *h, \
- uint8_t *validation_algorithm) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_set_key_id(protocol, error) \
- int protocol##_set_key_id (hicn_type_t type, hicn_protocol_t *h, \
- uint8_t *key_id) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_key_id(protocol, error) \
- int protocol##_get_key_id (hicn_type_t type, hicn_protocol_t *h, \
- uint8_t **key_id, uint8_t *key_id_size) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#define DECLARE_get_signature(protocol, error) \
- int protocol##_get_signature (hicn_type_t type, hicn_protocol_t *h, \
- uint8_t **signature) \
- { \
- return HICN_LIB_ERROR_##error; \
- }
-
-#endif /* HICN_OPS_H */
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables:
- * eval: (c-set-style "gnu")
- * End:
- */
diff --git a/lib/includes/hicn/packet.h b/lib/includes/hicn/packet.h
new file mode 100644
index 000000000..c4a0dd80e
--- /dev/null
+++ b/lib/includes/hicn/packet.h
@@ -0,0 +1,668 @@
+/*
+ * Copyright (c) 2017-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file compat.h
+ * @brief Implementation of the compatibility layer.
+ *
+ * The structure of the core API has evolved to support operations of a variety
+ * of packet formats in addition to IPv4/TCP and IPv6/TCP, namely with the use
+ * of ICMP for signalization and AH headers for integrity. The new API format
+ * has been designed to scale better with the multiplicity of packet formats,
+ * and provide a unified interface on top. We maintain an interface for the
+ * former API in this file, which mainly acts as a wrapper on top of new calls.
+ *
+ */
+#ifndef HICN_PACKET_H
+#define HICN_PACKET_H
+
+#include <limits.h>
+
+#include <hicn/base.h>
+#include <hicn/common.h>
+#include <hicn/name.h>
+
+/* Packet buffer definition */
+
+typedef struct __attribute__ ((packed))
+{
+ /*
+ * We store an offset to the packet header.
+ *
+ * NOTE: This is a signed value.
+ *
+ * In most implementations, the buffer located closeby to the current packet
+ * buffer (eg msgbuf in hicn-light, and vlib buffer in VPP), and an int16_t
+ * would be sufficient. This is not the case in transport though and we have
+ * to use a full integer.
+ */
+ int64_t header;
+
+ /*
+ * Packet format [4]
+ */
+ hicn_packet_format_t format;
+
+ /*
+ * Packet type [2]
+ */
+ uint16_t type;
+
+ /*
+ * Buffer size [2]
+ */
+ uint16_t buffer_size;
+
+ /*
+ * Packet len [2]
+ */
+ uint16_t len;
+
+#ifdef OPAQUE_IP
+ /* Interest or data packet */
+ union
+ {
+ uint16_t ipv4;
+ uint16_t ipv6;
+ };
+#endif /* OPAQUE_IP */
+ /*
+ * L4 offset [1]
+ */
+ union
+ {
+ uint8_t tcp;
+ uint8_t udp;
+ uint8_t icmp;
+ };
+ /*
+ * New header offset [1]
+ */
+ uint8_t newhdr;
+
+ /*
+ * AH offset [2]
+ */
+ uint16_t ah;
+
+ /*
+ * Payload offset [2]
+ */
+ uint16_t payload;
+} hicn_packet_buffer_t;
+
+static_assert (sizeof (hicn_packet_buffer_t) == 24, "");
+
+static inline uint8_t *
+_pkbuf_get_ipv4 (const hicn_packet_buffer_t *pkbuf)
+{
+#ifdef OPAQUE_IP
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header + pkbuf->ipv4;
+#else
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header;
+#endif
+ _ASSERT (header);
+ return header;
+}
+#define pkbuf_get_ipv4(pkbuf) ((_ipv4_header_t *) (_pkbuf_get_ipv4 (pkbuf)))
+
+static inline uint8_t *
+_pkbuf_get_ipv6 (const hicn_packet_buffer_t *pkbuf)
+{
+#ifdef OPAQUE_IP
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header + pkbuf->ipv6;
+#else
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header;
+#endif
+ assert (header);
+ return header;
+}
+#define pkbuf_get_ipv6(pkbuf) ((_ipv6_header_t *) (_pkbuf_get_ipv6 (pkbuf)))
+
+static inline uint8_t *
+_pkbuf_get_tcp (const hicn_packet_buffer_t *pkbuf)
+{
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header + pkbuf->tcp;
+ assert (header);
+ return header;
+}
+#define pkbuf_get_tcp(pkbuf) ((_tcp_header_t *) (_pkbuf_get_tcp (pkbuf)))
+
+static inline uint8_t *
+_pkbuf_get_udp (const hicn_packet_buffer_t *pkbuf)
+{
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header + pkbuf->udp;
+ assert (header);
+ return header;
+}
+#define pkbuf_get_udp(pkbuf) ((_udp_header_t *) (_pkbuf_get_udp (pkbuf)))
+
+static inline uint8_t *
+_pkbuf_get_icmp (const hicn_packet_buffer_t *pkbuf)
+{
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header + pkbuf->icmp;
+ assert (header);
+ return header;
+}
+#define pkbuf_get_icmp(pkbuf) ((_icmp_header_t *) (_pkbuf_get_icmp (pkbuf)))
+
+static inline uint8_t *
+_pkbuf_get_ah (const hicn_packet_buffer_t *pkbuf)
+{
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header + pkbuf->ah;
+ assert (header);
+ return header;
+}
+#define pkbuf_get_ah(pkbuf) ((_ah_header_t *) (_pkbuf_get_ah (pkbuf)))
+
+static inline uint8_t *
+_pkbuf_get_new (const hicn_packet_buffer_t *pkbuf)
+{
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header + pkbuf->newhdr;
+ assert (header);
+ return header;
+}
+#define pkbuf_get_new(pkbuf) ((_new_header_t *) (_pkbuf_get_new (pkbuf)))
+
+static inline uint8_t *
+pkbuf_get_header (const hicn_packet_buffer_t *pkbuf)
+{
+ uint8_t *header = (uint8_t *) pkbuf + pkbuf->header;
+ assert (header);
+ return header;
+}
+
+static inline void
+pkbuf_set_header (hicn_packet_buffer_t *pkbuf, uint8_t *header)
+{
+ ssize_t offset = header - (uint8_t *) pkbuf;
+ assert (offset < INT64_MAX);
+ assert (offset > INT64_MIN);
+ pkbuf->header = (int64_t) offset;
+}
+
+/*
+ * Packet buffer operations
+ *
+ * A packet buffer can either be initialized either:
+ *
+ * 1) from an empty buffer (packet crafting).
+ *
+ * #define MTU 1500
+ * size_t size = MTU;
+ * u8 buffer[MTU];
+ *
+ * hicn_packet_t pkbuf;
+ * hicn_packet_set_format(&pkbuf, HICN_PACKET_FORMAT_NEW);
+ * hicn_packet_set_buffer(&pkbuf, &buffer, size);
+ * hicn_packet_init_header(&pkbuf, 0);
+ *
+ * An empty (but correct) packet is not available in the buffer, ready to be
+ * modified and/or sent.
+ *
+ * 2) from an existing buffer (packet reception):
+ *
+ * hicn_packet_t pkbuf;
+ * hicn_packet_set_buffer(&pkbuf, &buffer, size);
+ * hicn_packet_analyze(&pkbuf);
+ *
+ * It is then possible to retrieve properties of the packet such as format and
+ * type (interest, data, etc.).
+ *
+ * hicn_packet_get_format(&pkbuf);
+ * hicn_packet_get_type(&pkbuf);
+ *
+ * */
+
+hicn_packet_format_t
+hicn_packet_get_format (const hicn_packet_buffer_t *pkbuf);
+
+void hicn_packet_set_format (hicn_packet_buffer_t *pkbuf,
+ hicn_packet_format_t format);
+
+hicn_packet_type_t hicn_packet_get_type (const hicn_packet_buffer_t *pkbuf);
+
+void hicn_packet_initialize_type (hicn_packet_buffer_t *pkbuf,
+ hicn_packet_type_t type);
+
+void hicn_packet_set_type (hicn_packet_buffer_t *pkbuf,
+ hicn_packet_type_t type);
+
+bool hicn_packet_is_interest (const hicn_packet_buffer_t *pkbuf);
+
+bool hicn_packet_is_data (const hicn_packet_buffer_t *pkbuf);
+
+bool hicn_packet_is_undefined (const hicn_packet_buffer_t *pkbuf);
+
+/**
+ * @brief Initialize the buffer from packet buffer metadata (builds a valid
+ * packet).
+ * @param [in] pkbuf - hICN packet buffer
+ * @return hICN error code
+ *
+ * Packet type, format, and a buffer are required.
+ */
+int hicn_packet_init_header (hicn_packet_buffer_t *pkbuf,
+ size_t additional_header_size);
+
+/**
+ * @brief Reset information stored in the packet header.
+ * @param [in] pkbuf - hICN packet buffer
+ * @return hICN error code
+ */
+int hicn_packet_reset (hicn_packet_buffer_t *pkbuf);
+
+/**
+ * @brief Analyze buffer to populate metadata in packet buffer.
+ * @param [in] pkbuf - hICN packet buffer
+ * @return hICN error code
+ */
+int hicn_packet_analyze (hicn_packet_buffer_t *pkbuf);
+
+/**
+ * @brief Initialize hicn packet storage space with a buffer
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] buffer - Packet storage buffer
+ * @param [in] analyze - Flag indicating whether to analyze the buffer
+ * content to populate packet format, header's offsets, etc.
+ * @return hICN error code
+ */
+int hicn_packet_set_buffer (hicn_packet_buffer_t *pkbuf, u8 *buffer,
+ uint16_t buffer_size, uint16_t len);
+
+/**
+ * @brief Retrieve the storage buffer.
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [out] buffer - Packet buffer
+ * @param [out] buffer_size - Packet buffer size
+ * @return Pointer to storage buffer (this only returns the pointer; no copy is
+ * made)
+ */
+int hicn_packet_get_buffer (const hicn_packet_buffer_t *pkbuf, u8 **buffer,
+ uint16_t *buffer_size, uint16_t *len);
+
+/**
+ * @brief Retrieve the packet length
+ * @param [in] pkbuf - hICN packet buffer
+ * @return Length of the stored packet
+ */
+size_t hicn_packet_get_len (const hicn_packet_buffer_t *pkbuf);
+
+/**
+ * @brief Set the packet length
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] len - hICN packet length
+ * @return None
+ */
+int hicn_packet_set_len (hicn_packet_buffer_t *pkbuf, size_t len);
+
+/**
+ * @brief Return total length of hicn headers (before payload)
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [out] len - Total headers length
+ * @return Headers' len
+ */
+int hicn_packet_get_header_len (const hicn_packet_buffer_t *pkbuf,
+ size_t *len);
+
+/**
+ * @brief Return the length of hICN payload in the packet.
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [out] len - hICN payload length
+ * @return Payload len
+ */
+int hicn_packet_get_payload_len (const hicn_packet_buffer_t *pkbuf,
+ size_t *len);
+
+/**
+ * @brief Sets the payload of a packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] packet - packet header
+ * @param [in] payload - payload to set
+ * @param [in] payload_length - size of the payload to set
+ * @return hICN error code
+ *
+ * NOTE:
+ * - The buffer holding payload is assumed sufficiently large
+ * - This function updates header fields with the new length, but no checksum.
+ */
+int hicn_packet_set_payload (const hicn_packet_buffer_t *pkbuf,
+ const u8 *payload, u16 payload_length);
+
+/**
+ * @brief Retrieves the payload of a packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [out] payload - pointer to buffer for storing the result
+ * @param [out] payload_length - size of the retreived payload
+ * @param [in] hard_copy - Flag : if true (eg. 1), a copy of the payload is
+ * made into the payload buffer, otherwise (0) the pointer is changed to point
+ * to the payload offset in the packet.
+ * @return hICN error code
+ *
+ * NOTE:
+ * - The buffer holding payload is assumed sufficiently large
+ */
+int hicn_packet_get_payload (const hicn_packet_buffer_t *pkbuf, u8 **payload,
+ size_t *payload_size, bool hard_copy);
+
+/* Header fields manipulation */
+
+/**
+ * @brief Return total length of hicn headers (but signature payload)
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [out] header_length - Total length of headers
+ * @return hICN error code
+ */
+int hicn_packet_get_header_length_from_format (hicn_packet_format_t format,
+ size_t *header_length);
+
+/**
+ * @brief Sets payload length
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] packet - packet header
+ * @param [in] payload_length - payload length
+ * @return hICN error code
+ */
+int hicn_packet_set_payload_length (const hicn_packet_buffer_t *pkbuf,
+ const size_t payload_length);
+
+/**
+ * @brief Compare two hICN packets
+ * @param [in] packet_1 - First packet
+ * @param [in] packet_2 - Second packet
+ * @return 0 if both packets are considered equal, any other value otherwise.
+ */
+int hicn_packet_compare (const hicn_packet_buffer_t *pkbuf11,
+ const hicn_packet_buffer_t *pkbuf22);
+
+/**
+ * @brief Retrieve the name of an interest/data packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [out] name - name holding the result
+ * @return hICN error code
+ */
+int hicn_packet_get_name (const hicn_packet_buffer_t *pkbuf,
+ hicn_name_t *name);
+
+/**
+ * @brief Sets the name of an interest/data packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] packet - packet header
+ * @param [in] name - name to set into packet
+ * @return hICN error code
+ */
+int hicn_packet_set_name (const hicn_packet_buffer_t *pkbuf,
+ const hicn_name_t *name);
+
+/**
+ * @brief Retrieve the locator of an interest / data packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [out] ip_address - retrieved locator
+ * @return hICN error code
+ */
+int hicn_packet_get_locator (const hicn_packet_buffer_t *pkbuf,
+ hicn_ip_address_t *prefix);
+
+/**
+ * @brief Sets the locator of an interest / data packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] packet - packet header
+ * @param [out] ip_address - retrieved locator
+ * @return hICN error code
+ */
+int hicn_packet_set_locator (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *prefix);
+
+int hicn_packet_save_header (const hicn_packet_buffer_t *pkbuf, u8 *header,
+ size_t *header_len, bool copy_ah);
+
+int hicn_packet_load_header (const hicn_packet_buffer_t *pkbuf,
+ const u8 *header, size_t header_len);
+
+int hicn_packet_get_lifetime (const hicn_packet_buffer_t *pkbuf,
+ u32 *lifetime);
+int hicn_packet_set_lifetime (const hicn_packet_buffer_t *pkbuf, u32 lifetime);
+
+/* Interest */
+int hicn_interest_get_name (const hicn_packet_buffer_t *pkbuf,
+ hicn_name_t *name);
+int hicn_interest_set_name (const hicn_packet_buffer_t *pkbuf,
+ const hicn_name_t *name);
+int hicn_interest_get_locator (const hicn_packet_buffer_t *pkbuf,
+ hicn_ip_address_t *prefix);
+int hicn_interest_set_locator (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *prefix);
+int hicn_interest_compare (const hicn_packet_buffer_t *pkbuf11,
+ const hicn_packet_buffer_t *pkbuf2);
+int hicn_interest_set_lifetime (const hicn_packet_buffer_t *pkbuf,
+ u32 lifetime);
+int hicn_interest_get_lifetime (const hicn_packet_buffer_t *pkbuf,
+ u32 *lifetime);
+int hicn_interest_get_header_length (const hicn_packet_buffer_t *pkbuf,
+ size_t *header_length);
+int hicn_interest_get_payload_length (const hicn_packet_buffer_t *pkbuf,
+ size_t *payload_length);
+int hicn_interest_set_payload (const hicn_packet_buffer_t *pkbuf,
+ const u8 *payload, size_t payload_length);
+int hicn_interest_get_payload (const hicn_packet_buffer_t *pkbuf, u8 **payload,
+ size_t *payload_size, bool hard_copy);
+int hicn_interest_reset_for_hash (hicn_packet_buffer_t *pkbuf);
+
+/* Data */
+
+int hicn_data_get_name (const hicn_packet_buffer_t *pkbuf, hicn_name_t *name);
+int hicn_data_set_name (const hicn_packet_buffer_t *pkbuf,
+ const hicn_name_t *name);
+int hicn_data_get_locator (const hicn_packet_buffer_t *pkbuf,
+ hicn_ip_address_t *prefix);
+int hicn_data_set_locator (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *prefix);
+int hicn_data_compare (const hicn_packet_buffer_t *pkbuf11,
+ const hicn_packet_buffer_t *pkbuf22);
+int hicn_data_get_expiry_time (const hicn_packet_buffer_t *pkbuf,
+ u32 *expiry_time);
+int hicn_data_set_expiry_time (const hicn_packet_buffer_t *pkbuf,
+ u32 expiry_time);
+int hicn_data_get_header_length (const hicn_packet_buffer_t *pkbuf,
+ size_t *header_length);
+int hicn_data_get_payload_length (const hicn_packet_buffer_t *pkbuf,
+ size_t *payload_length);
+
+/* Path label */
+
+/**
+ * @brief Returns the path label from a data packet
+ * @param [in] pkbuf - packet buffer
+ * @param [in] hdr - packet header
+ * @param [in] path_label - pointer in which to store the path label value
+ * @return hICN error code
+ */
+int hicn_data_get_path_label (const hicn_packet_buffer_t *pkbufdr,
+ hicn_path_label_t *path_label);
+
+/**
+ * @brief Returns the path label from a packet
+ * @param [in] pkbuf - packet buffer
+ * @param [in] hdr - packet header
+ * @param [in] path_label - pointer in which to store the path label value
+ * @return hICN error code
+ */
+int hicn_get_path_label (const hicn_packet_buffer_t *pkbufdr,
+ hicn_path_label_t *path_label);
+
+int hicn_data_set_path_label (const hicn_packet_buffer_t *pkbuf,
+ hicn_path_label_t path_label);
+
+/* Data specific flags */
+
+int hicn_packet_get_payload_type (const hicn_packet_buffer_t *pkbuf,
+
+ hicn_payload_type_t *payload_type);
+int hicn_packet_set_payload_type (const hicn_packet_buffer_t *pkbuf,
+
+ const hicn_payload_type_t payload_type);
+
+int hicn_data_get_payload (const hicn_packet_buffer_t *pkbuf, u8 **payload,
+ size_t *payload_size, bool hard_copy);
+int hicn_data_set_payload (const hicn_packet_buffer_t *pkbuf,
+ const u8 *payload, size_t payload_length);
+int hicn_data_get_payload_type (hicn_payload_type_t *payload_type);
+int hicn_data_set_payload_type (hicn_payload_type_t payload_type);
+int hicn_data_reset_for_hash (hicn_packet_buffer_t *pkbuf);
+int hicn_data_is_last (const hicn_packet_buffer_t *pkbuf, int *is_last);
+int hicn_data_set_last (const hicn_packet_buffer_t *pkbuf);
+
+/* Security */
+
+/**
+ * @brief Retrieves the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [out] bytes - Retrieved signature size
+ * @return hICN error code
+ */
+int hicn_packet_get_signature_size (const hicn_packet_buffer_t *pkbuf,
+ size_t *bytes);
+
+/**
+ * @brief Sets the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [in] bytes - Retrieved signature size
+ * @return hICN error code
+ */
+int hicn_packet_set_signature_size (const hicn_packet_buffer_t *pkbuf,
+ size_t bytes);
+
+/**
+ * @brief Sets the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [in] signature_timestamp - Signature timestamp to set
+ * @return hICN error code
+ */
+int hicn_packet_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf,
+ uint64_t signature_timestamp);
+
+/**
+ * @brief Sets the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [out] signature_timestamp - Retrieved signature timestamp
+ * @return hICN error code
+ */
+int hicn_packet_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf,
+ uint64_t *signature_timestamp);
+
+/**
+ * @brief Sets the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [in] validation_algorithm - Validation algorithm to set
+ * @return hICN error code
+ */
+int hicn_packet_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf,
+ uint8_t validation_algorithm);
+
+/**
+ * @brief Sets the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [out] validation_algorithm - Retrieved validation algorithm
+ * @return hICN error code
+ */
+int hicn_packet_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf,
+ uint8_t *validation_algorithm);
+
+/**
+ * @brief Sets the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [in] key_id - Key id to set
+ * @param [in] key_len - Key length
+ * @return hICN error code
+ */
+int hicn_packet_set_key_id (const hicn_packet_buffer_t *pkbuf, uint8_t *key_id,
+ size_t key_len);
+
+/**
+ * @brief Sets the signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] packet - packet header
+ * @param [out] key_id - Retrieved key id
+ * @return hICN error code
+ */
+int hicn_packet_get_key_id (const hicn_packet_buffer_t *pkbuf,
+ uint8_t **key_id, uint8_t *key_id_length);
+
+int hicn_packet_get_signature (const hicn_packet_buffer_t *pkbuf,
+ uint8_t **sign_buf);
+
+int hicn_packet_get_signature_padding (const hicn_packet_buffer_t *pkbuf,
+ size_t *bytes);
+int hicn_packet_set_signature_padding (const hicn_packet_buffer_t *pkbuf,
+ size_t bytes);
+
+/* Checksums */
+
+/**
+ * @brief Update checksums in packet headers
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] packet - packet header
+ * @return hICN error code
+ */
+int hicn_packet_compute_checksum (const hicn_packet_buffer_t *pkbuf);
+
+/**
+ * @brief compute the checksum of the packet header, adding init_sum to the
+ * final value
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] packet - packet header
+ * @param [in] init_sum - value to add to the final checksum
+ * @return hICN error code
+ */
+int hicn_packet_compute_header_checksum (const hicn_packet_buffer_t *pkbuf,
+ u16 init_sum);
+
+/**
+ * @brief Verify checksums in packet headers
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] packet - packet header
+ * @return hICN error code
+ */
+int hicn_packet_check_integrity_no_payload (const hicn_packet_buffer_t *pkbuf,
+ u16 init_sum);
+
+int hicn_interest_rewrite (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old);
+
+int hicn_data_rewrite (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old,
+ const hicn_faceid_t face_id, u8 reset_pl);
+
+#endif /* HICN_PACKET_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/includes/hicn/policy.h b/lib/includes/hicn/policy.h
index e29888bd2..50b771537 100644
--- a/lib/includes/hicn/policy.h
+++ b/lib/includes/hicn/policy.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -30,37 +30,44 @@
/* POLICY TAG */
-#define foreach_policy_tag \
- /* Interface type */ \
- _(WIRED, 'E') \
- _(WIFI, 'W') \
- _(CELLULAR, 'C') \
- /* QoS */ \
- _(BEST_EFFORT, 'b') \
- _(REALTIME, 'r') \
- _(MULTIPATH, 'M') \
- /* Security */ \
- _(TRUSTED, 'T')
-
-typedef enum {
-#define _(x, y) POLICY_TAG_ ## x,
-foreach_policy_tag
+#define foreach_policy_tag \
+ /* Interface type */ \
+ _ (WIRED, 'E') \
+ _ (WIFI, 'W') \
+ _ (CELLULAR, 'C') \
+ /* QoS */ \
+ _ (BEST_EFFORT, 'b') \
+ _ (REALTIME, 'r') \
+ _ (MULTIPATH, 'M') \
+ /* Security */ \
+ _ (TRUSTED, 'T')
+
+typedef enum
+{
+#define _(x, y) POLICY_TAG_##x,
+ foreach_policy_tag
#undef _
POLICY_TAG_N
} policy_tag_t;
+#define IS_VALID_POLICY_TAG(x) (x != POLICY_TAG_N)
+
#define MAXSZ_POLICY_TAG_ 11
-#define MAXSZ_POLICY_TAG MAXSZ_POLICY_TAG_ + 1
+#define MAXSZ_POLICY_TAG MAXSZ_POLICY_TAG_ + 1
-extern const char * policy_tag_str[];
+extern const char *policy_tag_str[];
extern const char policy_tag_short_str[];
-static inline
-policy_tag_t
-policy_tag_from_str(const char * str)
+static inline policy_tag_t
+policy_tag_from_str (const char *str)
{
-#define _(x, y) if (strcasecmp(str, policy_tag_str[POLICY_TAG_ ## x] ) == 0) { return POLICY_TAG_ ## x; } else
-foreach_policy_tag
+#define _(x, y) \
+ if (strcasecmp (str, policy_tag_str[POLICY_TAG_##x]) == 0) \
+ { \
+ return POLICY_TAG_##x; \
+ } \
+ else
+ foreach_policy_tag
#undef _
return POLICY_TAG_N;
}
@@ -69,182 +76,188 @@ foreach_policy_tag
typedef int policy_tags_t;
-static inline
-void policy_tags_add(policy_tags_t * tags, policy_tag_t tag)
+static inline void
+policy_tags_add (policy_tags_t *tags, policy_tag_t tag)
{
- *tags |= (1 << tag);
+ *tags |= (1 << tag);
}
-static inline
-void policy_tags_remove(policy_tags_t * tags, policy_tag_t tag)
+static inline void
+policy_tags_remove (policy_tags_t *tags, policy_tag_t tag)
{
- *tags &= ~(1 << tag);
+ *tags &= ~(1 << tag);
}
-static inline
-int policy_tags_has(policy_tags_t tags, policy_tag_t tag)
+static inline int
+policy_tags_has (policy_tags_t tags, policy_tag_t tag)
{
- return tags & (1 << tag);
+ return tags & (1 << tag);
}
-static inline
-void policy_tags_union(policy_tags_t * tags, policy_tags_t * tags_to_union)
+static inline void
+policy_tags_union (policy_tags_t *tags, policy_tags_t *tags_to_union)
{
-#define _(x, y) *tags |= policy_tags_has(*tags_to_union, POLICY_TAG_ ## x) ? (1 << POLICY_TAG_ ## x) : 0;
-foreach_policy_tag
+#define _(x, y) \
+ *tags |= policy_tags_has (*tags_to_union, POLICY_TAG_##x) ? \
+ (1 << POLICY_TAG_##x) : \
+ 0;
+ foreach_policy_tag
#undef _
}
#define POLICY_TAGS_EMPTY 0
-static inline
-int
-policy_tags_snprintf(char * s, size_t size, policy_tags_t tags)
+static inline int
+policy_tags_snprintf (char *s, size_t size, policy_tags_t tags)
{
-#define _(x, y) s[POLICY_TAG_ ## x] = policy_tags_has(tags, POLICY_TAG_ ## x) ? y : '.';
-foreach_policy_tag
+#define _(x, y) \
+ s[POLICY_TAG_##x] = policy_tags_has (tags, POLICY_TAG_##x) ? y : '.';
+ foreach_policy_tag
#undef _
s[POLICY_TAG_N] = '\0';
- return POLICY_TAG_N + 1;
+ return POLICY_TAG_N + 1;
}
#define MAXSZ_POLICY_TAGS_ POLICY_TAG_N + 1
-#define MAXSZ_POLICY_TAGS MAXSZ_POLICY_TAGS_ + 1
+#define MAXSZ_POLICY_TAGS MAXSZ_POLICY_TAGS_ + 1
/* POLICY STATE */
/* TODO vs. weight */
-#define foreach_policy_state \
- _(NEUTRAL) \
- _(REQUIRE) \
- _(PREFER) \
- _(AVOID) \
- _(PROHIBIT) \
- _(N)
-
-typedef enum {
-#define _(x) POLICY_STATE_ ## x,
-foreach_policy_state
+#define foreach_policy_state \
+ _ (NEUTRAL) \
+ _ (REQUIRE) \
+ _ (PREFER) \
+ _ (AVOID) \
+ _ (PROHIBIT) \
+ _ (N)
+
+typedef enum
+{
+#define _(x) POLICY_STATE_##x,
+ foreach_policy_state
#undef _
} policy_state_t;
#define MAXSZ_POLICY_STATE_ 8
-#define MAXSZ_POLICY_STATE MAXSZ_POLICY_STATE_ + 1
+#define MAXSZ_POLICY_STATE MAXSZ_POLICY_STATE_ + 1
+
+extern const char *policy_state_str[];
-extern const char * policy_state_str[];
+#define policy_state_str(x) policy_state_str[x]
+policy_state_t policy_state_from_str (const char *str);
/* POLICY TAG STATE */
-typedef struct {
- policy_state_t state;
- uint8_t disabled;
+typedef struct __attribute__ ((packed, aligned (1)))
+{
+ policy_state_t state;
+ uint8_t disabled;
} policy_tag_state_t;
#define MAXSZ_POLICY_TAG_STATE_ 8
-#define MAXSZ_POLICY_TAG_STATE MAXSZ_POLICY_TAG_STATE_ + 1
-
-int policy_tag_state_snprintf(char * s, size_t size, const policy_tag_state_t * tag_state);
+#define MAXSZ_POLICY_TAG_STATE MAXSZ_POLICY_TAG_STATE_ + 1
+int policy_tag_state_snprintf (char *s, size_t size,
+ const policy_tag_state_t *tag_state);
/* INTERFACE STATS */
-typedef struct {
- float throughput;
- float latency;
- float loss_rate;
+typedef struct
+{
+ float throughput;
+ float latency;
+ float loss_rate;
} interface_stats_t;
-#define INTERFACE_STATS_NONE { \
- .throughput = 0, \
- .latency = 0, \
- .loss_rate = 0, \
-}
-
+#define INTERFACE_STATS_EMPTY \
+ { \
+ .throughput = 0, .latency = 0, .loss_rate = 0, \
+ }
/* POLICY STATS */
-typedef struct {
- interface_stats_t wired;
- interface_stats_t wifi;
- interface_stats_t cellular;
- interface_stats_t all;
+typedef struct
+{
+ interface_stats_t wired;
+ interface_stats_t wifi;
+ interface_stats_t cellular;
+ interface_stats_t all;
} policy_stats_t;
-#define POLICY_STATS_NONE { \
- .wired = INTERFACE_STATS_NONE, \
- .wifi = INTERFACE_STATS_NONE, \
- .cellular = INTERFACE_STATS_NONE, \
- .all = INTERFACE_STATS_NONE, \
-}
+#define POLICY_STATS_EMPTY \
+ (policy_stats_t) \
+ { \
+ .wired = INTERFACE_STATS_EMPTY, .wifi = INTERFACE_STATS_EMPTY, \
+ .cellular = INTERFACE_STATS_EMPTY, .all = INTERFACE_STATS_EMPTY, \
+ }
-typedef struct {
- uint32_t num_packets;
- uint32_t num_bytes;
- uint32_t num_losses;
- uint32_t latency_idle;
+typedef struct
+{
+ uint32_t num_packets;
+ uint32_t num_bytes;
+ uint32_t num_losses;
+ uint32_t latency_idle;
} interface_counters_t;
-#define INTERFACE_COUNTERS_NONE { \
- .num_packets = 0, \
- .num_bytes = 0, \
- .num_losses = 0, \
- .latency_idle = 0, \
-}
+#define INTERFACE_COUNTERS_EMPTY \
+ { \
+ .num_packets = 0, .num_bytes = 0, .num_losses = 0, .latency_idle = 0, \
+ }
-typedef struct {
- interface_counters_t wired;
- interface_counters_t wifi;
- interface_counters_t cellular;
- interface_counters_t all;
- uint64_t last_update;
+typedef struct
+{
+ interface_counters_t wired;
+ interface_counters_t wifi;
+ interface_counters_t cellular;
+ interface_counters_t all;
+ uint64_t last_update;
} policy_counters_t;
-#define POLICY_COUNTERS_NONE (policy_counters_t) { \
- .wired = INTERFACE_COUNTERS_NONE, \
- .wifi = INTERFACE_COUNTERS_NONE, \
- .cellular = INTERFACE_COUNTERS_NONE, \
- .all = INTERFACE_COUNTERS_NONE, \
- .last_update = 0, \
-}
+#define POLICY_COUNTERS_EMPTY \
+ (policy_counters_t) \
+ { \
+ .wired = INTERFACE_COUNTERS_EMPTY, .wifi = INTERFACE_COUNTERS_EMPTY, \
+ .cellular = INTERFACE_COUNTERS_EMPTY, .all = INTERFACE_COUNTERS_EMPTY, \
+ .last_update = 0, \
+ }
/* POLICY */
#define APP_NAME_LEN 128
-typedef struct {
- char app_name[APP_NAME_LEN];
- policy_tag_state_t tags[POLICY_TAG_N];
- policy_stats_t stats;
+typedef struct
+{
+ char app_name[APP_NAME_LEN];
+ policy_tag_state_t tags[POLICY_TAG_N];
+ policy_stats_t stats;
} hicn_policy_t;
-static const hicn_policy_t POLICY_NONE = {
+static const hicn_policy_t POLICY_EMPTY = {
.app_name = { 0 },
.tags = {
-#ifdef __ANDROID__
#define _(x, y) { POLICY_STATE_NEUTRAL, 0 },
-#else
-#define _(x, y) [POLICY_TAG_ ## x] = { POLICY_STATE_NEUTRAL, 0 },
-#endif
foreach_policy_tag
#undef _
},
- .stats = POLICY_STATS_NONE,
+ .stats = POLICY_STATS_EMPTY,
};
-
/* POLICY DESCRIPTION */
#define PFX_STRLEN 4 /* eg. /128 */
-typedef struct {
- int family;
- union {
- char ipv4_prefix[INET_ADDRSTRLEN + PFX_STRLEN];
- char ipv6_prefix[INET6_ADDRSTRLEN + PFX_STRLEN];
- };
- hicn_policy_t policy;
+typedef struct
+{
+ int family;
+ union
+ {
+ char ipv4_prefix[INET_ADDRSTRLEN + PFX_STRLEN];
+ char ipv6_prefix[INET6_ADDRSTRLEN + PFX_STRLEN];
+ };
+ hicn_policy_t policy;
} policy_description_t;
#endif /* HICN_POLICY_H */
diff --git a/lib/includes/hicn/protocol/ah.h b/lib/includes/hicn/protocol/ah.h
index 575da80d7..36fd7d509 100644
--- a/lib/includes/hicn/protocol/ah.h
+++ b/lib/includes/hicn/protocol/ah.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -35,19 +35,19 @@
typedef struct
{
- u8 nh; // (to match with reserved in IPSEC AH)
- u8 payloadlen; // Len of signature/HMAC in 4-bytes words (maximum size)
+ u8 nh; // To match with reserved in IPSEC AH
+ // Length of the signature field. Note that the signature might be smaller
+ // than the field: the actual size is computed from the field size and
+ // signaturePadding.
+ u8 payloadlen;
union
{
u16 reserved;
struct
{
- u8 validationAlgorithm; // As defined in parc_SignerAlgorithm.h
- u8 signatureGap; // used to match IPSEC specification and to
- // have the real size of the signature(without
- // padding). It is the result of Maximum
- // signature size - real size
+ u8 validationAlgorithm;
+ u8 signaturePadding;
};
};
union
diff --git a/lib/includes/hicn/protocol/icmp.h b/lib/includes/hicn/protocol/icmp.h
index 36954bb6d..9315e1e56 100644
--- a/lib/includes/hicn/protocol/icmp.h
+++ b/lib/includes/hicn/protocol/icmp.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -34,7 +34,7 @@ typedef struct
u16 csum;
} _icmp_header_t;
-#define ICMP_HDRLEN sizeof(_icmp_header_t)
+#define ICMP_HDRLEN sizeof (_icmp_header_t)
static_assert (EXPECTED_ICMP_HDRLEN == ICMP_HDRLEN,
"Size of ICMP struct does not match its expected size.");
@@ -54,13 +54,13 @@ typedef struct
{
u16 id;
u16 sequence;
- } echo; /* echo datagram */
- u32 gateway; /* gateway address */
+ } echo; /* echo datagram */
+ u32 gateway; /* gateway address */
struct
{
u16 _unused;
u16 mtu;
- } frag; /* path mtu discovery */
+ } frag; /* path mtu discovery */
struct
{
u16 expected_lbl;
@@ -69,7 +69,7 @@ typedef struct
};
} _icmp_wldr_header_t;
-#define ICMPWLDR_HDRLEN sizeof(_icmp_wldr_header_t)
+#define ICMPWLDR_HDRLEN sizeof (_icmp_wldr_header_t)
static_assert (EXPECTED_ICMPWLDR_HDRLEN == ICMPWLDR_HDRLEN,
"Size of ICMPWLDR struct does not match its expected size.");
diff --git a/lib/includes/hicn/protocol/icmprd.h b/lib/includes/hicn/protocol/icmprd.h
index aa1fa01ae..17088c22a 100644
--- a/lib/includes/hicn/protocol/icmprd.h
+++ b/lib/includes/hicn/protocol/icmprd.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -33,12 +33,12 @@ typedef struct
u8 type;
u8 code;
u16 csum;
- ip4_address_t ip;
+ ipv4_address_t ip;
_ipv4_header_t iph;
u8 data[64];
} _icmprd4_header_t;
-#define ICMPRD4_HDRLEN sizeof(_icmprd4_header_t)
+#define ICMPRD4_HDRLEN sizeof (_icmprd4_header_t)
static_assert (EXPECTED_ICMPRD4_HDRLEN == ICMPRD4_HDRLEN,
"Size of ICMPWLDR struct does not match its expected size.");
@@ -53,11 +53,11 @@ typedef struct
u8 code;
u16 csum;
u32 res;
- ip6_address_t tgt;
- ip6_address_t dst;
+ ipv6_address_t tgt;
+ ipv6_address_t dst;
} _icmprd_header_t;
-#define ICMPRD_HDRLEN sizeof(_icmprd_header_t)
+#define ICMPRD_HDRLEN sizeof (_icmprd_header_t)
static_assert (EXPECTED_ICMPRD_HDRLEN == ICMPRD_HDRLEN,
"Size of ICMPWLDR struct does not match its expected size.");
diff --git a/lib/includes/hicn/protocol/ipv4.h b/lib/includes/hicn/protocol/ipv4.h
index 8a5b6683b..89435b516 100644
--- a/lib/includes/hicn/protocol/ipv4.h
+++ b/lib/includes/hicn/protocol/ipv4.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,9 +16,10 @@
#ifndef HICN_PROTOCOL_IPV4
#define HICN_PROTOCOL_IPV4
+#include <hicn/util/ip_address.h>
+
#include "../base.h"
#include "../common.h"
-#include "../protocol.h"
/* Headers were adapted from linux' definitions in netinet/ip.h */
@@ -34,11 +35,11 @@ typedef struct
struct
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
- u8 ihl:4;
- u8 version:4;
+ u8 ihl : 4;
+ u8 version : 4;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
- u8 version:4;
- u8 ihl:4;
+ u8 version : 4;
+ u8 ihl : 4;
#else
#error "Unsupported endianness"
#endif
@@ -53,13 +54,14 @@ typedef struct
u8 ttl;
u8 protocol;
u16 csum;
- ip4_address_t saddr;
- ip4_address_t daddr;
+ ipv4_address_t saddr;
+ ipv4_address_t daddr;
} _ipv4_header_t;
-#define ipv4_header_bytes(ipv4_header) (sizeof(u32) * (ipv4_header->version_ihl & 0xf))
+#define ipv4_header_bytes(ipv4_header) \
+ (sizeof (u32) * (ipv4_header->version_ihl & 0xf))
-#define IPV4_HDRLEN sizeof(_ipv4_header_t)
+#define IPV4_HDRLEN sizeof (_ipv4_header_t)
static_assert (EXPECTED_IPV4_HDRLEN == IPV4_HDRLEN,
"Size of IPV4 struct does not match its expected size.");
@@ -70,29 +72,28 @@ static_assert (EXPECTED_IPV4_HDRLEN == IPV4_HDRLEN,
typedef struct
{
- ip4_address_t ip_src;
- ip4_address_t ip_dst;
+ ipv4_address_t ip_src;
+ ipv4_address_t ip_dst;
u8 zero;
u8 protocol;
u16 size;
} ipv4_pseudo_header_t;
-#define IPV4_PSHDRLEN sizeof(ipv4_pseudo_header_t)
+#define IPV4_PSHDRLEN sizeof (ipv4_pseudo_header_t)
static_assert (EXPECTED_IPV4_PSHDRLEN == IPV4_PSHDRLEN,
"Size of IPV4_PSHDR struct does not match its expected size.");
/* Default field values */
-#define IPV4_DEFAULT_VERSION 4
-#define IPV4_DEFAULT_IHL 5
-#define IPV4_DEFAULT_TOS 0
-#define IPV4_DEFAULT_PAYLOAD_LENGTH 0
-#define IPV4_DEFAULT_ID 300
-#define IPV4_DEFAULT_FRAG_OFF 0x000
-#define IPV4_DEFAULT_TTL 64
-#define IPV4_DEFAULT_PROTOCOL IPPROTO_TCP
-#define IPV4_DEFAULT_SRC_IP 0, 0, 0, 0
-#define IPV4_DEFAULT_DST_IP 0, 0, 0, 0
-
+#define IPV4_DEFAULT_VERSION 4
+#define IPV4_DEFAULT_IHL 5
+#define IPV4_DEFAULT_TOS 0
+#define IPV4_DEFAULT_PAYLOAD_LENGTH 0
+#define IPV4_DEFAULT_ID 300
+#define IPV4_DEFAULT_FRAG_OFF 0x000
+#define IPV4_DEFAULT_TTL 64
+#define IPV4_DEFAULT_PROTOCOL IPPROTO_TCP
+#define IPV4_DEFAULT_SRC_IP 0, 0, 0, 0
+#define IPV4_DEFAULT_DST_IP 0, 0, 0, 0
#endif /* HICN_PROTOCOL_IPV4 */
diff --git a/lib/includes/hicn/protocol/ipv6.h b/lib/includes/hicn/protocol/ipv6.h
index 5a83abcae..6e8e30af3 100644
--- a/lib/includes/hicn/protocol/ipv6.h
+++ b/lib/includes/hicn/protocol/ipv6.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,8 @@
#ifndef HICN_PROTOCOL_IPV6_H
#define HICN_PROTOCOL_IPV6_H
+#include <hicn/util/ip_address.h>
+
#include "../common.h"
/*
@@ -25,22 +27,26 @@
typedef struct
{
+#if 0 // TEMPORARY FIX
union
{
struct
{
- u32 version_class_flow; /* version, traffic class and 20 bits of flow-ID */
- u16 len; /* payload length */
- u8 nxt; /* next header */
- u8 hlim; /* hop limit */
+#endif
+ u32 version_class_flow; /* version, traffic class and 20 bits of flow-ID */
+ u16 len; /* payload length */
+ u8 nxt; /* next header */
+ u8 hlim; /* hop limit */
+#if 0
};
u8 vfc; /* 4 bits version, top 4 bits class */
};
- ip6_address_t saddr; /* source address */
- ip6_address_t daddr; /* destination address */
+#endif
+ ipv6_address_t saddr; /* source address */
+ ipv6_address_t daddr; /* destination address */
} _ipv6_header_t;
-#define IPV6_HDRLEN sizeof(_ipv6_header_t)
+#define IPV6_HDRLEN sizeof (_ipv6_header_t)
static_assert (EXPECTED_IPV6_HDRLEN == IPV6_HDRLEN,
"Size of IPV6 struct does not match its expected size.");
@@ -51,23 +57,23 @@ static_assert (EXPECTED_IPV6_HDRLEN == IPV6_HDRLEN,
typedef struct
{
- ip6_address_t ip_src;
- ip6_address_t ip_dst;
+ ipv6_address_t ip_src;
+ ipv6_address_t ip_dst;
u32 size;
u16 zeros;
u8 zero;
u8 protocol;
} ipv6_pseudo_header_t;
-#define IPV6_PSHDRLEN sizeof(ipv6_pseudo_header_t)
+#define IPV6_PSHDRLEN sizeof (ipv6_pseudo_header_t)
static_assert (EXPECTED_IPV6_PSHDRLEN == IPV6_PSHDRLEN,
"Size of IPV6_PSHDR struct does not match its expected size.");
/* Default field values */
-#define IPV6_DEFAULT_VERSION 6
-#define IPV6_DEFAULT_TRAFFIC_CLASS 0
-#define IPV6_DEFAULT_FLOW_LABEL 0
-#define IPV6_DEFAULT_PAYLOAD_LENGTH 0
+#define IPV6_DEFAULT_VERSION 6
+#define IPV6_DEFAULT_TRAFFIC_CLASS 0
+#define IPV6_DEFAULT_FLOW_LABEL 0
+#define IPV6_DEFAULT_PAYLOAD_LENGTH 0
#endif
diff --git a/lib/includes/hicn/protocol/new.h b/lib/includes/hicn/protocol/new.h
new file mode 100644
index 000000000..e688bef21
--- /dev/null
+++ b/lib/includes/hicn/protocol/new.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file protocol/ah.h
+ * @brief AH packet header
+ */
+#ifndef HICN_PROTOCOL_NEW_H
+#define HICN_PROTOCOL_NEW_H
+
+#include "../common.h"
+#include "../name.h"
+
+/*
+ * The length of the new header struct must be 28 bytes.
+ */
+#define EXPECTED_NEW_HDRLEN 32
+
+typedef struct
+{
+ u8 version_reserved;
+ u8 flags;
+ u16 payload_length;
+ u32 lifetime;
+ hicn_ip_address_t prefix;
+ u32 suffix;
+ u32 path_label;
+} _new_header_t;
+
+#define NEW_HDRLEN sizeof (_new_header_t)
+static_assert (EXPECTED_NEW_HDRLEN == NEW_HDRLEN,
+ "Size of new_header Struct does not match its expected size.");
+
+/* TCP flags bit 0 first. */
+#define foreach_hicn_new_flag \
+ _ (SIG) /**< Signature header after. */ \
+ _ (MAN) /**< Payload type is manifest. */ \
+ _ (INT) /**< Packet is interest. */ \
+ _ (LST) /**< Last data. */
+
+enum
+{
+#define _(f) HICN_NEW_FLAG_BIT_##f,
+ foreach_hicn_new_flag
+#undef _
+ HICN_NEW_N_FLAG_BITS,
+};
+
+enum
+{
+#define _(f) HICN_NEW_FLAG_##f = 1 << HICN_NEW_FLAG_BIT_##f,
+ foreach_hicn_new_flag
+#undef _
+};
+
+static inline int
+_get_new_header_version (const _new_header_t *new_hdr)
+{
+ return ((new_hdr->version_reserved >> 4) & 0x0F);
+}
+
+static inline void
+_set_new_header_version (_new_header_t *new_hdr)
+{
+ new_hdr->version_reserved = (0x9 << 4) & 0xF0;
+}
+
+#endif /* HICN_PROTOCOL_NEW_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/includes/hicn/protocol/tcp.h b/lib/includes/hicn/protocol/tcp.h
index 347682299..1731f0c24 100644
--- a/lib/includes/hicn/protocol/tcp.h
+++ b/lib/includes/hicn/protocol/tcp.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -59,55 +59,55 @@ typedef struct
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
struct
{
- u16 reserved:4;
- u16 doff:4;
- u16 fin:1;
- u16 syn:1;
- u16 rst:1;
- u16 psh:1;
- u16 ack:1;
- u16 urg:1;
- u16 ece:1;
- u16 cwr:1;
+ u16 reserved : 4;
+ u16 doff : 4;
+ u16 fin : 1;
+ u16 syn : 1;
+ u16 rst : 1;
+ u16 psh : 1;
+ u16 ack : 1;
+ u16 urg : 1;
+ u16 ece : 1;
+ u16 cwr : 1;
};
struct
- { /* __ denotes unchanged bitfields */
- u16 timescale:4;
- u16 __doff:4;
- u16 __fin:1;
- u16 __syn:1;
- u16 __rst:1;
- u16 sig:1;
- u16 __ack:1;
- u16 man:1;
- u16 id:1;
- u16 __cwr:1;
+ { /* __ denotes unchanged bitfields */
+ u16 timescale : 4;
+ u16 __doff : 4;
+ u16 __fin : 1;
+ u16 __syn : 1;
+ u16 __rst : 1;
+ u16 sig : 1;
+ u16 __ack : 1;
+ u16 man : 1;
+ u16 id : 1;
+ u16 __cwr : 1;
};
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
struct
{
- u16 doff:4;
- u16 reserved:4;
- u16 cwr:1;
- u16 ece:1;
- u16 urg:1;
- u16 ack:1;
- u16 psh:1;
- u16 rst:1;
- u16 syn:1;
- u16 fin:1;
+ u16 doff : 4;
+ u16 reserved : 4;
+ u16 cwr : 1;
+ u16 ece : 1;
+ u16 urg : 1;
+ u16 ack : 1;
+ u16 psh : 1;
+ u16 rst : 1;
+ u16 syn : 1;
+ u16 fin : 1;
};
struct
{
- u16 __doff:4;
- u16 timescale:4;
- u16 __cwr:1;
- u16 id:1 u16 man:1;
- u16 __ack:1;
- u16 sig:1;
- u16 __rst:1;
- u16 __syn:1;
- u16 __fin:1;
+ u16 __doff : 4;
+ u16 timescale : 4;
+ u16 __cwr : 1;
+ u16 id : 1 u16 man : 1;
+ u16 __ack : 1;
+ u16 sig : 1;
+ u16 __rst : 1;
+ u16 __syn : 1;
+ u16 __fin : 1;
};
#endif
};
@@ -124,20 +124,20 @@ typedef struct
};
} _tcp_header_t;
-#define TCP_HDRLEN sizeof(_tcp_header_t)
+#define TCP_HDRLEN sizeof (_tcp_header_t)
static_assert (EXPECTED_TCP_HDRLEN == TCP_HDRLEN,
"Size of TCP struct does not match its expected size.");
/* TCP flags bit 0 first. */
-#define foreach_tcp_flag \
- _ (FIN) /**< No more data from sender. */ \
- _ (SYN) /**< Synchronize sequence numbers. */ \
- _ (RST) /**< Reset the connection. */ \
- _ (PSH) /**< Push function. */ \
- _ (ACK) /**< Ack field significant. */ \
- _ (URG) /**< Urgent pointer field significant. */ \
- _ (ECE) /**< ECN-echo. Receiver got CE packet */ \
- _ (CWR) /**< Sender reduced congestion window */
+#define foreach_tcp_flag \
+ _ (FIN) /**< No more data from sender. */ \
+ _ (SYN) /**< Synchronize sequence numbers. */ \
+ _ (RST) /**< Reset the connection. */ \
+ _ (PSH) /**< Push function. */ \
+ _ (ACK) /**< Ack field significant. */ \
+ _ (URG) /**< Urgent pointer field significant. */ \
+ _ (ECE) /**< ECN-echo. Receiver got CE packet */ \
+ _ (CWR) /**< Sender reduced congestion window */
enum
{
diff --git a/lib/includes/hicn/protocol/udp.h b/lib/includes/hicn/protocol/udp.h
index 75d1ea98c..0e0dddd2c 100644
--- a/lib/includes/hicn/protocol/udp.h
+++ b/lib/includes/hicn/protocol/udp.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,7 +29,7 @@ typedef struct
u16 checksum;
} _udp_header_t;
-#define UDP_HDRLEN sizeof(_udp_header_t)
+#define UDP_HDRLEN sizeof (_udp_header_t)
static_assert (EXPECTED_UDP_HDRLEN == UDP_HDRLEN,
"Size of UDP struct does not match its expected size.");
diff --git a/lib/includes/hicn/strategy.h b/lib/includes/hicn/strategy.h
new file mode 100644
index 000000000..196d59efa
--- /dev/null
+++ b/lib/includes/hicn/strategy.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file strategy.h
+ * \brief hICN forwarding strategy
+ */
+#ifndef HICN_STRATEGY_H
+#define HICN_STRATEGY_H
+
+#include <string.h>
+
+#define foreach_strategy_type \
+ _ (UNDEFINED) \
+ _ (LOADBALANCER) \
+ _ (LOW_LATENCY) \
+ _ (RANDOM) \
+ _ (REPLICATION) \
+ _ (BESTPATH) \
+ _ (LOCAL_REMOTE) \
+ _ (N)
+
+typedef enum
+{
+#define _(x) STRATEGY_TYPE_##x,
+ foreach_strategy_type
+#undef _
+} strategy_type_t;
+
+extern const char *strategy_str[];
+#define strategy_str(x) strategy_str[x]
+
+#define IS_VALID_STRATEGY_TYPE(x) IS_VALID_ENUM_TYPE (STRATEGY_TYPE, x)
+
+static inline strategy_type_t
+strategy_type_from_str (const char *strategy_str)
+{
+#define _(x) \
+ if (strcasecmp (strategy_str, #x) == 0) \
+ return STRATEGY_TYPE_##x; \
+ else
+ foreach_strategy_type
+#undef _
+ return STRATEGY_TYPE_UNDEFINED;
+}
+
+#define STRATEGY_TYPE_VALID(type) \
+ ((type != STRATEGY_TYPE_UNDEFINED) && (type != STRATEGY_TYPE_N))
+
+#define MAX_FWD_STRATEGY_RELATED_PREFIXES 10
+
+#endif /* HICN_STRATEGY_H */
diff --git a/lib/includes/hicn/util/array.h b/lib/includes/hicn/util/array.h
index 56cfcad8b..f56c13140 100644
--- a/lib/includes/hicn/util/array.h
+++ b/lib/includes/hicn/util/array.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,178 +23,167 @@
#include <assert.h>
#include <hicn/util/log.h>
-#include <math.h> // log2
+#include <math.h> // log2
#include <string.h> // memmove
#define BUFSIZE 1024
-typedef int(*cmp_t)(const void * x, const void * y);
-
-#define TYPEDEF_ARRAY_H(NAME, T) \
- \
-typedef struct { \
- size_t size; \
- size_t max_size_log; \
- T * elements; \
-} NAME ## _t; \
- \
-int NAME ## _initialize(NAME ## _t * array); \
- \
-int NAME ## _finalize(NAME ## _t * array); \
- \
-NAME ## _t * NAME ## _create(); \
- \
-void NAME ## _free(NAME ## _t * array); \
- \
-int NAME ## _add(NAME ## _t * array, T element); \
- \
-int NAME ## _remove_index(NAME ## _t * array, int index, T * element); \
- \
-int NAME ## _remove(NAME ## _t * array, const T search, T * element); \
- \
-int NAME ## _get(const NAME ## _t * array, const T search, T * element); \
- \
-int NAME ## _get_index(const NAME ## _t * array, int index, T * element); \
- \
-int NAME ## _get_elements(const NAME ## _t * array, T ** elements); \
- \
-size_t NAME ## _len(const NAME ## _t * array);
-
+#define TYPEDEF_ARRAY_H(NAME, T) \
+ \
+ typedef struct \
+ { \
+ size_t size; \
+ size_t max_size_log; \
+ T *elements; \
+ } NAME##_t; \
+ \
+ int NAME##_initialize (NAME##_t *array); \
+ \
+ int NAME##_finalize (NAME##_t *array); \
+ \
+ NAME##_t *NAME##_create (); \
+ \
+ void NAME##_free (NAME##_t *array); \
+ \
+ int NAME##_add (NAME##_t *array, T element); \
+ \
+ int NAME##_remove_index (NAME##_t *array, int index, T *element); \
+ \
+ int NAME##_remove (NAME##_t *array, const T search, T *element); \
+ \
+ int NAME##_get (const NAME##_t *array, const T search, T *element); \
+ \
+ int NAME##_get_index (const NAME##_t *array, int index, T *element); \
+ \
+ int NAME##_get_elements (const NAME##_t *array, T **elements); \
+ \
+ size_t NAME##_len (const NAME##_t *array);
#define ARRAY_MAX_SIZE_LOG_INIT 0
-#define TYPEDEF_ARRAY(NAME, T, CMP, SNPRINTF) \
-int \
-NAME ## _initialize(NAME ## _t * array) \
-{ \
- array->max_size_log = ARRAY_MAX_SIZE_LOG_INIT; \
- array->size = 0; \
- if (array->max_size_log == 0) { \
- array->elements = NULL; \
- return 0; \
- } \
- array->elements = malloc((1 << array->max_size_log) * sizeof(T)); \
- if (!array->elements) \
- return -1; \
- return 0; \
-} \
- \
-int \
-NAME ## _finalize(NAME ## _t * array) \
-{ \
- for (unsigned i = 0; i < array->size; i++) { \
- NAME ## _remove_index(array, i, NULL); \
- } \
- return 0; \
-} \
- \
-NAME ## _t * \
-NAME ## _create() \
-{ \
- NAME ## _t * array = malloc(sizeof(NAME ## _t)); \
- if (!array) \
- goto ERR_MALLOC; \
- \
- if (NAME ## _initialize(array) < 0) \
- goto ERR_INITIALIZE; \
- \
- return array; \
- \
-ERR_INITIALIZE: \
- free(array); \
-ERR_MALLOC: \
- return NULL; \
-} \
- \
-void \
-NAME ## _free(NAME ## _t * array) \
-{ \
- NAME ## _finalize(array); \
- free(array->elements); \
- free(array); \
-} \
- \
-int \
-NAME ## _add(NAME ## _t * array, T element) \
-{ \
- /* Ensure sufficient space for next addition */ \
- size_t new_size_log = (array->size > 0) ? log2(array->size)+1 : 1; \
- if (new_size_log > array->max_size_log) { \
- array->max_size_log = new_size_log; \
- array->elements = realloc(array->elements, \
- (1 << new_size_log) * sizeof(T)); \
- } \
- \
- if (!array->elements) \
- goto ERR_REALLOC; \
- \
- array->elements[array->size++] = element; \
- return 0; \
- \
-ERR_REALLOC: \
- return -1; \
-} \
- \
-int \
-NAME ## _remove_index(NAME ## _t * array, int index, T * element) \
-{ \
- if (index > NAME ## _len(array)) \
- return -1; \
- if (element) \
- *element = array->elements[index]; \
- if (index < array->size) \
- memmove(array->elements + index, array->elements + index + 1, \
- array->size - index); \
- array->size--; \
- return 0; \
-} \
- \
-int \
-NAME ## _remove(NAME ## _t * array, const T search, T * element) \
-{ \
- for (unsigned i = 0; i < array->size; i++) { \
- if (CMP(search, array->elements[i]) == 0) \
- return facelet_array_remove_index(array, i, element); \
- } \
- /* Not found */ \
- if (element) \
- *element = NULL; \
- return 0; \
-} \
- \
-int \
-NAME ## _get(const NAME ## _t * array, const T search, T * element) \
-{ \
- assert(element); \
- for (unsigned i = 0; i < array->size; i++) \
- if (CMP(search, array->elements[i]) == 0) { \
- *element = array->elements[i]; \
- return 0; \
- } \
- /* Not found */ \
- *element = NULL; \
- return 0; \
-} \
- \
-int \
-NAME ## _get_index(const NAME ## _t * array, int index, T * element) \
-{ \
- assert(element); \
- *element = array->elements[index]; \
- return 0; \
-} \
- \
-int \
-NAME ## _get_elements(const NAME ## _t * array, T ** elements) \
-{ \
- *elements = array->elements; \
- return 0; \
-} \
- \
-size_t \
-NAME ## _len(const NAME ## _t * array) \
-{ \
- return array->size; \
-}
+#define TYPEDEF_ARRAY(NAME, T, CMP, SNPRINTF) \
+ int NAME##_initialize (NAME##_t *array) \
+ { \
+ array->max_size_log = ARRAY_MAX_SIZE_LOG_INIT; \
+ array->size = 0; \
+ if (array->max_size_log == 0) \
+ { \
+ array->elements = NULL; \
+ return 0; \
+ } \
+ array->elements = malloc ((1 << array->max_size_log) * sizeof (T)); \
+ if (!array->elements) \
+ return -1; \
+ return 0; \
+ } \
+ \
+ int NAME##_finalize (NAME##_t *array) \
+ { \
+ for (unsigned i = 0; i < array->size; i++) \
+ { \
+ NAME##_remove_index (array, i, NULL); \
+ } \
+ return 0; \
+ } \
+ \
+ NAME##_t *NAME##_create () \
+ { \
+ NAME##_t *array = malloc (sizeof (NAME##_t)); \
+ if (!array) \
+ goto ERR_MALLOC; \
+ \
+ if (NAME##_initialize (array) < 0) \
+ goto ERR_INITIALIZE; \
+ \
+ return array; \
+ \
+ ERR_INITIALIZE: \
+ free (array); \
+ ERR_MALLOC: \
+ return NULL; \
+ } \
+ \
+ void NAME##_free (NAME##_t *array) \
+ { \
+ NAME##_finalize (array); \
+ free (array->elements); \
+ free (array); \
+ } \
+ \
+ int NAME##_add (NAME##_t *array, T element) \
+ { \
+ /* Ensure sufficient space for next addition */ \
+ size_t new_size_log = (array->size > 0) ? log2 (array->size) + 1 : 1; \
+ if (new_size_log > array->max_size_log) \
+ { \
+ array->max_size_log = new_size_log; \
+ array->elements = \
+ realloc (array->elements, (1 << new_size_log) * sizeof (T)); \
+ } \
+ \
+ if (!array->elements) \
+ goto ERR_REALLOC; \
+ \
+ array->elements[array->size++] = element; \
+ return 0; \
+ \
+ ERR_REALLOC: \
+ return -1; \
+ } \
+ \
+ int NAME##_remove_index (NAME##_t *array, int index, T *element) \
+ { \
+ if (index > NAME##_len (array)) \
+ return -1; \
+ if (element) \
+ *element = array->elements[index]; \
+ if (index < array->size) \
+ memmove (array->elements + index, array->elements + index + 1, \
+ array->size - index); \
+ array->size--; \
+ return 0; \
+ } \
+ \
+ int NAME##_remove (NAME##_t *array, const T search, T *element) \
+ { \
+ for (unsigned i = 0; i < array->size; i++) \
+ { \
+ if (CMP (search, array->elements[i]) == 0) \
+ return NAME##_remove_index (array, i, element); \
+ } \
+ /* Not found */ \
+ if (element) \
+ *element = NULL; \
+ return 0; \
+ } \
+ \
+ int NAME##_get (const NAME##_t *array, const T search, T *element) \
+ { \
+ assert (element); \
+ for (unsigned i = 0; i < array->size; i++) \
+ if (CMP (search, array->elements[i]) == 0) \
+ { \
+ *element = array->elements[i]; \
+ return 0; \
+ } \
+ /* Not found */ \
+ *element = NULL; \
+ return 0; \
+ } \
+ \
+ int NAME##_get_index (const NAME##_t *array, int index, T *element) \
+ { \
+ assert (element); \
+ *element = array->elements[index]; \
+ return 0; \
+ } \
+ \
+ int NAME##_get_elements (const NAME##_t *array, T **elements) \
+ { \
+ *elements = array->elements; \
+ return 0; \
+ } \
+ \
+ size_t NAME##_len (const NAME##_t *array) { return array->size; }
#endif /* UTIL_ARRAY_H */
diff --git a/lib/includes/hicn/util/bitmap.h b/lib/includes/hicn/util/bitmap.h
new file mode 100644
index 000000000..d83c838b7
--- /dev/null
+++ b/lib/includes/hicn/util/bitmap.h
@@ -0,0 +1,332 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file bitmap.h
+ * \brief Bitmap
+ *
+ * A bitmap is implemented as a wrapper over a vector made of bit elements
+ */
+
+#ifndef UTIL_BITMAP_H
+#define UTIL_BITMAP_H
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/param.h> // MIN, MAX
+
+#include <hicn/common.h>
+#include <hicn/util/vector.h>
+
+typedef hicn_uword bitmap_t;
+
+#define WORD_WIDTH (sizeof (bitmap_t) * 8)
+
+#define WORD_WIDTH (sizeof (bitmap_t) * 8)
+#define BITMAP_WIDTH(bitmap) (sizeof ((bitmap)[0]) * 8)
+#define BITMAP_INVALID_INDEX ((uint32_t) (~0))
+
+static inline int
+hicn_get_lowest_set_bit_index (hicn_uword w)
+{
+ return hicn_uword_bits > 32 ? __builtin_ctzll (w) : __builtin_ctz (w);
+}
+
+/**
+ * @brief Allocate and initialize a bitmap
+ *
+ * @param[in,out] bitmap Bitmap to allocate and initialize
+ * @param[in] max_size Bitmap max_size
+ */
+#define bitmap_init(bitmap, init_size, max_size) \
+ vector_init ( \
+ bitmap, next_pow2 ((init_size) / BITMAP_WIDTH (bitmap)), \
+ max_size == 0 ? 0 : next_pow2 ((max_size) / BITMAP_WIDTH (bitmap)))
+
+/*
+ * @brief Ensures a bitmap is sufficiently large to hold an element at the
+ * given position.
+ *
+ * @param[in] bitmap The bitmap for which to validate the position.
+ * @param[in] pos The position to validate.
+ *
+ * NOTE:
+ * - This function should always be called before writing to a bitmap element
+ * to eventually make room for it (the bitmap will eventually be resized).
+ */
+static inline int
+bitmap_ensure_pos (bitmap_t **bitmap, off_t pos)
+{
+ size_t offset = pos / BITMAP_WIDTH (*bitmap);
+ return vector_ensure_pos (*bitmap, offset);
+}
+
+/**
+ * @brief Returns the allocated size of a bitmap.
+ *
+ * @see listener_table_get_by_id
+ */
+#define bitmap_get_alloc_size(bitmap) vector_get_alloc_size (bitmap)
+
+/**
+ * @brief Retrieve the state of the i-th bit in the bitmap.
+ *
+ * @param[in] bitmap The bitmap to access.
+ * @param[in] i The bit position.
+ */
+static inline int
+_bitmap_get (const bitmap_t *bitmap, off_t i)
+{
+ size_t offset = i / BITMAP_WIDTH (bitmap);
+ assert (offset < bitmap_get_alloc_size (bitmap));
+ size_t pos = i % BITMAP_WIDTH (bitmap);
+ return (bitmap[offset] >> pos) & 1;
+}
+
+/**
+ * @brief Retrieve the state of the i-th bit in the bitmap.
+ * Does not sanity check the position.
+ *
+ * @param[in] bitmap The bitmap to access.
+ * @param[in] i The bit position.
+ */
+static inline int
+_bitmap_get_no_check (const bitmap_t *bitmap, off_t i)
+{
+ size_t offset = i / BITMAP_WIDTH (bitmap);
+ size_t pos = i % BITMAP_WIDTH (bitmap);
+ return (bitmap[offset] >> pos) & 1;
+}
+
+/*
+ * @brief Returns whether the i-th bit is set (equal to 1) in a bitmap.
+ *
+ * @param[in] bitmap The bitmap to access.
+ * @param[in] i The bit position.
+ *
+ * @return bool
+ */
+#define bitmap_is_set(bitmap, i) (_bitmap_get ((bitmap), (i)) == 1)
+#define bitmap_is_unset(bitmap, i) (_bitmap_get ((bitmap), (i)) == 0)
+
+#define bitmap_is_set_no_check(bitmap, i) \
+ (_bitmap_get_no_check ((bitmap), (i)) == 1)
+#define bitmap_is_unset_no_check(bitmap, i) \
+ (_bitmap_get_no_check ((bitmap), (i)) == 0)
+
+static inline int
+_bitmap_set_no_check (bitmap_t *bitmap, off_t i)
+{
+ size_t offset = i / BITMAP_WIDTH (bitmap);
+ size_t pos = i % BITMAP_WIDTH (bitmap);
+ bitmap[offset] |= (hicn_uword) (1) << pos;
+ return 0;
+}
+
+static inline int
+_bitmap_set (bitmap_t **bitmap_ptr, off_t i)
+{
+ if (bitmap_ensure_pos (bitmap_ptr, i) < 0)
+ return -1;
+
+ bitmap_t *bitmap = *bitmap_ptr;
+ return _bitmap_set_no_check (bitmap, i);
+}
+
+/*
+ * @brief Set i-th bit to 1 in a bitmap. Reallocate the vector if the bit
+ * position is greater than the vector length.
+ *
+ * @param[in] bitmap The bitmap to access.
+ * @param[in] i The bit position.
+ *
+ * @return bool
+ */
+#define bitmap_set(bitmap, i) _bitmap_set ((bitmap_t **) &bitmap, i)
+
+/*
+ * @brief Set i-th bit to 1 in a bitmap. Unsafe version, does not check
+ * boundaries.
+ *
+ * @param[in] bitmap The bitmap to access.
+ * @param[in] i The bit position.
+ *
+ * @return bool
+ */
+#define bitmap_set_no_check(bitmap, i) _bitmap_set_no_check (bitmap, i)
+
+#define bitmap_unset(bitmap, i) _bitmap_unset (bitmap, i, 1)
+#define bitmap_unset_no_check(bitmap, i) _bitmap_unset (bitmap, i, 0)
+
+static inline int
+_bitmap_unset (bitmap_t *bitmap, off_t i, int check)
+{
+ if (check && bitmap_ensure_pos (&bitmap, i) < 0)
+ return -1;
+ size_t offset = i / BITMAP_WIDTH (bitmap);
+ size_t pos = i % BITMAP_WIDTH (bitmap);
+ bitmap[offset] &= ~((hicn_uword) (1) << pos);
+ return 0;
+}
+
+static inline int
+bitmap_set_range (bitmap_t *bitmap, off_t from, off_t to)
+{
+ assert (from <= to);
+ ssize_t offset_from = from / BITMAP_WIDTH (bitmap);
+ ssize_t offset_to = to / BITMAP_WIDTH (bitmap);
+ size_t pos_from = from % BITMAP_WIDTH (bitmap);
+ size_t pos_to = to % BITMAP_WIDTH (bitmap);
+
+ /*
+ * First block initialization is needed if <from> is not aligned with the
+ * bitmap element size or if to is within the same one.
+ */
+ if ((pos_from != 0) ||
+ ((offset_to == offset_from) && (pos_to != BITMAP_WIDTH (bitmap) - 1)))
+ {
+ size_t from_end = MIN (to, (offset_from + 1) * BITMAP_WIDTH (bitmap));
+ for (size_t k = from; k < from_end; k++)
+ {
+ if (bitmap_set (bitmap, k) < 0)
+ goto END;
+ }
+ }
+
+ /*
+ * Second block is needed if <to> is not aligned with the bitmap element
+ * size
+ */
+ if ((pos_to != BITMAP_WIDTH (bitmap) - 1) && (offset_to != offset_from))
+ {
+ size_t to_start = MAX (from, offset_to * BITMAP_WIDTH (bitmap));
+ for (size_t k = to_start; k < (size_t) to; k++)
+ {
+ if (bitmap_set (bitmap, k) < 0)
+ goto END;
+ }
+ }
+
+ if (pos_from != 0)
+ offset_from += 1;
+ if (pos_to != BITMAP_WIDTH (bitmap) - 1)
+ offset_to -= 1;
+
+ /*
+ * We need to cover both elements at position offset_from and offset_to
+ * provided that offset_from is not bigger
+ */
+ if (offset_to >= offset_from)
+ {
+ memset (&bitmap[offset_from], 0xFF,
+ (offset_to - offset_from + 1) * sizeof (bitmap[0]));
+ }
+
+ return 0;
+
+END:
+ return -1;
+}
+
+#define bitmap_set_to(bitmap, to) bitmap_set_range ((bitmap), 0, (to))
+
+#define bitmap_free(bitmap) vector_free (bitmap)
+
+static inline hicn_uword
+bitmap_next_set_no_check (const bitmap_t *bitmap, hicn_uword i, size_t length)
+{
+ hicn_uword pos = i / WORD_WIDTH;
+ hicn_uword offset = i % WORD_WIDTH;
+ hicn_uword tmp;
+ hicn_uword mask = ~((1ULL << offset) - 1);
+
+ if (pos < length)
+ {
+ // This will zeroes all bits < i
+ tmp = bitmap[pos] & mask;
+ if (tmp)
+ return hicn_get_lowest_set_bit_index (tmp) + pos * WORD_WIDTH;
+
+ for (pos += 1; pos < length; pos++)
+ {
+ tmp = bitmap[pos];
+ if (tmp)
+ return hicn_get_lowest_set_bit_index (tmp) + pos * WORD_WIDTH;
+ }
+ }
+
+ return BITMAP_INVALID_INDEX;
+}
+
+static inline hicn_uword
+bitmap_next_set (const bitmap_t *bitmap, hicn_uword i)
+{
+ return bitmap_next_set_no_check (bitmap, i, vector_get_alloc_size (bitmap));
+}
+
+static inline hicn_uword
+bitmap_next_unset_no_check (const bitmap_t *bitmap, hicn_uword i,
+ size_t length)
+{
+ hicn_uword pos = i / WORD_WIDTH;
+ hicn_uword offset = i % WORD_WIDTH;
+ hicn_uword tmp;
+ hicn_uword mask = ~((1ULL << offset) - 1);
+
+ if (pos < length)
+ {
+ // This will zeroes all bits < i
+ tmp = ~bitmap[pos] & mask;
+ if (tmp)
+ return hicn_get_lowest_set_bit_index (tmp) + pos * WORD_WIDTH;
+
+ for (pos += 1; pos < length; pos++)
+ {
+ tmp = ~bitmap[pos];
+ if (tmp)
+ return hicn_get_lowest_set_bit_index (tmp) + pos * WORD_WIDTH;
+ }
+ }
+ return BITMAP_INVALID_INDEX;
+}
+
+static inline hicn_uword
+bitmap_next_unset (const bitmap_t *bitmap, hicn_uword i)
+{
+ return bitmap_next_unset_no_check (bitmap, i,
+ vector_get_alloc_size (bitmap));
+}
+
+#define bitmap_first_set(bitmap) bitmap_next_set (bitmap, 0)
+#define bitmap_first_set_no_check(bitmap, size) \
+ bitmap_next_set_no_check (bitmap, 0, size)
+
+#define bitmap_first_unset(bitmap) bitmap_next_unset (bitmap, 0)
+#define bitmap_first_unset_no_check(bitmap, size) \
+ bitmap_next_unset_no_check (bitmap, 0, size)
+
+static inline void
+bitmap_print (const bitmap_t *bitmap, size_t n_words)
+{
+ for (size_t word = 0; word < n_words; word++)
+ {
+ for (int bit = sizeof (hicn_uword) - 1; bit >= 0; bit--)
+ (bitmap_is_set_no_check (&bitmap[word], bit)) ? printf ("1") :
+ printf ("0");
+ }
+}
+
+#endif /* UTIL_BITMAP_H */
diff --git a/lib/includes/hicn/util/hash.h b/lib/includes/hicn/util/hash.h
new file mode 100644
index 000000000..8dbe0d680
--- /dev/null
+++ b/lib/includes/hicn/util/hash.h
@@ -0,0 +1,368 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * \file hash.h
+ * \brief Simple non-cryptographic hash implementation.
+ *
+ * Two helpers are provided :
+ * hash(buf, len) : hash a buffer <buf> of length <len>
+ * hash_struct(buf) : hash a buffer corresponding to an allocated struct
+ *
+ * This file consists in excerpts from Jenkins hash (public domain).
+ * http://www.burtleburtle.net/bob/c/lookup3.c
+ */
+#ifndef UTIL_HASH_H
+#define UTIL_HASH_H
+
+#include <stdint.h>
+#include <stddef.h> // size_t
+
+#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
+ __BYTE_ORDER == __LITTLE_ENDIAN) || \
+ (defined(i386) || defined(__i386__) || defined(__i486__) || \
+ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
+#define HASH_LITTLE_ENDIAN 1
+#define HASH_BIG_ENDIAN 0
+#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
+ __BYTE_ORDER == __BIG_ENDIAN) || \
+ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
+#define HASH_LITTLE_ENDIAN 0
+#define HASH_BIG_ENDIAN 1
+#else
+#define HASH_LITTLE_ENDIAN 0
+#define HASH_BIG_ENDIAN 0
+#endif
+
+#define hashsize(n) ((uint32_t) 1 << (n))
+#define hashmask(n) (hashsize (n) - 1)
+#define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
+
+#define mix(a, b, c) \
+ { \
+ a -= c; \
+ a ^= rot (c, 4); \
+ c += b; \
+ b -= a; \
+ b ^= rot (a, 6); \
+ a += c; \
+ c -= b; \
+ c ^= rot (b, 8); \
+ b += a; \
+ a -= c; \
+ a ^= rot (c, 16); \
+ c += b; \
+ b -= a; \
+ b ^= rot (a, 19); \
+ a += c; \
+ c -= b; \
+ c ^= rot (b, 4); \
+ b += a; \
+ }
+
+#define final(a, b, c) \
+ { \
+ c ^= b; \
+ c -= rot (b, 14); \
+ a ^= c; \
+ a -= rot (c, 11); \
+ b ^= a; \
+ b -= rot (a, 25); \
+ c ^= b; \
+ c -= rot (b, 16); \
+ a ^= c; \
+ a -= rot (c, 4); \
+ b ^= a; \
+ b -= rot (a, 14); \
+ c ^= b; \
+ c -= rot (b, 24); \
+ }
+
+static inline uint32_t
+hashlittle (const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a, b, c; /* internal state */
+ union
+ {
+ const void *ptr;
+ size_t i;
+ } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t) length) + initval;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0))
+ {
+ const uint32_t *k = (const uint32_t *) key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c)
+ */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix (a, b, c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial)
+ * block */
+ /*
+ * "k[2]&0xffffff" actually reads beyond the end of the string, but
+ * then masks off the part it's not allowed to read. Because the
+ * string is aligned, the masked-off tail is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch (length)
+ {
+ case 12:
+ c += k[2];
+ b += k[1];
+ a += k[0];
+ break;
+ case 11:
+ c += k[2] & 0xffffff;
+ b += k[1];
+ a += k[0];
+ break;
+ case 10:
+ c += k[2] & 0xffff;
+ b += k[1];
+ a += k[0];
+ break;
+ case 9:
+ c += k[2] & 0xff;
+ b += k[1];
+ a += k[0];
+ break;
+ case 8:
+ b += k[1];
+ a += k[0];
+ break;
+ case 7:
+ b += k[1] & 0xffffff;
+ a += k[0];
+ break;
+ case 6:
+ b += k[1] & 0xffff;
+ a += k[0];
+ break;
+ case 5:
+ b += k[1] & 0xff;
+ a += k[0];
+ break;
+ case 4:
+ a += k[0];
+ break;
+ case 3:
+ a += k[0] & 0xffffff;
+ break;
+ case 2:
+ a += k[0] & 0xffff;
+ break;
+ case 1:
+ a += k[0] & 0xff;
+ break;
+ case 0:
+ return c; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ k8 = (const uint8_t *) k;
+ switch (length)
+ {
+ case 12:
+ c += k[2];
+ b += k[1];
+ a += k[0];
+ break;
+ case 11:
+ c += ((uint32_t) k8[10]) << 16; /* fall through */
+ case 10:
+ c += ((uint32_t) k8[9]) << 8; /* fall through */
+ case 9:
+ c += k8[8]; /* fall through */
+ case 8:
+ b += k[1];
+ a += k[0];
+ break;
+ case 7:
+ b += ((uint32_t) k8[6]) << 16; /* fall through */
+ case 6:
+ b += ((uint32_t) k8[5]) << 8; /* fall through */
+ case 5:
+ b += k8[4]; /* fall through */
+ case 4:
+ a += k[0];
+ break;
+ case 3:
+ a += ((uint32_t) k8[2]) << 16; /* fall through */
+ case 2:
+ a += ((uint32_t) k8[1]) << 8; /* fall through */
+ case 1:
+ a += k8[0];
+ break;
+ case 0:
+ return c;
+ }
+
+#endif /* !valgrind */
+ }
+ else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0))
+ {
+ const uint16_t *k = (const uint16_t *) key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing
+ */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t) k[1]) << 16);
+ b += k[2] + (((uint32_t) k[3]) << 16);
+ c += k[4] + (((uint32_t) k[5]) << 16);
+ mix (a, b, c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block
+ */
+ k8 = (const uint8_t *) k;
+ switch (length)
+ {
+ case 12:
+ c += k[4] + (((uint32_t) k[5]) << 16);
+ b += k[2] + (((uint32_t) k[3]) << 16);
+ a += k[0] + (((uint32_t) k[1]) << 16);
+ break;
+ case 11:
+ c += ((uint32_t) k8[10]) << 16; /* fall through */
+ case 10:
+ c += k[4];
+ b += k[2] + (((uint32_t) k[3]) << 16);
+ a += k[0] + (((uint32_t) k[1]) << 16);
+ break;
+ case 9:
+ c += k8[8]; /* fall through */
+ case 8:
+ b += k[2] + (((uint32_t) k[3]) << 16);
+ a += k[0] + (((uint32_t) k[1]) << 16);
+ break;
+ case 7:
+ b += ((uint32_t) k8[6]) << 16; /* fall through */
+ case 6:
+ b += k[2];
+ a += k[0] + (((uint32_t) k[1]) << 16);
+ break;
+ case 5:
+ b += k8[4]; /* fall through */
+ case 4:
+ a += k[0] + (((uint32_t) k[1]) << 16);
+ break;
+ case 3:
+ a += ((uint32_t) k8[2]) << 16; /* fall through */
+ case 2:
+ a += k[0];
+ break;
+ case 1:
+ a += k8[0];
+ break;
+ case 0:
+ return c; /* zero length requires no mixing */
+ }
+ }
+ else
+ { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *) key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c)
+ */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t) k[1]) << 8;
+ a += ((uint32_t) k[2]) << 16;
+ a += ((uint32_t) k[3]) << 24;
+ b += k[4];
+ b += ((uint32_t) k[5]) << 8;
+ b += ((uint32_t) k[6]) << 16;
+ b += ((uint32_t) k[7]) << 24;
+ c += k[8];
+ c += ((uint32_t) k[9]) << 8;
+ c += ((uint32_t) k[10]) << 16;
+ c += ((uint32_t) k[11]) << 24;
+ mix (a, b, c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c)
+ */
+ switch (length) /* all the case statements fall through */
+ {
+ case 12:
+ c += ((uint32_t) k[11]) << 24;
+ case 11:
+ c += ((uint32_t) k[10]) << 16;
+ case 10:
+ c += ((uint32_t) k[9]) << 8;
+ case 9:
+ c += k[8];
+ case 8:
+ b += ((uint32_t) k[7]) << 24;
+ case 7:
+ b += ((uint32_t) k[6]) << 16;
+ case 6:
+ b += ((uint32_t) k[5]) << 8;
+ case 5:
+ b += k[4];
+ case 4:
+ a += ((uint32_t) k[3]) << 24;
+ case 3:
+ a += ((uint32_t) k[2]) << 16;
+ case 2:
+ a += ((uint32_t) k[1]) << 8;
+ case 1:
+ a += k[0];
+ break;
+ case 0:
+ return c;
+ }
+ }
+
+ final (a, b, c);
+ return c;
+}
+
+/* Helpers */
+
+#define HASH_INITVAL 1
+//#define hash(buf, len) (hash_t)hashlittle(buf, len, HASH_INITVAL)
+#define hash(buf, len) hashlittle (buf, len, HASH_INITVAL)
+#define hash_struct(buf) hash (buf, sizeof (*buf))
+
+#define str_hash(str) (hash (str, strlen (str)))
+#define str_hash_eq(a, b) (str_hash (b) - str_hash (a))
+
+#endif /* UTIL_JENKINS_HASH_H */
diff --git a/lib/includes/hicn/util/ip_address.h b/lib/includes/hicn/util/ip_address.h
index 4facd9ad0..979efaa40 100644
--- a/lib/includes/hicn/util/ip_address.h
+++ b/lib/includes/hicn/util/ip_address.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,10 +20,9 @@
#ifndef UTIL_IP_ADDRESS_H
#define UTIL_IP_ADDRESS_H
-
#ifdef __APPLE__
#include <libkern/OSByteOrder.h>
-#define __bswap_constant_32(x) OSSwapInt32(x)
+#define __bswap_constant_32(x) OSSwapInt32 (x)
#include <machine/endian.h>
#else
#ifdef __ANDROID__
@@ -33,10 +32,11 @@
#endif
#include <errno.h>
+#include <assert.h>
#ifndef _WIN32
-#include <netinet/in.h> // struct sockadd
-#include <arpa/inet.h> // inet_ntop
-#include <netdb.h> // struct addrinfo
+#include <netinet/in.h> // struct sockadd
+#include <arpa/inet.h> // inet_ntop
+#include <netdb.h> // struct addrinfo
#endif
#include <stdbool.h>
#include <stdlib.h>
@@ -45,11 +45,12 @@
#include "types.h"
-#define bytes_to_bits(x) (x * 8)
-#define IPV6_ADDR_LEN 16 /* bytes */
-#define IPV4_ADDR_LEN 4 /* bytes */
-#define IPV6_ADDR_LEN_BITS bytes_to_bits(IPV6_ADDR_LEN)
-#define IPV4_ADDR_LEN_BITS bytes_to_bits(IPV4_ADDR_LEN)
+#define bytes_to_bits(x) (x * 8)
+#define IPV6_ADDR_LEN 16 /* bytes */
+#define IPV4_ADDR_LEN 4 /* bytes */
+#define IPV6_ADDR_LEN_BITS bytes_to_bits (IPV6_ADDR_LEN)
+#define IPV4_ADDR_LEN_BITS bytes_to_bits (IPV4_ADDR_LEN)
+#define MAX_IPV6_PREFIX_LEN 128
/* Presentation format */
#ifndef INET_ADDRSTRLEN
@@ -61,29 +62,47 @@
#endif
//#define INET_MAX_ADDRSTRLEN INET6_ADDRSTRLEN
-#define IP_MAX_ADDR_LEN IPV6_ADDR_LEN
+#define IP_ADDRESS_MAX_LEN IPV6_ADDR_LEN
#define DUMMY_PORT 1234
-typedef union {
- struct {
- u32 pad[3];
- union {
- struct in_addr as_inaddr;
- u8 buffer[4];
- u8 as_u8[4];
- u16 as_u16[2];
- u32 as_u32;
- } v4;
- };
- union {
- struct in6_addr as_in6addr;
- u8 buffer[16];
- u8 as_u8[16];
- u16 as_u16[8];
- u32 as_u32[4];
- u64 as_u64[2];
- } v6;
+typedef union
+{
+ struct in_addr as_inaddr;
+ u8 buffer[4];
+ u8 as_u8[4];
+ u16 as_u16[2];
+ u32 as_u32;
+} ipv4_address_t;
+
+static_assert (sizeof (ipv4_address_t) == 4, "");
+
+typedef union __attribute__ ((__packed__))
+{
+ struct in6_addr as_in6addr;
+ u8 buffer[16];
+ u8 as_u8[16];
+ u16 as_u16[8];
+ u32 as_u32[4];
+ u64 as_u64[2];
+} ipv6_address_t;
+
+static_assert (sizeof (ipv6_address_t) == 16, "");
+
+#ifdef HICN_VPP_PLUGIN
+#include <vnet/ip/ip46_address.h>
+static_assert (sizeof (ipv4_address_t) == sizeof (ip4_address_t), "");
+static_assert (sizeof (ipv6_address_t) == sizeof (ip6_address_t), "");
+#endif
+
+typedef union
+{
+ struct
+ {
+ u32 pad[3];
+ ipv4_address_t v4;
+ };
+ ipv6_address_t v6;
#if 0 /* removed as prone to error due to IPv4 padding */
u8 buffer[IP_MAX_ADDR_LEN];
u8 as_u8[IP_MAX_ADDR_LEN];
@@ -91,79 +110,117 @@ typedef union {
u32 as_u32[IP_MAX_ADDR_LEN >> 2];
u64 as_u64[IP_MAX_ADDR_LEN >> 3];
#endif
-} ip_address_t;
+#ifdef HICN_VPP_PLUGIN
+ ip46_address_t as_ip46;
+#endif /* HICN_VPP_PLUGIN */
+} hicn_ip_address_t;
+
+static_assert (sizeof (hicn_ip_address_t) == 16, "");
+
+#define hicn_ip_address_is_v4(ip) \
+ (((ip)->pad[0] | (ip)->pad[1] | (ip)->pad[2]) == 0)
#define MAXSZ_IP4_ADDRESS_ INET_ADDRSTRLEN - 1
#define MAXSZ_IP6_ADDRESS_ INET6_ADDRSTRLEN - 1
-#define MAXSZ_IP_ADDRESS_ MAXSZ_IP6_ADDRESS_
-#define MAXSZ_IP4_ADDRESS MAXSZ_IP4_ADDRESS_ + 1
-#define MAXSZ_IP6_ADDRESS MAXSZ_IP6_ADDRESS_ + 1
-#define MAXSZ_IP_ADDRESS MAXSZ_IP_ADDRESS_ + 1
+#define MAXSZ_IP_ADDRESS_ MAXSZ_IP6_ADDRESS_
+#define MAXSZ_IP4_ADDRESS MAXSZ_IP4_ADDRESS_ + 1
+#define MAXSZ_IP6_ADDRESS MAXSZ_IP6_ADDRESS_ + 1
+#define MAXSZ_IP_ADDRESS MAXSZ_IP_ADDRESS_ + 1
-typedef struct {
+#define IP_ADDRESS_V4_OFFSET_LEN 12
+
+typedef struct
+{
int family;
- ip_address_t address;
+ hicn_ip_address_t address;
u8 len;
-} ip_prefix_t;
+} hicn_ip_prefix_t;
-#define MAXSZ_PREFIX_ MAXSZ_IP_ADDRESS_ + 1 + 3
-#define MAXSZ_PREFIX MAXSZ_PREFIX_ + 1
+#define MAXSZ_IP_PREFIX_ MAXSZ_IP_ADDRESS_ + 1 + 3
+#define MAXSZ_IP_PREFIX MAXSZ_IP_PREFIX_ + 1
-extern const ip_address_t IPV4_LOOPBACK;
-extern const ip_address_t IPV6_LOOPBACK;
-extern const ip_address_t IPV4_ANY;
-extern const ip_address_t IPV6_ANY;
-extern const ip_address_t IP_ADDRESS_EMPTY;
+extern const hicn_ip_address_t IPV4_LOOPBACK;
+extern const hicn_ip_address_t IPV6_LOOPBACK;
+extern const hicn_ip_address_t IPV4_ANY;
+extern const hicn_ip_address_t IPV6_ANY;
-#define IP_ANY(family) (family == AF_INET) ? IPV4_ANY : IPV6_ANY
+extern const ipv4_address_t IP4_ADDRESS_EMPTY;
+extern const ipv6_address_t IP6_ADDRESS_EMPTY;
+extern const hicn_ip_address_t IP_ADDRESS_EMPTY;
+#define IP_ANY(family) (family == AF_INET) ? IPV4_ANY : IPV6_ANY
-#define MAX_PORT 1 << (8 * sizeof(u16))
-#define IS_VALID_PORT(x) ((x > 0) && ((int)x < MAX_PORT))
+#define MAX_PORT 1 << (8 * sizeof (u16))
+#define IS_VALID_PORT(x) ((x > 0) && ((int) x < MAX_PORT))
#define MAXSZ_PORT_ 5
-#define MAXSZ_PORT MAXSZ_PORT_ + 1
+#define MAXSZ_PORT MAXSZ_PORT_ + 1
#define IS_VALID_FAMILY(x) ((x == AF_INET) || (x == AF_INET6))
/* IP address */
-
-int ip_address_get_family (const char * ip_address);
-int ip_address_len (int family);
-const u8 * ip_address_get_buffer(const ip_address_t * ip_address, int family);
-int ip_address_ntop (const ip_address_t * ip_address, char *dst,
- const size_t len, int family);
-int ip_address_pton (const char *ip_address_str, ip_address_t * ip_address);
-int ip_address_snprintf(char * s, size_t size, const ip_address_t * ip_address,
- int family);
-int ip_address_to_sockaddr(const ip_address_t * ip_address, struct sockaddr *sa,
- int family);
-int ip_address_cmp(const ip_address_t * ip1, const ip_address_t * ip2, int family);
-int ip_address_empty(const ip_address_t * ip);
+int hicn_ip_address_get_family (const hicn_ip_address_t *address);
+int hicn_ip_address_str_get_family (const char *ip_address);
+int hicn_ip_address_len (int family);
+int hicn_ip_address_get_len (const hicn_ip_address_t *ip_address);
+
+int hicn_ip_address_get_len_bits (const hicn_ip_address_t *ip_address);
+const u8 *hicn_ip_address_get_buffer (const hicn_ip_address_t *ip_address,
+ int family);
+int hicn_ip_address_ntop (const hicn_ip_address_t *ip_address, char *dst,
+ const size_t len, int family);
+int hicn_ip_address_pton (const char *ip_address_str,
+ hicn_ip_address_t *ip_address);
+int hicn_ip_address_snprintf (char *s, size_t size,
+ const hicn_ip_address_t *ip_address);
+int hicn_ip_address_to_sockaddr (const hicn_ip_address_t *ip_address,
+ struct sockaddr *sa, int family);
+int hicn_ip_address_cmp (const hicn_ip_address_t *ip1,
+ const hicn_ip_address_t *ip2);
+bool hicn_ip_address_equals (const hicn_ip_address_t *ip1,
+ const hicn_ip_address_t *ip2);
+int hicn_ip_address_empty (const hicn_ip_address_t *ip);
+
+uint8_t hicn_ip_address_get_bit (const hicn_ip_address_t *address,
+ uint8_t pos);
+
+bool hicn_ip_address_match_family (const hicn_ip_address_t *address,
+ int family);
+
+uint32_t hicn_ip_address_get_hash (const hicn_ip_address_t *address);
+
+void hicn_ip_address_clear (hicn_ip_address_t *address);
/* Prefix */
-int ip_prefix_pton (const char *ip_address_str, ip_prefix_t * ip_prefix);
-int ip_prefix_ntop_short (const ip_prefix_t * ip_prefix, char *dst, size_t size);
-int ip_prefix_ntop (const ip_prefix_t * ip_prefix, char *dst, size_t size);
-int ip_prefix_len (const ip_prefix_t * prefix);
-bool ip_prefix_empty (const ip_prefix_t * prefix);
-int ip_prefix_to_sockaddr(const ip_prefix_t * prefix, struct sockaddr *sa);
-int ip_prefix_cmp(const ip_prefix_t * prefix1, const ip_prefix_t * prefix2);
+int hicn_ip_prefix_pton (const char *ip_address_str,
+ hicn_ip_prefix_t *hicn_ip_prefix);
+int hicn_ip_prefix_ntop_short (const hicn_ip_prefix_t *hicn_ip_prefix,
+ char *dst, size_t size);
+int hicn_ip_prefix_ntop (const hicn_ip_prefix_t *hicn_ip_prefix, char *dst,
+ size_t size);
+int hicn_ip_prefix_snprintf (char *s, size_t size,
+ const hicn_ip_prefix_t *prefix);
+int hicn_ip_prefix_len (const hicn_ip_prefix_t *prefix);
+bool hicn_ip_prefix_empty (const hicn_ip_prefix_t *prefix);
+int hicn_ip_prefix_to_sockaddr (const hicn_ip_prefix_t *prefix,
+ struct sockaddr *sa);
+int hicn_ip_prefix_cmp (const hicn_ip_prefix_t *prefix1,
+ const hicn_ip_prefix_t *prefix2);
/* URL */
#define MAXSZ_PROTO_ 8 /* inetX:// */
-#define MAXSZ_PROTO MAXSZ_PROTO_ + NULLTERM
+#define MAXSZ_PROTO MAXSZ_PROTO_ + NULLTERM
#define MAXSZ_URL4_ MAXSZ_PROTO_ + MAXSZ_IP4_ADDRESS_ + MAXSZ_PORT_
#define MAXSZ_URL6_ MAXSZ_PROTO_ + MAXSZ_IP6_ADDRESS_ + MAXSZ_PORT_
-#define MAXSZ_URL_ MAXSZ_URL6_
-#define MAXSZ_URL4 MAXSZ_URL4_ + NULLTERM
-#define MAXSZ_URL6 MAXSZ_URL6_ + NULLTERM
-#define MAXSZ_URL MAXSZ_URL_ + NULLTERM
+#define MAXSZ_URL_ MAXSZ_URL6_
+#define MAXSZ_URL4 MAXSZ_URL4_ + NULLTERM
+#define MAXSZ_URL6 MAXSZ_URL6_ + NULLTERM
+#define MAXSZ_URL MAXSZ_URL_ + NULLTERM
-int url_snprintf(char * s, size_t size, int family,
- const ip_address_t * ip_address, u16 port);
+int url_snprintf (char *s, size_t size, const hicn_ip_address_t *ip_address,
+ u16 port);
#endif /* UTIL_IP_ADDRESS_H */
diff --git a/lib/includes/hicn/util/khash.h b/lib/includes/hicn/util/khash.h
new file mode 100644
index 000000000..17401091f
--- /dev/null
+++ b/lib/includes/hicn/util/khash.h
@@ -0,0 +1,826 @@
+/* The MIT License
+
+ Copyright (c) 2008, 2009, 2011 by Attractive Chaos <attractor@live.co.uk>
+
+ 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.
+*/
+
+/*
+ An example:
+
+#include "khash.h"
+KHASH_MAP_INIT_INT(32, char)
+int main() {
+ int ret, is_missing;
+ khiter_t k;
+ khash_t(32) *h = kh_init(32);
+ k = kh_put(32, h, 5, &ret);
+ kh_value(h, k) = 10;
+ k = kh_get(32, h, 10);
+ is_missing = (k == kh_end(h));
+ k = kh_get(32, h, 5);
+ kh_del(32, h, k);
+ for (k = kh_begin(h); k != kh_end(h); ++k)
+ if (kh_exist(h, k)) kh_value(h, k) = 1;
+ kh_destroy(32, h);
+ return 0;
+}
+*/
+
+/*
+ 2013-05-02 (0.2.8):
+
+ * Use quadratic probing. When the capacity is power of 2, stepping
+ function i*(i+1)/2 guarantees to traverse each bucket. It is better than
+ double hashing on cache performance and is more robust than linear probing.
+
+ In theory, double hashing should be more robust than quadratic
+ probing. However, my implementation is probably not for large hash tables,
+ because the second hash function is closely tied to the first hash function,
+ which reduce the effectiveness of double hashing.
+
+ Reference: http://research.cs.vt.edu/AVresearch/hashing/quadratic.php
+
+ 2011-12-29 (0.2.7):
+
+ * Minor code clean up; no actual effect.
+
+ 2011-09-16 (0.2.6):
+
+ * The capacity is a power of 2. This seems to dramatically improve the
+ speed for simple keys. Thank Zilong Tan for the suggestion.
+ Reference:
+
+ - http://code.google.com/p/ulib/
+ - http://nothings.org/computer/judy/
+
+ * Allow to optionally use linear probing which usually has better
+ performance for random input. Double hashing is still the default as
+ it is more robust to certain non-random input.
+
+ * Added Wang's integer hash function (not used by default). This hash
+ function is more robust to certain non-random input.
+
+ 2011-02-14 (0.2.5):
+
+ * Allow to declare global functions.
+
+ 2009-09-26 (0.2.4):
+
+ * Improve portability
+
+ 2008-09-19 (0.2.3):
+
+ * Corrected the example
+ * Improved interfaces
+
+ 2008-09-11 (0.2.2):
+
+ * Improved speed a little in kh_put()
+
+ 2008-09-10 (0.2.1):
+
+ * Added kh_clear()
+ * Fixed a compiling error
+
+ 2008-09-02 (0.2.0):
+
+ * Changed to token concatenation which increases flexibility.
+
+ 2008-08-31 (0.1.2):
+
+ * Fixed a bug in kh_get(), which has not been tested previously.
+
+ 2008-08-31 (0.1.1):
+
+ * Added destructor
+*/
+
+#ifndef __AC_KHASH_H
+#define __AC_KHASH_H
+
+/*!
+ @header
+
+ Generic hash table library.
+ */
+
+#define AC_VERSION_KHASH_H "0.2.8"
+
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+/* compiler specific configuration */
+
+#if UINT_MAX == 0xffffffffu
+typedef unsigned int khint32_t;
+#elif ULONG_MAX == 0xffffffffu
+typedef unsigned long khint32_t;
+#endif
+
+#if ULONG_MAX == ULLONG_MAX
+typedef unsigned long khint64_t;
+#else
+typedef unsigned long long khint64_t;
+#endif
+
+#ifndef kh_inline
+#ifdef _MSC_VER
+#define kh_inline __inline
+#else
+#define kh_inline inline
+#endif
+#endif /* kh_inline */
+
+#ifndef klib_unused
+#if (defined __clang__ && __clang_major__ >= 3) || \
+ (defined __GNUC__ && __GNUC__ >= 3)
+#define klib_unused __attribute__ ((__unused__))
+#else
+#define klib_unused
+#endif
+#endif /* klib_unused */
+
+typedef khint32_t khint_t;
+typedef khint_t khiter_t;
+
+#define __ac_isempty(flag, i) ((flag[i >> 4] >> ((i & 0xfU) << 1)) & 2)
+#define __ac_isdel(flag, i) ((flag[i >> 4] >> ((i & 0xfU) << 1)) & 1)
+#define __ac_iseither(flag, i) ((flag[i >> 4] >> ((i & 0xfU) << 1)) & 3)
+#define __ac_set_isdel_false(flag, i) \
+ (flag[i >> 4] &= ~(1ul << ((i & 0xfU) << 1)))
+#define __ac_set_isempty_false(flag, i) \
+ (flag[i >> 4] &= ~(2ul << ((i & 0xfU) << 1)))
+#define __ac_set_isboth_false(flag, i) \
+ (flag[i >> 4] &= ~(3ul << ((i & 0xfU) << 1)))
+#define __ac_set_isdel_true(flag, i) (flag[i >> 4] |= 1ul << ((i & 0xfU) << 1))
+
+#define __ac_fsize(m) ((m) < 16 ? 1 : (m) >> 4)
+
+#ifndef kroundup32
+#define kroundup32(x) \
+ (--(x), (x) |= (x) >> 1, (x) |= (x) >> 2, (x) |= (x) >> 4, (x) |= (x) >> 8, \
+ (x) |= (x) >> 16, ++(x))
+#endif
+
+#ifndef kcalloc
+#define kcalloc(N, Z) calloc (N, Z)
+#endif
+#ifndef kmalloc
+#define kmalloc(Z) malloc (Z)
+#endif
+#ifndef krealloc
+#define krealloc(P, Z) realloc (P, Z)
+#endif
+#ifndef kfree
+#define kfree(P) free (P)
+#endif
+
+static const double __ac_HASH_UPPER = 0.77;
+
+#define __KHASH_TYPE(name, khkey_t, khval_t) \
+ typedef struct kh_##name##_s \
+ { \
+ khint_t n_buckets, size, n_occupied, upper_bound; \
+ khint32_t *flags; \
+ khkey_t *keys; \
+ khval_t *vals; \
+ } kh_##name##_t;
+
+#define __KHASH_PROTOTYPES(name, khkey_t, khval_t) \
+ extern kh_##name##_t *kh_init_##name (void); \
+ extern void kh_destroy_##name (kh_##name##_t *h); \
+ extern void kh_clear_##name (kh_##name##_t *h); \
+ extern khint_t kh_get_##name (const kh_##name##_t *h, khkey_t key); \
+ extern int kh_resize_##name (kh_##name##_t *h, khint_t new_n_buckets); \
+ extern khint_t kh_put_##name (kh_##name##_t *h, khkey_t key, int *ret); \
+ extern void kh_del_##name (kh_##name##_t *h, khint_t x);
+
+#define __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, \
+ __hash_equal) \
+ SCOPE kh_##name##_t *kh_init_##name (void) \
+ { \
+ return (kh_##name##_t *) kcalloc (1, sizeof (kh_##name##_t)); \
+ } \
+ SCOPE void kh_destroy_##name (kh_##name##_t *h) \
+ { \
+ if (h) \
+ { \
+ kfree ((void *) h->keys); \
+ kfree (h->flags); \
+ kfree ((void *) h->vals); \
+ kfree (h); \
+ } \
+ } \
+ SCOPE void kh_clear_##name (kh_##name##_t *h) \
+ { \
+ if (h && h->flags) \
+ { \
+ memset (h->flags, 0xaa, \
+ __ac_fsize (h->n_buckets) * sizeof (khint32_t)); \
+ h->size = h->n_occupied = 0; \
+ } \
+ } \
+ SCOPE khint_t kh_get_##name (const kh_##name##_t *h, khkey_t key) \
+ { \
+ if (h->n_buckets) \
+ { \
+ khint_t k, i, last, mask, step = 0; \
+ mask = h->n_buckets - 1; \
+ k = __hash_func (key); \
+ i = k & mask; \
+ last = i; \
+ while (!__ac_isempty (h->flags, i) && \
+ (__ac_isdel (h->flags, i) || !__hash_equal (h->keys[i], key))) \
+ { \
+ i = (i + (++step)) & mask; \
+ if (i == last) \
+ return h->n_buckets; \
+ } \
+ return __ac_iseither (h->flags, i) ? h->n_buckets : i; \
+ } \
+ else \
+ return 0; \
+ } \
+ SCOPE int kh_resize_##name (kh_##name##_t *h, khint_t new_n_buckets) \
+ { /* This function uses 0.25*n_buckets bytes of \
+ working space instead of \
+ [sizeof(key_t+val_t)+.25]*n_buckets. */ \
+ khint32_t *new_flags = 0; \
+ khint_t j = 1; \
+ { \
+ kroundup32 (new_n_buckets); \
+ if (new_n_buckets < 4) \
+ new_n_buckets = 4; \
+ if (h->size >= (khint_t) (new_n_buckets * __ac_HASH_UPPER + 0.5)) \
+ j = 0; /* requested size is too small */ \
+ else \
+ { /* hash table size to be changed (shrink or expand); rehash */ \
+ new_flags = (khint32_t *) kmalloc (__ac_fsize (new_n_buckets) * \
+ sizeof (khint32_t)); \
+ if (!new_flags) \
+ return -1; \
+ memset (new_flags, 0xaa, \
+ __ac_fsize (new_n_buckets) * sizeof (khint32_t)); \
+ if (h->n_buckets < new_n_buckets) \
+ { /* expand */ \
+ khkey_t *new_keys = (khkey_t *) krealloc ( \
+ (void *) h->keys, new_n_buckets * sizeof (khkey_t)); \
+ if (!new_keys) \
+ { \
+ kfree (new_flags); \
+ return -1; \
+ } \
+ h->keys = new_keys; \
+ if (kh_is_map) \
+ { \
+ khval_t *new_vals = (khval_t *) krealloc ( \
+ (void *) h->vals, new_n_buckets * sizeof (khval_t)); \
+ if (!new_vals) \
+ { \
+ kfree (new_flags); \
+ return -1; \
+ } \
+ h->vals = new_vals; \
+ } \
+ } /* otherwise shrink */ \
+ } \
+ } \
+ if (j) \
+ { /* rehashing is needed */ \
+ for (j = 0; j != h->n_buckets; ++j) \
+ { \
+ if (__ac_iseither (h->flags, j) == 0) \
+ { \
+ khkey_t key = h->keys[j]; \
+ khval_t val; \
+ khint_t new_mask; \
+ new_mask = new_n_buckets - 1; \
+ if (kh_is_map) \
+ val = h->vals[j]; \
+ __ac_set_isdel_true (h->flags, j); \
+ while (1) \
+ { /* kick-out process; sort of like in Cuckoo hashing */ \
+ khint_t k, i, step = 0; \
+ k = __hash_func (key); \
+ i = k & new_mask; \
+ while (!__ac_isempty (new_flags, i)) \
+ i = (i + (++step)) & new_mask; \
+ __ac_set_isempty_false (new_flags, i); \
+ if (i < h->n_buckets && __ac_iseither (h->flags, i) == 0) \
+ { /* kick out the existing element */ \
+ { \
+ khkey_t tmp = h->keys[i]; \
+ h->keys[i] = key; \
+ key = tmp; \
+ } \
+ if (kh_is_map) \
+ { \
+ khval_t tmp = h->vals[i]; \
+ h->vals[i] = val; \
+ val = tmp; \
+ } \
+ __ac_set_isdel_true ( \
+ h->flags, \
+ i); /* mark it as deleted in the old hash table */ \
+ } \
+ else \
+ { /* write the element and jump out of the loop */ \
+ h->keys[i] = key; \
+ if (kh_is_map) \
+ h->vals[i] = val; \
+ break; \
+ } \
+ } \
+ } \
+ } \
+ if (h->n_buckets > new_n_buckets) \
+ { /* shrink the hash table */ \
+ h->keys = (khkey_t *) krealloc ( \
+ (void *) h->keys, new_n_buckets * sizeof (khkey_t)); \
+ if (kh_is_map) \
+ h->vals = (khval_t *) krealloc ( \
+ (void *) h->vals, new_n_buckets * sizeof (khval_t)); \
+ } \
+ kfree (h->flags); /* free the working space */ \
+ h->flags = new_flags; \
+ h->n_buckets = new_n_buckets; \
+ h->n_occupied = h->size; \
+ h->upper_bound = (khint_t) (h->n_buckets * __ac_HASH_UPPER + 0.5); \
+ } \
+ return 0; \
+ } \
+ SCOPE khint_t kh_put_##name (kh_##name##_t *h, khkey_t key, int *ret) \
+ { \
+ khint_t x; \
+ if (h->n_occupied >= h->upper_bound) \
+ { /* update the hash table */ \
+ if (h->n_buckets > (h->size << 1)) \
+ { \
+ if (kh_resize_##name (h, h->n_buckets - 1) < 0) \
+ { /* clear "deleted" elements */ \
+ *ret = -1; \
+ return h->n_buckets; \
+ } \
+ } \
+ else if (kh_resize_##name (h, h->n_buckets + 1) < 0) \
+ { /* expand the hash table */ \
+ *ret = -1; \
+ return h->n_buckets; \
+ } \
+ } /* TODO: to implement automatically shrinking; resize() already \
+ support shrinking */ \
+ { \
+ khint_t k, i, site, last, mask = h->n_buckets - 1, step = 0; \
+ x = site = h->n_buckets; \
+ k = __hash_func (key); \
+ i = k & mask; \
+ if (__ac_isempty (h->flags, i)) \
+ x = i; /* for speed up */ \
+ else \
+ { \
+ last = i; \
+ while ( \
+ !__ac_isempty (h->flags, i) && \
+ (__ac_isdel (h->flags, i) || !__hash_equal (h->keys[i], key))) \
+ { \
+ if (__ac_isdel (h->flags, i)) \
+ site = i; \
+ i = (i + (++step)) & mask; \
+ if (i == last) \
+ { \
+ x = site; \
+ break; \
+ } \
+ } \
+ if (x == h->n_buckets) \
+ { \
+ if (__ac_isempty (h->flags, i) && site != h->n_buckets) \
+ x = site; \
+ else \
+ x = i; \
+ } \
+ } \
+ } \
+ if (__ac_isempty (h->flags, x)) \
+ { /* not present at all */ \
+ h->keys[x] = key; \
+ __ac_set_isboth_false (h->flags, x); \
+ ++h->size; \
+ ++h->n_occupied; \
+ *ret = 1; \
+ } \
+ else if (__ac_isdel (h->flags, x)) \
+ { /* deleted */ \
+ h->keys[x] = key; \
+ __ac_set_isboth_false (h->flags, x); \
+ ++h->size; \
+ *ret = 2; \
+ } \
+ else \
+ *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \
+ return x; \
+ } \
+ SCOPE void kh_del_##name (kh_##name##_t *h, khint_t x) \
+ { \
+ if (x != h->n_buckets && !__ac_iseither (h->flags, x)) \
+ { \
+ __ac_set_isdel_true (h->flags, x); \
+ --h->size; \
+ } \
+ }
+
+#define KHASH_DECLARE(name, khkey_t, khval_t) \
+ __KHASH_TYPE (name, khkey_t, khval_t) \
+ __KHASH_PROTOTYPES (name, khkey_t, khval_t)
+
+#define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, \
+ __hash_equal) \
+ __KHASH_TYPE (name, khkey_t, khval_t) \
+ __KHASH_IMPL (name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, \
+ __hash_equal)
+
+#define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, \
+ __hash_equal) \
+ KHASH_INIT2 (name, static kh_inline klib_unused, khkey_t, khval_t, \
+ kh_is_map, __hash_func, __hash_equal)
+
+/* --- BEGIN OF HASH FUNCTIONS --- */
+
+/*! @function
+ @abstract Integer hash function
+ @param key The integer [khint32_t]
+ @return The hash value [khint_t]
+ */
+#define kh_int_hash_func(key) (khint32_t) (key)
+/*! @function
+ @abstract Integer comparison function
+ */
+#define kh_int_hash_equal(a, b) ((a) == (b))
+/*! @function
+ @abstract 64-bit integer hash function
+ @param key The integer [khint64_t]
+ @return The hash value [khint_t]
+ */
+#define kh_int64_hash_func(key) (khint32_t) ((key) >> 33 ^ (key) ^ (key) << 11)
+/*! @function
+ @abstract 64-bit integer comparison function
+ */
+#define kh_int64_hash_equal(a, b) ((a) == (b))
+/*! @function
+ @abstract const char* hash function
+ @param s Pointer to a null terminated string
+ @return The hash value
+ */
+static kh_inline khint_t
+__ac_X31_hash_string (const char *s)
+{
+ khint_t h = (khint_t) *s;
+ if (h)
+ for (++s; *s; ++s)
+ h = (h << 5) - h + (khint_t) *s;
+ return h;
+}
+/*! @function
+ @abstract Another interface to const char* hash function
+ @param key Pointer to a null terminated string [const char*]
+ @return The hash value [khint_t]
+ */
+#define kh_str_hash_func(key) __ac_X31_hash_string (key)
+/*! @function
+ @abstract Const char* comparison function
+ */
+#define kh_str_hash_equal(a, b) (strcmp (a, b) == 0)
+
+static kh_inline khint_t
+__ac_Wang_hash (khint_t key)
+{
+ key += ~(key << 15);
+ key ^= (key >> 10);
+ key += (key << 3);
+ key ^= (key >> 6);
+ key += ~(key << 11);
+ key ^= (key >> 16);
+ return key;
+}
+#define kh_int_hash_func2(key) __ac_Wang_hash ((khint_t) key)
+
+/* --- END OF HASH FUNCTIONS --- */
+
+/* Other convenient macros... */
+
+/*!
+ @abstract Type of the hash table.
+ @param name Name of the hash table [symbol]
+ */
+#define khash_t(name) kh_##name##_t
+
+/*! @function
+ @abstract Initiate a hash table.
+ @param name Name of the hash table [symbol]
+ @return Pointer to the hash table [khash_t(name)*]
+ */
+#define kh_init(name) kh_init_##name ()
+
+/*! @function
+ @abstract Destroy a hash table.
+ @param name Name of the hash table [symbol]
+ @param h Pointer to the hash table [khash_t(name)*]
+ */
+#define kh_destroy(name, h) kh_destroy_##name (h)
+
+/*! @function
+ @abstract Reset a hash table without deallocating memory.
+ @param name Name of the hash table [symbol]
+ @param h Pointer to the hash table [khash_t(name)*]
+ */
+#define kh_clear(name, h) kh_clear_##name (h)
+
+/*! @function
+ @abstract Resize a hash table.
+ @param name Name of the hash table [symbol]
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param s New size [khint_t]
+ */
+#define kh_resize(name, h, s) kh_resize_##name (h, s)
+
+/*! @function
+ @abstract Insert a key to the hash table.
+ @param name Name of the hash table [symbol]
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param k Key [type of keys]
+ @param r Extra return code: -1 if the operation failed;
+ 0 if the key is present in the hash table;
+ 1 if the bucket is empty (never used); 2 if the element in
+ the bucket has been deleted [int*]
+ @return Iterator to the inserted element [khint_t]
+ */
+#define kh_put(name, h, k, r) kh_put_##name (h, k, r)
+
+/*! @function
+ @abstract Retrieve a key from the hash table.
+ @param name Name of the hash table [symbol]
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param k Key [type of keys]
+ @return Iterator to the found element, or kh_end(h) if the element is
+ absent [khint_t]
+ */
+#define kh_get(name, h, k) kh_get_##name (h, k)
+
+/*! @function
+ @abstract Remove a key from the hash table.
+ @param name Name of the hash table [symbol]
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param k Iterator to the element to be deleted [khint_t]
+ */
+#define kh_del(name, h, k) kh_del_##name (h, k)
+
+/*! @function
+ @abstract Test whether a bucket contains data.
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param x Iterator to the bucket [khint_t]
+ @return 1 if containing data; 0 otherwise [int]
+ */
+#define kh_exist(h, x) (!__ac_iseither ((h)->flags, (x)))
+
+/*! @function
+ @abstract Get key given an iterator
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param x Iterator to the bucket [khint_t]
+ @return Key [type of keys]
+ */
+#define kh_key(h, x) ((h)->keys[x])
+
+/*! @function
+ @abstract Get value given an iterator
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param x Iterator to the bucket [khint_t]
+ @return Value [type of values]
+ @discussion For hash sets, calling this results in segfault.
+ */
+#define kh_val(h, x) ((h)->vals[x])
+
+/*! @function
+ @abstract Alias of kh_val()
+ */
+#define kh_value(h, x) ((h)->vals[x])
+
+/*! @function
+ @abstract Get the start iterator
+ @param h Pointer to the hash table [khash_t(name)*]
+ @return The start iterator [khint_t]
+ */
+#define kh_begin(h) (khint_t) (0)
+
+/*! @function
+ @abstract Get the end iterator
+ @param h Pointer to the hash table [khash_t(name)*]
+ @return The end iterator [khint_t]
+ */
+#define kh_end(h) ((h)->n_buckets)
+
+/*! @function
+ @abstract Get the number of elements in the hash table
+ @param h Pointer to the hash table [khash_t(name)*]
+ @return Number of elements in the hash table [khint_t]
+ */
+#define kh_size(h) ((h)->size)
+
+/*! @function
+ @abstract Get the number of buckets in the hash table
+ @param h Pointer to the hash table [khash_t(name)*]
+ @return Number of buckets in the hash table [khint_t]
+ */
+#define kh_n_buckets(h) ((h)->n_buckets)
+
+/*! @function
+ @abstract Iterate over the entries in the hash table
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param kvar Variable to which key will be assigned
+ @param vvar Variable to which value will be assigned
+ @param code Block of code to execute
+ */
+#define kh_foreach(h, kvar, vvar, code) \
+ { \
+ khint_t __i; \
+ for (__i = kh_begin (h); __i != kh_end (h); ++__i) \
+ { \
+ if (!kh_exist (h, __i)) \
+ continue; \
+ (kvar) = kh_key (h, __i); \
+ (vvar) = kh_val (h, __i); \
+ code; \
+ } \
+ }
+
+/*! @function
+ @abstract Iterate over the values in the hash table
+ @param h Pointer to the hash table [khash_t(name)*]
+ @param vvar Variable to which value will be assigned
+ @param code Block of code to execute
+ */
+#define kh_foreach_value(h, vvar, code) \
+ { \
+ khint_t __i; \
+ for (__i = kh_begin (h); __i != kh_end (h); ++__i) \
+ { \
+ if (!kh_exist (h, __i)) \
+ continue; \
+ (vvar) = kh_val (h, __i); \
+ code; \
+ } \
+ }
+
+/* More convenient interfaces */
+
+/*! @function
+ @abstract Instantiate a hash set containing integer keys
+ @param name Name of the hash table [symbol]
+ */
+#define KHASH_SET_INIT_INT(name) \
+ KHASH_INIT (name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal)
+
+/*! @function
+ @abstract Instantiate a hash map containing integer keys
+ @param name Name of the hash table [symbol]
+ @param khval_t Type of values [type]
+ */
+#define KHASH_MAP_INIT_INT(name, khval_t) \
+ KHASH_INIT (name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal)
+
+/*! @function
+ @abstract Instantiate a hash set containing 64-bit integer keys
+ @param name Name of the hash table [symbol]
+ */
+#define KHASH_SET_INIT_INT64(name) \
+ KHASH_INIT (name, khint64_t, char, 0, kh_int64_hash_func, \
+ kh_int64_hash_equal)
+
+/*! @function
+ @abstract Instantiate a hash map containing 64-bit integer keys
+ @param name Name of the hash table [symbol]
+ @param khval_t Type of values [type]
+ */
+#define KHASH_MAP_INIT_INT64(name, khval_t) \
+ KHASH_INIT (name, khint64_t, khval_t, 1, kh_int64_hash_func, \
+ kh_int64_hash_equal)
+
+typedef const char *kh_cstr_t;
+/*! @function
+ @abstract Instantiate a hash map containing const char* keys
+ @param name Name of the hash table [symbol]
+ */
+#define KHASH_SET_INIT_STR(name) \
+ KHASH_INIT (name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal)
+
+/*! @function
+ @abstract Instantiate a hash map containing const char* keys
+ @param name Name of the hash table [symbol]
+ @param khval_t Type of values [type]
+ */
+#define KHASH_MAP_INIT_STR(name, khval_t) \
+ KHASH_INIT (name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal)
+
+/******************************************************************************
+ * Custom return codes
+ ******************************************************************************/
+
+// RESET: same as added, but the key was already added in the past
+#define foreach_kh_rc \
+ _ (REPLACED) \
+ _ (ADDED) \
+ _ (RESET) \
+ _ (NOT_FOUND) \
+ _ (FOUND) \
+ _ (FAIL)
+
+typedef enum
+{
+#define _(x) KH_##x,
+ foreach_kh_rc
+#undef _
+} kh_rc;
+
+/******************************************************************************
+ * Custom
+ *high-level interface
+ ******************************************************************************/
+
+#define _kh_var(x) _kh_var_##x
+
+/**
+ * @brief Return the value corresponding to a key in the hashtable.
+ * @return The value associated with the key or null if not found
+ */
+#define kh_get_val(kname, hashtable, key, default_val) \
+ ({ \
+ khiter_t _kh_var (k) = kh_get (kname, hashtable, key); \
+ (_kh_var (k) != kh_end (hashtable) ? kh_val (hashtable, _kh_var (k)) : \
+ default_val); \
+ })
+
+/**
+ * @brief Add key/value pair in the hashtable.
+ * @return 0 if an existing value (corresponding to the provided key)
+ * has been replaced; 1 if a new key/value pair has been added
+ * (the key was not already present in the hash table);
+ * 2 if a new key/value pair has been added in correspondence
+ * of a key previously deleted key
+ */
+#define kh_put_val(kname, hashtable, key, val) \
+ ({ \
+ int _kh_var (ret); \
+ khiter_t _kh_var (k) = kh_put (kname, hashtable, key, &_kh_var (ret)); \
+ kh_value (hashtable, _kh_var (k)) = val; \
+ _kh_var (ret); \
+ })
+
+/**
+ * @brief Remove a key/value pair from the hashtable.
+ * @return void
+ */
+#define kh_remove_val(kname, hashtable, key) \
+ ({ \
+ khiter_t _kh_var (k) = kh_get (kname, hashtable, key); \
+ if (_kh_var (k) != kh_end (hashtable)) \
+ { \
+ free ((void *) kh_key (hashtable, _kh_var (k))); \
+ kh_del (kname, hashtable, _kh_var (k)); \
+ } \
+ })
+
+/**
+ * @brief Free the hashtable.
+ * @return void
+ */
+#define kh_free(kname, hashtable) \
+ ({ \
+ const void *_kh_var (key); \
+ unsigned _kh_var (val); \
+ (void) _kh_var (val); \
+ \
+ kh_foreach (hashtable, _kh_var (key), _kh_var (val), { \
+ free ((void *) _kh_var (key)); \
+ }) kh_destroy (kname, hashtable); \
+ })
+
+#endif /* __AC_KHASH_H */
diff --git a/lib/includes/hicn/util/log.h b/lib/includes/hicn/util/log.h
index 6763d464f..b9b7725d6 100644
--- a/lib/includes/hicn/util/log.h
+++ b/lib/includes/hicn/util/log.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,53 +17,72 @@
#define UTIL_LOG_H
#include <stdarg.h> // va_*
-#include <stdio.h> // FILE
-#include <time.h> // time, localtime
+#include <stdio.h> // FILE
+#include <time.h> // time, localtime
-#define LOG_FATAL 0
-#define LOG_ERROR 1
-#define LOG_WARN 2
-#define LOG_INFO 3
-#define LOG_DEBUG 4
-#define LOG_TRACE 5
+typedef enum
+{
+ LOG_FATAL,
+ LOG_ERROR,
+ LOG_WARN,
+ LOG_INFO,
+ LOG_DEBUG,
+ LOG_TRACE
+} log_level_t;
-typedef struct {
+typedef struct
+{
int log_level;
int debug;
- FILE * log_file;
+ FILE *log_file;
} log_conf_t;
-#define DEFAULT_LOG_CONF { \
- .log_level = LOG_INFO, \
- .debug = 0, \
- .log_file = NULL, \
-};
+#define DEFAULT_LOG_CONF \
+ { \
+ .log_level = LOG_INFO, \
+ .debug = 0, \
+ .log_file = NULL, \
+ };
extern log_conf_t log_conf;
-#define WITH_DEBUG(BLOCK) \
- if (log_conf.log_level >= LOG_DEBUG) \
- BLOCK
+#define WITH_ERROR(BLOCK) \
+ if (log_conf.log_level >= LOG_ERROR) \
+ BLOCK
+#define WITH_WARN(BLOCK) \
+ if (log_conf.log_level >= LOG_WARN) \
+ BLOCK
+#define WITH_INFO(BLOCK) \
+ if (log_conf.log_level >= LOG_INFO) \
+ BLOCK
+#define WITH_DEBUG(BLOCK) \
+ if (log_conf.log_level >= LOG_DEBUG) \
+ BLOCK
+#define WITH_TRACE(BLOCK) \
+ if (log_conf.log_level >= LOG_TRACE) \
+ BLOCK
-#define FATAL(fmt, ...) (_log(LOG_FATAL, fmt, ##__VA_ARGS__ ))
+#define FATAL(fmt, ...) (_log (LOG_FATAL, fmt, ##__VA_ARGS__))
#ifdef ERROR
#undef ERROR
#endif
-#define ERROR(fmt, ...) (_log(LOG_ERROR, fmt, ##__VA_ARGS__ ))
-#define WARN(fmt, ...) (_log(LOG_WARN, fmt, ##__VA_ARGS__ ))
-#define INFO(fmt, ...) (_log(LOG_INFO, fmt, ##__VA_ARGS__ ))
-#define DEBUG(fmt, ...) (_log(LOG_DEBUG, fmt, ##__VA_ARGS__ ))
-#define TRACE(fmt, ...) (_log(LOG_TRACE, fmt, ##__VA_ARGS__ ))
+#define ERROR(fmt, ...) (_log (LOG_ERROR, fmt, ##__VA_ARGS__))
+#define WARN(fmt, ...) (_log (LOG_WARN, fmt, ##__VA_ARGS__))
+#define INFO(fmt, ...) (_log (LOG_INFO, fmt, ##__VA_ARGS__))
+#define DEBUG(fmt, ...) (_log (LOG_DEBUG, fmt, ##__VA_ARGS__))
+#define TRACE(fmt, ...) (_log (LOG_TRACE, fmt, ##__VA_ARGS__))
-void _log_va(int level, const char *fmt, va_list ap);
+void _log_va (int level, const char *fmt, va_list ap);
-void _log(int level, const char *fmt, ...);
+void _log (int level, const char *fmt, ...);
-void fatal(char *fmt, ...);
+void fatal (char *fmt, ...);
+
+int loglevel_from_str (const char *loglevel);
#ifdef HAVE_BACKTRACE
#include <execinfo.h>
-void print_trace(void);
+void print_trace (void);
#endif
#endif // UTIL_LOG_H
diff --git a/lib/includes/hicn/util/map.h b/lib/includes/hicn/util/map.h
index 01195865e..6e23f222f 100644
--- a/lib/includes/hicn/util/map.h
+++ b/lib/includes/hicn/util/map.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,231 +20,227 @@
#include "set.h"
-#define ERR_MAP_EXISTS -2
+#define ERR_MAP_EXISTS -2
#define ERR_MAP_NOT_FOUND -3
-#define TYPEDEF_MAP_H(NAME, KEY_T, VAL_T) \
- \
-typedef struct { \
- KEY_T key; \
- VAL_T value; \
-} NAME ## _pair_t; \
- \
-NAME ## _pair_t * NAME ## _pair_create(KEY_T key, VAL_T value); \
- \
-void NAME ## _pair_free(NAME ## _pair_t * pair); \
- \
-int NAME ## _pair_cmp(const NAME ## _pair_t * p1, const NAME ## _pair_t * p2); \
- \
-TYPEDEF_SET_H(NAME ## _pair_set, NAME ## _pair_t *) \
- \
-typedef struct NAME ## _s { \
- NAME ## _pair_set_t pair_set; \
-} NAME ## _t; \
- \
-int NAME ## _initialize(NAME ## _t * map); \
- \
-int NAME ## _finalize(NAME ## _t * map); \
- \
-NAME ## _t * NAME ## _create(); \
- \
-void NAME ## _free(NAME ## _t * map); \
- \
-int NAME ## _add(NAME ## _t * map, KEY_T key, VAL_T value); \
- \
-int NAME ## _remove(NAME ## _t * map, KEY_T key, VAL_T * value); \
- \
-int NAME ## _get(NAME ## _t * map, KEY_T key, VAL_T * value); \
- \
-void NAME ## _dump(NAME ## _t * map);
+#define TYPEDEF_MAP_H(NAME, KEY_T, VAL_T) \
+ \
+ typedef struct \
+ { \
+ KEY_T key; \
+ VAL_T value; \
+ } NAME##_pair_t; \
+ \
+ NAME##_pair_t *NAME##_pair_create (KEY_T key, VAL_T value); \
+ \
+ void NAME##_pair_free (NAME##_pair_t *pair); \
+ \
+ int NAME##_pair_cmp (const NAME##_pair_t *p1, const NAME##_pair_t *p2); \
+ \
+ TYPEDEF_SET_H (NAME##_pair_set, NAME##_pair_t *) \
+ \
+ typedef struct NAME##_s \
+ { \
+ NAME##_pair_set_t pair_set; \
+ } NAME##_t; \
+ \
+ int NAME##_initialize (NAME##_t *map); \
+ \
+ int NAME##_finalize (NAME##_t *map); \
+ \
+ NAME##_t *NAME##_create (); \
+ \
+ void NAME##_free (NAME##_t *map); \
+ \
+ int NAME##_add (NAME##_t *map, KEY_T key, VAL_T value); \
+ \
+ int NAME##_remove (NAME##_t *map, KEY_T key, VAL_T *value); \
+ \
+ int NAME##_get (NAME##_t *map, KEY_T key, VAL_T *value); \
+ \
+ void NAME##_dump (NAME##_t *map); \
+ \
+ int NAME##_get_key_array (NAME##_t *map, KEY_T **array); \
+ \
+ int NAME##_get_value_array (NAME##_t *map, VAL_T **array);
-
-
-
-#define TYPEDEF_MAP(NAME, KEY_T, VAL_T, CMP, KEY_SNPRINTF, VALUE_SNPRINTF) \
- \
-NAME ## _pair_t * NAME ## _pair_create(KEY_T key, VAL_T value) \
-{ \
- /* Create pair */ \
- NAME ## _pair_t * pair = malloc(sizeof(NAME ## _pair_t)); \
- if (!pair) \
- return NULL; \
- \
- pair->key = key; \
- pair->value = value; \
- \
- return pair; \
-} \
- \
-void NAME ## _pair_free(NAME ## _pair_t * pair) \
-{ \
- free(pair); \
-} \
- \
-int \
-NAME ## _pair_cmp(const NAME ## _pair_t * p1, const NAME ## _pair_t * p2) \
-{ \
- return (CMP(p1->key, p2->key)); \
-} \
- \
-int \
-NAME ## _pair_snprintf(char * buf, size_t size, const NAME ## _pair_t * pair) { \
- int rc; \
- rc = KEY_SNPRINTF(buf, BUFSIZE/2, (KEY_T)pair->key); \
- if (rc < 0) \
- return rc; \
- rc = VALUE_SNPRINTF(buf+rc, BUFSIZE/2, (VAL_T)pair->value); \
- return (int)rc; \
-} \
- \
-TYPEDEF_SET(NAME ## _pair_set, NAME ## _pair_t *, NAME ## _pair_cmp, NAME ## _pair_snprintf); \
- \
-int \
-NAME ## _initialize(NAME ## _t * map) \
-{ \
- return NAME ## _pair_set_initialize(&map->pair_set); \
-} \
- \
-int \
-NAME ## _finalize(NAME ## _t * map) \
-{ \
- NAME ## _pair_t ** array; \
- int n = NAME ## _pair_set_get_array(&map->pair_set, &array); \
- if (n < 0) \
- return -1; \
- for (unsigned i = 0; i < n; i++) { \
- NAME ## _pair_t * pair = array[i]; \
- NAME ## _pair_set_remove(&map->pair_set, pair, NULL); \
- NAME ## _pair_free(pair); \
- } \
- free(array); \
- return NAME ## _pair_set_finalize(&map->pair_set); \
-} \
- \
-NAME ## _t * \
-NAME ## _create() \
-{ \
- NAME ## _t * map = malloc(sizeof(NAME ## _t)); \
- if (!map) \
- goto ERR_MALLOC; \
- \
- if (NAME ## _initialize(map) < 0) \
- goto ERR_INITIALIZE; \
- \
- return map; \
- \
-ERR_INITIALIZE: \
- free(map); \
-ERR_MALLOC: \
- return NULL; \
-} \
- \
-void \
-NAME ## _free(NAME ## _t * map) \
-{ \
- NAME ## _finalize(map); \
- free(map); \
-} \
- \
-int \
-NAME ## _add(NAME ## _t * map, KEY_T key, VAL_T value) \
-{ \
- int rc; \
- NAME ## _pair_t * found = NULL; \
- \
- NAME ## _pair_t * pair = NAME ## _pair_create(key, value); \
- if (!pair) \
- return -1; \
- \
- rc = NAME ## _pair_set_get(&map->pair_set, pair, &found); \
- if (rc < 0) \
- return -1; \
- if (found) { \
- NAME ## _pair_free(pair); \
- return ERR_MAP_EXISTS; \
- } \
- \
- rc = NAME ## _pair_set_add(&map->pair_set, pair); \
- if (rc < 0) { \
- NAME ## _pair_free(pair); \
- return -1; \
- } \
- return 0; \
-} \
- \
-int \
-NAME ## _remove(NAME ## _t * map, KEY_T key, VAL_T * value) \
-{ \
- NAME ## _pair_t * found = NULL; \
- NAME ## _pair_t search = { .key = key }; \
- int rc = NAME ## _pair_set_remove(&map->pair_set, &search, &found); \
- if (rc < 0) \
- return ERR_MAP_NOT_FOUND; \
- if (value) \
- *value = found->value; \
- NAME ## _pair_free(found); \
- return 0; \
-} \
- \
-int \
-NAME ## _get(NAME ## _t * map, KEY_T key, VAL_T * value) \
-{ \
- NAME ## _pair_t * found = NULL, search = { .key = key }; \
- int rc = NAME ## _pair_set_get(&map->pair_set, &search, &found); \
- if (rc < 0) \
- return -1; \
- if (found) \
- *value = found->value; \
- return 0; \
-} \
- \
-void \
-NAME ## _dump(NAME ## _t * map) { \
- NAME ## _pair_set_dump(&map->pair_set); \
-} \
- \
-int \
-NAME ## _get_key_array(NAME ## _t * map, KEY_T **array) { \
- NAME ## _pair_t ** pair_array; \
- int n = NAME ## _pair_set_get_array(&map->pair_set, &pair_array); \
- if (n < 0) \
- return -1; \
- if (!array) \
- goto END; \
- /* Allocate result array */ \
- *array = malloc(n * sizeof(KEY_T)); \
- if (!array) { \
- free(pair_array); \
- return -1; \
- } \
- /* Copy keys */ \
- for (int i = 0; i < n; i++) \
- (*array)[i] = pair_array[i]->key; \
- free(pair_array); \
-END: \
- return n; \
-} \
- \
-int \
-NAME ## _get_value_array(NAME ## _t * map, VAL_T **array) { \
- NAME ## _pair_t ** pair_array; \
- int n = NAME ## _pair_set_get_array(&map->pair_set, &pair_array); \
- if (n < 0) \
- return -1; \
- if (!array) \
- goto END; \
- /* Allocate result array */ \
- *array = malloc(n * sizeof(VAL_T)); \
- if (!array) { \
- free(pair_array); \
- return -1; \
- } \
- /* Copy values */ \
- for (int i = 0; i < n; i++) \
- (*array)[i] = pair_array[i]->value; \
- free(pair_array); \
-END: \
- return n; \
-}
+#define TYPEDEF_MAP(NAME, KEY_T, VAL_T, CMP, KEY_SNPRINTF, VALUE_SNPRINTF) \
+ \
+ NAME##_pair_t *NAME##_pair_create (KEY_T key, VAL_T value) \
+ { \
+ /* Create pair */ \
+ NAME##_pair_t *pair = malloc (sizeof (NAME##_pair_t)); \
+ if (!pair) \
+ return NULL; \
+ \
+ pair->key = key; \
+ pair->value = value; \
+ \
+ return pair; \
+ } \
+ \
+ void NAME##_pair_free (NAME##_pair_t *pair) { free (pair); } \
+ \
+ int NAME##_pair_cmp (const NAME##_pair_t *p1, const NAME##_pair_t *p2) \
+ { \
+ return (CMP (p1->key, p2->key)); \
+ } \
+ \
+ int NAME##_pair_snprintf (char *buf, size_t size, \
+ const NAME##_pair_t *pair) \
+ { \
+ int rc; \
+ rc = KEY_SNPRINTF (buf, BUFSIZE / 2, (KEY_T) pair->key); \
+ if (rc < 0) \
+ return rc; \
+ rc = VALUE_SNPRINTF (buf + rc, BUFSIZE / 2, (VAL_T) pair->value); \
+ return (int) rc; \
+ } \
+ \
+ TYPEDEF_SET (NAME##_pair_set, NAME##_pair_t *, NAME##_pair_cmp, \
+ NAME##_pair_snprintf); \
+ \
+ int NAME##_initialize (NAME##_t *map) \
+ { \
+ return NAME##_pair_set_initialize (&map->pair_set); \
+ } \
+ \
+ int NAME##_finalize (NAME##_t *map) \
+ { \
+ NAME##_pair_t **array; \
+ int n = NAME##_pair_set_get_array (&map->pair_set, &array); \
+ if (n < 0) \
+ return -1; \
+ for (unsigned i = 0; i < n; i++) \
+ { \
+ NAME##_pair_t *pair = array[i]; \
+ NAME##_pair_set_remove (&map->pair_set, pair, NULL); \
+ NAME##_pair_free (pair); \
+ } \
+ free (array); \
+ return NAME##_pair_set_finalize (&map->pair_set); \
+ } \
+ \
+ NAME##_t *NAME##_create () \
+ { \
+ NAME##_t *map = malloc (sizeof (NAME##_t)); \
+ if (!map) \
+ goto ERR_MALLOC; \
+ \
+ if (NAME##_initialize (map) < 0) \
+ goto ERR_INITIALIZE; \
+ \
+ return map; \
+ \
+ ERR_INITIALIZE: \
+ free (map); \
+ ERR_MALLOC: \
+ return NULL; \
+ } \
+ \
+ void NAME##_free (NAME##_t *map) \
+ { \
+ NAME##_finalize (map); \
+ free (map); \
+ } \
+ \
+ int NAME##_add (NAME##_t *map, KEY_T key, VAL_T value) \
+ { \
+ int rc; \
+ NAME##_pair_t *found = NULL; \
+ \
+ NAME##_pair_t *pair = NAME##_pair_create (key, value); \
+ if (!pair) \
+ return -1; \
+ \
+ rc = NAME##_pair_set_get (&map->pair_set, pair, &found); \
+ if (rc < 0) \
+ return -1; \
+ if (found) \
+ { \
+ NAME##_pair_free (pair); \
+ return ERR_MAP_EXISTS; \
+ } \
+ \
+ rc = NAME##_pair_set_add (&map->pair_set, pair); \
+ if (rc < 0) \
+ { \
+ NAME##_pair_free (pair); \
+ return -1; \
+ } \
+ return 0; \
+ } \
+ \
+ int NAME##_remove (NAME##_t *map, KEY_T key, VAL_T *value) \
+ { \
+ NAME##_pair_t *found = NULL; \
+ NAME##_pair_t search = { .key = key }; \
+ int rc = NAME##_pair_set_remove (&map->pair_set, &search, &found); \
+ if (rc < 0) \
+ return ERR_MAP_NOT_FOUND; \
+ if (value) \
+ *value = found->value; \
+ NAME##_pair_free (found); \
+ return 0; \
+ } \
+ \
+ int NAME##_get (NAME##_t *map, KEY_T key, VAL_T *value) \
+ { \
+ NAME##_pair_t *found = NULL, search = { .key = key }; \
+ int rc = NAME##_pair_set_get (&map->pair_set, &search, &found); \
+ if (rc < 0) \
+ return -1; \
+ if (found) \
+ *value = found->value; \
+ return 0; \
+ } \
+ \
+ void NAME##_dump (NAME##_t *map) { NAME##_pair_set_dump (&map->pair_set); } \
+ \
+ int NAME##_get_key_array (NAME##_t *map, KEY_T **array) \
+ { \
+ NAME##_pair_t **pair_array; \
+ int n = NAME##_pair_set_get_array (&map->pair_set, &pair_array); \
+ if (n < 0) \
+ return -1; \
+ if (!array) \
+ goto END; \
+ /* Allocate result array */ \
+ *array = malloc (n * sizeof (KEY_T)); \
+ if (!array) \
+ { \
+ free (pair_array); \
+ return -1; \
+ } \
+ /* Copy keys */ \
+ for (int i = 0; i < n; i++) \
+ (*array)[i] = pair_array[i]->key; \
+ free (pair_array); \
+ END: \
+ return n; \
+ } \
+ \
+ int NAME##_get_value_array (NAME##_t *map, VAL_T **array) \
+ { \
+ NAME##_pair_t **pair_array; \
+ int n = NAME##_pair_set_get_array (&map->pair_set, &pair_array); \
+ if (n < 0) \
+ return -1; \
+ if (!array) \
+ goto END; \
+ /* Allocate result array */ \
+ *array = malloc (n * sizeof (VAL_T)); \
+ if (!array) \
+ { \
+ free (pair_array); \
+ return -1; \
+ } \
+ /* Copy values */ \
+ for (int i = 0; i < n; i++) \
+ (*array)[i] = pair_array[i]->value; \
+ free (pair_array); \
+ END: \
+ return n; \
+ }
#endif /* UTIL_MAP_H */
diff --git a/lib/includes/hicn/util/pool.h b/lib/includes/hicn/util/pool.h
new file mode 100644
index 000000000..b8acadc44
--- /dev/null
+++ b/lib/includes/hicn/util/pool.h
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file pool.h
+ * \brief Fixed-size pool allocator.
+ *
+ * This memory pool allocates a single block of memory that is used to
+ * efficiently allocate/deallocate fixed-size blocks for high churn data
+ * structures.
+ *
+ * Internally this data structure leverages a vector for managing elements (and
+ * it thus resizeable if needed), as well as a list of free indices (in the
+ * form of another vector) and a bitmap marking free indices also (for fast
+ * iteration).
+ *
+ * The internal API manipulates a pointer to the vector that that is can be
+ * seamlessly resized, and a more convenient user interface is provided through
+ * macros.
+ *
+ * The vector of free indices is managed as a stack where elements indices are
+ * retrieved from and put back to the end of the vector. In the bitmap,
+ * available elements are set to 1, and unset to 0 when in use.
+ *
+ * The pool is not currently resized down when releasing elements.
+ *
+ * It is freely inspired (and simplified) from the VPP infra infrastructure
+ * library.
+ */
+
+#ifndef UTIL_POOL_H
+#define UTIL_POOL_H
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#include "bitmap.h"
+#include <hicn/util/vector.h>
+#include "../common.h"
+
+/* Pool header */
+
+typedef struct
+{
+ size_t elt_size;
+ size_t alloc_size;
+ size_t max_size;
+ bitmap_t *free_bitmap; /* bitmap of free indices */
+ off_t *free_indices; /* vector of free indices */
+} pool_hdr_t;
+
+#define POOL_HDRLEN SIZEOF_ALIGNED (pool_hdr_t)
+
+/* This header actually prepends the actual content of the pool. */
+#define pool_hdr(pool) ((pool_hdr_t *) ((uint8_t *) (pool) -POOL_HDRLEN))
+
+/******************************************************************************/
+/* Helpers */
+
+/** Local variable naming macro. */
+#define _pool_var(v) _pool_##v
+
+/**
+ * @brief Allocate and initialize a pool data structure (helper).
+ *
+ * @param[in,out] pool_ptr Pointer to the pool data structure.
+ * @param[in] elt_size Size of elements in vector.
+ * @param[in] max_size Maximum size.
+ *
+ * NOTE: that an empty pool might be equal to NULL.
+ */
+void _pool_init (void **pool_ptr, size_t elt_size, size_t init_size,
+ size_t max_size);
+
+/**
+ * @brief Free a pool data structure (helper).
+ *
+ * @param[in] pool_ptr Pointer to the pool data structure.
+ */
+void _pool_free (void **pool_ptr);
+
+/**
+ * @brief Resize a pool data structure (helper).
+ *
+ * @param pool_ptr Pointer to the pool data structure.
+ *
+ * This function should only be called internally, as the resize is implicitly
+ * done (if allowed by the maximum size) when the user tries to get a new slot.
+ */
+void _pool_resize (void **pool_ptr, size_t elt_size);
+
+/**
+ * @brief Get a free element from the pool data structure (helper).
+ *
+ * @param[in] pool Pointer to the pool data structure to use.
+ * @param[in,out] elt Pointer to an empty element that will be used to return
+ * the allocated one from the pool.
+ *
+ * NOTES:
+ * - The memory chunk is cleared upon attribution
+ */
+off_t _pool_get (void **pool, void **elt, size_t elt_size);
+
+/**
+ * @brief Put an element back into the pool data structure (helper).
+ *
+ * @param[in] pool_ptr Pointer to the pool data structure to use.
+ * @param[in] elt Pointer to the pool element to put back.
+ */
+void _pool_put (void **pool, void **elt, size_t elt_size);
+
+/**
+ * @brief Validate a pool element by index (helper).
+ *
+ * @param[in] pool The pool data structure to use.
+ * @param[in] id The index of the element to validate.
+ *
+ * @return bool A flag indicating whether the index is valid or not.
+ */
+bool _pool_validate_id (void **pool_ptr, off_t id);
+/******************************************************************************/
+/* Public API */
+
+/**
+ * @brief Allocate and initialize a pool data structure.
+ *
+ * @param[in,out] pool Pointer to the pool data structure.
+ * @param[in] elt_size Size of elements in pool.
+ * @param[in] max_size Maximum size.
+ *
+ * NOTE: that an empty pool might be equal to NULL.
+ */
+#define pool_init(pool, init_size, max_size) \
+ _pool_init ((void **) &pool, sizeof (pool[0]), init_size, max_size);
+
+/**
+ * @brief Free a pool data structure.
+ *
+ * @param[in] pool The pool data structure to free.
+ */
+#define pool_free(pool) _pool_free ((void **) &pool);
+
+/**
+ * @brief Get a free element from the pool data structure.
+ *
+ * @param[in] pool The pool data structure to use.
+ * @param[in,out] elt An empty element that will be used to return the
+ * allocated one from the pool.
+ *
+ * NOTES:
+ * - The memory chunk is cleared upon attribution
+ */
+#define pool_get(pool, elt) \
+ _pool_get ((void **) &pool, (void **) &elt, sizeof (*elt))
+
+/**
+ * @brief Put an element back into the pool data structure.
+ *
+ * @param[in] pool The pool data structure to use.
+ * @param[in] elt The pool element to put back.
+ */
+#define pool_put(pool, elt) \
+ _pool_put ((void **) &pool, (void **) &elt, sizeof (*elt))
+
+/**
+ * @brief Validate a pool element by index.
+ *
+ * @param[in] pool The pool data structure to use.
+ * @param[in] id The index of the element to validate.
+ *
+ * @return bool A flag indicating whether the index is valid or not.
+ */
+#define pool_validate_id(pool, id) _pool_validate_id ((void **) &pool, (id))
+
+#define pool_get_free_indices_size(pool) \
+ vector_len (pool_hdr (pool)->free_indices)
+
+/**
+ * @brief Returns the current length of the pool.
+ *
+ * @param[in] pool The pool data structure for which to return the length.
+ *
+ * @return size_t The current length of the pool.
+ *
+ * NOTE:
+ * - The pool length corresponds to the number of allocated elements, not the
+ * size of the pool.
+ */
+#define pool_len(pool) \
+ (pool_hdr (pool)->alloc_size - pool_get_free_indices_size (pool))
+
+/**
+ * @brief Enumerate elements from a pool.
+ *
+ * @param[in] pool The pool data structure to enumerate.
+ * @param[in, out] i An integer that will be used for enumeration.
+ * @param[in, out] eltp A pointer to the element type that will be used for
+ * enumeration.
+ * @param[in] BODY Block to execute during enumeration.
+ *
+ * Enumeration will iteratively execute BODY with (i, eltp) corresponding
+ * respectively to the index and element found in the pool.
+ *
+ * NOTE: i stars at 0.
+ */
+#define pool_enumerate(pool, i, eltp, BODY) \
+ do \
+ { \
+ pool_hdr_t *_pool_var (ph) = pool_hdr (pool); \
+ bitmap_t *_pool_var (fb) = _pool_var (ph)->free_bitmap; \
+ for ((i) = 0; (i) < _pool_var (ph)->alloc_size; (i)++) \
+ { \
+ if (bitmap_is_set (_pool_var (fb), (i))) \
+ continue; \
+ eltp = (pool) + (i); \
+ do \
+ { \
+ BODY; \
+ } \
+ while (0); \
+ } \
+ } \
+ while (0)
+
+#define pool_enumerate_typed(pool, i, TYPE, ELTP, BODY) \
+ do \
+ { \
+ pool_hdr_t *_pool_var (ph) = pool_hdr (pool); \
+ bitmap_t *_pool_var (fb) = _pool_var (ph)->free_bitmap; \
+ TYPE ELTP = NULL; \
+ for ((i) = 0; (i) < _pool_var (ph)->alloc_size; (i)++) \
+ { \
+ if (bitmap_is_set (_pool_var (fb), (i))) \
+ continue; \
+ ELTP = (pool) + (i); \
+ do \
+ { \
+ BODY; \
+ } \
+ while (0); \
+ } \
+ } \
+ while (0)
+
+/**
+ * @brief Iterate over elements in a pool.
+ *
+ * @param[in] pool The pool data structure to iterate over.
+ * @param[in,out] eltp A pointer to the element type that will be used for
+ * iteration.
+ * @param[in] BODY Block to execute during iteration.
+ *
+ * Iteration will execute BODY with eltp corresponding successively to all
+ * elements found in the pool. It is implemented using the more generic
+ * enumeration function.
+ */
+#define pool_foreach(pool, eltp, BODY) \
+ do \
+ { \
+ unsigned _pool_var (i); \
+ pool_enumerate ((pool), _pool_var (i), (eltp), BODY); \
+ } \
+ while (0)
+
+#define pool_get_alloc_size(pool) pool_hdr (pool)->alloc_size
+
+#define pool_foreach_typed(pool, TYPE, ELTP, BODY) \
+ do \
+ { \
+ unsigned _pool_var (i); \
+ pool_enumerate_typed ((pool), _pool_var (i), TYPE, ELTP, BODY); \
+ } \
+ while (0)
+
+#ifdef WITH_TESTS
+#define pool_get_free_indices(pool) pool_hdr (pool)->free_indices
+#define pool_get_free_bitmap(pool) pool_hdr (pool)->free_bitmap
+#endif /* WITH_TESTS */
+
+#endif /* UTIL_POOL_H */
diff --git a/lib/includes/hicn/util/ring.h b/lib/includes/hicn/util/ring.h
new file mode 100644
index 000000000..9510672b3
--- /dev/null
+++ b/lib/includes/hicn/util/ring.h
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file ring.h
+ * \brief Fixed-size pool allocator.
+ */
+
+#ifndef UTIL_RING_H
+#define UTIL_RING_H
+
+#include <assert.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/param.h> // MIN
+#include <sys/types.h>
+
+#include <stdio.h> // XXX debug
+
+#include "../common.h"
+
+/******************************************************************************/
+/* Ring header */
+
+typedef struct
+{
+ size_t roff;
+ size_t woff;
+ size_t size;
+ size_t max_size;
+} ring_hdr_t;
+
+/* Make sure elements following the header are aligned */
+#define RING_HDRLEN SIZEOF_ALIGNED (ring_hdr_t)
+
+/* This header actually prepends the actual content of the vector */
+#define ring_hdr(ring) ((ring_hdr_t *) ((uint8_t *) ring - RING_HDRLEN))
+
+/******************************************************************************/
+/* Helpers */
+
+/** Local variable naming macro. */
+#define _ring_var(v) _ring_##v
+
+/**
+ * @brief Allocate and initialize a ring data structure (helper function).
+ *
+ * @param[in,out] ring_ptr Ring buffer to allocate and initialize.
+ * @param[in] elt_size Size of a ring element.
+ * @param[in] max_size Maximum vector size (O = unlimited).
+ */
+void _ring_init (void **ring_ptr, size_t elt_size, size_t max_size);
+
+/**
+ * @brief Free a ring data structure.
+ *
+ * @param ring_ptr[in] Pointer to the ring data structure to free.
+ */
+void _ring_free (void **ring_ptr);
+
+static inline int
+_ring_add (void **ring_ptr, size_t elt_size, void *eltp)
+{
+ assert (*ring_ptr);
+ ring_hdr_t *rh = ring_hdr (*ring_ptr);
+
+ /* We always write ! */
+ memcpy ((uint8_t *) *ring_ptr + rh->woff * elt_size, eltp, elt_size);
+ rh->woff++;
+ if (rh->woff == rh->max_size)
+ rh->woff = 0;
+ if (rh->size < rh->max_size)
+ {
+ rh->size++;
+ }
+ else
+ {
+ /* One packet was dropped */
+ rh->roff++;
+ if (rh->roff == rh->max_size)
+ rh->roff = 0;
+ }
+ return 0;
+}
+
+static inline unsigned
+_ring_get_fullness (void **ring_ptr)
+{
+ assert (*ring_ptr);
+ ring_hdr_t *rh = ring_hdr (*ring_ptr);
+ return (unsigned int) (rh->size * 100 / rh->max_size);
+}
+
+static inline unsigned
+_ring_is_full (void **ring_ptr)
+{
+ assert (*ring_ptr);
+ ring_hdr_t *rh = ring_hdr (*ring_ptr);
+ return rh->size == rh->max_size;
+}
+
+static inline size_t
+_ring_get_size (void **ring_ptr)
+{
+ assert (*ring_ptr);
+ ring_hdr_t *rh = ring_hdr (*ring_ptr);
+ return rh->size;
+}
+
+static inline int
+_ring_advance (void **ring_ptr, unsigned n)
+{
+ assert (*ring_ptr);
+ ring_hdr_t *rh = ring_hdr (*ring_ptr);
+ assert (n <= rh->size);
+
+ rh->roff += n;
+ rh->size -= n;
+ while (rh->roff >= rh->max_size)
+ rh->roff -= rh->max_size;
+ return 0;
+}
+
+static inline int
+_ring_get (void **ring_ptr, size_t elt_size, unsigned i, void *eltp)
+{
+ assert (*ring_ptr);
+ ring_hdr_t *rh = ring_hdr (*ring_ptr);
+ assert (i <= rh->size);
+ size_t pos = rh->roff + i;
+ if (pos >= rh->max_size)
+ pos -= rh->max_size;
+ memcpy (eltp, (uint8_t *) *ring_ptr + pos * elt_size, elt_size);
+ return 0;
+}
+
+/******************************************************************************/
+/* Public API */
+
+/**
+ * @brief Allocate and initialize a ring data structure.
+ *
+ * @param[in,out] ring Ring to allocate and initialize.
+ * @param[in] max_size Maximum ring size (nonzero).
+ *
+ * NOTE:
+ * - Allocated memory is set to 0 (used by bitmap)
+ */
+
+#define ring_init(RING, MAX_SIZE) \
+ _ring_init ((void **) &(RING), sizeof ((RING)[0]), (MAX_SIZE))
+
+#define ring_free(RING) _ring_free ((void **) &(RING))
+
+#define ring_get_fullness(RING) _ring_get_fullness ((void **) &(RING))
+
+#define ring_is_full(RING) _ring_is_full ((void **) &(RING))
+
+#define ring_get_size(RING) _ring_get_size ((void **) &(RING))
+
+#define ring_add(RING, ELT) \
+ _ring_add ((void **) &(RING), sizeof (RING[0]), ELT)
+
+#define ring_add_value(RING, VALUE) \
+ do \
+ { \
+ typeof (VALUE) _ring_var (v) = VALUE; \
+ _ring_add ((void **) &(RING), sizeof (RING[0]), &_ring_var (v)); \
+ } \
+ while (0)
+
+#define ring_advance(RING, N) _ring_advance ((void **) &(RING), (N))
+
+#define ring_get(RING, I, ELTP) \
+ _ring_get ((void **) &RING, sizeof (RING[0]), (I), (ELTP))
+
+/**
+ * @brief Helper function used by ring_foreach().
+ */
+#define ring_enumerate_n(RING, I, ELTP, COUNT, BODY) \
+ ({ \
+ for ((I) = 0; (I) < MIN (ring_get_size (RING), (COUNT)); (I)++) \
+ { \
+ ring_get ((RING), (I), (ELTP)); \
+ { \
+ BODY; \
+ } \
+ } \
+ })
+
+#define ring_enumerate(ring, i, eltp, BODY) \
+ ring_enumerate_n ((ring), (i), (eltp), 1, (BODY))
+
+/**
+ * @brief Iterate over elements in a ring.
+ *
+ * @param[in] pool The ring data structure to iterate over
+ * @param[in, out] eltp A pointer to the element that will be used for
+ * iteration
+ * @param[in] BODY Block to execute during iteration
+ *
+ * @note Iteration will execute BODY with eltp corresponding successively to
+ * all elements found in the ring. It is implemented using the more generic
+ * enumeration function.
+ */
+#define ring_foreach_n(ring, eltp, count, BODY) \
+ ({ \
+ unsigned _ring_var (i); \
+ ring_enumerate_n ((ring), _ring_var (i), (eltp), (count), BODY); \
+ })
+
+#define ring_foreach(ring, eltp, BODY) \
+ ring_foreach_n ((ring), (eltp), 1, (BODY))
+
+#endif /* UTIL_RING_H */
diff --git a/lib/includes/hicn/util/set.h b/lib/includes/hicn/util/set.h
index bc2e3caac..0a5ff6777 100644
--- a/lib/includes/hicn/util/set.h
+++ b/lib/includes/hicn/util/set.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,214 +25,196 @@
#define thread_local _Thread_local
//#endif /* ! __ANDROID__ */
-#define ERR_SET_EXISTS -2
+#define ERR_SET_EXISTS -2
#define ERR_SET_NOT_FOUND -3
/* FIXME: buffer overflow when this is too small... investigate */
#define BUFSIZE 1024
-static inline
-int
-int_cmp(const int x, const int y)
+static inline int
+int_cmp (const int x, const int y)
{
- return x - y;
+ return x - y;
}
-static inline
-int
-int_snprintf(char * buf, size_t size, int value) {
- return snprintf(buf, size, "%d", value);
+static inline int
+int_snprintf (char *buf, size_t size, int value)
+{
+ return snprintf (buf, size, "%d", value);
}
-static inline
-int
-string_snprintf(char * buf, size_t size, const char * s) {
- return snprintf(buf, size, "%s", s);
+static inline int
+string_snprintf (char *buf, size_t size, const char *s)
+{
+ return snprintf (buf, size, "%s", s);
}
-static inline
-int
-generic_snprintf(char * buf, size_t size, const void * value) {
- return snprintf(buf, BUFSIZE, "%p", value);
+static inline int
+generic_snprintf (char *buf, size_t size, const void *value)
+{
+ return snprintf (buf, BUFSIZE, "%p", value);
}
-typedef int(*cmp_t)(const void * x, const void * y);
-
-#define TYPEDEF_SET_H(NAME, T) \
- \
-typedef struct { \
- size_t size; \
- void * root; \
-} NAME ## _t; \
- \
-int NAME ## _initialize(NAME ## _t * set); \
- \
-int NAME ## _finalize(NAME ## _t * set); \
- \
-NAME ## _t * NAME ## _create(); \
- \
-void NAME ## _free(NAME ## _t * set); \
- \
-int NAME ## _add(NAME ## _t * set, const T element); \
- \
-int NAME ## _remove(NAME ## _t * set, const T search, T * element); \
- \
-int NAME ## _clear(NAME ## _t * set); \
- \
-int NAME ## _get(const NAME ## _t * set, const T search, T * element); \
- \
-int NAME ## _get_array(const NAME ## _t * set, T ** element); \
- \
-void NAME ## _dump(NAME ## _t * set);
+typedef int (*cmp_t) (const void *x, const void *y);
+#define TYPEDEF_SET_H(NAME, T) \
+ \
+ typedef struct \
+ { \
+ size_t size; \
+ void *root; \
+ } NAME##_t; \
+ \
+ int NAME##_initialize (NAME##_t *set); \
+ \
+ int NAME##_finalize (NAME##_t *set); \
+ \
+ NAME##_t *NAME##_create (); \
+ \
+ void NAME##_free (NAME##_t *set); \
+ \
+ int NAME##_add (NAME##_t *set, const T element); \
+ \
+ int NAME##_remove (NAME##_t *set, const T search, T *element); \
+ \
+ int NAME##_clear (NAME##_t *set); \
+ \
+ int NAME##_get (const NAME##_t *set, const T search, T *element); \
+ \
+ int NAME##_get_array (const NAME##_t *set, T **element); \
+ \
+ void NAME##_dump (NAME##_t *set);
-
-
-#define TYPEDEF_SET(NAME, T, CMP, SNPRINTF) \
-int \
-NAME ## _initialize(NAME ## _t * set) \
-{ \
- set->root = NULL; \
- set->size = 0; \
- return 0; \
-} \
- \
-int \
-NAME ## _finalize(NAME ## _t * set) \
-{ \
- return NAME ## _clear(set); \
-} \
- \
-NAME ## _t * \
-NAME ## _create() \
-{ \
- NAME ## _t * set = malloc(sizeof(NAME ## _t)); \
- if (!set) \
- goto ERR_MALLOC; \
- \
- if (NAME ## _initialize(set) < 0) \
- goto ERR_INITIALIZE; \
- \
- return set; \
- \
-ERR_INITIALIZE: \
- free(set); \
-ERR_MALLOC: \
- return NULL; \
-} \
- \
-void \
-NAME ## _free(NAME ## _t * set) \
-{ \
- NAME ## _finalize(set); \
- free(set); \
-} \
- \
-int \
-NAME ## _add(NAME ## _t * set, const T element) \
-{ \
- T * found = tfind(element, &set->root, (cmp_t)CMP); \
- void * ptr = tsearch(element, &set->root, (cmp_t)CMP); \
- if (!ptr) \
- return -1; \
- if (!found) \
- set->size++; \
- return 0; \
-} \
- \
-int \
-NAME ## _remove(NAME ## _t * set, const T search, T * element) \
-{ \
- T * found = tfind(search, &set->root, (cmp_t)CMP); \
- if (!found) \
- return ERR_SET_NOT_FOUND; \
- if (element) \
- *element = *found; \
- tdelete(search, &set->root, (cmp_t)CMP); \
- set->size--; \
- return 0; \
-} \
- \
-int \
-NAME ## _clear(NAME ## _t * set) \
-{ \
- T * array; \
- int n = NAME ## _get_array(set, &array); \
- if (n < 0) \
- return -1; \
- for (unsigned i = 0; i < n; i++) { \
- T element = array[i]; \
- NAME ## _remove(set, element, NULL); \
- } \
- free(array); \
- return 0; \
-} \
- \
-int \
-NAME ## _get(const NAME ## _t * set, const T search, T * element) \
-{ \
- T * found = tfind(search, &set->root, (cmp_t)CMP); \
- if (element) \
- *element = found ? *found : NULL; \
- return 0; \
-} \
- \
-static void \
-NAME ## _dump_node(const void *nodep, const VISIT which, \
- const int depth) \
-{ \
- char buf[BUFSIZE]; \
- switch (which) { \
- case preorder: \
- case endorder: \
- break; \
- case postorder: \
- case leaf: \
- SNPRINTF(buf, BUFSIZE, *(T*)nodep); \
- INFO("%s", buf); \
- break; \
- } \
-} \
- \
-void \
-NAME ## _dump(NAME ## _t * set) { \
- twalk(set->root, NAME ## _dump_node); \
-} \
- \
-thread_local \
-T * NAME ## _array_pos = NULL; \
- \
-static void \
-NAME ## _add_node_to_array(const void *nodep, const VISIT which, \
- const int depth) \
-{ \
- if (!NAME ## _array_pos) \
- return; \
- switch (which) { \
- case preorder: \
- case endorder: \
- break; \
- case postorder: \
- case leaf: \
- *NAME ## _array_pos = *(T*)nodep; \
- NAME ## _array_pos++; \
- break; \
- } \
-} \
- \
-int \
-NAME ## _get_array(const NAME ## _t * set, T ** element) \
-{ \
- if (!element) \
- goto END; \
- *element = malloc(set->size * sizeof(T)); \
- if (!*element) \
- return -1; \
- NAME ## _array_pos = *element; \
- twalk(set->root, NAME ## _add_node_to_array); \
- NAME ## _array_pos = NULL; \
-END: \
- return (int)(set->size); \
-}
+#define TYPEDEF_SET(NAME, T, CMP, SNPRINTF) \
+ int NAME##_initialize (NAME##_t *set) \
+ { \
+ set->root = NULL; \
+ set->size = 0; \
+ return 0; \
+ } \
+ \
+ int NAME##_finalize (NAME##_t *set) { return NAME##_clear (set); } \
+ \
+ NAME##_t *NAME##_create () \
+ { \
+ NAME##_t *set = malloc (sizeof (NAME##_t)); \
+ if (!set) \
+ goto ERR_MALLOC; \
+ \
+ if (NAME##_initialize (set) < 0) \
+ goto ERR_INITIALIZE; \
+ \
+ return set; \
+ \
+ ERR_INITIALIZE: \
+ free (set); \
+ ERR_MALLOC: \
+ return NULL; \
+ } \
+ \
+ void NAME##_free (NAME##_t *set) \
+ { \
+ NAME##_finalize (set); \
+ free (set); \
+ } \
+ \
+ int NAME##_add (NAME##_t *set, const T element) \
+ { \
+ T *found = tfind (element, &set->root, (cmp_t) CMP); \
+ void *ptr = tsearch (element, &set->root, (cmp_t) CMP); \
+ if (!ptr) \
+ return -1; \
+ if (!found) \
+ set->size++; \
+ return 0; \
+ } \
+ \
+ int NAME##_remove (NAME##_t *set, const T search, T *element) \
+ { \
+ T *found = tfind (search, &set->root, (cmp_t) CMP); \
+ if (!found) \
+ return ERR_SET_NOT_FOUND; \
+ if (element) \
+ *element = *found; \
+ tdelete (search, &set->root, (cmp_t) CMP); \
+ set->size--; \
+ return 0; \
+ } \
+ \
+ int NAME##_clear (NAME##_t *set) \
+ { \
+ T *array; \
+ int n = NAME##_get_array (set, &array); \
+ if (n < 0) \
+ return -1; \
+ for (unsigned i = 0; i < n; i++) \
+ { \
+ T element = array[i]; \
+ NAME##_remove (set, element, NULL); \
+ } \
+ free (array); \
+ return 0; \
+ } \
+ \
+ int NAME##_get (const NAME##_t *set, const T search, T *element) \
+ { \
+ T *found = tfind (search, &set->root, (cmp_t) CMP); \
+ if (element) \
+ *element = found ? *found : NULL; \
+ return 0; \
+ } \
+ \
+ static void NAME##_dump_node (const void *nodep, const VISIT which, \
+ const int depth) \
+ { \
+ char buf[BUFSIZE]; \
+ switch (which) \
+ { \
+ case preorder: \
+ case endorder: \
+ break; \
+ case postorder: \
+ case leaf: \
+ SNPRINTF (buf, BUFSIZE, *(T *) nodep); \
+ INFO ("%s", buf); \
+ break; \
+ } \
+ } \
+ \
+ void NAME##_dump (NAME##_t *set) { twalk (set->root, NAME##_dump_node); } \
+ \
+ thread_local T *NAME##_array_pos = NULL; \
+ \
+ static void NAME##_add_node_to_array (const void *nodep, const VISIT which, \
+ const int depth) \
+ { \
+ if (!NAME##_array_pos) \
+ return; \
+ switch (which) \
+ { \
+ case preorder: \
+ case endorder: \
+ break; \
+ case postorder: \
+ case leaf: \
+ *NAME##_array_pos = *(T *) nodep; \
+ NAME##_array_pos++; \
+ break; \
+ } \
+ } \
+ \
+ int NAME##_get_array (const NAME##_t *set, T **element) \
+ { \
+ if (!element) \
+ goto END; \
+ *element = calloc (set->size, sizeof (T)); \
+ if (!*element) \
+ return -1; \
+ NAME##_array_pos = *element; \
+ twalk (set->root, NAME##_add_node_to_array); \
+ NAME##_array_pos = NULL; \
+ END: \
+ return (int) (set->size); \
+ }
#endif /* UTIL_SET_H */
diff --git a/lib/includes/hicn/util/slab.h b/lib/includes/hicn/util/slab.h
new file mode 100644
index 000000000..2c6546add
--- /dev/null
+++ b/lib/includes/hicn/util/slab.h
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @brief The slab is used to store elements of the same size.
+ *
+ * The slab contains blocks of contiguous memory. Each block contains multiple
+ * chunks. An element is stored inside a chunk and the chunk has a header with
+ * a pointer to the block it belongs to.
+ *
+ * Blocks are stored in two doubly-linked lists: 'full' for blocks that
+ * are already full, 'partial_or_empty' for blocks with available chunks. When
+ * a block becomes full it is moved into the 'full' list and vice versa.
+ *
+ * When allocationg an element, a block is taken from the 'partial_or_empty'
+ * list if such list is not empty. If empty, a new block of contiguous memory
+ * is created and put in the 'partial_or_empty' list. Then, a chunk is taken
+ * from the block. When releasing an element, the block it belongs to is
+ * retrieved from the chunk header and used to release the chunk.
+ *
+ * Blocks are created with increasing capacity (i.e. number of chunks they
+ * contain) such that every new block allocaion doubles the total number of
+ * chunks stored in the slab.
+ */
+
+#ifndef UTIL_SLAB_H
+#define UTIL_SLAB_H
+
+#include <stddef.h>
+
+#define SLAB_INIT_SIZE 32
+
+/* CHUNK */
+
+typedef struct block_s block_t;
+typedef struct
+{
+ block_t *block; // Pointer to the block that contains the chunk
+} chunk_hdr_t;
+
+#define CHUNK_HDRLEN SIZEOF_ALIGNED (chunk_hdr_t)
+#define chunk_hdr(chunk) ((chunk_hdr_t *) ((uint8_t *) (chunk) -CHUNK_HDRLEN))
+
+/* BLOCK */
+
+struct block_s
+{
+ void *pool;
+ block_t *prev;
+ block_t *next;
+};
+
+/* SLAB */
+
+typedef struct
+{
+ size_t num_chunks; // Total number of chunks (from all blocks) currently
+ // stored in the slab
+ size_t chunk_size;
+ block_t *full;
+ block_t *partial_or_empty;
+} slab_t;
+
+/* Internal API */
+
+slab_t *_slab_create (size_t elt_size, size_t num_elts);
+void *_slab_get (slab_t *slab);
+void _slab_put (slab_t *slab, void *elt);
+
+/* Public API */
+
+/**
+ * @brief Create a slab able to store elements of type 'TYPE'.
+ *
+ * @param[in] TYPE Type of the elements to store in the slab.
+ * @param[in] SIZE Initial size of the slab, i.e. size of the initial block.
+ * @return slab_t* The slab created, NULL if error.
+ */
+#define slab_create(TYPE, SIZE) _slab_create (sizeof (TYPE), SIZE)
+
+/**
+ * @brief Free a slab.
+ *
+ * @param[in] slab Slab to free.
+ */
+void slab_free (slab_t *slab);
+
+/**
+ * @brief Get an element from the slab.
+ *
+ * @param[in] TYPE Type of the elements stored in the slab.
+ * @param[in] SLAB Slab to take the element from.
+ * @return TYPE* Element retrieved from the slab
+ */
+#define slab_get(TYPE, SLAB) (TYPE *) _slab_get (SLAB)
+
+/**
+ * @brief Same as 'slab_get' but with a different signature, to avoid passing
+ * the type that is instead inferred from the element.
+ *
+ * @param[in] SLAB Slab to take the element from.
+ * @param[in, out] ELT Element retrieved from the slab.
+ */
+#define slab_get2(SLAB, ELT) ELT = (typeof (*(ELT)) *) _slab_get (SLAB)
+
+/**
+ * @brief Put an element back into the slab.
+ *
+ * @param[in] SLAB Slab to return the element to.
+ * @param[in] ELT Element to put in the slab.
+ */
+#define slab_put(SLAB, ELT) _slab_put (SLAB, (void *) ELT)
+
+#endif /* UTIL_SLAB_H */
diff --git a/lib/includes/hicn/util/sstrncpy.h b/lib/includes/hicn/util/sstrncpy.h
new file mode 100644
index 000000000..0b397c26b
--- /dev/null
+++ b/lib/includes/hicn/util/sstrncpy.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef UTIL_SSTRNCPY_H
+#define UTIL_SSTRNCPY_H
+
+#ifndef __STDC_WANT_LIB_EXT1__
+#define __STDC_WANT_LIB_EXT1__ 1
+#endif
+
+#include <errno.h>
+#include <string.h>
+
+#ifdef __STDC_LIB_EXT1__
+// If safe string functions already available in the system, use them
+#elif ENABLE_SAFEC
+// If safe string functions not available and SafeC is enabled,
+// use SafeC
+#include <safe_string.h>
+#else
+// Use custom safe string functions
+typedef int errno_t;
+#define EOK 0
+
+#ifndef HICN_VPP_PLUGIN
+/* This function is already defined in vppinfra/string.h */
+
+/**
+ * @brief This function assures a null byte at the end of the buffer.
+ */
+static inline errno_t
+strcpy_s (char *dst, size_t n, const char *src)
+{
+ if (!dst || !src || !n)
+ {
+ fprintf (stderr, "[strncpy] invalid input received");
+ return EINVAL;
+ }
+
+ dst[n - 1] = 0;
+ strncpy (dst, src, n);
+
+ if (dst[n - 1] != 0)
+ {
+ fprintf (stderr, "[strncpy] '%s' has been trucated\n", src);
+ dst[n - 1] = 0;
+ return EINVAL;
+ }
+
+ return EOK;
+}
+
+static inline size_t
+strnlen_s (const char *s, size_t maxlen)
+{
+ if (s == NULL)
+ return 0;
+
+ return strnlen (s, maxlen);
+}
+#endif /* HICN_VPP_PLUGIN */
+
+#endif /* __STDC_LIB_EXT1__ */
+#endif /* UTIL_SSTRNCPY_H */
diff --git a/lib/includes/hicn/util/token.h b/lib/includes/hicn/util/token.h
index 43e0a77b2..c62c294bc 100644
--- a/lib/includes/hicn/util/token.h
+++ b/lib/includes/hicn/util/token.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,12 +19,12 @@
* Concatenate preprocessor tokens A and B without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
-#define PPCAT_NX(A, B) A ## B
+#define PPCAT_NX(A, B) A##B
/*
* Concatenate preprocessor tokens A and B after macro-expanding them.
*/
-#define PPCAT(A, B) PPCAT_NX(A, B)
+#define PPCAT(A, B) PPCAT_NX (A, B)
/* Token stringification */
@@ -37,4 +37,4 @@
/*
* Turn A into a string literal after macro-expanding it.
*/
-#define STRINGIZE(A) STRINGIZE_NX(A)
+#define STRINGIZE(A) STRINGIZE_NX (A)
diff --git a/lib/includes/hicn/util/types.h b/lib/includes/hicn/util/types.h
index 017e85b72..a883b8220 100644
--- a/lib/includes/hicn/util/types.h
+++ b/lib/includes/hicn/util/types.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,21 +19,63 @@
#include <hicn/util/windows/windows_Utils.h>
#endif
+/* Standard types. */
+#include <stdint.h>
+
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
-/* Helper for avoiding warnings about type-punning */
-#define UNION_CAST(x, destType) \
- (((union {__typeof__(x) a; destType b;})x).b)
+typedef int8_t i8;
+typedef int16_t i16;
+typedef int32_t i32;
+typedef int64_t i64;
+
+typedef double f64;
+typedef float f32;
+
+/* Architecture-dependent uword size */
+#if INTPTR_MAX == INT64_MAX
+#define hicn_log2_uword_bits 6
+#elif INTPTR_MAX == INT32_MAX
+#define hicn_log2_uword_bits 5
+#else
+#error "Impossible to detect architecture"
+#endif
+
+#define _hicn_uword_bits (1 << hicn_log2_uword_bits)
-//typedef unsigned int hash_t;
+/* Word types. */
+#if _hicn_uword_bits == 64
+/* 64 bit word machines. */
+typedef u64 hicn_uword;
+#define hicn_uword_bits 64
+#else
+/* 32 bit word machines. */
+typedef u32 hicn_uword;
+#define hicn_uword_bits 32
+#endif
+
+typedef hicn_uword hicn_ip_csum_t;
+
+/* Helper for avoiding warnings about type-punning */
+#define UNION_CAST(x, destType) \
+ (((union { \
+ __typeof__ (x) a; \
+ destType b; \
+ }) x) \
+ .b)
-typedef int (*cmp_t)(const void *, const void *);
+typedef int (*cmp_t) (const void *, const void *);
/* Enums */
-#define IS_VALID_ENUM_TYPE(NAME, x) ((x > NAME ## _UNDEFINED) && (x < NAME ## _N))
+#define IS_VALID_ENUM_TYPE(NAME, x) ((x > NAME##_UNDEFINED) && (x < NAME##_N))
+
+/* Float */
+
+uint32_t htonf (float f);
+float ntohf (uint32_t i);
#endif /* UTIL_TYPES */
diff --git a/lib/includes/hicn/util/vector.h b/lib/includes/hicn/util/vector.h
new file mode 100644
index 000000000..e693df9e3
--- /dev/null
+++ b/lib/includes/hicn/util/vector.h
@@ -0,0 +1,470 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file vector.h
+ * \brief Resizeable static array
+ *
+ * A vector is a resizeable area of contiguous memory that contains elements of
+ * fixed size. It is mostly useful to serve as the basis for more advanced data
+ * structures such as memory pools.
+ *
+ * The internal API manipulates a pointer to the vector so that it can be
+ * seamlessly resized, and a more convenient user interface is provided through
+ * macros.
+ *
+ * A vector starts at index 0, and is typed according to the elements it
+ * contains. For that matter, the data structure header precedes the returned
+ * pointer which corresponds to the storage area.
+ *
+ * A vector is by default used as a stack where an end marker is maintained and
+ * new elements are pushed right after this end marker (an indication of
+ * the size of the vector) after ensuring the vector is sufficiently large.
+ *
+ * A user should not store any pointer to vector elements as this might change
+ * during reallocations, but should use indices instead.
+ *
+ * NOTE: a maximum size is currently not implemented.
+ *
+ * It is freely inspired (and simplified) from the VPP infra infrastructure
+ * library.
+ */
+
+#ifndef UTIL_VECTOR_H
+#define UTIL_VECTOR_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/types.h>
+#include <stdbool.h>
+
+#include "../common.h"
+
+/******************************************************************************/
+/* Vector header */
+
+typedef struct
+{
+ size_t cur_size; /** Vector current size (corresponding to the highest used
+ element). */
+ size_t alloc_size; /** The currently allocated size. */
+ size_t max_size; /** The maximum allowed size (0 = no limit) */
+} vector_hdr_t;
+
+/* Make sure elements following the header are aligned */
+#define VECTOR_HDRLEN SIZEOF_ALIGNED (vector_hdr_t)
+
+/* This header actually prepends the actual content of the vector */
+#define vector_hdr(vector) \
+ ((vector_hdr_t *) ((uint8_t *) vector - VECTOR_HDRLEN))
+
+/******************************************************************************/
+/* Helpers */
+
+/** Local variable naming macro. */
+#define _vector_var(v) _vector_##v
+
+/**
+ * @brief Allocate and initialize a vector data structure (helper function).
+ *
+ * @param[in,out] vector_ptr Vector to allocate and initialize.
+ * @param[in] elt_size Size of a vector element.
+ * @param[in] init_size Initial vector size.
+ * @param[in] max_size Maximum vector size (O = unlimited).
+ * @return int 0 if successful, -1 otherwise
+ */
+int _vector_init (void **vector_ptr, size_t elt_size, size_t init_size,
+ size_t max_size);
+
+/**
+ * @brief Free a vector data structure.
+ *
+ * @param vector_ptr[in] Pointer to the vector data structure to free.
+ */
+void _vector_free (void **vector_ptr);
+
+/**
+ * @brief Resize a vector data structure.
+ *
+ * @param[in] vector_ptr A pointer to the vector data structure to resize.
+ * @param[in] elt_size The size of a vector element.
+ * @param[in] pos The position at which the vector should be able to hold an
+ * element.
+ *
+ * @return int Flag indicating whether the vector has been correctly resized.
+ *
+ * NOTE:
+ * - The resize operation does not specify the final size of the vector but
+ * instead ensure that it is large enough to hold an element at the specified
+ * position. This allows the caller not to care about doing successive calls to
+ * this API while the vector is growing in size.
+ */
+int _vector_resize (void **vector_ptr, size_t elt_size, off_t pos);
+
+/**
+ * @brief Ensures a vector is sufficiently large to hold an element at the
+ * given position.
+ *
+ * @param[in] vector_ptr A pointer to the vector data structure to resize.
+ * @param[in] elt_size The size of a vector element.
+ * @param[in] pos The position to validate.
+ *
+ * @return int Flag indicating whether the vector is available.
+ *
+ * NOTE:
+ * - This function should always be called before writing to a vector element
+ * to eventually make room for it (the vector will eventually be resized).
+ * - This function can fail if the vector is full and for any reason it cannot
+ * be resized.
+ */
+static inline int
+_vector_ensure_pos (void **vector_ptr, size_t elt_size, off_t pos)
+{
+ vector_hdr_t *vh = vector_hdr (*vector_ptr);
+ if (pos >= (off_t) vh->alloc_size)
+ return _vector_resize (vector_ptr, elt_size, pos + 1);
+ return 0;
+}
+
+/**
+ * @brief Push an element at the end of a vector.
+ *
+ * @param[in] vector_ptr A pointer to the vector data structure to resize.
+ * @param[in] elt_size The size of a vector element.
+ * @param[in] elt The element to insert.
+ *
+ * NOTE:
+ * - This function ensures there is sufficient room for inserting the element,
+ * and evenutually resizes the vector to make room for it (if allowed by
+ * maximum size).
+ */
+static inline int
+_vector_push (void **vector_ptr, size_t elt_size, void *elt)
+{
+ vector_hdr_t *vh = vector_hdr (*vector_ptr);
+ if (_vector_ensure_pos (vector_ptr, elt_size, vh->cur_size) < 0)
+ return -1;
+
+ /* Always get header after a potential resize */
+ vh = vector_hdr (*vector_ptr);
+ memcpy ((uint8_t *) *vector_ptr + vh->cur_size * elt_size, elt, elt_size);
+ vh = vector_hdr (*vector_ptr);
+ vh->cur_size++;
+ return 0;
+}
+
+/**
+ * @brief Remove all the occurrencies of an element from the vector.
+ * The order of the elements is NOT maintained.
+ *
+ * @param[in, out] vector The vector data structure to resize
+ * @param[in] elt_size The size of a vector element
+ * @param[in] elt The element to remove
+ * @return int Number of elemets (equal to 'elt') removed from the vector
+ */
+static inline int
+_vector_remove_unordered (void *vector, size_t elt_size, void *elt)
+{
+ size_t num_removed = 0;
+ vector_hdr_t *vh = vector_hdr (vector);
+ for (size_t i = 0; i < vector_hdr (vector)->cur_size; i++)
+ {
+ if (memcmp ((uint8_t *) vector + i * elt_size, elt, elt_size) == 0)
+ {
+ vh->cur_size--;
+ // Copy last element to current position (hence order is not
+ // maintained)
+ memcpy ((uint8_t *) vector + i * elt_size,
+ (uint8_t *) vector + vh->cur_size * elt_size, elt_size);
+ num_removed++;
+ }
+ }
+ return (int) num_removed;
+}
+
+/**
+ * @brief Get the element at the specified position and store in 'elt'.
+ *
+ * @param[in] vector Pointer to the vector data structure to use
+ * @param[in] pos Position of the element to retrieve
+ * @param[in] elt_size The size of a vector element
+ * @param[in] elt The element where the result is stored
+ * @return int 0 if successful, -1 otherwise
+ */
+static inline int
+_vector_get (void *vector, off_t pos, size_t elt_size, void *elt)
+{
+ vector_hdr_t *vh = vector_hdr (vector);
+ if ((size_t) pos >= vh->alloc_size)
+ return -1;
+
+ memcpy (elt, (uint8_t *) vector + pos * elt_size, elt_size);
+ return 0;
+}
+
+/**
+ * @brief Check if specified element is present in vector.
+ *
+ * @param[in] vector Pointer to the vector data structure to use
+ * @param[in] elt_size The size of a vector element
+ * @param[in] elt The element to search for
+ * @return true If specified element is contained in the vector
+ * @return false
+ */
+static inline bool
+_vector_contains (void *vector, size_t elt_size, void *elt)
+{
+ for (size_t i = 0; i < vector_hdr (vector)->cur_size; i++)
+ {
+ if (memcmp ((uint8_t *) vector + i * elt_size, elt, elt_size) == 0)
+ return true;
+ }
+
+ return false;
+}
+
+/**
+ * @brief Remove the element at the specified position from the vector.
+ * Relative element order is preserved by shifting left the elements after the
+ * target.
+ *
+ * @param[in, out] vector Pointer to the vector data structure to use
+ * @param[in] elt_size The size of a vector element
+ * @param[in] pos Position of the element to remove
+ * @return int 0 if successful, -1 otherwise
+ */
+static inline int
+_vector_remove_at (void **vector_ptr, size_t elt_size, off_t pos)
+{
+ vector_hdr_t *vh = vector_hdr (*vector_ptr);
+ if ((size_t) pos >= vh->cur_size)
+ return -1;
+
+ // Shift backward by one position all the elements after the one specified
+ memmove ((uint8_t *) (*vector_ptr) + pos * elt_size,
+ (uint8_t *) (*vector_ptr) + (pos + 1) * elt_size,
+ (vh->cur_size - 1 - pos) * elt_size);
+ vh->cur_size--;
+
+ return 0;
+}
+
+/******************************************************************************/
+/* Public API */
+
+/**
+ * @brief Allocate and initialize a vector data structure.
+ *
+ * @param[in,out] vector Vector to allocate and initialize.
+ * @param[in] init_size Initial vector size.
+ * @param[in] max_size Maximum vector size (nonzero).
+ *
+ * NOTE:
+ * - Allocated memory is set to 0 (used by bitmap)
+ */
+
+#define vector_init(vector, init_size, max_size) \
+ _vector_init ((void **) &vector, sizeof (vector[0]), init_size, max_size)
+
+/**
+ * @brief Free a vector data structure.
+ *
+ * @param[in] vector The vector data structure to free.
+ */
+#define vector_free(vector) _vector_free ((void **) &vector)
+
+/**
+ * @brief Resize a vector data structure.
+ *
+ * @param[in] vector The vector data structure to resize.
+ * @param[in] pos The position at which the vector should be able to hold an
+ * element.
+ *
+ * @return int Flag indicating whether the vector has been correctly resized.
+ *
+ * NOTE:
+ * - The resize operation does not specify the final size of the vector but
+ * instead ensure that it is large enough to hold an element at the specified
+ * position. This allows the caller not to care about doing successive calls to
+ * this API while the vector is growing in size.
+ * - If the new size is smaller than the current size, the content of the
+ * vector will be truncated.
+ * - Newly allocated memory is set to 0 (used by bitmap)
+ */
+#define vector_resize(vector) \
+ _vector_resize ((void **) &(vector), sizeof ((vector)[0]), 0)
+
+/**
+ * @brief Ensures a vector is sufficiently large to hold an element at the
+ * given position.
+ *
+ * @param[in] vector The vector for which to validate the position.
+ * @param[in] pos The position to validate.
+ *
+ * NOTE:
+ * - This function should always be called before writing to a vector element
+ * to eventually make room for it (the vector will eventually be resized).
+ */
+#define vector_ensure_pos(vector, pos) \
+ _vector_ensure_pos ((void **) &(vector), sizeof ((vector)[0]), pos);
+
+/**
+ * @brief Push an element at the end of a vector.
+ *
+ * @param[in] vector The vector in which to insert the element.
+ * @param[in] elt The element to insert.
+ *
+ * NOTE:
+ * - This function ensures there is sufficient room for inserting the element,
+ * and evenutually resizes the vector to make room for it (if allowed by
+ * maximum size).
+ */
+#define vector_push(vector, elt) \
+ ({ \
+ typeof (elt) _vector_var (x) = elt; \
+ _vector_push ((void **) &(vector), sizeof ((vector)[0]), \
+ (void *) (&_vector_var (x))); \
+ })
+
+#define vector_at(vector, pos) \
+ ({ \
+ assert ((size_t) pos < vector_hdr (vector)->cur_size); \
+ (vector)[(pos)]; \
+ })
+
+#define vector_set(vector, pos, elt) \
+ ({ \
+ assert (pos < vector_hdr (vector)->cur_size); \
+ (vector)[(pos)] = elt; \
+ })
+
+/**
+ * @brief Clear the vector content, i.e. new pushes will insert starting from
+ * position 0.
+ *
+ * @param[in, out] vector The vector to reset
+ */
+#define vector_reset(vector) (vector_len (vector) = 0)
+
+/**
+ * @brief Get the element at the specified position and store in 'elt'.
+ *
+ * @param[in] vector The vector data structure to use
+ * @param[in] pos Position of the element to retrieve
+ * @param[in] elt The element where the result is stored
+ * @return int 0 if successful, -1 otherwise
+ */
+#define vector_get(vector, pos, elt) \
+ _vector_get ((void *) (vector), (pos), sizeof ((vector)[0]), \
+ (void *) (&elt));
+
+/**
+ * @brief Check if specified element is present in vector.
+ *
+ * @param[in] vector The vector data structure to use
+ * @param[in] elt The element to search for
+ * @return true If specified element is contained in the vector
+ * @return false
+ */
+#define vector_contains(vector, elt) \
+ ({ \
+ typeof (elt) _vector_var (x) = elt; \
+ _vector_contains ((void *) (vector), sizeof ((vector)[0]), \
+ (void *) (&_vector_var (x))); \
+ })
+
+/**
+ * @brief Remove the element at the specified position from the vector.
+ * Relative element order is preserved by shifting left the elements after the
+ * target.
+ *
+ * @param[in, out] vector The vector data structure to use
+ * @param[in] pos Position of the element to remove
+ * @return int 0 if successful, -1 otherwise
+ */
+#define vector_remove_at(vector, pos) \
+ _vector_remove_at ((void **) &(vector), sizeof ((vector)[0]), (pos))
+
+/**
+ * @brief Remove all the occurrencies of an element from the vector.
+ * The order of the elements is NOT maintained.
+ *
+ * @param[in, out] vector The vector data structure to resize
+ * @param[in] elt The element to remove
+ * @return int Number of elemets (equal to 'elt') removed from the vector
+ */
+#define vector_remove_unordered(vector, elt) \
+ ({ \
+ typeof (elt) x = elt; \
+ _vector_remove_unordered ((void *) (vector), sizeof ((vector)[0]), \
+ (void *) (&x)); \
+ })
+
+/**
+ * @brief Returns the length of a vector.
+ *
+ * @param[in] vector The vector from which to get the size.
+ *
+ * @see vector_ensure_pos
+ *
+ * NOTE:
+ * - The size of the vector corresponds to the highest accessed index (for
+ * example as specified in the resize operation) and not the currently
+ * allocated size which will typically be bigger to amortize allocations.
+ * - A user should always call vector_ensure_pos to ensure the vector is
+ * sufficiently large to hold an element at the specified position.
+ */
+#define vector_len(vector) vector_hdr (vector)->cur_size
+
+/**
+ * @brief Returns the allocated size of a vector.
+ */
+#define vector_get_alloc_size(vector) vector_hdr (vector)->alloc_size
+
+/**
+ * @brief Iterate over elements in a vector.
+ *
+ * @param[in] pool The vector data structure to iterate over
+ * @param[in, out] eltp A pointer to the element that will be used for
+ * iteration
+ * @param[in] BODY Block to execute during iteration
+ *
+ * @note Iteration will execute BODY with eltp corresponding successively to
+ * all elements found in the vector. It is implemented using the more generic
+ * enumeration function.
+ */
+#define vector_foreach(vector, eltp, BODY) \
+ ({ \
+ unsigned _vector_var (i); \
+ vector_enumerate ((vector), _vector_var (i), (eltp), BODY); \
+ })
+
+/**
+ * @brief Helper function used by vector_foreach().
+ */
+#define vector_enumerate(vector, i, eltp, BODY) \
+ ({ \
+ for ((i) = 0; (i) < vector_len (vector); (i)++) \
+ { \
+ eltp = (vector) + (i); \
+ { \
+ BODY; \
+ } \
+ } \
+ })
+
+#endif /* UTIL_VECTOR_H */
diff --git a/lib/includes/hicn/util/win_portability.h b/lib/includes/hicn/util/win_portability.h
index 5f30cfbb2..609203afc 100644
--- a/lib/includes/hicn/util/win_portability.h
+++ b/lib/includes/hicn/util/win_portability.h
@@ -1,45 +1,45 @@
-/*
- * Copyright (c) 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/util/windows/windows_Utils.h>
-#include <afunix.h>
-#include <io.h>
-#include <iphlpapi.h>
-#include <process.h>
-#include <stdio.h>
-#pragma comment(lib, "IPHLPAPI.lib")
-
-#ifndef in_port_t
-#define in_port_t uint16_t
-#endif
-
-#ifndef in_addr_t
-#define in_addr_t uint32_t
-#endif
-
-#ifndef strncasecmp
-#define strncasecmp _strnicmp
-#endif
-
-#ifndef strcasecmp
-#define strcasecmp _stricmp
-#endif
-
-#define HAVE_STRUCT_TIMESPEC
-
-#ifndef getline
-int getline(char **lineptr, size_t *n, FILE *stream);
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <hicn/util/windows/windows_Utils.h>
+#include <afunix.h>
+#include <io.h>
+#include <iphlpapi.h>
+#include <process.h>
+#include <stdio.h>
+#pragma comment(lib, "IPHLPAPI.lib")
+
+#ifndef in_port_t
+#define in_port_t uint16_t
+#endif
+
+#ifndef in_addr_t
+#define in_addr_t uint32_t
+#endif
+
+#ifndef strncasecmp
+#define strncasecmp _strnicmp
+#endif
+
+#ifndef strcasecmp
+#define strcasecmp _stricmp
+#endif
+
+#define HAVE_STRUCT_TIMESPEC
+
+#ifndef getline
+int getline (char **lineptr, size_t *n, FILE *stream);
#endif \ No newline at end of file
diff --git a/lib/includes/hicn/util/windows/dlfcn.h b/lib/includes/hicn/util/windows/dlfcn.h
index 7775226cd..f1457964e 100644
--- a/lib/includes/hicn/util/windows/dlfcn.h
+++ b/lib/includes/hicn/util/windows/dlfcn.h
@@ -5,8 +5,8 @@
#define RTLD_GLOBAL 0x100 /* do not hide entries in this module */
#define RTLD_LOCAL 0x000 /* hide entries in this module */
-#define RTLD_LAZY 0x000 /* accept unresolved externs */
-#define RTLD_NOW 0x001 /* abort if module has unresolved externs */
+#define RTLD_LAZY 0x000 /* accept unresolved externs */
+#define RTLD_NOW 0x001 /* abort if module has unresolved externs */
/*
How to call in Windows:
@@ -16,15 +16,16 @@
*/
#ifdef __cplusplus
-extern "C" {
+extern "C"
+{
#endif
- void *dlopen (const char *filename, int flag);
- int dlclose (void *handle);
+ void *dlopen (const char *filename, int flag);
+ int dlclose (void *handle);
- void *dlsym (void *handle, const char *name);
+ void *dlsym (void *handle, const char *name);
-const char *dlerror (void);
+ const char *dlerror (void);
#ifdef __cplusplus
}
diff --git a/lib/includes/hicn/util/windows/windows_utils.h b/lib/includes/hicn/util/windows/windows_utils.h
index d24aaadbf..e15c0d752 100755..100644
--- a/lib/includes/hicn/util/windows/windows_utils.h
+++ b/lib/includes/hicn/util/windows/windows_utils.h
@@ -1,162 +1,166 @@
-/*
- * Copyright (c) 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.
- */
-
-#ifndef WINDOWS_UTILS_H
-#define WINDOWS_UTILS_H
-#define WIN32_LEAN_AND_MEAN
-#define HAVE_STRUCT_TIMESPEC
-#ifndef NOMINMAX
-#define NOMINMAX
-#endif
-#include <Windows.h>
-#include <stdint.h>
-#include <io.h>
-#include <stdlib.h>
-#include <winsock2.h>
-#include <WS2tcpip.h>
-#include "dlfcn.h"
-
-#ifndef IOVEC
-#define IOVEC
-struct iovec {
- void* iov_base;
- size_t iov_len;
-};
-#endif
-
-typedef uint16_t in_port_t;
-
-#ifndef SLEEP
-#define SLEEP
-#define sleep Sleep
-#endif
-
-#ifndef USLEEP
-#define USLEEP
-void usleep(__int64 usec);
-#endif
-
-#ifndef S_ISDIR
-#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
-#endif
-
-#define PARCLibrary_DISABLE_ATOMICS
-#include <BaseTsd.h>
-typedef SSIZE_T ssize_t;
-
-#ifndef __ATTRIBUTE__
-#define __ATTRIBUTE__
-#define __attribute__(A)
-#endif
-
-#ifndef RESTRICT
-#define RESTRICT
-#define restrict __restrict
-#endif
-
-#ifndef GETTIMEOFDAY
-#define GETTIMEOFDAY
-int gettimeofday(struct timeval * tp, struct timezone * tzp);
-#endif
-
-#ifndef timersub
-#define timersub(a, b, result) \
- do { \
- (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
- (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
- if ((result)->tv_usec < 0) { \
- --(result)->tv_sec; \
- (result)->tv_usec += 1000000; \
- } \
- } while (0)
-#endif // timersub
-
-#ifndef dup
-#define dup _dup
-#endif
-
-#ifndef access
-#define access _access
-#endif
-
-#ifndef __cplusplus
-
-#ifndef read
-#define read _read
-#endif
-
-#ifndef close
-#define close _close
-#endif
-
-#ifndef write
-#define write _write
-#endif
-
-#ifndef open
-#define open _open
-#endif
-
-#endif
-
-#ifndef unlink
-#define unlink _unlink
-#endif
-
-#ifndef strcasecmp
-#define strncasecmp _strnicmp
-#endif
-
-#ifndef strcasecmp
-
-#define strcasecmp _stricmp
-#endif
-
-#ifndef S_ISREG
-#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
-#endif
-#ifndef R_OK
-#define R_OK 4 /* Test for read permission. */
-#endif
-#ifndef W_OK
-#define W_OK 2 /* Test for write permission. */
-#endif
-#ifndef F_OK
-#define F_OK 0
-#endif
-
-#ifndef STDIN_FILENO
-#define STDIN_FILENO _fileno(stdin)
-#endif
-
-#ifndef STDOUT_FILENO
-#define STDOUT_FILENO _fileno(stdout)
-#endif
-
-#ifndef STDERR_FILENO
-#define STDERR_FILENO _fileno(stderr)
-#endif
-
-#endif
-
-#ifndef __bswap_constant_32
-#define __bswap_constant_32(x) \
- ((((x) & 0xff000000u) >> 24) | (((x) & 0x00ff0000u) >> 8) \
- | (((x) & 0x0000ff00u) << 8) | (((x) & 0x000000ffu) << 24))
-#endif
-
-#ifndef bzero
-#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef WINDOWS_UTILS_H
+#define WINDOWS_UTILS_H
+#define WIN32_LEAN_AND_MEAN
+#define HAVE_STRUCT_TIMESPEC
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <Windows.h>
+#include <stdint.h>
+#include <io.h>
+#include <stdlib.h>
+#include <winsock2.h>
+#include <WS2tcpip.h>
+#include "dlfcn.h"
+
+#ifndef IOVEC
+#define IOVEC
+struct iovec
+{
+ void *iov_base;
+ size_t iov_len;
+};
+#endif
+
+typedef uint16_t in_port_t;
+
+#ifndef SLEEP
+#define SLEEP
+#define sleep Sleep
+#endif
+
+#ifndef USLEEP
+#define USLEEP
+void usleep (__int64 usec);
+#endif
+
+#ifndef S_ISDIR
+#define S_ISDIR(mode) (((mode) &S_IFMT) == S_IFDIR)
+#endif
+
+#define PARCLibrary_DISABLE_ATOMICS
+#include <BaseTsd.h>
+typedef SSIZE_T ssize_t;
+
+#ifndef __ATTRIBUTE__
+#define __ATTRIBUTE__
+#define __attribute__(A)
+#endif
+
+#ifndef RESTRICT
+#define RESTRICT
+#define restrict __restrict
+#endif
+
+#ifndef GETTIMEOFDAY
+#define GETTIMEOFDAY
+int gettimeofday (struct timeval *tp, struct timezone *tzp);
+#endif
+
+#ifndef timersub
+#define timersub(a, b, result) \
+ do \
+ { \
+ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
+ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
+ if ((result)->tv_usec < 0) \
+ { \
+ --(result)->tv_sec; \
+ (result)->tv_usec += 1000000; \
+ } \
+ } \
+ while (0)
+#endif // timersub
+
+#ifndef dup
+#define dup _dup
+#endif
+
+#ifndef access
+#define access _access
+#endif
+
+#ifndef __cplusplus
+
+#ifndef read
+#define read _read
+#endif
+
+#ifndef close
+#define close _close
+#endif
+
+#ifndef write
+#define write _write
+#endif
+
+#ifndef open
+#define open _open
+#endif
+
+#endif
+
+#ifndef unlink
+#define unlink _unlink
+#endif
+
+#ifndef strcasecmp
+#define strncasecmp _strnicmp
+#endif
+
+#ifndef strcasecmp
+
+#define strcasecmp _stricmp
+#endif
+
+#ifndef S_ISREG
+#define S_ISREG(mode) (((mode) &S_IFMT) == S_IFREG)
+#endif
+#ifndef R_OK
+#define R_OK 4 /* Test for read permission. */
+#endif
+#ifndef W_OK
+#define W_OK 2 /* Test for write permission. */
+#endif
+#ifndef F_OK
+#define F_OK 0
+#endif
+
+#ifndef STDIN_FILENO
+#define STDIN_FILENO _fileno (stdin)
+#endif
+
+#ifndef STDOUT_FILENO
+#define STDOUT_FILENO _fileno (stdout)
+#endif
+
+#ifndef STDERR_FILENO
+#define STDERR_FILENO _fileno (stderr)
+#endif
+
+#endif
+
+#ifndef __bswap_constant_32
+#define __bswap_constant_32(x) \
+ ((((x) &0xff000000u) >> 24) | (((x) &0x00ff0000u) >> 8) | \
+ (((x) &0x0000ff00u) << 8) | (((x) &0x000000ffu) << 24))
+#endif
+
+#ifndef bzero
+#define bzero(b, len) (memset ((b), '\0', (len)), (void) 0)
#endif \ No newline at end of file
diff --git a/lib/includes/hicn/validation.h b/lib/includes/hicn/validation.h
new file mode 100644
index 000000000..05be6d306
--- /dev/null
+++ b/lib/includes/hicn/validation.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file validation.h
+ * \brief Functions for input validation
+ */
+#include <ctype.h>
+#include <hicn/util/sstrncpy.h>
+
+static inline bool
+is_number (const char *string, size_t maxlen)
+{
+ size_t len = strnlen_s (string, maxlen);
+ for (size_t i = 0; i < len; i++)
+ {
+ if (!isdigit (string[i]))
+ return false;
+ }
+ return len != 0;
+}
+
+/**
+ * A symbolic name must be at least 1 character and must begin with an alpha.
+ * The remainder must be an alphanum.
+ */
+static inline bool
+is_symbolic_name (const char *name, size_t maxlen)
+{
+ size_t len = strnlen_s (name, maxlen);
+ if (len <= 0)
+ return false;
+ if (!isalpha (name[0]))
+ return false;
+
+ for (size_t i = 1; i < len; i++)
+ {
+ if (!isalnum (name[i]) && name[i] != '_' && name[i] != '-')
+ return false;
+ }
+
+ return true;
+}
diff --git a/lib/src/CMakeLists.txt b/lib/src/CMakeLists.txt
index 2588bde8b..27446a493 100644
--- a/lib/src/CMakeLists.txt
+++ b/lib/src/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,53 +11,124 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Source and Header files
+##############################################################
list(APPEND LIBHICN_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/common.c
- ${CMAKE_CURRENT_SOURCE_DIR}/compat.c
- ${CMAKE_CURRENT_SOURCE_DIR}/error.c
- ${CMAKE_CURRENT_SOURCE_DIR}/mapme.c
- ${CMAKE_CURRENT_SOURCE_DIR}/name.c
- ${CMAKE_CURRENT_SOURCE_DIR}/ops.c
- ${CMAKE_CURRENT_SOURCE_DIR}/policy.c
- ${CMAKE_CURRENT_SOURCE_DIR}/protocol/ah.c
- ${CMAKE_CURRENT_SOURCE_DIR}/protocol/icmp.c
- ${CMAKE_CURRENT_SOURCE_DIR}/protocol/ipv4.c
- ${CMAKE_CURRENT_SOURCE_DIR}/protocol/ipv6.c
- ${CMAKE_CURRENT_SOURCE_DIR}/protocol/tcp.c
- ${CMAKE_CURRENT_SOURCE_DIR}/util/ip_address.c
- ${CMAKE_CURRENT_SOURCE_DIR}/util/log.c
+ base.c
+ common.c
+ error.c
+ face.c
+ mapme.c
+ name.c
+ ops.c
+ packet.c
+ policy.c
+ strategy.c
+ protocol/ah.c
+ protocol/icmp.c
+ protocol/ipv4.c
+ protocol/ipv6.c
+ protocol/tcp.c
+ protocol/udp.c
+ protocol/new.c
+ util/ip_address.c
+ util/log.c
+ util/pool.c
+ util/ring.c
+ util/slab.c
+ util/types.c
+ util/vector.c
)
if (WIN32)
list(APPEND LIBHICN_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/util/windows/dlfcn.c
+ util/windows/dlfcn.c
)
endif ()
-set (COMPILER_DEFINITIONS "-DWITH_MAPME")
+
+##############################################################
+# Compiler definitions
+##############################################################
+set (COMPILER_DEFINITIONS
+ PUBLIC "-DWITH_MAPME"
+ PUBLIC "-DWITH_POLICY"
+)
include(BuildMacros)
include(WindowsMacros)
-if (DISABLE_SHARED_LIBRARIES)
- build_library(${LIBHICN}
- STATIC
- SOURCES ${LIBHICN_SOURCE_FILES} ${LIBHICN_HEADER_FILES} ${LIBHICN_HEADER_FILES_PROTOCOL} ${LIBHICN_HEADER_FILES_UTIL}
- COMPONENT lib${LIBHICN}
- INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../includes
- DEFINITIONS ${COMPILER_DEFINITIONS}
- HEADER_ROOT_DIR hicn
- INSTALL_HEADERS ${LIBHICN_HEADER_FILES} ${LIBHICN_HEADER_FILES_PROTOCOL} ${LIBHICN_HEADER_FILES_UTIL}
- LINK_LIBRARIES ${WSOCK32_LIBRARY} ${WS2_32_LIBRARY}
+##############################################################
+# Build type
+##############################################################
+set (BUILD_TYPES "STATIC")
+
+if (NOT DISABLE_SHARED_LIBRARIES)
+ list(APPEND BUILD_TYPES
+ "SHARED"
)
-else ()
- build_library(${LIBHICN}
- SHARED STATIC
- SOURCES ${LIBHICN_SOURCE_FILES} ${LIBHICN_HEADER_FILES} ${LIBHICN_HEADER_FILES_PROTOCOL} ${LIBHICN_HEADER_FILES_UTIL}
- COMPONENT lib${LIBHICN}
- INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../includes
- DEFINITIONS ${COMPILER_DEFINITIONS}
- HEADER_ROOT_DIR hicn
- INSTALL_HEADERS ${LIBHICN_HEADER_FILES} ${LIBHICN_HEADER_FILES_PROTOCOL} ${LIBHICN_HEADER_FILES_UTIL}
- LINK_LIBRARIES ${WSOCK32_LIBRARY} ${WS2_32_LIBRARY}
+endif()
+
+
+##############################################################
+# Compiler Options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ PRIVATE "-Wno-address-of-packed-member"
+)
+
+
+##############################################################
+# Link libraries
+##############################################################
+if (WIN32)
+ list(APPEND LIBRARIES
+ PRIVATE ${WSOCK32_LIBRARY}
+ PRIVATE ${WS2_32_LIBRARY}
)
endif ()
+
+
+##############################################################
+# Build library
+##############################################################
+build_library(${LIBHICN}
+ ${BUILD_TYPES}
+ SOURCES ${LIBHICN_SOURCE_FILES}
+ COMPONENT ${LIBHICN_COMPONENT}
+ INCLUDE_DIRS
+ PUBLIC
+ $<BUILD_INTERFACE:${Libhicn_INCLUDE_DIRS}>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+ $<BUILD_INTERFACE:${THIRD_PARTY_INCLUDE_DIRS}>
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ INSTALL_HEADERS ${LIBHICN_HEADER_FILES} ${LIBHICN_HEADER_FILES_PROTOCOL} ${LIBHICN_HEADER_FILES_UTIL}
+ DEPENDS ${THIRD_PARTY_DEPENDENCIES}
+ LINK_LIBRARIES
+ PRIVATE ${WSOCK32_LIBRARY}
+ PRIVATE ${WS2_32_LIBRARY}
+ PUBLIC ${THIRD_PARTY_LIBRARIES}
+ VERSION ${CURRENT_VERSION}
+ EXPORT_NAME ${LIBHICN_COMPONENT}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
+
+##############################################################
+# Unit tests
+##############################################################
+if (${BUILD_TESTS})
+ add_subdirectory(test)
+endif()
+
+
+##############################################################
+# Cmake config files
+##############################################################
+create_cmake_config (
+ ${LIBHICN_COMPONENT}
+ INCLUDE_DIRS ${HICN_INCLUDE_DIRS}
+ VERSION ${CURRENT_VERSION}
+ COMPONENT ${LIBHICN_COMPONENT}
+ NAMESPACE hicn
+)
diff --git a/lib/src/base.c b/lib/src/base.c
new file mode 100644
index 000000000..1852666a6
--- /dev/null
+++ b/lib/src/base.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file base.c
+ * @brief Implementation of base hICN definitions.
+ */
+
+#include <hicn/base.h>
+#include "ops.h"
+
+const char *_hicn_packet_type_str[] = {
+#define _(x) [HICN_PACKET_TYPE_##x] = #x,
+ foreach_packet_type
+#undef _
+};
+
+int
+hicn_packet_format_snprintf (char *s, size_t size, hicn_packet_format_t format)
+{
+ char *cur = s;
+ int rc;
+
+ HICN_PACKET_FORMAT_ENUMERATE (format, i, protocol, {
+ if (i > 0)
+ {
+ rc = snprintf (cur, size - (cur - s), "%s", "/");
+ if (rc < 0 || rc >= size - (cur - s))
+ return rc;
+ cur += rc;
+ }
+
+ rc = snprintf (cur, size - (cur - s), "%s", hicn_ops_vft[protocol]->name);
+ if (rc < 0 || rc >= size - (cur - s))
+ return rc;
+ cur += rc;
+ });
+ return (int) (cur - s);
+}
diff --git a/lib/src/common.c b/lib/src/common.c
index 562771e09..362034942 100644
--- a/lib/src/common.c
+++ b/lib/src/common.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,8 +20,8 @@
*/
#include <stdlib.h>
-#include <string.h> // memset
-#include <sys/types.h> // getaddrinfo
+#include <string.h> // memset
+#include <sys/types.h> // getaddrinfo
#ifndef _WIN32
#include <sys/socket.h>
#include <netdb.h>
@@ -31,8 +31,6 @@
#include <hicn/common.h>
#include <hicn/util/log.h>
-
-
int
get_addr_family (const char *ip_address)
{
@@ -56,61 +54,48 @@ get_addr_family (const char *ip_address)
/* hashes */
-u32
-cumulative_hash32 (const void *data, size_t len, u32 lastValue)
-{
- // Standard FNV 32-bit prime: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
- const u32 fnv1a_prime = 0x01000193;
- u32 hash = lastValue;
- size_t i;
+// FNV-1a 32-bit http://www.isthe.com/chongo/tech/comp/fnv/
+typedef u_int32_t Fnv32_t;
+#define FNV_32_PRIME ((Fnv32_t) 0x01000193)
+#define FNV1_32_INIT ((Fnv32_t) 0x811c9dc5)
+#define FNV1_32A_INIT FNV1_32_INIT
- const char *chardata = data;
+Fnv32_t
+cumulative_hash32 (const void *buf, size_t len, Fnv32_t hval)
+{
+ unsigned char *bp = (unsigned char *) buf; /* start of buffer */
+ unsigned char *be = bp + len; /* beyond end of buffer */
- for (i = 0; i < len; i++)
+ /*
+ * FNV-1a hash each octet in the buffer
+ */
+ while (bp < be)
{
- hash = hash ^ chardata[i];
- hash = hash * fnv1a_prime;
- }
-
- return hash;
-}
-
-u32
-hash32 (const void *data, size_t len)
-{
- // Standard FNV 32-bit offset: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
- const u32 fnv1a_offset = 0x811C9DC5;
- return cumulative_hash32 (data, len, fnv1a_offset);
-}
-u64
-cumulative_hash64 (const void *data, size_t len, u64 lastValue)
-{
- // Standard FNV 64-bit prime: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
- const u64 fnv1a_prime = 0x00000100000001B3ULL;
- u64 hash = lastValue;
- const char *chardata = data;
- size_t i;
+ /* xor the bottom with the current octet */
+ hval ^= (Fnv32_t) *bp++;
- for (i = 0; i < len; i++)
- {
- hash = hash ^ chardata[i];
- hash = hash * fnv1a_prime;
+ /* multiply by the 32 bit FNV magic prime mod 2^32 */
+#if defined(NO_FNV_GCC_OPTIMIZATION)
+ hval *= FNV_32_PRIME;
+#else
+ hval +=
+ (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
+#endif
}
- return hash;
+ /* return our new hash value */
+ return hval;
}
-u64
-hash64 (const void *data, size_t len)
+u32
+hash32 (const void *data, size_t len)
{
- // Standard FNV 64-bit offset: see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param
- const u64 fnv1a_offset = 0xCBF29CE484222325ULL;
- return cumulative_hash64 (data, len, fnv1a_offset);
+ return cumulative_hash32 (data, len, FNV1_32A_INIT);
}
void
-hicn_packet_dump (const uint8_t * buffer, size_t len)
+hicn_packet_dump (const uint8_t *buffer, size_t len)
{
int i;
unsigned char buff[17];
diff --git a/lib/src/compat.c b/lib/src/compat.c
deleted file mode 100644
index 932c11d9e..000000000
--- a/lib/src/compat.c
+++ /dev/null
@@ -1,1273 +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.
- */
-
-/**
- * @file compat.c
- * @brief Implementation of the compatibility layer.
- */
-#ifndef _WIN32
-#include <netinet/in.h>
-#endif
-#include <string.h> // memset
-#include <stddef.h> // offsetof
-
-#include <hicn/common.h>
-#include <hicn/compat.h>
-#include <hicn/error.h>
-#include <hicn/header.h>
-#include <hicn/name.h>
-#include <hicn/ops.h>
-
-#define member_size(type, member) sizeof (((type *) 0)->member)
-#define ARRAY_SIZE(a) (sizeof (a) / sizeof (*(a)))
-
-#define HICN_NAME_COMPONENT_SIZE 2
-
-int
-hicn_packet_get_format (const hicn_header_t *h, hicn_format_t *format)
-{
- *format = HF_UNSPEC;
-
- switch (HICN_IP_VERSION (h))
- {
- case 4:
- switch (h->v4.ip.protocol)
- {
- case IPPROTO_TCP:
- if (h->v4.tcp.flags & AH_FLAG)
- *format = HF_INET_TCP_AH;
- else
- *format = HF_INET_TCP;
- break;
- case IPPROTO_ICMP:
- *format = HF_INET_ICMP;
- break;
- default:
- return HICN_LIB_ERROR_NOT_HICN;
- }
- break;
- case 6:
- switch (h->v6.ip.nxt)
- {
- case IPPROTO_TCP:
- if (h->v6.tcp.flags & AH_FLAG)
- *format = HF_INET6_TCP_AH;
- else
- *format = HF_INET6_TCP;
- break;
- case IPPROTO_ICMPV6:
- *format = HF_INET6_ICMP;
- break;
- default:
- return HICN_LIB_ERROR_NOT_HICN;
- }
- break;
- default:
- return HICN_LIB_ERROR_NOT_HICN;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-/**
- * @brief Convert (former) hICN format into (newer) hICN type
- * @param [in] format - hICN format
- * @return hICN type, all zero'ed if type is unknown
- */
-hicn_type_t
-hicn_format_to_type (hicn_format_t format)
-{
- switch (format)
- {
- case HF_INET_TCP:
- return HICN_TYPE_IPV4_TCP;
- case HF_INET6_TCP:
- return HICN_TYPE_IPV6_TCP;
- case HF_INET_ICMP:
- return HICN_TYPE_IPV4_ICMP;
- case HF_INET6_ICMP:
- return HICN_TYPE_IPV6_ICMP;
- case HF_INET_TCP_AH:
- return HICN_TYPE_IPV4_TCP_AH;
- case HF_INET6_TCP_AH:
- return HICN_TYPE_IPV6_TCP_AH;
- case HF_INET_ICMP_AH:
- return HICN_TYPE_IPV4_ICMP_AH;
- case HF_INET6_ICMP_AH:
- return HICN_TYPE_IPV6_ICMP_AH;
- default:
- break;
- }
- return HICN_TYPE_NONE;
-}
-
-/**
- * @brief Parse hICN header and return hICN type
- * @param [in] h - hICN header
- * @param [out] format - hICN type
- * @return hICN error code
- *
- * This function is used to wrap old API calls to new ones
- */
-hicn_type_t
-hicn_header_to_type (const hicn_header_t *h)
-{
- hicn_format_t format;
- hicn_packet_get_format (h, &format);
- return hicn_format_to_type (format);
-}
-
-int
-hicn_packet_init_header (hicn_format_t format, hicn_header_t *packet)
-{
- hicn_type_t type = hicn_format_to_type (format);
-
- if (hicn_type_is_none (type))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- return hicn_ops_vft[type.l1]->init_packet_header (type, &packet->protocol);
-}
-
-int
-hicn_packet_compute_checksum (hicn_format_t format, hicn_header_t *h)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->update_checksums (type, &h->protocol, 0, ~0);
-}
-
-int
-hicn_packet_compute_header_checksum (hicn_format_t format, hicn_header_t *h,
- u16 init_sum)
-{
- hicn_type_t type = hicn_format_to_type (format);
- /* payload_length == 0: ignore payload */
- return hicn_ops_vft[type.l1]->update_checksums (type, &h->protocol, init_sum,
- 0);
-}
-
-int
-hicn_packet_check_integrity_no_payload (hicn_format_t format, hicn_header_t *h,
- u16 init_sum)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->verify_checksums (type, &h->protocol, init_sum,
- 0);
-}
-
-int
-hicn_packet_get_header_length_from_format (hicn_format_t format,
- size_t *header_length)
-{
- *header_length = _is_ipv4 (format) * IPV4_HDRLEN;
- *header_length += _is_ipv6 (format) * IPV6_HDRLEN;
- *header_length += _is_icmp (format) * ICMP_HDRLEN;
- *header_length += _is_tcp (format) * TCP_HDRLEN;
- *header_length += _is_ah (format) * AH_HDRLEN;
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_header_length (hicn_format_t format, const hicn_header_t *h,
- size_t *header_length)
-{
- hicn_packet_get_header_length_from_format (format, header_length);
- int is_ah = _is_ah (format);
- int is_ipv4 = _is_ipv4 (format);
- int is_ipv6 = _is_ipv6 (format);
- // The signature payload is expressed as number of 32 bits words
- if (is_ah && is_ipv4)
- *header_length += (h->v4ah.ah.payloadlen) << 2;
- else if (is_ah && is_ipv6)
- *header_length += (h->v6ah.ah.payloadlen) << 2;
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_payload_length (hicn_format_t format, const hicn_header_t *h,
- size_t *payload_length)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->get_payload_length (type, &h->protocol,
- payload_length);
-}
-
-int
-hicn_packet_set_payload_length (hicn_format_t format, hicn_header_t *h,
- const size_t payload_length)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->set_payload_length (type, &h->protocol,
- payload_length);
-}
-
-int
-hicn_packet_compare (const hicn_header_t *packet1,
- const hicn_header_t *packet2)
-{
- hicn_type_t type1 = hicn_header_to_type (packet1);
- hicn_type_t type2 = hicn_header_to_type (packet2);
-
- size_t len1, len2;
- int rc;
-
- if (type1.as_u32 != type2.as_u32)
- return HICN_LIB_ERROR_UNEXPECTED;
-
- rc = hicn_ops_vft[type1.l1]->get_length (type1, &packet1->protocol, &len1);
- if (PREDICT_FALSE (rc < 0))
- return HICN_LIB_ERROR_UNEXPECTED;
-
- rc = hicn_ops_vft[type2.l1]->get_length (type2, &packet2->protocol, &len2);
- if (PREDICT_FALSE (rc < 0))
- return HICN_LIB_ERROR_UNEXPECTED;
-
- if (len1 != len2)
- return HICN_LIB_ERROR_UNEXPECTED;
-
- return memcmp ((u8 *) packet1, (u8 *) packet2, len1);
-}
-
-int
-hicn_packet_get_name (hicn_format_t format, const hicn_header_t *h,
- hicn_name_t *name, u8 is_interest)
-{
- hicn_type_t type = hicn_format_to_type (format);
-
- if (is_interest)
- return hicn_ops_vft[type.l1]->get_interest_name (type, &h->protocol, name);
- else
- return hicn_ops_vft[type.l1]->get_data_name (type, &h->protocol, name);
-}
-
-int
-hicn_packet_set_name (hicn_format_t format, hicn_header_t *h,
- const hicn_name_t *name, u8 is_interest)
-{
- hicn_type_t type = hicn_format_to_type (format);
-
-#ifndef HICN_VPP_PLUGIN
- if (name->type & HNT_IOV)
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
-#endif /* HICN_VPP_PLUGIN */
-
- if (is_interest)
- return hicn_ops_vft[type.l1]->set_interest_name (type, &h->protocol, name);
- else
- return hicn_ops_vft[type.l1]->set_data_name (type, &h->protocol, name);
-}
-
-int
-hicn_packet_set_payload (hicn_format_t format, hicn_header_t *h,
- const u8 *payload, u16 payload_length)
-{
- hicn_type_t type = hicn_format_to_type (format);
- size_t header_length;
- int rc;
-
- rc = hicn_ops_vft[type.l1]->get_header_length (type, &h->protocol,
- &header_length);
- if (rc < 0)
- return rc;
-
- memcpy ((u8 *) h + header_length, payload, payload_length);
-
- return hicn_ops_vft[type.l1]->set_payload_length (type, &h->protocol,
- payload_length);
-}
-
-int
-hicn_packet_get_payload (hicn_format_t format, const hicn_header_t *h,
- u8 **payload, size_t *payload_size, bool hard_copy)
-{
- size_t header_length, payload_length;
- int rc;
- hicn_type_t type = hicn_format_to_type (format);
-
- rc = hicn_ops_vft[type.l1]->get_header_length (type, &h->protocol,
- &header_length);
- if (rc < 0)
- return rc;
-
- rc = hicn_ops_vft[type.l1]->get_payload_length (type, &h->protocol,
- &payload_length);
- if (rc < 0)
- return rc;
-
- if (hard_copy)
- {
- memcpy (payload, (u8 *) h + header_length, payload_length);
- }
- else
- {
- *payload = (u8 *) h + header_length;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_locator (hicn_format_t format, const hicn_header_t *h,
- ip_address_t *address, bool is_interest)
-{
- int is_ipv4 = (format & HFO_INET);
- int is_ipv6 = (format & HFO_INET6) >> 1;
-
- if (is_ipv4)
- {
- address->v4.as_inaddr =
- is_interest ? h->v4.ip.saddr.as_inaddr : h->v4.ip.daddr.as_inaddr;
- }
- else if (is_ipv6)
- {
- address->v6.as_in6addr =
- is_interest ? h->v6.ip.saddr.as_in6addr : h->v6.ip.daddr.as_in6addr;
- }
- else
- {
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_locator (hicn_format_t format, hicn_header_t *h,
- const ip_address_t *address, bool is_interest)
-{
- int is_ipv4 = (format & HFO_INET);
- int is_ipv6 = (format & HFO_INET6) >> 1;
-
- if (is_ipv6)
- {
- if (is_interest)
- h->v6.ip.saddr.as_in6addr = address->v6.as_in6addr;
- else
- h->v6.ip.daddr.as_in6addr = address->v6.as_in6addr;
- }
- else if (is_ipv4)
- {
- if (is_interest)
- h->v4.ip.saddr.as_inaddr = address->v4.as_inaddr;
- else
- h->v4.ip.daddr.as_inaddr = address->v4.as_inaddr;
- }
- else
- {
- return HICN_LIB_ERROR_INVALID_PARAMETER;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_signature_size (hicn_format_t format, const hicn_header_t *h,
- size_t *bytes)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->get_signature_size (type, &h->protocol, bytes);
-}
-
-int
-hicn_packet_set_signature_size (hicn_format_t format, hicn_header_t *h,
- size_t bytes)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->set_signature_size (type, &h->protocol, bytes);
-}
-
-int
-hicn_packet_get_signature_gap (hicn_format_t format, const hicn_header_t *h,
- uint8_t *bytes)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->get_signature_gap (type, &h->protocol, bytes);
-}
-
-int
-hicn_packet_set_signature_gap (hicn_format_t format, hicn_header_t *h,
- uint8_t bytes)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->set_signature_gap (type, &h->protocol, bytes);
-}
-
-int
-hicn_packet_set_signature_timestamp (hicn_format_t format, hicn_header_t *h,
- uint64_t signature_timestamp)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->set_signature_timestamp (type, &h->protocol,
- signature_timestamp);
-}
-
-int
-hicn_packet_get_signature_timestamp (hicn_format_t format,
- const hicn_header_t *h,
- uint64_t *signature_timestamp)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->get_signature_timestamp (type, &h->protocol,
- signature_timestamp);
-}
-
-int
-hicn_packet_set_validation_algorithm (hicn_format_t format, hicn_header_t *h,
- uint8_t validation_algorithm)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->set_validation_algorithm (
- type, &h->protocol, validation_algorithm);
-}
-
-int
-hicn_packet_get_validation_algorithm (hicn_format_t format,
- const hicn_header_t *h,
- uint8_t *validation_algorithm)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->get_validation_algorithm (
- type, &h->protocol, validation_algorithm);
-}
-
-int
-hicn_packet_set_key_id (hicn_format_t format, hicn_header_t *h,
- uint8_t *key_id)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->set_key_id (type, &h->protocol, key_id);
-}
-
-int
-hicn_packet_get_key_id (hicn_format_t format, hicn_header_t *h,
- uint8_t **key_id, uint8_t *key_id_length)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->get_key_id (type, &h->protocol, key_id,
- key_id_length);
-}
-
-int
-hicn_packet_get_hoplimit (const hicn_header_t *h, u8 *hops)
-{
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *hops = h->v6.ip.hlim;
- break;
- case 4:
- *hops = h->v4.ip.ttl;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_hoplimit (hicn_header_t *h, u8 hops)
-{
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.ip.hlim = hops;
- break;
- case 4:
- h->v4.ip.ttl = hops;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_lifetime (const hicn_header_t *h, u32 *lifetime)
-{
- hicn_type_t type = hicn_header_to_type (h);
- return hicn_ops_vft[type.l1]->get_lifetime (type, &h->protocol,
- (hicn_lifetime_t *) lifetime);
-}
-
-int
-hicn_packet_set_lifetime (hicn_header_t *h, u32 lifetime)
-{
- hicn_type_t type = hicn_header_to_type (h);
- return hicn_ops_vft[type.l1]->set_lifetime (type, &h->protocol,
- (hicn_lifetime_t) lifetime);
-}
-
-int
-hicn_packet_get_reserved_bits (const hicn_header_t *h, u8 *reserved_bits)
-{
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *reserved_bits = (u8) (h->v6.tcp.reserved);
- break;
- case 4:
- *reserved_bits = (u8) (h->v4.tcp.reserved);
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_reserved_bits (hicn_header_t *h, const u8 reserved_bits)
-{
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.reserved = reserved_bits;
- break;
- case 4:
- h->v4.tcp.reserved = reserved_bits;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_payload_type (const hicn_header_t *h,
- hicn_payload_type_t *payload_type)
-{
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *payload_type =
- ((h->v6.tcp.flags & HICN_TCP_FLAG_URG) == HICN_TCP_FLAG_URG);
- break;
- case 4:
- *payload_type =
- ((h->v4.tcp.flags & HICN_TCP_FLAG_URG) == HICN_TCP_FLAG_URG);
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- if (*payload_type == HPT_UNSPEC)
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_payload_type (hicn_header_t *h,
- hicn_payload_type_t payload_type)
-{
- if (payload_type != HPT_DATA && payload_type != HPT_MANIFEST)
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- if (payload_type)
- h->v6.tcp.flags = h->v6.tcp.flags | HICN_TCP_FLAG_URG;
- else
- h->v6.tcp.flags = h->v6.tcp.flags & ~HICN_TCP_FLAG_URG;
- break;
- case 4:
- if (payload_type)
- h->v4.tcp.flags = h->v4.tcp.flags | HICN_TCP_FLAG_URG;
- else
- h->v4.tcp.flags = h->v4.tcp.flags & ~HICN_TCP_FLAG_URG;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_syn (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags | HICN_TCP_FLAG_SYN;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags | HICN_TCP_FLAG_SYN;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_reset_syn (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags & ~HICN_TCP_FLAG_SYN;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags & ~HICN_TCP_FLAG_SYN;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_test_syn (hicn_format_t format, const hicn_header_t *h, bool *flag)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *flag = h->v6.tcp.flags & HICN_TCP_FLAG_SYN;
- break;
- case 4:
- *flag = h->v4.tcp.flags & HICN_TCP_FLAG_SYN;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_ack (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags | HICN_TCP_FLAG_ACK;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags | HICN_TCP_FLAG_ACK;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_reset_ack (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags & ~HICN_TCP_FLAG_ACK;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags & ~HICN_TCP_FLAG_ACK;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_test_ack (hicn_format_t format, const hicn_header_t *h, bool *flag)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *flag = h->v6.tcp.flags & HICN_TCP_FLAG_ACK;
- break;
- case 4:
- *flag = h->v4.tcp.flags & HICN_TCP_FLAG_ACK;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_rst (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags | HICN_TCP_FLAG_RST;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags | HICN_TCP_FLAG_RST;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_reset_rst (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags & ~HICN_TCP_FLAG_RST;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags & ~HICN_TCP_FLAG_RST;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_test_rst (hicn_format_t format, const hicn_header_t *h, bool *flag)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *flag = h->v6.tcp.flags & HICN_TCP_FLAG_RST;
- break;
- case 4:
- *flag = h->v4.tcp.flags & HICN_TCP_FLAG_RST;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_fin (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags | HICN_TCP_FLAG_FIN;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags | HICN_TCP_FLAG_FIN;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_reset_fin (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags & ~HICN_TCP_FLAG_FIN;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags & ~HICN_TCP_FLAG_FIN;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_test_fin (hicn_format_t format, const hicn_header_t *h, bool *flag)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *flag = h->v6.tcp.flags & HICN_TCP_FLAG_FIN;
- break;
- case 4:
- *flag = h->v4.tcp.flags & HICN_TCP_FLAG_FIN;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_ece (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags | HICN_TCP_FLAG_ECE;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags | HICN_TCP_FLAG_ECE;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_reset_ece (hicn_format_t format, hicn_header_t *h)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.flags = h->v6.tcp.flags & ~HICN_TCP_FLAG_ECE;
- break;
- case 4:
- h->v4.tcp.flags = h->v4.tcp.flags & ~HICN_TCP_FLAG_ECE;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_test_ece (hicn_format_t format, const hicn_header_t *h, bool *flag)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *flag = h->v6.tcp.flags & HICN_TCP_FLAG_ECE;
- break;
- case 4:
- *flag = h->v4.tcp.flags & HICN_TCP_FLAG_ECE;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_src_port (hicn_format_t format, hicn_header_t *h, u16 src_port)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.sport = htons (src_port);
- break;
- case 4:
- h->v4.tcp.sport = htons (src_port);
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_src_port (hicn_format_t format, const hicn_header_t *h,
- u16 *src_port)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *src_port = ntohs (h->v6.tcp.sport);
- break;
- case 4:
- *src_port = ntohs (h->v4.tcp.sport);
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_set_dst_port (hicn_format_t format, hicn_header_t *h, u16 dst_port)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- h->v6.tcp.dport = htons (dst_port);
- break;
- case 4:
- h->v4.tcp.dport = htons (dst_port);
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_get_dst_port (hicn_format_t format, const hicn_header_t *h,
- u16 *dst_port)
-{
- if (!_is_tcp (format))
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
-
- switch (HICN_IP_VERSION (h))
- {
- case 6:
- *dst_port = ntohs (h->v6.tcp.dport);
- break;
- case 4:
- *dst_port = ntohs (h->v4.tcp.dport);
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
- return HICN_LIB_ERROR_NONE;
-}
-
-int
-hicn_packet_copy_header (hicn_format_t format, const hicn_header_t *packet,
- hicn_header_t *destination, bool copy_ah)
-{
- size_t header_length = _is_ipv4 (format) * IPV4_HDRLEN;
- header_length += _is_ipv6 (format) * IPV6_HDRLEN;
- header_length += _is_icmp (format) * ICMP_HDRLEN;
- header_length += _is_tcp (format) * TCP_HDRLEN;
- header_length += _is_ah (format) * copy_ah * AH_HDRLEN;
-
- memcpy (destination, packet, header_length);
-
- return HICN_LIB_ERROR_NONE;
-}
-
-#define _INTEREST 1
-#define _DATA 0
-
-/* Interest */
-
-int
-hicn_interest_get_name (hicn_format_t format, const hicn_header_t *interest,
- hicn_name_t *name)
-{
- return hicn_packet_get_name (format, interest, name, _INTEREST);
-}
-
-int
-hicn_interest_set_name (hicn_format_t format, hicn_header_t *interest,
- const hicn_name_t *name)
-{
- int ret_err = hicn_packet_reset_ece (
- format, interest); // interest packet -> ece flag unset
- if (ret_err < 0)
- return HICN_LIB_ERROR_UNEXPECTED;
- return hicn_packet_set_name (format, interest, name, _INTEREST);
-}
-
-int
-hicn_interest_get_locator (hicn_format_t format, const hicn_header_t *interest,
- ip_address_t *address)
-{
- return hicn_packet_get_locator (format, interest, address, _INTEREST);
-}
-
-int
-hicn_interest_set_locator (hicn_format_t format, hicn_header_t *interest,
- const ip_address_t *address)
-{
- return hicn_packet_set_locator (format, interest, address, _INTEREST);
-}
-
-int
-hicn_interest_compare (const hicn_header_t *interest_1,
- const hicn_header_t *interest_2)
-{
- return hicn_packet_compare (interest_1, interest_2);
-}
-
-int
-hicn_interest_get_lifetime (const hicn_header_t *interest, u32 *lifetime)
-{
- return hicn_packet_get_lifetime (interest, lifetime);
-}
-
-int
-hicn_interest_set_lifetime (hicn_header_t *interest, u32 lifetime)
-{
- return hicn_packet_set_lifetime (interest, lifetime);
-}
-
-int
-hicn_interest_get_header_length (hicn_format_t format,
- const hicn_header_t *interest,
- size_t *header_length)
-{
- return hicn_packet_get_header_length (format, interest, header_length);
-}
-
-int
-hicn_interest_get_payload_length (hicn_format_t format,
- const hicn_header_t *interest,
- size_t *payload_length)
-{
- return hicn_packet_get_payload_length (format, interest, payload_length);
-}
-
-int
-hicn_interest_get_payload (hicn_format_t format, const hicn_header_t *interest,
- u8 **payload, size_t *payload_size, bool hard_copy)
-{
- return hicn_packet_get_payload (format, interest, payload, payload_size,
- hard_copy);
-}
-
-int
-hicn_interest_set_payload (hicn_format_t format, hicn_header_t *interest,
- const u8 *payload, size_t payload_length)
-{
- return hicn_packet_set_payload (format, interest, payload,
- (u16) payload_length);
-}
-
-int
-hicn_interest_reset_for_hash (hicn_format_t format, hicn_header_t *packet)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->reset_interest_for_hash (type,
- &packet->protocol);
-}
-
-/* Data */
-
-int
-hicn_data_get_name (hicn_format_t format, const hicn_header_t *data,
- hicn_name_t *name)
-{
- return hicn_packet_get_name (format, data, name, _DATA);
-}
-
-int
-hicn_data_set_name (hicn_format_t format, hicn_header_t *data,
- const hicn_name_t *name)
-{
- int ret_err =
- hicn_packet_set_ece (format, data); // data packet -> ece flag set
- if (ret_err < 0)
- return HICN_LIB_ERROR_UNEXPECTED;
- return hicn_packet_set_name (format, data, name, _DATA);
-}
-
-int
-hicn_data_get_locator (hicn_format_t format, const hicn_header_t *data,
- ip_address_t *address)
-{
- return hicn_packet_get_locator (format, data, address, _DATA);
-}
-
-int
-hicn_data_set_locator (hicn_format_t format, hicn_header_t *data,
- const ip_address_t *address)
-{
- return hicn_packet_set_locator (format, data, address, _DATA);
-}
-
-int
-hicn_data_compare (const hicn_header_t *data_1, const hicn_header_t *data_2)
-{
- return hicn_packet_compare (data_1, data_2);
-}
-
-int
-hicn_data_get_expiry_time (const hicn_header_t *data, u32 *expiry_time)
-{
- return hicn_packet_get_lifetime (data, expiry_time);
-}
-
-int
-hicn_data_set_expiry_time (hicn_header_t *data, u32 expiry_time)
-{
- return hicn_packet_set_lifetime (data, (hicn_lifetime_t) expiry_time);
-}
-
-int
-hicn_data_get_header_length (hicn_format_t format, hicn_header_t *data,
- size_t *header_length)
-{
- return hicn_packet_get_header_length (format, data, header_length);
-}
-
-int
-hicn_data_get_payload_length (hicn_format_t format, const hicn_header_t *data,
- size_t *payload_length)
-{
- return hicn_packet_get_payload_length (format, data, payload_length);
-}
-
-int
-hicn_data_set_payload_type (hicn_header_t *data,
- hicn_payload_type_t payload_type)
-{
- return hicn_packet_set_payload_type (data, payload_type);
-}
-
-int
-hicn_data_get_payload_type (const hicn_header_t *data,
- hicn_payload_type_t *payload_type)
-{
- return hicn_packet_get_payload_type (data, payload_type);
-}
-
-int
-hicn_data_get_path_label (const hicn_header_t *data, u32 *path_label)
-{
- hicn_type_t type = hicn_header_to_type (data);
- return hicn_ops_vft[type.l1]->get_data_pathlabel (type, &data->protocol,
- path_label);
-}
-
-int
-hicn_data_set_path_label (hicn_header_t *data, u32 path_label)
-{
- hicn_type_t type = hicn_header_to_type (data);
- return hicn_ops_vft[type.l1]->set_data_pathlabel (type, &data->protocol,
- path_label);
-}
-
-int
-hicn_data_set_payload (hicn_format_t format, hicn_header_t *data,
- const u8 *payload, size_t payload_length)
-{
- return hicn_packet_set_payload (format, data, payload, (u16) payload_length);
-}
-
-int
-hicn_data_get_payload (hicn_format_t format, const hicn_header_t *data,
- u8 **payload, size_t *payload_size, bool hard_copy)
-{
- return hicn_packet_get_payload (format, data, payload, payload_size,
- hard_copy);
-}
-
-int
-hicn_data_reset_for_hash (hicn_format_t format, hicn_header_t *packet)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->reset_data_for_hash (type, &packet->protocol);
-}
-
-int
-hicn_packet_get_signature (hicn_format_t format, hicn_header_t *packet,
- uint8_t **sign_buf)
-{
- hicn_type_t type = hicn_format_to_type (format);
- return hicn_ops_vft[type.l1]->get_signature (type, &packet->protocol,
- sign_buf);
-}
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables:
- * eval: (c-set-style "gnu")
- * End:
- */
diff --git a/lib/src/error.c b/lib/src/error.c
index ab5d6e27d..0d7c80d9b 100644
--- a/lib/src/error.c
+++ b/lib/src/error.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,7 +21,7 @@
#include <hicn/error.h>
const char *HICN_LIB_ERROR_STRING[] = {
-#define _(a,b,c) [b] = c,
+#define _(a, b, c) [b] = c,
foreach_libhicn_error
#undef _
};
diff --git a/lib/src/face.c b/lib/src/face.c
new file mode 100644
index 000000000..81395c4b1
--- /dev/null
+++ b/lib/src/face.c
@@ -0,0 +1,455 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file face.c
+ * \brief Implementation of face abstraction
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <hicn/face.h>
+#include <hicn/util/token.h>
+
+#define member_size(type, member) sizeof (((type *) 0)->member)
+
+/* Netdevice */
+
+const char *_netdevice_type_str[] = {
+#define _(x) [NETDEVICE_TYPE_##x] = STRINGIZE (x),
+ foreach_netdevice_type
+#undef _
+};
+
+netdevice_t *
+netdevice_create_from_index (u32 index)
+{
+ netdevice_t *netdevice = malloc (sizeof (netdevice_t));
+ if (!netdevice)
+ goto ERR_MALLOC;
+
+ int rc = netdevice_set_index (netdevice, index);
+ if (rc < 0)
+ goto ERR_INIT;
+
+ return netdevice;
+
+ERR_INIT:
+ free (netdevice);
+ERR_MALLOC:
+ return NULL;
+}
+
+netdevice_t *
+netdevice_create_from_name (const char *name)
+{
+ netdevice_t *netdevice = malloc (sizeof (netdevice_t));
+ if (!netdevice)
+ goto ERR_MALLOC;
+
+ int rc = netdevice_set_name (netdevice, name);
+ if (rc < 0)
+ goto ERR_INIT;
+
+ return netdevice;
+
+ERR_INIT:
+ free (netdevice);
+ERR_MALLOC:
+ return NULL;
+}
+
+/**
+ * \brief Update the index of the netdevice based on the name
+ */
+int
+netdevice_update_index (netdevice_t *netdevice)
+{
+ netdevice->index = if_nametoindex (netdevice->name);
+ if (netdevice->index == 0)
+ return -1;
+ return 0;
+}
+
+int
+netdevice_update_name (netdevice_t *netdevice)
+{
+ if (!if_indextoname (netdevice->index, netdevice->name))
+ return -1;
+ return 0;
+}
+
+void
+netdevice_free (netdevice_t *netdevice)
+{
+ free (netdevice);
+}
+
+int
+netdevice_get_index (const netdevice_t *netdevice, u32 *index)
+{
+ if (netdevice->index == 0)
+ return -1;
+ *index = netdevice->index;
+ return 0;
+}
+
+int
+netdevice_set_index (netdevice_t *netdevice, u32 index)
+{
+ netdevice->index = index;
+ return netdevice_update_name (netdevice);
+}
+
+int
+netdevice_get_name (const netdevice_t *netdevice, const char **name)
+{
+ if (netdevice->name[0] == '\0')
+ return -1;
+ *name = netdevice->name;
+ return 0;
+}
+
+int
+netdevice_set_name (netdevice_t *netdevice, const char *name)
+{
+ memset (netdevice->name, 0, sizeof (netdevice->name));
+ int rc = snprintf (netdevice->name, IFNAMSIZ, "%s", name);
+ if (rc < 0)
+ return -1;
+ if (rc >= IFNAMSIZ)
+ return -2; /* truncated */
+ return netdevice_update_index (netdevice);
+}
+
+int
+netdevice_cmp (const netdevice_t *nd1, const netdevice_t *nd2)
+{
+ return (nd1->index - nd2->index);
+}
+
+bool
+netdevice_is_empty (const netdevice_t *netdevice)
+{
+ return (netdevice->index != 0) || (netdevice->name[0] != '\0');
+}
+
+/* Face state */
+
+const char *_face_state_str[] = {
+#define _(x) [FACE_STATE_##x] = STRINGIZE (x),
+ foreach_face_state
+#undef _
+};
+
+/* Face type */
+
+const char *_face_type_str[] = {
+#define _(x) [FACE_TYPE_##x] = STRINGIZE (x),
+ foreach_face_type
+#undef _
+};
+
+face_type_t
+face_type_from_str (const char *str)
+{
+#define _(x) \
+ if (strcasecmp (str, STRINGIZE (x)) == 0) \
+ return FACE_TYPE_##x; \
+ else
+ foreach_face_type
+#undef _
+ return FACE_TYPE_UNDEFINED;
+}
+
+/* Face */
+
+int
+face_initialize (face_t *face)
+{
+ memset (face, 0, sizeof (face_t)); /* 0'ed for hash */
+ return 1;
+}
+
+int
+face_initialize_udp (face_t *face, const char *interface_name,
+ const hicn_ip_address_t *local_addr, u16 local_port,
+ const hicn_ip_address_t *remote_addr, u16 remote_port,
+ int family)
+{
+ if (!local_addr)
+ return -1;
+
+ *face = (face_t){
+ .type = FACE_TYPE_UDP,
+ .family = family,
+ .local_addr = *local_addr,
+ .local_port = local_port,
+ .remote_addr = remote_addr ? *remote_addr : IP_ADDRESS_EMPTY,
+ .remote_port = remote_port,
+ };
+
+ snprintf (face->netdevice.name, IFNAMSIZ, "%s", interface_name);
+
+ return 1;
+}
+
+int
+face_initialize_udp_sa (face_t *face, const char *interface_name,
+ const struct sockaddr *local_addr,
+ const struct sockaddr *remote_addr)
+{
+ if (!local_addr)
+ return -1;
+
+ if (remote_addr && (local_addr->sa_family != remote_addr->sa_family))
+ return -1;
+
+ switch (local_addr->sa_family)
+ {
+ case AF_INET:
+ {
+ struct sockaddr_in *lsai = (struct sockaddr_in *) local_addr;
+ struct sockaddr_in *rsai = (struct sockaddr_in *) remote_addr;
+ *face = (face_t){
+ .type = FACE_TYPE_UDP,
+ .family = AF_INET,
+ .local_addr.v4.as_inaddr = lsai->sin_addr,
+ .local_port = lsai ? ntohs (lsai->sin_port) : 0,
+ .remote_addr = IP_ADDRESS_EMPTY,
+ .remote_port = rsai ? ntohs (rsai->sin_port) : 0,
+ };
+ if (rsai)
+ face->remote_addr.v4.as_inaddr = rsai->sin_addr;
+ }
+ break;
+ case AF_INET6:
+ {
+ struct sockaddr_in6 *lsai = (struct sockaddr_in6 *) local_addr;
+ struct sockaddr_in6 *rsai = (struct sockaddr_in6 *) remote_addr;
+ *face = (face_t){
+ .type = FACE_TYPE_UDP,
+ .family = AF_INET6,
+ .local_addr.v6.as_in6addr = lsai->sin6_addr,
+ .local_port = lsai ? ntohs (lsai->sin6_port) : 0,
+ .remote_addr = IP_ADDRESS_EMPTY,
+ .remote_port = rsai ? ntohs (rsai->sin6_port) : 0,
+ };
+ if (rsai)
+ face->remote_addr.v6.as_in6addr = rsai->sin6_addr;
+ }
+ break;
+ default:
+ return -1;
+ }
+
+ snprintf (face->netdevice.name, IFNAMSIZ, "%s", interface_name);
+
+ return 1;
+}
+
+face_t *
+face_create ()
+{
+ face_t *face = calloc (1, sizeof (face_t)); /* 0'ed for hash */
+ return face;
+}
+
+face_t *
+face_create_udp (const char *interface_name,
+ const hicn_ip_address_t *local_addr, u16 local_port,
+ const hicn_ip_address_t *remote_addr, u16 remote_port,
+ int family)
+{
+ face_t *face = face_create ();
+ if (face_initialize_udp (face, interface_name, local_addr, local_port,
+ remote_addr, remote_port, family) < 0)
+ goto ERR_INIT;
+ return face;
+
+ERR_INIT:
+ free (face);
+ return NULL;
+}
+
+face_t *
+face_create_udp_sa (const char *interface_name,
+ const struct sockaddr *local_addr,
+ const struct sockaddr *remote_addr)
+{
+ face_t *face = face_create ();
+ if (face_initialize_udp_sa (face, interface_name, local_addr, remote_addr) <
+ 0)
+ goto ERR_INIT;
+ return face;
+
+ERR_INIT:
+ free (face);
+ return NULL;
+}
+
+void
+face_free (face_t *face)
+{
+ free (face);
+}
+
+/**
+ * \brief Compare two faces
+ * \param [in] f1 - First face
+ * \param [in] f2 - Second face
+ * \return whether faces are equal, ie both their types are parameters are
+ * equal.
+ *
+ * NOTE: this function implements a partial order.
+ */
+int
+face_cmp (const face_t *f1, const face_t *f2)
+{
+
+ int ret = f1->type - f2->type;
+ if (ret != 0)
+ return ret;
+
+ ret = f1->family - f2->family;
+ if (ret != 0)
+ return ret;
+
+ /*
+ * FIXME As hicn-light API might not return the netdevice, we can discard the
+ * comparison when one of the two is not set for now...
+ */
+ if ((f1->netdevice.index != 0) && (f2->netdevice.index != 0))
+ {
+ ret = netdevice_cmp (&f1->netdevice, &f2->netdevice);
+ if (ret != 0)
+ return ret;
+ }
+
+ switch (f1->type)
+ {
+ case FACE_TYPE_HICN:
+ ret = hicn_ip_address_cmp (&f1->local_addr, &f2->local_addr);
+ if (ret != 0)
+ return ret;
+
+ ret = hicn_ip_address_cmp (&f1->remote_addr, &f2->remote_addr);
+ if (ret != 0)
+ return ret;
+
+ break;
+
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_UDP:
+ ret = hicn_ip_address_cmp (&f1->local_addr, &f2->local_addr);
+ if (ret != 0)
+ return ret;
+
+ ret = f1->local_port - f2->local_port;
+ if (ret != 0)
+ return ret;
+
+ ret = hicn_ip_address_cmp (&f1->remote_addr, &f2->remote_addr);
+ if (ret != 0)
+ return ret;
+
+ ret = f1->remote_port - f2->remote_port;
+ if (ret != 0)
+ return ret;
+
+ break;
+ default:
+ break;
+ }
+
+ return 0;
+}
+
+/* /!\ Please update constants in header file upon changes */
+size_t
+face_snprintf (char *s, size_t size, const face_t *face)
+{
+ char local[MAXSZ_IP_ADDRESS];
+ char remote[MAXSZ_IP_ADDRESS];
+ char tags[MAXSZ_POLICY_TAGS];
+
+ if (!hicn_ip_address_match_family (&face->local_addr, face->family))
+ return 0;
+ if (!hicn_ip_address_match_family (&face->remote_addr, face->family))
+ return 0;
+
+ hicn_ip_address_snprintf (local, MAXSZ_IP_ADDRESS, &face->local_addr);
+ hicn_ip_address_snprintf (remote, MAXSZ_IP_ADDRESS, &face->remote_addr);
+ policy_tags_snprintf (tags, MAXSZ_POLICY_TAGS, face->tags);
+
+ switch (face->type)
+ {
+ case FACE_TYPE_HICN:
+ {
+
+ return snprintf (s, size, "%s [%s -> %s] [%s]",
+ face_type_str (face->type), local, remote, tags);
+ }
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_UDP:
+ {
+ return snprintf (s, size, "%s [%s:%d -> %s:%d] [%s]",
+ face_type_str (face->type), local, face->local_port,
+ remote, face->remote_port, tags);
+ }
+ default:
+ return -1;
+ }
+}
+
+policy_tags_t
+face_get_tags (const face_t *face)
+{
+ return face->tags;
+}
+
+int
+face_set_tags (face_t *face, policy_tags_t tags)
+{
+ face->tags = tags;
+ return 1;
+}
+
+face_protocol_t
+get_protocol (face_type_t face_type)
+{
+ switch (face_type)
+ {
+ case FACE_TYPE_HICN:
+ case FACE_TYPE_HICN_LISTENER:
+ return FACE_PROTOCOL_HICN;
+
+ case FACE_TYPE_TCP:
+ case FACE_TYPE_TCP_LISTENER:
+ return FACE_PROTOCOL_TCP;
+
+ case FACE_TYPE_UDP:
+ case FACE_TYPE_UDP_LISTENER:
+ return FACE_PROTOCOL_UDP;
+
+ case FACE_TYPE_UNDEFINED:
+ case FACE_TYPE_N:
+ break;
+ }
+ return FACE_PROTOCOL_UNKNOWN;
+}
diff --git a/lib/src/libhicn-config.cmake.in b/lib/src/libhicn-config.cmake.in
new file mode 100644
index 000000000..1ae219280
--- /dev/null
+++ b/lib/src/libhicn-config.cmake.in
@@ -0,0 +1,12 @@
+set(Libhicn_VERSION "@VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@")
+
+@PACKAGE_INIT@
+
+set(Libhicn_VERSION_MAJOR "@VERSION_MAJOR@")
+set(Libhicn_VERSION_MINOR "@VERSION_MINOR@")
+set(Libhicn_VERSION_PATCH "@VERSION_PATCH@")
+
+set_and_check(Libhicn_INCLUDE_DIRS "@PACKAGE_Libhicn_INCLUDE_DIRS@")
+include("${CMAKE_CURRENT_LIST_DIR}/libhicn-targets.cmake")
+
+check_required_components(Libhicn)
diff --git a/lib/src/mapme.c b/lib/src/mapme.c
index 3e7e8bc80..3f864e768 100644
--- a/lib/src/mapme.c
+++ b/lib/src/mapme.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,12 +22,48 @@
#include <hicn/common.h>
#include <hicn/error.h>
-#include <hicn/protocol/ipv4.h>
-#include <hicn/protocol/ipv6.h>
+#include "protocol/ipv4.h"
+#include "protocol/ipv6.h"
+#include "protocol/icmprd.h"
+
+/** @brief MAP-Me packet header for IPv4 */
+typedef struct
+{
+ _ipv4_header_t ip;
+ _icmprd4_header_t icmp_rd;
+ seq_t seq;
+ u8 len;
+ u8 _pad[3];
+} hicn_mapme_v4_header_t;
+
+/** @brief MAP-Me packet header for IPv6 */
+typedef struct
+{
+ _ipv6_header_t ip;
+ _icmprd_header_t icmp_rd;
+ seq_t seq;
+ u8 len;
+ u8 _pad[3];
+} hicn_mapme_v6_header_t;
+
+/** @brief MAP-Me packet header (IP version agnostic) */
+typedef union
+{
+ hicn_mapme_v4_header_t v4;
+ hicn_mapme_v6_header_t v6;
+} hicn_mapme_header_t;
+
+#define HICN_MAPME_V4_HDRLEN sizeof (hicn_mapme_v4_header_t)
+#define HICN_MAPME_V6_HDRLEN sizeof (hicn_mapme_v6_header_t)
+
+static_assert (EXPECTED_MAPME_V4_HDRLEN == HICN_MAPME_V4_HDRLEN,
+ "Size of MAPME_V4 struct does not match its expected size.");
+static_assert (EXPECTED_MAPME_V6_HDRLEN == HICN_MAPME_V6_HDRLEN,
+ "Size of MAPME_V6 struct does not match its expected size.");
size_t
-hicn_mapme_v4_create_packet (u8 * buf, const hicn_prefix_t * prefix,
- const mapme_params_t * params)
+hicn_mapme_v4_create_packet (u8 *buf, const hicn_prefix_t *prefix,
+ const mapme_params_t *params)
{
hicn_mapme_v4_header_t *mh = (hicn_mapme_v4_header_t *) buf;
/* *INDENT-OFF* */
@@ -41,14 +77,14 @@ hicn_mapme_v4_create_packet (u8 * buf, const hicn_prefix_t * prefix,
.ttl = HICN_MAPME_TTL,
.protocol = IPPROTO_ICMP,
.csum = 0,
- .saddr.as_u32 = 0,
- .daddr = prefix->name.ip4,
+ .saddr.as_u32 = IPV4_LOOPBACK.v4.as_u32,
+ .daddr = prefix->name.v4,
},
.icmp_rd = {
.type = ((params->type == UPDATE) || (params->type == NOTIFICATION)) ? HICN_MAPME_ICMP_TYPE_IPV4 : HICN_MAPME_ICMP_TYPE_ACK_IPV4,
.code = HICN_MAPME_ICMP_CODE,
.csum = 0,
- .ip = prefix->name.ip4,
+ .ip = prefix->name.v4,
},
.seq = htonl(params->seq),
.len = prefix->len,
@@ -59,15 +95,15 @@ hicn_mapme_v4_create_packet (u8 * buf, const hicn_prefix_t * prefix,
}
size_t
-hicn_mapme_v6_create_packet (u8 * buf, const hicn_prefix_t * prefix,
- const mapme_params_t * params)
+hicn_mapme_v6_create_packet (u8 *buf, const hicn_prefix_t *prefix,
+ const mapme_params_t *params)
{
hicn_mapme_v6_header_t *mh = (hicn_mapme_v6_header_t *) buf;
/* *INDENT-OFF* */
*mh = (hicn_mapme_v6_header_t) {
.ip = {
- .saddr = {{0}},
- .daddr = prefix->name.ip6,
+ .saddr = IPV6_LOOPBACK.v6,
+ .daddr = prefix->name.v6,
.version_class_flow = htonl(
(IPV6_DEFAULT_VERSION << 28) |
(IPV6_DEFAULT_TRAFFIC_CLASS << 20) |
@@ -81,8 +117,8 @@ hicn_mapme_v6_create_packet (u8 * buf, const hicn_prefix_t * prefix,
.code = HICN_MAPME_ICMP_CODE,
.csum = 0,
.res = 0,
- .tgt = prefix->name.ip6,
- .dst = prefix->name.ip6,
+ .tgt = prefix->name.v6,
+ .dst = prefix->name.v6,
},
.seq = htonl(params->seq),
.len = prefix->len,
@@ -92,20 +128,20 @@ hicn_mapme_v6_create_packet (u8 * buf, const hicn_prefix_t * prefix,
}
size_t
-hicn_mapme_create_packet (u8 * buf, const hicn_prefix_t * prefix,
- const mapme_params_t * params)
+hicn_mapme_create_packet (u8 *buf, const hicn_prefix_t *prefix,
+ const mapme_params_t *params)
{
/* We currently ignore subsequent protocol definitions */
- if (PREDICT_TRUE (params->protocol == IPPROTO_IPV6))
+ if (HICN_EXPECT_TRUE (params->protocol == IPPROTO_IPV6))
return hicn_mapme_v6_create_packet (buf, prefix, params);
else
return hicn_mapme_v4_create_packet (buf, prefix, params);
}
size_t
-hicn_mapme_v4_create_ack (u8 * buf, const mapme_params_t * params)
+hicn_mapme_v4_create_ack (u8 *buf, const mapme_params_t *params)
{
- ip4_address_t tmp; // tmp storage for swapping IP addresses for ACK
+ ipv4_address_t tmp; // tmp storage for swapping IP addresses for ACK
hicn_mapme_v4_header_t *mh = (hicn_mapme_v4_header_t *) buf;
tmp = mh->ip.daddr;
@@ -119,9 +155,9 @@ hicn_mapme_v4_create_ack (u8 * buf, const mapme_params_t * params)
}
size_t
-hicn_mapme_v6_create_ack (u8 * buf, const mapme_params_t * params)
+hicn_mapme_v6_create_ack (u8 *buf, const mapme_params_t *params)
{
- ip6_address_t tmp; // tmp storage for swapping IP addresses for ACK
+ ipv6_address_t tmp; // tmp storage for swapping IP addresses for ACK
hicn_mapme_v6_header_t *mh = (hicn_mapme_v6_header_t *) buf;
tmp = mh->ip.daddr;
@@ -135,32 +171,33 @@ hicn_mapme_v6_create_ack (u8 * buf, const mapme_params_t * params)
}
size_t
-hicn_mapme_create_ack (u8 * buf, const mapme_params_t * params)
+hicn_mapme_create_ack (u8 *buf, const mapme_params_t *params)
{
/* We currently ignore subsequent protocol definitions */
- if (PREDICT_TRUE (params->protocol == IPPROTO_IPV6))
+ if (HICN_EXPECT_TRUE (params->protocol == IPPROTO_IPV6))
return hicn_mapme_v6_create_ack (buf, params);
else
return hicn_mapme_v4_create_ack (buf, params);
}
int
-hicn_mapme_v4_parse_packet (const u8 * packet, hicn_prefix_t * prefix,
- mapme_params_t * params)
+hicn_mapme_v4_parse_packet (const u8 *packet, hicn_prefix_t *prefix,
+ mapme_params_t *params)
{
hicn_mapme_v4_header_t *mh = (hicn_mapme_v4_header_t *) packet;
/* *INDENT-OFF* */
*prefix = (hicn_prefix_t) {
.name = {
- .ip4 = HICN_MAPME_TYPE_IS_IU (mh->icmp_rd.type) ? mh->ip.daddr : mh->ip.saddr,
+ .v4 = HICN_MAPME_TYPE_IS_IU (mh->icmp_rd.type) ? mh->ip.daddr : mh->ip.saddr,
},
.len = mh->len,
};
- *params = (mapme_params_t) {
+ *params = (mapme_params_t){
.protocol = IPPROTO_IP,
- .type = (mh->icmp_rd.type == HICN_MAPME_ICMP_TYPE_IPV4) ? UPDATE : UPDATE_ACK,
+ .type =
+ (mh->icmp_rd.type == HICN_MAPME_ICMP_TYPE_IPV4) ? UPDATE : UPDATE_ACK,
.seq = ntohl (mh->seq),
};
/* *INDENT-ON* */
@@ -169,22 +206,23 @@ hicn_mapme_v4_parse_packet (const u8 * packet, hicn_prefix_t * prefix,
}
int
-hicn_mapme_v6_parse_packet (const u8 * packet, hicn_prefix_t * prefix,
- mapme_params_t * params)
+hicn_mapme_v6_parse_packet (const u8 *packet, hicn_prefix_t *prefix,
+ mapme_params_t *params)
{
hicn_mapme_v6_header_t *mh = (hicn_mapme_v6_header_t *) packet;
/* *INDENT-OFF* */
*prefix = (hicn_prefix_t) {
.name = {
- .ip6 = HICN_MAPME_TYPE_IS_IU (mh->icmp_rd.type) ? mh->ip.daddr : mh->ip.saddr,
+ .v6 = HICN_MAPME_TYPE_IS_IU (mh->icmp_rd.type) ? mh->ip.daddr : mh->ip.saddr,
},
.len = mh->len,
};
- *params = (mapme_params_t) {
+ *params = (mapme_params_t){
.protocol = IPPROTO_IPV6,
- .type = (mh->icmp_rd.type == HICN_MAPME_ICMP_TYPE_IPV6) ? UPDATE : UPDATE_ACK,
+ .type =
+ (mh->icmp_rd.type == HICN_MAPME_ICMP_TYPE_IPV6) ? UPDATE : UPDATE_ACK,
.seq = ntohl (mh->seq),
};
/* *INDENT-ON* */
@@ -193,8 +231,8 @@ hicn_mapme_v6_parse_packet (const u8 * packet, hicn_prefix_t * prefix,
}
int
-hicn_mapme_parse_packet (const u8 * packet, hicn_prefix_t * prefix,
- mapme_params_t * params)
+hicn_mapme_parse_packet (const u8 *packet, hicn_prefix_t *prefix,
+ mapme_params_t *params)
{
switch (HICN_IP_VERSION (packet))
{
@@ -203,8 +241,9 @@ hicn_mapme_parse_packet (const u8 * packet, hicn_prefix_t * prefix,
case 6:
return hicn_mapme_v6_parse_packet (packet, prefix, params);
default:
- return HICN_LIB_ERROR_UNEXPECTED;
+ break;
}
+ return HICN_LIB_ERROR_UNEXPECTED;
}
/*
diff --git a/lib/src/name.c b/lib/src/name.c
index 54b2a76aa..f363eea90 100644
--- a/lib/src/name.c
+++ b/lib/src/name.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,533 +19,470 @@
*/
#ifndef _WIN32
-#include <arpa/inet.h> // inet_ptin
+#include <arpa/inet.h> // inet_ptin
#endif
#include <errno.h>
#include <stdio.h>
-#include <stdlib.h> // strtoul
-#include <string.h> // memcpy
+#include <stdlib.h> // strtoul
+#include <string.h> // memcpy
#include <hicn/common.h>
#include <hicn/error.h>
#include <hicn/name.h>
+#include <hicn/util/sstrncpy.h>
+
+#define MIN(a, b) (((a) < (b)) ? (a) : (b))
-#if ! HICN_VPP_PLUGIN
int
-hicn_name_create (const char *ip_address, u32 id, hicn_name_t * name)
+hicn_name_create (const char *ip_address, u32 id, hicn_name_t *name)
{
int af, rc;
- af = get_addr_family (ip_address);
-
- switch (af)
- {
- case AF_INET:
- if (name->type == HNT_UNSPEC)
- {
- name->type = HNT_CONTIGUOUS_V4;
- }
- name->len = IPV4_ADDR_LEN;
- break;
- case AF_INET6:
- if (name->type == HNT_UNSPEC)
- {
- name->type = HNT_CONTIGUOUS_V6;
- }
- name->len = IPV6_ADDR_LEN;
- break;
- default:
- return HICN_LIB_ERROR_INVALID_IP_ADDRESS;
- }
+ memset (name, 0, sizeof (hicn_name_t));
- if ((name->type != HNT_CONTIGUOUS_V4) && (name->type != HNT_CONTIGUOUS_V6))
- {
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- }
+ af = get_addr_family (ip_address);
+ int v4 = (af == AF_INET);
+ u8 *dst = (u8 *) (v4 * (intptr_t) (name->prefix.v4.as_u8) +
+ (1 - v4) * (intptr_t) (name->prefix.v6.as_u8));
+ rc = inet_pton (af, ip_address, dst);
- rc = inet_pton (af, ip_address, name->buffer);
- if (rc <= 0)
+ if (rc != 1)
{
return HICN_LIB_ERROR_UNKNOWN_ADDRESS;
}
- *(u32 *) (name->buffer + name->len) = id;
+
+ name->suffix = id;
return HICN_LIB_ERROR_NONE;
}
int
-hicn_name_create_from_ip_prefix (const ip_prefix_t * prefix, u32 id,
- hicn_name_t * name)
+hicn_name_create_from_ip_address (const hicn_ip_address_t ip_address,
+ u32 suffix, hicn_name_t *name)
{
- switch (prefix->family)
- {
- case AF_INET:
- name->type = HNT_CONTIGUOUS_V4;
- memcpy (name->buffer, prefix->address.v4.buffer,
- ip_address_len(prefix->family));
- name->len = IPV4_ADDR_LEN;
- break;
- case AF_INET6:
- name->type = HNT_CONTIGUOUS_V6;
- memcpy (name->buffer, prefix->address.v6.buffer,
- ip_address_len(prefix->family));
- name->len = IPV6_ADDR_LEN;
- break;
- default:
- return HICN_LIB_ERROR_INVALID_IP_ADDRESS;
- }
-
- *(u32 *) (name->buffer + name->len) = id;
+ name->prefix = ip_address;
+ name->suffix = suffix;
return HICN_LIB_ERROR_NONE;
}
-u8
-hicn_name_get_length (const hicn_name_t * name)
+int
+hicn_name_create_from_ip_prefix (const hicn_ip_prefix_t *prefix, u32 id,
+ hicn_name_t *name)
{
- return name->len;
+ name->prefix = prefix->address;
+ name->suffix = id;
+
+ return HICN_LIB_ERROR_NONE;
}
int
-hicn_name_compare (const hicn_name_t * name_1, const hicn_name_t * name_2,
- bool consider_segment)
+hicn_name_compare (const hicn_name_t *name_1, const hicn_name_t *name_2,
+ bool consider_segment)
{
- hicn_name_t *name1 = (hicn_name_t *) name_1;
- hicn_name_t *name2 = (hicn_name_t *) name_2;
+ int ret;
+ ret = memcmp (&name_1->prefix.v6.buffer, &name_2->prefix.v6.buffer,
+ sizeof (name_1->prefix.v6));
- if ((name1->type == HNT_CONTIGUOUS_V4 && name2->type == HNT_CONTIGUOUS_V6)
- || (name1->type == HNT_CONTIGUOUS_V6
- && name2->type == HNT_CONTIGUOUS_V4))
- {
- return -1;
- }
+ if (consider_segment)
+ ret |= !(name_1->suffix == name_2->suffix);
- if ((name1->type == HNT_IOV_V4 && name2->type == HNT_IOV_V6) ||
- (name1->type == HNT_IOV_V6 && name2->type == HNT_IOV_V4))
- {
- return -1;
- }
+ return ret;
+}
- if ((name1->type == HNT_IOV_V4 && name2->type == HNT_CONTIGUOUS_V6) ||
- (name1->type == HNT_IOV_V6 && name2->type == HNT_CONTIGUOUS_V4))
- {
- return -1;
- }
+uint32_t
+_hicn_name_get_hash (const hicn_name_t *name, bool consider_suffix)
+{
+ uint32_t hash = hash32 (&name->prefix, sizeof (name->prefix));
- if (name1->type == HNT_UNSPEC || name2->type == HNT_UNSPEC)
- {
- return -1;
- }
+ if (consider_suffix)
+ hash = cumulative_hash32 (&name->suffix, sizeof (name->suffix), hash);
- size_t len1 = 0, len2 = 0;
+ return hash;
+}
- u8 *buffer11, *buffer12, *buffer21, *buffer22;
+int
+hicn_name_empty (hicn_name_t *name)
+{
+ return _is_unspec (name);
+}
- switch (name1->type)
- {
- case HNT_CONTIGUOUS_V4:
- buffer11 = name1->buffer;
- buffer12 = name1->buffer + IPV4_ADDR_LEN;
- len1 = IPV4_ADDR_LEN;
- break;
- case HNT_CONTIGUOUS_V6:
- buffer11 = name1->buffer;
- buffer12 = name1->buffer + IPV6_ADDR_LEN;
- len1 = IPV6_ADDR_LEN;
- break;
- case HNT_IOV_V4:
- buffer11 = name1->iov.buffers[0].iov_base;
- buffer12 = name1->iov.buffers[1].iov_base;
- len1 = IPV4_ADDR_LEN;
- break;
- case HNT_IOV_V6:
- buffer11 = name1->iov.buffers[0].iov_base;
- buffer12 = name1->iov.buffers[1].iov_base;
- len1 = IPV6_ADDR_LEN;
- break;
- default:
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- }
+int
+hicn_name_copy (hicn_name_t *dst, const hicn_name_t *src)
+{
+ *dst = *src;
+ return HICN_LIB_ERROR_NONE;
+}
- switch (name2->type)
- {
- case HNT_CONTIGUOUS_V4:
- buffer21 = name2->buffer;
- buffer22 = name2->buffer + IPV4_ADDR_LEN;
- len2 = IPV4_ADDR_LEN;
- break;
- case HNT_CONTIGUOUS_V6:
- buffer21 = name2->buffer;
- buffer22 = name2->buffer + IPV6_ADDR_LEN;
- len2 = IPV6_ADDR_LEN;
- break;
- case HNT_IOV_V4:
- buffer21 = name2->iov.buffers[0].iov_base;
- buffer22 = name2->iov.buffers[1].iov_base;
- len2 = IPV4_ADDR_LEN;
- break;
- case HNT_IOV_V6:
- buffer21 = name2->iov.buffers[0].iov_base;
- buffer22 = name2->iov.buffers[1].iov_base;
- len2 = IPV6_ADDR_LEN;
- break;
- default:
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- }
+int
+hicn_name_copy_prefix_to_destination (u8 *dst, const hicn_name_t *name)
+{
+ int v4 = _is_inet4 (name);
+ const u8 *src = (u8 *) (v4 * (intptr_t) (name->prefix.v4.as_u8) +
+ (1 - v4) * (intptr_t) (name->prefix.v6.as_u8));
+ size_t size = v4 * IPV4_ADDR_LEN + (1 - v4) * IPV6_ADDR_LEN;
+ memcpy (dst, src, size);
- // Sanity check
- if (len1 != len2)
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
+ return HICN_LIB_ERROR_NONE;
+}
- int ret1 = memcmp ((u8 *) buffer11, (u8 *) buffer21, len1);
+int
+hicn_name_set_suffix (hicn_name_t *name, hicn_name_suffix_t suffix)
+{
+ name->suffix = suffix;
+ return HICN_LIB_ERROR_NONE;
+}
- if (!consider_segment)
+int
+hicn_name_to_sockaddr_address (const hicn_name_t *name,
+ struct sockaddr *ip_address)
+{
+ struct sockaddr_in6 *tmp6 = (struct sockaddr_in6 *) ip_address;
+ struct sockaddr_in *tmp4 = (struct sockaddr_in *) ip_address;
+
+ assert (!_is_unspec (name));
+
+ if (_is_inet4 (name))
+ {
+ tmp4->sin_family = AF_INET;
+ tmp4->sin_port = DUMMY_PORT;
+ memcpy (&tmp4->sin_addr, &name->prefix.v4, IPV4_ADDR_LEN);
+ }
+ else
{
- return ret1;
+ tmp6->sin6_family = AF_INET6;
+ tmp6->sin6_scope_id = 0;
+ tmp6->sin6_port = DUMMY_PORT;
+ memcpy (&tmp6->sin6_addr, &name->prefix.v6, IPV6_ADDR_LEN);
}
- int ret2 = memcmp ((u8 *) buffer12, (u8 *) buffer22, HICN_SEGMENT_LEN);
-
- return ret1 || ret2;
+ return HICN_LIB_ERROR_NONE;
}
int
-hicn_name_hash (const hicn_name_t * name, u32 * hash, bool consider_suffix)
+hicn_name_to_hicn_ip_prefix (const hicn_name_t *name, hicn_ip_prefix_t *prefix)
{
- switch (name->type)
- {
- case HNT_CONTIGUOUS_V4:
- *hash = hash32 (name->buffer, consider_suffix ? HICN_V4_NAME_LEN : HICN_V4_PREFIX_LEN);
- break;
- case HNT_CONTIGUOUS_V6:
- *hash = hash32 (name->buffer, consider_suffix ? HICN_V6_NAME_LEN : HICN_V6_PREFIX_LEN);
- break;
- case HNT_IOV_V4:
- case HNT_IOV_V6:
- *hash =
- hash32 (name->iov.buffers[0].iov_base, name->iov.buffers[0].iov_len);
- if (consider_suffix)
- {
- *hash = cumulative_hash32 (name->iov.buffers[1].iov_base,
- name->iov.buffers[1].iov_len, *hash);
- }
- break;
- default:
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- }
-
+ int family, rc;
+ rc = hicn_name_get_family (name, &family);
+ if (rc)
+ return rc;
+
+ prefix->family = family;
+ prefix->address.v6.as_u64[0] = name->prefix.v6.as_u64[0];
+ prefix->address.v6.as_u64[1] = name->prefix.v6.as_u64[1];
+ prefix->len = 128;
return HICN_LIB_ERROR_NONE;
}
int
-hicn_name_empty (hicn_name_t * name)
+hicn_name_get_seq_number (const hicn_name_t *name, u32 *seq_number)
{
- return name->type == HNT_UNSPEC ? 1 : 0;
+ *seq_number = name->suffix;
+ return HICN_LIB_ERROR_NONE;
}
int
-hicn_name_copy (hicn_name_t * dst, const hicn_name_t * src)
+hicn_name_ntop (const hicn_name_t *src, char *dst, size_t len)
{
- switch (src->type)
+ int offset;
+ const char *rc = NULL;
+ int v4 = _is_inet4 (src);
+ const u8 *addr = (u8 *) (v4 * (intptr_t) src->prefix.v4.as_u8 +
+ (1 - v4) * (intptr_t) src->prefix.v6.as_u8);
+ int family = v4 * AF_INET + (1 - v4) * AF_INET6;
+ rc = inet_ntop (family, addr, dst, (socklen_t) len);
+
+ if (!rc)
{
- case HNT_CONTIGUOUS_V4:
- case HNT_CONTIGUOUS_V6:
- *dst = *src;
- break;
- case HNT_IOV_V4:
- case HNT_IOV_V6:
- dst->type =
- src->type == HNT_IOV_V4 ? HNT_CONTIGUOUS_V4 : HNT_CONTIGUOUS_V6;
- memcpy (dst->buffer, src->iov.buffers[0].iov_base,
- src->iov.buffers[0].iov_len);
- memcpy (dst->buffer + src->iov.buffers[0].iov_len,
- src->iov.buffers[1].iov_base, src->iov.buffers[1].iov_len);
- break;
- default:
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
+ return HICN_LIB_ERROR_UNSPECIFIED;
}
+ offset = (int) strnlen_s (dst, len);
+ dst[offset] = '|';
+
+ snprintf (dst + offset + 1, len - offset - 1, "%lu",
+ (unsigned long) (src->suffix));
+
return HICN_LIB_ERROR_NONE;
}
int
-hicn_name_copy_to_destination (u8 * dst, const hicn_name_t * src,
- bool copy_suffix)
+hicn_name_pton (const char *src, hicn_name_t *dst)
{
- size_t length;
+ return HICN_LIB_ERROR_NOT_IMPLEMENTED;
+}
- switch (src->type)
- {
- case HNT_CONTIGUOUS_V4:
- if (copy_suffix)
- {
- length = HICN_V4_NAME_LEN;
- }
- else
- {
- length = IPV4_ADDR_LEN;
- }
- memcpy (dst, src->buffer, length);
- break;
- case HNT_CONTIGUOUS_V6:
- if (copy_suffix)
- {
- length = HICN_V6_NAME_LEN;
- }
- else
- {
- length = IPV6_ADDR_LEN;
- }
- memcpy (dst, src->buffer, length);
- break;
- case HNT_IOV_V4:
- case HNT_IOV_V6:
- memcpy (dst, src->iov.buffers[0].iov_base, src->iov.buffers[0].iov_len);
- if (copy_suffix)
- {
- memcpy (dst + src->iov.buffers[0].iov_len,
- src->iov.buffers[1].iov_base, src->iov.buffers[1].iov_len);
- }
- break;
- default:
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- }
+int
+hicn_name_get_family (const hicn_name_t *name, int *family)
+{
+ assert (!_is_unspec (name));
+ int v4 = _is_inet4 (name);
+ *family = v4 * AF_INET + (1 - v4) * AF_INET6;
return HICN_LIB_ERROR_NONE;
}
+bool
+hicn_name_is_v4 (const hicn_name_t *name)
+{
+ return _is_inet4 (name);
+}
+
int
-hicn_name_set_seq_number (hicn_name_t * name, u32 seq_number)
+hicn_name_snprintf (char *s, size_t size, const hicn_name_t *name)
{
- u8 *sequence_number = NULL;
+ int n, rc;
+ n = hicn_ip_address_snprintf (s, size, &name->prefix);
+ if (n < 0 || n >= size)
+ return n;
+ rc = snprintf (s + n, size - n, "|%d", name->suffix);
+ if (rc < 0)
+ return rc;
+ return rc + n;
+}
- switch (name->type)
- {
- case HNT_CONTIGUOUS_V6:
- sequence_number = name->buffer + IPV6_ADDR_LEN;
- break;
- case HNT_CONTIGUOUS_V4:
- sequence_number = name->buffer + IPV4_ADDR_LEN;
- break;
- case HNT_IOV_V6:
- case HNT_IOV_V4:
- sequence_number = name->iov.buffers[1].iov_base;
- break;
- case HNT_UNSPEC:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
+int
+hicn_name_no_suffix_snprintf (char *s, size_t size, const hicn_name_t *name)
+{
+ return hicn_ip_address_snprintf (s, size, &name->prefix);
+}
- if (sequence_number)
- {
- *(u32 *) sequence_number = seq_number;
- }
- else
- {
- return HICN_LIB_ERROR_UNEXPECTED;
- }
+int
+hicn_prefix_create_from_ip_prefix (const hicn_ip_prefix_t *hicn_ip_prefix,
+ hicn_prefix_t *prefix)
+{
+ if (hicn_ip_prefix->family != AF_INET && hicn_ip_prefix->family != AF_INET6)
+ return HICN_LIB_ERROR_INVALID_IP_ADDRESS;
+ prefix->name = hicn_ip_prefix->address;
+ prefix->len = (u8) (hicn_ip_prefix->len);
return HICN_LIB_ERROR_NONE;
}
int
-hicn_name_to_sockaddr_address (const hicn_name_t * name,
- struct sockaddr *ip_address)
+hicn_name_cmp (const hicn_name_t *n1, const hicn_name_t *n2)
{
- struct sockaddr_in6 *tmp6 = (struct sockaddr_in6 *) ip_address;
- struct sockaddr_in *tmp4 = (struct sockaddr_in *) ip_address;
-
- switch (name->type)
- {
- case HNT_CONTIGUOUS_V6:
- tmp6->sin6_family = AF_INET6;
- tmp6->sin6_scope_id = 0;
- tmp6->sin6_port = DUMMY_PORT;
- memcpy (&tmp6->sin6_addr, name->buffer, IPV6_ADDR_LEN);
- break;
- case HNT_IOV_V6:
- tmp6->sin6_family = AF_INET6;
- tmp6->sin6_scope_id = 0;
- tmp6->sin6_port = DUMMY_PORT;
- memcpy (&tmp6->sin6_addr, name->iov.buffers[0].iov_base,
- name->iov.buffers[0].iov_len);
- break;
- case HNT_CONTIGUOUS_V4:
- tmp4->sin_family = AF_INET;
- tmp4->sin_port = DUMMY_PORT;
- memcpy (&tmp4->sin_addr, name->buffer, IPV4_ADDR_LEN);
- break;
- case HNT_IOV_V4:
- tmp4->sin_family = AF_INET;
- tmp4->sin_port = DUMMY_PORT;
- memcpy (&tmp4->sin_addr, name->iov.buffers[0].iov_base,
- name->iov.buffers[0].iov_len);
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
+ int rc = hicn_ip_address_cmp (&n1->prefix, &n2->prefix);
+ if (rc != 0)
+ return rc;
+ return n2->suffix - n1->suffix;
+}
- return HICN_LIB_ERROR_NONE;
+bool
+hicn_name_equals (const hicn_name_t *n1, const hicn_name_t *n2)
+{
+ return (hicn_name_cmp (n1, n2) == 0);
}
int
-hicn_name_to_ip_prefix (const hicn_name_t * name, ip_prefix_t * prefix)
+hicn_prefix_create_from_ip_address_len (const hicn_ip_address_t *ip_address,
+ uint8_t len, hicn_prefix_t *prefix)
{
- switch (name->type)
- {
- case HNT_CONTIGUOUS_V6:
- memcpy (&prefix->address.v6.buffer, name->buffer, IPV6_ADDR_LEN);
- prefix->family = AF_INET6;
- break;
- case HNT_IOV_V6:
- memcpy (&prefix->address.v6.buffer, name->iov.buffers[0].iov_base,
- name->iov.buffers[0].iov_len);
- prefix->family = AF_INET6;
- break;
- case HNT_CONTIGUOUS_V4:
- memcpy (&prefix->address.v4.buffer, name->buffer, IPV4_ADDR_LEN);
- prefix->family = AF_INET;
- break;
- case HNT_IOV_V4:
- memcpy (&prefix->address.v4.buffer, name->iov.buffers[0].iov_base,
- name->iov.buffers[0].iov_len);
- prefix->family = AF_INET;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
+ prefix->name = *ip_address;
+ prefix->len = len;
return HICN_LIB_ERROR_NONE;
}
+hicn_prefix_t *
+hicn_prefix_dup (const hicn_prefix_t *prefix)
+{
+ hicn_prefix_t *copy = malloc (sizeof (hicn_prefix_t));
+ if (!copy)
+ goto ERR_MALLOC;
+ if (hicn_prefix_copy (copy, prefix) < 0)
+ goto ERR_COPY;
+ return copy;
+
+ERR_COPY:
+ free (copy);
+ERR_MALLOC:
+ return NULL;
+}
+
int
-hicn_name_get_seq_number (const hicn_name_t * name, u32 * seq_number)
+hicn_prefix_copy (hicn_prefix_t *dst, const hicn_prefix_t *src)
{
- const u8 *sequence_number = NULL;
+ dst->name = src->name;
+ dst->len = src->len;
+ return 0;
+}
- switch (name->type)
+bool
+hicn_prefix_is_v4 (const hicn_prefix_t *prefix)
+{
+ return hicn_ip_address_is_v4 (&prefix->name);
+}
+
+/*
+ * The ip address is in network byte order (big endian, msb last) in
+ * hicn_{prefix,name}_t, as in ip_address_t which builds upon struct in*_addr,
+ * But the bits are in host order... so we cannot use builtin functions to get
+ * the position of the first 1 unless we swap bytes as was done previously,
+ * which is costly and non-essential.
+ *
+ *
+ * Example:
+ *
+ * bits | 127 .. 120 | ... | 8 9 10 11 12 13 14 15 | 0 .. 7 |
+ * diff | | ... | 1 0 1 0 0 0 0 0 | |
+ * ^
+ * bit of interest ----------------+
+ */
+
+uint64_t
+_log2_nbo (uint64_t val)
+{
+ assert (val != 0); /* There is at least 1 bit set (network byte order) */
+
+ uint64_t result = 0;
+
+ /* Search for the first 1, starting from left */
+
+ /* The first 32 bits of val are 0 */
+ if (!(val & 0x00000000FFFFFFFF))
{
- case HNT_CONTIGUOUS_V6:
- sequence_number = name->buffer + IPV6_ADDR_LEN;
- break;
- case HNT_CONTIGUOUS_V4:
- sequence_number = name->buffer + IPV4_ADDR_LEN;
- break;
- case HNT_IOV_V6:
- case HNT_IOV_V4:
- sequence_number = name->iov.buffers[1].iov_base;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
+ val = val >> 32;
+ result = result | 32;
}
- if (sequence_number)
+ if (!(val & 0x0000FFFF))
{
- *seq_number = *(u32 *) sequence_number;
+ val = val >> 16;
+ result = result | 16;
}
- else
+
+ if (!(val & 0x00FF))
{
- return HICN_LIB_ERROR_UNEXPECTED;
+ val = val >> 8;
+ result = result | 8;
}
- return HICN_LIB_ERROR_NONE;
+ /* Val now contains the byte with at last 1 bit set (host bit order) */
+ if (val & 0xF0)
+ val = val >> 4;
+ else
+ result = result | 4;
+
+ if (val & 0xC)
+ val = val >> 2;
+ else
+ result = result | 2;
+
+ if (val & 0x2)
+ val = val >> 1;
+ else
+ result = result | 1;
+
+ return result;
}
-int
-hicn_name_ntop (const hicn_name_t * src, char *dst, size_t len)
+uint32_t
+hicn_prefix_lpm (const hicn_prefix_t *p1, const hicn_prefix_t *p2)
{
- int offset;
- const char *rc;
- void *seg_number = NULL;
-
- switch (src->type)
+ uint32_t prefix_len = 0;
+ /* Test each block of 64 bits as a whole */
+ for (unsigned i = 0; i < 2; i++)
{
- case HNT_CONTIGUOUS_V6:
- rc = inet_ntop (AF_INET6, src->buffer, dst, (socklen_t)len);
- seg_number = (u8 *) src->buffer + IPV6_ADDR_LEN;
- break;
- case HNT_CONTIGUOUS_V4:
- rc = inet_ntop (AF_INET, src->buffer, dst, (socklen_t)len);
- seg_number = (u8 *) src->buffer + IPV4_ADDR_LEN;
- break;
- case HNT_IOV_V6:
- rc = inet_ntop (AF_INET6, src->iov.buffers[0].iov_base, dst, (socklen_t)len);
- seg_number = src->iov.buffers[1].iov_base;
- break;
- case HNT_IOV_V4:
- rc = inet_ntop (AF_INET, src->iov.buffers[0].iov_base, dst, (socklen_t)len);
- seg_number = src->iov.buffers[1].iov_base;
- break;
- default:
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- }
- if (!rc)
- {
- goto ERR;
+ /* Check for differences in the two u64 */
+ uint64_t diff = p1->name.v6.as_u64[i] ^ p2->name.v6.as_u64[i];
+ if (diff)
+ {
+ /*
+ * As the ip_address_t mimics in*_addr and has network byte order
+ * (and host bit order, we cannot directly use 64-bit operations:
+ */
+ prefix_len += _log2_nbo (diff);
+ break;
+ }
+ prefix_len += 8 * sizeof (uint64_t);
}
- offset = (int) strlen (dst);
- dst[offset] = '|';
-
- sprintf (dst + offset + 1, "%lu", (unsigned long) (*(u32 *) seg_number));
-
- return HICN_LIB_ERROR_NONE;
+ /* Bound the returned prefix length by the length of all input */
+ return MIN (prefix_len,
+ MIN (hicn_prefix_get_len (p1), hicn_prefix_get_len (p2)));
+}
-ERR:
- return HICN_LIB_ERROR_UNSPECIFIED;
+void
+hicn_prefix_clear (hicn_prefix_t *prefix, uint8_t start_from)
+{
+ uint8_t *buffer = prefix->name.v6.as_u8;
+
+ /* Compute the offset of the byte from which to clear the name... */
+ uint8_t offset = start_from / 8;
+ if (hicn_prefix_is_v4 (prefix))
+ offset += IP_ADDRESS_V4_OFFSET_LEN; /* Ignore padding */
+ /* ... and the position of the first bit to clear */
+ uint8_t pos = start_from % 8;
+
+ /* Mask to clear specific bits at offset...
+ * pos 7 6 5 4 3 2 1 0 (eg. start_from = 19, pos = 3)
+ * mask 0 0 0 0 0 1 1 1 (= 1<<pos - 1)
+ * */
+ uint8_t mask = 0xFF ^ ((1 << (8 - pos)) - 1);
+ buffer[offset] &= mask;
+
+ /* ... then fully clear remaining bytes */
+ for (uint8_t i = offset + 1; i < HICN_PREFIX_MAX_LEN; i++)
+ buffer[i] = 0;
}
-int
-hicn_name_pton (const char *src, hicn_name_t * dst)
+void
+hicn_prefix_truncate (hicn_prefix_t *prefix, uint8_t len)
{
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
+ hicn_prefix_clear (prefix, len);
+ prefix->len = len;
}
int
-hicn_name_get_family (const hicn_name_t * name, int *family)
+hicn_prefix_cmp (const hicn_prefix_t *p1, const hicn_prefix_t *p2)
{
- switch (name->type)
- {
- case HNT_CONTIGUOUS_V6:
- case HNT_IOV_V6:
- *family = AF_INET6;
- break;
- case HNT_CONTIGUOUS_V4:
- case HNT_IOV_V4:
- *family = AF_INET;
- break;
- default:
- return HICN_LIB_ERROR_UNEXPECTED;
- }
+ if (p1->len != p2->len)
+ return p2->len - p1->len;
+ return hicn_ip_address_cmp (&p1->name, &p2->name);
+}
- return HICN_LIB_ERROR_NONE;
+bool
+hicn_prefix_equals (const hicn_prefix_t *p1, const hicn_prefix_t *p2)
+{
+ return hicn_prefix_cmp (p1, p2) == 0;
}
int
-hicn_prefix_create_from_ip_prefix (const ip_prefix_t * ip_prefix,
- hicn_prefix_t * prefix)
+hicn_prefix_snprintf (char *s, size_t size, const hicn_prefix_t *prefix)
{
- switch (ip_prefix->family)
- {
- case AF_INET:
- prefix->name.ip4.as_u32 = ip_prefix->address.v4.as_u32;
- break;
- case AF_INET6:
- prefix->name.ip6.as_u64[0] = ip_prefix->address.v6.as_u64[0];
- prefix->name.ip6.as_u64[1] = ip_prefix->address.v6.as_u64[1];
- break;
- default:
- return HICN_LIB_ERROR_INVALID_IP_ADDRESS;
- }
- prefix->len = (u8) (ip_prefix->len);
+ hicn_ip_prefix_t ip_prefix = { .family =
+ hicn_ip_address_get_family (&prefix->name),
+ .address = prefix->name,
+ .len = prefix->len };
+ return hicn_ip_prefix_snprintf (s, size, &ip_prefix);
+}
- return HICN_LIB_ERROR_NONE;
+uint8_t
+_hicn_prefix_get_bit (const hicn_prefix_t *prefix, uint8_t pos)
+{
+ const hicn_ip_address_t *address = hicn_prefix_get_ip_address (prefix);
+ return hicn_ip_address_get_bit (address, pos);
}
-#endif /* ! HICN_VPP_PLUGIN */
+uint8_t
+hicn_prefix_get_bit (const hicn_prefix_t *prefix, uint8_t pos)
+{
+ assert (pos <= hicn_prefix_get_len (prefix));
+ return _hicn_prefix_get_bit (prefix, pos);
+}
+int
+hicn_prefix_get_ip_prefix (const hicn_prefix_t *prefix,
+ hicn_ip_prefix_t *ip_prefix)
+{
+ *ip_prefix =
+ (hicn_ip_prefix_t){ .family = hicn_ip_address_get_family (&prefix->name),
+ .address = prefix->name,
+ .len = prefix->len };
+ return HICN_LIB_ERROR_NONE;
+}
/*
* fd.io coding-style-patch-verification: ON
diff --git a/lib/src/ops.c b/lib/src/ops.c
index ef12e9bf0..2c38b5374 100644
--- a/lib/src/ops.c
+++ b/lib/src/ops.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,25 +22,35 @@
#include <netinet/in.h>
#endif
#include <stdlib.h>
-#include <hicn/ops.h>
-#include <hicn/header.h>
+
+#include "ops.h"
+#include "protocol.h"
extern const hicn_ops_t hicn_ops_ipv4;
extern const hicn_ops_t hicn_ops_icmp;
+extern const hicn_ops_t hicn_ops_udp;
extern const hicn_ops_t hicn_ops_tcp;
extern const hicn_ops_t hicn_ops_ipv6;
+extern const hicn_ops_t hicn_ops_new;
extern const hicn_ops_t hicn_ops_ah;
/* Declare empty operations (terminates recursion on protocol layers) */
-DECLARE_init_packet_header (none, NONE);
+
+int
+none_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ pkbuf->payload = pkbuf->len;
+ return HICN_LIB_ERROR_NONE;
+}
+
DECLARE_get_interest_locator (none, NONE);
DECLARE_set_interest_locator (none, NONE);
DECLARE_get_interest_name (none, NONE);
DECLARE_set_interest_name (none, NONE);
DECLARE_get_interest_name_suffix (none, NONE);
DECLARE_set_interest_name_suffix (none, NONE);
-DECLARE_mark_packet_as_interest (none, NONE);
-DECLARE_mark_packet_as_data (none, NONE);
+DECLARE_get_type (none, NONE);
+DECLARE_set_type (none, NONE);
DECLARE_reset_interest_for_hash (none, NONE);
DECLARE_get_data_locator (none, NONE);
DECLARE_set_data_locator (none, NONE);
@@ -48,21 +58,20 @@ DECLARE_get_data_name (none, NONE);
DECLARE_set_data_name (none, NONE);
DECLARE_get_data_name_suffix (none, NONE);
DECLARE_set_data_name_suffix (none, NONE);
-DECLARE_get_data_pathlabel (none, NONE);
-DECLARE_set_data_pathlabel (none, NONE);
-DECLARE_update_data_pathlabel (none, NONE);
+DECLARE_get_data_path_label (none, NONE);
+DECLARE_set_data_path_label (none, NONE);
+DECLARE_update_data_path_label (none, NONE);
DECLARE_reset_data_for_hash (none, NONE);
DECLARE_get_lifetime (none, NONE);
DECLARE_set_lifetime (none, NONE);
DECLARE_update_checksums (none, NONE);
+DECLARE_update_checksums_incremental (none, NONE);
DECLARE_verify_checksums (none, NONE);
DECLARE_rewrite_interest (none, NONE);
DECLARE_rewrite_data (none, NONE);
-DECLARE_get_length (none, NONE);
-DECLARE_get_header_length (none, NONE);
-DECLARE_get_current_header_length (none, NONE);
-DECLARE_get_payload_length (none, NONE);
-DECLARE_set_payload_length (none, NONE);
+DECLARE_set_payload_len (none, NONE);
+DECLARE_get_payload_type (none, NONE);
+DECLARE_set_payload_type (none, NONE);
DECLARE_get_signature_size (none, NONE);
DECLARE_set_signature_size (none, NONE);
DECLARE_set_signature_timestamp (none, NONE);
@@ -72,9 +81,12 @@ DECLARE_get_validation_algorithm (none, NONE);
DECLARE_set_key_id (none, NONE);
DECLARE_get_key_id (none, NONE);
DECLARE_get_signature (none, NONE);
-DECLARE_get_signature_gap (none, NONE);
-DECLARE_set_signature_gap (none, NONE);
-DECLARE_HICN_OPS (none);
+DECLARE_has_signature (none, NONE);
+DECLARE_get_signature_padding (none, NONE);
+DECLARE_set_signature_padding (none, NONE);
+DECLARE_is_last_data (none, NONE);
+DECLARE_set_last_data (none, NONE);
+DECLARE_HICN_OPS (none, 0);
/**
* @brief Virtual function table for packet operations
@@ -84,10 +96,12 @@ const hicn_ops_t *const hicn_ops_vft[] = {
/* 0 */ [IPPROTO_IP] = &hicn_ops_ipv4,
/* 1 */[IPPROTO_ICMP] = &hicn_ops_icmp,
/* 6 */[IPPROTO_TCP] = &hicn_ops_tcp,
+ /* 6 */[IPPROTO_UDP] = &hicn_ops_udp,
/* 41 */[IPPROTO_IPV6] = &hicn_ops_ipv6,
/* 51 */[IPPROTO_AH] = &hicn_ops_ah,
/* 58 */[IPPROTO_ICMPV6] = &hicn_ops_icmp,
- [IPPROTO_NONE] = &hicn_ops_none,
+ /* 59 */[IPPROTO_NONE] = &hicn_ops_none,
+ /* 98 */[IPPROTO_ENCAP] = &hicn_ops_new,
};
/*
diff --git a/lib/src/ops.h b/lib/src/ops.h
new file mode 100644
index 000000000..843945690
--- /dev/null
+++ b/lib/src/ops.h
@@ -0,0 +1,979 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file base.h
+ * @brief Protocol-independent packet operations
+ */
+
+#ifndef HICN_OPS_H
+#define HICN_OPS_H
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include <hicn/base.h>
+#include <hicn/error.h>
+#include <hicn/name.h>
+#include <hicn/packet.h> // HICN_OPAQUE_LEN
+#include <hicn/util/ip_address.h>
+
+#include "protocol.h"
+
+/*
+ * In order to provide fast lookup and accelerate packet operations, we allow
+ * ourselves to use a header cache structure under the responsibility of the
+ * caller, and that can be associated to each packet. This structure is exposed
+ * as a opaque pointer.
+ */
+
+/*
+ * hICN operations on packets
+ *
+ * All prototypes take an hicn_type_t parameter as their first argument, as
+ * this decides the sequence of protocols that are being used by the different
+ * operations.
+ */
+
+typedef struct hicn_ops_s
+{
+ const char *name;
+
+ size_t header_len;
+
+ /**
+ * @brief Initialize the headers of the hicn packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ */
+ int (*init_packet_header) (hicn_packet_buffer_t *pkbuf, size_t pos);
+
+ /**
+ * @brief Retrieves an Interest locator
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [out] ip_address - Retrieved locator
+ * @return hICN error code
+ */
+ int (*get_interest_locator) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos,
+ hicn_ip_address_t *ip_address);
+
+ /**
+ * @brief Sets an Interest locator
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] ip_address - Locator to set
+ * @return hICN error code
+ */
+ int (*set_interest_locator) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address);
+
+ /**
+ * @brief Retrieves an Interest name
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [out] name - Retrieved name
+ * @return hICN error code
+ */
+ int (*get_interest_name) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos, hicn_name_t *name);
+
+ /**
+ * @brief Sets an Interest name
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] name - Name to set
+ * @return hICN error code
+ */
+ int (*set_interest_name) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_t *name);
+
+ /**
+ * @brief Retrieves an Interest name suffix
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [out] suffix - Retrieved name suffix
+ * @return hICN error code
+ */
+ int (*get_interest_name_suffix) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos,
+ hicn_name_suffix_t *suffix);
+
+ /**
+ * @brief Sets an Interest name suffix
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] suffix - Name suffix to set
+ * @return hICN error code
+ */
+ int (*set_interest_name_suffix) (const hicn_packet_buffer_t *pkbuf,
+ size_t pos,
+ const hicn_name_suffix_t *suffix);
+
+ /**
+ * @brief Get packet type
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Position within the network layers
+ * @param [out] type - Packet type
+ * @return hICN error code
+ */
+ int (*get_type) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_packet_type_t *type);
+
+ /**
+ * @brief Set flag to mark current packet as interest
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Position within the network layers
+ * @param [in] type - Packet type
+ * @return hICN error code
+ */
+ int (*set_type) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_packet_type_t type);
+
+ /**
+ * @brief Clear the necessary Interest fields in order to hash it
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @return hICN error code
+ */
+ int (*reset_interest_for_hash) (hicn_packet_buffer_t *pkbuf, size_t pos);
+
+ /**
+ * @brief Retrieves a Data locator
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [out] ip_address - Retrieved locator
+ * @return hICN error code
+ */
+ int (*get_data_locator) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_ip_address_t *ip_address);
+
+ /**
+ * @brief Sets a Data locator
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] ip_address - Locator to set
+ * @return hICN error code
+ */
+ int (*set_data_locator) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address);
+
+ /**
+ * @brief Retrieves a Data name
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [out] name - Retrieved name
+ * @return hICN error code
+ */
+ int (*get_data_name) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_name_t *name);
+
+ /**
+ * @brief Sets a Data name
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] name - Name to set
+ * @return hICN error code
+ */
+ int (*set_data_name) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_t *name);
+
+ /**
+ * @brief Retrieves a Data name suffix
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [out] suffix - Retrieved name suffix
+ * @return hICN error code
+ */
+ int (*get_data_name_suffix) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos, hicn_name_suffix_t *suffix);
+
+ /**
+ * @brief Sets a Data name suffix
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] suffix - Name suffix to set
+ * @return hICN error code
+ */
+ int (*set_data_name_suffix) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_suffix_t *suffix);
+
+ /**
+ * @brief Retrieves a Data path_label
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [out] path_label - Retrieved path_label
+ * @return hICN error code
+ */
+ int (*get_data_path_label) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos, hicn_path_label_t *path_label);
+
+ /**
+ * @brief Sets a Data path_label
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] path_label - Pathlabel to set
+ * @return hICN error code
+ */
+ int (*set_data_path_label) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_path_label_t path_label);
+
+ /**
+ * @brief Update a Data path_label with a new face identifier
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] path_label - Face identifier used to update path_label
+ * @return hICN error code
+ */
+ int (*update_data_path_label) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_faceid_t face_id);
+
+ /**
+ * @brief Clear the necessary Data fields in order to hash it
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @return hICN error code
+ */
+ int (*reset_data_for_hash) (hicn_packet_buffer_t *pkbuf, size_t pos);
+
+ /**
+ * @brief Retrieves an Interest or Data lifetime
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] path_label - Retrieved lifetime
+ * @return hICN error code
+ */
+ int (*get_lifetime) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_lifetime_t *lifetime);
+
+ /**
+ * @brief Sets an Interest or Data lifetime
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] path_label - Lifetime to set
+ * @return hICN error code
+ */
+ int (*set_lifetime) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_lifetime_t lifetime);
+
+ /**
+ * @brief Update all checksums in packet headers
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] partial_csum - Partial checksum (set to 0, used internally to
+ * carry intermediate values from IP pseudo-header)
+ * @param [in] payload_len - Payload len (can be set to ~0, retrieved
+ * and used internally to carry payload len across protocol headers)
+ * @return hICN error code
+ *
+ * Payload len is initialized during the initial steps (eg. IP) if not
+ * provided (value is ~0), and not ignored (value is 0).
+ */
+ int (*update_checksums) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len);
+
+ /**
+ * @brief Update all checksums in packet headers
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] old_val - Pointer to the old value
+ * @param [in] new_val - Pointer to the new value
+ * @param [in] size - Size of the changed value
+ * @param [in] skip_first - Skip the first protocol (ignore IP checksum)
+ * @return hICN error code
+ */
+ int (*update_checksums_incremental) (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first);
+
+ /**
+ * @brief Validate all checksums in packet headers
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] partial_csum - Partial checksum, or zero if no partial
+ * checksum available
+ * @param [in] payload_len - Payload len (can be set to ~0, retrieved
+ * and used internally to carry payload len across protocol headers)
+ * @return hICN error code
+ */
+ int (*verify_checksums) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ u16 partial_csum, size_t payload_len);
+
+ /**
+ * @brief Rewrite an Interest packet header (locator)
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] addr_new - New locator
+ * @param [in] addr_old - Old locator (set to NULL, used internally to
+ * compute incremental checksums)
+ * @return hICN error code
+ */
+ int (*rewrite_interest) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old);
+
+ /**
+ * @brief Rewrite a Data packet header (locator + path_label)
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @param [in] addr_new - New locator
+ * @param [in] addr_old - Old locator (set to NULL, used internally to
+ * compute incremental checksums)
+ * @param [in] face_id - Face identifier used to update path_label
+ * @param [in] reset_pl - If not zero, reset the current path_label
+ * before update it
+ * @return hICN error code
+ */
+ int (*rewrite_data) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old,
+ const hicn_faceid_t face_id, u8 reset_pl);
+
+ /**
+ * @brief Return the packet len
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @parma [out] len - Returned packet len
+ * @return hICN error code
+ */
+ int (*get_len) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ size_t *len);
+
+ /**
+ * @brief Return the current packet header len
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @parma [out] header_len - Returned packet current header len
+ * @return hICN error code
+ */
+ int (*get_current_header_len) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos, size_t *header_len);
+
+ /**
+ * @brief Sets the packet paylaod len
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Depth in the header stack
+ * @parma [out] payload_len - Payload len to set
+ * @return hICN error code
+ */
+ int (*set_payload_len) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t payload_len);
+
+ /**
+ * @brief Retrieves an Interest or Data signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] signature_size - Retrieved signature size
+ * @return hICN error code
+ */
+ int (*get_signature_size) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos, size_t *signature_size);
+
+ /**
+ * @brief Sets an Interest or Data signature size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] signature_size - Signature size to set
+ * @return hICN error code
+ */
+ int (*set_signature_size) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_size);
+
+ /**
+ * @brief Sets an Interest or Data signature padding between maximum size and
+ * real size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] signature_size - Signature size to set
+ * @return hICN error code
+ */
+ int (*set_signature_padding) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_padding);
+
+ /**
+ * @brief gets an Interest or Data signature padding between maximum size and
+ * real size
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] signature_size - retrieve the padding between maximum size and
+ * real size
+ * @return hICN error code
+ */
+ int (*get_signature_padding) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos, size_t *signature_padding);
+
+ /**
+ * @brief Gets the signature timestamp
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] signature_timestamp - Retrieved signature timestamp
+ * @return hICN error code
+ */
+ int (*get_signature_timestamp) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos,
+ uint64_t *signature_timestamp);
+
+ /**
+ * @brief Sets the signature timestamp
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] signature_timestamp - Signature timestamp to set
+ * @return hICN error code
+ */
+ int (*set_signature_timestamp) (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, uint64_t signature_timestamp);
+
+ /**
+ * @brief Gets the signature validation algorithm
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] validation_algorithm - Retrieved validation_algorithm
+ * @return hICN error code
+ */
+ int (*get_validation_algorithm) (const hicn_packet_buffer_t *pkbuf,
+ const size_t pos,
+ uint8_t *validation_algorithm);
+
+ /**
+ * @brief Sets the signature validation algorithm
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] validation_algorithm - Validation algorithm enumeration
+ * @return hICN error code
+ */
+ int (*set_validation_algorithm) (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, uint8_t validation_algorithm);
+
+ /**
+ * @brief Gets the key id
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] key_id - Retrieved key id first byte address
+ * @return hICN error code
+ */
+ int (*get_key_id) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ uint8_t **key_id, uint8_t *key_id_size);
+
+ /**
+ * @brief Sets the key id
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] key_id - Key id first byte address
+ * @return hICN error code
+ */
+ int (*set_key_id) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *key_id, size_t size);
+
+ /**
+ * @brief Get a pointer to the signature field in the packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] signature - Pointer to the memory region holding the
+ * signature
+ * @return hICN error code
+ */
+ int (*get_signature) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ uint8_t **signature);
+
+ /**
+ * @brief Returns whether the packet holds a signature.
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] flag - Boolean indicating whether the packet has a signature.
+ * @return hICN error code
+ */
+ int (*has_signature) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ bool *flag);
+
+ /**
+ * @brief Set payload type of the packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in,out] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [in] payload_type - The payload type of this packet
+ * @return hICN error code
+ */
+ int (*set_payload_type) (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t payload_type);
+
+ /**
+ * @brief Get payload type from the packet
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] payload_type - The payload type of this packet
+ * @return hICN error code
+ */
+ int (*get_payload_type) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_payload_type_t *payload_type);
+
+ /**
+ * @brief Check if data packet is last one.
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in] pos - Current position in the sequence of headers while
+ * executing command
+ * @param [out] is_last - 1 if last data, 0 otherwise
+ * @return hICN error code
+ */
+ int (*is_last_data) (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ int *is_last);
+
+ /**
+ * @brief Mark data packet as last
+ * @param [in] pkbuf - hICN packet buffer
+ * @param [in, out] pos - Current position in the sequence of headers while
+ * executing command
+ * @return hICN error code
+ */
+ int (*set_last_data) (const hicn_packet_buffer_t *pkbuf, size_t pos);
+
+} hicn_ops_t;
+
+#define DECLARE_HICN_OPS(protocol, len) \
+ const hicn_ops_t hicn_ops_##protocol = { \
+ ATTR_INIT (name, #protocol), \
+ ATTR_INIT (header_len, len), \
+ ATTR_INIT (init_packet_header, protocol##_init_packet_header), \
+ ATTR_INIT (get_interest_locator, protocol##_get_interest_locator), \
+ ATTR_INIT (set_interest_locator, protocol##_set_interest_locator), \
+ ATTR_INIT (get_interest_name, protocol##_get_interest_name), \
+ ATTR_INIT (set_interest_name, protocol##_set_interest_name), \
+ ATTR_INIT (get_interest_name_suffix, \
+ protocol##_get_interest_name_suffix), \
+ ATTR_INIT (set_interest_name_suffix, \
+ protocol##_set_interest_name_suffix), \
+ ATTR_INIT (get_type, protocol##_get_type), \
+ ATTR_INIT (set_type, protocol##_set_type), \
+ ATTR_INIT (reset_interest_for_hash, protocol##_reset_interest_for_hash), \
+ ATTR_INIT (get_data_locator, protocol##_get_data_locator), \
+ ATTR_INIT (set_data_locator, protocol##_set_data_locator), \
+ ATTR_INIT (get_data_name, protocol##_get_data_name), \
+ ATTR_INIT (set_data_name, protocol##_set_data_name), \
+ ATTR_INIT (get_data_name_suffix, protocol##_get_data_name_suffix), \
+ ATTR_INIT (set_data_name_suffix, protocol##_set_data_name_suffix), \
+ ATTR_INIT (get_data_path_label, protocol##_get_data_path_label), \
+ ATTR_INIT (set_data_path_label, protocol##_set_data_path_label), \
+ ATTR_INIT (update_data_path_label, protocol##_update_data_path_label), \
+ ATTR_INIT (reset_data_for_hash, protocol##_reset_data_for_hash), \
+ ATTR_INIT (get_lifetime, protocol##_get_lifetime), \
+ ATTR_INIT (set_lifetime, protocol##_set_lifetime), \
+ ATTR_INIT (update_checksums, protocol##_update_checksums), \
+ ATTR_INIT (update_checksums_incremental, \
+ protocol##_update_checksums_incremental), \
+ ATTR_INIT (verify_checksums, protocol##_verify_checksums), \
+ ATTR_INIT (rewrite_interest, protocol##_rewrite_interest), \
+ ATTR_INIT (rewrite_data, protocol##_rewrite_data), \
+ ATTR_INIT (set_payload_len, protocol##_set_payload_len), \
+ ATTR_INIT (get_payload_type, protocol##_get_payload_type), \
+ ATTR_INIT (set_payload_type, protocol##_set_payload_type), \
+ ATTR_INIT (get_signature_size, protocol##_get_signature_size), \
+ ATTR_INIT (get_signature_timestamp, protocol##_get_signature_timestamp), \
+ ATTR_INIT (set_signature_timestamp, protocol##_set_signature_timestamp), \
+ ATTR_INIT (get_validation_algorithm, \
+ protocol##_get_validation_algorithm), \
+ ATTR_INIT (set_validation_algorithm, \
+ protocol##_set_validation_algorithm), \
+ ATTR_INIT (get_key_id, protocol##_get_key_id), \
+ ATTR_INIT (set_key_id, protocol##_set_key_id), \
+ ATTR_INIT (get_signature, protocol##_get_signature), \
+ ATTR_INIT (has_signature, protocol##_has_signature), \
+ ATTR_INIT (set_signature_padding, protocol##_set_signature_padding), \
+ ATTR_INIT (set_signature_size, protocol##_set_signature_size), \
+ ATTR_INIT (get_signature_padding, protocol##_get_signature_padding), \
+ ATTR_INIT (is_last_data, protocol##_is_last_data), \
+ }
+
+/**
+ * @brief Protocol-independent packet operations VFT
+ * NOTE: The following declarations should be kept in order
+ */
+extern const hicn_ops_t *const hicn_ops_vft[];
+
+static inline uint8_t
+PROT (const hicn_packet_buffer_t *pkbuf, int pos)
+{
+ if (pos < -1 || pos >= HICN_PACKET_FORMAT_SIZE - 1)
+ return IPPROTO_NONE;
+ hicn_packet_format_t format = hicn_packet_get_format (pkbuf);
+ return HICN_PACKET_FORMAT_GET (format, pos + 1);
+}
+
+#define CALL_CHILD(method, pkbuf, pos, ...) \
+ hicn_ops_vft[PROT (pkbuf, (pos))]->method (pkbuf, (pos) + 1, ##__VA_ARGS__);
+
+#define CALL(method, pkbuf, ...) CALL_CHILD (method, pkbuf, -1, ##__VA_ARGS__)
+
+/** Shortcuts to entry points in VFT */
+#define HICN_OPS4 hicn_ops_vft[IPPROTO_IP]
+#define HICN_OPS6 hicn_ops_vft[IPPROTO_IPV6]
+
+/* Helpers for simple declarations */
+
+#define DECLARE_init_packet_header(protocol, error) \
+ int protocol##_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_interest_locator(protocol, error) \
+ int protocol##_get_interest_locator (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ hicn_ip_address_t *ip_address) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_interest_locator(protocol, error) \
+ int protocol##_set_interest_locator (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ const hicn_ip_address_t *ip_address) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_interest_name(protocol, error) \
+ int protocol##_get_interest_name (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, hicn_name_t *name) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_interest_name(protocol, error) \
+ int protocol##_set_interest_name (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, const hicn_name_t *name) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_interest_name_suffix(protocol, error) \
+ int protocol##_get_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ hicn_name_suffix_t *suffix) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_interest_name_suffix(protocol, error) \
+ int protocol##_set_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ const hicn_name_suffix_t *suffix) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_type(protocol, error) \
+ int protocol##_get_type (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, hicn_packet_type_t *type) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_type(protocol, error) \
+ int protocol##_set_type (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, hicn_packet_type_t type) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_reset_interest_for_hash(protocol, error) \
+ int protocol##_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, \
+ size_t pos) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_data_locator(protocol, error) \
+ int protocol##_get_data_locator (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ hicn_ip_address_t *ip_address) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_data_locator(protocol, error) \
+ int protocol##_set_data_locator (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ const hicn_ip_address_t *ip_address) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_data_name(protocol, error) \
+ int protocol##_get_data_name (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, hicn_name_t *name) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_data_name(protocol, error) \
+ int protocol##_set_data_name (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, const hicn_name_t *name) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_data_name_suffix(protocol, error) \
+ int protocol##_get_data_name_suffix (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ hicn_name_suffix_t *suffix) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_data_name_suffix(protocol, error) \
+ int protocol##_set_data_name_suffix (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ const hicn_name_suffix_t *suffix) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_data_path_label(protocol, error) \
+ int protocol##_get_data_path_label (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ hicn_path_label_t *path_label) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_data_path_label(protocol, error) \
+ int protocol##_set_data_path_label (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ const hicn_path_label_t path_label) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_update_data_path_label(protocol, error) \
+ int protocol##_update_data_path_label (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ const hicn_faceid_t face_id) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_reset_data_for_hash(protocol, error) \
+ int protocol##_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, \
+ size_t pos) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_lifetime(protocol, error) \
+ int protocol##_get_lifetime (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, hicn_lifetime_t *lifetime) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_lifetime(protocol, error) \
+ int protocol##_set_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos, \
+ const hicn_lifetime_t lifetime) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_update_checksums(protocol, error) \
+ int protocol##_update_checksums (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, u16 partial_csum, \
+ size_t payload_len) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_update_checksums_incremental(protocol, error) \
+ int protocol##_update_checksums_incremental ( \
+ const hicn_packet_buffer_t *pkbuf, size_t pos, u16 *old_val, \
+ u16 *new_val, u8 size, bool skip_first) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_verify_checksums(protocol, error) \
+ int protocol##_verify_checksums (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, u16 partial_csum, \
+ size_t payload_len) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_rewrite_interest(protocol, error) \
+ int protocol##_rewrite_interest ( \
+ const hicn_packet_buffer_t *pkbuf, size_t pos, \
+ const hicn_ip_address_t *addr_new, hicn_ip_address_t *addr_old) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_rewrite_data(protocol, error) \
+ int protocol##_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos, \
+ const hicn_ip_address_t *addr_new, \
+ hicn_ip_address_t *addr_old, \
+ const hicn_faceid_t face_id, u8 reset_pl) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_payload_len(protocol, error) \
+ int protocol##_set_payload_len (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, size_t payload_len) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_payload_type(protocol, error) \
+ int protocol##_get_payload_type (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ hicn_payload_type_t *payload_type) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_payload_type(protocol, error) \
+ int protocol##_set_payload_type (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ hicn_payload_type_t payload_type) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_signature_size(protocol, error) \
+ int protocol##_get_signature_size (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ size_t *signature_size) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_signature_size(protocol, error) \
+ int protocol##_set_signature_size (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, size_t signature_size) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_signature_padding(protocol, error) \
+ int protocol##_set_signature_padding (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, size_t padding) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_signature_padding(protocol, error) \
+ int protocol##_get_signature_padding (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, size_t *padding) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_signature_timestamp(protocol, error) \
+ int protocol##_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ uint64_t signature_timestamp) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_signature_timestamp(protocol, error) \
+ int protocol##_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ uint64_t *signature_timestamp) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_validation_algorithm(protocol, error) \
+ int protocol##_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos, \
+ uint8_t validation_algorithm) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_validation_algorithm(protocol, error) \
+ int protocol##_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, \
+ uint8_t *validation_algorithm) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_key_id(protocol, error) \
+ int protocol##_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos, \
+ uint8_t *key_id, size_t size) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_key_id(protocol, error) \
+ int protocol##_get_key_id (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, uint8_t **key_id, \
+ uint8_t *key_id_size) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_get_signature(protocol, error) \
+ int protocol##_get_signature (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, uint8_t **signature) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_has_signature(protocol, error) \
+ int protocol##_has_signature (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, bool *flag) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_is_last_data(protocol, error) \
+ int protocol##_is_last_data (const hicn_packet_buffer_t *pkbuf, \
+ const size_t pos, int *is_last) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#define DECLARE_set_last_data(protocol, error) \
+ int protocol##_set_last_data (const hicn_packet_buffer_t *pkbuf, \
+ size_t pos) \
+ { \
+ return HICN_LIB_ERROR_##error; \
+ }
+
+#endif /* HICN_OPS_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/packet.c b/lib/src/packet.c
new file mode 100644
index 000000000..bebfad23e
--- /dev/null
+++ b/lib/src/packet.c
@@ -0,0 +1,806 @@
+/*
+ * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file packet.c
+ * @brief Implementation of the compatibility layer.
+ */
+#ifndef _WIN32
+#include <netinet/in.h>
+#endif
+#include <string.h> // memset
+#include <stddef.h> // offsetof
+
+#include <hicn/common.h>
+#include <hicn/packet.h>
+#include <hicn/error.h>
+#include <hicn/name.h>
+#include <hicn/util/log.h>
+#include "ops.h"
+
+#define member_size(type, member) sizeof (((type *) 0)->member)
+#define ARRAY_SIZE(a) (sizeof (a) / sizeof (*(a)))
+
+#define HICN_NAME_COMPONENT_SIZE 2
+
+hicn_packet_format_t
+hicn_packet_get_format (const hicn_packet_buffer_t *pkbuf)
+{
+ return pkbuf->format;
+}
+
+void
+hicn_packet_set_format (hicn_packet_buffer_t *pkbuf,
+ hicn_packet_format_t format)
+{
+ pkbuf->format = format;
+}
+
+hicn_packet_type_t
+hicn_packet_get_type (const hicn_packet_buffer_t *pkbuf)
+{
+ return pkbuf->type;
+}
+
+void
+hicn_packet_initialize_type (hicn_packet_buffer_t *pkbuf,
+ hicn_packet_type_t type)
+{
+ assert (pkbuf->format != HICN_PACKET_FORMAT_NONE);
+ pkbuf->type = type;
+ CALL (set_type, pkbuf, type);
+}
+
+void
+hicn_packet_set_type (hicn_packet_buffer_t *pkbuf, hicn_packet_type_t type)
+{
+ pkbuf->type = type;
+}
+
+bool
+hicn_packet_is_interest (const hicn_packet_buffer_t *pkbuf)
+{
+ return pkbuf->type == HICN_PACKET_TYPE_INTEREST;
+}
+
+bool
+hicn_packet_is_data (const hicn_packet_buffer_t *pkbuf)
+{
+ return pkbuf->type == HICN_PACKET_TYPE_DATA;
+}
+
+bool
+hicn_packet_is_undefined (const hicn_packet_buffer_t *pkbuf)
+{
+ return pkbuf->type == HICN_PACKET_TYPE_UNDEFINED;
+}
+
+int
+hicn_packet_init_header (hicn_packet_buffer_t *pkbuf,
+ size_t additional_header_size)
+{
+ if (hicn_packet_is_undefined (pkbuf))
+ return HICN_LIB_ERROR_UNEXPECTED;
+ if (hicn_packet_get_format (pkbuf) == HICN_PACKET_FORMAT_NONE)
+ return HICN_LIB_ERROR_UNEXPECTED;
+ if (!pkbuf_get_header (pkbuf))
+ return HICN_LIB_ERROR_UNEXPECTED;
+ pkbuf->len = 0;
+ pkbuf->payload = 0;
+
+ int rc = CALL (init_packet_header, pkbuf);
+
+ /*
+ * Additional header size is there for the signature, and assumes the AH
+ * header is always located at the end...
+ */
+ pkbuf->len += additional_header_size;
+ pkbuf->payload += additional_header_size;
+
+ return rc;
+}
+
+int
+hicn_packet_reset (hicn_packet_buffer_t *pkbuf)
+{
+ memset (pkbuf, 0, sizeof (hicn_packet_buffer_t));
+ hicn_packet_set_format (pkbuf, HICN_PACKET_FORMAT_NONE);
+ hicn_packet_set_type (pkbuf, HICN_PACKET_TYPE_UNDEFINED);
+ hicn_packet_set_len (pkbuf, 0);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+hicn_packet_analyze (hicn_packet_buffer_t *pkbuf)
+{
+ u8 *header = pkbuf_get_header (pkbuf);
+ u8 protocol;
+ u16 offset = 0;
+ bool has_signature;
+ size_t signature_size;
+ int rc;
+
+ /* Bootstrap: assume IP packet, and get version from header */
+ switch (HICN_IP_VERSION (pkbuf_get_header (pkbuf)))
+ {
+ case 4:
+ protocol = IPPROTO_IP;
+ break;
+ case 6:
+ protocol = IPPROTO_IPV6;
+ break;
+ case 9:
+ protocol = IPPROTO_ENCAP; // new
+ break;
+ default:
+ goto ERR;
+ }
+
+ hicn_packet_format_t *format = &pkbuf->format;
+ for (unsigned i = 0; i < HICN_PACKET_FORMAT_SIZE; i++)
+ {
+ HICN_PACKET_FORMAT_SET (*format, i, protocol);
+
+ /* Next protocol + increment offset */
+ switch (protocol)
+ {
+
+ /*
+ * All packets either start with IPv4 or IPv6, so we take the
+ * opportunity to update packet length there
+ */
+ case IPPROTO_IP:
+ {
+ if (i > 0)
+ goto ERR;
+#ifdef OPAQUE_IP
+ pkbuf->ipv4 = offset;
+#else
+ assert (offset == 0);
+#endif /* OPAQUE_IP */
+ _ipv4_header_t *ipv4 = (_ipv4_header_t *) (header + offset);
+ protocol = ipv4->protocol;
+ offset += IPV4_HDRLEN;
+
+ // hicn_packet_set_len (pkbuf, htons (ipv4->len));
+ if (hicn_packet_get_len (pkbuf) != htons (ipv4->len))
+ {
+ ERROR ("Invalid packet size in IPv4 header %d != %d",
+ htons (ipv4->len), hicn_packet_get_len (pkbuf));
+ goto ERR;
+ }
+ break;
+ }
+ case IPPROTO_IPV6:
+ {
+ if (i > 0)
+ goto ERR;
+#ifdef OPAQUE_IP
+ pkbuf->ipv6 = offset;
+#else
+ assert (offset == 0);
+#endif /* OPAQUE_IP */
+ _ipv6_header_t *ipv6 = (_ipv6_header_t *) (header + offset);
+ protocol = ipv6->nxt;
+ offset += IPV6_HDRLEN;
+ // hicn_packet_set_len (pkbuf, IPV6_HDRLEN + htons (ipv6->len));
+ if (hicn_packet_get_len (pkbuf) != IPV6_HDRLEN + htons (ipv6->len))
+ {
+ ERROR ("Invalid packet size in IPv6 header %d != %d",
+ IPV6_HDRLEN + htons (ipv6->len),
+ hicn_packet_get_len (pkbuf));
+ goto ERR;
+ }
+ break;
+ }
+ case IPPROTO_TCP:
+ pkbuf->tcp = offset;
+ /* After TCP, we might eventually have a AH header */
+ rc = CALL_CHILD (has_signature, pkbuf, i - 1, &has_signature);
+ if (rc < 0)
+ goto ERR;
+ protocol = has_signature ? IPPROTO_AH : IPPROTO_NONE;
+ offset += TCP_HDRLEN;
+ break;
+ case IPPROTO_UDP:
+ pkbuf->udp = offset;
+ protocol = IPPROTO_ENCAP;
+ offset += UDP_HDRLEN;
+ break;
+ case IPPROTO_ICMP:
+ case IPPROTO_ICMPV6:
+ pkbuf->icmp = offset;
+ /* After ICMP, we might eventually have a AH header */
+ // CALL_CHILD (has_signature, pkbuf, i - 1, &has_signature);
+ protocol = /* has_signature ? IPPROTO_AH : */ IPPROTO_NONE;
+ offset += ICMP_HDRLEN;
+ break;
+
+ case IPPROTO_ENCAP:
+ pkbuf->newhdr = offset;
+ /* After ENCAP, we might eventually have a AH header */
+ rc = CALL_CHILD (has_signature, pkbuf, i - 1, &has_signature);
+ if (rc < 0)
+ goto ERR;
+ protocol = has_signature ? IPPROTO_AH : IPPROTO_NONE;
+ offset += NEW_HDRLEN;
+ break;
+
+ case IPPROTO_AH:
+ pkbuf->ah = offset;
+ protocol = IPPROTO_NONE;
+ offset += AH_HDRLEN;
+
+ rc = CALL_CHILD (get_signature_size, pkbuf, i - 1, &signature_size);
+ if (rc < 0)
+ goto ERR;
+ offset += signature_size;
+ break;
+
+ case IPPROTO_NONE:
+ /* NONE until we terminate the list of protocols */
+ break;
+
+ default:
+ goto ERR;
+ }
+ }
+ pkbuf->payload = offset;
+
+ rc = CALL (get_type, pkbuf, (hicn_packet_type_t *) (&pkbuf->type));
+ if (rc < 0)
+ goto ERR;
+
+ return HICN_LIB_ERROR_NONE;
+
+ERR:
+ pkbuf->format = HICN_PACKET_FORMAT_NONE;
+ pkbuf->type = HICN_PACKET_TYPE_UNDEFINED;
+ return HICN_LIB_ERROR_UNEXPECTED;
+}
+
+int
+hicn_packet_set_buffer (hicn_packet_buffer_t *pkbuf, u8 *buffer,
+ uint16_t buffer_size, uint16_t len)
+{
+ pkbuf_set_header (pkbuf, buffer);
+ pkbuf->buffer_size = buffer_size;
+ pkbuf->len = len;
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+hicn_packet_get_buffer (const hicn_packet_buffer_t *pkbuf, u8 **buffer,
+ uint16_t *buffer_size, uint16_t *len)
+{
+ *buffer = pkbuf_get_header (pkbuf);
+ *buffer_size = pkbuf->buffer_size;
+ *len = pkbuf->len;
+ return HICN_LIB_ERROR_NONE;
+}
+
+size_t
+hicn_packet_get_len (const hicn_packet_buffer_t *pkbuf)
+{
+ return pkbuf->len;
+}
+
+int
+hicn_packet_set_len (hicn_packet_buffer_t *pkbuf, size_t len)
+{
+ pkbuf->len = len;
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+hicn_packet_get_header_len (const hicn_packet_buffer_t *pkbuf, size_t *len)
+{
+ *len = pkbuf->payload;
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+hicn_packet_get_payload_len (const hicn_packet_buffer_t *pkbuf, size_t *len)
+{
+ *len = hicn_packet_get_len (pkbuf) - pkbuf->payload;
+ return HICN_LIB_ERROR_NONE;
+}
+
+// XXX this fails with chained membufs in libtransport
+int
+hicn_packet_set_payload (const hicn_packet_buffer_t *pkbuf, const u8 *payload,
+ u16 payload_len)
+{
+ memcpy (pkbuf_get_header (pkbuf) + pkbuf->payload, payload, payload_len);
+
+ return CALL (set_payload_len, pkbuf, payload_len);
+}
+
+int
+hicn_packet_get_payload (const hicn_packet_buffer_t *pkbuf, u8 **payload,
+ size_t *payload_size, bool hard_copy)
+{
+ *payload_size = hicn_packet_get_len (pkbuf) - pkbuf->payload;
+
+ if (hard_copy)
+ {
+ memcpy (payload, pkbuf_get_header (pkbuf) + pkbuf->payload,
+ *payload_size);
+ }
+ else
+ {
+ *payload = pkbuf_get_header (pkbuf) + pkbuf->payload;
+ }
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+/* Header fields manipulation */
+
+int
+hicn_packet_get_header_length_from_format (hicn_packet_format_t format,
+ size_t *header_length)
+{
+ *header_length = 0;
+ HICN_PACKET_FORMAT_ENUMERATE (format, i, protocol, {
+ *header_length += hicn_ops_vft[protocol]->header_len;
+ });
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+hicn_packet_compute_checksum (const hicn_packet_buffer_t *pkbuf)
+{
+ return CALL (update_checksums, pkbuf, 0, ~0);
+}
+
+int
+hicn_packet_compute_header_checksum (const hicn_packet_buffer_t *pkbuf,
+ u16 init_sum)
+{
+ /* payload_len == 0: ignore payload */
+ return CALL (update_checksums, pkbuf, init_sum, 0);
+}
+
+int
+hicn_packet_check_integrity_no_payload (const hicn_packet_buffer_t *pkbuf,
+ u16 init_sum)
+{
+ return CALL (verify_checksums, pkbuf, init_sum, 0);
+}
+
+int
+hicn_packet_set_payload_length (const hicn_packet_buffer_t *pkbuf,
+ const size_t payload_len)
+{
+ return CALL (set_payload_len, pkbuf, payload_len);
+}
+
+int
+hicn_packet_compare (const hicn_packet_buffer_t *pkbuf1,
+ const hicn_packet_buffer_t *pkbuf2)
+{
+ hicn_packet_format_t format1 = hicn_packet_get_format (pkbuf1);
+ hicn_packet_format_t format2 = hicn_packet_get_format (pkbuf2);
+
+ if (format1 != format2)
+ return HICN_LIB_ERROR_UNEXPECTED;
+
+ size_t len1 = hicn_packet_get_len (pkbuf1);
+ size_t len2 = hicn_packet_get_len (pkbuf2);
+
+ if (len1 != len2)
+ return HICN_LIB_ERROR_UNEXPECTED;
+
+ return memcmp (pkbuf_get_header (pkbuf1), pkbuf_get_header (pkbuf2), len1);
+}
+
+int
+hicn_packet_get_name (const hicn_packet_buffer_t *pkbuf, hicn_name_t *name)
+{
+ switch (pkbuf->type)
+ {
+ case HICN_PACKET_TYPE_INTEREST:
+ return hicn_interest_get_name (pkbuf, name);
+ case HICN_PACKET_TYPE_DATA:
+ return hicn_data_get_name (pkbuf, name);
+ default:
+ return HICN_LIB_ERROR_UNEXPECTED;
+ }
+}
+
+int
+hicn_packet_set_name (const hicn_packet_buffer_t *pkbuf,
+ const hicn_name_t *name)
+{
+ switch (pkbuf->type)
+ {
+ case HICN_PACKET_TYPE_INTEREST:
+ return hicn_interest_set_name (pkbuf, name);
+ case HICN_PACKET_TYPE_DATA:
+ return hicn_data_set_name (pkbuf, name);
+ default:
+ return HICN_LIB_ERROR_UNEXPECTED;
+ }
+}
+
+int
+hicn_packet_get_locator (const hicn_packet_buffer_t *pkbuf,
+ hicn_ip_address_t *address)
+{
+ switch (pkbuf->type)
+ {
+ case HICN_PACKET_TYPE_INTEREST:
+ return hicn_interest_get_locator (pkbuf, address);
+ case HICN_PACKET_TYPE_DATA:
+ return hicn_data_get_locator (pkbuf, address);
+ default:
+ return HICN_LIB_ERROR_UNEXPECTED;
+ }
+}
+
+int
+hicn_packet_set_locator (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *address)
+{
+ switch (pkbuf->type)
+ {
+ case HICN_PACKET_TYPE_INTEREST:
+ return hicn_interest_set_locator (pkbuf, address);
+ case HICN_PACKET_TYPE_DATA:
+ return hicn_data_set_locator (pkbuf, address);
+ default:
+ return HICN_LIB_ERROR_UNEXPECTED;
+ }
+}
+
+int
+hicn_packet_get_signature_size (const hicn_packet_buffer_t *pkbuf,
+ size_t *bytes)
+{
+ return CALL (get_signature_size, pkbuf, bytes);
+}
+
+int
+hicn_packet_set_signature_size (const hicn_packet_buffer_t *pkbuf,
+ size_t bytes)
+{
+ return CALL (set_signature_size, pkbuf, bytes);
+}
+
+int
+hicn_packet_get_signature_padding (const hicn_packet_buffer_t *pkbuf,
+ size_t *bytes)
+{
+ return CALL (get_signature_padding, pkbuf, bytes);
+}
+
+int
+hicn_packet_set_signature_padding (const hicn_packet_buffer_t *pkbuf,
+ size_t bytes)
+{
+ return CALL (set_signature_padding, pkbuf, bytes);
+}
+
+int
+hicn_packet_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf,
+ uint64_t signature_timestamp)
+{
+ return CALL (set_signature_timestamp, pkbuf, signature_timestamp);
+}
+
+int
+hicn_packet_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf,
+ uint64_t *signature_timestamp)
+{
+ return CALL (get_signature_timestamp, pkbuf, signature_timestamp);
+}
+
+int
+hicn_packet_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf,
+ uint8_t validation_algorithm)
+{
+ return CALL (set_validation_algorithm, pkbuf, validation_algorithm);
+}
+
+int
+hicn_packet_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf,
+ uint8_t *validation_algorithm)
+{
+ return CALL (get_validation_algorithm, pkbuf, validation_algorithm);
+}
+
+int
+hicn_packet_set_key_id (const hicn_packet_buffer_t *pkbuf, uint8_t *key_id,
+ size_t key_len)
+{
+ return CALL (set_key_id, pkbuf, key_id, key_len);
+}
+
+int
+hicn_packet_get_key_id (const hicn_packet_buffer_t *pkbuf, uint8_t **key_id,
+ uint8_t *key_id_len)
+{
+ return CALL (get_key_id, pkbuf, key_id, key_id_len);
+}
+
+int
+hicn_packet_get_lifetime (const hicn_packet_buffer_t *pkbuf,
+ hicn_lifetime_t *lifetime)
+{
+ return CALL (get_lifetime, pkbuf, lifetime);
+}
+
+int
+hicn_packet_set_lifetime (const hicn_packet_buffer_t *pkbuf,
+ hicn_lifetime_t lifetime)
+{
+ return CALL (set_lifetime, pkbuf, lifetime);
+}
+
+int
+hicn_packet_get_payload_type (const hicn_packet_buffer_t *pkbuf,
+ hicn_payload_type_t *payload_type)
+{
+ return CALL (get_payload_type, pkbuf, payload_type);
+}
+
+int
+hicn_packet_set_payload_type (const hicn_packet_buffer_t *pkbuf,
+ hicn_payload_type_t payload_type)
+{
+ return CALL (set_payload_type, pkbuf, payload_type);
+}
+
+int
+hicn_packet_save_header (const hicn_packet_buffer_t *pkbuf, u8 *header,
+ size_t *header_len, bool copy_ah)
+{
+ hicn_packet_format_t format = hicn_packet_get_format (pkbuf);
+ if (copy_ah || !HICN_PACKET_FORMAT_IS_AH (format))
+ {
+ int rc = hicn_packet_get_header_len (pkbuf, header_len);
+ if (HICN_LIB_IS_ERROR (rc))
+ return rc;
+ }
+ else
+ {
+ /* Copy up until the ah header (which we assume is last) */
+ *header_len = pkbuf->ah;
+ }
+
+ memcpy (header, pkbuf_get_header (pkbuf), *header_len);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+hicn_packet_load_header (const hicn_packet_buffer_t *pkbuf, const u8 *header,
+ size_t header_len)
+{
+ memcpy (pkbuf_get_header (pkbuf), header, header_len);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+/* Interest */
+
+int
+hicn_interest_get_name (const hicn_packet_buffer_t *pkbuf, hicn_name_t *name)
+{
+ return CALL (get_interest_name, pkbuf, name);
+}
+
+int
+hicn_interest_set_name (const hicn_packet_buffer_t *pkbuf,
+ const hicn_name_t *name)
+{
+ return CALL (set_interest_name, pkbuf, name);
+}
+
+int
+hicn_interest_get_locator (const hicn_packet_buffer_t *pkbuf,
+ hicn_ip_address_t *address)
+{
+ return CALL (get_interest_locator, pkbuf, address);
+}
+
+int
+hicn_interest_set_locator (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *address)
+{
+ return CALL (set_interest_locator, pkbuf, address);
+}
+
+int
+hicn_interest_compare (const hicn_packet_buffer_t *pkbuf1,
+ const hicn_packet_buffer_t *pkbuf2)
+{
+ return hicn_packet_compare (pkbuf1, pkbuf2);
+}
+
+int
+hicn_interest_get_lifetime (const hicn_packet_buffer_t *pkbuf,
+ hicn_lifetime_t *lifetime)
+{
+ return hicn_packet_get_lifetime (pkbuf, lifetime);
+}
+
+int
+hicn_interest_set_lifetime (const hicn_packet_buffer_t *pkbuf,
+ hicn_lifetime_t lifetime)
+{
+ return hicn_packet_set_lifetime (pkbuf, lifetime);
+}
+
+int
+hicn_interest_get_payload (const hicn_packet_buffer_t *pkbuf, u8 **payload,
+ size_t *payload_size, bool hard_copy)
+{
+ return hicn_packet_get_payload (pkbuf, payload, payload_size, hard_copy);
+}
+
+int
+hicn_interest_set_payload (const hicn_packet_buffer_t *pkbuf,
+ const u8 *payload, size_t payload_len)
+{
+ return hicn_packet_set_payload (pkbuf, payload, (u16) payload_len);
+}
+
+int
+hicn_interest_reset_for_hash (hicn_packet_buffer_t *pkbuf)
+{
+ return CALL (reset_interest_for_hash, pkbuf);
+}
+
+/* Data */
+
+int
+hicn_data_get_name (const hicn_packet_buffer_t *pkbuf, hicn_name_t *name)
+{
+ return CALL (get_data_name, pkbuf, name);
+}
+
+int
+hicn_data_set_name (const hicn_packet_buffer_t *pkbuf, const hicn_name_t *name)
+{
+ return CALL (set_data_name, pkbuf, name);
+}
+
+int
+hicn_data_get_locator (const hicn_packet_buffer_t *pkbuf,
+ hicn_ip_address_t *address)
+{
+ return CALL (get_data_locator, pkbuf, address);
+}
+
+int
+hicn_data_set_locator (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *address)
+{
+ return CALL (set_data_locator, pkbuf, address);
+}
+
+int
+hicn_data_compare (const hicn_packet_buffer_t *pkbuf1,
+ const hicn_packet_buffer_t *pkbuf2)
+{
+ return hicn_packet_compare (pkbuf1, pkbuf2);
+}
+
+int
+hicn_data_get_expiry_time (const hicn_packet_buffer_t *pkbuf,
+ hicn_lifetime_t *expiry_time)
+{
+ return hicn_packet_get_lifetime (pkbuf, expiry_time);
+}
+
+int
+hicn_data_set_expiry_time (const hicn_packet_buffer_t *pkbuf,
+ hicn_lifetime_t expiry_time)
+{
+ return hicn_packet_set_lifetime (pkbuf, expiry_time);
+}
+
+/* Path label */
+
+int
+hicn_data_get_path_label (const hicn_packet_buffer_t *pkbuf,
+ hicn_path_label_t *path_label)
+{
+ return CALL (get_data_path_label, pkbuf, path_label);
+}
+
+int
+hicn_get_path_label (const hicn_packet_buffer_t *pkbuf,
+ hicn_path_label_t *path_label)
+{
+ if (!hicn_packet_is_data (pkbuf))
+ return INVALID_PATH_LABEL;
+ return hicn_data_get_path_label (pkbuf, path_label);
+}
+
+int
+hicn_data_set_path_label (const hicn_packet_buffer_t *pkbuf,
+ hicn_path_label_t path_label)
+{
+ return CALL (set_data_path_label, pkbuf, path_label);
+}
+
+int
+hicn_data_set_payload (const hicn_packet_buffer_t *pkbuf, const u8 *payload,
+ size_t payload_len)
+{
+ return hicn_packet_set_payload (pkbuf, payload, (u16) payload_len);
+}
+
+int
+hicn_data_get_payload (const hicn_packet_buffer_t *pkbuf, u8 **payload,
+ size_t *payload_size, bool hard_copy)
+{
+ return hicn_packet_get_payload (pkbuf, payload, payload_size, hard_copy);
+}
+
+int
+hicn_data_reset_for_hash (hicn_packet_buffer_t *pkbuf)
+{
+ return CALL (reset_data_for_hash, pkbuf);
+}
+
+int
+hicn_data_is_last (const hicn_packet_buffer_t *pkbuf, int *is_last)
+{
+ return CALL (is_last_data, pkbuf, is_last);
+}
+
+int
+hicn_data_set_last (const hicn_packet_buffer_t *pkbuf)
+{
+ return CALL (set_last_data, pkbuf);
+}
+
+int
+hicn_packet_get_signature (const hicn_packet_buffer_t *pkbuf,
+ uint8_t **sign_buf)
+{
+ return CALL (get_signature, pkbuf, sign_buf);
+}
+
+int
+hicn_interest_rewrite (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
+{
+ return CALL (rewrite_interest, pkbuf, addr_new, addr_old);
+}
+
+int
+hicn_data_rewrite (const hicn_packet_buffer_t *pkbuf,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
+{
+ return CALL (rewrite_data, pkbuf, addr_new, addr_old, face_id, reset_pl);
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/policy.c b/lib/src/policy.c
index 694f0ea5e..4a4b9fa89 100644
--- a/lib/src/policy.c
+++ b/lib/src/policy.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,41 +21,53 @@
#include <stdio.h>
#include <hicn/policy.h>
-const char * policy_tag_str[] = {
- #define _(x, y) [POLICY_TAG_ ## x] = STRINGIZE(x),
- foreach_policy_tag
- #undef _
+const char *policy_tag_str[] = {
+#define _(x, y) [POLICY_TAG_##x] = STRINGIZE (x),
+ foreach_policy_tag
+#undef _
};
const char policy_tag_short_str[] = {
- #define _(x, y) [POLICY_TAG_ ## x] = y,
- foreach_policy_tag
- #undef _
+#define _(x, y) [POLICY_TAG_##x] = y,
+ foreach_policy_tag
+#undef _
};
-const char * policy_state_str[] = {
- #define _(x) [POLICY_STATE_ ## x] = STRINGIZE(x),
- foreach_policy_state
- #undef _
+const char *policy_state_str[] = {
+#define _(x) [POLICY_STATE_##x] = STRINGIZE (x),
+ foreach_policy_state
+#undef _
};
+policy_state_t
+policy_state_from_str (const char *str)
+{
+#define _(x) \
+ if (strcasecmp (str, #x) == 0) \
+ return POLICY_STATE_##x; \
+ else
+ foreach_policy_state
+#undef _
+ return POLICY_STATE_N;
+}
+
int
-policy_tag_state_snprintf(char * s, size_t size, const policy_tag_state_t * tag_state)
+policy_tag_state_snprintf (char *s, size_t size,
+ const policy_tag_state_t *tag_state)
{
- char *cur = s;
- int rc;
-
- if (tag_state->disabled > 1)
- return -1;
-
- rc = snprintf(cur, s + size - cur, "%s%s", (tag_state->disabled == 1) ? "!" : "", policy_state_str[tag_state->state]);
- if (rc >= (int)(s + size - cur))
- return (int)(s + size - cur);
- if (rc < 0)
- return rc;
- cur += rc;
- if (size != 0 && cur >= s + size)
- return (int)(cur - s);
-
- return (int)(cur - s);
+ char *cur = s;
+ int rc;
+
+ if (tag_state->disabled > 1)
+ return -1;
+
+ rc = snprintf (cur, s + size - cur, "%s%s",
+ (tag_state->disabled == 1) ? "!" : "",
+ policy_state_str[tag_state->state]);
+ if (rc >= (int) (s + size - cur))
+ return (int) (s + size - cur);
+ if (rc < 0)
+ return rc;
+ cur += rc;
+ return (int) (cur - s);
}
diff --git a/lib/includes/hicn/protocol.h b/lib/src/protocol.h
index a97cc99cf..58bbb2ac2 100644
--- a/lib/includes/hicn/protocol.h
+++ b/lib/src/protocol.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -27,18 +27,7 @@
#include "protocol/icmprd.h"
#include "protocol/tcp.h"
#include "protocol/udp.h"
-
-typedef union
-{
- _ipv4_header_t ipv4;
- _ipv6_header_t ipv6;
- _tcp_header_t tcp;
- _udp_header_t udp;
- _icmp_header_t icmp;
- _icmprd_header_t icmprd;
- _ah_header_t ah;
- void *bytes;
-} hicn_protocol_t;
+#include "protocol/new.h"
#endif /* HICN_PROTOCOL_H */
diff --git a/lib/src/protocol/ah.c b/lib/src/protocol/ah.c
index 13340eae1..ea028d559 100644
--- a/lib/src/protocol/ah.c
+++ b/lib/src/protocol/ah.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,12 +18,12 @@
* @brief hICN operations for AH header
*/
-#include <string.h> // memcpy
#include <hicn/common.h>
#include <hicn/error.h>
-#include <hicn/header.h>
-#include <hicn/ops.h>
-#include <hicn/protocol/ah.h>
+#include <string.h> // memcpy
+
+#include "../ops.h"
+#include "ah.h"
DECLARE_get_interest_locator (ah, UNEXPECTED);
DECLARE_set_interest_locator (ah, UNEXPECTED);
@@ -31,206 +31,242 @@ DECLARE_get_interest_name (ah, UNEXPECTED);
DECLARE_set_interest_name (ah, UNEXPECTED);
DECLARE_get_interest_name_suffix (ah, UNEXPECTED);
DECLARE_set_interest_name_suffix (ah, UNEXPECTED);
-DECLARE_mark_packet_as_interest (ah, UNEXPECTED);
-DECLARE_mark_packet_as_data (ah, UNEXPECTED);
+DECLARE_get_type (ah, UNEXPECTED);
+DECLARE_set_type (ah, UNEXPECTED);
DECLARE_get_data_locator (ah, UNEXPECTED);
DECLARE_set_data_locator (ah, UNEXPECTED);
DECLARE_get_data_name (ah, UNEXPECTED);
DECLARE_set_data_name (ah, UNEXPECTED);
DECLARE_get_data_name_suffix (ah, UNEXPECTED);
DECLARE_set_data_name_suffix (ah, UNEXPECTED);
-DECLARE_get_data_pathlabel (ah, UNEXPECTED);
-DECLARE_set_data_pathlabel (ah, UNEXPECTED);
-DECLARE_update_data_pathlabel (ah, UNEXPECTED);
+DECLARE_get_data_path_label (ah, UNEXPECTED);
+DECLARE_set_data_path_label (ah, UNEXPECTED);
+DECLARE_update_data_path_label (ah, UNEXPECTED);
DECLARE_get_lifetime (ah, UNEXPECTED);
DECLARE_set_lifetime (ah, UNEXPECTED);
-DECLARE_get_payload_length (ah, UNEXPECTED);
-DECLARE_set_payload_length (ah, UNEXPECTED);
+// DECLARE_get_payload_len (ah, UNEXPECTED);
+DECLARE_set_payload_len (ah, UNEXPECTED);
+DECLARE_get_payload_type (ah, UNEXPECTED);
+DECLARE_set_payload_type (ah, UNEXPECTED);
+DECLARE_is_last_data (ah, UNEXPECTED);
+DECLARE_set_last_data (ah, UNEXPECTED);
int
-ah_init_packet_header (hicn_type_t type, hicn_protocol_t *h)
+ah_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- /* *INDENT-OFF* */
- h->ah = (_ah_header_t){
+ pkbuf->ah = pkbuf->len;
+ if (AH_HDRLEN > pkbuf->buffer_size - pkbuf->len)
+ return -1;
+ pkbuf->len += AH_HDRLEN;
+
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ /* clang-format off */
+ *ah = (_ah_header_t){
.nh = (u8) 0,
.payloadlen = (u8) 0,
.reserved = (u16) 0,
};
- /* *INDENT-ON* */
- return CHILD_OPS (init_packet_header, type, h);
+ /* clang-format on */
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
}
int
-ah_reset_interest_for_hash (hicn_type_t type, hicn_protocol_t *h)
+ah_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
size_t signature_size;
- int rc =
- hicn_ops_vft[type.l1]->get_signature_size (type, h, &signature_size);
+ int rc = CALL (get_signature_size, pkbuf, &signature_size);
if (rc < 0)
return rc;
- memset (&(h->ah.validationPayload), 0, signature_size);
- return CHILD_OPS (reset_interest_for_hash, type, h);
+ memset (&(ah->validationPayload), 0, signature_size);
+ ah->signaturePadding = 0;
+ return CALL_CHILD (reset_interest_for_hash, pkbuf, pos);
}
int
-ah_reset_data_for_hash (hicn_type_t type, hicn_protocol_t *h)
+ah_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
size_t signature_size;
- int rc =
- hicn_ops_vft[type.l1]->get_signature_size (type, h, &signature_size);
+ int rc = CALL (get_signature_size, pkbuf, &signature_size);
if (rc < 0)
return rc;
- memset (&(h->ah.validationPayload), 0, signature_size);
- return CHILD_OPS (reset_interest_for_hash, type, h);
+ memset (&(ah->validationPayload), 0, signature_size);
+ ah->signaturePadding = 0;
+ return CALL_CHILD (reset_interest_for_hash, pkbuf, pos);
}
int
-ah_update_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+ah_update_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
/* Nothing to do as there is no checksum in AH */
return HICN_LIB_ERROR_NONE;
}
int
-ah_verify_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+ah_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 *old_val, u16 *new_val, u8 size,
+ bool skip_first)
{
- /* Nothing to do as there is no checksum in AH */
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (update_checksums_incremental, pkbuf, pos, old_val,
+ new_val, size, false);
}
int
-ah_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new, ip46_address_t *addr_old)
+ah_verify_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
- /* Nothing to do on signature */
+ /* Nothing to do as there is no checksum in AH */
return HICN_LIB_ERROR_NONE;
}
int
-ah_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new, ip46_address_t *addr_old,
- const hicn_faceid_t face_id, u8 reset_pl)
+ah_rewrite_interest (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
{
/* Nothing to do on signature */
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_length (hicn_type_t type, const hicn_protocol_t *h, size_t *length)
-{
- return HICN_LIB_ERROR_NOT_IMPLEMENTED;
-}
-
-int
-ah_get_current_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ah_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
{
- *header_length = AH_HDRLEN + (h->ah.payloadlen << 2);
+ /* Nothing to do on signature */
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ah_get_signature (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **signature)
{
- size_t child_header_length = 0;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
- *header_length = AH_HDRLEN + (h->ah.payloadlen << 2) + child_header_length;
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ *signature = ah->validationPayload;
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_signature (hicn_type_t type, hicn_protocol_t *h, uint8_t **signature)
+ah_has_signature (const hicn_packet_buffer_t *pkbuf, size_t pos, bool *flag)
{
- *signature = h->ah.validationPayload;
+ *flag = true;
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_signature_size (hicn_type_t type, const hicn_protocol_t *h,
+ah_get_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
size_t *signature_size)
{
- *signature_size = h->ah.payloadlen << 2;
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ *signature_size = ah->payloadlen << 2;
return HICN_LIB_ERROR_NONE;
}
int
-ah_set_signature_size (hicn_type_t type, hicn_protocol_t *h,
- const size_t signature_size)
+ah_set_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_size)
{
- h->ah.payloadlen = (u8) (signature_size >> 2);
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ ah->payloadlen = signature_size >> 2;
return HICN_LIB_ERROR_NONE;
}
int
-ah_set_signature_timestamp (hicn_type_t type, hicn_protocol_t *h,
+ah_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint64_t signature_timestamp)
{
- uint64_t netwok_order_timestamp = htonll (signature_timestamp);
- memcpy (h->ah.timestamp_as_u8, &netwok_order_timestamp, sizeof (uint64_t));
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ uint64_t netwok_order_timestamp = hicn_net_to_host_64 (signature_timestamp);
+ memcpy (ah->timestamp_as_u8, &netwok_order_timestamp, sizeof (uint64_t));
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_signature_timestamp (hicn_type_t type, const hicn_protocol_t *h,
+ah_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint64_t *signature_timestamp)
{
- memcpy (signature_timestamp, h->ah.timestamp_as_u8, sizeof (uint64_t));
- *signature_timestamp = ntohll (*signature_timestamp);
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ memcpy (signature_timestamp, ah->timestamp_as_u8, sizeof (uint64_t));
+ *signature_timestamp = hicn_host_to_net_64 (*signature_timestamp);
return HICN_LIB_ERROR_NONE;
}
int
-ah_set_validation_algorithm (hicn_type_t type, hicn_protocol_t *h,
+ah_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint8_t validation_algorithm)
{
- h->ah.validationAlgorithm = validation_algorithm;
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ ah->validationAlgorithm = validation_algorithm;
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_validation_algorithm (hicn_type_t type, const hicn_protocol_t *h,
+ah_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint8_t *validation_algorithm)
{
- *validation_algorithm = h->ah.validationAlgorithm;
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ *validation_algorithm = ah->validationAlgorithm;
return HICN_LIB_ERROR_NONE;
}
int
-ah_set_signature_gap (hicn_type_t type, hicn_protocol_t *h, uint8_t gap)
+ah_set_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t padding)
{
- h->ah.signatureGap = gap;
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ ah->signaturePadding = padding;
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_signature_gap (hicn_type_t type, const hicn_protocol_t *h, uint8_t *gap)
+ah_get_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *padding)
{
- *gap = h->ah.signatureGap;
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ *padding = ah->signaturePadding;
return HICN_LIB_ERROR_NONE;
}
int
-ah_set_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t *key_id)
+ah_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos, uint8_t *key_id,
+ size_t size)
{
- memcpy (h->ah.keyId, key_id, sizeof (h->ah.keyId));
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ if (size != sizeof (ah->keyId))
+ return HICN_LIB_ERROR_INVALID_PARAMETER;
+
+ memcpy (ah->keyId, key_id, sizeof (ah->keyId));
return HICN_LIB_ERROR_NONE;
}
int
-ah_get_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t **key_id,
+ah_get_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos, uint8_t **key_id,
uint8_t *key_id_size)
{
- *key_id = h->ah.keyId;
- *key_id_size = sizeof (h->ah.keyId);
+ _ah_header_t *ah = pkbuf_get_ah (pkbuf);
+
+ *key_id = ah->keyId;
+ *key_id_size = sizeof (ah->keyId);
return HICN_LIB_ERROR_NONE;
}
-DECLARE_HICN_OPS (ah);
+DECLARE_HICN_OPS (ah, AH_HDRLEN);
/*
* fd.io coding-style-patch-verification: ON
diff --git a/lib/src/protocol/ah.h b/lib/src/protocol/ah.h
new file mode 100644
index 000000000..ee124f92a
--- /dev/null
+++ b/lib/src/protocol/ah.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * @file protocol/ah.h
+ * @brief AH packet header
+ */
+#ifndef HICN_PROTOCOL_AH_H
+#define HICN_PROTOCOL_AH_H
+
+#include <hicn/common.h>
+
+/*
+ * The TCP PSH flag is set to indicate TCP payload in fact contains a AH header
+ * with signature information for the packet
+ */
+#define AH_FLAG 0x10
+
+/*
+ * The length of the AH struct must be 44 bytes.
+ */
+#define EXPECTED_AH_HDRLEN 44
+
+typedef struct
+{
+ u8 nh; // To match with reserved in IPSEC AH
+ // Length of the signature field. Note that the signature might be smaller
+ // than the field: the actual size is computed from the field size and
+ // signaturePadding.
+ u8 payloadlen;
+ union
+ {
+ u16 reserved;
+
+ struct
+ {
+ u8 validationAlgorithm;
+ u8 signaturePadding;
+ };
+ };
+ union
+ {
+ struct
+ {
+ u32 spi;
+ u32 seq;
+ };
+ // Unix timestamp indicating when the signature has been calculated
+ u8 timestamp_as_u8[8];
+ u16 timestamp_as_u16[4];
+ u32 timestamp_as_u32[2];
+ };
+ // ICV would follow
+ u8 keyId[32]; // Hash of pub key
+ /* 44 B + validationPayload */
+ u8 validationPayload[0]; // Holds the signature
+} _ah_header_t;
+
+#define AH_HDRLEN sizeof (_ah_header_t)
+static_assert (EXPECTED_AH_HDRLEN == AH_HDRLEN,
+ "Size of AH Struct does not match its expected size.");
+
+#endif /* HICN_PROTOCOL_AH_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/icmp.c b/lib/src/protocol/icmp.c
index 5783cf52c..add871bcf 100644
--- a/lib/src/protocol/icmp.c
+++ b/lib/src/protocol/icmp.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,10 +13,11 @@
* limitations under the License.
*/
-#include <string.h>
-#include <hicn/protocol/icmp.h>
#include <hicn/error.h>
-#include <hicn/ops.h>
+#include <string.h>
+
+#include "icmp.h"
+#include "../ops.h"
DECLARE_get_interest_locator (icmp, UNEXPECTED);
DECLARE_set_interest_locator (icmp, UNEXPECTED);
@@ -24,81 +25,104 @@ DECLARE_get_interest_name (icmp, UNEXPECTED);
DECLARE_set_interest_name (icmp, UNEXPECTED);
DECLARE_get_interest_name_suffix (icmp, UNEXPECTED);
DECLARE_set_interest_name_suffix (icmp, UNEXPECTED);
-DECLARE_mark_packet_as_interest (icmp, UNEXPECTED);
-DECLARE_mark_packet_as_data (icmp, UNEXPECTED);
DECLARE_get_data_locator (icmp, UNEXPECTED);
DECLARE_set_data_locator (icmp, UNEXPECTED);
DECLARE_get_data_name (icmp, UNEXPECTED);
DECLARE_set_data_name (icmp, UNEXPECTED);
DECLARE_get_data_name_suffix (icmp, UNEXPECTED);
DECLARE_set_data_name_suffix (icmp, UNEXPECTED);
-DECLARE_get_data_pathlabel (icmp, UNEXPECTED);
-DECLARE_set_data_pathlabel (icmp, UNEXPECTED);
-DECLARE_update_data_pathlabel (icmp, UNEXPECTED);
+DECLARE_get_data_path_label (icmp, UNEXPECTED);
+DECLARE_set_data_path_label (icmp, UNEXPECTED);
+DECLARE_update_data_path_label (icmp, UNEXPECTED);
DECLARE_get_lifetime (icmp, UNEXPECTED);
DECLARE_set_lifetime (icmp, UNEXPECTED);
-DECLARE_get_length (icmp, UNEXPECTED);
-DECLARE_get_payload_length (icmp, UNEXPECTED);
-DECLARE_set_payload_length (icmp, UNEXPECTED);
+// DECLARE_get_payload_len (icmp, UNEXPECTED);
+DECLARE_set_payload_len (icmp, UNEXPECTED);
+DECLARE_get_payload_type (icmp, UNEXPECTED);
+DECLARE_set_payload_type (icmp, UNEXPECTED);
DECLARE_get_signature (icmp, UNEXPECTED);
+DECLARE_has_signature (icmp, UNEXPECTED);
+DECLARE_is_last_data (icmp, UNEXPECTED);
+DECLARE_set_last_data (icmp, UNEXPECTED);
int
-icmp_init_packet_header (hicn_type_t type, hicn_protocol_t *h)
+icmp_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- h->icmp = (_icmp_header_t){
+ pkbuf->icmp = pkbuf->len;
+ if (ICMP_HDRLEN > pkbuf->buffer_size - pkbuf->len)
+ return -1;
+ pkbuf->len += ICMP_HDRLEN;
+
+ _icmp_header_t *icmp = pkbuf_get_icmp (pkbuf);
+
+ *icmp = (_icmp_header_t){
.type = 0,
.code = 0,
.csum = 0,
};
- return HICN_LIB_ERROR_NONE; // CHILD_OPS(init_packet_header, type, h->icmp);
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
}
int
-icmp_reset_interest_for_hash (hicn_type_t type, hicn_protocol_t *h)
+icmp_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- h->icmp.csum = 0;
+ _icmp_header_t *icmp = pkbuf_get_icmp (pkbuf);
+
+ icmp->csum = 0;
- return CHILD_OPS (reset_interest_for_hash, type, h);
+ return CALL_CHILD (reset_interest_for_hash, pkbuf, pos);
}
int
-icmp_reset_data_for_hash (hicn_type_t type, hicn_protocol_t *h)
+icmp_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- h->icmp.csum = 0;
+ _icmp_header_t *icmp = pkbuf_get_icmp (pkbuf);
+
+ icmp->csum = 0;
- return CHILD_OPS (reset_data_for_hash, type, h);
+ return CALL_CHILD (reset_data_for_hash, pkbuf, pos);
}
int
-icmp_update_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+icmp_update_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- // h->icmp.csum = 0;
- // h->icmp.csum = csum(h->bytes, TCP_HDRLEN + payload_length,
+ // icmp->csum = 0;
+ // icmp->csum = csum(h->bytes, TCP_HDRLEN + payload_len,
// ~partial_csum);
//
- // return CHILD_OPS(update_checksums, type, h->icmp, 0, payload_length);
+ // return CALL_CHILD(update_checksums, pkbuf, pos->icmp, 0,
+ // payload_len);
}
int
-icmp_verify_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+icmp_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first)
{
return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- // if (csum(h->bytes, TCP_HDRLEN + payload_length, ~partial_csum) != 0)
+}
+
+int
+icmp_verify_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
+{
+ return HICN_LIB_ERROR_NOT_IMPLEMENTED;
+ // if (csum(h->bytes, TCP_HDRLEN + payload_len, ~partial_csum) != 0)
// return HICN_LIB_ERROR_CORRUPTED_PACKET;
- // return CHILD_OPS(verify_checksums, type, h->icmp, 0, payload_length);
+ // return CALL_CHILD(verify_checksums, pkbuf, pos->icmp, 0,
+ // payload_len);
}
int
-icmp_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new,
- ip46_address_t *addr_old)
+icmp_rewrite_interest (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
{
return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- // u16 *icmp_checksum = &(h->icmp.csum);
+ // u16 *icmp_checksum = &(icmp->csum);
//
// /*
// * Padding fields are set to zero so we can apply checksum on the
@@ -119,12 +143,13 @@ icmp_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
}
int
-icmp_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new, ip46_address_t *addr_old,
- const hicn_faceid_t face_id, u8 reset_pl)
+icmp_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
{
return HICN_LIB_ERROR_NOT_IMPLEMENTED;
- // u16 *icmp_checksum = &(h->icmp.csum);
+ // u16 *icmp_checksum = &(icmp->csum);
//
// /*
// * Padding fields are set to zero so we can apply checksum on the
@@ -139,9 +164,9 @@ icmp_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
// csum = ip_csum_add_even (csum, addr_new->ip6.as_u64[0]);
// csum = ip_csum_add_even (csum, addr_new->ip6.as_u64[1]);
//
- // csum = ip_csum_sub_even (csum, h->icmp.pathlabel);
- // icmp_update_data_pathlabel(type, h, face_id);
- // csum = ip_csum_add_even (csum, h->icmp.pathlabel);
+ // csum = ip_csum_sub_even (csum, icmp->path_label);
+ // icmp_update_data_path_label(pkbuf, pos, face_id);
+ // csum = ip_csum_add_even (csum, icmp->path_label);
//
// *icmp_checksum = ip_csum_fold (csum);
//
@@ -149,95 +174,93 @@ icmp_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
}
int
-icmp_get_current_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+icmp_get_type (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_packet_type_t *type)
{
- *header_length = ICMP_HDRLEN;
+ *type = HICN_PACKET_TYPE_MAPME;
return HICN_LIB_ERROR_NONE;
}
int
-icmp_get_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+icmp_set_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_packet_type_t type)
{
- size_t child_header_length = 0;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
-
- *header_length = ICMP_HDRLEN + child_header_length;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (set_type, pkbuf, pos, type);
}
int
-icmp_get_signature_size (hicn_type_t type, const hicn_protocol_t *h,
+icmp_get_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
size_t *signature_size)
{
- return CHILD_OPS (get_signature_size, type, h, signature_size);
+ return CALL_CHILD (get_signature_size, pkbuf, pos, signature_size);
}
int
-icmp_set_signature_size (hicn_type_t type, hicn_protocol_t *h,
+icmp_set_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
size_t signature_size)
{
- return CHILD_OPS (set_signature_size, type, h, signature_size);
+ return CALL_CHILD (set_signature_size, pkbuf, pos, signature_size);
}
int
-icmp_set_signature_gap (hicn_type_t type, hicn_protocol_t *h, uint8_t gap)
+icmp_set_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t padding)
{
- return CHILD_OPS (set_signature_gap, type, h, gap);
+ return CALL_CHILD (set_signature_padding, pkbuf, pos, padding);
}
int
-icmp_get_signature_gap (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *gap)
+icmp_get_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *padding)
{
- return CHILD_OPS (get_signature_gap, type, h, gap);
+ return CALL_CHILD (get_signature_padding, pkbuf, pos, padding);
}
int
-icmp_set_signature_timestamp (hicn_type_t type, hicn_protocol_t *h,
+icmp_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint64_t signature_timestamp)
{
- return CHILD_OPS (set_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (set_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-icmp_get_signature_timestamp (hicn_type_t type, const hicn_protocol_t *h,
+icmp_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint64_t *signature_timestamp)
{
- return CHILD_OPS (get_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (get_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-icmp_set_validation_algorithm (hicn_type_t type, hicn_protocol_t *h,
+icmp_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint8_t validation_algorithm)
{
- return CHILD_OPS (set_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (set_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-icmp_get_validation_algorithm (hicn_type_t type, const hicn_protocol_t *h,
+icmp_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
uint8_t *validation_algorithm)
{
- return CHILD_OPS (get_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (get_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-icmp_set_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t *key_id)
+icmp_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *key_id, size_t key_len)
{
- return CHILD_OPS (set_key_id, type, h, key_id);
+ return CALL_CHILD (set_key_id, pkbuf, pos, key_id, key_len);
}
int
-icmp_get_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t **key_id,
- uint8_t *key_id_size)
+icmp_get_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **key_id, uint8_t *key_id_size)
{
- return CHILD_OPS (get_key_id, type, h, key_id, key_id_size);
+ return CALL_CHILD (get_key_id, pkbuf, pos, key_id, key_id_size);
}
-DECLARE_HICN_OPS (icmp);
+DECLARE_HICN_OPS (icmp, ICMP_HDRLEN);
/*
* fd.io coding-style-patch-verification: ON
diff --git a/lib/src/protocol/icmp.h b/lib/src/protocol/icmp.h
new file mode 100644
index 000000000..6cbba6398
--- /dev/null
+++ b/lib/src/protocol/icmp.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * @file protocol/icmp.h
+ * @brief ICMP packet header
+ */
+#ifndef HICN_PROTOCOL_ICMP_H
+#define HICN_PROTOCOL_ICMP_H
+
+#include <hicn/common.h>
+
+/*
+ * The length of the ICMP header struct must be 4 bytes.
+ */
+#define EXPECTED_ICMP_HDRLEN 4
+
+typedef struct
+{
+ u8 type;
+ u8 code;
+ u16 csum;
+} _icmp_header_t;
+
+#define ICMP_HDRLEN sizeof (_icmp_header_t)
+static_assert (EXPECTED_ICMP_HDRLEN == ICMP_HDRLEN,
+ "Size of ICMP struct does not match its expected size.");
+
+/*
+ * The length of the ICMPWLDR header struct must be 4 bytes.
+ */
+#define EXPECTED_ICMPWLDR_HDRLEN 8
+
+typedef struct
+{
+ u8 type;
+ u8 code;
+ u16 csum;
+ union
+ {
+ struct
+ {
+ u16 id;
+ u16 sequence;
+ } echo; /* echo datagram */
+ u32 gateway; /* gateway address */
+ struct
+ {
+ u16 _unused;
+ u16 mtu;
+ } frag; /* path mtu discovery */
+ struct
+ {
+ u16 expected_lbl;
+ u16 received_lbl;
+ } wldr_notification_lbl;
+ };
+} _icmp_wldr_header_t;
+
+#define ICMPWLDR_HDRLEN sizeof (_icmp_wldr_header_t)
+static_assert (EXPECTED_ICMPWLDR_HDRLEN == ICMPWLDR_HDRLEN,
+ "Size of ICMPWLDR struct does not match its expected size.");
+
+#endif /* HICN_PROTOCOL_ICMP_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/icmprd.h b/lib/src/protocol/icmprd.h
new file mode 100644
index 000000000..7edff8111
--- /dev/null
+++ b/lib/src/protocol/icmprd.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * @file protocol/icmp-rd.c
+ * @brief hICN operations for ICMP Redirect header
+ */
+#ifndef HICN_PROTOCOL_ICMPRD_H
+#define HICN_PROTOCOL_ICMPRD_H
+
+#include <hicn/common.h>
+#include "ipv4.h"
+
+/*
+ * The length of the ICMPRD4 header struct must be 92 bytes.
+ */
+#define EXPECTED_ICMPRD4_HDRLEN 92
+
+typedef struct
+{
+ u8 type;
+ u8 code;
+ u16 csum;
+ ipv4_address_t ip;
+ _ipv4_header_t iph;
+ u8 data[64];
+} _icmprd4_header_t;
+
+#define ICMPRD4_HDRLEN sizeof (_icmprd4_header_t)
+static_assert (EXPECTED_ICMPRD4_HDRLEN == ICMPRD4_HDRLEN,
+ "Size of ICMPWLDR struct does not match its expected size.");
+
+/*
+ * The length of the ICMPRD header struct must be 40 bytes.
+ */
+#define EXPECTED_ICMPRD_HDRLEN 40
+
+typedef struct
+{
+ u8 type;
+ u8 code;
+ u16 csum;
+ u32 res;
+ ipv6_address_t tgt;
+ ipv6_address_t dst;
+} _icmprd_header_t;
+
+#define ICMPRD_HDRLEN sizeof (_icmprd_header_t)
+static_assert (EXPECTED_ICMPRD_HDRLEN == ICMPRD_HDRLEN,
+ "Size of ICMPWLDR struct does not match its expected size.");
+
+#endif /* HICN_PROTOCOL_ICMPRD_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/ipv4.c b/lib/src/protocol/ipv4.c
index cf50f9996..daa5a706a 100644
--- a/lib/src/protocol/ipv4.c
+++ b/lib/src/protocol/ipv4.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,7 +14,7 @@
*/
/**
- * @file protocol/ipv4.c
+ * @file protocol/ipv4->c
* @brief hICN operations for IPv4 header
*
* NOTE: IPv4 options (affecting the header size) are currently not supported.
@@ -28,241 +28,262 @@
#include <string.h>
#include <hicn/error.h>
-#include <hicn/ops.h>
#include <hicn/common.h>
-#include <hicn/header.h>
-#include <hicn/protocol/ipv4.h>
-typedef unsigned short u_short;
-int ipv4_get_payload_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *payload_length);
+#include "../ops.h"
+#include "ipv4.h"
+
+#define UINT16_T_MASK 0x0000ffff // 1111 1111 1111 1111
+
+#define ipv4_get_payload_len(pkbuf, ipv4) htons (ipv4->len - pkbuf->payload)
int
-ipv4_init_packet_header (hicn_type_t type, hicn_protocol_t *h)
+ipv4_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- size_t total_header_length;
- int rc =
- hicn_ops_vft[type.l1]->get_header_length (type, h, &total_header_length);
- if (rc < 0)
- return rc;
+ assert (pkbuf->len == 0);
+ if (IPV4_HDRLEN > pkbuf->buffer_size - pkbuf->len)
+ return -1;
+ pkbuf->len += IPV4_HDRLEN;
- h->ipv4 = (_ipv4_header_t){
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ hicn_packet_format_t format = hicn_packet_get_format (pkbuf);
+
+ size_t header_len;
+ hicn_packet_get_header_length_from_format (pkbuf->format, &header_len);
+
+ /* We initialize the len considering an empty payload */
+ *ipv4 = (_ipv4_header_t){
.version_ihl = (IPV4_DEFAULT_VERSION << 4) | (0x0f & IPV4_DEFAULT_IHL),
.tos = IPV4_DEFAULT_TOS,
- .len = htons ((u16) total_header_length),
+ .len = htons (header_len),
.id = htons (IPV4_DEFAULT_ID),
.frag_off = htons (IPV4_DEFAULT_FRAG_OFF),
.ttl = HICN_DEFAULT_TTL,
- .protocol = type.l2,
+ .protocol = HICN_PACKET_FORMAT_GET (format, pos + 1),
.csum = 0,
.saddr.as_u32 = 0,
.daddr.as_u32 = 0,
};
- return CHILD_OPS (init_packet_header, type, h);
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
}
int
-ipv4_get_interest_locator (hicn_type_t type, const hicn_protocol_t *h,
- ip46_address_t *ip_address)
+ipv4_get_interest_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_ip_address_t *ip_address)
{
- ip_address->ip4 = h->ipv4.saddr;
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ ip_address->v4 = ipv4->saddr;
return HICN_LIB_ERROR_NONE;
}
int
-ipv4_set_interest_locator (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *ip_address)
+ipv4_set_interest_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address)
{
- h->ipv4.saddr = ip_address->ip4;
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ ipv4->saddr = ip_address->v4;
return HICN_LIB_ERROR_NONE;
}
int
-ipv4_get_interest_name (hicn_type_t type, const hicn_protocol_t *h,
+ipv4_get_interest_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_t *name)
{
- name->ip4.prefix_as_ip4 = h->ipv4.daddr;
-#ifndef HICN_VPP_PLUGIN
- name->type = HNT_CONTIGUOUS_V4;
- name->len = HICN_V4_NAME_LEN;
-#endif /* HICN_VPP_PLUGIN */
- return CHILD_OPS (get_interest_name_suffix, type, h, &(name->ip4.suffix));
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ name->prefix.v4 = ipv4->daddr;
+ return CALL_CHILD (get_interest_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv4_set_interest_name (hicn_type_t type, hicn_protocol_t *h,
+ipv4_set_interest_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_t *name)
{
- h->ipv4.daddr = name->ip4.prefix_as_ip4;
- return CHILD_OPS (set_interest_name_suffix, type, h, &(name->ip4.suffix));
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ ipv4->daddr = name->prefix.v4;
+ return CALL_CHILD (set_interest_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv4_get_interest_name_suffix (hicn_type_t type, const hicn_protocol_t *h,
+ipv4_get_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (get_interest_name_suffix, type, h, suffix);
+ return CALL_CHILD (get_interest_name_suffix, pkbuf, pos, suffix);
}
int
-ipv4_set_interest_name_suffix (hicn_type_t type, hicn_protocol_t *h,
+ipv4_set_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (set_interest_name_suffix, type, h, suffix);
+ return CALL_CHILD (set_interest_name_suffix, pkbuf, pos, suffix);
}
int
-ipv4_mark_packet_as_interest (hicn_type_t type, hicn_protocol_t *h)
+ipv4_get_type (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_packet_type_t *type)
{
- return CHILD_OPS (mark_packet_as_interest, type, h);
+ return CALL_CHILD (get_type, pkbuf, pos, type);
}
int
-ipv4_mark_packet_as_data (hicn_type_t type, hicn_protocol_t *h)
+ipv4_set_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_packet_type_t type)
{
- return CHILD_OPS (mark_packet_as_data, type, h);
+ return CALL_CHILD (set_type, pkbuf, pos, type);
}
int
-ipv4_reset_interest_for_hash (hicn_type_t type, hicn_protocol_t *h)
+ipv4_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
/* Sets everything to 0 up to IP destination address */
- memset (&(h->ipv4), 0, 16);
+ memset (ipv4, 0, 16);
- return CHILD_OPS (reset_interest_for_hash, type, h);
+ return CALL_CHILD (reset_interest_for_hash, pkbuf, pos);
}
int
-ipv4_get_data_locator (hicn_type_t type, const hicn_protocol_t *h,
- ip46_address_t *ip_address)
+ipv4_get_data_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_ip_address_t *ip_address)
{
- ip_address->ip4 = h->ipv4.daddr;
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ ip_address->v4 = ipv4->daddr;
return HICN_LIB_ERROR_NONE;
}
int
-ipv4_set_data_locator (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *ip_address)
+ipv4_set_data_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address)
{
- h->ipv4.daddr = ip_address->ip4;
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ ipv4->daddr = ip_address->v4;
return HICN_LIB_ERROR_NONE;
}
int
-ipv4_get_data_name (hicn_type_t type, const hicn_protocol_t *h,
+ipv4_get_data_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_t *name)
{
- name->ip4.prefix_as_ip4 = h->ipv4.saddr;
-#ifndef HICN_VPP_PLUGIN
- name->type = HNT_CONTIGUOUS_V4;
- name->len = HICN_V4_NAME_LEN;
-#endif /* HICN_VPP_PLUGIN */
- return CHILD_OPS (get_data_name_suffix, type, h, &(name->ip4.suffix));
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ name->prefix.v4 = ipv4->saddr;
+ return CALL_CHILD (get_data_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv4_set_data_name (hicn_type_t type, hicn_protocol_t *h,
+ipv4_set_data_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_t *name)
{
- h->ipv4.saddr = name->ip4.prefix_as_ip4;
- return CHILD_OPS (set_data_name_suffix, type, h, &(name->ip4.suffix));
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ ipv4->saddr = name->prefix.v4;
+ return CALL_CHILD (set_data_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv4_get_data_name_suffix (hicn_type_t type, const hicn_protocol_t *h,
+ipv4_get_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (get_data_name_suffix, type, h, suffix);
+ return CALL_CHILD (get_data_name_suffix, pkbuf, pos, suffix);
}
int
-ipv4_set_data_name_suffix (hicn_type_t type, hicn_protocol_t *h,
+ipv4_set_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (set_data_name_suffix, type, h, suffix);
+ return CALL_CHILD (set_data_name_suffix, pkbuf, pos, suffix);
}
int
-ipv4_get_data_pathlabel (hicn_type_t type, const hicn_protocol_t *h,
- u32 *pathlabel)
+ipv4_get_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t *path_label)
{
- return CHILD_OPS (get_data_pathlabel, type, h, pathlabel);
+ return CALL_CHILD (get_data_path_label, pkbuf, pos, path_label);
}
int
-ipv4_set_data_pathlabel (hicn_type_t type, hicn_protocol_t *h,
- const u32 pathlabel)
+ipv4_set_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t path_label)
{
- return CHILD_OPS (set_data_pathlabel, type, h, pathlabel);
+ return CALL_CHILD (set_data_path_label, pkbuf, pos, path_label);
}
int
-ipv4_update_data_pathlabel (hicn_type_t type, hicn_protocol_t *h,
- const hicn_faceid_t face_id)
+ipv4_update_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_faceid_t face_id)
{
- return CHILD_OPS (update_data_pathlabel, type, h, face_id);
+ return CALL_CHILD (update_data_path_label, pkbuf, pos, face_id);
}
int
-ipv4_reset_data_for_hash (hicn_type_t type, hicn_protocol_t *h)
+ipv4_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
/* Sets everything to 0 up to source address */
- memset (&h->ipv4, 0, 12);
+ memset (ipv4, 0, 12);
/* Clears destination address */
- memset (&(h->ipv4.daddr), 0, 4);
+ memset (&(ipv4->daddr), 0, 4);
- return CHILD_OPS (reset_data_for_hash, type, h);
+ return CALL_CHILD (reset_data_for_hash, pkbuf, pos);
}
int
-ipv4_get_lifetime (hicn_type_t type, const hicn_protocol_t *h,
+ipv4_get_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_lifetime_t *lifetime)
{
- return CHILD_OPS (get_lifetime, type, h, lifetime);
+ return CALL_CHILD (get_lifetime, pkbuf, pos, lifetime);
}
int
-ipv4_set_lifetime (hicn_type_t type, hicn_protocol_t *h,
+ipv4_set_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_lifetime_t lifetime)
{
- return CHILD_OPS (set_lifetime, type, h, lifetime);
+ return CALL_CHILD (set_lifetime, pkbuf, pos, lifetime);
}
int
-ipv4_update_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+ipv4_update_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
/*
* Checksum field is not accounted for in lower layers, so we can compute
* them in any order. Note that it is only a header checksum.
*/
- h->ipv4.csum = 0;
- h->ipv4.csum = csum (h, IPV4_HDRLEN, 0);
+ ipv4->csum = 0;
+ ipv4->csum = csum (pkbuf_get_header (pkbuf), IPV4_HDRLEN, 0);
- /* Retrieve payload length if not specified, as it is not available later */
- if (payload_length == 0)
+ /* Retrieve payload len if not specified, as it is not available later */
+ if (payload_len == 0)
{
- int rc = ipv4_get_payload_length (type, h, &payload_length);
- if (rc < 0)
- return rc;
+ payload_len = ipv4_get_payload_len (pkbuf, ipv4);
}
- /* Ignore the payload if payload_length = ~0 */
- if (payload_length == ~0)
+ /* Ignore the payload if payload_len = ~0 */
+ if (payload_len == ~0)
{
- payload_length = 0;
+ payload_len = 0;
}
/* Build pseudo-header */
ipv4_pseudo_header_t psh;
- psh.ip_src = h->ipv4.saddr;
- psh.ip_dst = h->ipv4.daddr;
+ psh.ip_src = ipv4->saddr;
+ psh.ip_dst = ipv4->daddr;
/* Size is u32 and not u16, we cannot copy and need to care about endianness
*/
- psh.size = htons (ntohs (h->ipv4.len) - (u16) IPV4_HDRLEN);
+ psh.size = htons (ntohs (ipv4->len) - (u16) IPV4_HDRLEN);
psh.zero = 0;
- psh.protocol = (u8) h->ipv4.protocol;
+ psh.protocol = (u8) ipv4->protocol;
/* Compute partial checksum based on pseudo-header */
if (partial_csum != 0)
@@ -271,217 +292,245 @@ ipv4_update_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
}
partial_csum = csum (&psh, IPV4_PSHDRLEN, partial_csum);
- return CHILD_OPS (update_checksums, type, h, partial_csum, payload_length);
+ return CALL_CHILD (update_checksums, pkbuf, pos, partial_csum, payload_len);
+}
+
+int
+ipv4_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first)
+{
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ /* We update the child first */
+ int rc = CALL_CHILD (update_checksums_incremental, pkbuf, pos, old_val,
+ new_val, size, false);
+ if (rc < 0)
+ return rc;
+
+ if (!skip_first)
+ {
+ for (uint8_t i = 0; i < size; i++)
+ {
+ uint16_t old_csum = ~ipv4->csum;
+ uint16_t not_old_val = ~(*old_val);
+ uint32_t sum = (uint32_t) old_csum + not_old_val + *new_val;
+
+ while (sum >> 16)
+ {
+ sum = (sum >> 16) + (sum & UINT16_T_MASK);
+ }
+
+ ipv4->csum = ~sum;
+ ++old_val;
+ ++new_val;
+ }
+ }
+
+ return HICN_LIB_ERROR_NONE;
}
int
-ipv4_verify_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+ipv4_verify_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
/*
* Checksum field is not accounted for in lower layers, so we can compute
* them in any order. Note that it is only a header checksum.
*/
- if (csum (h, IPV4_HDRLEN, 0) != 0)
+ if (csum (pkbuf_get_header (pkbuf), IPV4_HDRLEN, 0) != 0)
return HICN_LIB_ERROR_CORRUPTED_PACKET;
- /* Retrieve payload length if not specified, as it is not available later */
- if (payload_length == 0)
+ /* Retrieve payload len if not specified, as it is not available later */
+ if (payload_len == 0)
{
- int rc = ipv4_get_payload_length (type, h, &payload_length);
- if (rc < 0)
- return rc;
+ payload_len = ipv4_get_payload_len (pkbuf, ipv4);
}
/* Build pseudo-header */
ipv4_pseudo_header_t psh;
- psh.ip_src = h->ipv4.saddr;
- psh.ip_dst = h->ipv4.daddr;
+ psh.ip_src = ipv4->saddr;
+ psh.ip_dst = ipv4->daddr;
/* Size is u32 and not u16, we cannot copy and need to care about endianness
*/
- psh.size = htons (ntohs (h->ipv4.len) - (u16) IPV4_HDRLEN);
+ psh.size = htons (ntohs (ipv4->len) - (u16) IPV4_HDRLEN);
psh.zero = 0;
- psh.protocol = (u8) h->ipv4.protocol;
+ psh.protocol = (u8) ipv4->protocol;
/* Compute partial checksum based on pseudo-header */
partial_csum = csum (&psh, IPV4_PSHDRLEN, 0);
- return CHILD_OPS (update_checksums, type, h, partial_csum, payload_length);
+ return CALL_CHILD (verify_checksums, pkbuf, pos, partial_csum, payload_len);
}
int
-ipv4_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new,
- ip46_address_t *addr_old)
+ipv4_rewrite_interest (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
{
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
// ASSERT(addr_old == NULL);
- addr_old->ip4 = h->ipv4.saddr;
+ addr_old->v4 = ipv4->saddr;
addr_old->pad[0] = 0;
addr_old->pad[1] = 0;
addr_old->pad[2] = 0;
- h->ipv4.saddr = addr_new->ip4;
- h->ipv4.csum = 0;
- h->ipv4.csum = csum (&h->ipv4, IPV4_HDRLEN, 0);
+ ipv4->saddr = addr_new->v4;
+ ipv4->csum = 0;
+ ipv4->csum = csum (&ipv4, IPV4_HDRLEN, 0);
- return CHILD_OPS (rewrite_interest, type, h, addr_new, addr_old);
+ return CALL_CHILD (rewrite_interest, pkbuf, pos, addr_new, addr_old);
}
int
-ipv4_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new, ip46_address_t *addr_old,
- const hicn_faceid_t face_id, u8 reset_pl)
+ipv4_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
{
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
// ASSERT(addr_old == NULL);
- addr_old->ip4 = h->ipv4.daddr;
+ addr_old->v4 = ipv4->daddr;
addr_old->pad[0] = 0;
addr_old->pad[1] = 0;
addr_old->pad[2] = 0;
- h->ipv4.daddr = addr_new->ip4;
- h->ipv4.csum = 0;
- h->ipv4.csum = csum (&h->ipv4, IPV4_HDRLEN, 0);
+ ipv4->daddr = addr_new->v4;
+ ipv4->csum = 0;
+ ipv4->csum = csum (&ipv4, IPV4_HDRLEN, 0);
- return CHILD_OPS (rewrite_data, type, h, addr_new, addr_old, face_id,
- reset_pl);
+ return CALL_CHILD (rewrite_data, pkbuf, pos, addr_new, addr_old, face_id,
+ reset_pl);
}
int
-ipv4_get_current_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ipv4_set_payload_len (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t payload_len)
{
- *header_length = IPV4_HDRLEN;
+ _ipv4_header_t *ipv4 = pkbuf_get_ipv4 (pkbuf);
+
+ size_t child_header_len = hicn_ops_vft[pos + 1]->header_len;
+
+ ipv4->len = htons ((u16) (payload_len + IPV4_HDRLEN + child_header_len));
return HICN_LIB_ERROR_NONE;
}
int
-ipv4_get_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ipv4_get_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t *payload_type)
{
- *header_length = h->ipv4.len;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (get_payload_type, pkbuf, pos, payload_type);
}
int
-ipv4_get_current_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ipv4_set_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t payload_type)
{
- *header_length = IPV4_HDRLEN;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (set_payload_type, pkbuf, pos, payload_type);
}
int
-ipv4_get_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ipv4_get_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *signature_size)
{
- size_t child_header_length = 0;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
- *header_length = IPV4_HDRLEN + child_header_length;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (get_signature_size, pkbuf, pos, signature_size);
}
int
-ipv4_get_payload_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *payload_length)
+ipv4_set_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_size)
{
- size_t child_header_length;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
- *payload_length = htons (h->ipv4.len) - IPV4_HDRLEN - child_header_length;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (set_signature_size, pkbuf, pos, signature_size);
}
int
-ipv4_set_payload_length (hicn_type_t type, hicn_protocol_t *h,
- size_t payload_length)
+ipv4_set_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t padding)
{
- size_t child_header_length;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
- h->ipv4.len =
- htons ((u_short) (payload_length + IPV4_HDRLEN + child_header_length));
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (set_signature_padding, pkbuf, pos, padding);
}
int
-ipv4_get_signature_size (hicn_type_t type, const hicn_protocol_t *h,
- size_t *signature_size)
+ipv4_get_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *padding)
{
- return CHILD_OPS (get_signature_size, type, h, signature_size);
+ return CALL_CHILD (get_signature_padding, pkbuf, pos, padding);
}
int
-ipv4_set_signature_size (hicn_type_t type, hicn_protocol_t *h,
- size_t signature_size)
+ipv4_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t signature_timestamp)
{
- return CHILD_OPS (set_signature_size, type, h, signature_size);
+ return CALL_CHILD (set_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-ipv4_set_signature_gap (hicn_type_t type, hicn_protocol_t *h, uint8_t gap)
+ipv4_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t *signature_timestamp)
{
- return CHILD_OPS (set_signature_gap, type, h, gap);
+ return CALL_CHILD (get_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-ipv4_get_signature_gap (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *gap)
+ipv4_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t validation_algorithm)
{
- return CHILD_OPS (get_signature_gap, type, h, gap);
+ return CALL_CHILD (set_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-ipv4_set_signature_timestamp (hicn_type_t type, hicn_protocol_t *h,
- uint64_t signature_timestamp)
+ipv4_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *validation_algorithm)
{
- return CHILD_OPS (set_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (get_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-ipv4_get_signature_timestamp (hicn_type_t type, const hicn_protocol_t *h,
- uint64_t *signature_timestamp)
+ipv4_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *key_id, size_t key_len)
{
- return CHILD_OPS (get_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (set_key_id, pkbuf, pos, key_id, key_len);
}
int
-ipv4_set_validation_algorithm (hicn_type_t type, hicn_protocol_t *h,
- uint8_t validation_algorithm)
+ipv4_get_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **key_id, uint8_t *key_id_size)
{
- return CHILD_OPS (set_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (get_key_id, pkbuf, pos, key_id, key_id_size);
}
int
-ipv4_get_validation_algorithm (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *validation_algorithm)
+ipv4_get_signature (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **signature)
{
- return CHILD_OPS (get_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (get_signature, pkbuf, pos, signature);
}
int
-ipv4_set_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t *key_id)
+ipv4_has_signature (const hicn_packet_buffer_t *pkbuf, size_t pos, bool *flag)
{
- return CHILD_OPS (set_key_id, type, h, key_id);
+ return CALL_CHILD (has_signature, pkbuf, pos, flag);
}
int
-ipv4_get_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t **key_id,
- uint8_t *key_id_size)
+ipv4_is_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos, int *is_last)
{
- return CHILD_OPS (get_key_id, type, h, key_id, key_id_size);
+ return CALL_CHILD (is_last_data, pkbuf, pos, is_last);
}
int
-ipv4_get_signature (hicn_type_t type, hicn_protocol_t *h, uint8_t **signature)
+ipv4_set_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos)
{
- return CHILD_OPS (get_signature, type, h, signature);
+ return CALL_CHILD (set_last_data, pkbuf, pos);
}
-DECLARE_HICN_OPS (ipv4);
+DECLARE_HICN_OPS (ipv4, IPV4_HDRLEN);
/*
* fd.io coding-style-patch-verification: ON
diff --git a/lib/src/protocol/ipv4.h b/lib/src/protocol/ipv4.h
new file mode 100644
index 000000000..5d729b955
--- /dev/null
+++ b/lib/src/protocol/ipv4.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+#ifndef HICN_PROTOCOL_IPV4
+#define HICN_PROTOCOL_IPV4
+
+#include <hicn/util/ip_address.h>
+
+#include <hicn/base.h>
+#include <hicn/common.h>
+
+/* Headers were adapted from linux' definitions in netinet/ip.h */
+
+/*
+ * The length of the IPV4 header struct must be 20 bytes.
+ */
+#define EXPECTED_IPV4_HDRLEN 20
+
+typedef struct
+{
+ union
+ {
+ struct
+ {
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+ u8 ihl : 4;
+ u8 version : 4;
+#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+ u8 version : 4;
+ u8 ihl : 4;
+#else
+#error "Unsupported endianness"
+#endif
+ };
+
+ u8 version_ihl;
+ };
+ u8 tos;
+
+ /*
+ * This is the total length of the IP packet, including the IP header.
+ * NOTE: vriable len header size is currently not supported by the lib.
+ */
+ u16 len;
+
+ u16 id;
+ u16 frag_off;
+ u8 ttl;
+ u8 protocol;
+ u16 csum;
+ ipv4_address_t saddr;
+ ipv4_address_t daddr;
+} _ipv4_header_t;
+
+#define ipv4_header_bytes(ipv4_header) \
+ (sizeof (u32) * (ipv4_header->version_ihl & 0xf))
+
+#define IPV4_HDRLEN sizeof (_ipv4_header_t)
+static_assert (EXPECTED_IPV4_HDRLEN == IPV4_HDRLEN,
+ "Size of IPV4 struct does not match its expected size.");
+
+/*
+ * The length of the IPV4 pseudo header struct must be 12 bytes.
+ */
+#define EXPECTED_IPV4_PSHDRLEN 12
+
+typedef struct
+{
+ ipv4_address_t ip_src;
+ ipv4_address_t ip_dst;
+ u8 zero;
+ u8 protocol;
+ u16 size;
+} ipv4_pseudo_header_t;
+
+#define IPV4_PSHDRLEN sizeof (ipv4_pseudo_header_t)
+static_assert (EXPECTED_IPV4_PSHDRLEN == IPV4_PSHDRLEN,
+ "Size of IPV4_PSHDR struct does not match its expected size.");
+
+/* Default field values */
+#define IPV4_DEFAULT_VERSION 4
+#define IPV4_DEFAULT_IHL 5
+#define IPV4_DEFAULT_TOS 0
+#define IPV4_DEFAULT_PAYLOAD_LENGTH 0
+#define IPV4_DEFAULT_ID 300
+#define IPV4_DEFAULT_FRAG_OFF 0x000
+#define IPV4_DEFAULT_TTL 64
+#define IPV4_DEFAULT_PROTOCOL IPPROTO_TCP
+#define IPV4_DEFAULT_SRC_IP 0, 0, 0, 0
+#define IPV4_DEFAULT_DST_IP 0, 0, 0, 0
+
+#endif /* HICN_PROTOCOL_IPV4 */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/ipv6.c b/lib/src/protocol/ipv6.c
index 7ac55b2be..c5fa643aa 100644
--- a/lib/src/protocol/ipv6.c
+++ b/lib/src/protocol/ipv6.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,224 +17,252 @@
#include <string.h>
#include <hicn/common.h>
#include <hicn/error.h>
-#include <hicn/ops.h>
+
+#include "ipv6.h"
+#include "../ops.h"
typedef unsigned short u_short;
-int ipv6_get_payload_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *payload_length);
+
+#ifdef OPAQUE_IP
+#define GET_IPV6_HEADER(pkbuf) \
+ (_ipv6_header_t *) ((pkbuf)->header + (pkbuf)->ipv6)
+#else
+#define GET_IPV6_HEADER(pkbuf) (_ipv6_header_t *) ((pkbuf)->header)
+#endif /* OPAQUE_IP */
int
-ipv6_init_packet_header (hicn_type_t type, hicn_protocol_t *h)
+ipv6_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- size_t total_header_length;
- int rc = CHILD_OPS (get_header_length, type, h, &total_header_length);
- if (rc < 0)
- return rc;
+ assert (pkbuf->len == 0);
+ if (IPV6_HDRLEN > pkbuf->buffer_size - pkbuf->len)
+ return -1;
+ pkbuf->len += IPV6_HDRLEN;
+
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
- /* *INDENT-OFF* */
- h->ipv6 = (_ipv6_header_t){
- .saddr = { { 0 } },
- .daddr = { { 0 } },
+ hicn_packet_format_t format = hicn_packet_get_format (pkbuf);
+
+ size_t header_len;
+ hicn_packet_get_header_length_from_format (pkbuf->format, &header_len);
+
+ /* clang-format off */
+ *ipv6 = (_ipv6_header_t){
+ .saddr = IP6_ADDRESS_EMPTY,
+ .daddr = IP6_ADDRESS_EMPTY,
.version_class_flow = htonl ((IPV6_DEFAULT_VERSION << 28) |
(IPV6_DEFAULT_TRAFFIC_CLASS << 20) |
(IPV6_DEFAULT_FLOW_LABEL & 0xfffff)),
- .len = htons ((u16) total_header_length),
- .nxt = type.l2,
+ .len = htons(header_len - IPV6_HDRLEN),
+ .nxt = HICN_PACKET_FORMAT_GET(format, pos+1),
.hlim = HICN_DEFAULT_TTL,
};
- /* *INDENT-ON* */
- return CHILD_OPS (init_packet_header, type, h);
+ /* clang-format on */
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
}
int
-ipv6_get_interest_locator (hicn_type_t type, const hicn_protocol_t *h,
- ip46_address_t *ip_address)
+ipv6_get_interest_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_ip_address_t *ip_address)
{
- ip_address->ip6 = h->ipv6.saddr;
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ ip_address->v6 = ipv6->saddr;
return HICN_LIB_ERROR_NONE;
}
int
-ipv6_set_interest_locator (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *ip_address)
+ipv6_set_interest_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address)
{
- h->ipv6.saddr = ip_address->ip6;
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ ipv6->saddr = ip_address->v6;
return HICN_LIB_ERROR_NONE;
}
int
-ipv6_get_interest_name (hicn_type_t type, const hicn_protocol_t *h,
+ipv6_get_interest_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_t *name)
{
- name->ip6.prefix_as_ip6 = h->ipv6.daddr;
-#ifndef HICN_VPP_PLUGIN
- name->type = HNT_CONTIGUOUS_V6;
- name->len = HICN_V6_NAME_LEN;
-#endif /* HICN_VPP_PLUGIN */
- return CHILD_OPS (get_interest_name_suffix, type, h, &(name->ip6.suffix));
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ name->prefix.v6 = ipv6->daddr;
+ return CALL_CHILD (get_interest_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv6_set_interest_name (hicn_type_t type, hicn_protocol_t *h,
+ipv6_set_interest_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_t *name)
{
- h->ipv6.daddr = name->ip6.prefix_as_ip6;
- return CHILD_OPS (set_interest_name_suffix, type, h, &(name->ip6.suffix));
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ ipv6->daddr = name->prefix.v6;
+ return CALL_CHILD (set_interest_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv6_get_interest_name_suffix (hicn_type_t type, const hicn_protocol_t *h,
+ipv6_get_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (get_interest_name_suffix, type, h, suffix);
+ return CALL_CHILD (get_interest_name_suffix, pkbuf, pos, suffix);
}
int
-ipv6_set_interest_name_suffix (hicn_type_t type, hicn_protocol_t *h,
+ipv6_set_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (set_interest_name_suffix, type, h, suffix);
+ return CALL_CHILD (set_interest_name_suffix, pkbuf, pos, suffix);
}
int
-ipv6_mark_packet_as_interest (hicn_type_t type, hicn_protocol_t *h)
+ipv6_get_type (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_packet_type_t *type)
{
- return CHILD_OPS (mark_packet_as_interest, type, h);
+ return CALL_CHILD (get_type, pkbuf, pos, type);
}
int
-ipv6_mark_packet_as_data (hicn_type_t type, hicn_protocol_t *h)
+ipv6_set_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_packet_type_t type)
{
- return CHILD_OPS (mark_packet_as_data, type, h);
+ return CALL_CHILD (set_type, pkbuf, pos, type);
}
int
-ipv6_reset_interest_for_hash (hicn_type_t type, hicn_protocol_t *h)
+ipv6_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
/* Sets everything to 0 up to IP destination address */
- memset (&(h->ipv6), 0, 24);
+ memset (ipv6, 0, 24);
- return CHILD_OPS (reset_interest_for_hash, type, h);
+ return CALL_CHILD (reset_interest_for_hash, pkbuf, pos);
}
int
-ipv6_get_data_locator (hicn_type_t type, const hicn_protocol_t *h,
- ip46_address_t *ip_address)
+ipv6_get_data_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_ip_address_t *ip_address)
{
- ip_address->ip6 = h->ipv6.daddr;
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ ip_address->v6 = ipv6->daddr;
return HICN_LIB_ERROR_NONE;
}
int
-ipv6_set_data_locator (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *ip_address)
+ipv6_set_data_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address)
{
- h->ipv6.daddr = ip_address->ip6;
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ ipv6->daddr = ip_address->v6;
return HICN_LIB_ERROR_NONE;
}
int
-ipv6_get_data_name (hicn_type_t type, const hicn_protocol_t *h,
+ipv6_get_data_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_t *name)
{
- name->ip6.prefix_as_ip6 = h->ipv6.saddr;
-#ifndef HICN_VPP_PLUGIN
- name->type = HNT_CONTIGUOUS_V6;
- name->len = HICN_V6_NAME_LEN;
-#endif /* HICN_VPP_PLUGIN */
- return CHILD_OPS (get_data_name_suffix, type, h, &(name->ip6.suffix));
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ name->prefix.v6 = ipv6->saddr;
+ return CALL_CHILD (get_data_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv6_set_data_name (hicn_type_t type, hicn_protocol_t *h,
+ipv6_set_data_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_t *name)
{
- h->ipv6.saddr = name->ip6.prefix_as_ip6;
- return CHILD_OPS (set_data_name_suffix, type, h, &(name->ip6.suffix));
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ ipv6->saddr = name->prefix.v6;
+ return CALL_CHILD (set_data_name_suffix, pkbuf, pos, &(name->suffix));
}
int
-ipv6_get_data_name_suffix (hicn_type_t type, const hicn_protocol_t *h,
+ipv6_get_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (get_data_name_suffix, type, h, suffix);
+ return CALL_CHILD (get_data_name_suffix, pkbuf, pos, suffix);
}
int
-ipv6_set_data_name_suffix (hicn_type_t type, hicn_protocol_t *h,
+ipv6_set_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_suffix_t *suffix)
{
- return CHILD_OPS (set_data_name_suffix, type, h, suffix);
+ return CALL_CHILD (set_data_name_suffix, pkbuf, pos, suffix);
}
int
-ipv6_get_data_pathlabel (hicn_type_t type, const hicn_protocol_t *h,
- u32 *pathlabel)
+ipv6_get_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t *path_label)
{
- return CHILD_OPS (get_data_pathlabel, type, h, pathlabel);
+ return CALL_CHILD (get_data_path_label, pkbuf, pos, path_label);
}
int
-ipv6_set_data_pathlabel (hicn_type_t type, hicn_protocol_t *h,
- const u32 pathlabel)
+ipv6_set_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t path_label)
{
- return CHILD_OPS (set_data_pathlabel, type, h, pathlabel);
+ return CALL_CHILD (set_data_path_label, pkbuf, pos, path_label);
}
int
-ipv6_update_data_pathlabel (hicn_type_t type, hicn_protocol_t *h,
- const hicn_faceid_t face_id)
+ipv6_update_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_faceid_t face_id)
{
- return CHILD_OPS (update_data_pathlabel, type, h, face_id);
+ return CALL_CHILD (update_data_path_label, pkbuf, pos, face_id);
}
int
-ipv6_reset_data_for_hash (hicn_type_t type, hicn_protocol_t *h)
+ipv6_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
/* IP: Set everithing to 0 up to destination address */
- memset (&h->ipv6, 0, 8);
+ memset (ipv6, 0, 8);
/* Clears destination address */
- memset (&(h->ipv6.daddr), 0, 16);
+ memset (&(ipv6->daddr), 0, 16);
- return CHILD_OPS (reset_data_for_hash, type, h);
+ return CALL_CHILD (reset_data_for_hash, pkbuf, pos);
}
int
-ipv6_get_lifetime (hicn_type_t type, const hicn_protocol_t *h,
+ipv6_get_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_lifetime_t *lifetime)
{
- return CHILD_OPS (get_lifetime, type, h, lifetime);
+ return CALL_CHILD (get_lifetime, pkbuf, pos, lifetime);
}
int
-ipv6_set_lifetime (hicn_type_t type, hicn_protocol_t *h,
+ipv6_set_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_lifetime_t lifetime)
{
- return CHILD_OPS (set_lifetime, type, h, lifetime);
+ return CALL_CHILD (set_lifetime, pkbuf, pos, lifetime);
}
int
-ipv6_update_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+ipv6_update_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
- /* Retrieve payload length if not specified */
- if (payload_length == ~0)
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ /* Retrieve payload len if not specified */
+ if (payload_len == ~0)
{
- int rc = ipv6_get_payload_length (type, h, &payload_length);
- if (rc < 0)
- return rc;
+ payload_len = hicn_packet_get_len (pkbuf) - pkbuf->payload;
}
/* Build pseudo-header */
ipv6_pseudo_header_t psh;
- psh.ip_src = h->ipv6.saddr;
- psh.ip_dst = h->ipv6.daddr;
+ psh.ip_src = ipv6->saddr;
+ psh.ip_dst = ipv6->daddr;
/* Size is u32 and not u16, we cannot copy and need to care about endianness
*/
- psh.size = htonl (ntohs (h->ipv6.len));
+ psh.size = htonl (ntohs (ipv6->len));
psh.zeros = 0;
psh.zero = 0;
- psh.protocol = h->ipv6.nxt;
+ psh.protocol = ipv6->nxt;
/* Compute partial checksum based on pseudo-header */
if (partial_csum != 0)
@@ -243,31 +271,41 @@ ipv6_update_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
}
partial_csum = csum (&psh, IPV6_PSHDRLEN, partial_csum);
- return CHILD_OPS (update_checksums, type, h, partial_csum, payload_length);
+ return CALL_CHILD (update_checksums, pkbuf, pos, partial_csum, payload_len);
}
int
-ipv6_verify_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+ipv6_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first)
{
- /* Retrieve payload length if not specified */
- if (payload_length == ~0)
+ /* We update the child only */
+ return CALL_CHILD (update_checksums_incremental, pkbuf, pos, old_val,
+ new_val, size, false);
+}
+
+int
+ipv6_verify_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
+{
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ /* Retrieve payload len if not specified */
+ if (payload_len == ~0)
{
- int rc = ipv6_get_payload_length (type, h, &payload_length);
- if (rc < 0)
- return rc;
+ payload_len = hicn_packet_get_len (pkbuf) - pkbuf->payload;
}
/* Build pseudo-header */
ipv6_pseudo_header_t pseudo;
- pseudo.ip_src = h->ipv6.saddr;
- pseudo.ip_dst = h->ipv6.daddr;
+ pseudo.ip_src = ipv6->saddr;
+ pseudo.ip_dst = ipv6->daddr;
/* Size is u32 and not u16, we cannot copy and need to care about endianness
*/
- pseudo.size = htonl (ntohs (h->ipv6.len));
+ pseudo.size = htonl (ntohs (ipv6->len));
pseudo.zeros = 0;
pseudo.zero = 0;
- pseudo.protocol = h->ipv6.nxt;
+ pseudo.protocol = ipv6->nxt;
/* Compute partial checksum based on pseudo-header */
if (partial_csum != 0)
@@ -276,161 +314,161 @@ ipv6_verify_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
}
partial_csum = csum (&pseudo, IPV6_PSHDRLEN, partial_csum);
- return CHILD_OPS (verify_checksums, type, h, partial_csum, payload_length);
+ return CALL_CHILD (verify_checksums, pkbuf, pos, partial_csum, payload_len);
}
int
-ipv6_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new,
- ip46_address_t *addr_old)
+ipv6_rewrite_interest (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
{
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
// ASSERT(addr_old == NULL);
- addr_old->ip6 = h->ipv6.saddr;
- h->ipv6.saddr = addr_new->ip6;
+ addr_old->v6 = ipv6->saddr;
+ ipv6->saddr = addr_new->v6;
- return CHILD_OPS (rewrite_interest, type, h, addr_new, addr_old);
+ return CALL_CHILD (rewrite_interest, pkbuf, pos, addr_new, addr_old);
}
int
-ipv6_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new, ip46_address_t *addr_old,
- const hicn_faceid_t face_id, u8 reset_pl)
+ipv6_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
{
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
// ASSERT(addr_old == NULL);
- addr_old->ip6 = h->ipv6.daddr;
- h->ipv6.daddr = addr_new->ip6;
+ addr_old->v6 = ipv6->daddr;
+ ipv6->daddr = addr_new->v6;
- return CHILD_OPS (rewrite_data, type, h, addr_new, addr_old, face_id,
- reset_pl);
+ return CALL_CHILD (rewrite_data, pkbuf, pos, addr_new, addr_old, face_id,
+ reset_pl);
}
int
-ipv6_get_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ipv6_set_payload_len (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t payload_len)
{
- *header_length = IPV6_HDRLEN + ntohs (h->ipv6.len);
+ _ipv6_header_t *ipv6 = pkbuf_get_ipv6 (pkbuf);
+
+ ipv6->len = htons ((u_short) (payload_len + pkbuf->payload - IPV6_HDRLEN));
return HICN_LIB_ERROR_NONE;
}
int
-ipv6_get_current_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ipv6_get_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t *payload_type)
{
- *header_length = IPV6_HDRLEN;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (get_payload_type, pkbuf, pos, payload_type);
}
int
-ipv6_get_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+ipv6_set_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t payload_type)
{
- size_t child_header_length = 0;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
- *header_length = IPV6_HDRLEN + child_header_length;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (set_payload_type, pkbuf, pos, payload_type);
}
int
-ipv6_get_payload_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *payload_length)
+ipv6_get_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *signature_size)
{
- size_t child_header_length;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
- *payload_length = ntohs (h->ipv6.len) - child_header_length;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (get_signature_size, pkbuf, pos, signature_size);
}
int
-ipv6_set_payload_length (hicn_type_t type, hicn_protocol_t *h,
- size_t payload_length)
+ipv6_set_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_size)
{
- size_t child_header_length;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
- h->ipv6.len = htons ((u_short) (payload_length + child_header_length));
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (set_signature_size, pkbuf, pos, signature_size);
}
int
-ipv6_get_signature_size (hicn_type_t type, const hicn_protocol_t *h,
- size_t *signature_size)
+ipv6_set_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t padding)
{
- return CHILD_OPS (get_signature_size, type, h, signature_size);
+ return CALL_CHILD (set_signature_padding, pkbuf, pos, padding);
}
int
-ipv6_set_signature_size (hicn_type_t type, hicn_protocol_t *h,
- size_t signature_size)
+ipv6_get_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *padding)
+{
+ return CALL_CHILD (get_signature_padding, pkbuf, pos, padding);
+}
+
+int
+ipv6_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t signature_timestamp)
{
- return CHILD_OPS (set_signature_size, type, h, signature_size);
+ return CALL_CHILD (set_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-ipv6_set_signature_gap (hicn_type_t type, hicn_protocol_t *h, uint8_t gap)
+ipv6_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t *signature_timestamp)
{
- return CHILD_OPS (set_signature_gap, type, h, gap);
+ return CALL_CHILD (get_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-ipv6_get_signature_gap (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *gap)
+ipv6_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t validation_algorithm)
{
- return CHILD_OPS (get_signature_gap, type, h, gap);
+ return CALL_CHILD (set_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-ipv6_set_signature_timestamp (hicn_type_t type, hicn_protocol_t *h,
- uint64_t signature_timestamp)
+ipv6_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *validation_algorithm)
{
- return CHILD_OPS (set_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (get_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-ipv6_get_signature_timestamp (hicn_type_t type, const hicn_protocol_t *h,
- uint64_t *signature_timestamp)
+ipv6_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *key_id, size_t key_len)
{
- return CHILD_OPS (get_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (set_key_id, pkbuf, pos, key_id, key_len);
}
int
-ipv6_set_validation_algorithm (hicn_type_t type, hicn_protocol_t *h,
- uint8_t validation_algorithm)
+ipv6_get_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **key_id, uint8_t *key_id_size)
{
- return CHILD_OPS (set_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (get_key_id, pkbuf, pos, key_id, key_id_size);
}
int
-ipv6_get_validation_algorithm (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *validation_algorithm)
+ipv6_get_signature (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **signature)
{
- return CHILD_OPS (get_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (get_signature, pkbuf, pos, signature);
}
int
-ipv6_set_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t *key_id)
+ipv6_has_signature (const hicn_packet_buffer_t *pkbuf, size_t pos, bool *flag)
{
- return CHILD_OPS (set_key_id, type, h, key_id);
+ return CALL_CHILD (has_signature, pkbuf, pos, flag);
}
int
-ipv6_get_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t **key_id,
- uint8_t *key_id_size)
+ipv6_is_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos, int *is_last)
{
- return CHILD_OPS (get_key_id, type, h, key_id, key_id_size);
+ return CALL_CHILD (is_last_data, pkbuf, pos, is_last);
}
int
-ipv6_get_signature (hicn_type_t type, hicn_protocol_t *h, uint8_t **signature)
+ipv6_set_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos)
{
- return CHILD_OPS (get_signature, type, h, signature);
+ return CALL_CHILD (set_last_data, pkbuf, pos);
}
-DECLARE_HICN_OPS (ipv6);
+DECLARE_HICN_OPS (ipv6, IPV6_HDRLEN);
/*
* fd.io coding-style-patch-verification: ON
diff --git a/lib/src/protocol/ipv6.h b/lib/src/protocol/ipv6.h
new file mode 100644
index 000000000..9a51096a0
--- /dev/null
+++ b/lib/src/protocol/ipv6.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+#ifndef HICN_PROTOCOL_IPV6_H
+#define HICN_PROTOCOL_IPV6_H
+
+#include <hicn/util/ip_address.h>
+
+#include <hicn/common.h>
+
+/*
+ * The length of the IPV6 header struct must be 40 bytes.
+ */
+#define EXPECTED_IPV6_HDRLEN 40
+
+typedef struct
+{
+#if 0 // TEMPORARY FIX
+ union
+ {
+ struct
+ {
+#endif
+ u32 version_class_flow; /* version, traffic class and 20 bits of flow-ID */
+ u16 len; /* payload length */
+ u8 nxt; /* next header */
+ u8 hlim; /* hop limit */
+#if 0
+ };
+ u8 vfc; /* 4 bits version, top 4 bits class */
+ };
+#endif
+ ipv6_address_t saddr; /* source address */
+ ipv6_address_t daddr; /* destination address */
+} _ipv6_header_t;
+
+#define IPV6_HDRLEN sizeof (_ipv6_header_t)
+static_assert (EXPECTED_IPV6_HDRLEN == IPV6_HDRLEN,
+ "Size of IPV6 struct does not match its expected size.");
+
+/*
+ * The length of the IPV6 pseudo header struct must be 40 bytes.
+ */
+#define EXPECTED_IPV6_PSHDRLEN 40
+
+typedef struct
+{
+ ipv6_address_t ip_src;
+ ipv6_address_t ip_dst;
+ u32 size;
+ u16 zeros;
+ u8 zero;
+ u8 protocol;
+} ipv6_pseudo_header_t;
+
+#define IPV6_PSHDRLEN sizeof (ipv6_pseudo_header_t)
+static_assert (EXPECTED_IPV6_PSHDRLEN == IPV6_PSHDRLEN,
+ "Size of IPV6_PSHDR struct does not match its expected size.");
+
+/* Default field values */
+#define IPV6_DEFAULT_VERSION 6
+#define IPV6_DEFAULT_TRAFFIC_CLASS 0
+#define IPV6_DEFAULT_FLOW_LABEL 0
+#define IPV6_DEFAULT_PAYLOAD_LENGTH 0
+
+#endif
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/new.c b/lib/src/protocol/new.c
new file mode 100644
index 000000000..e86ce4753
--- /dev/null
+++ b/lib/src/protocol/new.c
@@ -0,0 +1,563 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <hicn/common.h>
+#include <hicn/error.h>
+
+#include "udp.h"
+#include "../ops.h"
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-function"
+
+int
+new_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ pkbuf->newhdr = pkbuf->len;
+ if (NEW_HDRLEN > pkbuf->buffer_size - pkbuf->len)
+ return -1;
+ pkbuf->len += NEW_HDRLEN;
+
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_format_t format = hicn_packet_get_format (pkbuf);
+
+ memset (new, 0, sizeof (_new_header_t));
+ _set_new_header_version (new);
+ uint8_t ah_flag = (HICN_PACKET_FORMAT_GET (format, pos + 1) == IPPROTO_AH) ?
+ HICN_NEW_FLAG_SIG :
+ 0;
+ new->flags |= ah_flag;
+
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
+}
+
+int
+new_get_type (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_packet_type_t *type)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ /* Interest packets have the INT bit set */
+ if (new->flags & HICN_NEW_FLAG_INT)
+ *type = HICN_PACKET_TYPE_INTEREST;
+ else
+ *type = HICN_PACKET_TYPE_DATA;
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_packet_type_t type)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ switch (type)
+ {
+ case HICN_PACKET_TYPE_INTEREST:
+ new->flags |= HICN_NEW_FLAG_INT;
+ break;
+ case HICN_PACKET_TYPE_DATA:
+ new->flags &= ~HICN_NEW_FLAG_INT;
+ break;
+ default:
+ return -1;
+ }
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_get_interest_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_ip_address_t *ip_address)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+ _unused (new);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_interest_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+ _unused (new);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_get_interest_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_name_t *name)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ name->prefix = new->prefix;
+ name->suffix = ntohl (new->suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+// XXX never called and thus packet is never initialized as interest
+// DECLARE_set_interest_name (udp, UNEXPECTED);
+int
+new_set_interest_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_t *name)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ int rc = new_set_type (pkbuf, pos, HICN_PACKET_TYPE_INTEREST);
+ if (rc)
+ return rc;
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ new->prefix = name->prefix;
+ new->suffix = htonl (name->suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_get_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_name_suffix_t *suffix)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ *suffix = ntohl (new->suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_suffix_t *suffix)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ new->suffix = htonl (*suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+ _unused (new);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
+}
+
+int
+new_get_data_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_ip_address_t *ip_address)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+ _unused (new);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_data_locator (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *ip_address)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+ _unused (new);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_get_data_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_name_t *name)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ name->prefix = new->prefix;
+ name->suffix = ntohl (new->suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_data_name (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_t *name)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ int rc = new_set_type (pkbuf, pos, HICN_PACKET_TYPE_DATA);
+ if (rc)
+ return rc;
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ new->prefix = name->prefix;
+ new->suffix = htonl (name->suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_get_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_name_suffix_t *suffix)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ *suffix = ntohl (new->suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_suffix_t *suffix)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ new->suffix = htonl (*suffix);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_get_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t *path_label)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ *path_label = ntohl (new->path_label);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t path_label)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ new->path_label = htonl (path_label);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_update_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_faceid_t face_id)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_path_label_t new_pl;
+ update_path_label (new->path_label, face_id, &new_pl);
+ new->path_label = new_pl;
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ return CALL_CHILD (reset_data_for_hash, pkbuf, pos);
+}
+
+int
+new_get_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_lifetime_t *lifetime)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ *lifetime = ntohl (new->lifetime);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_lifetime_t lifetime)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ new->lifetime = htonl (lifetime);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_update_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
+{
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first)
+{
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_verify_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
+{
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_rewrite_interest (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+ _unused (new);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_INTEREST);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+ _unused (new);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_payload_len (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t payload_len)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ /*
+ * The value we have to store in the header is the sum of headers following
+ * the current header + the new payload size
+ */
+
+ size_t child_header_len =
+ (pkbuf->payload - pkbuf->newhdr) - sizeof (_new_header_t);
+ new->payload_len = htons ((u16) child_header_len + payload_len);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_get_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *signature_size)
+{
+ return CALL_CHILD (get_signature_size, pkbuf, pos, signature_size);
+}
+
+int
+new_set_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_size)
+{
+ return CALL_CHILD (set_signature_size, pkbuf, pos, signature_size);
+}
+
+int
+new_set_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t padding)
+{
+ return CALL_CHILD (set_signature_padding, pkbuf, pos, padding);
+}
+
+int
+new_get_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *padding)
+{
+ return CALL_CHILD (get_signature_padding, pkbuf, pos, padding);
+}
+
+int
+new_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t signature_timestamp)
+{
+ return CALL_CHILD (set_signature_timestamp, pkbuf, pos, signature_timestamp);
+}
+
+int
+new_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t *signature_timestamp)
+{
+ return CALL_CHILD (get_signature_timestamp, pkbuf, pos, signature_timestamp);
+}
+
+int
+new_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t validation_algorithm)
+{
+ return CALL_CHILD (set_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
+}
+
+int
+new_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *validation_algorithm)
+{
+ return CALL_CHILD (get_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
+}
+
+int
+new_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos, uint8_t *key_id,
+ size_t key_len)
+{
+ return CALL_CHILD (set_key_id, pkbuf, pos, key_id, key_len);
+}
+
+int
+new_get_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **key_id, uint8_t *key_id_size)
+{
+ return CALL_CHILD (get_key_id, pkbuf, pos, key_id, key_id_size);
+}
+
+int
+new_get_signature (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **signature)
+{
+ return CALL_CHILD (get_signature, pkbuf, pos, signature);
+}
+
+int
+new_has_signature (const hicn_packet_buffer_t *pkbuf, size_t pos, bool *flag)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ return new->flags &HICN_NEW_FLAG_SIG;
+}
+
+int
+new_get_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t *payload_type)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ *payload_type = ((new->flags &HICN_NEW_FLAG_MAN) == HICN_NEW_FLAG_MAN);
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t payload_type)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ if (payload_type != HPT_DATA && payload_type != HPT_MANIFEST)
+ return HICN_LIB_ERROR_INVALID_PARAMETER;
+
+ if (payload_type)
+ new->flags |= HICN_NEW_FLAG_MAN;
+ else
+ new->flags &= ~HICN_NEW_FLAG_MAN;
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_is_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos, int *is_last)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ *is_last = new->flags &HICN_NEW_FLAG_LST;
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+new_set_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ _new_header_t *new = pkbuf_get_new (pkbuf);
+
+ hicn_packet_type_t type;
+ _ASSERT (new_get_type (pkbuf, pos, &type) == 0);
+ _ASSERT (type == HICN_PACKET_TYPE_DATA);
+
+ new->flags |= HICN_NEW_FLAG_LST;
+ return HICN_LIB_ERROR_NONE;
+}
+
+DECLARE_HICN_OPS (new, NEW_HDRLEN);
+
+#pragma GCC diagnostic pop
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/new.h b/lib/src/protocol/new.h
new file mode 100644
index 000000000..7679910f4
--- /dev/null
+++ b/lib/src/protocol/new.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+/**
+ * @file protocol/ah.h
+ * @brief AH packet header
+ */
+#ifndef HICN_PROTOCOL_NEW_H
+#define HICN_PROTOCOL_NEW_H
+
+#include <hicn/common.h>
+#include <hicn/name.h>
+
+/*
+ * The length of the new header struct must be 28 bytes.
+ */
+#define EXPECTED_NEW_HDRLEN 32
+
+typedef struct
+{
+ u8 version_reserved;
+ u8 flags;
+
+ /* Size of the payload direcly after the new header */
+ u16 payload_len;
+
+ u32 lifetime;
+
+ /* Name prefix and suffix */
+ hicn_ip_address_t prefix;
+ u32 suffix;
+
+ /* We reserve 32 bits for the path label */
+ u32 path_label;
+} _new_header_t;
+
+#define NEW_HDRLEN sizeof (_new_header_t)
+static_assert (EXPECTED_NEW_HDRLEN == NEW_HDRLEN,
+ "Size of new_header Struct does not match its expected size.");
+
+/* TCP flags bit 0 first. */
+#define foreach_hicn_new_flag \
+ _ (SIG) /**< Signature header after. */ \
+ _ (MAN) /**< Payload type is manifest. */ \
+ _ (INT) /**< Packet is interest. */ \
+ _ (LST) /**< Last data. */
+
+enum
+{
+#define _(f) HICN_NEW_FLAG_BIT_##f,
+ foreach_hicn_new_flag
+#undef _
+ HICN_NEW_N_FLAG_BITS,
+};
+
+enum
+{
+#define _(f) HICN_NEW_FLAG_##f = 1 << HICN_NEW_FLAG_BIT_##f,
+ foreach_hicn_new_flag
+#undef _
+};
+
+static inline int
+_get_new_header_version (const _new_header_t *new_hdr)
+{
+ return ((new_hdr->version_reserved >> 4) & 0x0F);
+}
+
+static inline void
+_set_new_header_version (_new_header_t *new_hdr)
+{
+ new_hdr->version_reserved = (0x9 << 4) & 0xF0;
+}
+
+#endif /* HICN_PROTOCOL_NEW_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/tcp.c b/lib/src/protocol/tcp.c
index cfeac1907..e09495ecd 100644
--- a/lib/src/protocol/tcp.c
+++ b/lib/src/protocol/tcp.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,9 +14,12 @@
*/
#include <string.h>
-#include <hicn/protocol/tcp.h>
+
+#include <hicn/base.h>
#include <hicn/error.h>
-#include <hicn/ops.h>
+
+#include "tcp.h"
+#include "../ops.h"
#define TCP_DEFAULT_SRC_PORT 0x8000
#define TCP_DEFAULT_DST_PORT 0x0080
@@ -32,6 +35,8 @@
#define TCP_DEFAULT_SYN 1
#define TCP_DEFAULT_FIN 0
+#define UINT16_T_MASK 0x0000ffff // 1111 1111 1111 1111
+
DECLARE_get_interest_locator (tcp, UNEXPECTED);
DECLARE_set_interest_locator (tcp, UNEXPECTED);
DECLARE_get_interest_name (tcp, UNEXPECTED);
@@ -40,11 +45,27 @@ DECLARE_get_data_locator (tcp, UNEXPECTED);
DECLARE_set_data_locator (tcp, UNEXPECTED);
DECLARE_get_data_name (tcp, UNEXPECTED);
DECLARE_set_data_name (tcp, UNEXPECTED);
-DECLARE_get_length (tcp, UNEXPECTED);
-DECLARE_get_payload_length (tcp, UNEXPECTED);
-DECLARE_set_payload_length (tcp, UNEXPECTED);
+DECLARE_set_payload_len (tcp, UNEXPECTED);
-always_inline int
+int tcp_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first);
+
+static inline void
+reset_for_hash (hicn_packet_buffer_t *pkbuf)
+{
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ tcp->sport = 0;
+ tcp->dport = 0;
+ tcp->seq_ack = 0;
+ tcp->data_offset_and_reserved = 0;
+ tcp->flags = 0;
+ tcp->window = 0;
+ tcp->csum = 0;
+ tcp->urg_ptr = 0;
+}
+
+static inline int
check_tcp_checksum (u16 csum)
{
/* As per RFC1624
@@ -67,9 +88,17 @@ check_tcp_checksum (u16 csum)
}
int
-tcp_init_packet_header (hicn_type_t type, hicn_protocol_t *h)
+tcp_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- h->tcp = (_tcp_header_t){
+ pkbuf->tcp = pkbuf->len;
+ if (TCP_HDRLEN > pkbuf->buffer_size - pkbuf->len)
+ return -1;
+ pkbuf->len += TCP_HDRLEN;
+
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ hicn_packet_format_t format = hicn_packet_get_format (pkbuf);
+
+ *tcp = (_tcp_header_t){
.sport = htons (TCP_DEFAULT_SRC_PORT),
.dport = htons (TCP_DEFAULT_DST_PORT),
.seq = 0,
@@ -84,131 +113,170 @@ tcp_init_packet_header (hicn_type_t type, hicn_protocol_t *h)
.urg_ptr = 65000,
};
- uint8_t ah_flag = type.l2 == IPPROTO_AH ? AH_FLAG : 0;
+ uint8_t ah_flag =
+ (HICN_PACKET_FORMAT_GET (format, pos + 1) == IPPROTO_AH) ? AH_FLAG : 0;
- h->tcp.flags |= ah_flag;
+ tcp->flags |= ah_flag;
- return CHILD_OPS (init_packet_header, type, h);
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
}
int
-tcp_get_interest_name_suffix (hicn_type_t type, const hicn_protocol_t *h,
- hicn_name_suffix_t *suffix)
-{
- *suffix = ntohl (h->tcp.name_suffix);
+tcp_get_type (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_packet_type_t *type)
+{
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ /* Data packets have the ECE bit set */
+ if (tcp->flags & HICN_TCP_FLAG_ECE)
+ *type = HICN_PACKET_TYPE_DATA;
+ else
+ *type = HICN_PACKET_TYPE_INTEREST;
return HICN_LIB_ERROR_NONE;
}
int
-tcp_set_interest_name_suffix (hicn_type_t type, hicn_protocol_t *h,
- const hicn_name_suffix_t *suffix)
+tcp_set_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_packet_type_t type)
{
- h->tcp.name_suffix = htonl (*suffix);
-
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ switch (type)
+ {
+ case HICN_PACKET_TYPE_INTEREST:
+ tcp->flags &= ~HICN_TCP_FLAG_ECE;
+ break;
+ case HICN_PACKET_TYPE_DATA:
+ tcp->flags |= HICN_TCP_FLAG_ECE;
+ break;
+ default:
+ return HICN_LIB_ERROR_INVALID_PARAMETER;
+ }
return HICN_LIB_ERROR_NONE;
}
int
-tcp_mark_packet_as_interest (hicn_type_t type, hicn_protocol_t *h)
+tcp_get_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_name_suffix_t *suffix)
{
- h->tcp.flags &= ~HICN_TCP_FLAG_ECE;
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ *suffix = ntohl (tcp->name_suffix);
return HICN_LIB_ERROR_NONE;
}
int
-tcp_mark_packet_as_data (hicn_type_t type, hicn_protocol_t *h)
+tcp_set_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_suffix_t *suffix)
{
- h->tcp.flags |= HICN_TCP_FLAG_ECE;
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ int rc = tcp_set_type (pkbuf, pos, HICN_PACKET_TYPE_INTEREST);
+ if (rc)
+ return rc;
+
+ tcp->name_suffix = htonl (*suffix);
+
return HICN_LIB_ERROR_NONE;
}
int
-tcp_reset_interest_for_hash (hicn_type_t type, hicn_protocol_t *h)
+tcp_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- memset (&(h->tcp), 0, 4);
- memset (&(h->tcp.seq_ack), 0, 12);
-
- return CHILD_OPS (reset_interest_for_hash, type, h);
+ reset_for_hash (pkbuf);
+ return CALL_CHILD (reset_interest_for_hash, pkbuf, pos);
}
int
-tcp_get_data_name_suffix (hicn_type_t type, const hicn_protocol_t *h,
+tcp_get_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_name_suffix_t *suffix)
{
- *suffix = ntohl (h->tcp.name_suffix);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ *suffix = ntohl (tcp->name_suffix);
return HICN_LIB_ERROR_NONE;
}
int
-tcp_set_data_name_suffix (hicn_type_t type, hicn_protocol_t *h,
+tcp_set_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_name_suffix_t *suffix)
{
- h->tcp.name_suffix = htonl (*suffix);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ int rc = tcp_set_type (pkbuf, pos, HICN_PACKET_TYPE_DATA);
+ if (rc)
+ return rc;
+
+ tcp->name_suffix = htonl (*suffix);
return HICN_LIB_ERROR_NONE;
}
int
-tcp_get_data_pathlabel (hicn_type_t type, const hicn_protocol_t *h,
- u32 *pathlabel)
+tcp_get_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t *path_label)
{
- *pathlabel = h->tcp.seq_ack;
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ *path_label =
+ (hicn_path_label_t) (tcp->seq_ack >> (32 - HICN_PATH_LABEL_SIZE_BITS));
return HICN_LIB_ERROR_NONE;
}
int
-tcp_set_data_pathlabel (hicn_type_t type, hicn_protocol_t *h,
- const u32 pathlabel)
+tcp_set_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t path_label)
{
- h->tcp.seq_ack = pathlabel;
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ hicn_path_label_t old_path_label;
+ tcp_get_data_path_label (pkbuf, pos, &old_path_label);
+
+ tcp->seq_ack = (path_label << (32 - HICN_PATH_LABEL_SIZE_BITS));
+
+ tcp_update_checksums_incremental (
+ pkbuf, pos, (uint16_t *) &old_path_label, (uint16_t *) &path_label,
+ sizeof (hicn_path_label_t) / sizeof (uint16_t), true);
+
return HICN_LIB_ERROR_NONE;
}
int
-tcp_update_data_pathlabel (hicn_type_t type, hicn_protocol_t *h,
- const hicn_faceid_t face_id)
+tcp_update_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_faceid_t face_id)
{
- hicn_pathlabel_t pl =
- (hicn_pathlabel_t) (h->tcp.seq_ack >> (32 - HICN_PATH_LABEL_SIZE));
+ assert (sizeof (hicn_path_label_t) == 1);
- hicn_pathlabel_t new_pl;
+ hicn_path_label_t old_path_label;
+ hicn_path_label_t new_path_label;
- update_pathlabel (pl, face_id, &new_pl);
- h->tcp.seq_ack = (new_pl << (32 - HICN_PATH_LABEL_SIZE));
+ tcp_get_data_path_label (pkbuf, pos, &old_path_label);
+ update_path_label (old_path_label, face_id, &new_path_label);
+ tcp_set_data_path_label (pkbuf, pos, new_path_label);
return HICN_LIB_ERROR_NONE;
}
int
-tcp_reset_data_for_hash (hicn_type_t type, hicn_protocol_t *h)
+tcp_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
{
- memset (&(h->tcp), 0, 4);
- memset (&(h->tcp.seq_ack), 0, 12);
-
- return CHILD_OPS (reset_data_for_hash, type, h);
+ reset_for_hash (pkbuf);
+ return CALL_CHILD (reset_data_for_hash, pkbuf, pos);
}
int
-tcp_get_lifetime (hicn_type_t type, const hicn_protocol_t *h,
+tcp_get_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
hicn_lifetime_t *lifetime)
{
- *lifetime = ntohs (h->tcp.urg_ptr)
- << (h->tcp.data_offset_and_reserved & 0xF);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ *lifetime = ntohs (tcp->urg_ptr) << (tcp->data_offset_and_reserved & 0xF);
return HICN_LIB_ERROR_NONE;
}
int
-tcp_set_lifetime (hicn_type_t type, hicn_protocol_t *h,
+tcp_set_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
const hicn_lifetime_t lifetime)
{
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
u8 multiplier = 0;
u32 lifetime_scaled = lifetime;
- if (PREDICT_FALSE (lifetime >= HICN_MAX_LIFETIME))
+ if (HICN_EXPECT_FALSE (lifetime >= HICN_MAX_LIFETIME))
{
- h->tcp.urg_ptr = htons (HICN_MAX_LIFETIME_SCALED);
- h->tcp.data_offset_and_reserved =
- (h->tcp.data_offset_and_reserved & ~0x0F) |
- HICN_MAX_LIFETIME_MULTIPLIER;
+ tcp->urg_ptr = htons (HICN_MAX_LIFETIME_SCALED);
+ tcp->data_offset_and_reserved =
+ (tcp->data_offset_and_reserved & ~0x0F) | HICN_MAX_LIFETIME_MULTIPLIER;
return HICN_LIB_ERROR_NONE;
}
@@ -219,41 +287,76 @@ tcp_set_lifetime (hicn_type_t type, hicn_protocol_t *h,
lifetime_scaled = lifetime_scaled >> 1;
}
- h->tcp.urg_ptr = htons (lifetime_scaled);
- h->tcp.data_offset_and_reserved =
- (h->tcp.data_offset_and_reserved & ~0x0F) | multiplier;
+ tcp->urg_ptr = htons (lifetime_scaled);
+ tcp->data_offset_and_reserved =
+ (tcp->data_offset_and_reserved & ~0x0F) | multiplier;
return HICN_LIB_ERROR_NONE;
}
int
-tcp_update_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+tcp_update_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
- h->tcp.csum = 0;
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ /* TODO bound checks for payload_len based on pkbuf size */
+ assert (payload_len != ~0);
- if (PREDICT_TRUE (partial_csum != 0))
+ tcp->csum = 0;
+
+ if (HICN_EXPECT_TRUE (partial_csum != 0))
{
partial_csum = ~partial_csum;
}
- h->tcp.csum = csum (h, TCP_HDRLEN + payload_length, partial_csum);
+ tcp->csum =
+ csum (pkbuf_get_header (pkbuf), TCP_HDRLEN + payload_len, partial_csum);
+
+ return CALL_CHILD (update_checksums, pkbuf, pos, 0, payload_len);
+}
+
+int
+tcp_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first)
+{
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ if (skip_first)
+ return HICN_LIB_ERROR_INVALID_PARAMETER;
+
+ for (uint8_t i = 0; i < size; i++)
+ {
+ uint16_t old_csum = ~tcp->csum;
+ uint16_t not_old_val = ~(*old_val);
+ uint32_t sum = (uint32_t) old_csum + not_old_val + *new_val;
+
+ while (sum >> 16)
+ {
+ sum = (sum >> 16) + (sum & UINT16_T_MASK);
+ }
+
+ tcp->csum = ~sum;
+ ++old_val;
+ ++new_val;
+ }
- return CHILD_OPS (update_checksums, type, h, 0, payload_length);
+ return CALL_CHILD (update_checksums_incremental, pkbuf, pos, old_val,
+ new_val, size, false);
}
int
-tcp_verify_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
- size_t payload_length)
+tcp_verify_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
{
- if (PREDICT_TRUE (partial_csum != 0))
+ if (HICN_EXPECT_TRUE (partial_csum != 0))
{
partial_csum = ~partial_csum;
}
- if (csum (h, TCP_HDRLEN + payload_length, partial_csum) != 0)
+ if (csum (pkbuf_get_header (pkbuf), TCP_HDRLEN + payload_len,
+ partial_csum) != 0)
return HICN_LIB_ERROR_CORRUPTED_PACKET;
- return CHILD_OPS (verify_checksums, type, h, 0, payload_length);
+ return CALL_CHILD (verify_checksums, pkbuf, pos, 0, payload_len);
}
#define TCP_OFFSET_MASK 13
@@ -278,10 +381,14 @@ tcp_verify_checksums (hicn_type_t type, hicn_protocol_t *h, u16 partial_csum,
#define TCP_DEFAULT_FIN 0
int
-tcp_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new, ip46_address_t *addr_old)
+tcp_rewrite_interest (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
{
- u16 *tcp_checksum = &(h->tcp.csum);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ _ipv6_header_t *ip6 = pkbuf_get_ipv6 (pkbuf);
+
+ u16 *tcp_checksum = &(tcp->csum);
int ret = check_tcp_checksum (*tcp_checksum);
if (ret)
@@ -294,14 +401,14 @@ tcp_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
* whole struct by interpreting it as IPv6 in all cases
*
* v4 code would be:
- * csum = ip_csum_sub_even (*tcp_checksum, h->ipv4.saddr.as_u32);
- * csum = ip_csum_add_even (csum, h->ipv4.saddr.as_u32);
+ * csum = ip_csum_sub_even (*tcp_checksum, h->tcp.saddr.as_u32);
+ * csum = ip_csum_add_even (csum, h->tcp.saddr.as_u32);
*/
- ip_csum_t csum =
- ip_csum_sub_even (*tcp_checksum, (ip_csum_t) (h->ipv6.saddr.as_u64[0]));
- csum = ip_csum_sub_even (csum, (ip_csum_t) (h->ipv6.saddr.as_u64[1]));
- csum = ip_csum_add_even (csum, (ip_csum_t) (h->ipv6.saddr.as_u64[0]));
- csum = ip_csum_add_even (csum, (ip_csum_t) (h->ipv6.saddr.as_u64[1]));
+ hicn_ip_csum_t csum =
+ ip_csum_sub_even (*tcp_checksum, (hicn_ip_csum_t) (ip6->saddr.as_u64[0]));
+ csum = ip_csum_sub_even (csum, (hicn_ip_csum_t) (ip6->saddr.as_u64[1]));
+ csum = ip_csum_add_even (csum, (hicn_ip_csum_t) (ip6->saddr.as_u64[0]));
+ csum = ip_csum_add_even (csum, (hicn_ip_csum_t) (ip6->saddr.as_u64[1]));
*tcp_checksum = ip_csum_fold (csum);
@@ -309,21 +416,22 @@ tcp_rewrite_interest (hicn_type_t type, hicn_protocol_t *h,
}
int
-tcp_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
- const ip46_address_t *addr_new, ip46_address_t *addr_old,
- const hicn_faceid_t face_id, u8 reset_pl)
+tcp_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
{
-
- u16 *tcp_checksum = &(h->tcp.csum);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ u16 *tcp_checksum = &(tcp->csum);
int ret = check_tcp_checksum (*tcp_checksum);
/*
* update path label
*/
- u16 old_pl = h->tcp.seq_ack;
+ u16 old_pl = tcp->seq_ack;
if (reset_pl)
- h->tcp.seq_ack = 0;
- tcp_update_data_pathlabel (type, h, face_id);
+ tcp->seq_ack = 0;
+ tcp_update_data_path_label (pkbuf, pos, face_id);
if (ret)
{
@@ -335,18 +443,18 @@ tcp_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
* whole struct by interpreting it as IPv6 in all cases
*
* v4 code would be:
- * csum = ip_csum_sub_even (*tcp_checksum, h->ipv4.saddr.as_u32);
- * csum = ip_csum_add_even (csum, h->ipv4.saddr.as_u32);
+ * csum = ip_csum_sub_even (*tcp_checksum, h->tcp.saddr.as_u32);
+ * csum = ip_csum_add_even (csum, h->tcp.saddr.as_u32);
*/
- ip_csum_t csum =
- ip_csum_sub_even (*tcp_checksum, (ip_csum_t) (addr_old->ip6.as_u64[0]));
- csum =
- ip_csum_sub_even (*tcp_checksum, (ip_csum_t) (addr_old->ip6.as_u64[1]));
- csum = ip_csum_add_even (csum, (ip_csum_t) (addr_new->ip6.as_u64[0]));
- csum = ip_csum_add_even (csum, (ip_csum_t) (addr_new->ip6.as_u64[1]));
+ hicn_ip_csum_t csum = ip_csum_sub_even (
+ *tcp_checksum, (hicn_ip_csum_t) (addr_old->v6.as_u64[0]));
+ csum = ip_csum_sub_even (*tcp_checksum,
+ (hicn_ip_csum_t) (addr_old->v6.as_u64[1]));
+ csum = ip_csum_add_even (csum, (hicn_ip_csum_t) (addr_new->v6.as_u64[0]));
+ csum = ip_csum_add_even (csum, (hicn_ip_csum_t) (addr_new->v6.as_u64[1]));
csum = ip_csum_sub_even (csum, old_pl);
- csum = ip_csum_add_even (csum, h->tcp.seq_ack);
+ csum = ip_csum_add_even (csum, tcp->seq_ack);
*tcp_checksum = ip_csum_fold (csum);
@@ -354,101 +462,134 @@ tcp_rewrite_data (hicn_type_t type, hicn_protocol_t *h,
}
int
-tcp_get_current_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+tcp_get_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *signature_size)
{
- *header_length = TCP_HDRLEN;
- return HICN_LIB_ERROR_NONE;
+ return CALL_CHILD (get_signature_size, pkbuf, pos, signature_size);
}
int
-tcp_get_header_length (hicn_type_t type, const hicn_protocol_t *h,
- size_t *header_length)
+tcp_set_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_size)
{
- size_t child_header_length = 0;
- int rc = CHILD_OPS (get_header_length, type, h, &child_header_length);
- if (rc < 0)
- return rc;
+ return CALL_CHILD (set_signature_size, pkbuf, pos, signature_size);
+}
- *header_length = TCP_HDRLEN + child_header_length;
- return HICN_LIB_ERROR_NONE;
+int
+tcp_set_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t padding)
+{
+ return CALL_CHILD (set_signature_padding, pkbuf, pos, padding);
}
int
-tcp_get_signature_size (hicn_type_t type, const hicn_protocol_t *h,
- size_t *signature_size)
+tcp_get_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *padding)
{
- return CHILD_OPS (get_signature_size, type, h, signature_size);
+ return CALL_CHILD (get_signature_padding, pkbuf, pos, padding);
}
int
-tcp_set_signature_size (hicn_type_t type, hicn_protocol_t *h,
- size_t signature_size)
+tcp_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t signature_timestamp)
{
- return CHILD_OPS (set_signature_size, type, h, signature_size);
+ return CALL_CHILD (set_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-tcp_set_signature_gap (hicn_type_t type, hicn_protocol_t *h, uint8_t gap)
+tcp_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t *signature_timestamp)
{
- return CHILD_OPS (set_signature_gap, type, h, gap);
+ return CALL_CHILD (get_signature_timestamp, pkbuf, pos, signature_timestamp);
}
int
-tcp_get_signature_gap (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *gap)
+tcp_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t validation_algorithm)
{
- return CHILD_OPS (get_signature_gap, type, h, gap);
+ return CALL_CHILD (set_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-tcp_set_signature_timestamp (hicn_type_t type, hicn_protocol_t *h,
- uint64_t signature_timestamp)
+tcp_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *validation_algorithm)
{
- return CHILD_OPS (set_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (get_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
}
int
-tcp_get_signature_timestamp (hicn_type_t type, const hicn_protocol_t *h,
- uint64_t *signature_timestamp)
+tcp_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos, uint8_t *key_id,
+ size_t key_len)
{
- return CHILD_OPS (get_signature_timestamp, type, h, signature_timestamp);
+ return CALL_CHILD (set_key_id, pkbuf, pos, key_id, key_len);
}
int
-tcp_set_validation_algorithm (hicn_type_t type, hicn_protocol_t *h,
- uint8_t validation_algorithm)
+tcp_get_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **key_id, uint8_t *key_id_size)
{
- return CHILD_OPS (set_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (get_key_id, pkbuf, pos, key_id, key_id_size);
}
int
-tcp_get_validation_algorithm (hicn_type_t type, const hicn_protocol_t *h,
- uint8_t *validation_algorithm)
+tcp_get_signature (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **signature)
{
- return CHILD_OPS (get_validation_algorithm, type, h, validation_algorithm);
+ return CALL_CHILD (get_signature, pkbuf, pos, signature);
}
int
-tcp_set_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t *key_id)
+tcp_has_signature (const hicn_packet_buffer_t *pkbuf, size_t pos, bool *flag)
{
- return CHILD_OPS (set_key_id, type, h, key_id);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ *flag = tcp->flags & AH_FLAG;
+ return HICN_LIB_ERROR_NONE;
}
int
-tcp_get_key_id (hicn_type_t type, hicn_protocol_t *h, uint8_t **key_id,
- uint8_t *key_id_size)
+tcp_get_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t *payload_type)
{
- return CHILD_OPS (get_key_id, type, h, key_id, key_id_size);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ *payload_type = ((tcp->flags & HICN_TCP_FLAG_URG) == HICN_TCP_FLAG_URG);
+ return HICN_LIB_ERROR_NONE;
}
int
-tcp_get_signature (hicn_type_t type, hicn_protocol_t *h, uint8_t **signature)
+tcp_set_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t payload_type)
{
- return CHILD_OPS (get_signature, type, h, signature);
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ if (payload_type != HPT_DATA && payload_type != HPT_MANIFEST)
+ return HICN_LIB_ERROR_INVALID_PARAMETER;
+
+ if (payload_type)
+ tcp->flags |= HICN_TCP_FLAG_URG;
+ else
+ tcp->flags &= ~HICN_TCP_FLAG_URG;
+
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+tcp_is_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos, int *is_last)
+{
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ *is_last = (tcp->flags & HICN_TCP_FLAG_RST) == HICN_TCP_FLAG_RST;
+ return HICN_LIB_ERROR_NONE;
+}
+
+int
+tcp_set_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ _tcp_header_t *tcp = pkbuf_get_tcp (pkbuf);
+ tcp->flags |= HICN_TCP_FLAG_RST;
+ return HICN_LIB_ERROR_NONE;
}
-DECLARE_HICN_OPS (tcp);
+DECLARE_HICN_OPS (tcp, TCP_HDRLEN);
/*
* fd.io coding-style-patch-verification: ON
diff --git a/lib/src/protocol/tcp.h b/lib/src/protocol/tcp.h
new file mode 100644
index 000000000..e563372d0
--- /dev/null
+++ b/lib/src/protocol/tcp.h
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+#ifndef HICN_PROTOCOL_TCP_H
+#define HICN_PROTOCOL_TCP_H
+
+#include <hicn/base.h>
+#include <hicn/common.h>
+#include <hicn/name.h>
+
+/*
+ * The length of the TCP header struct must be 20 bytes.
+ */
+#define EXPECTED_TCP_HDRLEN 20
+
+/*
+ * NOTE: bitfields are problematic for portability reasons. There are provided
+ * here for reference and documentation purposes, we might just provide a macro
+ * to disable and use it instead of __BYTE_ORDER__.
+ */
+typedef struct
+{
+ u16 sport;
+ u16 dport;
+ union
+ {
+ u32 seq;
+ hicn_name_suffix_t name_suffix;
+ };
+ union
+ {
+ u32 seq_ack;
+ struct
+ {
+ hicn_path_label_t pathlabel;
+ u8 pad[3];
+ };
+ };
+
+ union
+ {
+ struct
+ {
+ u8 data_offset_and_reserved;
+ u8 flags;
+ };
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+ struct
+ {
+ u16 reserved : 4;
+ u16 doff : 4;
+ u16 fin : 1;
+ u16 syn : 1;
+ u16 rst : 1;
+ u16 psh : 1;
+ u16 ack : 1;
+ u16 urg : 1;
+ u16 ece : 1;
+ u16 cwr : 1;
+ };
+ struct
+ { /* __ denotes unchanged bitfields */
+ u16 timescale : 4;
+ u16 __doff : 4;
+ u16 __fin : 1;
+ u16 __syn : 1;
+ u16 __rst : 1;
+ u16 sig : 1;
+ u16 __ack : 1;
+ u16 man : 1;
+ u16 id : 1;
+ u16 __cwr : 1;
+ };
+#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+ struct
+ {
+ u16 doff : 4;
+ u16 reserved : 4;
+ u16 cwr : 1;
+ u16 ece : 1;
+ u16 urg : 1;
+ u16 ack : 1;
+ u16 psh : 1;
+ u16 rst : 1;
+ u16 syn : 1;
+ u16 fin : 1;
+ };
+ struct
+ {
+ u16 __doff : 4;
+ u16 timescale : 4;
+ u16 __cwr : 1;
+ u16 id : 1 u16 man : 1;
+ u16 __ack : 1;
+ u16 sig : 1;
+ u16 __rst : 1;
+ u16 __syn : 1;
+ u16 __fin : 1;
+ };
+#endif
+ };
+ union
+ {
+ u16 window;
+ u16 ldr;
+ };
+ u16 csum;
+ union
+ {
+ u16 urg_ptr;
+ u16 lifetime;
+ };
+} _tcp_header_t;
+
+#define TCP_HDRLEN sizeof (_tcp_header_t)
+static_assert (EXPECTED_TCP_HDRLEN == TCP_HDRLEN,
+ "Size of TCP struct does not match its expected size.");
+
+/* TCP flags bit 0 first. */
+#define foreach_tcp_flag \
+ _ (FIN) /**< No more data from sender. */ \
+ _ (SYN) /**< Synchronize sequence numbers. */ \
+ _ (RST) /**< Reset the connection. */ \
+ _ (PSH) /**< Push function. */ \
+ _ (ACK) /**< Ack field significant. */ \
+ _ (URG) /**< Urgent pointer field significant. */ \
+ _ (ECE) /**< ECN-echo. Receiver got CE packet */ \
+ _ (CWR) /**< Sender reduced congestion window */
+
+enum
+{
+#define _(f) HICN_TCP_FLAG_BIT_##f,
+ foreach_tcp_flag
+#undef _
+ HICN_TCP_N_FLAG_BITS,
+};
+
+enum
+{
+#define _(f) HICN_TCP_FLAG_##f = 1 << HICN_TCP_FLAG_BIT_##f,
+ foreach_tcp_flag
+#undef _
+};
+
+#endif /* HICN_PROTOCOL_TCP_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/udp.c b/lib/src/protocol/udp.c
new file mode 100644
index 000000000..56de0065f
--- /dev/null
+++ b/lib/src/protocol/udp.c
@@ -0,0 +1,308 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <hicn/common.h>
+#include <hicn/error.h>
+
+#include "udp.h"
+#include "../ops.h"
+
+DECLARE_get_interest_locator (udp, UNEXPECTED);
+DECLARE_set_interest_locator (udp, UNEXPECTED);
+DECLARE_get_interest_name (udp, UNEXPECTED);
+DECLARE_set_interest_name (udp, UNEXPECTED);
+DECLARE_get_data_locator (udp, UNEXPECTED);
+DECLARE_set_data_locator (udp, UNEXPECTED);
+DECLARE_get_data_name (udp, UNEXPECTED);
+DECLARE_set_data_name (udp, UNEXPECTED);
+DECLARE_set_payload_len (udp, UNEXPECTED);
+
+int
+udp_init_packet_header (hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ pkbuf->udp = pkbuf->len;
+ if (UDP_HDRLEN > pkbuf->buffer_size - pkbuf->len)
+ return -1;
+ pkbuf->len += UDP_HDRLEN;
+
+ _udp_header_t *udp = pkbuf_get_udp (pkbuf);
+
+ size_t len = hicn_packet_get_len (pkbuf) -
+ ((u8 *) udp - pkbuf_get_header (pkbuf)) -
+ sizeof (_udp_header_t);
+
+ // clang-format off
+ *udp = (_udp_header_t){
+ .src_port = 0,
+ .dst_port = 0,
+ .len = htons ((u16) len),
+ .checksum = 0
+ };
+ // clang-format on
+ return CALL_CHILD (init_packet_header, pkbuf, pos);
+}
+
+int
+udp_get_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_name_suffix_t *suffix)
+{
+ return CALL_CHILD (get_interest_name_suffix, pkbuf, pos, suffix);
+}
+
+int
+udp_set_interest_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_suffix_t *suffix)
+{
+ return CALL_CHILD (set_interest_name_suffix, pkbuf, pos, suffix);
+}
+
+int
+udp_get_type (const hicn_packet_buffer_t *pkbuf, const size_t pos,
+ hicn_packet_type_t *type)
+{
+ return CALL_CHILD (get_type, pkbuf, pos, type);
+}
+
+int
+udp_set_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_packet_type_t type)
+{
+ return CALL_CHILD (set_type, pkbuf, pos, type);
+}
+
+int
+udp_reset_interest_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ return CALL_CHILD (reset_interest_for_hash, pkbuf, pos);
+}
+
+int
+udp_get_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_name_suffix_t *suffix)
+{
+ return CALL_CHILD (get_data_name_suffix, pkbuf, pos, suffix);
+}
+
+int
+udp_set_data_name_suffix (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_name_suffix_t *suffix)
+{
+ return CALL_CHILD (set_data_name_suffix, pkbuf, pos, suffix);
+}
+
+int
+udp_get_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t *path_label)
+{
+ return CALL_CHILD (get_data_path_label, pkbuf, pos, path_label);
+}
+
+int
+udp_set_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_path_label_t path_label)
+{
+ return CALL_CHILD (set_data_path_label, pkbuf, pos, path_label);
+}
+
+int
+udp_update_data_path_label (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_faceid_t face_id)
+{
+ return CALL_CHILD (update_data_path_label, pkbuf, pos, face_id);
+}
+
+int
+udp_reset_data_for_hash (hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ return CALL_CHILD (reset_data_for_hash, pkbuf, pos);
+}
+
+int
+udp_get_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_lifetime_t *lifetime)
+{
+ return CALL_CHILD (get_lifetime, pkbuf, pos, lifetime);
+}
+
+int
+udp_set_lifetime (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_lifetime_t lifetime)
+{
+ return CALL_CHILD (set_lifetime, pkbuf, pos, lifetime);
+}
+
+int
+udp_update_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
+{
+ return CALL_CHILD (update_checksums, pkbuf, pos, partial_csum, payload_len);
+}
+
+int
+udp_update_checksums_incremental (const hicn_packet_buffer_t *pkbuf,
+ size_t pos, u16 *old_val, u16 *new_val,
+ u8 size, bool skip_first)
+{
+ return CALL_CHILD (update_checksums_incremental, pkbuf, pos, old_val,
+ new_val, size, false);
+}
+
+int
+udp_verify_checksums (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ u16 partial_csum, size_t payload_len)
+{
+ return CALL_CHILD (verify_checksums, pkbuf, pos, partial_csum, payload_len);
+}
+
+int
+udp_rewrite_interest (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old)
+{
+ return CALL_CHILD (rewrite_interest, pkbuf, pos, addr_new, addr_old);
+}
+
+int
+udp_rewrite_data (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ const hicn_ip_address_t *addr_new,
+ hicn_ip_address_t *addr_old, const hicn_faceid_t face_id,
+ u8 reset_pl)
+{
+ return CALL_CHILD (rewrite_data, pkbuf, pos, addr_new, addr_old, face_id,
+ reset_pl);
+}
+
+int
+udp_get_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t *payload_type)
+{
+ return CALL_CHILD (get_payload_type, pkbuf, pos, payload_type);
+}
+
+int
+udp_set_payload_type (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ hicn_payload_type_t payload_type)
+{
+ return CALL_CHILD (set_payload_type, pkbuf, pos, payload_type);
+}
+
+int
+udp_get_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *signature_size)
+{
+ return CALL_CHILD (get_signature_size, pkbuf, pos, signature_size);
+}
+
+int
+udp_set_signature_size (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t signature_size)
+{
+ return CALL_CHILD (set_signature_size, pkbuf, pos, signature_size);
+}
+
+int
+udp_has_signature (const hicn_packet_buffer_t *pkbuf, size_t pos, bool *flag)
+{
+ return CALL_CHILD (has_signature, pkbuf, pos, flag);
+}
+
+int
+udp_set_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t padding)
+{
+ return CALL_CHILD (set_signature_padding, pkbuf, pos, padding);
+}
+
+int
+udp_get_signature_padding (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ size_t *padding)
+{
+ return CALL_CHILD (get_signature_padding, pkbuf, pos, padding);
+}
+
+int
+udp_set_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t signature_timestamp)
+{
+ return CALL_CHILD (set_signature_timestamp, pkbuf, pos, signature_timestamp);
+}
+
+int
+udp_get_signature_timestamp (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint64_t *signature_timestamp)
+{
+ return CALL_CHILD (get_signature_timestamp, pkbuf, pos, signature_timestamp);
+}
+
+int
+udp_set_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t validation_algorithm)
+{
+ return CALL_CHILD (set_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
+}
+
+int
+udp_get_validation_algorithm (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t *validation_algorithm)
+{
+ return CALL_CHILD (get_validation_algorithm, pkbuf, pos,
+ validation_algorithm);
+}
+
+int
+udp_set_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos, uint8_t *key_id,
+ size_t key_len)
+{
+ return CALL_CHILD (set_key_id, pkbuf, pos, key_id, key_len);
+}
+
+int
+udp_get_key_id (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **key_id, uint8_t *key_id_size)
+{
+ return CALL_CHILD (get_key_id, pkbuf, pos, key_id, key_id_size);
+}
+
+int
+udp_get_signature (const hicn_packet_buffer_t *pkbuf, size_t pos,
+ uint8_t **signature)
+{
+ return CALL_CHILD (get_signature, pkbuf, pos, signature);
+}
+
+int
+udp_is_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos, int *is_last)
+{
+ return CALL_CHILD (is_last_data, pkbuf, pos, is_last);
+}
+
+int
+udp_set_last_data (const hicn_packet_buffer_t *pkbuf, size_t pos)
+{
+ return CALL_CHILD (set_last_data, pkbuf, pos);
+}
+
+DECLARE_HICN_OPS (udp, UDP_HDRLEN);
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/protocol/udp.h b/lib/src/protocol/udp.h
new file mode 100644
index 000000000..23f5317b3
--- /dev/null
+++ b/lib/src/protocol/udp.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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.
+ */
+
+#ifndef HICN_PROTOCOL_UDP_H
+#define HICN_PROTOCOL_UDP_H
+
+/*
+ * The len of the UDP header struct must be 8 bytes.
+ */
+#define EXPECTED_UDP_HDRLEN 8
+
+typedef struct
+{
+ u16 src_port;
+ u16 dst_port;
+ u16 len;
+ u16 checksum;
+} _udp_header_t;
+
+#define UDP_HDRLEN sizeof (_udp_header_t)
+static_assert (EXPECTED_UDP_HDRLEN == UDP_HDRLEN,
+ "Size of UDP struct does not match its expected size.");
+
+#endif /* HICN_PROTOCOL_UDP_H */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/lib/src/strategy.c b/lib/src/strategy.c
new file mode 100644
index 000000000..3b797664a
--- /dev/null
+++ b/lib/src/strategy.c
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hicn/strategy.h>
+
+const char *strategy_str[] = {
+#define _(x) [STRATEGY_TYPE_##x] = #x,
+ foreach_strategy_type
+#undef _
+}; \ No newline at end of file
diff --git a/lib/src/test/CMakeLists.txt b/lib/src/test/CMakeLists.txt
new file mode 100644
index 000000000..8cf4359d2
--- /dev/null
+++ b/lib/src/test/CMakeLists.txt
@@ -0,0 +1,55 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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.
+
+find_package(Threads REQUIRED)
+
+##############################################################
+# Test sources
+##############################################################
+list(APPEND TESTS_SRC
+ main.cc
+ test_name.cc
+ test_new_header.cc
+ test_udp_header.cc
+ test_validation.cc
+ test_bitmap.cc
+ test_interest_manifest.cc
+ test_ip_address.cc
+ test_khash.cc
+ test_pool.cc
+ test_ring.cc
+ test_slab.cc
+ test_vector.cc
+)
+
+##############################################################
+# Build single unit test executable and add it to test list
+##############################################################
+build_executable(lib_tests
+ NO_INSTALL
+ SOURCES ${TESTS_SRC}
+ LINK_LIBRARIES
+ PRIVATE ${LIBHICN_STATIC}
+ PRIVATE ${GTEST_LIBRARIES}
+ PRIVATE ${CMAKE_THREAD_LIBS_INIT}
+ INCLUDE_DIRS
+ PRIVATE ${Libhicn_INCLUDE_DIRS}
+ PRIVATE ${GTEST_INCLUDE_DIRS}
+ DEPENDS gtest ${LIBHICN_SHARED}
+ COMPONENT ${LIBHICN_COMPONENT}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${DEFAULT_COMPILER_OPTIONS}
+ LINK_FLAGS ${LINK_FLAGS}
+)
+
+add_test_internal(lib_tests)
diff --git a/lib/src/test/main.cc b/lib/src/test/main.cc
new file mode 100644
index 000000000..042fcd6c0
--- /dev/null
+++ b/lib/src/test/main.cc
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+int
+main (int argc, char **argv)
+{
+ ::testing::InitGoogleTest (&argc, argv);
+ return RUN_ALL_TESTS ();
+}
diff --git a/lib/src/test/test_bitmap.cc b/lib/src/test/test_bitmap.cc
new file mode 100644
index 000000000..7fc8eef71
--- /dev/null
+++ b/lib/src/test/test_bitmap.cc
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C"
+{
+#define WITH_TESTS
+#include <hicn/util/bitmap.h>
+}
+
+#define DEFAULT_SIZE 10
+
+class BitmapTest : public ::testing::Test
+{
+protected:
+ BitmapTest () {}
+
+ virtual ~BitmapTest () {}
+
+ bitmap_t *bitmap;
+};
+
+/*
+ * TEST: bitmap allocation
+ */
+TEST_F (BitmapTest, BitmapAllocation)
+{
+ int rc;
+
+ /*
+ * We take a value < 32 on purpose to avoid confusion on the choice of a 32
+ * or 64 bit integer for storage
+ */
+ size_t size_not_pow2 = DEFAULT_SIZE;
+ bitmap_init (bitmap, size_not_pow2, 0);
+
+ /*
+ * Bitmap should have been allocated with a size rounded to the next power
+ * of 2
+ */
+ EXPECT_EQ (bitmap_get_alloc_size (bitmap), 1UL);
+
+ /* By default, no element should be set */
+ EXPECT_FALSE (bitmap_is_set (bitmap, 0));
+ EXPECT_TRUE (bitmap_is_unset (bitmap, 0));
+
+ EXPECT_EQ (bitmap_get_alloc_size (bitmap), 1UL);
+
+ EXPECT_FALSE (bitmap_is_set (bitmap, size_not_pow2 - 1));
+ EXPECT_TRUE (bitmap_is_unset (bitmap, size_not_pow2 - 1));
+
+ /* Bitmap should not have been reallocated */
+ EXPECT_EQ (bitmap_get_alloc_size (bitmap), 1UL);
+
+ /* After setting a bit after the end, bitmap should have been reallocated */
+ bitmap_set (bitmap, sizeof (bitmap[0]) * 8 - 1);
+ EXPECT_EQ (bitmap_get_alloc_size (bitmap), 1UL);
+
+ /* After setting a bit after the end, bitmap should have been reallocated */
+ rc = bitmap_set (bitmap, sizeof (bitmap[0]) * 8);
+ EXPECT_GE (rc, 0);
+ EXPECT_EQ (bitmap_get_alloc_size (bitmap), 2UL);
+
+ rc = bitmap_set (bitmap, sizeof (bitmap[0]) * 8 + 1);
+ EXPECT_GE (rc, 0);
+ EXPECT_EQ (bitmap_get_alloc_size (bitmap), 2UL);
+
+ bitmap_free (bitmap);
+
+ size_t size_pow2 = 16;
+
+ /* Limiting test for allocation size */
+ bitmap_init (bitmap, size_pow2, 0);
+ EXPECT_EQ (bitmap_get_alloc_size (bitmap), 1UL);
+
+ bitmap_free (bitmap);
+}
+
+TEST_F (BitmapTest, BitmapSet)
+{
+ bitmap_init (bitmap, DEFAULT_SIZE, 0);
+
+ bitmap_set (bitmap, 20);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 20));
+ EXPECT_FALSE (bitmap_is_unset (bitmap, 20));
+ EXPECT_FALSE (bitmap_is_set (bitmap, 19));
+ EXPECT_TRUE (bitmap_is_unset (bitmap, 19));
+
+ // Test edge cases (i.e. start and end of block)
+ off_t start_position = 0;
+ bitmap_set (bitmap, start_position);
+ EXPECT_TRUE (bitmap_is_set (bitmap, start_position));
+ EXPECT_FALSE (bitmap_is_unset (bitmap, start_position));
+
+ off_t end_position = BITMAP_WIDTH (bitmap) - 1;
+ bitmap_set (bitmap, end_position);
+ EXPECT_TRUE (bitmap_is_set (bitmap, end_position));
+ EXPECT_FALSE (bitmap_is_unset (bitmap, end_position));
+
+ bitmap_free (bitmap);
+}
+
+TEST_F (BitmapTest, BitmapUnSet)
+{
+ bitmap_init (bitmap, DEFAULT_SIZE, 0);
+
+ bitmap_set (bitmap, 20);
+ bitmap_set (bitmap, 19);
+ bitmap_unset (bitmap, 20);
+ EXPECT_FALSE (bitmap_is_set (bitmap, 20));
+ EXPECT_TRUE (bitmap_is_unset (bitmap, 20));
+ EXPECT_TRUE (bitmap_is_set (bitmap, 19));
+ EXPECT_FALSE (bitmap_is_unset (bitmap, 19));
+
+ bitmap_free (bitmap);
+}
+
+TEST_F (BitmapTest, BitmapSetTo)
+{
+ bitmap_init (bitmap, DEFAULT_SIZE, 0);
+
+ bitmap_set_to (bitmap, 40);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 20));
+ EXPECT_TRUE (bitmap_is_set (bitmap, 21));
+ EXPECT_TRUE (bitmap_is_unset (bitmap, 41));
+ EXPECT_TRUE (bitmap_is_unset (bitmap, 42));
+
+ bitmap_free (bitmap);
+}
+
+TEST_F (BitmapTest, BitmapFirstSet)
+{
+ bitmap_init (bitmap, DEFAULT_SIZE, 0);
+
+ // Get first set bit. It should be INVALID_INDEX
+ EXPECT_EQ (bitmap_first_set (bitmap), BITMAP_INVALID_INDEX);
+
+ // set bit 40
+ bitmap_set (bitmap, 40);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 40));
+
+ // Get first set bit. It should be bit 40 (surprise):)
+ EXPECT_EQ (bitmap_first_set (bitmap), hicn_uword (40));
+
+ // set bit 3
+ bitmap_set (bitmap, 3);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 3));
+
+ // The first set bit now should be bit #3
+ EXPECT_EQ (bitmap_first_set (bitmap), hicn_uword (3));
+
+ bitmap_free (bitmap);
+}
+
+TEST_F (BitmapTest, BitmapFirstUnSet)
+{
+ bitmap_init (bitmap, DEFAULT_SIZE, 0);
+
+ // Get first unset bit. It should be 0
+ EXPECT_EQ (bitmap_first_unset (bitmap), hicn_uword (0));
+
+ // set bit 0
+ bitmap_set (bitmap, 0);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 0));
+
+ // Get first unset bit. It should be bit 1
+ EXPECT_EQ (bitmap_first_unset (bitmap), hicn_uword (1));
+
+ // set bit 3
+ bitmap_set (bitmap, 3);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 3));
+
+ // The first set bit now should be still 1
+ EXPECT_EQ (bitmap_first_unset (bitmap), hicn_uword (1));
+
+ bitmap_free (bitmap);
+}
+
+TEST_F (BitmapTest, BitmapNextSet)
+{
+ bitmap_init (bitmap, DEFAULT_SIZE, 0);
+
+ // Get next unset bit >= 0. It should be INVALID
+ EXPECT_EQ (bitmap_next_set (bitmap, 0), BITMAP_INVALID_INDEX);
+
+ // set bit 0
+ bitmap_set (bitmap, 0);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 0));
+
+ // Get next set bit >= 0. It should be bit 0
+ EXPECT_EQ (bitmap_next_set (bitmap, 0), hicn_uword (0));
+
+ // set bit 3
+ bitmap_set (bitmap, 3);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 3));
+
+ // Get next set bit >= 1. It should be 3
+ EXPECT_EQ (bitmap_next_set (bitmap, 1), hicn_uword (3));
+
+ // set (N-2)th bit
+ bitmap_set (bitmap, DEFAULT_SIZE * WORD_WIDTH - 2);
+ EXPECT_TRUE (bitmap_is_set (bitmap, DEFAULT_SIZE * WORD_WIDTH - 2));
+ EXPECT_EQ (bitmap_next_set (bitmap, DEFAULT_SIZE * WORD_WIDTH - 3),
+ DEFAULT_SIZE * WORD_WIDTH - 2);
+
+ // set (N-1)th bit
+ bitmap_unset (bitmap, DEFAULT_SIZE * WORD_WIDTH - 2);
+ bitmap_set (bitmap, DEFAULT_SIZE * WORD_WIDTH - 1);
+ EXPECT_TRUE (bitmap_is_set (bitmap, DEFAULT_SIZE * WORD_WIDTH - 1));
+ EXPECT_EQ (bitmap_next_set (bitmap, DEFAULT_SIZE * WORD_WIDTH - 2),
+ DEFAULT_SIZE * WORD_WIDTH - 1);
+ EXPECT_EQ (bitmap_next_set (bitmap, DEFAULT_SIZE * WORD_WIDTH - 1),
+ DEFAULT_SIZE * WORD_WIDTH - 1);
+
+ bitmap_free (bitmap);
+}
+
+TEST_F (BitmapTest, BitmapNextUnSet)
+{
+ bitmap_init (bitmap, DEFAULT_SIZE, 0);
+
+ // Get next unset bit >= 0. It should be 0
+ EXPECT_EQ (bitmap_next_unset (bitmap, 0), hicn_uword (0));
+
+ // set bit 0
+ bitmap_set (bitmap, 0);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 0));
+
+ // Get next set bit >= 0. It should be bit 1
+ EXPECT_EQ (bitmap_next_unset (bitmap, 0), hicn_uword (1));
+
+ // set bit 3
+ bitmap_set (bitmap, 3);
+ EXPECT_TRUE (bitmap_is_set (bitmap, 3));
+
+ // Get next unset bit after 3. It should be 4
+ EXPECT_EQ (bitmap_next_unset (bitmap, 3), hicn_uword (4));
+
+ bitmap_free (bitmap);
+}
diff --git a/lib/src/test/test_interest_manifest.cc b/lib/src/test/test_interest_manifest.cc
new file mode 100644
index 000000000..25ac83728
--- /dev/null
+++ b/lib/src/test/test_interest_manifest.cc
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+
+extern "C"
+{
+#include <hicn/interest_manifest.h>
+}
+
+static constexpr hicn_uword WORD_SIZE = WORD_WIDTH;
+
+class InterestManifestTest : public ::testing::Test
+{
+protected:
+ static constexpr u32 n_suffixes = 0x00000014 + 1;
+ static constexpr u32 padding = 0x21232425;
+ static constexpr hicn_uword bitmap_word = ~0ULL;
+ static inline std::vector<uint32_t> values = { 10, 22, 23, 43, 54, 65, 66,
+ 4, 33, 2, 44, 99, 87, 67,
+ 78, 98, 76, 1, 7, 123 };
+ InterestManifestTest () {}
+ virtual ~InterestManifestTest () {}
+
+ uint8_t buffer[512];
+ hicn_uword bitmap_saved[BITMAP_SIZE];
+};
+
+TEST_F (InterestManifestTest, OneWordBitmapUpdate)
+{
+ hicn_uword initial_bitmap[1];
+ hicn_uword curr_bitmap[1] = { 0 };
+ initial_bitmap[0] =
+ 0x0000000000000b07; // ...000000000000000000000101100000111
+
+ // Consume first 4 'one' bits (i.e. suffixes), reaching position 9
+ size_t pos = 0, max_suffixes = 4;
+ pos = interest_manifest_update_bitmap (initial_bitmap, curr_bitmap, pos,
+ WORD_SIZE, max_suffixes);
+ EXPECT_EQ (pos, std::size_t (9));
+ EXPECT_EQ (curr_bitmap[0], hicn_uword (0x0000000000000107));
+
+ // Consume the remaining 2 'one' bits, reaching end of bitmap
+ hicn_uword curr_bitmap2[1] = { 0 };
+ pos = interest_manifest_update_bitmap (initial_bitmap, curr_bitmap2, pos,
+ WORD_SIZE, max_suffixes);
+ EXPECT_EQ (pos, WORD_SIZE);
+ EXPECT_EQ (curr_bitmap2[0], hicn_uword (0x00000a00));
+
+ // Consume all suffixes at once
+ hicn_uword curr_bitmap3[1] = { 0 };
+ max_suffixes = 16;
+ pos = interest_manifest_update_bitmap (initial_bitmap, curr_bitmap3, 0,
+ WORD_SIZE, max_suffixes);
+ EXPECT_EQ (pos, WORD_SIZE);
+ EXPECT_EQ (curr_bitmap3[0], initial_bitmap[0]);
+}
+
+TEST_F (InterestManifestTest, TwoWordBitmapUpdate)
+{
+ hicn_uword initial_bitmap[2];
+ initial_bitmap[0] = 0x0000000000000b07;
+ initial_bitmap[1] = 0x0000000000000b07;
+ // -> 0000000000000000000010110000011100000000000000000000101100000111
+
+ int expected_pos[] = { WORD_SIZE + 2, 2 * WORD_SIZE };
+ u32 expected_bitmap[][2] = { { 0x00000b07, 0x00000003 },
+ { 0x0, 0x00000b04 } };
+
+ // Loop to consume all suffixes
+ int pos = 0, max_suffixes = 8, i = 0, len = WORD_SIZE * 2;
+ while (pos != len)
+ {
+ hicn_uword curr_bitmap[2] = { 0 };
+ pos = interest_manifest_update_bitmap (initial_bitmap, curr_bitmap, pos,
+ len, max_suffixes);
+
+ EXPECT_EQ (pos, expected_pos[i]);
+ EXPECT_EQ (curr_bitmap[0], expected_bitmap[i][0]);
+ EXPECT_EQ (curr_bitmap[1], expected_bitmap[i][1]);
+ i++;
+ }
+}
+
+TEST_F (InterestManifestTest, SerializeDeserialize)
+{
+#if hicn_uword_bits == 64
+#define F(x) hicn_host_to_net_64 (x)
+#elif hicn_uword_bits == 32
+#define F(x) hicn_host_to_net_32 (x)
+#else
+#error "Unrecognized architecture"
+#endif
+
+ auto header = reinterpret_cast<interest_manifest_header_t *> (buffer);
+ interest_manifest_init (header, 0);
+
+ for (const auto &v : values)
+ {
+ interest_manifest_add_suffix (header, v);
+ }
+
+ EXPECT_EQ (header->n_suffixes, n_suffixes);
+
+ // Save bitmap
+ memcpy (bitmap_saved, header->request_bitmap, sizeof (bitmap_saved));
+
+ // Serialize manifest
+ interest_manifest_serialize (header);
+
+ // If architecture is little endian, bytes should be now swapped
+ EXPECT_THAT (header->n_suffixes, ::testing::Eq (hicn_host_to_net_32 (
+ n_suffixes) /* 0x14000000 */));
+
+ for (unsigned i = 0; i < BITMAP_SIZE; i++)
+ {
+ EXPECT_THAT (header->request_bitmap[i],
+ ::testing::Eq (F (bitmap_saved[i])));
+ }
+
+ hicn_name_suffix_t *suffix = (hicn_name_suffix_t *) (header + 1);
+ for (unsigned i = 0; i < n_suffixes; i++)
+ {
+ if (i == 0)
+ {
+ EXPECT_THAT (*(suffix + i), ::testing::Eq (hicn_name_suffix_t (0)));
+ }
+ else
+ {
+ EXPECT_THAT (*(suffix + i),
+ ::testing::Eq (hicn_host_to_net_32 (values[i - 1])));
+ }
+ }
+
+ // Deserialize manifest
+ interest_manifest_deserialize (header);
+
+ // Bytes should now be as before
+ EXPECT_THAT (header->n_suffixes, ::testing::Eq (n_suffixes));
+
+ int i = 0;
+ unsigned long pos;
+ interest_manifest_foreach_suffix (header, suffix, pos)
+ {
+ if (pos == 0)
+ {
+ EXPECT_THAT (*suffix, ::testing::Eq (hicn_name_suffix_t (0)));
+ }
+ else
+ {
+ EXPECT_THAT (*suffix, ::testing::Eq (values[i]));
+ i++;
+ }
+ }
+}
+
+TEST_F (InterestManifestTest, ForEach)
+{
+ unsigned long pos;
+ hicn_name_suffix_t *suffix = nullptr;
+ auto header = reinterpret_cast<interest_manifest_header_t *> (buffer);
+ interest_manifest_init (header, 0);
+
+ for (const auto &v : values)
+ {
+ interest_manifest_add_suffix (header, v);
+ }
+
+ // Iterate over interest manifest. bBbitmap should be all 1, we should be
+ // able to iterate over all suffixes.
+ interest_manifest_foreach_suffix (header, suffix, pos)
+ {
+ if (pos == 0)
+ {
+ EXPECT_EQ (*suffix, hicn_name_suffix_t (0));
+ }
+ else
+ {
+ EXPECT_EQ (*suffix, values[pos - 1]);
+ }
+ }
+
+ std::set<uint32_t> set_values (values.begin (), values.end ());
+
+ // Unset few bitmap positions
+ interest_manifest_del_suffix (header, 5 + 1);
+ set_values.erase (values[5]);
+
+ interest_manifest_del_suffix (header, 6 + 1);
+ set_values.erase (values[6]);
+
+ interest_manifest_del_suffix (header, 12 + 1);
+ set_values.erase (values[12]);
+
+ interest_manifest_del_suffix (header, 17 + 1);
+ set_values.erase (values[17]);
+
+ // Iterate over interest manifest and remove elements in manifest from set.
+ // The set should be empty at the end.
+ interest_manifest_foreach_suffix (header, suffix, pos)
+ {
+ if (pos > 0)
+ {
+ EXPECT_TRUE (set_values.find (*suffix) != set_values.end ())
+ << "The value was " << *suffix;
+ set_values.erase (*suffix);
+ }
+ }
+
+ EXPECT_TRUE (set_values.empty ());
+} \ No newline at end of file
diff --git a/lib/src/test/test_ip_address.cc b/lib/src/test/test_ip_address.cc
new file mode 100644
index 000000000..1a7efb603
--- /dev/null
+++ b/lib/src/test/test_ip_address.cc
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+extern "C"
+{
+#define WITH_TESTS
+#include <hicn/util/ip_address.h>
+}
+
+#define DEFAULT_SIZE 10
+
+class IPAddressTest : public ::testing::Test
+{
+protected:
+ IPAddressTest () {}
+
+ virtual ~IPAddressTest () {}
+};
+
+TEST_F (IPAddressTest, IPAddressGetBit)
+{
+ hicn_ip_address_t a_0, a_1, a_1_0, a_1_1, a_1_48, a_1_49, a_1_63, a_1_64,
+ a_1_127;
+
+ hicn_ip_address_pton ("0::0", &a_0);
+ hicn_ip_address_pton ("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", &a_1);
+
+ hicn_ip_address_pton ("8000::0", &a_1_0);
+ hicn_ip_address_pton ("4000::0", &a_1_1);
+ hicn_ip_address_pton ("0:0:0:8000::0", &a_1_48);
+ hicn_ip_address_pton ("0:0:0:4000::0", &a_1_49);
+ hicn_ip_address_pton ("0:0:0:1::0", &a_1_63);
+ hicn_ip_address_pton ("0::8000:0:0:0", &a_1_64);
+ hicn_ip_address_pton ("0::1", &a_1_127);
+
+#if 0
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_0, i), 0);
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1, i), 1);
+#endif
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1_0, i), (i == 0) ? 1 : 0);
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1_1, i), (i == 1) ? 1 : 0);
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1_48, i), (i == 48) ? 1 : 0);
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1_49, i), (i == 49) ? 1 : 0);
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1_63, i), (i == 63) ? 1 : 0);
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1_64, i), (i == 64) ? 1 : 0);
+ for (unsigned i = 0; i < 128; i++)
+ EXPECT_EQ (hicn_ip_address_get_bit (&a_1_127, i), (i == 127) ? 1 : 0);
+}
diff --git a/lib/src/test/test_khash.cc b/lib/src/test/test_khash.cc
new file mode 100644
index 000000000..da6b62071
--- /dev/null
+++ b/lib/src/test/test_khash.cc
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C"
+{
+#include <hicn/util/khash.h>
+}
+
+KHASH_MAP_INIT_INT (int, unsigned char)
+
+typedef struct
+{
+ unsigned key;
+ unsigned char val;
+} int_unpack_t;
+
+typedef struct
+{
+ unsigned key;
+ unsigned char val;
+} __attribute__ ((__packed__)) int_packed_t;
+
+#define hash_eq(a, b) ((a).key == (b).key)
+#define hash_func(a) ((a).key)
+
+KHASH_INIT (iun, int_unpack_t, char, 0, hash_func, hash_eq)
+KHASH_INIT (ipk, int_packed_t, char, 0, hash_func, hash_eq)
+
+class KHashTest : public ::testing::Test
+{
+protected:
+ KHashTest () {}
+
+ virtual ~KHashTest ()
+ {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void
+ SetUp ()
+ {
+ khash = kh_init (int);
+ }
+
+ virtual void
+ TearDown ()
+ {
+ kh_destroy (int, khash);
+ }
+ khash_t (int) * khash;
+};
+
+TEST_F (KHashTest, KhashIntSize)
+{
+ int ret;
+ int k;
+ int size = kh_size (khash);
+
+ EXPECT_EQ (size, 0);
+ k = kh_put (int, khash, 10, &ret);
+ if (ret == 1)
+ {
+ kh_val (khash, k) = 10;
+ }
+ size = kh_size (khash);
+ EXPECT_EQ (size, 1);
+}
+
+TEST_F (KHashTest, KhashIntPut)
+{
+ int ret;
+ int k;
+ k = kh_put (int, khash, 10, &ret);
+ if (ret == 1)
+ {
+ kh_val (khash, k) = 10;
+ }
+ int size = kh_size (khash);
+ EXPECT_EQ (size, 1);
+ k = kh_put (int, khash, 20, &ret);
+ if (ret == 1)
+ {
+ kh_val (khash, k) = 20;
+ }
+ size = kh_size (khash);
+ EXPECT_EQ (size, 2);
+}
+
+TEST_F (KHashTest, KhashCheckValue)
+{
+ int ret;
+ int k;
+ k = kh_put (int, khash, 10, &ret);
+ if (ret == 1)
+ {
+ kh_val (khash, k) = 100;
+ }
+ k = kh_put (int, khash, 20, &ret);
+ if (ret == 1)
+ {
+ kh_val (khash, k) = 200;
+ }
+
+ k = kh_put (int, khash, 10, &ret);
+ int val = -1;
+ if (!ret)
+ val = kh_val (khash, k);
+ EXPECT_EQ (val, 100);
+
+ k = kh_put (int, khash, 20, &ret);
+ val = -1;
+ if (!ret)
+ val = kh_val (khash, k);
+ EXPECT_EQ (val, 200);
+}
+
+// Check that there are no collisions in case of same key hash
+typedef struct
+{
+ int x;
+} Key;
+#define hash_key(key) 1 // Hash is always 1 to simulate collisions
+#define key_hash_eq(a, b) (a->x == b->x) // Function used in case of collisions
+KHASH_INIT (test_map, const Key *, unsigned, 1, hash_key, key_hash_eq);
+
+TEST_F (KHashTest, Collisions)
+{
+ int ret;
+ khiter_t k;
+
+ kh_test_map_t *map = kh_init (test_map);
+ Key key1 = { .x = 10 };
+ Key key2 = { .x = 11 };
+
+ k = kh_put_test_map (map, &key1, &ret);
+ ASSERT_EQ (ret, 1);
+ kh_val (map, k) = 15u;
+
+ k = kh_put_test_map (map, &key2, &ret);
+ ASSERT_EQ (ret, 1);
+ kh_val (map, k) = 27u;
+
+ k = kh_get_test_map (map, &key1);
+ ASSERT_NE (k, kh_end (map));
+ unsigned val = kh_val (map, k);
+ EXPECT_EQ (val, 15u);
+
+ k = kh_get_test_map (map, &key2);
+ ASSERT_NE (k, kh_end (map));
+ val = kh_val (map, k);
+ EXPECT_EQ (val, 27u);
+
+ kh_destroy_test_map (map);
+}
diff --git a/lib/src/test/test_name.cc b/lib/src/test/test_name.cc
new file mode 100644
index 000000000..0cf160f70
--- /dev/null
+++ b/lib/src/test/test_name.cc
@@ -0,0 +1,401 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C"
+{
+#include <hicn/name.h>
+#include <hicn/common.h>
+#include <hicn/error.h>
+}
+
+class NameTest : public ::testing::Test
+{
+protected:
+ const char *ipv6_prefix = "b001::abcd:1234:abcd:1234";
+ const char *ipv4_prefix = "12.13.14.15";
+ const uint32_t suffix = 12345;
+
+ NameTest () : name_{}, name4_{}, name6_{}
+ {
+ ipv6_prefix_bytes = {};
+ int rc = inet_pton (AF_INET6, ipv6_prefix, &ipv6_prefix_bytes.v6);
+ EXPECT_EQ (rc, 1);
+
+ ipv4_prefix_bytes = {};
+ rc = inet_pton (AF_INET, ipv4_prefix, &ipv4_prefix_bytes.v4);
+ EXPECT_EQ (rc, 1);
+
+ rc = hicn_name_create (ipv4_prefix, suffix, &name4_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_name_create (ipv6_prefix, suffix, &name6_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ }
+
+ virtual ~NameTest () {}
+
+ void
+ nameHashTest (const char *prefix)
+ {
+ // Create 2 names
+ uint32_t suffix = 13579;
+ hicn_name_t name_a, name_b;
+ int rc = hicn_name_create (prefix, suffix, &name_a);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_name_create (prefix, suffix, &name_b);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // The hash should be equal, with and without considering the suffix
+ uint32_t hash_a, hash_b;
+ hash_a = hicn_name_get_hash (&name_a);
+ hash_b = hicn_name_get_hash (&name_b);
+ EXPECT_EQ (hash_a, hash_b);
+
+ hash_a = hicn_name_get_prefix_hash (&name_a);
+ hash_b = hicn_name_get_prefix_hash (&name_b);
+ EXPECT_EQ (hash_a, hash_b);
+
+ // Now let's change the suffix
+ rc = hicn_name_set_suffix (&name_a, 97531);
+ // They should result equal if we do not consider the suffix
+ hash_a = hicn_name_get_prefix_hash (&name_a);
+ hash_b = hicn_name_get_prefix_hash (&name_b);
+ EXPECT_EQ (hash_a, hash_b);
+
+ // And different if we consider it
+ hash_a = hicn_name_get_hash (&name_a);
+ hash_b = hicn_name_get_hash (&name_b);
+ EXPECT_NE (hash_a, hash_b);
+ }
+
+ void
+ nameCopyTest (const char *prefix)
+ {
+ uint32_t suffix = 13579;
+ hicn_name_t name_a, name_b;
+ int rc = hicn_name_create (prefix, suffix, &name_a);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_name_copy (&name_b, &name_a);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_name_compare (&name_a, &name_b, 1);
+ EXPECT_EQ (rc, 0);
+ }
+
+ void
+ nameCompareTest (const char *prefix)
+ {
+ // Create 2 names
+ uint32_t suffix = 13579;
+ hicn_name_t name_a, name_b;
+ int rc = hicn_name_create (prefix, suffix, &name_a);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_name_create (prefix, suffix, &name_b);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // They should be equal, with and without considering the suffix
+ rc = hicn_name_compare (&name_a, &name_b, 1);
+ EXPECT_EQ (rc, 0);
+ rc = hicn_name_compare (&name_a, &name_b, 0);
+ EXPECT_EQ (rc, 0);
+
+ // Now let's change the suffix
+ rc = hicn_name_set_suffix (&name_a, 97531);
+ // They should result equal if we do not consider the suffix
+ rc = hicn_name_compare (&name_a, &name_b, 0);
+ EXPECT_EQ (rc, 0);
+ // And different if we consider the suffix
+ rc = hicn_name_compare (&name_a, &name_b, 1);
+ EXPECT_NE (rc, 0);
+ }
+
+ void
+ nameFromIpPrefixTest (const hicn_ip_prefix_t &hicn_ip_prefix)
+ {
+ uint32_t suffix = 54321;
+ hicn_name_t name;
+ int rc = hicn_name_create_from_ip_prefix (&hicn_ip_prefix, suffix, &name);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = memcmp (hicn_ip_prefix.address.v6.as_u8, name.prefix.v6.as_u8,
+ sizeof (name.prefix.v6));
+ EXPECT_EQ (rc, 0);
+ EXPECT_EQ (suffix, name.suffix);
+ }
+
+ void
+ nameToIpPrefixTest (const char *prefix)
+ {
+ uint32_t suffix = 54321;
+ hicn_name_t name;
+ int rc = hicn_name_create (prefix, suffix, &name);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Get family
+ int family;
+ rc = hicn_name_get_family (&name, &family);
+
+ hicn_ip_prefix_t hicn_ip_prefix;
+ rc = hicn_name_to_hicn_ip_prefix (&name, &hicn_ip_prefix);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hicn_ip_prefix.family, family);
+ rc = hicn_ip_address_cmp (&hicn_ip_prefix.address, &name.prefix);
+ EXPECT_EQ (rc, 0);
+ }
+
+ hicn_name_t name_, name4_, name6_;
+ hicn_ip_address_t ipv6_prefix_bytes, ipv4_prefix_bytes;
+};
+
+/**
+ * Name Initialization
+ */
+TEST_F (NameTest, NameInitialization)
+{
+ EXPECT_TRUE (_is_unspec (&name_));
+ uint32_t suffix = 12345;
+
+ // Initialize ipv6 name
+ hicn_name_t name6;
+ int rc = hicn_name_create (ipv6_prefix, suffix, &name6);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Check name is correctly created
+ rc = hicn_ip_address_cmp (&name6.prefix, &ipv6_prefix_bytes);
+ EXPECT_EQ (rc, 0);
+ EXPECT_EQ (name6.suffix, suffix);
+
+ // Initialize ipv4 name
+ hicn_name_t name4;
+ rc = hicn_name_create (ipv4_prefix, suffix, &name4);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Check name is correctly created
+ rc = hicn_ip_address_cmp (&name4.prefix, &ipv4_prefix_bytes);
+ EXPECT_EQ (name4.prefix.pad[0], 0UL);
+ EXPECT_EQ (name4.prefix.pad[1], 0UL);
+ EXPECT_EQ (name4.prefix.pad[2], 0UL);
+ EXPECT_EQ (rc, 0);
+ EXPECT_EQ (name4.suffix, suffix);
+
+ // Try also to reuse previously initialized name
+ rc = hicn_name_create (ipv4_prefix, suffix, &name6);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Check name is correctly created
+ rc = hicn_ip_address_cmp (&name6.prefix, &ipv4_prefix_bytes);
+ EXPECT_EQ (name6.prefix.pad[0], 0UL);
+ EXPECT_EQ (name6.prefix.pad[1], 0UL);
+ EXPECT_EQ (name6.prefix.pad[2], 0UL);
+ EXPECT_EQ (rc, 0);
+ EXPECT_EQ (name6.suffix, suffix);
+}
+
+/**
+ * Name from ip prefix
+ */
+TEST_F (NameTest, NameFromIpPrefix6)
+{
+ hicn_ip_prefix_t hicn_ip_prefix = { .family = AF_INET6,
+ .address = {},
+ .len = 64 };
+
+ hicn_ip_prefix.address.v6.as_u64[0] = ipv6_prefix_bytes.v6.as_u64[0];
+ hicn_ip_prefix.address.v6.as_u64[1] = ipv6_prefix_bytes.v6.as_u64[1];
+
+ nameFromIpPrefixTest (hicn_ip_prefix);
+}
+
+TEST_F (NameTest, NameFromIpPrefix4)
+{
+ hicn_ip_prefix_t hicn_ip_prefix = { .family = AF_INET,
+ .address = {},
+ .len = 64 };
+ hicn_ip_prefix.address.v4.as_u32 = ipv4_prefix_bytes.v4.as_u32;
+ hicn_ip_prefix.address.pad[0] = 0;
+ hicn_ip_prefix.address.pad[1] = 0;
+ hicn_ip_prefix.address.pad[2] = 0;
+ nameFromIpPrefixTest (hicn_ip_prefix);
+}
+
+TEST_F (NameTest, NameCompare6) { nameCompareTest (ipv6_prefix); }
+
+TEST_F (NameTest, NameCompare4) { nameCompareTest (ipv4_prefix); }
+
+TEST_F (NameTest, NameHash6) { nameHashTest (ipv6_prefix); }
+
+TEST_F (NameTest, NameHash4) { nameHashTest (ipv4_prefix); }
+
+TEST_F (NameTest, NameEmpty)
+{
+ int rc = hicn_name_empty (&name_);
+ EXPECT_EQ (rc, 1);
+
+ name_.prefix.v6 = ipv6_prefix_bytes.v6;
+ rc = hicn_name_empty (&name_);
+ EXPECT_EQ (rc, 0);
+}
+
+TEST_F (NameTest, NameCopy6) { nameCopyTest (ipv6_prefix); }
+
+TEST_F (NameTest, NameCopy4) { nameCopyTest (ipv4_prefix); }
+
+TEST_F (NameTest, NameCopyToDestination)
+{
+ ipv4_address_t dst4;
+ ipv6_address_t dst6;
+
+ // Copy names to destination
+ int rc = hicn_name_copy_prefix_to_destination (dst4.as_u8, &name4_);
+ EXPECT_EQ (rc, 0);
+ rc = hicn_name_copy_prefix_to_destination (dst6.as_u8, &name6_);
+ EXPECT_EQ (rc, 0);
+
+ // Check copy succeeded
+ EXPECT_TRUE (dst4.as_u32 == name4_.prefix.v4.as_u32);
+ EXPECT_TRUE (dst6.as_u64[0] == name6_.prefix.v6.as_u64[0]);
+ EXPECT_TRUE (dst6.as_u64[1] == name6_.prefix.v6.as_u64[1]);
+}
+
+TEST_F (NameTest, SetGetSuffix)
+{
+ uint32_t suffix2 = 55555, suffix_ret;
+
+ // Check if suffix is correct
+ int rc = hicn_name_get_seq_number (&name6_, &suffix_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (suffix, suffix_ret);
+
+ // Set new suffix
+ rc = hicn_name_set_suffix (&name6_, suffix2);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Check suffix was set
+ rc = hicn_name_get_seq_number (&name6_, &suffix_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (suffix2, suffix_ret);
+}
+
+TEST_F (NameTest, NameToSockAddr)
+{
+ struct sockaddr_in saddr4;
+ struct sockaddr_in6 saddr6;
+
+ int rc =
+ hicn_name_to_sockaddr_address (&name6_, (struct sockaddr *) (&saddr6));
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = memcmp (name6_.prefix.v6.as_u8, saddr6.sin6_addr.s6_addr,
+ sizeof (name6_.prefix.v6));
+ EXPECT_EQ (rc, 0);
+
+ rc = hicn_name_to_sockaddr_address (&name4_, (struct sockaddr *) (&saddr4));
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (name4_.prefix.v4.as_u32, saddr4.sin_addr.s_addr);
+}
+
+TEST_F (NameTest, NameToIpPrefix)
+{
+ nameToIpPrefixTest (ipv4_prefix);
+ nameToIpPrefixTest (ipv6_prefix);
+}
+
+TEST_F (NameTest, NameNToP)
+{
+ char dst[128];
+
+ // V6
+ int rc = hicn_name_ntop (&name6_, dst, 128);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Build expected name
+ std::stringstream expected6;
+ expected6 << ipv6_prefix << "|" << suffix;
+
+ rc = strcmp (dst, expected6.str ().c_str ());
+ EXPECT_EQ (rc, 0);
+
+ // V4
+ rc = hicn_name_ntop (&name4_, dst, 128);
+ std::stringstream expected4;
+ expected4 << ipv4_prefix << "|" << suffix;
+
+ rc = strcmp (dst, expected4.str ().c_str ());
+ EXPECT_EQ (rc, 0);
+}
+
+class PrefixTest : public ::testing::Test
+{
+protected:
+ PrefixTest () {}
+
+ virtual ~PrefixTest () {}
+};
+
+#define HICN_PREFIX(P, STR) \
+ hicn_prefix_t P; \
+ hicn_ip_prefix_t _##P; \
+ EXPECT_EQ (hicn_ip_prefix_pton (STR, &_##P), 0); \
+ EXPECT_EQ (hicn_prefix_create_from_ip_prefix (&_##P, &P), 0);
+
+TEST_F (PrefixTest, PrefixClear)
+{
+ HICN_PREFIX (hp_all, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128");
+
+ for (unsigned i = 0; i < 127; i++)
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, i), 1);
+
+ hicn_prefix_truncate (&hp_all, 127);
+ EXPECT_EQ (hicn_prefix_get_len (&hp_all), 127);
+
+ for (unsigned i = 0; i < 126; i++)
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, i), 1) << "bit[" << i << "] != 1";
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, 127), 0);
+
+ hicn_prefix_truncate (&hp_all, 126);
+ EXPECT_EQ (hicn_prefix_get_len (&hp_all), 126);
+
+ for (unsigned i = 0; i < 125; i++)
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, i), 1);
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, 126), 0);
+ EXPECT_EQ (_hicn_prefix_get_bit (&hp_all, 127), 0);
+}
+
+TEST_F (PrefixTest, PrefixClear2)
+{
+ HICN_PREFIX (hp_all, "b002::3");
+
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, 125), 0);
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, 126), 1);
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, 127), 1);
+
+ hicn_prefix_truncate (&hp_all, 127);
+ EXPECT_EQ (hicn_prefix_get_len (&hp_all), 127);
+
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, 125), 0);
+ EXPECT_EQ (hicn_prefix_get_bit (&hp_all, 126), 1);
+ EXPECT_EQ (_hicn_prefix_get_bit (&hp_all, 127), 0);
+}
+
+TEST_F (PrefixTest, PrefixLPM)
+{
+ HICN_PREFIX (b007, "b007::/64");
+ HICN_PREFIX (b009, "b009::/64");
+
+ EXPECT_EQ (hicn_prefix_lpm (&b007, &b009), (uint32_t) 12);
+
+ HICN_PREFIX (pfx, "1122:3344:5566:7788:9900:aabb:ccdd:eeff/128");
+ EXPECT_EQ (hicn_prefix_lpm (&pfx, &pfx), (uint32_t) 128);
+}
diff --git a/lib/src/test/test_new_header.cc b/lib/src/test/test_new_header.cc
new file mode 100644
index 000000000..c936b6910
--- /dev/null
+++ b/lib/src/test/test_new_header.cc
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C"
+{
+#include <hicn/name.h>
+#include <hicn/common.h>
+#include <hicn/error.h>
+#include <hicn/packet.h>
+
+#include "../protocol/ah.h"
+#include "../protocol/new.h"
+}
+
+class NewHeaderTest : public ::testing::Test
+{
+protected:
+ const char *ipv6_prefix = "b001::abcd:1234:abcd:1234";
+ const char *ipv4_prefix = "12.13.14.15";
+ const uint32_t suffix = 12345;
+
+ NewHeaderTest (hicn_packet_format_t format)
+ : buffer_ (new uint8_t[NEW_HDRLEN]),
+ format_ (format), name_{}, name4_{}, name6_{}
+ {
+
+ int rc = inet_pton (AF_INET6, ipv6_prefix, &ipv6_prefix_bytes.v6);
+ EXPECT_EQ (rc, 1);
+
+ rc = inet_pton (AF_INET, ipv4_prefix, &ipv4_prefix_bytes.v4);
+ EXPECT_EQ (rc, 1);
+
+ rc = hicn_name_create (ipv4_prefix, suffix, &name4_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_name_create (ipv6_prefix, suffix, &name6_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ }
+
+ NewHeaderTest () : NewHeaderTest (HICN_PACKET_FORMAT_NEW) {}
+
+ virtual ~NewHeaderTest () { delete[] buffer_; }
+
+ void
+ checkCommon ()
+ {
+ // Initialize header
+ hicn_packet_set_format (&pkbuf_, format_);
+ // pkbuf_set_type (&pkbuf_, HICN_PACKET_TYPE_UNDEFINED);
+ int rc = hicn_packet_init_header (&pkbuf_, 0);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ auto new_hdr = (_new_header_t *) buffer_;
+
+ // Check fields
+ EXPECT_EQ (new_hdr->prefix.v6.as_u64[0], 0UL);
+ EXPECT_EQ (new_hdr->prefix.v6.as_u64[1], 0UL);
+ EXPECT_EQ (new_hdr->suffix, 0UL);
+ EXPECT_EQ (new_hdr->lifetime, 0UL);
+ EXPECT_EQ (new_hdr->path_label, 0UL);
+ EXPECT_EQ (new_hdr->payload_len, 0UL);
+ EXPECT_EQ (_get_new_header_version (new_hdr), 0x9);
+ EXPECT_EQ (new_hdr->flags, 0);
+ }
+
+ virtual void
+ SetUp () override
+ {
+ checkCommon ();
+ }
+
+ uint8_t *buffer_;
+ hicn_packet_buffer_t pkbuf_;
+ hicn_packet_format_t format_;
+ hicn_name_t name_, name4_, name6_;
+ hicn_ip_address_t ipv6_prefix_bytes, ipv4_prefix_bytes;
+};
+
+#if 0
+class NewHeaderAHTest : public NewHeaderTest
+{
+protected:
+ NewHeaderAHTest () : NewHeaderTest (NEW_HDRLEN + AH_HDRLEN, HF_NEW_AH) {}
+
+ virtual void
+ SetUp () override
+ {
+ auto new_hdr = &header_->protocol.newhdr;
+ checkCommon (new_hdr);
+ EXPECT_NE (new_hdr->flags, 0);
+ }
+};
+
+/**
+ * Header Initialization
+ */
+TEST_F (NewHeaderTest, GetFormat)
+{
+ // Get format from existing packet
+ hicn_format_t format;
+ int rc = hicn_packet_get_format (header_, &format);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Check it corresponds to the new header format
+ EXPECT_EQ (format, HF_NEW);
+}
+
+TEST_F (NewHeaderAHTest, GetFormat)
+{
+ // Get format from existing packet
+ hicn_format_t format;
+ int rc = hicn_packet_get_format (header_, &format);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Check it corresponds to the new header format
+ EXPECT_EQ (format, HF_NEW_AH);
+}
+
+/**
+ * @brief Checksum functions are not required, but we keep them for
+ * compatibility.
+ */
+TEST_F (NewHeaderTest, Checksum)
+{
+ // Get format from existing packet
+ int rc = hicn_packet_compute_checksum (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_compute_header_checksum (format_, header_, 0);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_check_integrity_no_payload (format_, header_, 0);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+}
+
+TEST_F (NewHeaderAHTest, Checksum)
+{
+ // Get format from existing packet
+ int rc = hicn_packet_compute_checksum (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_compute_header_checksum (format_, header_, 0);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_check_integrity_no_payload (format_, header_, 0);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+}
+
+TEST_F (NewHeaderTest, GetHeaderLengthFromFormat)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length_from_format (format_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, NEW_HDRLEN);
+}
+
+TEST_F (NewHeaderAHTest, GetHeaderLengthFromFormat)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length_from_format (format_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, NEW_HDRLEN + AH_HDRLEN);
+}
+
+TEST_F (NewHeaderTest, GetHeaderLength)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length (format_, header_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, NEW_HDRLEN);
+}
+
+TEST_F (NewHeaderAHTest, GetHeaderLength)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length (format_, header_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, NEW_HDRLEN + AH_HDRLEN);
+}
+
+TEST_F (NewHeaderTest, SetGetPayloadLength)
+{
+ // Get format from existing packet
+ std::size_t payload_len = 1000, payload_len_ret;
+ int rc = hicn_packet_set_payload_length (format_, header_, payload_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_packet_get_payload_length (format_, header_, &payload_len_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (payload_len, payload_len_ret);
+}
+
+TEST_F (NewHeaderAHTest, SetGetPayloadLength)
+{
+ // Get format from existing packet
+ std::size_t payload_len = 1000, payload_len_ret;
+ int rc = hicn_packet_set_payload_length (format_, header_, payload_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_packet_get_payload_length (format_, header_, &payload_len_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (payload_len, payload_len_ret);
+}
+
+TEST_F (NewHeaderTest, SetGetName)
+{
+ // Get v6 name and set it to new_header
+ hicn_name_t name_ret;
+ int rc = hicn_packet_set_name (format_, header_, &name6_, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_name (format_, header_, &name_ret, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_name_compare (&name6_, &name_ret, 1);
+ EXPECT_EQ (rc, 0);
+}
+
+TEST_F (NewHeaderTest, SetGetLocator)
+{
+ // This function does nothing but it is set for compatibility
+ hicn_ip_address_t locator;
+ memset (&locator, 0, sizeof (locator));
+ locator.v6.as_u8[15] = 1;
+ int rc = hicn_packet_set_interest (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_set_locator (format_, header_, &locator, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_locator (format_, header_, &locator, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+}
+
+TEST_F (NewHeaderTest, SetGetSignatureSize)
+{
+ // No AH, so we should get an error
+ // FixMe no error raised here
+ size_t signature_size = 128;
+ int rc = hicn_packet_set_signature_size (format_, header_, signature_size);
+ (void) rc;
+ // EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Same for hicn_packet_get_signature_size
+ rc = hicn_packet_get_signature_size (format_, header_, &signature_size);
+ // EXPECT_NE (rc, HICN_LIB_ERROR_NONE);
+}
+
+TEST_F (NewHeaderAHTest, SetGetSignatureSize)
+{
+ // No AH, so we should get an error
+ size_t signature_size = 128, signature_size_ret;
+ int rc = hicn_packet_set_signature_size (format_, header_, signature_size);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Same for hicn_packet_get_signature_size
+ rc = hicn_packet_get_signature_size (format_, header_, &signature_size_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (signature_size, signature_size_ret);
+}
+
+TEST_F (NewHeaderTest, IsInterestIsData)
+{
+ // Mark packet as interest
+ int rc = hicn_packet_set_interest (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ int ret;
+ rc = hicn_packet_is_interest (format_, header_, &ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (ret, 1);
+
+ // Mark packet as data
+ rc = hicn_packet_set_data (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_is_interest (format_, header_, &ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (ret, 0);
+}
+
+TEST_F (NewHeaderTest, SetGetLifetime)
+{
+ // Lifetime
+ u32 lifetime = 20000, lifetime_ret; // 20 sec.
+ int rc = hicn_packet_set_lifetime (format_, header_, lifetime);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_lifetime (format_, header_, &lifetime_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (lifetime, lifetime_ret);
+}
+
+TEST_F (NewHeaderAHTest, SetGetLifetime)
+{
+ // Lifetime
+ u32 lifetime = 20000, lifetime_ret; // 20 sec.
+ int rc = hicn_packet_set_lifetime (format_, header_, lifetime);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_lifetime (format_, header_, &lifetime_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (lifetime, lifetime_ret);
+}
+
+TEST_F (NewHeaderTest, SetGetPayloadType)
+{
+ // Lifetime
+ hicn_payload_type_t payload_type = HPT_MANIFEST, payload_type_ret;
+ int rc = hicn_packet_set_payload_type (format_, header_, payload_type);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_payload_type (format_, header_, &payload_type_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (payload_type, payload_type_ret);
+
+ payload_type = HPT_DATA;
+
+ rc = hicn_packet_set_payload_type (format_, header_, payload_type);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_payload_type (format_, header_, &payload_type_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (payload_type, payload_type_ret);
+}
+#endif
diff --git a/lib/src/test/test_pool.cc b/lib/src/test/test_pool.cc
new file mode 100644
index 000000000..cbb5ce068
--- /dev/null
+++ b/lib/src/test/test_pool.cc
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C"
+{
+#define WITH_TESTS
+#include <hicn/util/pool.h>
+}
+
+/*
+ * TODO
+ * - test max_size
+ */
+
+#define DEFAULT_SIZE 10
+
+class PoolTest : public ::testing::Test
+{
+protected:
+ PoolTest () {}
+ virtual ~PoolTest () {}
+
+ int *pool;
+};
+
+TEST_F (PoolTest, PoolAllocation)
+{
+ int rc;
+
+ pool_init (pool, DEFAULT_SIZE, 0);
+
+ size_t pool_size = next_pow2 (DEFAULT_SIZE);
+
+ EXPECT_EQ (pool_get_alloc_size (pool), pool_size);
+
+ /* Check that free indices and bitmaps are correctly initialize */
+ off_t *fi = pool_get_free_indices (pool);
+ EXPECT_EQ (vector_len (fi), pool_size);
+ EXPECT_EQ (fi[0], (long) (pool_size - 1));
+ EXPECT_EQ (fi[pool_size - 1], 0);
+
+ /* The allocated size of the underlying vector should be the next power of
+ * two
+ */
+ EXPECT_EQ (vector_get_alloc_size (fi), pool_size);
+
+ bitmap_t *fb = pool_get_free_bitmap (pool);
+ EXPECT_TRUE (bitmap_is_set (fb, 0));
+ EXPECT_TRUE (bitmap_is_set (fb, pool_size - 2));
+ EXPECT_TRUE (bitmap_is_set (fb, pool_size - 1));
+ EXPECT_TRUE (bitmap_is_unset (fb, pool_size));
+
+ /* Getting elements from the pool should correctly update the free indices
+ * and bitmap */
+ int *elt;
+
+ rc = pool_get (pool, elt);
+ EXPECT_GE (rc, 0);
+ EXPECT_EQ (vector_len (fi), pool_size - 1);
+ EXPECT_TRUE (bitmap_is_unset (fb, 0));
+
+ rc = pool_get (pool, elt);
+ EXPECT_GE (rc, 0);
+ EXPECT_EQ (vector_len (fi), pool_size - 2);
+ EXPECT_TRUE (bitmap_is_unset (fb, 1));
+
+ for (unsigned i = 0; i < pool_size - 4; i++)
+ {
+ rc = pool_get (pool, elt);
+ EXPECT_GE (rc, 0);
+ }
+
+ rc = pool_get (pool, elt);
+ EXPECT_GE (rc, 0);
+ EXPECT_EQ (vector_len (fi), 1UL);
+ EXPECT_TRUE (bitmap_is_unset (fb, pool_size - 2));
+
+ rc = pool_get (pool, elt);
+ EXPECT_GE (rc, 0);
+ EXPECT_EQ (vector_len (fi), 0UL);
+ EXPECT_TRUE (bitmap_is_unset (fb, pool_size - 1));
+
+ /*
+ * Getting elements within the allocated range should not have triggered a
+ * resize
+ */
+ EXPECT_EQ (pool_len (pool), pool_size);
+
+ /*
+ * Getting elements once the allocated range has been exceeded should
+ * trigger a resize
+ */
+ rc = pool_get (pool, elt);
+ EXPECT_GE (rc, 0);
+
+ EXPECT_EQ (pool_get_alloc_size (pool), pool_size * 2);
+
+ EXPECT_EQ (pool_len (pool), pool_size + 1);
+
+ /*
+ * Doubling the size, we should have again pool_size elements free, minus 1
+ */
+ EXPECT_EQ (pool_get_free_indices_size (pool), pool_size - 1);
+
+ /*
+ * NOTE: this is wrong as there has been a realloc and the old fi
+ * pointer is now invalid
+ */
+ // EXPECT_EQ(vector_len(fi), pool_size - 1);
+
+ /* And the bitmap should also be correctly modified */
+ fb = pool_get_free_bitmap (pool);
+ EXPECT_TRUE (bitmap_is_unset (fb, pool_size));
+
+ /* Check that surrounding values are also correct */
+ EXPECT_TRUE (bitmap_is_unset (fb, pool_size - 1));
+ EXPECT_TRUE (bitmap_is_set (fb, pool_size + 1));
+
+ /* Setting elements after should through */
+
+ /* Check that free indices and bitmaps are correctly updated */
+
+ pool_free (pool);
+}
+
+TEST_F (PoolTest, PoolPut)
+{
+ pool_init (pool, DEFAULT_SIZE, 0);
+
+ int *elt;
+ pool_get (pool, elt);
+ *elt = 10;
+ pool_put (pool, elt);
+
+ pool_free (pool);
+}
+
+TEST_F (PoolTest, PoolGetForceBitmapRealloc)
+{
+ const int N = 64;
+ int *elts[N];
+ int *elt = NULL;
+ pool_init (pool, N, 0);
+
+ for (int i = 0; i < N; i++)
+ pool_get (pool, elts[i]);
+ pool_get (pool, elt);
+
+ pool_free (pool);
+}
+
+TEST_F (PoolTest, PoolGetAfterReleasing)
+{
+ int *elt1 = NULL, *elt2 = NULL, *tmp = NULL;
+ pool_init (pool, DEFAULT_SIZE, 0);
+
+ // If two elements are requested...
+ off_t id1 = pool_get (pool, elt1);
+ pool_get (pool, tmp);
+
+ // ...and the first one is released...
+ pool_put (pool, elt1);
+
+ // ...requesting a new one should return
+ // the first one (that was freed)
+ off_t id2 = pool_get (pool, elt2);
+ EXPECT_EQ (id1, id2);
+ EXPECT_EQ (elt1, elt2);
+
+ pool_free (pool);
+}
+
+TEST_F (PoolTest, PoolGetMultipleElementsAfterReleasing)
+{
+ const int N = 2;
+ int *elts[N];
+ pool_init (pool, N, 0);
+
+ for (int i = 0; i < N; i++)
+ pool_get (pool, elts[i]);
+ for (int i = 0; i < N; i++)
+ pool_put (pool, elts[i]);
+ for (int i = 0; i < N; i++)
+ pool_get (pool, elts[i]);
+
+ pool_free (pool);
+}
diff --git a/lib/src/test/test_ring.cc b/lib/src/test/test_ring.cc
new file mode 100644
index 000000000..f0b0371e8
--- /dev/null
+++ b/lib/src/test/test_ring.cc
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <netinet/in.h>
+
+extern "C"
+{
+#define WITH_TESTS
+#include <hicn/util/ring.h>
+}
+
+#define DEFAULT_SIZE 10UL
+
+class RingTest : public ::testing::Test
+{
+protected:
+ RingTest () { ring_init (ring, DEFAULT_SIZE); }
+ virtual ~RingTest () { ring_free (ring); }
+
+ int *ring = NULL;
+};
+
+/* TEST: Ring allocation and initialization */
+TEST_F (RingTest, RingAddOne)
+{
+ int val = -1;
+ /* Allocated size should be the next power of two */
+ EXPECT_EQ (ring_get_size (ring), 0UL);
+ ring_add_value (ring, 1);
+ EXPECT_EQ (ring_get_size (ring), 1UL);
+ ring_get (ring, 0, &val);
+ EXPECT_EQ (val, 1);
+ EXPECT_EQ (ring_get_size (ring), 1UL);
+ ring_advance (ring, 1);
+ EXPECT_EQ (ring_get_size (ring), 0UL);
+}
+
+TEST_F (RingTest, RingAddMany)
+{
+ size_t i = 0;
+ int val = -1;
+ size_t count = 0;
+
+ /* Allocated size should be the next power of two */
+ EXPECT_EQ (ring_get_size (ring), 0UL);
+ for (unsigned i = 0; i < DEFAULT_SIZE; i++)
+ ring_add_value (ring, i);
+ EXPECT_EQ (ring_get_size (ring), DEFAULT_SIZE);
+
+ count = 0;
+ ring_enumerate_n (ring, i, &val, 1, {
+ EXPECT_EQ (val, (int) (i));
+ count++;
+ });
+ EXPECT_EQ (count, 1UL);
+
+ count = 0;
+ ring_enumerate_n (ring, i, &val, DEFAULT_SIZE, {
+ EXPECT_EQ (val, (int) (i));
+ count++;
+ });
+ EXPECT_EQ (count, DEFAULT_SIZE);
+
+ count = 0;
+ ring_enumerate_n (ring, i, &val, DEFAULT_SIZE + 1, {
+ EXPECT_EQ (val, (int) (i));
+ count++;
+ });
+ EXPECT_EQ (count, DEFAULT_SIZE);
+
+ // Drop one
+ ring_add_value (ring, DEFAULT_SIZE);
+ EXPECT_EQ (ring_get_size (ring), DEFAULT_SIZE);
+
+ count = 0;
+ ring_enumerate_n (ring, i, &val, DEFAULT_SIZE, {
+ EXPECT_EQ (val, (int) (i + 1)); // all values shoud be shifted
+ count++;
+ });
+ EXPECT_EQ (count, DEFAULT_SIZE);
+
+ ring_advance (ring, DEFAULT_SIZE);
+ EXPECT_EQ (ring_get_size (ring), 0UL);
+}
diff --git a/lib/src/test/test_slab.cc b/lib/src/test/test_slab.cc
new file mode 100644
index 000000000..15deff3c1
--- /dev/null
+++ b/lib/src/test/test_slab.cc
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C"
+{
+#include <hicn/util/slab.h>
+}
+
+class SlabTest : public ::testing::Test
+{
+protected:
+ SlabTest () {}
+ virtual ~SlabTest () { slab_free (slab); }
+
+ slab_t *slab;
+};
+
+typedef struct
+{
+ int index;
+ int val;
+} element_t;
+
+TEST_F (SlabTest, SlabCreateAndGetSingleChunk)
+{
+ slab = slab_create (element_t, 16);
+ ASSERT_NE (slab, nullptr);
+
+ element_t *e = slab_get (element_t, slab);
+ ASSERT_NE (e, nullptr);
+ slab_put (slab, e);
+}
+
+TEST_F (SlabTest, SlabGetChunks)
+{
+ slab = slab_create (element_t, 2);
+
+ // Force creation of multiple blocks (since initial size is only 2)
+ for (int i = 0; i < 100; i++)
+ {
+ element_t *e = slab_get (element_t, slab);
+ EXPECT_NE (e, nullptr);
+ }
+}
+
+TEST_F (SlabTest, SlabGetAndPutChunksNoResize)
+{
+ constexpr int NUM_ELEMENTS = 64;
+ element_t *elements[NUM_ELEMENTS];
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ elements[i] = NULL;
+
+ // Initial size=NUM_ELEMENTS, only one block will be created
+ slab = slab_create (element_t, NUM_ELEMENTS);
+
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ {
+ elements[i] = slab_get (element_t, slab);
+ EXPECT_NE (elements[i], nullptr);
+ }
+
+ // Release all chunks
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ slab_put (slab, elements[i]);
+}
+
+TEST_F (SlabTest, SlabGetAndPutChunks)
+{
+ constexpr int NUM_ELEMENTS = 100;
+ element_t *elements[NUM_ELEMENTS];
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ elements[i] = NULL;
+
+ // Initial size=2 while NUM_ELEMENTS=100, to force creation of multiple
+ // blocks
+ slab = slab_create (sizeof (element_t), 2);
+
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ {
+ elements[i] = slab_get (element_t, slab);
+ EXPECT_NE (elements[i], nullptr);
+ }
+
+ // Release all chunks
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ slab_put (slab, elements[i]);
+}
+
+TEST_F (SlabTest, SlabGetAndPutSomeChunks)
+{
+ slab = slab_create (element_t, 2);
+
+ constexpr int NUM_ELEMENTS = 100;
+ element_t *elements[NUM_ELEMENTS];
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ elements[i] = NULL;
+
+ // Get chunks...
+ for (int i = 0; i < NUM_ELEMENTS; i++)
+ {
+ elements[i] = slab_get (element_t, slab);
+ EXPECT_NE (elements[i], nullptr);
+
+ // ...and return only some of them
+ if (i % 5 == 0)
+ slab_put (slab, elements[i]);
+ }
+}
+
+TEST_F (SlabTest, SlabGetSameChunkTwice)
+{
+ slab = slab_create (element_t, 1);
+
+ // Get chunk and update it before returning it
+ element_t *e = slab_get (element_t, slab);
+ ASSERT_NE (e, nullptr);
+ element_t *prev = e;
+ e->index = 2;
+ e->val = 3;
+ slab_put (slab, e);
+
+ // Get a chunk again: it should return the previous one
+ // without wiping its memory
+ e = slab_get (element_t, slab);
+ ASSERT_NE (e, nullptr);
+ EXPECT_EQ (e, prev);
+ EXPECT_EQ (e->index, 2);
+ EXPECT_EQ (e->val, 3);
+
+ // Try to get an additional chunk: it should return a new chunk
+ // (different from previous one)
+ e = slab_get (element_t, slab);
+ EXPECT_NE (e, prev);
+} \ No newline at end of file
diff --git a/lib/src/test/test_udp_header.cc b/lib/src/test/test_udp_header.cc
new file mode 100644
index 000000000..2856c8ebf
--- /dev/null
+++ b/lib/src/test/test_udp_header.cc
@@ -0,0 +1,360 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C"
+{
+#include <hicn/name.h>
+#include <hicn/common.h>
+#include <hicn/error.h>
+#include <hicn/packet.h>
+
+#include "../protocol/ah.h"
+#include "../protocol/ipv6.h"
+#include "../protocol/udp.h"
+#include "../protocol/new.h"
+}
+
+class UdpHeaderTest : public ::testing::Test
+{
+protected:
+ const char *ipv6_prefix = "b001::abcd:1234:abcd:1234";
+ const char *ipv4_prefix = "12.13.14.15";
+ const uint32_t suffix = 12345;
+
+ UdpHeaderTest (size_t hdr_size, hicn_packet_format_t format)
+ : buffer_ (new uint8_t[hdr_size]), hdr_size_ (hdr_size),
+ format_ (format), name_{}, name4_{}, name6_{}
+ {
+ int rc = inet_pton (AF_INET6, ipv6_prefix, &ipv6_prefix_bytes.v6);
+ EXPECT_EQ (rc, 1);
+
+ rc = inet_pton (AF_INET, ipv4_prefix, &ipv4_prefix_bytes.v4);
+ EXPECT_EQ (rc, 1);
+
+ rc = hicn_name_create (ipv4_prefix, suffix, &name4_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_name_create (ipv6_prefix, suffix, &name6_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ }
+
+ UdpHeaderTest ()
+ : UdpHeaderTest (NEW_HDRLEN + UDP_HDRLEN + IPV6_HDRLEN,
+ HICN_PACKET_FORMAT_IPV6_UDP)
+ {
+ }
+
+ virtual ~UdpHeaderTest () { delete[] buffer_; }
+
+ // checked everytime we build the packet...
+ void
+ checkCommon ()
+ {
+ /* Initialize packet buffer headers */
+ hicn_packet_set_format (&pkbuf_, format_);
+ hicn_packet_set_type (&pkbuf_, HICN_PACKET_TYPE_INTEREST);
+ hicn_packet_set_buffer (&pkbuf_, buffer_, hdr_size_, 0);
+ int rc = hicn_packet_init_header (&pkbuf_, 0);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ auto ip6_hdr = (_ipv6_header_t *) buffer_;
+
+ // Check fields
+ EXPECT_EQ (ip6_hdr->saddr.as_u64[0], 0UL);
+ EXPECT_EQ (ip6_hdr->saddr.as_u64[1], 0UL);
+ EXPECT_EQ (ip6_hdr->daddr.as_u64[0], 0UL);
+ EXPECT_EQ (ip6_hdr->daddr.as_u64[1], 0UL);
+ EXPECT_EQ (ip6_hdr->nxt, IPPROTO_UDP);
+
+ _udp_header_t *udp_hdr = (_udp_header_t *) (ip6_hdr + 1);
+ EXPECT_EQ (udp_hdr->src_port, 0UL);
+ EXPECT_EQ (udp_hdr->dst_port, 0UL);
+ EXPECT_EQ (udp_hdr->checksum, 0UL);
+ // EXPECT_EQ (ntohs (udp_hdr->length), NEW_HDRLEN + AH_HDRLEN);
+
+ _new_header_t *new_hdr = (_new_header_t *) (udp_hdr + 1);
+ EXPECT_EQ (new_hdr->prefix.v6.as_u64[0], 0UL);
+ EXPECT_EQ (new_hdr->prefix.v6.as_u64[1], 0UL);
+ EXPECT_EQ (new_hdr->suffix, 0UL);
+ EXPECT_EQ (new_hdr->lifetime, 0UL);
+ EXPECT_EQ (new_hdr->path_label, 0UL);
+ EXPECT_EQ (new_hdr->payload_len, 0UL);
+ EXPECT_EQ (_get_new_header_version (new_hdr), 0x9);
+ }
+
+ virtual void
+ SetUp () override
+ {
+ checkCommon ();
+ }
+
+ uint8_t *buffer_;
+ size_t hdr_size_;
+ hicn_packet_buffer_t pkbuf_;
+ hicn_packet_format_t format_;
+ hicn_name_t name_, name4_, name6_;
+ hicn_ip_address_t ipv6_prefix_bytes, ipv4_prefix_bytes;
+};
+
+class UdpHeaderAHTest : public UdpHeaderTest
+{
+protected:
+ UdpHeaderAHTest ()
+ : UdpHeaderTest (AH_HDRLEN + NEW_HDRLEN + UDP_HDRLEN + IPV6_HDRLEN,
+ HICN_PACKET_FORMAT_IPV6_UDP_AH)
+ {
+ }
+};
+
+/**
+ * Header Initialization
+ */
+TEST_F (UdpHeaderTest, GetFormat)
+{
+ hicn_packet_format_t format = hicn_packet_get_format (&pkbuf_);
+ EXPECT_EQ (format, HICN_PACKET_FORMAT_IPV6_UDP);
+}
+
+TEST_F (UdpHeaderAHTest, GetFormat)
+{
+ // Get format from existing packet
+ hicn_packet_format_t format = hicn_packet_get_format (&pkbuf_);
+
+ // Check it corresponds to the new header format
+ EXPECT_EQ (format, HICN_PACKET_FORMAT_IPV6_UDP_AH);
+}
+
+#if 0
+
+// /**
+// * @brief Checksum functions are not required, but we keep them for
+// * compatibility.
+// */
+// TEST_F (NewHeaderTest, Checksum)
+// {
+// // Get format from existing packet
+// int rc = hicn_packet_compute_checksum (format_, header_);
+// EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+// rc = hicn_packet_compute_header_checksum (format_, header_, 0);
+// EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+// rc = hicn_packet_check_integrity_no_payload (format_, header_, 0);
+// EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+// }
+
+// TEST_F (NewHeaderAHTest, Checksum)
+// {
+// // Get format from existing packet
+// int rc = hicn_packet_compute_checksum (format_, header_);
+// EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+// rc = hicn_packet_compute_header_checksum (format_, header_, 0);
+// EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+// rc = hicn_packet_check_integrity_no_payload (format_, header_, 0);
+// EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+// }
+
+TEST_F (UdpHeaderTest, GetHeaderLengthFromFormat)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length_from_format (format_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, UDP_HDRLEN + IPV6_HDRLEN + NEW_HDRLEN);
+}
+
+TEST_F (UdpHeaderAHTest, GetHeaderLengthFromFormat)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length_from_format (format_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, UDP_HDRLEN + IPV6_HDRLEN + NEW_HDRLEN + AH_HDRLEN);
+}
+
+TEST_F (UdpHeaderTest, GetHeaderLength)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length (format_, header_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, UDP_HDRLEN + IPV6_HDRLEN + NEW_HDRLEN);
+}
+
+TEST_F (UdpHeaderAHTest, GetHeaderLength)
+{
+ // Get format from existing packet
+ std::size_t hdr_len;
+ int rc = hicn_packet_get_header_length (format_, header_, &hdr_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (hdr_len, UDP_HDRLEN + IPV6_HDRLEN + NEW_HDRLEN + AH_HDRLEN);
+}
+
+TEST_F (UdpHeaderTest, SetGetPayloadLength)
+{
+ // Get format from existing packet
+ std::size_t payload_len = 1000, payload_len_ret;
+ int rc = hicn_packet_set_payload_length (format_, header_, payload_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_packet_get_payload_length (format_, header_, &payload_len_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (payload_len, payload_len_ret);
+}
+
+TEST_F (UdpHeaderAHTest, SetGetPayloadLength)
+{
+ // Get format from existing packet
+ std::size_t payload_len = 1000, payload_len_ret;
+ int rc = hicn_packet_set_payload_length (format_, header_, payload_len);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ rc = hicn_packet_get_payload_length (format_, header_, &payload_len_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (payload_len, payload_len_ret);
+}
+
+TEST_F (UdpHeaderTest, SetGetName)
+{
+ // Get v6 name and set it to new_header
+ hicn_name_t name_ret;
+
+ int rc = hicn_packet_set_interest (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_set_name (format_, header_, &name6_, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_name (format_, header_, &name_ret, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_name_compare (&name6_, &name_ret, 1);
+ EXPECT_EQ (rc, 0);
+}
+
+TEST_F (UdpHeaderTest, SetGetLocator)
+{
+ // This function does nothing but it is set for compatibility
+ hicn_ip_address_t locator;
+ memset (&locator, 0, sizeof (locator));
+ locator.v6.as_u8[15] = 1;
+ int rc = hicn_packet_set_interest (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_set_locator (format_, header_, &locator, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_locator (format_, header_, &locator, 1);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+}
+
+TEST_F (UdpHeaderTest, SetGetSignatureSize)
+{
+ // No AH, so we should get an error
+ // FixMe no error raised here
+ size_t signature_size = 128;
+ int rc = hicn_packet_set_signature_size (format_, header_, signature_size);
+ (void) rc;
+ // EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Same for hicn_packet_get_signature_size
+ rc = hicn_packet_get_signature_size (format_, header_, &signature_size);
+ // EXPECT_NE (rc, HICN_LIB_ERROR_NONE);
+}
+
+TEST_F (UdpHeaderAHTest, SetGetSignatureSize)
+{
+ // No AH, so we should get an error
+ size_t signature_size = 128, signature_size_ret;
+ int rc = hicn_packet_set_signature_size (format_, header_, signature_size);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ // Same for hicn_packet_get_signature_size
+ rc = hicn_packet_get_signature_size (format_, header_, &signature_size_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (signature_size, signature_size_ret);
+}
+
+TEST_F (UdpHeaderTest, IsInterestIsData)
+{
+ // Mark packet as interest
+ int rc = hicn_packet_set_interest (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ int ret;
+ rc = hicn_packet_is_interest (format_, header_, &ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (ret, 1);
+
+ // Mark packet as data
+ rc = hicn_packet_set_data (format_, header_);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_is_interest (format_, header_, &ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+ EXPECT_EQ (ret, 0);
+}
+
+TEST_F (UdpHeaderTest, SetGetLifetime)
+{
+ // Lifetime
+ u32 lifetime = 20000, lifetime_ret; // 20 sec.
+ int rc = hicn_packet_set_lifetime (format_, header_, lifetime);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_lifetime (format_, header_, &lifetime_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (lifetime, lifetime_ret);
+}
+
+TEST_F (UdpHeaderAHTest, SetGetLifetime)
+{
+ // Lifetime
+ u32 lifetime = 20000, lifetime_ret; // 20 sec.
+ int rc = hicn_packet_set_lifetime (format_, header_, lifetime);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_lifetime (format_, header_, &lifetime_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (lifetime, lifetime_ret);
+}
+
+TEST_F (UdpHeaderTest, SetGetPayloadType)
+{
+ // Lifetime
+ hicn_payload_type_t payload_type = HPT_MANIFEST, payload_type_ret;
+ int rc = hicn_packet_set_payload_type (format_, header_, payload_type);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_payload_type (format_, header_, &payload_type_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (payload_type, payload_type_ret);
+
+ payload_type = HPT_DATA;
+
+ rc = hicn_packet_set_payload_type (format_, header_, payload_type);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ rc = hicn_packet_get_payload_type (format_, header_, &payload_type_ret);
+ EXPECT_EQ (rc, HICN_LIB_ERROR_NONE);
+
+ EXPECT_EQ (payload_type, payload_type_ret);
+}
+#endif
diff --git a/lib/src/test/test_validation.cc b/lib/src/test/test_validation.cc
new file mode 100644
index 000000000..091f26d65
--- /dev/null
+++ b/lib/src/test/test_validation.cc
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C"
+{
+#include <hicn/validation.h>
+}
+
+static constexpr int BUF_SIZE = 10;
+
+class ValidationTest : public ::testing::Test
+{
+};
+
+TEST_F (ValidationTest, SymbolicName)
+{
+ const char symbolic_name_correct[BUF_SIZE] = "conn0";
+ const char symbolic_name_empty[BUF_SIZE] = "";
+ const char symbolic_name_wrong[BUF_SIZE] = "1conn0";
+
+ EXPECT_TRUE (is_symbolic_name (symbolic_name_correct, BUF_SIZE));
+ EXPECT_FALSE (is_symbolic_name (symbolic_name_empty, BUF_SIZE));
+ EXPECT_FALSE (is_symbolic_name (symbolic_name_wrong, BUF_SIZE));
+}
+
+TEST_F (ValidationTest, Number)
+{
+ const char number_correct[BUF_SIZE] = "123";
+ const char number_empty[BUF_SIZE] = "";
+ const char number_wrong[BUF_SIZE] = "a123";
+ const char number_wrong_2[BUF_SIZE] = "12T3";
+ const char number_wrong_3[BUF_SIZE] = "a";
+ const char number_wrong_negative[BUF_SIZE] = "-123";
+
+ EXPECT_TRUE (is_number (number_correct, BUF_SIZE));
+ EXPECT_FALSE (is_number (number_empty, BUF_SIZE));
+ EXPECT_FALSE (is_number (number_wrong, BUF_SIZE));
+ EXPECT_FALSE (is_number (number_wrong_2, BUF_SIZE));
+ EXPECT_FALSE (is_number (number_wrong_3, BUF_SIZE));
+ EXPECT_FALSE (is_number (number_wrong_negative, BUF_SIZE));
+} \ No newline at end of file
diff --git a/lib/src/test/test_vector.cc b/lib/src/test/test_vector.cc
new file mode 100644
index 000000000..88b0bb7cf
--- /dev/null
+++ b/lib/src/test/test_vector.cc
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+extern "C"
+{
+#include <hicn/util/vector.h>
+}
+
+static constexpr size_t DEFAULT_SIZE = 10;
+static constexpr size_t N_ELEMENTS = 5;
+
+class VectorTest : public ::testing::Test
+{
+protected:
+ VectorTest () { vector_init (vector, DEFAULT_SIZE, 0); }
+ virtual ~VectorTest () { vector_free (vector); }
+
+ int *vector = NULL;
+};
+
+TEST_F (VectorTest, VectorAllocateAndResize)
+{
+ // Allocated size should be the next power of two
+ EXPECT_EQ (vector_get_alloc_size (vector), 16UL);
+
+ // Setting elements within the allocated size should not trigger a resize
+ vector_ensure_pos (vector, 15);
+ EXPECT_EQ (vector_get_alloc_size (vector), 16UL);
+
+ // Setting elements after should through
+ vector_ensure_pos (vector, 16);
+ EXPECT_EQ (vector_get_alloc_size (vector), 32UL);
+}
+
+TEST_F (VectorTest, VectorSize)
+{
+ EXPECT_EQ (vector_len (vector), size_t (0));
+
+ // Check size after pushing one element
+ vector_push (vector, 1);
+ EXPECT_EQ (vector_len (vector), size_t (1));
+
+ // Check size after pushing additional elements
+ vector_push (vector, 2);
+ vector_push (vector, 3);
+ EXPECT_EQ (vector_len (vector), size_t (3));
+
+ // Try adding multiple elements
+ const int n_elements_to_add = 5;
+ size_t expected_new_len = vector_len (vector) + n_elements_to_add;
+ for (int i = 0; i < n_elements_to_add; i++)
+ vector_push (vector, i);
+ EXPECT_EQ (vector_len (vector), expected_new_len);
+}
+
+TEST_F (VectorTest, VectorCheckValue)
+{
+ // Add elements
+ vector_push (vector, 109);
+ vector_push (vector, 200);
+ EXPECT_EQ (vector_at (vector, 0), 109);
+ EXPECT_EQ (vector_at (vector, 1), 200);
+
+ // Update element
+ vector_set (vector, 1, 400);
+ EXPECT_EQ (vector_at (vector, 1), 400);
+
+ // Add at last available position
+ size_t prev_size = vector_len (vector);
+ vector_set (vector, vector_len (vector) - 1, 123);
+ EXPECT_EQ (vector_at (vector, vector_len (vector) - 1), 123);
+ EXPECT_EQ (prev_size, vector_len (vector)) << "Size should not have changed";
+}
+
+TEST_F (VectorTest, RemoveElement)
+{
+ // Populate vector
+ for (size_t i = 0; i < N_ELEMENTS; i++)
+ vector_push (vector, i);
+ EXPECT_EQ (vector_len (vector), N_ELEMENTS);
+ for (size_t i = 0; i < vector_len (vector); i++)
+ EXPECT_EQ (vector_at (vector, i), (int) i);
+
+ // Remove element
+ int value_to_remove = 3;
+ int num_removed = vector_remove_unordered (vector, value_to_remove);
+
+ EXPECT_EQ (vector_len (vector), N_ELEMENTS - 1);
+ EXPECT_EQ (num_removed, 1);
+ for (size_t i = 0; i < vector_len (vector); i++)
+ EXPECT_NE (vector_at (vector, i), value_to_remove);
+}
+
+TEST_F (VectorTest, RemoveNonExistingElement)
+{
+ // Push some initial values
+ vector_push (vector, 1);
+ vector_push (vector, 2);
+ vector_push (vector, 3);
+ EXPECT_EQ (vector_len (vector), size_t (3));
+
+ // Remove non-existing element
+ int num_removed = vector_remove_unordered (vector, 5);
+ EXPECT_EQ (num_removed, 0);
+ size_t prev_size = vector_len (vector);
+ EXPECT_EQ (prev_size, vector_len (vector)) << "Size should not have changed";
+}
+
+TEST_F (VectorTest, RemoveDuplicatedElement)
+{
+ // Populate vector
+ for (size_t i = 0; i < N_ELEMENTS; i++)
+ vector_push (vector, i);
+ EXPECT_EQ (vector_len (vector), N_ELEMENTS);
+ for (size_t i = 0; i < vector_len (vector); i++)
+ EXPECT_EQ (vector_at (vector, i), (int) i);
+ vector_set (vector, 0, 3); // Duplicate element
+
+ // Remove (duplicated) elements
+ int value_to_remove = 3;
+ int num_removed = vector_remove_unordered (vector, value_to_remove);
+
+ EXPECT_EQ (vector_len (vector), N_ELEMENTS - 2);
+ EXPECT_EQ (num_removed, 2);
+ for (size_t i = 0; i < vector_len (vector); i++)
+ EXPECT_NE (vector_at (vector, i), value_to_remove);
+}
+
+TEST_F (VectorTest, Iterate)
+{
+ for (size_t i = 0; i < N_ELEMENTS; i++)
+ vector_push (vector, i);
+
+ int count = 0;
+ int *elem;
+ vector_foreach (vector, elem, { EXPECT_EQ (*elem, count++); });
+}
+
+TEST_F (VectorTest, MultipleResize)
+{
+ // Use small vector (size=1) to force multiple realloc operations
+ int *small_vector;
+ vector_init (small_vector, 1, 0);
+
+ for (size_t i = 0; i < N_ELEMENTS; i++)
+ vector_push (small_vector, i);
+
+ for (size_t i = 0; i < N_ELEMENTS; i++)
+ EXPECT_EQ (vector_at (small_vector, i), (int) i);
+
+ EXPECT_EQ (vector_len (small_vector), 5UL);
+ EXPECT_EQ (vector_get_alloc_size (small_vector), 8UL);
+
+ vector_free (small_vector);
+}
+
+TEST_F (VectorTest, MaxSize)
+{
+ const int max_size = 4;
+
+ // Fill the vector until max size is reached
+ int *small_vector;
+ vector_init (small_vector, 2, max_size);
+ for (int i = 0; i < max_size; i++)
+ vector_push (small_vector, i);
+
+ // Try expanding or appending elements should fail
+ int rc = vector_ensure_pos (small_vector, max_size);
+ EXPECT_EQ (rc, -1);
+ rc = vector_push (small_vector, 123);
+ EXPECT_EQ (rc, -1);
+
+ vector_free (small_vector);
+}
+
+TEST_F (VectorTest, Contains)
+{
+ // No elements
+ EXPECT_EQ (vector_contains (vector, 1), false);
+
+ // Push one element
+ vector_push (vector, 1);
+ EXPECT_EQ (vector_contains (vector, 1), true);
+
+ // Update element
+ vector_set (vector, 0, 2);
+ EXPECT_EQ (vector_contains (vector, 1), false);
+ EXPECT_EQ (vector_contains (vector, 2), true);
+}
+
+TEST_F (VectorTest, Remove)
+{
+ // Remove element at invalid position
+ int rc = vector_remove_at (vector, 2);
+ EXPECT_EQ (rc, -1); // Failure
+
+ // Push two elements and remove the second one
+ vector_push (vector, 1);
+ vector_push (vector, 2);
+ rc = vector_remove_at (vector, 1);
+ EXPECT_EQ (rc, 0); // Success
+ EXPECT_EQ (vector_len (vector), size_t (1));
+
+ // Push another element: it should replace the previous one
+ vector_push (vector, 3);
+ EXPECT_EQ (vector_len (vector), size_t (2));
+ EXPECT_EQ (vector_at (vector, 1), 3);
+}
+
+TEST_F (VectorTest, RemoveInTheMiddle)
+{
+ for (size_t i = 0; i < N_ELEMENTS; i++)
+ vector_push (vector, i);
+
+ // Remove element in central position
+ int rc = vector_remove_at (vector, 2);
+ EXPECT_EQ (rc, 0); // Success
+ EXPECT_EQ (vector_contains (vector, 2), false);
+ EXPECT_EQ (vector_len (vector), N_ELEMENTS - 1);
+
+ // Check if elements have been shifted (preserving the order)
+ int expected[] = { 0, 1, 3, 4 };
+ for (size_t i = 0; i < vector_len (vector); i++)
+ EXPECT_EQ (vector_at (vector, i), expected[i]);
+}
+
+TEST_F (VectorTest, Reset)
+{
+ vector_push (vector, 1);
+ vector_push (vector, 2);
+ EXPECT_EQ (vector_len (vector), size_t (2));
+
+ vector_reset (vector);
+ EXPECT_EQ (vector_len (vector), size_t (0));
+
+ vector_push (vector, 5);
+ EXPECT_EQ (vector_len (vector), size_t (1));
+ EXPECT_EQ (vector_contains (vector, 5), true);
+ EXPECT_EQ (vector_at (vector, 0), 5);
+} \ No newline at end of file
diff --git a/lib/src/util/ip_address.c b/lib/src/util/ip_address.c
index 49916547d..b50864c96 100644
--- a/lib/src/util/ip_address.c
+++ b/lib/src/util/ip_address.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,44 +20,58 @@
#include <hicn/util/ip_address.h>
#include <hicn/util/log.h>
+#include <hicn/util/sstrncpy.h>
+#include <hicn/common.h>
#if __BYTE_ORDER == __LITTLE_ENDIAN
#ifdef __ANDROID__
-#define SWAP(x) bswap_32(x)
+#define SWAP(x) bswap_32 (x)
#else
-#define SWAP(x) __bswap_constant_32(x)
+#define SWAP(x) __bswap_constant_32 (x)
#endif
#else
#define SWAP(x) x
#endif
-
/* No htonl() with const */
-const ip_address_t IPV4_LOOPBACK = {
- .v4.as_inaddr.s_addr = SWAP(INADDR_LOOPBACK),
+const hicn_ip_address_t IPV4_LOOPBACK = {
+ .v4.as_inaddr.s_addr = SWAP (INADDR_LOOPBACK),
+};
+
+const hicn_ip_address_t IPV6_LOOPBACK = {
+ .v6.as_in6addr = IN6ADDR_LOOPBACK_INIT,
};
-const ip_address_t IPV6_LOOPBACK ={
- .v6.as_in6addr = IN6ADDR_LOOPBACK_INIT,
+const hicn_ip_address_t IPV4_ANY = {
+ .v4.as_inaddr.s_addr = INADDR_ANY,
};
-const ip_address_t IPV4_ANY = {
- .v4.as_inaddr.s_addr = INADDR_ANY,
+const hicn_ip_address_t IPV6_ANY = {
+ .v6.as_in6addr = IN6ADDR_ANY_INIT,
};
-const ip_address_t IPV6_ANY = {
- .v6.as_in6addr = IN6ADDR_ANY_INIT,
+const ipv4_address_t IP4_ADDRESS_EMPTY = {
+ .as_u32 = 0,
};
-const ip_address_t IP_ADDRESS_EMPTY = {
- .v6.as_u64 = { 0 },
+const ipv6_address_t IP6_ADDRESS_EMPTY = {
+ .as_u64 = { 0, 0 },
};
+const hicn_ip_address_t IP_ADDRESS_EMPTY = {
+ .v6.as_u64 = { 0, 0 },
+};
/* IP address */
int
-ip_address_get_family (const char * ip_address)
+hicn_ip_address_get_family (const hicn_ip_address_t *address)
+{
+ return hicn_ip_address_is_v4 (address) ? AF_INET : AF_INET6;
+}
+
+int
+hicn_ip_address_str_get_family (const char *ip_address)
{
struct addrinfo hint, *res = NULL;
int rc;
@@ -78,27 +92,41 @@ ip_address_get_family (const char * ip_address)
}
int
-ip_address_len (int family)
+hicn_ip_address_len (int family)
{
return (family == AF_INET6) ? IPV6_ADDR_LEN :
- (family == AF_INET) ? IPV4_ADDR_LEN : 0;
+ (family == AF_INET) ? IPV4_ADDR_LEN :
+ 0;
}
int
-ip_address_ntop (const ip_address_t * ip_address, char *dst, const size_t len,
- int family)
+hicn_ip_address_get_len (const hicn_ip_address_t *ip_address)
{
- const char * s;
- switch(family) {
+ return hicn_ip_address_len (hicn_ip_address_get_family (ip_address));
+}
+
+int
+hicn_ip_address_get_len_bits (const hicn_ip_address_t *ip_address)
+{
+ return bytes_to_bits (hicn_ip_address_get_len (ip_address));
+}
+
+int
+hicn_ip_address_ntop (const hicn_ip_address_t *ip_address, char *dst,
+ const size_t len, int family)
+{
+ const char *s;
+ switch (family)
+ {
case AF_INET:
- s = inet_ntop (AF_INET, ip_address->v4.buffer, dst, (socklen_t)len);
+ s = inet_ntop (AF_INET, ip_address->v4.buffer, dst, (socklen_t) len);
break;
case AF_INET6:
- s = inet_ntop (AF_INET6, ip_address->v6.buffer, dst, (socklen_t)len);
+ s = inet_ntop (AF_INET6, ip_address->v6.buffer, dst, (socklen_t) len);
break;
default:
return -1;
- }
+ }
return (s ? 1 : -1);
}
@@ -106,22 +134,26 @@ ip_address_ntop (const ip_address_t * ip_address, char *dst, const size_t len,
* Parse ip addresses in presentation format
*/
int
-ip_address_pton (const char *ip_address_str, ip_address_t * ip_address)
+hicn_ip_address_pton (const char *hicn_ip_address_str,
+ hicn_ip_address_t *ip_address)
{
int pton_fd;
int family;
- family = ip_address_get_family (ip_address_str);
+ family = hicn_ip_address_str_get_family (hicn_ip_address_str);
- switch (family) {
+ switch (family)
+ {
case AF_INET:
ip_address->pad[0] = 0;
ip_address->pad[1] = 0;
ip_address->pad[2] = 0;
- pton_fd = inet_pton (AF_INET, ip_address_str, &ip_address->v4.buffer);
+ pton_fd =
+ inet_pton (AF_INET, hicn_ip_address_str, &ip_address->v4.buffer);
break;
case AF_INET6:
- pton_fd = inet_pton (AF_INET6, ip_address_str, &ip_address->v6.buffer);
+ pton_fd =
+ inet_pton (AF_INET6, hicn_ip_address_str, &ip_address->v6.buffer);
break;
default:
return -1;
@@ -132,36 +164,38 @@ ip_address_pton (const char *ip_address_str, ip_address_t * ip_address)
if (pton_fd <= 0)
return -1;
- return 1;
+ return 0;
}
int
-ip_address_snprintf(char * s, size_t size, const ip_address_t * ip_address, int family)
+hicn_ip_address_snprintf (char *s, size_t size,
+ const hicn_ip_address_t *ip_address)
{
-
- const char * rc;
- switch(family) {
- case AF_INET:
- if (size < INET_ADDRSTRLEN)
- return -1;
- rc = inet_ntop (AF_INET, ip_address->v4.buffer, s, INET_ADDRSTRLEN);
- break;
- case AF_INET6:
- if (size < INET6_ADDRSTRLEN)
- return -1;
- rc = inet_ntop (AF_INET6, ip_address->v6.buffer, s, INET6_ADDRSTRLEN);
- break;
- default:
- return -1;
+ const char *rc;
+ int family = hicn_ip_address_get_family (ip_address);
+ switch (family)
+ {
+ case AF_INET:
+ if (size < INET_ADDRSTRLEN)
+ return -1;
+ rc = inet_ntop (AF_INET, ip_address->v4.buffer, s, INET_ADDRSTRLEN);
+ break;
+ case AF_INET6:
+ if (size < INET6_ADDRSTRLEN)
+ return -1;
+ rc = inet_ntop (AF_INET6, ip_address->v6.buffer, s, INET6_ADDRSTRLEN);
+ break;
+ default:
+ return -1;
}
- if (!rc)
- return -1;
- return (int)strlen(s);
+ if (!rc)
+ return -1;
+ return (int) strnlen_s (s, MAXSZ_IP_ADDRESS);
}
int
-ip_address_to_sockaddr(const ip_address_t * ip_address,
- struct sockaddr *sa, int family)
+hicn_ip_address_to_sockaddr (const hicn_ip_address_t *ip_address,
+ struct sockaddr *sa, int family)
{
struct sockaddr_in6 *tmp6 = (struct sockaddr_in6 *) sa;
struct sockaddr_in *tmp4 = (struct sockaddr_in *) sa;
@@ -187,64 +221,72 @@ ip_address_to_sockaddr(const ip_address_t * ip_address,
}
int
-ip_address_cmp(const ip_address_t * ip1, const ip_address_t * ip2, int family)
+hicn_ip_address_cmp (const hicn_ip_address_t *ip1,
+ const hicn_ip_address_t *ip2)
{
- switch(family) {
- case AF_INET:
- return memcmp(&ip1->v4, &ip2->v4, sizeof(ip1->v4));
- break;
- case AF_INET6:
- return memcmp(&ip1->v6, &ip2->v6, sizeof(ip1->v6));
- break;
- default:
- return memcmp(ip1, ip2, sizeof(ip_address_t));
- }
+ /* This works as soon as all members are initialized */
+ return memcmp (ip1, ip2, sizeof (hicn_ip_address_t));
}
-int
-ip_address_empty(const ip_address_t * ip)
+bool
+hicn_ip_address_equals (const hicn_ip_address_t *ip1,
+ const hicn_ip_address_t *ip2)
{
- return (memcmp(ip, &IP_ADDRESS_EMPTY, sizeof(IP_ADDRESS_EMPTY)) == 0);
+ return hicn_ip_address_cmp (ip1, ip2) == 0;
}
+int
+hicn_ip_address_empty (const hicn_ip_address_t *ip)
+{
+ return (memcmp (ip, &IP_ADDRESS_EMPTY, sizeof (hicn_ip_address_t)) == 0);
+}
+void
+hicn_ip_address_clear (hicn_ip_address_t *address)
+{
+ memset (address, 0, sizeof (hicn_ip_address_t));
+}
/* Prefix */
/* Parse IP Prefixes in presentation format (in bits, separated by a slash) */
int
-ip_prefix_pton (const char *ip_address_str, ip_prefix_t * ip_prefix)
+hicn_ip_prefix_pton (const char *hicn_ip_address_str,
+ hicn_ip_prefix_t *hicn_ip_prefix)
{
int pton_fd;
char *p;
char *eptr;
- char *addr = strdup (ip_address_str);
+ char *addr = strdup (hicn_ip_address_str);
p = strchr (addr, '/');
- if (!p) {
- ip_prefix->len = ~0; // until we get the ip address family
- } else {
- ip_prefix->len = (u8)strtoul (p + 1, &eptr, 10);
- *p = 0;
- }
+ if (!p)
+ {
+ hicn_ip_prefix->len = ~0; // until we get the ip address family
+ }
+ else
+ {
+ hicn_ip_prefix->len = (u8) strtoul (p + 1, &eptr, 10);
+ *p = 0;
+ }
- ip_prefix->family = ip_address_get_family (addr);
+ hicn_ip_prefix->family = hicn_ip_address_str_get_family (addr);
- switch (ip_prefix->family)
+ switch (hicn_ip_prefix->family)
{
case AF_INET6:
- if (ip_prefix->len == (u8)~0)
- ip_prefix->len = IPV6_ADDR_LEN_BITS;
- if (ip_prefix->len > IPV6_ADDR_LEN_BITS)
- goto ERR;
- pton_fd = inet_pton (AF_INET6, addr, &ip_prefix->address.v6.buffer);
+ if (hicn_ip_prefix->len == (u8) ~0)
+ hicn_ip_prefix->len = IPV6_ADDR_LEN_BITS;
+ if (hicn_ip_prefix->len > IPV6_ADDR_LEN_BITS)
+ goto ERR;
+ pton_fd = inet_pton (AF_INET6, addr, &hicn_ip_prefix->address.v6.buffer);
break;
case AF_INET:
- if (ip_prefix->len == (u8)~0)
- ip_prefix->len = IPV4_ADDR_LEN_BITS;
- if (ip_prefix->len > IPV4_ADDR_LEN_BITS)
- goto ERR;
- pton_fd = inet_pton (AF_INET, addr, &ip_prefix->address.v4.buffer);
+ if (hicn_ip_prefix->len == (u8) ~0)
+ hicn_ip_prefix->len = IPV4_ADDR_LEN_BITS;
+ if (hicn_ip_prefix->len > IPV4_ADDR_LEN_BITS)
+ goto ERR;
+ pton_fd = inet_pton (AF_INET, addr, &hicn_ip_prefix->address.v4.buffer);
break;
default:
goto ERR;
@@ -253,139 +295,180 @@ ip_prefix_pton (const char *ip_address_str, ip_prefix_t * ip_prefix)
// 0 = not in presentation format
// < 0 = other error (use perror)
if (pton_fd <= 0)
- goto ERR;
+ goto ERR;
- free(addr);
- return 1;
+ free (addr);
+ return 0;
ERR:
free (addr);
return -1;
}
int
-ip_prefix_ntop_short(const ip_prefix_t * ip_prefix, char *dst, size_t size)
+hicn_ip_prefix_ntop_short (const hicn_ip_prefix_t *hicn_ip_prefix, char *dst,
+ size_t size)
{
char ip_s[MAXSZ_IP_ADDRESS];
- const char * s;
- switch(ip_prefix->family) {
+ const char *s;
+ switch (hicn_ip_prefix->family)
+ {
case AF_INET:
- s = inet_ntop (AF_INET, ip_prefix->address.v4.buffer, ip_s, MAXSZ_IP_ADDRESS);
+ s = inet_ntop (AF_INET, hicn_ip_prefix->address.v4.buffer, ip_s,
+ MAXSZ_IP_ADDRESS);
break;
case AF_INET6:
- s = inet_ntop (AF_INET6, ip_prefix->address.v6.buffer, ip_s, MAXSZ_IP_ADDRESS);
+ s = inet_ntop (AF_INET6, hicn_ip_prefix->address.v6.buffer, ip_s,
+ MAXSZ_IP_ADDRESS);
break;
default:
return -1;
- }
+ }
if (!s)
- return -1;
- int rc = snprintf(dst, size, "%s", ip_s);
+ return -1;
+ int rc = snprintf (dst, size, "%s", ip_s);
if (rc >= size)
- return (int)size;
+ return (int) size;
return rc;
}
int
-ip_prefix_ntop(const ip_prefix_t * ip_prefix, char *dst, size_t size)
+hicn_ip_prefix_ntop (const hicn_ip_prefix_t *hicn_ip_prefix, char *dst,
+ size_t size)
{
char ip_s[MAXSZ_IP_ADDRESS];
- const char * s;
- switch(ip_prefix->family) {
+ const char *s;
+ switch (hicn_ip_prefix->family)
+ {
case AF_INET:
- s = inet_ntop (AF_INET, ip_prefix->address.v4.buffer, ip_s, MAXSZ_IP_ADDRESS);
+ s = inet_ntop (AF_INET, hicn_ip_prefix->address.v4.buffer, ip_s,
+ MAXSZ_IP_ADDRESS);
break;
case AF_INET6:
- s = inet_ntop (AF_INET6, ip_prefix->address.v6.buffer, ip_s, MAXSZ_IP_ADDRESS);
+ s = inet_ntop (AF_INET6, hicn_ip_prefix->address.v6.buffer, ip_s,
+ MAXSZ_IP_ADDRESS);
break;
default:
return -1;
- }
+ }
if (!s)
- return -1;
- int rc = snprintf(dst, size, "%s/%d", ip_s, ip_prefix->len);
+ return -1;
+ int rc = snprintf (dst, size, "%s/%d", ip_s, hicn_ip_prefix->len);
if (rc >= size)
- return (int)size;
+ return (int) size;
return rc;
}
int
-ip_prefix_len (const ip_prefix_t * prefix)
+hicn_ip_prefix_snprintf (char *s, size_t size, const hicn_ip_prefix_t *prefix)
+{
+ return hicn_ip_prefix_ntop (prefix, s, size);
+}
+
+int
+hicn_ip_prefix_len (const hicn_ip_prefix_t *prefix)
{
- return prefix->len; // ip_address_len(&prefix->address, prefix->family);
+ return prefix->len; // hicn_ip_address_len(&prefix->address, prefix->family);
}
const u8 *
-ip_address_get_buffer(const ip_address_t * ip_address, int family)
+hicn_ip_address_get_buffer (const hicn_ip_address_t *ip_address, int family)
{
- switch(family) {
+ switch (family)
+ {
case AF_INET:
return ip_address->v4.buffer;
case AF_INET6:
return ip_address->v6.buffer;
default:
return NULL;
- }
+ }
}
bool
-ip_prefix_empty (const ip_prefix_t * prefix)
+hicn_ip_prefix_empty (const hicn_ip_prefix_t *prefix)
{
return prefix->len == 0;
}
int
-ip_prefix_to_sockaddr(const ip_prefix_t * prefix,
- struct sockaddr *sa)
+hicn_ip_prefix_to_sockaddr (const hicn_ip_prefix_t *prefix,
+ struct sockaddr *sa)
{
- // XXX assert len == ip_address_len
- return ip_address_to_sockaddr(&prefix->address, sa, prefix->family);
+ // XXX assert len == hicn_ip_address_len
+ return hicn_ip_address_to_sockaddr (&prefix->address, sa, prefix->family);
}
int
-ip_prefix_cmp(const ip_prefix_t * prefix1, const ip_prefix_t * prefix2)
+hicn_ip_prefix_cmp (const hicn_ip_prefix_t *prefix1,
+ const hicn_ip_prefix_t *prefix2)
+{
+ if (prefix1->family < prefix2->family)
+ return -1;
+ else if (prefix1->family > prefix2->family)
+ return 1;
+
+ if (prefix1->len < prefix2->len)
+ return -1;
+ else if (prefix1->len > prefix2->len)
+ return 1;
+
+ return hicn_ip_address_cmp (&prefix1->address, &prefix2->address);
+}
+
+/* Network byte order + host bit order */
+
+uint8_t
+hicn_ip_address_get_bit (const hicn_ip_address_t *address, uint8_t pos)
{
- if (prefix1->family < prefix2->family)
- return -1;
- else if (prefix1->family > prefix2->family)
- return 1;
+ return (address->v6.as_u8[pos / 8] >> (7 - pos % 8)) & 0x1;
+}
- if (prefix1->len < prefix2->len)
- return -1;
- else if (prefix1->len > prefix2->len)
- return 1;
+bool
+hicn_ip_address_match_family (const hicn_ip_address_t *address, int family)
+{
+ return hicn_ip_address_get_family (address) == family;
+}
- return ip_address_cmp(&prefix1->address, &prefix2->address, prefix1->family);
+uint32_t
+hicn_ip_address_get_hash (const hicn_ip_address_t *address)
+{
+ return hash32 (address, sizeof (address));
}
/* URL */
#define MAXSZ_PROTO_ 8 /* inetX:// */
-#define MAXSZ_PROTO MAXSZ_PROTO_ + NULLTERM
+#define MAXSZ_PROTO MAXSZ_PROTO_ + NULLTERM
#define MAXSZ_URL4_ MAXSZ_PROTO_ + MAXSZ_IP4_ADDRESS_ + MAXSZ_PORT_
#define MAXSZ_URL6_ MAXSZ_PROTO_ + MAXSZ_IP6_ADDRESS_ + MAXSZ_PORT_
-#define MAXSZ_URL_ MAXSZ_URL6_
-#define MAXSZ_URL4 MAXSZ_URL4_ + NULLTERM
-#define MAXSZ_URL6 MAXSZ_URL6_ + NULLTERM
-#define MAXSZ_URL MAXSZ_URL_ + NULLTERM
+#define MAXSZ_URL_ MAXSZ_URL6_
+#define MAXSZ_URL4 MAXSZ_URL4_ + NULLTERM
+#define MAXSZ_URL6 MAXSZ_URL6_ + NULLTERM
+#define MAXSZ_URL MAXSZ_URL_ + NULLTERM
int
-url_snprintf(char * s, size_t size, int family,
- const ip_address_t * ip_address, u16 port)
+url_snprintf (char *s, size_t size, const hicn_ip_address_t *ip_address,
+ u16 port)
{
- char ip_address_s[MAXSZ_IP_ADDRESS];
- int rc;
+ char hicn_ip_address_s[MAXSZ_IP_ADDRESS];
+ int rc;
- /* Other address are currently not supported */
- if (!IS_VALID_FAMILY(family))
- return -1;
+ int family = hicn_ip_address_get_family (ip_address);
- rc = ip_address_snprintf(ip_address_s, MAXSZ_IP_ADDRESS, ip_address, family);
- if (rc >= MAXSZ_IP_ADDRESS)
- WARN("[url_snprintf] Unexpected ip_address truncation");
- if (rc < 0)
- return rc;
+ /* Other address are currently not supported */
+ if (!IS_VALID_FAMILY (family))
+ return -1;
- return snprintf(s, size, "inet%c://%s:%d", (family == AF_INET) ? '4' : '6',
- ip_address_s, port);
+ if (!hicn_ip_address_match_family (ip_address, family))
+ return -1;
+ rc =
+ hicn_ip_address_snprintf (hicn_ip_address_s, MAXSZ_IP_ADDRESS, ip_address);
+ if (rc >= MAXSZ_IP_ADDRESS)
+ WARN ("[url_snprintf] Unexpected ip_address truncation");
+ if (rc < 0)
+ return rc;
+
+ return snprintf (s, size, "inet%c://%s:%d", (family == AF_INET) ? '4' : '6',
+ hicn_ip_address_s, port);
}
diff --git a/lib/src/util/log.c b/lib/src/util/log.c
index c1fc999ad..91a87e848 100644
--- a/lib/src/util/log.c
+++ b/lib/src/util/log.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,6 +18,7 @@
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
+#include <strings.h>
#ifdef __ANDROID__
#include <android/log.h>
@@ -25,154 +26,184 @@
log_conf_t log_conf = DEFAULT_LOG_CONF;
-#define FMT_DATETIME "%02d-%02d-%04d %02d:%02d:%02d"
-#define FMT_DATETIME_LEN 20
-#define snprintf_nowarn(...) (snprintf(__VA_ARGS__) < 0 ? abort() : (void)0)
+#define FMT_DATETIME "%02d-%02d-%04d %02d:%02d:%02d"
+#define FMT_DATETIME_LEN 20
+#define snprintf_nowarn(...) (snprintf (__VA_ARGS__) < 0 ? abort () : (void) 0)
+#define COLOR_RED "\033[31m"
+#define COLOR_YELLOW "\033[33m"
+#define COLOR_RESET "\033[0m"
static char ts[FMT_DATETIME_LEN];
-static char *timestamp(void)
+static char *
+timestamp (void)
{
- time_t tv;
- struct tm *tm;
+ time_t tv;
+ struct tm *tm;
- time(&tv);
- tm = localtime(&tv);
+ time (&tv);
+ tm = localtime (&tv);
- snprintf_nowarn(ts, FMT_DATETIME_LEN, FMT_DATETIME, tm->tm_mday,
- tm->tm_mon + 1, tm->tm_year + 1900, tm->tm_hour, tm->tm_min,
- tm->tm_sec);
- return ts;
+ snprintf_nowarn (ts, FMT_DATETIME_LEN, FMT_DATETIME, tm->tm_mday,
+ tm->tm_mon + 1, tm->tm_year + 1900, tm->tm_hour, tm->tm_min,
+ tm->tm_sec);
+ return ts;
}
-void _log_va(int level, const char *fmt, va_list ap)
-{
+void
+_log_va (int level, const char *fmt, va_list ap)
+{
#if 0
if (!conf.log_system)
return;
#endif
- char *prefix;
+ char *prefix;
#ifdef __ANDROID__
- int prio = -1;
- if (level > log_conf.log_level)
- return;
-
- switch (level) {
- case LOG_FATAL:
- prio = ANDROID_LOG_FATAL;
- prefix = "FATAL: ";
- break;
- case LOG_ERROR:
- prio = ANDROID_LOG_ERROR;
- prefix = "ERROR: ";
- break;
- case LOG_WARN:
- prio = ANDROID_LOG_WARN;
- prefix = "WARNING: ";
- break;
- case LOG_INFO:
- prio = ANDROID_LOG_INFO;
- prefix = "";
- break;
- case LOG_DEBUG:
- prio = ANDROID_LOG_DEBUG;
- prefix = "DEBUG: ";
- break;
- case LOG_TRACE:
- prio = ANDROID_LOG_DEBUG;
- prefix = "TRACE: ";
- break;
- default:
- prio = ANDROID_LOG_INFO;
- prefix = "";
- break;
- }
-
- if (log_conf.log_file) {
- FILE *f = log_conf.log_file;
- fprintf(f, "%s %s", timestamp(), prefix);
- vfprintf(f, fmt, ap);
- fprintf(f, "\n");
- } else {
- __android_log_vprint(ANDROID_LOG_INFO, "HICN FACEMGR", fmt, ap);
- }
+ int prio = -1;
+ if (level > log_conf.log_level)
+ return;
+
+ switch (level)
+ {
+ case LOG_FATAL:
+ prio = ANDROID_LOG_FATAL;
+ prefix = "FATAL: ";
+ break;
+ case LOG_ERROR:
+ prio = ANDROID_LOG_ERROR;
+ prefix = "ERROR: ";
+ break;
+ case LOG_WARN:
+ prio = ANDROID_LOG_WARN;
+ prefix = "WARNING: ";
+ break;
+ case LOG_INFO:
+ prio = ANDROID_LOG_INFO;
+ prefix = "";
+ break;
+ case LOG_DEBUG:
+ prio = ANDROID_LOG_DEBUG;
+ prefix = "DEBUG: ";
+ break;
+ case LOG_TRACE:
+ prio = ANDROID_LOG_DEBUG;
+ prefix = "TRACE: ";
+ break;
+ default:
+ prio = ANDROID_LOG_INFO;
+ prefix = "";
+ break;
+ }
+
+ if (log_conf.log_file)
+ {
+ FILE *f = log_conf.log_file;
+ fprintf (f, "%s %s", timestamp (), prefix);
+ vfprintf (f, fmt, ap);
+ fprintf (f, "\n");
+ }
+ else
+ {
+ __android_log_vprint (prio, "HICN FACEMGR", fmt, ap);
+ }
#else
- if (level > log_conf.log_level)
- return;
-
- switch (level) {
- case LOG_FATAL:
- prefix = "FATAL: ";
- break;
- case LOG_ERROR:
- prefix = "ERROR: ";
- break;
- case LOG_WARN:
- prefix = "WARNING: ";
- break;
- case LOG_INFO:
- prefix = "";
- break;
- case LOG_DEBUG:
- prefix = "DEBUG: ";
- break;
- case LOG_TRACE:
- prefix = "TRACE: ";
- break;
- default:
- prefix = "";
- break;
- }
- FILE *f = log_conf.log_file ? log_conf.log_file : stdout;
- fprintf(f, "%s %s", timestamp(), prefix);
- vfprintf(f, fmt, ap);
- fprintf(f, "\n");
+ if (level > log_conf.log_level)
+ return;
+
+ char *color = COLOR_RESET;
+ switch (level)
+ {
+ case LOG_FATAL:
+ prefix = "FATAL: ";
+ break;
+ case LOG_ERROR:
+ prefix = "ERROR: ";
+ color = COLOR_RED;
+ break;
+ case LOG_WARN:
+ prefix = "WARNING: ";
+ color = COLOR_YELLOW;
+ break;
+ case LOG_INFO:
+ prefix = "";
+ break;
+ case LOG_DEBUG:
+ prefix = "DEBUG: ";
+ break;
+ case LOG_TRACE:
+ prefix = "TRACE: ";
+ break;
+ default:
+ prefix = "";
+ break;
+ }
+ FILE *f = log_conf.log_file ? log_conf.log_file : stdout;
+ fprintf (f, "%s%s %s", color, timestamp (), prefix);
+ vfprintf (f, fmt, ap);
+ fprintf (f, "%s\n", COLOR_RESET);
#ifdef DEBUG
- fflush(f);
+ fflush (f);
#endif
#endif
}
-void _log(int level, const char *fmt, ...)
+void
+_log (int level, const char *fmt, ...)
{
- va_list ap;
+ va_list ap;
- va_start(ap, fmt);
- _log_va(level, fmt, ap);
- va_end(ap);
+ va_start (ap, fmt);
+ _log_va (level, fmt, ap);
+ va_end (ap);
}
#ifdef HAVE_BACKTRACE
#include <execinfo.h>
-void print_trace(void)
+void
+print_trace (void)
{
- void *array[32];
- size_t size;
+ void *array[32];
+ size_t size;
- size = backtrace(array, 32);
- fflush(conf.log_file);
- backtrace_symbols_fd(array, size, fileno(conf.log_file));
+ size = backtrace (array, 32);
+ fflush (conf.log_file);
+ backtrace_symbols_fd (array, size, fileno (conf.log_file));
}
#endif
-void fatal(char *fmt, ...)
+void
+fatal (char *fmt, ...)
{
- va_list ap;
+ va_list ap;
- va_start(ap, fmt);
- _log_va(LOG_FATAL, fmt, ap);
- va_end(ap);
+ va_start (ap, fmt);
+ _log_va (LOG_FATAL, fmt, ap);
+ va_end (ap);
#ifdef HAVE_BACKTRACE
- print_trace();
+ print_trace ();
#endif
- exit(200);
+ exit (200);
}
+
+const char *loglevel_str[] = { "fatal", "error", "warn",
+ "info", "debug", "trace" };
+
+int
+loglevel_from_str (const char *loglevel)
+{
+ for (int i = 0; i <= LOG_TRACE; i++)
+ {
+ if (strcasecmp (loglevel, loglevel_str[i]) == 0)
+ return i;
+ }
+ return -1;
+} \ No newline at end of file
diff --git a/lib/src/util/pool.c b/lib/src/util/pool.c
new file mode 100644
index 000000000..2c1e90b5e
--- /dev/null
+++ b/lib/src/util/pool.c
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file pool.c
+ * \brief Implementation of fixed-size pool allocator.
+ *
+ * NOTE:
+ * - Ideally, we should have a single realloc per resize, that would encompass
+ * both the free indices vector and bitmap, by nesting data structures.
+ * Because of the added complexity, and by lack of evidence of the need for
+ * this, we currently rely on a simpler implementation.
+ */
+
+#include <assert.h>
+#include <stdlib.h> // calloc
+
+#include <hicn/util/pool.h>
+#include <hicn/util/log.h>
+
+#include <stdio.h> // XXX
+
+void
+_pool_init (void **pool_ptr, size_t elt_size, size_t init_size,
+ size_t max_size)
+{
+ assert (pool_ptr);
+ assert (elt_size);
+
+ init_size = next_pow2 (init_size);
+
+ if (max_size && init_size > max_size)
+ goto ERR_MAX_SIZE;
+
+ /* The initial pool size is rounded to the next power of two */
+ size_t alloc_size = next_pow2 (init_size);
+
+ pool_hdr_t *ph = calloc (POOL_HDRLEN + alloc_size * elt_size, 1);
+ if (!ph)
+ goto ERR_MALLOC;
+
+ ph->elt_size = elt_size;
+ ph->alloc_size = alloc_size;
+ ph->max_size = max_size;
+
+ /* Free indices */
+ off_t *free_indices;
+ vector_init (free_indices, init_size, max_size);
+ for (unsigned i = 0; i < init_size; i++)
+ free_indices[i] = (init_size - 1) - i;
+ vector_len (free_indices) = init_size;
+ ph->free_indices = free_indices;
+
+ /* Free bitmap */
+ bitmap_t *fb = ph->free_bitmap;
+ bitmap_init (fb, init_size, max_size);
+ bitmap_set_to (fb, init_size);
+ ph->free_bitmap = fb;
+
+ *pool_ptr = (uint8_t *) ph + POOL_HDRLEN;
+
+ return;
+
+ERR_MALLOC:
+ERR_MAX_SIZE:
+ *pool_ptr = NULL;
+ return;
+}
+
+void
+_pool_free (void **pool_ptr)
+{
+ pool_hdr_t *ph = pool_hdr (*pool_ptr);
+ vector_free (ph->free_indices);
+ bitmap_free (ph->free_bitmap);
+
+ free (pool_hdr (*pool_ptr));
+ *pool_ptr = NULL;
+}
+
+bool
+_pool_validate_id (void **pool_ptr, off_t id)
+{
+ pool_hdr_t *ph = pool_hdr (*pool_ptr);
+ size_t pool_size = pool_get_alloc_size (*pool_ptr);
+ if (id >= pool_size || !bitmap_is_unset (ph->free_bitmap, id))
+ return false;
+
+ return true;
+}
+
+void
+_pool_resize (void **pool_ptr, size_t elt_size)
+{
+ pool_hdr_t *ph = pool_hdr (*pool_ptr);
+ size_t old_size = ph->alloc_size;
+ size_t new_size = old_size * 2;
+
+ WARN ("pool_resize to %lu", new_size);
+
+ if (ph->max_size && new_size > ph->max_size)
+ goto ERR_MAX_SIZE;
+
+ /* Double pool storage */
+ ph = realloc (ph, POOL_HDRLEN + new_size * elt_size);
+ if (!ph)
+ goto ERR_REALLOC;
+ ph->elt_size = elt_size;
+ ph->alloc_size = new_size;
+
+ /*
+ * After resize, the pool will have new free indices, ranging from
+ * old_size to (new_size - 1)
+ */
+ vector_ensure_pos (ph->free_indices, old_size);
+ for (unsigned i = 0; i < old_size; i++)
+ ph->free_indices[i] = new_size - 1 - i;
+ vector_len (ph->free_indices) = old_size;
+
+ /* We also need to update the bitmap */
+ bitmap_ensure_pos (&(ph->free_bitmap), new_size - 1);
+ bitmap_set_range (ph->free_bitmap, old_size, new_size - 1);
+
+ /* Reassign pool pointer */
+ *pool_ptr = (uint8_t *) ph + POOL_HDRLEN;
+
+ return;
+
+ERR_REALLOC:
+ERR_MAX_SIZE:
+ *pool_ptr = NULL;
+ return;
+}
+
+off_t
+_pool_get (void **pool_ptr, void **elt, size_t elt_size)
+{
+ pool_hdr_t *ph = pool_hdr (*pool_ptr);
+ uint64_t l = vector_len (ph->free_indices);
+ if (l == 0)
+ {
+ _pool_resize (pool_ptr, elt_size);
+ ph = pool_hdr (*pool_ptr);
+ l = vector_len (ph->free_indices);
+ }
+ off_t free_id = ph->free_indices[l - 1];
+ vector_len (ph->free_indices)--;
+ bitmap_unset (ph->free_bitmap, free_id);
+ *elt = *pool_ptr + free_id * elt_size;
+ return free_id;
+}
+
+void
+_pool_put (void **pool_ptr, void **elt, size_t elt_size)
+{
+ pool_hdr_t *ph = pool_hdr (*pool_ptr);
+ uint64_t l = vector_len (ph->free_indices);
+ vector_ensure_pos (ph->free_indices, l);
+ off_t freed_id = (*elt - *pool_ptr) / elt_size;
+ ph->free_indices[l] = freed_id;
+ vector_len (ph->free_indices)++;
+ bitmap_set (ph->free_bitmap, freed_id);
+}
diff --git a/hicn-light/src/hicn/config/controlListRoutes.h b/lib/src/util/ring.c
index 341552add..2c722a842 100644
--- a/hicn-light/src/hicn/config/controlListRoutes.h
+++ b/lib/src/util/ring.c
@@ -1,5 +1,6 @@
+
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,16 +15,35 @@
*/
/**
- * @file control_ListRoutes.h
- * @brief List the icn-light routes
- *
- * Implements the "list routes" and "help list routes" nodes of the command tree
- *
+ * \file ring.c
+ * \brief Implementation of ring buffer.
*/
-#ifndef Control_ListRoutes_h
-#define Control_ListRoutes_h
-#include <hicn/config/controlState.h>
-CommandOps *controlListRoutes_Create(ControlState *state);
-CommandOps *controlListRoutes_HelpCreate(ControlState *state);
-#endif // Control_ListRoutes_h
+#include <stdlib.h>
+
+#include <hicn/util/ring.h>
+
+void
+_ring_init (void **ring_ptr, size_t elt_size, size_t max_size)
+{
+ assert (ring_ptr);
+ assert (elt_size > 0);
+ // we use a static array, not a vector (for now)
+ assert (max_size != 0);
+
+ ring_hdr_t *rh = malloc (RING_HDRLEN + max_size * elt_size);
+
+ rh->roff = 0;
+ rh->woff = 0;
+ rh->size = 0;
+ rh->max_size = max_size;
+
+ *ring_ptr = (uint8_t *) rh + RING_HDRLEN;
+}
+
+void
+_ring_free (void **ring_ptr)
+{
+ free (ring_hdr (*ring_ptr));
+ *ring_ptr = NULL;
+}
diff --git a/lib/src/util/slab.c b/lib/src/util/slab.c
new file mode 100644
index 000000000..763dcb444
--- /dev/null
+++ b/lib/src/util/slab.c
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hicn/util/pool.h>
+#include <hicn/util/slab.h>
+#include <stdlib.h>
+
+/* BLOCK LINKED LISTS */
+
+static void
+block_add_to_head (block_t **head_ptr, block_t *block)
+{
+ if (head_ptr == NULL || block == NULL)
+ return;
+
+ block->prev = NULL;
+ if (*head_ptr != NULL)
+ {
+ block->next = *head_ptr;
+ block->next->prev = block;
+ }
+
+ *head_ptr = block;
+}
+
+static block_t *
+block_remove_from_head (block_t **head_ptr)
+{
+ if (head_ptr == NULL || *head_ptr == NULL)
+ return NULL;
+
+ block_t *old_head = *head_ptr;
+ *head_ptr = old_head->next;
+
+ if (*head_ptr != NULL)
+ (*head_ptr)->prev = NULL;
+ return old_head;
+}
+
+static void
+block_remove (block_t **head_ptr, block_t *block)
+{
+ if (*head_ptr == NULL || block == NULL)
+ return;
+
+ if (block == *head_ptr)
+ *head_ptr = block->next;
+ if (block->next != NULL)
+ block->next->prev = block->prev;
+ if (block->prev != NULL)
+ block->prev->next = block->next;
+}
+
+static bool
+is_block_list_empty (block_t *block)
+{
+ return block == NULL;
+}
+
+static void
+block_list_free (block_t **head)
+{
+ if (head == NULL || *head == NULL)
+ return;
+
+ block_t *curr_block = *head;
+ while (curr_block != NULL)
+ {
+ block_t *next = curr_block->next;
+ pool_free (curr_block->pool);
+ free (curr_block);
+
+ curr_block = next;
+ }
+
+ *head = NULL;
+}
+
+/* BLOCK */
+
+static bool
+is_block_full (block_t *block)
+{
+ return pool_get_free_indices_size (block->pool) == 0;
+}
+
+static void
+block_set_ptr_in_chunks (block_t *block, size_t chunk_size)
+{
+ void *chunk = block->pool;
+
+ // Cannot use `pool_foreach()` since it requires to know the type
+ // while here we use a generic (void *)
+ for (int i = 0; i < pool_get_alloc_size (block->pool); i++)
+ {
+ chunk_hdr_t *hdr = (chunk_hdr_t *) chunk;
+ hdr->block = block;
+
+ chunk = (uint8_t *) (chunk) + chunk_size; // Move to next chunk
+ }
+}
+
+static block_t *
+block_create (size_t chunk_size, size_t num_chunks)
+{
+ block_t *block = malloc (sizeof (block_t));
+ if (block == NULL)
+ return NULL;
+
+ block->prev = block->next = NULL;
+ _pool_init (&block->pool, chunk_size, num_chunks, 0);
+ block_set_ptr_in_chunks (block, chunk_size);
+
+ return block;
+}
+
+/* SLAB */
+
+slab_t *
+_slab_create (size_t elt_size, size_t num_elts)
+{
+ // Initialize slab
+ slab_t *slab = malloc (sizeof (slab_t));
+ if (slab == NULL)
+ return NULL;
+
+ *slab = (slab_t){ .num_chunks = next_pow2 (num_elts),
+ .chunk_size = CHUNK_HDRLEN + elt_size,
+ .full = NULL,
+ .partial_or_empty = NULL };
+
+ // Add initial empty block to partial or empty list
+ block_t *block = block_create (slab->chunk_size, slab->num_chunks);
+ block_add_to_head (&slab->partial_or_empty, block);
+
+ return slab;
+}
+
+void
+slab_free (slab_t *slab)
+{
+ block_list_free (&slab->full);
+ block_list_free (&slab->partial_or_empty);
+ free (slab);
+}
+
+void *
+_slab_get (slab_t *slab)
+{
+ // Create new empty block if none with available chunks
+ if (is_block_list_empty (slab->partial_or_empty))
+ {
+ block_t *block = block_create (slab->chunk_size, slab->num_chunks);
+ block_add_to_head (&slab->partial_or_empty, block);
+
+ slab->num_chunks *= 2; // Grow size exponentially
+ }
+
+ // Get chunck from first block in 'partial_or_empty' list
+ void *chunk;
+ _pool_get (&slab->partial_or_empty->pool, &chunk, slab->chunk_size);
+
+ // If the current block (i.e. head of 'partial_or_empty' list) if full,
+ // move it to the 'full' list
+ if (is_block_full (slab->partial_or_empty))
+ {
+ block_t *block = block_remove_from_head (&slab->partial_or_empty);
+ block_add_to_head (&slab->full, block);
+ }
+
+ return (uint8_t *) chunk + CHUNK_HDRLEN;
+}
+
+void
+_slab_put (slab_t *slab, void *chunk)
+{
+ // Get which block the chunk (that we want to release) belong to
+ chunk_hdr_t *hdr = chunk_hdr (chunk);
+ block_t *block = hdr->block;
+
+ // Put chunk back into block
+ bool is_full = is_block_full (block);
+ _pool_put (&block->pool, (void *) &hdr, slab->chunk_size);
+
+ // If the block was previously full, move it to 'partial_or_empty' list
+ if (is_full)
+ {
+ block_remove (&slab->full, block);
+ block_add_to_head (&slab->partial_or_empty, block);
+ }
+} \ No newline at end of file
diff --git a/lib/src/util/types.c b/lib/src/util/types.c
new file mode 100644
index 000000000..744192593
--- /dev/null
+++ b/lib/src/util/types.c
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hicn/util/types.h>
+
+uint32_t
+htonf (float f)
+{
+ uint32_t i;
+ uint32_t sign = 0;
+
+ if (f < 0)
+ {
+ sign = 1;
+ f = -f;
+ }
+
+ // i[31] = sign bit
+ i = sign << 31;
+
+ // i[30 to 16] = int(f)[14 to 0]
+ i |= (((uint32_t) f) & 0x7fff) << 16;
+
+ // i[15 to 0] = fraction(f) bits [15 to 0]
+ i |= (uint32_t) ((f - (uint32_t) f) * 65536.0f) & 0xffff;
+
+ return i;
+}
+
+float
+ntohf (uint32_t i)
+{
+ // integer part = i[14 to 0]
+ float f = (i >> 16) & 0x7fff;
+
+ // fraction part = i[15 to 0]
+ f += (i & 0xffff) / 65536.0f;
+
+ // sign = i[31]
+ if ((i >> 31) & 1)
+ f = -f;
+
+ return f;
+}
diff --git a/lib/src/util/vector.c b/lib/src/util/vector.c
new file mode 100644
index 000000000..1f5cd0269
--- /dev/null
+++ b/lib/src/util/vector.c
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * \file vector.c
+ * \brief Implementation of resizeable static array
+ */
+
+#include <assert.h>
+#include <stddef.h> // size_t
+#include <stdlib.h> // calloc
+#include <stdio.h>
+
+#include <hicn/util/vector.h>
+
+#define DEFAULT_VECTOR_SIZE 64
+
+int
+_vector_init (void **vector_ptr, size_t elt_size, size_t init_size,
+ size_t max_size)
+{
+ assert (vector_ptr);
+ assert (max_size == 0 || init_size < max_size);
+
+ if (init_size == 0)
+ init_size = DEFAULT_VECTOR_SIZE;
+
+ *vector_ptr = NULL;
+ int rc = _vector_resize (vector_ptr, elt_size, init_size);
+ if (rc < 0)
+ return -1;
+
+ vector_hdr_t *vh = vector_hdr (*vector_ptr);
+ vh->cur_size = 0;
+ vh->max_size = max_size;
+
+ return 0;
+}
+
+void
+_vector_free (void **vector_ptr)
+{
+ free (vector_hdr (*vector_ptr));
+ *vector_ptr = NULL;
+}
+
+int
+_vector_resize (void **vector_ptr, size_t elt_size, off_t pos)
+{
+ vector_hdr_t *vh;
+ size_t old_size;
+
+ if (*vector_ptr)
+ {
+ vh = vector_hdr (*vector_ptr);
+ old_size = vh->alloc_size;
+ }
+ else
+ {
+ vh = NULL;
+ old_size = 0;
+ }
+
+ /* Round the allocated size to the next power of 2 of the requested position
+ */
+ size_t new_size = next_pow2 (pos);
+
+ /* Don't grow the vector back */
+ if (new_size < old_size)
+ return 0;
+
+ /* Don't exceed maximum size (for init, check is done beforehand) */
+ if (vh && vh->max_size && new_size > vh->max_size)
+ return -1;
+
+ vh = realloc (vh, VECTOR_HDRLEN + new_size * elt_size);
+ if (!vh)
+ return -1;
+ vh->alloc_size = new_size;
+
+ /* Zero out the newly allocated memory (except headers) */
+ memset ((uint8_t *) vh + VECTOR_HDRLEN + old_size * elt_size, 0,
+ (new_size - old_size) * elt_size);
+
+ /* Reassign vector pointer */
+ *vector_ptr = (uint8_t *) vh + VECTOR_HDRLEN;
+
+ return 0;
+}
diff --git a/lib/src/util/windows/dlfcn.c b/lib/src/util/windows/dlfcn.c
index c8173cdb0..5606074a0 100644
--- a/lib/src/util/windows/dlfcn.c
+++ b/lib/src/util/windows/dlfcn.c
@@ -1,4 +1,4 @@
-/* dlfcn.c */
+/* dlfcn.c */
#include <inttypes.h>
#include <stdio.h>
@@ -6,60 +6,68 @@
#include <string.h>
#include <windows.h>
-static struct {
- long lasterror;
- const char *err_rutin;
-} var = {
- 0,
- NULL
-};
+static struct
+{
+ long lasterror;
+ const char *err_rutin;
+} var = { 0, NULL };
-void *dlopen (const char *filename, int flags)
+void *
+dlopen (const char *filename, int flags)
{
- HINSTANCE hInst;
+ HINSTANCE hInst;
- hInst= LoadLibrary (filename);
- if (hInst==NULL) {
- var.lasterror = GetLastError ();
- var.err_rutin = "dlopen";
+ hInst = LoadLibrary (filename);
+ if (hInst == NULL)
+ {
+ var.lasterror = GetLastError ();
+ var.err_rutin = "dlopen";
}
- return hInst;
+ return hInst;
}
-int dlclose (void *handle)
+int
+dlclose (void *handle)
{
- BOOL ok;
- int rc= 0;
+ BOOL ok;
+ int rc = 0;
- ok= FreeLibrary ((HINSTANCE)handle);
- if (! ok) {
- var.lasterror = GetLastError ();
- var.err_rutin = "dlclose";
- rc= -1;
+ ok = FreeLibrary ((HINSTANCE) handle);
+ if (!ok)
+ {
+ var.lasterror = GetLastError ();
+ var.err_rutin = "dlclose";
+ rc = -1;
}
- return rc;
+ return rc;
}
-void *dlsym (void *handle, const char *name)
+void *
+dlsym (void *handle, const char *name)
{
- FARPROC fp;
+ FARPROC fp;
- fp= GetProcAddress ((HINSTANCE)handle, name);
- if (!fp) {
- var.lasterror = GetLastError ();
- var.err_rutin = "dlsym";
+ fp = GetProcAddress ((HINSTANCE) handle, name);
+ if (!fp)
+ {
+ var.lasterror = GetLastError ();
+ var.err_rutin = "dlsym";
}
- return (void *)(intptr_t)fp;
+ return (void *) (intptr_t) fp;
}
-const char *dlerror (void)
+const char *
+dlerror (void)
{
-static char errstr [88];
+ static char errstr[88];
- if (var.lasterror) {
- sprintf (errstr, "%s error #%ld", var.err_rutin, var.lasterror);
- return errstr;
- } else {
- return NULL;
+ if (var.lasterror)
+ {
+ snprintf (errstr, 88, "%s error #%ld", var.err_rutin, var.lasterror);
+ return errstr;
+ }
+ else
+ {
+ return NULL;
}
} \ No newline at end of file
diff --git a/libtransport/.clang-format b/libtransport/.clang-format
index 513da4d69..ae46ce82d 100644
--- a/libtransport/.clang-format
+++ b/libtransport/.clang-format
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/libtransport/CMakeLists.txt b/libtransport/CMakeLists.txt
index a5009f353..62c0c0788 100644
--- a/libtransport/CMakeLists.txt
+++ b/libtransport/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,29 +11,36 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+##############################################################
+# Project and cmake version
+##############################################################
# CMake 3.11 required to use FetchContent
cmake_minimum_required(VERSION 3.11 FATAL_ERROR)
-
project(libtransport)
+
+##############################################################
+# Cmake modules
+##############################################################
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
- "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
+ ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules
)
+include("${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake")
-include(DefaultConfiguration)
-include(BuildMacros)
-if (NOT CMAKE_BUILD_TYPE)
- message(STATUS "${PROJECT_NAME}: No build type selected, default to Release")
- set(CMAKE_BUILD_TYPE "Release")
-endif ()
+##############################################################
+# C/CXX Standard
+##############################################################
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_C_STANDARD 11)
-set(TRANSPORT_ROOT_PATH "src")
+##############################################################
+# Libs and Bins names
+##############################################################
set(LIBTRANSPORT hicntransport)
-set(LIBTRANSPORT_COMPONENT libhicntransport)
+set(LIBTRANSPORT_COMPONENT lib${LIBTRANSPORT})
if ((BUILD_HICNPLUGIN OR BUILD_MEMIF_CONNECTOR) AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
set(__vpp__ 1)
@@ -42,19 +49,32 @@ endif ()
set(LIBTRANSPORT ${LIBTRANSPORT} CACHE INTERNAL "" FORCE)
set(LIBTRANSPORT_SHARED ${LIBTRANSPORT}.shared CACHE INTERNAL "" FORCE)
set(LIBTRANSPORT_STATIC ${LIBTRANSPORT}.static CACHE INTERNAL "" FORCE)
-set(LIBTRANSPORT_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/src CACHE INTERNAL "" FORCE)
-include(WindowsMacros)
-include(IosMacros)
-find_package_wrapper(Asio REQUIRED)
-find_package(OpenSSL REQUIRED)
+##############################################################
+# Dependencies and third party libs
+##############################################################
+find_package(Asio ${ASIO_DEFAULT_VERSION} REQUIRED)
+find_package(OpenSSL ${OPENSSL_DEFAULT_VERSION} EXACT REQUIRED)
find_package(Threads REQUIRED)
-find_package(OpenSSL REQUIRED)
-find_package(Libconfig++ REQUIRED)
+find_package(Libconfig++ ${LIBCONFIG_DEFAULT_VERSION} REQUIRED)
+add_subdirectory(third-party)
+
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- find_package_wrapper(Libhicn REQUIRED)
+ include(CommonSetup)
+ find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
+
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
+
+ list(APPEND HICN_LIBRARIES hicn::hicn.${LIBTYPE})
else()
if (DISABLE_SHARED_LIBRARIES)
if (WIN32)
@@ -73,34 +93,16 @@ else()
endif()
endif()
-include(Packaging)
-
-add_subdirectory(third-party)
-
-set(LIBRARIES
- PRIVATE ${HICN_LIBRARIES}
- PRIVATE ${CMAKE_THREAD_LIBS_INIT}
- PRIVATE ${CMAKE_DL_LIBS}
- PRIVATE ${OPENSSL_LIBRARIES}
- PRIVATE ${LIBCONFIG_CPP_LIBRARIES}
- PRIVATE ${THIRD_PARTY_LIBRARIES}
-)
-# Include dirs -- Order does matter!
-list(APPEND LIBTRANSPORT_INTERNAL_INCLUDE_DIRS
- ${HICN_INCLUDE_DIRS}
- ${HICNPLUGIN_INCLUDE_DIRS}
- ${CMAKE_THREADS_INCLUDE_DIRS}
- ${ASIO_INCLUDE_DIRS}
- ${WINDOWS_INCLUDE_DIRS}
- ${OPENSSL_INCLUDE_DIR}
- ${CONFIG_INCLUDE_DIRS}
- ${THIRD_PARTY_INCLUDE_DIRS}
-)
+##############################################################
+# Packaging and versioning
+##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
-list(APPEND DEPENDENCIES
- ${THIRD_PARTY_DEPENDENCIES}
-)
+##############################################################
+# Subdirectories
+##############################################################
add_subdirectory(includes/hicn/transport)
-add_subdirectory(${TRANSPORT_ROOT_PATH})
+add_subdirectory(src)
diff --git a/libtransport/cmake/Modules/DefaultConfiguration.cmake b/libtransport/cmake/Modules/DefaultConfiguration.cmake
deleted file mode 100644
index 402ad86f5..000000000
--- a/libtransport/cmake/Modules/DefaultConfiguration.cmake
+++ /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.
-
-# C/c++ standard
-set(CMAKE_CXX_STANDARD 17)
-set(CMAKE_C_STANDARD 11)
-
-# Compilation flags
-
-set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
-if (NOT WIN32)
- set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fpermissive")
- set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -fpermissive")
- set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} -fpermissive")
-endif ()
-
-set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DDEBUG")
-set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
-set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO}")
-set(CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL}") \ No newline at end of file
diff --git a/libtransport/cmake/Modules/Packaging.cmake b/libtransport/cmake/packaging.cmake
index 9ff26aecc..afdf3b371 100644
--- a/libtransport/cmake/Modules/Packaging.cmake
+++ b/libtransport/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -28,7 +28,7 @@ set(${LIBTRANSPORT_COMPONENT}-dev_DESCRIPTION
CACHE STRING "Header files for developing using libhicntransport."
)
-set(${LIBTRANSPORT_COMPONENT}-devel_DESCRIPTION
+set(lib${LIBTRANSPORT}-devel_DESCRIPTION
CACHE STRING "Header files for developing using libhicntransport."
)
@@ -37,31 +37,44 @@ set(${LIBTRANSPORT_COMPONENT}-io-modules_DESCRIPTION
)
set(${LIBTRANSPORT_COMPONENT}_DEB_DEPENDENCIES
- "lib${LIBHICN} (>= stable_version), libparc (>= 1.0), libconfig++9v5 (>= 1.5-0.4build1)"
+ "lib${LIBHICN} (= stable_version), libconfig++9v5 (>= 1.5-0.4build1)"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${LIBTRANSPORT_COMPONENT}_RPM_DEPENDENCIES
- "lib${LIBHICN} >= stable_version, libparc >= 1.0, libconfig >= 1.5-9.el8"
+ "lib${LIBHICN} = stable_version, libconfig >= 1.5-9.el8"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${LIBTRANSPORT_COMPONENT}-dev_DEB_DEPENDENCIES
- "${LIBTRANSPORT_COMPONENT} (>= stable_version), libasio-dev (>= 1.10), lib${LIBHICN}-dev (>= stable_version), libparc-dev (>= 1.0), libconfig++-dev (>= 1.5-0.4build1)"
+ "${LIBTRANSPORT_COMPONENT} (= stable_version), libasio-dev (>= 1.10), lib${LIBHICN}-dev (= stable_version), libconfig++-dev (>= 1.5-0.4build1)"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${LIBTRANSPORT_COMPONENT}-dev_RPM_DEPENDENCIES
- "${LIBTRANSPORT_COMPONENT} >= stable_version, asio-devel >= 1.10, lib${LIBHICN}-devel >= stable_version, libparc-devel >= 1.0, libconfig-devel >= 1.5-9.el8"
+ "${LIBTRANSPORT_COMPONENT} = stable_version, asio-devel >= 1.10, lib${LIBHICN}-devel = stable_version, libconfig-devel >= 1.5-9.el8"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${LIBTRANSPORT_COMPONENT}-io-modules_DEB_DEPENDENCIES
- "${LIBTRANSPORT_COMPONENT} (>= stable_version), libmemif (>= stable_version), vpp (>= stable_version-release), vpp (<< next_version-release), hicn-plugin (>= stable_version)"
+ "${LIBTRANSPORT_COMPONENT} (= stable_version), vpp (>= ${PREFIX_VERSION}), hicn-plugin (= stable_version)"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${LIBTRANSPORT_COMPONENT}-io-modules_RPM_DEPENDENCIES
- "${LIBTRANSPORT_COMPONENT} >= stable_version, libmemif >= stable_version, vpp >= stable_version-release, vpp < next_version-release, hicn-plugin >= stable_version"
+ "${LIBTRANSPORT_COMPONENT} = stable_version, vpp >= ${PREFIX_VERSION}, hicn-plugin = stable_version"
CACHE STRING "Dependencies for deb/rpm package."
)
+
+if (INTERNAL_ENVIRONMENT)
+ include(CheckSsl)
+ CheckSsl()
+ set(${LIBTRANSPORT_COMPONENT}_DEB_DEPENDENCIES
+ "${${LIBTRANSPORT_COMPONENT}_DEB_DEPENDENCIES}, ${OPENSSL_DEPENDENCY}"
+ CACHE STRING "Dependencies for deb/rpm package."
+ )
+ set(${LIBTRANSPORT_COMPONENT}-dev_DEB_DEPENDENCIES
+ "${${LIBTRANSPORT_COMPONENT}-dev_DEB_DEPENDENCIES}, ${OPENSSL_DEPENDENCY_DEV}"
+ CACHE STRING "Dependencies for deb/rpm package."
+ )
+endif ()
diff --git a/libtransport/includes/hicn/transport/CMakeLists.txt b/libtransport/includes/hicn/transport/CMakeLists.txt
index eb339fb5a..8b9f907b9 100644
--- a/libtransport/includes/hicn/transport/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2020 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -23,14 +23,21 @@ add_subdirectory(portability)
add_subdirectory(auth)
add_subdirectory(utils)
-set(LIBTRANSPORT_INCLUDE_DIRS
- ${CMAKE_CURRENT_SOURCE_DIR}/../.. ""
+
+##############################################################
+# Public headers directory
+##############################################################
+set(Libhicntransport_INCLUDE_DIRS
+ ${CMAKE_CURRENT_SOURCE_DIR}/../..
CACHE INTERNAL
"" FORCE
)
+
+##############################################################
+# Header files to install
+##############################################################
set(LIBHICNTRANSPORT_TO_INSTALL_HEADER_FILES
- ${HEADER_FILES} ""
- CACHE INTERNAL
- "" FORCE
+ ${HEADER_FILES}
+ PARENT_SCOPE
)
diff --git a/libtransport/includes/hicn/transport/auth/CMakeLists.txt b/libtransport/includes/hicn/transport/auth/CMakeLists.txt
index 1e9fe4698..0b5ae1836 100644
--- a/libtransport/includes/hicn/transport/auth/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/auth/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -15,7 +15,6 @@ list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/common.h
${CMAKE_CURRENT_SOURCE_DIR}/crypto_hash.h
${CMAKE_CURRENT_SOURCE_DIR}/crypto_suite.h
- ${CMAKE_CURRENT_SOURCE_DIR}/identity.h
${CMAKE_CURRENT_SOURCE_DIR}/key_id.h
${CMAKE_CURRENT_SOURCE_DIR}/policies.h
${CMAKE_CURRENT_SOURCE_DIR}/signer.h
diff --git a/libtransport/includes/hicn/transport/auth/common.h b/libtransport/includes/hicn/transport/auth/common.h
index fb0e82eb7..d2282436e 100644
--- a/libtransport/includes/hicn/transport/auth/common.h
+++ b/libtransport/includes/hicn/transport/auth/common.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/auth/crypto_hash.h b/libtransport/includes/hicn/transport/auth/crypto_hash.h
index 90f1627e9..9535e07c7 100644
--- a/libtransport/includes/hicn/transport/auth/crypto_hash.h
+++ b/libtransport/includes/hicn/transport/auth/crypto_hash.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -27,8 +27,6 @@ extern "C" {
namespace transport {
namespace auth {
-typedef const EVP_MD *(*CryptoHashEVP)(void);
-
enum class CryptoHashType : uint8_t {
UNKNOWN,
SHA256,
@@ -42,7 +40,7 @@ class CryptoHash {
// Constructors
CryptoHash();
CryptoHash(const CryptoHash &other);
- CryptoHash(CryptoHash &&other);
+ CryptoHash(CryptoHash &&other) noexcept;
CryptoHash(CryptoHashType hash_type);
CryptoHash(const uint8_t *hash, std::size_t size, CryptoHashType hash_type);
CryptoHash(const std::vector<uint8_t> &hash, CryptoHashType hash_type);
@@ -57,12 +55,10 @@ class CryptoHash {
// Compute the hash of given buffer
void computeDigest(const uint8_t *buffer, std::size_t len);
void computeDigest(const std::vector<uint8_t> &buffer);
-
- // Compute the hash of given membuf
void computeDigest(const utils::MemBuf *buffer);
// Return the computed hash
- std::vector<uint8_t> getDigest() const;
+ const utils::MemBuf::Ptr &getDigest() const;
// Return the computed hash as a string
std::string getStringDigest() const;
@@ -82,19 +78,19 @@ class CryptoHash {
// Reset hash
void reset();
- // Return OpenSSL EVP function associated to a given hash type
- static CryptoHashEVP getEVP(CryptoHashType hash_type);
+ // Return the OpenSSL EVP_MD pointer associated to a given hash type
+ static const EVP_MD *getMD(CryptoHashType hash_type);
// Return hash size
static std::size_t getSize(CryptoHashType hash_type);
// Compare two raw buffers
- static bool compareDigest(const uint8_t *h1, const uint8_t *h2,
+ static bool compareDigest(const uint8_t *digest1, const uint8_t *digest2,
CryptoHashType hash_type);
private:
CryptoHashType digest_type_;
- std::vector<uint8_t> digest_;
+ utils::MemBuf::Ptr digest_;
std::size_t digest_size_;
};
diff --git a/libtransport/includes/hicn/transport/auth/crypto_suite.h b/libtransport/includes/hicn/transport/auth/crypto_suite.h
index d0f1de395..f3b535264 100644
--- a/libtransport/includes/hicn/transport/auth/crypto_suite.h
+++ b/libtransport/includes/hicn/transport/auth/crypto_suite.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,29 +26,36 @@ namespace auth {
enum class CryptoSuite : uint8_t {
UNKNOWN,
+ DSA_BLAKE2B512,
+ DSA_BLAKE2S256,
+ DSA_SHA256,
+ DSA_SHA512,
ECDSA_BLAKE2B512,
ECDSA_BLAKE2S256,
ECDSA_SHA256,
ECDSA_SHA512,
- RSA_BLAKE2B512,
- RSA_BLAKE2S256,
- RSA_SHA256,
- RSA_SHA512,
+ ED25519,
+ ED448,
HMAC_BLAKE2B512,
HMAC_BLAKE2S256,
HMAC_SHA256,
HMAC_SHA512,
- DSA_BLAKE2B512,
- DSA_BLAKE2S256,
- DSA_SHA256,
- DSA_SHA512,
+ RSA_BLAKE2B512,
+ RSA_BLAKE2S256,
+ RSA_SHA256,
+ RSA_SHA512,
};
// Return the suite associated to the given NID
CryptoSuite getSuite(int nid);
+// Return the string representation of given suite
+std::string getStringSuite(CryptoSuite suite);
+
// Return the hash type associated to the given suite
CryptoHashType getHashType(CryptoSuite suite);
+// Return the OpenSSL EVP_MD pointer associated to a given suite
+const EVP_MD *getMD(CryptoSuite suite);
} // namespace auth
} // namespace transport
diff --git a/libtransport/includes/hicn/transport/auth/identity.h b/libtransport/includes/hicn/transport/auth/identity.h
deleted file mode 100644
index be072f5d3..000000000
--- a/libtransport/includes/hicn/transport/auth/identity.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <errno.h>
-#include <fcntl.h>
-#include <hicn/transport/auth/signer.h>
-#include <unistd.h>
-
-extern "C" {
-#include <openssl/pkcs12.h>
-#include <openssl/rand.h>
-#include <openssl/x509.h>
-#include <openssl/x509v3.h>
-}
-
-namespace transport {
-namespace auth {
-
-class Identity {
- // This class holds several information about a client, including its public
- // key.
- public:
- // Generate a new identity from the given parameters. The identity will be
- // saved in 'keystore_path' and encrypted using 'keystore_pwd'.
- Identity(const std::string &keystore_path, const std::string &keystore_pwd,
- CryptoSuite suite, unsigned int signature_len,
- unsigned int validity_days, const std::string &subject_name);
-
- // Create an identity from an already existing keystore path.
- Identity(std::string &keystore_path, std::string &keystore_pwd,
- CryptoHashType hash_type);
-
- Identity(const Identity &other);
- Identity(Identity &&other);
- ~Identity();
-
- // Return the asymmetric signer object created from the public key.
- std::shared_ptr<AsymmetricSigner> getSigner() const;
-
- // Return the key store filename.
- std::string getFilename() const;
-
- // Return the key store password.
- std::string getPassword() const;
-
- std::shared_ptr<X509> getCertificate() const;
-
- std::shared_ptr<EVP_PKEY> getPrivateKey() const;
-
- // Generate a new random identity.
- static Identity generateIdentity(const std::string &subject_name = "");
-
- private:
- static void free_key(EVP_PKEY *T) { EVP_PKEY_free(T); }
-
- std::string pwd_;
- std::string filename_;
- std::shared_ptr<AsymmetricSigner> signer_;
- std::shared_ptr<X509> cert_;
-};
-
-} // namespace auth
-} // namespace transport
diff --git a/libtransport/includes/hicn/transport/auth/key_id.h b/libtransport/includes/hicn/transport/auth/key_id.h
index 3aa09336f..8723ae698 100644
--- a/libtransport/includes/hicn/transport/auth/key_id.h
+++ b/libtransport/includes/hicn/transport/auth/key_id.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/auth/policies.h b/libtransport/includes/hicn/transport/auth/policies.h
index 00464d54b..b9755595c 100644
--- a/libtransport/includes/hicn/transport/auth/policies.h
+++ b/libtransport/includes/hicn/transport/auth/policies.h
@@ -23,10 +23,10 @@ namespace auth {
* perform after verification.
*/
enum class VerificationPolicy {
+ UNKNOWN,
ABORT,
- ACCEPT,
DROP,
- UNKNOWN,
+ ACCEPT,
};
} // namespace auth
diff --git a/libtransport/includes/hicn/transport/auth/signer.h b/libtransport/includes/hicn/transport/auth/signer.h
index 405dd83cf..f9e07efae 100644
--- a/libtransport/includes/hicn/transport/auth/signer.h
+++ b/libtransport/includes/hicn/transport/auth/signer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,18 +21,19 @@
#include <hicn/transport/errors/errors.h>
#include <hicn/transport/utils/membuf.h>
+#include <memory>
extern "C" {
#include <openssl/evp.h>
#include <openssl/hmac.h>
+#include <openssl/pkcs12.h>
+#include <openssl/x509.h>
}
namespace transport {
namespace auth {
-class Identity;
class Signer {
// The base class from which all signer classes derive.
- friend class Identity;
public:
Signer();
@@ -41,11 +42,15 @@ class Signer {
// Sign a packet.
virtual void signPacket(PacketPtr packet);
+ virtual void signBuffer(const uint8_t *buffer, std::size_t len);
virtual void signBuffer(const std::vector<uint8_t> &buffer);
virtual void signBuffer(const utils::MemBuf *buffer);
// Return the signature.
- std::vector<uint8_t> getSignature() const;
+ const utils::MemBuf::Ptr &getSignature() const;
+
+ // Return the signature as a string.
+ std::string getStringSignature() const;
// Return the signature size in bytes.
virtual std::size_t getSignatureSize() const;
@@ -61,9 +66,12 @@ class Signer {
// Return the hash algorithm associated to the signer.
CryptoHashType getHashType() const;
+ // Print signature to stdout.
+ void display();
+
protected:
CryptoSuite suite_;
- std::vector<uint8_t> signature_;
+ utils::MemBuf::Ptr signature_;
std::size_t signature_len_;
std::shared_ptr<EVP_PKEY> key_;
CryptoHash key_id_;
@@ -75,6 +83,7 @@ class VoidSigner : public Signer {
VoidSigner() = default;
void signPacket(PacketPtr packet) override;
+ void signBuffer(const uint8_t *buffer, std::size_t len) override;
void signBuffer(const std::vector<uint8_t> &buffer) override;
void signBuffer(const utils::MemBuf *buffer) override;
};
@@ -84,10 +93,17 @@ class AsymmetricSigner : public Signer {
public:
AsymmetricSigner() = default;
- // Construct an AsymmetricSigner from a key store and a given crypto suite.
+ // Create an AsymmetricSigner from a keystore file (.p12).
+ AsymmetricSigner(std::string keystore_path, std::string password);
+
+ // Construct an AsymmetricSigner from a key store and a given crypto
+ // suite.
AsymmetricSigner(CryptoSuite suite, std::shared_ptr<EVP_PKEY> key,
std::shared_ptr<EVP_PKEY> pub_key);
+ void setKey(CryptoSuite suite, std::shared_ptr<EVP_PKEY> key,
+ std::shared_ptr<EVP_PKEY> pub_key);
+
std::size_t getSignatureFieldSize() const override;
};
diff --git a/libtransport/includes/hicn/transport/auth/verifier.h b/libtransport/includes/hicn/transport/auth/verifier.h
index 6321d4ed5..2e086df4f 100644
--- a/libtransport/includes/hicn/transport/auth/verifier.h
+++ b/libtransport/includes/hicn/transport/auth/verifier.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -40,9 +40,9 @@ class Verifier {
// The VerificationFailedCallback will be called by the transport if a
// data packet (either a manifest or a content object) was not validated.
// The application decides what to do then by returning a
- // VerificationPolicy object.
+ // new VerificationPolicy.
using VerificationFailedCallback = std::function<auth::VerificationPolicy(
- const core::ContentObject &content_object, std::error_code ec)>;
+ Suffix suffix, VerificationPolicy policy)>;
// The list of VerificationPolicy that will trigger the
// VerificationFailedCallback.
@@ -54,12 +54,15 @@ class Verifier {
// Verify a single packet or buffer.
virtual bool verifyPacket(PacketPtr packet);
+ virtual bool verifyBuffer(const uint8_t *buffer, std::size_t len,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) = 0;
virtual bool verifyBuffer(const std::vector<uint8_t> &buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) = 0;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) = 0;
virtual bool verifyBuffer(const utils::MemBuf *buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) = 0;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) = 0;
// Verify a batch of packets. Return a mapping from packet suffixes to their
// VerificationPolicy.
@@ -96,13 +99,13 @@ class Verifier {
void getVerificationFailedCallback(
VerificationFailedCallback **verification_failed_cb);
+ // Call VerificationFailedCallback if it is set and update the packet policy.
+ void callVerificationFailedCallback(Suffix suffix,
+ VerificationPolicy &policy);
+
protected:
VerificationFailedCallback verification_failed_cb_;
std::vector<VerificationPolicy> failed_policies_;
-
- // Call VerificationFailedCallback if it is set and update the packet policy.
- void callVerificationFailedCallback(PacketPtr packet,
- VerificationPolicy &policy);
};
class VoidVerifier : public Verifier {
@@ -110,12 +113,15 @@ class VoidVerifier : public Verifier {
// and always returns true.
public:
bool verifyPacket(PacketPtr packet) override;
+ bool verifyBuffer(const uint8_t *buffer, std::size_t len,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
bool verifyBuffer(const std::vector<uint8_t> &buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) override;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
bool verifyBuffer(const utils::MemBuf *buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) override;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
PolicyMap verifyPackets(const std::vector<PacketPtr> &packets) override;
@@ -143,12 +149,15 @@ class AsymmetricVerifier : public Verifier {
void useCertificate(const std::string &cert_path);
void useCertificate(std::shared_ptr<X509> cert);
+ bool verifyBuffer(const uint8_t *buffer, std::size_t len,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
bool verifyBuffer(const std::vector<uint8_t> &buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) override;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
bool verifyBuffer(const utils::MemBuf *buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) override;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
private:
std::shared_ptr<EVP_PKEY> key_;
@@ -166,12 +175,15 @@ class SymmetricVerifier : public Verifier {
// Create and set a symmetric key from a passphrase.
void setPassphrase(const std::string &passphrase);
+ bool verifyBuffer(const uint8_t *buffer, std::size_t len,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
bool verifyBuffer(const std::vector<uint8_t> &buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) override;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
bool verifyBuffer(const utils::MemBuf *buffer,
- const std::vector<uint8_t> &signature,
- CryptoHashType hash_type) override;
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) override;
protected:
std::shared_ptr<EVP_PKEY> key_;
diff --git a/libtransport/includes/hicn/transport/core/CMakeLists.txt b/libtransport/includes/hicn/transport/core/CMakeLists.txt
index 14c795a7a..34048d93a 100644
--- a/libtransport/includes/hicn/transport/core/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/core/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/core/asio_wrapper.h b/libtransport/includes/hicn/transport/core/asio_wrapper.h
index 78cad35dc..41b660587 100644
--- a/libtransport/includes/hicn/transport/core/asio_wrapper.h
+++ b/libtransport/includes/hicn/transport/core/asio_wrapper.h
@@ -23,6 +23,9 @@ TRANSPORT_CLANG_DISABLE_WARNING("-Wdeprecated-declarations")
#ifndef ASIO_STANDALONE
#define ASIO_STANDALONE
#endif
+#ifdef __APPLE__
+TRANSPORT_CLANG_DISABLE_WARNING("-Wshorten-64-to-32")
+#endif
#include <asio.hpp>
TRANSPORT_POP_WARNING
diff --git a/libtransport/includes/hicn/transport/core/connector.h b/libtransport/includes/hicn/transport/core/connector.h
index dcf38cdc8..7882b285d 100644
--- a/libtransport/includes/hicn/transport/core/connector.h
+++ b/libtransport/includes/hicn/transport/core/connector.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#pragma once
+#include <glog/logging.h>
#include <hicn/transport/core/connector_stats.h>
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/endpoint.h>
@@ -29,6 +30,7 @@
#include <deque>
#include <functional>
+#include <system_error>
namespace transport {
@@ -50,54 +52,51 @@ class Connector : public std::enable_shared_from_this<Connector> {
enum class Role : std::uint8_t { CONSUMER, PRODUCER };
- public:
static constexpr std::size_t queue_size = 4096;
static constexpr std::uint32_t invalid_connector = ~0;
-
-#ifdef LINUX
+ static constexpr std::uint32_t max_reconnection_reattempts = 5;
static constexpr std::uint16_t max_burst = 256;
-#endif
using Ptr = std::shared_ptr<Connector>;
- using PacketQueue = std::deque<Packet::Ptr>;
+ using ReceptionBuffer = std::vector<utils::MemBuf::Ptr>;
+ using PacketQueue = std::deque<utils::MemBuf::Ptr>;
using PacketReceivedCallback = std::function<void(
- Connector *, utils::MemBuf &, const std::error_code &)>;
+ Connector *, const ReceptionBuffer &, const std::error_code &)>;
using PacketSentCallback =
std::function<void(Connector *, const std::error_code &)>;
using OnCloseCallback = std::function<void(Connector *)>;
- using OnReconnectCallback = std::function<void(Connector *)>;
+ using OnReconnectCallback =
+ std::function<void(Connector *, const std::error_code &)>;
using Id = std::uint64_t;
template <typename ReceiveCallback, typename SentCallback, typename OnClose,
typename OnReconnect>
Connector(ReceiveCallback &&receive_callback, SentCallback &&packet_sent,
OnClose &&close_callback, OnReconnect &&on_reconnect)
- : receive_callback_(std::forward<ReceiveCallback &&>(receive_callback)),
- sent_callback_(std::forward<SentCallback &&>(packet_sent)),
- on_close_callback_(std::forward<OnClose &&>(close_callback)),
- on_reconnect_callback_(std::forward<OnReconnect &&>(on_reconnect)),
- state_(State::CLOSED),
- connector_id_(invalid_connector) {}
+ : receive_callback_(std::forward<ReceiveCallback>(receive_callback)),
+ sent_callback_(std::forward<SentCallback>(packet_sent)),
+ on_close_callback_(std::forward<OnClose>(close_callback)),
+ on_reconnect_callback_(std::forward<OnReconnect>(on_reconnect)) {}
virtual ~Connector(){};
template <typename ReceiveCallback>
void setReceiveCallback(ReceiveCallback &&callback) {
- receive_callback_ = std::forward<ReceiveCallback &&>(callback);
+ receive_callback_ = std::forward<ReceiveCallback>(callback);
}
template <typename SentCallback>
void setSentCallback(SentCallback &&callback) {
- sent_callback_ = std::forward<SentCallback &&>(callback);
+ sent_callback_ = std::forward<SentCallback>(callback);
}
template <typename OnClose>
void setOnCloseCallback(OnClose &&callback) {
- on_close_callback_ = std::forward<OnClose &&>(callback);
+ on_close_callback_ = std::forward<OnClose>(callback);
}
template <typename OnReconnect>
- void setReconnectCallback(const OnReconnect &&callback) {
+ void setReconnectCallback(OnReconnect &&callback) {
on_reconnect_callback_ = std::forward<OnReconnect>(callback);
}
@@ -115,7 +114,15 @@ class Connector : public std::enable_shared_from_this<Connector> {
virtual void send(Packet &packet) = 0;
- virtual void send(const uint8_t *packet, std::size_t len) = 0;
+ virtual void send(const utils::MemBuf::Ptr &buffer) = 0;
+
+ virtual void receive(const std::vector<utils::MemBuf::Ptr> &buffers) {
+ receive_callback_(this, buffers, std::make_error_code(std::errc()));
+ }
+
+ virtual void reconnect() {
+ on_reconnect_callback_(this, std::make_error_code(std::errc()));
+ }
virtual void close() = 0;
@@ -127,36 +134,48 @@ class Connector : public std::enable_shared_from_this<Connector> {
Id getConnectorId() { return connector_id_; }
- void setConnectorName(std::string connector_name) {
+ void setConnectorName(const std::string &connector_name) {
connector_name_ = connector_name;
}
- std::string getConnectorName() { return connector_name_; }
+ std::string getConnectorName() const { return connector_name_; }
+
+ template <typename EP>
+ void setLocalEndpoint(EP &&endpoint) {
+ local_endpoint_ = std::forward<EP>(endpoint);
+ }
- Endpoint getLocalEndpoint() { return local_endpoint_; }
+ Endpoint getLocalEndpoint() const { return local_endpoint_; }
- Endpoint getRemoteEndpoint() { return remote_endpoint_; }
+ Endpoint getRemoteEndpoint() const { return remote_endpoint_; }
void setRole(Role r) { role_ = r; }
- Role getRole() { return role_; }
+ Role getRole() const { return role_; }
static utils::MemBuf::Ptr getPacketFromBuffer(uint8_t *buffer,
std::size_t size) {
utils::MemBuf::Ptr ret;
- auto format = Packet::getFormatFromBuffer(buffer, size);
+ hicn_packet_buffer_t pkbuf;
+ hicn_packet_set_buffer(&pkbuf, buffer, size, size);
+ hicn_packet_analyze(&pkbuf);
+ hicn_packet_type_t type = hicn_packet_get_type(&pkbuf);
- if (TRANSPORT_EXPECT_TRUE(format != HF_UNSPEC && !_is_icmp(format))) {
- if (Packet::isInterest(buffer)) {
+ // XXX reuse pkbuf when creating the packet, to avoid reanalyzing it
+
+ switch (type) {
+ case HICN_PACKET_TYPE_INTEREST:
ret = core::PacketManager<>::getInstance()
.getPacketFromExistingBuffer<Interest>(buffer, size);
- } else {
+ break;
+ case HICN_PACKET_TYPE_DATA:
ret = core::PacketManager<>::getInstance()
.getPacketFromExistingBuffer<ContentObject>(buffer, size);
- }
- } else {
- ret = core::PacketManager<>::getInstance().getMemBuf(buffer, size);
+ break;
+ default:
+ ret = core::PacketManager<>::getInstance().getMemBuf(buffer, size);
+ break;
}
return ret;
@@ -191,8 +210,8 @@ class Connector : public std::enable_shared_from_this<Connector> {
OnReconnectCallback on_reconnect_callback_;
// Connector state
- std::atomic<State> state_;
- Id connector_id_;
+ std::atomic<State> state_ = State::CLOSED;
+ Id connector_id_ = invalid_connector;
// Endpoints
Endpoint local_endpoint_;
@@ -206,6 +225,9 @@ class Connector : public std::enable_shared_from_this<Connector> {
// Stats
AtomicConnectorStats stats_;
+
+ // Connection attempts
+ std::uint32_t connection_reattempts_ = 0;
};
} // namespace core
diff --git a/libtransport/includes/hicn/transport/core/content_object.h b/libtransport/includes/hicn/transport/core/content_object.h
index 38baafc69..3d6d98c48 100644
--- a/libtransport/includes/hicn/transport/core/content_object.h
+++ b/libtransport/includes/hicn/transport/core/content_object.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,41 +29,37 @@ namespace core {
class ContentObject : public Packet {
public:
using Ptr = std::shared_ptr<ContentObject>;
- using HICNContentObject = hicn_header_t;
+ using HICNContentObject = u8;
- ContentObject(Packet::Format format = HF_INET6_TCP,
- std::size_t additional_header_size = 0);
+ ContentObject(Packet::Format format, std::size_t additional_header_size = 0);
- ContentObject(const Name &name, Packet::Format format = HF_INET6_TCP,
+ ContentObject(const Name &name, Packet::Format format,
std::size_t additional_header_size = 0);
- ContentObject(const Name &name, hicn_format_t format,
+ ContentObject(const Name &name, hicn_packet_format_t format,
std::size_t additional_header_size, const uint8_t *payload,
std::size_t payload_size);
template <typename... Args>
- ContentObject(CopyBufferOp op, Args &&... args)
+ ContentObject(CopyBufferOp op, Args &&...args)
: Packet(op, std::forward<Args>(args)...) {
- if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) <
- 0) {
+ if (hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
template <typename... Args>
- ContentObject(WrapBufferOp op, Args &&... args)
+ ContentObject(WrapBufferOp op, Args &&...args)
: Packet(op, std::forward<Args>(args)...) {
- if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) <
- 0) {
+ if (hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
template <typename... Args>
- ContentObject(CreateOp op, Args &&... args)
- : Packet(op, std::forward<Args>(args)...) {
- if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) <
- 0) {
+ ContentObject(CreateOp op, Args &&...args)
+ : Packet(op, HICN_PACKET_TYPE_DATA, std::forward<Args>(args)...) {
+ if (hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
@@ -82,13 +78,13 @@ class ContentObject : public Packet {
void setName(const Name &name) override;
- uint32_t getPathLabel() const;
+ hicn_path_label_t getPathLabel() const;
- ContentObject &setPathLabel(uint32_t path_label);
+ ContentObject &setPathLabel(hicn_path_label_t path_label);
- void setLocator(const ip_address_t &ip_address) override;
+ void setLocator(const hicn_ip_address_t &ip_address) override;
- ip_address_t getLocator() const override;
+ hicn_ip_address_t getLocator() const override;
void setLifetime(uint32_t lifetime) override;
@@ -96,6 +92,10 @@ class ContentObject : public Packet {
auto shared_from_this() { return utils::shared_from(this); }
+ bool isLast() const;
+
+ void setLast();
+
private:
void resetForHash() override;
};
diff --git a/libtransport/includes/hicn/transport/core/endpoint.h b/libtransport/includes/hicn/transport/core/endpoint.h
index cb6b0f562..2278a1759 100644
--- a/libtransport/includes/hicn/transport/core/endpoint.h
+++ b/libtransport/includes/hicn/transport/core/endpoint.h
@@ -42,22 +42,28 @@ class Endpoint {
~Endpoint() = default;
Endpoint &operator=(const Endpoint &other) {
- address_ = other.address_;
- port_ = other.port_;
+ if (this != &other) {
+ address_ = other.address_;
+ port_ = other.port_;
+ }
+
return *this;
}
Endpoint &operator=(Endpoint &&other) {
- address_ = std::move(other.address_);
- port_ = std::move(other.port_);
+ if (this != &other) {
+ address_ = std::move(other.address_);
+ port_ = std::move(other.port_);
+ }
+
return *this;
}
#if 0
template <typename Ip, typename Port>
Endpoint(Ip &&ip_address, Port &&port)
- : address_(std::forward<Ip &&>(ip_address)),
- port_(std::forward<Port &&>(port)) {}
+ : address_(std::forward<Ip>(ip_address)),
+ port_(std::forward<Port>(port)) {}
#endif
asio::ip::address getAddress() { return address_; }
diff --git a/libtransport/includes/hicn/transport/core/global_object_pool.h b/libtransport/includes/hicn/transport/core/global_object_pool.h
index d7f3a9e41..f98df521f 100644
--- a/libtransport/includes/hicn/transport/core/global_object_pool.h
+++ b/libtransport/includes/hicn/transport/core/global_object_pool.h
@@ -27,9 +27,10 @@ namespace transport {
namespace core {
template <std::size_t packet_pool_size = 1024, std::size_t chunk_size = 2048>
-class PacketManager
- : public utils::Singleton<PacketManager<packet_pool_size, chunk_size>> {
- friend class utils::Singleton<PacketManager<packet_pool_size, chunk_size>>;
+class PacketManager : public utils::ThreadLocalSingleton<
+ PacketManager<packet_pool_size, chunk_size>> {
+ friend class utils::ThreadLocalSingleton<
+ PacketManager<packet_pool_size, chunk_size>>;
public:
using MemoryPool = utils::FixedBlockAllocator<chunk_size, packet_pool_size>;
@@ -71,7 +72,10 @@ class PacketManager
template <
typename PacketType, typename... Args,
typename = std::enable_if_t<std::is_base_of<Packet, PacketType>::value>>
- typename PacketType::Ptr getPacket(Args &&... args) {
+ typename PacketType::Ptr getPacket(Args &&...args) {
+ static_assert(sizeof(PacketType) + sizeof(std::shared_ptr<PacketType>) +
+ sizeof(std::max_align_t) <=
+ sizeof(PacketStorage::packet_and_shared_ptr));
PacketType *memory = nullptr;
memory = reinterpret_cast<PacketType *>(memory_pool_.allocateBlock());
@@ -98,7 +102,7 @@ class PacketManager
template <typename PacketType, typename... Args>
typename PacketType::Ptr getPacketFromExistingBuffer(uint8_t *buffer,
std::size_t length,
- Args &&... args) {
+ Args &&...args) {
auto offset = offsetof(PacketStorage, align);
auto memory = reinterpret_cast<PacketType *>(buffer - offset);
utils::STLAllocator<PacketType, MemoryPool> allocator(memory,
diff --git a/libtransport/includes/hicn/transport/core/interest.h b/libtransport/includes/hicn/transport/core/interest.h
index a5b9cf375..270ea7027 100644
--- a/libtransport/includes/hicn/transport/core/interest.h
+++ b/libtransport/includes/hicn/transport/core/interest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,6 +21,10 @@
#include <set>
+extern "C" {
+#include <hicn/interest_manifest.h>
+}
+
namespace transport {
namespace core {
@@ -29,46 +33,35 @@ const uint32_t MAX_AGGREGATED_INTEREST = 128;
class Interest
: public Packet /*, public std::enable_shared_from_this<Interest>*/ {
- private:
- struct InterestManifestHeader {
- /* This can be 16 bits, but we use 32 bits for alignment */
- uint32_t n_suffixes;
- /* Followed by the list of prefixes to ask */
- /* ... */
- };
-
public:
using Ptr = std::shared_ptr<Interest>;
- Interest(Packet::Format format = HF_INET6_TCP,
- std::size_t additional_header_size = 0);
+ Interest(Packet::Format format, std::size_t additional_header_size = 0);
- Interest(const Name &interest_name, Packet::Format format = HF_INET6_TCP,
+ Interest(const Name &interest_name, Packet::Format format,
std::size_t additional_header_size = 0);
Interest(MemBuf &&buffer);
template <typename... Args>
- Interest(CopyBufferOp op, Args &&... args)
+ Interest(CopyBufferOp op, Args &&...args)
: Packet(op, std::forward<Args>(args)...) {
- if (hicn_interest_get_name(format_, packet_start_,
- name_.getStructReference()) < 0) {
+ if (hicn_interest_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
template <typename... Args>
- Interest(WrapBufferOp op, Args &&... args)
+ Interest(WrapBufferOp op, Args &&...args)
: Packet(op, std::forward<Args>(args)...) {
- if (hicn_interest_get_name(format_, packet_start_,
- name_.getStructReference()) < 0) {
+ if (hicn_interest_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
template <typename... Args>
- Interest(CreateOp op, Args &&... args)
- : Packet(op, std::forward<Args>(args)...) {}
+ Interest(CreateOp op, Args &&...args)
+ : Packet(op, HICN_PACKET_TYPE_INTEREST, std::forward<Args>(args)...) {}
/* Move constructor */
Interest(Interest &&other_interest);
@@ -87,24 +80,36 @@ class Interest
void setName(const Name &name) override;
- void setLocator(const ip_address_t &ip_address) override;
+ void setLocator(const hicn_ip_address_t &ip_address) override;
- ip_address_t getLocator() const override;
+ hicn_ip_address_t getLocator() const override;
void setLifetime(uint32_t lifetime) override;
uint32_t getLifetime() const override;
- bool hasManifest();
+ bool hasManifest() const;
void appendSuffix(std::uint32_t suffix);
void encodeSuffixes();
+ void serializeSuffixes();
+
+ void deserializeSuffixes();
+
uint32_t *firstSuffix();
uint32_t numberOfSuffixes();
+ hicn_uword *getRequestBitmap();
+
+ interest_manifest_header_t *getIntManifestHeader();
+
+ void setRequestBitmap(const uint32_t *request_bitmap);
+
+ bool isValid();
+
auto shared_from_this() { return utils::shared_from(this); }
private:
diff --git a/libtransport/includes/hicn/transport/core/io_module.h b/libtransport/includes/hicn/transport/core/io_module.h
index ea3cf4e16..cfaa61975 100644
--- a/libtransport/includes/hicn/transport/core/io_module.h
+++ b/libtransport/includes/hicn/transport/core/io_module.h
@@ -19,6 +19,7 @@
#include <hicn/transport/core/connector.h>
#include <hicn/transport/core/packet.h>
#include <hicn/transport/core/prefix.h>
+#include <hicn/transport/portability/endianess.h>
#include <hicn/transport/portability/portability.h>
#include <hicn/transport/utils/chrono_typedefs.h>
#include <hicn/transport/utils/membuf.h>
@@ -40,7 +41,7 @@ typedef struct {
class Connector;
-class IoModule {
+class IoModule : utils::NonCopyable {
protected:
IoModule()
: inet_address_({}),
@@ -48,13 +49,12 @@ class IoModule {
mtu_(1500),
output_interface_(""),
content_store_reserved_(5000) {
- inet_address_.v4.as_u32 = htonl(0x7f00001);
+ inet_address_.v4.as_u32 = portability::host_to_net(0x7f00001);
inet6_address_.v6.as_u8[15] = 0x01;
}
public:
static IoModule *load(const char *);
- static bool unload(IoModule *);
public:
virtual ~IoModule();
@@ -64,15 +64,21 @@ class IoModule {
virtual bool isConnected() = 0;
virtual void init(Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
Connector::OnReconnectCallback &&reconnect_callback,
asio::io_service &io_service,
const std::string &app_name = "Libtransport") = 0;
virtual void registerRoute(const Prefix &prefix) = 0;
+ virtual void sendMapme() {}
+
+ virtual void setForwardingStrategy(const Prefix &prefix,
+ std::string &strategy){};
virtual std::uint32_t getMtu() = 0;
- virtual bool isControlMessage(const uint8_t *message) = 0;
+ virtual bool isControlMessage(utils::MemBuf &packet_buffer) = 0;
virtual void processControlMessageReply(utils::MemBuf &packet_buffer) = 0;
@@ -82,14 +88,14 @@ class IoModule {
counters_.tx_packets++;
counters_.tx_bytes += packet.payloadSize() + packet.headerSize();
- if (_is_ipv4(packet.getFormat())) {
+ if (HICN_PACKET_FORMAT_IS_IPV4(packet.getFormat())) {
packet.setLocator(inet_address_);
} else {
packet.setLocator(inet6_address_);
}
}
- virtual void send(const uint8_t *packet, std::size_t len) = 0;
+ virtual void send(const utils::MemBuf::Ptr &buffer) = 0;
void setContentStoreSize(uint32_t cs_size) {
content_store_reserved_ = cs_size;
@@ -103,14 +109,9 @@ class IoModule {
const std::string &getOutputInterface() { return output_interface_; }
-#ifndef ANDROID
- private:
- void *handle_;
-#endif
-
protected:
- ip_address_t inet_address_;
- ip_address_t inet6_address_;
+ hicn_ip_address_t inet_address_;
+ hicn_ip_address_t inet6_address_;
uint16_t mtu_;
std::string output_interface_;
uint32_t content_store_reserved_;
diff --git a/libtransport/includes/hicn/transport/core/name.h b/libtransport/includes/hicn/transport/core/name.h
index 033582289..14ea10898 100644
--- a/libtransport/includes/hicn/transport/core/name.h
+++ b/libtransport/includes/hicn/transport/core/name.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -46,12 +46,13 @@ class Name {
friend class Packet;
friend class ContentObject;
friend class Interest;
+ friend class Prefix;
static const uint32_t standard_name_string_length = 100;
public:
using NameStruct = hicn_name_t;
- using Type = hicn_name_type_t;
+ enum class Type { UNDEFINED, V4, V6 };
Name();
@@ -69,6 +70,8 @@ class Name {
Name(const Name &name);
+ ~Name();
+
Name &operator=(const Name &name);
bool operator==(const Name &name) const;
@@ -91,23 +94,22 @@ class Name {
uint32_t getSuffix() const;
- std::shared_ptr<Sockaddr> getAddress() const;
-
Name &setSuffix(uint32_t seq_number);
- ip_prefix_t toIpAddress() const;
+ hicn_ip_prefix_t toIpAddress() const;
+
+ std::string getPrefix() const;
- void copyToDestination(uint8_t *destination,
- bool include_suffix = false) const;
+ void copyPrefixToDestination(uint8_t *destination) const;
int getAddressFamily() const;
private:
- TRANSPORT_ALWAYS_INLINE const NameStruct *getConstStructReference() const {
- return &name_;
+ TRANSPORT_ALWAYS_INLINE const NameStruct &getConstStructReference() const {
+ return name_;
}
- TRANSPORT_ALWAYS_INLINE NameStruct *getStructReference() { return &name_; }
+ TRANSPORT_ALWAYS_INLINE NameStruct &getStructReference() { return name_; }
NameStruct name_;
};
diff --git a/libtransport/includes/hicn/transport/core/packet.h b/libtransport/includes/hicn/transport/core/packet.h
index 269a1571a..31d856cd5 100644
--- a/libtransport/includes/hicn/transport/core/packet.h
+++ b/libtransport/includes/hicn/transport/core/packet.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,15 +26,18 @@
#include <hicn/transport/utils/membuf.h>
#include <hicn/transport/utils/object_pool.h>
+extern "C" {
+#ifndef _WIN32
+TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat")
+#endif
+#include <hicn/packet.h>
+}
+
namespace transport {
namespace auth {
class Signer;
-class AsymmetricSigner;
-class SymmetricSigner;
class Verifier;
-class AsymmetricVerifier;
-class SymmetricVerifier;
} // namespace auth
namespace core {
@@ -51,16 +54,14 @@ namespace core {
class Packet : public utils::MemBuf,
public std::enable_shared_from_this<Packet> {
friend class auth::Signer;
- friend class auth::SymmetricSigner;
- friend class auth::AsymmetricSigner;
friend class auth::Verifier;
- friend class auth::AsymmetricVerifier;
- friend class auth::SymmetricVerifier;
public:
using Ptr = std::shared_ptr<Packet>;
using MemBufPtr = std::shared_ptr<utils::MemBuf>;
- using Format = hicn_format_t;
+ using Format = hicn_packet_format_t;
+ using Type = hicn_packet_type_t;
+
static constexpr size_t default_mtu = 1500;
/**
@@ -68,211 +69,120 @@ class Packet : public utils::MemBuf,
* the eventual payload will be added by prepending the payload buffer
* to the buffer chain whose the fist buffer is the header itself.
*/
- Packet(Format format = HF_INET6_TCP, std::size_t additional_header_size = 0);
-
- /**
- * Create new IP packet using raw buffer.
- */
-
+ Packet(Type type, Format format, std::size_t additional_header_size = 0);
/* Copy buffer */
Packet(CopyBufferOp, const uint8_t *buffer, std::size_t size);
/* Wrap buffer */
Packet(WrapBufferOp, uint8_t *buffer, std::size_t length, std::size_t size);
/* Create new using pre-allocated buffer */
- Packet(CreateOp, uint8_t *buffer, std::size_t length, std::size_t size,
- Format format = HF_INET6_TCP, std::size_t additional_header_size = 0);
- /* Move MemBuf */
- Packet(MemBuf &&buffer);
+ Packet(CreateOp, Type type, uint8_t *buffer, std::size_t length,
+ std::size_t size, Format format,
+ std::size_t additional_header_size = 0);
+ Packet(MemBuf &&buffer);
Packet(Packet &&other);
-
- /*
- * Copy constructor and assignemnt operators.
- */
Packet(const Packet &other);
- Packet &operator=(const Packet &other);
-
- friend bool operator==(const Packet &l_packet, const Packet &r_packet);
+ // Destructor
virtual ~Packet();
- static std::size_t getHeaderSizeFromFormat(Format format,
- std::size_t signature_size = 0) {
- std::size_t header_length;
- hicn_packet_get_header_length_from_format(format, &header_length);
- int is_ah = _is_ah(format);
- return is_ah * (header_length + signature_size) + (!is_ah) * header_length;
- }
-
- static std::size_t getHeaderSizeFromBuffer(Format format,
- const uint8_t *buffer);
-
- static std::size_t getPayloadSizeFromBuffer(Format format,
- const uint8_t *buffer);
-
- static bool isInterest(const uint8_t *buffer);
-
- bool isInterest();
-
- static Format getFormatFromBuffer(const uint8_t *buffer, std::size_t length) {
- Format format = HF_UNSPEC;
- hicn_packet_get_format((const hicn_header_t *)buffer, &format);
- return format;
- }
-
- void reset() {
- clear();
- packet_start_ = reinterpret_cast<hicn_header_t *>(writableData());
- header_offset_ = 0;
- format_ = HF_UNSPEC;
- payload_type_ = PayloadType::UNSPECIFIED;
- name_.clear();
+ // Operators
+ Packet &operator=(const Packet &other);
+ friend bool operator==(const Packet &l_packet, const Packet &r_packet);
- if (isChained()) {
- separateChain(next(), prev());
- }
- }
+ // Cast to MemBuf
+ std::shared_ptr<utils::MemBuf> acquireMemBufReference();
- void setFormat(Packet::Format format = HF_INET6_TCP,
- std::size_t additional_header_size = 0);
+ // Format
+ Format getFormat() const;
+ void setFormat(Packet::Format format);
- std::size_t payloadSize() const;
+ void initialize(std::size_t additional_header_size = 0);
+ void analyze();
- std::size_t headerSize() const;
+ void initializeType(Packet::Type type);
+ hicn_packet_type_t getType() const;
+ void setType(Packet::Type type);
- std::shared_ptr<utils::MemBuf> acquireMemBufReference();
+ void setBuffer();
+ // Name
virtual const Name &getName() const = 0;
-
virtual Name &getWritableName() = 0;
-
virtual void setName(const Name &name) = 0;
+ // Lifetime
virtual void setLifetime(uint32_t lifetime) = 0;
-
virtual uint32_t getLifetime() const = 0;
- Packet &appendPayload(const uint8_t *buffer, std::size_t length);
+ // Locator
+ virtual void setLocator(const hicn_ip_address_t &locator) = 0;
+ virtual hicn_ip_address_t getLocator() const = 0;
- Packet &appendPayload(std::unique_ptr<utils::MemBuf> &&payload);
+ // Payload type
+ PayloadType getPayloadType() const;
+ Packet &setPayloadType(PayloadType payload_type);
+ // Payload
std::unique_ptr<utils::MemBuf> getPayload() const;
+ Packet &appendPayload(std::unique_ptr<utils::MemBuf> &&payload);
+ Packet &appendPayload(const uint8_t *buffer, std::size_t length);
- Packet &updateLength(std::size_t length = 0);
+ // Sizes
+ std::size_t headerSize() const;
+ std::size_t payloadSize() const;
- PayloadType getPayloadType() const;
+ // Digest
+ auth::CryptoHash computeDigest(auth::CryptoHashType algorithm) const;
- Packet &setPayloadType(PayloadType payload_type);
+ bool isInterest();
- Format getFormat() const;
+ // Reset packet
+ void reset();
+ // Utils
+ Packet &updateLength(std::size_t length = 0);
void dump() const;
- static void dump(uint8_t *buffer, std::size_t length);
-
- virtual void setLocator(const ip_address_t &locator) = 0;
-
- virtual ip_address_t getLocator() const = 0;
-
- /**
- * @brief Set signature timestamp, in milliseconds.
- */
- void setSignatureTimestamp(const uint64_t &timestamp_milliseconds);
+ // TCP methods
+ void setChecksum();
+ bool checkIntegrity() const;
+ // Authentication Header methods
+ bool hasAH() const;
+ utils::MemBuf::Ptr getSignature() const;
+ std::size_t getSignatureFieldSize() const;
+ std::size_t getSignatureSize() const;
uint64_t getSignatureTimestamp() const;
-
- void setValidationAlgorithm(const auth::CryptoSuite &validation_algorithm);
-
+ auth::KeyId getKeyId() const;
auth::CryptoSuite getValidationAlgorithm() const;
-
+ void setSignature(const utils::MemBuf::Ptr &signature);
+ void setSignatureFieldSize(std::size_t size);
+ void setSignatureSize(std::size_t size);
+ void setSignatureTimestamp(const uint64_t &timestamp_ms);
void setKeyId(const auth::KeyId &key_id);
+ void setValidationAlgorithm(const auth::CryptoSuite &algo);
- auth::KeyId getKeyId() const;
-
- virtual auth::CryptoHash computeDigest(auth::CryptoHashType algorithm) const;
-
- void setChecksum() {
- uint16_t partial_csum =
- csum(data() + HICN_V6_TCP_HDRLEN, length() - HICN_V6_TCP_HDRLEN, 0);
-
- for (utils::MemBuf *current = next(); current != this;
- current = current->next()) {
- partial_csum = csum(current->data(), current->length(), ~partial_csum);
- }
-
- if (hicn_packet_compute_header_checksum(format_, packet_start_,
- partial_csum) < 0) {
- throw errors::MalformedPacketException();
- }
- }
+ void saveHeader(u8 *header, size_t *header_len);
+ void loadHeader(u8 *header, size_t header_len);
- bool checkIntegrity() const;
-
- Packet &setSyn();
- Packet &resetSyn();
- bool testSyn() const;
- Packet &setAck();
- Packet &resetAck();
- bool testAck() const;
- Packet &setRst();
- Packet &resetRst();
- bool testRst() const;
- Packet &setFin();
- Packet &resetFin();
- bool testFin() const;
- Packet &resetFlags();
- std::string printFlags() const;
-
- Packet &setSrcPort(uint16_t srcPort);
- Packet &setDstPort(uint16_t dstPort);
- uint16_t getSrcPort() const;
- uint16_t getDstPort() const;
-
- Packet &setTTL(uint8_t hops);
- uint8_t getTTL() const;
+ // Static methods
+ static Format toAHFormat(const Format &format);
+ static Format getFormatFromBuffer(const uint8_t *buffer, std::size_t length);
+ static std::size_t getHeaderSizeFromFormat(Format format,
+ std::size_t signature_size = 0);
+ static std::size_t getHeaderSizeFromBuffer(const uint8_t *buffer,
+ size_t length);
+ static std::size_t getPayloadSizeFromBuffer(const uint8_t *buffer,
+ size_t length);
+ static void dump(uint8_t *buffer, std::size_t length);
private:
virtual void resetForHash() = 0;
- void setSignatureSize(std::size_t size_bytes);
- void setSignatureSizeGap(std::size_t size_bytes);
void prependPayload(const uint8_t **buffer, std::size_t *size);
- bool authenticationHeader() const { return _is_ah(format_); }
-
- std::size_t getSignatureSize() const {
- size_t size_bytes;
- int ret =
- hicn_packet_get_signature_size(format_, packet_start_, &size_bytes);
-
- if (ret < 0) {
- throw errors::RuntimeException("Packet without Authentication Header.");
- }
-
- return size_bytes;
- }
-
- std::size_t getSignatureSizeGap() const {
- uint8_t size_bytes;
- int ret =
- hicn_packet_get_signature_gap(format_, packet_start_, &size_bytes);
-
- if (ret < 0) {
- throw errors::RuntimeException("Packet without Authentication Header.");
- }
-
- return (size_t)size_bytes;
- }
-
- std::size_t getSignatureSizeReal() const {
- return getSignatureSize() - getSignatureSizeGap();
- }
-
- uint8_t *getSignature() const;
-
protected:
- hicn_header_t *packet_start_;
- std::size_t header_offset_;
- mutable Format format_;
+ hicn_packet_buffer_t pkbuf_;
Name name_;
mutable PayloadType payload_type_;
static const core::Name base_name;
diff --git a/libtransport/includes/hicn/transport/core/payload_type.h b/libtransport/includes/hicn/transport/core/payload_type.h
index 8c918f792..a528500ad 100644
--- a/libtransport/includes/hicn/transport/core/payload_type.h
+++ b/libtransport/includes/hicn/transport/core/payload_type.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,15 @@
#pragma once
+#include <hicn/transport/portability/portability.h>
+
+extern "C" {
+#ifndef _WIN32
+TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat")
+#endif
+#include <hicn/base.h>
+};
+
namespace transport {
namespace core {
@@ -27,4 +36,4 @@ enum class PayloadType : uint16_t {
} // end namespace core
-} // end namespace transport \ No newline at end of file
+} // end namespace transport
diff --git a/libtransport/includes/hicn/transport/core/prefix.h b/libtransport/includes/hicn/transport/core/prefix.h
index 7ef667bc8..791fbc770 100644
--- a/libtransport/includes/hicn/transport/core/prefix.h
+++ b/libtransport/includes/hicn/transport/core/prefix.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,16 +25,18 @@ class Prefix {
public:
Prefix();
- Prefix(const char *prefix);
-
Prefix(const std::string &prefix);
- Prefix(std::string &&prefix);
-
- Prefix(std::string &prefix, uint16_t prefix_length);
+ Prefix(const std::string &prefix, uint16_t prefix_length);
Prefix(const core::Name &content_name, uint16_t prefix_length);
+ bool operator<(const Prefix &prefix) const;
+
+ bool operator==(const Prefix &prefix) const;
+
+ bool operator!=(const Prefix &prefix) const { return !operator==(prefix); }
+
std::unique_ptr<Sockaddr> toSockaddr() const;
uint16_t getPrefixLength() const;
@@ -43,36 +45,34 @@ class Prefix {
std::string getNetwork() const;
- int contains(const ip_address_t &content_name) const;
+ Prefix &setNetwork(const std::string &network);
- int contains(const core::Name &content_name) const;
+ int getAddressFamily() const;
- Name getName() const;
+ bool contains(const hicn_ip_address_t &content_name) const;
- Name getRandomName() const;
+ bool contains(const core::Name &content_name) const;
Name getName(const core::Name &mask, const core::Name &components,
const core::Name &content_name) const;
Name mapName(const core::Name &content_name) const;
- Prefix &setNetwork(std::string &network);
-
- int getAddressFamily() const;
-
- Prefix &setAddressFamily(int address_family);
-
+ Name makeName() const;
Name makeRandomName() const;
+ Name makeNameWithIndex(std::uint64_t index) const;
- const ip_prefix_t &toIpPrefixStruct() const;
+ const hicn_ip_prefix_t &toIpPrefixStruct() const;
private:
static bool checkPrefixLengthAndAddressFamily(uint16_t prefix_length,
int family);
- void buildPrefix(std::string &prefix, uint16_t prefix_length, int family);
+ void buildPrefix(const std::string &prefix, uint16_t prefix_length,
+ int family);
- ip_prefix_t ip_prefix_;
+ private:
+ hicn_ip_prefix_t hicn_ip_prefix_;
};
} // end namespace core
diff --git a/libtransport/includes/hicn/transport/errors/CMakeLists.txt b/libtransport/includes/hicn/transport/errors/CMakeLists.txt
index 1d35c5b34..c8642b51b 100644
--- a/libtransport/includes/hicn/transport/errors/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/errors/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/errors.h b/libtransport/includes/hicn/transport/errors/errors.h
index b659820fa..09ce97221 100644
--- a/libtransport/includes/hicn/transport/errors/errors.h
+++ b/libtransport/includes/hicn/transport/errors/errors.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/indexing_exception.h b/libtransport/includes/hicn/transport/errors/indexing_exception.h
index 731314f0e..bdcc39aef 100644
--- a/libtransport/includes/hicn/transport/errors/indexing_exception.h
+++ b/libtransport/includes/hicn/transport/errors/indexing_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h b/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h
index 60226f576..26e0f98af 100644
--- a/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h
+++ b/libtransport/includes/hicn/transport/errors/invalid_ip_address_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h b/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h
index f0cfe0b82..9b3ec7466 100644
--- a/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h
+++ b/libtransport/includes/hicn/transport/errors/malformed_ahpacket_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/malformed_name_exception.h b/libtransport/includes/hicn/transport/errors/malformed_name_exception.h
index 4ef45d2e8..57412cf7f 100644
--- a/libtransport/includes/hicn/transport/errors/malformed_name_exception.h
+++ b/libtransport/includes/hicn/transport/errors/malformed_name_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h b/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h
index ec5c97e6e..996d6a4ab 100644
--- a/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h
+++ b/libtransport/includes/hicn/transport/errors/malformed_packet_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/not_implemented_exception.h b/libtransport/includes/hicn/transport/errors/not_implemented_exception.h
index e9869163d..3291fa425 100644
--- a/libtransport/includes/hicn/transport/errors/not_implemented_exception.h
+++ b/libtransport/includes/hicn/transport/errors/not_implemented_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/null_pointer_exception.h b/libtransport/includes/hicn/transport/errors/null_pointer_exception.h
index bd06485ed..7edb619b8 100644
--- a/libtransport/includes/hicn/transport/errors/null_pointer_exception.h
+++ b/libtransport/includes/hicn/transport/errors/null_pointer_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/runtime_exception.h b/libtransport/includes/hicn/transport/errors/runtime_exception.h
index ba5128a7e..498c41a7c 100644
--- a/libtransport/includes/hicn/transport/errors/runtime_exception.h
+++ b/libtransport/includes/hicn/transport/errors/runtime_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/tokenizer_exception.h b/libtransport/includes/hicn/transport/errors/tokenizer_exception.h
index 76eda838e..31f79644a 100644
--- a/libtransport/includes/hicn/transport/errors/tokenizer_exception.h
+++ b/libtransport/includes/hicn/transport/errors/tokenizer_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h b/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h
index 6f71471e4..c8e4eadd4 100644
--- a/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h
+++ b/libtransport/includes/hicn/transport/errors/unexpected_manifest_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/http/CMakeLists.txt b/libtransport/includes/hicn/transport/http/CMakeLists.txt
index 9f4cdaf39..36a2ca5ce 100644
--- a/libtransport/includes/hicn/transport/http/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/http/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2020 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/http/client_connection.h b/libtransport/includes/hicn/transport/http/client_connection.h
index 7e78e9c59..d5edf6cd0 100644
--- a/libtransport/includes/hicn/transport/http/client_connection.h
+++ b/libtransport/includes/hicn/transport/http/client_connection.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -31,7 +31,7 @@ namespace http {
using namespace interface;
using namespace core;
-class HTTPClientConnection {
+class HTTPClientConnection : private utils::NonCopyable {
static constexpr uint32_t max_buffer_capacity = 64 * 1024;
public:
@@ -39,7 +39,7 @@ class HTTPClientConnection {
public:
virtual void onBytesReceived(std::unique_ptr<utils::MemBuf> &&buffer) = 0;
virtual void onSuccess(std::size_t bytes) = 0;
- virtual void onError(const std::error_code ec) = 0;
+ virtual void onError(const std::error_code &ec) = 0;
};
enum class RC : uint32_t { DOWNLOAD_FAILED, DOWNLOAD_SUCCESS };
diff --git a/libtransport/includes/hicn/transport/http/default_values.h b/libtransport/includes/hicn/transport/http/default_values.h
index 2d5a6b821..8cf247e19 100644
--- a/libtransport/includes/hicn/transport/http/default_values.h
+++ b/libtransport/includes/hicn/transport/http/default_values.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/http/facade.h b/libtransport/includes/hicn/transport/http/facade.h
index 8a465ce94..c886a7588 100644
--- a/libtransport/includes/hicn/transport/http/facade.h
+++ b/libtransport/includes/hicn/transport/http/facade.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/http/message.h b/libtransport/includes/hicn/transport/http/message.h
index b8756224f..a07941413 100644
--- a/libtransport/includes/hicn/transport/http/message.h
+++ b/libtransport/includes/hicn/transport/http/message.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/http/request.h b/libtransport/includes/hicn/transport/http/request.h
index b62f5b061..9939fbcaf 100644
--- a/libtransport/includes/hicn/transport/http/request.h
+++ b/libtransport/includes/hicn/transport/http/request.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/http/response.h b/libtransport/includes/hicn/transport/http/response.h
index bab41acb8..79def27cd 100644
--- a/libtransport/includes/hicn/transport/http/response.h
+++ b/libtransport/includes/hicn/transport/http/response.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt b/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt
index 40623dfe1..43f95a466 100644
--- a/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/interfaces/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -21,13 +21,7 @@ list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/global_conf_interface.h
${CMAKE_CURRENT_SOURCE_DIR}/statistics.h
${CMAKE_CURRENT_SOURCE_DIR}/portal.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/notification.h
)
-if (${OPENSSL_VERSION} VERSION_EQUAL "1.1.1a" OR ${OPENSSL_VERSION} VERSION_GREATER "1.1.1a")
- list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_producer.h
- ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.h
- )
-endif()
-
set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
diff --git a/libtransport/includes/hicn/transport/interfaces/callbacks.h b/libtransport/includes/hicn/transport/interfaces/callbacks.h
index 22e111799..41e4fba3b 100644
--- a/libtransport/includes/hicn/transport/interfaces/callbacks.h
+++ b/libtransport/includes/hicn/transport/interfaces/callbacks.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,7 @@
#pragma once
#include <hicn/transport/auth/policies.h>
+#include <hicn/transport/interfaces/notification.h>
#include <hicn/transport/interfaces/statistics.h>
#include <functional>
@@ -60,6 +61,12 @@ using ConsumerTimerCallback =
std::function<void(ConsumerSocket &, const TransportStatistics &stats)>;
/**
+ * The ConsumerTimerCallback is called when the forwarding/recovery stategy is
+ * changes.
+ */
+using StrategyCallback = std::function<void(notification::Strategy strategy)>;
+
+/**
* The ProducerContentCallback will be called by the producer socket right after
* a content has been segmented and published.
*/
diff --git a/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h b/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h
index a9fe6fac6..e1465d375 100644
--- a/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h
+++ b/libtransport/includes/hicn/transport/interfaces/global_conf_interface.h
@@ -26,8 +26,16 @@ namespace transport {
namespace interface {
namespace global_config {
-static const constexpr char io_module_section[] = "io_module";
-void parseConfigurationFile(const std::string& path = "");
+class GlobalConfigInterface {
+ public:
+ GlobalConfigInterface();
+ ~GlobalConfigInterface();
+ void parseConfigurationFile(const std::string& path = "") const;
+
+ private:
+ void libtransportConfigInit() const;
+ void libtransportConfigTerminate() const;
+};
class ConfigurationObject {
public:
@@ -49,7 +57,9 @@ class ConfigurationObject {
class IoModuleConfiguration : public ConfigurationObject {
public:
- std::string getKey() const override { return io_module_section; }
+ static inline char section[] = "io_module";
+
+ std::string getKey() const override { return section; }
std::string name;
std::vector<std::string> search_path;
diff --git a/libtransport/src/interfaces/tls_socket_consumer.h b/libtransport/includes/hicn/transport/interfaces/notification.h
index 845a9181f..a0945c3f0 100644
--- a/libtransport/src/interfaces/tls_socket_consumer.h
+++ b/libtransport/includes/hicn/transport/interfaces/notification.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,22 +15,17 @@
#pragma once
-#include <hicn/transport/interfaces/socket_consumer.h>
+#include <variant>
namespace transport {
-
-namespace implementation {
-class TLSConsumerSocket;
-}
-
namespace interface {
+namespace notification {
-class TLSConsumerSocket : public ConsumerSocket {
- public:
- TLSConsumerSocket(implementation::TLSConsumerSocket *implementation);
- ~TLSConsumerSocket();
-};
+enum class ForwardingStrategy { BEST_PATH, REPLICATION, BOTH, NONE };
+enum class RecoveryStrategy { RECOVERY_OFF, RTX_ONLY, FEC_ONLY, RTX_AND_FEC };
-} // namespace interface
+using Strategy = std::variant<ForwardingStrategy, RecoveryStrategy>;
-} // end namespace transport
+} // namespace notification
+} // namespace interface
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_consumer.h b/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_consumer.h
deleted file mode 100644
index 224493f00..000000000
--- a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_consumer.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <hicn/transport/interfaces/socket_consumer.h>
-
-namespace transport {
-
-namespace interface {
-
-class P2PSecureConsumerSocket : public ConsumerSocket {
- public:
- P2PSecureConsumerSocket(int handshake_protocol, int transport_protocol);
- ~P2PSecureConsumerSocket() = default;
- void registerPrefix(const Prefix &producer_namespace);
-};
-
-} // namespace interface
-} // end namespace transport
diff --git a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_producer.h b/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_producer.h
deleted file mode 100644
index d86744514..000000000
--- a/libtransport/includes/hicn/transport/interfaces/p2psecure_socket_producer.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <hicn/transport/auth/identity.h>
-#include <hicn/transport/interfaces/socket_producer.h>
-
-namespace transport {
-
-namespace interface {
-
-class P2PSecureProducerSocket : public ProducerSocket {
- public:
- P2PSecureProducerSocket();
- P2PSecureProducerSocket(bool rtc,
- const std::shared_ptr<auth::Identity> &identity);
- ~P2PSecureProducerSocket() = default;
-};
-
-} // namespace interface
-
-} // end namespace transport
diff --git a/libtransport/includes/hicn/transport/interfaces/portal.h b/libtransport/includes/hicn/transport/interfaces/portal.h
index 66fc84256..bca78cb3b 100644
--- a/libtransport/includes/hicn/transport/interfaces/portal.h
+++ b/libtransport/includes/hicn/transport/interfaces/portal.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,6 +19,8 @@
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/interest.h>
#include <hicn/transport/core/prefix.h>
+#include <hicn/transport/utils/event_thread.h>
+#include <hicn/transport/utils/noncopyable.h>
#include <functional>
@@ -28,58 +30,18 @@ namespace transport {
namespace interface {
-template <typename PrefixType>
-class BasicBindConfig {
- static_assert(std::is_same<core::Prefix, PrefixType>::value,
- "Prefix must be a Prefix type.");
-
- const uint32_t standard_cs_reserved = 5000;
-
- public:
- template <typename T>
- BasicBindConfig(T &&prefix)
- : prefix_(std::forward<T &&>(prefix)),
- content_store_reserved_(standard_cs_reserved) {}
-
- template <typename T>
- BasicBindConfig(T &&prefix, uint32_t cs_reserved)
- : prefix_(std::forward<T &&>(prefix)),
- content_store_reserved_(cs_reserved) {}
-
- TRANSPORT_ALWAYS_INLINE const PrefixType &prefix() const { return prefix_; }
-
- TRANSPORT_ALWAYS_INLINE uint32_t csReserved() const {
- return content_store_reserved_;
- }
-
- private:
- PrefixType prefix_;
- uint32_t content_store_reserved_;
-};
-
-using BindConfig = BasicBindConfig<core::Prefix>;
-
-class Portal {
+class Portal : private utils::NonCopyable {
public:
/**
- * Consumer callback is an abstract class containing two methods to be
- * implemented by a consumer application.
+ * Transport callback is an abstract class containing two methods to be
+ * implemented by a consumer/producer application.
*/
- class ConsumerCallback {
+ class TransportCallback {
public:
+ virtual void onInterest(core::Interest &i) = 0;
virtual void onContentObject(core::Interest &i, core::ContentObject &c) = 0;
virtual void onTimeout(core::Interest::Ptr &i, const core::Name &n) = 0;
- virtual void onError(std::error_code ec) = 0;
- };
-
- /**
- * Producer callback is an abstract class containing two methods to be
- * implemented by a producer application.
- */
- class ProducerCallback {
- public:
- virtual void onInterest(core::Interest &i) = 0;
- virtual void onError(std::error_code ec) = 0;
+ virtual void onError(const std::error_code &ec) = 0;
};
using OnContentObjectCallback =
@@ -89,21 +51,14 @@ class Portal {
Portal();
- Portal(asio::io_service &io_service);
+ Portal(::utils::EventThread &worker);
/**
- * Set the consumer callback.
- *
- * @param consumer_callback - The pointer to the ConsumerCallback object.
- */
- void setConsumerCallback(ConsumerCallback *consumer_callback);
-
- /**
- * Set the producer callback.
+ * Set the transport protocl callback.
*
* @param producer_callback - The pointer to the ProducerCallback object.
*/
- void setProducerCallback(ProducerCallback *producer_callback);
+ void registerTransportCallback(TransportCallback *transport_callback);
/**
* Connect the transport to the local hicn forwarder.
@@ -140,40 +95,18 @@ class Portal {
* parameter. Otherwise ConsumerCallback::onTimeout will be used.
*/
void sendInterest(
- core::Interest::Ptr &&interest,
+ core::Interest::Ptr &interest, uint32_t lifetime,
OnContentObjectCallback &&on_content_object_callback = UNSET_CALLBACK,
OnInterestTimeoutCallback &&on_interest_timeout_callback =
UNSET_CALLBACK);
/**
- * Register a producer name to the local forwarder and optionally set the
- * content store size in a per-face manner.
- *
- * @param config - The configuration for the local forwarder binding.
- */
- void bind(const BindConfig &config);
-
- void runEventsLoop();
-
- /**
- * Run one event and return.
- */
- void runOneEvent();
-
- /**
* Send a data packet to the local forwarder. As opposite to sendInterest, the
* ownership of the content object is not transferred to the portal.
*
* @param content_object - The data packet.
*/
void sendContentObject(core::ContentObject &content_object);
- /**
- * Stop the event loop, canceling all the pending events in the event queue.
- *
- * Beware that stopping the event loop DOES NOT disconnect the transport from
- * the local forwarder, the connector underneath will stay connected.
- */
- void stopEventsLoop();
/**
* Disconnect the transport from the local forwarder.
@@ -188,15 +121,26 @@ class Portal {
/**
* Get a reference to the io_service object.
*/
- asio::io_service &getIoService();
+ utils::EventThread &getThread();
/**
* Register a route to the local forwarder.
*/
void registerRoute(core::Prefix &prefix);
+ /**
+ * Send a MAP-Me command to traverse NATs.
+ */
+ void sendMapme();
+
+ /**
+ * Set forwarding strategy
+ */
+ void setForwardingStrategy(core::Prefix &prefix, std::string &strategy);
+
private:
- void *implementation_;
+ class Impl;
+ Impl *implementation_;
};
} // namespace interface
diff --git a/libtransport/includes/hicn/transport/interfaces/publication_options.h b/libtransport/includes/hicn/transport/interfaces/publication_options.h
index 6910e5371..f4f409d00 100644
--- a/libtransport/includes/hicn/transport/interfaces/publication_options.h
+++ b/libtransport/includes/hicn/transport/interfaces/publication_options.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,7 +25,7 @@ class PublicationOptions {
public:
template <typename T>
PublicationOptions(T&& name, uint32_t lifetime)
- : name_(std::forward<T&&>(name)),
+ : name_(std::forward<T>(name)),
content_lifetime_milliseconds_(lifetime) {}
TRANSPORT_ALWAYS_INLINE const core::Name& getName() const { return name_; }
diff --git a/libtransport/includes/hicn/transport/interfaces/socket_consumer.h b/libtransport/includes/hicn/transport/interfaces/socket_consumer.h
index 5e0e81b9f..1c709eb72 100644
--- a/libtransport/includes/hicn/transport/interfaces/socket_consumer.h
+++ b/libtransport/includes/hicn/transport/interfaces/socket_consumer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,6 +23,8 @@
#include <hicn/transport/interfaces/callbacks.h>
#include <hicn/transport/interfaces/socket_options_default_values.h>
#include <hicn/transport/interfaces/socket_options_keys.h>
+#include <hicn/transport/utils/event_thread.h>
+#include <hicn/transport/utils/noncopyable.h>
#define CONSUMER_FINISHED 0
#define CONSUMER_BUSY 1
@@ -45,7 +47,7 @@ using namespace core;
* It allows to retrieve an application data from one/many producers, by
* hiding all the complexity of the transport protocol used underneath.
*/
-class ConsumerSocket {
+class ConsumerSocket : private utils::NonCopyable {
public:
/**
* The ReadCallback is a class which can be used by the transport for both
@@ -124,7 +126,7 @@ class ConsumerSocket {
*
* @param ec - An error code describing the error.
*/
- virtual void readError(const std::error_code ec) noexcept = 0;
+ virtual void readError(const std::error_code &ec) noexcept = 0;
/**
* This callback will be invoked when the whole content is retrieved. The
@@ -166,7 +168,12 @@ class ConsumerSocket {
* 110, 104-117
* - RTC: Real time communication
*/
- explicit ConsumerSocket(int protocol, asio::io_service &io_service);
+ explicit ConsumerSocket(int protocol, ::utils::EventThread &worker);
+
+ /**
+ * @brief Move contructor
+ */
+ ConsumerSocket(ConsumerSocket &&other) noexcept;
/**
* @brief Destroy the consumer socket.
@@ -200,12 +207,10 @@ class ConsumerSocket {
* content retrieval succeeded. This information can be obtained from the
* error code in CONTENT_RETRIEVED callback.
*/
- int consume(const Name &name);
- int asyncConsume(const Name &name);
+ int consume(const Name &name, bool blocking = false);
/**
- * Stops the consumer socket. If several downloads are queued (using
- * asyncConsume), this call stops just the current one.
+ * Stops the consumer socket.
*/
void stop();
@@ -245,6 +250,9 @@ class ConsumerSocket {
int setSocketOption(int socket_option_key,
interface::IcnObserver *socket_option_value);
+ int setSocketOption(int socket_option_key,
+ const std::shared_ptr<auth::Signer> &socket_option_value);
+
int setSocketOption(
int socket_option_key,
const std::shared_ptr<auth::Verifier> &socket_option_value);
@@ -255,6 +263,9 @@ class ConsumerSocket {
int setSocketOption(int socket_option_key,
ConsumerTimerCallback socket_option_value);
+ int setSocketOption(int socket_option_key,
+ StrategyCallback socket_option_value);
+
int getSocketOption(int socket_option_key, double &socket_option_value);
int getSocketOption(int socket_option_key, uint32_t &socket_option_value);
@@ -272,6 +283,9 @@ class ConsumerSocket {
int getSocketOption(int socket_option_key, IcnObserver **socket_option_value);
int getSocketOption(int socket_option_key,
+ std::shared_ptr<auth::Signer> &socket_option_value);
+
+ int getSocketOption(int socket_option_key,
std::shared_ptr<auth::Verifier> &socket_option_value);
int getSocketOption(int socket_option_key, std::string &socket_option_value);
@@ -280,6 +294,9 @@ class ConsumerSocket {
ConsumerTimerCallback **socket_option_value);
int getSocketOption(int socket_option_key,
+ StrategyCallback **socket_option_value);
+
+ int getSocketOption(int socket_option_key,
interface::TransportStatistics **socket_option_value);
protected:
diff --git a/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h b/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h
index f4945ac8a..5558197f8 100644
--- a/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h
+++ b/libtransport/includes/hicn/transport/interfaces/socket_options_default_values.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,7 +15,14 @@
#pragma once
+#include <hicn/transport/portability/portability.h>
+
+extern "C" {
+#ifndef _WIN32
+TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat")
+#endif
#include <hicn/base.h>
+};
#include <chrono>
#include <cstdint>
@@ -26,13 +33,17 @@ namespace interface {
namespace default_values {
-static constexpr uint32_t interest_lifetime = 1001; // milliseconds
-static constexpr uint32_t never_expire_time = HICN_MAX_LIFETIME;
-static constexpr uint32_t content_object_expiry_time =
+// Packet format
+static constexpr hicn_packet_format_t packet_format =
+ HICN_PACKET_FORMAT_DEFAULT;
+
+// Parameters
+static const uint32_t interest_lifetime = 1001; // milliseconds
+static const uint32_t never_expire_time = HICN_MAX_LIFETIME;
+static const uint32_t content_object_expiry_time =
never_expire_time; // milliseconds -> 50 seconds
-static constexpr uint32_t content_object_packet_size =
- 1500; // The ethernet MTU
-static constexpr uint32_t producer_socket_output_buffer_size =
+static const uint32_t content_object_packet_size = 1500; // The ethernet MTU
+static const uint32_t producer_socket_output_buffer_size =
150000; // Content Object
static constexpr uint32_t log_2_default_buffer_size = 12;
static constexpr uint32_t signature_size = 260; // bytes
@@ -40,28 +51,31 @@ static constexpr uint32_t key_locator_size = 60; // bytes
static constexpr uint32_t limit_guard = 80; // bytes
static constexpr uint32_t digest_size = 34; // bytes
static constexpr uint32_t max_out_of_order_segments = 3; // content object
+static constexpr uint32_t manifest_max_capacity = 30;
+static constexpr uint32_t manifest_factor_relevant = 100;
+static constexpr uint32_t manifest_factor_alert = 20;
// RAAQM
-static constexpr int sample_number = 30;
-static constexpr double gamma_value = 1;
-static constexpr double beta_value = 0.8;
-static constexpr double drop_factor = 0.2;
-static constexpr double minimum_drop_probability = 0.00001;
-static constexpr int path_id = 0;
-static constexpr double rate_alpha = 0.8;
+static const int sample_number = 30;
+static const double gamma_value = 1;
+static const double beta_value = 0.8;
+static const double drop_factor = 0.2;
+static const double minimum_drop_probability = 0.00001;
+static const int path_id = 0;
+static const double rate_alpha = 0.8;
// Rate estimation
-static constexpr uint32_t batch = 50;
-static constexpr uint32_t kv = 20;
-static constexpr double alpha = 0.8;
-static constexpr uint32_t rate_choice = 0;
+static const uint32_t batch = 50;
+static const uint32_t kv = 20;
+static const double alpha = 0.8;
+static const uint32_t rate_choice = 0;
// maximum allowed values
-static constexpr uint32_t transport_protocol_min_retransmissions = 0;
-static constexpr uint32_t transport_protocol_max_retransmissions = 128;
-static constexpr uint32_t max_content_object_size = 8096;
-static constexpr uint32_t min_window_size = 1; // Interests
-static constexpr uint32_t max_window_size = 256 * 2; // Interests
+static const uint32_t transport_protocol_min_retransmissions = 0;
+static const uint32_t transport_protocol_max_retransmissions = 128;
+static const uint32_t max_content_object_size = 8096;
+static const uint32_t min_window_size = 1; // Interests
+static const uint32_t max_window_size = 256 * 2; // Interests
} // namespace default_values
diff --git a/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h b/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h
index 00cd44075..a14c8414c 100644
--- a/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h
+++ b/libtransport/includes/hicn/transport/interfaces/socket_options_keys.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,15 +26,30 @@ namespace transport {
namespace interface {
typedef enum {
- RAAQM = 0,
- CBR = 1,
- RTC = 2,
+ UNKNOWN = 0,
+ BYTE_STREAM = 1,
+ RTC_PROD = 2,
+} ProductionProtocolAlgorithms;
+
+typedef enum {
+ RAAQM = 10,
+ CBR = 11,
+ RTC = 12,
} TransportProtocolAlgorithms;
typedef enum {
- BYTE_STREAM = 10,
- RTC_PROD = 11,
-} ProductionProtocolAlgorithms;
+ RECOVERY_OFF = 20,
+ RTX_ONLY = 21,
+ FEC_ONLY = 22,
+ DELAY_BASED = 23,
+ LOW_RATE = 24,
+ LOW_RATE_AND_BESTPATH = 25,
+ LOW_RATE_AND_REPLICATION = 26,
+ LOW_RATE_AND_ALL_FWD_STRATEGIES = 27,
+ FEC_ONLY_LOW_RES_LOSSES = 28,
+ DELAY_AND_BESTPATH = 29,
+ DELAY_AND_REPLICATION = 30,
+} RtcTransportRecoveryStrategies;
typedef enum {
INPUT_BUFFER_SIZE = 101,
@@ -45,19 +60,24 @@ typedef enum {
DATA_PACKET_SIZE = 106,
INTEREST_LIFETIME = 107,
CONTENT_OBJECT_EXPIRY_TIME = 108,
- MIN_WINDOW_SIZE = 111,
- MAX_WINDOW_SIZE = 112,
- CURRENT_WINDOW_SIZE = 113,
- ASYNC_MODE = 114,
- MAKE_MANIFEST = 115,
- PORTAL = 116,
- RUNNING = 117,
- APPLICATION_BUFFER = 118,
- HASH_ALGORITHM = 119,
- SIGNER = 121,
- VERIFIER = 122,
- STATS_INTERVAL = 125,
- SUFFIX_STRATEGY = 126
+ MAX_SEGMENT_SIZE = 109,
+ MIN_WINDOW_SIZE = 110,
+ MAX_WINDOW_SIZE = 111,
+ CURRENT_WINDOW_SIZE = 112,
+ ASYNC_MODE = 113,
+ PORTAL = 114,
+ RUNNING = 115,
+ APPLICATION_BUFFER = 116,
+ HASH_ALGORITHM = 117,
+ SIGNER = 118,
+ VERIFIER = 119,
+ MANIFEST_MAX_CAPACITY = 120,
+ MANIFEST_FACTOR_RELEVANT = 121,
+ MANIFEST_FACTOR_ALERT = 122,
+ STATS_INTERVAL = 123,
+ SUFFIX_STRATEGY = 124,
+ PACKET_FORMAT = 125,
+ FEC_TYPE = 126,
} GeneralTransportOptions;
typedef enum {
@@ -87,7 +107,9 @@ typedef enum {
CONTENT_OBJECT_TO_VERIFY = 413,
VERIFICATION_FAILED = 414,
READ_CALLBACK = 415,
- STATS_SUMMARY = 416
+ STATS_SUMMARY = 416,
+ FWD_STRATEGY_CHANGE = 417,
+ REC_STRATEGY_CHANGE = 418,
} ConsumerCallbacksOptions;
typedef enum {
@@ -100,7 +122,8 @@ typedef enum {
CONTENT_OBJECT_READY = 510,
CONTENT_OBJECT_OUTPUT = 511,
CONTENT_PRODUCED = 512,
- CONTENT_OBJECT_TO_SIGN = 513
+ CONTENT_OBJECT_TO_SIGN = 513,
+ PRODUCER_CALLBACK = 514,
} ProducerCallbacksOptions;
typedef enum { OUTPUT_INTERFACE = 601 } DataLinkOptions;
@@ -116,6 +139,13 @@ typedef enum {
RSA_256 = 802,
} SignatureType;
+typedef enum {
+ RECOVERY_STRATEGY = 901,
+ AGGREGATED_DATA = 902,
+ CONTENT_SHARING_MODE = 903,
+ AGGREGATED_INTERESTS = 904,
+} RtcTransportOptions;
+
} // namespace interface
} // end namespace transport
diff --git a/libtransport/includes/hicn/transport/interfaces/socket_producer.h b/libtransport/includes/hicn/transport/interfaces/socket_producer.h
index 27b603dfe..2627b3138 100644
--- a/libtransport/includes/hicn/transport/interfaces/socket_producer.h
+++ b/libtransport/includes/hicn/transport/interfaces/socket_producer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,6 +23,8 @@
#include <hicn/transport/interfaces/callbacks.h>
#include <hicn/transport/interfaces/socket_options_default_values.h>
#include <hicn/transport/interfaces/socket_options_keys.h>
+#include <hicn/transport/utils/event_thread.h>
+#include <hicn/transport/utils/noncopyable.h>
namespace transport {
@@ -34,12 +36,28 @@ namespace interface {
using namespace core;
-class ProducerSocket {
+class ProducerSocket : private utils::NonCopyable {
public:
+ /**
+ * @brief This class is used by the transport to notify events to the
+ * application.
+ */
+ class Callback {
+ public:
+ /**
+ * @brief This will invoked in an error occurred in the production protocol.
+ *
+ * @param ec - An error code describing the error.
+ */
+ virtual void produceError(const std::error_code &ec) noexcept = 0;
+ };
+
explicit ProducerSocket(
int protocol = ProductionProtocolAlgorithms::BYTE_STREAM);
- explicit ProducerSocket(int protocol, asio::io_service &io_service);
+ explicit ProducerSocket(int protocol, ::utils::EventThread &worker);
+
+ ProducerSocket(ProducerSocket &&other) noexcept;
virtual ~ProducerSocket();
@@ -63,21 +81,18 @@ class ProducerSocket {
uint32_t produceDatagram(const Name &content_name,
std::unique_ptr<utils::MemBuf> &&buffer);
- void asyncProduce(const Name &suffix, const uint8_t *buf, size_t buffer_size,
- bool is_last = true, uint32_t *start_offset = nullptr);
-
- void asyncProduce(Name content_name, std::unique_ptr<utils::MemBuf> &&buffer,
- bool is_last, uint32_t offset,
- uint32_t **last_segment = nullptr);
-
void produce(ContentObject &content_object);
- void serveForever();
+ void sendMapme();
void stop();
+ void start();
+
asio::io_service &getIoService();
+ int setSocketOption(int socket_option_key, Callback *socket_option_value);
+
int setSocketOption(int socket_option_key, uint32_t socket_option_value);
int setSocketOption(int socket_option_key,
@@ -108,6 +123,10 @@ class ProducerSocket {
int setSocketOption(int socket_option_key,
const std::shared_ptr<auth::Signer> &socket_option_value);
+ int setSocketOption(
+ int socket_option_key,
+ const std::shared_ptr<auth::Verifier> &socket_option_value);
+
int setSocketOption(int socket_option_key,
const std::string &socket_option_value);
@@ -136,6 +155,9 @@ class ProducerSocket {
int getSocketOption(int socket_option_key,
std::shared_ptr<auth::Signer> &socket_option_value);
+ int getSocketOption(int socket_option_key,
+ std::shared_ptr<auth::Verifier> &socket_option_value);
+
int getSocketOption(int socket_option_key, std::string &socket_option_value);
protected:
diff --git a/libtransport/includes/hicn/transport/interfaces/statistics.h b/libtransport/includes/hicn/transport/interfaces/statistics.h
index 1ff6f3edd..e83aa9a27 100644
--- a/libtransport/includes/hicn/transport/interfaces/statistics.h
+++ b/libtransport/includes/hicn/transport/interfaces/statistics.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,7 @@
#pragma once
#include <hicn/transport/portability/c_portability.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <cstdint>
@@ -37,6 +38,8 @@ class TransportStatistics {
static constexpr double default_alpha = 0.7;
public:
+ enum class statsAlerts : uint8_t { CONGESTION, LATENCY, LOSSES };
+
TransportStatistics(double alpha = default_alpha)
: retx_count_(0),
bytes_received_(0),
@@ -51,11 +54,15 @@ class TransportStatistics {
lost_data_(0),
definitely_lost_data_(0),
recovered_data_(0),
- status_(-1),
+ status_(0),
// avg_data_rtt_(0),
avg_pending_pkt_(0.0),
received_nacks_(0),
- received_fec_(0) {}
+ received_fec_(0),
+ in_congestion_(false),
+ residual_loss_rate_(0.0),
+ quality_score_(5),
+ alerts_(0) {}
TRANSPORT_ALWAYS_INLINE void updateRetxCount(uint64_t retx) {
retx_count_ += retx;
@@ -65,8 +72,11 @@ class TransportStatistics {
bytes_received_ += bytes;
}
- TRANSPORT_ALWAYS_INLINE void updateAverageRtt(uint64_t rtt) {
- average_rtt_ = (alpha_ * average_rtt_) + ((1. - alpha_) * double(rtt));
+ TRANSPORT_ALWAYS_INLINE void updateAverageRtt(
+ const utils::SteadyTime::Microseconds &rtt) {
+ double rtt_milliseconds = double(rtt.count()) / 1000.0;
+
+ average_rtt_ = (alpha_ * average_rtt_) + ((1. - alpha_) * rtt_milliseconds);
}
TRANSPORT_ALWAYS_INLINE void updateAverageWindowSize(double current_window) {
@@ -120,6 +130,26 @@ class TransportStatistics {
received_fec_ += pkt;
}
+ TRANSPORT_ALWAYS_INLINE void updateResidualLossRate(double val) {
+ residual_loss_rate_ = val;
+ }
+
+ TRANSPORT_ALWAYS_INLINE void updateQualityScore(uint8_t val) {
+ quality_score_ = val;
+ }
+
+ TRANSPORT_ALWAYS_INLINE void updateCongestionState(bool state) {
+ in_congestion_ = state;
+ }
+
+ TRANSPORT_ALWAYS_INLINE void setAlert(statsAlerts x) {
+ alerts_ |= 1UL << (uint32_t)x;
+ }
+
+ TRANSPORT_ALWAYS_INLINE void clearAlert(statsAlerts x) {
+ alerts_ &= ~(1UL << (uint32_t)x);
+ }
+
TRANSPORT_ALWAYS_INLINE uint64_t getRetxCount() const { return retx_count_; }
TRANSPORT_ALWAYS_INLINE uint64_t getBytesRecv() const {
@@ -174,6 +204,18 @@ class TransportStatistics {
return received_fec_;
}
+ TRANSPORT_ALWAYS_INLINE double getResidualLossRate() const {
+ return residual_loss_rate_;
+ }
+
+ TRANSPORT_ALWAYS_INLINE uint8_t getQualityScore() const {
+ return quality_score_;
+ }
+
+ TRANSPORT_ALWAYS_INLINE bool isCongested() const { return in_congestion_; }
+
+ TRANSPORT_ALWAYS_INLINE uint32_t getAlerts() const { return alerts_; }
+
TRANSPORT_ALWAYS_INLINE void setAlpha(double val) { alpha_ = val; }
TRANSPORT_ALWAYS_INLINE void reset() {
@@ -193,6 +235,8 @@ class TransportStatistics {
avg_pending_pkt_ = 0;
received_nacks_ = 0;
received_fec_ = 0;
+ in_congestion_ = false;
+ quality_score_ = 5;
}
private:
@@ -213,6 +257,14 @@ class TransportStatistics {
double avg_pending_pkt_;
uint32_t received_nacks_;
uint32_t received_fec_;
+ bool in_congestion_;
+ double residual_loss_rate_;
+ uint8_t quality_score_;
+
+ // alerts is a bit vector used to signal to the upper layer that
+ // something bad is appening in the network, the encode is done accoding to
+ // the enum alerts;
+ uint32_t alerts_;
};
} // namespace interface
diff --git a/libtransport/includes/hicn/transport/portability/CMakeLists.txt b/libtransport/includes/hicn/transport/portability/CMakeLists.txt
index 8094c0661..d29ec737c 100644
--- a/libtransport/includes/hicn/transport/portability/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/portability/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -14,6 +14,9 @@
list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/c_portability.h
${CMAKE_CURRENT_SOURCE_DIR}/portability.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/cpu.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/cache.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/endianess.h
)
list(APPEND SOURCE_FILES
diff --git a/libtransport/includes/hicn/transport/portability/c_portability.h b/libtransport/includes/hicn/transport/portability/c_portability.h
index 2675de000..bc697d8b1 100644
--- a/libtransport/includes/hicn/transport/portability/c_portability.h
+++ b/libtransport/includes/hicn/transport/portability/c_portability.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/libtransport/includes/hicn/transport/portability/cache.h b/libtransport/includes/hicn/transport/portability/cache.h
new file mode 100644
index 000000000..ae113c7d6
--- /dev/null
+++ b/libtransport/includes/hicn/transport/portability/cache.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <hicn/transport/portability/platform.h>
+
+namespace transport {
+namespace portability {
+namespace cache {
+
+/**
+ * @Prefetch utilities
+ */
+
+/* Default cache line size of 64 bytes. */
+#ifndef LOG2_CACHE_LINE_BYTES
+static constexpr const std::size_t klog2_cache_line_bytes = 6;
+#else
+static constexpr const std::size_t klog2_cache_line_bytes =
+ LOG2_CACHE_LINE_BYTES;
+#endif
+
+/* How much data prefetch instruction prefetches */
+#ifndef LOG2_CACHE_PREFETCH_BYTES
+static constexpr const std::size_t klog2_cache_prefetch_bytes =
+ klog2_cache_line_bytes;
+#else
+static constexpr const std::size_t klog2_cache_prefetch_bytes =
+ LOG2_CACHE_PREFETCH_BYTES;
+#endif
+
+/* Default cache line fill buffers. */
+#ifndef N_PREFETCHES
+static constexpr const std::size_t kn_prefetches = 16;
+#else
+static constexpr const std::size_t kn_prefetches = N_PREFETCHES;
+#endif
+
+static constexpr const std::size_t kcache_line_bytes =
+ (1 << klog2_cache_line_bytes);
+static constexpr const std::size_t kcache_prefetch_bytes =
+ (1 << klog2_cache_prefetch_bytes);
+
+static constexpr const int READ = 0;
+static constexpr const int LOAD = 0; /* alias for read */
+static constexpr const int WRITE = 1;
+static constexpr const int STORE = 1; /* alias for write */
+
+#if defined(__GNUC__) || defined(__clang__)
+// Clang & GCC
+
+template <int type>
+static inline void _prefetch(uint8_t *addr, std::size_t n, std::size_t size) {
+ if (size > n * kcache_prefetch_bytes) {
+ __builtin_prefetch(addr + n * kcache_prefetch_bytes, type,
+ /* locality */ 3);
+ }
+}
+
+template <typename T, int type>
+static inline void prefetch(T *addr, std::size_t size) {
+ uint8_t *_addr = reinterpret_cast<uint8_t *>(addr);
+
+ _prefetch<type>(_addr, 0, size);
+ _prefetch<type>(_addr, 1, size);
+ _prefetch<type>(_addr, 2, size);
+ _prefetch<type>(_addr, 3, size);
+}
+#endif
+
+} // namespace cache
+} // namespace portability
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/portability/cpu.h b/libtransport/includes/hicn/transport/portability/cpu.h
new file mode 100644
index 000000000..036bf9cd9
--- /dev/null
+++ b/libtransport/includes/hicn/transport/portability/cpu.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#if defined(__aarch64__) && defined(__ARM_NEON) || defined(__i686__)
+#define TRANSPORT_HAVE_VEC128
+#endif
+
+#if defined(__SSE4_2__) && __GNUC__ >= 4
+#define TRANSPORT_HAVE_VEC128
+#endif
+
+#if defined(__ALTIVEC__)
+#define TRANSPORT_HAVE_VEC128
+#endif
+
+#if defined(__AVX2__)
+#define TRANSPORT_HAVE_VEC256
+#if defined(__clang__) && __clang_major__ < 4
+#undef TRANSPORT_HAVE_VEC256
+#endif
+#endif
+
+#if defined(__AVX512BITALG__)
+#define TRANSPORT_HAVE_VEC512
+#endif
diff --git a/libtransport/includes/hicn/transport/portability/endianess.h b/libtransport/includes/hicn/transport/portability/endianess.h
new file mode 100644
index 000000000..c18ac82cf
--- /dev/null
+++ b/libtransport/includes/hicn/transport/portability/endianess.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <hicn/transport/errors/errors.h>
+
+namespace transport {
+namespace portability {
+
+#if (__BYTE_ORDER__) == (__ORDER_LITTLE_ENDIAN__)
+static constexpr const bool kIsBigEndian = false;
+static constexpr const bool kIsLittleEndian = true;
+#else
+static constexpr const bool kIsBigEndian = true;
+static constexpr const bool kIsLittleEndian = false;
+#endif
+
+template <typename T>
+inline T bswap(T value) {
+ throw errors::RuntimeException("Not implemented");
+}
+
+template <>
+inline int16_t bswap(int16_t value) {
+ return __builtin_bswap16(value);
+}
+
+template <>
+inline int32_t bswap(int32_t value) {
+ return __builtin_bswap32(value);
+}
+
+template <>
+inline int64_t bswap(int64_t value) {
+ return __builtin_bswap64(value);
+}
+
+template <>
+inline uint16_t bswap(uint16_t value) {
+ return __builtin_bswap16(value);
+}
+
+template <>
+inline uint32_t bswap(uint32_t value) {
+ return __builtin_bswap32(value);
+}
+
+template <>
+inline uint64_t bswap(uint64_t value) {
+ return __builtin_bswap64(value);
+}
+
+template <typename T>
+inline T host_to_net(T value) {
+ if constexpr (kIsLittleEndian) {
+ return bswap(value);
+ }
+
+ return value;
+}
+
+template <typename T>
+inline T net_to_host(T value) {
+ if constexpr (kIsLittleEndian) {
+ return bswap(value);
+ }
+
+ return value;
+}
+
+} // namespace portability
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/portability/portability.h b/libtransport/includes/hicn/transport/portability/portability.h
index 24ef012f7..fd6eca4de 100644
--- a/libtransport/includes/hicn/transport/portability/portability.h
+++ b/libtransport/includes/hicn/transport/portability/portability.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,11 +26,9 @@
#include <cstddef>
+namespace transport {
namespace portability {
-constexpr bool little_endian_arch = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__;
-constexpr bool big_endian_arch = !little_endian_arch;
-
// Generalize warning push/pop.
#if defined(__GNUC__) || defined(__clang__)
// Clang & GCC
@@ -69,3 +67,4 @@ constexpr bool big_endian_arch = !little_endian_arch;
#endif
} // namespace portability
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/portability/win_portability.h b/libtransport/includes/hicn/transport/portability/win_portability.h
index 24c7a932a..81aa828cd 100644
--- a/libtransport/includes/hicn/transport/portability/win_portability.h
+++ b/libtransport/includes/hicn/transport/portability/win_portability.h
@@ -1,44 +1,44 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Copyright 2017 Facebook, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-#define WIN32_LEAN_AND_MEAN
-#ifndef NOMINMAX
-#define NOMINMAX
-#endif
-#include <fcntl.h>
-#include <io.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <time.h>
-#include <windows.h>
-#include <winsock2.h>
-#include <ws2ipdef.h>
-#include <ws2tcpip.h>
-
-#include <algorithm>
-
-#define __ORDER_LITTLE_ENDIAN__ 0x41424344UL
-#define __ORDER_BIG_ENDIAN__ 0x44434241UL
-#define __BYTE_ORDER__ ('ABCD')
-#undef DELETE
-
-#define HAVE_STRUCT_TIMESPEC
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Copyright 2017 Facebook, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#define WIN32_LEAN_AND_MEAN
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <fcntl.h>
+#include <io.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <time.h>
+#include <windows.h>
+#include <winsock2.h>
+#include <ws2ipdef.h>
+#include <ws2tcpip.h>
+
+#include <algorithm>
+
+#define __ORDER_LITTLE_ENDIAN__ 0x41424344UL
+#define __ORDER_BIG_ENDIAN__ 0x44434241UL
+#define __BYTE_ORDER__ ('ABCD')
+#undef DELETE
+
+#define HAVE_STRUCT_TIMESPEC
#include <pthread.h> \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/utils/CMakeLists.txt b/libtransport/includes/hicn/transport/utils/CMakeLists.txt
index 75f727f03..060b83b63 100644
--- a/libtransport/includes/hicn/transport/utils/CMakeLists.txt
+++ b/libtransport/includes/hicn/transport/utils/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -19,6 +19,7 @@ list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/chrono_typedefs.h
${CMAKE_CURRENT_SOURCE_DIR}/branch_prediction.h
${CMAKE_CURRENT_SOURCE_DIR}/ring_buffer.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_quality_score.h
${CMAKE_CURRENT_SOURCE_DIR}/literals.h
${CMAKE_CURRENT_SOURCE_DIR}/conversions.h
${CMAKE_CURRENT_SOURCE_DIR}/linux.h
@@ -31,9 +32,9 @@ list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/string_utils.h
${CMAKE_CURRENT_SOURCE_DIR}/file.h
${CMAKE_CURRENT_SOURCE_DIR}/shared_ptr_utils.h
- ${CMAKE_CURRENT_SOURCE_DIR}/move_wrapper.h
${CMAKE_CURRENT_SOURCE_DIR}/noncopyable.h
${CMAKE_CURRENT_SOURCE_DIR}/singleton.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/traffic_generator.h
)
if(NOT WIN32)
diff --git a/libtransport/includes/hicn/transport/utils/array.h b/libtransport/includes/hicn/transport/utils/array.h
index 7c0ed65d8..d57bfabaf 100644
--- a/libtransport/includes/hicn/transport/utils/array.h
+++ b/libtransport/includes/hicn/transport/utils/array.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/branch_prediction.h b/libtransport/includes/hicn/transport/utils/branch_prediction.h
index 8cbfaca76..626cb1573 100644
--- a/libtransport/includes/hicn/transport/utils/branch_prediction.h
+++ b/libtransport/includes/hicn/transport/utils/branch_prediction.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/chrono_typedefs.h b/libtransport/includes/hicn/transport/utils/chrono_typedefs.h
index 8f28e763c..14234eaa1 100644
--- a/libtransport/includes/hicn/transport/utils/chrono_typedefs.h
+++ b/libtransport/includes/hicn/transport/utils/chrono_typedefs.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,11 +17,102 @@
#include <chrono>
+namespace std {
+namespace chrono {
+namespace detail {
+
+template <typename From, typename To>
+struct posix_duration_cast;
+
+// chrono -> timespec caster
+template <typename Rep, typename Period>
+struct posix_duration_cast<std::chrono::duration<Rep, Period>,
+ struct timespec> {
+ static struct timespec cast(std::chrono::duration<Rep, Period> const &d) {
+ struct timespec tv;
+
+ std::chrono::seconds const sec =
+ std::chrono::duration_cast<std::chrono::seconds>(d);
+
+ tv.tv_sec = sec.count();
+ tv.tv_nsec =
+ std::chrono::duration_cast<std::chrono::nanoseconds>(d - sec).count();
+
+ return tv;
+ }
+};
+
+// timespec -> chrono caster
+template <typename Rep, typename Period>
+struct posix_duration_cast<struct timespec,
+ std::chrono::duration<Rep, Period>> {
+ static std::chrono::duration<Rep, Period> cast(struct timespec const &tv) {
+ return std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(
+ std::chrono::seconds(tv.tv_sec) + std::chrono::nanoseconds(tv.tv_nsec));
+ }
+};
+
+} // namespace detail
+
+// chrono -> timespec
+template <typename T, typename Rep, typename Period>
+auto duration_cast(std::chrono::duration<Rep, Period> const &d) ->
+ typename std::enable_if<std::is_same<T, struct timespec>::value,
+ struct timespec>::type {
+ return detail::posix_duration_cast<std::chrono::duration<Rep, Period>,
+ timespec>::cast(d);
+}
+
+// timespec -> chrono
+template <typename Duration>
+Duration duration_cast(struct timespec const &tv) {
+ return detail::posix_duration_cast<struct timespec, Duration>::cast(tv);
+}
+
+} // namespace chrono
+} // namespace std
+
namespace utils {
-using SteadyClock = std::chrono::steady_clock;
-using TimePoint = SteadyClock::time_point;
-using Milliseconds = std::chrono::milliseconds;
-using Microseconds = std::chrono::microseconds;
+template <typename T>
+class Time {
+ public:
+ using Clock = T;
+ using TimePoint = typename Clock::time_point;
+ using Rep = uint64_t;
+ using Seconds = std::chrono::duration<Rep>;
+ using Milliseconds = std::chrono::duration<Rep, std::milli>;
+ using Microseconds = std::chrono::duration<Rep, std::micro>;
+
+ static auto now() { return Clock::now(); }
+
+ // From epochs
+ static auto nowMs() {
+ return std::chrono::duration_cast<Milliseconds>(now().time_since_epoch());
+ }
+
+ // From epoch
+ static auto nowUs() {
+ return std::chrono::duration_cast<Microseconds>(now().time_since_epoch());
+ }
+
+ template <typename D>
+ static auto getDuration(const TimePoint &start, const TimePoint &end) {
+ return std::chrono::duration_cast<D>(end - start);
+ }
+
+ static auto getDurationS(const TimePoint &start, const TimePoint &end) {
+ return getDuration<Seconds>(start, end);
+ }
+ static auto getDurationMs(const TimePoint &start, const TimePoint &end) {
+ return getDuration<Milliseconds>(start, end);
+ }
+ static auto getDurationUs(const TimePoint &start, const TimePoint &end) {
+ return getDuration<Microseconds>(start, end);
+ }
+};
+
+using SteadyTime = Time<std::chrono::steady_clock>;
+using SystemTime = Time<std::chrono::system_clock>;
} // namespace utils
diff --git a/libtransport/includes/hicn/transport/utils/color.h b/libtransport/includes/hicn/transport/utils/color.h
new file mode 100644
index 000000000..3e8d93e14
--- /dev/null
+++ b/libtransport/includes/hicn/transport/utils/color.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <array>
+#include <ostream>
+#include <random>
+#include <sstream>
+
+namespace utils {
+
+#define foreach_modifier \
+ _(RESET, 0) \
+ _(BOLD, 1) \
+ _(FG_DEFAULT, 39) \
+ _(FG_BLACK, 30) \
+ _(FG_RED, 31) \
+ _(FG_GREEN, 32) \
+ _(FG_YELLOW, 33) \
+ _(FG_BLUE, 34) \
+ _(FG_MAGENTA, 35) \
+ _(FG_CYAN, 36) \
+ _(FG_LIGHT_GRAY, 37) \
+ _(FG_DARK_GRAY, 90) \
+ _(FG_LIGHT_RED, 91) \
+ _(FG_LIGHT_GREEN, 92) \
+ _(FG_LIGHT_YELLOW, 93) \
+ _(FG_LIGHT_BLUE, 94) \
+ _(FG_LIGHT_MAGENTA, 95) \
+ _(FG_LIGHT_CYAN, 96) \
+ _(FG_WHITE, 97) \
+ _(BG_RED, 41) \
+ _(BG_GREEN, 42) \
+ _(BG_BLUE, 44) \
+ _(BG_DEFAULT, 49)
+
+class ColorModifier {
+ static inline const std::size_t n_modifiers = 23;
+ static inline const char format_string_start[] = "\033[";
+ static inline const char format_string_end[] = "m";
+
+ public:
+ enum class Code {
+#define _(name, value) name = value,
+ foreach_modifier
+#undef _
+ };
+
+ static inline std::array<Code, n_modifiers> code_array = {
+#define _(name, value) Code::name,
+ foreach_modifier
+#undef _
+ };
+
+ static Code getRandomModifier() {
+ static std::random_device rd;
+ static std::mt19937 gen(rd());
+ static std::uniform_int_distribution<> distr(4, 17);
+
+ return code_array[distr(gen)];
+ }
+
+ ColorModifier(Code code) : code_(code), color_string_() {
+ std::stringstream ss;
+ if (std::getenv("COLORTERM") != nullptr) {
+ ss << format_string_start << static_cast<int>(code_) << format_string_end;
+ color_string_ = ss.str();
+ }
+ }
+
+ ColorModifier() : ColorModifier(getRandomModifier()) {}
+
+ friend std::ostream& operator<<(std::ostream& os, const ColorModifier& mod) {
+ return os << mod.color_string_;
+ }
+
+ private:
+ Code code_;
+ std::string color_string_;
+};
+
+} // namespace utils \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/utils/conversions.h b/libtransport/includes/hicn/transport/utils/conversions.h
index 52d3e3168..812803175 100644
--- a/libtransport/includes/hicn/transport/utils/conversions.h
+++ b/libtransport/includes/hicn/transport/utils/conversions.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/daemonizator.h b/libtransport/includes/hicn/transport/utils/daemonizator.h
index 028d74865..1d0a0b309 100644
--- a/libtransport/includes/hicn/transport/utils/daemonizator.h
+++ b/libtransport/includes/hicn/transport/utils/daemonizator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/event_thread.h b/libtransport/includes/hicn/transport/utils/event_thread.h
index 15ec1d62c..164c853a5 100644
--- a/libtransport/includes/hicn/transport/utils/event_thread.h
+++ b/libtransport/includes/hicn/transport/utils/event_thread.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,16 +29,16 @@ class EventThread {
EventThread(asio::io_service& io_service, bool detached = false)
: internal_io_service_(nullptr),
io_service_(std::ref(io_service)),
- work_(std::make_unique<asio::io_service::work>(io_service_)),
+ work_guard_(asio::make_work_guard(io_service_.get())),
thread_(nullptr),
detached_(detached) {
run();
}
- EventThread(bool detached = false)
+ explicit EventThread(bool detached = false)
: internal_io_service_(std::make_unique<asio::io_service>()),
io_service_(std::ref(*internal_io_service_)),
- work_(std::make_unique<asio::io_service::work>(io_service_)),
+ work_guard_(asio::make_work_guard(io_service_.get())),
thread_(nullptr),
detached_(detached) {
run();
@@ -47,22 +47,12 @@ class EventThread {
EventThread(const EventThread&) = delete;
EventThread& operator=(const EventThread&) = delete;
- EventThread(EventThread&& other)
+ EventThread(EventThread&& other) noexcept
: internal_io_service_(std::move(other.internal_io_service_)),
io_service_(std::move(other.io_service_)),
- work_(std::move(other.work_)),
+ work_guard_(std::move(other.work_guard_)),
thread_(std::move(other.thread_)),
- detached_(std::move(other.detached_)) {}
-
- EventThread& operator=(EventThread&& other) {
- internal_io_service_ = std::move(other.internal_io_service_);
- io_service_ = std::move(other.io_service_);
- work_ = std::move(other.work_);
- thread_ = std::move(other.thread_);
- detached_ = other.detached_;
-
- return *this;
- }
+ detached_(other.detached_) {}
~EventThread() { stop(); }
@@ -89,16 +79,29 @@ class EventThread {
template <typename Func>
void add(Func&& f) {
- io_service_.get().post(std::forward<Func&&>(f));
+ io_service_.get().post(std::forward<Func>(f));
}
template <typename Func>
void tryRunHandlerNow(Func&& f) {
- io_service_.get().dispatch(std::forward<Func&&>(f));
+ io_service_.get().dispatch(std::forward<Func>(f));
+ }
+
+ template <typename Func>
+ void addAndWaitForExecution(Func&& f) const {
+ auto promise = std::promise<void>();
+ auto future = promise.get_future();
+
+ asio::dispatch(io_service_.get(), [&promise, f = std::forward<Func>(f)]() {
+ f();
+ promise.set_value();
+ });
+
+ future.wait();
}
void stop() {
- work_.reset();
+ add([this]() { work_guard_.reset(); });
if (thread_ && thread_->joinable()) {
thread_->join();
@@ -107,14 +110,14 @@ class EventThread {
thread_.reset();
}
- bool stopped() { return io_service_.get().stopped(); }
+ bool stopped() const { return io_service_.get().stopped(); }
asio::io_service& getIoService() { return io_service_; }
private:
std::unique_ptr<asio::io_service> internal_io_service_;
std::reference_wrapper<asio::io_service> io_service_;
- std::unique_ptr<asio::io_service::work> work_;
+ asio::executor_work_guard<asio::io_context::executor_type> work_guard_;
std::unique_ptr<std::thread> thread_;
bool detached_;
};
diff --git a/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h b/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h
index 298b6f9d1..19b52b37e 100644
--- a/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h
+++ b/libtransport/includes/hicn/transport/utils/fixed_block_allocator.h
@@ -1,23 +1,28 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
*/
#pragma once
#include <hicn/transport/portability/c_portability.h>
+#include <hicn/transport/utils/branch_prediction.h>
#include <hicn/transport/utils/singleton.h>
#include <hicn/transport/utils/spinlock.h>
#include <stdint.h>
#include <cassert>
#include <cstdlib>
+#include <list>
#include <memory>
namespace utils {
template <std::size_t SIZE = 512, std::size_t OBJECTS = 4096>
class FixedBlockAllocator
- : public utils::Singleton<FixedBlockAllocator<SIZE, OBJECTS>> {
- friend class utils::Singleton<FixedBlockAllocator<SIZE, OBJECTS>>;
+ : public utils::ThreadLocalSingleton<FixedBlockAllocator<SIZE, OBJECTS>> {
+ friend class utils::ThreadLocalSingleton<FixedBlockAllocator<SIZE, OBJECTS>>;
+
+ static inline const std::size_t BLOCK_SIZE = SIZE;
+ static inline const std::size_t BLOCKS_PER_POOL = OBJECTS;
public:
~FixedBlockAllocator() {
@@ -26,19 +31,19 @@ class FixedBlockAllocator
}
}
- void* allocateBlock(size_t size = SIZE) {
- assert(size <= SIZE);
+ void* allocateBlock() {
uint32_t index;
-
SpinLock::Acquire locked(lock_);
void* p_block = pop();
if (!p_block) {
- if (TRANSPORT_EXPECT_FALSE(current_pool_index_ >= max_objects_)) {
+ if (TRANSPORT_EXPECT_FALSE(current_pool_index_ >= BLOCKS_PER_POOL)) {
// Allocate new memory block
p_pools_.emplace_front(
- new typename std::aligned_storage<SIZE>::type[max_objects_]);
+ new typename std::aligned_storage<SIZE>::type[BLOCKS_PER_POOL]);
// reset current_pool_index_
current_pool_index_ = 0;
+ // Increase total block count
+ block_count_ += BLOCKS_PER_POOL;
}
auto& latest = p_pools_.front();
@@ -59,7 +64,7 @@ class FixedBlockAllocator
}
public:
- std::size_t blockSize() { return block_size_; }
+ std::size_t blockSize() { return BLOCK_SIZE; }
uint32_t blockCount() { return block_count_; }
@@ -69,20 +74,32 @@ class FixedBlockAllocator
uint32_t deallocations() { return deallocations_; }
+ void reset() {
+ p_head_ = nullptr;
+ blocks_in_use_ = 0;
+ allocations_ = 0;
+ deallocations_ = 0;
+ current_pool_index_ = 0;
+ block_count_ = BLOCKS_PER_POOL;
+
+ // Delete all memory pools but the first one
+ for (auto it = std::next(p_pools_.begin()); it != p_pools_.end();) {
+ delete[] * it;
+ it = p_pools_.erase(it);
+ }
+ }
+
private:
FixedBlockAllocator()
- : block_size_(SIZE),
- object_size_(SIZE),
- max_objects_(OBJECTS),
- p_head_(NULL),
+ : p_head_(NULL),
current_pool_index_(0),
- block_count_(0),
+ block_count_(BLOCKS_PER_POOL),
blocks_in_use_(0),
allocations_(0),
deallocations_(0) {
static_assert(SIZE >= sizeof(long*), "SIZE must be at least 8 bytes");
p_pools_.emplace_front(
- new typename std::aligned_storage<SIZE>::type[max_objects_]);
+ new typename std::aligned_storage<SIZE>::type[BLOCKS_PER_POOL]);
}
void push(void* p_memory) {
@@ -106,12 +123,6 @@ class FixedBlockAllocator
Block* p_next;
};
- static std::unique_ptr<FixedBlockAllocator> instance_;
-
- const std::size_t block_size_;
- const std::size_t object_size_;
- const std::size_t max_objects_;
-
Block* p_head_;
uint32_t current_pool_index_;
std::list<typename std::aligned_storage<SIZE>::type*> p_pools_;
@@ -123,10 +134,6 @@ class FixedBlockAllocator
SpinLock lock_;
};
-template <std::size_t A, std::size_t B>
-std::unique_ptr<FixedBlockAllocator<A, B>>
- FixedBlockAllocator<A, B>::instance_ = nullptr;
-
/**
* STL Allocator trait to be used with allocate_shared.
*/
diff --git a/libtransport/includes/hicn/transport/utils/hash.h b/libtransport/includes/hicn/transport/utils/hash.h
index 6815ca4bf..7943596e6 100644
--- a/libtransport/includes/hicn/transport/utils/hash.h
+++ b/libtransport/includes/hicn/transport/utils/hash.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/libtransport/includes/hicn/transport/utils/linux.h b/libtransport/includes/hicn/transport/utils/linux.h
index 4fbf5f01e..14ef179ac 100644
--- a/libtransport/includes/hicn/transport/utils/linux.h
+++ b/libtransport/includes/hicn/transport/utils/linux.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -44,7 +44,7 @@ static TRANSPORT_ALWAYS_INLINE int retrieveInterfaceAddress(
uint16_t prefix = 0;
memcpy(&prefix, tmp->sin6_addr.s6_addr, sizeof(uint16_t));
- if (htons(LINK_LOCAL_PREFIX) != prefix) {
+ if (portability::host_to_net(LINK_LOCAL_PREFIX) != prefix) {
*address = *(struct sockaddr_in6 *)ifa->ifa_addr;
getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), addr,
sizeof(addr), NULL, 0, NI_NUMERICHOST);
diff --git a/libtransport/includes/hicn/transport/utils/literals.h b/libtransport/includes/hicn/transport/utils/literals.h
index bd00e0a58..531f67362 100644
--- a/libtransport/includes/hicn/transport/utils/literals.h
+++ b/libtransport/includes/hicn/transport/utils/literals.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/log.h b/libtransport/includes/hicn/transport/utils/log.h
index 0947b755e..f4d39b6b1 100644
--- a/libtransport/includes/hicn/transport/utils/log.h
+++ b/libtransport/includes/hicn/transport/utils/log.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/membuf.h b/libtransport/includes/hicn/transport/utils/membuf.h
index 6f92c2208..4b442dda3 100644
--- a/libtransport/includes/hicn/transport/utils/membuf.h
+++ b/libtransport/includes/hicn/transport/utils/membuf.h
@@ -30,6 +30,7 @@
#include <cinttypes>
#include <cstddef>
#include <cstring>
+#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
diff --git a/libtransport/includes/hicn/transport/utils/noncopyable.h b/libtransport/includes/hicn/transport/utils/noncopyable.h
index 83923e647..0c54d24a3 100644
--- a/libtransport/includes/hicn/transport/utils/noncopyable.h
+++ b/libtransport/includes/hicn/transport/utils/noncopyable.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/object_pool.h b/libtransport/includes/hicn/transport/utils/object_pool.h
index d9b28e663..63288c655 100644
--- a/libtransport/includes/hicn/transport/utils/object_pool.h
+++ b/libtransport/includes/hicn/transport/utils/object_pool.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,7 @@
#pragma once
#include <hicn/transport/utils/branch_prediction.h>
+#include <hicn/transport/utils/noncopyable.h>
#include <hicn/transport/utils/spinlock.h>
#include <deque>
@@ -25,7 +26,7 @@
namespace utils {
template <typename T>
-class ObjectPool {
+class ObjectPool : private utils::NonCopyable {
class ObjectDeleter {
public:
ObjectDeleter(ObjectPool<T> *pool = nullptr) : pool_(pool) {}
@@ -47,8 +48,20 @@ class ObjectPool {
ObjectPool() : destructor_(false) {}
- // No copies
- ObjectPool(const ObjectPool &other) = delete;
+ ObjectPool(ObjectPool &&other)
+ : object_pool_lock_(std::move(other.object_pool_lock_)),
+ object_pool_(std::move(other.object_pool_)),
+ destructor_(other.destructor_) {}
+
+ ObjectPool &operator=(ObjectPool &&other) {
+ if (this != &other) {
+ object_pool_lock_ = std::move(other.object_pool_lock_);
+ object_pool_ = std::move(other.object_pool_);
+ destructor_ = other.destructor_;
+ }
+
+ return *this;
+ }
~ObjectPool() {
destructor_ = true;
diff --git a/libtransport/includes/hicn/transport/utils/ring_buffer.h b/libtransport/includes/hicn/transport/utils/ring_buffer.h
index 52629b82b..3032032c9 100644
--- a/libtransport/includes/hicn/transport/utils/ring_buffer.h
+++ b/libtransport/includes/hicn/transport/utils/ring_buffer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/rtc_quality_score.h b/libtransport/includes/hicn/transport/utils/rtc_quality_score.h
new file mode 100644
index 000000000..2e8ca97d3
--- /dev/null
+++ b/libtransport/includes/hicn/transport/utils/rtc_quality_score.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RTCQualityScore {
+ public:
+ RTCQualityScore(){};
+ ~RTCQualityScore(){};
+
+ uint8_t getQualityScore(uint64_t RTT, uint32_t loss_rate) {
+ uint32_t delay_index = getDelay(RTT);
+ uint32_t loss_index = getLossRate(loss_rate);
+ return quality_score_[loss_index][delay_index];
+ }
+
+ private:
+ // see quality score map
+ uint8_t quality_score_[7][6]{{5, 5, 5, 4, 3, 1}, {5, 4, 3, 2, 1, 1},
+ {5, 3, 2, 1, 1, 1}, {5, 2, 1, 1, 1, 1},
+ {4, 1, 1, 1, 1, 1}, {3, 1, 1, 1, 1, 1},
+ {1, 1, 1, 1, 1, 1}};
+
+ uint8_t getDelay(uint64_t RTT) {
+ uint64_t OWD = RTT / 2;
+ // we should never get a OWD of 0. so we take the first col if OWD is < 5ms
+ if (OWD < 5) return 0;
+ if (OWD < 50) return 1;
+ if (OWD < 100) return 2;
+ if (OWD < 200) return 3;
+ if (OWD < 300) return 4;
+ return 5;
+ }
+
+ uint8_t getLossRate(uint32_t loss_rate) {
+ // we use 3% as mean loss rate
+ if (loss_rate < 3) return 0;
+ if (loss_rate < 10) return 1;
+ if (loss_rate < 20) return 2;
+ if (loss_rate < 30) return 3;
+ if (loss_rate < 40) return 4;
+ if (loss_rate < 50) return 5;
+ return 6;
+ }
+};
+
+} // namespace rtc
+
+} // namespace protocol
+
+} // namespace transport
diff --git a/libtransport/includes/hicn/transport/utils/singleton.h b/libtransport/includes/hicn/transport/utils/singleton.h
index 4b7b19c0a..cdd8b03bf 100644
--- a/libtransport/includes/hicn/transport/utils/singleton.h
+++ b/libtransport/includes/hicn/transport/utils/singleton.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -32,4 +32,17 @@ class Singleton : NonCopyable {
~Singleton() {}
};
+template <typename T>
+class ThreadLocalSingleton : NonCopyable {
+ public:
+ static T& getInstance() {
+ static thread_local T instance;
+ return instance;
+ }
+
+ protected:
+ ThreadLocalSingleton() {}
+ ~ThreadLocalSingleton() {}
+};
+
} // namespace utils \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/utils/spinlock.h b/libtransport/includes/hicn/transport/utils/spinlock.h
index 009a94454..40fc48de3 100644
--- a/libtransport/includes/hicn/transport/utils/spinlock.h
+++ b/libtransport/includes/hicn/transport/utils/spinlock.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/string_tokenizer.h b/libtransport/includes/hicn/transport/utils/string_tokenizer.h
index 36630eb58..2b2b893a0 100644
--- a/libtransport/includes/hicn/transport/utils/string_tokenizer.h
+++ b/libtransport/includes/hicn/transport/utils/string_tokenizer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/string_utils.h b/libtransport/includes/hicn/transport/utils/string_utils.h
index 313c28cc6..5f9cca13b 100644
--- a/libtransport/includes/hicn/transport/utils/string_utils.h
+++ b/libtransport/includes/hicn/transport/utils/string_utils.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/includes/hicn/transport/utils/thread_pool.h b/libtransport/includes/hicn/transport/utils/thread_pool.h
new file mode 100644
index 000000000..76218ff09
--- /dev/null
+++ b/libtransport/includes/hicn/transport/utils/thread_pool.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <hicn/transport/utils/event_thread.h>
+#include <hicn/transport/utils/noncopyable.h>
+
+#include <thread>
+#include <vector>
+
+namespace utils {
+
+class ThreadPool : public NonCopyable {
+ public:
+ explicit ThreadPool(
+ std::size_t n_threads = std::thread::hardware_concurrency())
+ : workers_(n_threads > 0 ? n_threads : 1) {}
+
+ ~ThreadPool() = default;
+
+ std::size_t getNThreads() const { return workers_.size(); }
+ EventThread &getWorker(std::size_t i) { return workers_.at(i); }
+ std::vector<EventThread> &getWorkers() { return workers_; }
+
+ private:
+ std::vector<EventThread> workers_;
+};
+
+} // namespace utils \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/utils/traffic_generator.h b/libtransport/includes/hicn/transport/utils/traffic_generator.h
new file mode 100644
index 000000000..abd84886d
--- /dev/null
+++ b/libtransport/includes/hicn/transport/utils/traffic_generator.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <random>
+#include <string>
+
+namespace transport {
+
+class TrafficGenerator {
+ public:
+ TrafficGenerator(uint32_t count);
+ virtual ~TrafficGenerator() = default;
+ bool hasFinished();
+ uint32_t getSentCount();
+ virtual std::pair<std::string, uint32_t> getPrefixAndSuffix();
+
+ virtual std::string getPrefix() = 0;
+ virtual uint32_t getSuffix() = 0;
+ virtual void reset();
+
+ protected:
+ void onSuffixGenerated();
+
+ uint32_t count_;
+ uint32_t sent_;
+};
+
+/* Fixed prefix, incremental suffix */
+class IncrSuffixTrafficGenerator : public TrafficGenerator {
+ public:
+ explicit IncrSuffixTrafficGenerator(std::string prefix, uint32_t suffix,
+ uint32_t count);
+ std::string getPrefix() override;
+ uint32_t getSuffix() override;
+ void reset() override;
+
+ private:
+ std::string prefix_;
+ uint32_t suffix_;
+ uint32_t initial_suffix_;
+};
+
+/* Random prefix, random suffix */
+class RandomTrafficGenerator : public TrafficGenerator {
+ public:
+ static constexpr char NET_PREFIX[] = "2001:db8:1::/64";
+
+ RandomTrafficGenerator(uint32_t count, std::string net_prefix = NET_PREFIX);
+ std::string getPrefix() override;
+ uint32_t getSuffix() override;
+
+ private:
+ std::string net_prefix_;
+ std::default_random_engine rand_engine_;
+ std::uniform_int_distribution<uint32_t> uniform_distribution_;
+};
+
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/includes/hicn/transport/utils/uri.h b/libtransport/includes/hicn/transport/utils/uri.h
index 7c28e8552..30675e880 100644
--- a/libtransport/includes/hicn/transport/utils/uri.h
+++ b/libtransport/includes/hicn/transport/utils/uri.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/CMakeLists.txt b/libtransport/src/CMakeLists.txt
index 5e0cd38e7..477a21cb1 100644
--- a/libtransport/src/CMakeLists.txt
+++ b/libtransport/src/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,10 +11,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-include(GNUInstallDirs)
-
-set(ASIO_STANDALONE 1)
-
+##############################################################
+# Source files
+##############################################################
add_subdirectory(core)
add_subdirectory(interfaces)
add_subdirectory(protocols)
@@ -23,49 +22,131 @@ add_subdirectory(implementation)
add_subdirectory(utils)
add_subdirectory(http)
-include(Packager)
-extract_version()
-configure_file("config.h.in" "hicn/transport/config.h" @ONLY)
-install(
- FILES ${CMAKE_CURRENT_BINARY_DIR}/hicn/transport/config.h
- DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/hicn/transport
- COMPONENT ${LIBTRANSPORT_COMPONENT}-dev
+
+##############################################################
+# Libraries to link
+##############################################################
+set(LIBRARIES
+ PRIVATE ${HICN_LIBRARIES}
+ PRIVATE ${CMAKE_THREAD_LIBS_INIT}
+ PRIVATE ${CMAKE_DL_LIBS}
+ PRIVATE ${OPENSSL_LIBRARIES}
+ PRIVATE ${LIBCONFIG_CPP_LIBRARIES}
+ PRIVATE ${THIRD_PARTY_LIBRARIES}
)
-install(
- FILES "transport.config"
- DESTINATION ${CMAKE_INSTALL_FULL_SYSCONFDIR}/hicn
- COMPONENT ${LIBTRANSPORT_COMPONENT}
+
+##############################################################
+# Include dirs
+##############################################################
+list(APPEND LIBTRANSPORT_INTERNAL_INCLUDE_DIRS
+ PRIVATE
+ ${CMAKE_THREADS_INCLUDE_DIRS}
+ ${ASIO_INCLUDE_DIRS}
+ ${WINDOWS_INCLUDE_DIRS}
+ ${LIBCONFIG_CPP_INCLUDE_DIRS}
+ ${THIRD_PARTY_INCLUDE_DIRS}
+ PUBLIC
+ ${ASIO_INCLUDE_DIRS}
+ ${OPENSSL_INCLUDE_DIR}
)
-list(APPEND COMPILER_DEFINITIONS
- "-DASIO_STANDALONE"
+list(APPEND LIBTRANSPORT_INTERNAL_INCLUDE_DIRS
+ PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/
+ PUBLIC
+ $<BUILD_INTERFACE:${Libhicntransport_INCLUDE_DIRS}>
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
-list(INSERT LIBTRANSPORT_INTERNAL_INCLUDE_DIRS 0
- ${CMAKE_CURRENT_SOURCE_DIR}/
- ${CMAKE_CURRENT_BINARY_DIR}/
+
+##############################################################
+# Dependencies
+##############################################################
+list(APPEND DEPENDENCIES
+ ${THIRD_PARTY_DEPENDENCIES}
)
-set(LIBTRANSPORT_INCLUDE_DIRS
- ${LIBTRANSPORT_INCLUDE_DIRS}
- "" CACHE INTERNAL
- "" FORCE
+##############################################################
+# Compiler definitions
+##############################################################
+list(APPEND COMPILER_DEFINITIONS
+ PUBLIC "-DASIO_STANDALONE"
+)
+
+if (ENABLE_RELY)
+ list(APPEND COMPILER_DEFINITIONS
+ PRIVATE "-DENABLE_RELY=1"
+ )
+endif()
+
+
+##############################################################
+# Compiler options
+##############################################################
+list(APPEND COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
)
if (NOT WIN32)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
+ list(APPEND COMPILER_OPTIONS
+ PRIVATE "-pthread"
+ )
else ()
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4200 -D_WIN32_WINDOWS=0x0400")
+ list(APPEND COMPILER_OPTIONS
+ PRIVATE "-/wd4200 -D_WIN32_WINDOWS=0x0400"
+ )
if (CMAKE_BUILD_TYPE EQUAL "RELEASE")
- set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /NODEFAULTLIB:\"MSVCRTD\"" )
+ list(APPEND COMPILER_OPTIONS
+ PRIVATE "/NODEFAULTLIB:\"MSVCRTD\""
+ )
endif ()
endif ()
if (${CMAKE_SYSTEM_NAME} MATCHES "Android")
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++ -isystem -lm")
+ list(APPEND COMPILER_OPTIONS
+ PRIVATE "-stdlib=libc++"
+ PRIVATE "-isystem"
+ PRIVATE "-lm"
+ )
endif()
+
+##############################################################
+# Configuration file
+##############################################################
+configure_file("config.h.in" "hicn/transport/config.h" @ONLY)
+install(
+ FILES ${CMAKE_CURRENT_BINARY_DIR}/hicn/transport/config.h
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/hicn/transport
+ COMPONENT ${LIBTRANSPORT_COMPONENT}-dev
+)
+
+if (${CMAKE_SYSTEM_NAME} MATCHES Darwin OR ${CMAKE_SYSTEM_NAME} MATCHES Linux)
+ install(
+ FILES "transport.config"
+ DESTINATION ${CMAKE_INSTALL_FULL_SYSCONFDIR}/hicn
+ COMPONENT ${LIBTRANSPORT_COMPONENT}
+ )
+else ()
+ install(
+ FILES "transport.config"
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/etc/hicn
+ COMPONENT ${LIBTRANSPORT_COMPONENT}
+ )
+endif()
+
+
+##############################################################
+# IO Modules
+##############################################################
+add_subdirectory(io_modules)
+
+
+##############################################################
+# Build type
+##############################################################
set (BUILD_TYPES "STATIC")
if (NOT DISABLE_SHARED_LIBRARIES)
@@ -74,8 +155,10 @@ if (NOT DISABLE_SHARED_LIBRARIES)
)
endif()
-add_subdirectory(io_modules)
+##############################################################
+# Build library
+##############################################################
build_library(${LIBTRANSPORT}
${BUILD_TYPES}
SOURCES ${SOURCE_FILES} ${HEADER_FILES}
@@ -84,12 +167,29 @@ build_library(${LIBTRANSPORT}
OBJECT_LIBRARIES ${THIRD_PARTY_OBJECT_LIBRARIES}
DEPENDS ${DEPENDENCIES}
COMPONENT ${LIBTRANSPORT_COMPONENT}
- INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIRS} ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
- HEADER_ROOT_DIR hicn/transport
+ INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
DEFINITIONS ${COMPILER_DEFINITIONS}
- VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_REVISION}
+ VERSION ${CURRENT_VERSION}
+ EXPORT_NAME ${LIBTRANSPORT_COMPONENT}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
+
+##############################################################
+# Unit tests
+##############################################################
if (${BUILD_TESTS})
add_subdirectory(test)
endif()
+
+
+##############################################################
+# Cmake config files
+##############################################################
+create_cmake_config (
+ ${LIBTRANSPORT_COMPONENT}
+ INCLUDE_DIRS ${Libhicntransport_INCLUDE_DIRS}
+ VERSION ${CURRENT_VERSION}
+ COMPONENT ${LIBTRANSPORT_COMPONENT}
+ NAMESPACE hicn
+)
diff --git a/libtransport/src/auth/CMakeLists.txt b/libtransport/src/auth/CMakeLists.txt
index 699bc1050..8d3286338 100644
--- a/libtransport/src/auth/CMakeLists.txt
+++ b/libtransport/src/auth/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -14,7 +14,6 @@
list(APPEND SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/signer.cc
${CMAKE_CURRENT_SOURCE_DIR}/verifier.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/identity.cc
${CMAKE_CURRENT_SOURCE_DIR}/crypto_hash.cc
${CMAKE_CURRENT_SOURCE_DIR}/crypto_suite.cc
)
diff --git a/libtransport/src/auth/crypto_hash.cc b/libtransport/src/auth/crypto_hash.cc
index b4b0a8b81..cf781d08e 100644
--- a/libtransport/src/auth/crypto_hash.cc
+++ b/libtransport/src/auth/crypto_hash.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,9 +13,9 @@
* limitations under the License.
*/
+#include <glog/logging.h>
#include <hicn/transport/auth/crypto_hash.h>
-
-using namespace std;
+#include <hicn/transport/core/global_object_pool.h>
namespace transport {
namespace auth {
@@ -27,90 +27,77 @@ CryptoHash::CryptoHash(const CryptoHash &other)
digest_(other.digest_),
digest_size_(other.digest_size_) {}
-CryptoHash::CryptoHash(CryptoHash &&other)
- : digest_type_(move(other.digest_type_)),
- digest_(other.digest_),
- digest_size_(other.digest_size_) {
- other.reset();
-}
+CryptoHash::CryptoHash(CryptoHash &&other) noexcept
+ : digest_type_(std::move(other.digest_type_)),
+ digest_(std::move(other.digest_)),
+ digest_size_(other.digest_size_) {}
-CryptoHash::CryptoHash(CryptoHashType hash_type) { setType(hash_type); }
+CryptoHash::CryptoHash(CryptoHashType hash_type)
+ : digest_(core::PacketManager<>::getInstance().getMemBuf()) {
+ setType(hash_type);
+}
CryptoHash::CryptoHash(const uint8_t *hash, size_t size,
CryptoHashType hash_type)
: digest_type_(hash_type), digest_size_(size) {
- digest_.resize(size);
- memcpy(digest_.data(), hash, size);
+ digest_ = core::PacketManager<>::getInstance().getMemBuf();
+ digest_->append(size);
+ memcpy(digest_->writableData(), hash, size);
}
-CryptoHash::CryptoHash(const vector<uint8_t> &hash, CryptoHashType hash_type)
+CryptoHash::CryptoHash(const std::vector<uint8_t> &hash,
+ CryptoHashType hash_type)
: CryptoHash(hash.data(), hash.size(), hash_type) {}
CryptoHash &CryptoHash::operator=(const CryptoHash &other) {
- digest_type_ = other.digest_type_;
- digest_ = other.digest_;
- digest_size_ = other.digest_size_;
+ if (this != &other) {
+ digest_type_ = other.digest_type_;
+ digest_ = other.digest_;
+ digest_size_ = other.digest_size_;
+ }
return *this;
}
bool CryptoHash::operator==(const CryptoHash &other) const {
- return (digest_type_ == other.digest_type_ && digest_ == other.digest_);
+ return (digest_type_ == other.digest_type_ && *digest_ == *other.digest_);
}
void CryptoHash::computeDigest(const uint8_t *buffer, size_t len) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(digest_type_);
-
- if (hash_evp == nullptr) {
+ const EVP_MD *hash_md = CryptoHash::getMD(digest_type_);
+ if (hash_md == nullptr) {
throw errors::RuntimeException("Unknown hash type");
}
- EVP_Digest(buffer, len, digest_.data(), (unsigned int *)&digest_size_,
- (*hash_evp)(), nullptr);
+ if (EVP_Digest(buffer, len, digest_->writableData(),
+ reinterpret_cast<unsigned int *>(&digest_size_), hash_md,
+ nullptr) != 1) {
+ throw errors::RuntimeException("Digest computation failed.");
+ };
}
-void CryptoHash::computeDigest(const vector<uint8_t> &buffer) {
+void CryptoHash::computeDigest(const std::vector<uint8_t> &buffer) {
computeDigest(buffer.data(), buffer.size());
}
void CryptoHash::computeDigest(const utils::MemBuf *buffer) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(digest_type_);
-
- if (hash_evp == nullptr) {
- throw errors::RuntimeException("Unknown hash type");
+ if (buffer->isChained()) {
+ throw errors::RuntimeException(
+ "Digest of chained membuf is not supported.");
}
- EVP_MD_CTX *mcdtx = EVP_MD_CTX_new();
- const utils::MemBuf *p = buffer;
-
- if (EVP_DigestInit_ex(mcdtx, (*hash_evp)(), nullptr) == 0) {
- throw errors::RuntimeException("Digest initialization failed");
- }
-
- do {
- if (EVP_DigestUpdate(mcdtx, p->data(), p->length()) != 1) {
- throw errors::RuntimeException("Digest update failed");
- }
-
- p = p->next();
- } while (p != buffer);
-
- if (EVP_DigestFinal_ex(mcdtx, digest_.data(),
- (unsigned int *)&digest_size_) != 1) {
- throw errors::RuntimeException("Digest computation failed");
- }
-
- EVP_MD_CTX_free(mcdtx);
+ computeDigest(buffer->data(), buffer->length());
}
-vector<uint8_t> CryptoHash::getDigest() const { return digest_; }
+const utils::MemBuf::Ptr &CryptoHash::getDigest() const { return digest_; }
-string CryptoHash::getStringDigest() const {
- stringstream string_digest;
+std::string CryptoHash::getStringDigest() const {
+ std::stringstream string_digest;
- string_digest << hex << setfill('0');
+ string_digest << std::hex << std::setfill('0');
- for (auto byte : digest_) {
- string_digest << hex << setw(2) << static_cast<int>(byte);
+ for (size_t i = 0; i < digest_size_; ++i) {
+ string_digest << std::hex << std::setw(2)
+ << static_cast<int>(digest_->data()[i]);
}
return string_digest.str();
@@ -121,80 +108,65 @@ CryptoHashType CryptoHash::getType() const { return digest_type_; }
size_t CryptoHash::getSize() const { return digest_size_; }
void CryptoHash::setType(CryptoHashType hash_type) {
- reset();
digest_type_ = hash_type;
digest_size_ = CryptoHash::getSize(hash_type);
- digest_.resize(digest_size_);
+ DCHECK(digest_size_ <= digest_->tailroom());
+ digest_->setLength(digest_size_);
}
void CryptoHash::display() {
switch (digest_type_) {
case CryptoHashType::SHA256:
- cout << "SHA256";
+ LOG(INFO) << "SHA256: " << getStringDigest();
break;
case CryptoHashType::SHA512:
- cout << "SHA512";
+ LOG(INFO) << "SHA512: " << getStringDigest();
break;
case CryptoHashType::BLAKE2S256:
- cout << "BLAKE2s256";
+ LOG(INFO) << "BLAKE2s256: " << getStringDigest();
break;
case CryptoHashType::BLAKE2B512:
- cout << "BLAKE2b512";
+ LOG(INFO) << "BLAKE2b512: " << getStringDigest();
break;
default:
- cout << "UNKNOWN";
+ LOG(INFO) << "UNKNOWN: " << getStringDigest();
break;
}
-
- cout << ": " << getStringDigest() << endl;
}
void CryptoHash::reset() {
digest_type_ = CryptoHashType::UNKNOWN;
- digest_.clear();
digest_size_ = 0;
+ digest_->setLength(0);
}
-CryptoHashEVP CryptoHash::getEVP(CryptoHashType hash_type) {
+const EVP_MD *CryptoHash::getMD(CryptoHashType hash_type) {
switch (hash_type) {
case CryptoHashType::SHA256:
- return &EVP_sha256;
- break;
+ return EVP_sha256();
case CryptoHashType::SHA512:
- return &EVP_sha512;
- break;
+ return EVP_sha512();
case CryptoHashType::BLAKE2S256:
- return &EVP_blake2s256;
- break;
+ return EVP_blake2s256();
case CryptoHashType::BLAKE2B512:
- return &EVP_blake2b512;
- break;
+ return EVP_blake2b512();
default:
return nullptr;
- break;
}
}
size_t CryptoHash::getSize(CryptoHashType hash_type) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(hash_type);
-
- if (hash_evp == nullptr) {
- return 0;
- }
-
- return EVP_MD_size((*hash_evp)());
+ const EVP_MD *hash_md = CryptoHash::getMD(hash_type);
+ return hash_md == nullptr ? 0 : EVP_MD_size(hash_md);
}
bool CryptoHash::compareDigest(const uint8_t *digest1, const uint8_t *digest2,
CryptoHashType hash_type) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(hash_type);
-
- if (hash_evp == nullptr) {
- return false;
- }
-
- return !static_cast<bool>(
- memcmp(digest1, digest2, CryptoHash::getSize(hash_type)));
+ const EVP_MD *hash_md = CryptoHash::getMD(hash_type);
+ return hash_md == nullptr
+ ? false
+ : !static_cast<bool>(
+ memcmp(digest1, digest2, CryptoHash::getSize(hash_type)));
}
} // namespace auth
diff --git a/libtransport/src/auth/crypto_suite.cc b/libtransport/src/auth/crypto_suite.cc
index 7e898ef09..e7b097ac4 100644
--- a/libtransport/src/auth/crypto_suite.cc
+++ b/libtransport/src/auth/crypto_suite.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,62 +20,112 @@ namespace auth {
CryptoSuite getSuite(int nid) {
switch (nid) {
+ case NID_ED25519:
+ return CryptoSuite::ED25519;
+ case NID_ED448:
+ return CryptoSuite::ED448;
case NID_ecdsa_with_SHA256:
return CryptoSuite::ECDSA_SHA256;
- break;
case NID_ecdsa_with_SHA512:
return CryptoSuite::ECDSA_SHA512;
- break;
case NID_sha256WithRSAEncryption:
return CryptoSuite::RSA_SHA256;
- break;
case NID_sha512WithRSAEncryption:
return CryptoSuite::RSA_SHA512;
- break;
case NID_hmacWithSHA256:
return CryptoSuite::HMAC_SHA256;
- break;
case NID_hmacWithSHA512:
return CryptoSuite::HMAC_SHA512;
- break;
case NID_dsa_with_SHA256:
return CryptoSuite::DSA_SHA256;
- break;
case NID_dsa_with_SHA512:
return CryptoSuite::DSA_SHA512;
- break;
default:
return CryptoSuite::UNKNOWN;
- break;
}
}
-CryptoHashType getHashType(CryptoSuite suite) {
+std::string getStringSuite(CryptoSuite suite) {
switch (suite) {
+ case CryptoSuite::ED25519:
+ return "ED25519";
+ case CryptoSuite::ED448:
+ return "ED448";
case CryptoSuite::ECDSA_BLAKE2B512:
+ return "ECDSA_BLAKE2B512";
+ case CryptoSuite::ECDSA_BLAKE2S256:
+ return "ECDSA_BLAKE2S256";
+ case CryptoSuite::ECDSA_SHA256:
+ return "ECDSA_SHA256";
+ case CryptoSuite::ECDSA_SHA512:
+ return "ECDSA_SHA512";
case CryptoSuite::RSA_BLAKE2B512:
+ return "RSA_BLAKE2B512";
+ case CryptoSuite::RSA_BLAKE2S256:
+ return "RSA_BLAKE2S256";
+ case CryptoSuite::RSA_SHA256:
+ return "RSA_SHA256";
+ case CryptoSuite::RSA_SHA512:
+ return "RSA_SHA512";
case CryptoSuite::HMAC_BLAKE2B512:
+ return "HMAC_BLAKE2B512";
+ case CryptoSuite::HMAC_BLAKE2S256:
+ return "HMAC_BLAKE2S256";
+ case CryptoSuite::HMAC_SHA256:
+ return "HMAC_SHA256";
+ case CryptoSuite::HMAC_SHA512:
+ return "HMAC_SHA512";
+ case CryptoSuite::DSA_BLAKE2B512:
+ return "DSA_BLAKE2B512";
+ case CryptoSuite::DSA_BLAKE2S256:
+ return "DSA_BLAKE2S256";
+ case CryptoSuite::DSA_SHA256:
+ return "DSA_SHA256";
+ case CryptoSuite::DSA_SHA512:
+ return "DSA_SHA512";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+CryptoHashType getHashType(CryptoSuite suite) {
+ switch (suite) {
case CryptoSuite::DSA_BLAKE2B512:
+ case CryptoSuite::ECDSA_BLAKE2B512:
+ case CryptoSuite::HMAC_BLAKE2B512:
+ case CryptoSuite::RSA_BLAKE2B512:
return CryptoHashType::BLAKE2B512;
+ case CryptoSuite::DSA_BLAKE2S256:
case CryptoSuite::ECDSA_BLAKE2S256:
- case CryptoSuite::RSA_BLAKE2S256:
case CryptoSuite::HMAC_BLAKE2S256:
- case CryptoSuite::DSA_BLAKE2S256:
+ case CryptoSuite::RSA_BLAKE2S256:
return CryptoHashType::BLAKE2S256;
+ case CryptoSuite::DSA_SHA256:
case CryptoSuite::ECDSA_SHA256:
- case CryptoSuite::RSA_SHA256:
+ case CryptoSuite::ED25519:
+ case CryptoSuite::ED448:
case CryptoSuite::HMAC_SHA256:
- case CryptoSuite::DSA_SHA256:
+ case CryptoSuite::RSA_SHA256:
return CryptoHashType::SHA256;
+ case CryptoSuite::DSA_SHA512:
case CryptoSuite::ECDSA_SHA512:
- case CryptoSuite::RSA_SHA512:
case CryptoSuite::HMAC_SHA512:
- case CryptoSuite::DSA_SHA512:
+ case CryptoSuite::RSA_SHA512:
return CryptoHashType::SHA512;
default:
return CryptoHashType::UNKNOWN;
}
}
+const EVP_MD *getMD(CryptoSuite suite) {
+ switch (suite) {
+ case CryptoSuite::ED25519:
+ case CryptoSuite::ED448:
+ return nullptr;
+ default:
+ return CryptoHash::getMD(getHashType(suite));
+ }
+}
+
} // namespace auth
} // namespace transport
diff --git a/libtransport/src/auth/identity.cc b/libtransport/src/auth/identity.cc
deleted file mode 100644
index f56532033..000000000
--- a/libtransport/src/auth/identity.cc
+++ /dev/null
@@ -1,288 +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/auth/identity.h>
-
-using namespace std;
-
-// function needed to create the a certificate
-static bool _addRandomSerial(X509 *cert) {
- unsigned long serial = 0;
- unsigned char serial_bytes[sizeof(serial)];
-
- // Construct random positive serial number.
- RAND_bytes(serial_bytes, sizeof(serial_bytes));
- serial_bytes[0] &= 0x7F;
- serial = 0;
- for (size_t i = 0; i < sizeof(serial_bytes); i++) {
- serial = (256 * serial) + serial_bytes[i];
- }
- ASN1_INTEGER_set(X509_get_serialNumber(cert), serial);
- return true;
-}
-
-static bool _addValidityPeriod(X509 *cert, size_t validityDays) {
- // Set the validity from now for the specified number of days.
- X509_gmtime_adj(X509_get_notBefore(cert), (long)0);
- X509_gmtime_adj(X509_get_notAfter(cert), (long)(60 * 60 * 24 * validityDays));
- return true;
-}
-
-static bool _addSubjectName(X509 *cert, const char *subjectname) {
- // Set up the simple subject name and issuer name for the certificate.
- X509_NAME *name = X509_get_subject_name(cert);
-
- if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
- (unsigned char *)subjectname, -1, -1, 0)) {
- if (X509_set_issuer_name(cert, name)) {
- return true;
- }
- }
- return false;
-}
-static bool _addCertificateExtensionWithContext(X509 *cert, int nid,
- const char *value) {
- X509_EXTENSION *extension;
- X509V3_CTX context;
-
- X509V3_set_ctx_nodb(&context);
- X509V3_set_ctx(&context, cert, cert, NULL, NULL, 0);
- extension = X509V3_EXT_conf_nid(NULL, &context, nid, value);
- if (extension == NULL) {
- return false;
- }
- X509_add_ext(cert, extension, -1);
- X509_EXTENSION_free(extension);
- return true;
-}
-static bool _addCertificateExtension(X509 *cert, int nid, const char *value) {
- X509_EXTENSION *extension = X509V3_EXT_conf_nid(NULL, NULL, nid, value);
- if (extension == NULL) {
- return false;
- }
- X509_add_ext(cert, extension, -1);
- X509_EXTENSION_free(extension);
- return true;
-}
-
-static bool _addExtensions(X509 *cert) {
- // Add the necessary extensions.
- if (_addCertificateExtension(cert, NID_basic_constraints,
- "critical,CA:FALSE") == true) {
- if (_addCertificateExtension(
- cert, NID_key_usage,
- "digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment,"
- "keyAgreement") == true) {
- if (_addCertificateExtension(cert, NID_ext_key_usage, "clientAuth") ==
- true) {
- return true;
- }
- }
- }
- return false;
-}
-static bool _addKeyIdentifier(X509 *cert) {
- unsigned char spkid[SHA256_DIGEST_LENGTH];
- char spkid_hex[1 + 2 * SHA256_DIGEST_LENGTH];
- if (ASN1_item_digest(ASN1_ITEM_rptr(X509_PUBKEY), EVP_sha256(),
- X509_get_X509_PUBKEY(cert), spkid, NULL)) {
- for (int i = 0; i < 32; i++) {
- snprintf(&spkid_hex[2 * i], 3, "%02X", (unsigned)spkid[i]);
- }
- if (_addCertificateExtension(cert, NID_subject_key_identifier, spkid_hex) ==
- true) {
- if (_addCertificateExtensionWithContext(
- cert, NID_authority_key_identifier, "keyid:always") == true) {
- return true;
- }
- }
- }
- return false;
-}
-
-namespace transport {
-namespace auth {
-
-Identity::Identity(const string &keystore_path, const string &keystore_pwd,
- CryptoSuite suite, unsigned int signature_len,
- unsigned int validity_days, const string &subject_name)
- : cert_(X509_new(), ::X509_free) {
- // create the file and complete it.
- // first we create the certificate
-
- // to create the cert we will need a private key
-
- std::shared_ptr<EVP_PKEY> privateKey(EVP_PKEY_new(), EVP_PKEY_free);
-
- if (suite == CryptoSuite::RSA_SHA512 || suite == CryptoSuite::RSA_SHA256) {
- RSA *rsa = RSA_new();
- BIGNUM *pub_exp;
-
- pub_exp = BN_new();
-
- BN_set_word(pub_exp, RSA_F4);
- if (1 != RSA_generate_key_ex(rsa, signature_len, pub_exp, NULL))
- throw errors::RuntimeException("can't generate the key");
- if (1 != EVP_PKEY_set1_RSA(privateKey.get(), rsa))
- throw errors::RuntimeException("can't generate the key");
- } else if (suite == CryptoSuite::ECDSA_SHA256) {
- int curve_params;
- switch (signature_len) {
- case 160u:
- curve_params = NID_secp160k1;
- break;
- case 192u:
- curve_params = NID_secp192k1;
- break;
- case 224u:
- curve_params = NID_secp224k1;
- break;
- case 256u:
- curve_params = NID_secp256k1;
- break;
- default:
- curve_params = -1;
- break;
- }
- if (curve_params == -1)
- throw errors::RuntimeException("can't generate the key");
- EC_KEY *ec_key = EC_KEY_new_by_curve_name(curve_params);
- if (ec_key == NULL)
- throw errors::RuntimeException("can't create ecdsa key from curve");
- EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
- if (EC_KEY_generate_key(ec_key) == 0)
- throw errors::RuntimeException("can't generate the ecdsa key");
- if (EVP_PKEY_set1_EC_KEY(privateKey.get(), ec_key) == 0)
- throw errors::RuntimeException("can't generate the ecdsa key");
- } else if (suite == CryptoSuite::DSA_SHA256) {
- DSA *dsa = DSA_new();
- unsigned char buffer[32];
- if (RAND_bytes(buffer, sizeof(buffer)) != 1) {
- throw errors::RuntimeException("can't generate the key");
- }
- if (DSA_generate_parameters_ex(dsa, signature_len, buffer, sizeof(buffer),
- NULL, NULL, NULL) != 1)
- throw errors::RuntimeException("can't generate the key");
- if (DSA_generate_key(dsa) != 1)
- throw errors::RuntimeException("can't generate the key");
- if (EVP_PKEY_set1_DSA(privateKey.get(), dsa) != 1)
- throw errors::RuntimeException("can't generate the key");
- }
- bool success = true;
- success = success && (X509_set_version(cert_.get(), 2) == 1); // 2 => X509v3
- success = success && _addRandomSerial(cert_.get());
- success = success && _addValidityPeriod(cert_.get(), validity_days);
- success = success && (X509_set_pubkey(cert_.get(), privateKey.get()) == 1);
- success = success && _addSubjectName(cert_.get(), subject_name.c_str());
- success = success && _addExtensions(cert_.get());
- success =
- success && (X509_sign(cert_.get(), privateKey.get(), EVP_sha256()) != 0);
- success = success && _addKeyIdentifier(cert_.get());
- if (!success) {
- throw errors::RuntimeException("error while creating the certificate");
- }
- // the certificate is created. We create the pkcs12 object to write the p12
- // file
- PKCS12 *p12 = PKCS12_create(
- keystore_pwd.c_str(), "ccnxuser", privateKey.get(), cert_.get(), NULL, 0,
- 0, 0 /*default iter*/, PKCS12_DEFAULT_ITER /*mac_iter*/, 0);
- filename_ = keystore_path;
- int fp = open(filename_.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600);
- if (fp == -1) throw errors::RuntimeException("impossible to create the file");
- FILE *fp_f = fdopen(fp, "wb");
- if (fp_f == NULL)
- throw errors::RuntimeException("impossible to create the file");
- i2d_PKCS12_fp(fp_f, p12);
- fclose(fp_f);
- close(fp);
- std::shared_ptr<EVP_PKEY> publickey(X509_get_pubkey(cert_.get()),
- EVP_PKEY_free);
- signer_ = std::shared_ptr<AsymmetricSigner>(
- new AsymmetricSigner(suite, privateKey, publickey));
- signer_->signature_len_ = signature_len;
-}
-
-Identity::Identity(string &keystore_path, string &keystore_pwd,
- CryptoHashType hash_type)
- : cert_(X509_new(), ::X509_free) {
- filename_ = keystore_path;
- pwd_ = keystore_path;
- // get the key and certificate by first opening the keystore file
- FILE *p12file = fopen(keystore_path.c_str(), "r");
- if (p12file == NULL)
- throw errors::RuntimeException("impossible open keystore");
- PKCS12 *p12 = d2i_PKCS12_fp(p12file, NULL);
- EVP_PKEY *privatekey;
- EVP_PKEY *publickey;
- X509 *cert = cert_.get();
- // now we parse the file to get the first key and certificate
- if (1 != PKCS12_parse(p12, keystore_pwd.c_str(), &privatekey, &cert, NULL))
- throw errors::RuntimeException("impossible to get the private key");
- publickey = X509_get_pubkey(cert);
- // to have the cryptosuite we use the nid number that is used to identify the
- // suite.
- CryptoSuite suite = getSuite(X509_get_signature_nid(cert));
- signer_ = std::shared_ptr<AsymmetricSigner>(new AsymmetricSigner(
- suite, std::shared_ptr<EVP_PKEY>(privatekey, EVP_PKEY_free),
- std::shared_ptr<EVP_PKEY>(publickey, EVP_PKEY_free)));
- PKCS12_free(p12);
-}
-
-Identity::Identity(const Identity &other) {
- pwd_ = other.pwd_;
- filename_ = other.filename_;
- signer_ = other.signer_;
- cert_ = other.cert_;
-}
-
-Identity::Identity(Identity &&other) {
- signer_ = std::move(other.signer_);
- other.signer_.reset();
- cert_ = std::move(other.cert_);
- other.cert_.reset();
- pwd_ = other.pwd_;
- other.pwd_ = "";
- filename_ = other.filename_;
- other.filename_ = "";
- signer_ = other.signer_;
- other.signer_ = nullptr;
-}
-
-Identity::~Identity() {}
-
-shared_ptr<AsymmetricSigner> Identity::getSigner() const { return signer_; }
-
-string Identity::getFilename() const { return filename_; }
-
-std::shared_ptr<X509> Identity::getCertificate() const { return cert_; }
-std::shared_ptr<EVP_PKEY> Identity::getPrivateKey() const {
- return signer_->key_;
-}
-
-string Identity::getPassword() const { return pwd_; }
-
-Identity Identity::generateIdentity(const string &subject_name) {
- string keystore_name = "keystore";
- string keystore_password = "password";
- size_t key_length = 1024;
- unsigned int validity_days = 30;
- CryptoSuite suite = CryptoSuite::RSA_SHA256;
-
- return Identity(keystore_name, keystore_password, suite,
- (unsigned int)key_length, validity_days, subject_name);
-}
-
-} // namespace auth
-} // namespace transport
diff --git a/libtransport/src/auth/signer.cc b/libtransport/src/auth/signer.cc
index 884e850ca..5fcb242be 100644
--- a/libtransport/src/auth/signer.cc
+++ b/libtransport/src/auth/signer.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,9 +13,12 @@
* limitations under the License.
*/
+#include <glog/logging.h>
#include <hicn/transport/auth/signer.h>
+#include <hicn/transport/core/interest.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
-using namespace std;
+#include "hicn/transport/core/global_object_pool.h"
namespace transport {
namespace auth {
@@ -24,131 +27,122 @@ namespace auth {
// Base Signer
// ---------------------------------------------------------
Signer::Signer()
- : suite_(CryptoSuite::UNKNOWN), signature_len_(0), key_(nullptr) {}
+ : suite_(CryptoSuite::UNKNOWN),
+ signature_(core::PacketManager<>::getInstance().getMemBuf()),
+ signature_len_(0),
+ key_(nullptr) {}
Signer::~Signer() {}
void Signer::signPacket(PacketPtr packet) {
- assert(key_ != nullptr);
- core::Packet::Format format = packet->getFormat();
-
- if (!packet->authenticationHeader()) {
+ DCHECK(key_ != nullptr);
+ if (!packet->hasAH()) {
throw errors::MalformedAHPacketException();
}
// Set signature size
size_t signature_field_len = getSignatureFieldSize();
- packet->setSignatureSize(signature_field_len);
- packet->setSignatureSizeGap(0u);
+ packet->setSignatureFieldSize(signature_field_len);
+ packet->updateLength(); // update IP payload length
// Copy IP+TCP / ICMP header before zeroing them
- hicn_header_t header_copy;
- hicn_packet_copy_header(format, packet->packet_start_, &header_copy, false);
+ u8 header_copy[HICN_HDRLEN_MAX];
+ size_t header_len;
+ packet->saveHeader(header_copy, &header_len);
+
+ // Copy bitmap from interest manifest
+ uint32_t request_bitmap[BITMAP_SIZE] = {0};
+ if (packet->isInterest()) {
+ core::Interest *interest = dynamic_cast<core::Interest *>(packet);
+ if (interest->hasManifest())
+ memcpy(request_bitmap, interest->getRequestBitmap(),
+ BITMAP_SIZE * sizeof(uint32_t));
+ }
// Fill in the hICN AH header
- auto now = chrono::duration_cast<chrono::milliseconds>(
- chrono::system_clock::now().time_since_epoch())
- .count();
+ auto now = utils::SteadyTime::nowMs().count();
packet->setSignatureTimestamp(now);
packet->setValidationAlgorithm(suite_);
// Set key ID
- vector<uint8_t> key_id = key_id_.getDigest();
- packet->setKeyId({key_id.data(), key_id.size()});
+ const utils::MemBuf::Ptr &key_id = key_id_.getDigest();
+ packet->setKeyId({key_id->writableData(), key_id->length()});
// Reset fields to compute the packet hash
packet->resetForHash();
// Compute the signature and put it in the packet
signBuffer(packet);
- hicn_packet_copy_header(format, &header_copy, packet->packet_start_, false);
+ packet->setSignature(signature_);
+ packet->setSignatureSize(signature_len_);
- // Set the gap between the signature field size and the signature real size.
- packet->setSignatureSizeGap(signature_field_len - signature_len_);
- memcpy(packet->getSignature(), signature_.data(), signature_len_);
-}
+ // Restore header
+ packet->loadHeader(header_copy, header_len);
-void Signer::signBuffer(const std::vector<uint8_t> &buffer) {
- assert(key_ != nullptr);
- CryptoHashEVP hash_evp = CryptoHash::getEVP(getHashType());
-
- if (hash_evp == nullptr) {
- throw errors::RuntimeException("Unknown hash type");
+ // Restore bitmap in interest manifest
+ if (packet->isInterest()) {
+ core::Interest *interest = dynamic_cast<core::Interest *>(packet);
+ interest->setRequestBitmap(request_bitmap);
}
+}
- shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
+void Signer::signBuffer(const uint8_t *buffer, std::size_t len) {
+ const EVP_MD *hash_md = getMD(suite_);
- if (mdctx == nullptr) {
- throw errors::RuntimeException("Digest context allocation failed");
+ std::shared_ptr<EVP_MD_CTX> md_ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free);
+ if (md_ctx == nullptr) {
+ throw errors::RuntimeException("Signature context allocation failed");
}
- if (EVP_DigestSignInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
- key_.get()) != 1) {
- throw errors::RuntimeException("Digest initialization failed");
+ if (EVP_DigestSignInit(md_ctx.get(), nullptr, hash_md, nullptr, key_.get()) !=
+ 1) {
+ throw errors::RuntimeException("Signature initialization failed");
}
- if (EVP_DigestSignUpdate(mdctx.get(), buffer.data(), buffer.size()) != 1) {
- throw errors::RuntimeException("Digest update failed");
- }
+ if (EVP_DigestSign(md_ctx.get(), nullptr, &signature_len_, buffer, len) !=
+ 1) {
+ throw errors::RuntimeException("Signature length computation failed");
+ };
- if (EVP_DigestSignFinal(mdctx.get(), nullptr, &signature_len_) != 1) {
- throw errors::RuntimeException("Digest computation failed");
- }
+ DCHECK(signature_len_ <= signature_->tailroom());
+ signature_->setLength(signature_len_);
- signature_.resize(signature_len_);
+ if (EVP_DigestSign(md_ctx.get(), signature_->writableData(), &signature_len_,
+ buffer, len) != 1) {
+ throw errors::RuntimeException("Signature computation failed");
+ };
- if (EVP_DigestSignFinal(mdctx.get(), signature_.data(), &signature_len_) !=
- 1) {
- throw errors::RuntimeException("Digest computation failed");
- }
+ DCHECK(signature_len_ <= signature_->tailroom());
+ signature_->setLength(signature_len_);
+}
- signature_.resize(signature_len_);
+void Signer::signBuffer(const std::vector<uint8_t> &buffer) {
+ signBuffer(buffer.data(), buffer.size());
}
void Signer::signBuffer(const utils::MemBuf *buffer) {
- assert(key_ != nullptr);
- CryptoHashEVP hash_evp = CryptoHash::getEVP(getHashType());
-
- if (hash_evp == nullptr) {
- throw errors::RuntimeException("Unknown hash type");
- }
-
- const utils::MemBuf *p = buffer;
- shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
-
- if (mdctx == nullptr) {
- throw errors::RuntimeException("Digest context allocation failed");
+ if (buffer->isChained()) {
+ throw errors::RuntimeException(
+ "Signature of chained membuf is not supported.");
}
- if (EVP_DigestSignInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
- key_.get()) != 1) {
- throw errors::RuntimeException("Digest initialization failed");
- }
-
- do {
- if (EVP_DigestSignUpdate(mdctx.get(), p->data(), p->length()) != 1) {
- throw errors::RuntimeException("Digest update failed");
- }
-
- p = p->next();
- } while (p != buffer);
+ signBuffer(buffer->data(), buffer->length());
+}
- if (EVP_DigestSignFinal(mdctx.get(), nullptr, &signature_len_) != 1) {
- throw errors::RuntimeException("Digest computation failed");
- }
+const utils::MemBuf::Ptr &Signer::getSignature() const { return signature_; }
- signature_.resize(signature_len_);
+std::string Signer::getStringSignature() const {
+ std::stringstream string_sig;
+ string_sig << std::hex << std::setfill('0');
- if (EVP_DigestSignFinal(mdctx.get(), signature_.data(), &signature_len_) !=
- 1) {
- throw errors::RuntimeException("Digest computation failed");
+ for (size_t i = 0; i < signature_len_; ++i) {
+ string_sig << std::hex << std::setw(2)
+ << static_cast<int>(signature_->data()[i]);
}
- signature_.resize(signature_len_);
+ return string_sig.str();
}
-vector<uint8_t> Signer::getSignature() const { return signature_; }
-
size_t Signer::getSignatureSize() const { return signature_len_; }
size_t Signer::getSignatureFieldSize() const {
@@ -159,37 +153,79 @@ size_t Signer::getSignatureFieldSize() const {
return (signature_len_ + 4) - (signature_len_ % 4);
}
+CryptoSuite Signer::getSuite() const { return suite_; }
+
CryptoHashType Signer::getHashType() const {
return ::transport::auth::getHashType(suite_);
}
-CryptoSuite Signer::getSuite() const { return suite_; }
+void Signer::display() {
+ LOG(INFO) << getStringSuite(suite_) << ": " << getStringSignature();
+}
// ---------------------------------------------------------
// Void Signer
// ---------------------------------------------------------
-void VoidSigner::signPacket(PacketPtr packet){};
+void VoidSigner::signPacket(PacketPtr packet) {}
+
+void VoidSigner::signBuffer(const uint8_t *buffer, std::size_t len) {}
-void VoidSigner::signBuffer(const std::vector<uint8_t> &buffer){};
+void VoidSigner::signBuffer(const std::vector<uint8_t> &buffer) {}
-void VoidSigner::signBuffer(const utils::MemBuf *buffer){};
+void VoidSigner::signBuffer(const utils::MemBuf *buffer) {}
// ---------------------------------------------------------
// Asymmetric Signer
// ---------------------------------------------------------
-AsymmetricSigner::AsymmetricSigner(CryptoSuite suite, shared_ptr<EVP_PKEY> key,
- shared_ptr<EVP_PKEY> pub_key) {
+AsymmetricSigner::AsymmetricSigner(CryptoSuite suite,
+ std::shared_ptr<EVP_PKEY> key,
+ std::shared_ptr<EVP_PKEY> pub_key)
+ : Signer() {
+ setKey(suite, key, pub_key);
+}
+
+AsymmetricSigner::AsymmetricSigner(std::string keystore_path,
+ std::string password)
+ : Signer() {
+ FILE *p12file = fopen(keystore_path.c_str(), "r");
+
+ if (p12file == nullptr) {
+ throw errors::RuntimeException("failed to read keystore");
+ }
+
+ std::unique_ptr<PKCS12, decltype(&PKCS12_free)> p12(
+ d2i_PKCS12_fp(p12file, nullptr), &PKCS12_free);
+ X509 *cert_raw;
+ EVP_PKEY *key_raw;
+
+ if (PKCS12_parse(p12.get(), password.c_str(), &key_raw, &cert_raw, nullptr) !=
+ 1) {
+ fclose(p12file);
+ throw errors::RuntimeException("failed to parse keystore");
+ }
+
+ std::shared_ptr<EVP_PKEY> key(key_raw, EVP_PKEY_free);
+ std::shared_ptr<EVP_PKEY> pub_key(X509_get_pubkey(cert_raw), EVP_PKEY_free);
+
+ setKey(transport::auth::getSuite(X509_get_signature_nid(cert_raw)), key,
+ pub_key);
+
+ fclose(p12file);
+}
+
+void AsymmetricSigner::setKey(CryptoSuite suite, std::shared_ptr<EVP_PKEY> key,
+ std::shared_ptr<EVP_PKEY> pub_key) {
suite_ = suite;
key_ = key;
- key_id_ = CryptoHash(getHashType());
- vector<uint8_t> pbk(i2d_PublicKey(pub_key.get(), nullptr));
- uint8_t *pbk_ptr = pbk.data();
- int len = i2d_PublicKey(pub_key.get(), &pbk_ptr);
+ signature_len_ = EVP_PKEY_size(key_.get());
+ DCHECK(signature_len_ <= signature_->tailroom());
+ signature_->setLength(signature_len_);
- signature_len_ = EVP_PKEY_size(key.get());
- signature_.resize(signature_len_);
- key_id_.computeDigest(pbk_ptr, len);
+ // Key ID is not supported yet.
+ uint8_t id[8] = {0};
+ key_id_ = CryptoHash(getHashType());
+ key_id_.computeDigest(id, 8);
}
size_t AsymmetricSigner::getSignatureFieldSize() const {
@@ -205,24 +241,29 @@ size_t AsymmetricSigner::getSignatureFieldSize() const {
// ---------------------------------------------------------
// Symmetric Signer
// ---------------------------------------------------------
-SymmetricSigner::SymmetricSigner(CryptoSuite suite, const string &passphrase) {
+SymmetricSigner::SymmetricSigner(CryptoSuite suite,
+ const std::string &passphrase)
+ : Signer() {
suite_ = suite;
- key_ = shared_ptr<EVP_PKEY>(
+ key_ = std::shared_ptr<EVP_PKEY>(
EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, nullptr,
(const unsigned char *)passphrase.c_str(),
passphrase.size()),
EVP_PKEY_free);
- key_id_ = CryptoHash(getHashType());
- CryptoHashEVP hash_evp = CryptoHash::getEVP(getHashType());
-
- if (hash_evp == nullptr) {
+ const EVP_MD *hash_md = getMD(suite_);
+ if (hash_md == nullptr) {
throw errors::RuntimeException("Unknown hash type");
}
- signature_len_ = EVP_MD_size((*hash_evp)());
- signature_.resize(signature_len_);
- key_id_.computeDigest((uint8_t *)passphrase.c_str(), passphrase.size());
+ signature_len_ = EVP_MD_size(hash_md);
+ DCHECK(signature_len_ <= signature_->tailroom());
+ signature_->setLength(signature_len_);
+
+ // Key ID is not supported yet.
+ uint8_t id[8] = {0};
+ key_id_ = CryptoHash(getHashType());
+ key_id_.computeDigest(id, 8);
}
} // namespace auth
diff --git a/libtransport/src/auth/verifier.cc b/libtransport/src/auth/verifier.cc
index c9ac1650f..0919aec7d 100644
--- a/libtransport/src/auth/verifier.cc
+++ b/libtransport/src/auth/verifier.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,14 +14,16 @@
*/
#include <hicn/transport/auth/verifier.h>
+#include <hicn/transport/core/global_object_pool.h>
+#include <hicn/transport/core/interest.h>
#include <protocols/errors.h>
-using namespace std;
+#include "glog/logging.h"
namespace transport {
namespace auth {
-const vector<VerificationPolicy> Verifier::DEFAULT_FAILED_POLICIES = {
+const std::vector<VerificationPolicy> Verifier::DEFAULT_FAILED_POLICIES = {
VerificationPolicy::DROP,
VerificationPolicy::ABORT,
};
@@ -36,42 +38,55 @@ Verifier::Verifier()
Verifier::~Verifier() {}
bool Verifier::verifyPacket(PacketPtr packet) {
- core::Packet::Format format = packet->getFormat();
-
- if (!packet->authenticationHeader()) {
+ if (!packet->hasAH()) {
throw errors::MalformedAHPacketException();
}
- // Get crypto suite, hash type, signature length
+ // Get crypto suite
CryptoSuite suite = packet->getValidationAlgorithm();
- CryptoHashType hash_type = getHashType(suite);
- size_t signature_len = packet->getSignatureSizeReal();
// Copy IP+TCP / ICMP header before zeroing them
- hicn_header_t header_copy;
- hicn_packet_copy_header(format, packet->packet_start_, &header_copy, false);
- packet->setSignatureSizeGap(0u);
+ u8 header_copy[HICN_HDRLEN_MAX];
+ size_t header_len;
+ packet->saveHeader(header_copy, &header_len);
+
+ // Copy bitmap from interest manifest
+ uint32_t request_bitmap[BITMAP_SIZE] = {0};
+ if (packet->isInterest()) {
+ core::Interest *interest = dynamic_cast<core::Interest *>(packet);
+ memcpy(request_bitmap, interest->getRequestBitmap(),
+ BITMAP_SIZE * sizeof(uint32_t));
+ }
// Retrieve packet signature
- uint8_t *packet_signature = packet->getSignature();
- vector<uint8_t> signature_raw(packet_signature,
- packet_signature + signature_len);
+ utils::MemBuf::Ptr signature_raw = packet->getSignature();
+ std::size_t signature_len = packet->getSignatureSize();
+ DCHECK(signature_len <= signature_raw->tailroom());
+ signature_raw->setLength(signature_len);
// Reset fields that are not used to compute signature
packet->resetForHash();
// Check signatures
- bool valid_packet = verifyBuffer(static_cast<utils::MemBuf *>(packet),
- signature_raw, hash_type);
+ bool valid_packet =
+ verifyBuffer(static_cast<utils::MemBuf *>(packet), signature_raw, suite);
// Restore header
- hicn_packet_copy_header(format, &header_copy, packet->packet_start_, false);
- packet->setSignatureSizeGap(packet->getSignatureSize() - signature_len);
+ packet->loadHeader(header_copy, header_len);
+ packet->setSignature(signature_raw);
+ packet->setSignatureSize(signature_raw->length());
+
+ // Restore bitmap in interest manifest
+ if (packet->isInterest()) {
+ core::Interest *interest = dynamic_cast<core::Interest *>(packet);
+ interest->setRequestBitmap(request_bitmap);
+ }
return valid_packet;
}
-Verifier::PolicyMap Verifier::verifyPackets(const vector<PacketPtr> &packets) {
+Verifier::PolicyMap Verifier::verifyPackets(
+ const std::vector<PacketPtr> &packets) {
PolicyMap policies;
for (const auto &packet : packets) {
@@ -82,8 +97,8 @@ Verifier::PolicyMap Verifier::verifyPackets(const vector<PacketPtr> &packets) {
policy = VerificationPolicy::ACCEPT;
}
+ callVerificationFailedCallback(suffix, policy);
policies[suffix] = policy;
- callVerificationFailedCallback(packet, policy);
}
return policies;
@@ -105,14 +120,15 @@ Verifier::PolicyMap Verifier::verifyHashes(const SuffixMap &packet_map,
}
}
+ callVerificationFailedCallback(packet_hash.first, policy);
policies[packet_hash.first] = policy;
}
return policies;
}
-Verifier::PolicyMap Verifier::verifyPackets(const vector<PacketPtr> &packets,
- const SuffixMap &suffix_map) {
+Verifier::PolicyMap Verifier::verifyPackets(
+ const std::vector<PacketPtr> &packets, const SuffixMap &suffix_map) {
PolicyMap policies;
for (const auto &packet : packets) {
@@ -130,8 +146,8 @@ Verifier::PolicyMap Verifier::verifyPackets(const vector<PacketPtr> &packets,
}
}
+ callVerificationFailedCallback(suffix, policy);
policies[suffix] = policy;
- callVerificationFailedCallback(packet, policy);
}
return policies;
@@ -139,7 +155,7 @@ Verifier::PolicyMap Verifier::verifyPackets(const vector<PacketPtr> &packets,
void Verifier::setVerificationFailedCallback(
VerificationFailedCallback verfication_failed_cb,
- const vector<VerificationPolicy> &failed_policies) {
+ const std::vector<VerificationPolicy> &failed_policies) {
verification_failed_cb_ = verfication_failed_cb;
failed_policies_ = failed_policies;
}
@@ -149,7 +165,7 @@ void Verifier::getVerificationFailedCallback(
*verfication_failed_cb = &verification_failed_cb_;
}
-void Verifier::callVerificationFailedCallback(PacketPtr packet,
+void Verifier::callVerificationFailedCallback(Suffix suffix,
VerificationPolicy &policy) {
if (verification_failed_cb_ == interface::VOID_HANDLER) {
return;
@@ -157,10 +173,7 @@ void Verifier::callVerificationFailedCallback(PacketPtr packet,
if (find(failed_policies_.begin(), failed_policies_.end(), policy) !=
failed_policies_.end()) {
- policy = verification_failed_cb_(
- static_cast<const core::ContentObject &>(*packet),
- make_error_code(
- protocol::protocol_error::signature_verification_failed));
+ policy = verification_failed_cb_(suffix, policy);
}
}
@@ -169,217 +182,188 @@ void Verifier::callVerificationFailedCallback(PacketPtr packet,
// ---------------------------------------------------------
bool VoidVerifier::verifyPacket(PacketPtr packet) { return true; }
-bool VoidVerifier::verifyBuffer(const vector<uint8_t> &buffer,
- const vector<uint8_t> &signature,
- CryptoHashType hash_type) {
+bool VoidVerifier::verifyBuffer(const uint8_t *buffer, std::size_t len,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
+ return true;
+}
+
+bool VoidVerifier::verifyBuffer(const std::vector<uint8_t> &buffer,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
return true;
}
bool VoidVerifier::verifyBuffer(const utils::MemBuf *buffer,
- const vector<uint8_t> &signature,
- CryptoHashType hash_type) {
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
return true;
}
Verifier::PolicyMap VoidVerifier::verifyPackets(
- const vector<PacketPtr> &packets) {
+ const std::vector<PacketPtr> &packets) {
PolicyMap policies;
for (const auto &packet : packets) {
- policies[packet->getName().getSuffix()] = VerificationPolicy::ACCEPT;
+ auth::Suffix suffix = packet->getName().getSuffix();
+ VerificationPolicy policy = VerificationPolicy::ACCEPT;
+ callVerificationFailedCallback(suffix, policy);
+ policies[suffix] = policy;
}
return policies;
}
Verifier::PolicyMap VoidVerifier::verifyPackets(
- const vector<PacketPtr> &packets, const SuffixMap &suffix_map) {
+ const std::vector<PacketPtr> &packets, const SuffixMap &suffix_map) {
return verifyPackets(packets);
}
// ---------------------------------------------------------
// Asymmetric Verifier
// ---------------------------------------------------------
-AsymmetricVerifier::AsymmetricVerifier(shared_ptr<EVP_PKEY> key) {
+AsymmetricVerifier::AsymmetricVerifier(std::shared_ptr<EVP_PKEY> key) {
setKey(key);
}
-AsymmetricVerifier::AsymmetricVerifier(const string &cert_path) {
+AsymmetricVerifier::AsymmetricVerifier(const std::string &cert_path) {
useCertificate(cert_path);
}
-AsymmetricVerifier::AsymmetricVerifier(shared_ptr<X509> cert) {
+AsymmetricVerifier::AsymmetricVerifier(std::shared_ptr<X509> cert) {
useCertificate(cert);
}
-void AsymmetricVerifier::setKey(shared_ptr<EVP_PKEY> key) { key_ = key; };
+void AsymmetricVerifier::setKey(std::shared_ptr<EVP_PKEY> key) { key_ = key; };
-void AsymmetricVerifier::useCertificate(const string &cert_path) {
+void AsymmetricVerifier::useCertificate(const std::string &cert_path) {
FILE *certf = fopen(cert_path.c_str(), "rb");
if (certf == nullptr) {
throw errors::RuntimeException("Certificate not found");
}
- shared_ptr<X509> cert = shared_ptr<X509>(
+ std::shared_ptr<X509> cert = std::shared_ptr<X509>(
PEM_read_X509(certf, nullptr, nullptr, nullptr), ::X509_free);
useCertificate(cert);
fclose(certf);
}
-void AsymmetricVerifier::useCertificate(shared_ptr<X509> cert) {
- key_ = shared_ptr<EVP_PKEY>(X509_get_pubkey(cert.get()), ::EVP_PKEY_free);
+void AsymmetricVerifier::useCertificate(std::shared_ptr<X509> cert) {
+ key_ =
+ std::shared_ptr<EVP_PKEY>(X509_get_pubkey(cert.get()), ::EVP_PKEY_free);
}
-bool AsymmetricVerifier::verifyBuffer(const vector<uint8_t> &buffer,
- const vector<uint8_t> &signature,
- CryptoHashType hash_type) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(hash_type);
-
- if (hash_evp == nullptr) {
- throw errors::RuntimeException("Unknown hash type");
- }
-
- shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
+bool AsymmetricVerifier::verifyBuffer(const uint8_t *buffer, std::size_t len,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
+ const EVP_MD *hash_md = getMD(suite);
- if (mdctx == nullptr) {
- throw errors::RuntimeException("Digest context allocation failed");
+ std::shared_ptr<EVP_MD_CTX> md_ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free);
+ if (md_ctx == nullptr) {
+ throw errors::RuntimeException("Signature context allocation failed");
}
- if (EVP_DigestVerifyInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
+ if (EVP_DigestVerifyInit(md_ctx.get(), nullptr, hash_md, nullptr,
key_.get()) != 1) {
- throw errors::RuntimeException("Digest initialization failed");
+ throw errors::RuntimeException("Signature initialization failed");
}
- if (EVP_DigestVerifyUpdate(mdctx.get(), buffer.data(), buffer.size()) != 1) {
- throw errors::RuntimeException("Digest update failed");
- }
+ return EVP_DigestVerify(md_ctx.get(), signature->data(), signature->length(),
+ buffer, len) == 1;
+};
- return EVP_DigestVerifyFinal(mdctx.get(), signature.data(),
- signature.size()) == 1;
+bool AsymmetricVerifier::verifyBuffer(const std::vector<uint8_t> &buffer,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
+ return verifyBuffer(buffer.data(), buffer.size(), signature, suite);
}
bool AsymmetricVerifier::verifyBuffer(const utils::MemBuf *buffer,
- const vector<uint8_t> &signature,
- CryptoHashType hash_type) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(hash_type);
-
- if (hash_evp == nullptr) {
- throw errors::RuntimeException("Unknown hash type");
- }
-
- const utils::MemBuf *p = buffer;
- shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
-
- if (mdctx == nullptr) {
- throw errors::RuntimeException("Digest context allocation failed");
- }
-
- if (EVP_DigestVerifyInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
- key_.get()) != 1) {
- throw errors::RuntimeException("Digest initialization failed");
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
+ if (buffer->isChained()) {
+ throw errors::RuntimeException(
+ "Signature of chained membuf is not supported.");
}
- do {
- if (EVP_DigestVerifyUpdate(mdctx.get(), p->data(), p->length()) != 1) {
- throw errors::RuntimeException("Digest update failed");
- }
-
- p = p->next();
- } while (p != buffer);
-
- return EVP_DigestVerifyFinal(mdctx.get(), signature.data(),
- signature.size()) == 1;
+ return verifyBuffer(buffer->data(), buffer->length(), signature, suite);
}
// ---------------------------------------------------------
// Symmetric Verifier
// ---------------------------------------------------------
-SymmetricVerifier::SymmetricVerifier(const string &passphrase) {
+SymmetricVerifier::SymmetricVerifier(const std::string &passphrase) {
setPassphrase(passphrase);
}
// Create and set a symmetric key from a passphrase.
-void SymmetricVerifier::setPassphrase(const string &passphrase) {
- key_ = shared_ptr<EVP_PKEY>(
+void SymmetricVerifier::setPassphrase(const std::string &passphrase) {
+ key_ = std::shared_ptr<EVP_PKEY>(
EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, nullptr,
(const unsigned char *)passphrase.c_str(),
passphrase.size()),
EVP_PKEY_free);
}
-bool SymmetricVerifier::verifyBuffer(const vector<uint8_t> &buffer,
- const vector<uint8_t> &signature,
- CryptoHashType hash_type) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(hash_type);
-
- if (hash_evp == nullptr) {
+bool SymmetricVerifier::verifyBuffer(const uint8_t *buffer, std::size_t len,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
+ const EVP_MD *hash_md = getMD(suite);
+ if (hash_md == nullptr) {
throw errors::RuntimeException("Unknown hash type");
}
- vector<uint8_t> signature_bis(signature.size());
+ const utils::MemBuf::Ptr &signature_bis =
+ core::PacketManager<>::getInstance().getMemBuf();
size_t signature_bis_len;
- shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
- if (mdctx == nullptr) {
- throw errors::RuntimeException("Digest context allocation failed");
+ std::shared_ptr<EVP_MD_CTX> md_ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free);
+ if (md_ctx == nullptr) {
+ throw errors::RuntimeException("Signature context allocation failed");
}
- if (EVP_DigestSignInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
- key_.get()) != 1) {
- throw errors::RuntimeException("Digest initialization failed");
+ if (EVP_DigestSignInit(md_ctx.get(), nullptr, hash_md, nullptr, key_.get()) !=
+ 1) {
+ throw errors::RuntimeException("Signature initialization failed");
}
- if (EVP_DigestSignUpdate(mdctx.get(), buffer.data(), buffer.size()) != 1) {
- throw errors::RuntimeException("Digest update failed");
- }
+ if (EVP_DigestSign(md_ctx.get(), nullptr, &signature_bis_len, buffer, len) !=
+ 1) {
+ throw errors::RuntimeException("Signature length computation failed");
+ };
- if (EVP_DigestSignFinal(mdctx.get(), signature_bis.data(),
- &signature_bis_len) != 1) {
- throw errors::RuntimeException("Digest computation failed");
- }
+ DCHECK(signature_bis_len <= signature_bis->tailroom());
+ signature_bis->append(signature_bis_len);
- return signature == signature_bis && signature.size() == signature_bis_len;
-}
-
-bool SymmetricVerifier::verifyBuffer(const utils::MemBuf *buffer,
- const vector<uint8_t> &signature,
- CryptoHashType hash_type) {
- CryptoHashEVP hash_evp = CryptoHash::getEVP(hash_type);
+ if (EVP_DigestSign(md_ctx.get(), signature_bis->writableData(),
+ &signature_bis_len, buffer, len) != 1) {
+ throw errors::RuntimeException("Signature computation failed");
+ };
- if (hash_evp == nullptr) {
- throw errors::RuntimeException("Unknown hash type");
- }
+ DCHECK(signature_bis_len <= signature_bis->tailroom());
+ signature_bis->setLength(signature_bis_len);
- const utils::MemBuf *p = buffer;
- vector<uint8_t> signature_bis(signature.size());
- size_t signature_bis_len;
- shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
-
- if (mdctx == nullptr) {
- throw errors::RuntimeException("Digest context allocation failed");
- }
-
- if (EVP_DigestSignInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
- key_.get()) != 1) {
- throw errors::RuntimeException("Digest initialization failed");
- }
-
- do {
- if (EVP_DigestSignUpdate(mdctx.get(), p->data(), p->length()) != 1) {
- throw errors::RuntimeException("Digest update failed");
- }
+ return signature->length() == signature_bis_len &&
+ *signature == *signature_bis;
+}
- p = p->next();
- } while (p != buffer);
+bool SymmetricVerifier::verifyBuffer(const std::vector<uint8_t> &buffer,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
+ return verifyBuffer(buffer.data(), buffer.size(), signature, suite);
+}
- if (EVP_DigestSignFinal(mdctx.get(), signature_bis.data(),
- &signature_bis_len) != 1) {
- throw errors::RuntimeException("Digest computation failed");
+bool SymmetricVerifier::verifyBuffer(const utils::MemBuf *buffer,
+ const utils::MemBuf::Ptr &signature,
+ CryptoSuite suite) {
+ if (buffer->isChained()) {
+ throw errors::RuntimeException(
+ "Signature of chained membuf is not supported.");
}
- return signature == signature_bis && signature.size() == signature_bis_len;
+ return verifyBuffer(buffer->data(), buffer->length(), signature, suite);
}
} // namespace auth
diff --git a/libtransport/src/config.h.in b/libtransport/src/config.h.in
index 73a326a84..231a370aa 100644
--- a/libtransport/src/config.h.in
+++ b/libtransport/src/config.h.in
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,13 +19,12 @@
#define HICNTRANSPORT_VERSION_MAJOR "@VERSION_MAJOR@"
#define HICNTRANSPORT_VERSION_MINOR "@VERSION_MINOR@"
-#define HICNTRANSPORT_VERSION_REVISION "@VERSION_REVISION@"
+#define HICNTRANSPORT_VERSION_PATCH "@VERSION_PATCH@"
#ifndef ASIO_STANDALONE
#cmakedefine ASIO_STANDALONE
#endif
#define RAAQM_CONFIG_PATH "@raaqm_config_path@"
-#define ENABLE_RELY @ENABLE_RELY@
#cmakedefine __vpp__
diff --git a/libtransport/src/core/CMakeLists.txt b/libtransport/src/core/CMakeLists.txt
index e442bb863..777772a04 100644
--- a/libtransport/src/core/CMakeLists.txt
+++ b/libtransport/src/core/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -14,14 +14,18 @@
list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/facade.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}/pending_interest.h
${CMAKE_CURRENT_SOURCE_DIR}/portal.h
${CMAKE_CURRENT_SOURCE_DIR}/errors.h
${CMAKE_CURRENT_SOURCE_DIR}/global_configuration.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/global_id_counter.h
${CMAKE_CURRENT_SOURCE_DIR}/local_connector.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/global_workers.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp_connector.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp_listener.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/global_module_manager.h
)
list(APPEND SOURCE_FILES
@@ -35,8 +39,22 @@ list(APPEND SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/portal.cc
${CMAKE_CURRENT_SOURCE_DIR}/global_configuration.cc
${CMAKE_CURRENT_SOURCE_DIR}/io_module.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/local_connector.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp_connector.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/udp_listener.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/constructor.cc
)
+if (NOT ${CMAKE_SYSTEM_NAME} MATCHES Android)
+ if (UNIX AND NOT APPLE)
+ list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/memif_connector.cc
+ )
+
+ list(APPEND HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/memif_connector.h
+ )
+ endif()
+endif()
+
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
-set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE) \ No newline at end of file
+set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
diff --git a/libtransport/src/core/constructor.cc b/libtransport/src/core/constructor.cc
new file mode 100644
index 000000000..0c7f0dfa8
--- /dev/null
+++ b/libtransport/src/core/constructor.cc
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <core/global_configuration.h>
+#include <core/global_module_manager.h>
+#include <core/global_workers.h>
+#include <hicn/transport/core/global_object_pool.h>
+
+namespace transport {
+namespace core {
+
+void __attribute__((constructor)) libtransportInit() {
+ // First the global module manager is initialized
+ GlobalModuleManager::getInstance();
+ // Then the packet allocator is initialized
+ PacketManager<>::getInstance();
+ // Then the global configuration is initialized
+ GlobalConfiguration::getInstance();
+ // Then the global workers are initialized
+ GlobalWorkers::getInstance();
+}
+
+} // namespace core
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/core/content_object.cc b/libtransport/src/core/content_object.cc
index 411494fdf..7ed6c57ab 100644
--- a/libtransport/src/core/content_object.cc
+++ b/libtransport/src/core/content_object.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/errors/errors.h>
+#include <hicn/transport/portability/endianess.h>
#include <hicn/transport/utils/branch_prediction.h>
extern "C" {
@@ -34,30 +35,29 @@ namespace core {
ContentObject::ContentObject(const Name &name, Packet::Format format,
std::size_t additional_header_size)
- : Packet(format, additional_header_size) {
- if (TRANSPORT_EXPECT_FALSE(
- hicn_data_set_name(format, packet_start_, &name.name_) < 0)) {
+ : Packet(HICN_PACKET_TYPE_DATA, format, additional_header_size) {
+ if (TRANSPORT_EXPECT_FALSE(hicn_data_set_name(&pkbuf_, &name.name_) < 0)) {
throw errors::RuntimeException("Error filling the packet name.");
}
- if (TRANSPORT_EXPECT_FALSE(hicn_data_get_name(format_, packet_start_,
- name_.getStructReference()) <
- 0)) {
+ if (TRANSPORT_EXPECT_FALSE(
+ hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0)) {
throw errors::MalformedPacketException();
}
}
-#ifdef __ANDROID__
-ContentObject::ContentObject(hicn_format_t format,
+ContentObject::ContentObject(hicn_packet_format_t format,
std::size_t additional_header_size)
- : ContentObject(Name("0::0|0"), format, additional_header_size) {}
+ : ContentObject(
+#ifdef __ANDROID__
+ Name("0::0|0"),
#else
-ContentObject::ContentObject(hicn_format_t format,
- std::size_t additional_header_size)
- : ContentObject(Packet::base_name, format, additional_header_size) {}
+ Packet::base_name,
#endif
+ format, additional_header_size) {
+}
-ContentObject::ContentObject(const Name &name, hicn_format_t format,
+ContentObject::ContentObject(const Name &name, hicn_packet_format_t format,
std::size_t additional_header_size,
const uint8_t *payload, std::size_t size)
: ContentObject(name, format, additional_header_size) {
@@ -80,9 +80,8 @@ ContentObject::~ContentObject() {}
const Name &ContentObject::getName() const {
if (!name_) {
- if (hicn_data_get_name(format_, packet_start_,
- (hicn_name_t *)name_.getConstStructReference()) <
- 0) {
+ if (hicn_data_get_name(
+ &pkbuf_, (hicn_name_t *)&name_.getConstStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
@@ -93,31 +92,27 @@ const Name &ContentObject::getName() const {
Name &ContentObject::getWritableName() { return const_cast<Name &>(getName()); }
void ContentObject::setName(const Name &name) {
- if (hicn_data_set_name(format_, packet_start_,
- name.getConstStructReference()) < 0) {
+ if (hicn_data_set_name(&pkbuf_, &name.getConstStructReference()) < 0) {
throw errors::RuntimeException("Error setting content object name.");
}
- if (hicn_data_get_name(format_, packet_start_, name_.getStructReference()) <
- 0) {
+ if (hicn_data_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
-uint32_t ContentObject::getPathLabel() const {
- uint32_t path_label;
- if (hicn_data_get_path_label(packet_start_, &path_label) < 0) {
+hicn_path_label_t ContentObject::getPathLabel() const {
+ hicn_path_label_t path_label;
+ if (hicn_data_get_path_label(&pkbuf_, &path_label) < 0) {
throw errors::RuntimeException(
"Error retrieving the path label from content object");
}
- return ntohl(path_label);
+ return path_label;
}
-ContentObject &ContentObject::setPathLabel(uint32_t path_label) {
- path_label = htonl(path_label);
- if (hicn_data_set_path_label((hicn_header_t *)packet_start_, path_label) <
- 0) {
+ContentObject &ContentObject::setPathLabel(hicn_path_label_t path_label) {
+ if (hicn_data_set_path_label(&pkbuf_, path_label) < 0) {
throw errors::RuntimeException(
"Error setting the path label from content object");
}
@@ -125,18 +120,18 @@ ContentObject &ContentObject::setPathLabel(uint32_t path_label) {
return *this;
}
-void ContentObject::setLocator(const ip_address_t &ip_address) {
- if (hicn_data_set_locator(format_, packet_start_, &ip_address) < 0) {
+void ContentObject::setLocator(const hicn_ip_address_t &ip_address) {
+ if (hicn_data_set_locator(&pkbuf_, &ip_address) < 0) {
throw errors::RuntimeException("Error setting content object locator");
}
return;
}
-ip_address_t ContentObject::getLocator() const {
- ip_address_t ip;
+hicn_ip_address_t ContentObject::getLocator() const {
+ hicn_ip_address_t ip;
- if (hicn_data_get_locator(format_, packet_start_, &ip) < 0) {
+ if (hicn_data_get_locator(&pkbuf_, &ip) < 0) {
throw errors::RuntimeException("Error getting content object locator.");
}
@@ -144,7 +139,7 @@ ip_address_t ContentObject::getLocator() const {
}
void ContentObject::setLifetime(uint32_t lifetime) {
- if (hicn_data_set_expiry_time(packet_start_, lifetime) < 0) {
+ if (hicn_data_set_expiry_time(&pkbuf_, lifetime) < 0) {
throw errors::MalformedPacketException();
}
}
@@ -152,7 +147,7 @@ void ContentObject::setLifetime(uint32_t lifetime) {
uint32_t ContentObject::getLifetime() const {
uint32_t lifetime = 0;
- if (hicn_data_get_expiry_time(packet_start_, &lifetime) < 0) {
+ if (hicn_data_get_expiry_time(&pkbuf_, &lifetime) < 0) {
throw errors::MalformedPacketException();
}
@@ -160,13 +155,29 @@ uint32_t ContentObject::getLifetime() const {
}
void ContentObject::resetForHash() {
- if (hicn_data_reset_for_hash(
- format_, reinterpret_cast<hicn_header_t *>(packet_start_)) < 0) {
+ if (hicn_data_reset_for_hash(&pkbuf_) < 0) {
throw errors::RuntimeException(
"Error resetting content object fields for hash computation.");
}
}
+bool ContentObject::isLast() const {
+ int is_last = 0;
+ if (hicn_data_is_last(&pkbuf_, &is_last) < 0) {
+ throw errors::RuntimeException(
+ "Impossible to get last data flag from packet header.");
+ }
+
+ return is_last;
+}
+
+void ContentObject::setLast() {
+ if (hicn_data_set_last(&pkbuf_) < 0) {
+ throw errors::RuntimeException(
+ "Impossible to set last data flag to packet header.");
+ }
+}
+
} // end namespace core
} // end namespace transport
diff --git a/libtransport/src/core/errors.cc b/libtransport/src/core/errors.cc
index 82647a60b..68fd7bf38 100644
--- a/libtransport/src/core/errors.cc
+++ b/libtransport/src/core/errors.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -39,6 +39,15 @@ std::string core_category_impl::message(int ev) const {
case core_error::configuration_not_applied: {
return "Configuration was not applied due to wrong parameters.";
}
+ case core_error::send_failed: {
+ return "Error sending data to socket.";
+ }
+ case core_error::send_buffer_allocation_failed: {
+ return "Error allocating buffers to send data.";
+ }
+ case core_error::receive_failed: {
+ return "Error receiving data from socket.";
+ }
default: {
return "Unknown core error";
}
diff --git a/libtransport/src/core/errors.h b/libtransport/src/core/errors.h
index a46f1dbcd..4532e6dc5 100644
--- a/libtransport/src/core/errors.h
+++ b/libtransport/src/core/errors.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -36,7 +36,10 @@ const std::error_category& core_category();
enum class core_error {
success = 0,
configuration_parse_failed,
- configuration_not_applied
+ configuration_not_applied,
+ send_failed,
+ send_buffer_allocation_failed,
+ receive_failed
};
/**
diff --git a/libtransport/src/core/facade.h b/libtransport/src/core/facade.h
index 199081271..77c1d16d2 100644
--- a/libtransport/src/core/facade.h
+++ b/libtransport/src/core/facade.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,16 +15,16 @@
#pragma once
+#include <core/manifest.h>
#include <core/manifest_format_fixed.h>
-#include <core/manifest_inline.h>
#include <core/portal.h>
namespace transport {
namespace core {
-using ContentObjectManifest = core::ManifestInline<ContentObject, Fixed>;
-using InterestManifest = core::ManifestInline<Interest, Fixed>;
+using ContentObjectManifest = core::Manifest<Fixed>;
+using InterestManifest = core::Manifest<Fixed>;
} // namespace core
diff --git a/libtransport/src/core/global_configuration.cc b/libtransport/src/core/global_configuration.cc
index 9da37c2fa..f53e1f0e2 100644
--- a/libtransport/src/core/global_configuration.cc
+++ b/libtransport/src/core/global_configuration.cc
@@ -68,6 +68,7 @@ void GlobalConfiguration::parseConfiguration(const std::string& path) {
// variable comes first.
std::unique_lock<std::mutex> lck(cp_mtx_);
if (const char* env_c = std::getenv(GlobalConfiguration::conf_file)) {
+ conf_file_path_ = env_c;
parseTransportConfig(env_c);
} else if (!path.empty()) {
conf_file_path_ = path;
diff --git a/libtransport/src/io_modules/forwarder/global_id_counter.h b/libtransport/src/core/global_id_counter.h
index 0a67b76d5..0a67b76d5 100644
--- a/libtransport/src/io_modules/forwarder/global_id_counter.h
+++ b/libtransport/src/core/global_id_counter.h
diff --git a/libtransport/src/core/global_module_manager.h b/libtransport/src/core/global_module_manager.h
new file mode 100644
index 000000000..c9d272cdb
--- /dev/null
+++ b/libtransport/src/core/global_module_manager.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <glog/logging.h>
+#include <hicn/transport/utils/singleton.h>
+
+#ifndef _WIN32
+#include <dlfcn.h>
+#endif
+
+#include <atomic>
+#include <iostream>
+#include <mutex>
+#include <unordered_map>
+
+namespace transport {
+namespace core {
+
+class GlobalModuleManager : public utils::Singleton<GlobalModuleManager> {
+ public:
+ friend class utils::Singleton<GlobalModuleManager>;
+
+ ~GlobalModuleManager() {
+ for (const auto &[key, value] : modules_) {
+ unload(value);
+ }
+ }
+
+ void *loadModule(const std::string &module_name) {
+ void *handle = nullptr;
+ const char *error = nullptr;
+
+ // Lock
+ std::unique_lock lck(mtx_);
+
+ auto it = modules_.find(module_name);
+ if (it != modules_.end()) {
+ return it->second;
+ }
+
+ // open module
+ handle = dlopen(module_name.c_str(), RTLD_NOW);
+ if (!handle) {
+ if ((error = dlerror()) != nullptr) {
+ LOG(ERROR) << error;
+ }
+ return nullptr;
+ }
+
+ auto ret = modules_.try_emplace(module_name, handle);
+ DCHECK(ret.second);
+
+ return handle;
+ }
+
+ void unload(void *handle) {
+ // destroy object and close module
+ dlclose(handle);
+ }
+
+ bool unloadModule(const std::string &module_name) {
+ // Lock
+ std::unique_lock lck(mtx_);
+ auto it = modules_.find(module_name);
+ if (it != modules_.end()) {
+ unload(it->second);
+ return true;
+ }
+
+ return false;
+ }
+
+ private:
+ GlobalModuleManager() = default;
+ std::mutex mtx_;
+ std::unordered_map<std::string, void *> modules_;
+};
+
+} // namespace core
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/core/global_workers.h b/libtransport/src/core/global_workers.h
new file mode 100644
index 000000000..c5d794ef2
--- /dev/null
+++ b/libtransport/src/core/global_workers.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <hicn/transport/utils/singleton.h>
+#include <hicn/transport/utils/thread_pool.h>
+
+#include <atomic>
+#include <mutex>
+
+namespace transport {
+namespace core {
+
+class GlobalWorkers : public utils::Singleton<GlobalWorkers> {
+ public:
+ friend class utils::Singleton<GlobalWorkers>;
+
+ ::utils::EventThread& getWorker() {
+ return thread_pool_.getWorker(counter_++ % thread_pool_.getNThreads());
+ }
+
+ auto& getWorkers() { return thread_pool_.getWorkers(); }
+
+ private:
+ GlobalWorkers() : counter_(0), thread_pool_() {}
+
+ std::atomic_uint16_t counter_;
+ ::utils::ThreadPool thread_pool_;
+};
+
+} // namespace core
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/core/interest.cc b/libtransport/src/core/interest.cc
index 9d868ced0..c3eb7c379 100644
--- a/libtransport/src/core/interest.cc
+++ b/libtransport/src/core/interest.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -21,7 +21,9 @@ extern "C" {
#ifndef _WIN32
TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat")
#endif
+#include <hicn/base.h>
#include <hicn/hicn.h>
+#include <hicn/interest_manifest.h>
}
#include <cstring>
@@ -33,29 +35,30 @@ namespace core {
Interest::Interest(const Name &interest_name, Packet::Format format,
std::size_t additional_header_size)
- : Packet(format, additional_header_size) {
- if (hicn_interest_set_name(format_, packet_start_,
- interest_name.getConstStructReference()) < 0) {
+ : Packet(HICN_PACKET_TYPE_INTEREST, format, additional_header_size) {
+ if (hicn_interest_set_name(&pkbuf_,
+ &interest_name.getConstStructReference()) < 0) {
throw errors::MalformedPacketException();
}
- if (hicn_interest_get_name(format_, packet_start_,
- name_.getStructReference()) < 0) {
+ if (hicn_interest_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
+Interest::Interest(hicn_packet_format_t format,
+ std::size_t additional_header_size)
+ : Interest(
#ifdef __ANDROID__
-Interest::Interest(hicn_format_t format, std::size_t additional_header_size)
- : Interest(Name("0::0|0"), format, additional_header_size) {}
+ Name("0::0|0"),
#else
-Interest::Interest(hicn_format_t format, std::size_t additional_header_size)
- : Interest(base_name, format, additional_header_size) {}
+ base_name,
#endif
+ format, additional_header_size) {
+}
Interest::Interest(MemBuf &&buffer) : Packet(std::move(buffer)) {
- if (hicn_interest_get_name(format_, packet_start_,
- name_.getStructReference()) < 0) {
+ if (hicn_interest_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
@@ -73,15 +76,13 @@ Interest &Interest::operator=(const Interest &other) {
return (Interest &)Packet::operator=(other);
}
-Interest::~Interest() {}
+Interest::~Interest() = default;
const Name &Interest::getName() const {
- if (!name_) {
- if (hicn_interest_get_name(format_, packet_start_,
- (hicn_name_t *)name_.getConstStructReference()) <
- 0) {
- throw errors::MalformedPacketException();
- }
+ if (!name_ &&
+ hicn_interest_get_name(
+ &pkbuf_, (hicn_name_t *)&name_.getConstStructReference()) < 0) {
+ throw errors::MalformedPacketException();
}
return name_;
@@ -90,29 +91,27 @@ const Name &Interest::getName() const {
Name &Interest::getWritableName() { return const_cast<Name &>(getName()); }
void Interest::setName(const Name &name) {
- if (hicn_interest_set_name(format_, packet_start_,
- name.getConstStructReference()) < 0) {
+ if (hicn_interest_set_name(&pkbuf_, &name.getConstStructReference()) < 0) {
throw errors::RuntimeException("Error setting interest name.");
}
- if (hicn_interest_get_name(format_, packet_start_,
- name_.getStructReference()) < 0) {
+ if (hicn_interest_get_name(&pkbuf_, &name_.getStructReference()) < 0) {
throw errors::MalformedPacketException();
}
}
-void Interest::setLocator(const ip_address_t &ip_address) {
- if (hicn_interest_set_locator(format_, packet_start_, &ip_address) < 0) {
+void Interest::setLocator(const hicn_ip_address_t &ip_address) {
+ if (hicn_interest_set_locator(&pkbuf_, &ip_address) < 0) {
throw errors::RuntimeException("Error setting interest locator.");
}
return;
}
-ip_address_t Interest::getLocator() const {
- ip_address_t ip;
+hicn_ip_address_t Interest::getLocator() const {
+ hicn_ip_address_t ip;
- if (hicn_interest_get_locator(format_, packet_start_, &ip) < 0) {
+ if (hicn_interest_get_locator(&pkbuf_, &ip) < 0) {
throw errors::RuntimeException("Error getting interest locator.");
}
@@ -120,7 +119,7 @@ ip_address_t Interest::getLocator() const {
}
void Interest::setLifetime(uint32_t lifetime) {
- if (hicn_interest_set_lifetime(packet_start_, lifetime) < 0) {
+ if (hicn_interest_set_lifetime(&pkbuf_, lifetime) < 0) {
throw errors::MalformedPacketException();
}
}
@@ -128,7 +127,7 @@ void Interest::setLifetime(uint32_t lifetime) {
uint32_t Interest::getLifetime() const {
uint32_t lifetime = 0;
- if (hicn_interest_get_lifetime(packet_start_, &lifetime) < 0) {
+ if (hicn_interest_get_lifetime(&pkbuf_, &lifetime) < 0) {
throw errors::MalformedPacketException();
}
@@ -136,14 +135,20 @@ uint32_t Interest::getLifetime() const {
}
void Interest::resetForHash() {
- if (hicn_interest_reset_for_hash(
- format_, reinterpret_cast<hicn_header_t *>(packet_start_)) < 0) {
+ if (hicn_interest_reset_for_hash(&pkbuf_) < 0) {
throw errors::RuntimeException(
"Error resetting interest fields for hash computation.");
}
+
+ // Reset request bitmap in manifest
+ if (hasManifest()) {
+ auto int_manifest_header =
+ (interest_manifest_header_t *)(writableData() + headerSize());
+ memset(int_manifest_header->request_bitmap, 0, BITMAP_SIZE * sizeof(u32));
+ }
}
-bool Interest::hasManifest() {
+bool Interest::hasManifest() const {
return (getPayloadType() == PayloadType::MANIFEST);
}
@@ -162,19 +167,43 @@ void Interest::encodeSuffixes() {
// We assume interest does not hold signature for the moment.
auto int_manifest_header =
- (InterestManifestHeader *)(writableData() + headerSize());
- int_manifest_header->n_suffixes = suffix_set_.size();
+ (interest_manifest_header_t *)(writableData() + headerSize());
+
+ interest_manifest_init(int_manifest_header, name_.getSuffix());
+ for (auto it = suffix_set_.begin(); it != suffix_set_.end(); it++) {
+ interest_manifest_add_suffix(int_manifest_header, *it);
+ }
+
std::size_t additional_length =
- sizeof(InterestManifestHeader) +
+ sizeof(interest_manifest_header_t) +
int_manifest_header->n_suffixes * sizeof(uint32_t);
- uint32_t *suffix = (uint32_t *)(int_manifest_header + 1);
- for (auto it = suffix_set_.begin(); it != suffix_set_.end(); it++, suffix++) {
- *suffix = *it;
+ append(additional_length);
+ updateLength();
+}
+
+void Interest::serializeSuffixes() {
+ if (!hasManifest()) {
+ return;
}
- append(additional_length);
- updateLength(additional_length);
+ // We assume interest does not hold signature for the moment.
+ auto int_manifest_header =
+ (interest_manifest_header_t *)(writableData() + headerSize());
+ // Serialize interest manifest
+ interest_manifest_serialize(int_manifest_header);
+}
+
+void Interest::deserializeSuffixes() {
+ if (!hasManifest()) {
+ return;
+ }
+
+ // We assume interest does not hold signature for the moment.
+ auto int_manifest_header =
+ (interest_manifest_header_t *)(writableData() + headerSize());
+ // Serialize interest manifest
+ interest_manifest_deserialize(int_manifest_header);
}
uint32_t *Interest::firstSuffix() {
@@ -182,7 +211,7 @@ uint32_t *Interest::firstSuffix() {
return nullptr;
}
- auto ret = (InterestManifestHeader *)(writableData() + headerSize());
+ auto ret = (interest_manifest_header_t *)(writableData() + headerSize());
ret += 1;
return (uint32_t *)ret;
@@ -193,11 +222,39 @@ uint32_t Interest::numberOfSuffixes() {
return 0;
}
- auto header = (InterestManifestHeader *)(writableData() + headerSize());
+ auto header = (interest_manifest_header_t *)(writableData() + headerSize());
return header->n_suffixes;
}
+hicn_uword *Interest::getRequestBitmap() {
+ if (!hasManifest()) return nullptr;
+
+ auto header = (interest_manifest_header_t *)(writableData() + headerSize());
+ return header->request_bitmap;
+}
+
+interest_manifest_header_t *Interest::getIntManifestHeader() {
+ if (!hasManifest()) return nullptr;
+
+ auto header = (interest_manifest_header_t *)(writableData() + headerSize());
+ return header;
+};
+
+void Interest::setRequestBitmap(const uint32_t *request_bitmap) {
+ if (!hasManifest()) return;
+
+ auto header = (interest_manifest_header_t *)(writableData() + headerSize());
+ memcpy(header->request_bitmap, request_bitmap,
+ BITMAP_SIZE * sizeof(uint32_t));
+}
+
+bool Interest::isValid() {
+ if (!hasManifest()) return true;
+ auto header = (interest_manifest_header_t *)(writableData() + headerSize());
+ return interest_manifest_is_valid(header, payloadSize());
+}
+
} // end namespace core
} // end namespace transport
diff --git a/libtransport/src/core/io_module.cc b/libtransport/src/core/io_module.cc
index a751eabf5..0fdb735c4 100644
--- a/libtransport/src/core/io_module.cc
+++ b/libtransport/src/core/io_module.cc
@@ -16,11 +16,14 @@
#ifndef _WIN32
#include <dlfcn.h>
#endif
+#include <core/global_module_manager.h>
#include <glog/logging.h>
#include <hicn/transport/core/io_module.h>
+#include <iostream>
+
#ifdef ANDROID
-#include <io_modules/udp/hicn_forwarder_module.h>
+#include <io_modules/hicn-light/hicn_forwarder_module.h>
#elif _WIN32
#include <hicn/util/windows/windows_utils.h>
#endif
@@ -36,53 +39,28 @@ IoModule *IoModule::load(const char *module_name) {
#ifdef ANDROID
return new HicnForwarderModule();
#else
- void *handle = 0;
- IoModule *module = 0;
- IoModule *(*creator)(void) = 0;
- const char *error = 0;
+ IoModule *iomodule = nullptr;
+ IoModule *(*creator)(void) = nullptr;
+ const char *error = nullptr;
- // open module
- handle = dlopen(module_name, RTLD_NOW);
- if (!handle) {
- if ((error = dlerror()) != 0) {
- LOG(ERROR) << error;
- }
- return 0;
- }
+ auto handle = GlobalModuleManager::getInstance().loadModule(module_name);
// get factory method
creator = (IoModule * (*)(void)) dlsym(handle, "create_module");
if (!creator) {
- if ((error = dlerror()) != 0) {
- LOG(ERROR) << error;
- return 0;
+ if ((error = dlerror()) != nullptr) {
+ LOG(ERROR) << error << ": " << module_name;
}
+
+ return nullptr;
}
// create object and return it
- module = (*creator)();
- module->handle_ = handle;
-
- return module;
-#endif
-}
-
-bool IoModule::unload(IoModule *module) {
- if (!module) {
- return false;
- }
+ iomodule = (*creator)();
-#ifdef ANDROID
- delete module;
-#else
- // destroy object and close module
- void *handle = module->handle_;
- delete module;
- dlclose(handle);
+ return iomodule;
#endif
-
- return true;
}
} // namespace core
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/libtransport/src/core/local_connector.cc b/libtransport/src/core/local_connector.cc
deleted file mode 100644
index 50dadc677..000000000
--- a/libtransport/src/core/local_connector.cc
+++ /dev/null
@@ -1,46 +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 <core/local_connector.h>
-#include <glog/logging.h>
-#include <hicn/transport/core/asio_wrapper.h>
-#include <hicn/transport/core/content_object.h>
-#include <hicn/transport/core/interest.h>
-#include <hicn/transport/errors/not_implemented_exception.h>
-
-namespace transport {
-namespace core {
-
-LocalConnector::~LocalConnector() {}
-
-void LocalConnector::close() { state_ = State::CLOSED; }
-
-void LocalConnector::send(Packet &packet) {
- if (!isConnected()) {
- return;
- }
-
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Sending packet to local socket.";
- io_service_.get().post([this, p{packet.shared_from_this()}]() mutable {
- receive_callback_(this, *p, std::make_error_code(std::errc(0)));
- });
-}
-
-void LocalConnector::send(const uint8_t *packet, std::size_t len) {
- throw errors::NotImplementedException();
-}
-
-} // namespace core
-} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/core/local_connector.h b/libtransport/src/core/local_connector.h
index 0e2d8f676..bf64b71d6 100644
--- a/libtransport/src/core/local_connector.h
+++ b/libtransport/src/core/local_connector.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,10 +15,11 @@
#pragma once
+#include <core/errors.h>
#include <hicn/transport/core/asio_wrapper.h>
#include <hicn/transport/core/connector.h>
#include <hicn/transport/core/global_object_pool.h>
-#include <hicn/transport/utils/move_wrapper.h>
+#include <hicn/transport/errors/not_implemented_exception.h>
#include <hicn/transport/utils/shared_ptr_utils.h>
#include <io_modules/forwarder/errors.h>
@@ -34,19 +35,48 @@ class LocalConnector : public Connector {
OnClose &&close_callback, OnReconnect &&on_reconnect)
: Connector(receive_callback, packet_sent, close_callback, on_reconnect),
io_service_(io_service),
- io_service_work_(io_service_.get()) {
- state_ = State::CONNECTED;
- }
+ io_service_work_(io_service_.get()) {}
- ~LocalConnector() override;
+ ~LocalConnector() override = default;
- void send(Packet &packet) override;
+ auto shared_from_this() { return utils::shared_from(this); }
- void send(const uint8_t *packet, std::size_t len) override;
+ void send(Packet &packet) override { send(packet.shared_from_this()); }
- void close() override;
+ void send(const utils::MemBuf::Ptr &buffer) override {
+ throw errors::NotImplementedException();
+ }
- auto shared_from_this() { return utils::shared_from(this); }
+ void receive(const std::vector<utils::MemBuf::Ptr> &buffers) override {
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Sending packet to local socket.";
+ std::weak_ptr<LocalConnector> self = shared_from_this();
+ io_service_.get().post([self, _buffers{std::move(buffers)}]() mutable {
+ if (auto ptr = self.lock()) {
+ ptr->receive_callback_(ptr.get(), _buffers,
+ make_error_code(core_error::success));
+ }
+ });
+ }
+
+ void reconnect() override {
+ state_ = State::CONNECTED;
+ std::weak_ptr<LocalConnector> self = shared_from_this();
+ io_service_.get().post([self]() {
+ if (auto ptr = self.lock()) {
+ ptr->on_reconnect_callback_(ptr.get(),
+ make_error_code(core_error::success));
+ }
+ });
+ }
+
+ void close() override {
+ std::weak_ptr<LocalConnector> self = shared_from_this();
+ io_service_.get().post([self]() mutable {
+ if (auto ptr = self.lock()) {
+ ptr->on_close_callback_(ptr.get());
+ }
+ });
+ }
private:
std::reference_wrapper<asio::io_service> io_service_;
diff --git a/libtransport/src/core/manifest.cc b/libtransport/src/core/manifest.cc
deleted file mode 100644
index 3f890f3d0..000000000
--- a/libtransport/src/core/manifest.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/transport/core/manifest.h>
-
-namespace transport {
-
-namespace core {
-
-std::string ManifestEncoding::manifest_type = std::string("manifest_type");
-
-std::map<ManifestType, std::string> ManifestEncoding::manifest_types = {
- {FINAL_CHUNK_NUMBER, "FinalChunkNumber"}, {NAME_LIST, "NameList"}};
-
-std::string ManifestEncoding::final_chunk_number =
- std::string("final_chunk_number");
-std::string ManifestEncoding::content_name = std::string("content_name");
-
-} // end namespace core
-
-} // end namespace transport \ No newline at end of file
diff --git a/libtransport/src/core/manifest.h b/libtransport/src/core/manifest.h
index 9b25ebd67..40832bb6b 100644
--- a/libtransport/src/core/manifest.h
+++ b/libtransport/src/core/manifest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,138 +16,73 @@
#pragma once
#include <core/manifest_format.h>
-#include <hicn/transport/core/content_object.h>
-#include <hicn/transport/core/name.h>
-
-#include <set>
+#include <glog/logging.h>
+#include <hicn/transport/auth/verifier.h>
+#include <hicn/transport/core/global_object_pool.h>
+#include <hicn/transport/core/packet.h>
namespace transport {
-
namespace core {
-using typename core::Name;
-using typename core::Packet;
-using typename core::PayloadType;
-
-template <typename Base, typename FormatTraits, typename ManifestImpl>
-class Manifest : public Base {
- static_assert(std::is_base_of<Packet, Base>::value,
- "Base must inherit from packet!");
-
+template <typename FormatTraits>
+class Manifest : public FormatTraits::Encoder, public FormatTraits::Decoder {
public:
- // core::ContentObjectManifest::Ptr
+ using Ptr = std::shared_ptr<Manifest>;
using Encoder = typename FormatTraits::Encoder;
using Decoder = typename FormatTraits::Decoder;
- Manifest(std::size_t signature_size = 0)
- : Base(HF_INET6_TCP_AH, signature_size),
- encoder_(*this, signature_size),
- decoder_(*this) {
- Base::setPayloadType(PayloadType::MANIFEST);
- }
-
- Manifest(const core::Name &name, std::size_t signature_size = 0)
- : Base(name, HF_INET6_TCP_AH, signature_size),
- encoder_(*this, signature_size),
- decoder_(*this) {
- Base::setPayloadType(PayloadType::MANIFEST);
- }
+ using Hash = typename FormatTraits::Hash;
+ using HashType = typename FormatTraits::HashType;
+ using Suffix = typename FormatTraits::Suffix;
+ using SuffixList = typename FormatTraits::SuffixList;
+ using HashEntry = std::pair<auth::CryptoHashType, std::vector<uint8_t>>;
- template <typename T>
- Manifest(T &&base)
- : Base(std::forward<T &&>(base)),
- encoder_(*this, 0, false),
- decoder_(*this) {
- Base::setPayloadType(PayloadType::MANIFEST);
+ Manifest(Packet::Ptr packet, bool clear = false)
+ : Encoder(packet, clear), Decoder(packet), packet_(packet) {
+ packet->setPayloadType(PayloadType::MANIFEST);
}
virtual ~Manifest() = default;
- std::size_t estimateManifestSize(std::size_t additional_entries = 0) {
- return static_cast<ManifestImpl &>(*this).estimateManifestSizeImpl(
- additional_entries);
- }
+ Packet::Ptr getPacket() const { return packet_; }
- /*
- * After the call to encode, users MUST call clear before adding data
- * to the manifest.
- */
- Manifest &encode() { return static_cast<ManifestImpl &>(*this).encodeImpl(); }
-
- Manifest &decode() {
- Manifest::decoder_.decode();
-
- manifest_type_ = decoder_.getManifestType();
- hash_algorithm_ = decoder_.getHashAlgorithm();
- is_last_ = decoder_.getIsFinalManifest();
-
- return static_cast<ManifestImpl &>(*this).decodeImpl();
+ void setHeaders(ManifestType type, uint8_t max_capacity, HashType hash_algo,
+ bool is_last, const Name &base_name) {
+ Encoder::setType(type);
+ Encoder::setMaxCapacity(max_capacity);
+ Encoder::setHashAlgorithm(hash_algo);
+ Encoder::setIsLast(is_last);
+ Encoder::setBaseName(base_name);
}
- static std::size_t getManifestHeaderSize() {
- return Encoder::getManifestHeaderSize();
- }
+ auth::Verifier::SuffixMap getSuffixMap() const {
+ auth::Verifier::SuffixMap suffix_map;
- static std::size_t getManifestEntrySize() {
- return Encoder::getManifestEntrySize();
- }
+ HashType hash_algo = Decoder::getHashAlgorithm();
+ SuffixList suffix_list = Decoder::getEntries();
- Manifest &setManifestType(ManifestType type) {
- manifest_type_ = type;
- encoder_.setManifestType(manifest_type_);
- return *this;
- }
+ for (auto it = suffix_list.begin(); it != suffix_list.end(); ++it) {
+ Hash hash(it->second, Hash::getSize(hash_algo), hash_algo);
+ suffix_map[it->first] = hash;
+ }
- Manifest &setHashAlgorithm(auth::CryptoHashType hash_algorithm) {
- hash_algorithm_ = hash_algorithm;
- encoder_.setHashAlgorithm(hash_algorithm_);
- return *this;
+ return suffix_map;
}
- auth::CryptoHashType getHashAlgorithm() { return hash_algorithm_; }
-
- ManifestType getManifestType() const { return manifest_type_; }
-
- bool isFinalManifest() const { return is_last_; }
-
- Manifest &setVersion(ManifestVersion version) {
- encoder_.setVersion(version);
- return *this;
- }
-
- Manifest &setFinalBlockNumber(std::uint32_t final_block_number) {
- encoder_.setFinalBlockNumber(final_block_number);
- return *this;
- }
-
- uint32_t getFinalBlockNumber() const {
- return decoder_.getFinalBlockNumber();
- }
-
- ManifestVersion getVersion() const { return decoder_.getVersion(); }
-
- Manifest &setFinalManifest(bool is_final_manifest) {
- encoder_.setIsFinalManifest(is_final_manifest);
- is_last_ = is_final_manifest;
- return *this;
- }
-
- Manifest &clear() {
- encoder_.clear();
- decoder_.clear();
- return *this;
- }
+ static Manifest::Ptr createContentManifest(Packet::Format format,
+ const core::Name &manifest_name,
+ std::size_t signature_size) {
+ ContentObject::Ptr content_object =
+ core::PacketManager<>::getInstance().getPacket<ContentObject>(
+ format, signature_size);
+ content_object->setName(manifest_name);
+ return std::make_shared<Manifest>(content_object, true);
+ };
protected:
- ManifestType manifest_type_;
- auth::CryptoHashType hash_algorithm_;
- bool is_last_;
-
- Encoder encoder_;
- Decoder decoder_;
+ Packet::Ptr packet_;
};
} // end namespace core
-
} // end namespace transport
diff --git a/libtransport/src/core/manifest_format.h b/libtransport/src/core/manifest_format.h
index 90d221f5e..89412316a 100644
--- a/libtransport/src/core/manifest_format.h
+++ b/libtransport/src/core/manifest_format.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,46 +17,40 @@
#include <hicn/transport/auth/crypto_hash.h>
#include <hicn/transport/core/name.h>
+#include <hicn/transport/interfaces/socket_options_keys.h>
+#include <protocols/fec_utils.h>
#include <cinttypes>
#include <type_traits>
#include <unordered_map>
namespace transport {
-
namespace core {
-enum class ManifestFields : uint8_t {
- VERSION,
- HASH_ALGORITHM,
- SEGMENT_CALCULATION_STRATEGY,
- FINAL_MANIFEST,
- NAME_HASH_LIST,
- BASE_NAME
-};
-
-enum class ManifestVersion : uint8_t {
- VERSION_1 = 1,
-};
-
enum class ManifestType : uint8_t {
INLINE_MANIFEST = 1,
FINAL_CHUNK_NUMBER = 2,
FLIC_MANIFEST = 3,
};
-/**
- * INCREMENTAL: Manifests will be received inline with the data with no specific
- * assumption regarding the manifest capacity. Consumers can send interests
- * using a +1 heuristic.
- *
- * MANIFEST_CAPACITY_BASED: manifests with capacity N have a suffix multiple of
- * N+1: 0, N+1, 2(N+1) etc. Contents have a suffix incremented by 1 except when
- * it conflicts with a manifest: 1, 2, ..., N, N+2, N+3, ..., 2N+1, 2N+3
- */
-enum class NextSegmentCalculationStrategy : uint8_t {
- INCREMENTAL = 1,
- MANIFEST_CAPACITY_BASED = 2,
+struct ParamsRTC {
+ std::uint64_t timestamp;
+ std::uint32_t prod_rate;
+ std::uint32_t prod_seg;
+ protocol::fec::FECType fec_type;
+
+ bool operator==(const ParamsRTC &other) const {
+ return (timestamp == other.timestamp && prod_rate == other.prod_rate &&
+ prod_seg == other.prod_seg && fec_type == other.fec_type);
+ }
+};
+
+struct ParamsBytestream {
+ std::uint32_t final_segment;
+
+ bool operator==(const ParamsBytestream &other) const {
+ return (final_segment == other.final_segment);
+ }
};
template <typename T>
@@ -84,22 +78,25 @@ class ManifestEncoder {
return static_cast<Implementation &>(*this).clearImpl();
}
- ManifestEncoder &setManifestType(ManifestType type) {
- return static_cast<Implementation &>(*this).setManifestTypeImpl(type);
+ bool isEncoded() const {
+ return static_cast<const Implementation &>(*this).isEncodedImpl();
}
- ManifestEncoder &setHashAlgorithm(auth::CryptoHashType hash) {
- return static_cast<Implementation &>(*this).setHashAlgorithmImpl(hash);
+ ManifestEncoder &setType(ManifestType type) {
+ return static_cast<Implementation &>(*this).setTypeImpl(type);
}
- ManifestEncoder &setFinalChunkNumber(uint32_t final_chunk) {
- return static_cast<Implementation &>(*this).setFinalChunkImpl(final_chunk);
+ ManifestEncoder &setMaxCapacity(uint8_t max_capacity) {
+ return static_cast<Implementation &>(*this).setMaxCapacityImpl(
+ max_capacity);
}
- ManifestEncoder &setNextSegmentCalculationStrategy(
- NextSegmentCalculationStrategy strategy) {
- return static_cast<Implementation &>(*this)
- .setNextSegmentCalculationStrategyImpl(strategy);
+ ManifestEncoder &setHashAlgorithm(auth::CryptoHashType hash) {
+ return static_cast<Implementation &>(*this).setHashAlgorithmImpl(hash);
+ }
+
+ ManifestEncoder &setIsLast(bool is_last) {
+ return static_cast<Implementation &>(*this).setIsLastImpl(is_last);
}
template <
@@ -110,40 +107,36 @@ class ManifestEncoder {
return static_cast<Implementation &>(*this).setBaseNameImpl(name);
}
- template <typename Hash>
- ManifestEncoder &addSuffixAndHash(uint32_t suffix, Hash &&hash) {
- return static_cast<Implementation &>(*this).addSuffixAndHashImpl(
- suffix, std::forward<Hash &&>(hash));
+ ManifestEncoder &setParamsBytestream(const ParamsBytestream &params) {
+ return static_cast<Implementation &>(*this).setParamsBytestreamImpl(params);
}
- ManifestEncoder &setIsFinalManifest(bool is_last) {
- return static_cast<Implementation &>(*this).setIsFinalManifestImpl(is_last);
+ ManifestEncoder &setParamsRTC(const ParamsRTC &params) {
+ return static_cast<Implementation &>(*this).setParamsRTCImpl(params);
}
- ManifestEncoder &setVersion(ManifestVersion version) {
- return static_cast<Implementation &>(*this).setVersionImpl(version);
- }
-
- std::size_t estimateSerializedLength(std::size_t number_of_entries) {
- return static_cast<Implementation &>(*this).estimateSerializedLengthImpl(
- number_of_entries);
+ template <typename Hash>
+ ManifestEncoder &addEntry(uint32_t suffix, Hash &&hash) {
+ return static_cast<Implementation &>(*this).addEntryImpl(
+ suffix, std::forward<Hash>(hash));
}
- ManifestEncoder &update() {
- return static_cast<Implementation &>(*this).updateImpl();
+ ManifestEncoder &removeEntry(uint32_t suffix) {
+ return static_cast<Implementation &>(*this).removeEntryImpl(suffix);
}
- ManifestEncoder &setFinalBlockNumber(std::uint32_t final_block_number) {
- return static_cast<Implementation &>(*this).setFinalBlockNumberImpl(
- final_block_number);
+ std::size_t manifestHeaderSize() const {
+ return static_cast<const Implementation &>(*this).manifestHeaderSizeImpl();
}
- static std::size_t getManifestHeaderSize() {
- return Implementation::getManifestHeaderSizeImpl();
+ std::size_t manifestPayloadSize(size_t additional_entries = 0) const {
+ return static_cast<const Implementation &>(*this).manifestPayloadSizeImpl(
+ additional_entries);
}
- static std::size_t getManifestEntrySize() {
- return Implementation::getManifestEntrySizeImpl();
+ std::size_t manifestSize(size_t additional_entries = 0) const {
+ return static_cast<const Implementation &>(*this).manifestSizeImpl(
+ additional_entries);
}
};
@@ -152,55 +145,68 @@ class ManifestDecoder {
public:
virtual ~ManifestDecoder() = default;
+ ManifestDecoder &decode() {
+ return static_cast<Implementation &>(*this).decodeImpl();
+ }
+
ManifestDecoder &clear() {
return static_cast<Implementation &>(*this).clearImpl();
}
- void decode() { static_cast<Implementation &>(*this).decodeImpl(); }
+ bool isDecoded() const {
+ return static_cast<const Implementation &>(*this).isDecodedImpl();
+ }
- ManifestType getManifestType() const {
- return static_cast<const Implementation &>(*this).getManifestTypeImpl();
+ ManifestType getType() const {
+ return static_cast<const Implementation &>(*this).getTypeImpl();
}
- auth::CryptoHashType getHashAlgorithm() const {
- return static_cast<const Implementation &>(*this).getHashAlgorithmImpl();
+ interface::ProductionProtocolAlgorithms getTransportType() const {
+ return static_cast<const Implementation &>(*this).getTransportTypeImpl();
+ }
+
+ uint8_t getMaxCapacity() const {
+ return static_cast<const Implementation &>(*this).getMaxCapacityImpl();
}
- uint32_t getFinalChunkNumber() const {
- return static_cast<const Implementation &>(*this).getFinalChunkImpl();
+ auth::CryptoHashType getHashAlgorithm() const {
+ return static_cast<const Implementation &>(*this).getHashAlgorithmImpl();
}
- NextSegmentCalculationStrategy getNextSegmentCalculationStrategy() const {
- return static_cast<const Implementation &>(*this)
- .getNextSegmentCalculationStrategyImpl();
+ bool getIsLast() const {
+ return static_cast<const Implementation &>(*this).getIsLastImpl();
}
core::Name getBaseName() const {
return static_cast<const Implementation &>(*this).getBaseNameImpl();
}
- auto getSuffixHashList() {
- return static_cast<Implementation &>(*this).getSuffixHashListImpl();
+ ParamsBytestream getParamsBytestream() const {
+ return static_cast<const Implementation &>(*this).getParamsBytestreamImpl();
+ }
+
+ ParamsRTC getParamsRTC() const {
+ return static_cast<const Implementation &>(*this).getParamsRTCImpl();
}
- bool getIsFinalManifest() const {
- return static_cast<const Implementation &>(*this).getIsFinalManifestImpl();
+ auto getEntries() const {
+ return static_cast<const Implementation &>(*this).getEntriesImpl();
}
- ManifestVersion getVersion() const {
- return static_cast<const Implementation &>(*this).getVersionImpl();
+ std::size_t manifestHeaderSize() const {
+ return static_cast<const Implementation &>(*this).manifestHeaderSizeImpl();
}
- std::size_t estimateSerializedLength(std::size_t number_of_entries) const {
- return static_cast<const Implementation &>(*this)
- .estimateSerializedLengthImpl(number_of_entries);
+ std::size_t manifestPayloadSize(size_t additional_entries = 0) const {
+ return static_cast<const Implementation &>(*this).manifestPayloadSizeImpl(
+ additional_entries);
}
- uint32_t getFinalBlockNumber() const {
- return static_cast<const Implementation &>(*this).getFinalBlockNumberImpl();
+ std::size_t manifestSize(size_t additional_entries = 0) const {
+ return static_cast<const Implementation &>(*this).manifestSizeImpl(
+ additional_entries);
}
};
} // namespace core
-
} // namespace transport
diff --git a/libtransport/src/core/manifest_format_fixed.cc b/libtransport/src/core/manifest_format_fixed.cc
index 11d4a56cb..bda666c0c 100644
--- a/libtransport/src/core/manifest_format_fixed.cc
+++ b/libtransport/src/core/manifest_format_fixed.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,211 +18,331 @@
#include <hicn/transport/utils/literals.h>
namespace transport {
-
namespace core {
-// TODO use preallocated pool of membufs
-FixedManifestEncoder::FixedManifestEncoder(Packet &packet,
- std::size_t signature_size,
- bool clear)
+// ---------------------------------------------------------
+// FixedManifest
+// ---------------------------------------------------------
+size_t FixedManifest::manifestHeaderSize(
+ interface::ProductionProtocolAlgorithms transport_type) {
+ uint32_t params_size = 0;
+
+ switch (transport_type) {
+ case interface::ProductionProtocolAlgorithms::BYTE_STREAM:
+ params_size = MANIFEST_PARAMS_BYTESTREAM_SIZE;
+ break;
+ case interface::ProductionProtocolAlgorithms::RTC_PROD:
+ params_size = MANIFEST_PARAMS_RTC_SIZE;
+ break;
+ default:
+ break;
+ }
+
+ return MANIFEST_META_SIZE + MANIFEST_ENTRY_META_SIZE + params_size;
+}
+
+size_t FixedManifest::manifestPayloadSize(size_t nb_entries) {
+ return nb_entries * MANIFEST_ENTRY_SIZE;
+}
+
+// ---------------------------------------------------------
+// FixedManifestEncoder
+// ---------------------------------------------------------
+FixedManifestEncoder::FixedManifestEncoder(Packet::Ptr packet, bool clear)
: packet_(packet),
- max_size_(Packet::default_mtu - packet_.headerSize()),
- manifest_header_(reinterpret_cast<ManifestHeader *>(
- packet_.writableData() + packet_.headerSize())),
- manifest_entries_(
- reinterpret_cast<ManifestEntry *>(manifest_header_ + 1)),
- current_entry_(0),
- signature_size_(signature_size) {
+ transport_type_(interface::ProductionProtocolAlgorithms::UNKNOWN),
+ encoded_(false) {
+ manifest_meta_ = reinterpret_cast<ManifestMeta *>(packet_->writableData() +
+ packet_->headerSize());
+ manifest_entry_meta_ =
+ reinterpret_cast<ManifestEntryMeta *>(manifest_meta_ + 1);
+
if (clear) {
- *manifest_header_ = {0};
+ *manifest_meta_ = {0};
+ *manifest_entry_meta_ = {0};
}
}
FixedManifestEncoder::~FixedManifestEncoder() {}
FixedManifestEncoder &FixedManifestEncoder::encodeImpl() {
- packet_.append(sizeof(ManifestHeader) +
- manifest_header_->number_of_entries * sizeof(ManifestEntry));
- packet_.updateLength();
+ if (encoded_) {
+ return *this;
+ }
+
+ // Copy manifest header
+ manifest_meta_->transport_type = static_cast<uint8_t>(transport_type_);
+ manifest_entry_meta_->nb_entries = manifest_entries_.size();
+
+ packet_->append(manifestHeaderSizeImpl());
+
+ packet_->updateLength();
+ auto params = reinterpret_cast<uint8_t *>(manifest_entry_meta_ + 1);
+
+ switch (transport_type_) {
+ case interface::ProductionProtocolAlgorithms::BYTE_STREAM: {
+ auto bytestream = reinterpret_cast<const uint8_t *>(&params_bytestream_);
+ std::memcpy(params, bytestream, MANIFEST_PARAMS_BYTESTREAM_SIZE);
+ break;
+ }
+ case interface::ProductionProtocolAlgorithms::RTC_PROD: {
+ auto rtc = reinterpret_cast<const uint8_t *>(&params_rtc_);
+ std::memcpy(params, rtc, MANIFEST_PARAMS_RTC_SIZE);
+ break;
+ }
+ default:
+ break;
+ }
+
+ // Copy manifest entries
+ auto payload = reinterpret_cast<const uint8_t *>(manifest_entries_.data());
+ packet_->appendPayload(payload, manifestPayloadSizeImpl());
+
+ packet_->updateLength();
+ if (TRANSPORT_EXPECT_FALSE(packet_->payloadSize() < manifestSizeImpl())) {
+ throw errors::RuntimeException("Error encoding the manifest");
+ }
+
+ encoded_ = true;
return *this;
}
FixedManifestEncoder &FixedManifestEncoder::clearImpl() {
- packet_.trimEnd(sizeof(ManifestHeader) +
- manifest_header_->number_of_entries * sizeof(ManifestEntry));
- current_entry_ = 0;
- *manifest_header_ = {0};
+ if (encoded_) {
+ packet_->trimEnd(manifestSizeImpl());
+ }
+
+ transport_type_ = interface::ProductionProtocolAlgorithms::UNKNOWN;
+ encoded_ = false;
+ *manifest_meta_ = {0};
+ *manifest_entry_meta_ = {0};
+ params_bytestream_ = {0};
+ params_rtc_ = {0};
+ manifest_entries_.clear();
+
return *this;
}
-FixedManifestEncoder &FixedManifestEncoder::setHashAlgorithmImpl(
- auth::CryptoHashType algorithm) {
- manifest_header_->hash_algorithm = static_cast<uint8_t>(algorithm);
+bool FixedManifestEncoder::isEncodedImpl() const { return encoded_; }
+
+FixedManifestEncoder &FixedManifestEncoder::setTypeImpl(
+ ManifestType manifest_type) {
+ manifest_meta_->type = static_cast<uint8_t>(manifest_type);
return *this;
}
-FixedManifestEncoder &FixedManifestEncoder::setManifestTypeImpl(
- ManifestType manifest_type) {
- manifest_header_->manifest_type = static_cast<uint8_t>(manifest_type);
+FixedManifestEncoder &FixedManifestEncoder::setMaxCapacityImpl(
+ uint8_t max_capacity) {
+ manifest_meta_->max_capacity = max_capacity;
+ return *this;
+}
+
+FixedManifestEncoder &FixedManifestEncoder::setHashAlgorithmImpl(
+ auth::CryptoHashType algorithm) {
+ manifest_meta_->hash_algorithm = static_cast<uint8_t>(algorithm);
return *this;
}
-FixedManifestEncoder &
-FixedManifestEncoder::setNextSegmentCalculationStrategyImpl(
- NextSegmentCalculationStrategy strategy) {
- manifest_header_->next_segment_strategy = static_cast<uint8_t>(strategy);
+FixedManifestEncoder &FixedManifestEncoder::setIsLastImpl(bool is_last) {
+ manifest_meta_->is_last = static_cast<uint8_t>(is_last);
return *this;
}
FixedManifestEncoder &FixedManifestEncoder::setBaseNameImpl(
const core::Name &base_name) {
- base_name.copyToDestination(
- reinterpret_cast<uint8_t *>(&manifest_header_->prefix[0]), false);
- manifest_header_->flags.ipv6 =
+ manifest_entry_meta_->is_ipv6 =
base_name.getAddressFamily() == AF_INET6 ? 1_U8 : 0_U8;
+ base_name.copyPrefixToDestination(
+ reinterpret_cast<uint8_t *>(&manifest_entry_meta_->prefix[0]));
return *this;
}
-FixedManifestEncoder &FixedManifestEncoder::addSuffixAndHashImpl(
- uint32_t suffix, const auth::CryptoHash &hash) {
- auto _hash = hash.getDigest();
- addSuffixHashBytes(suffix, _hash.data(), _hash.size());
+FixedManifestEncoder &FixedManifestEncoder::setParamsBytestreamImpl(
+ const ParamsBytestream &params) {
+ transport_type_ = interface::ProductionProtocolAlgorithms::BYTE_STREAM;
+ params_bytestream_ = TransportParamsBytestream{
+ .final_segment = params.final_segment,
+ };
return *this;
}
-void FixedManifestEncoder::addSuffixHashBytes(uint32_t suffix,
- const uint8_t *hash,
- std::size_t length) {
- manifest_entries_[current_entry_].suffix = htonl(suffix);
- // std::copy(hash, hash + length,
- // manifest_entries_[current_entry_].hash);
- std::memcpy(
- reinterpret_cast<uint8_t *>(manifest_entries_[current_entry_].hash), hash,
- length);
+FixedManifestEncoder &FixedManifestEncoder::setParamsRTCImpl(
+ const ParamsRTC &params) {
+ transport_type_ = interface::ProductionProtocolAlgorithms::RTC_PROD;
+ params_rtc_ = TransportParamsRTC{
+ .timestamp = params.timestamp,
+ .prod_rate = params.prod_rate,
+ .prod_seg = params.prod_seg,
+ .fec_type = static_cast<uint32_t>(params.fec_type),
+ };
+ return *this;
+}
- manifest_header_->number_of_entries++;
- current_entry_++;
+FixedManifestEncoder &FixedManifestEncoder::addEntryImpl(
+ uint32_t suffix, const auth::CryptoHash &hash) {
+ ManifestEntry last_entry = {
+ .suffix = portability::host_to_net(suffix),
+ .hash = {0},
+ };
- if (TRANSPORT_EXPECT_FALSE(estimateSerializedLengthImpl() > max_size_)) {
- throw errors::RuntimeException("Manifest size exceeded the packet MTU!");
- }
-}
+ auto last_hash = reinterpret_cast<uint8_t *>(last_entry.hash);
+ std::memcpy(last_hash, hash.getDigest()->data(), hash.getSize());
-FixedManifestEncoder &FixedManifestEncoder::setIsFinalManifestImpl(
- bool is_last) {
- manifest_header_->flags.is_last = static_cast<uint8_t>(is_last);
+ manifest_entries_.push_back(last_entry);
return *this;
}
-FixedManifestEncoder &FixedManifestEncoder::setVersionImpl(
- ManifestVersion version) {
- manifest_header_->version = static_cast<uint8_t>(version);
+FixedManifestEncoder &FixedManifestEncoder::removeEntryImpl(uint32_t suffix) {
+ for (auto it = manifest_entries_.begin(); it != manifest_entries_.end();) {
+ if (it->suffix == suffix)
+ it = manifest_entries_.erase(it);
+ else
+ ++it;
+ }
return *this;
}
-std::size_t FixedManifestEncoder::estimateSerializedLengthImpl(
- std::size_t additional_entries) {
- return sizeof(ManifestHeader) +
- (manifest_header_->number_of_entries + additional_entries) *
- sizeof(ManifestEntry);
+size_t FixedManifestEncoder::manifestHeaderSizeImpl() const {
+ return FixedManifest::manifestHeaderSize(transport_type_);
}
-FixedManifestEncoder &FixedManifestEncoder::updateImpl() {
- max_size_ = Packet::default_mtu - packet_.headerSize() - signature_size_;
- return *this;
+size_t FixedManifestEncoder::manifestPayloadSizeImpl(
+ size_t additional_entries) const {
+ return FixedManifest::manifestPayloadSize(manifest_entries_.size() +
+ additional_entries);
}
-FixedManifestEncoder &FixedManifestEncoder::setFinalBlockNumberImpl(
- std::uint32_t final_block_number) {
- manifest_header_->final_block_number = htonl(final_block_number);
- return *this;
+size_t FixedManifestEncoder::manifestSizeImpl(size_t additional_entries) const {
+ return manifestHeaderSizeImpl() + manifestPayloadSizeImpl(additional_entries);
}
-std::size_t FixedManifestEncoder::getManifestHeaderSizeImpl() {
- return sizeof(ManifestHeader);
+// ---------------------------------------------------------
+// FixedManifestDecoder
+// ---------------------------------------------------------
+FixedManifestDecoder::FixedManifestDecoder(Packet::Ptr packet)
+ : packet_(packet), decoded_(false) {
+ manifest_meta_ =
+ reinterpret_cast<ManifestMeta *>(packet_->getPayload()->writableData());
+ manifest_entry_meta_ =
+ reinterpret_cast<ManifestEntryMeta *>(manifest_meta_ + 1);
}
-std::size_t FixedManifestEncoder::getManifestEntrySizeImpl() {
- return sizeof(ManifestEntry);
-}
-
-FixedManifestDecoder::FixedManifestDecoder(Packet &packet)
- : packet_(packet),
- manifest_header_(reinterpret_cast<ManifestHeader *>(
- packet_.getPayload()->writableData())),
- manifest_entries_(reinterpret_cast<ManifestEntry *>(
- packet_.getPayload()->writableData() + sizeof(ManifestHeader))) {}
-
FixedManifestDecoder::~FixedManifestDecoder() {}
-void FixedManifestDecoder::decodeImpl() {
- std::size_t packet_size = packet_.payloadSize();
+FixedManifestDecoder &FixedManifestDecoder::decodeImpl() {
+ if (decoded_) {
+ return *this;
+ }
- if (packet_size < sizeof(ManifestHeader) ||
- packet_size < estimateSerializedLengthImpl()) {
+ if (packet_->payloadSize() < manifestSizeImpl()) {
throw errors::RuntimeException(
- "The packet does not match expected manifest size.");
+ "The packet payload size does not match expected manifest size");
}
-}
-FixedManifestDecoder &FixedManifestDecoder::clearImpl() { return *this; }
+ switch (getTransportTypeImpl()) {
+ case interface::ProductionProtocolAlgorithms::BYTE_STREAM:
+ params_bytestream_ = reinterpret_cast<TransportParamsBytestream *>(
+ manifest_entry_meta_ + 1);
+ manifest_entries_ =
+ reinterpret_cast<ManifestEntry *>(params_bytestream_ + 1);
+ break;
+ case interface::ProductionProtocolAlgorithms::RTC_PROD:
+ params_rtc_ =
+ reinterpret_cast<TransportParamsRTC *>(manifest_entry_meta_ + 1);
+ manifest_entries_ = reinterpret_cast<ManifestEntry *>(params_rtc_ + 1);
+ break;
+ default:
+ manifest_entries_ =
+ reinterpret_cast<ManifestEntry *>(manifest_entry_meta_ + 1);
+ break;
+ }
-ManifestType FixedManifestDecoder::getManifestTypeImpl() const {
- return static_cast<ManifestType>(manifest_header_->manifest_type);
+ decoded_ = true;
+ return *this;
}
-auth::CryptoHashType FixedManifestDecoder::getHashAlgorithmImpl() const {
- return static_cast<auth::CryptoHashType>(manifest_header_->hash_algorithm);
+FixedManifestDecoder &FixedManifestDecoder::clearImpl() {
+ decoded_ = false;
+ return *this;
}
-NextSegmentCalculationStrategy
-FixedManifestDecoder::getNextSegmentCalculationStrategyImpl() const {
- return static_cast<NextSegmentCalculationStrategy>(
- manifest_header_->next_segment_strategy);
+bool FixedManifestDecoder::isDecodedImpl() const { return decoded_; }
+
+ManifestType FixedManifestDecoder::getTypeImpl() const {
+ return static_cast<ManifestType>(manifest_meta_->type);
}
-typename Fixed::SuffixList FixedManifestDecoder::getSuffixHashListImpl() {
- typename Fixed::SuffixList hash_list;
+interface::ProductionProtocolAlgorithms
+FixedManifestDecoder::getTransportTypeImpl() const {
+ return static_cast<interface::ProductionProtocolAlgorithms>(
+ manifest_meta_->transport_type);
+}
- for (int i = 0; i < manifest_header_->number_of_entries; i++) {
- hash_list.insert(hash_list.end(),
- std::make_pair(ntohl(manifest_entries_[i].suffix),
- reinterpret_cast<uint8_t *>(
- &manifest_entries_[i].hash[0])));
- }
+uint8_t FixedManifestDecoder::getMaxCapacityImpl() const {
+ return manifest_meta_->max_capacity;
+}
- return hash_list;
+auth::CryptoHashType FixedManifestDecoder::getHashAlgorithmImpl() const {
+ return static_cast<auth::CryptoHashType>(manifest_meta_->hash_algorithm);
+}
+
+bool FixedManifestDecoder::getIsLastImpl() const {
+ return static_cast<bool>(manifest_meta_->is_last);
}
core::Name FixedManifestDecoder::getBaseNameImpl() const {
- if (static_cast<bool>(manifest_header_->flags.ipv6)) {
- return core::Name(AF_INET6,
- reinterpret_cast<uint8_t *>(&manifest_header_->prefix));
+ if (static_cast<bool>(manifest_entry_meta_->is_ipv6)) {
+ return core::Name(
+ AF_INET6, reinterpret_cast<uint8_t *>(&manifest_entry_meta_->prefix));
} else {
- return core::Name(AF_INET,
- reinterpret_cast<uint8_t *>(&manifest_header_->prefix));
+ return core::Name(
+ AF_INET, reinterpret_cast<uint8_t *>(&manifest_entry_meta_->prefix));
}
}
-bool FixedManifestDecoder::getIsFinalManifestImpl() const {
- return static_cast<bool>(manifest_header_->flags.is_last);
+ParamsBytestream FixedManifestDecoder::getParamsBytestreamImpl() const {
+ return ParamsBytestream{
+ .final_segment = params_bytestream_->final_segment,
+ };
+}
+
+ParamsRTC FixedManifestDecoder::getParamsRTCImpl() const {
+ return ParamsRTC{
+ .timestamp = params_rtc_->timestamp,
+ .prod_rate = params_rtc_->prod_rate,
+ .prod_seg = params_rtc_->prod_seg,
+ .fec_type = static_cast<protocol::fec::FECType>(params_rtc_->fec_type),
+ };
}
-ManifestVersion FixedManifestDecoder::getVersionImpl() const {
- return static_cast<ManifestVersion>(manifest_header_->version);
+typename Fixed::SuffixList FixedManifestDecoder::getEntriesImpl() const {
+ typename Fixed::SuffixList hash_list;
+
+ for (int i = 0; i < manifest_entry_meta_->nb_entries; i++) {
+ hash_list.insert(
+ hash_list.end(),
+ std::make_pair(
+ portability::net_to_host(manifest_entries_[i].suffix),
+ reinterpret_cast<uint8_t *>(&manifest_entries_[i].hash[0])));
+ }
+
+ return hash_list;
}
-std::size_t FixedManifestDecoder::estimateSerializedLengthImpl(
- std::size_t additional_entries) const {
- return sizeof(ManifestHeader) +
- (additional_entries + manifest_header_->number_of_entries) *
- sizeof(ManifestEntry);
+size_t FixedManifestDecoder::manifestHeaderSizeImpl() const {
+ interface::ProductionProtocolAlgorithms type = getTransportTypeImpl();
+ return FixedManifest::manifestHeaderSize(type);
}
-uint32_t FixedManifestDecoder::getFinalBlockNumberImpl() const {
- return ntohl(manifest_header_->final_block_number);
+size_t FixedManifestDecoder::manifestPayloadSizeImpl(
+ size_t additional_entries) const {
+ size_t nb_entries = manifest_entry_meta_->nb_entries + additional_entries;
+ return FixedManifest::manifestPayloadSize(nb_entries);
}
-} // end namespace core
+size_t FixedManifestDecoder::manifestSizeImpl(size_t additional_entries) const {
+ return manifestHeaderSizeImpl() + manifestPayloadSizeImpl(additional_entries);
+}
+} // end namespace core
} // end namespace transport
diff --git a/libtransport/src/core/manifest_format_fixed.h b/libtransport/src/core/manifest_format_fixed.h
index 56ad4ef6d..7ab371974 100644
--- a/libtransport/src/core/manifest_format_fixed.h
+++ b/libtransport/src/core/manifest_format_fixed.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,26 +24,72 @@ namespace transport {
namespace core {
-// 0 1 2 3
-// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
-// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-// |Version| MType |HashAlg|NextStr| Flags |NumberOfEntries|
-// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-// | Final Block Number |
-// +---------------------------------------------------------------|
-// | |
-// + +
-// | |
-// + Prefix +
-// | |
-// + +
-// | |
-// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-// | Suffix |
-// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-// | Hash Value |
-// | |
-// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// Manifest Metadata:
+// 0 1 2 3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | Type | TTYpe | Max Capacity | Hash Algo |L| Reserved |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+// Manifest Entry Metadata:
+// 0 1 2 3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | Nb entries |I| Reserved |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | |
+// + +
+// | |
+// + Prefix +
+// | |
+// + +
+// | |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+// Manifest Transport Parameters - Bytestream:
+// 0 1 2 3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | Final Segment |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+// Manifest Transport Parameters - RTC:
+// 0 1 2 3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | |
+// + Timestamp +
+// | |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | Production Rate |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | Current Segment |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | FEC Type |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+// Manifest Entry:
+// 0 1 2 3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | Packet Suffix |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | |
+// + +
+// | |
+// + +
+// | |
+// + +
+// | |
+// + Packet Digest +
+// | |
+// + +
+// | |
+// + +
+// | |
+// + +
+// | |
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
class FixedManifestEncoder;
class FixedManifestDecoder;
@@ -58,113 +104,143 @@ struct Fixed {
using SuffixList = std::list<std::pair<uint32_t, uint8_t *>>;
};
-struct Flags {
- std::uint8_t ipv6 : 1;
- std::uint8_t is_last : 1;
- std::uint8_t unused : 6;
+const size_t MANIFEST_META_SIZE = 4;
+struct __attribute__((__packed__)) ManifestMeta {
+ std::uint8_t type : 4;
+ std::uint8_t transport_type : 4;
+ std::uint8_t max_capacity;
+ std::uint8_t hash_algorithm;
+ std::uint8_t is_last;
};
+static_assert(sizeof(ManifestMeta) == MANIFEST_META_SIZE);
-struct ManifestEntry {
+const size_t MANIFEST_ENTRY_META_SIZE = 20;
+struct __attribute__((__packed__)) ManifestEntryMeta {
+ std::uint8_t nb_entries;
+ std::uint8_t is_ipv6;
+ std::uint16_t unused;
+ std::uint32_t prefix[4];
+};
+static_assert(sizeof(ManifestEntryMeta) == MANIFEST_ENTRY_META_SIZE);
+
+const size_t MANIFEST_PARAMS_BYTESTREAM_SIZE = 4;
+struct __attribute__((__packed__)) TransportParamsBytestream {
+ std::uint32_t final_segment;
+};
+static_assert(sizeof(TransportParamsBytestream) ==
+ MANIFEST_PARAMS_BYTESTREAM_SIZE);
+
+const size_t MANIFEST_PARAMS_RTC_SIZE = 20;
+struct __attribute__((__packed__)) TransportParamsRTC {
+ std::uint64_t timestamp;
+ std::uint32_t prod_rate;
+ std::uint32_t prod_seg;
+ std::uint32_t fec_type;
+};
+static_assert(sizeof(TransportParamsRTC) == MANIFEST_PARAMS_RTC_SIZE);
+
+const size_t MANIFEST_ENTRY_SIZE = 36;
+struct __attribute__((__packed__)) ManifestEntry {
std::uint32_t suffix;
std::uint32_t hash[8];
};
+static_assert(sizeof(ManifestEntry) == MANIFEST_ENTRY_SIZE);
-struct ManifestHeader {
- std::uint8_t version : 4;
- std::uint8_t manifest_type : 4;
- std::uint8_t hash_algorithm : 4;
- std::uint8_t next_segment_strategy : 4;
- Flags flags;
- std::uint8_t number_of_entries;
- std::uint32_t final_block_number;
- std::uint32_t prefix[4];
- ManifestEntry entries[0];
+class FixedManifest {
+ public:
+ static size_t manifestHeaderSize(
+ interface::ProductionProtocolAlgorithms transport_type);
+ static size_t manifestPayloadSize(size_t nb_entries);
};
-static const constexpr std::uint8_t manifest_version = 1;
-
class FixedManifestEncoder : public ManifestEncoder<FixedManifestEncoder> {
public:
- FixedManifestEncoder(Packet &packet, std::size_t signature_size = 0,
- bool clear = true);
+ FixedManifestEncoder(Packet::Ptr packet, bool clear = false);
~FixedManifestEncoder();
FixedManifestEncoder &encodeImpl();
-
FixedManifestEncoder &clearImpl();
+ bool isEncodedImpl() const;
- FixedManifestEncoder &setManifestTypeImpl(ManifestType manifest_type);
-
+ // ManifestMeta
+ FixedManifestEncoder &setTypeImpl(ManifestType manifest_type);
+ FixedManifestEncoder &setMaxCapacityImpl(uint8_t max_capacity);
FixedManifestEncoder &setHashAlgorithmImpl(Fixed::HashType algorithm);
+ FixedManifestEncoder &setIsLastImpl(bool is_last);
- FixedManifestEncoder &setNextSegmentCalculationStrategyImpl(
- NextSegmentCalculationStrategy strategy);
-
+ // ManifestEntryMeta
FixedManifestEncoder &setBaseNameImpl(const core::Name &base_name);
- FixedManifestEncoder &addSuffixAndHashImpl(uint32_t suffix,
- const Fixed::Hash &hash);
-
- FixedManifestEncoder &setIsFinalManifestImpl(bool is_last);
+ // TransportParams
+ FixedManifestEncoder &setParamsBytestreamImpl(const ParamsBytestream &params);
+ FixedManifestEncoder &setParamsRTCImpl(const ParamsRTC &params);
- FixedManifestEncoder &setVersionImpl(ManifestVersion version);
+ // ManifestEntry
+ FixedManifestEncoder &addEntryImpl(uint32_t suffix, const Fixed::Hash &hash);
+ FixedManifestEncoder &removeEntryImpl(uint32_t suffix);
- std::size_t estimateSerializedLengthImpl(std::size_t additional_entries = 0);
-
- FixedManifestEncoder &updateImpl();
-
- FixedManifestEncoder &setFinalBlockNumberImpl(
- std::uint32_t final_block_number);
-
- static std::size_t getManifestHeaderSizeImpl();
-
- static std::size_t getManifestEntrySizeImpl();
+ size_t manifestHeaderSizeImpl() const;
+ size_t manifestPayloadSizeImpl(size_t additional_entries = 0) const;
+ size_t manifestSizeImpl(size_t additional_entries = 0) const;
private:
- void addSuffixHashBytes(uint32_t suffix, const uint8_t *hash,
- std::size_t length);
-
- Packet &packet_;
- std::size_t max_size_;
- ManifestHeader *manifest_header_;
- ManifestEntry *manifest_entries_;
- std::size_t current_entry_;
- std::size_t signature_size_;
+ Packet::Ptr packet_;
+ interface::ProductionProtocolAlgorithms transport_type_;
+ bool encoded_;
+
+ // Manifest Header
+ ManifestMeta *manifest_meta_;
+ ManifestEntryMeta *manifest_entry_meta_;
+ TransportParamsBytestream params_bytestream_;
+ TransportParamsRTC params_rtc_;
+
+ // Manifest Entries
+ std::vector<ManifestEntry> manifest_entries_;
};
class FixedManifestDecoder : public ManifestDecoder<FixedManifestDecoder> {
public:
- FixedManifestDecoder(Packet &packet);
+ FixedManifestDecoder(Packet::Ptr packet);
~FixedManifestDecoder();
- void decodeImpl();
-
+ FixedManifestDecoder &decodeImpl();
FixedManifestDecoder &clearImpl();
+ bool isDecodedImpl() const;
- ManifestType getManifestTypeImpl() const;
-
+ // ManifestMeta
+ ManifestType getTypeImpl() const;
+ interface::ProductionProtocolAlgorithms getTransportTypeImpl() const;
+ uint8_t getMaxCapacityImpl() const;
Fixed::HashType getHashAlgorithmImpl() const;
+ bool getIsLastImpl() const;
- NextSegmentCalculationStrategy getNextSegmentCalculationStrategyImpl() const;
-
- typename Fixed::SuffixList getSuffixHashListImpl();
-
+ // ManifestEntryMeta
core::Name getBaseNameImpl() const;
- bool getIsFinalManifestImpl() const;
+ // TransportParams
+ ParamsBytestream getParamsBytestreamImpl() const;
+ ParamsRTC getParamsRTCImpl() const;
- std::size_t estimateSerializedLengthImpl(
- std::size_t additional_entries = 0) const;
+ // ManifestEntry
+ typename Fixed::SuffixList getEntriesImpl() const;
- ManifestVersion getVersionImpl() const;
-
- uint32_t getFinalBlockNumberImpl() const;
+ size_t manifestHeaderSizeImpl() const;
+ size_t manifestPayloadSizeImpl(size_t additional_entries = 0) const;
+ size_t manifestSizeImpl(size_t additional_entries = 0) const;
private:
- Packet &packet_;
- ManifestHeader *manifest_header_;
+ Packet::Ptr packet_;
+ bool decoded_;
+
+ // Manifest Header
+ ManifestMeta *manifest_meta_;
+ ManifestEntryMeta *manifest_entry_meta_;
+ TransportParamsBytestream *params_bytestream_;
+ TransportParamsRTC *params_rtc_;
+
+ // Manifest Entries
ManifestEntry *manifest_entries_;
};
diff --git a/libtransport/src/core/manifest_inline.h b/libtransport/src/core/manifest_inline.h
deleted file mode 100644
index a487ccfe3..000000000
--- a/libtransport/src/core/manifest_inline.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 <core/manifest.h>
-#include <core/manifest_format.h>
-#include <hicn/transport/portability/portability.h>
-
-#include <set>
-
-namespace transport {
-
-namespace core {
-
-template <typename Base, typename FormatTraits>
-class ManifestInline
- : public Manifest<Base, FormatTraits, ManifestInline<Base, FormatTraits>> {
- using ManifestBase =
- Manifest<Base, FormatTraits, ManifestInline<Base, FormatTraits>>;
-
- using Hash = typename FormatTraits::Hash;
- using HashType = typename FormatTraits::HashType;
- using Suffix = typename FormatTraits::Suffix;
- using SuffixList = typename FormatTraits::SuffixList;
- using HashEntry = std::pair<auth::CryptoHashType, std::vector<uint8_t>>;
-
- public:
- ManifestInline() : ManifestBase() {}
-
- ManifestInline(const core::Name &name, std::size_t signature_size = 0)
- : ManifestBase(name, signature_size) {}
-
- template <typename T>
- ManifestInline(T &&base) : ManifestBase(std::forward<T &&>(base)) {}
-
- static TRANSPORT_ALWAYS_INLINE ManifestInline *createManifest(
- const core::Name &manifest_name, ManifestVersion version,
- ManifestType type, HashType algorithm, bool is_last,
- const Name &base_name, NextSegmentCalculationStrategy strategy,
- std::size_t signature_size) {
- auto manifest = new ManifestInline(manifest_name, signature_size);
- manifest->setVersion(version);
- manifest->setManifestType(type);
- manifest->setHashAlgorithm(algorithm);
- manifest->setFinalManifest(is_last);
- manifest->setBaseName(base_name);
- manifest->setNextSegmentCalculationStrategy(strategy);
-
- return manifest;
- }
-
- ManifestInline &encodeImpl() {
- ManifestBase::encoder_.encode();
- return *this;
- }
-
- ManifestInline &decodeImpl() {
- base_name_ = ManifestBase::decoder_.getBaseName();
- next_segment_strategy_ =
- ManifestBase::decoder_.getNextSegmentCalculationStrategy();
- suffix_hash_map_ = ManifestBase::decoder_.getSuffixHashList();
-
- return *this;
- }
-
- std::size_t estimateManifestSizeImpl(std::size_t additional_entries = 0) {
- return ManifestBase::encoder_.estimateSerializedLength(additional_entries);
- }
-
- ManifestInline &setBaseName(const Name &name) {
- base_name_ = name;
- ManifestBase::encoder_.setBaseName(base_name_);
- return *this;
- }
-
- const Name &getBaseName() { return base_name_; }
-
- ManifestInline &addSuffixHash(Suffix suffix, const Hash &hash) {
- ManifestBase::encoder_.addSuffixAndHash(suffix, hash);
- return *this;
- }
-
- // Call this function only after the decode function!
- const SuffixList &getSuffixList() { return suffix_hash_map_; }
-
- ManifestInline &setNextSegmentCalculationStrategy(
- NextSegmentCalculationStrategy strategy) {
- next_segment_strategy_ = strategy;
- ManifestBase::encoder_.setNextSegmentCalculationStrategy(
- next_segment_strategy_);
- return *this;
- }
-
- NextSegmentCalculationStrategy getNextSegmentCalculationStrategy() {
- return next_segment_strategy_;
- }
-
- // Convert several manifests into a single map from suffixes to packet hashes.
- // All manifests must have been decoded beforehand.
- static std::unordered_map<Suffix, Hash> getSuffixMap(
- const std::vector<ManifestInline *> &manifests) {
- std::unordered_map<Suffix, Hash> suffix_map;
-
- for (auto manifest_ptr : manifests) {
- HashType hash_type = manifest_ptr->getHashAlgorithm();
- SuffixList suffix_list = manifest_ptr->getSuffixList();
-
- for (auto it = suffix_list.begin(); it != suffix_list.end(); ++it) {
- Hash hash(it->second, Hash::getSize(hash_type), hash_type);
- suffix_map[it->first] = hash;
- }
- }
-
- return suffix_map;
- }
-
- static std::unordered_map<Suffix, Hash> getSuffixMap(
- ManifestInline *manifest) {
- return getSuffixMap(std::vector<ManifestInline *>{manifest});
- }
-
- private:
- core::Name base_name_;
- NextSegmentCalculationStrategy next_segment_strategy_;
- SuffixList suffix_hash_map_;
-};
-
-} // namespace core
-} // namespace transport
diff --git a/libtransport/src/core/memif_connector.cc b/libtransport/src/core/memif_connector.cc
new file mode 100644
index 000000000..a224beb11
--- /dev/null
+++ b/libtransport/src/core/memif_connector.cc
@@ -0,0 +1,503 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <core/errors.h>
+#include <core/memif_connector.h>
+#include <glog/logging.h>
+#include <hicn/transport/errors/not_implemented_exception.h>
+#include <sys/epoll.h>
+
+#include <cstdlib>
+
+/* sstrncpy */
+#include <hicn/util/sstrncpy.h>
+
+#define CANCEL_TIMER 1
+
+namespace transport {
+
+namespace core {
+
+MemifConnector::MemifConnector(PacketReceivedCallback &&receive_callback,
+ PacketSentCallback &&packet_sent,
+ OnCloseCallback &&close_callback,
+ OnReconnectCallback &&on_reconnect,
+ asio::io_service &io_service,
+ std::string app_name)
+ : Connector(std::move(receive_callback), std::move(packet_sent),
+ std::move(close_callback), std::move(on_reconnect)),
+ event_reactor_(),
+ memif_worker_(std::bind(&MemifConnector::threadMain, this)),
+ timer_set_(false),
+ send_timer_(event_reactor_),
+ disconnect_timer_(event_reactor_),
+ io_service_(io_service),
+ work_(asio::make_work_guard(io_service_)),
+ memif_connection_({0}),
+ tx_buf_counter_(0),
+ is_reconnection_(false),
+ data_available_(false),
+ app_name_(app_name),
+ socket_filename_(""),
+ buffer_size_(kbuf_size),
+ log2_ring_size_(klog2_ring_size),
+ max_memif_bufs_(1 << klog2_ring_size) {}
+
+MemifConnector::~MemifConnector() {
+ try {
+ close();
+ } catch (errors::RuntimeException &e) {
+ // do nothing
+ }
+}
+
+void MemifConnector::connect(uint32_t memif_id, long memif_mode,
+ const std::string &socket_filename,
+ std::size_t buffer_size,
+ std::size_t log2_ring_size) {
+ state_ = State::CONNECTING;
+
+ memif_id_ = memif_id;
+ socket_filename_ = socket_filename;
+ buffer_size_ = buffer_size;
+ log2_ring_size_ = log2_ring_size;
+ max_memif_bufs_ = 1 << log2_ring_size;
+ createMemif(memif_id, memif_mode);
+}
+
+int MemifConnector::createMemif(uint32_t index, uint8_t is_master) {
+ int err = MEMIF_ERR_SUCCESS;
+
+ memif_socket_args_t socket_args;
+ memif_conn_args_t args;
+ memset(&socket_args, 0, sizeof(memif_socket_args_t));
+ memset(&args, 0, sizeof(memif_conn_args_t));
+
+ // Setup memif socket first
+
+ int rc = strcpy_s(socket_args.path, sizeof(socket_args.path) - 1,
+ socket_filename_.c_str());
+ if (rc != EOK) {
+ std::string error = "Provided socket path is larger than " +
+ std::to_string(sizeof(socket_args.path)) + " bytes.";
+ throw errors::RuntimeException(error);
+ }
+
+ rc = strcpy_s(socket_args.app_name, sizeof(socket_args.app_name) - 1,
+ app_name_.c_str());
+ if (rc != EOK) {
+ std::string error = "Provided app_name is larger than " +
+ std::to_string(sizeof(socket_args.app_name)) +
+ " bytes.";
+ throw errors::RuntimeException(error);
+ }
+
+ socket_args.on_control_fd_update = controlFdUpdate;
+ socket_args.alloc = nullptr;
+ socket_args.realloc = nullptr;
+ socket_args.free = nullptr;
+
+ err = memif_create_socket(&args.socket, &socket_args, this);
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
+ throw errors::RuntimeException(memif_strerror(err));
+ }
+
+ // Setup memif connection using provided memif_socket_handle_t
+ args.is_master = is_master;
+ args.log2_ring_size = log2_ring_size_;
+ args.buffer_size = buffer_size_;
+ args.num_s2m_rings = 1;
+ args.num_m2s_rings = 1;
+ strcpy_s((char *)args.interface_name, sizeof(args.interface_name), IF_NAME);
+ args.mode = memif_interface_mode_t::MEMIF_INTERFACE_MODE_IP;
+ args.interface_id = index;
+ err = memif_create(&memif_connection_.conn, &args, onConnect, onDisconnect,
+ onInterrupt, this);
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
+ throw errors::RuntimeException(memif_strerror(err));
+ }
+
+ memif_connection_.index = (uint16_t)index;
+ memif_connection_.tx_qid = 0;
+ /* alloc memif buffers */
+ memif_connection_.rx_buf_num = 0;
+ memif_connection_.rx_bufs = static_cast<memif_buffer_t *>(
+ malloc(sizeof(memif_buffer_t) * max_memif_bufs_));
+ memif_connection_.tx_buf_num = 0;
+ memif_connection_.tx_bufs = static_cast<memif_buffer_t *>(
+ malloc(sizeof(memif_buffer_t) * max_memif_bufs_));
+
+ return 0;
+}
+
+int MemifConnector::deleteMemif() {
+ if (memif_connection_.rx_bufs) {
+ free(memif_connection_.rx_bufs);
+ }
+
+ memif_connection_.rx_bufs = nullptr;
+ memif_connection_.rx_buf_num = 0;
+
+ if (memif_connection_.tx_bufs) {
+ free(memif_connection_.tx_bufs);
+ }
+
+ memif_connection_.tx_bufs = nullptr;
+ memif_connection_.tx_buf_num = 0;
+
+ int err;
+ /* disconenct then delete memif connection */
+ err = memif_delete(&memif_connection_.conn);
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
+ LOG(ERROR) << "memif_delete: " << memif_strerror(err);
+ }
+
+ if (TRANSPORT_EXPECT_FALSE(memif_connection_.conn != nullptr)) {
+ LOG(ERROR) << "memif delete fail";
+ }
+
+ state_ = State::CLOSED;
+
+ return 0;
+}
+
+int MemifConnector::controlFdUpdate(memif_fd_event_t fde, void *private_ctx) {
+ auto self = reinterpret_cast<MemifConnector *>(private_ctx);
+ uint32_t evt = 0;
+
+ /* convert memif event definitions to epoll events */
+ auto events = fde.type;
+ auto fd = fde.fd;
+
+ if (events & MEMIF_FD_EVENT_ERROR) {
+ LOG(ERROR) << "memif fd event: Error";
+ return -1;
+ }
+
+ if (events & MEMIF_FD_EVENT_DEL) {
+ DLOG_IF(INFO, VLOG_IS_ON(4)) << "memif fd event: DEL fd " << fd;
+ return self->event_reactor_.delFileDescriptor(fd);
+ }
+
+ if (events & MEMIF_FD_EVENT_MOD) {
+ DLOG_IF(INFO, VLOG_IS_ON(4)) << "memif fd event: MOD fd " << fd;
+ return self->event_reactor_.modFileDescriptor(fd, evt);
+ }
+
+ if (events & MEMIF_FD_EVENT_READ) {
+ evt |= EPOLLIN;
+ }
+
+ if (events & MEMIF_FD_EVENT_WRITE) {
+ evt |= EPOLLOUT;
+ }
+
+ DLOG_IF(INFO, VLOG_IS_ON(4)) << "memif fd event: ADD fd " << fd;
+ return self->event_reactor_.addFileDescriptor(
+ fd, evt, [fde](const utils::Event &evt) -> int {
+ int event = 0;
+ int memif_err = 0;
+
+ if (evt.events & EPOLLIN) {
+ event |= MEMIF_FD_EVENT_READ;
+ }
+
+ if (evt.events & EPOLLOUT) {
+ event |= MEMIF_FD_EVENT_WRITE;
+ }
+
+ if (evt.events & EPOLLERR) {
+ event |= MEMIF_FD_EVENT_ERROR;
+ }
+
+ memif_err = memif_control_fd_handler(fde.private_ctx,
+ memif_fd_event_type_t(event));
+
+ if (TRANSPORT_EXPECT_FALSE(memif_err != MEMIF_ERR_SUCCESS)) {
+ LOG(ERROR) << "memif_control_fd_handler: "
+ << memif_strerror(memif_err);
+ }
+
+ return 0;
+ });
+}
+
+uint16_t MemifConnector::bufferAlloc(long n, uint16_t qid,
+ std::error_code &ec) {
+ int err;
+ uint16_t r = 0;
+ /* set data pointer to shared memory and set buffer_len to shared mmeory
+ * buffer len */
+ err = memif_buffer_alloc(memif_connection_.conn, qid,
+ memif_connection_.tx_bufs, n, &r, buffer_size_);
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
+ ec = make_error_code(core_error::send_buffer_allocation_failed);
+ }
+
+ memif_connection_.tx_buf_num += r;
+ return r;
+}
+
+uint16_t MemifConnector::txBurst(uint16_t qid, std::error_code &ec) {
+ int err = MEMIF_ERR_SUCCESS;
+ ec = make_error_code(core_error::success);
+ uint16_t tx = 0;
+
+ /* inform peer memif interface about data in shared memory buffers */
+ /* mark memif buffers as free */
+ err = memif_tx_burst(memif_connection_.conn, qid, memif_connection_.tx_bufs,
+ memif_connection_.tx_buf_num, &tx);
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
+ ec = make_error_code(core_error::send_failed);
+ }
+
+ memif_connection_.tx_buf_num -= tx;
+ return tx;
+}
+
+void MemifConnector::scheduleSend(std::uint64_t delay) {
+ if (!timer_set_) {
+ timer_set_ = true;
+ send_timer_.expiresFromNow(std::chrono::microseconds(delay));
+ send_timer_.asyncWait(
+ std::bind(&MemifConnector::sendCallback, this, std::placeholders::_1));
+ }
+}
+
+void MemifConnector::sendCallback(const std::error_code &ec) {
+ timer_set_ = false;
+
+ if (TRANSPORT_EXPECT_TRUE(!ec && state_ == State::CONNECTED)) {
+ doSend();
+ }
+}
+
+/* informs user about connected status. private_ctx is used by user to identify
+ connection (multiple connections WIP) */
+int MemifConnector::onConnect(memif_conn_handle_t conn, void *private_ctx) {
+ auto self = reinterpret_cast<MemifConnector *>(private_ctx);
+ self->state_ = State::CONNECTED;
+ memif_refill_queue(conn, 0, -1, 0);
+
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Memif " << self->app_name_ << " connected";
+
+ // We are connected. Notify higher layers.
+ self->io_service_.post([self]() {
+ self->on_reconnect_callback_(self, make_error_code(core_error::success));
+ });
+
+ self->doSend();
+
+ return 0;
+}
+
+/* informs user about disconnected status. private_ctx is used by user to
+ identify connection (multiple connections WIP) */
+int MemifConnector::onDisconnect(memif_conn_handle_t conn, void *private_ctx) {
+ MemifConnector *connector = (MemifConnector *)private_ctx;
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Memif " << connector->app_name_ << " disconnected";
+ return 0;
+}
+
+void MemifConnector::threadMain() { event_reactor_.runEventLoop(200); }
+
+int MemifConnector::onInterrupt(memif_conn_handle_t conn, void *private_ctx,
+ uint16_t qid) {
+ MemifConnector *connector = (MemifConnector *)private_ctx;
+
+ Details &c = connector->memif_connection_;
+ std::weak_ptr<MemifConnector> self = connector->shared_from_this();
+ std::vector<::utils::MemBuf::Ptr> v;
+ std::error_code ec = make_error_code(core_error::success);
+
+ int err = MEMIF_ERR_SUCCESS, ret_val;
+ uint16_t rx = 0;
+
+ do {
+ err = memif_rx_burst(conn, qid, c.rx_bufs, max_burst, &rx);
+ ret_val = err;
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS &&
+ err != MEMIF_ERR_NOBUF)) {
+ ec = make_error_code(core_error::receive_failed);
+ LOG(ERROR) << "memif_rx_burst: " << memif_strerror(err);
+ goto error;
+ }
+
+ c.rx_buf_num += rx;
+
+ if (TRANSPORT_EXPECT_FALSE(connector->io_service_.stopped())) {
+ LOG(ERROR) << "socket stopped: ignoring " << rx << " packets";
+ goto error;
+ }
+
+ std::size_t packet_length;
+ v.reserve(rx);
+ for (int i = 0; i < rx; i++) {
+ auto buffer = connector->getRawBuffer();
+ packet_length = (c.rx_bufs + i)->len;
+ std::memcpy(buffer.first, (c.rx_bufs + i)->data, packet_length);
+ auto packet = connector->getPacketFromBuffer(buffer.first, packet_length);
+ v.emplace_back(std::move(packet));
+ }
+
+ /* mark memif buffers and shared memory buffers as free */
+ /* free processed buffers */
+
+ err = memif_refill_queue(conn, qid, rx, 0);
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
+ LOG(ERROR) << "memif_buffer_free: " << memif_strerror(err);
+ }
+
+ c.rx_buf_num -= rx;
+
+ } while (ret_val == MEMIF_ERR_NOBUF);
+
+ connector->io_service_.post([self, buffers = std::move(v)]() {
+ if (auto c = self.lock()) {
+ c->receive_callback_(c.get(), buffers,
+ std::make_error_code(std::errc(0)));
+ }
+ });
+
+ return 0;
+
+error:
+ err = memif_refill_queue(c.conn, qid, rx, 0);
+
+ if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
+ LOG(ERROR) << "memif_buffer_free: " << memif_strerror(err);
+ }
+ c.rx_buf_num -= rx;
+
+ connector->io_service_.post([self, ec]() {
+ if (auto c = self.lock()) {
+ c->receive_callback_(c.get(), {}, ec);
+ }
+ });
+
+ return 0;
+}
+
+void MemifConnector::close() {
+ if (state_ != State::CLOSED) {
+ disconnect_timer_.expiresFromNow(std::chrono::microseconds(50));
+ disconnect_timer_.asyncWait([this](const std::error_code &ec) {
+ deleteMemif();
+ event_reactor_.stop();
+ });
+ }
+
+ if (memif_worker_.joinable()) {
+ memif_worker_.join();
+ }
+}
+
+void MemifConnector::send(Packet &packet) { send(packet.shared_from_this()); }
+
+void MemifConnector::send(const utils::MemBuf::Ptr &buffer) {
+ {
+ utils::SpinLock::Acquire locked(write_msgs_lock_);
+ output_buffer_.push_back(buffer);
+ }
+#if CANCEL_TIMER
+ scheduleSend(50);
+#endif
+}
+
+int MemifConnector::doSend() {
+ std::size_t max = 0;
+ std::size_t size = 0;
+ std::error_code ec = make_error_code(core_error::success);
+ int ret = 0;
+ uint64_t delay = 50; // microseconds
+
+ utils::SpinLock::Acquire locked(write_msgs_lock_);
+
+ // Check if there are pending buffers to send
+ if (memif_connection_.tx_buf_num > 0) {
+ ret = txBurst(memif_connection_.tx_qid, ec);
+ if (TRANSPORT_EXPECT_FALSE(ec.operator bool())) {
+ delay = 200;
+ goto done;
+ }
+ }
+
+ // Continue trying to send buffers in output_buffer_
+ size = output_buffer_.size();
+ max = size < max_burst ? size : max_burst;
+
+ ret = bufferAlloc(max, memif_connection_.tx_qid, ec);
+ if (TRANSPORT_EXPECT_FALSE(ec.operator bool() && ret == 0)) {
+ delay = 200;
+ goto done;
+ }
+
+ // Fill allocated buffers and remove them from output_buffer_
+ for (uint16_t i = 0; i < ret; i++) {
+ auto packet = output_buffer_.front().get();
+ const utils::MemBuf *current = packet;
+ std::size_t offset = 0;
+ uint8_t *shared_buffer =
+ reinterpret_cast<uint8_t *>(memif_connection_.tx_bufs[i].data);
+ do {
+ std::memcpy(shared_buffer + offset, current->data(), current->length());
+ offset += current->length();
+ current = current->next();
+ } while (current != packet);
+
+ memif_connection_.tx_bufs[i].len = uint32_t(offset);
+ output_buffer_.pop_front();
+ }
+
+ // Try to send them
+ ret = txBurst(memif_connection_.tx_qid, ec);
+ if (TRANSPORT_EXPECT_FALSE(ec.operator bool())) {
+ LOG(ERROR) << "Tx burst failed " << ec.message();
+ delay = 200;
+ goto done;
+ }
+
+done:
+ memif_refill_queue(memif_connection_.conn, memif_connection_.tx_qid, ret, 0);
+
+ // If there are still packets to send, schedule another send
+ if (memif_connection_.tx_buf_num > 0 || !output_buffer_.empty()) {
+ scheduleSend(delay);
+ }
+
+ // If error, signal to upper layers
+ if (ec.operator bool()) {
+ std::weak_ptr<MemifConnector> self = shared_from_this();
+ io_service_.post([self, ec]() {
+ if (auto c = self.lock()) {
+ c->sent_callback_(c.get(), ec);
+ }
+ });
+ }
+
+ return 0;
+}
+
+} // end namespace core
+
+} // end namespace transport
diff --git a/libtransport/src/io_modules/memif/memif_connector.h b/libtransport/src/core/memif_connector.h
index 0a189f893..d36be4616 100644
--- a/libtransport/src/io_modules/memif/memif_connector.h
+++ b/libtransport/src/core/memif_connector.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,27 +25,48 @@
#include <utils/fd_deadline_timer.h>
#include <deque>
+#include <future>
#include <mutex>
#include <thread>
+extern "C" {
+#include <libmemif.h>
+};
+
#define _Static_assert static_assert
namespace transport {
namespace core {
-typedef struct memif_connection memif_connection_t;
-
#define APP_NAME "libtransport"
#define IF_NAME "vpp_connection"
-#define MEMIF_BUF_SIZE 2048
-#define MEMIF_LOG2_RING_SIZE 13
-#define MAX_MEMIF_BUFS (1 << MEMIF_LOG2_RING_SIZE)
-
class MemifConnector : public Connector {
- using memif_conn_handle_t = void *;
+ static inline std::size_t kbuf_size = 2048;
+ static inline std::size_t klog2_ring_size = 13;
+
using PacketRing = utils::CircularFifo<utils::MemBuf::Ptr, queue_size>;
+ struct Details {
+ // index
+ uint16_t index;
+ // memif conenction handle
+ memif_conn_handle_t conn;
+ // transmit queue id
+ uint16_t tx_qid;
+ // tx buffers
+ memif_buffer_t *tx_bufs;
+ // allocated tx buffers counter
+ // number of tx buffers pointing to shared memory
+ uint16_t tx_buf_num;
+ // rx buffers
+ memif_buffer_t *rx_bufs;
+ // allocated rx buffers counter
+ // number of rx buffers pointing to shared memory
+ uint16_t rx_buf_num;
+ // interface ip address
+ uint8_t ip_addr[4];
+ };
public:
MemifConnector(PacketReceivedCallback &&receive_callback,
@@ -59,11 +80,14 @@ class MemifConnector : public Connector {
void send(Packet &packet) override;
- void send(const uint8_t *packet, std::size_t len) override;
+ void send(const utils::MemBuf::Ptr &buffer) override;
void close() override;
- void connect(uint32_t memif_id, long memif_mode);
+ void connect(uint32_t memif_id, long memif_mode,
+ const std::string &socket_filename,
+ std::size_t buffer_size = kbuf_size,
+ std::size_t log2_ring_size = klog2_ring_size);
TRANSPORT_ALWAYS_INLINE uint32_t getMemifId() { return memif_id_; };
@@ -72,13 +96,13 @@ class MemifConnector : public Connector {
int doSend();
- int createMemif(uint32_t index, uint8_t mode, char *s);
+ int createMemif(uint32_t index, uint8_t is_master);
uint32_t getMemifConfiguration();
int deleteMemif();
- static int controlFdUpdate(int fd, uint8_t events, void *private_ctx);
+ static int controlFdUpdate(memif_fd_event_t fde, void *private_ctx);
static int onConnect(memif_conn_handle_t conn, void *private_ctx);
@@ -89,27 +113,26 @@ class MemifConnector : public Connector {
void threadMain();
- int txBurst(uint16_t qid);
+ uint16_t txBurst(uint16_t qid, std::error_code &ec);
+
+ uint16_t bufferAlloc(long n, uint16_t qid, std::error_code &ec);
- int bufferAlloc(long n, uint16_t qid);
+ void scheduleSend(std::uint64_t delay);
void sendCallback(const std::error_code &ec);
- void processInputBuffer(std::uint16_t total_packets);
+ auto shared_from_this() { return utils::shared_from(this); }
private:
- static utils::EpollEventReactor main_event_reactor_;
- static std::unique_ptr<std::thread> main_worker_;
-
int epfd;
- std::unique_ptr<std::thread> memif_worker_;
utils::EpollEventReactor event_reactor_;
+ std::thread memif_worker_;
std::atomic_bool timer_set_;
- std::unique_ptr<utils::FdDeadlineTimer> send_timer_;
- std::unique_ptr<utils::FdDeadlineTimer> disconnect_timer_;
+ utils::FdDeadlineTimer send_timer_;
+ utils::FdDeadlineTimer disconnect_timer_;
asio::io_service &io_service_;
asio::executor_work_guard<asio::io_context::executor_type> work_;
- std::unique_ptr<memif_connection_t> memif_connection_;
+ Details memif_connection_;
uint16_t tx_buf_counter_;
PacketRing input_buffer_;
@@ -121,8 +144,9 @@ class MemifConnector : public Connector {
uint16_t transmission_index_;
utils::SpinLock write_msgs_lock_;
std::string socket_filename_;
-
- static std::once_flag flag_;
+ std::size_t buffer_size_;
+ std::size_t log2_ring_size_;
+ std::size_t max_memif_bufs_;
};
} // end namespace core
diff --git a/libtransport/src/core/name.cc b/libtransport/src/core/name.cc
index 795c8a697..4f8ba7873 100644
--- a/libtransport/src/core/name.cc
+++ b/libtransport/src/core/name.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,6 +14,7 @@
*/
#include <core/manifest_format.h>
+#include <hicn/name.h>
#include <hicn/transport/core/name.h>
#include <hicn/transport/errors/errors.h>
#include <hicn/transport/errors/tokenizer_exception.h>
@@ -24,32 +25,31 @@ namespace transport {
namespace core {
-Name::Name() { name_ = {}; }
+Name::Name() { std::memset(&name_, 0, sizeof(name_)); }
+/**
+ * XXX This function does not use the name API provided by libhicn
+ */
Name::Name(int family, const uint8_t *ip_address, std::uint32_t suffix)
: name_({}) {
- name_.type = HNT_UNSPEC;
std::size_t length;
uint8_t *dst = NULL;
if (family == AF_INET) {
- dst = name_.ip4.prefix_as_u8;
+ dst = name_.prefix.v4.as_u8;
length = IPV4_ADDR_LEN;
- name_.type = HNT_CONTIGUOUS_V4;
} else if (family == AF_INET6) {
- dst = name_.ip6.prefix_as_u8;
+ dst = name_.prefix.v6.as_u8;
length = IPV6_ADDR_LEN;
- name_.type = HNT_CONTIGUOUS_V6;
} else {
throw errors::RuntimeException("Specified name family does not exist.");
}
std::memcpy(dst, ip_address, length);
- *reinterpret_cast<std::uint32_t *>(dst + length) = suffix;
+ name_.suffix = suffix;
}
Name::Name(const char *name, uint32_t segment) {
- name_.type = HNT_UNSPEC;
if (hicn_name_create(name, segment, &name_) < 0) {
throw errors::InvalidIpAddressException();
}
@@ -59,7 +59,6 @@ Name::Name(const std::string &uri, uint32_t segment)
: Name(uri.c_str(), segment) {}
Name::Name(const std::string &uri) {
- name_.type = HNT_UNSPEC;
utils::StringTokenizer tokenizer(uri, "|");
std::string ip_address;
std::string seq_number;
@@ -80,9 +79,13 @@ Name::Name(const std::string &uri) {
Name::Name(const Name &name) { this->name_ = name.name_; }
+Name::~Name() {}
+
Name &Name::operator=(const Name &name) {
- if (hicn_name_copy(&this->name_, &name.name_) < 0) {
- throw errors::MalformedNameException();
+ if (this != &name) {
+ if (hicn_name_copy(&this->name_, &name.name_) < 0) {
+ throw errors::MalformedNameException();
+ }
}
return *this;
@@ -122,16 +125,20 @@ std::string Name::toString() const {
}
uint32_t Name::getHash32(bool consider_suffix) const {
- uint32_t hash;
- if (hicn_name_hash(&name_, &hash, consider_suffix) < 0) {
+ uint32_t hash = _hicn_name_get_hash(&name_, consider_suffix);
+ if (hash < 0) {
throw errors::RuntimeException("Error computing the hash of the name!");
}
return hash;
}
-void Name::clear() { name_.type = HNT_UNSPEC; };
+void Name::clear() { std::memset(&name_, 0, sizeof(name_)); };
-Name::Type Name::getType() const { return name_.type; }
+Name::Type Name::getType() const {
+ int family;
+ hicn_name_get_family(&name_, &family);
+ return family == AF_INET ? Name::Type::V4 : Name::Type::V6;
+}
uint32_t Name::getSuffix() const {
uint32_t ret = 0;
@@ -142,49 +149,32 @@ uint32_t Name::getSuffix() const {
return ret;
}
-Name &Name::setSuffix(uint32_t seq_number) {
- if (hicn_name_set_seq_number(&name_, seq_number) < 0) {
- throw errors::RuntimeException(
- "Impossible to set the sequence number to the name.");
+Name &Name::setSuffix(hicn_name_suffix_t suffix) {
+ if (hicn_name_set_suffix(&name_, suffix) < 0) {
+ throw errors::RuntimeException("Impossible to set name suffix.");
}
return *this;
}
-std::shared_ptr<Sockaddr> Name::getAddress() const {
- Sockaddr *ret = nullptr;
-
- switch (name_.type) {
- case HNT_CONTIGUOUS_V4:
- case HNT_IOV_V4:
- ret = (Sockaddr *)new Sockaddr4;
- break;
- case HNT_CONTIGUOUS_V6:
- case HNT_IOV_V6:
- ret = (Sockaddr *)new Sockaddr6;
- break;
- default:
- throw errors::MalformedNameException();
- }
-
- if (hicn_name_to_sockaddr_address((hicn_name_t *)&name_, ret) < 0) {
- throw errors::MalformedNameException();
- }
-
- return std::shared_ptr<Sockaddr>(ret);
-}
-
-ip_prefix_t Name::toIpAddress() const {
- ip_prefix_t ret;
+hicn_ip_prefix_t Name::toIpAddress() const {
+ hicn_ip_prefix_t ret;
std::memset(&ret, 0, sizeof(ret));
- if (hicn_name_to_ip_prefix(&name_, &ret) < 0) {
+ if (hicn_name_to_hicn_ip_prefix(&name_, &ret) < 0) {
throw errors::InvalidIpAddressException();
}
return ret;
}
+std::string Name::getPrefix() const {
+ char prefix[MAXSZ_HICN_NAME];
+ hicn_name_no_suffix_snprintf(prefix, MAXSZ_HICN_NAME, &name_);
+
+ return std::string(prefix);
+}
+
int Name::getAddressFamily() const {
int ret = 0;
@@ -195,8 +185,8 @@ int Name::getAddressFamily() const {
return ret;
}
-void Name::copyToDestination(uint8_t *destination, bool include_suffix) const {
- if (hicn_name_copy_to_destination(destination, &name_, include_suffix) < 0) {
+void Name::copyPrefixToDestination(uint8_t *destination) const {
+ if (hicn_name_copy_prefix_to_destination(destination, &name_) < 0) {
throw errors::RuntimeException(
"Impossibe to copy the name into the "
"provided destination");
diff --git a/libtransport/src/core/packet.cc b/libtransport/src/core/packet.cc
index 51337201f..bcd0b8498 100644
--- a/libtransport/src/core/packet.cc
+++ b/libtransport/src/core/packet.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#include <glog/logging.h>
#include <hicn/transport/auth/crypto_hash.h>
+#include <hicn/transport/core/global_object_pool.h>
#include <hicn/transport/core/packet.h>
#include <hicn/transport/errors/malformed_packet_exception.h>
#include <hicn/transport/utils/hash.h>
@@ -23,6 +24,7 @@ extern "C" {
#ifndef _WIN32
TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat")
#endif
+#include <hicn/base.h>
#include <hicn/error.h>
}
@@ -32,64 +34,70 @@ namespace core {
const core::Name Packet::base_name("0::0|0");
-Packet::Packet(Format format, std::size_t additional_header_size)
+Packet::Packet(Type type, Format format, std::size_t additional_header_size)
: utils::MemBuf(utils::MemBuf(CREATE, 2048)),
- packet_start_(reinterpret_cast<hicn_header_t *>(writableData())),
- header_offset_(0),
- format_(format),
payload_type_(PayloadType::UNSPECIFIED) {
- setFormat(format_, additional_header_size);
+ /*
+ * We define the format and the storage area of the packet buffer we
+ * manipulate
+ */
+ setFormat(format);
+ setBuffer();
+ initializeType(type); // type requires packet format
+ initialize(additional_header_size);
}
-Packet::Packet(MemBuf &&buffer)
- : utils::MemBuf(std::move(buffer)),
- packet_start_(reinterpret_cast<hicn_header_t *>(writableData())),
- header_offset_(0),
- format_(getFormatFromBuffer(data(), length())),
- payload_type_(PayloadType::UNSPECIFIED) {}
-
Packet::Packet(CopyBufferOp, const uint8_t *buffer, std::size_t size)
: utils::MemBuf(COPY_BUFFER, buffer, size),
- packet_start_(reinterpret_cast<hicn_header_t *>(writableData())),
- header_offset_(0),
- format_(getFormatFromBuffer(data(), length())),
- payload_type_(PayloadType::UNSPECIFIED) {}
+ payload_type_(PayloadType::UNSPECIFIED) {
+ setBuffer();
+ analyze();
+}
Packet::Packet(WrapBufferOp, uint8_t *buffer, std::size_t length,
std::size_t size)
: utils::MemBuf(WRAP_BUFFER, buffer, length, size),
- packet_start_(reinterpret_cast<hicn_header_t *>(writableData())),
- header_offset_(0),
- format_(getFormatFromBuffer(this->data(), this->length())),
- payload_type_(PayloadType::UNSPECIFIED) {}
+ payload_type_(PayloadType::UNSPECIFIED) {
+ setBuffer();
+ analyze();
+}
-Packet::Packet(CreateOp, uint8_t *buffer, std::size_t length, std::size_t size,
- Format format, std::size_t additional_header_size)
+Packet::Packet(CreateOp, Type type, uint8_t *buffer, std::size_t length,
+ std::size_t size, Format format,
+ std::size_t additional_header_size)
: utils::MemBuf(WRAP_BUFFER, buffer, length, size),
- packet_start_(reinterpret_cast<hicn_header_t *>(writableData())),
- header_offset_(0),
- format_(format),
payload_type_(PayloadType::UNSPECIFIED) {
clear();
- setFormat(format_, additional_header_size);
+ setType(type);
+ setFormat(format);
+ setBuffer();
+ initialize(additional_header_size);
}
-Packet::Packet(const Packet &other)
- : utils::MemBuf(other),
- packet_start_(reinterpret_cast<hicn_header_t *>(writableData())),
- header_offset_(other.header_offset_),
- format_(other.format_),
- payload_type_(PayloadType::UNSPECIFIED) {}
+Packet::Packet(MemBuf &&buffer)
+ : utils::MemBuf(std::move(buffer)),
+ payload_type_(PayloadType::UNSPECIFIED) {
+ setBuffer();
+ analyze();
+}
+
+/*
+ * In the two following constructors, we inherit the pkbuf and only need to
+ * recompute the pointer fields, aka the buffer.
+ */
Packet::Packet(Packet &&other)
: utils::MemBuf(std::move(other)),
- packet_start_(other.packet_start_),
- header_offset_(other.header_offset_),
- format_(other.format_),
+ pkbuf_(other.pkbuf_),
+ payload_type_(PayloadType::UNSPECIFIED) {
+ hicn_packet_reset(&other.pkbuf_);
+}
+
+Packet::Packet(const Packet &other)
+ : utils::MemBuf(other),
+ pkbuf_(other.pkbuf_),
payload_type_(PayloadType::UNSPECIFIED) {
- other.packet_start_ = nullptr;
- other.format_ = HF_UNSPEC;
- other.header_offset_ = 0;
+ setBuffer();
}
Packet::~Packet() {}
@@ -97,86 +105,82 @@ Packet::~Packet() {}
Packet &Packet::operator=(const Packet &other) {
if (this != &other) {
*this = other;
- packet_start_ = reinterpret_cast<hicn_header_t *>(writableData());
+ setBuffer();
}
return *this;
}
-std::size_t Packet::getHeaderSizeFromBuffer(Format format,
- const uint8_t *buffer) {
- size_t header_length;
-
- if (hicn_packet_get_header_length(format, (hicn_header_t *)buffer,
- &header_length) < 0) {
- throw errors::MalformedPacketException();
- }
-
- return header_length;
+std::shared_ptr<utils::MemBuf> Packet::acquireMemBufReference() {
+ return std::static_pointer_cast<utils::MemBuf>(shared_from_this());
}
-bool Packet::isInterest(const uint8_t *buffer) {
- bool is_interest = false;
-
- if (TRANSPORT_EXPECT_FALSE(hicn_packet_test_ece(HF_INET6_TCP,
- (const hicn_header_t *)buffer,
- &is_interest) < 0)) {
- throw errors::RuntimeException(
- "Impossible to retrieve ece flag from packet");
- }
+Packet::Format Packet::getFormat() const {
+ return hicn_packet_get_format(&pkbuf_);
+}
- return !is_interest;
+void Packet::setFormat(Packet::Format format) {
+ hicn_packet_set_format(&pkbuf_, format);
}
-void Packet::setFormat(Packet::Format format,
- std::size_t additional_header_size) {
- format_ = format;
- if (hicn_packet_init_header(format_, packet_start_) < 0) {
+void Packet::initialize(std::size_t additional_header_size) {
+ if (hicn_packet_init_header(&pkbuf_, additional_header_size) < 0) {
throw errors::RuntimeException("Unexpected error initializing the packet.");
}
- auto header_size = getHeaderSizeFromFormat(format_);
- assert(header_size <= tailroom());
+ auto header_size = getHeaderSizeFromFormat(getFormat());
+ DCHECK(header_size <= tailroom());
append(header_size);
-
- assert(additional_header_size <= tailroom());
+ DCHECK(additional_header_size <= tailroom());
append(additional_header_size);
+}
- header_offset_ = length();
+void Packet::analyze() {
+ if (hicn_packet_analyze(&pkbuf_) < 0)
+ throw errors::MalformedPacketException();
}
-bool Packet::isInterest() { return Packet::isInterest(data()); }
+Packet::Type Packet::getType() const { return hicn_packet_get_type(&pkbuf_); }
-std::size_t Packet::getPayloadSizeFromBuffer(Format format,
- const uint8_t *buffer) {
- std::size_t payload_length;
- if (TRANSPORT_EXPECT_FALSE(
- hicn_packet_get_payload_length(format, (hicn_header_t *)buffer,
- &payload_length) < 0)) {
- throw errors::MalformedPacketException();
- }
+void Packet::initializeType(Packet::Type type) {
+ hicn_packet_initialize_type(&pkbuf_, type);
+}
- return payload_length;
+void Packet::setType(Packet::Type type) { hicn_packet_set_type(&pkbuf_, type); }
+
+void Packet::setBuffer() {
+ hicn_packet_set_buffer(&pkbuf_, writableData(),
+ this->capacity() - this->headroom(), this->length());
}
-std::size_t Packet::payloadSize() const {
- std::size_t ret = 0;
+PayloadType Packet::getPayloadType() const {
+ if (payload_type_ == PayloadType::UNSPECIFIED) {
+ hicn_payload_type_t ret;
- if (length()) {
- ret = getPayloadSizeFromBuffer(format_,
- reinterpret_cast<uint8_t *>(packet_start_));
+ if (hicn_packet_get_payload_type(&pkbuf_, &ret) < 0) {
+ throw errors::RuntimeException("Impossible to retrieve payload type.");
+ }
+
+ payload_type_ = (PayloadType)ret;
}
- return ret;
+ return payload_type_;
}
-std::size_t Packet::headerSize() const {
- if (header_offset_ == 0 && length()) {
- const_cast<Packet *>(this)->header_offset_ = getHeaderSizeFromBuffer(
- format_, reinterpret_cast<uint8_t *>(packet_start_));
+Packet &Packet::setPayloadType(PayloadType payload_type) {
+ if (hicn_packet_set_payload_type(&pkbuf_, hicn_payload_type_t(payload_type)) <
+ 0) {
+ throw errors::RuntimeException("Error setting payload type of the packet.");
}
- return header_offset_;
+ payload_type_ = payload_type;
+ return *this;
+}
+
+std::unique_ptr<utils::MemBuf> Packet::getPayload() const {
+ auto ret = clone();
+ ret->trimStart(headerSize());
+ return ret;
}
Packet &Packet::appendPayload(std::unique_ptr<utils::MemBuf> &&payload) {
@@ -196,70 +200,71 @@ Packet &Packet::appendPayload(const uint8_t *buffer, std::size_t length) {
return *this;
}
-std::unique_ptr<utils::MemBuf> Packet::getPayload() const {
- auto ret = clone();
- ret->trimStart(headerSize());
- return ret;
+std::size_t Packet::headerSize() const {
+ std::size_t len;
+ hicn_packet_get_header_len(&pkbuf_, &len);
+ return len;
}
-Packet &Packet::updateLength(std::size_t length) {
- std::size_t total_length = length;
+std::size_t Packet::payloadSize() const {
+ std::size_t len;
+ hicn_packet_get_payload_len(&pkbuf_, &len);
+ return len;
+}
- const utils::MemBuf *current = this;
- do {
- total_length += current->length();
- current = current->next();
- } while (current != this);
+auth::CryptoHash Packet::computeDigest(auth::CryptoHashType algorithm) const {
+ auth::CryptoHash hash;
+ hash.setType(algorithm);
- total_length -= headerSize();
+ // Copy IP+TCP/ICMP header before zeroing them
+ u8 header_copy[HICN_HDRLEN_MAX];
+ size_t header_len;
+ hicn_packet_save_header(&pkbuf_, header_copy, &header_len,
+ /* copy_ah */ false);
+ const_cast<Packet *>(this)->resetForHash();
- if (hicn_packet_set_payload_length(format_, packet_start_, total_length) <
- 0) {
- throw errors::RuntimeException("Error setting the packet payload.");
- }
+ hash.computeDigest(this);
+ hicn_packet_load_header(&pkbuf_, header_copy, header_len);
- return *this;
+ return hash;
}
-PayloadType Packet::getPayloadType() const {
- if (payload_type_ == PayloadType::UNSPECIFIED) {
- hicn_payload_type_t ret;
- if (hicn_packet_get_payload_type(packet_start_, &ret) < 0) {
- throw errors::RuntimeException("Impossible to retrieve payload type.");
- }
+void Packet::reset() {
+ clear();
+ hicn_packet_reset(&pkbuf_);
+ setBuffer();
+ payload_type_ = PayloadType::UNSPECIFIED;
+ name_.clear();
- payload_type_ = (PayloadType)ret;
+ if (isChained()) {
+ separateChain(next(), prev());
}
-
- return payload_type_;
}
-Packet &Packet::setPayloadType(PayloadType payload_type) {
- if (hicn_packet_set_payload_type(packet_start_,
- hicn_payload_type_t(payload_type)) < 0) {
- throw errors::RuntimeException("Error setting payload type of the packet.");
- }
+bool Packet::isInterest() {
+ return hicn_packet_get_type(&pkbuf_) == HICN_PACKET_TYPE_INTEREST;
+}
- payload_type_ = payload_type;
+Packet &Packet::updateLength(std::size_t length) {
+ std::size_t total_length = length;
- return *this;
-}
+ const utils::MemBuf *current = this;
+ do {
+ total_length += current->length();
+ current = current->next();
+ } while (current != this);
-Packet::Format Packet::getFormat() const {
- /**
- * We check packet start because after a movement it will result in a nullptr
- */
- if (format_ == HF_UNSPEC && length()) {
- if (hicn_packet_get_format(packet_start_, &format_) < 0) {
- LOG(ERROR) << "Unexpected packet format HF_UNSPEC.";
- }
+ if (hicn_packet_set_len(&pkbuf_, total_length) < 0) {
+ throw errors::RuntimeException("Error setting the packet length.");
}
- return format_;
-}
+ total_length -= headerSize();
-std::shared_ptr<utils::MemBuf> Packet::acquireMemBufReference() {
- return std::static_pointer_cast<utils::MemBuf>(shared_from_this());
+ if (hicn_packet_set_payload_length(&pkbuf_, total_length) < 0) {
+ throw errors::RuntimeException("Error setting the packet payload length.");
+ }
+
+ return *this;
}
void Packet::dump() const {
@@ -274,364 +279,282 @@ void Packet::dump() const {
} while (current != this);
}
-void Packet::dump(uint8_t *buffer, std::size_t length) {
- hicn_packet_dump(buffer, length);
-}
+void Packet::setChecksum() {
+ size_t header_len = 0;
+ if (hicn_packet_get_header_len(&pkbuf_, &header_len) < 0)
+ throw errors::RuntimeException(
+ "Error setting getting packet header length.");
-void Packet::setSignatureSize(std::size_t size_bytes) {
- if (!authenticationHeader()) {
- throw errors::RuntimeException("Packet without Authentication Header.");
- }
+ uint16_t partial_csum = csum(data() + header_len, length() - header_len, 0);
- int ret = hicn_packet_set_signature_size(format_, packet_start_, size_bytes);
+ for (utils::MemBuf *current = next(); current != this;
+ current = current->next()) {
+ partial_csum = csum(current->data(), current->length(), ~partial_csum);
+ }
- if (ret < 0) {
- throw errors::RuntimeException("Error setting signature size.");
+ if (hicn_packet_compute_header_checksum(&pkbuf_, partial_csum) < 0) {
+ throw errors::MalformedPacketException();
}
}
-void Packet::setSignatureSizeGap(std::size_t size_bytes) {
- if (!authenticationHeader()) {
- throw errors::RuntimeException("Packet without Authentication Header.");
- }
+bool Packet::checkIntegrity() const {
+ size_t header_len = 0;
+ if (hicn_packet_get_header_len(&pkbuf_, &header_len) < 0)
+ throw errors::RuntimeException(
+ "Error setting getting packet header length.");
- int ret = hicn_packet_set_signature_gap(format_, packet_start_,
- (uint8_t)size_bytes);
+ uint16_t partial_csum = csum(data() + header_len, length() - header_len, 0);
- if (ret < 0) {
- throw errors::RuntimeException("Error setting signature size.");
+ for (const utils::MemBuf *current = next(); current != this;
+ current = current->next()) {
+ partial_csum = csum(current->data(), current->length(), ~partial_csum);
+ }
+
+ if (hicn_packet_check_integrity_no_payload(&pkbuf_, partial_csum) < 0) {
+ return false;
}
+
+ return true;
}
-uint8_t *Packet::getSignature() const {
- if (!authenticationHeader()) {
+bool Packet::hasAH() const { return HICN_PACKET_FORMAT_IS_AH(getFormat()); }
+
+utils::MemBuf::Ptr Packet::getSignature() const {
+ if (!hasAH()) {
throw errors::RuntimeException("Packet without Authentication Header.");
}
uint8_t *signature;
- int ret = hicn_packet_get_signature(format_, packet_start_, &signature);
+ int ret = hicn_packet_get_signature(&pkbuf_, &signature);
if (ret < 0) {
throw errors::RuntimeException("Error getting signature.");
}
- return signature;
+ utils::MemBuf::Ptr membuf = PacketManager<>::getInstance().getMemBuf();
+ membuf->append(getSignatureFieldSize());
+ memcpy(membuf->writableData(), signature, getSignatureFieldSize());
+
+ return membuf;
}
-void Packet::setSignatureTimestamp(const uint64_t &timestamp) {
- if (!authenticationHeader()) {
+std::size_t Packet::getSignatureFieldSize() const {
+ if (!hasAH()) {
throw errors::RuntimeException("Packet without Authentication Header.");
}
- int ret =
- hicn_packet_set_signature_timestamp(format_, packet_start_, timestamp);
-
+ size_t field_size;
+ int ret = hicn_packet_get_signature_size(&pkbuf_, &field_size);
if (ret < 0) {
- throw errors::RuntimeException("Error setting the signature timestamp.");
+ throw errors::RuntimeException("Error reading signature field size");
}
+ return field_size;
}
-uint64_t Packet::getSignatureTimestamp() const {
- if (!authenticationHeader()) {
+std::size_t Packet::getSignatureSize() const {
+ if (!hasAH()) {
throw errors::RuntimeException("Packet without Authentication Header.");
}
- uint64_t return_value;
- int ret = hicn_packet_get_signature_timestamp(format_, packet_start_,
- &return_value);
-
+ size_t padding;
+ int ret = hicn_packet_get_signature_padding(&pkbuf_, &padding);
if (ret < 0) {
- throw errors::RuntimeException("Error getting the signature timestamp.");
+ throw errors::RuntimeException("Error reading signature padding");
+ }
+
+ size_t size = getSignatureFieldSize() - padding;
+ if (size < 0) {
+ throw errors::RuntimeException("Error reading signature size");
}
- return return_value;
+ return size;
}
-void Packet::setValidationAlgorithm(
- const auth::CryptoSuite &validation_algorithm) {
- if (!authenticationHeader()) {
+uint64_t Packet::getSignatureTimestamp() const {
+ if (!hasAH()) {
throw errors::RuntimeException("Packet without Authentication Header.");
}
- int ret = hicn_packet_set_validation_algorithm(format_, packet_start_,
- uint8_t(validation_algorithm));
-
+ uint64_t timestamp;
+ int ret = hicn_packet_get_signature_timestamp(&pkbuf_, &timestamp);
if (ret < 0) {
- throw errors::RuntimeException("Error setting the validation algorithm.");
+ throw errors::RuntimeException("Error getting the signature timestamp.");
}
+ return timestamp;
}
-auth::CryptoSuite Packet::getValidationAlgorithm() const {
- if (!authenticationHeader()) {
+auth::KeyId Packet::getKeyId() const {
+ if (!hasAH()) {
throw errors::RuntimeException("Packet without Authentication Header.");
}
- uint8_t return_value;
- int ret = hicn_packet_get_validation_algorithm(format_, packet_start_,
- &return_value);
-
+ auth::KeyId key_id;
+ int ret = hicn_packet_get_key_id(&pkbuf_, &key_id.first, &key_id.second);
if (ret < 0) {
throw errors::RuntimeException("Error getting the validation algorithm.");
}
-
- return auth::CryptoSuite(return_value);
+ return key_id;
}
-void Packet::setKeyId(const auth::KeyId &key_id) {
- if (!authenticationHeader()) {
+auth::CryptoSuite Packet::getValidationAlgorithm() const {
+ if (!hasAH()) {
throw errors::RuntimeException("Packet without Authentication Header.");
}
- int ret = hicn_packet_set_key_id(format_, packet_start_, key_id.first);
-
+ uint8_t return_value;
+ int ret = hicn_packet_get_validation_algorithm(&pkbuf_, &return_value);
if (ret < 0) {
- throw errors::RuntimeException("Error setting the key id.");
+ throw errors::RuntimeException("Error getting the validation algorithm.");
}
+ return auth::CryptoSuite(return_value);
}
-auth::KeyId Packet::getKeyId() const {
- if (!authenticationHeader()) {
+void Packet::setSignature(const utils::MemBuf::Ptr &signature) {
+ if (!hasAH()) {
throw errors::RuntimeException("Packet without Authentication Header.");
}
- auth::KeyId return_value;
- int ret = hicn_packet_get_key_id(format_, packet_start_, &return_value.first,
- &return_value.second);
-
+ uint8_t *signature_field;
+ int ret = hicn_packet_get_signature(&pkbuf_, &signature_field);
if (ret < 0) {
- throw errors::RuntimeException("Error getting the validation algorithm.");
+ throw errors::RuntimeException("Error getting signature.");
}
-
- return return_value;
-}
-
-auth::CryptoHash Packet::computeDigest(auth::CryptoHashType algorithm) const {
- auth::CryptoHash hash;
- hash.setType(algorithm);
-
- // Copy IP+TCP/ICMP header before zeroing them
- hicn_header_t header_copy;
-
- hicn_packet_copy_header(format_, packet_start_, &header_copy, false);
-
- const_cast<Packet *>(this)->resetForHash();
-
- hash.computeDigest(this);
- hicn_packet_copy_header(format_, &header_copy, packet_start_, false);
-
- return hash;
+ memcpy(signature_field, signature->data(), signature->length());
}
-bool Packet::checkIntegrity() const {
- uint16_t partial_csum =
- csum(data() + HICN_V6_TCP_HDRLEN, length() - HICN_V6_TCP_HDRLEN, 0);
-
- for (const utils::MemBuf *current = next(); current != this;
- current = current->next()) {
- partial_csum = csum(current->data(), current->length(), ~partial_csum);
- }
-
- if (hicn_packet_check_integrity_no_payload(format_, packet_start_,
- partial_csum) < 0) {
- return false;
+void Packet::setSignatureFieldSize(std::size_t size) {
+ if (!hasAH()) {
+ throw errors::RuntimeException("Packet without Authentication Header.");
}
- return true;
-}
-
-void Packet::prependPayload(const uint8_t **buffer, std::size_t *size) {
- auto last = prev();
- auto to_copy = std::min(*size, last->tailroom());
- std::memcpy(last->writableTail(), *buffer, to_copy);
- last->append(to_copy);
- *size -= to_copy;
- *buffer += to_copy;
-}
-
-Packet &Packet::setSyn() {
- if (hicn_packet_set_syn(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error setting syn bit in the packet.");
+ int ret = hicn_packet_set_signature_size(&pkbuf_, size);
+ if (ret < 0) {
+ throw errors::RuntimeException("Error setting signature size.");
}
-
- return *this;
}
-Packet &Packet::resetSyn() {
- if (hicn_packet_reset_syn(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error resetting syn bit in the packet.");
+void Packet::setSignatureSize(std::size_t size) {
+ if (!hasAH()) {
+ throw errors::RuntimeException("Packet without Authentication Header.");
}
- return *this;
-}
-
-bool Packet::testSyn() const {
- bool res = false;
- if (hicn_packet_test_syn(format_, packet_start_, &res) < 0) {
- throw errors::RuntimeException("Error testing syn bit in the packet.");
+ size_t padding = getSignatureFieldSize() - size;
+ if (padding < 0) {
+ throw errors::RuntimeException("Error setting signature padding.");
}
- return res;
-}
-
-Packet &Packet::setAck() {
- if (hicn_packet_set_ack(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error setting ack bit in the packet.");
+ int ret = hicn_packet_set_signature_padding(&pkbuf_, padding);
+ if (ret < 0) {
+ throw errors::RuntimeException("Error setting signature padding.");
}
-
- return *this;
}
-Packet &Packet::resetAck() {
- if (hicn_packet_reset_ack(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error resetting ack bit in the packet.");
+void Packet::setSignatureTimestamp(const uint64_t &timestamp) {
+ if (!hasAH()) {
+ throw errors::RuntimeException("Packet without Authentication Header.");
}
- return *this;
-}
-
-bool Packet::testAck() const {
- bool res = false;
- if (hicn_packet_test_ack(format_, packet_start_, &res) < 0) {
- throw errors::RuntimeException("Error testing ack bit in the packet.");
+ int ret = hicn_packet_set_signature_timestamp(&pkbuf_, timestamp);
+ if (ret < 0) {
+ throw errors::RuntimeException("Error setting the signature timestamp.");
}
-
- return res;
}
-Packet &Packet::setRst() {
- if (hicn_packet_set_rst(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error setting rst bit in the packet.");
+void Packet::setKeyId(const auth::KeyId &key_id) {
+ if (!hasAH()) {
+ throw errors::RuntimeException("Packet without Authentication Header.");
}
- return *this;
-}
-
-Packet &Packet::resetRst() {
- if (hicn_packet_reset_rst(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error resetting rst bit in the packet.");
+ int ret = hicn_packet_set_key_id(&pkbuf_, key_id.first, key_id.second);
+ if (ret < 0) {
+ throw errors::RuntimeException("Error setting the key id.");
}
-
- return *this;
}
-bool Packet::testRst() const {
- bool res = false;
- if (hicn_packet_test_rst(format_, packet_start_, &res) < 0) {
- throw errors::RuntimeException("Error testing rst bit in the packet.");
+void Packet::setValidationAlgorithm(
+ const auth::CryptoSuite &validation_algorithm) {
+ if (!hasAH()) {
+ throw errors::RuntimeException("Packet without Authentication Header.");
}
- return res;
-}
-
-Packet &Packet::setFin() {
- if (hicn_packet_set_fin(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error setting fin bit in the packet.");
+ int ret = hicn_packet_set_validation_algorithm(&pkbuf_,
+ uint8_t(validation_algorithm));
+ if (ret < 0) {
+ throw errors::RuntimeException("Error setting the validation algorithm.");
}
-
- return *this;
}
-Packet &Packet::resetFin() {
- if (hicn_packet_reset_fin(format_, packet_start_) < 0) {
- throw errors::RuntimeException("Error resetting fin bit in the packet.");
- }
-
- return *this;
+Packet::Format Packet::toAHFormat(const Format &format) {
+ return hicn_get_ah_format(format);
}
-bool Packet::testFin() const {
- bool res = false;
- if (hicn_packet_test_fin(format_, packet_start_, &res) < 0) {
- throw errors::RuntimeException("Error testing fin bit in the packet.");
- }
+Packet::Format Packet::getFormatFromBuffer(const uint8_t *buffer,
+ std::size_t length) {
+ hicn_packet_buffer_t pkbuf;
+ /* un-const to be able to use pkbuf API */
+ hicn_packet_set_buffer(&pkbuf, (uint8_t *)buffer, length, length);
+ if (hicn_packet_analyze(&pkbuf) < 0) throw errors::MalformedPacketException();
- return res;
+ return hicn_packet_get_format(&pkbuf);
}
-Packet &Packet::resetFlags() {
- resetSyn();
- resetAck();
- resetRst();
- resetFin();
-
- return *this;
+std::size_t Packet::getHeaderSizeFromFormat(Format format,
+ std::size_t signature_size) {
+ std::size_t header_length;
+ hicn_packet_get_header_length_from_format(format, &header_length);
+ int is_ah = HICN_PACKET_FORMAT_IS_AH(format);
+ return is_ah * (header_length + signature_size) + (!is_ah) * header_length;
}
-std::string Packet::printFlags() const {
- std::string flags;
-
- if (testSyn()) {
- flags += "S";
- }
-
- if (testAck()) {
- flags += "A";
- }
+std::size_t Packet::getHeaderSizeFromBuffer(const uint8_t *buffer,
+ std::size_t length) {
+ size_t header_length;
- if (testRst()) {
- flags += "R";
- }
+ hicn_packet_buffer_t pkbuf;
+ /* un-const to be able to use pkbuf API */
+ hicn_packet_set_buffer(&pkbuf, (uint8_t *)buffer, length, length);
+ if (hicn_packet_analyze(&pkbuf) < 0) throw errors::MalformedPacketException();
- if (testFin()) {
- flags += "F";
- }
+ int rc = hicn_packet_get_header_len(&pkbuf, &header_length);
+ if (TRANSPORT_EXPECT_FALSE(rc < 0)) throw errors::MalformedPacketException();
- return flags;
+ return header_length;
}
-Packet &Packet::setSrcPort(uint16_t srcPort) {
- if (hicn_packet_set_src_port(format_, packet_start_, srcPort) < 0) {
- throw errors::RuntimeException("Error setting source port in the packet.");
- }
+std::size_t Packet::getPayloadSizeFromBuffer(const uint8_t *buffer,
+ std::size_t length) {
+ std::size_t payload_length;
- return *this;
-}
+ hicn_packet_buffer_t pkbuf;
+ /* un-const to be able to use pkbuf API */
+ hicn_packet_set_buffer(&pkbuf, (uint8_t *)buffer, length, length);
+ if (hicn_packet_analyze(&pkbuf) < 0) throw errors::MalformedPacketException();
-Packet &Packet::setDstPort(uint16_t dstPort) {
- if (hicn_packet_set_dst_port(format_, packet_start_, dstPort) < 0) {
- throw errors::RuntimeException(
- "Error setting destination port in the packet.");
- }
+ int rc = hicn_packet_get_payload_len(&pkbuf, &payload_length);
+ if (TRANSPORT_EXPECT_FALSE(rc < 0)) throw errors::MalformedPacketException();
- return *this;
+ return payload_length;
}
-uint16_t Packet::getSrcPort() const {
- uint16_t port = 0;
-
- if (hicn_packet_get_src_port(format_, packet_start_, &port) < 0) {
- throw errors::RuntimeException("Error reading source port in the packet.");
- }
-
- return port;
+void Packet::dump(uint8_t *buffer, std::size_t length) {
+ hicn_packet_dump(buffer, length);
}
-uint16_t Packet::getDstPort() const {
- uint16_t port = 0;
-
- if (hicn_packet_get_dst_port(format_, packet_start_, &port) < 0) {
- throw errors::RuntimeException(
- "Error reading destination port in the packet.");
- }
-
- return port;
+void Packet::prependPayload(const uint8_t **buffer, std::size_t *size) {
+ auto last = prev();
+ auto to_copy = std::min(*size, last->tailroom());
+ std::memcpy(last->writableTail(), *buffer, to_copy);
+ last->append(to_copy);
+ *size -= to_copy;
+ *buffer += to_copy;
}
-Packet &Packet::setTTL(uint8_t hops) {
- if (hicn_packet_set_hoplimit(packet_start_, hops) < 0) {
- throw errors::RuntimeException("Error setting TTL.");
- }
-
- return *this;
+void Packet::saveHeader(u8 *header, size_t *header_len) {
+ hicn_packet_save_header(&pkbuf_, header, header_len, /* copy_ah */ false);
}
-uint8_t Packet::getTTL() const {
- uint8_t hops = 0;
- if (hicn_packet_get_hoplimit(packet_start_, &hops) < 0) {
- throw errors::RuntimeException("Error reading TTL.");
- }
-
- return hops;
+void Packet::loadHeader(u8 *header, size_t header_len) {
+ hicn_packet_load_header(&pkbuf_, header, header_len);
}
} // end namespace core
diff --git a/libtransport/src/core/pending_interest.cc b/libtransport/src/core/pending_interest.cc
deleted file mode 100644
index fbe98cab5..000000000
--- a/libtransport/src/core/pending_interest.cc
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <core/pending_interest.h>
-
-namespace transport {
-
-namespace core {
-
-PendingInterest::PendingInterest()
- : interest_(nullptr, nullptr),
- timer_(),
- on_content_object_callback_(),
- on_interest_timeout_callback_() {}
-
-PendingInterest::PendingInterest(Interest::Ptr &&interest,
- std::unique_ptr<asio::steady_timer> &&timer)
- : interest_(std::move(interest)),
- timer_(std::move(timer)),
- on_content_object_callback_(),
- on_interest_timeout_callback_() {}
-
-PendingInterest::PendingInterest(
- Interest::Ptr &&interest, OnContentObjectCallback &&on_content_object,
- OnInterestTimeoutCallback &&on_interest_timeout,
- std::unique_ptr<asio::steady_timer> &&timer)
- : interest_(std::move(interest)),
- timer_(std::move(timer)),
- on_content_object_callback_(std::move(on_content_object)),
- on_interest_timeout_callback_(std::move(on_interest_timeout)) {}
-
-PendingInterest::~PendingInterest() {}
-
-void PendingInterest::cancelTimer() { timer_->cancel(); }
-
-void PendingInterest::setInterest(Interest::Ptr &&interest) {
- interest_ = std::move(interest);
-}
-
-Interest::Ptr &&PendingInterest::getInterest() { return std::move(interest_); }
-
-const OnContentObjectCallback &PendingInterest::getOnDataCallback() const {
- return on_content_object_callback_;
-}
-
-void PendingInterest::setOnContentObjectCallback(
- OnContentObjectCallback &&on_content_object) {
- PendingInterest::on_content_object_callback_ = on_content_object;
-}
-
-const OnInterestTimeoutCallback &PendingInterest::getOnTimeoutCallback() const {
- return on_interest_timeout_callback_;
-}
-
-void PendingInterest::setOnTimeoutCallback(
- OnInterestTimeoutCallback &&on_interest_timeout) {
- PendingInterest::on_interest_timeout_callback_ = on_interest_timeout;
-}
-
-} // end namespace core
-
-} // end namespace transport
diff --git a/libtransport/src/core/pending_interest.h b/libtransport/src/core/pending_interest.h
index 99a8bd327..f49348bac 100644
--- a/libtransport/src/core/pending_interest.h
+++ b/libtransport/src/core/pending_interest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -42,70 +42,60 @@ class PendingInterest {
public:
using Ptr = utils::ObjectPool<PendingInterest>::Ptr;
- // PendingInterest()
- // : interest_(nullptr, nullptr),
- // timer_(),
- // on_content_object_callback_(),
- // on_interest_timeout_callback_() {}
-
- PendingInterest(Interest::Ptr &&interest,
- std::unique_ptr<asio::steady_timer> &&timer)
- : interest_(std::move(interest)),
- timer_(std::move(timer)),
- on_content_object_callback_(),
- on_interest_timeout_callback_() {}
-
- PendingInterest(Interest::Ptr &&interest,
+
+ PendingInterest(asio::io_service &io_service, const Interest::Ptr &interest)
+ : interest_(interest), timer_(io_service) {}
+
+ PendingInterest(asio::io_service &io_service, const Interest::Ptr &interest,
OnContentObjectCallback &&on_content_object,
- OnInterestTimeoutCallback &&on_interest_timeout,
- std::unique_ptr<asio::steady_timer> &&timer)
- : interest_(std::move(interest)),
- timer_(std::move(timer)),
+ OnInterestTimeoutCallback &&on_interest_timeout)
+ : interest_(interest),
+ timer_(io_service),
on_content_object_callback_(std::move(on_content_object)),
on_interest_timeout_callback_(std::move(on_interest_timeout)) {}
~PendingInterest() = default;
template <typename Handler>
- TRANSPORT_ALWAYS_INLINE void startCountdown(Handler &&cb) {
- timer_->expires_from_now(
- std::chrono::milliseconds(interest_->getLifetime()));
- timer_->async_wait(std::forward<Handler &&>(cb));
+ void startCountdown(uint32_t lifetime, Handler &&cb) {
+ timer_.expires_from_now(std::chrono::milliseconds(lifetime));
+ timer_.async_wait(std::forward<Handler>(cb));
}
- TRANSPORT_ALWAYS_INLINE void cancelTimer() { timer_->cancel(); }
-
- TRANSPORT_ALWAYS_INLINE Interest::Ptr &&getInterest() {
- return std::move(interest_);
+ void cancelTimer() {
+ try {
+ timer_.cancel();
+ } catch (asio::system_error &e) {
+ // do nothing
+ }
}
- TRANSPORT_ALWAYS_INLINE void setInterest(Interest::Ptr &interest) {
- interest_ = interest;
- }
+ Interest::Ptr &&getInterest() { return std::move(interest_); }
+
+ const Interest::Ptr &getInterestReference() const { return interest_; }
+
+ void setInterest(const Interest::Ptr &interest) { interest_ = interest; }
- TRANSPORT_ALWAYS_INLINE const OnContentObjectCallback &getOnDataCallback()
- const {
+ const OnContentObjectCallback &getOnDataCallback() const {
return on_content_object_callback_;
}
- TRANSPORT_ALWAYS_INLINE void setOnContentObjectCallback(
- OnContentObjectCallback &&on_content_object) {
- PendingInterest::on_content_object_callback_ = on_content_object;
+ void setOnContentObjectCallback(OnContentObjectCallback &&on_content_object) {
+ PendingInterest::on_content_object_callback_ = std::move(on_content_object);
}
- TRANSPORT_ALWAYS_INLINE const OnInterestTimeoutCallback &
- getOnTimeoutCallback() const {
+ const OnInterestTimeoutCallback &getOnTimeoutCallback() const {
return on_interest_timeout_callback_;
}
- TRANSPORT_ALWAYS_INLINE void setOnTimeoutCallback(
- OnInterestTimeoutCallback &&on_interest_timeout) {
- PendingInterest::on_interest_timeout_callback_ = on_interest_timeout;
+ void setOnTimeoutCallback(OnInterestTimeoutCallback &&on_interest_timeout) {
+ PendingInterest::on_interest_timeout_callback_ =
+ std::move(on_interest_timeout);
}
private:
Interest::Ptr interest_;
- std::unique_ptr<asio::steady_timer> timer_;
+ asio::steady_timer timer_;
OnContentObjectCallback on_content_object_callback_;
OnInterestTimeoutCallback on_interest_timeout_callback_;
};
diff --git a/libtransport/src/core/portal.cc b/libtransport/src/core/portal.cc
index c4c0cf8ba..72b6a6f37 100644
--- a/libtransport/src/core/portal.cc
+++ b/libtransport/src/core/portal.cc
@@ -43,12 +43,14 @@ std::string Portal::io_module_path_ = defaultIoModule();
std::string Portal::defaultIoModule() {
using namespace std::placeholders;
GlobalConfiguration::getInstance().registerConfigurationParser(
- io_module_section,
+ IoModuleConfiguration::section,
std::bind(&Portal::parseIoModuleConfiguration, _1, _2));
GlobalConfiguration::getInstance().registerConfigurationGetter(
- io_module_section, std::bind(&Portal::getModuleConfiguration, _1, _2));
+ IoModuleConfiguration::section,
+ std::bind(&Portal::getModuleConfiguration, _1, _2));
GlobalConfiguration::getInstance().registerConfigurationSetter(
- io_module_section, std::bind(&Portal::setModuleConfiguration, _1, _2));
+ IoModuleConfiguration::section,
+ std::bind(&Portal::setModuleConfiguration, _1, _2));
// return default
conf_.name = default_module;
@@ -57,7 +59,7 @@ std::string Portal::defaultIoModule() {
void Portal::getModuleConfiguration(ConfigurationObject& object,
std::error_code& ec) {
- assert(object.getKey() == io_module_section);
+ DCHECK(object.getKey() == IoModuleConfiguration::section);
auto conf = dynamic_cast<const IoModuleConfiguration&>(object);
conf = conf_;
@@ -103,7 +105,7 @@ std::string getIoModulePath(const std::string& name,
void Portal::setModuleConfiguration(const ConfigurationObject& object,
std::error_code& ec) {
- assert(object.getKey() == io_module_section);
+ DCHECK(object.getKey() == IoModuleConfiguration::section);
const IoModuleConfiguration& conf =
dynamic_cast<const IoModuleConfiguration&>(object);
@@ -147,4 +149,4 @@ void Portal::parseIoModuleConfiguration(const libconfig::Setting& io_config,
}
} // namespace core
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/libtransport/src/core/portal.h b/libtransport/src/core/portal.h
index f6a9ce85b..c4ba096b9 100644
--- a/libtransport/src/core/portal.h
+++ b/libtransport/src/core/portal.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#pragma once
+#include <core/global_workers.h>
#include <core/pending_interest.h>
#include <glog/logging.h>
#include <hicn/transport/config.h>
@@ -28,6 +29,7 @@
#include <hicn/transport/interfaces/global_conf_interface.h>
#include <hicn/transport/interfaces/portal.h>
#include <hicn/transport/portability/portability.h>
+#include <hicn/transport/utils/event_thread.h>
#include <hicn/transport/utils/fixed_block_allocator.h>
#include <future>
@@ -54,11 +56,11 @@ class HandlerMemory {
HandlerMemory(const HandlerMemory &) = delete;
HandlerMemory &operator=(const HandlerMemory &) = delete;
- TRANSPORT_ALWAYS_INLINE void *allocate(std::size_t size) {
+ void *allocate(std::size_t /* size */) {
return utils::FixedBlockAllocator<128, 8192>::getInstance().allocateBlock();
}
- TRANSPORT_ALWAYS_INLINE void deallocate(void *pointer) {
+ void deallocate(void *pointer) {
utils::FixedBlockAllocator<128, 8192>::getInstance().deallocateBlock(
pointer);
}
@@ -69,13 +71,9 @@ class HandlerMemory {
HandlerMemory(const HandlerMemory &) = delete;
HandlerMemory &operator=(const HandlerMemory &) = delete;
- TRANSPORT_ALWAYS_INLINE void *allocate(std::size_t size) {
- return ::operator new(size);
- }
+ void *allocate(std::size_t size) { return ::operator new(size); }
- TRANSPORT_ALWAYS_INLINE void deallocate(void *pointer) {
- ::operator delete(pointer);
- }
+ void deallocate(void *pointer) { ::operator delete(pointer); }
#endif
};
@@ -92,21 +90,19 @@ class HandlerAllocator {
HandlerAllocator(const HandlerAllocator<U> &other) noexcept
: memory_(other.memory_) {}
- TRANSPORT_ALWAYS_INLINE bool operator==(
- const HandlerAllocator &other) const noexcept {
+ bool operator==(const HandlerAllocator &other) const noexcept {
return &memory_ == &other.memory_;
}
- TRANSPORT_ALWAYS_INLINE bool operator!=(
- const HandlerAllocator &other) const noexcept {
+ bool operator!=(const HandlerAllocator &other) const noexcept {
return &memory_ != &other.memory_;
}
- TRANSPORT_ALWAYS_INLINE T *allocate(std::size_t n) const {
+ T *allocate(std::size_t n) const {
return static_cast<T *>(memory_.allocate(sizeof(T) * n));
}
- TRANSPORT_ALWAYS_INLINE void deallocate(T *p, std::size_t /*n*/) const {
+ void deallocate(T *p, std::size_t /*n*/) const {
return memory_.deallocate(p);
}
@@ -135,7 +131,7 @@ class CustomAllocatorHandler {
}
template <typename... Args>
- void operator()(Args &&... args) {
+ void operator()(Args &&...args) {
handler_(std::forward<Args>(args)...);
}
@@ -151,49 +147,16 @@ inline CustomAllocatorHandler<Handler> makeCustomAllocatorHandler(
return CustomAllocatorHandler<Handler>(m, h);
}
-class Pool {
- public:
- Pool(asio::io_service &io_service) : io_service_(io_service) {
- increasePendingInterestPool();
- }
-
- TRANSPORT_ALWAYS_INLINE void increasePendingInterestPool() {
- // Create pool of pending interests to reuse
- for (uint32_t i = 0; i < pit_size; i++) {
- pending_interests_pool_.add(new PendingInterest(
- Interest::Ptr(nullptr),
- std::make_unique<asio::steady_timer>(io_service_)));
- }
- }
- PendingInterest::Ptr getPendingInterest() {
- auto res = pending_interests_pool_.get();
- while (TRANSPORT_EXPECT_FALSE(!res.first)) {
- increasePendingInterestPool();
- res = pending_interests_pool_.get();
- }
-
- return std::move(res.second);
- }
-
- private:
- utils::ObjectPool<PendingInterest> pending_interests_pool_;
- asio::io_service &io_service_;
-};
-
} // namespace portal_details
class PortalConfiguration;
-using PendingInterestHashTable =
- std::unordered_map<uint32_t, PendingInterest::Ptr>;
-
-using interface::BindConfig;
+using PendingInterestHashTable = std::unordered_map<uint32_t, PendingInterest>;
/**
* Portal is a opaque class which is used for sending/receiving interest/data
- * packets over multiple kind of connector. The connector itself is defined by
- * the template ForwarderInt, which is resolved at compile time. It is then not
- * possible to decide at runtime what the connector will be.
+ * packets over multiple kind of io_modules. The io_module itself is an external
+ * module loaded at runtime.
*
* The tasks performed by portal are the following:
* - Sending/Receiving Interest packets
@@ -210,83 +173,117 @@ using interface::BindConfig;
* users of this class.
*/
-class Portal {
- public:
- using ConsumerCallback = interface::Portal::ConsumerCallback;
- using ProducerCallback = interface::Portal::ProducerCallback;
+class Portal : public ::utils::NonCopyable,
+ public std::enable_shared_from_this<Portal> {
+ private:
+ Portal() : Portal(GlobalWorkers::getInstance().getWorker()) {}
+ Portal(::utils::EventThread &worker)
+ : io_module_(nullptr),
+ worker_(worker),
+ app_name_("libtransport_application"),
+ transport_callback_(nullptr),
+ is_consumer_(false) {}
+
+ public:
+ using TransportCallback = interface::Portal::TransportCallback;
friend class PortalConfiguration;
- Portal() : Portal(internal_io_service_) {}
+ static std::shared_ptr<Portal> createShared() {
+ return std::shared_ptr<Portal>(new Portal());
+ }
- Portal(asio::io_service &io_service)
- : io_module_(nullptr, [](IoModule *module) { IoModule::unload(module); }),
- io_service_(io_service),
- packet_pool_(io_service),
- app_name_("libtransport_application"),
- consumer_callback_(nullptr),
- producer_callback_(nullptr),
- is_consumer_(false) {
- /**
- * This workaroung allows to initialize memory for packet buffers *before*
- * any static variables that may be initialized in the io_modules. In this
- * way static variables in modules will be destroyed before the packet
- * memory.
- */
- PacketManager<>::getInstance();
+ static std::shared_ptr<Portal> createShared(::utils::EventThread &worker) {
+ return std::shared_ptr<Portal>(new Portal(worker));
}
+
+ bool isConnected() const { return io_module_.get() != nullptr; }
+
/**
- * Set the consumer callback.
+ * Set the transport callback. Must be called from the same worker thread.
*
- * @param consumer_callback - The pointer to the ConsumerCallback object.
+ * @param consumer_callback - The pointer to the TransportCallback object.
*/
- void setConsumerCallback(ConsumerCallback *consumer_callback) {
- consumer_callback_ = consumer_callback;
+ void registerTransportCallback(TransportCallback *transport_callback) {
+ DCHECK(std::this_thread::get_id() == worker_.getThreadId());
+ transport_callback_ = transport_callback;
}
/**
- * Set the producer callback.
- *
- * @param producer_callback - The pointer to the ProducerCallback object.
+ * Unset the consumer callback. Must be called from the same worker thread.
*/
- void setProducerCallback(ProducerCallback *producer_callback) {
- producer_callback_ = producer_callback;
+ void unregisterTransportCallback() {
+ DCHECK(std::this_thread::get_id() == worker_.getThreadId());
+ transport_callback_ = nullptr;
}
/**
- * Specify the output interface to use. This method will be useful in a future
- * scenario where the library will be able to forward packets without
+ * Specify the output interface to use. This method will be useful in a
+ * future scenario where the library will be able to forward packets without
* connecting to a local forwarder. Now it is not used.
*
* @param output_interface - The output interface to use for
* forwarding/receiving packets.
*/
- TRANSPORT_ALWAYS_INLINE void setOutputInterface(
- const std::string &output_interface) {
- io_module_->setOutputInterface(output_interface);
+ void setOutputInterface(const std::string &output_interface) {
+ if (io_module_) {
+ io_module_->setOutputInterface(output_interface);
+ }
}
/**
* Connect the transport to the local hicn forwarder.
*
- * @param is_consumer - Boolean specifying if the application on top of portal
- * is a consumer or a producer.
+ * @param is_consumer - Boolean specifying if the application on top of
+ * portal is a consumer or a producer.
*/
- TRANSPORT_ALWAYS_INLINE void connect(bool is_consumer = true) {
- if (!io_module_) {
- pending_interest_hash_table_.reserve(portal_details::pit_size);
- io_module_.reset(IoModule::load(io_module_path_.c_str()));
-
- CHECK(io_module_);
-
- io_module_->init(std::bind(&Portal::processIncomingMessages, this,
- std::placeholders::_1, std::placeholders::_2,
- std::placeholders::_3),
- std::bind(&Portal::setLocalRoutes, this), io_service_,
- app_name_);
- io_module_->connect(is_consumer);
- is_consumer_ = is_consumer;
+ void connect(bool is_consumer = true) {
+ if (isConnected()) {
+ return;
}
+
+ worker_.addAndWaitForExecution([this, is_consumer]() {
+ if (!io_module_) {
+ pending_interest_hash_table_.reserve(portal_details::pit_size);
+ io_module_.reset(IoModule::load(io_module_path_.c_str()));
+
+ CHECK(io_module_);
+
+ std::weak_ptr<Portal> self(shared_from_this());
+
+ io_module_->init(
+ [self](Connector *c, const std::vector<utils::MemBuf::Ptr> &buffers,
+ const std::error_code &ec) {
+ if (auto ptr = self.lock()) {
+ ptr->processIncomingMessages(c, buffers, ec);
+ }
+ },
+ [self](Connector *c, const std::error_code &ec) {
+ if (!ec) {
+ return;
+ }
+ auto ptr = self.lock();
+ if (ptr && ptr->transport_callback_) {
+ ptr->transport_callback_->onError(ec);
+ }
+ },
+ [self]([[maybe_unused]] Connector *c) { /* Nothing to do here */ },
+ [self](Connector *c, const std::error_code &ec) {
+ auto ptr = self.lock();
+ if (ptr) {
+ if (ec && ptr->transport_callback_) {
+ ptr->transport_callback_->onError(ec);
+ return;
+ }
+ ptr->setLocalRoutes();
+ }
+ },
+ worker_.getIoService(), app_name_);
+
+ io_module_->connect(is_consumer);
+ is_consumer_ = is_consumer;
+ }
+ });
}
/**
@@ -295,18 +292,13 @@ class Portal {
~Portal() { killConnection(); }
/**
- * Compute name hash
- */
- TRANSPORT_ALWAYS_INLINE uint32_t getHash(const Name &name) {
- return name.getHash32(false) + name.getSuffix();
- }
-
- /**
* Check if there is already a pending interest for a given name.
*
* @param name - The interest name.
*/
- TRANSPORT_ALWAYS_INLINE bool interestIsPending(const Name &name) {
+ bool interestIsPending(const Name &name) {
+ DCHECK(std::this_thread::get_id() == worker_.getThreadId());
+
auto it = pending_interest_hash_table_.find(getHash(name));
if (it != pending_interest_hash_table_.end()) {
return true;
@@ -316,58 +308,53 @@ class Portal {
}
/**
- * Send an interest through to the local forwarder.
+ * @brief Add interest to PIT
*
- * @param interest - The pointer to the interest. The ownership of the
- * interest is transferred by the caller to portal.
- *
- * @param on_content_object_callback - If the caller wishes to use a different
- * callback to be called for this interest, it can set this parameter.
- * Otherwise ConsumerCallback::onContentObject will be used.
- *
- * @param on_interest_timeout_callback - If the caller wishes to use a
- * different callback to be called for this interest, it can set this
- * parameter. Otherwise ConsumerCallback::onTimeout will be used.
*/
- TRANSPORT_ALWAYS_INLINE void sendInterest(
- Interest::Ptr &&interest,
+ void addInterestToPIT(
+ const Interest::Ptr &interest, uint32_t lifetime,
OnContentObjectCallback &&on_content_object_callback = UNSET_CALLBACK,
OnInterestTimeoutCallback &&on_interest_timeout_callback =
UNSET_CALLBACK) {
- // Send it
- interest->encodeSuffixes();
- io_module_->send(*interest);
-
uint32_t initial_hash = interest->getName().getHash32(false);
auto hash = initial_hash + interest->getName().getSuffix();
uint32_t seq = interest->getName().getSuffix();
- uint32_t *suffix = interest->firstSuffix();
- auto n_suffixes = interest->numberOfSuffixes();
+ const uint32_t *suffix = interest->firstSuffix() != nullptr
+ ? interest->firstSuffix() + 1
+ : nullptr;
+ auto n_suffixes =
+ interest->numberOfSuffixes() > 0 ? interest->numberOfSuffixes() - 1 : 0;
uint32_t counter = 0;
// Set timers
do {
- auto pending_interest = packet_pool_.getPendingInterest();
- pending_interest->setInterest(interest);
- pending_interest->setOnContentObjectCallback(
+ auto pend_int = pending_interest_hash_table_.try_emplace(
+ hash, worker_.getIoService(), interest);
+ PendingInterest &pending_interest = pend_int.first->second;
+ if (!pend_int.second) {
+ // element was already in map
+ pend_int.first->second.cancelTimer();
+ pending_interest.setInterest(interest);
+ }
+
+ pending_interest.setOnContentObjectCallback(
std::move(on_content_object_callback));
- pending_interest->setOnTimeoutCallback(
+ pending_interest.setOnTimeoutCallback(
std::move(on_interest_timeout_callback));
- pending_interest->startCountdown(
- portal_details::makeCustomAllocatorHandler(
- async_callback_memory_,
- std::bind(&Portal::timerHandler, this, std::placeholders::_1,
- hash, seq)));
-
- auto it = pending_interest_hash_table_.find(hash);
- if (it != pending_interest_hash_table_.end()) {
- it->second->cancelTimer();
-
- // Get reference to interest packet in order to have it destroyed.
- auto _int = it->second->getInterest();
- it->second = std::move(pending_interest);
- } else {
- pending_interest_hash_table_[hash] = std::move(pending_interest);
+ if (is_consumer_) {
+ auto self = weak_from_this();
+ pending_interest.startCountdown(
+ lifetime, portal_details::makeCustomAllocatorHandler(
+ async_callback_memory_,
+ [self, hash, seq](const std::error_code &ec) {
+ if (TRANSPORT_EXPECT_FALSE(ec.operator bool())) {
+ return;
+ }
+
+ if (auto ptr = self.lock()) {
+ ptr->timerHandler(hash, seq);
+ }
+ }));
}
if (suffix) {
@@ -375,224 +362,261 @@ class Portal {
seq = *suffix;
suffix++;
}
-
} while (counter++ < n_suffixes);
}
- /**
- * Handler fot the timer set when the interest is sent.
- *
- * @param ec - Error code which says whether the timer expired or has been
- * canceled upon data packet reception.
- *
- * @param hash - The index of the interest in the pending interest hash table.
- */
- TRANSPORT_ALWAYS_INLINE void timerHandler(const std::error_code &ec,
- uint32_t hash, uint32_t seq) {
- bool is_stopped = io_service_.stopped();
- if (TRANSPORT_EXPECT_FALSE(is_stopped)) {
- return;
- }
+ void matchContentObjectInPIT(ContentObject &content_object) {
+ uint32_t hash = getHash(content_object.getName());
+ auto it = pending_interest_hash_table_.find(hash);
+ if (it != pending_interest_hash_table_.end()) {
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Found pending interest.";
+
+ PendingInterest &pend_interest = it->second;
+ pend_interest.cancelTimer();
+ auto _int = pend_interest.getInterest();
+ auto callback = pend_interest.getOnDataCallback();
+ pending_interest_hash_table_.erase(it);
- if (TRANSPORT_EXPECT_TRUE(!ec)) {
- PendingInterestHashTable::iterator it =
- pending_interest_hash_table_.find(hash);
- if (it != pending_interest_hash_table_.end()) {
- PendingInterest::Ptr ptr = std::move(it->second);
- pending_interest_hash_table_.erase(it);
- auto _int = ptr->getInterest();
- Name &name = const_cast<Name &>(_int->getName());
- name.setSuffix(seq);
-
- if (ptr->getOnTimeoutCallback() != UNSET_CALLBACK) {
- ptr->on_interest_timeout_callback_(_int, name);
- } else if (consumer_callback_) {
- consumer_callback_->onTimeout(_int, name);
+ if (is_consumer_) {
+ // Send object is for the app
+ if (callback != UNSET_CALLBACK) {
+ callback(*_int, content_object);
+ } else if (transport_callback_) {
+ transport_callback_->onContentObject(*_int, content_object);
}
+ } else {
+ // Send content object to the network
+ io_module_->send(content_object);
}
+ } else if (is_consumer_) {
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "No interest pending for received content object.";
}
}
/**
- * Register a producer name to the local forwarder and optionally set the
- * content store size in a per-face manner.
+ * Send an interest through to the local forwarder.
*
- * @param config - The configuration for the local forwarder binding.
- */
- TRANSPORT_ALWAYS_INLINE void bind(const BindConfig &config) {
- assert(io_module_);
- io_module_->setContentStoreSize(config.csReserved());
- served_namespaces_.push_back(config.prefix());
- setLocalRoutes();
- }
-
- /**
- * Start the event loop. This function blocks here and calls the callback set
- * by the application upon interest/data received or timeout.
+ * @param interest - The pointer to the interest. The ownership of the
+ * interest is transferred by the caller to portal.
+ *
+ * @param on_content_object_callback - If the caller wishes to use a
+ * different callback to be called for this interest, it can set this
+ * parameter. Otherwise ConsumerCallback::onContentObject will be used.
+ *
+ * @param on_interest_timeout_callback - If the caller wishes to use a
+ * different callback to be called for this interest, it can set this
+ * parameter. Otherwise ConsumerCallback::onTimeout will be used.
*/
- TRANSPORT_ALWAYS_INLINE void runEventsLoop() {
- if (io_service_.stopped()) {
- io_service_.reset(); // ensure that run()/poll() will do some work
- }
+ void sendInterest(
+ Interest::Ptr &interest, uint32_t lifetime,
+ OnContentObjectCallback &&on_content_object_callback = UNSET_CALLBACK,
+ OnInterestTimeoutCallback &&on_interest_timeout_callback =
+ UNSET_CALLBACK) {
+ DCHECK(std::this_thread::get_id() == worker_.getThreadId());
- io_service_.run();
+ addInterestToPIT(interest, lifetime, std::move(on_content_object_callback),
+ std::move(on_interest_timeout_callback));
+ interest->serializeSuffixes();
+ io_module_->send(*interest);
}
/**
- * Run one event and return.
+ * Handler fot the timer set when the interest is sent.
+ *
+ * @param ec - Error code which says whether the timer expired or has been
+ * canceled upon data packet reception.
+ *
+ * @param hash - The index of the interest in the pending interest hash
+ * table.
*/
- TRANSPORT_ALWAYS_INLINE void runOneEvent() {
- if (io_service_.stopped()) {
- io_service_.reset(); // ensure that run()/poll() will do some work
- }
+ void timerHandler(uint32_t hash, uint32_t seq) {
+ PendingInterestHashTable::iterator it =
+ pending_interest_hash_table_.find(hash);
+ if (it != pending_interest_hash_table_.end()) {
+ PendingInterest &pend_interest = it->second;
+ auto _int = pend_interest.getInterest();
+ auto callback = pend_interest.getOnTimeoutCallback();
+ pending_interest_hash_table_.erase(it);
+ Name &name = const_cast<Name &>(_int->getName());
+ name.setSuffix(seq);
- io_service_.run_one();
+ if (callback != UNSET_CALLBACK) {
+ callback(_int, name);
+ } else if (transport_callback_) {
+ transport_callback_->onTimeout(_int, name);
+ }
+ }
}
/**
- * Send a data packet to the local forwarder. As opposite to sendInterest, the
- * ownership of the content object is not transferred to the portal.
+ * Send a data packet to the local forwarder.
*
* @param content_object - The data packet.
*/
- TRANSPORT_ALWAYS_INLINE void sendContentObject(
- ContentObject &content_object) {
- io_module_->send(content_object);
+ void sendContentObject(ContentObject &content_object) {
+ DCHECK(io_module_);
+ DCHECK(std::this_thread::get_id() == worker_.getThreadId());
+ matchContentObjectInPIT(content_object);
}
/**
- * Stop the event loop, canceling all the pending events in the event queue.
- *
- * Beware that stopping the event loop DOES NOT disconnect the transport from
- * the local forwarder, the connector underneath will stay connected.
+ * Disconnect the transport from the local forwarder.
*/
- TRANSPORT_ALWAYS_INLINE void stopEventsLoop() {
- if (!io_service_.stopped()) {
- io_service_.dispatch([this]() {
- clear();
- io_service_.stop();
- });
+ void killConnection() {
+ if (TRANSPORT_EXPECT_TRUE(io_module_ != nullptr)) {
+ io_module_->closeConnection();
}
}
/**
- * Disconnect the transport from the local forwarder.
+ * Clear the pending interest hash table.
*/
- TRANSPORT_ALWAYS_INLINE void killConnection() {
- io_module_->closeConnection();
+ void clear() {
+ worker_.tryRunHandlerNow([self{shared_from_this()}]() { self->doClear(); });
}
/**
- * Clear the pending interest hash table.
+ * Get a reference to the io_service object.
*/
- TRANSPORT_ALWAYS_INLINE void clear() {
- if (!io_service_.stopped()) {
- io_service_.dispatch(std::bind(&Portal::doClear, this));
- } else {
- doClear();
- }
- }
+ utils::EventThread &getThread() { return worker_; }
/**
- * Remove one pending interest.
+ * Register a route to the local forwarder.
*/
- TRANSPORT_ALWAYS_INLINE void clearOne(const Name &name) {
- if (!io_service_.stopped()) {
- io_service_.dispatch(std::bind(&Portal::doClearOne, this, name));
- } else {
- doClearOne(name);
- }
+ void registerRoute(const Prefix &prefix) {
+ std::weak_ptr<Portal> self = shared_from_this();
+ worker_.tryRunHandlerNow([self, prefix]() {
+ if (auto ptr = self.lock()) {
+ auto ret = ptr->served_namespaces_.insert(prefix);
+ if (ret.second && ptr->io_module_ && ptr->io_module_->isConnected()) {
+ ptr->io_module_->registerRoute(prefix);
+ }
+ }
+ });
}
/**
- * Get a reference to the io_service object.
+ * Send a MAP-Me update to traverse NATs.
*/
- TRANSPORT_ALWAYS_INLINE asio::io_service &getIoService() {
- return io_service_;
+ TRANSPORT_ALWAYS_INLINE void sendMapme() {
+ if (io_module_->isConnected()) {
+ io_module_->sendMapme();
+ }
}
/**
- * Register a route to the local forwarder.
+ * set forwarding strategy
*/
- TRANSPORT_ALWAYS_INLINE void registerRoute(Prefix &prefix) {
- served_namespaces_.push_back(prefix);
+ TRANSPORT_ALWAYS_INLINE void setForwardingStrategy(Prefix &prefix,
+ std::string &strategy) {
if (io_module_->isConnected()) {
- io_module_->registerRoute(prefix);
+ io_module_->setForwardingStrategy(prefix, strategy);
}
}
/**
* Check if the transport is connected to a forwarder or not
*/
- TRANSPORT_ALWAYS_INLINE bool isConnectedToFwd() {
+ bool isConnectedToFwd() {
std::string mod = io_module_path_.substr(0, io_module_path_.find("."));
if (mod == "forwarder_module") return false;
return true;
}
+ auto &getServedNamespaces() { return served_namespaces_; }
+
private:
/**
+ * Compute name hash
+ */
+ uint32_t getHash(const Name &name) {
+ return name.getHash32(false) + name.getSuffix();
+ }
+
+ /**
* Clear the pending interest hash table.
*/
- TRANSPORT_ALWAYS_INLINE void doClear() {
+ void doClear() {
for (auto &pend_interest : pending_interest_hash_table_) {
- pend_interest.second->cancelTimer();
-
- // Get interest packet from pending interest and do nothing with it. It
- // will get destroyed as it goes out of scope.
- auto _int = pend_interest.second->getInterest();
+ pend_interest.second.cancelTimer();
}
pending_interest_hash_table_.clear();
}
- /**
- * Remove one pending interest.
- */
- TRANSPORT_ALWAYS_INLINE void doClearOne(const Name &name) {
- auto it = pending_interest_hash_table_.find(getHash(name));
-
- if (it != pending_interest_hash_table_.end()) {
- it->second->cancelTimer();
+ void dumpPIT() {
+ std::vector<Name> sorted_elements;
+ for (const auto &[key, value] : pending_interest_hash_table_) {
+ sorted_elements.push_back(value.getInterestReference()->getName());
+ }
- // Get interest packet from pending interest and do nothing with it. It
- // will get destroyed as it goes out of scope.
- auto _int = it->second->getInterest();
+ std::sort(sorted_elements.begin(), sorted_elements.end(),
+ [](const Name &a, const Name &b) {
+ return a.getSuffix() < b.getSuffix();
+ });
- pending_interest_hash_table_.erase(it);
+ for (auto &elt : sorted_elements) {
+ LOG(INFO) << elt;
}
}
/**
- * Callback called by the underlying connector upon reception of a packet from
- * the local forwarder.
+ * Callback called by the underlying connector upon reception of a packet
+ * from the local forwarder.
*
* @param packet_buffer - The bytes of the packet.
*/
- TRANSPORT_ALWAYS_INLINE void processIncomingMessages(
- Connector *c, utils::MemBuf &buffer, const std::error_code &ec) {
- bool is_stopped = io_service_.stopped();
- if (TRANSPORT_EXPECT_FALSE(is_stopped)) {
+ void processIncomingMessages(Connector *c,
+ const std::vector<utils::MemBuf::Ptr> &buffers,
+ const std::error_code &ec) {
+ if (!transport_callback_) {
return;
}
- if (TRANSPORT_EXPECT_FALSE(io_module_->isControlMessage(buffer.data()))) {
- processControlMessage(buffer);
+ if (TRANSPORT_EXPECT_FALSE(ec.operator bool())) {
+ // Error receiving from underlying infra.
+ if (transport_callback_) {
+ transport_callback_->onError(ec);
+ }
+
return;
}
- // The buffer is a base class for an interest or a content object
- Packet &packet_buffer = static_cast<Packet &>(buffer);
+ for (auto &buffer_ptr : buffers) {
+ auto &buffer = *buffer_ptr;
- auto format = packet_buffer.getFormat();
- if (TRANSPORT_EXPECT_TRUE(_is_tcp(format))) {
- if (is_consumer_) {
- processContentObject(static_cast<ContentObject &>(packet_buffer));
- } else {
- processInterest(static_cast<Interest &>(packet_buffer));
+ if (TRANSPORT_EXPECT_FALSE(io_module_->isControlMessage(buffer))) {
+ processControlMessage(buffer);
+ return;
+ }
+
+ // The buffer is a base class for an interest or a content object
+ Packet &packet_buffer = static_cast<Packet &>(buffer);
+
+ switch (packet_buffer.getType()) {
+ case HICN_PACKET_TYPE_INTEREST:
+ if (!is_consumer_) {
+ processInterest(static_cast<Interest &>(packet_buffer));
+ } else {
+ LOG(ERROR) << "Received an Interest packet with name "
+ << packet_buffer.getName()
+ << " in a consumer transport. Ignoring it.";
+ }
+ break;
+ case HICN_PACKET_TYPE_DATA:
+ if (is_consumer_) {
+ processContentObject(static_cast<ContentObject &>(packet_buffer));
+ } else {
+ LOG(ERROR) << "Received a Data packet with name "
+ << packet_buffer.getName()
+ << " in a producer transport. Ignoring it.";
+ }
+ break;
+ default:
+ LOG(ERROR) << "Received not supported packet. Ignoring it.";
+ break;
}
- } else {
- LOG(ERROR) << "Received not supported packet. Ignoring it.";
}
}
@@ -601,19 +625,25 @@ class Portal {
* It register the prefixes in the served_namespaces_ list to the local
* forwarder.
*/
- TRANSPORT_ALWAYS_INLINE void setLocalRoutes() {
+ void setLocalRoutes() {
+ DCHECK(io_module_);
+ DCHECK(io_module_->isConnected());
+ DCHECK(std::this_thread::get_id() == worker_.getThreadId());
+
for (auto &prefix : served_namespaces_) {
- if (io_module_->isConnected()) {
- io_module_->registerRoute(prefix);
- }
+ io_module_->registerRoute(prefix);
}
}
- TRANSPORT_ALWAYS_INLINE void processInterest(Interest &interest) {
+ void processInterest(Interest &interest) {
// Interest for a producer
DLOG_IF(INFO, VLOG_IS_ON(3)) << "processInterest " << interest.getName();
- if (TRANSPORT_EXPECT_TRUE(producer_callback_ != nullptr)) {
- producer_callback_->onInterest(interest);
+
+ // Save interest in PIT
+ interest.deserializeSuffixes();
+ addInterestToPIT(interest.shared_from_this(), interest.getLifetime());
+ if (TRANSPORT_EXPECT_TRUE(transport_callback_ != nullptr)) {
+ transport_callback_->onInterest(interest);
}
}
@@ -625,57 +655,33 @@ class Portal {
*
* @param content_object - The data packet
*/
- TRANSPORT_ALWAYS_INLINE void processContentObject(
- ContentObject &content_object) {
+ void processContentObject(ContentObject &content_object) {
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "processContentObject " << content_object.getName();
- uint32_t hash = getHash(content_object.getName());
-
- auto it = pending_interest_hash_table_.find(hash);
- if (it != pending_interest_hash_table_.end()) {
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Found pending interest.";
-
- PendingInterest::Ptr interest_ptr = std::move(it->second);
- pending_interest_hash_table_.erase(it);
- interest_ptr->cancelTimer();
- auto _int = interest_ptr->getInterest();
-
- if (interest_ptr->getOnDataCallback() != UNSET_CALLBACK) {
- interest_ptr->on_content_object_callback_(*_int, content_object);
- } else if (consumer_callback_) {
- consumer_callback_->onContentObject(*_int, content_object);
- }
- } else {
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "No interest pending for received content object.";
- }
+ matchContentObjectInPIT(content_object);
}
/**
- * Process a control message. Control messages are different depending on the
- * connector, then the forwarder_interface will do the job of understanding
- * them.
+ * Process a control message. Control messages are different depending on
+ * the connector, then the forwarder_interface will do the job of
+ * understanding them.
*/
- TRANSPORT_ALWAYS_INLINE void processControlMessage(
- utils::MemBuf &packet_buffer) {
+ void processControlMessage(utils::MemBuf &packet_buffer) {
io_module_->processControlMessageReply(packet_buffer);
}
private:
portal_details::HandlerMemory async_callback_memory_;
- std::unique_ptr<IoModule, void (*)(IoModule *)> io_module_;
+ std::unique_ptr<IoModule> io_module_;
- asio::io_service &io_service_;
- asio::io_service internal_io_service_;
- portal_details::Pool packet_pool_;
+ ::utils::EventThread &worker_;
std::string app_name_;
PendingInterestHashTable pending_interest_hash_table_;
- std::list<Prefix> served_namespaces_;
+ std::set<Prefix> served_namespaces_;
- ConsumerCallback *consumer_callback_;
- ProducerCallback *producer_callback_;
+ TransportCallback *transport_callback_;
bool is_consumer_;
diff --git a/libtransport/src/core/prefix.cc b/libtransport/src/core/prefix.cc
index d598cff75..8c5b153bc 100644
--- a/libtransport/src/core/prefix.cc
+++ b/libtransport/src/core/prefix.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,8 +13,10 @@
* limitations under the License.
*/
+#include <glog/logging.h>
#include <hicn/transport/core/prefix.h>
#include <hicn/transport/errors/errors.h>
+#include <hicn/transport/portability/endianess.h>
#include <hicn/transport/utils/string_tokenizer.h>
#ifndef _WIN32
@@ -35,11 +37,7 @@ namespace transport {
namespace core {
-Prefix::Prefix() { std::memset(&ip_prefix_, 0, sizeof(ip_prefix_t)); }
-
-Prefix::Prefix(const char *prefix) : Prefix(std::string(prefix)) {}
-
-Prefix::Prefix(std::string &&prefix) : Prefix(prefix) {}
+Prefix::Prefix() { std::memset(&hicn_ip_prefix_, 0, sizeof(hicn_ip_prefix_t)); }
Prefix::Prefix(const std::string &prefix) {
utils::StringTokenizer st(prefix, "/");
@@ -56,7 +54,7 @@ Prefix::Prefix(const std::string &prefix) {
buildPrefix(ip_address, uint16_t(atoi(prefix_length.c_str())), family);
}
-Prefix::Prefix(std::string &prefix, uint16_t prefix_length) {
+Prefix::Prefix(const std::string &prefix, uint16_t prefix_length) {
int family = get_addr_family(prefix.c_str());
buildPrefix(prefix, prefix_length, family);
}
@@ -68,24 +66,28 @@ Prefix::Prefix(const core::Name &content_name, uint16_t prefix_length) {
throw errors::InvalidIpAddressException();
}
- ip_prefix_ = content_name.toIpAddress();
- ip_prefix_.len = (u8)prefix_length;
- ip_prefix_.family = family;
+ hicn_ip_prefix_ = content_name.toIpAddress();
+ hicn_ip_prefix_.len = (u8)prefix_length;
+ hicn_ip_prefix_.family = family;
}
-void Prefix::buildPrefix(std::string &prefix, uint16_t prefix_length,
+void Prefix::buildPrefix(const std::string &prefix, uint16_t prefix_length,
int family) {
if (!checkPrefixLengthAndAddressFamily(prefix_length, family)) {
throw errors::InvalidIpAddressException();
}
+ std::memset(&hicn_ip_prefix_, 0, sizeof(hicn_ip_prefix_t));
+
int ret;
switch (family) {
case AF_INET:
- ret = inet_pton(AF_INET, prefix.c_str(), ip_prefix_.address.v4.buffer);
+ ret =
+ inet_pton(AF_INET, prefix.c_str(), hicn_ip_prefix_.address.v4.buffer);
break;
case AF_INET6:
- ret = inet_pton(AF_INET6, prefix.c_str(), ip_prefix_.address.v6.buffer);
+ ret = inet_pton(AF_INET6, prefix.c_str(),
+ hicn_ip_prefix_.address.v6.buffer);
break;
default:
throw errors::InvalidIpAddressException();
@@ -95,14 +97,22 @@ void Prefix::buildPrefix(std::string &prefix, uint16_t prefix_length,
throw errors::InvalidIpAddressException();
}
- ip_prefix_.len = (u8)prefix_length;
- ip_prefix_.family = family;
+ hicn_ip_prefix_.len = (u8)prefix_length;
+ hicn_ip_prefix_.family = family;
+}
+
+bool Prefix::operator<(const Prefix &other) const {
+ return hicn_ip_prefix_cmp(&hicn_ip_prefix_, &other.hicn_ip_prefix_) < 0;
+}
+
+bool Prefix::operator==(const Prefix &other) const {
+ return hicn_ip_prefix_cmp(&hicn_ip_prefix_, &other.hicn_ip_prefix_) == 0;
}
std::unique_ptr<Sockaddr> Prefix::toSockaddr() const {
Sockaddr *ret = nullptr;
- switch (ip_prefix_.family) {
+ switch (hicn_ip_prefix_.family) {
case AF_INET6:
ret = (Sockaddr *)new Sockaddr6;
break;
@@ -113,72 +123,79 @@ std::unique_ptr<Sockaddr> Prefix::toSockaddr() const {
throw errors::InvalidIpAddressException();
}
- if (ip_prefix_to_sockaddr(&ip_prefix_, ret) < 0) {
+ if (hicn_ip_prefix_to_sockaddr(&hicn_ip_prefix_, ret) < 0) {
throw errors::InvalidIpAddressException();
}
return std::unique_ptr<Sockaddr>(ret);
}
-uint16_t Prefix::getPrefixLength() const { return ip_prefix_.len; }
+uint16_t Prefix::getPrefixLength() const { return hicn_ip_prefix_.len; }
Prefix &Prefix::setPrefixLength(uint16_t prefix_length) {
- ip_prefix_.len = (u8)prefix_length;
- return *this;
-}
-
-int Prefix::getAddressFamily() const { return ip_prefix_.family; }
+ if (!checkPrefixLengthAndAddressFamily(prefix_length,
+ hicn_ip_prefix_.family)) {
+ throw errors::InvalidIpAddressException();
+ }
-Prefix &Prefix::setAddressFamily(int address_family) {
- ip_prefix_.family = address_family;
+ hicn_ip_prefix_.len = (u8)prefix_length;
return *this;
}
+int Prefix::getAddressFamily() const { return hicn_ip_prefix_.family; }
+
std::string Prefix::getNetwork() const {
- if (!checkPrefixLengthAndAddressFamily(ip_prefix_.len, ip_prefix_.family)) {
+ if (!checkPrefixLengthAndAddressFamily(hicn_ip_prefix_.len,
+ hicn_ip_prefix_.family)) {
throw errors::InvalidIpAddressException();
}
- std::size_t size =
- ip_prefix_.family == 4 + AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN;
-
- std::string network(size, 0);
+ char buffer[INET6_ADDRSTRLEN];
- if (ip_prefix_ntop_short(&ip_prefix_, (char *)network.c_str(), size) < 0) {
+ if (hicn_ip_prefix_ntop_short(&hicn_ip_prefix_, buffer, INET6_ADDRSTRLEN) <
+ 0) {
throw errors::RuntimeException(
"Impossible to retrieve network from ip address.");
}
- return network;
+ return buffer;
}
-int Prefix::contains(const ip_address_t &content_name) const {
- int res =
- ip_address_cmp(&content_name, &(ip_prefix_.address), ip_prefix_.family);
-
- if (ip_prefix_.len != (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN_BITS
- : IPV4_ADDR_LEN_BITS)) {
- const u8 *ip_prefix_buffer =
- ip_address_get_buffer(&(ip_prefix_.address), ip_prefix_.family);
- const u8 *content_name_buffer =
- ip_address_get_buffer(&content_name, ip_prefix_.family);
- uint8_t mask = 0xFF >> (ip_prefix_.len % 8);
- mask = ~mask;
-
- res += (ip_prefix_buffer[ip_prefix_.len] & mask) ==
- (content_name_buffer[ip_prefix_.len] & mask);
+bool Prefix::contains(const hicn_ip_address_t &content_name) const {
+ uint64_t mask[2] = {0, 0};
+ auto content_name_copy = content_name;
+ auto network_copy = hicn_ip_prefix_.address;
+
+ auto prefix_length = getPrefixLength();
+ if (hicn_ip_prefix_.family == AF_INET) {
+ prefix_length += 3 * IPV4_ADDR_LEN_BITS;
}
- return res;
-}
+ if (prefix_length == 0) {
+ mask[0] = mask[1] = 0;
+ } else if (prefix_length <= 64) {
+ mask[0] = portability::host_to_net((uint64_t)(~0) << (64 - prefix_length));
+ mask[1] = 0;
+ } else if (prefix_length == 128) {
+ mask[0] = mask[1] = 0xffffffffffffffff;
+ } else {
+ prefix_length -= 64;
+ mask[0] = 0xffffffffffffffff;
+ mask[1] = portability::host_to_net((uint64_t)(~0) << (64 - prefix_length));
+ }
-int Prefix::contains(const core::Name &content_name) const {
- return contains(content_name.toIpAddress().address);
+ // Apply mask
+ content_name_copy.v6.as_u64[0] &= mask[0];
+ content_name_copy.v6.as_u64[1] &= mask[1];
+
+ network_copy.v6.as_u64[0] &= mask[0];
+ network_copy.v6.as_u64[1] &= mask[1];
+
+ return hicn_ip_address_cmp(&network_copy, &content_name_copy) == 0;
}
-Name Prefix::getName() const {
- std::string s(getNetwork());
- return Name(s);
+bool Prefix::contains(const core::Name &content_name) const {
+ return contains(content_name.toIpAddress().address);
}
/*
@@ -187,23 +204,25 @@ Name Prefix::getName() const {
*/
Name Prefix::getName(const core::Name &mask, const core::Name &components,
const core::Name &content_name) const {
- if (ip_prefix_.family != mask.getAddressFamily() ||
- ip_prefix_.family != components.getAddressFamily() ||
- ip_prefix_.family != content_name.getAddressFamily())
+ if (hicn_ip_prefix_.family != mask.getAddressFamily() ||
+ hicn_ip_prefix_.family != components.getAddressFamily() ||
+ hicn_ip_prefix_.family != content_name.getAddressFamily())
throw errors::RuntimeException(
- "Prefix, mask, components and content name are not of the same address "
- "family");
-
- ip_address_t mask_ip = mask.toIpAddress().address;
- ip_address_t component_ip = components.toIpAddress().address;
- ip_address_t name_ip = content_name.toIpAddress().address;
- const u8 *mask_ip_buffer = ip_address_get_buffer(&mask_ip, ip_prefix_.family);
+ "Prefix, mask, components and content name are not of the same"
+ "address family");
+
+ hicn_ip_address_t mask_ip = mask.toIpAddress().address;
+ hicn_ip_address_t component_ip = components.toIpAddress().address;
+ hicn_ip_address_t name_ip = content_name.toIpAddress().address;
+ const u8 *mask_ip_buffer =
+ hicn_ip_address_get_buffer(&mask_ip, hicn_ip_prefix_.family);
const u8 *component_ip_buffer =
- ip_address_get_buffer(&component_ip, ip_prefix_.family);
- u8 *name_ip_buffer =
- const_cast<u8 *>(ip_address_get_buffer(&name_ip, ip_prefix_.family));
+ hicn_ip_address_get_buffer(&component_ip, hicn_ip_prefix_.family);
+ u8 *name_ip_buffer = const_cast<u8 *>(
+ hicn_ip_address_get_buffer(&name_ip, hicn_ip_prefix_.family));
- int addr_len = ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN : IPV4_ADDR_LEN;
+ int addr_len =
+ hicn_ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN : IPV4_ADDR_LEN;
for (int i = 0; i < addr_len; i++) {
if (mask_ip_buffer[i]) {
@@ -211,108 +230,98 @@ Name Prefix::getName(const core::Name &mask, const core::Name &components,
}
}
- // if (this->contains(name_ip))
- // throw errors::RuntimeException("Mask overrides the prefix");
- return Name(ip_prefix_.family, (uint8_t *)&name_ip);
-}
-
-Name Prefix::getRandomName() const {
- ip_address_t name_ip = ip_prefix_.address;
- u8 *name_ip_buffer =
- const_cast<u8 *>(ip_address_get_buffer(&name_ip, ip_prefix_.family));
-
- int addr_len =
- (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN * 8 : IPV4_ADDR_LEN * 8) -
- ip_prefix_.len;
-
- size_t size = (size_t)ceil((float)addr_len / 8.0);
- uint8_t *buffer = (uint8_t *)malloc(sizeof(uint8_t) * size);
-
- RAND_bytes(buffer, (int)size);
-
- int j = 0;
- for (uint8_t i = (uint8_t)ceil((float)ip_prefix_.len / 8.0);
- i < (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN : IPV4_ADDR_LEN);
- i++) {
- name_ip_buffer[i] = buffer[j];
- j++;
- }
- free(buffer);
-
- return Name(ip_prefix_.family, (uint8_t *)&name_ip);
+ return Name(hicn_ip_prefix_.family, (uint8_t *)&name_ip);
}
/*
* Map a name in a different name prefix to this name prefix
*/
Name Prefix::mapName(const core::Name &content_name) const {
- if (ip_prefix_.family != content_name.getAddressFamily())
+ if (hicn_ip_prefix_.family != content_name.getAddressFamily())
throw errors::RuntimeException(
"Prefix content name are not of the same address "
"family");
- ip_address_t name_ip = content_name.toIpAddress().address;
- const u8 *ip_prefix_buffer =
- ip_address_get_buffer(&(ip_prefix_.address), ip_prefix_.family);
- u8 *name_ip_buffer =
- const_cast<u8 *>(ip_address_get_buffer(&name_ip, ip_prefix_.family));
-
- memcpy(name_ip_buffer, ip_prefix_buffer, ip_prefix_.len / 8);
-
- if (ip_prefix_.len != (ip_prefix_.family == AF_INET6 ? IPV6_ADDR_LEN_BITS
- : IPV4_ADDR_LEN_BITS)) {
- uint8_t mask = 0xFF >> (ip_prefix_.len % 8);
- name_ip_buffer[ip_prefix_.len / 8 + 1] =
- (name_ip_buffer[ip_prefix_.len / 8 + 1] & mask) |
- (ip_prefix_buffer[ip_prefix_.len / 8 + 1] & ~mask);
+ hicn_ip_address_t name_ip = content_name.toIpAddress().address;
+ const u8 *hicn_ip_prefix_buffer = hicn_ip_address_get_buffer(
+ &(hicn_ip_prefix_.address), hicn_ip_prefix_.family);
+ u8 *name_ip_buffer = const_cast<u8 *>(
+ hicn_ip_address_get_buffer(&name_ip, hicn_ip_prefix_.family));
+
+ memcpy(name_ip_buffer, hicn_ip_prefix_buffer, hicn_ip_prefix_.len / 8);
+
+ if (hicn_ip_prefix_.len != (hicn_ip_prefix_.family == AF_INET6
+ ? IPV6_ADDR_LEN_BITS
+ : IPV4_ADDR_LEN_BITS)) {
+ uint8_t mask = 0xFF >> (hicn_ip_prefix_.len % 8);
+ name_ip_buffer[hicn_ip_prefix_.len / 8 + 1] =
+ (name_ip_buffer[hicn_ip_prefix_.len / 8 + 1] & mask) |
+ (hicn_ip_prefix_buffer[hicn_ip_prefix_.len / 8 + 1] & ~mask);
}
- return Name(ip_prefix_.family, (uint8_t *)&name_ip);
+ return Name(hicn_ip_prefix_.family, (uint8_t *)&name_ip);
}
-Prefix &Prefix::setNetwork(std::string &network) {
- if (!inet_pton(AF_INET6, network.c_str(), ip_prefix_.address.v6.buffer)) {
+Prefix &Prefix::setNetwork(const std::string &network) {
+ if (hicn_ip_address_pton(network.c_str(), &hicn_ip_prefix_.address) < 0) {
throw errors::RuntimeException("The network name is not valid.");
}
return *this;
}
+Name Prefix::makeName() const { return makeNameWithIndex(0); }
+
Name Prefix::makeRandomName() const {
- srand((unsigned int)time(nullptr));
-
- if (ip_prefix_.family == AF_INET6) {
- std::default_random_engine eng((std::random_device())());
- std::uniform_int_distribution<uint32_t> idis(
- 0, std::numeric_limits<uint32_t>::max());
- uint64_t random_number = idis(eng);
-
- uint32_t hash_size_bits = IPV6_ADDR_LEN_BITS - ip_prefix_.len;
- uint64_t ip_address[2];
- memcpy(ip_address, ip_prefix_.address.v6.buffer, sizeof(uint64_t));
- memcpy(ip_address + 1, ip_prefix_.address.v6.buffer + 8, sizeof(uint64_t));
- std::string network(IPV6_ADDR_LEN * 3, 0);
-
- // Let's do the magic ;)
- int shift_size = hash_size_bits > sizeof(random_number) * 8
- ? sizeof(random_number) * 8
- : hash_size_bits;
-
- ip_address[1] >>= shift_size;
- ip_address[1] <<= shift_size;
-
- ip_address[1] |= random_number >> (sizeof(uint64_t) * 8 - shift_size);
-
- if (!inet_ntop(ip_prefix_.family, ip_address, (char *)network.c_str(),
- IPV6_ADDR_LEN * 3)) {
- throw errors::RuntimeException(
- "Impossible to retrieve network from ip address.");
- }
+ std::default_random_engine eng((std::random_device())());
+ std::uniform_int_distribution<uint32_t> idis(
+ 0, std::numeric_limits<uint32_t>::max());
+ uint64_t random_number = idis(eng);
+
+ return makeNameWithIndex(random_number);
+}
+
+Name Prefix::makeNameWithIndex(std::uint64_t index) const {
+ uint16_t prefix_length = getPrefixLength();
+
+ Name ret;
- return Name(network);
+ // Adjust prefix length depending on the address family
+ if (getAddressFamily() == AF_INET) {
+ // Sanity check
+ DCHECK(prefix_length <= 32);
+ // Convert prefix length to ip46_address_t prefix length
+ prefix_length += IPV4_ADDR_LEN_BITS * 3;
}
- return Name();
+ std::memcpy(ret.getStructReference().prefix.v6.as_u8,
+ hicn_ip_prefix_.address.v6.as_u8, sizeof(hicn_ip_address_t));
+
+ // Convert index in network byte order
+ index = portability::host_to_net(index);
+
+ // Apply mask
+ uint64_t mask;
+ if (prefix_length == 0) {
+ mask = 0;
+ } else if (prefix_length <= 64) {
+ mask = 0;
+ } else if (prefix_length == 128) {
+ mask = 0xffffffffffffffff;
+ } else {
+ prefix_length -= 64;
+ mask = portability::host_to_net((uint64_t)(~0) << (64 - prefix_length));
+ }
+
+ ret.getStructReference().prefix.v6.as_u64[1] &= mask;
+ // Eventually truncate index if too big
+ index &= ~mask;
+
+ // Apply index
+ ret.getStructReference().prefix.v6.as_u64[1] |= index;
+
+ // Done
+ return ret;
}
bool Prefix::checkPrefixLengthAndAddressFamily(uint16_t prefix_length,
@@ -332,7 +341,9 @@ bool Prefix::checkPrefixLengthAndAddressFamily(uint16_t prefix_length,
return true;
}
-const ip_prefix_t &Prefix::toIpPrefixStruct() const { return ip_prefix_; }
+const hicn_ip_prefix_t &Prefix::toIpPrefixStruct() const {
+ return hicn_ip_prefix_;
+}
} // namespace core
diff --git a/libtransport/src/core/tcp_socket_connector.cc b/libtransport/src/core/tcp_socket_connector.cc
index a30264271..7758e2cf2 100644
--- a/libtransport/src/core/tcp_socket_connector.cc
+++ b/libtransport/src/core/tcp_socket_connector.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -85,8 +85,10 @@ void TcpSocketConnector::send(const uint8_t *packet, std::size_t len,
const PacketSentCallback &packet_sent) {
if (packet_sent != 0) {
asio::async_write(socket_, asio::buffer(packet, len),
- [packet_sent](std::error_code ec,
- std::size_t /*length*/) { packet_sent(); });
+ [packet_sent](const std::error_code &ec)
+ std::size_t /*length*/) {
+ packet_sent();
+ });
} else {
if (state_ == ConnectorState::CONNECTED) {
asio::write(socket_, asio::buffer(packet, len));
@@ -151,7 +153,7 @@ void TcpSocketConnector::doWrite() {
asio::async_write(
socket_, std::move(array),
- [this, packet_store = std::move(packet_store)](std::error_code ec,
+ [this, packet_store = std::move(packet_store)](const std::error_code &ec,
std::size_t length) {
if (TRANSPORT_EXPECT_TRUE(!ec)) {
if (!output_buffer_.empty()) {
@@ -172,7 +174,7 @@ void TcpSocketConnector::doReadBody(std::size_t body_length) {
asio::async_read(
socket_, asio::buffer(read_msg_->writableTail(), body_length),
asio::transfer_exactly(body_length),
- [this](std::error_code ec, std::size_t length) {
+ [this](const std::error_code &ec, std::size_t length) {
read_msg_->append(length);
if (TRANSPORT_EXPECT_TRUE(!ec)) {
receive_callback_(std::move(read_msg_));
@@ -195,7 +197,7 @@ void TcpSocketConnector::doReadHeader() {
asio::buffer(read_msg_->writableData(),
NetworkMessage::fixed_header_length),
asio::transfer_exactly(NetworkMessage::fixed_header_length),
- [this](std::error_code ec, std::size_t length) {
+ [this](const std::error_code &ec, std::size_t length) {
if (TRANSPORT_EXPECT_TRUE(!ec)) {
read_msg_->append(NetworkMessage::fixed_header_length);
std::size_t body_length = 0;
@@ -235,7 +237,7 @@ void TcpSocketConnector::tryReconnect() {
void TcpSocketConnector::doConnect() {
asio::async_connect(
socket_, endpoint_iterator_,
- [this](std::error_code ec, tcp::resolver::iterator) {
+ [this](const std::error_code &ec, tcp::resolver::iterator) {
if (!ec) {
timer_.cancel();
state_ = ConnectorState::CONNECTED;
diff --git a/libtransport/src/core/tcp_socket_connector.h b/libtransport/src/core/tcp_socket_connector.h
index 21db8301e..2901a5c9d 100644
--- a/libtransport/src/core/tcp_socket_connector.h
+++ b/libtransport/src/core/tcp_socket_connector.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/core/udp_connector.cc b/libtransport/src/core/udp_connector.cc
new file mode 100644
index 000000000..5f620b1a8
--- /dev/null
+++ b/libtransport/src/core/udp_connector.cc
@@ -0,0 +1,371 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ */
+
+#include <core/errors.h>
+#include <core/udp_connector.h>
+#include <glog/logging.h>
+#include <hicn/transport/utils/branch_prediction.h>
+
+#include <iostream>
+#include <thread>
+#include <vector>
+
+namespace transport {
+namespace core {
+
+UdpTunnelConnector::~UdpTunnelConnector() {}
+
+void UdpTunnelConnector::connect(const std::string &hostname, uint16_t port,
+ const std::string &bind_address,
+ uint16_t bind_port) {
+ if (state_ == State::CLOSED) {
+ state_ = State::CONNECTING;
+
+ asio::ip::udp::resolver::query query(asio::ip::udp::v4(), hostname,
+ std::to_string(port));
+
+ endpoint_iterator_ = resolver_.resolve(query);
+ remote_endpoint_send_ = *endpoint_iterator_;
+ socket_->open(remote_endpoint_send_.protocol());
+
+ if (!bind_address.empty() && bind_port != 0) {
+ using namespace asio::ip;
+
+ auto address = address::from_string(bind_address);
+ if (address.is_v6()) {
+ std::error_code ec;
+ socket_->set_option(asio::ip::v6_only(false), ec);
+ // Call succeeds only on dual stack systems.
+ }
+
+ socket_->bind(udp::endpoint(address, bind_port));
+ }
+
+ remote_endpoint_ = Endpoint(remote_endpoint_send_);
+ local_endpoint_ = Endpoint(socket_->local_endpoint());
+
+ auto self = shared_from_this();
+ doConnect(self);
+ }
+}
+
+void UdpTunnelConnector::send(Packet &packet) {
+ send(packet.shared_from_this());
+}
+
+void UdpTunnelConnector::send(const utils::MemBuf::Ptr &buffer) {
+ auto self = shared_from_this();
+ io_service_.post([self, buffer]() {
+ bool write_in_progress = !self->output_buffer_.empty();
+ self->output_buffer_.push_back(std::move(buffer));
+ if (TRANSPORT_EXPECT_TRUE(self->state_ == State::CONNECTED)) {
+ if (!write_in_progress) {
+ self->doSendPacket(self);
+ }
+ } else {
+ self->data_available_ = true;
+ }
+ });
+}
+
+void UdpTunnelConnector::close() {
+ DLOG_IF(INFO, VLOG_IS_ON(2)) << "UDPTunnelConnector::close";
+ state_ = State::CLOSED;
+ bool is_socket_owned = socket_.use_count() == 1;
+ if (is_socket_owned) {
+ // Here we use a shared ptr to keep the object alive until we call the close
+ // function
+ auto self = shared_from_this();
+ io_service_.dispatch([this, self]() {
+ socket_->close();
+ // on_close_callback_(shared_from_this());
+ });
+ }
+}
+
+void UdpTunnelConnector::doSendPacket(
+ const std::shared_ptr<UdpTunnelConnector> &self) {
+#ifdef LINUX
+ send_timer_.expires_from_now(std::chrono::microseconds(50));
+ send_timer_.async_wait([self](const std::error_code &ec) {
+ if (ec) {
+ return;
+ }
+
+ self->writeHandler();
+ });
+#else
+ auto packet = output_buffer_.front().get();
+ auto array = std::vector<asio::const_buffer>();
+
+ const ::utils::MemBuf *current = packet;
+ do {
+ array.push_back(asio::const_buffer(current->data(), current->length()));
+ current = current->next();
+ } while (current != packet);
+
+ socket_->async_send(std::move(array), [this, self](const std::error_code &ec,
+ std::size_t length) {
+ if (TRANSPORT_EXPECT_TRUE(!ec)) {
+ sent_callback_(this, make_error_code(core_error::success));
+ } else if (ec.value() == static_cast<int>(std::errc::operation_canceled)) {
+ // The connection has been closed by the application.
+ return;
+ } else {
+ sendFailed();
+ sent_callback_(this, ec);
+ }
+
+ output_buffer_.pop_front();
+ if (!output_buffer_.empty()) {
+ doSendPacket(self);
+ }
+ });
+#endif
+}
+
+void UdpTunnelConnector::retryConnection() {
+ // The connection was refused. In this case let's retry to reconnect.
+ connection_reattempts_++;
+ LOG(ERROR) << "Error in UDP: Connection refused. Retrying...";
+ state_ = State::CONNECTING;
+ timer_.expires_from_now(std::chrono::milliseconds(500));
+ std::weak_ptr<UdpTunnelConnector> self = shared_from_this();
+ timer_.async_wait([self, this](const std::error_code &ec) {
+ if (ec) {
+ }
+ if (auto ptr = self.lock()) {
+ doConnect(ptr);
+ }
+ });
+ return;
+}
+
+#ifdef LINUX
+void UdpTunnelConnector::writeHandler() {
+ if (TRANSPORT_EXPECT_FALSE(state_ != State::CONNECTED)) {
+ return;
+ }
+
+ auto len = std::min(output_buffer_.size(), std::size_t(Connector::max_burst));
+
+ if (len) {
+ int m = 0;
+ for (auto &p : output_buffer_) {
+ auto packet = p.get();
+ ::utils::MemBuf *current = packet;
+ int b = 0;
+ do {
+ // array.push_back(asio::const_buffer(current->data(),
+ // current->length()));
+ tx_iovecs_[m][b].iov_base = current->writableData();
+ tx_iovecs_[m][b].iov_len = current->length();
+ current = current->next();
+ b++;
+ } while (current != packet);
+
+ tx_msgs_[m].msg_hdr.msg_iov = tx_iovecs_[m];
+ tx_msgs_[m].msg_hdr.msg_iovlen = b;
+ tx_msgs_[m].msg_hdr.msg_name = remote_endpoint_send_.data();
+ tx_msgs_[m].msg_hdr.msg_namelen = remote_endpoint_send_.size();
+ m++;
+
+ if (--len == 0) {
+ break;
+ }
+ }
+
+ int retval = sendmmsg(socket_->native_handle(), tx_msgs_, m, MSG_DONTWAIT);
+ if (retval > 0) {
+ while (retval--) {
+ output_buffer_.pop_front();
+ }
+ } else if (errno != EWOULDBLOCK && errno != EAGAIN) { // NOSONAR
+ LOG(ERROR) << "Error sending messages: " << strerror(errno);
+ sent_callback_(this, make_error_code(core_error::send_failed));
+ return;
+ }
+ }
+
+ if (!output_buffer_.empty()) {
+ send_timer_.expires_from_now(std::chrono::microseconds(50));
+ std::weak_ptr<UdpTunnelConnector> self = shared_from_this();
+ send_timer_.async_wait([self](const std::error_code &ec) {
+ if (ec) {
+ return;
+ }
+ if (auto ptr = self.lock()) {
+ ptr->writeHandler();
+ }
+ });
+ } else {
+ sent_callback_(this, make_error_code(core_error::success));
+ }
+}
+
+void UdpTunnelConnector::readHandler(const std::error_code &ec) {
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "UdpTunnelConnector receive packet";
+
+ if (TRANSPORT_EXPECT_TRUE(!ec)) {
+ if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
+ if (current_position_ == 0) {
+ for (int i = 0; i < max_burst; i++) {
+ auto read_buffer = getRawBuffer();
+ rx_iovecs_[i][0].iov_base = read_buffer.first;
+ rx_iovecs_[i][0].iov_len = read_buffer.second;
+ rx_msgs_[i].msg_hdr.msg_iov = rx_iovecs_[i];
+ rx_msgs_[i].msg_hdr.msg_iovlen = 1;
+ }
+ }
+
+ int res = recvmmsg(socket_->native_handle(), rx_msgs_ + current_position_,
+ max_burst - current_position_, MSG_DONTWAIT, nullptr);
+ if (res < 0) {
+ if (errno == EWOULDBLOCK || errno == EAGAIN) { // NOSONAR
+ // Try again later
+ return;
+ }
+
+ if (errno == ECONNREFUSED &&
+ connection_reattempts_ < max_reconnection_reattempts) {
+ retryConnection();
+ return;
+ }
+
+ LOG(ERROR) << "Error receiving messages! " << strerror(errno) << " "
+ << res;
+ std::vector<utils::MemBuf::Ptr> v;
+ auto ec = make_error_code(core_error::receive_failed);
+
+ receive_callback_(this, v, ec);
+ return;
+ }
+
+ std::vector<utils::MemBuf::Ptr> v;
+ v.reserve(res);
+ for (int i = 0; i < res; i++) {
+ auto packet = getPacketFromBuffer(
+ reinterpret_cast<uint8_t *>(
+ rx_msgs_[current_position_].msg_hdr.msg_iov[0].iov_base),
+ rx_msgs_[current_position_].msg_len);
+ receiveSuccess(*packet);
+ v.push_back(std::move(packet));
+ ++current_position_;
+ }
+
+ receive_callback_(this, v, make_error_code(core_error::success));
+
+ doRecvPacket();
+ } else {
+ LOG(ERROR) << "Error in UDP: Receiving packets from a not "
+ "connected socket.";
+ }
+ } else if (ec.value() == static_cast<int>(std::errc::operation_canceled)) {
+ LOG(ERROR) << "The connection has been closed by the application.";
+ return;
+ } else {
+ if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
+ // receive_callback_(this, *read_msg_, ec);
+ LOG(ERROR) << "Error in UDP connector: " << ec.value() << " "
+ << ec.message();
+ } else {
+ LOG(ERROR) << "Error in connector while not connected. " << ec.value()
+ << " " << ec.message();
+ }
+ }
+}
+#endif
+
+void UdpTunnelConnector::doRecvPacket() {
+ std::weak_ptr<UdpTunnelConnector> self = shared_from_this();
+#ifdef LINUX
+ if (state_ == State::CONNECTED) {
+#if ((ASIO_VERSION / 100 % 1000) < 11)
+ socket_->async_receive(asio::null_buffers(),
+#else
+ socket_->async_wait(asio::ip::tcp::socket::wait_read,
+#endif
+ [self](const std::error_code &ec) {
+ if (ec) {
+ LOG(ERROR)
+ << "Error in UDP connector: " << ec.value()
+ << " " << ec.message();
+ return;
+ }
+ if (auto ptr = self.lock()) {
+ ptr->readHandler(ec);
+ }
+ });
+ }
+#else
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "UdpTunnelConnector receive packet";
+ read_msg_ = getRawBuffer();
+ socket_->async_receive_from(
+ asio::buffer(read_msg_.first, read_msg_.second), remote_endpoint_recv_,
+ [this, self](const std::error_code &ec, std::size_t length) {
+ if (auto ptr = self.lock()) {
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "UdpTunnelConnector received packet length=" << length;
+ if (TRANSPORT_EXPECT_TRUE(!ec)) {
+ if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
+ auto packet = getPacketFromBuffer(read_msg_.first, length);
+ receiveSuccess(*packet);
+ std::vector<utils::MemBuf::Ptr> v{std::move(packet)};
+ receive_callback_(this, v, make_error_code(core_error::success));
+ doRecvPacket();
+ } else {
+ LOG(ERROR) << "Error in UDP: Receiving packets from a not "
+ "connected socket.";
+ }
+ } else if (ec.value() ==
+ static_cast<int>(std::errc::operation_canceled)) {
+ LOG(ERROR) << "The connection has been closed by the application.";
+ return;
+ } else if (ec.value() ==
+ static_cast<int>(std::errc::connection_refused)) {
+ if (connection_reattempts_ < max_reconnection_reattempts) {
+ retryConnection();
+ }
+ } else {
+ if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
+ LOG(ERROR) << "Error in UDP connector: " << ec.value()
+ << ec.message();
+ } else {
+ LOG(ERROR) << "Error while not connected";
+ }
+ }
+ }
+ });
+#endif
+}
+
+void UdpTunnelConnector::doConnect(
+ std::shared_ptr<UdpTunnelConnector> &self_shared) {
+ std::weak_ptr<UdpTunnelConnector> self = self_shared;
+ asio::async_connect(*socket_, endpoint_iterator_,
+ [this, self](const std::error_code &ec,
+ asio::ip::udp::resolver::iterator) {
+ if (auto ptr = self.lock()) {
+ if (!ec) {
+ state_ = State::CONNECTED;
+ doRecvPacket();
+
+ if (data_available_) {
+ data_available_ = false;
+ doSendPacket(ptr);
+ }
+
+ on_reconnect_callback_(
+ this, make_error_code(core_error::success));
+ } else {
+ LOG(ERROR) << "UDP Connection failed!!!";
+ retryConnection();
+ }
+ }
+ });
+}
+
+} // namespace core
+
+} // namespace transport
diff --git a/libtransport/src/io_modules/forwarder/udp_tunnel.h b/libtransport/src/core/udp_connector.h
index 4f044f93f..002f4ca9f 100644
--- a/libtransport/src/io_modules/forwarder/udp_tunnel.h
+++ b/libtransport/src/core/udp_connector.h
@@ -1,13 +1,13 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
*/
#pragma once
+#include <core/errors.h>
#include <hicn/transport/core/asio_wrapper.h>
#include <hicn/transport/core/connector.h>
#include <hicn/transport/portability/platform.h>
-#include <io_modules/forwarder/errors.h>
#include <iostream>
#include <memory>
@@ -30,16 +30,15 @@ class UdpTunnelConnector : public Connector {
: Connector(receive_callback, packet_sent, on_close_callback,
on_reconnect),
io_service_(io_service),
- strand_(std::make_shared<asio::io_service::strand>(io_service_)),
socket_(std::make_shared<asio::ip::udp::socket>(io_service_)),
resolver_(io_service_),
timer_(io_service_),
#ifdef LINUX
send_timer_(io_service_),
- tx_iovecs_{0},
- tx_msgs_{0},
- rx_iovecs_{0},
- rx_msgs_{0},
+ tx_iovecs_{},
+ tx_msgs_{},
+ rx_iovecs_{},
+ rx_msgs_{},
current_position_(0),
#else
read_msg_(nullptr, 0),
@@ -61,17 +60,16 @@ class UdpTunnelConnector : public Connector {
#else
io_service_((asio::io_context &)(socket->get_executor().context())),
#endif
- strand_(strand),
socket_(socket),
resolver_(io_service_),
- remote_endpoint_send_(std::forward<EndpointType &&>(remote_endpoint)),
+ remote_endpoint_send_(std::forward<EndpointType>(remote_endpoint)),
timer_(io_service_),
#ifdef LINUX
send_timer_(io_service_),
- tx_iovecs_{0},
- tx_msgs_{0},
- rx_iovecs_{0},
- rx_msgs_{0},
+ tx_iovecs_{},
+ tx_msgs_{},
+ rx_iovecs_{},
+ rx_msgs_{},
current_position_(0),
#else
read_msg_(nullptr, 0),
@@ -88,7 +86,7 @@ class UdpTunnelConnector : public Connector {
void send(Packet &packet) override;
- void send(const uint8_t *packet, std::size_t len) override;
+ void send(const utils::MemBuf::Ptr &buffer) override;
void close() override;
@@ -99,26 +97,27 @@ class UdpTunnelConnector : public Connector {
auto shared_from_this() { return utils::shared_from(this); }
private:
- void doConnect();
+ void retryConnection();
+ void doConnect(std::shared_ptr<UdpTunnelConnector> &self);
void doRecvPacket();
- void doRecvPacket(utils::MemBuf &buffer) {
- receive_callback_(this, buffer, make_error_code(forwarder_error::success));
+ void doRecvPacket(utils::MemBuf::Ptr &buffer) {
+ std::vector<utils::MemBuf::Ptr> v{std::move(buffer)};
+ receive_callback_(this, v, make_error_code(core_error::success));
}
#ifdef LINUX
- void readHandler(std::error_code ec);
- void writeHandler(std::error_code ec);
+ void readHandler(const std::error_code &ec);
+ void writeHandler();
#endif
void setConnected() { state_ = State::CONNECTED; }
- void doSendPacket();
+ void doSendPacket(const std::shared_ptr<UdpTunnelConnector> &self);
void doClose();
private:
asio::io_service &io_service_;
- std::shared_ptr<asio::io_service::strand> strand_;
std::shared_ptr<asio::ip::udp::socket> socket_;
asio::ip::udp::resolver resolver_;
asio::ip::udp::resolver::iterator endpoint_iterator_;
diff --git a/libtransport/src/io_modules/forwarder/udp_tunnel_listener.cc b/libtransport/src/core/udp_listener.cc
index d047cc568..caa97e0ee 100644
--- a/libtransport/src/io_modules/forwarder/udp_tunnel_listener.cc
+++ b/libtransport/src/core/udp_listener.cc
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
*/
+#include <core/udp_connector.h>
+#include <core/udp_listener.h>
#include <glog/logging.h>
+#include <hicn/transport/portability/endianess.h>
#include <hicn/transport/utils/hash.h>
-#include <io_modules/forwarder/udp_tunnel.h>
-#include <io_modules/forwarder/udp_tunnel_listener.h>
#ifndef LINUX
namespace std {
@@ -16,7 +17,7 @@ size_t hash<asio::ip::udp::endpoint>::operator()(
: utils::hash::fnv32_buf(
endpoint.address().to_v6().to_bytes().data(), 16);
uint16_t port = endpoint.port();
- return utils::hash::fnv32_buf(&port, 2, hash_ip);
+ return utils::hash::fnv32_buf(&port, 2, (unsigned int)hash_ip);
}
} // namespace std
#endif
@@ -35,7 +36,7 @@ void UdpTunnelListener::close() {
}
#ifdef LINUX
-void UdpTunnelListener::readHandler(std::error_code ec) {
+void UdpTunnelListener::readHandler(const std::error_code &ec) {
DLOG_IF(INFO, VLOG_IS_ON(3)) << "UdpTunnelConnector receive packet";
if (TRANSPORT_EXPECT_TRUE(!ec)) {
@@ -83,7 +84,8 @@ void UdpTunnelListener::readHandler(std::error_code ec) {
std::copy_n(reinterpret_cast<uint8_t *>(&addr->sin_addr),
address_bytes.size(), address_bytes.begin());
address_v4 address(address_bytes);
- remote_endpoint_ = udp::endpoint(address, ntohs(addr->sin_port));
+ remote_endpoint_ =
+ udp::endpoint(address, portability::net_to_host(addr->sin_port));
} else {
auto addr = reinterpret_cast<struct sockaddr_in6 *>(
&remote_endpoints_[current_position_]);
@@ -91,7 +93,8 @@ void UdpTunnelListener::readHandler(std::error_code ec) {
std::copy_n(reinterpret_cast<uint8_t *>(&addr->sin6_addr),
address_bytes.size(), address_bytes.begin());
address_v6 address(address_bytes);
- remote_endpoint_ = udp::endpoint(address, ntohs(addr->sin6_port));
+ remote_endpoint_ =
+ udp::endpoint(address, portability::net_to_host(addr->sin6_port));
}
/**
@@ -102,7 +105,8 @@ void UdpTunnelListener::readHandler(std::error_code ec) {
std::make_shared<UdpTunnelConnector>(
socket_, strand_, receive_callback_,
[](Connector *, const std::error_code &) {}, [](Connector *) {},
- [](Connector *) {}, std::move(remote_endpoint_)));
+ [](Connector *, const std::error_code &) {},
+ std::move(remote_endpoint_)));
connector = ret.first;
connector->second->setConnectorId(connector_id);
}
@@ -112,7 +116,7 @@ void UdpTunnelListener::readHandler(std::error_code ec) {
*/
UdpTunnelConnector *c =
dynamic_cast<UdpTunnelConnector *>(connector->second.get());
- c->doRecvPacket(*packet);
+ c->doRecvPacket(packet);
++current_position_;
}
@@ -141,7 +145,7 @@ void UdpTunnelListener::doRecvPacket() {
read_msg_ = Connector::getRawBuffer();
socket_->async_receive_from(
asio::buffer(read_msg_.first, read_msg_.second), remote_endpoint_,
- [this](std::error_code ec, std::size_t length) {
+ [this](const std::error_code &ec, std::size_t length) {
if (TRANSPORT_EXPECT_TRUE(!ec)) {
auto packet = Connector::getPacketFromBuffer(read_msg_.first, length);
auto connector_id =
@@ -153,7 +157,8 @@ void UdpTunnelListener::doRecvPacket() {
connector_id, std::make_shared<UdpTunnelConnector>(
socket_, strand_, receive_callback_,
[](Connector *, const std::error_code &) {},
- [](Connector *) {}, [](Connector *) {},
+ [](Connector *) {},
+ [](Connector *, const std::error_code &) {},
std::move(remote_endpoint_)));
connector = ret.first;
connector->second->setConnectorId(connector_id);
@@ -161,7 +166,7 @@ void UdpTunnelListener::doRecvPacket() {
UdpTunnelConnector *c =
dynamic_cast<UdpTunnelConnector *>(connector->second.get());
- c->doRecvPacket(*packet);
+ c->doRecvPacket(packet);
doRecvPacket();
} else if (ec.value() ==
static_cast<int>(std::errc::operation_canceled)) {
diff --git a/libtransport/src/io_modules/forwarder/udp_tunnel_listener.h b/libtransport/src/core/udp_listener.h
index 5d197dcb0..d8095a262 100644
--- a/libtransport/src/io_modules/forwarder/udp_tunnel_listener.h
+++ b/libtransport/src/core/udp_listener.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
*/
#pragma once
@@ -40,12 +40,12 @@ class UdpTunnelListener
socket_(std::make_shared<asio::ip::udp::socket>(io_service_,
endpoint.protocol())),
local_endpoint_(endpoint),
- receive_callback_(std::forward<ReceiveCallback &&>(receive_callback)),
+ receive_callback_(std::forward<ReceiveCallback>(receive_callback)),
#ifndef LINUX
read_msg_(nullptr, 0)
#else
- iovecs_{0},
- msgs_{0},
+ iovecs_{},
+ msgs_{},
current_position_(0)
#endif
{
@@ -63,12 +63,12 @@ class UdpTunnelListener
void close();
int deleteConnector(Connector *connector) {
- return connectors_.erase(connector->getConnectorId());
+ return (int)connectors_.erase(connector->getConnectorId());
}
template <typename ReceiveCallback>
void setReceiveCallback(ReceiveCallback &&callback) {
- receive_callback_ = std::forward<ReceiveCallback &&>(callback);
+ receive_callback_ = std::forward<ReceiveCallback>(callback);
}
Connector *findConnector(Connector::Id connId) {
@@ -83,7 +83,7 @@ class UdpTunnelListener
private:
void doRecvPacket();
- void readHandler(std::error_code ec);
+ void readHandler(const std::error_code &ec);
asio::io_service &io_service_;
std::shared_ptr<asio::io_service::strand> strand_;
diff --git a/libtransport/src/http/CMakeLists.txt b/libtransport/src/http/CMakeLists.txt
index 2407faea3..0060f8714 100644
--- a/libtransport/src/http/CMakeLists.txt
+++ b/libtransport/src/http/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/libtransport/src/http/client_connection.cc b/libtransport/src/http/client_connection.cc
index b4ab7cbc3..05fa3e335 100644
--- a/libtransport/src/http/client_connection.cc
+++ b/libtransport/src/http/client_connection.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -77,9 +77,7 @@ class HTTPClientConnection::Implementation
auto end = std::chrono::steady_clock::now();
LOG(INFO) << method_map[method].c_str() << " " << url.c_str() << " ["
<< name_.str() << "] duration: "
- << std::chrono::duration_cast<std::chrono::microseconds>(end -
- start)
- .count()
+ << utils::SteadyTime::getDurationUs(start, end).count()
<< " [usec] " << size << " [bytes]";
};
@@ -106,7 +104,7 @@ class HTTPClientConnection::Implementation
HTTPClientConnection &setTimeout(const std::chrono::seconds &timeout) {
timer_->cancel();
timer_->expires_from_now(timeout);
- timer_->async_wait([this](std::error_code ec) {
+ timer_->async_wait([this](const std::error_code &ec) {
if (!ec) {
consumer_.stop();
}
@@ -147,18 +145,14 @@ class HTTPClientConnection::Implementation
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;
+ uint16_t *word = (uint16_t *)(&locator_hash);
+ for (std::size_t i = 0; i < sizeof(locator_hash) / 2; i++) {
+ name_ << ":" << std::hex << word[i];
}
- 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;
+ word = (uint16_t *)(&request_hash);
+ for (std::size_t i = 0; i < sizeof(request_hash) / 2; i++) {
+ name_ << ":" << std::hex << word[i];
}
name_ << "|0";
@@ -199,7 +193,7 @@ class HTTPClientConnection::Implementation
}
}
- void readError(const std::error_code ec) noexcept override {
+ void readError(const std::error_code &ec) noexcept override {
LOG(ERROR) << "Error " << ec.message() << " during download of "
<< current_url_.c_str();
if (read_bytes_callback_) {
diff --git a/libtransport/src/http/request.cc b/libtransport/src/http/request.cc
index 29118fd88..ad726741a 100644
--- a/libtransport/src/http/request.cc
+++ b/libtransport/src/http/request.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/http/response.cc b/libtransport/src/http/response.cc
index c665fbc5f..727e2c755 100644
--- a/libtransport/src/http/response.cc
+++ b/libtransport/src/http/response.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/implementation/CMakeLists.txt b/libtransport/src/implementation/CMakeLists.txt
index daf899d06..c759dd964 100644
--- a/libtransport/src/implementation/CMakeLists.txt
+++ b/libtransport/src/implementation/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -19,21 +19,8 @@ list(APPEND HEADER_FILES
if (${OPENSSL_VERSION} VERSION_EQUAL "1.1.1a" OR ${OPENSSL_VERSION} VERSION_GREATER "1.1.1a")
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_producer.cc
- # ${CMAKE_CURRENT_SOURCE_DIR}/tls_rtc_socket_producer.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_producer.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_consumer.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.cc
${CMAKE_CURRENT_SOURCE_DIR}/socket.cc
)
-
- list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_producer.h
- # ${CMAKE_CURRENT_SOURCE_DIR}/tls_rtc_socket_producer.h
- ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_producer.h
- ${CMAKE_CURRENT_SOURCE_DIR}/tls_socket_consumer.h
- ${CMAKE_CURRENT_SOURCE_DIR}/p2psecure_socket_consumer.h
- )
endif()
set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
diff --git a/libtransport/src/implementation/p2psecure_socket_consumer.cc b/libtransport/src/implementation/p2psecure_socket_consumer.cc
deleted file mode 100644
index 4b14da5d2..000000000
--- a/libtransport/src/implementation/p2psecure_socket_consumer.cc
+++ /dev/null
@@ -1,400 +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 <implementation/p2psecure_socket_consumer.h>
-#include <interfaces/tls_socket_consumer.h>
-#include <openssl/bio.h>
-#include <openssl/ssl.h>
-#include <openssl/tls1.h>
-
-#include <random>
-
-namespace transport {
-namespace implementation {
-
-void P2PSecureConsumerSocket::setInterestPayload(
- interface::ConsumerSocket &c, const core::Interest &interest) {
- Interest &int2 = const_cast<Interest &>(interest);
- random_suffix_ = int2.getName().getSuffix();
-
- if (payload_ != NULL) int2.appendPayload(std::move(payload_));
-}
-
-/* Return the number of read bytes in the return param */
-int readOld(BIO *b, char *buf, int size) {
- if (size < 0) return size;
-
- P2PSecureConsumerSocket *socket;
- socket = (P2PSecureConsumerSocket *)BIO_get_data(b);
-
- std::unique_lock<std::mutex> lck(socket->mtx_);
-
- if (!socket->something_to_read_) {
- if (!socket->transport_protocol_->isRunning()) {
- socket->network_name_.setSuffix(socket->random_suffix_);
- socket->ConsumerSocket::asyncConsume(socket->network_name_);
- }
-
- if (!socket->something_to_read_) socket->cv_.wait(lck);
- }
-
- size_t size_to_read, read;
- size_t chain_size = socket->head_->length();
-
- if (socket->head_->isChained())
- chain_size = socket->head_->computeChainDataLength();
-
- if (chain_size > (size_t)size) {
- read = size_to_read = (size_t)size;
- } else {
- read = size_to_read = chain_size;
- socket->something_to_read_ = false;
- }
-
- while (size_to_read) {
- if (socket->head_->length() < size_to_read) {
- std::memcpy(buf, socket->head_->data(), socket->head_->length());
- size_to_read -= socket->head_->length();
- buf += socket->head_->length();
- socket->head_ = socket->head_->pop();
- } else {
- std::memcpy(buf, socket->head_->data(), size_to_read);
- socket->head_->trimStart(size_to_read);
- size_to_read = 0;
- }
- }
-
- return (int)read;
-}
-
-/* Return the number of read bytes in readbytes */
-int read(BIO *b, char *buf, size_t size, size_t *readbytes) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = readOld(b, buf, (int)size);
-
- if (ret <= 0) {
- *readbytes = 0;
- return ret;
- }
-
- *readbytes = (size_t)ret;
-
- return 1;
-}
-
-/* Return the number of written bytes in the return param */
-int writeOld(BIO *b, const char *buf, int num) {
- P2PSecureConsumerSocket *socket;
- socket = (P2PSecureConsumerSocket *)BIO_get_data(b);
-
- socket->payload_ = utils::MemBuf::copyBuffer(buf, num);
-
- socket->ConsumerSocket::setSocketOption(
- ConsumerCallbacksOptions::INTEREST_OUTPUT,
- (ConsumerInterestCallback)std::bind(
- &P2PSecureConsumerSocket::setInterestPayload, socket,
- std::placeholders::_1, std::placeholders::_2));
-
- return num;
-}
-
-/* Return the number of written bytes in written */
-int write(BIO *b, const char *buf, size_t size, size_t *written) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = writeOld(b, buf, (int)size);
-
- if (ret <= 0) {
- *written = 0;
- return ret;
- }
-
- *written = (size_t)ret;
-
- return 1;
-}
-
-long ctrl(BIO *b, int cmd, long num, void *ptr) { return 1; }
-
-int P2PSecureConsumerSocket::addHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context,
- const unsigned char **out,
- size_t *outlen, X509 *x,
- size_t chainidx, int *al,
- void *add_arg) {
- if (ext_type == 100) {
- *out = (unsigned char *)malloc(4);
- *(uint32_t *)*out = 10;
- *outlen = 4;
- }
- return 1;
-}
-
-void P2PSecureConsumerSocket::freeHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context,
- const unsigned char *out,
- void *add_arg) {
- free(const_cast<unsigned char *>(out));
-}
-
-int P2PSecureConsumerSocket::parseHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context,
- const unsigned char *in,
- size_t inlen, X509 *x,
- size_t chainidx, int *al,
- void *add_arg) {
- P2PSecureConsumerSocket *socket =
- reinterpret_cast<P2PSecureConsumerSocket *>(add_arg);
- if (ext_type == 100) {
- memcpy(&socket->secure_prefix_, in, sizeof(ip_prefix_t));
- }
- return 1;
-}
-
-P2PSecureConsumerSocket::P2PSecureConsumerSocket(
- interface::ConsumerSocket *consumer, int handshake_protocol,
- int transport_protocol)
- : ConsumerSocket(consumer, handshake_protocol),
- name_(),
- tls_consumer_(nullptr),
- decrypted_content_(),
- payload_(),
- head_(),
- something_to_read_(false),
- content_downloaded_(false),
- random_suffix_(),
- secure_prefix_(),
- producer_namespace_(),
- read_callback_decrypted_(),
- mtx_(),
- cv_(),
- protocol_(transport_protocol) {
- /* Create the (d)TLS state */
- const SSL_METHOD *meth = TLS_client_method();
- ctx_ = SSL_CTX_new(meth);
-
- int result =
- SSL_CTX_set_ciphersuites(ctx_,
- "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_"
- "SHA256:TLS_AES_128_GCM_SHA256");
- if (result != 1) {
- throw errors::RuntimeException(
- "Unable to set cipher list on TLS subsystem. Aborting.");
- }
-
- SSL_CTX_set_min_proto_version(ctx_, TLS1_3_VERSION);
- SSL_CTX_set_max_proto_version(ctx_, TLS1_3_VERSION);
- SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, NULL);
- SSL_CTX_set_ssl_version(ctx_, meth);
-
- result = SSL_CTX_add_custom_ext(
- ctx_, 100, SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
- P2PSecureConsumerSocket::addHicnKeyIdCb,
- P2PSecureConsumerSocket::freeHicnKeyIdCb, NULL,
- P2PSecureConsumerSocket::parseHicnKeyIdCb, this);
-
- ssl_ = SSL_new(ctx_);
-
- bio_meth_ = BIO_meth_new(BIO_TYPE_CONNECT, "secure consumer socket");
- BIO_meth_set_read(bio_meth_, 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);
- SSL_set_bio(ssl_, bio, bio);
-
- std::default_random_engine generator;
- std::uniform_int_distribution<int> distribution(
- 1, std::numeric_limits<uint32_t>::max());
- random_suffix_ = 0;
-
- this->ConsumerSocket::setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK,
- this);
-};
-
-P2PSecureConsumerSocket::~P2PSecureConsumerSocket() {
- BIO_meth_free(bio_meth_);
- SSL_shutdown(ssl_);
-}
-
-int P2PSecureConsumerSocket::handshake() {
- int result = 1;
-
- if (!(SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) {
- return 1;
- }
-
- ConsumerSocket::getSocketOption(MAX_WINDOW_SIZE, old_max_win_);
- ConsumerSocket::getSocketOption(CURRENT_WINDOW_SIZE, old_current_win_);
-
- ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, (double)1.0);
- ConsumerSocket::setSocketOption(CURRENT_WINDOW_SIZE, (double)1.0);
-
- network_name_ = producer_namespace_.getRandomName();
- network_name_.setSuffix(0);
-
- DLOG_IF(INFO, VLOG_IS_ON(2)) << "Start handshake at " << network_name_;
- result = SSL_connect(this->ssl_);
-
- return result;
-}
-
-void P2PSecureConsumerSocket::initSessionSocket() {
- tls_consumer_ =
- 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,
- &stats_summary_callback);
-
- uint32_t lifetime;
- this->getSocketOption(GeneralTransportOptions::INTEREST_LIFETIME, lifetime);
-
- tls_consumer_->setSocketOption(GeneralTransportOptions::INTEREST_LIFETIME,
- lifetime);
- tls_consumer_->setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK,
- read_callback_decrypted_);
- tls_consumer_->setSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY,
- *stats_summary_callback);
- tls_consumer_->setSocketOption(GeneralTransportOptions::STATS_INTERVAL,
- this->timer_interval_milliseconds_);
- tls_consumer_->setSocketOption(MAX_WINDOW_SIZE, old_max_win_);
- tls_consumer_->setSocketOption(CURRENT_WINDOW_SIZE, old_current_win_);
- tls_consumer_->connect();
-}
-
-int P2PSecureConsumerSocket::consume(const Name &name) {
- if (transport_protocol_->isRunning()) {
- return CONSUMER_BUSY;
- }
-
- if (handshake() != 1) {
- throw errors::RuntimeException("Unable to perform client handshake");
- } else {
- DLOG_IF(INFO, VLOG_IS_ON(2)) << "Handshake performed!";
- }
-
- initSessionSocket();
-
- if (tls_consumer_ == nullptr) {
- throw errors::RuntimeException("TLS socket does not exist");
- }
-
- std::shared_ptr<Name> prefix_name = std::make_shared<Name>(
- secure_prefix_.family,
- ip_address_get_buffer(&(secure_prefix_.address), secure_prefix_.family));
- std::shared_ptr<Prefix> prefix =
- std::make_shared<Prefix>(*prefix_name, secure_prefix_.len);
-
- if (payload_ != nullptr)
- return tls_consumer_->consume((prefix->mapName(name)), std::move(payload_));
- else
- return tls_consumer_->consume((prefix->mapName(name)));
-}
-
-int P2PSecureConsumerSocket::asyncConsume(const Name &name) {
- if (transport_protocol_->isRunning()) {
- return CONSUMER_BUSY;
- }
-
- if (handshake() != 1) {
- throw errors::RuntimeException("Unable to perform client handshake");
- } else {
- DLOG_IF(INFO, VLOG_IS_ON(2)) << "Handshake performed!";
- }
-
- initSessionSocket();
-
- if (tls_consumer_ == nullptr) {
- throw errors::RuntimeException("TLS socket does not exist");
- }
-
- std::shared_ptr<Name> prefix_name = std::make_shared<Name>(
- secure_prefix_.family,
- ip_address_get_buffer(&(secure_prefix_.address), secure_prefix_.family));
- std::shared_ptr<Prefix> prefix =
- std::make_shared<Prefix>(*prefix_name, secure_prefix_.len);
-
- if (payload_ != NULL)
- return tls_consumer_->asyncConsume((prefix->mapName(name)),
- std::move(payload_));
- else
- return tls_consumer_->asyncConsume((prefix->mapName(name)));
-}
-
-void P2PSecureConsumerSocket::registerPrefix(const Prefix &producer_namespace) {
- producer_namespace_ = producer_namespace;
-}
-
-int P2PSecureConsumerSocket::setSocketOption(
- int socket_option_key, ReadCallback *socket_option_value) {
- 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_decrypted_ = socket_option_value;
- break;
- default:
- return SOCKET_OPTION_NOT_SET;
- }
-
- return SOCKET_OPTION_SET;
- });
-}
-
-void P2PSecureConsumerSocket::getReadBuffer(uint8_t **application_buffer,
- size_t *max_length){};
-
-void P2PSecureConsumerSocket::readDataAvailable(size_t length) noexcept {};
-
-size_t P2PSecureConsumerSocket::maxBufferSize() const {
- return SSL3_RT_MAX_PLAIN_LENGTH;
-}
-
-void P2PSecureConsumerSocket::readBufferAvailable(
- std::unique_ptr<utils::MemBuf> &&buffer) noexcept {
- std::unique_lock<std::mutex> lck(this->mtx_);
- if (head_) {
- head_->prependChain(std::move(buffer));
- } else {
- head_ = std::move(buffer);
- }
-
- something_to_read_ = true;
- cv_.notify_one();
-}
-
-void P2PSecureConsumerSocket::readError(const std::error_code ec) noexcept {};
-
-void P2PSecureConsumerSocket::readSuccess(std::size_t total_size) noexcept {
- std::unique_lock<std::mutex> lck(this->mtx_);
- content_downloaded_ = true;
- something_to_read_ = true;
- cv_.notify_one();
-}
-
-bool P2PSecureConsumerSocket::isBufferMovable() noexcept { return true; }
-
-} // namespace implementation
-} // namespace transport
diff --git a/libtransport/src/implementation/p2psecure_socket_consumer.h b/libtransport/src/implementation/p2psecure_socket_consumer.h
deleted file mode 100644
index a35a50352..000000000
--- a/libtransport/src/implementation/p2psecure_socket_consumer.h
+++ /dev/null
@@ -1,136 +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/interfaces/socket_consumer.h>
-#include <implementation/tls_socket_consumer.h>
-#include <openssl/bio.h>
-#include <openssl/ssl.h>
-
-namespace transport {
-namespace implementation {
-
-class P2PSecureConsumerSocket : public ConsumerSocket,
- 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);
-
- /* Return the number of read bytes in the return param */
- friend int readOld(BIO *h, char *buf, int size);
-
- /* Return the number of written bytes in written */
- friend int write(BIO *b, const char *buf, size_t size, size_t *written);
-
- /* Return the number of written bytes in the return param */
- friend int writeOld(BIO *h, const char *buf, int num);
-
- friend long ctrl(BIO *b, int cmd, long num, void *ptr);
-
- public:
- explicit P2PSecureConsumerSocket(interface::ConsumerSocket *consumer,
- int handshake_protocol,
- int transport_protocol);
-
- ~P2PSecureConsumerSocket();
-
- int consume(const Name &name) override;
-
- int asyncConsume(const Name &name) override;
-
- void registerPrefix(const Prefix &producer_namespace);
-
- int setSocketOption(
- int socket_option_key,
- interface::ConsumerSocket::ReadCallback *socket_option_value) override;
-
- using ConsumerSocket::getSocketOption;
- using ConsumerSocket::setSocketOption;
-
- protected:
- /* Callback invoked once an interest has been received and its payload
- * decrypted */
- ConsumerInterestCallback on_interest_input_decrypted_;
- ConsumerInterestCallback on_interest_process_decrypted_;
-
- private:
- Name name_;
- std::shared_ptr<TLSConsumerSocket> tls_consumer_;
- /* SSL handle */
- SSL *ssl_;
- SSL_CTX *ctx_;
- BIO_METHOD *bio_meth_;
- /* Chain of MemBuf to be used as a temporary buffer to pass descypted data
- * from the underlying layer to the application */
- std::unique_ptr<utils::MemBuf> decrypted_content_;
- /* Chain of MemBuf holding the payload to be written into interest or data */
- std::unique_ptr<utils::MemBuf> payload_;
- /* Chain of MemBuf holding the data retrieved from the underlying layer */
- std::unique_ptr<utils::MemBuf> head_;
- bool something_to_read_;
- bool content_downloaded_;
- double old_max_win_;
- double old_current_win_;
- uint32_t random_suffix_;
- ip_prefix_t secure_prefix_;
- Prefix producer_namespace_;
- interface::ConsumerSocket::ReadCallback *read_callback_decrypted_;
- std::mutex mtx_;
-
- /* Condition variable for the wait */
- std::condition_variable cv_;
-
- int protocol_;
-
- 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,
- size_t chainidx, int *al, void *add_arg);
-
- static void freeHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context, const unsigned char *out,
- void *add_arg);
-
- static int parseHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context, const unsigned char *in,
- size_t inlen, X509 *x, size_t chainidx, int *al,
- void *add_arg);
-
- virtual void getReadBuffer(uint8_t **application_buffer,
- size_t *max_length) override;
-
- virtual void readDataAvailable(size_t length) noexcept override;
-
- virtual size_t maxBufferSize() const override;
-
- virtual void readBufferAvailable(
- std::unique_ptr<utils::MemBuf> &&buffer) noexcept override;
-
- virtual void readError(const std::error_code ec) noexcept override;
-
- virtual void readSuccess(std::size_t total_size) noexcept override;
-
- virtual bool isBufferMovable() noexcept override;
-
- int handshake();
-
- void initSessionSocket();
-};
-
-} // namespace implementation
-
-} // end namespace transport
diff --git a/libtransport/src/implementation/p2psecure_socket_producer.cc b/libtransport/src/implementation/p2psecure_socket_producer.cc
deleted file mode 100644
index 3748001fc..000000000
--- a/libtransport/src/implementation/p2psecure_socket_producer.cc
+++ /dev/null
@@ -1,376 +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/core/interest.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 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(
- interface::ProducerSocket *producer_socket)
- : ProducerSocket(producer_socket,
- ProductionProtocolAlgorithms::BYTE_STREAM),
- mtx_(),
- cv_(),
- map_producers(),
- list_producers() {}
-
-P2PSecureProducerSocket::P2PSecureProducerSocket(
- interface::ProducerSocket *producer_socket, bool rtc,
- const std::shared_ptr<auth::Identity> &identity)
- : ProducerSocket(producer_socket,
- ProductionProtocolAlgorithms::BYTE_STREAM),
- rtc_(rtc),
- mtx_(),
- cv_(),
- map_producers(),
- list_producers() {
- /* Setup SSL context (identity and parameter to use TLS 1.3) */
- cert_509_ = identity->getCertificate().get();
- pkey_rsa_ = identity->getPrivateKey().get();
-
- /* Set the callback so that when an interest is received we catch it and we
- * decrypt the payload before passing it to the application. */
- ProducerSocket::setSocketOption(
- ProducerCallbacksOptions::INTEREST_INPUT,
- (ProducerInterestCallback)std::bind(
- &P2PSecureProducerSocket::onInterestCallback, this,
- std::placeholders::_1, std::placeholders::_2));
-}
-
-P2PSecureProducerSocket::~P2PSecureProducerSocket() {}
-
-void P2PSecureProducerSocket::initSessionSocket(
- std::unique_ptr<TLSProducerSocket> &producer) {
- producer->on_content_produced_application_ =
- this->on_content_produced_application_;
- producer->setSocketOption(CONTENT_OBJECT_EXPIRY_TIME,
- this->content_object_expiry_time_);
- producer->setSocketOption(SIGNER, this->signer_);
- producer->setSocketOption(MAKE_MANIFEST, this->making_manifest_);
- producer->setSocketOption(DATA_PACKET_SIZE,
- (uint32_t)(this->data_packet_size_));
- uint32_t output_buffer_size = 0;
- this->getSocketOption(GeneralTransportOptions::OUTPUT_BUFFER_SIZE,
- output_buffer_size);
- producer->setSocketOption(GeneralTransportOptions::OUTPUT_BUFFER_SIZE,
- output_buffer_size);
-
- if (!rtc_) {
- producer->setInterface(new interface::TLSProducerSocket(producer.get()));
- } else {
- // TODO
- // TLSRTCProducerSocket *rtc_producer =
- // dynamic_cast<TLSRTCProducerSocket *>(producer.get());
- // rtc_producer->setInterface(
- // new interface::TLSRTCProducerSocket(rtc_producer));
- }
-}
-
-void P2PSecureProducerSocket::onInterestCallback(interface::ProducerSocket &p,
- Interest &interest) {
- std::unique_lock<std::mutex> lck(mtx_);
- std::unique_ptr<TLSProducerSocket> tls_producer;
- auto it = map_producers.find(interest.getName());
-
- if (it != map_producers.end()) {
- return;
- }
-
- if (!rtc_) {
- tls_producer =
- std::make_unique<TLSProducerSocket>(nullptr, this, interest.getName());
- } else {
- // TODO
- // tls_producer = std::make_unique<TLSRTCProducerSocket>(nullptr, this,
- // interest.getName());
- }
-
- initSessionSocket(tls_producer);
- TLSProducerSocket *tls_producer_ptr = tls_producer.get();
- map_producers.insert({interest.getName(), move(tls_producer)});
-
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Start handshake at " << interest.getName();
-
- if (!rtc_) {
- tls_producer_ptr->onInterest(*tls_producer_ptr, interest);
- tls_producer_ptr->async_accept();
- } else {
- // TODO
- // TLSRTCProducerSocket *rtc_producer_ptr =
- // dynamic_cast<TLSRTCProducerSocket *>(tls_producer_ptr);
- // rtc_producer_ptr->onInterest(*rtc_producer_ptr, interest);
- // rtc_producer_ptr->async_accept();
- }
-}
-
-uint32_t P2PSecureProducerSocket::produceDatagram(
- const Name &content_name, std::unique_ptr<utils::MemBuf> &&buffer) {
- // TODO
- throw errors::NotImplementedException();
-
- if (!rtc_) {
- throw errors::RuntimeException(
- "RTC must be the transport protocol to start the production of current "
- "data. Aborting.");
- }
-
- std::unique_lock<std::mutex> lck(mtx_);
-
- if (list_producers.empty()) cv_.wait(lck);
-
- // TODO
- // for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- // {
- // TLSRTCProducerSocket *rtc_producer =
- // dynamic_cast<TLSRTCProducerSocket *>(it->get());
- // rtc_producer->produce(utils::MemBuf::copyBuffer(buffer, buffer_size));
- // }
-
- return 0;
-}
-
-uint32_t P2PSecureProducerSocket::produceStream(
- const Name &content_name, std::unique_ptr<utils::MemBuf> &&buffer,
- bool is_last, uint32_t start_offset) {
- if (rtc_) {
- throw errors::RuntimeException(
- "RTC transport protocol is not compatible with the production of "
- "current data. Aborting.");
- }
-
- std::unique_lock<std::mutex> lck(mtx_);
- uint32_t segments = 0;
-
- if (list_producers.empty()) cv_.wait(lck);
-
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- segments += (*it)->produceStream(content_name, buffer->clone(), is_last,
- start_offset);
-
- return segments;
-}
-
-uint32_t P2PSecureProducerSocket::produceStream(const Name &content_name,
- const uint8_t *buffer,
- size_t buffer_size,
- bool is_last,
- uint32_t start_offset) {
- if (rtc_) {
- throw errors::RuntimeException(
- "RTC transport protocol is not compatible with the production of "
- "current data. Aborting.");
- }
-
- std::unique_lock<std::mutex> lck(mtx_);
- uint32_t segments = 0;
- if (list_producers.empty()) cv_.wait(lck);
-
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- segments += (*it)->produceStream(content_name, buffer, buffer_size, is_last,
- start_offset);
-
- return segments;
-}
-
-// void P2PSecureProducerSocket::asyncProduce(const Name &content_name,
-// const uint8_t *buf,
-// size_t buffer_size, bool is_last,
-// uint32_t *start_offset) {
-// if (rtc_) {
-// throw errors::RuntimeException(
-// "RTC transport protocol is not compatible with the production of "
-// "current data. Aborting.");
-// }
-
-// std::unique_lock<std::mutex> lck(mtx_);
-// if (list_producers.empty()) cv_.wait(lck);
-
-// for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
-// {
-// (*it)->asyncProduce(content_name, buf, buffer_size, is_last,
-// start_offset);
-// }
-// }
-
-void P2PSecureProducerSocket::asyncProduce(
- Name content_name, std::unique_ptr<utils::MemBuf> &&buffer, bool is_last,
- uint32_t offset, uint32_t **last_segment) {
- if (rtc_) {
- throw errors::RuntimeException(
- "RTC transport protocol is not compatible with the production of "
- "current data. Aborting.");
- }
-
- std::unique_lock<std::mutex> lck(mtx_);
- if (list_producers.empty()) cv_.wait(lck);
-
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++) {
- (*it)->asyncProduce(content_name, buffer->clone(), is_last, offset,
- last_segment);
- }
-}
-
-/* Redefinition of socket options to avoid name hiding */
-int P2PSecureProducerSocket::setSocketOption(
- int socket_option_key, ProducerInterestCallback socket_option_value) {
- if (!list_producers.empty()) {
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
- }
-
- switch (socket_option_key) {
- case ProducerCallbacksOptions::INTEREST_INPUT:
- on_interest_input_decrypted_ = socket_option_value;
- return SOCKET_OPTION_SET;
-
- case ProducerCallbacksOptions::INTEREST_DROP:
- on_interest_dropped_input_buffer_ = socket_option_value;
- return SOCKET_OPTION_SET;
-
- case ProducerCallbacksOptions::INTEREST_PASS:
- on_interest_inserted_input_buffer_ = socket_option_value;
- return SOCKET_OPTION_SET;
-
- case ProducerCallbacksOptions::CACHE_HIT:
- on_interest_satisfied_output_buffer_ = socket_option_value;
- return SOCKET_OPTION_SET;
-
- case ProducerCallbacksOptions::CACHE_MISS:
- on_interest_process_decrypted_ = socket_option_value;
- return SOCKET_OPTION_SET;
-
- default:
- return SOCKET_OPTION_NOT_SET;
- }
-}
-
-int P2PSecureProducerSocket::setSocketOption(
- int socket_option_key,
- const std::shared_ptr<auth::Signer> &socket_option_value) {
- if (!list_producers.empty())
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
-
- switch (socket_option_key) {
- case GeneralTransportOptions::SIGNER: {
- signer_.reset();
- signer_ = socket_option_value;
-
- return SOCKET_OPTION_SET;
- }
- default:
- return SOCKET_OPTION_NOT_SET;
- }
-}
-
-int P2PSecureProducerSocket::setSocketOption(int socket_option_key,
- uint32_t socket_option_value) {
- if (!list_producers.empty()) {
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
- }
- switch (socket_option_key) {
- case GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME:
- content_object_expiry_time_ =
- socket_option_value; // HICN_HANDSHAKE_CONTENT_EXPIRY_TIME;
- return SOCKET_OPTION_SET;
- }
- return ProducerSocket::setSocketOption(socket_option_key,
- socket_option_value);
-}
-
-int P2PSecureProducerSocket::setSocketOption(int socket_option_key,
- bool socket_option_value) {
- if (!list_producers.empty())
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
-
- return ProducerSocket::setSocketOption(socket_option_key,
- socket_option_value);
-}
-
-int P2PSecureProducerSocket::setSocketOption(int socket_option_key,
- Name *socket_option_value) {
- if (!list_producers.empty())
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
-
- return ProducerSocket::setSocketOption(socket_option_key,
- socket_option_value);
-}
-
-int P2PSecureProducerSocket::setSocketOption(
- int socket_option_key, ProducerContentObjectCallback socket_option_value) {
- if (!list_producers.empty())
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
-
- return ProducerSocket::setSocketOption(socket_option_key,
- socket_option_value);
-}
-
-int P2PSecureProducerSocket::setSocketOption(
- int socket_option_key, ProducerContentCallback socket_option_value) {
- if (!list_producers.empty())
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
-
- switch (socket_option_key) {
- case ProducerCallbacksOptions::CONTENT_PRODUCED:
- on_content_produced_application_ = socket_option_value;
- break;
-
- default:
- return SOCKET_OPTION_NOT_SET;
- }
-
- return SOCKET_OPTION_SET;
-}
-
-int P2PSecureProducerSocket::setSocketOption(
- int socket_option_key, auth::CryptoHashType socket_option_value) {
- if (!list_producers.empty())
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
-
- return ProducerSocket::setSocketOption(socket_option_key,
- socket_option_value);
-}
-
-int P2PSecureProducerSocket::setSocketOption(
- int socket_option_key, const std::string &socket_option_value) {
- if (!list_producers.empty())
- for (auto it = list_producers.cbegin(); it != list_producers.cend(); it++)
- (*it)->setSocketOption(socket_option_key, socket_option_value);
-
- return ProducerSocket::setSocketOption(socket_option_key,
- socket_option_value);
-}
-
-} // namespace implementation
-} // namespace transport
diff --git a/libtransport/src/implementation/p2psecure_socket_producer.h b/libtransport/src/implementation/p2psecure_socket_producer.h
deleted file mode 100644
index f94347258..000000000
--- a/libtransport/src/implementation/p2psecure_socket_producer.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/auth/identity.h>
-#include <hicn/transport/auth/signer.h>
-#include <implementation/socket_producer.h>
-// #include <implementation/tls_rtc_socket_producer.h>
-#include <implementation/tls_socket_producer.h>
-#include <openssl/ssl.h>
-#include <utils/content_store.h>
-
-#include <condition_variable>
-#include <forward_list>
-#include <mutex>
-
-namespace transport {
-namespace implementation {
-
-class P2PSecureProducerSocket : public ProducerSocket {
- friend class TLSProducerSocket;
- // TODO
- // friend class TLSRTCProducerSocket;
-
- public:
- explicit P2PSecureProducerSocket(interface::ProducerSocket *producer_socket);
-
- explicit P2PSecureProducerSocket(
- interface::ProducerSocket *producer_socket, bool rtc,
- const std::shared_ptr<auth::Identity> &identity);
-
- ~P2PSecureProducerSocket();
-
- uint32_t produceDatagram(const Name &content_name,
- std::unique_ptr<utils::MemBuf> &&buffer) override;
-
- uint32_t produceStream(const Name &content_name, const uint8_t *buffer,
- size_t buffer_size, bool is_last = true,
- uint32_t start_offset = 0) override;
-
- uint32_t produceStream(const Name &content_name,
- std::unique_ptr<utils::MemBuf> &&buffer,
- bool is_last = true,
- uint32_t start_offset = 0) override;
-
- void asyncProduce(Name content_name, std::unique_ptr<utils::MemBuf> &&buffer,
- bool is_last, uint32_t offset,
- uint32_t **last_segment = nullptr) override;
-
- int setSocketOption(int socket_option_key,
- ProducerInterestCallback socket_option_value) override;
-
- int setSocketOption(
- int socket_option_key,
- const std::shared_ptr<auth::Signer> &socket_option_value) override;
-
- int setSocketOption(int socket_option_key,
- uint32_t socket_option_value) override;
-
- int setSocketOption(int socket_option_key, bool socket_option_value) override;
-
- int setSocketOption(int socket_option_key,
- Name *socket_option_value) override;
-
- int setSocketOption(
- int socket_option_key,
- ProducerContentObjectCallback socket_option_value) override;
-
- int setSocketOption(int socket_option_key,
- ProducerContentCallback socket_option_value) override;
-
- int setSocketOption(int socket_option_key,
- auth::CryptoHashType socket_option_value) override;
-
- int setSocketOption(int socket_option_key,
- const std::string &socket_option_value) override;
-
- using ProducerSocket::getSocketOption;
- // using ProducerSocket::onInterest;
-
- protected:
- /* Callback invoked once an interest has been received and its payload
- * decrypted */
- ProducerInterestCallback on_interest_input_decrypted_;
- ProducerInterestCallback on_interest_process_decrypted_;
- ProducerContentCallback on_content_produced_application_;
-
- private:
- bool rtc_;
- std::mutex mtx_;
- /* Condition variable for the wait */
- std::condition_variable cv_;
- X509 *cert_509_;
- EVP_PKEY *pkey_rsa_;
- std::unordered_map<core::Name, std::unique_ptr<TLSProducerSocket>,
- core::hash<core::Name>, core::compare2<core::Name>>
- map_producers;
- std::list<std::unique_ptr<TLSProducerSocket>> list_producers;
-
- void onInterestCallback(interface::ProducerSocket &p, Interest &interest);
-
- void initSessionSocket(std::unique_ptr<TLSProducerSocket> &producer);
-};
-
-} // namespace implementation
-} // namespace transport
diff --git a/libtransport/src/implementation/socket.cc b/libtransport/src/implementation/socket.cc
index 2e21f2bc3..c554d09d3 100644
--- a/libtransport/src/implementation/socket.cc
+++ b/libtransport/src/implementation/socket.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,13 +14,27 @@
*/
#include <core/global_configuration.h>
+#include <hicn/transport/interfaces/socket_options_default_values.h>
#include <implementation/socket.h>
namespace transport {
namespace implementation {
Socket::Socket(std::shared_ptr<core::Portal> &&portal)
- : portal_(std::move(portal)), is_async_(false) {}
+ : portal_(std::move(portal)),
+ is_async_(false),
+ signer_(std::make_shared<auth::VoidSigner>()),
+ verifier_(std::make_shared<auth::VoidVerifier>()) {}
+
+int Socket::setSocketOption(int socket_option_key,
+ hicn_packet_format_t packet_format) {
+ return SOCKET_OPTION_NOT_SET;
+}
+
+int Socket::getSocketOption(int socket_option_key,
+ hicn_packet_format_t &packet_format) {
+ return SOCKET_OPTION_NOT_GET;
+}
} // namespace implementation
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/libtransport/src/implementation/socket.h b/libtransport/src/implementation/socket.h
index cf22c03e1..d0d2ba2ac 100644
--- a/libtransport/src/implementation/socket.h
+++ b/libtransport/src/implementation/socket.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,8 @@
#pragma once
#include <core/facade.h>
+#include <hicn/transport/auth/signer.h>
+#include <hicn/transport/auth/verifier.h>
#include <hicn/transport/config.h>
#include <hicn/transport/interfaces/callbacks.h>
#include <hicn/transport/interfaces/socket_options_default_values.h>
@@ -38,7 +40,28 @@ class Socket {
virtual void connect() = 0;
virtual bool isRunning() = 0;
- virtual asio::io_service &getIoService() { return portal_->getIoService(); }
+ virtual asio::io_service &getIoService() {
+ return portal_->getThread().getIoService();
+ }
+
+ int setSocketOption(int socket_option_key,
+ hicn_packet_format_t packet_format);
+ int getSocketOption(int socket_option_key,
+ hicn_packet_format_t &packet_format);
+
+ int getSocketOption(int socket_option_key,
+ std::shared_ptr<core::Portal> &socket_option_value) {
+ switch (socket_option_key) {
+ case interface::GeneralTransportOptions::PORTAL:
+ socket_option_value = portal_;
+ break;
+ default:
+ return SOCKET_OPTION_NOT_GET;
+ ;
+ }
+
+ return SOCKET_OPTION_GET;
+ }
protected:
Socket(std::shared_ptr<core::Portal> &&portal);
@@ -48,6 +71,8 @@ class Socket {
protected:
std::shared_ptr<core::Portal> portal_;
bool is_async_;
+ std::shared_ptr<auth::Signer> signer_;
+ std::shared_ptr<auth::Verifier> verifier_;
};
} // namespace implementation
diff --git a/libtransport/src/implementation/socket_consumer.h b/libtransport/src/implementation/socket_consumer.h
index e0981af7f..3117e21e7 100644
--- a/libtransport/src/implementation/socket_consumer.h
+++ b/libtransport/src/implementation/socket_consumer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -20,6 +20,7 @@
#include <hicn/transport/interfaces/socket_options_default_values.h>
#include <hicn/transport/interfaces/statistics.h>
#include <hicn/transport/utils/event_thread.h>
+#include <implementation/socket.h>
#include <protocols/cbr.h>
#include <protocols/raaqm.h>
#include <protocols/rtc/rtc.h>
@@ -38,7 +39,7 @@ class ConsumerSocket : public Socket {
std::shared_ptr<core::Portal> &&portal)
: Socket(std::move(portal)),
consumer_interface_(consumer),
- async_downloader_(),
+ packet_format_(default_values::packet_format),
interest_lifetime_(default_values::interest_lifetime),
min_window_size_(default_values::min_window_size),
max_window_size_(default_values::max_window_size),
@@ -56,6 +57,8 @@ class ConsumerSocket : public Socket {
rate_estimation_observer_(nullptr),
rate_estimation_batching_parameter_(default_values::batch),
rate_estimation_choice_(0),
+ manifest_factor_relevant_(default_values::manifest_factor_relevant),
+ manifest_factor_alert_(default_values::manifest_factor_alert),
verifier_(std::make_shared<auth::VoidVerifier>()),
verify_signature_(false),
reset_window_(false),
@@ -64,41 +67,43 @@ class ConsumerSocket : public Socket {
on_interest_satisfied_(VOID_HANDLER),
on_content_object_input_(VOID_HANDLER),
stats_summary_(VOID_HANDLER),
+ on_fwd_strategy_(VOID_HANDLER),
+ on_rec_strategy_(VOID_HANDLER),
read_callback_(nullptr),
timer_interval_milliseconds_(0),
+ recovery_strategy_(RtcTransportRecoveryStrategies::RTX_ONLY),
+ aggregated_data_(false),
+ content_sharing_mode_(false),
+ aggregated_interests_(false),
guard_raaqm_params_() {
switch (protocol) {
case TransportProtocolAlgorithms::CBR:
transport_protocol_ =
- std::make_unique<protocol::CbrTransportProtocol>(this);
+ std::make_shared<protocol::CbrTransportProtocol>(this);
break;
case TransportProtocolAlgorithms::RTC:
transport_protocol_ =
- std::make_unique<protocol::rtc::RTCTransportProtocol>(this);
+ std::make_shared<protocol::rtc::RTCTransportProtocol>(this);
break;
case TransportProtocolAlgorithms::RAAQM:
default:
transport_protocol_ =
- std::make_unique<protocol::RaaqmTransportProtocol>(this);
+ std::make_shared<protocol::RaaqmTransportProtocol>(this);
break;
}
}
public:
ConsumerSocket(interface::ConsumerSocket *consumer, int protocol)
- : ConsumerSocket(consumer, protocol, std::make_shared<core::Portal>()) {}
+ : ConsumerSocket(consumer, protocol, core::Portal::createShared()) {}
ConsumerSocket(interface::ConsumerSocket *consumer, int protocol,
- asio::io_service &io_service)
- : ConsumerSocket(consumer, protocol,
- std::make_shared<core::Portal>(io_service)) {
+ ::utils::EventThread &worker)
+ : ConsumerSocket(consumer, protocol, core::Portal::createShared(worker)) {
is_async_ = true;
}
- ~ConsumerSocket() {
- stop();
- async_downloader_.stop();
- }
+ ~ConsumerSocket() { stop(); }
interface::ConsumerSocket *getInterface() {
return consumer_interface_;
@@ -122,18 +127,6 @@ class ConsumerSocket : public Socket {
transport_protocol_->start();
- return is_async_ ? CONSUMER_RUNNING : 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;
}
@@ -149,6 +142,9 @@ class ConsumerSocket : public Socket {
}
}
+ using Socket::getSocketOption;
+ using Socket::setSocketOption;
+
virtual int setSocketOption(int socket_option_key,
ReadCallback *socket_option_value) {
// Reschedule the function on the io_service to avoid race condition in
@@ -265,6 +261,23 @@ class ConsumerSocket : public Socket {
timer_interval_milliseconds_ = socket_option_value;
break;
+ case RtcTransportOptions::RECOVERY_STRATEGY:
+ recovery_strategy_ =
+ (RtcTransportRecoveryStrategies)socket_option_value;
+ break;
+
+ case MANIFEST_FACTOR_RELEVANT:
+ manifest_factor_relevant_ = socket_option_value;
+ break;
+
+ case MANIFEST_FACTOR_ALERT:
+ manifest_factor_alert_ = socket_option_value;
+ break;
+
+ case GeneralTransportOptions::PACKET_FORMAT:
+ packet_format_ = socket_option_value;
+ break;
+
default:
return SOCKET_OPTION_NOT_SET;
}
@@ -310,7 +323,6 @@ class ConsumerSocket : public Socket {
on_content_object_input_ = VOID_HANDLER;
break;
}
-
default:
return SOCKET_OPTION_NOT_SET;
}
@@ -328,6 +340,21 @@ class ConsumerSocket : public Socket {
result = SOCKET_OPTION_SET;
break;
+ case RtcTransportOptions::AGGREGATED_DATA:
+ aggregated_data_ = socket_option_value;
+ result = SOCKET_OPTION_SET;
+ break;
+
+ case RtcTransportOptions::CONTENT_SHARING_MODE:
+ content_sharing_mode_ = socket_option_value;
+ result = SOCKET_OPTION_SET;
+ break;
+
+ case RtcTransportOptions::AGGREGATED_INTERESTS:
+ aggregated_interests_ = socket_option_value;
+ result = SOCKET_OPTION_SET;
+ break;
+
default:
return result;
}
@@ -405,37 +432,49 @@ class ConsumerSocket : public Socket {
int setSocketOption(
int socket_option_key,
+ const std::shared_ptr<auth::Signer> &socket_option_value) {
+ if (!transport_protocol_->isRunning()) {
+ switch (socket_option_key) {
+ case GeneralTransportOptions::SIGNER:
+ signer_.reset();
+ signer_ = socket_option_value;
+ break;
+ default:
+ return SOCKET_OPTION_NOT_SET;
+ }
+ }
+ return SOCKET_OPTION_SET;
+ }
+
+ int setSocketOption(
+ int socket_option_key,
const std::shared_ptr<auth::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 SOCKET_OPTION_NOT_SET;
}
}
-
- return result;
+ return SOCKET_OPTION_SET;
}
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 DataLinkOptions::OUTPUT_INTERFACE:
+ switch (socket_option_key) {
+ case DataLinkOptions::OUTPUT_INTERFACE:
+ if (!transport_protocol_->isRunning()) {
output_interface_ = socket_option_value;
portal_->setOutputInterface(output_interface_);
result = SOCKET_OPTION_SET;
- break;
-
- default:
- return result;
- }
+ }
+ break;
+ default:
+ return result;
}
return result;
}
@@ -461,6 +500,29 @@ class ConsumerSocket : public Socket {
});
}
+ int setSocketOption(int socket_option_key,
+ StrategyCallback 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,
+ StrategyCallback socket_option_value) -> int {
+ switch (socket_option_key) {
+ case ConsumerCallbacksOptions::FWD_STRATEGY_CHANGE:
+ on_fwd_strategy_ = socket_option_value;
+ break;
+ case ConsumerCallbacksOptions::REC_STRATEGY_CHANGE:
+ on_rec_strategy_ = 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) {
@@ -532,6 +594,22 @@ class ConsumerSocket : public Socket {
socket_option_value = timer_interval_milliseconds_;
break;
+ case RtcTransportOptions::RECOVERY_STRATEGY:
+ socket_option_value = recovery_strategy_;
+ break;
+
+ case GeneralTransportOptions::MANIFEST_FACTOR_RELEVANT:
+ socket_option_value = manifest_factor_relevant_;
+ break;
+
+ case GeneralTransportOptions::MANIFEST_FACTOR_ALERT:
+ socket_option_value = manifest_factor_alert_;
+ break;
+
+ case GeneralTransportOptions::PACKET_FORMAT:
+ socket_option_value = packet_format_;
+ break;
+
default:
return SOCKET_OPTION_NOT_GET;
}
@@ -553,6 +631,18 @@ class ConsumerSocket : public Socket {
socket_option_value = reset_window_;
break;
+ case RtcTransportOptions::AGGREGATED_DATA:
+ socket_option_value = aggregated_data_;
+ break;
+
+ case RtcTransportOptions::CONTENT_SHARING_MODE:
+ socket_option_value = content_sharing_mode_;
+ break;
+
+ case RtcTransportOptions::AGGREGATED_INTERESTS:
+ socket_option_value = aggregated_interests_;
+ break;
+
default:
return SOCKET_OPTION_NOT_GET;
}
@@ -628,10 +718,11 @@ class ConsumerSocket : public Socket {
}
int getSocketOption(int socket_option_key,
- std::shared_ptr<core::Portal> &socket_option_value) {
+ IcnObserver **socket_option_value) {
+ utils::SpinLock::Acquire locked(guard_raaqm_params_);
switch (socket_option_key) {
- case PORTAL:
- socket_option_value = portal_;
+ case RateEstimationOptions::RATE_ESTIMATION_OBSERVER:
+ *socket_option_value = (rate_estimation_observer_);
break;
default:
@@ -642,18 +733,15 @@ class ConsumerSocket : public Socket {
}
int getSocketOption(int socket_option_key,
- IcnObserver **socket_option_value) {
- utils::SpinLock::Acquire locked(guard_raaqm_params_);
+ std::shared_ptr<auth::Signer> &socket_option_value) {
switch (socket_option_key) {
- case RateEstimationOptions::RATE_ESTIMATION_OBSERVER:
- *socket_option_value = (rate_estimation_observer_);
- break;
+ case GeneralTransportOptions::SIGNER:
+ socket_option_value = signer_;
+ return SOCKET_OPTION_GET;
default:
return SOCKET_OPTION_NOT_GET;
}
-
- return SOCKET_OPTION_GET;
}
int getSocketOption(int socket_option_key,
@@ -665,7 +753,6 @@ class ConsumerSocket : public Socket {
default:
return SOCKET_OPTION_NOT_GET;
}
-
return SOCKET_OPTION_GET;
}
@@ -677,7 +764,6 @@ class ConsumerSocket : public Socket {
default:
return SOCKET_OPTION_NOT_GET;
}
-
return SOCKET_OPTION_GET;
}
@@ -714,6 +800,29 @@ class ConsumerSocket : public Socket {
});
}
+ int getSocketOption(int socket_option_key,
+ StrategyCallback **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,
+ StrategyCallback **socket_option_value) -> int {
+ switch (socket_option_key) {
+ case ConsumerCallbacksOptions::FWD_STRATEGY_CHANGE:
+ *socket_option_value = &on_fwd_strategy_;
+ break;
+ case ConsumerCallbacksOptions::REC_STRATEGY_CHANGE:
+ *socket_option_value = &on_rec_strategy_;
+ 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,
@@ -726,9 +835,9 @@ class ConsumerSocket : public Socket {
/* Condition variable for the wait */
std::condition_variable cv;
bool done = false;
- portal_->getIoService().dispatch([&socket_option_key,
- &socket_option_value, &mtx, &cv,
- &result, &done, &func]() {
+ portal_->getThread().tryRunHandlerNow([&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);
@@ -748,13 +857,12 @@ class ConsumerSocket : public Socket {
protected:
interface::ConsumerSocket *consumer_interface_;
- 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_;
+ hicn_packet_format_t packet_format_;
int interest_lifetime_;
double min_window_size_;
@@ -776,6 +884,8 @@ class ConsumerSocket : public Socket {
int rate_estimation_choice_;
// Verification parameters
+ uint32_t manifest_factor_relevant_;
+ uint32_t manifest_factor_alert_;
std::shared_ptr<auth::Verifier> verifier_;
transport::auth::KeyId *key_id_;
std::atomic_bool verify_signature_;
@@ -787,17 +897,25 @@ class ConsumerSocket : public Socket {
ConsumerInterestCallback on_interest_satisfied_;
ConsumerContentObjectCallback on_content_object_input_;
ConsumerTimerCallback stats_summary_;
+ StrategyCallback on_fwd_strategy_;
+ StrategyCallback on_rec_strategy_;
ReadCallback *read_callback_;
uint32_t timer_interval_milliseconds_;
// Transport protocol
- std::unique_ptr<protocol::TransportProtocol> transport_protocol_;
+ std::shared_ptr<protocol::TransportProtocol> transport_protocol_;
// Statistic
TransportStatistics stats_;
+ // RTC protocol
+ RtcTransportRecoveryStrategies recovery_strategy_;
+ bool aggregated_data_;
+ bool content_sharing_mode_;
+ bool aggregated_interests_;
+
utils::SpinLock guard_raaqm_params_;
std::string output_interface_;
};
diff --git a/libtransport/src/implementation/socket_producer.h b/libtransport/src/implementation/socket_producer.h
index 9daf79b9d..c5e0929b2 100644
--- a/libtransport/src/implementation/socket_producer.h
+++ b/libtransport/src/implementation/socket_producer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -40,6 +40,7 @@ namespace implementation {
using namespace core;
using namespace interface;
+using ProducerCallback = interface::ProducerSocket::Callback;
class ProducerSocket : public Socket {
private:
@@ -47,12 +48,15 @@ class ProducerSocket : public Socket {
std::shared_ptr<core::Portal> &&portal)
: Socket(std::move(portal)),
producer_interface_(producer_socket),
+ packet_format_(default_values::packet_format),
data_packet_size_(default_values::content_object_packet_size),
+ max_segment_size_(default_values::content_object_packet_size),
content_object_expiry_time_(default_values::content_object_expiry_time),
- async_thread_(),
- making_manifest_(false),
+ manifest_max_capacity_(default_values::manifest_max_capacity),
hash_algorithm_(auth::CryptoHashType::SHA256),
- suffix_strategy_(core::NextSegmentCalculationStrategy::INCREMENTAL),
+ suffix_strategy_(std::make_shared<utils::IncrementalSuffixStrategy>(0)),
+ aggregated_data_(false),
+ fec_setting_(""),
on_interest_input_(VOID_HANDLER),
on_interest_dropped_input_buffer_(VOID_HANDLER),
on_interest_inserted_input_buffer_(VOID_HANDLER),
@@ -63,29 +67,30 @@ class ProducerSocket : public Socket {
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) {
+ on_content_produced_(VOID_HANDLER),
+ application_callback_(nullptr) {
switch (protocol) {
case ProductionProtocolAlgorithms::RTC_PROD:
production_protocol_ =
- std::make_unique<protocol::RTCProductionProtocol>(this);
+ std::make_shared<protocol::RTCProductionProtocol>(this);
break;
case ProductionProtocolAlgorithms::BYTE_STREAM:
default:
production_protocol_ =
- std::make_unique<protocol::ByteStreamProductionProtocol>(this);
+ std::make_shared<protocol::ByteStreamProductionProtocol>(this);
break;
}
}
public:
ProducerSocket(interface::ProducerSocket *producer, int protocol)
- : ProducerSocket(producer, protocol, std::make_shared<core::Portal>()) {}
+ : ProducerSocket(producer, protocol, core::Portal::createShared()) {
+ is_async_ = true;
+ }
ProducerSocket(interface::ProducerSocket *producer, int protocol,
- asio::io_service &io_service)
- : ProducerSocket(producer, protocol,
- std::make_shared<core::Portal>(io_service)) {
- is_async_ = true;
+ ::utils::EventThread &worker)
+ : ProducerSocket(producer, protocol, core::Portal::createShared(worker)) {
}
virtual ~ProducerSocket() {}
@@ -98,31 +103,9 @@ class ProducerSocket : public Socket {
producer_interface_ = producer_socket;
}
- void connect() override {
- portal_->connect(false);
- production_protocol_->start();
- }
+ void connect() override { portal_->connect(false); }
- bool isRunning() override { return !production_protocol_->isRunning(); };
-
- 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 + produceStream(content_name, std::move(buf),
- is_last, offset);
- } else {
- produceStream(content_name, std::move(buf), is_last, offset);
- }
- });
- }
- }
+ bool isRunning() override { return production_protocol_->isRunning(); };
virtual uint32_t produceStream(const Name &content_name,
std::unique_ptr<utils::MemBuf> &&buffer,
@@ -156,12 +139,38 @@ class ProducerSocket : public Socket {
production_protocol_->produce(content_object);
}
+ void sendMapme() { production_protocol_->sendMapme(); }
+
void registerPrefix(const Prefix &producer_namespace) {
- production_protocol_->registerNamespaceWithNetwork(producer_namespace);
+ portal_->registerRoute(producer_namespace);
}
+ void start() { production_protocol_->start(); }
void stop() { production_protocol_->stop(); }
+ using Socket::getSocketOption;
+ using Socket::setSocketOption;
+
+ virtual int setSocketOption(int socket_option_key,
+ ProducerCallback *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,
+ ProducerCallback *socket_option_value) -> int {
+ switch (socket_option_key) {
+ case ProducerCallbacksOptions::PRODUCER_CALLBACK:
+ application_callback_ = socket_option_value;
+ break;
+ default:
+ return SOCKET_OPTION_NOT_SET;
+ }
+
+ return SOCKET_OPTION_SET;
+ });
+ }
+
virtual int setSocketOption(int socket_option_key,
uint32_t socket_option_value) {
switch (socket_option_key) {
@@ -172,6 +181,17 @@ class ProducerSocket : public Socket {
}
break;
+ case GeneralTransportOptions::MANIFEST_MAX_CAPACITY:
+ manifest_max_capacity_ = socket_option_value;
+ break;
+
+ case GeneralTransportOptions::MAX_SEGMENT_SIZE:
+ if (socket_option_value <= default_values::max_content_object_size &&
+ socket_option_value > 0) {
+ max_segment_size_ = socket_option_value;
+ }
+ break;
+
case GeneralTransportOptions::OUTPUT_BUFFER_SIZE:
production_protocol_->setOutputBufferSize(socket_option_value);
break;
@@ -180,6 +200,10 @@ class ProducerSocket : public Socket {
content_object_expiry_time_ = socket_option_value;
break;
+ case GeneralTransportOptions::PACKET_FORMAT:
+ packet_format_ = socket_option_value;
+ break;
+
default:
return SOCKET_OPTION_NOT_SET;
}
@@ -260,8 +284,8 @@ class ProducerSocket : public Socket {
virtual int setSocketOption(int socket_option_key, bool socket_option_value) {
switch (socket_option_key) {
- case GeneralTransportOptions::MAKE_MANIFEST:
- making_manifest_ = socket_option_value;
+ case RtcTransportOptions::AGGREGATED_DATA:
+ aggregated_data_ = socket_option_value;
break;
default:
@@ -385,7 +409,7 @@ class ProducerSocket : public Socket {
virtual int setSocketOption(
int socket_option_key,
- core::NextSegmentCalculationStrategy socket_option_value) {
+ const std::shared_ptr<utils::SuffixStrategy> &socket_option_value) {
switch (socket_option_key) {
case GeneralTransportOptions::SUFFIX_STRATEGY:
suffix_strategy_ = socket_option_value;
@@ -413,21 +437,68 @@ class ProducerSocket : public Socket {
return SOCKET_OPTION_SET;
}
+ virtual int setSocketOption(
+ int socket_option_key,
+ const std::shared_ptr<auth::Verifier> &socket_option_value) {
+ switch (socket_option_key) {
+ case GeneralTransportOptions::VERIFIER:
+ verifier_.reset();
+ verifier_ = socket_option_value;
+ return SOCKET_OPTION_SET;
+
+ default:
+ return SOCKET_OPTION_NOT_SET;
+ }
+ }
+
+ int getSocketOption(int socket_option_key,
+ ProducerCallback **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,
+ ProducerCallback **socket_option_value) -> int {
+ switch (socket_option_key) {
+ case ProducerCallbacksOptions::PRODUCER_CALLBACK:
+ *socket_option_value = application_callback_;
+ break;
+ default:
+ return SOCKET_OPTION_NOT_GET;
+ }
+
+ return SOCKET_OPTION_GET;
+ });
+ }
+
virtual int getSocketOption(int socket_option_key,
uint32_t &socket_option_value) {
switch (socket_option_key) {
+ case GeneralTransportOptions::MANIFEST_MAX_CAPACITY:
+ socket_option_value = (uint32_t)manifest_max_capacity_;
+ break;
+
case GeneralTransportOptions::OUTPUT_BUFFER_SIZE:
- socket_option_value = production_protocol_->getOutputBufferSize();
+ socket_option_value =
+ (uint32_t)production_protocol_->getOutputBufferSize();
break;
case GeneralTransportOptions::DATA_PACKET_SIZE:
socket_option_value = (uint32_t)data_packet_size_;
break;
+ case GeneralTransportOptions::MAX_SEGMENT_SIZE:
+ socket_option_value = (uint32_t)max_segment_size_;
+ break;
+
case GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME:
socket_option_value = content_object_expiry_time_;
break;
+ case GeneralTransportOptions::PACKET_FORMAT:
+ socket_option_value = packet_format_;
+ break;
+
default:
return SOCKET_OPTION_NOT_SET;
}
@@ -438,14 +509,14 @@ class ProducerSocket : public Socket {
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;
-
case GeneralTransportOptions::ASYNC_MODE:
socket_option_value = is_async_;
break;
+ case RtcTransportOptions::AGGREGATED_DATA:
+ socket_option_value = aggregated_data_;
+ break;
+
default:
return SOCKET_OPTION_NOT_GET;
}
@@ -547,21 +618,6 @@ class ProducerSocket : public Socket {
});
}
- virtual int getSocketOption(
- int socket_option_key,
- std::shared_ptr<core::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,
auth::CryptoHashType &socket_option_value) {
switch (socket_option_key) {
@@ -577,7 +633,7 @@ class ProducerSocket : public Socket {
virtual int getSocketOption(
int socket_option_key,
- core::NextSegmentCalculationStrategy &socket_option_value) {
+ std::shared_ptr<utils::SuffixStrategy> &socket_option_value) {
switch (socket_option_key) {
case GeneralTransportOptions::SUFFIX_STRATEGY:
socket_option_value = suffix_strategy_;
@@ -603,9 +659,43 @@ class ProducerSocket : public Socket {
return SOCKET_OPTION_GET;
}
+ int getSocketOption(int socket_option_key,
+ std::shared_ptr<auth::Verifier> &socket_option_value) {
+ switch (socket_option_key) {
+ case GeneralTransportOptions::VERIFIER:
+ socket_option_value = verifier_;
+ return SOCKET_OPTION_GET;
+
+ default:
+ return SOCKET_OPTION_NOT_GET;
+ }
+ }
+
+ int getSocketOption(int socket_option_key, std::string &socket_option_value) {
+ switch (socket_option_key) {
+ case GeneralTransportOptions::FEC_TYPE:
+ socket_option_value = fec_setting_;
+ 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;
+ int result = SOCKET_OPTION_NOT_SET;
+ switch (socket_option_key) {
+ case GeneralTransportOptions::FEC_TYPE:
+ fec_setting_ = socket_option_value;
+ result = SOCKET_OPTION_SET;
+ break;
+
+ default:
+ return result;
+ }
+ return result;
}
// If the thread calling lambda_func is not the same of io_service, this
@@ -623,9 +713,9 @@ class ProducerSocket : public Socket {
std::condition_variable cv;
bool done = false;
- portal_->getIoService().dispatch([&socket_option_key,
- &socket_option_value, &mtx, &cv,
- &result, &done, &func]() {
+ portal_->getThread().tryRunHandlerNow([&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);
@@ -655,9 +745,9 @@ class ProducerSocket : public Socket {
/* Condition variable for the wait */
std::condition_variable cv;
bool done = false;
- portal_->getIoService().dispatch([&socket_option_key,
- &socket_option_value, &mtx, &cv,
- &result, &done, &func]() {
+ portal_->getThread().tryRunHandlerNow([&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);
@@ -677,20 +767,24 @@ class ProducerSocket : public Socket {
// Threads
protected:
interface::ProducerSocket *producer_interface_;
- asio::io_service io_service_;
+ std::atomic<hicn_packet_format_t> packet_format_;
std::atomic<size_t> data_packet_size_;
+ std::atomic<size_t> max_segment_size_;
std::atomic<uint32_t> content_object_expiry_time_;
- utils::EventThread async_thread_;
-
- std::atomic<bool> making_manifest_;
+ std::atomic<uint32_t> manifest_max_capacity_;
std::atomic<auth::CryptoHashType> hash_algorithm_;
std::atomic<auth::CryptoSuite> crypto_suite_;
utils::SpinLock signer_lock_;
- std::shared_ptr<auth::Signer> signer_;
- core::NextSegmentCalculationStrategy suffix_strategy_;
+ std::shared_ptr<utils::SuffixStrategy> suffix_strategy_;
- std::unique_ptr<protocol::ProductionProtocol> production_protocol_;
+ std::shared_ptr<protocol::ProductionProtocol> production_protocol_;
+
+ // RTC transport
+ bool aggregated_data_;
+
+ // FEC setting
+ std::string fec_setting_;
// callbacks
ProducerInterestCallback on_interest_input_;
@@ -706,6 +800,8 @@ class ProducerSocket : public Socket {
ProducerContentObjectCallback on_content_object_evicted_from_output_buffer_;
ProducerContentCallback on_content_produced_;
+
+ ProducerCallback *application_callback_;
};
} // namespace implementation
diff --git a/libtransport/src/implementation/tls_rtc_socket_producer.cc b/libtransport/src/implementation/tls_rtc_socket_producer.cc
deleted file mode 100644
index db62b10c1..000000000
--- a/libtransport/src/implementation/tls_rtc_socket_producer.cc
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/transport/core/interest.h>
-#include <hicn/transport/interfaces/p2psecure_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 {
-
-int TLSRTCProducerSocket::read(BIO *b, char *buf, size_t size,
- size_t *readbytes) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = TLSRTCProducerSocket::readOld(b, buf, (int)size);
-
- if (ret <= 0) {
- *readbytes = 0;
- return ret;
- }
-
- *readbytes = (size_t)ret;
-
- return 1;
-}
-
-int TLSRTCProducerSocket::readOld(BIO *b, char *buf, int size) {
- TLSRTCProducerSocket *socket;
- socket = (TLSRTCProducerSocket *)BIO_get_data(b);
-
- std::unique_lock<std::mutex> lck(socket->mtx_);
- if (!socket->something_to_read_) {
- (socket->cv_).wait(lck);
- }
-
- utils::MemBuf *membuf = socket->handshake_packet_->next();
- int size_to_read;
-
- if ((int)membuf->length() > size) {
- size_to_read = size;
- } else {
- size_to_read = membuf->length();
- socket->something_to_read_ = false;
- }
-
- std::memcpy(buf, membuf->data(), size_to_read);
- membuf->trimStart(size_to_read);
-
- return size_to_read;
-}
-
-int TLSRTCProducerSocket::write(BIO *b, const char *buf, size_t size,
- size_t *written) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = TLSRTCProducerSocket::writeOld(b, buf, (int)size);
-
- if (ret <= 0) {
- *written = 0;
- return ret;
- }
-
- *written = (size_t)ret;
-
- return 1;
-}
-
-int TLSRTCProducerSocket::writeOld(BIO *b, const char *buf, int num) {
- TLSRTCProducerSocket *socket;
- socket = (TLSRTCProducerSocket *)BIO_get_data(b);
-
- if (socket->getHandshakeState() != SERVER_FINISHED && socket->first_) {
- bool making_manifest = socket->parent_->making_manifest_;
-
- socket->tls_chunks_--;
- socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST,
- false);
- socket->parent_->ProducerSocket::produce(
- socket->name_, (const uint8_t *)buf, num, socket->tls_chunks_ == 0, 0);
- socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST,
- making_manifest);
- socket->first_ = false;
-
- } else {
- std::unique_ptr<utils::MemBuf> mbuf =
- utils::MemBuf::copyBuffer(buf, (std::size_t)num, 0, 0);
- auto a = mbuf.release();
-
- socket->async_thread_.add([socket = socket, a]() {
- socket->to_call_oncontentproduced_--;
- auto mbuf = std::unique_ptr<utils::MemBuf>(a);
-
- socket->RTCProducerSocket::produce(std::move(mbuf));
-
- ProducerContentCallback on_content_produced_application;
- socket->getSocketOption(ProducerCallbacksOptions::CONTENT_PRODUCED,
- on_content_produced_application);
-
- if (socket->to_call_oncontentproduced_ == 0 &&
- on_content_produced_application) {
- on_content_produced_application(
- (transport::interface::ProducerSocket &)(*socket->getInterface()),
- std::error_code(), 0);
- }
- });
- }
-
- return num;
-}
-
-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);
- BIO_meth_set_write(bio_meth, TLSRTCProducerSocket::writeOld);
- BIO_meth_set_ctrl(bio_meth, TLSProducerSocket::ctrl);
- BIO *bio = BIO_new(bio_meth);
- BIO_set_init(bio, 1);
- BIO_set_data(bio, this);
- SSL_set_bio(ssl_, bio, bio);
-}
-
-void TLSRTCProducerSocket::accept() {
- HandshakeState handshake_state = getHandshakeState();
-
- if (handshake_state == UNINITIATED || handshake_state == CLIENT_HELLO) {
- tls_chunks_ = 1;
- int result = SSL_accept(ssl_);
-
- if (result != 1)
- throw errors::RuntimeException("Unable to perform client handshake");
- }
-
- DLOG_IF(INFO, VLOG_IS_ON(2)) << "Handshake performed!";
-
- parent_->list_producers.push_front(
- std::move(parent_->map_producers[handshake_name_]));
- parent_->map_producers.erase(handshake_name_);
-
- ProducerInterestCallback on_interest_process_decrypted;
- getSocketOption(ProducerCallbacksOptions::CACHE_MISS,
- on_interest_process_decrypted);
-
- if (on_interest_process_decrypted) {
- Interest inter(std::move(handshake_packet_));
- on_interest_process_decrypted(
- (transport::interface::ProducerSocket &)(*getInterface()), inter);
- }
-
- parent_->cv_.notify_one();
-}
-
-int TLSRTCProducerSocket::async_accept() {
- if (!async_thread_.stopped()) {
- async_thread_.add([this]() { this->TLSRTCProducerSocket::accept(); });
- } else {
- throw errors::RuntimeException(
- "Async thread not running, impossible to perform handshake");
- }
-
- return 1;
-}
-
-void TLSRTCProducerSocket::produce(std::unique_ptr<utils::MemBuf> &&buffer) {
- HandshakeState handshake_state = getHandshakeState();
-
- if (handshake_state != SERVER_FINISHED) {
- throw errors::RuntimeException(
- "New handshake on the same P2P secure producer socket not supported");
- }
-
- size_t buf_size = buffer->length();
- tls_chunks_ = ceil((float)buf_size / (float)SSL3_RT_MAX_PLAIN_LENGTH);
- to_call_oncontentproduced_ = tls_chunks_;
-
- SSL_write(ssl_, buffer->data(), buf_size);
- BIO *wbio = SSL_get_wbio(ssl_);
- int i = BIO_flush(wbio);
- (void)i; // To shut up gcc 5
-}
-
-} // namespace implementation
-} // namespace transport
diff --git a/libtransport/src/implementation/tls_rtc_socket_producer.h b/libtransport/src/implementation/tls_rtc_socket_producer.h
deleted file mode 100644
index 92c657afc..000000000
--- a/libtransport/src/implementation/tls_rtc_socket_producer.h
+++ /dev/null
@@ -1,57 +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 <implementation/tls_socket_producer.h>
-
-namespace transport {
-namespace implementation {
-
-class P2PSecureProducerSocket;
-
-class TLSRTCProducerSocket : public TLSProducerSocket {
- friend class P2PSecureProducerSocket;
-
- public:
- explicit TLSRTCProducerSocket(interface::ProducerSocket *producer_socket,
- P2PSecureProducerSocket *parent,
- const Name &handshake_name);
-
- ~TLSRTCProducerSocket() = default;
-
- uint32_t produceDatagram(const Name &content_name,
- std::unique_ptr<utils::MemBuf> &&buffer) override;
-
- void accept() override;
-
- int async_accept() override;
-
- using TLSProducerSocket::onInterest;
- using TLSProducerSocket::produce;
-
- protected:
- static int read(BIO *b, char *buf, size_t size, size_t *readbytes);
-
- static int readOld(BIO *h, char *buf, int size);
-
- static int write(BIO *b, const char *buf, size_t size, size_t *written);
-
- static int writeOld(BIO *h, const char *buf, int num);
-};
-
-} // namespace implementation
-
-} // end namespace transport
diff --git a/libtransport/src/implementation/tls_socket_consumer.cc b/libtransport/src/implementation/tls_socket_consumer.cc
deleted file mode 100644
index 65472b41d..000000000
--- a/libtransport/src/implementation/tls_socket_consumer.cc
+++ /dev/null
@@ -1,368 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <implementation/tls_socket_consumer.h>
-#include <openssl/bio.h>
-#include <openssl/ssl.h>
-#include <openssl/tls1.h>
-
-#include <random>
-
-namespace transport {
-namespace implementation {
-
-void TLSConsumerSocket::setInterestPayload(interface::ConsumerSocket &c,
- const core::Interest &interest) {
- Interest &int2 = const_cast<Interest &>(interest);
- random_suffix_ = int2.getName().getSuffix();
-
- if (payload_ != NULL) int2.appendPayload(std::move(payload_));
-}
-
-/* Return the number of read bytes in the return param */
-int readOldTLS(BIO *b, char *buf, int size) {
- if (size < 0) return size;
-
- TLSConsumerSocket *socket;
- socket = (TLSConsumerSocket *)BIO_get_data(b);
-
- std::unique_lock<std::mutex> lck(socket->mtx_);
-
- if (!socket->something_to_read_) {
- if (!socket->transport_protocol_->isRunning()) {
- socket->network_name_.setSuffix(socket->random_suffix_);
- socket->ConsumerSocket::asyncConsume(socket->network_name_);
- }
-
- if (!socket->something_to_read_) socket->cv_.wait(lck);
- }
-
- size_t size_to_read, read;
- size_t chain_size = socket->head_->length();
-
- if (socket->head_->isChained())
- chain_size = socket->head_->computeChainDataLength();
-
- if (chain_size > (size_t)size) {
- read = size_to_read = (size_t)size;
- } else {
- read = size_to_read = chain_size;
- socket->something_to_read_ = false;
- }
-
- while (size_to_read) {
- if (socket->head_->length() < size_to_read) {
- std::memcpy(buf, socket->head_->data(), socket->head_->length());
- size_to_read -= socket->head_->length();
- buf += socket->head_->length();
- socket->head_ = socket->head_->pop();
- } else {
- std::memcpy(buf, socket->head_->data(), size_to_read);
- socket->head_->trimStart(size_to_read);
- size_to_read = 0;
- }
- }
-
- return (int)read;
-}
-
-/* Return the number of read bytes in readbytes */
-int readTLS(BIO *b, char *buf, size_t size, size_t *readbytes) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = readOldTLS(b, buf, (int)size);
-
- if (ret <= 0) {
- *readbytes = 0;
- return ret;
- }
-
- *readbytes = (size_t)ret;
-
- return 1;
-}
-
-/* Return the number of written bytes in the return param */
-int writeOldTLS(BIO *b, const char *buf, int num) {
- TLSConsumerSocket *socket;
- socket = (TLSConsumerSocket *)BIO_get_data(b);
-
- socket->payload_ = utils::MemBuf::copyBuffer(buf, num);
-
- socket->ConsumerSocket::setSocketOption(
- ConsumerCallbacksOptions::INTEREST_OUTPUT,
- (ConsumerInterestCallback)std::bind(
- &TLSConsumerSocket::setInterestPayload, socket, std::placeholders::_1,
- std::placeholders::_2));
-
- return num;
-}
-
-/* Return the number of written bytes in written */
-int writeTLS(BIO *b, const char *buf, size_t size, size_t *written) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = writeOldTLS(b, buf, (int)size);
-
- if (ret <= 0) {
- *written = 0;
- return ret;
- }
-
- *written = (size_t)ret;
-
- return 1;
-}
-
-long ctrlTLS(BIO *b, int cmd, long num, void *ptr) { return 1; }
-
-TLSConsumerSocket::TLSConsumerSocket(interface::ConsumerSocket *consumer_socket,
- int protocol, SSL *ssl)
- : ConsumerSocket(consumer_socket, protocol),
- name_(),
- decrypted_content_(),
- payload_(),
- head_(),
- something_to_read_(false),
- content_downloaded_(false),
- random_suffix_(),
- producer_namespace_(),
- read_callback_decrypted_(),
- mtx_(),
- cv_(),
- async_downloader_tls_() {
- /* Create the (d)TLS state */
- const SSL_METHOD *meth = TLS_client_method();
- ctx_ = SSL_CTX_new(meth);
-
- int result =
- SSL_CTX_set_ciphersuites(ctx_,
- "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_"
- "SHA256:TLS_AES_128_GCM_SHA256");
- if (result != 1) {
- throw errors::RuntimeException(
- "Unable to set cipher list on TLS subsystem. Aborting.");
- }
-
- SSL_CTX_set_min_proto_version(ctx_, TLS1_3_VERSION);
- SSL_CTX_set_max_proto_version(ctx_, TLS1_3_VERSION);
- SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, NULL);
- SSL_CTX_set_ssl_version(ctx_, meth);
-
- ssl_ = ssl;
-
- BIO_METHOD *bio_meth =
- BIO_meth_new(BIO_TYPE_CONNECT, "secure consumer socket");
- BIO_meth_set_read(bio_meth, 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);
- SSL_set_bio(ssl_, bio, bio);
-
- std::default_random_engine generator;
- std::uniform_int_distribution<int> distribution(
- 1, std::numeric_limits<uint32_t>::max());
- random_suffix_ = 0;
-
- this->ConsumerSocket::setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK,
- this);
-};
-
-/* 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);
-
- this->ConsumerSocket::setSocketOption(
- ConsumerCallbacksOptions::INTEREST_OUTPUT,
- (ConsumerInterestCallback)std::bind(
- &TLSConsumerSocket::setInterestPayload, this, std::placeholders::_1,
- std::placeholders::_2));
-
- return consume(name);
-}
-
-int TLSConsumerSocket::consume(const Name &name) {
- if (transport_protocol_->isRunning()) {
- return CONSUMER_BUSY;
- }
-
- if ((SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) {
- throw errors::RuntimeException("Handshake not performed");
- }
-
- return download_content(name);
-}
-
-int TLSConsumerSocket::download_content(const Name &name) {
- network_name_ = name;
- network_name_.setSuffix(0);
- something_to_read_ = false;
- content_downloaded_ = false;
-
- std::size_t max_buffer_size = read_callback_decrypted_->maxBufferSize();
- std::size_t buffer_size =
- read_callback_decrypted_->maxBufferSize() + SSL3_RT_MAX_PLAIN_LENGTH;
- decrypted_content_ = utils::MemBuf::createCombined(buffer_size);
- int result = -1;
- std::size_t size = 0;
-
- while (!content_downloaded_ || something_to_read_) {
- result = SSL_read(this->ssl_, decrypted_content_->writableTail(),
- SSL3_RT_MAX_PLAIN_LENGTH);
-
- /* SSL_read returns the data only if there were SSL3_RT_MAX_PLAIN_LENGTH of
- * the data has been fully downloaded */
-
- /* ASSERT((result < SSL3_RT_MAX_PLAIN_LENGTH && content_downloaded_) || */
- /* result == SSL3_RT_MAX_PLAIN_LENGTH); */
-
- if (result >= 0) {
- size += result;
- decrypted_content_->append(result);
- } else {
- throw errors::RuntimeException("Unable to download content");
- }
-
- if (decrypted_content_->length() >= max_buffer_size) {
- if (read_callback_decrypted_->isBufferMovable()) {
- /* No need to perform an additional copy. The whole buffer will be
- * tranferred to the application. */
- read_callback_decrypted_->readBufferAvailable(
- std::move(decrypted_content_));
- decrypted_content_ = utils::MemBuf::create(buffer_size);
- } else {
- /* The buffer will be copied into the application-provided buffer */
- uint8_t *buffer;
- std::size_t length;
- std::size_t total_length = decrypted_content_->length();
-
- while (decrypted_content_->length()) {
- buffer = nullptr;
- length = 0;
- read_callback_decrypted_->getReadBuffer(&buffer, &length);
-
- if (!buffer || !length) {
- throw errors::RuntimeException(
- "Invalid buffer provided by the application.");
- }
-
- auto to_copy = std::min(decrypted_content_->length(), length);
- std::memcpy(buffer, decrypted_content_->data(), to_copy);
- decrypted_content_->trimStart(to_copy);
- }
-
- read_callback_decrypted_->readDataAvailable(total_length);
- decrypted_content_->clear();
- }
- }
- }
-
- read_callback_decrypted_->readSuccess(size);
-
- return CONSUMER_FINISHED;
-}
-
-int TLSConsumerSocket::asyncConsume(const Name &name,
- std::unique_ptr<utils::MemBuf> &&buffer) {
- this->payload_ = std::move(buffer);
-
- this->ConsumerSocket::setSocketOption(
- ConsumerCallbacksOptions::INTEREST_OUTPUT,
- (ConsumerInterestCallback)std::bind(
- &TLSConsumerSocket::setInterestPayload, this, std::placeholders::_1,
- std::placeholders::_2));
-
- return asyncConsume(name);
-}
-
-int TLSConsumerSocket::asyncConsume(const Name &name) {
- if ((SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) {
- throw errors::RuntimeException("Handshake not performed");
- }
-
- if (!async_downloader_tls_.stopped()) {
- async_downloader_tls_.add([this, name]() { download_content(name); });
- }
-
- return CONSUMER_RUNNING;
-}
-
-void TLSConsumerSocket::registerPrefix(const Prefix &producer_namespace) {
- producer_namespace_ = producer_namespace;
-}
-
-int TLSConsumerSocket::setSocketOption(int socket_option_key,
- ReadCallback *socket_option_value) {
- 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_decrypted_ = socket_option_value;
- break;
- default:
- return SOCKET_OPTION_NOT_SET;
- }
-
- return SOCKET_OPTION_SET;
- });
-}
-
-void TLSConsumerSocket::getReadBuffer(uint8_t **application_buffer,
- size_t *max_length) {}
-
-void TLSConsumerSocket::readDataAvailable(size_t length) noexcept {}
-
-size_t TLSConsumerSocket::maxBufferSize() const {
- return SSL3_RT_MAX_PLAIN_LENGTH;
-}
-
-void TLSConsumerSocket::readBufferAvailable(
- std::unique_ptr<utils::MemBuf> &&buffer) noexcept {
- std::unique_lock<std::mutex> lck(this->mtx_);
-
- if (head_) {
- head_->prependChain(std::move(buffer));
- } else {
- head_ = std::move(buffer);
- }
-
- something_to_read_ = true;
- cv_.notify_one();
-}
-
-void TLSConsumerSocket::readError(const std::error_code ec) noexcept {}
-
-void TLSConsumerSocket::readSuccess(std::size_t total_size) noexcept {
- std::unique_lock<std::mutex> lck(this->mtx_);
- content_downloaded_ = true;
- something_to_read_ = true;
- cv_.notify_one();
-}
-
-bool TLSConsumerSocket::isBufferMovable() noexcept { return true; }
-
-} // namespace implementation
-} // namespace transport
diff --git a/libtransport/src/implementation/tls_socket_consumer.h b/libtransport/src/implementation/tls_socket_consumer.h
deleted file mode 100644
index be08ec47d..000000000
--- a/libtransport/src/implementation/tls_socket_consumer.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/interfaces/socket_consumer.h>
-#include <implementation/socket_consumer.h>
-#include <openssl/ssl.h>
-
-namespace transport {
-namespace implementation {
-
-class TLSConsumerSocket : public ConsumerSocket,
- 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);
-
- /* Return the number of read bytes in the return param */
- friend int readOldTLS(BIO *h, char *buf, int size);
-
- /* Return the number of written bytes in written */
- friend int writeTLS(BIO *b, const char *buf, size_t size, size_t *written);
-
- /* Return the number of written bytes in the return param */
- friend int writeOldTLS(BIO *h, const char *buf, int num);
-
- friend long ctrlTLS(BIO *b, int cmd, long num, void *ptr);
-
- public:
- explicit TLSConsumerSocket(interface::ConsumerSocket *consumer_socket,
- int protocol, SSL *ssl_);
-
- ~TLSConsumerSocket();
-
- int consume(const Name &name, std::unique_ptr<utils::MemBuf> &&buffer);
- int consume(const Name &name) override;
-
- int asyncConsume(const Name &name, std::unique_ptr<utils::MemBuf> &&buffer);
- int asyncConsume(const Name &name) override;
-
- void registerPrefix(const Prefix &producer_namespace);
-
- int setSocketOption(
- int socket_option_key,
- interface::ConsumerSocket::ReadCallback *socket_option_value) override;
-
- using ConsumerSocket::getSocketOption;
- using ConsumerSocket::setSocketOption;
-
- protected:
- /* Callback invoked once an interest has been received and its payload
- * decrypted */
- ConsumerInterestCallback on_interest_input_decrypted_;
- ConsumerInterestCallback on_interest_process_decrypted_;
-
- private:
- Name name_;
- /* SSL handle */
- SSL *ssl_;
- SSL_CTX *ctx_;
- /* Chain of MemBuf to be used as a temporary buffer to pass descypted data
- * from the underlying layer to the application */
- std::unique_ptr<utils::MemBuf> decrypted_content_;
- /* Chain of MemBuf holding the payload to be written into interest or data */
- std::unique_ptr<utils::MemBuf> payload_;
- /* Chain of MemBuf holding the data retrieved from the underlying layer */
- std::unique_ptr<utils::MemBuf> head_;
- bool something_to_read_;
- bool content_downloaded_;
- uint32_t random_suffix_;
- Prefix producer_namespace_;
- interface::ConsumerSocket::ReadCallback *read_callback_decrypted_;
- std::mutex mtx_;
- /* Condition variable for the wait */
- std::condition_variable cv_;
- utils::EventThread async_downloader_tls_;
-
- void setInterestPayload(interface::ConsumerSocket &c,
- const core::Interest &interest);
-
- virtual void getReadBuffer(uint8_t **application_buffer,
- size_t *max_length) override;
-
- virtual void readDataAvailable(size_t length) noexcept override;
-
- virtual size_t maxBufferSize() const override;
-
- virtual void readBufferAvailable(
- std::unique_ptr<utils::MemBuf> &&buffer) noexcept override;
-
- virtual void readError(const std::error_code ec) noexcept override;
-
- virtual void readSuccess(std::size_t total_size) noexcept override;
-
- virtual bool isBufferMovable() noexcept override;
-
- int download_content(const Name &name);
-};
-
-} // namespace implementation
-} // end namespace transport
diff --git a/libtransport/src/implementation/tls_socket_producer.cc b/libtransport/src/implementation/tls_socket_producer.cc
deleted file mode 100644
index 3992ca45c..000000000
--- a/libtransport/src/implementation/tls_socket_producer.cc
+++ /dev/null
@@ -1,551 +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/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 implementation {
-
-/* Return the number of read bytes in readbytes */
-int TLSProducerSocket::read(BIO *b, char *buf, size_t size, size_t *readbytes) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = TLSProducerSocket::readOld(b, buf, (int)size);
-
- if (ret <= 0) {
- *readbytes = 0;
- return ret;
- }
-
- *readbytes = (size_t)ret;
-
- return 1;
-}
-
-/* Return the number of read bytes in the return param */
-int TLSProducerSocket::readOld(BIO *b, char *buf, int size) {
- TLSProducerSocket *socket;
- socket = (TLSProducerSocket *)BIO_get_data(b);
-
- std::unique_lock<std::mutex> lck(socket->mtx_);
-
- DLOG_IF(INFO, VLOG_IS_ON(4)) << "Start wait on the CV.";
-
- if (!socket->something_to_read_) {
- (socket->cv_).wait(lck);
- }
-
- DLOG_IF(INFO, VLOG_IS_ON(4)) << "CV unlocked.";
-
- /* Either there already is something to read, or the thread has been waken up.
- * We must return the payload in the interest anyway */
- utils::MemBuf *membuf = socket->handshake_packet_->next();
- int size_to_read;
-
- if ((int)membuf->length() > size) {
- size_to_read = size;
- } else {
- size_to_read = (int)membuf->length();
- socket->something_to_read_ = false;
- }
-
- std::memcpy(buf, membuf->data(), size_to_read);
- membuf->trimStart(size_to_read);
-
- return size_to_read;
-}
-
-/* Return the number of written bytes in written */
-int TLSProducerSocket::write(BIO *b, const char *buf, size_t size,
- size_t *written) {
- int ret;
-
- if (size > INT_MAX) size = INT_MAX;
-
- ret = TLSProducerSocket::writeOld(b, buf, (int)size);
-
- if (ret <= 0) {
- *written = 0;
- return ret;
- }
-
- *written = (size_t)ret;
-
- return 1;
-}
-
-/* Return the number of written bytes in the return param */
-int TLSProducerSocket::writeOld(BIO *b, const char *buf, int num) {
- TLSProducerSocket *socket;
- socket = (TLSProducerSocket *)BIO_get_data(b);
-
- if (socket->getHandshakeState() != SERVER_FINISHED && socket->first_) {
- bool making_manifest = socket->parent_->making_manifest_;
-
- //! socket->tls_chunks_ corresponds to is_last
- socket->tls_chunks_--;
- socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST,
- false);
- socket->parent_->ProducerSocket::produceStream(
- socket->name_, (const uint8_t *)buf, num, socket->tls_chunks_ == 0,
- socket->last_segment_);
- socket->parent_->setSocketOption(GeneralTransportOptions::MAKE_MANIFEST,
- making_manifest);
- socket->first_ = false;
- } else {
- socket->still_writing_ = true;
-
- std::unique_ptr<utils::MemBuf> mbuf =
- utils::MemBuf::copyBuffer(buf, (std::size_t)num, 0, 0);
- auto a = mbuf.release();
-
- socket->async_thread_.add([socket = socket, a]() {
- auto mbuf = std::unique_ptr<utils::MemBuf>(a);
-
- socket->tls_chunks_--;
- socket->to_call_oncontentproduced_--;
-
- socket->last_segment_ += socket->ProducerSocket::produceStream(
- socket->name_, std::move(mbuf), socket->tls_chunks_ == 0,
- socket->last_segment_);
-
- ProducerContentCallback *on_content_produced_application;
- socket->getSocketOption(ProducerCallbacksOptions::CONTENT_PRODUCED,
- &on_content_produced_application);
-
- if (socket->to_call_oncontentproduced_ == 0 &&
- on_content_produced_application) {
- on_content_produced_application->operator()(*socket->getInterface(),
- std::error_code(), 0);
- }
- });
- }
-
- return num;
-}
-
-TLSProducerSocket::TLSProducerSocket(interface::ProducerSocket *producer_socket,
- P2PSecureProducerSocket *parent,
- const Name &handshake_name)
- : ProducerSocket(producer_socket,
- ProductionProtocolAlgorithms::BYTE_STREAM),
- on_content_produced_application_(),
- mtx_(),
- cv_(),
- something_to_read_(false),
- handshake_state_(UNINITIATED),
- name_(),
- handshake_packet_(),
- last_segment_(0),
- parent_(parent),
- first_(true),
- handshake_name_(handshake_name),
- tls_chunks_(0),
- to_call_oncontentproduced_(0),
- still_writing_(false),
- encryption_thread_() {
- const SSL_METHOD *meth = TLS_server_method();
- ctx_ = SSL_CTX_new(meth);
-
- /* Setup SSL context (identity and parameter to use TLS 1.3) */
- SSL_CTX_use_certificate(ctx_, parent->cert_509_);
- SSL_CTX_use_PrivateKey(ctx_, parent->pkey_rsa_);
-
- int result =
- SSL_CTX_set_ciphersuites(ctx_,
- "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_"
- "SHA256:TLS_AES_128_GCM_SHA256");
-
- if (result != 1) {
- throw errors::RuntimeException(
- "Unable to set cipher list on TLS subsystem. Aborting.");
- }
-
- // We force it to be TLS 1.3
- SSL_CTX_set_min_proto_version(ctx_, TLS1_3_VERSION);
- SSL_CTX_set_max_proto_version(ctx_, TLS1_3_VERSION);
- SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, NULL);
- SSL_CTX_set_num_tickets(ctx_, 0);
-
- result = SSL_CTX_add_custom_ext(
- ctx_, 100, SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
- TLSProducerSocket::addHicnKeyIdCb, TLSProducerSocket::freeHicnKeyIdCb,
- this, TLSProducerSocket::parseHicnKeyIdCb, NULL);
-
- ssl_ = SSL_new(ctx_);
-
- /* Setup this producer socker as the bio that TLS will use to write and read
- * data (in stream mode) */
- BIO_METHOD *bio_meth =
- BIO_meth_new(BIO_TYPE_ACCEPT, "secure producer socket");
- BIO_meth_set_read(bio_meth, TLSProducerSocket::readOld);
- BIO_meth_set_write(bio_meth, TLSProducerSocket::writeOld);
- BIO_meth_set_ctrl(bio_meth, TLSProducerSocket::ctrl);
- BIO *bio = BIO_new(bio_meth);
- BIO_set_init(bio, 1);
- BIO_set_data(bio, this);
- SSL_set_bio(ssl_, bio, bio);
-
- /* Set the callback so that when an interest is received we catch it and we
- * decrypt the payload before passing it to the application. */
- this->ProducerSocket::setSocketOption(
- ProducerCallbacksOptions::CACHE_MISS,
- (ProducerInterestCallback)std::bind(&TLSProducerSocket::cacheMiss, this,
- std::placeholders::_1,
- std::placeholders::_2));
-
- this->ProducerSocket::setSocketOption(
- ProducerCallbacksOptions::CONTENT_PRODUCED,
- (ProducerContentCallback)bind(
- &TLSProducerSocket::onContentProduced, this, std::placeholders::_1,
- std::placeholders::_2, std::placeholders::_3));
-}
-
-/* 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() {
- HandshakeState handshake_state = getHandshakeState();
-
- if (handshake_state == UNINITIATED || handshake_state == CLIENT_HELLO) {
- tls_chunks_ = 1;
- int result = SSL_accept(ssl_);
-
- if (result != 1)
- throw errors::RuntimeException("Unable to perform client handshake");
- }
-
- parent_->list_producers.push_front(
- std::move(parent_->map_producers[handshake_name_]));
- parent_->map_producers.erase(handshake_name_);
-
- ProducerInterestCallback *on_interest_process_decrypted;
- getSocketOption(ProducerCallbacksOptions::CACHE_MISS,
- &on_interest_process_decrypted);
-
- if (*on_interest_process_decrypted) {
- Interest inter(std::move(*handshake_packet_));
- handshake_packet_.reset();
- on_interest_process_decrypted->operator()(*getInterface(), inter);
- } else {
- throw errors::RuntimeException(
- "On interest process unset: unable to perform handshake");
- }
-
- handshake_state_ = SERVER_FINISHED;
- DLOG_IF(INFO, VLOG_IS_ON(2)) << "Handshake performed!";
-}
-
-int TLSProducerSocket::async_accept() {
- if (!async_thread_.stopped()) {
- async_thread_.add([this]() { this->accept(); });
- } else {
- throw errors::RuntimeException(
- "Async thread not running: unable to perform handshake");
- }
-
- return 1;
-}
-
-void TLSProducerSocket::onInterest(ProducerSocket &p, Interest &interest) {
- HandshakeState handshake_state = getHandshakeState();
-
- if (handshake_state == UNINITIATED || handshake_state == CLIENT_HELLO) {
- std::unique_lock<std::mutex> lck(mtx_);
-
- name_ = interest.getName();
- // interest.separateHeaderPayload();
- handshake_packet_ = interest.acquireMemBufReference();
- something_to_read_ = true;
-
- cv_.notify_one();
- return;
- } else if (handshake_state == SERVER_FINISHED) {
- // interest.separateHeaderPayload();
- handshake_packet_ = interest.acquireMemBufReference();
- something_to_read_ = true;
-
- if (interest.getPayload()->length() > 0) {
- SSL_read(
- ssl_,
- const_cast<unsigned char *>(interest.getPayload()->writableData()),
- (int)interest.getPayload()->length());
- }
-
- ProducerInterestCallback *on_interest_input_decrypted;
- getSocketOption(ProducerCallbacksOptions::INTEREST_INPUT,
- &on_interest_input_decrypted);
-
- if (*on_interest_input_decrypted)
- (*on_interest_input_decrypted)(*getInterface(), interest);
- }
-}
-
-void TLSProducerSocket::cacheMiss(interface::ProducerSocket &p,
- Interest &interest) {
- HandshakeState handshake_state = getHandshakeState();
-
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "On cache miss in TLS socket producer.";
-
- if (handshake_state == CLIENT_HELLO) {
- std::unique_lock<std::mutex> lck(mtx_);
-
- // interest.separateHeaderPayload();
- handshake_packet_ = interest.acquireMemBufReference();
- something_to_read_ = true;
- handshake_state_ = CLIENT_FINISHED;
-
- cv_.notify_one();
- } else if (handshake_state == SERVER_FINISHED) {
- // interest.separateHeaderPayload();
- handshake_packet_ = interest.acquireMemBufReference();
- something_to_read_ = true;
-
- if (interest.getPayload()->length() > 0) {
- SSL_read(
- ssl_,
- const_cast<unsigned char *>(interest.getPayload()->writableData()),
- (int)interest.getPayload()->length());
- }
-
- if (on_interest_process_decrypted_ != VOID_HANDLER)
- on_interest_process_decrypted_(*getInterface(), interest);
- }
-}
-
-TLSProducerSocket::HandshakeState TLSProducerSocket::getHandshakeState() {
- if (SSL_in_before(ssl_)) {
- handshake_state_ = UNINITIATED;
- }
-
- if (SSL_in_init(ssl_) && handshake_state_ == UNINITIATED) {
- handshake_state_ = CLIENT_HELLO;
- }
-
- return handshake_state_;
-}
-
-void TLSProducerSocket::onContentProduced(interface::ProducerSocket &p,
- const std::error_code &err,
- uint64_t bytes_written) {}
-
-uint32_t TLSProducerSocket::produceStream(
- const Name &content_name, std::unique_ptr<utils::MemBuf> &&buffer,
- bool is_last, uint32_t start_offset) {
- if (getHandshakeState() != SERVER_FINISHED) {
- throw errors::RuntimeException(
- "New handshake on the same P2P secure producer socket not supported");
- }
-
- size_t buf_size = buffer->length();
- name_ = production_protocol_->getNamespaces().front().mapName(content_name);
- tls_chunks_ = to_call_oncontentproduced_ =
- (int)ceil((float)buf_size / (float)SSL3_RT_MAX_PLAIN_LENGTH);
-
- if (!is_last) {
- tls_chunks_++;
- }
-
- last_segment_ = start_offset;
-
- SSL_write(ssl_, buffer->data(), (int)buf_size);
- BIO *wbio = SSL_get_wbio(ssl_);
- int i = BIO_flush(wbio);
- (void)i; // To shut up gcc 5
-
- return 0;
-}
-
-long TLSProducerSocket::ctrl(BIO *b, int cmd, long num, void *ptr) {
- if (cmd == BIO_CTRL_FLUSH) {
- }
-
- return 1;
-}
-
-int TLSProducerSocket::addHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context,
- const unsigned char **out, size_t *outlen,
- X509 *x, size_t chainidx, int *al,
- void *add_arg) {
- TLSProducerSocket *socket = reinterpret_cast<TLSProducerSocket *>(add_arg);
-
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "On addHicnKeyIdCb, for the prefix registration.";
-
- if (ext_type == 100) {
- auto &prefix =
- socket->parent_->production_protocol_->getNamespaces().front();
- const ip_prefix_t &ip_prefix = prefix.toIpPrefixStruct();
- int inet_family = prefix.getAddressFamily();
- uint16_t prefix_len_bits = prefix.getPrefixLength();
- uint8_t prefix_len_bytes = prefix_len_bits / 8;
- uint8_t prefix_len_u32 = prefix_len_bits / 32;
-
- ip_prefix_t *out_ip = (ip_prefix_t *)malloc(sizeof(ip_prefix_t));
- out_ip->family = inet_family;
- out_ip->len = prefix_len_bits + 32;
- u8 *out_ip_buf = const_cast<u8 *>(
- ip_address_get_buffer(&(out_ip->address), inet_family));
- *out = reinterpret_cast<unsigned char *>(out_ip);
-
- RAND_bytes((unsigned char *)&socket->key_id_, 4);
-
- memcpy(out_ip_buf, ip_address_get_buffer(&(ip_prefix.address), inet_family),
- prefix_len_bytes);
- memcpy((out_ip_buf + prefix_len_bytes), &socket->key_id_, 4);
- *outlen = sizeof(ip_prefix_t);
-
- ip_address_t mask = {};
- ip_address_t keyId_component = {};
- u32 *mask_buf;
- u32 *keyId_component_buf;
-
- switch (inet_family) {
- case AF_INET:
- mask_buf = &(mask.v4.as_u32);
- keyId_component_buf = &(keyId_component.v4.as_u32);
- break;
- case AF_INET6:
- mask_buf = mask.v6.as_u32;
- keyId_component_buf = keyId_component.v6.as_u32;
- break;
- default:
- throw errors::RuntimeException("Unknown protocol");
- }
-
- if (prefix_len_bits > (inet_family == AF_INET6 ? IPV6_ADDR_LEN_BITS - 32
- : IPV4_ADDR_LEN_BITS - 32))
- throw errors::RuntimeException(
- "Not enough space in the content name to add key_id");
-
- mask_buf[prefix_len_u32] = 0xffffffff;
- keyId_component_buf[prefix_len_u32] = socket->key_id_;
- socket->last_segment_ = 0;
-
- socket->on_interest_process_decrypted_ =
- socket->parent_->on_interest_process_decrypted_;
-
- socket->registerPrefix(
- Prefix(prefix.getName(Name(inet_family, (uint8_t *)&mask),
- Name(inet_family, (uint8_t *)&keyId_component),
- prefix.getName()),
- out_ip->len));
- socket->connect();
- }
- return 1;
-}
-
-void TLSProducerSocket::freeHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context,
- const unsigned char *out,
- void *add_arg) {
- free(const_cast<unsigned char *>(out));
-}
-
-int TLSProducerSocket::parseHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context,
- const unsigned char *in, size_t inlen,
- X509 *x, size_t chainidx, int *al,
- void *add_arg) {
- return 1;
-}
-
-int TLSProducerSocket::setSocketOption(
- int socket_option_key, ProducerInterestCallback socket_option_value) {
- return rescheduleOnIOService(
- socket_option_key, socket_option_value,
- [this](int socket_option_key,
- ProducerInterestCallback socket_option_value) -> int {
- int result = SOCKET_OPTION_SET;
-
- switch (socket_option_key) {
- case ProducerCallbacksOptions::INTEREST_INPUT:
- on_interest_input_decrypted_ = socket_option_value;
- break;
-
- case ProducerCallbacksOptions::INTEREST_DROP:
- on_interest_dropped_input_buffer_ = socket_option_value;
- break;
-
- case ProducerCallbacksOptions::INTEREST_PASS:
- on_interest_inserted_input_buffer_ = socket_option_value;
- break;
-
- case ProducerCallbacksOptions::CACHE_HIT:
- on_interest_satisfied_output_buffer_ = socket_option_value;
- break;
-
- case ProducerCallbacksOptions::CACHE_MISS:
- on_interest_process_decrypted_ = socket_option_value;
- break;
-
- default:
- result = SOCKET_OPTION_NOT_SET;
- break;
- }
-
- return result;
- });
-}
-
-int TLSProducerSocket::setSocketOption(
- int socket_option_key, ProducerContentCallback socket_option_value) {
- return rescheduleOnIOService(
- socket_option_key, socket_option_value,
- [this](int socket_option_key,
- ProducerContentCallback socket_option_value) -> int {
- switch (socket_option_key) {
- case ProducerCallbacksOptions::CONTENT_PRODUCED:
- on_content_produced_application_ = socket_option_value;
- break;
-
- default:
- return SOCKET_OPTION_NOT_SET;
- }
-
- return SOCKET_OPTION_SET;
- });
-}
-
-int TLSProducerSocket::getSocketOption(
- int socket_option_key, ProducerContentCallback **socket_option_value) {
- return rescheduleOnIOService(
- socket_option_key, socket_option_value,
- [this](int socket_option_key,
- ProducerContentCallback **socket_option_value) -> int {
- switch (socket_option_key) {
- case ProducerCallbacksOptions::CONTENT_PRODUCED:
- *socket_option_value = &on_content_produced_application_;
- break;
-
- default:
- return SOCKET_OPTION_NOT_GET;
- }
-
- return SOCKET_OPTION_GET;
- });
-}
-
-} // namespace implementation
-} // namespace transport
diff --git a/libtransport/src/implementation/tls_socket_producer.h b/libtransport/src/implementation/tls_socket_producer.h
deleted file mode 100644
index a542a4d9f..000000000
--- a/libtransport/src/implementation/tls_socket_producer.h
+++ /dev/null
@@ -1,154 +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 <implementation/socket_producer.h>
-#include <openssl/ssl.h>
-
-#include <condition_variable>
-#include <mutex>
-
-namespace transport {
-namespace implementation {
-
-class P2PSecureProducerSocket;
-
-class TLSProducerSocket : virtual public ProducerSocket {
- friend class P2PSecureProducerSocket;
-
- public:
- explicit TLSProducerSocket(interface::ProducerSocket *producer_socket,
- P2PSecureProducerSocket *parent,
- const Name &handshake_name);
-
- ~TLSProducerSocket();
-
- uint32_t produceStream(const Name &content_name, const uint8_t *buffer,
- size_t buffer_size, bool is_last = true,
- uint32_t start_offset = 0) override {
- return produceStream(content_name,
- utils::MemBuf::copyBuffer(buffer, buffer_size),
- is_last, start_offset);
- }
-
- uint32_t produceStream(const Name &content_name,
- std::unique_ptr<utils::MemBuf> &&buffer,
- bool is_last = true,
- uint32_t start_offset = 0) override;
-
- virtual void accept();
-
- virtual int async_accept();
-
- virtual int setSocketOption(
- int socket_option_key,
- ProducerInterestCallback socket_option_value) override;
-
- virtual int setSocketOption(
- int socket_option_key,
- ProducerContentCallback socket_option_value) override;
-
- virtual int getSocketOption(
- int socket_option_key,
- ProducerContentCallback **socket_option_value) override;
-
- int getSocketOption(int socket_option_key,
- ProducerContentCallback &socket_option_value);
-
- int getSocketOption(int socket_option_key,
- ProducerInterestCallback &socket_option_value);
-
- using ProducerSocket::getSocketOption;
- // using ProducerSocket::onInterest;
- using ProducerSocket::setSocketOption;
-
- protected:
- enum HandshakeState {
- UNINITIATED,
- CLIENT_HELLO, // when CLIENT_HELLO interest has been received
- CLIENT_FINISHED, // when CLIENT_FINISHED interest has been received
- SERVER_FINISHED, // when handshake is done
- };
- /* Callback invoked once an interest has been received and its payload
- * decrypted */
- ProducerInterestCallback on_interest_input_decrypted_;
- ProducerInterestCallback on_interest_process_decrypted_;
- ProducerContentCallback on_content_produced_application_;
- std::mutex mtx_;
- /* Condition variable for the wait */
- std::condition_variable cv_;
- /* Bool variable, true if there is something to read (an interest arrived) */
- bool something_to_read_;
- /* Bool variable, true if CLIENT_FINISHED interest has been received */
- HandshakeState handshake_state_;
- /* First interest that open a secure connection */
- transport::core::Name name_;
- /* SSL handle */
- SSL *ssl_;
- SSL_CTX *ctx_;
- Packet::MemBufPtr handshake_packet_;
- std::unique_ptr<utils::MemBuf> head_;
- std::uint32_t last_segment_;
- std::uint32_t key_id_;
- std::thread *handshake;
- P2PSecureProducerSocket *parent_;
- bool first_;
- Name handshake_name_;
- int tls_chunks_;
- int to_call_oncontentproduced_;
- bool still_writing_;
- utils::EventThread encryption_thread_;
- utils::EventThread async_thread_;
-
- void onInterest(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);
-
- /* Return the number of read bytes in the return param */
- static int readOld(BIO *h, char *buf, int size);
-
- /* Return the number of written bytes in written */
- static int write(BIO *b, const char *buf, size_t size, size_t *written);
-
- /* Return the number of written bytes in the return param */
- static int writeOld(BIO *h, const char *buf, int num);
-
- static long ctrl(BIO *b, int cmd, long num, void *ptr);
-
- static int addHicnKeyIdCb(SSL *s, unsigned int ext_type, unsigned int context,
- const unsigned char **out, size_t *outlen, X509 *x,
- size_t chainidx, int *al, void *add_arg);
-
- static void freeHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context, const unsigned char *out,
- void *add_arg);
-
- static int parseHicnKeyIdCb(SSL *s, unsigned int ext_type,
- unsigned int context, const unsigned char *in,
- size_t inlen, X509 *x, size_t chainidx, int *al,
- void *add_arg);
-
- void onContentProduced(interface::ProducerSocket &p,
- const std::error_code &err, uint64_t bytes_written);
-
- HandshakeState getHandshakeState();
-};
-
-} // namespace implementation
-} // end namespace transport
diff --git a/libtransport/src/interfaces/CMakeLists.txt b/libtransport/src/interfaces/CMakeLists.txt
index 7ec024fec..bf8f8dcf8 100644
--- a/libtransport/src/interfaces/CMakeLists.txt
+++ b/libtransport/src/interfaces/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -19,20 +19,4 @@ list(APPEND SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/global_configuration.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/interfaces/callbacks.cc b/libtransport/src/interfaces/callbacks.cc
index 6869ac3f7..776b4cbe7 100644
--- a/libtransport/src/interfaces/callbacks.cc
+++ b/libtransport/src/interfaces/callbacks.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/interfaces/global_configuration.cc b/libtransport/src/interfaces/global_configuration.cc
index cecdacc07..f8e7a90c3 100644
--- a/libtransport/src/interfaces/global_configuration.cc
+++ b/libtransport/src/interfaces/global_configuration.cc
@@ -14,6 +14,7 @@
*/
#include <core/global_configuration.h>
+#include <core/global_workers.h>
#include <glog/logging.h>
#include <hicn/transport/interfaces/global_conf_interface.h>
@@ -23,10 +24,29 @@ namespace transport {
namespace interface {
namespace global_config {
-void parseConfigurationFile(const std::string& path) {
+GlobalConfigInterface::GlobalConfigInterface() { libtransportConfigInit(); }
+
+GlobalConfigInterface::~GlobalConfigInterface() {
+ libtransportConfigTerminate();
+}
+
+void GlobalConfigInterface::parseConfigurationFile(
+ const std::string &path) const {
core::GlobalConfiguration::getInstance().parseConfiguration(path);
}
+void GlobalConfigInterface::libtransportConfigInit() const {
+ // nothing to do
+}
+
+void GlobalConfigInterface::libtransportConfigTerminate() const {
+ // cleanup workers
+ auto &workers = core::GlobalWorkers::getInstance().getWorkers();
+ for (auto &worker : workers) {
+ worker.stop();
+ }
+}
+
void ConfigurationObject::get() {
std::error_code ec;
core::GlobalConfiguration::getInstance().getConfiguration(*this, ec);
diff --git a/libtransport/src/interfaces/p2psecure_socket_consumer.cc b/libtransport/src/interfaces/p2psecure_socket_consumer.cc
deleted file mode 100644
index e473a1e2e..000000000
--- a/libtransport/src/interfaces/p2psecure_socket_consumer.cc
+++ /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.
- */
-
-#include <hicn/transport/interfaces/p2psecure_socket_consumer.h>
-#include <implementation/p2psecure_socket_consumer.h>
-
-namespace transport {
-namespace interface {
-
-P2PSecureConsumerSocket::P2PSecureConsumerSocket(int handshake_protocol,
- int transport_protocol)
- : ConsumerSocket() {
- socket_ = std::unique_ptr<implementation::ConsumerSocket>(
- new implementation::P2PSecureConsumerSocket(this, handshake_protocol,
- transport_protocol));
-}
-
-void P2PSecureConsumerSocket::registerPrefix(const Prefix &producer_namespace) {
- implementation::P2PSecureConsumerSocket &secure_consumer_socket =
- *(static_cast<implementation::P2PSecureConsumerSocket *>(socket_.get()));
- secure_consumer_socket.registerPrefix(producer_namespace);
-}
-
-} // namespace interface
-} // namespace transport
diff --git a/libtransport/src/interfaces/p2psecure_socket_producer.cc b/libtransport/src/interfaces/p2psecure_socket_producer.cc
deleted file mode 100644
index 10d8a1367..000000000
--- a/libtransport/src/interfaces/p2psecure_socket_producer.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hicn/transport/interfaces/p2psecure_socket_producer.h>
-#include <implementation/p2psecure_socket_producer.h>
-
-namespace transport {
-namespace interface {
-
-P2PSecureProducerSocket::P2PSecureProducerSocket() {
- socket_ = std::make_unique<implementation::P2PSecureProducerSocket>(this);
-}
-
-P2PSecureProducerSocket::P2PSecureProducerSocket(
- bool rtc, const std::shared_ptr<auth::Identity> &identity) {
- socket_ = std::make_unique<implementation::P2PSecureProducerSocket>(this, rtc,
- identity);
-}
-
-} // namespace interface
-} // namespace transport
diff --git a/libtransport/src/interfaces/portal.cc b/libtransport/src/interfaces/portal.cc
index 9db0621f6..898766c50 100644
--- a/libtransport/src/interfaces/portal.cc
+++ b/libtransport/src/interfaces/portal.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,83 +13,106 @@
* limitations under the License.
*/
+#include <core/portal.h>
#include <hicn/transport/interfaces/portal.h>
-#include <implementation/socket.h>
namespace transport {
namespace interface {
-Portal::Portal() { implementation_ = new core::Portal(); }
+class Portal::Impl {
+ public:
+ Impl() : portal_(core::Portal::createShared()) {}
+ Impl(::utils::EventThread &worker)
+ : portal_(core::Portal::createShared(worker)) {}
-Portal::Portal(asio::io_service &io_service) {
- implementation_ = new core::Portal(io_service);
-}
+ void registerTransportCallback(TransportCallback *transport_callback) {
+ portal_->registerTransportCallback(transport_callback);
+ }
+
+ void connect(bool is_consumer) { portal_->connect(is_consumer); }
+
+ bool interestIsPending(const core::Name &name) {
+ return portal_->interestIsPending(name);
+ }
+
+ void sendInterest(core::Interest::Ptr &interest, uint32_t lifetime,
+ OnContentObjectCallback &&on_content_object_callback,
+ OnInterestTimeoutCallback &&on_interest_timeout_callback) {
+ portal_->sendInterest(interest, lifetime,
+ std::move(on_content_object_callback),
+ std::move(on_interest_timeout_callback));
+ }
+
+ void sendContentObject(core::ContentObject &content_object) {
+ portal_->sendContentObject(content_object);
+ }
+
+ void killConnection() { portal_->killConnection(); }
+
+ void clear() { portal_->clear(); }
-Portal::~Portal() { delete reinterpret_cast<core::Portal *>(implementation_); }
+ utils::EventThread &getThread() { return portal_->getThread(); }
-void Portal::setConsumerCallback(ConsumerCallback *consumer_callback) {
- reinterpret_cast<core::Portal *>(implementation_)
- ->setConsumerCallback(consumer_callback);
+ void registerRoute(core::Prefix &prefix) { portal_->registerRoute(prefix); }
+
+ void sendMapme() { portal_->sendMapme(); }
+
+ void setForwardingStrategy(core::Prefix &prefix, std::string &strategy) {
+ portal_->setForwardingStrategy(prefix, strategy);
+ }
+
+ private:
+ std::shared_ptr<core::Portal> portal_;
+};
+
+Portal::Portal() { implementation_ = new Impl(); }
+
+Portal::Portal(::utils::EventThread &worker) {
+ implementation_ = new Impl(worker);
}
-void Portal::setProducerCallback(ProducerCallback *producer_callback) {
- reinterpret_cast<core::Portal *>(implementation_)
- ->setProducerCallback(producer_callback);
+Portal::~Portal() { delete implementation_; }
+
+void Portal::registerTransportCallback(TransportCallback *transport_callback) {
+ implementation_->registerTransportCallback(transport_callback);
}
void Portal::connect(bool is_consumer) {
- reinterpret_cast<core::Portal *>(implementation_)->connect(is_consumer);
+ implementation_->connect(is_consumer);
}
bool Portal::interestIsPending(const core::Name &name) {
- return reinterpret_cast<core::Portal *>(implementation_)
- ->interestIsPending(name);
+ return implementation_->interestIsPending(name);
}
void Portal::sendInterest(
- core::Interest::Ptr &&interest,
+ core::Interest::Ptr &interest, uint32_t lifetime,
OnContentObjectCallback &&on_content_object_callback,
OnInterestTimeoutCallback &&on_interest_timeout_callback) {
- reinterpret_cast<core::Portal *>(implementation_)
- ->sendInterest(std::move(interest), std::move(on_content_object_callback),
- std::move(on_interest_timeout_callback));
-}
-
-void Portal::bind(const BindConfig &config) {
- reinterpret_cast<core::Portal *>(implementation_)->bind(config);
-}
-
-void Portal::runEventsLoop() {
- reinterpret_cast<core::Portal *>(implementation_)->runEventsLoop();
-}
-
-void Portal::runOneEvent() {
- reinterpret_cast<core::Portal *>(implementation_)->runOneEvent();
+ implementation_->sendInterest(interest, lifetime,
+ std::move(on_content_object_callback),
+ std::move(on_interest_timeout_callback));
}
void Portal::sendContentObject(core::ContentObject &content_object) {
- reinterpret_cast<core::Portal *>(implementation_)
- ->sendContentObject(content_object);
+ implementation_->sendContentObject(content_object);
}
-void Portal::stopEventsLoop() {
- reinterpret_cast<core::Portal *>(implementation_)->stopEventsLoop();
-}
+void Portal::killConnection() { implementation_->killConnection(); }
-void Portal::killConnection() {
- reinterpret_cast<core::Portal *>(implementation_)->killConnection();
-}
+void Portal::clear() { implementation_->clear(); }
-void Portal::clear() {
- reinterpret_cast<core::Portal *>(implementation_)->clear();
-}
+utils::EventThread &Portal::getThread() { return implementation_->getThread(); }
-asio::io_service &Portal::getIoService() {
- return reinterpret_cast<core::Portal *>(implementation_)->getIoService();
+void Portal::registerRoute(core::Prefix &prefix) {
+ implementation_->registerRoute(prefix);
}
-void Portal::registerRoute(core::Prefix &prefix) {
- reinterpret_cast<core::Portal *>(implementation_)->registerRoute(prefix);
+void Portal::sendMapme() { implementation_->sendMapme(); }
+
+void Portal::setForwardingStrategy(core::Prefix &prefix,
+ std::string &strategy) {
+ implementation_->setForwardingStrategy(prefix, strategy);
}
} // namespace interface
diff --git a/libtransport/src/interfaces/socket_consumer.cc b/libtransport/src/interfaces/socket_consumer.cc
index 4eee73cab..afb672c95 100644
--- a/libtransport/src/interfaces/socket_consumer.cc
+++ b/libtransport/src/interfaces/socket_consumer.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,23 +23,28 @@ ConsumerSocket::ConsumerSocket(int protocol) {
socket_ = std::make_unique<implementation::ConsumerSocket>(this, protocol);
}
-ConsumerSocket::ConsumerSocket(int protocol, asio::io_service &io_service) {
- socket_ = std::make_unique<implementation::ConsumerSocket>(this, protocol,
- io_service);
+ConsumerSocket::ConsumerSocket(int protocol, ::utils::EventThread &worker) {
+ socket_ =
+ std::make_unique<implementation::ConsumerSocket>(this, protocol, worker);
}
ConsumerSocket::ConsumerSocket() {}
-ConsumerSocket::~ConsumerSocket() { socket_->stop(); }
+ConsumerSocket::ConsumerSocket(ConsumerSocket &&other) noexcept
+ : socket_(std::move(other.socket_)) {}
+
+ConsumerSocket::~ConsumerSocket() {
+ if (socket_) {
+ 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);
+int ConsumerSocket::consume(const Name &name, bool blocking) {
+ return socket_->consume(name);
}
void ConsumerSocket::stop() { socket_->stop(); }
@@ -97,6 +102,12 @@ int ConsumerSocket::setSocketOption(int socket_option_key,
int ConsumerSocket::setSocketOption(
int socket_option_key,
+ const std::shared_ptr<auth::Signer> &socket_option_value) {
+ return socket_->setSocketOption(socket_option_key, socket_option_value);
+}
+
+int ConsumerSocket::setSocketOption(
+ int socket_option_key,
const std::shared_ptr<auth::Verifier> &socket_option_value) {
return socket_->setSocketOption(socket_option_key, socket_option_value);
}
@@ -111,6 +122,11 @@ int ConsumerSocket::setSocketOption(int socket_option_key,
return socket_->setSocketOption(socket_option_key, socket_option_value);
}
+int ConsumerSocket::setSocketOption(int socket_option_key,
+ StrategyCallback 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);
@@ -148,6 +164,11 @@ int ConsumerSocket::getSocketOption(int socket_option_key,
}
int ConsumerSocket::getSocketOption(
+ int socket_option_key, std::shared_ptr<auth::Signer> &socket_option_value) {
+ return socket_->getSocketOption(socket_option_key, socket_option_value);
+}
+
+int ConsumerSocket::getSocketOption(
int socket_option_key,
std::shared_ptr<auth::Verifier> &socket_option_value) {
return socket_->getSocketOption(socket_option_key, socket_option_value);
@@ -169,6 +190,11 @@ int ConsumerSocket::getSocketOption(
return socket_->getSocketOption(socket_option_key, socket_option_value);
}
+int ConsumerSocket::getSocketOption(int socket_option_key,
+ StrategyCallback **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
index b04947dfd..77e3bf633 100644
--- a/libtransport/src/interfaces/socket_producer.cc
+++ b/libtransport/src/interfaces/socket_producer.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -33,14 +33,21 @@ ProducerSocket::ProducerSocket(int protocol) {
socket_ = std::make_unique<implementation::ProducerSocket>(this, protocol);
}
-ProducerSocket::ProducerSocket(int protocol, asio::io_service &io_service) {
- socket_ = std::make_unique<implementation::ProducerSocket>(this, protocol,
- io_service);
+ProducerSocket::ProducerSocket(int protocol, ::utils::EventThread &worker) {
+ socket_ =
+ std::make_unique<implementation::ProducerSocket>(this, protocol, worker);
}
+ProducerSocket::ProducerSocket(ProducerSocket &&other) noexcept
+ : socket_(std::move(other.socket_)) {}
+
ProducerSocket::ProducerSocket(bool) {}
-ProducerSocket::~ProducerSocket() { socket_->stop(); }
+ProducerSocket::~ProducerSocket() {
+ if (socket_) {
+ socket_->stop();
+ }
+}
void ProducerSocket::connect() { socket_->connect(); }
@@ -76,18 +83,14 @@ void ProducerSocket::produce(ContentObject &content_object) {
return socket_->produce(content_object);
}
-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::sendMapme() { return socket_->sendMapme(); }
void ProducerSocket::registerPrefix(const Prefix &producer_namespace) {
return socket_->registerPrefix(producer_namespace);
}
+void ProducerSocket::start() { return socket_->start(); }
+
void ProducerSocket::stop() { return socket_->stop(); }
asio::io_service &ProducerSocket::getIoService() {
@@ -95,6 +98,11 @@ asio::io_service &ProducerSocket::getIoService() {
};
int ProducerSocket::setSocketOption(int socket_option_key,
+ Callback *socket_option_value) {
+ return socket_->setSocketOption(socket_option_key, socket_option_value);
+}
+
+int ProducerSocket::setSocketOption(int socket_option_key,
uint32_t socket_option_value) {
return socket_->setSocketOption(socket_option_key, socket_option_value);
}
@@ -140,9 +148,15 @@ int ProducerSocket::setSocketOption(
return socket_->setSocketOption(socket_option_key, socket_option_value);
}
+int ProducerSocket::setSocketOption(
+ int socket_option_key,
+ const std::shared_ptr<auth::Verifier> &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);
+ return socket_->getSocketOption(socket_option_key, socket_option_value);
}
int ProducerSocket::setSocketOption(int socket_option_key,
@@ -181,6 +195,12 @@ int ProducerSocket::getSocketOption(
return socket_->getSocketOption(socket_option_key, socket_option_value);
}
+int ProducerSocket::getSocketOption(
+ int socket_option_key,
+ std::shared_ptr<auth::Verifier> &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
deleted file mode 100644
index 7326fcbcb..000000000
--- a/libtransport/src/interfaces/tls_rtc_socket_producer.cc
+++ /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.
- */
-
-#include <implementation/tls_rtc_socket_producer.h>
-#include <interfaces/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
deleted file mode 100644
index 3ea84095b..000000000
--- a/libtransport/src/interfaces/tls_rtc_socket_producer.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <hicn/transport/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
diff --git a/libtransport/src/interfaces/tls_socket_consumer.cc b/libtransport/src/interfaces/tls_socket_consumer.cc
deleted file mode 100644
index 6c1c535b5..000000000
--- a/libtransport/src/interfaces/tls_socket_consumer.cc
+++ /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.
- */
-
-#include <implementation/tls_socket_consumer.h>
-#include <interfaces/tls_socket_consumer.h>
-
-namespace transport {
-namespace interface {
-
-TLSConsumerSocket::TLSConsumerSocket(
- implementation::TLSConsumerSocket *implementation) {
- socket_ = std::unique_ptr<implementation::TLSConsumerSocket>(implementation);
-}
-
-TLSConsumerSocket::~TLSConsumerSocket() { socket_.release(); }
-
-} // namespace interface
-} // namespace transport
diff --git a/libtransport/src/interfaces/tls_socket_producer.cc b/libtransport/src/interfaces/tls_socket_producer.cc
deleted file mode 100644
index 037702f72..000000000
--- a/libtransport/src/interfaces/tls_socket_producer.cc
+++ /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.
- */
-
-#include <implementation/tls_socket_producer.h>
-#include <interfaces/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/interfaces/tls_socket_producer.h b/libtransport/src/interfaces/tls_socket_producer.h
deleted file mode 100644
index 3c662176a..000000000
--- a/libtransport/src/interfaces/tls_socket_producer.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <hicn/transport/interfaces/socket_producer.h>
-
-namespace transport {
-
-namespace implementation {
-class TLSProducerSocket;
-}
-
-namespace interface {
-
-class TLSProducerSocket : public ProducerSocket {
- public:
- TLSProducerSocket(implementation::TLSProducerSocket *implementation);
- ~TLSProducerSocket();
-};
-
-} // namespace interface
-
-} // end namespace transport
diff --git a/libtransport/src/io_modules/CMakeLists.txt b/libtransport/src/io_modules/CMakeLists.txt
index 29aec236a..ce7ec221d 100644
--- a/libtransport/src/io_modules/CMakeLists.txt
+++ b/libtransport/src/io_modules/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,25 +11,68 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-if (${CMAKE_SYSTEM_NAME} MATCHES Android)
+
+##############################################################
+# Android case: no submodules
+##############################################################
+if (${CMAKE_SYSTEM_NAME} MATCHES Android OR ${CMAKE_SYSTEM_NAME} MATCHES iOS)
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/udp/hicn_forwarder_module.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/udp/udp_socket_connector.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn-light/hicn_forwarder_module.cc
)
list(APPEND HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/udp/hicn_forwarder_module.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udp/udp_socket_connector.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn-light/hicn_forwarder_module.h
+ )
+
+ if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ find_package(Libhicnctrl ${CURRENT_VERSION} REQUIRED NO_MODULE)
+
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
+
+ list(APPEND LIBHICNCTRL_LIBRARIES hicn::hicnctrl.${LIBTYPE})
+ else()
+ if (DISABLE_SHARED_LIBRARIES)
+ if (WIN32)
+ set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_STATIC})
+ else ()
+ set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_STATIC} log)
+ endif ()
+ list(APPEND DEPENDENCIES
+ ${LIBHICNCTRL_STATIC}
+ )
+ else()
+ set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_SHARED})
+ list(APPEND DEPENDENCIES
+ ${LIBHICNCTRL_SHARED}
+ )
+ endif()
+ endif()
+
+ list(APPEND LIBRARIES
+ PRIVATE ${LIBHICNCTRL_LIBRARIES}
+ )
+
+ list(APPEND LIBTRANSPORT_INTERNAL_INCLUDE_DIRS
+ PUBLIC
+ $<BUILD_INTERFACE:${LIBHICNCTRL_INCLUDE_DIRS}>
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
set(HEADER_FILES ${HEADER_FILES} PARENT_SCOPE)
+ set(LIBRARIES ${LIBRARIES} PARENT_SCOPE)
+ set(LIBTRANSPORT_INTERNAL_INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} PARENT_SCOPE)
else()
- add_subdirectory(udp)
- add_subdirectory(loopback)
+##############################################################
+# Compile submodules
+##############################################################
+ add_subdirectory(hicn-light)
add_subdirectory(forwarder)
if (__vpp__)
add_subdirectory(memif)
endif()
-endif() \ No newline at end of file
+endif()
diff --git a/libtransport/src/io_modules/forwarder/CMakeLists.txt b/libtransport/src/io_modules/forwarder/CMakeLists.txt
index a1d0c5db5..2235d842e 100644
--- a/libtransport/src/io_modules/forwarder/CMakeLists.txt
+++ b/libtransport/src/io_modules/forwarder/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -17,25 +17,19 @@ list(APPEND MODULE_HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/errors.h
${CMAKE_CURRENT_SOURCE_DIR}/forwarder_module.h
${CMAKE_CURRENT_SOURCE_DIR}/forwarder.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnel_listener.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnel.h
- ${CMAKE_CURRENT_SOURCE_DIR}/global_counter.h
)
list(APPEND MODULE_SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/errors.cc
${CMAKE_CURRENT_SOURCE_DIR}/forwarder_module.cc
${CMAKE_CURRENT_SOURCE_DIR}/forwarder.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnel_listener.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_tunnel.cc
)
build_module(forwarder_module
- SHARED
SOURCES ${MODULE_SOURCE_FILES}
DEPENDS ${DEPENDENCIES}
COMPONENT ${LIBTRANSPORT_COMPONENT}-io-modules
- INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIRS} ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
+ INCLUDE_DIRS ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS} ${Libhicn_INCLUDE_DIRS}
DEFINITIONS ${COMPILER_DEFINITIONS}
- COMPILE_OPTIONS ${COMPILE_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
)
diff --git a/libtransport/src/io_modules/forwarder/errors.cc b/libtransport/src/io_modules/forwarder/errors.cc
index b5f131499..6e93d0453 100644
--- a/libtransport/src/io_modules/forwarder/errors.cc
+++ b/libtransport/src/io_modules/forwarder/errors.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
*/
#include <io_modules/forwarder/errors.h>
diff --git a/libtransport/src/io_modules/forwarder/forwarder.cc b/libtransport/src/io_modules/forwarder/forwarder.cc
index 0546cb8b3..d5f0b589e 100644
--- a/libtransport/src/io_modules/forwarder/forwarder.cc
+++ b/libtransport/src/io_modules/forwarder/forwarder.cc
@@ -14,12 +14,12 @@
*/
#include <core/global_configuration.h>
+#include <core/global_id_counter.h>
#include <core/local_connector.h>
+#include <core/udp_connector.h>
+#include <core/udp_listener.h>
#include <glog/logging.h>
#include <io_modules/forwarder/forwarder.h>
-#include <io_modules/forwarder/global_id_counter.h>
-#include <io_modules/forwarder/udp_tunnel.h>
-#include <io_modules/forwarder/udp_tunnel_listener.h>
namespace transport {
@@ -89,11 +89,14 @@ void Forwarder::initConnectors() {
Connector::Id Forwarder::registerLocalConnector(
asio::io_service &io_service,
Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
Connector::OnReconnectCallback &&reconnect_callback) {
utils::SpinLock::Acquire locked(connector_lock_);
auto id = GlobalCounter<Connector::Id>::getInstance().getNext();
auto connector = std::make_shared<LocalConnector>(
- io_service, receive_callback, nullptr, nullptr, reconnect_callback);
+ io_service, std::move(receive_callback), std::move(sent_callback),
+ std::move(close_callback), std::move(reconnect_callback));
connector->setConnectorId(id);
local_connectors_.emplace(id, std::move(connector));
return id;
@@ -105,6 +108,7 @@ Forwarder &Forwarder::deleteConnector(Connector::Id id) {
if (it != local_connectors_.end()) {
it->second->close();
local_connectors_.erase(it);
+ } else {
}
return *this;
@@ -120,9 +124,9 @@ Connector::Ptr Forwarder::getConnector(Connector::Id id) {
return nullptr;
}
-void Forwarder::onPacketFromListener(Connector *connector,
- utils::MemBuf &packet_buffer,
- const std::error_code &ec) {
+void Forwarder::onPacketFromListener(
+ Connector *connector, const std::vector<utils::MemBuf::Ptr> &packets,
+ const std::error_code &ec) {
// Create connector
connector->setReceiveCallback(
std::bind(&Forwarder::onPacketReceived, this, std::placeholders::_1,
@@ -135,32 +139,21 @@ void Forwarder::onPacketFromListener(Connector *connector,
remote_connectors_.emplace(connector->getConnectorId(),
connector->shared_from_this());
}
+
// TODO Check if control packet or not. For the moment it is not.
- onPacketReceived(connector, packet_buffer, ec);
+ onPacketReceived(connector, packets, ec);
}
void Forwarder::onPacketReceived(Connector *connector,
- utils::MemBuf &packet_buffer,
+ const std::vector<utils::MemBuf::Ptr> &packets,
const std::error_code &ec) {
- // Figure out the type of packet we received
- bool is_interest = Packet::isInterest(packet_buffer.data());
-
- Packet *packet = nullptr;
- if (is_interest) {
- packet = static_cast<Interest *>(&packet_buffer);
- } else {
- packet = static_cast<ContentObject *>(&packet_buffer);
+ if (ec) {
+ LOG(ERROR) << "Error receiving packet: " << ec.message();
+ return;
}
for (auto &c : local_connectors_) {
- auto role = c.second->getRole();
- auto is_producer = role == Connector::Role::PRODUCER;
- if ((is_producer && is_interest) || (!is_producer && !is_interest)) {
- c.second->send(*packet);
- } else {
- LOG(ERROR) << "Error sending packet to local connector. is_interest = "
- << is_interest << " - is_producer = " << is_producer;
- }
+ c.second->receive(packets);
}
// PCS Lookup + FIB lookup. Skip for now
@@ -168,19 +161,24 @@ void Forwarder::onPacketReceived(Connector *connector,
// Forward packet to local connectors
}
-void Forwarder::send(Packet &packet) {
+void Forwarder::send(Packet &packet, Connector::Id connector_id) {
// TODo Here a nice PIT/CS / FIB would be required:)
// For now let's just forward the packet on the remote connector we get
- if (remote_connectors_.begin() == remote_connectors_.end()) {
- return;
+ for (auto &c : remote_connectors_) {
+ auto remote_endpoint = c.second->getRemoteEndpoint();
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Sending packet to: " << remote_endpoint.getAddress() << ":"
+ << remote_endpoint.getPort();
+ c.second->send(packet);
}
- auto remote_endpoint =
- remote_connectors_.begin()->second->getRemoteEndpoint();
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "Sending packet to: " << remote_endpoint.getAddress() << ":"
- << remote_endpoint.getPort();
- remote_connectors_.begin()->second->send(packet);
+ for (auto &c : local_connectors_) {
+ if (c.first != connector_id) {
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Sending packet to local connector " << c.first << std::endl;
+ c.second->receive({packet.shared_from_this()});
+ }
+ }
}
void Forwarder::onPacketSent(Connector *connector, const std::error_code &ec) {}
@@ -292,4 +290,4 @@ void Forwarder::parseForwarderConfiguration(
}
} // namespace core
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/libtransport/src/io_modules/forwarder/forwarder.h b/libtransport/src/io_modules/forwarder/forwarder.h
index 5b564bb5e..1022bf81b 100644
--- a/libtransport/src/io_modules/forwarder/forwarder.h
+++ b/libtransport/src/io_modules/forwarder/forwarder.h
@@ -15,13 +15,13 @@
#pragma once
+#include <core/udp_listener.h>
#include <hicn/transport/core/io_module.h>
#include <hicn/transport/core/prefix.h>
#include <hicn/transport/utils/event_thread.h>
#include <hicn/transport/utils/singleton.h>
#include <hicn/transport/utils/spinlock.h>
#include <io_modules/forwarder/configuration.h>
-#include <io_modules/forwarder/udp_tunnel_listener.h>
#include <atomic>
#include <libconfig.h++>
@@ -31,9 +31,8 @@ namespace transport {
namespace core {
-class Forwarder : public utils::Singleton<Forwarder> {
+class Forwarder {
static constexpr char forwarder_config_section[] = "forwarder";
- friend class utils::Singleton<Forwarder>;
public:
Forwarder();
@@ -47,20 +46,24 @@ class Forwarder : public utils::Singleton<Forwarder> {
Connector::Id registerLocalConnector(
asio::io_service &io_service,
Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
Connector::OnReconnectCallback &&reconnect_callback);
Forwarder &deleteConnector(Connector::Id id);
Connector::Ptr getConnector(Connector::Id id);
- void send(Packet &packet);
+ void send(Packet &packet, Connector::Id id);
void stop();
private:
- void onPacketFromListener(Connector *connector, utils::MemBuf &packet_buffer,
+ void onPacketFromListener(Connector *connector,
+ const std::vector<utils::MemBuf::Ptr> &packets,
const std::error_code &ec);
- void onPacketReceived(Connector *connector, utils::MemBuf &packet_buffer,
+ void onPacketReceived(Connector *connector,
+ const std::vector<utils::MemBuf::Ptr> &packets,
const std::error_code &ec);
void onPacketSent(Connector *connector, const std::error_code &ec);
void onConnectorClosed(Connector *connector);
@@ -86,5 +89,20 @@ class Forwarder : public utils::Singleton<Forwarder> {
Configuration config_;
};
+class ForwarderGlobal : public ::utils::Singleton<ForwarderGlobal> {
+ friend class utils::Singleton<ForwarderGlobal>;
+
+ public:
+ ~ForwarderGlobal() {}
+ std::shared_ptr<Forwarder> &getReference() { return forwarder_; }
+
+ private:
+ ForwarderGlobal() : forwarder_(std::make_shared<Forwarder>()) {}
+
+ private:
+ std::shared_ptr<Forwarder> forwarder_;
+};
+
} // namespace core
-} // namespace transport \ No newline at end of file
+
+} // namespace transport
diff --git a/libtransport/src/io_modules/forwarder/forwarder_module.cc b/libtransport/src/io_modules/forwarder/forwarder_module.cc
index 4f95b9ca0..ca9466f01 100644
--- a/libtransport/src/io_modules/forwarder/forwarder_module.cc
+++ b/libtransport/src/io_modules/forwarder/forwarder_module.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,24 +25,21 @@ ForwarderModule::ForwarderModule()
: IoModule(),
name_(""),
connector_id_(Connector::invalid_connector),
- forwarder_(Forwarder::getInstance()) {}
+ forwarder_ptr_(ForwarderGlobal::getInstance().getReference()),
+ forwarder_(*forwarder_ptr_) {}
-ForwarderModule::~ForwarderModule() {
- forwarder_.deleteConnector(connector_id_);
-}
+ForwarderModule::~ForwarderModule() {}
bool ForwarderModule::isConnected() { return true; }
void ForwarderModule::send(Packet &packet) {
IoModule::send(packet);
- forwarder_.send(packet);
+ forwarder_.send(packet, connector_id_);
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Sending from " << connector_id_ << " to " << 1 - connector_id_;
-
- // local_faces_.at(1 - local_id_).onPacket(packet);
}
-void ForwarderModule::send(const uint8_t *packet, std::size_t len) {
+void ForwarderModule::send(const utils::MemBuf::Ptr &buffer) {
// not supported
throw errors::NotImplementedException();
}
@@ -58,11 +55,14 @@ void ForwarderModule::closeConnection() {
}
void ForwarderModule::init(Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
Connector::OnReconnectCallback &&reconnect_callback,
asio::io_service &io_service,
const std::string &app_name) {
connector_id_ = forwarder_.registerLocalConnector(
- io_service, std::move(receive_callback), std::move(reconnect_callback));
+ io_service, std::move(receive_callback), std::move(sent_callback),
+ std::move(close_callback), std::move(reconnect_callback));
name_ = app_name;
}
@@ -78,7 +78,9 @@ void ForwarderModule::connect(bool is_consumer) {
std::uint32_t ForwarderModule::getMtu() { return interface_mtu; }
-bool ForwarderModule::isControlMessage(const uint8_t *message) { return false; }
+bool ForwarderModule::isControlMessage(utils::MemBuf &packet_buffer) {
+ return false;
+}
extern "C" IoModule *create_module(void) { return new ForwarderModule(); }
diff --git a/libtransport/src/io_modules/forwarder/forwarder_module.h b/libtransport/src/io_modules/forwarder/forwarder_module.h
index 58bfb7996..a48701161 100644
--- a/libtransport/src/io_modules/forwarder/forwarder_module.h
+++ b/libtransport/src/io_modules/forwarder/forwarder_module.h
@@ -38,11 +38,13 @@ class ForwarderModule : public IoModule {
void connect(bool is_consumer) override;
void send(Packet &packet) override;
- void send(const uint8_t *packet, std::size_t len) override;
+ void send(const utils::MemBuf::Ptr &buffer) override;
bool isConnected() override;
void init(Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
Connector::OnReconnectCallback &&reconnect_callback,
asio::io_service &io_service,
const std::string &app_name = "Libtransport") override;
@@ -51,15 +53,19 @@ class ForwarderModule : public IoModule {
std::uint32_t getMtu() override;
- bool isControlMessage(const uint8_t *message) override;
+ bool isControlMessage(utils::MemBuf &packet_buffer) override;
void processControlMessageReply(utils::MemBuf &packet_buffer) override;
void closeConnection() override;
private:
+ static void initForwarder();
+
+ private:
std::string name_;
Connector::Id connector_id_;
+ std::shared_ptr<Forwarder> forwarder_ptr_;
Forwarder &forwarder_;
};
diff --git a/libtransport/src/io_modules/forwarder/udp_tunnel.cc b/libtransport/src/io_modules/forwarder/udp_tunnel.cc
deleted file mode 100644
index bf6a69b92..000000000
--- a/libtransport/src/io_modules/forwarder/udp_tunnel.cc
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- */
-
-#include <glog/logging.h>
-#include <hicn/transport/utils/branch_prediction.h>
-#include <io_modules/forwarder/errors.h>
-#include <io_modules/forwarder/udp_tunnel.h>
-
-#include <iostream>
-#include <thread>
-#include <vector>
-
-namespace transport {
-namespace core {
-
-UdpTunnelConnector::~UdpTunnelConnector() {}
-
-void UdpTunnelConnector::connect(const std::string &hostname, uint16_t port,
- const std::string &bind_address,
- uint16_t bind_port) {
- if (state_ == State::CLOSED) {
- state_ = State::CONNECTING;
- endpoint_iterator_ = resolver_.resolve({hostname, std::to_string(port)});
- remote_endpoint_send_ = *endpoint_iterator_;
- socket_->open(remote_endpoint_send_.protocol());
-
- if (!bind_address.empty() && bind_port != 0) {
- using namespace asio::ip;
- socket_->bind(
- udp::endpoint(address::from_string(bind_address), bind_port));
- }
-
- state_ = State::CONNECTED;
-
- remote_endpoint_ = Endpoint(remote_endpoint_send_);
- local_endpoint_ = Endpoint(socket_->local_endpoint());
-
- doRecvPacket();
-
-#ifdef LINUX
- send_timer_.expires_from_now(std::chrono::microseconds(50));
- send_timer_.async_wait(std::bind(&UdpTunnelConnector::writeHandler, this,
- std::placeholders::_1));
-#endif
- }
-}
-
-void UdpTunnelConnector::send(Packet &packet) {
- strand_->post([this, pkt{packet.shared_from_this()}]() {
- bool write_in_progress = !output_buffer_.empty();
- output_buffer_.push_back(std::move(pkt));
- if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
- if (!write_in_progress) {
- doSendPacket();
- }
- } else {
- data_available_ = true;
- }
- });
-}
-
-void UdpTunnelConnector::send(const uint8_t *packet, std::size_t len) {}
-
-void UdpTunnelConnector::close() {
- DLOG_IF(INFO, VLOG_IS_ON(2)) << "UDPTunnelConnector::close";
- state_ = State::CLOSED;
- bool is_socket_owned = socket_.use_count() == 1;
- if (is_socket_owned) {
- io_service_.dispatch([this]() {
- this->socket_->close();
- // on_close_callback_(shared_from_this());
- });
- }
-}
-
-void UdpTunnelConnector::doSendPacket() {
-#ifdef LINUX
- send_timer_.expires_from_now(std::chrono::microseconds(50));
- send_timer_.async_wait(std::bind(&UdpTunnelConnector::writeHandler, this,
- std::placeholders::_1));
-#else
- auto packet = output_buffer_.front().get();
- auto array = std::vector<asio::const_buffer>();
-
- const ::utils::MemBuf *current = packet;
- do {
- array.push_back(asio::const_buffer(current->data(), current->length()));
- current = current->next();
- } while (current != packet);
-
- socket_->async_send_to(
- std::move(array), remote_endpoint_send_,
- strand_->wrap([this](std::error_code ec, std::size_t length) {
- if (TRANSPORT_EXPECT_TRUE(!ec)) {
- sent_callback_(this, make_error_code(forwarder_error::success));
- } else if (ec.value() ==
- static_cast<int>(std::errc::operation_canceled)) {
- // The connection has been closed by the application.
- return;
- } else {
- sendFailed();
- sent_callback_(this, ec);
- }
-
- output_buffer_.pop_front();
- if (!output_buffer_.empty()) {
- doSendPacket();
- }
- }));
-#endif
-}
-
-#ifdef LINUX
-void UdpTunnelConnector::writeHandler(std::error_code ec) {
- if (TRANSPORT_EXPECT_FALSE(state_ != State::CONNECTED)) {
- return;
- }
-
- auto len = std::min(output_buffer_.size(), std::size_t(Connector::max_burst));
-
- if (len) {
- int m = 0;
- for (auto &p : output_buffer_) {
- auto packet = p.get();
- ::utils::MemBuf *current = packet;
- int b = 0;
- do {
- // array.push_back(asio::const_buffer(current->data(),
- // current->length()));
- tx_iovecs_[m][b].iov_base = current->writableData();
- tx_iovecs_[m][b].iov_len = current->length();
- current = current->next();
- b++;
- } while (current != packet);
-
- tx_msgs_[m].msg_hdr.msg_iov = tx_iovecs_[m];
- tx_msgs_[m].msg_hdr.msg_iovlen = b;
- tx_msgs_[m].msg_hdr.msg_name = remote_endpoint_send_.data();
- tx_msgs_[m].msg_hdr.msg_namelen = remote_endpoint_send_.size();
- m++;
-
- if (--len == 0) {
- break;
- }
- }
-
- int retval = sendmmsg(socket_->native_handle(), tx_msgs_, m, MSG_DONTWAIT);
- if (retval > 0) {
- while (retval--) {
- output_buffer_.pop_front();
- }
- } else if (retval != EWOULDBLOCK && retval != EAGAIN) {
- LOG(ERROR) << "Error sending messages! " << strerror(errno)
- << " << retval";
- return;
- }
- }
-
- if (!output_buffer_.empty()) {
- send_timer_.expires_from_now(std::chrono::microseconds(50));
- send_timer_.async_wait(std::bind(&UdpTunnelConnector::writeHandler, this,
- std::placeholders::_1));
- }
-}
-
-void UdpTunnelConnector::readHandler(std::error_code ec) {
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "UdpTunnelConnector receive packet";
-
- if (TRANSPORT_EXPECT_TRUE(!ec)) {
- if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
- if (current_position_ == 0) {
- for (int i = 0; i < max_burst; i++) {
- auto read_buffer = getRawBuffer();
- rx_iovecs_[i][0].iov_base = read_buffer.first;
- rx_iovecs_[i][0].iov_len = read_buffer.second;
- rx_msgs_[i].msg_hdr.msg_iov = rx_iovecs_[i];
- rx_msgs_[i].msg_hdr.msg_iovlen = 1;
- }
- }
-
- int res = recvmmsg(socket_->native_handle(), rx_msgs_ + current_position_,
- max_burst - current_position_, MSG_DONTWAIT, nullptr);
- if (res < 0) {
- LOG(ERROR) << "Error receiving messages! " << strerror(errno) << " "
- << res;
- return;
- }
-
- for (int i = 0; i < res; i++) {
- auto packet = getPacketFromBuffer(
- reinterpret_cast<uint8_t *>(
- rx_msgs_[current_position_].msg_hdr.msg_iov[0].iov_base),
- rx_msgs_[current_position_].msg_len);
- receiveSuccess(*packet);
- receive_callback_(this, *packet,
- make_error_code(forwarder_error::success));
- ++current_position_;
- }
-
- doRecvPacket();
- } else {
- LOG(ERROR)
- << "Error in UDP: Receiving packets from a not connected socket.";
- }
- } else if (ec.value() == static_cast<int>(std::errc::operation_canceled)) {
- LOG(ERROR) << "The connection has been closed by the application.";
- return;
- } else {
- if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
- // receive_callback_(this, *read_msg_, ec);
- LOG(ERROR) << "Error in UDP connector: " << ec.value() << " "
- << ec.message();
- } else {
- LOG(ERROR) << "Error in connector while not connected. " << ec.value()
- << " " << ec.message();
- }
- }
-}
-#endif
-
-void UdpTunnelConnector::doRecvPacket() {
-#ifdef LINUX
- if (state_ == State::CONNECTED) {
-#if ((ASIO_VERSION / 100 % 1000) < 11)
- socket_->async_receive(asio::null_buffers(),
-#else
- socket_->async_wait(asio::ip::tcp::socket::wait_read,
-#endif
- std::bind(&UdpTunnelConnector::readHandler, this,
- std::placeholders::_1));
- }
-#else
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "UdpTunnelConnector receive packet";
- read_msg_ = getRawBuffer();
- socket_->async_receive_from(
- asio::buffer(read_msg_.first, read_msg_.second), remote_endpoint_recv_,
- [this](std::error_code ec, std::size_t length) {
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "UdpTunnelConnector received packet length=" << length;
- if (TRANSPORT_EXPECT_TRUE(!ec)) {
- if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
- auto packet = getPacketFromBuffer(read_msg_.first, length);
- receiveSuccess(*packet);
- receive_callback_(this, *packet,
- make_error_code(forwarder_error::success));
- doRecvPacket();
- } else {
- LOG(ERROR) << "Error in UDP: Receiving packets from a not "
- "connected socket.";
- }
- } else if (ec.value() ==
- static_cast<int>(std::errc::operation_canceled)) {
- LOG(ERROR) << "The connection has been closed by the application.";
- return;
- } else {
- if (TRANSPORT_EXPECT_TRUE(state_ == State::CONNECTED)) {
- LOG(ERROR) << "Error in UDP connector: " << ec.value()
- << ec.message();
- } else {
- LOG(ERROR) << "Error while not connected";
- }
- }
- });
-#endif
-}
-
-void UdpTunnelConnector::doConnect() {
- asio::async_connect(
- *socket_, endpoint_iterator_,
- [this](std::error_code ec, asio::ip::udp::resolver::iterator) {
- if (!ec) {
- state_ = State::CONNECTED;
- doRecvPacket();
-
- if (data_available_) {
- data_available_ = false;
- doSendPacket();
- }
- } else {
- LOG(ERROR) << "UDP Connection failed!!!";
- timer_.expires_from_now(std::chrono::milliseconds(500));
- timer_.async_wait(std::bind(&UdpTunnelConnector::doConnect, this));
- }
- });
-}
-
-} // namespace core
-
-} // namespace transport
diff --git a/libtransport/src/io_modules/hicn-light/CMakeLists.txt b/libtransport/src/io_modules/hicn-light/CMakeLists.txt
new file mode 100644
index 000000000..ae3aec52d
--- /dev/null
+++ b/libtransport/src/io_modules/hicn-light/CMakeLists.txt
@@ -0,0 +1,63 @@
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# 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.
+
+if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
+ find_package(Libhicnctrl ${HICN_CURRENT_VERSION} REQUIRED NO_MODULE)
+
+ if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+ else()
+ set(LIBTYPE shared)
+ endif()
+
+ list(APPEND LIBHICNCTRL_LIBRARIES hicn::hicnctrl.${LIBTYPE})
+else()
+ if (DISABLE_SHARED_LIBRARIES)
+ if (WIN32)
+ set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_STATIC})
+ else ()
+ set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_STATIC} log)
+ endif ()
+ list(APPEND DEPENDENCIES
+ ${LIBHICNCTRL_STATIC}
+ )
+ else()
+ set(LIBHICNCTRL_LIBRARIES ${LIBHICNCTRL_SHARED})
+ list(APPEND DEPENDENCIES
+ ${LIBHICNCTRL_SHARED}
+ )
+ endif()
+endif()
+
+list(APPEND MODULE_HEADER_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_forwarder_module.h
+)
+
+list(APPEND MODULE_SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_forwarder_module.cc
+)
+
+build_module(hicnlight_module
+ SHARED
+ SOURCES ${MODULE_SOURCE_FILES}
+ DEPENDS ${DEPENDENCIES}
+ COMPONENT ${LIBTRANSPORT_COMPONENT}
+ LINK_LIBRARIES PRIVATE ${LIBHICNCTRL_LIBRARIES}
+ INCLUDE_DIRS
+ PRIVATE
+ ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
+ ${Libhicn_INCLUDE_DIRS}
+ ${Libhicnctrl_INCLUDE_DIRS}
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
diff --git a/libtransport/src/io_modules/hicn-light/hicn_forwarder_module.cc b/libtransport/src/io_modules/hicn-light/hicn_forwarder_module.cc
new file mode 100644
index 000000000..98bd42fb5
--- /dev/null
+++ b/libtransport/src/io_modules/hicn-light/hicn_forwarder_module.cc
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.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 <core/udp_connector.h>
+#include <hicn/transport/utils/uri.h>
+#include <io_modules/hicn-light/hicn_forwarder_module.h>
+
+extern "C" {
+#include <hicn/ctrl/hicn-light.h>
+}
+
+namespace transport {
+
+namespace core {
+
+HicnForwarderModule::ForwarderUrlInitializer
+ HicnForwarderModule::forwarder_url_initializer_;
+
+HicnForwarderModule::HicnForwarderModule()
+ : IoModule(), connector_(nullptr), seq_(0) {}
+
+HicnForwarderModule::~HicnForwarderModule() {}
+
+void HicnForwarderModule::connect(bool is_consumer) {
+ if (!connector_->isConnected()) {
+ // Parse forwarder URI
+ utils::Uri uri;
+ uri.parse(forwarder_url_initializer_.getForwarderUrl());
+
+ // Safechecks
+ CHECK(uri.getProtocol() == "hicn")
+ << "The protocol of the forwarder url should be hicn";
+ uint16_t port_min = (1 << 10);
+ uint16_t port_max = (1 << 16) - 1;
+
+ uint16_t port = std::stoul(uri.getPort());
+
+ CHECK(port > port_min && port < port_max)
+ << "The port should be between " << port_min << " and " << port_max;
+
+ VLOG(1) << "Connecting to " << uri.getLocator() << ":" << uri.getPort();
+
+ connector_->connect(uri.getLocator(), port);
+ connector_->setRole(is_consumer ? Connector::Role::CONSUMER
+ : Connector::Role::PRODUCER);
+ }
+}
+
+bool HicnForwarderModule::isConnected() { return connector_->isConnected(); }
+
+void HicnForwarderModule::send(Packet &packet) {
+ IoModule::send(packet);
+ packet.setChecksum();
+ connector_->send(packet);
+}
+
+void HicnForwarderModule::send(const utils::MemBuf::Ptr &packet) {
+ counters_.tx_packets++;
+ counters_.tx_bytes += packet->length();
+
+ // Perfect forwarding
+ connector_->send(packet);
+}
+
+void HicnForwarderModule::registerRoute(const Prefix &prefix) {
+ auto command = createCommandRoute(prefix.toSockaddr(),
+ (uint8_t)prefix.getPrefixLength());
+ if (!command) {
+ // TODO error
+ return;
+ }
+ send(command);
+}
+
+void HicnForwarderModule::sendMapme() {
+ auto command = createCommandMapmeSendUpdate();
+ if (!command) {
+ // TODO error
+ return;
+ }
+ send(command);
+}
+
+void HicnForwarderModule::setForwardingStrategy(const Prefix &prefix,
+ std::string &strategy) {
+ auto command = createCommandSetForwardingStrategy(
+ prefix.toSockaddr(), (uint8_t)prefix.getPrefixLength(), strategy);
+ if (!command) {
+ // TODO error
+ return;
+ }
+ send(command);
+}
+
+void HicnForwarderModule::closeConnection() {
+ auto command = createCommandDeleteConnection();
+ if (!command) {
+ // TODO error
+ return;
+ }
+
+ connector_->setSentCallback([](Connector *c, const std::error_code &ec) {
+ if (!ec) {
+ c->close();
+ }
+ });
+
+ send(command);
+}
+
+void HicnForwarderModule::init(
+ Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
+ Connector::OnReconnectCallback &&reconnect_callback,
+ asio::io_service &io_service, const std::string &app_name) {
+ if (!connector_) {
+ connector_.reset(new UdpTunnelConnector(
+ io_service, std::move(receive_callback), std::move(sent_callback),
+ std::move(close_callback), std::move(reconnect_callback)));
+ }
+}
+
+void HicnForwarderModule::processControlMessageReply(
+ utils::MemBuf &packet_buffer) {
+ if (packet_buffer.data()[0] == NACK_LIGHT) {
+ throw errors::RuntimeException(
+ "Received Nack message from hicn light forwarder.");
+ }
+}
+
+std::uint32_t HicnForwarderModule::getMtu() { return interface_mtu; }
+
+bool HicnForwarderModule::isControlMessage(utils::MemBuf &packet_buffer) {
+ return packet_buffer.data()[0] == ACK_LIGHT ||
+ packet_buffer.data()[0] == NACK_LIGHT;
+}
+
+/**
+ * @return A valid msg_route_add_t structure if the command was successful, or
+ * with .command_id == COMMAND_TYPE_UNDEFINED in case of error.
+ */
+utils::MemBuf::Ptr HicnForwarderModule::createCommandRoute(
+ std::unique_ptr<sockaddr> &&addr, uint8_t prefix_length) {
+ auto ret = PacketManager<>::getInstance().getMemBuf();
+ auto command = reinterpret_cast<msg_route_add_t *>(ret->writableData());
+ ret->append(sizeof(msg_route_add_t));
+ std::memset(command, 0, sizeof(*command));
+
+ if (!IS_VALID_FAMILY(addr->sa_family)) return nullptr;
+
+ *command = {
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_ROUTE_ADD,
+ .length = 1,
+ .seq_num = 0,
+ },
+ .payload =
+ {
+ .cost = 1,
+ .family = (uint8_t)addr->sa_family,
+ .len = prefix_length,
+ },
+ };
+
+ switch (addr->sa_family) {
+ case AF_INET:
+ command->payload.address.v4.as_inaddr =
+ ((sockaddr_in *)addr.get())->sin_addr;
+ break;
+ case AF_INET6:
+ command->payload.address.v6.as_in6addr =
+ ((sockaddr_in6 *)addr.get())->sin6_addr;
+ break;
+ }
+ snprintf(command->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ "SELF");
+
+ return ret;
+}
+
+utils::MemBuf::Ptr HicnForwarderModule::createCommandDeleteConnection() {
+ auto ret = PacketManager<>::getInstance().getMemBuf();
+ auto command =
+ reinterpret_cast<msg_connection_remove_t *>(ret->writableData());
+ ret->append(sizeof(msg_connection_remove_t));
+ std::memset(command, 0, sizeof(*command));
+
+ *command = {
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_CONNECTION_REMOVE,
+ .length = 1,
+ .seq_num = 0,
+ },
+ };
+
+ snprintf(command->payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s",
+ "SELF");
+
+ return ret;
+}
+
+utils::MemBuf::Ptr HicnForwarderModule::createCommandMapmeSendUpdate() {
+ auto ret = PacketManager<>::getInstance().getMemBuf();
+ auto command = reinterpret_cast<msg_mapme_add_t *>(ret->writableData());
+ ret->append(sizeof(msg_mapme_add_t));
+ std::memset(command, 0, sizeof(*command));
+
+ *command = {.header = {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_MAPME_ADD,
+ .length = 1,
+ .seq_num = seq_++,
+ }};
+
+ return ret;
+}
+
+utils::MemBuf::Ptr HicnForwarderModule::createCommandSetForwardingStrategy(
+ std::unique_ptr<sockaddr> &&addr, uint32_t prefix_len,
+ std::string strategy) {
+ auto ret = PacketManager<>::getInstance().getMemBuf();
+ auto command = reinterpret_cast<msg_strategy_set_t *>(ret->writableData());
+ ret->append(sizeof(msg_strategy_set_t));
+ std::memset(command, 0, sizeof(*command));
+
+ if (!IS_VALID_FAMILY(addr->sa_family)) return nullptr;
+
+ strategy_type_t strategy_type = strategy_type_from_str(strategy.c_str());
+ if (strategy_type == STRATEGY_TYPE_UNDEFINED) return nullptr;
+
+ *command = {
+ .header =
+ {
+ .message_type = REQUEST_LIGHT,
+ .command_id = COMMAND_TYPE_STRATEGY_SET,
+ .length = 1,
+ .seq_num = seq_++,
+ },
+ .payload =
+ {
+ .family = (uint8_t)addr->sa_family,
+ .len = (uint8_t)prefix_len,
+ .type = (uint8_t)strategy_type,
+ },
+ };
+
+ switch (addr->sa_family) {
+ case AF_INET:
+ command->payload.address.v4.as_inaddr =
+ ((sockaddr_in *)addr.get())->sin_addr;
+ break;
+ case AF_INET6:
+ command->payload.address.v6.as_in6addr =
+ ((sockaddr_in6 *)addr.get())->sin6_addr;
+ break;
+ }
+
+ return ret;
+}
+
+extern "C" IoModule *create_module(void) { return new HicnForwarderModule(); }
+
+} // namespace core
+
+} // namespace transport
diff --git a/libtransport/src/io_modules/hicn-light/hicn_forwarder_module.h b/libtransport/src/io_modules/hicn-light/hicn_forwarder_module.h
new file mode 100644
index 000000000..2378b93f8
--- /dev/null
+++ b/libtransport/src/io_modules/hicn-light/hicn_forwarder_module.h
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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 <core/global_configuration.h>
+#include <hicn/transport/core/io_module.h>
+#include <hicn/transport/core/prefix.h>
+
+#include <libconfig.h++>
+
+extern "C" {
+#include <hicn/ctrl/hicn-light.h>
+}
+
+namespace transport {
+
+namespace core {
+
+class UdpTunnelConnector;
+
+class HicnForwarderModule : public IoModule {
+ static constexpr std::uint16_t interface_mtu = 1500;
+
+ public:
+#if 0
+ union addressLight {
+ uint32_t ipv4;
+ struct in6_addr ipv6;
+ };
+
+ struct route_to_self_command {
+ uint8_t messageType;
+ uint8_t commandID;
+ uint16_t length;
+ uint32_t seqNum;
+ char symbolicOrConnid[16];
+ union addressLight address;
+ uint16_t cost;
+ uint8_t addressType;
+ uint8_t len;
+ };
+
+ using route_to_self_command = struct route_to_self_command;
+#endif
+
+ HicnForwarderModule();
+
+ ~HicnForwarderModule();
+
+ void connect(bool is_consumer) override;
+
+ void send(Packet &packet) override;
+ void send(const utils::MemBuf::Ptr &buffer) override;
+
+ bool isConnected() override;
+
+ void init(Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
+ Connector::OnReconnectCallback &&reconnect_callback,
+ asio::io_service &io_service,
+ const std::string &app_name = "Libtransport") override;
+
+ void registerRoute(const Prefix &prefix) override;
+
+ void sendMapme() override;
+
+ void setForwardingStrategy(const Prefix &prefix,
+ std::string &strategy) override;
+
+ std::uint32_t getMtu() override;
+
+ bool isControlMessage(utils::MemBuf &packet_buffer) override;
+
+ void processControlMessageReply(utils::MemBuf &packet_buffer) override;
+
+ void closeConnection() override;
+
+ private:
+ utils::MemBuf::Ptr createCommandRoute(std::unique_ptr<sockaddr> &&addr,
+ uint8_t prefix_length);
+ utils::MemBuf::Ptr createCommandDeleteConnection();
+ utils::MemBuf::Ptr createCommandMapmeSendUpdate();
+ utils::MemBuf::Ptr createCommandSetForwardingStrategy(
+ std::unique_ptr<sockaddr> &&addr, uint32_t prefix_len,
+ std::string strategy);
+
+ static void parseForwarderConfiguration(const libconfig::Setting &io_config,
+ std::error_code &ec);
+ static std::string initForwarderUrl();
+
+ private:
+ std::shared_ptr<UdpTunnelConnector> connector_;
+ /* Sequence number used for sending control messages */
+ uint32_t seq_;
+
+ class ForwarderUrlInitializer {
+ static inline char default_hicnlight_url[] = "hicn://127.0.0.1:9695";
+ static inline char hicnlight_configuration_section[] = "hicnlight";
+
+ public:
+ ForwarderUrlInitializer()
+ : forwarder_url_(ForwarderUrlInitializer::default_hicnlight_url) {
+ using namespace std::placeholders;
+ GlobalConfiguration::getInstance().registerConfigurationParser(
+ ForwarderUrlInitializer::hicnlight_configuration_section,
+ std::bind(&ForwarderUrlInitializer::parseForwarderConfiguration, this,
+ _1, _2));
+ }
+
+ std::string getForwarderUrl() { return forwarder_url_; }
+
+ private:
+ void parseForwarderConfiguration(const libconfig::Setting &forwarder_config,
+ std::error_code &ec) {
+ using namespace libconfig;
+
+ // forwarder url hicn://127.0.0.1:12345
+ if (forwarder_config.exists("forwarder_url")) {
+ // Get number of threads
+ forwarder_config.lookupValue("forwarder_url", forwarder_url_);
+ VLOG(1) << "Forwarder URL from config file: " << forwarder_url_;
+ }
+ }
+
+ // Url of the forwarder
+ std::string forwarder_url_;
+ };
+
+ static ForwarderUrlInitializer forwarder_url_initializer_;
+};
+
+extern "C" IoModule *create_module(void);
+
+} // namespace core
+
+} // namespace transport
diff --git a/libtransport/src/io_modules/loopback/local_face.cc b/libtransport/src/io_modules/loopback/local_face.cc
deleted file mode 100644
index b73444330..000000000
--- a/libtransport/src/io_modules/loopback/local_face.cc
+++ /dev/null
@@ -1,68 +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 <glog/logging.h>
-#include <hicn/transport/core/asio_wrapper.h>
-#include <hicn/transport/core/content_object.h>
-#include <hicn/transport/core/interest.h>
-#include <io_modules/loopback/local_face.h>
-
-namespace transport {
-namespace core {
-
-Face::Face(Connector::PacketReceivedCallback &&receive_callback,
- asio::io_service &io_service, const std::string &app_name)
- : receive_callback_(std::move(receive_callback)),
- io_service_(io_service),
- name_(app_name) {}
-
-Face::Face(const Face &other)
- : receive_callback_(other.receive_callback_),
- io_service_(other.io_service_),
- name_(other.name_) {}
-
-Face::Face(Face &&other)
- : receive_callback_(std::move(other.receive_callback_)),
- io_service_(other.io_service_),
- name_(std::move(other.name_)) {}
-
-Face &Face::operator=(const Face &other) {
- receive_callback_ = other.receive_callback_;
- io_service_ = other.io_service_;
- name_ = other.name_;
-
- return *this;
-}
-
-Face &Face::operator=(Face &&other) {
- receive_callback_ = std::move(other.receive_callback_);
- io_service_ = std::move(other.io_service_);
- name_ = std::move(other.name_);
-
- return *this;
-}
-
-void Face::onPacket(const Packet &packet) {
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Sending content to local socket.";
-
- if (Packet::isInterest(packet.data())) {
- rescheduleOnIoService<Interest>(packet);
- } else {
- rescheduleOnIoService<ContentObject>(packet);
- }
-}
-
-} // namespace core
-} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/io_modules/loopback/local_face.h b/libtransport/src/io_modules/loopback/local_face.h
deleted file mode 100644
index 1f4101447..000000000
--- a/libtransport/src/io_modules/loopback/local_face.h
+++ /dev/null
@@ -1,53 +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/core/asio_wrapper.h>
-#include <hicn/transport/core/connector.h>
-#include <hicn/transport/core/global_object_pool.h>
-#include <hicn/transport/utils/move_wrapper.h>
-
-namespace transport {
-namespace core {
-
-class Face {
- public:
- Face(Connector::PacketReceivedCallback &&receive_callback,
- asio::io_service &io_service, const std::string &app_name);
-
- Face(const Face &other);
- Face(Face &&other);
- void onPacket(const Packet &packet);
- Face &operator=(Face &&other);
- Face &operator=(const Face &other);
-
- private:
- template <typename T>
- void rescheduleOnIoService(const Packet &packet) {
- auto p = core::PacketManager<T>::getInstance().getPacket();
- p->replace(packet.data(), packet.length());
- io_service_.get().post([this, p]() mutable {
- receive_callback_(nullptr, *p, make_error_code(0));
- });
- }
-
- Connector::PacketReceivedCallback receive_callback_;
- std::reference_wrapper<asio::io_service> io_service_;
- std::string name_;
-};
-
-} // namespace core
-} // namespace transport
diff --git a/libtransport/src/io_modules/loopback/loopback_module.cc b/libtransport/src/io_modules/loopback/loopback_module.cc
deleted file mode 100644
index f7dd5e7b0..000000000
--- a/libtransport/src/io_modules/loopback/loopback_module.cc
+++ /dev/null
@@ -1,84 +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 <glog/logging.h>
-#include <hicn/transport/errors/not_implemented_exception.h>
-#include <io_modules/loopback/loopback_module.h>
-
-namespace transport {
-
-namespace core {
-
-std::vector<std::unique_ptr<LocalConnector>> LoopbackModule::local_faces_;
-std::atomic<uint32_t> LoopbackModule::global_counter_(0);
-
-LoopbackModule::LoopbackModule() : IoModule(), local_id_(~0) {}
-
-LoopbackModule::~LoopbackModule() {}
-
-void LoopbackModule::connect(bool is_consumer) {}
-
-bool LoopbackModule::isConnected() { return true; }
-
-void LoopbackModule::send(Packet &packet) {
- IoModule::send(packet);
-
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "LoopbackModule: sending from " << local_id_
- << " to " << 1 - local_id_;
-
- local_faces_.at(1 - local_id_)->send(packet);
-}
-
-void LoopbackModule::send(const uint8_t *packet, std::size_t len) {
- // not supported
- throw errors::NotImplementedException();
-}
-
-void LoopbackModule::registerRoute(const Prefix &prefix) {
- // For the moment we route packets from one socket to the other.
- // Next step will be to introduce a FIB
- return;
-}
-
-void LoopbackModule::closeConnection() {
- local_faces_.erase(local_faces_.begin() + local_id_);
-}
-
-void LoopbackModule::init(Connector::PacketReceivedCallback &&receive_callback,
- Connector::OnReconnectCallback &&reconnect_callback,
- asio::io_service &io_service,
- const std::string &app_name) {
- if (local_id_ == uint32_t(~0) && global_counter_ < 2) {
- local_id_ = global_counter_++;
- local_faces_.emplace(
- local_faces_.begin() + local_id_,
- new LocalConnector(io_service, std::move(receive_callback), nullptr,
- nullptr, std::move(reconnect_callback)));
- }
-}
-
-void LoopbackModule::processControlMessageReply(utils::MemBuf &packet_buffer) {
- return;
-}
-
-std::uint32_t LoopbackModule::getMtu() { return interface_mtu; }
-
-bool LoopbackModule::isControlMessage(const uint8_t *message) { return false; }
-
-extern "C" IoModule *create_module(void) { return new LoopbackModule(); }
-
-} // namespace core
-
-} // namespace transport
diff --git a/libtransport/src/io_modules/loopback/loopback_module.h b/libtransport/src/io_modules/loopback/loopback_module.h
deleted file mode 100644
index 219fa8841..000000000
--- a/libtransport/src/io_modules/loopback/loopback_module.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
-
-#include <core/local_connector.h>
-#include <hicn/transport/core/io_module.h>
-#include <hicn/transport/core/prefix.h>
-
-#include <atomic>
-
-namespace transport {
-
-namespace core {
-
-class LoopbackModule : public IoModule {
- static constexpr std::uint16_t interface_mtu = 1500;
-
- public:
- LoopbackModule();
-
- ~LoopbackModule();
-
- void connect(bool is_consumer) override;
-
- void send(Packet &packet) override;
- void send(const uint8_t *packet, std::size_t len) override;
-
- bool isConnected() override;
-
- void init(Connector::PacketReceivedCallback &&receive_callback,
- Connector::OnReconnectCallback &&reconnect_callback,
- asio::io_service &io_service,
- const std::string &app_name = "Libtransport") override;
-
- void registerRoute(const Prefix &prefix) override;
-
- std::uint32_t getMtu() override;
-
- bool isControlMessage(const uint8_t *message) override;
-
- void processControlMessageReply(utils::MemBuf &packet_buffer) override;
-
- void closeConnection() override;
-
- private:
- static std::vector<std::unique_ptr<LocalConnector>> local_faces_;
- static std::atomic<uint32_t> global_counter_;
-
- private:
- uint32_t local_id_;
-};
-
-extern "C" IoModule *create_module(void);
-
-} // namespace core
-
-} // namespace transport
diff --git a/libtransport/src/io_modules/memif/CMakeLists.txt b/libtransport/src/io_modules/memif/CMakeLists.txt
index fc1c1f135..134ac1db6 100644
--- a/libtransport/src/io_modules/memif/CMakeLists.txt
+++ b/libtransport/src/io_modules/memif/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,18 +11,28 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-find_package(Vpp REQUIRED)
-find_package(Libmemif REQUIRED)
+
+##############################################################
+# Dependencies and third party libs
+##############################################################
+find_package(Vpp ${VPP_DEFAULT_VERSION} EXACT REQUIRED)
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- find_package(HicnPlugin REQUIRED)
- find_package(SafeVapi REQUIRED)
+ find_package(HicnPlugin ${CURRENT_VERSION} REQUIRED)
+ find_package(SafeVapi ${CURRENT_VERSION} REQUIRED)
else()
list(APPEND DEPENDENCIES
${SAFE_VAPI_SHARED}
)
endif()
+list(APPEND DEPENDENCIES
+ ${MEMIF_THIRD_PARTY_DEPENDENCIES}
+)
+
+##############################################################
+# Sources
+##############################################################
list(APPEND MODULE_HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/hicn_vapi.h
${CMAKE_CURRENT_SOURCE_DIR}/memif_connector.h
@@ -32,23 +42,23 @@ list(APPEND MODULE_HEADER_FILES
list(APPEND MODULE_SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/hicn_vapi.c
- ${CMAKE_CURRENT_SOURCE_DIR}/memif_connector.cc
${CMAKE_CURRENT_SOURCE_DIR}/memif_vapi.c
${CMAKE_CURRENT_SOURCE_DIR}/vpp_forwarder_module.cc
)
build_module(memif_module
- SHARED
SOURCES ${MODULE_SOURCE_FILES}
DEPENDS ${DEPENDENCIES}
COMPONENT ${LIBTRANSPORT_COMPONENT}-io-modules
- LINK_LIBRARIES ${LIBMEMIF_LIBRARIES} ${SAFE_VAPI_LIBRARIES}
+ OBJECT_LIBRARIES ${MEMIF_THIRD_PARTY_OBJECT_LIBRARIES}
+ LINK_LIBRARIES PRIVATE ${HICN_LIBRARIES} ${SAFE_VAPI_LIBRARIES}
INCLUDE_DIRS
- ${LIBTRANSPORT_INCLUDE_DIRS}
- ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
- ${VPP_INCLUDE_DIRS}
- ${LIBMEMIF_INCLUDE_DIRS}
- ${SAFE_VAPI_INCLUDE_DIRS}
+ PUBLIC
+ ${MEMIF_THIRD_PARTY_INCLUDE_DIRS}
+ ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
+ ${VPP_INCLUDE_DIRS}
+ ${LIBMEMIF_INCLUDE_DIRS}
+ ${SAFE_VAPI_INCLUDE_DIRS}
DEFINITIONS ${COMPILER_DEFINITIONS}
- COMPILE_OPTIONS ${COMPILE_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS} ${MARCH_COMPILER_OPTIONS}
)
diff --git a/libtransport/src/io_modules/memif/hicn_vapi.c b/libtransport/src/io_modules/memif/hicn_vapi.c
index 6d78026ab..9fc64f720 100644
--- a/libtransport/src/io_modules/memif/hicn_vapi.c
+++ b/libtransport/src/io_modules/memif/hicn_vapi.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -27,8 +27,6 @@
#include <vlibapi/api.h>
#include <vlibmemory/api.h>
#include <vnet/ip/format.h>
-#include <vnet/ip/ip4_packet.h>
-#include <vnet/ip/ip6_packet.h>
#include <vpp_plugins/hicn/error.h>
#include <vppinfra/error.h>
@@ -46,9 +44,6 @@ u8 *format_vl_api_address_union(u8 *s, va_list *args) { return NULL; }
/*********************************************************************************/
-DEFINE_VAPI_MSG_IDS_HICN_API_JSON
-DEFINE_VAPI_MSG_IDS_IP_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) {
@@ -58,14 +53,15 @@ static vapi_error_e register_prod_app_cb(
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));
+ output_params->prod_addr =
+ (hicn_ip_address_t *)malloc(sizeof(hicn_ip_address_t));
+ memset(output_params->prod_addr, 0, sizeof(hicn_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));
+ sizeof(ipv6_address_t));
else
memcpy(&output_params->prod_addr->v4, reply->prod_addr.un.ip4,
- sizeof(ip4_address_t));
+ sizeof(ipv4_address_t));
output_params->face_id = reply->faceid;
return reply->retval;
@@ -78,13 +74,14 @@ int hicn_vapi_register_prod_app(vapi_ctx_t 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)) {
+ if (hicn_ip_address_is_v4(
+ (hicn_ip_address_t *)&input_params->prefix->address)) {
memcpy(&msg->payload.prefix.address.un.ip4, &input_params->prefix->address,
- sizeof(ip4_address_t));
+ sizeof(ipv4_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));
+ sizeof(ipv6_address_t));
msg->payload.prefix.address.af = ADDRESS_IP6;
}
msg->payload.prefix.len = input_params->prefix->len;
@@ -126,14 +123,14 @@ static vapi_error_e register_cons_app_cb(
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));
+ output_params->src6 = (hicn_ip_address_t *)malloc(sizeof(hicn_ip_address_t));
+ output_params->src4 = (hicn_ip_address_t *)malloc(sizeof(hicn_ip_address_t));
+ memset(output_params->src6, 0, sizeof(hicn_ip_address_t));
+ memset(output_params->src4, 0, sizeof(hicn_ip_address_t));
memcpy(&output_params->src6->v6, &reply->src_addr6.un.ip6,
- sizeof(ip6_address_t));
+ sizeof(ipv6_address_t));
memcpy(&output_params->src4->v4, &reply->src_addr4.un.ip4,
- sizeof(ip4_address_t));
+ sizeof(ipv4_address_t));
output_params->face_id1 = reply->faceid1;
output_params->face_id2 = reply->faceid2;
@@ -190,31 +187,31 @@ int hicn_vapi_register_route(vapi_ctx_t ctx,
vapi_msg_ip_route_add_del *msg = vapi_alloc_ip_route_add_del(ctx, 1);
msg->payload.is_add = 1;
- if (ip46_address_is_ip4((ip46_address_t *)(input_params->prod_addr))) {
+ if (hicn_ip_address_is_v4((hicn_ip_address_t *)(input_params->prod_addr))) {
memcpy(&msg->payload.route.prefix.address.un.ip4,
- &input_params->prefix->address.v4, sizeof(ip4_address_t));
+ &input_params->prefix->address.v4, sizeof(ipv4_address_t));
msg->payload.route.prefix.address.af = ADDRESS_IP4;
msg->payload.route.prefix.len = input_params->prefix->len;
} else {
memcpy(&msg->payload.route.prefix.address.un.ip6,
- &input_params->prefix->address.v6, sizeof(ip6_address_t));
+ &input_params->prefix->address.v6, sizeof(ipv6_address_t));
msg->payload.route.prefix.address.af = ADDRESS_IP6;
msg->payload.route.prefix.len = input_params->prefix->len;
}
msg->payload.route.paths[0].sw_if_index = ~0;
msg->payload.route.paths[0].table_id = 0;
- if (ip46_address_is_ip4((ip46_address_t *)(input_params->prod_addr))) {
+ if (hicn_ip_address_is_v4((hicn_ip_address_t *)(input_params->prod_addr))) {
memcpy(&(msg->payload.route.paths[0].nh.address.ip4),
- input_params->prod_addr->v4.as_u8, sizeof(ip4_address_t));
+ input_params->prod_addr->v4.as_u8, sizeof(ipv4_address_t));
msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP4;
} else {
memcpy(&(msg->payload.route.paths[0].nh.address.ip6),
- input_params->prod_addr->v6.as_u8, sizeof(ip6_address_t));
+ input_params->prod_addr->v6.as_u8, sizeof(ipv6_address_t));
msg->payload.route.paths[0].proto = FIB_API_PATH_NH_PROTO_IP6;
}
- msg->payload.route.paths[0].type = FIB_API_PATH_FLAG_NONE;
+ msg->payload.route.paths[0].type = FIB_API_PATH_TYPE_NORMAL;
msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE;
int ret = vapi_ip_route_add_del(ctx, msg, reigster_route_cb, NULL);
diff --git a/libtransport/src/io_modules/memif/hicn_vapi.h b/libtransport/src/io_modules/memif/hicn_vapi.h
index e94c97749..cfdc93fe3 100644
--- a/libtransport/src/io_modules/memif/hicn_vapi.h
+++ b/libtransport/src/io_modules/memif/hicn_vapi.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -27,7 +27,7 @@ extern "C" {
#include "stdint.h"
typedef struct {
- ip_prefix_t* prefix;
+ hicn_ip_prefix_t* prefix;
uint32_t swif;
uint32_t cs_reserved;
} hicn_producer_input_params;
@@ -42,20 +42,20 @@ typedef struct {
typedef struct {
uint32_t cs_reserved;
- ip_address_t* prod_addr;
+ hicn_ip_address_t* prod_addr;
uint32_t face_id;
} hicn_producer_output_params;
typedef struct {
- ip_address_t* src4;
- ip_address_t* src6;
+ hicn_ip_address_t* src4;
+ hicn_ip_address_t* src6;
uint32_t face_id1;
uint32_t face_id2;
} hicn_consumer_output_params;
typedef struct {
- ip_prefix_t* prefix;
- ip_address_t* prod_addr;
+ hicn_ip_prefix_t* prefix;
+ hicn_ip_address_t* prod_addr;
} hicn_producer_set_route_params;
int hicn_vapi_register_prod_app(vapi_ctx_t ctx,
diff --git a/libtransport/src/io_modules/memif/memif_connector.cc b/libtransport/src/io_modules/memif/memif_connector.cc
deleted file mode 100644
index 68ad52b63..000000000
--- a/libtransport/src/io_modules/memif/memif_connector.cc
+++ /dev/null
@@ -1,492 +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 <glog/logging.h>
-#include <hicn/transport/errors/not_implemented_exception.h>
-#include <io_modules/memif/memif_connector.h>
-#include <sys/epoll.h>
-
-#include <cstdlib>
-
-extern "C" {
-#include <memif/libmemif.h>
-};
-
-#define CANCEL_TIMER 1
-
-namespace transport {
-
-namespace core {
-
-struct memif_connection {
- uint16_t index;
- /* memif conenction handle */
- memif_conn_handle_t conn;
- /* transmit queue id */
- uint16_t tx_qid;
- /* tx buffers */
- memif_buffer_t *tx_bufs;
- /* allocated tx buffers counter */
- /* number of tx buffers pointing to shared memory */
- uint16_t tx_buf_num;
- /* rx buffers */
- memif_buffer_t *rx_bufs;
- /* allcoated rx buffers counter */
- /* number of rx buffers pointing to shared memory */
- uint16_t rx_buf_num;
- /* interface ip address */
- uint8_t ip_addr[4];
-};
-
-std::once_flag MemifConnector::flag_;
-utils::EpollEventReactor MemifConnector::main_event_reactor_;
-
-MemifConnector::MemifConnector(PacketReceivedCallback &&receive_callback,
- PacketSentCallback &&packet_sent,
- OnCloseCallback &&close_callback,
- OnReconnectCallback &&on_reconnect,
- asio::io_service &io_service,
- std::string app_name)
- : Connector(std::move(receive_callback), std::move(packet_sent),
- std::move(close_callback), std::move(on_reconnect)),
- memif_worker_(nullptr),
- timer_set_(false),
- send_timer_(std::make_unique<utils::FdDeadlineTimer>(event_reactor_)),
- disconnect_timer_(
- std::make_unique<utils::FdDeadlineTimer>(event_reactor_)),
- io_service_(io_service),
- work_(asio::make_work_guard(io_service_)),
- memif_connection_(std::make_unique<memif_connection_t>()),
- tx_buf_counter_(0),
- is_reconnection_(false),
- data_available_(false),
- app_name_(app_name),
- socket_filename_("") {
- std::call_once(MemifConnector::flag_, &MemifConnector::init, this);
-}
-
-MemifConnector::~MemifConnector() { close(); }
-
-void MemifConnector::init() {
- /* initialize memory interface */
- int err = memif_init(controlFdUpdate, const_cast<char *>(app_name_.c_str()),
- nullptr, nullptr, nullptr);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_init: " << memif_strerror(err);
- }
-}
-
-void MemifConnector::connect(uint32_t memif_id, long memif_mode) {
- state_ = State::CONNECTING;
-
- memif_id_ = memif_id;
- socket_filename_ = "/run/vpp/memif.sock";
-
- createMemif(memif_id, memif_mode, nullptr);
-
- while (state_ != State::CONNECTED) {
- MemifConnector::main_event_reactor_.runOneEvent();
- }
-
- int err;
-
- /* get interrupt queue id */
- int fd = -1;
- err = memif_get_queue_efd(memif_connection_->conn, 0, &fd);
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_get_queue_efd: " << memif_strerror(err);
- return;
- }
-
- // Remove fd from main epoll
- main_event_reactor_.delFileDescriptor(fd);
-
- // Add fd to epoll of instance
- event_reactor_.addFileDescriptor(
- fd, EPOLLIN, [this](const utils::Event &evt) -> int {
- return onInterrupt(memif_connection_->conn, this, 0);
- });
-
- memif_worker_ = std::make_unique<std::thread>(
- std::bind(&MemifConnector::threadMain, this));
-}
-
-int MemifConnector::createMemif(uint32_t index, uint8_t mode, char *s) {
- memif_connection_t *c = memif_connection_.get();
-
- /* setting memif connection arguments */
- memif_conn_args_t args;
- memset(&args, 0, sizeof(args));
-
- args.is_master = mode;
- args.log2_ring_size = MEMIF_LOG2_RING_SIZE;
- args.buffer_size = MEMIF_BUF_SIZE;
- args.num_s2m_rings = 1;
- args.num_m2s_rings = 1;
- strncpy((char *)args.interface_name, IF_NAME, strlen(IF_NAME) + 1);
- args.mode = memif_interface_mode_t::MEMIF_INTERFACE_MODE_IP;
-
- int err;
-
- err = memif_create_socket(&args.socket, socket_filename_.c_str(), nullptr);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- throw errors::RuntimeException(memif_strerror(err));
- }
-
- args.interface_id = index;
- /* last argument for memif_create (void * private_ctx) is used by user
- to identify connection. this context is returned with callbacks */
-
- /* default interrupt */
- if (s == nullptr) {
- err = memif_create(&c->conn, &args, onConnect, onDisconnect, onInterrupt,
- this);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- throw errors::RuntimeException(memif_strerror(err));
- }
- }
-
- c->index = (uint16_t)index;
- c->tx_qid = 0;
- /* alloc memif buffers */
- c->rx_buf_num = 0;
- c->rx_bufs = static_cast<memif_buffer_t *>(
- malloc(sizeof(memif_buffer_t) * MAX_MEMIF_BUFS));
- c->tx_buf_num = 0;
- c->tx_bufs = static_cast<memif_buffer_t *>(
- malloc(sizeof(memif_buffer_t) * MAX_MEMIF_BUFS));
-
- // memif_set_rx_mode (c->conn, MEMIF_RX_MODE_POLLING, 0);
-
- return 0;
-}
-
-int MemifConnector::deleteMemif() {
- memif_connection_t *c = memif_connection_.get();
-
- if (c->rx_bufs) {
- free(c->rx_bufs);
- }
-
- c->rx_bufs = nullptr;
- c->rx_buf_num = 0;
-
- if (c->tx_bufs) {
- free(c->tx_bufs);
- }
-
- c->tx_bufs = nullptr;
- c->tx_buf_num = 0;
-
- int err;
- /* disconenct then delete memif connection */
- err = memif_delete(&c->conn);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_delete: " << memif_strerror(err);
- }
-
- if (TRANSPORT_EXPECT_FALSE(c->conn != nullptr)) {
- LOG(ERROR) << "memif delete fail";
- }
-
- return 0;
-}
-
-int MemifConnector::controlFdUpdate(int fd, uint8_t events, void *private_ctx) {
- /* convert memif event definitions to epoll events */
- if (events & MEMIF_FD_EVENT_DEL) {
- return MemifConnector::main_event_reactor_.delFileDescriptor(fd);
- }
-
- uint32_t evt = 0;
-
- if (events & MEMIF_FD_EVENT_READ) {
- evt |= EPOLLIN;
- }
-
- if (events & MEMIF_FD_EVENT_WRITE) {
- evt |= EPOLLOUT;
- }
-
- if (events & MEMIF_FD_EVENT_MOD) {
- return MemifConnector::main_event_reactor_.modFileDescriptor(fd, evt);
- }
-
- return MemifConnector::main_event_reactor_.addFileDescriptor(
- fd, evt, [](const utils::Event &evt) -> int {
- uint32_t event = 0;
- int memif_err = 0;
-
- if (evt.events & EPOLLIN) {
- event |= MEMIF_FD_EVENT_READ;
- }
-
- if (evt.events & EPOLLOUT) {
- event |= MEMIF_FD_EVENT_WRITE;
- }
-
- if (evt.events & EPOLLERR) {
- event |= MEMIF_FD_EVENT_ERROR;
- }
-
- memif_err = memif_control_fd_handler(evt.data.fd, event);
-
- if (TRANSPORT_EXPECT_FALSE(memif_err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_control_fd_handler: "
- << memif_strerror(memif_err);
- }
-
- return 0;
- });
-}
-
-int MemifConnector::bufferAlloc(long n, uint16_t qid) {
- memif_connection_t *c = memif_connection_.get();
- int err;
- uint16_t r;
- /* set data pointer to shared memory and set buffer_len to shared mmeory
- * buffer len */
- err = memif_buffer_alloc(c->conn, qid, c->tx_bufs, n, &r, 2000);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_buffer_alloc: " << memif_strerror(err);
- return -1;
- }
-
- c->tx_buf_num += r;
- return r;
-}
-
-int MemifConnector::txBurst(uint16_t qid) {
- memif_connection_t *c = memif_connection_.get();
- int err;
- uint16_t r;
- /* inform peer memif interface about data in shared memory buffers */
- /* mark memif buffers as free */
- err = memif_tx_burst(c->conn, qid, c->tx_bufs, c->tx_buf_num, &r);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_tx_burst: " << memif_strerror(err);
- }
-
- // err = memif_refill_queue(c->conn, qid, r, 0);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_tx_burst: " << memif_strerror(err);
- c->tx_buf_num -= r;
- return -1;
- }
-
- c->tx_buf_num -= r;
- return 0;
-}
-
-void MemifConnector::sendCallback(const std::error_code &ec) {
- timer_set_ = false;
-
- if (TRANSPORT_EXPECT_TRUE(!ec && state_ == State::CONNECTED)) {
- doSend();
- }
-}
-
-void MemifConnector::processInputBuffer(std::uint16_t total_packets) {
- utils::MemBuf::Ptr ptr;
-
- for (; total_packets > 0; total_packets--) {
- if (input_buffer_.pop(ptr)) {
- receive_callback_(this, *ptr, std::make_error_code(std::errc(0)));
- }
- }
-}
-
-/* informs user about connected status. private_ctx is used by user to identify
- connection (multiple connections WIP) */
-int MemifConnector::onConnect(memif_conn_handle_t conn, void *private_ctx) {
- MemifConnector *connector = (MemifConnector *)private_ctx;
- connector->state_ = State::CONNECTED;
- memif_refill_queue(conn, 0, -1, 0);
-
- return 0;
-}
-
-/* informs user about disconnected status. private_ctx is used by user to
- identify connection (multiple connections WIP) */
-int MemifConnector::onDisconnect(memif_conn_handle_t conn, void *private_ctx) {
- MemifConnector *connector = (MemifConnector *)private_ctx;
- connector->state_ = State::CLOSED;
- return 0;
-}
-
-void MemifConnector::threadMain() { event_reactor_.runEventLoop(1000); }
-
-int MemifConnector::onInterrupt(memif_conn_handle_t conn, void *private_ctx,
- uint16_t qid) {
- MemifConnector *connector = (MemifConnector *)private_ctx;
-
- memif_connection_t *c = connector->memif_connection_.get();
- int err = MEMIF_ERR_SUCCESS, ret_val;
- uint16_t total_packets = 0;
- uint16_t rx;
-
- do {
- err = memif_rx_burst(conn, qid, c->rx_bufs, MAX_MEMIF_BUFS, &rx);
- ret_val = err;
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS &&
- err != MEMIF_ERR_NOBUF)) {
- LOG(ERROR) << "memif_rx_burst: " << memif_strerror(err);
- goto error;
- }
-
- c->rx_buf_num += rx;
-
- if (TRANSPORT_EXPECT_FALSE(connector->io_service_.stopped())) {
- LOG(ERROR) << "socket stopped: ignoring " << rx << " packets";
- goto error;
- }
-
- std::size_t packet_length;
- for (int i = 0; i < rx; i++) {
- auto buffer = connector->getRawBuffer();
- packet_length = (c->rx_bufs + i)->len;
- std::memcpy(buffer.first, (c->rx_bufs + i)->data, packet_length);
- auto packet = connector->getPacketFromBuffer(buffer.first, packet_length);
-
- if (!connector->input_buffer_.push(std::move(packet))) {
- LOG(ERROR) << "Error pushing packet. Ring buffer full.";
-
- // TODO Here we should consider the possibility to signal the congestion
- // to the application, that would react properly (e.g. slow down
- // message)
- }
- }
-
- /* mark memif buffers and shared memory buffers as free */
- /* free processed buffers */
-
- err = memif_refill_queue(conn, qid, rx, 0);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_buffer_free: " << memif_strerror(err);
- }
-
- c->rx_buf_num -= rx;
- total_packets += rx;
-
- } while (ret_val == MEMIF_ERR_NOBUF);
-
- connector->io_service_.post(
- std::bind(&MemifConnector::processInputBuffer, connector, total_packets));
-
- return 0;
-
-error:
- err = memif_refill_queue(c->conn, qid, rx, 0);
-
- if (TRANSPORT_EXPECT_FALSE(err != MEMIF_ERR_SUCCESS)) {
- LOG(ERROR) << "memif_buffer_free: " << memif_strerror(err);
- }
- c->rx_buf_num -= rx;
-
- return 0;
-}
-
-void MemifConnector::close() {
- if (state_ != State::CLOSED) {
- disconnect_timer_->expiresFromNow(std::chrono::microseconds(50));
- disconnect_timer_->asyncWait([this](const std::error_code &ec) {
- deleteMemif();
- event_reactor_.stop();
- });
-
- if (memif_worker_ && memif_worker_->joinable()) {
- memif_worker_->join();
- }
- }
-}
-
-void MemifConnector::send(Packet &packet) {
- {
- utils::SpinLock::Acquire locked(write_msgs_lock_);
- output_buffer_.push_back(packet.shared_from_this());
- }
-#if CANCEL_TIMER
- if (!timer_set_) {
- timer_set_ = true;
- send_timer_->expiresFromNow(std::chrono::microseconds(50));
- send_timer_->asyncWait(
- std::bind(&MemifConnector::sendCallback, this, std::placeholders::_1));
- }
-#endif
-}
-
-int MemifConnector::doSend() {
- std::size_t max = 0;
- int32_t n = 0;
- std::size_t size = 0;
-
- {
- utils::SpinLock::Acquire locked(write_msgs_lock_);
- size = output_buffer_.size();
- }
-
- do {
- max = size < MAX_MEMIF_BUFS ? size : MAX_MEMIF_BUFS;
- n = bufferAlloc(max, memif_connection_->tx_qid);
-
- if (TRANSPORT_EXPECT_FALSE(n < 0)) {
- LOG(ERROR) << "Error allocating buffers.";
- return -1;
- }
-
- for (uint16_t i = 0; i < n; i++) {
- utils::SpinLock::Acquire locked(write_msgs_lock_);
-
- auto packet = output_buffer_.front().get();
- const utils::MemBuf *current = packet;
- std::size_t offset = 0;
- uint8_t *shared_buffer =
- reinterpret_cast<uint8_t *>(memif_connection_->tx_bufs[i].data);
- do {
- std::memcpy(shared_buffer + offset, current->data(), current->length());
- offset += current->length();
- current = current->next();
- } while (current != packet);
-
- memif_connection_->tx_bufs[i].len = uint32_t(offset);
-
- output_buffer_.pop_front();
- }
-
- txBurst(memif_connection_->tx_qid);
-
- utils::SpinLock::Acquire locked(write_msgs_lock_);
- size = output_buffer_.size();
- } while (size > 0);
-
- return 0;
-}
-
-void MemifConnector::send(const uint8_t *packet, std::size_t len) {
- throw errors::NotImplementedException();
-}
-
-} // end namespace core
-
-} // end namespace transport
diff --git a/libtransport/src/io_modules/memif/memif_vapi.c b/libtransport/src/io_modules/memif/memif_vapi.c
index b3da2b012..54e2c3134 100644
--- a/libtransport/src/io_modules/memif/memif_vapi.c
+++ b/libtransport/src/io_modules/memif/memif_vapi.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,8 +22,6 @@
#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,
vapi_payload_memif_details *reply) {
@@ -45,6 +43,9 @@ static vapi_error_e memif_details_cb(vapi_ctx_t ctx, void *callback_ctx,
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);
+
+ // Initialize memif id to 0
+ *memif_id = 0;
int ret = vapi_memif_dump(ctx, msg, memif_details_cb, memif_id);
vapi_unlock();
return ret;
diff --git a/libtransport/src/io_modules/memif/memif_vapi.h b/libtransport/src/io_modules/memif/memif_vapi.h
index bcf06ed43..f5f0639e7 100644
--- a/libtransport/src/io_modules/memif/memif_vapi.h
+++ b/libtransport/src/io_modules/memif/memif_vapi.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -44,6 +44,10 @@ typedef struct memif_output_params_s {
int memif_vapi_get_next_memif_id(vapi_ctx_t ctx, uint32_t *memif_id);
+int memif_vapi_create_socket(vapi_ctx_t ctx,
+ memif_create_params_t *input_params,
+ memif_output_params_t *output_params);
+
int memif_vapi_create_memif(vapi_ctx_t ctx, memif_create_params_t *input_params,
memif_output_params_t *output_params);
diff --git a/libtransport/src/io_modules/memif/vpp_forwarder_module.cc b/libtransport/src/io_modules/memif/vpp_forwarder_module.cc
index 44c8376df..d04c60893 100644
--- a/libtransport/src/io_modules/memif/vpp_forwarder_module.cc
+++ b/libtransport/src/io_modules/memif/vpp_forwarder_module.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2023 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,16 +13,16 @@
* limitations under the License.
*/
+#include <core/memif_connector.h>
#include <glog/logging.h>
#include <hicn/transport/config.h>
#include <hicn/transport/errors/not_implemented_exception.h>
#include <io_modules/memif/hicn_vapi.h>
-#include <io_modules/memif/memif_connector.h>
#include <io_modules/memif/memif_vapi.h>
#include <io_modules/memif/vpp_forwarder_module.h>
extern "C" {
-#include <memif/libmemif.h>
+#include <libmemif.h>
};
typedef enum { MASTER = 0, SLAVE = 1 } memif_role_t;
@@ -39,21 +39,25 @@ namespace core {
VPPForwarderModule::VPPForwarderModule()
: IoModule(),
connector_(nullptr),
+ memif_id_(0),
sw_if_index_(~0),
face_id1_(~0),
face_id2_(~0),
is_consumer_(false) {}
-VPPForwarderModule::~VPPForwarderModule() { delete connector_; }
+VPPForwarderModule::~VPPForwarderModule() {}
void VPPForwarderModule::init(
Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
Connector::OnReconnectCallback &&reconnect_callback,
asio::io_service &io_service, const std::string &app_name) {
if (!connector_) {
- connector_ =
- new MemifConnector(std::move(receive_callback), 0, 0,
- std::move(reconnect_callback), io_service, app_name);
+ connector_ = std::make_unique<MemifConnector>(
+ std::move(receive_callback), std::move(sent_callback),
+ std::move(close_callback), std::move(reconnect_callback), io_service,
+ app_name);
}
}
@@ -62,7 +66,7 @@ void VPPForwarderModule::processControlMessageReply(
throw errors::NotImplementedException();
}
-bool VPPForwarderModule::isControlMessage(const uint8_t *message) {
+bool VPPForwarderModule::isControlMessage(utils::MemBuf &packet_buffer) {
return false;
}
@@ -73,12 +77,12 @@ void VPPForwarderModule::send(Packet &packet) {
connector_->send(packet);
}
-void VPPForwarderModule::send(const uint8_t *packet, std::size_t len) {
+void VPPForwarderModule::send(const utils::MemBuf::Ptr &buffer) {
counters_.tx_packets++;
- counters_.tx_bytes += len;
+ counters_.tx_bytes += buffer->length();
// Perfect forwarding
- connector_->send(packet, len);
+ connector_->send(buffer);
}
std::uint32_t VPPForwarderModule::getMtu() { return interface_mtu; }
@@ -120,8 +124,8 @@ uint32_t VPPForwarderModule::getMemifConfiguration() {
void VPPForwarderModule::consumerConnection() {
hicn_consumer_input_params input = {0};
hicn_consumer_output_params output = {0};
- ip_address_t ip4_address;
- ip_address_t ip6_address;
+ hicn_ip_address_t ip4_address;
+ hicn_ip_address_t ip6_address;
output.src4 = &ip4_address;
output.src6 = &ip6_address;
@@ -153,7 +157,8 @@ void VPPForwarderModule::connect(bool is_consumer) {
vapi_error_e ret = vapi_connect_safe(&sock_, 0);
while (ret != VAPI_OK && retry > 0) {
- LOG(ERROR) << "Error connecting to VPP through vapi. Retrying..";
+ LOG(ERROR) << "Error connecting to VPP through vapi (error: " << ret
+ << "). Retrying..";
--retry;
ret = vapi_connect_safe(&sock_, 0);
}
@@ -170,16 +175,17 @@ void VPPForwarderModule::connect(bool is_consumer) {
consumerConnection();
}
- connector_->connect(memif_id_, 0);
+ connector_->connect(memif_id_, 0 /* is_master = false */,
+ memif_socket_filename);
connector_->setRole(is_consumer_ ? Connector::Role::CONSUMER
: Connector::Role::PRODUCER);
}
void VPPForwarderModule::registerRoute(const Prefix &prefix) {
- const ip_prefix_t &addr = prefix.toIpPrefixStruct();
+ const hicn_ip_prefix_t &addr = prefix.toIpPrefixStruct();
- ip_prefix_t producer_prefix;
- ip_address_t producer_locator;
+ hicn_ip_prefix_t producer_prefix;
+ hicn_ip_address_t producer_locator;
if (face_id1_ == uint32_t(~0)) {
hicn_producer_input_params input;
@@ -207,7 +213,8 @@ void VPPForwarderModule::registerRoute(const Prefix &prefix) {
throw errors::RuntimeException(hicn_vapi_get_error_string(ret));
}
- inet6_address_ = *output.prod_addr;
+ std::memcpy(inet6_address_.v6.as_u8, output.prod_addr->v6.as_u8,
+ sizeof(inet6_address_));
face_id1_ = output.face_id;
} else {
@@ -228,8 +235,6 @@ void VPPForwarderModule::registerRoute(const Prefix &prefix) {
void VPPForwarderModule::closeConnection() {
if (VPPForwarderModule::sock_) {
- connector_->close();
-
if (is_consumer_) {
hicn_del_face_app_input_params params;
params.face_id = face_id1_;
@@ -242,6 +247,8 @@ void VPPForwarderModule::closeConnection() {
hicn_vapi_face_prod_del(VPPForwarderModule::sock_, &params);
}
+ connector_->close();
+
if (sw_if_index_ != uint32_t(~0)) {
int ret =
memif_vapi_delete_memif(VPPForwarderModule::sock_, sw_if_index_);
@@ -249,7 +256,6 @@ void VPPForwarderModule::closeConnection() {
LOG(ERROR) << "Error deleting memif with sw idx " << sw_if_index_;
}
}
-
vapi_disconnect_safe();
VPPForwarderModule::sock_ = nullptr;
}
diff --git a/libtransport/src/io_modules/memif/vpp_forwarder_module.h b/libtransport/src/io_modules/memif/vpp_forwarder_module.h
index 8c4114fed..5a5358078 100644
--- a/libtransport/src/io_modules/memif/vpp_forwarder_module.h
+++ b/libtransport/src/io_modules/memif/vpp_forwarder_module.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -32,7 +32,8 @@ namespace core {
class MemifConnector;
class VPPForwarderModule : public IoModule {
- static constexpr std::uint16_t interface_mtu = 1500;
+ static inline std::uint16_t interface_mtu = 1500;
+ static inline std::string const memif_socket_filename = "/run/vpp/memif.sock";
public:
VPPForwarderModule();
@@ -41,11 +42,13 @@ class VPPForwarderModule : public IoModule {
void connect(bool is_consumer) override;
void send(Packet &packet) override;
- void send(const uint8_t *packet, std::size_t len) override;
+ void send(const utils::MemBuf::Ptr &buffer) override;
bool isConnected() override;
void init(Connector::PacketReceivedCallback &&receive_callback,
+ Connector::PacketSentCallback &&sent_callback,
+ Connector::OnCloseCallback &&close_callback,
Connector::OnReconnectCallback &&reconnect_callback,
asio::io_service &io_service,
const std::string &app_name = "Libtransport") override;
@@ -54,7 +57,7 @@ class VPPForwarderModule : public IoModule {
std::uint32_t getMtu() override;
- bool isControlMessage(const uint8_t *message) override;
+ bool isControlMessage(utils::MemBuf &packet_buffer) override;
void processControlMessageReply(utils::MemBuf &packet_buffer) override;
@@ -66,7 +69,7 @@ class VPPForwarderModule : public IoModule {
void producerConnection();
private:
- MemifConnector *connector_;
+ std::shared_ptr<MemifConnector> connector_;
uint32_t memif_id_;
uint32_t sw_if_index_;
// A consumer socket in vpp has two faces (ipv4 and ipv6)
diff --git a/libtransport/src/io_modules/raw_socket/raw_socket_connector.cc b/libtransport/src/io_modules/raw_socket/raw_socket_connector.cc
deleted file mode 100644
index 62efdc3a5..000000000
--- a/libtransport/src/io_modules/raw_socket/raw_socket_connector.cc
+++ /dev/null
@@ -1,200 +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 <core/raw_socket_connector.h>
-#include <hicn/transport/utils/conversions.h>
-#include <net/if.h>
-#include <netdb.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-
-#define MY_DEST_MAC0 0x0a
-#define MY_DEST_MAC1 0x7b
-#define MY_DEST_MAC2 0x7c
-#define MY_DEST_MAC3 0x1c
-#define MY_DEST_MAC4 0x4a
-#define MY_DEST_MAC5 0x14
-
-namespace transport {
-
-namespace core {
-
-RawSocketConnector::RawSocketConnector(
- PacketReceivedCallback &&receive_callback,
- OnReconnect &&on_reconnect_callback, asio::io_service &io_service,
- std::string app_name)
- : Connector(std::move(receive_callback), std::move(on_reconnect_callback)),
- io_service_(io_service),
- socket_(io_service_, raw_protocol(PF_PACKET, SOCK_RAW)),
- // resolver_(io_service_),
- timer_(io_service_),
- read_msg_(packet_pool_.makePtr(nullptr)),
- data_available_(false),
- app_name_(app_name) {
- memset(&link_layer_address_, 0, sizeof(link_layer_address_));
-}
-
-RawSocketConnector::~RawSocketConnector() {}
-
-void RawSocketConnector::connect(const std::string &interface_name,
- const std::string &mac_address_str) {
- state_ = ConnectorState::CONNECTING;
- memset(&ethernet_header_, 0, sizeof(ethernet_header_));
- struct ifreq ifr;
- struct ifreq if_mac;
- uint8_t mac_address[6];
-
- utils::convertStringToMacAddress(mac_address_str, mac_address);
-
- // Get interface mac address
- int fd = static_cast<int>(socket_.native_handle());
-
- /* Get the index of the interface to send on */
- memset(&ifr, 0, sizeof(struct ifreq));
- strncpy(ifr.ifr_name, interface_name.c_str(), interface_name.size());
-
- // if (ioctl(fd, SIOCGIFINDEX, &if_idx) < 0) {
- // perror("SIOCGIFINDEX");
- // }
-
- /* Get the MAC address of the interface to send on */
- memset(&if_mac, 0, sizeof(struct ifreq));
- strncpy(if_mac.ifr_name, interface_name.c_str(), interface_name.size());
- if (ioctl(fd, SIOCGIFHWADDR, &if_mac) < 0) {
- perror("SIOCGIFHWADDR");
- throw errors::RuntimeException("Interface does not exist");
- }
-
- /* Ethernet header */
- for (int i = 0; i < 6; i++) {
- ethernet_header_.ether_shost[i] =
- ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[i];
- ethernet_header_.ether_dhost[i] = mac_address[i];
- }
-
- /* Ethertype field */
- ethernet_header_.ether_type = htons(ETH_P_IPV6);
-
- strcpy(ifr.ifr_name, interface_name.c_str());
-
- if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
- memcpy(link_layer_address_.sll_addr, ifr.ifr_hwaddr.sa_data, 6);
- }
-
- // memset(&ifr, 0, sizeof(ifr));
- // ioctl(fd, SIOCGIFFLAGS, &ifr);
- // ifr.ifr_flags |= IFF_PROMISC;
- // ioctl(fd, SIOCSIFFLAGS, &ifr);
-
- link_layer_address_.sll_family = AF_PACKET;
- link_layer_address_.sll_protocol = htons(ETH_P_ALL);
- link_layer_address_.sll_ifindex = if_nametoindex(interface_name.c_str());
- link_layer_address_.sll_hatype = 1;
- link_layer_address_.sll_halen = 6;
-
- // startConnectionTimer();
- doConnect();
- doRecvPacket();
-}
-
-void RawSocketConnector::send(const uint8_t *packet, std::size_t len,
- const PacketSentCallback &packet_sent) {
- if (packet_sent != 0) {
- socket_.async_send(
- asio::buffer(packet, len),
- [packet_sent](std::error_code ec, std::size_t /*length*/) {
- packet_sent();
- });
- } else {
- if (state_ == ConnectorState::CONNECTED) {
- socket_.send(asio::buffer(packet, len));
- }
- }
-}
-
-void RawSocketConnector::send(const Packet::MemBufPtr &packet) {
- io_service_.post([this, packet]() {
- bool write_in_progress = !output_buffer_.empty();
- output_buffer_.push_back(std::move(packet));
- if (TRANSPORT_EXPECT_TRUE(state_ == ConnectorState::CONNECTED)) {
- if (!write_in_progress) {
- doSendPacket();
- } else {
- // Tell the handle connect it has data to write
- data_available_ = true;
- }
- }
- });
-}
-
-void RawSocketConnector::close() {
- io_service_.post([this]() { socket_.close(); });
-}
-
-void RawSocketConnector::doSendPacket() {
- auto packet = output_buffer_.front().get();
- auto array = std::vector<asio::const_buffer>();
-
- const utils::MemBuf *current = packet;
- do {
- array.push_back(asio::const_buffer(current->data(), current->length()));
- current = current->next();
- } while (current != packet);
-
- socket_.async_send(
- std::move(array),
- [this /*, packet*/](std::error_code ec, std::size_t bytes_transferred) {
- if (TRANSPORT_EXPECT_TRUE(!ec)) {
- output_buffer_.pop_front();
- if (!output_buffer_.empty()) {
- doSendPacket();
- }
- } else {
- LOG(ERROR) << ec.value() << " " << ec.message();
- }
- });
-}
-
-void RawSocketConnector::doRecvPacket() {
- read_msg_ = getPacket();
- socket_.async_receive(
- asio::buffer(read_msg_->writableData(), packet_size),
- [this](std::error_code ec, std::size_t bytes_transferred) mutable {
- if (!ec) {
- // Ignore packets that are not for us
- uint8_t *dst_mac_address = const_cast<uint8_t *>(read_msg_->data());
- if (!std::memcmp(dst_mac_address, ethernet_header_.ether_shost,
- ETHER_ADDR_LEN)) {
- read_msg_->append(bytes_transferred);
- read_msg_->trimStart(sizeof(struct ether_header));
- receive_callback_(std::move(read_msg_));
- }
- } else {
- LOG(ERROR) << ec.value() << " " << ec.message();
- }
- doRecvPacket();
- });
-}
-
-void RawSocketConnector::doConnect() {
- state_ = ConnectorState::CONNECTED;
- socket_.bind(raw_endpoint(&link_layer_address_, sizeof(link_layer_address_)));
-}
-
-} // end namespace core
-
-} // end namespace transport
diff --git a/libtransport/src/io_modules/raw_socket/raw_socket_connector.h b/libtransport/src/io_modules/raw_socket/raw_socket_connector.h
deleted file mode 100644
index 06892b3d8..000000000
--- a/libtransport/src/io_modules/raw_socket/raw_socket_connector.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 <core/connector.h>
-#include <hicn/transport/config.h>
-#include <hicn/transport/core/asio_wrapper.h>
-#include <hicn/transport/core/name.h>
-#include <linux/if_packet.h>
-#include <net/ethernet.h>
-#include <sys/socket.h>
-
-#include <deque>
-
-namespace transport {
-
-namespace core {
-
-using asio::generic::raw_protocol;
-using raw_endpoint = asio::generic::basic_endpoint<raw_protocol>;
-
-class RawSocketConnector : public Connector {
- public:
- RawSocketConnector(PacketReceivedCallback &&receive_callback,
- OnReconnect &&reconnect_callback,
- asio::io_service &io_service,
- std::string app_name = "Libtransport");
-
- ~RawSocketConnector() override;
-
- void send(const Packet::MemBufPtr &packet) override;
-
- void send(const uint8_t *packet, std::size_t len,
- const PacketSentCallback &packet_sent = 0) override;
-
- void close() override;
-
- void connect(const std::string &interface_name,
- const std::string &mac_address_str);
-
- private:
- void doConnect();
-
- void doRecvPacket();
-
- void doSendPacket();
-
- private:
- asio::io_service &io_service_;
- raw_protocol::socket socket_;
-
- struct ether_header ethernet_header_;
-
- struct sockaddr_ll link_layer_address_;
-
- asio::steady_timer timer_;
-
- utils::ObjectPool<utils::MemBuf>::Ptr read_msg_;
-
- bool data_available_;
- std::string app_name_;
-};
-
-} // end namespace core
-
-} // end namespace transport
diff --git a/libtransport/src/io_modules/raw_socket/raw_socket_interface.cc b/libtransport/src/io_modules/raw_socket/raw_socket_interface.cc
deleted file mode 100644
index dcf489f59..000000000
--- a/libtransport/src/io_modules/raw_socket/raw_socket_interface.cc
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <core/raw_socket_interface.h>
-#include <hicn/transport/utils/linux.h>
-
-#include <fstream>
-
-namespace transport {
-
-namespace core {
-
-static std::string config_folder_path = "/etc/transport/interface.conf.d";
-
-RawSocketInterface::RawSocketInterface(RawSocketConnector &connector)
- : ForwarderInterface<RawSocketInterface, RawSocketConnector>(connector) {}
-
-RawSocketInterface::~RawSocketInterface() {}
-
-void RawSocketInterface::connect(bool is_consumer) {
- std::string complete_filename =
- config_folder_path + std::string("/") + output_interface_;
-
- std::ifstream is(complete_filename);
- std::string interface;
-
- if (is) {
- is >> remote_mac_address_;
- }
-
- // Get interface ip address
- struct sockaddr_in6 address = {0};
- utils::retrieveInterfaceAddress(output_interface_, &address);
-
- std::memcpy(&inet6_address_.v6.as_u8, &address.sin6_addr,
- sizeof(address.sin6_addr));
- connector_.connect(output_interface_, remote_mac_address_);
-}
-
-void RawSocketInterface::registerRoute(Prefix &prefix) { return; }
-
-} // namespace core
-
-} // namespace transport
diff --git a/libtransport/src/io_modules/raw_socket/raw_socket_interface.h b/libtransport/src/io_modules/raw_socket/raw_socket_interface.h
deleted file mode 100644
index 7036cac7e..000000000
--- a/libtransport/src/io_modules/raw_socket/raw_socket_interface.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <core/forwarder_interface.h>
-#include <core/raw_socket_connector.h>
-#include <hicn/transport/core/prefix.h>
-
-#include <atomic>
-#include <deque>
-
-namespace transport {
-
-namespace core {
-
-class RawSocketInterface
- : public ForwarderInterface<RawSocketInterface, RawSocketConnector> {
- public:
- typedef RawSocketConnector ConnectorType;
-
- RawSocketInterface(RawSocketConnector &connector);
-
- ~RawSocketInterface();
-
- void connect(bool is_consumer);
-
- void registerRoute(Prefix &prefix);
-
- std::uint16_t getMtu() { return interface_mtu; }
-
- TRANSPORT_ALWAYS_INLINE static bool isControlMessageImpl(
- const uint8_t *message) {
- return false;
- }
-
- TRANSPORT_ALWAYS_INLINE void processControlMessageReplyImpl(
- Packet::MemBufPtr &&packet_buffer) {}
-
- TRANSPORT_ALWAYS_INLINE void closeConnection(){};
-
- private:
- static constexpr std::uint16_t interface_mtu = 1500;
- std::string remote_mac_address_;
-};
-
-} // namespace core
-
-} // namespace transport
diff --git a/libtransport/src/io_modules/udp/CMakeLists.txt b/libtransport/src/io_modules/udp/CMakeLists.txt
deleted file mode 100644
index b9c19d063..000000000
--- a/libtransport/src/io_modules/udp/CMakeLists.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-list(APPEND MODULE_HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_forwarder_module.h
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_socket_connector.h
-)
-
-list(APPEND MODULE_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/hicn_forwarder_module.cc
- ${CMAKE_CURRENT_SOURCE_DIR}/udp_socket_connector.cc
-)
-
-build_module(hicnlight_module
- SHARED
- SOURCES ${MODULE_SOURCE_FILES}
- DEPENDS ${DEPENDENCIES}
- COMPONENT ${LIBTRANSPORT_COMPONENT}
- INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIRS} ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- COMPILE_OPTIONS ${COMPILE_FLAGS}
-)
diff --git a/libtransport/src/io_modules/udp/hicn_forwarder_module.cc b/libtransport/src/io_modules/udp/hicn_forwarder_module.cc
deleted file mode 100644
index ba08dd8c0..000000000
--- a/libtransport/src/io_modules/udp/hicn_forwarder_module.cc
+++ /dev/null
@@ -1,181 +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 <io_modules/udp/hicn_forwarder_module.h>
-#include <io_modules/udp/udp_socket_connector.h>
-
-union AddressLight {
- uint32_t ipv4;
- struct in6_addr ipv6;
-};
-
-typedef struct {
- uint8_t message_type;
- uint8_t command_id;
- uint16_t length;
- uint32_t seq_num;
-} CommandHeader;
-
-typedef struct {
- uint8_t message_type;
- uint8_t command_id;
- uint16_t length;
- uint32_t seq_num;
- char symbolic_or_connid[16];
- union AddressLight address;
- uint16_t cost;
- uint8_t address_type;
- uint8_t len;
-} RouteToSelfCommand;
-
-typedef struct {
- uint8_t message_type;
- uint8_t command_id;
- uint16_t length;
- uint32_t seq_num;
- char symbolic_or_connid[16];
-} DeleteSelfConnectionCommand;
-
-namespace {
-static constexpr uint8_t addr_inet = 1;
-static constexpr uint8_t addr_inet6 = 2;
-static constexpr uint8_t add_route_command = 3;
-static constexpr uint8_t delete_connection_command = 5;
-static constexpr uint8_t request_light = 0xc0;
-static constexpr char identifier[] = "SELF";
-
-void fillCommandHeader(CommandHeader *header) {
- // Allocate and fill the header
- header->message_type = request_light;
- header->length = 1;
-}
-
-RouteToSelfCommand createCommandRoute(std::unique_ptr<sockaddr> &&addr,
- uint8_t prefix_length) {
- RouteToSelfCommand command = {0};
-
- // check and set IP address
- if (addr->sa_family == AF_INET) {
- command.address_type = addr_inet;
- command.address.ipv4 = ((sockaddr_in *)addr.get())->sin_addr.s_addr;
- } else if (addr->sa_family == AF_INET6) {
- command.address_type = addr_inet6;
- command.address.ipv6 = ((sockaddr_in6 *)addr.get())->sin6_addr;
- }
-
- // Fill remaining payload fields
-#ifndef _WIN32
- strcpy(command.symbolic_or_connid, identifier);
-#else
- strcpy_s(command.symbolic_or_connid, 16, identifier);
-#endif
- command.cost = 1;
- command.len = (uint8_t)prefix_length;
-
- // Allocate and fill the header
- command.command_id = add_route_command;
- fillCommandHeader((CommandHeader *)&command);
-
- return command;
-}
-
-DeleteSelfConnectionCommand createCommandDeleteConnection() {
- DeleteSelfConnectionCommand command = {0};
- fillCommandHeader((CommandHeader *)&command);
- command.command_id = delete_connection_command;
-
-#ifndef _WIN32
- strcpy(command.symbolic_or_connid, identifier);
-#else
- strcpy_s(command.symbolic_or_connid, 16, identifier);
-#endif
-
- return command;
-}
-
-} // namespace
-
-namespace transport {
-
-namespace core {
-
-HicnForwarderModule::HicnForwarderModule() : IoModule(), connector_(nullptr) {}
-
-HicnForwarderModule::~HicnForwarderModule() {}
-
-void HicnForwarderModule::connect(bool is_consumer) {
- connector_->connect();
- connector_->setRole(is_consumer ? Connector::Role::CONSUMER
- : Connector::Role::PRODUCER);
-}
-
-bool HicnForwarderModule::isConnected() { return connector_->isConnected(); }
-
-void HicnForwarderModule::send(Packet &packet) {
- IoModule::send(packet);
- packet.setChecksum();
- connector_->send(packet);
-}
-
-void HicnForwarderModule::send(const uint8_t *packet, std::size_t len) {
- counters_.tx_packets++;
- counters_.tx_bytes += len;
-
- // Perfect forwarding
- connector_->send(packet, len);
-}
-
-void HicnForwarderModule::registerRoute(const Prefix &prefix) {
- auto command = createCommandRoute(prefix.toSockaddr(),
- (uint8_t)prefix.getPrefixLength());
- send((uint8_t *)&command, sizeof(RouteToSelfCommand));
-}
-
-void HicnForwarderModule::closeConnection() {
- auto command = createCommandDeleteConnection();
- send((uint8_t *)&command, sizeof(DeleteSelfConnectionCommand));
- connector_->close();
-}
-
-void HicnForwarderModule::init(
- Connector::PacketReceivedCallback &&receive_callback,
- Connector::OnReconnectCallback &&reconnect_callback,
- asio::io_service &io_service, const std::string &app_name) {
- if (!connector_) {
- connector_ = new UdpSocketConnector(std::move(receive_callback), nullptr,
- nullptr, std::move(reconnect_callback),
- io_service, app_name);
- }
-}
-
-void HicnForwarderModule::processControlMessageReply(
- utils::MemBuf &packet_buffer) {
- if (packet_buffer.data()[0] == nack_code) {
- throw errors::RuntimeException(
- "Received Nack message from hicn light forwarder.");
- }
-}
-
-std::uint32_t HicnForwarderModule::getMtu() { return interface_mtu; }
-
-bool HicnForwarderModule::isControlMessage(const uint8_t *message) {
- return message[0] == ack_code || message[0] == nack_code;
-}
-
-extern "C" IoModule *create_module(void) { return new HicnForwarderModule(); }
-
-} // namespace core
-
-} // namespace transport
diff --git a/libtransport/src/io_modules/udp/hicn_forwarder_module.h b/libtransport/src/io_modules/udp/hicn_forwarder_module.h
deleted file mode 100644
index 845db73bf..000000000
--- a/libtransport/src/io_modules/udp/hicn_forwarder_module.h
+++ /dev/null
@@ -1,86 +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/core/io_module.h>
-#include <hicn/transport/core/prefix.h>
-
-namespace transport {
-
-namespace core {
-
-class UdpSocketConnector;
-
-class HicnForwarderModule : public IoModule {
- static constexpr uint8_t ack_code = 0xc2;
- static constexpr uint8_t nack_code = 0xc3;
- static constexpr std::uint16_t interface_mtu = 1500;
-
- public:
- union addressLight {
- uint32_t ipv4;
- struct in6_addr ipv6;
- };
-
- struct route_to_self_command {
- uint8_t messageType;
- uint8_t commandID;
- uint16_t length;
- uint32_t seqNum;
- char symbolicOrConnid[16];
- union addressLight address;
- uint16_t cost;
- uint8_t addressType;
- uint8_t len;
- };
-
- using route_to_self_command = struct route_to_self_command;
-
- HicnForwarderModule();
-
- ~HicnForwarderModule();
-
- void connect(bool is_consumer) override;
-
- void send(Packet &packet) override;
- void send(const uint8_t *packet, std::size_t len) override;
-
- bool isConnected() override;
-
- void init(Connector::PacketReceivedCallback &&receive_callback,
- Connector::OnReconnectCallback &&reconnect_callback,
- asio::io_service &io_service,
- const std::string &app_name = "Libtransport") override;
-
- void registerRoute(const Prefix &prefix) override;
-
- std::uint32_t getMtu() override;
-
- bool isControlMessage(const uint8_t *message) override;
-
- void processControlMessageReply(utils::MemBuf &packet_buffer) override;
-
- void closeConnection() override;
-
- private:
- UdpSocketConnector *connector_;
-};
-
-extern "C" IoModule *create_module(void);
-
-} // namespace core
-
-} // namespace transport
diff --git a/libtransport/src/io_modules/udp/udp_socket_connector.cc b/libtransport/src/io_modules/udp/udp_socket_connector.cc
deleted file mode 100644
index 1412d8c07..000000000
--- a/libtransport/src/io_modules/udp/udp_socket_connector.cc
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef _WIN32
-#include <hicn/transport/portability/win_portability.h>
-#endif
-
-#include <glog/logging.h>
-#include <hicn/transport/errors/errors.h>
-#include <hicn/transport/utils/object_pool.h>
-#include <io_modules/udp/udp_socket_connector.h>
-
-#include <thread>
-#include <vector>
-
-namespace transport {
-
-namespace core {
-
-UdpSocketConnector::UdpSocketConnector(
- PacketReceivedCallback &&receive_callback, PacketSentCallback &&packet_sent,
- OnCloseCallback &&close_callback, OnReconnectCallback &&on_reconnect,
- asio::io_service &io_service, std::string app_name)
- : Connector(std::move(receive_callback), std::move(packet_sent),
- std::move(close_callback), std::move(on_reconnect)),
- io_service_(io_service),
- socket_(io_service_),
- resolver_(io_service_),
- connection_timer_(io_service_),
- read_msg_(std::make_pair(nullptr, 0)),
- is_reconnection_(false),
- data_available_(false),
- app_name_(app_name) {}
-
-UdpSocketConnector::~UdpSocketConnector() {}
-
-void UdpSocketConnector::connect(std::string ip_address, std::string port) {
- endpoint_iterator_ = resolver_.resolve(
- {ip_address, port, asio::ip::resolver_query_base::numeric_service});
-
- state_ = Connector::State::CONNECTING;
- doConnect();
-}
-
-void UdpSocketConnector::send(const uint8_t *packet, std::size_t len) {
- socket_.async_send(asio::buffer(packet, len),
- [this](std::error_code ec, std::size_t /*length*/) {
- if (sent_callback_) {
- sent_callback_(this, ec);
- }
- });
-}
-
-void UdpSocketConnector::send(Packet &packet) {
- io_service_.post([this, _packet{packet.shared_from_this()}]() {
- bool write_in_progress = !output_buffer_.empty();
- output_buffer_.push_back(std::move(_packet));
- if (TRANSPORT_EXPECT_TRUE(state_ == Connector::State::CONNECTED)) {
- if (!write_in_progress) {
- doWrite();
- }
- } else {
- // Tell the handle connect it has data to write
- data_available_ = true;
- }
- });
-}
-
-void UdpSocketConnector::close() {
- if (io_service_.stopped()) {
- doClose();
- } else {
- io_service_.dispatch(std::bind(&UdpSocketConnector::doClose, this));
- }
-}
-
-void UdpSocketConnector::doClose() {
- if (state_ != Connector::State::CLOSED) {
- state_ = Connector::State::CLOSED;
- if (socket_.is_open()) {
- socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both);
- socket_.close();
- }
- }
-}
-
-void UdpSocketConnector::doWrite() {
- auto packet = output_buffer_.front().get();
- auto array = std::vector<asio::const_buffer>();
-
- const utils::MemBuf *current = packet;
- do {
- array.push_back(asio::const_buffer(current->data(), current->length()));
- current = current->next();
- } while (current != packet);
-
- socket_.async_send(std::move(array), [this](std::error_code ec,
- std::size_t length) {
- if (TRANSPORT_EXPECT_TRUE(!ec)) {
- output_buffer_.pop_front();
- if (!output_buffer_.empty()) {
- doWrite();
- }
- } else if (ec.value() == static_cast<int>(std::errc::operation_canceled)) {
- // The connection has been closed by the application.
- return;
- } else {
- LOG(ERROR) << ec.value() << " " << ec.message();
- tryReconnect();
- }
- });
-}
-
-void UdpSocketConnector::doRead() {
- read_msg_ = getRawBuffer();
- socket_.async_receive(
- asio::buffer(read_msg_.first, read_msg_.second),
- [this](std::error_code ec, std::size_t length) {
- if (TRANSPORT_EXPECT_TRUE(!ec)) {
- auto packet = getPacketFromBuffer(read_msg_.first, length);
- receive_callback_(this, *packet, std::make_error_code(std::errc(0)));
- doRead();
- } else if (ec.value() ==
- static_cast<int>(std::errc::operation_canceled)) {
- // The connection has been closed by the application.
- return;
- } else {
- LOG(ERROR) << ec.value() << " " << ec.message();
- tryReconnect();
- }
- });
-}
-
-void UdpSocketConnector::tryReconnect() {
- if (state_ == Connector::State::CONNECTED) {
- LOG(ERROR) << "Connection lost. Trying to reconnect...";
- state_ = Connector::State::CONNECTING;
- is_reconnection_ = true;
- io_service_.post([this]() {
- if (socket_.is_open()) {
- socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both);
- socket_.close();
- }
-
- doConnect();
- startConnectionTimer();
- std::this_thread::sleep_for(std::chrono::milliseconds(500));
- });
- }
-}
-
-void UdpSocketConnector::doConnect() {
- asio::async_connect(
- socket_, endpoint_iterator_,
- [this](std::error_code ec, udp::resolver::iterator) {
- if (!ec) {
- connection_timer_.cancel();
- state_ = Connector::State::CONNECTED;
- doRead();
-
- if (data_available_) {
- data_available_ = false;
- doWrite();
- }
-
- if (is_reconnection_) {
- is_reconnection_ = false;
- }
-
- on_reconnect_callback_(this);
- } else {
- doConnect();
- std::this_thread::sleep_for(std::chrono::milliseconds(500));
- }
- });
-}
-
-bool UdpSocketConnector::checkConnected() {
- return state_ == Connector::State::CONNECTED;
-}
-
-void UdpSocketConnector::startConnectionTimer() {
- connection_timer_.expires_from_now(std::chrono::seconds(60));
- connection_timer_.async_wait(std::bind(&UdpSocketConnector::handleDeadline,
- this, std::placeholders::_1));
-}
-
-void UdpSocketConnector::handleDeadline(const std::error_code &ec) {
- if (!ec) {
- io_service_.post([this]() {
- socket_.close();
- LOG(ERROR) << "Error connecting. Is the forwarder running?";
- });
- }
-}
-
-} // end namespace core
-
-} // end namespace transport
diff --git a/libtransport/src/io_modules/udp/udp_socket_connector.h b/libtransport/src/io_modules/udp/udp_socket_connector.h
deleted file mode 100644
index c483e14aa..000000000
--- a/libtransport/src/io_modules/udp/udp_socket_connector.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <hicn/transport/config.h>
-#include <hicn/transport/core/asio_wrapper.h>
-#include <hicn/transport/core/connector.h>
-#include <hicn/transport/core/content_object.h>
-#include <hicn/transport/core/global_object_pool.h>
-#include <hicn/transport/core/interest.h>
-#include <hicn/transport/core/name.h>
-#include <hicn/transport/core/packet.h>
-#include <hicn/transport/utils/branch_prediction.h>
-
-#include <deque>
-
-namespace transport {
-namespace core {
-
-using asio::ip::udp;
-
-class UdpSocketConnector : public Connector {
- public:
- UdpSocketConnector(PacketReceivedCallback &&receive_callback,
- PacketSentCallback &&packet_sent,
- OnCloseCallback &&close_callback,
- OnReconnectCallback &&on_reconnect,
- asio::io_service &io_service,
- std::string app_name = "Libtransport");
-
- ~UdpSocketConnector() override;
-
- void send(Packet &packet) override;
-
- void send(const uint8_t *packet, std::size_t len) override;
-
- void close() override;
-
- void connect(std::string ip_address = "127.0.0.1", std::string port = "9695");
-
- private:
- void doConnect();
-
- void doRead();
-
- void doWrite();
-
- void doClose();
-
- bool checkConnected();
-
- private:
- void handleDeadline(const std::error_code &ec);
-
- void startConnectionTimer();
-
- void tryReconnect();
-
- asio::io_service &io_service_;
- asio::ip::udp::socket socket_;
- asio::ip::udp::resolver resolver_;
- asio::ip::udp::resolver::iterator endpoint_iterator_;
- asio::steady_timer connection_timer_;
-
- std::pair<uint8_t *, std::size_t> read_msg_;
-
- bool is_reconnection_;
- bool data_available_;
-
- std::string app_name_;
-};
-
-} // end namespace core
-
-} // end namespace transport
diff --git a/libtransport/src/libhicntransport-config.cmake.in b/libtransport/src/libhicntransport-config.cmake.in
new file mode 100644
index 000000000..9b8c51962
--- /dev/null
+++ b/libtransport/src/libhicntransport-config.cmake.in
@@ -0,0 +1,8 @@
+@PACKAGE_INIT@
+
+set(Libhicntransport_VERSION_MAJOR "@VERSION_MAJOR@")
+set(Libhicntransport_VERSION_MINOR "@VERSION_MINOR@")
+set(Libhicntransport_VERSION_PATCH "@VERSION_PATCH@")
+
+set_and_check(Libhicntransport_INCLUDE_DIRS "@PACKAGE_Libhicntransport_INCLUDE_DIRS@")
+include("${CMAKE_CURRENT_LIST_DIR}/libhicntransport-targets.cmake")
diff --git a/libtransport/src/protocols/CMakeLists.txt b/libtransport/src/protocols/CMakeLists.txt
index b763e95e2..51879a9ed 100644
--- a/libtransport/src/protocols/CMakeLists.txt
+++ b/libtransport/src/protocols/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -52,9 +52,15 @@ list(APPEND SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/errors.cc
)
-set(RAAQM_CONFIG_INSTALL_PREFIX
- ${CMAKE_INSTALL_FULL_SYSCONFDIR}/hicn
-)
+if (${CMAKE_SYSTEM_NAME} MATCHES Darwin OR ${CMAKE_SYSTEM_NAME} MATCHES Linux)
+ set(RAAQM_CONFIG_INSTALL_PREFIX
+ ${CMAKE_INSTALL_FULL_SYSCONFDIR}/hicn
+ )
+else()
+ set(RAAQM_CONFIG_INSTALL_PREFIX
+ ${CMAKE_INSTALL_PREFIX}/etc/hicn
+ )
+endif()
set(raaqm_config_path
${RAAQM_CONFIG_INSTALL_PREFIX}/consumer.conf
@@ -67,7 +73,7 @@ set(TRANSPORT_CONFIG
install(
FILES ${TRANSPORT_CONFIG}
- DESTINATION ${CMAKE_INSTALL_FULL_SYSCONFDIR}/hicn
+ DESTINATION ${RAAQM_CONFIG_INSTALL_PREFIX}
COMPONENT ${LIBTRANSPORT_COMPONENT}
)
diff --git a/libtransport/src/protocols/byte_stream_reassembly.cc b/libtransport/src/protocols/byte_stream_reassembly.cc
index ac36d4e61..b9eaf3bec 100644
--- a/libtransport/src/protocols/byte_stream_reassembly.cc
+++ b/libtransport/src/protocols/byte_stream_reassembly.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -36,15 +36,6 @@ ByteStreamReassembly::ByteStreamReassembly(
index_(Indexer::invalid_index),
download_complete_(false) {}
-void ByteStreamReassembly::reassemble(
- std::unique_ptr<ContentObjectManifest> &&manifest) {
- if (TRANSPORT_EXPECT_TRUE(manifest != nullptr) && read_buffer_->capacity()) {
- received_packets_.emplace(
- std::make_pair(manifest->getName().getSuffix(), nullptr));
- assembleContent();
- }
-}
-
void ByteStreamReassembly::reassemble(ContentObject &content_object) {
if (TRANSPORT_EXPECT_TRUE(read_buffer_->capacity())) {
received_packets_.emplace(
diff --git a/libtransport/src/protocols/byte_stream_reassembly.h b/libtransport/src/protocols/byte_stream_reassembly.h
index 278740bd3..a1f965d5c 100644
--- a/libtransport/src/protocols/byte_stream_reassembly.h
+++ b/libtransport/src/protocols/byte_stream_reassembly.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,9 +29,6 @@ class ByteStreamReassembly : public Reassembly {
protected:
void reassemble(core::ContentObject &content_object) override;
- void reassemble(
- std::unique_ptr<core::ContentObjectManifest> &&manifest) override;
-
void reassemble(utils::MemBuf &buffer, uint32_t suffix) override;
bool copyContent(core::ContentObject &content_object);
diff --git a/libtransport/src/protocols/cbr.cc b/libtransport/src/protocols/cbr.cc
index 1548cc68d..e3f0f1336 100644
--- a/libtransport/src/protocols/cbr.cc
+++ b/libtransport/src/protocols/cbr.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -37,11 +37,11 @@ void CbrTransportProtocol::afterDataUnsatisfied(uint64_t segment) {}
void CbrTransportProtocol::afterContentReception(
const Interest &interest, const ContentObject &content_object) {
auto segment = content_object.getName().getSuffix();
- auto now = utils::SteadyClock::now();
- auto rtt = std::chrono::duration_cast<utils::Microseconds>(
- now - interest_timepoints_[segment & mask]);
+ auto now = utils::SteadyTime::Clock::now();
+ auto rtt = utils::SteadyTime::getDurationUs(
+ interest_timepoints_[segment & mask], now);
// Update stats
- updateStats(segment, rtt.count(), now);
+ updateStats(segment, rtt, now);
}
} // end namespace protocol
diff --git a/libtransport/src/protocols/cbr.h b/libtransport/src/protocols/cbr.h
index 41cdbc98c..c178dbf60 100644
--- a/libtransport/src/protocols/cbr.h
+++ b/libtransport/src/protocols/cbr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/congestion_window_protocol.h b/libtransport/src/protocols/congestion_window_protocol.h
index 36ac6eb17..f9ff208cc 100644
--- a/libtransport/src/protocols/congestion_window_protocol.h
+++ b/libtransport/src/protocols/congestion_window_protocol.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/data_processing_events.h b/libtransport/src/protocols/data_processing_events.h
index 28732502b..182de3ed8 100644
--- a/libtransport/src/protocols/data_processing_events.h
+++ b/libtransport/src/protocols/data_processing_events.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/datagram_reassembly.cc b/libtransport/src/protocols/datagram_reassembly.cc
index 069873a52..a04b0eecf 100644
--- a/libtransport/src/protocols/datagram_reassembly.cc
+++ b/libtransport/src/protocols/datagram_reassembly.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,8 +29,9 @@ void DatagramReassembly::reassemble(core::ContentObject& content_object) {
auto read_buffer = content_object.getPayload();
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "Size of payload: " << read_buffer->length() << ". Trimming "
- << transport_protocol_->transportHeaderLength();
- read_buffer->trimStart(transport_protocol_->transportHeaderLength());
+ << transport_protocol_->transportHeaderLength(false);
+ // here we have only src data packet
+ read_buffer->trimStart(transport_protocol_->transportHeaderLength(false));
Reassembly::read_buffer_ = std::move(read_buffer);
Reassembly::notifyApplication();
}
diff --git a/libtransport/src/protocols/datagram_reassembly.h b/libtransport/src/protocols/datagram_reassembly.h
index de294df06..cefdca93b 100644
--- a/libtransport/src/protocols/datagram_reassembly.h
+++ b/libtransport/src/protocols/datagram_reassembly.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,10 +29,6 @@ class DatagramReassembly : public Reassembly {
virtual void reassemble(core::ContentObject &content_object) override;
void reassemble(utils::MemBuf &buffer, uint32_t suffix) override;
virtual void reInitialize() override;
- virtual void reassemble(
- std::unique_ptr<core::ContentObjectManifest> &&manifest) override {
- return;
- }
bool reassembleUnverified() override { return true; }
};
diff --git a/libtransport/src/protocols/errors.cc b/libtransport/src/protocols/errors.cc
index 183fcc574..a7dd26e16 100644
--- a/libtransport/src/protocols/errors.cc
+++ b/libtransport/src/protocols/errors.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/errors.h b/libtransport/src/protocols/errors.h
index 58dadae5a..33d5fbee4 100644
--- a/libtransport/src/protocols/errors.h
+++ b/libtransport/src/protocols/errors.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/fec/CMakeLists.txt b/libtransport/src/protocols/fec/CMakeLists.txt
index 6d61ae043..8ae0a7360 100644
--- a/libtransport/src/protocols/fec/CMakeLists.txt
+++ b/libtransport/src/protocols/fec/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/fec/fec.cc b/libtransport/src/protocols/fec/fec.cc
index 16a04cb98..d2105eb53 100644
--- a/libtransport/src/protocols/fec/fec.cc
+++ b/libtransport/src/protocols/fec/fec.cc
@@ -44,6 +44,7 @@
#include "fec.h"
+#include <assert.h>
#include <hicn/transport/portability/platform.h>
#include <stdio.h>
#include <stdlib.h>
@@ -60,72 +61,6 @@
#endif
/*
- * compatibility stuff
- */
-#ifdef MSDOS /* but also for others, e.g. sun... */
-#define NEED_BCOPY
-#define bcmp(a, b, n) memcmp(a, b, n)
-#endif
-
-#ifdef ANDROID
-#define bcmp(a, b, n) memcmp(a, b, n)
-#endif
-
-#ifdef NEED_BCOPY
-#define bcopy(s, d, siz) memcpy((d), (s), (siz))
-#define bzero(d, siz) memset((d), '\0', (siz))
-#endif
-
-/*
- * stuff used for testing purposes only
- */
-
-#ifdef TEST
-#define DEB(x)
-#define DDB(x) x
-#define DEBUG 0 /* minimal debugging */
-#ifdef MSDOS
-#include <time.h>
-struct timeval {
- unsigned long ticks;
-};
-#define gettimeofday(x, dummy) \
- { (x)->ticks = clock(); }
-#define DIFF_T(a, b) (1 + 1000000 * (a.ticks - b.ticks) / CLOCKS_PER_SEC)
-typedef unsigned long u_long;
-typedef unsigned short u_short;
-#else /* typically, unix systems */
-#include <sys/time.h>
-#define DIFF_T(a, b) \
- (1 + 1000000 * (a.tv_sec - b.tv_sec) + (a.tv_usec - b.tv_usec))
-#endif
-
-#define TICK(t) \
- { \
- struct timeval x; \
- gettimeofday(&x, NULL); \
- t = x.tv_usec + 1000000 * (x.tv_sec & 0xff); \
- }
-#define TOCK(t) \
- { \
- u_long t1; \
- TICK(t1); \
- if (t1 < t) \
- t = 256000000 + t1 - t; \
- else \
- t = t1 - t; \
- if (t == 0) t = 1; \
- }
-
-u_long ticks[10]; /* vars for timekeeping */
-#else
-#define DEB(x)
-#define DDB(x)
-#define TICK(x)
-#define TOCK(x)
-#endif /* TEST */
-
-/*
* You should not need to change anything beyond this point.
* The first part of the file implements linear algebra in GF.
*
@@ -402,31 +337,17 @@ static void matmul(gf *a, gf *b, gf *c, int n, int k, int m) {
}
}
-#ifdef DEBUGG
-/*
- * returns 1 if the square matrix is identiy
- * (only for test)
- */
-static int is_identity(gf *m, int k) {
- int row, col;
- for (row = 0; row < k; row++)
- for (col = 0; col < k; col++)
- if ((row == col && *m != 1) || (row != col && *m != 0))
- return 0;
- else
- m++;
- return 1;
-}
-#endif /* debug */
-
/*
* invert_mat() takes a matrix and produces its inverse
* k is the size of the matrix.
* (Gauss-Jordan, adapted from Numerical Recipes in C)
* Return non-zero if singular.
*/
-DEB(int pivloops = 0; int pivswaps = 0; /* diagnostic */)
+int pivloops = 0;
+int pivswaps = 0; /* diagnostic */
static int invert_mat(gf *src, int k) {
+ assert(k > 0);
+
gf c, *p;
int irow, icol, row, col, i, ix;
@@ -436,9 +357,9 @@ static int invert_mat(gf *src, int k) {
int *ipiv = (int *)my_malloc(k * sizeof(int), "ipiv");
gf *id_row = NEW_GF_MATRIX(1, k);
gf *temp_row = NEW_GF_MATRIX(1, k);
-
- bzero(id_row, k * sizeof(gf));
- DEB(pivloops = 0; pivswaps = 0; /* diagnostic */)
+ memset(id_row, '\0', k * sizeof(gf));
+ pivloops = 0;
+ pivswaps = 0; /* diagnostic */
/*
* ipiv marks elements already used as pivots.
*/
@@ -459,7 +380,7 @@ static int invert_mat(gf *src, int k) {
for (row = 0; row < k; row++) {
if (ipiv[row] != 1) {
for (ix = 0; ix < k; ix++) {
- DEB(pivloops++;)
+ pivloops++;
if (ipiv[ix] == 0) {
if (src[row * k + ix] != 0) {
irow = row;
@@ -497,12 +418,9 @@ static int invert_mat(gf *src, int k) {
fprintf(stderr, "singular matrix 2\n");
goto fail;
}
- if (c != 1) { /* otherwhise this is a NOP */
- /*
- * this is done often , but optimizing is not so
- * fruitful, at least in the obvious ways (unrolling)
- */
- DEB(pivswaps++;)
+
+ if (c != 1) {
+ pivswaps++;
c = inverse[c];
pivot_row[icol] = 1;
for (ix = 0; ix < k; ix++) pivot_row[ix] = gf_mul(c, pivot_row[ix]);
@@ -515,7 +433,7 @@ static int invert_mat(gf *src, int k) {
* we can optimize the addmul).
*/
id_row[icol] = 1;
- if (bcmp(pivot_row, id_row, k * sizeof(gf)) != 0) {
+ if (memcmp(pivot_row, id_row, k * sizeof(gf)) != 0) {
for (p = src, ix = 0; ix < k; ix++, p += k) {
if (ix != icol) {
c = p[icol];
@@ -560,6 +478,8 @@ fail:
*/
int invert_vdm(gf *src, int k) {
+ assert(k > 0);
+
int i, j, row, col;
gf *b, *c, *p;
gf t, xx;
@@ -614,14 +534,8 @@ int invert_vdm(gf *src, int k) {
static int fec_initialized = 0;
static void init_fec() {
- TICK(ticks[0]);
generate_gf();
- TOCK(ticks[0]);
- DDB(fprintf(stderr, "generate_gf took %ldus\n", ticks[0]);)
- TICK(ticks[0]);
init_mul_table();
- TOCK(ticks[0]);
- DDB(fprintf(stderr, "init_mul_table took %ldus\n", ticks[0]);)
fec_initialized = 1;
}
@@ -680,19 +594,14 @@ struct fec_parms *fec_new(int k, int n) {
* k*k vandermonde matrix, multiply right the bottom n-k rows
* by the inverse, and construct the identity matrix at the top.
*/
- TICK(ticks[3]);
invert_vdm(tmp_m, k); /* much faster than invert_mat */
matmul(tmp_m + k * k, tmp_m, retval->enc_matrix + k * k, n - k, k, k);
/*
* the upper matrix is I so do not bother with a slow multiply
*/
- bzero(retval->enc_matrix, k * k * sizeof(gf));
+ memset(retval->enc_matrix, '\0', k * k * sizeof(gf));
for (p = retval->enc_matrix, col = 0; col < k; col++, p += k + 1) *p = 1;
free(tmp_m);
- TOCK(ticks[3]);
-
- DDB(fprintf(stderr, "--- %ld us to build encoding matrix\n", ticks[3]);)
- DEB(pr_matrix(retval->enc_matrix, n, k, "encoding_matrix");)
return retval;
}
@@ -705,13 +614,13 @@ void fec_encode(struct fec_parms *code, gf *src[], gf *fec, int index, int sz) {
int i, k = code->k;
gf *p;
- if (GF_BITS > 8) sz /= 2;
+ if (GF_BITS > 8) sz /= 2; // NOSONAR
if (index < k)
- bcopy(src[index], fec, sz * sizeof(gf));
+ memcpy(fec, src[index], sz * sizeof(gf));
else if (index < code->n) {
p = &(code->enc_matrix[index * k]);
- bzero(fec, sz * sizeof(gf));
+ memset(fec, '\0', sz * sizeof(gf));
for (i = 0; i < k; i++) addmul(fec, src[i], p[i], sz);
} else
fprintf(stderr, "Invalid index %d (max %d)\n", index, code->n - 1);
@@ -733,22 +642,13 @@ static int shuffle(gf *pkt[], int index[], int k) {
int c = index[i];
if (index[c] == c) {
- DEB(fprintf(stderr, "\nshuffle, error at %d\n", i);)
+ fprintf(stderr, "\nshuffle, error at %d\n", i);
return 1;
}
SWAP(index[i], index[c], int);
SWAP(pkt[i], pkt[c], gf *);
}
}
- DEB(/* just test that it works... */
- for (i = 0; i < k; i++) {
- if (index[i] < k && index[i] != i) {
- fprintf(stderr, "shuffle: after\n");
- for (i = 0; i < k; i++) fprintf(stderr, "%3d ", index[i]);
- fprintf(stderr, "\n");
- return 1;
- }
- })
return 0;
}
@@ -757,20 +657,16 @@ static int shuffle(gf *pkt[], int index[], int k) {
* indexes. The matrix must be already allocated as
* a vector of k*k elements, in row-major order
*/
-static gf *build_decode_matrix(struct fec_parms *code, gf *pkt[], int index[]) {
+static gf *build_decode_matrix(struct fec_parms *code, int index[]) {
int i, k = code->k;
gf *p, *matrix = NEW_GF_MATRIX(k, k);
- TICK(ticks[9]);
for (i = 0, p = matrix; i < k; i++, p += k) {
-#if 1 /* this is simply an optimization, not very useful indeed */
if (index[i] < k) {
- bzero(p, k * sizeof(gf));
+ memset(p, '\0', k * sizeof(gf));
p[i] = 1;
- } else
-#endif
- if (index[i] < code->n)
- bcopy(&(code->enc_matrix[index[i] * k]), p, k * sizeof(gf));
+ } else if (index[i] < code->n)
+ memcpy(p, &(code->enc_matrix[index[i] * k]), k * sizeof(gf));
else {
fprintf(stderr, "decode: invalid index %d (max %d)\n", index[i],
code->n - 1);
@@ -778,12 +674,10 @@ static gf *build_decode_matrix(struct fec_parms *code, gf *pkt[], int index[]) {
return NULL;
}
}
- TICK(ticks[9]);
if (invert_mat(matrix, k)) {
free(matrix);
matrix = NULL;
}
- TOCK(ticks[9]);
return matrix;
}
@@ -800,39 +694,29 @@ static gf *build_decode_matrix(struct fec_parms *code, gf *pkt[], int index[]) {
*/
int fec_decode(struct fec_parms *code, gf *pkt[], int index[], int sz) {
gf *m_dec;
- gf **new_pkt;
+ gf **new_pkt = nullptr;
int row, col, k = code->k;
+ int i = 0;
- if (GF_BITS > 8) sz /= 2;
+ if (GF_BITS > 8) sz /= 2; // NOSONAR
if (shuffle(pkt, index, k)) /* error if true */
return 1;
- m_dec = build_decode_matrix(code, pkt, index);
+ m_dec = build_decode_matrix(code, index);
if (m_dec == NULL) return 1; /* error */
/*
* do the actual decoding
*/
- new_pkt = (gf **)my_malloc(k * sizeof(gf *), "new pkt pointers");
+ new_pkt = pkt + k;
for (row = 0; row < k; row++) {
if (index[row] >= k) {
- new_pkt[row] = (gf *)my_malloc(sz * sizeof(gf), "new pkt buffer");
- bzero(new_pkt[row], sz * sizeof(gf));
+ memset(new_pkt[i], '\0', sz * sizeof(gf));
for (col = 0; col < k; col++)
- addmul(new_pkt[row], pkt[col], m_dec[row * k + col], sz);
- }
- }
- /*
- * move pkts to their final destination
- */
- for (row = 0; row < k; row++) {
- if (index[row] >= k) {
- bcopy(new_pkt[row], pkt[row], sz * sizeof(gf));
- free(new_pkt[row]);
+ addmul(new_pkt[i], pkt[col], m_dec[row * k + col], sz);
+ i++;
}
}
- free(new_pkt);
free(m_dec);
-
return 0;
-}
+} \ No newline at end of file
diff --git a/libtransport/src/protocols/fec/rely.cc b/libtransport/src/protocols/fec/rely.cc
index 7a30a62e2..9e0a06dd8 100644
--- a/libtransport/src/protocols/fec/rely.cc
+++ b/libtransport/src/protocols/fec/rely.cc
@@ -23,38 +23,39 @@ namespace transport {
namespace protocol {
namespace fec {
-RelyEncoder::RelyEncoder(uint32_t k, uint32_t n, uint32_t seq_offset)
+RelyEncoder::RelyEncoder(uint32_t k, uint32_t n, uint32_t /* seq_offset */)
: RelyBase(k, n) {
configure(kmtu, ktimeout, kmax_stream_size);
set_repair_trigger(k_, n_ - k_, n_ - k_);
}
void RelyEncoder::onPacketProduced(core::ContentObject &content_object,
- uint32_t offset) {
+ uint32_t offset, uint32_t metadata) {
// Get pointer to payload, leaving space to insert FEC header.
// TODO Check if this additional header is really needed.
- auto data = content_object.writableData() + offset - sizeof(fec_header);
- auto length = content_object.length() - offset + sizeof(fec_header);
+ auto data = content_object.writableData() + offset - sizeof(fec_metadata);
+ auto length = content_object.length() - offset + sizeof(fec_metadata);
// Check packet length does not exceed maximum length supported by the
// encoder (otherwise segmentation would take place).
- assert(length < max_packet_bytes());
+ DCHECK(length < max_packet_bytes());
DLOG_IF(INFO, VLOG_IS_ON(4))
- << "Encoding packet of length " << length - sizeof(fec_header);
+ << "Encoding packet of length " << length - sizeof(fec_metadata);
- // Get the suffix. With rely we need to write it in the fec_header in order to
- // be able to recognize the seq number upon recovery.
+ // Get the suffix. With rely we need to write it in the fec_metadata in order
+ // to be able to recognize the seq number upon recovery.
auto suffix = content_object.getName().getSuffix();
DLOG_IF(INFO, VLOG_IS_ON(4)) << "Producing packet " << suffix
<< " (index == " << current_index_ << ")";
- // Consume payload. Add fec_header in front before feeding payload to encoder,
- // and copy original content of packet
- fec_header *h = reinterpret_cast<fec_header *>(data);
- fec_header copy = *h;
+ // Consume payload. Add fec_metadata in front before feeding payload to
+ // encoder, and copy original content of packet
+ fec_metadata *h = reinterpret_cast<fec_metadata *>(data);
+ fec_metadata copy = *h;
h->setSeqNumberBase(suffix);
+ h->setMetadataBase(metadata);
auto packets = consume(data, length, getCurrentTime());
- assert(packets == 1);
+ DCHECK(packets == 1);
// Update packet counter
current_index_ += packets;
@@ -62,7 +63,7 @@ void RelyEncoder::onPacketProduced(core::ContentObject &content_object,
// Restore original packet content and increment data pointer to the correct
// position
*h = copy;
- data += sizeof(fec_header);
+ data += sizeof(fec_metadata);
// Check position of this packet inside N size block
auto i = current_index_ % n_;
@@ -74,24 +75,24 @@ void RelyEncoder::onPacketProduced(core::ContentObject &content_object,
// TODO Optimize it by copying only the RELY header
// Be sure encoder can produce
- assert(can_produce());
+ DCHECK(can_produce());
// Check new payload size and make sure it fits in packet buffer
auto new_payload_size = produce_bytes();
- int difference = new_payload_size - length;
+ int difference = (int)(new_payload_size - length);
- assert(difference > 0);
- assert(content_object.ensureCapacity(difference));
+ DCHECK(difference > 0);
+ DCHECK(content_object.ensureCapacity(difference));
// Update length
DLOG_IF(INFO, VLOG_IS_ON(4)) << "The packet length will be incremented by "
- << difference + sizeof(fec_header);
- content_object.append(difference + sizeof(fec_header));
+ << difference + sizeof(fec_metadata);
+ content_object.append(difference + sizeof(fec_metadata));
content_object.updateLength();
// Make sure we got a source packet, otherwise we would put a repair symbol
// in a source packet
- assert(rely::packet_is_systematic(produce_data()));
+ DCHECK(rely::packet_is_systematic(produce_data()));
// Copy rely packet replacing old source packet.
std::memcpy(data, produce_data(), new_payload_size);
@@ -111,7 +112,7 @@ void RelyEncoder::onPacketProduced(core::ContentObject &content_object,
while (can_produce()) {
// The current index MUST be k_, because we enforce n - k repair to be
// produced after k sources
- assert(current_index_ == k_);
+ DCHECK(current_index_ == k_);
buffer packet;
if (!buffer_callback_) {
@@ -130,7 +131,7 @@ void RelyEncoder::onPacketProduced(core::ContentObject &content_object,
std::memcpy(packet->writableData(), produce_data(), produce_bytes());
// Push symbol in repair_packets
- packets_.emplace_back(0, std::move(packet));
+ packets_.emplace_back(0, metadata, std::move(packet));
// Advance the encoder
produce_next();
@@ -143,7 +144,7 @@ void RelyEncoder::onPacketProduced(core::ContentObject &content_object,
// If we have generated repair symbols, let's notify caller via the installed
// callback
if (packets_.size()) {
- assert(packets_.size() == n_ - k_);
+ DCHECK(packets_.size() == n_ - k_);
fec_callback_(packets_);
packets_.clear();
current_index_ = 0;
@@ -156,7 +157,7 @@ RelyDecoder::RelyDecoder(uint32_t k, uint32_t n, uint32_t seq_offset)
}
void RelyDecoder::onDataPacket(core::ContentObject &content_object,
- uint32_t offset) {
+ uint32_t offset, uint32_t metadata) {
// Adjust pointers to point to packet payload
auto data = content_object.writableData() + offset;
auto size = content_object.length() - offset;
@@ -164,30 +165,38 @@ void RelyDecoder::onDataPacket(core::ContentObject &content_object,
// Pass payload to decoder
consume(data, size, getCurrentTime());
+ producePackets();
+}
+
+void RelyDecoder::producePackets() {
// Drain decoder if possible
while (can_produce()) {
- // Get size of decoded packet
- auto size = produce_bytes();
-
- // Get buffer to copy packet in
- auto packet = core::PacketManager<>::getInstance().getMemBuf();
+ auto fec_header_size = sizeof(fec_metadata);
+ auto payload_size = produce_bytes() - sizeof(fec_metadata);
- // Copy buffer
- packet->append(size);
- std::memcpy(packet->writableData(), produce_data(), size);
+ buffer packet;
+ if (!buffer_callback_) {
+ packet = core::PacketManager<>::getInstance().getMemBuf();
+ packet->append(payload_size);
+ } else {
+ packet = buffer_callback_(payload_size);
+ }
// Read seq number
- fec_header *h = reinterpret_cast<fec_header *>(packet->writableData());
+ const fec_metadata *h =
+ reinterpret_cast<const fec_metadata *>(produce_data());
uint32_t index = h->getSeqNumberBase();
+ uint32_t metadata = h->getMetadataBase();
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "The index written in the packet is " << index;
- // Remove FEC header
- packet->trimStart(sizeof(fec_header));
+ // Copy payload
+ std::memcpy(packet->writableData(), produce_data() + fec_header_size,
+ payload_size);
// Save packet in buffer
- packets_.emplace_back(index, std::move(packet));
+ packets_.emplace_back(index, metadata, std::move(packet));
// Advance to next packet
produce_next();
@@ -198,8 +207,28 @@ void RelyDecoder::onDataPacket(core::ContentObject &content_object,
fec_callback_(packets_);
packets_.clear();
}
+
+ flushOutOfOrder();
+}
+
+void RelyDecoder::flushOutOfOrder() {
+ if (flush_timer_ == nullptr) return;
+ flush_timer_->cancel();
+
+ if (has_upcoming_flush()) {
+ flush_timer_->expires_from_now(std::chrono::milliseconds(
+ std::max((int64_t)0, upcoming_flush(getCurrentTime()))));
+
+ flush_timer_->async_wait([this](const std::error_code &ec) {
+ if (ec) return;
+ if (has_upcoming_flush()) {
+ flush(getCurrentTime());
+ producePackets();
+ }
+ });
+ }
}
} // namespace fec
} // namespace protocol
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/libtransport/src/protocols/fec/rely.h b/libtransport/src/protocols/fec/rely.h
index bfbdb30bc..cc81222b2 100644
--- a/libtransport/src/protocols/fec/rely.h
+++ b/libtransport/src/protocols/fec/rely.h
@@ -15,6 +15,7 @@
#pragma once
+#include <hicn/transport/portability/endianess.h>
#include <hicn/transport/utils/chrono_typedefs.h>
#include <hicn/transport/utils/membuf.h>
#include <protocols/fec/fec_info.h>
@@ -33,8 +34,12 @@ namespace fec {
* @brief Table of used codes.
*/
#define foreach_rely_fec_type \
+ _(Rely, 1, 2) \
_(Rely, 1, 3) \
+ _(Rely, 1, 4) \
_(Rely, 2, 3) \
+ _(Rely, 2, 6) \
+ _(Rely, 3, 9) \
_(Rely, 4, 5) \
_(Rely, 4, 6) \
_(Rely, 4, 7) \
@@ -74,11 +79,25 @@ class RelyBase : public virtual FECBase {
* decoding operations. It may be removed once we know the meaning of the
* fields in the rely header.
*/
- struct fec_header {
+ class fec_metadata {
+ public:
+ void setSeqNumberBase(uint32_t suffix) {
+ seq_number = portability::host_to_net(suffix);
+ }
+ uint32_t getSeqNumberBase() const {
+ return portability::net_to_host(seq_number);
+ }
+
+ void setMetadataBase(uint32_t value) {
+ metadata = portability::host_to_net(value);
+ }
+ uint32_t getMetadataBase() const {
+ return portability::net_to_host(metadata);
+ }
+
+ private:
uint32_t seq_number;
-
- void setSeqNumberBase(uint32_t suffix) { seq_number = htonl(suffix); }
- uint32_t getSeqNumberBase() { return ntohl(seq_number); }
+ uint32_t metadata;
};
/**
@@ -112,21 +131,20 @@ class RelyBase : public virtual FECBase {
#if RELY_DEBUG
return time_++;
#else
- auto _time = utils::SteadyClock::now().time_since_epoch();
- auto time = std::chrono::duration_cast<utils::Milliseconds>(_time).count();
- return time;
+ return utils::SteadyTime::nowMs().count();
#endif
}
- protected:
uint32_t k_;
uint32_t n_;
+
std::uint32_t seq_offset_;
+
/**
* @brief Vector of packets to be passed to caller callbacks. For encoder it
* will contain the repair packets, for decoder the recovered sources.
*/
- std::vector<std::pair<uint32_t, buffer>> packets_;
+ BufferArray packets_;
/**
* @brief Current index to be used for local packet count.
@@ -142,50 +160,56 @@ class RelyBase : public virtual FECBase {
* @brief The Rely Encoder implementation.
*
*/
-class RelyEncoder : private RelyBase,
- private rely::encoder,
- public ProducerFEC {
+class RelyEncoder : RelyBase, rely::encoder, public ProducerFEC {
public:
RelyEncoder(uint32_t k, uint32_t n, uint32_t seq_offset = 0);
/**
* Producers will call this function when they produce a data packet.
*/
- void onPacketProduced(core::ContentObject &content_object,
- uint32_t offset) override;
+ void onPacketProduced(core::ContentObject &content_object, uint32_t offset,
+ uint32_t metadata = FECBase::INVALID_METADATA) override;
/**
* @brief Get the fec header size, if added to source packets
+ * there is not need to distinguish between source and FEC packets here
*/
- std::size_t getFecHeaderSize() override {
- return header_bytes() + sizeof(fec_header) + 4;
+ std::size_t getFecHeaderSize(bool isFEC) override {
+ return header_bytes() + sizeof(fec_metadata) + 4;
}
- void reset() override {}
+ void reset() override {
+ // Nothing to do here
+ }
};
-class RelyDecoder : private RelyBase,
- private rely::decoder,
- public ConsumerFEC {
+class RelyDecoder : RelyBase, rely::decoder, public ConsumerFEC {
public:
RelyDecoder(uint32_t k, uint32_t n, uint32_t seq_offset = 0);
/**
* Consumers will call this function when they receive a data packet
*/
- void onDataPacket(core::ContentObject &content_object,
- uint32_t offset) override;
+ void onDataPacket(core::ContentObject &content_object, uint32_t offset,
+ uint32_t metadata = FECBase::INVALID_METADATA) override;
/**
* @brief Get the fec header size, if added to source packets
+ * there is not need to distinguish between source and FEC packets here
*/
- std::size_t getFecHeaderSize() override {
- return header_bytes() + sizeof(fec_header);
+ std::size_t getFecHeaderSize(bool isFEC) override {
+ return header_bytes() + sizeof(fec_metadata);
+ }
+
+ void reset() override {
+ // Nothing to do here
}
- void reset() override {}
+ private:
+ void producePackets();
+ void flushOutOfOrder();
};
} // namespace fec
} // namespace protocol
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/libtransport/src/protocols/fec/rs.cc b/libtransport/src/protocols/fec/rs.cc
index 2c23d515d..d42740c32 100644
--- a/libtransport/src/protocols/fec/rs.cc
+++ b/libtransport/src/protocols/fec/rs.cc
@@ -46,23 +46,26 @@ bool BlockCode::addRepairSymbol(const fec::buffer &packet, uint32_t i,
to_decode_ = true;
DLOG_IF(INFO, VLOG_IS_ON(4)) << "Adding symbol of size " << packet->length();
return addSymbol(packet, i, offset,
- packet->length() - sizeof(fec_header) - offset);
+ packet->length() - sizeof(fec_header) - offset,
+ FECBase::INVALID_METADATA);
}
bool BlockCode::addSourceSymbol(const fec::buffer &packet, uint32_t i,
- uint32_t offset) {
+ uint32_t offset, uint32_t metadata) {
DLOG_IF(INFO, VLOG_IS_ON(4)) << "Adding source symbol of size "
<< packet->length() << ", offset " << offset;
- return addSymbol(packet, i, offset, packet->length() - offset);
+ return addSymbol(packet, i, offset, packet->length() - offset, metadata);
}
bool BlockCode::addSymbol(const fec::buffer &packet, uint32_t i,
- uint32_t offset, std::size_t size) {
+ uint32_t offset, std::size_t size,
+ uint32_t metadata) {
if (size > max_buffer_size_) {
max_buffer_size_ = size;
}
- operator[](current_block_size_++) = std::make_tuple(i, packet, offset);
+ operator[](current_block_size_) = RSBufferInfo(offset, i, metadata, packet);
+ current_block_size_++;
if (current_block_size_ >= k_) {
if (to_decode_) {
@@ -80,12 +83,13 @@ bool BlockCode::addSymbol(const fec::buffer &packet, uint32_t i,
void BlockCode::encode() {
gf *data[n_];
- uint32_t base = std::get<0>(operator[](0));
+ uint32_t base = operator[](0).getIndex();
// Set packet length in first 2 bytes
for (uint32_t i = 0; i < k_; i++) {
- auto &packet = std::get<1>(operator[](i));
- auto offset = std::get<2>(operator[](i));
+ auto &packet = operator[](i).getBuffer();
+ auto offset = operator[](i).getOffset();
+ auto metadata_base = operator[](i).getMetadata();
auto ret =
packet->ensureCapacityAndFillUnused(max_buffer_size_ + offset, 0);
@@ -98,10 +102,11 @@ void BlockCode::encode() {
// Buffers should hold 2 *after* the padding, in order to be
// able to set the length for the encoding operation.
// packet->trimStart(offset);
- uint16_t *length = reinterpret_cast<uint16_t *>(packet->writableData() +
- max_buffer_size_ + offset);
+ fec_metadata *metadata = reinterpret_cast<fec_metadata *>(
+ packet->writableData() + max_buffer_size_ + offset);
auto buffer_length = packet->length() - offset;
- *length = htons(buffer_length);
+ metadata->setPacketLength(buffer_length);
+ metadata->setMetadataBase(metadata_base);
DLOG_IF(INFO, VLOG_IS_ON(4)) << "Current buffer size: " << packet->length();
@@ -109,7 +114,7 @@ void BlockCode::encode() {
}
// Finish to fill source block with the buffers to hold the repair symbols
- auto length = max_buffer_size_ + sizeof(fec_header) + LEN_SIZE_BYTES;
+ auto length = max_buffer_size_ + sizeof(fec_header) + METADATA_BYTES;
for (uint32_t i = k_; i < n_; i++) {
buffer packet;
if (!params_.buffer_callback_) {
@@ -133,19 +138,21 @@ void BlockCode::encode() {
DLOG_IF(INFO, VLOG_IS_ON(4)) << "Current symbol size: " << packet->length();
data[i] = packet->writableData();
- operator[](i) = std::make_tuple(i, std::move(packet), uint32_t(0));
+ operator[](i) = RSBufferInfo(uint32_t(0), i, FECBase::INVALID_METADATA,
+ std::move(packet));
}
// Generate repair symbols and put them in corresponding buffers
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "Calling encode with max_buffer_size_ = " << max_buffer_size_;
for (uint32_t i = k_; i < n_; i++) {
- fec_encode(code_, data, data[i], i, max_buffer_size_ + LEN_SIZE_BYTES);
+ fec_encode(code_, data, data[i], i,
+ (int)(max_buffer_size_ + METADATA_BYTES));
}
// Re-include header in repair packets
for (uint32_t i = k_; i < n_; i++) {
- auto &packet = std::get<1>(operator[](i));
+ auto &packet = operator[](i).getBuffer();
packet->prepend(sizeof(fec_header));
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "Produced repair symbol of size = " << packet->length();
@@ -153,16 +160,31 @@ void BlockCode::encode() {
}
void BlockCode::decode() {
- gf *data[k_];
+ gf *data[n_];
uint32_t index[k_];
+ buffer aux_fec_packets[n_ - k_];
+ // FEC packet number k0
+ uint32_t k0 = 0;
+
+ // Reorder block by index with in-place sorting
+ for (uint32_t i = 0; i < k_;) {
+ uint32_t idx = operator[](i).getIndex();
+ if (idx >= k_ || idx == i) {
+ i++;
+ } else {
+ std::swap(operator[](i), operator[](idx));
+ }
+ }
for (uint32_t i = 0; i < k_; i++) {
- auto &packet = std::get<1>(operator[](i));
- index[i] = std::get<0>(operator[](i));
- auto offset = std::get<2>(operator[](i));
+ auto &packet = operator[](i).getBuffer();
+ index[i] = operator[](i).getIndex();
+ auto offset = operator[](i).getOffset();
+ auto metadata_base = operator[](i).getMetadata();
sorted_index_[i] = index[i];
if (index[i] < k_) {
+ operator[](i).setReceived();
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "DECODE SOURCE - index " << index[i]
<< " - Current buffer size: " << packet->length();
@@ -173,49 +195,53 @@ void BlockCode::decode() {
// able to set the length for the encoding operation
packet->trimStart(offset);
packet->ensureCapacityAndFillUnused(max_buffer_size_, 0);
- uint16_t *length = reinterpret_cast<uint16_t *>(
- packet->writableData() + max_buffer_size_ - LEN_SIZE_BYTES);
-
- *length = htons(packet->length());
+ fec_metadata *metadata = reinterpret_cast<fec_metadata *>(
+ packet->writableData() + max_buffer_size_ - METADATA_BYTES);
+ metadata->setPacketLength(packet->length());
+ metadata->setMetadataBase(metadata_base);
} else {
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "DECODE SYMBOL - index " << index[i]
<< " - Current buffer size: " << packet->length();
packet->trimStart(sizeof(fec_header) + offset);
+ aux_fec_packets[k0] = core::PacketManager<>::getInstance().getMemBuf();
+ data[k_ + k0] = aux_fec_packets[k0]->writableData();
+ k0++;
}
-
data[i] = packet->writableData();
}
-
// We decode the source block
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "Calling decode with max_buffer_size_ = " << max_buffer_size_;
- fec_decode(code_, data, reinterpret_cast<int *>(index), max_buffer_size_);
- // Find the index in the block for recovered packets
- for (uint32_t i = 0; i < k_; i++) {
- if (index[i] != i) {
- for (uint32_t j = 0; j < k_; j++)
- if (sorted_index_[j] == uint32_t(index[i])) {
- sorted_index_[j] = i;
- }
- }
- }
+ fec_decode(code_, data, reinterpret_cast<int *>(index),
+ (int)max_buffer_size_);
- // Reorder block by index with in-place sorting
- for (uint32_t i = 0; i < k_; i++) {
- for (uint32_t j = sorted_index_[i]; j != i; j = sorted_index_[i]) {
- std::swap(sorted_index_[j], sorted_index_[i]);
- std::swap(operator[](j), operator[](i));
+ // Find the index in the block for recovered packets
+ for (uint32_t i = 0, j = 0; i < k_; i++) {
+ if (index[i] >= k_) {
+ operator[](i).setBuffer(aux_fec_packets[j++]);
+ operator[](i).setIndex(i);
}
}
// Adjust length according to the one written in the source packet
for (uint32_t i = 0; i < k_; i++) {
- auto &packet = std::get<1>(operator[](i));
- uint16_t *length = reinterpret_cast<uint16_t *>(
- packet->writableData() + max_buffer_size_ - LEN_SIZE_BYTES);
- packet->setLength(ntohs(*length));
+ auto &packet = operator[](i).getBuffer();
+ fec_metadata *metadata = reinterpret_cast<fec_metadata *>(
+ packet->writableData() + max_buffer_size_ - METADATA_BYTES);
+ DCHECK(metadata->getPacketLength() <= packet->capacity());
+ // Adjust buffer length
+ packet->setLength(metadata->getPacketLength());
+ // Adjust metadata
+ operator[](i).setMetadata(metadata->getMetadataBase());
+
+ // reset the point to the beginning of the packets for all received packets
+ if (operator[](i).getReceived()) {
+ auto &packet = operator[](i).getBuffer();
+ auto offset = operator[](i).getOffset();
+ packet->prepend(offset);
+ }
}
}
@@ -252,12 +278,11 @@ RSEncoder::RSEncoder(uint32_t k, uint32_t n, uint32_t seq_offset)
source_block_(k_, n_, seq_offset_, current_code_, *this) {}
void RSEncoder::consume(const fec::buffer &packet, uint32_t index,
- uint32_t offset) {
- if (!source_block_.addSourceSymbol(packet, index, offset)) {
- std::vector<std::pair<uint32_t, buffer>> repair_packets;
+ uint32_t offset, uint32_t metadata) {
+ if (!source_block_.addSourceSymbol(packet, index, offset, metadata)) {
+ fec::BufferArray repair_packets;
for (uint32_t i = k_; i < n_; i++) {
- repair_packets.emplace_back(std::move(std::get<0>(source_block_[i])),
- std::move(std::get<1>(source_block_[i])));
+ repair_packets.emplace_back(std::move(source_block_[i]));
}
fec_callback_(repair_packets);
@@ -265,9 +290,9 @@ void RSEncoder::consume(const fec::buffer &packet, uint32_t index,
}
void RSEncoder::onPacketProduced(core::ContentObject &content_object,
- uint32_t offset) {
+ uint32_t offset, uint32_t metadata) {
consume(content_object.shared_from_this(),
- content_object.getName().getSuffix(), offset);
+ content_object.getName().getSuffix(), offset, metadata);
}
RSDecoder::RSDecoder(uint32_t k, uint32_t n, uint32_t seq_offset)
@@ -276,10 +301,15 @@ RSDecoder::RSDecoder(uint32_t k, uint32_t n, uint32_t seq_offset)
void RSDecoder::recoverPackets(SourceBlocks::iterator &src_block_it) {
DLOG_IF(INFO, VLOG_IS_ON(4)) << "recoverPackets for " << k_;
auto &src_block = src_block_it->second;
- std::vector<std::pair<uint32_t, buffer>> source_packets(k_);
+ auto base_index = src_block_it->first;
+ BufferArray source_packets(k_);
+
+ // Iterate over packets in the block and adjust indexed accordingly. This must
+ // be done because indexes are from 0 to (n - k - 1), but we need indexes from
+ // base_index to base_index + (n - k - 1)
for (uint32_t i = 0; i < src_block.getK(); i++) {
- source_packets[i] = std::make_pair(src_block_it->first + i,
- std::move(std::get<1>(src_block[i])));
+ src_block[i].setIndex(base_index + src_block[i].getIndex());
+ source_packets[i] = FECBufferInfo(std::move(src_block[i]));
}
setProcessed(src_block_it->first);
@@ -296,9 +326,9 @@ void RSDecoder::recoverPackets(SourceBlocks::iterator &src_block_it) {
}
void RSDecoder::consumeSource(const fec::buffer &packet, uint32_t index,
- uint32_t offset) {
+ uint32_t offset, uint32_t metadata) {
// Normalize index
- assert(index >= seq_offset_);
+ DCHECK(index >= seq_offset_);
auto i = (index - seq_offset_) % n_;
// Get base
@@ -324,16 +354,19 @@ void RSDecoder::consumeSource(const fec::buffer &packet, uint32_t index,
// protocol that may come in the future.
auto it = src_blocks_.find(base);
if (it != src_blocks_.end()) {
- auto ret = it->second.addSourceSymbol(packet, i, offset);
+ auto ret = it->second.addSourceSymbol(packet, i, offset, metadata);
if (!ret) {
recoverPackets(it);
}
} else {
DLOG_IF(INFO, VLOG_IS_ON(4)) << "Adding to parked source packets";
- auto ret = parked_packets_.emplace(
- base, std::vector<std::pair<buffer, uint32_t>>());
- ret.first->second.emplace_back(packet, i);
+ auto ret = parked_packets_.emplace(base, BufferInfoArray());
+ ret.first->second.emplace_back(offset, i, metadata, packet);
+ /**
+ * If we reached k source packets, we do not have any missing packet to
+ * recover via FEC. Delete the block.
+ */
if (ret.first->second.size() >= k_) {
setProcessed(ret.first->first);
parked_packets_.erase(ret.first);
@@ -356,8 +389,8 @@ void RSDecoder::consumeRepair(const fec::buffer &packet, uint32_t offset) {
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "Decoder consume called for repair symbol. BASE = " << base
- << ", index = " << base + i << " and i = " << i << ". K=" << k
- << ", N=" << n;
+ << ", index = " << base + i << " and i = " << (int)i << ". K=" << (int)k
+ << ", N=" << (int)n;
// check if a source block already exist for this symbol
auto it = src_blocks_.find(base);
@@ -380,8 +413,9 @@ void RSDecoder::consumeRepair(const fec::buffer &packet, uint32_t offset) {
auto it2 = parked_packets_.find(base);
if (it2 != parked_packets_.end()) {
for (auto &packet_index : it2->second) {
- auto ret = it->second.addSourceSymbol(packet_index.first,
- packet_index.second, offset);
+ auto ret = it->second.addSourceSymbol(
+ packet_index.getBuffer(), packet_index.getIndex(),
+ packet_index.getOffset(), packet_index.getMetadata());
if (!ret) {
recoverPackets(it);
// Finish to delete packets in same source block that were
@@ -399,7 +433,7 @@ void RSDecoder::consumeRepair(const fec::buffer &packet, uint32_t offset) {
}
void RSDecoder::onDataPacket(core::ContentObject &content_object,
- uint32_t offset) {
+ uint32_t offset, uint32_t metadata) {
DLOG_IF(INFO, VLOG_IS_ON(4))
<< "Calling fec for data packet " << content_object.getName()
<< ". Offset: " << offset;
@@ -409,7 +443,7 @@ void RSDecoder::onDataPacket(core::ContentObject &content_object,
if (isSymbol(suffix)) {
consumeRepair(content_object.shared_from_this(), offset);
} else {
- consumeSource(content_object.shared_from_this(), suffix, offset);
+ consumeSource(content_object.shared_from_this(), suffix, offset, metadata);
}
}
diff --git a/libtransport/src/protocols/fec/rs.h b/libtransport/src/protocols/fec/rs.h
index e159ad9f7..6672eaa6b 100644
--- a/libtransport/src/protocols/fec/rs.h
+++ b/libtransport/src/protocols/fec/rs.h
@@ -18,6 +18,7 @@
#include <arpa/inet.h>
#include <hicn/transport/portability/c_portability.h>
+#include <hicn/transport/portability/endianess.h>
#include <hicn/transport/utils/membuf.h>
#include <protocols/fec/fec_info.h>
#include <protocols/fec_base.h>
@@ -34,10 +35,28 @@ namespace protocol {
namespace fec {
#define foreach_rs_fec_type \
+ _(RS, 1, 2) \
_(RS, 1, 3) \
+ _(RS, 1, 4) \
+ _(RS, 2, 3) \
+ _(RS, 2, 4) \
+ _(RS, 2, 5) \
+ _(RS, 2, 6) \
+ _(RS, 3, 6) \
+ _(RS, 3, 7) \
+ _(RS, 3, 8) \
+ _(RS, 3, 9) \
+ _(RS, 3, 10) \
+ _(RS, 3, 11) \
+ _(RS, 3, 12) \
_(RS, 4, 5) \
_(RS, 4, 6) \
_(RS, 4, 7) \
+ _(RS, 4, 8) \
+ _(RS, 4, 9) \
+ _(RS, 4, 10) \
+ _(RS, 4, 11) \
+ _(RS, 4, 12) \
_(RS, 6, 10) \
_(RS, 8, 10) \
_(RS, 8, 11) \
@@ -45,6 +64,8 @@ namespace fec {
_(RS, 8, 14) \
_(RS, 8, 16) \
_(RS, 8, 32) \
+ _(RS, 10, 20) \
+ _(RS, 10, 25) \
_(RS, 10, 30) \
_(RS, 10, 40) \
_(RS, 10, 60) \
@@ -56,12 +77,24 @@ namespace fec {
_(RS, 16, 27) \
_(RS, 17, 21) \
_(RS, 17, 34) \
+ _(RS, 20, 45) \
+ _(RS, 20, 50) \
+ _(RS, 20, 60) \
+ _(RS, 20, 70) \
+ _(RS, 30, 70) \
+ _(RS, 30, 75) \
+ _(RS, 30, 85) \
+ _(RS, 30, 95) \
_(RS, 32, 36) \
_(RS, 32, 41) \
_(RS, 32, 46) \
_(RS, 32, 54) \
_(RS, 34, 42) \
_(RS, 35, 70) \
+ _(RS, 40, 95) \
+ _(RS, 40, 100) \
+ _(RS, 40, 110) \
+ _(RS, 40, 120) \
_(RS, 52, 62)
static const constexpr uint16_t MAX_SOURCE_BLOCK_SIZE = 128;
@@ -73,9 +106,24 @@ static const constexpr uint16_t MAX_SOURCE_BLOCK_SIZE = 128;
* std::array allows to be constructed in place, saving the allocation at the
* price os knowing in advance its size.
*/
-using Packets = std::array<std::tuple</* index */ uint32_t, /* buffer */ buffer,
- uint32_t /* offset */>,
- MAX_SOURCE_BLOCK_SIZE>;
+class RSBufferInfo : public FECBufferInfo {
+ public:
+ RSBufferInfo() : FECBufferInfo() {}
+
+ RSBufferInfo(uint32_t offset, uint32_t index, uint32_t metadata,
+ buffer buffer)
+ : FECBufferInfo(index, metadata, buffer), offset_(offset) {}
+
+ uint32_t getOffset() { return offset_; }
+ RSBufferInfo &setOffset(uint32_t offset) {
+ offset_ = offset;
+ return *this;
+ }
+
+ private:
+ uint32_t offset_ = 0;
+};
+using Packets = std::array<RSBufferInfo, MAX_SOURCE_BLOCK_SIZE>;
/**
* FEC Header, prepended to symbol packets.
@@ -106,8 +154,10 @@ struct fec_header {
*/
uint8_t padding;
- void setSeqNumberBase(uint32_t suffix) { seq_number = htonl(suffix); }
- uint32_t getSeqNumberBase() { return ntohl(seq_number); }
+ void setSeqNumberBase(uint32_t suffix) {
+ seq_number = portability::host_to_net(suffix);
+ }
+ uint32_t getSeqNumberBase() { return portability::net_to_host(seq_number); }
void setEncodedSymbolId(uint8_t esi) { encoded_symbol_id = esi; }
uint8_t getEncodedSymbolId() { return encoded_symbol_id; }
void setSourceBlockLen(uint8_t k) { source_block_len = k; }
@@ -116,6 +166,8 @@ struct fec_header {
uint8_t getNFecSymbols() { return n_fec_symbols; }
};
+static_assert(sizeof(fec_header) <= 8, "fec_header is too large");
+
class rs;
/**
@@ -123,10 +175,38 @@ class rs;
*/
class BlockCode : public Packets {
/**
+ * @brief Metadata to include when encoding the buffers. This does not need to
+ * be sent over the network, but just to be included in the FEC protected
+ * bytes.
+ *
+ */
+ class __attribute__((__packed__)) fec_metadata {
+ public:
+ void setPacketLength(uint16_t length) {
+ packet_length = portability::host_to_net(length);
+ }
+ uint32_t getPacketLength() {
+ return portability::net_to_host(packet_length);
+ }
+
+ void setMetadataBase(uint32_t value) {
+ metadata = portability::host_to_net(value);
+ }
+ uint32_t getMetadataBase() { return portability::net_to_host(metadata); }
+
+ private:
+ uint16_t packet_length; /* Used to get the real size of the packet after we
+ pad it */
+ uint32_t
+ metadata; /* Caller may specify an integer for storing additional
+ metadata that can be used when recovering the packet. */
+ };
+
+ /**
* For variable length packet we need to prepend to the padded payload the
* real length of the packet. This is *not* sent over the network.
*/
- static constexpr std::size_t LEN_SIZE_BYTES = 2;
+ static constexpr std::size_t METADATA_BYTES = sizeof(fec_metadata);
public:
BlockCode(uint32_t k, uint32_t n, uint32_t seq_offset, struct fec_parms *code,
@@ -142,7 +222,8 @@ class BlockCode : public Packets {
* Add a source symbol to the source block.
*/
bool addSourceSymbol(const fec::buffer &packet, uint32_t i,
- uint32_t offset = 0);
+ uint32_t offset = 0,
+ uint32_t metadata = FECBase::INVALID_METADATA);
/**
* Get current length of source block.
@@ -169,7 +250,7 @@ class BlockCode : public Packets {
* Add symbol to source block
**/
bool addSymbol(const fec::buffer &packet, uint32_t i, uint32_t offset,
- std::size_t size);
+ std::size_t size, uint32_t metadata);
/**
* Starting from k source symbols, get the n - k repair symbols
@@ -310,15 +391,19 @@ class RSEncoder : public rs, public ProducerFEC {
/**
* Always consume source symbols.
*/
- void consume(const fec::buffer &packet, uint32_t index, uint32_t offset = 0);
+ void consume(const fec::buffer &packet, uint32_t index, uint32_t offset = 0,
+ uint32_t metadata = FECBase::INVALID_METADATA);
- void onPacketProduced(core::ContentObject &content_object,
- uint32_t offset) override;
+ void onPacketProduced(core::ContentObject &content_object, uint32_t offset,
+ uint32_t metadata = FECBase::INVALID_METADATA) override;
/**
* @brief Get the fec header size, if added to source packets
+ * in RS the source packets do not transport any FEC header
*/
- std::size_t getFecHeaderSize() override { return 0; }
+ std::size_t getFecHeaderSize(bool isFEC) override {
+ return isFEC ? sizeof(fec_header) : 0;
+ }
void clear() override {
rs::clear();
@@ -348,8 +433,8 @@ class RSDecoder : public rs, public ConsumerFEC {
/**
* Consume source symbol
*/
- void consumeSource(const fec::buffer &packet, uint32_t i,
- uint32_t offset = 0);
+ void consumeSource(const fec::buffer &packet, uint32_t i, uint32_t offset = 0,
+ uint32_t metadata = FECBase::INVALID_METADATA);
/**
* Consume repair symbol
@@ -359,13 +444,16 @@ class RSDecoder : public rs, public ConsumerFEC {
/**
* Consumers will call this function when they receive a data packet
*/
- void onDataPacket(core::ContentObject &content_object,
- uint32_t offset) override;
+ void onDataPacket(core::ContentObject &content_object, uint32_t offset,
+ uint32_t metadata = FECBase::INVALID_METADATA) override;
/**
* @brief Get the fec header size, if added to source packets
+ * in RS the source packets do not transport any FEC header
*/
- std::size_t getFecHeaderSize() override { return 0; }
+ std::size_t getFecHeaderSize(bool isFEC) override {
+ return isFEC ? sizeof(fec_header) : 0;
+ }
/**
* Clear decoder to reuse
@@ -398,8 +486,8 @@ class RSDecoder : public rs, public ConsumerFEC {
* not make any sense to build the source block, since we received all the
* source packet of the block.
*/
- std::unordered_map<uint32_t, std::vector<std::pair<buffer, uint32_t>>>
- parked_packets_;
+ using BufferInfoArray = std::vector<RSBufferInfo>;
+ std::unordered_map<uint32_t, BufferInfoArray> parked_packets_;
};
} // namespace fec
diff --git a/libtransport/src/protocols/fec_base.h b/libtransport/src/protocols/fec_base.h
index a1929d85e..28f6a820a 100644
--- a/libtransport/src/protocols/fec_base.h
+++ b/libtransport/src/protocols/fec_base.h
@@ -15,6 +15,7 @@
#pragma once
+#include <hicn/transport/core/asio_wrapper.h>
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/errors/not_implemented_exception.h>
@@ -25,12 +26,67 @@ namespace protocol {
namespace fec {
-using buffer = typename utils::MemBuf::Ptr;
-using BufferArray = std::vector<std::pair<uint32_t, buffer>>;
+using buffer = utils::MemBuf::Ptr;
+
+class FECBufferInfo {
+ public:
+ FECBufferInfo()
+ : index_(~0), metadata_(~0), received_(false), buffer_(nullptr) {}
+
+ template <typename T>
+ FECBufferInfo(uint32_t index, uint32_t metadata, T &&buffer)
+ : index_(index),
+ metadata_(metadata),
+ received_(false),
+ buffer_(std::forward<T>(buffer)) {}
+
+ // Getters
+ uint32_t getIndex() const { return index_; }
+
+ uint32_t getMetadata() const { return metadata_; }
+
+ bool getReceived() const { return received_; }
+
+ buffer &getBuffer() { return buffer_; }
+
+ // Setters
+ void setReceived() { received_ = true; }
+
+ FECBufferInfo &setIndex(uint32_t index) {
+ index_ = index;
+ return *this;
+ }
+
+ FECBufferInfo &setMetadata(uint32_t metadata) {
+ metadata_ = metadata;
+ return *this;
+ }
+
+ FECBufferInfo &setBuffer(buffer &buffer) {
+ buffer_ = buffer;
+ return *this;
+ }
+
+ FECBufferInfo &setBuffer(buffer &&buffer) {
+ buffer_ = std::move(buffer);
+ return *this;
+ }
+
+ private:
+ uint32_t index_;
+ uint32_t metadata_;
+ bool received_;
+ buffer buffer_;
+};
+
+using BufferArray = typename std::vector<FECBufferInfo>;
class FECBase {
public:
- virtual ~FECBase() = default;
+ static inline uint32_t INVALID_METADATA = ~0;
+ static inline uint32_t INVALID_INDEX = ~0;
+
+ virtual ~FECBase() {}
/**
* Callback to be called after the encode or the decode operations. In the
* former case it will contain the symbols, while in the latter the sources.
@@ -45,8 +101,10 @@ class FECBase {
/**
* @brief Get size of FEC header.
+ * the fec header size may be different if a packet is a data packet or a FEC
+ * packet
*/
- virtual std::size_t getFecHeaderSize() = 0;
+ virtual std::size_t getFecHeaderSize(bool isFEC) = 0;
/**
* Set callback to call after packet encoding / decoding
@@ -64,11 +122,21 @@ class FECBase {
buffer_callback_ = buffer_callback;
}
+ /**
+ * Creates the timer to flush packets. So far needed only if using Rely and
+ * want to avoid expired packets blocked by missing pkts to wait for a new
+ * packet to arrive and trigger the flush
+ */
+ void setIOService(asio::io_service &io_service) {
+ flush_timer_ = std::make_unique<asio::steady_timer>(io_service);
+ }
+
virtual void reset() = 0;
protected:
PacketsReady fec_callback_{0};
BufferRequested buffer_callback_{0};
+ std::unique_ptr<asio::steady_timer> flush_timer_;
};
/**
@@ -80,8 +148,9 @@ class ProducerFEC : public virtual FECBase {
/**
* Producers will call this function upon production of a new packet.
*/
- virtual void onPacketProduced(core::ContentObject &content_object,
- uint32_t offset) = 0;
+ virtual void onPacketProduced(
+ core::ContentObject &content_object, uint32_t offset,
+ uint32_t metadata = FECBase::INVALID_METADATA) = 0;
};
/**
@@ -95,9 +164,10 @@ class ConsumerFEC : public virtual FECBase {
* Consumers will call this function when they receive a data packet
*/
virtual void onDataPacket(core::ContentObject &content_object,
- uint32_t offset) = 0;
+ uint32_t offset,
+ uint32_t metadata = FECBase::INVALID_METADATA) = 0;
};
} // namespace fec
} // namespace protocol
-} // namespace transport \ No newline at end of file
+} // namespace transport
diff --git a/libtransport/src/protocols/incremental_indexer_bytestream.cc b/libtransport/src/protocols/incremental_indexer_bytestream.cc
index cc302a98a..b94f229e5 100644
--- a/libtransport/src/protocols/incremental_indexer_bytestream.cc
+++ b/libtransport/src/protocols/incremental_indexer_bytestream.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,9 +29,9 @@ void IncrementalIndexer::onContentObject(core::Interest &interest,
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Received content " << content_object.getName();
- assert(reassembly_);
+ DCHECK(reassembly_);
- if (TRANSPORT_EXPECT_FALSE(content_object.testRst())) {
+ if (TRANSPORT_EXPECT_FALSE(content_object.isLast())) {
final_suffix_ = content_object.getName().getSuffix();
}
diff --git a/libtransport/src/protocols/incremental_indexer_bytestream.h b/libtransport/src/protocols/incremental_indexer_bytestream.h
index c6a669629..4f9b6126f 100644
--- a/libtransport/src/protocols/incremental_indexer_bytestream.h
+++ b/libtransport/src/protocols/incremental_indexer_bytestream.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -48,7 +48,7 @@ class IncrementalIndexer : public Indexer {
IncrementalIndexer(const IncrementalIndexer &other) = delete;
IncrementalIndexer(IncrementalIndexer &&other)
- : Indexer(std::forward<Indexer>(other)),
+ : Indexer(other),
final_suffix_(other.final_suffix_),
first_suffix_(other.first_suffix_),
next_download_suffix_(other.next_download_suffix_),
@@ -62,7 +62,7 @@ class IncrementalIndexer : public Indexer {
next_reassembly_suffix_ = first_suffix_;
}
- virtual uint32_t checkNextSuffix() override {
+ virtual uint32_t checkNextSuffix() const override {
return next_download_suffix_ <= final_suffix_ ? next_download_suffix_
: Indexer::invalid_index;
}
@@ -76,7 +76,7 @@ class IncrementalIndexer : public Indexer {
first_suffix_ = suffix;
}
- uint32_t getFirstSuffix() override { return first_suffix_; }
+ uint32_t getFirstSuffix() const override { return first_suffix_; }
virtual uint32_t jumpToIndex(uint32_t index) override {
next_download_suffix_ = index;
@@ -95,14 +95,14 @@ class IncrementalIndexer : public Indexer {
return final_suffix_ != Indexer::invalid_index;
}
- virtual uint32_t getFinalSuffix() override { return final_suffix_; }
+ virtual uint32_t getFinalSuffix() const override { return final_suffix_; }
void enableFec(fec::FECType fec_type) override {}
void disableFec() override {}
void setNFec(uint32_t n_fec) override {}
- virtual uint32_t getNFec() override { return 0; }
+ virtual uint32_t getNFec() const override { return 0; }
virtual void onContentObject(core::Interest &interest,
core::ContentObject &content_object,
diff --git a/libtransport/src/protocols/index_manager_bytestream.cc b/libtransport/src/protocols/index_manager_bytestream.cc
index c78dc634d..952f36e0e 100644
--- a/libtransport/src/protocols/index_manager_bytestream.cc
+++ b/libtransport/src/protocols/index_manager_bytestream.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/index_manager_bytestream.h b/libtransport/src/protocols/index_manager_bytestream.h
index e14c8845b..7ea31dfa5 100644
--- a/libtransport/src/protocols/index_manager_bytestream.h
+++ b/libtransport/src/protocols/index_manager_bytestream.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -40,7 +40,9 @@ class IndexManager : public IncrementalIndexer {
indexer_->setFirstSuffix(suffix);
}
- uint32_t getFirstSuffix() override { return indexer_->getFirstSuffix(); }
+ uint32_t getFirstSuffix() const override {
+ return indexer_->getFirstSuffix();
+ }
uint32_t getNextReassemblySegment() override {
return indexer_->getNextReassemblySegment();
@@ -50,22 +52,26 @@ class IndexManager : public IncrementalIndexer {
return indexer_->isFinalSuffixDiscovered();
}
- uint32_t getFinalSuffix() override { return indexer_->getFinalSuffix(); }
+ uint32_t getFinalSuffix() const override {
+ return indexer_->getFinalSuffix();
+ }
uint32_t jumpToIndex(uint32_t index) override {
return indexer_->jumpToIndex(index);
}
void setNFec(uint32_t n_fec) override { return indexer_->setNFec(n_fec); }
- uint32_t getNFec() override { return indexer_->getNFec(); }
+ uint32_t getNFec() const override { return indexer_->getNFec(); }
void enableFec(fec::FECType fec_type) override {
return indexer_->enableFec(fec_type);
}
- double getFecOverhead() override { return indexer_->getFecOverhead(); }
+ double getFecOverhead() const override { return indexer_->getFecOverhead(); }
- double getMaxFecOverhead() override { return indexer_->getMaxFecOverhead(); }
+ double getMaxFecOverhead() const override {
+ return indexer_->getMaxFecOverhead();
+ }
void disableFec() override { return indexer_->disableFec(); }
diff --git a/libtransport/src/protocols/indexer.cc b/libtransport/src/protocols/indexer.cc
index 8d4cf04d7..41465755b 100644
--- a/libtransport/src/protocols/indexer.cc
+++ b/libtransport/src/protocols/indexer.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,10 +14,10 @@
*/
#include <implementation/socket_consumer.h>
+#include <protocols/errors.h>
#include <protocols/indexer.h>
namespace transport {
-
namespace protocol {
using namespace interface;
@@ -36,6 +36,35 @@ void Indexer::setVerifier() {
}
}
-} // end namespace protocol
+void Indexer::applyPolicy(core::Interest &interest,
+ core::ContentObject &content_object, bool reassembly,
+ auth::VerificationPolicy policy) const {
+ DCHECK(reassembly_ != nullptr);
+
+ switch (policy) {
+ case auth::VerificationPolicy::ACCEPT: {
+ if (reassembly) {
+ reassembly_->reassemble(content_object);
+ }
+ break;
+ }
+ case auth::VerificationPolicy::UNKNOWN:
+ if (reassembly && reassembly_->reassembleUnverified()) {
+ reassembly_->reassemble(content_object);
+ }
+ break;
+ case auth::VerificationPolicy::DROP:
+ transport_->onPacketDropped(
+ interest, content_object,
+ make_error_code(protocol_error::verification_failed));
+ break;
+ case auth::VerificationPolicy::ABORT: {
+ transport_->onContentReassembled(
+ make_error_code(protocol_error::session_aborted));
+ break;
+ }
+ }
+}
+} // end namespace protocol
} // end namespace transport
diff --git a/libtransport/src/protocols/indexer.h b/libtransport/src/protocols/indexer.h
index 7e3a52fb0..1bacb13aa 100644
--- a/libtransport/src/protocols/indexer.h
+++ b/libtransport/src/protocols/indexer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#pragma once
+#include <hicn/transport/auth/policies.h>
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/interest.h>
#include <protocols/fec_utils.h>
@@ -44,7 +45,7 @@ class Indexer {
/**
* Suffix getters
*/
- virtual uint32_t checkNextSuffix() = 0;
+ virtual uint32_t checkNextSuffix() const = 0;
virtual uint32_t getNextSuffix() = 0;
virtual uint32_t getNextReassemblySegment() = 0;
@@ -52,24 +53,24 @@ class Indexer {
* Set first suffix from where to start.
*/
virtual void setFirstSuffix(uint32_t suffix) = 0;
- virtual uint32_t getFirstSuffix() = 0;
+ virtual uint32_t getFirstSuffix() const = 0;
/**
* Functions to set/enable/disable fec
*/
virtual void setNFec(uint32_t n_fec) = 0;
- virtual uint32_t getNFec() = 0;
+ virtual uint32_t getNFec() const = 0;
virtual void enableFec(fec::FECType fec_type) = 0;
virtual void disableFec() = 0;
virtual bool isFec(uint32_t index) { return false; }
- virtual double getFecOverhead() { return 0.0; }
- virtual double getMaxFecOverhead() { return 0.0; }
+ virtual double getFecOverhead() const { return 0.0; }
+ virtual double getMaxFecOverhead() const { return 0.0; }
/**
* Final suffix helpers.
*/
virtual bool isFinalSuffixDiscovered() = 0;
- virtual uint32_t getFinalSuffix() = 0;
+ virtual uint32_t getFinalSuffix() const = 0;
/**
* Set reassembly protocol
@@ -84,9 +85,15 @@ class Indexer {
virtual void setVerifier();
/**
+ * Apply a verification policy
+ */
+ virtual void applyPolicy(core::Interest &interest,
+ core::ContentObject &content_object, bool reassembly,
+ auth::VerificationPolicy policy) const;
+ /**
* Jump to suffix. This may be useful if, for any protocol dependent
- * mechanism, we need to suddenly change current suffix. This does not modify
- * the way suffixes re incremented/decremented (that's part of the
+ * mechanism, we need to suddenly change current suffix. This does not
+ * modify the way suffixes re incremented/decremented (that's part of the
* implementation).
*/
virtual uint32_t jumpToIndex(uint32_t index) = 0;
@@ -108,6 +115,7 @@ class Indexer {
TransportProtocol *transport_;
Reassembly *reassembly_;
std::shared_ptr<auth::Verifier> verifier_;
+ auth::CryptoHashType manifest_hash_type_;
};
} // end namespace protocol
diff --git a/libtransport/src/protocols/manifest_incremental_indexer_bytestream.cc b/libtransport/src/protocols/manifest_incremental_indexer_bytestream.cc
index 168aa57af..0b15559a4 100644
--- a/libtransport/src/protocols/manifest_incremental_indexer_bytestream.cc
+++ b/libtransport/src/protocols/manifest_incremental_indexer_bytestream.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -31,8 +31,7 @@ ManifestIncrementalIndexer::ManifestIncrementalIndexer(
implementation::ConsumerSocket *icn_socket, TransportProtocol *transport)
: IncrementalIndexer(icn_socket, transport),
suffix_strategy_(utils::SuffixStrategyFactory::getSuffixStrategy(
- NextSegmentCalculationStrategy::INCREMENTAL, next_download_suffix_,
- 0)) {}
+ utils::NextSuffixStrategy::INCREMENTAL, next_download_suffix_)) {}
void ManifestIncrementalIndexer::onContentObject(
core::Interest &interest, core::ContentObject &content_object,
@@ -59,12 +58,7 @@ void ManifestIncrementalIndexer::onContentObject(
void ManifestIncrementalIndexer::onUntrustedManifest(
core::Interest &interest, core::ContentObject &content_object,
bool reassembly) {
- auto manifest =
- std::make_unique<ContentObjectManifest>(std::move(content_object));
-
- auth::VerificationPolicy policy = verifier_->verifyPackets(manifest.get());
-
- manifest->decode();
+ auth::VerificationPolicy policy = verifier_->verifyPackets(&content_object);
if (policy != auth::VerificationPolicy::ACCEPT) {
transport_->onContentReassembled(
@@ -72,35 +66,33 @@ void ManifestIncrementalIndexer::onUntrustedManifest(
return;
}
- processTrustedManifest(interest, std::move(manifest), reassembly);
+ core::ContentObjectManifest manifest(content_object.shared_from_this());
+ manifest.decode();
+
+ processTrustedManifest(interest, manifest, reassembly);
}
void ManifestIncrementalIndexer::processTrustedManifest(
- core::Interest &interest, std::unique_ptr<ContentObjectManifest> manifest,
+ core::Interest &interest, core::ContentObjectManifest &manifest,
bool reassembly) {
- if (TRANSPORT_EXPECT_FALSE(manifest->getVersion() !=
- core::ManifestVersion::VERSION_1)) {
- throw errors::RuntimeException("Received manifest with unknown version.");
- }
-
- switch (manifest->getManifestType()) {
+ switch (manifest.getType()) {
case core::ManifestType::INLINE_MANIFEST: {
- suffix_strategy_->setFinalSuffix(manifest->getFinalBlockNumber());
+ suffix_strategy_->setFinalSuffix(
+ manifest.getParamsBytestream().final_segment);
// The packets to verify with the received manifest
std::vector<auth::PacketPtr> packets;
// Convert the received manifest to a map of packet suffixes to hashes
- auth::Verifier::SuffixMap current_manifest =
- core::ContentObjectManifest::getSuffixMap(manifest.get());
+ auth::Verifier::SuffixMap suffix_map = manifest.getSuffixMap();
// Update 'suffix_map_' with new hashes from the received manifest and
// build 'packets'
- for (auto it = current_manifest.begin(); it != current_manifest.end();) {
+ for (auto it = suffix_map.begin(); it != suffix_map.end();) {
if (unverified_segments_.find(it->first) ==
unverified_segments_.end()) {
suffix_map_[it->first] = std::move(it->second);
- current_manifest.erase(it++);
+ suffix_map.erase(it++);
continue;
}
@@ -110,7 +102,7 @@ void ManifestIncrementalIndexer::processTrustedManifest(
// Verify unverified segments using the received manifest
auth::Verifier::PolicyMap policies =
- verifier_->verifyPackets(packets, current_manifest);
+ verifier_->verifyPackets(packets, suffix_map);
for (unsigned int i = 0; i < packets.size(); ++i) {
auth::Suffix suffix = packets[i]->getName().getSuffix();
@@ -127,7 +119,9 @@ void ManifestIncrementalIndexer::processTrustedManifest(
}
if (reassembly) {
- reassembly_->reassemble(std::move(manifest));
+ auto manifest_co =
+ std::dynamic_pointer_cast<ContentObject>(manifest.getPacket());
+ reassembly_->reassemble(*manifest_co);
}
break;
}
@@ -162,45 +156,15 @@ void ManifestIncrementalIndexer::onUntrustedContentObject(
applyPolicy(interest, content_object, reassembly, policy);
}
-void ManifestIncrementalIndexer::applyPolicy(
- core::Interest &interest, core::ContentObject &content_object,
- bool reassembly, auth::VerificationPolicy policy) {
- assert(reassembly_);
- switch (policy) {
- case auth::VerificationPolicy::ACCEPT: {
- if (reassembly && !reassembly_->reassembleUnverified()) {
- reassembly_->reassemble(content_object);
- }
- break;
- }
- case auth::VerificationPolicy::DROP: {
- transport_->onPacketDropped(
- interest, content_object,
- make_error_code(protocol_error::verification_failed));
- break;
- }
- case auth::VerificationPolicy::ABORT: {
- transport_->onContentReassembled(
- make_error_code(protocol_error::session_aborted));
- break;
- }
- case auth::VerificationPolicy::UNKNOWN: {
- if (reassembly && reassembly_->reassembleUnverified()) {
- reassembly_->reassemble(content_object);
- }
- }
- }
-}
-
-uint32_t ManifestIncrementalIndexer::checkNextSuffix() {
- return suffix_strategy_->getNextSuffix();
+uint32_t ManifestIncrementalIndexer::checkNextSuffix() const {
+ return suffix_strategy_->checkNextSuffix();
}
uint32_t ManifestIncrementalIndexer::getNextSuffix() {
auto ret = suffix_strategy_->getNextSuffix();
if (ret <= suffix_strategy_->getFinalSuffix() &&
- ret != utils::SuffixStrategy::INVALID_SUFFIX) {
+ ret != utils::SuffixStrategy::MAX_SUFFIX) {
suffix_queue_.push(ret);
return ret;
}
@@ -208,7 +172,7 @@ uint32_t ManifestIncrementalIndexer::getNextSuffix() {
return Indexer::invalid_index;
}
-uint32_t ManifestIncrementalIndexer::getFinalSuffix() {
+uint32_t ManifestIncrementalIndexer::getFinalSuffix() const {
return suffix_strategy_->getFinalSuffix();
}
diff --git a/libtransport/src/protocols/manifest_incremental_indexer_bytestream.h b/libtransport/src/protocols/manifest_incremental_indexer_bytestream.h
index d8cf5892f..8527b55c1 100644
--- a/libtransport/src/protocols/manifest_incremental_indexer_bytestream.h
+++ b/libtransport/src/protocols/manifest_incremental_indexer_bytestream.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -39,8 +39,7 @@ class ManifestIncrementalIndexer : public IncrementalIndexer {
ManifestIncrementalIndexer(IncrementalIndexer &&indexer)
: IncrementalIndexer(std::move(indexer)),
suffix_strategy_(utils::SuffixStrategyFactory::getSuffixStrategy(
- core::NextSegmentCalculationStrategy::INCREMENTAL,
- next_download_suffix_, 0)) {
+ utils::NextSuffixStrategy::INCREMENTAL, next_download_suffix_)) {
for (uint32_t i = first_suffix_; i < next_download_suffix_; i++) {
suffix_queue_.push(i);
}
@@ -54,7 +53,7 @@ class ManifestIncrementalIndexer : public IncrementalIndexer {
core::ContentObject &content_object,
bool reassembly) override;
- uint32_t checkNextSuffix() override;
+ uint32_t checkNextSuffix() const override;
uint32_t getNextSuffix() override;
@@ -62,7 +61,7 @@ class ManifestIncrementalIndexer : public IncrementalIndexer {
bool isFinalSuffixDiscovered() override;
- uint32_t getFinalSuffix() override;
+ uint32_t getFinalSuffix() const override;
protected:
std::unique_ptr<utils::SuffixStrategy> suffix_strategy_;
@@ -77,14 +76,11 @@ class ManifestIncrementalIndexer : public IncrementalIndexer {
core::ContentObject &content_object,
bool reassembly);
void processTrustedManifest(core::Interest &interest,
- std::unique_ptr<ContentObjectManifest> manifest,
+ core::ContentObjectManifest &manifest,
bool reassembly);
void onUntrustedContentObject(core::Interest &interest,
core::ContentObject &content_object,
bool reassembly);
- void applyPolicy(core::Interest &interest,
- core::ContentObject &content_object, bool reassembly,
- auth::VerificationPolicy policy);
};
} // end namespace protocol
diff --git a/libtransport/src/protocols/prod_protocol_bytestream.cc b/libtransport/src/protocols/prod_protocol_bytestream.cc
index f659cb37c..7f103e12b 100644
--- a/libtransport/src/protocols/prod_protocol_bytestream.cc
+++ b/libtransport/src/protocols/prod_protocol_bytestream.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -29,12 +29,7 @@ ByteStreamProductionProtocol::ByteStreamProductionProtocol(
implementation::ProducerSocket *icn_socket)
: ProductionProtocol(icn_socket) {}
-ByteStreamProductionProtocol::~ByteStreamProductionProtocol() {
- stop();
- if (listening_thread_.joinable()) {
- listening_thread_.join();
- }
-}
+ByteStreamProductionProtocol::~ByteStreamProductionProtocol() { stop(); }
uint32_t ByteStreamProductionProtocol::produceDatagram(
const Name &content_name, std::unique_ptr<utils::MemBuf> &&buffer) {
@@ -68,16 +63,16 @@ uint32_t ByteStreamProductionProtocol::produceStream(
return 0;
}
- Name name(content_name);
-
- // Get the atomic variables to ensure they keep the same value
- // during the production
-
// Total size of the data packet
uint32_t data_packet_size;
socket_->getSocketOption(GeneralTransportOptions::DATA_PACKET_SIZE,
data_packet_size);
+ // Maximum size of a segment
+ uint32_t max_segment_size;
+ socket_->getSocketOption(GeneralTransportOptions::MAX_SEGMENT_SIZE,
+ max_segment_size);
+
// Expiry time
uint32_t content_object_expiry_time;
socket_->getSocketOption(GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
@@ -88,106 +83,95 @@ uint32_t ByteStreamProductionProtocol::produceStream(
socket_->getSocketOption(GeneralTransportOptions::HASH_ALGORITHM, hash_algo);
// Suffix calculation strategy
- core::NextSegmentCalculationStrategy _suffix_strategy;
+ std::shared_ptr<utils::SuffixStrategy> suffix_strategy;
socket_->getSocketOption(GeneralTransportOptions::SUFFIX_STRATEGY,
- _suffix_strategy);
- auto suffix_strategy = utils::SuffixStrategyFactory::getSuffixStrategy(
- _suffix_strategy, start_offset);
+ suffix_strategy);
+ suffix_strategy->reset(start_offset);
+
+ // Default format
+ core::Packet::Format default_format;
+ socket_->getSocketOption(GeneralTransportOptions::PACKET_FORMAT,
+ default_format);
- auto buffer_size = buffer->length();
+ Name name(content_name);
+ size_t buffer_size = buffer->length();
+ size_t signature_length = signer_->getSignatureFieldSize();
+ uint32_t final_block_number = start_offset;
+
+ // Content-related
+ core::Packet::Format content_format;
+ uint32_t content_header_size;
+ uint64_t content_free_space;
+ uint32_t nb_segments;
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;
+ // Manifest-related
+ core::Packet::Format manifest_format;
+ uint32_t manifest_header_size;
+ uint64_t manifest_free_space;
+ uint32_t nb_manifests;
std::shared_ptr<core::ContentObjectManifest> manifest;
+ uint32_t manifest_capacity = manifest_max_capacity_;
bool is_last_manifest = false;
-
- // TODO Manifest may still be used for indexing
- if (making_manifest_ && !signer_) {
- LOG(FATAL) << "Making manifests without setting producer identity.";
+ ParamsBytestream transport_params;
+
+ manifest_format = Packet::toAHFormat(default_format);
+ content_format = !manifest_max_capacity_ ? Packet::toAHFormat(default_format)
+ : default_format;
+
+ content_header_size = (uint32_t)core::Packet::getHeaderSizeFromFormat(
+ content_format, signature_length);
+ manifest_header_size = (uint32_t)core::Packet::getHeaderSizeFromFormat(
+ manifest_format, signature_length);
+ content_free_space =
+ std::min(max_segment_size, data_packet_size - content_header_size);
+ manifest_free_space =
+ std::min(max_segment_size, data_packet_size - manifest_header_size);
+
+ // Compute the number of segments the data will be split into
+ nb_segments =
+ uint32_t(std::ceil(double(buffer_size) / double(content_free_space)));
+ if (content_free_space * nb_segments < buffer_size) {
+ nb_segments++;
}
- core::Packet::Format hf_format = core::Packet::Format::HF_UNSPEC;
- core::Packet::Format hf_format_ah = core::Packet::Format::HF_UNSPEC;
-
- if (name.getType() == HNT_CONTIGUOUS_V4 || 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 (name.getType() == HNT_CONTIGUOUS_V6 ||
- 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_->getSignatureFieldSize() : 0);
- } else if (signer_) {
- format = hf_format_ah;
- signature_length = signer_->getSignatureFieldSize();
- }
+ if (manifest_max_capacity_) {
+ nb_manifests = static_cast<uint32_t>(
+ std::ceil(float(nb_segments) / manifest_capacity));
+ final_block_number += nb_segments + nb_manifests - 1;
+ transport_params.final_segment =
+ is_last ? final_block_number : utils::SuffixStrategy::MAX_SUFFIX;
- 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(
+ manifest = ContentObjectManifest::createContentManifest(
+ manifest_format,
name.setSuffix(suffix_strategy->getNextManifestSuffix()),
- core::ManifestVersion::VERSION_1, core::ManifestType::INLINE_MANIFEST,
- hash_algo, is_last_manifest, name, _suffix_strategy,
- signer_ ? signer_->getSignatureFieldSize() : 0));
- manifest->setLifetime(content_object_expiry_time);
-
- if (is_last) {
- manifest->setFinalBlockNumber(final_block_number);
- } else {
- manifest->setFinalBlockNumber(utils::SuffixStrategy::INVALID_SUFFIX);
- }
+ signature_length);
+ manifest->setHeaders(core::ManifestType::INLINE_MANIFEST,
+ manifest_max_capacity_, hash_algo, is_last_manifest,
+ name);
+ manifest->setParamsBytestream(transport_params);
+ manifest->getPacket()->setLifetime(content_object_expiry_time);
}
- 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) {
+ auto self = shared_from_this();
+ for (unsigned int packaged_segments = 0; packaged_segments < nb_segments;
+ packaged_segments++) {
+ if (manifest_max_capacity_) {
+ if (manifest->Encoder::manifestSize(1) > manifest_free_space) {
manifest->encode();
+ auto manifest_co =
+ std::dynamic_pointer_cast<ContentObject>(manifest->getPacket());
- // If identity set, sign manifest
- if (signer_) {
- signer_->signPacket(manifest.get());
- }
+ signer_->signPacket(manifest_co.get());
// Send the current manifest
- passContentObjectToCallbacks(manifest);
-
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send manifest " << manifest->getName();
+ passContentObjectToCallbacks(manifest_co, self);
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Send manifest " << manifest_co->getName();
// Send content objects stored in the queue
while (!content_queue_.empty()) {
- passContentObjectToCallbacks(content_queue_.front());
+ passContentObjectToCallbacks(content_queue_.front(), self);
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Send content " << content_queue_.front()->getName();
content_queue_.pop();
@@ -195,86 +179,87 @@ uint32_t ByteStreamProductionProtocol::produceStream(
// 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(
+ // safely release this reference.
+ manifest = ContentObjectManifest::createContentManifest(
+ manifest_format,
name.setSuffix(suffix_strategy->getNextManifestSuffix()),
- core::ManifestVersion::VERSION_1,
- core::ManifestType::INLINE_MANIFEST, hash_algo, is_last_manifest,
- name, _suffix_strategy,
- signer_ ? signer_->getSignatureFieldSize() : 0));
-
- manifest->setLifetime(content_object_expiry_time);
- manifest->setFinalBlockNumber(
- is_last ? final_block_number
- : utils::SuffixStrategy::INVALID_SUFFIX);
+ signature_length);
+ manifest->setHeaders(core::ManifestType::INLINE_MANIFEST,
+ manifest_max_capacity_, hash_algo,
+ is_last_manifest, name);
+ manifest->setParamsBytestream(transport_params);
+ manifest->getPacket()->setLifetime(content_object_expiry_time);
}
}
- auto content_suffix = suffix_strategy->getNextContentSuffix();
+ // Create content object
+ uint32_t content_suffix = suffix_strategy->getNextContentSuffix();
auto content_object = std::make_shared<ContentObject>(
- name.setSuffix(content_suffix), format,
- signer_ && !making_manifest_ ? signer_->getSignatureFieldSize() : 0);
+ name.setSuffix(content_suffix), content_format,
+ !manifest_max_capacity_ ? signature_length : 0);
content_object->setLifetime(content_object_expiry_time);
auto b = buffer->cloneOne();
- b->trimStart(free_space_for_content * packaged_segments);
+ b->trimStart(content_free_space * packaged_segments);
b->trimEnd(b->length());
- if (TRANSPORT_EXPECT_FALSE(packaged_segments == number_of_segments - 1)) {
+ // Segment the input data
+ if (TRANSPORT_EXPECT_FALSE(packaged_segments == nb_segments - 1)) {
b->append(buffer_size - bytes_segmented);
bytes_segmented += (int)(buffer_size - bytes_segmented);
- if (is_last && making_manifest_) {
+ if (is_last && manifest_max_capacity_) {
is_last_manifest = true;
} else if (is_last) {
- content_object->setRst();
+ content_object->setLast();
}
} else {
- b->append(free_space_for_content);
- bytes_segmented += (int)(free_space_for_content);
+ b->append(content_free_space);
+ bytes_segmented += (int)(content_free_space);
}
+ // Set the segmented data as payload
content_object->appendPayload(std::move(b));
- if (making_manifest_) {
- using namespace std::chrono_literals;
+ // Either we sign the content object or we save its hash into the current
+ // manifest
+ if (manifest_max_capacity_) {
auth::CryptoHash hash = content_object->computeDigest(hash_algo);
- manifest->addSuffixHash(content_suffix, hash);
+ manifest->addEntry(content_suffix, hash);
content_queue_.push(content_object);
} else {
- if (signer_) {
- signer_->signPacket(content_object.get());
- }
- passContentObjectToCallbacks(content_object);
+ signer_->signPacket(content_object.get());
+ passContentObjectToCallbacks(content_object, self);
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Send content " << content_object->getName();
}
}
- if (making_manifest_) {
+ // We send the manifest that hasn't been fully filled yet
+ if (manifest_max_capacity_) {
if (is_last_manifest) {
- manifest->setFinalManifest(is_last_manifest);
+ manifest->setIsLast(is_last_manifest);
}
manifest->encode();
+ auto manifest_co =
+ std::dynamic_pointer_cast<ContentObject>(manifest->getPacket());
- if (signer_) {
- signer_->signPacket(manifest.get());
- }
+ signer_->signPacket(manifest_co.get());
- passContentObjectToCallbacks(manifest);
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send manifest " << manifest->getName();
+ passContentObjectToCallbacks(manifest_co, self);
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send manifest " << manifest_co->getName();
while (!content_queue_.empty()) {
- passContentObjectToCallbacks(content_queue_.front());
+ passContentObjectToCallbacks(content_queue_.front(), self);
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Send content " << content_queue_.front()->getName();
content_queue_.pop();
}
}
- portal_->getIoService().post([this]() {
+ portal_->getThread().add([this, self]() {
std::shared_ptr<ContentObject> co;
while (object_queue_for_callbacks_.pop(co)) {
if (*on_new_segment_) {
@@ -296,7 +281,7 @@ uint32_t ByteStreamProductionProtocol::produceStream(
}
});
- portal_->getIoService().dispatch([this, buffer_size]() {
+ portal_->getThread().add([this, buffer_size, self]() {
if (*on_content_produced_) {
on_content_produced_->operator()(*socket_->getInterface(),
std::make_error_code(std::errc(0)),
@@ -307,9 +292,10 @@ uint32_t ByteStreamProductionProtocol::produceStream(
return suffix_strategy->getTotalCount();
}
-void ByteStreamProductionProtocol::scheduleSendBurst() {
- portal_->getIoService().post([this]() {
- std::shared_ptr<ContentObject> co;
+void ByteStreamProductionProtocol::scheduleSendBurst(
+ const std::shared_ptr<ByteStreamProductionProtocol> &self) {
+ portal_->getThread().add([this, self]() {
+ ContentObject::Ptr co;
for (uint32_t i = 0; i < burst_size; i++) {
if (object_queue_for_callbacks_.pop(co)) {
@@ -321,11 +307,15 @@ void ByteStreamProductionProtocol::scheduleSendBurst() {
on_content_object_to_sign_->operator()(*socket_->getInterface(), *co);
}
+ output_buffer_.insert(co);
+
if (*on_content_object_in_output_buffer_) {
on_content_object_in_output_buffer_->operator()(
*socket_->getInterface(), *co);
}
+ portal_->sendContentObject(*co);
+
if (*on_content_object_output_) {
on_content_object_output_->operator()(*socket_->getInterface(), *co);
}
@@ -337,13 +327,12 @@ void ByteStreamProductionProtocol::scheduleSendBurst() {
}
void ByteStreamProductionProtocol::passContentObjectToCallbacks(
- const std::shared_ptr<ContentObject> &content_object) {
- output_buffer_.insert(content_object);
- portal_->sendContentObject(*content_object);
+ const std::shared_ptr<ContentObject> &content_object,
+ const std::shared_ptr<ByteStreamProductionProtocol> &self) {
object_queue_for_callbacks_.push(std::move(content_object));
if (object_queue_for_callbacks_.size() >= burst_size) {
- scheduleSendBurst();
+ scheduleSendBurst(self);
}
}
@@ -376,7 +365,5 @@ void ByteStreamProductionProtocol::onInterest(Interest &interest) {
}
}
-void ByteStreamProductionProtocol::onError(std::error_code ec) {}
-
} // namespace protocol
} // end namespace transport
diff --git a/libtransport/src/protocols/prod_protocol_bytestream.h b/libtransport/src/protocols/prod_protocol_bytestream.h
index cf36b90a5..809ad8d5c 100644
--- a/libtransport/src/protocols/prod_protocol_bytestream.h
+++ b/libtransport/src/protocols/prod_protocol_bytestream.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -50,16 +50,19 @@ class ByteStreamProductionProtocol : public ProductionProtocol {
uint32_t produceDatagram(const Name &content_name, const uint8_t *buffer,
size_t buffer_size) override;
+ auto shared_from_this() { return utils::shared_from(this); }
+
protected:
// Consumer Callback
// void reset() override;
void onInterest(core::Interest &i) override;
- void onError(std::error_code ec) override;
private:
void passContentObjectToCallbacks(
- const std::shared_ptr<ContentObject> &content_object);
- void scheduleSendBurst();
+ const std::shared_ptr<ContentObject> &content_object,
+ const std::shared_ptr<ByteStreamProductionProtocol> &self);
+ void scheduleSendBurst(
+ const std::shared_ptr<ByteStreamProductionProtocol> &self);
private:
// While manifests are being built, contents are stored in a queue
diff --git a/libtransport/src/protocols/prod_protocol_rtc.cc b/libtransport/src/protocols/prod_protocol_rtc.cc
index cdc882d81..83cd23ac6 100644
--- a/libtransport/src/protocols/prod_protocol_rtc.cc
+++ b/libtransport/src/protocols/prod_protocol_rtc.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,15 +13,21 @@
* limitations under the License.
*/
+#include <glog/logging.h>
#include <hicn/transport/core/global_object_pool.h>
#include <implementation/socket_producer.h>
#include <protocols/prod_protocol_rtc.h>
+#include <protocols/rtc/probe_handler.h>
#include <protocols/rtc/rtc_consts.h>
#include <stdlib.h>
#include <time.h>
#include <unordered_set>
+extern "C" {
+#include <hicn/util/bitmap.h>
+}
+
namespace transport {
namespace protocol {
@@ -31,117 +37,144 @@ RTCProductionProtocol::RTCProductionProtocol(
implementation::ProducerSocket *icn_socket)
: ProductionProtocol(icn_socket),
current_seg_(1),
+ prev_produced_bytes_(0),
+ prev_produced_packets_(0),
produced_bytes_(0),
produced_packets_(0),
- produced_fec_packets_(0),
- max_packet_production_(1),
- bytes_production_rate_(0),
+ max_packet_production_(UINT32_MAX),
+ bytes_production_rate_(UINT32_MAX),
packets_production_rate_(0),
- fec_packets_production_rate_(0),
- last_round_(std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count()),
+ last_produced_data_ts_(0),
+ last_round_(utils::SteadyTime::nowMs().count()),
allow_delayed_nacks_(false),
- queue_timer_on_(false),
- consumer_in_sync_(false),
- on_consumer_in_sync_(nullptr) {
- srand((unsigned int)time(NULL));
- prod_label_ = rand() % 256;
+ pending_fec_pace_(false),
+ max_len_(0),
+ queue_len_(0),
+ data_aggregation_(true),
+ data_aggregation_timer_switch_(false) {
+ std::uniform_int_distribution<> dis(0, 255);
+ prod_label_ = dis(gen_);
cache_label_ = (prod_label_ + 1) % 256;
- interests_queue_timer_ =
- std::make_unique<asio::steady_timer>(portal_->getIoService());
- round_timer_ = std::make_unique<asio::steady_timer>(portal_->getIoService());
+ round_timer_ =
+ std::make_unique<asio::steady_timer>(portal_->getThread().getIoService());
+ fec_pacing_timer_ =
+ std::make_unique<asio::steady_timer>(portal_->getThread().getIoService());
+ app_packets_timer_ =
+ std::make_unique<asio::steady_timer>(portal_->getThread().getIoService());
setOutputBufferSize(10000);
- scheduleRoundTimer();
+}
+
+RTCProductionProtocol::~RTCProductionProtocol() {}
+
+void RTCProductionProtocol::setProducerParam() {
+ // Flow name: here we assume there is only one prefix registered in the portal
+ flow_name_ = portal_->getServedNamespaces().begin()->makeName();
+
+ // Default format
+ core::Packet::Format default_format;
+ socket_->getSocketOption(interface::GeneralTransportOptions::PACKET_FORMAT,
+ default_format);
// FEC
using namespace std::placeholders;
enableFEC(std::bind(&RTCProductionProtocol::onFecPackets, this, _1),
std::bind(&RTCProductionProtocol::getBuffer, this, _1));
-}
-RTCProductionProtocol::~RTCProductionProtocol() {}
-
-void RTCProductionProtocol::registerNamespaceWithNetwork(
- const Prefix &producer_namespace) {
- ProductionProtocol::registerNamespaceWithNetwork(producer_namespace);
-
- flow_name_ = producer_namespace.getName();
- auto family = flow_name_.getAddressFamily();
-
- switch (family) {
- case AF_INET6:
- data_header_size_ =
- signer_ && !making_manifest_
- ? (uint32_t)Packet::getHeaderSizeFromFormat(
- HF_INET6_TCP_AH, signer_->getSignatureFieldSize())
- : (uint32_t)Packet::getHeaderSizeFromFormat(HF_INET6_TCP);
- ;
- break;
- case AF_INET:
- data_header_size_ =
- signer_ && !making_manifest_
- ? (uint32_t)Packet::getHeaderSizeFromFormat(
- HF_INET_TCP_AH, signer_->getSignatureFieldSize())
- : (uint32_t)Packet::getHeaderSizeFromFormat(HF_INET_TCP);
- break;
- default:
- throw errors::RuntimeException("Unknown name format.");
- }
+ // Aggregated data
+ socket_->getSocketOption(interface::RtcTransportOptions::AGGREGATED_DATA,
+ data_aggregation_);
+
+ size_t signature_size = signer_->getSignatureFieldSize();
+ data_header_format_ = {!manifest_max_capacity_
+ ? Packet::toAHFormat(default_format)
+ : default_format,
+ !manifest_max_capacity_ ? signature_size : 0};
+ manifest_header_format_ = {Packet::toAHFormat(default_format),
+ signature_size};
+ nack_header_format_ = {Packet::toAHFormat(default_format), signature_size};
+ fec_header_format_ = {Packet::toAHFormat(default_format), signature_size};
+
+ // Initialize verifier for aggregated interests
+ std::shared_ptr<auth::Verifier> verifier;
+ socket_->getSocketOption(implementation::GeneralTransportOptions::VERIFIER,
+ verifier);
+ verifier_ = std::make_shared<rtc::RTCVerifier>(verifier, 0, 0);
+
+ // Schedule round timer
+ scheduleRoundTimer();
}
void RTCProductionProtocol::scheduleRoundTimer() {
round_timer_->expires_from_now(
std::chrono::milliseconds(rtc::PRODUCER_STATS_INTERVAL));
- round_timer_->async_wait([this](std::error_code ec) {
+ std::weak_ptr<RTCProductionProtocol> self = shared_from_this();
+ round_timer_->async_wait([self](const std::error_code &ec) {
if (ec) return;
- updateStats();
+
+ auto sp = self.lock();
+ if (sp && sp->isRunning()) {
+ sp->updateStats(true);
+ }
});
}
-void RTCProductionProtocol::updateStats() {
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+void RTCProductionProtocol::updateStats(bool new_round) {
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint64_t duration = now - last_round_;
- if (duration == 0) duration = 1;
+ if (!new_round) {
+ duration += rtc::PRODUCER_STATS_INTERVAL;
+ } else {
+ prev_produced_bytes_ = 0;
+ prev_produced_packets_ = 0;
+ }
+
double per_second = rtc::MILLI_IN_A_SEC / duration;
uint32_t prev_packets_production_rate = packets_production_rate_;
- bytes_production_rate_ = ceil((double)produced_bytes_ * per_second);
- packets_production_rate_ = ceil((double)produced_packets_ * per_second);
- fec_packets_production_rate_ =
- ceil((double)produced_fec_packets_ * per_second);
-
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "Updating production rate: produced_bytes_ = " << produced_bytes_
- << " bps = " << bytes_production_rate_;
+ // bytes_production_rate_ does not take into account FEC!!! this is because
+ // each client requests a differen amount of FEC packet so the client itself
+ // increase the production rate in the right way
+ bytes_production_rate_ =
+ ceil((double)(produced_bytes_ + prev_produced_bytes_) * per_second);
+ packets_production_rate_ =
+ ceil((double)(produced_packets_ + prev_produced_packets_) * per_second);
+
+ if (fec_encoder_ && fec_type_ != fec::FECType::UNKNOWN) {
+ // add fec packets looking at the fec code. we don't use directly the number
+ // of fec packets produced in 1 round because it may happen that different
+ // numbers of blocks are generated during the rounds and this creates
+ // inconsistencies in the estimation of the production rate
+ uint32_t k = fec::FECUtils::getSourceSymbols(fec_type_);
+ uint32_t n = fec::FECUtils::getBlockSymbols(fec_type_);
+
+ packets_production_rate_ +=
+ ceil((double)packets_production_rate_ / (double)k) * (n - k);
+ }
// update the production rate as soon as it increases by 10% with respect to
// the last round
max_packet_production_ =
- produced_packets_ + ceil((double)produced_packets_ * 0.1);
+ produced_packets_ + ceil((double)produced_packets_ * 0.10);
if (max_packet_production_ < rtc::WIN_MIN)
max_packet_production_ = rtc::WIN_MIN;
- if (packets_production_rate_ != 0) {
- allow_delayed_nacks_ = false;
- } else if (prev_packets_production_rate == 0) {
- // at least 2 rounds with production rate = 0
+ if (packets_production_rate_ <= rtc::MIN_PRODUCTION_RATE ||
+ prev_packets_production_rate <= rtc::MIN_PRODUCTION_RATE) {
allow_delayed_nacks_ = true;
+ } else {
+ // at least 2 rounds with enough packets
+ allow_delayed_nacks_ = false;
}
- // check if the production rate is decreased. if yes send nacks if needed
- if (prev_packets_production_rate < packets_production_rate_) {
- sendNacksForPendingInterests();
+ if (new_round) {
+ prev_produced_bytes_ = produced_bytes_;
+ prev_produced_packets_ = produced_packets_;
+ produced_bytes_ = 0;
+ produced_packets_ = 0;
+ last_round_ = now;
+ scheduleRoundTimer();
}
-
- produced_bytes_ = 0;
- produced_packets_ = 0;
- produced_fec_packets_ = 0;
- last_round_ = now;
- scheduleRoundTimer();
}
uint32_t RTCProductionProtocol::produceStream(
@@ -164,75 +197,275 @@ void RTCProductionProtocol::produce(ContentObject &content_object) {
uint32_t RTCProductionProtocol::produceDatagram(
const Name &content_name, std::unique_ptr<utils::MemBuf> &&buffer) {
std::size_t buffer_size = buffer->length();
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Maybe Sending content object: " << content_name;
+
if (TRANSPORT_EXPECT_FALSE(buffer_size == 0)) return 0;
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Sending content object: " << content_name;
+
uint32_t data_packet_size;
socket_->getSocketOption(interface::GeneralTransportOptions::DATA_PACKET_SIZE,
data_packet_size);
-
- if (TRANSPORT_EXPECT_FALSE((buffer_size + data_header_size_ +
- rtc::DATA_HEADER_SIZE) > data_packet_size)) {
+ // this is a source packet but we check the fec header size of FEC packet in
+ // order to leave room for the header when FEC packets will be generated
+ uint32_t fec_header = 0;
+ if (fec_encoder_) fec_encoder_->getFecHeaderSize(true);
+ uint32_t headers_size =
+ (uint32_t)Packet::getHeaderSizeFromFormat(data_header_format_.first,
+ data_header_format_.second) +
+ rtc::DATA_HEADER_SIZE + fec_header;
+ if (TRANSPORT_EXPECT_FALSE((headers_size + buffer_size) > data_packet_size)) {
return 0;
}
+ if (!data_aggregation_) {
+ // if data aggregation is off emptyQueue will always return doing nothing
+ emptyQueue();
+
+ sendManifest(content_name);
+
+ // create content object
+ auto content_object =
+ core::PacketManager<>::getInstance().getPacket<ContentObject>(
+ data_header_format_.first, data_header_format_.second);
+
+ // add rtc header to the payload
+ struct rtc::data_packet_t header;
+ content_object->appendPayload((const uint8_t *)&header,
+ rtc::DATA_HEADER_SIZE);
+ content_object->appendPayload(buffer->data(), buffer->length());
+
+ // schedule actual sending on internal thread
+ portal_->getThread().tryRunHandlerNow(
+ [this, content_object{std::move(content_object)},
+ content_name]() mutable {
+ produceInternal(std::move(content_object), content_name);
+ });
+ } else {
+ // XXX here we assume that all the packets that we push to the queue have
+ // the same name
+ auto app_pkt = utils::MemBuf::copyBuffer(buffer->data(), buffer->length());
+ addPacketToQueue(std::move(app_pkt));
+ }
+
+ return 1;
+}
+
+void RTCProductionProtocol::addPacketToQueue(
+ std::unique_ptr<utils::MemBuf> &&buffer) {
+ std::size_t buffer_size = buffer->length();
+ if ((queue_len_ + buffer_size) > rtc::MAX_RTC_PAYLOAD_SIZE) {
+ emptyQueue(); // this should guaranty that the generated packet will never
+ // be larger than an MTU
+ }
+
+ waiting_app_packets_.push(std::move(buffer));
+ if (max_len_ < buffer_size) max_len_ = buffer_size;
+ queue_len_ += buffer_size;
+
+ if (waiting_app_packets_.size() >= rtc::MAX_AGGREGATED_PACKETS) {
+ emptyQueue();
+ }
+
+ if (waiting_app_packets_.size() >= 1 && !data_aggregation_timer_switch_) {
+ data_aggregation_timer_switch_ = true;
+ app_packets_timer_->expires_from_now(
+ std::chrono::milliseconds(rtc::AGGREGATED_PACKETS_TIMER));
+ std::weak_ptr<RTCProductionProtocol> self = shared_from_this();
+ app_packets_timer_->async_wait([self](const std::error_code &ec) {
+ if (ec) return;
+
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ if (!ptr->data_aggregation_timer_switch_) return;
+ ptr->emptyQueue();
+ }
+ });
+ }
+}
+
+void RTCProductionProtocol::emptyQueue() {
+ if (waiting_app_packets_.size() == 0) return; // queue is empty
+
+ Name n(flow_name_);
+
+ // cancel timer is scheduled
+ if (data_aggregation_timer_switch_) {
+ data_aggregation_timer_switch_ = false;
+ app_packets_timer_->cancel();
+ }
+
+ // send a manifest beforehand if the hash buffer if full
+ sendManifest(n);
+
+ // create content object
auto content_object =
core::PacketManager<>::getInstance().getPacket<ContentObject>(
- signer_ ? Format::HF_INET6_TCP_AH : Format::HF_INET6_TCP,
- signer_ ? signer_->getSignatureFieldSize() : 0);
+ data_header_format_.first, data_header_format_.second);
+
// add rtc header to the payload
struct rtc::data_packet_t header;
content_object->appendPayload((const uint8_t *)&header,
rtc::DATA_HEADER_SIZE);
- content_object->appendPayload(buffer->data(), buffer->length());
- // schedule actual sending on internal thread
- portal_->getIoService().dispatch([this,
- content_object{std::move(content_object)},
- content_name]() mutable {
- produceInternal(std::move(content_object), content_name);
+ // init aggregated header
+ rtc::AggrPktHeader hdr(
+ (uint8_t *)(content_object->getPayload()->data() + rtc::DATA_HEADER_SIZE),
+ max_len_, waiting_app_packets_.size());
+ uint32_t header_size = hdr.getHeaderLen();
+ content_object->append(header_size); // leave space for the aggregated header
+
+ uint8_t index = 0;
+ while (waiting_app_packets_.size() != 0) {
+ std::unique_ptr<utils::MemBuf> pkt =
+ std::move(waiting_app_packets_.front());
+ waiting_app_packets_.pop();
+ // XXX for the moment we have a single name, so this works, otherwise we
+ // need to do something else
+ hdr.addPacketToHeader(index, pkt->length());
+ // append packet
+ content_object->appendPayload(pkt->data(), pkt->length());
+ index++;
+ }
+
+ // reset queue values
+ max_len_ = 0;
+ queue_len_ = 0;
+
+ // the packet is ready we need to send it
+ portal_->getThread().tryRunHandlerNow(
+ [this, content_object{std::move(content_object)}, n]() mutable {
+ produceInternal(std::move(content_object), n);
+ });
+}
+
+void RTCProductionProtocol::sendManifest(const Name &name) {
+ if (!manifest_max_capacity_) {
+ return;
+ }
+
+ Name manifest_name = name;
+
+ // If there is not enough hashes to fill a manifest, return early
+ if (manifest_entries_.size() < manifest_max_capacity_) {
+ return;
+ }
+
+ // Create a new manifest
+ std::shared_ptr<core::ContentObjectManifest> manifest =
+ createManifest(manifest_name.setSuffix(current_seg_));
+ auto manifest_co =
+ std::dynamic_pointer_cast<ContentObject>(manifest->getPacket());
+
+ // Fill the manifest with packet hashes that were previously saved
+ uint32_t nb_entries;
+ for (nb_entries = 0; nb_entries < manifest_max_capacity_; ++nb_entries) {
+ if (manifest_entries_.empty()) {
+ break;
+ }
+ std::pair<uint32_t, auth::CryptoHash> front = manifest_entries_.front();
+ manifest->addEntry(front.first, front.second);
+ manifest_entries_.pop();
+ }
+
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Sending manifest " << manifest_co->getName().getSuffix()
+ << " of size " << nb_entries;
+
+ // Encode and send the manifest
+ manifest->encode();
+ portal_->getThread().tryRunHandlerNow(
+ [this, content_object{std::move(manifest_co)}, manifest_name]() mutable {
+ produceInternal(std::move(content_object), manifest_name);
+ });
+}
+
+std::shared_ptr<core::ContentObjectManifest>
+RTCProductionProtocol::createManifest(const Name &content_name) const {
+ Name name(content_name);
+
+ auth::CryptoHashType hash_algo;
+ socket_->getSocketOption(interface::GeneralTransportOptions::HASH_ALGORITHM,
+ hash_algo);
+
+ uint64_t now = utils::SteadyTime::nowMs().count();
+
+ // Create a new manifest
+ std::shared_ptr<core::ContentObjectManifest> manifest =
+ ContentObjectManifest::createContentManifest(
+ manifest_header_format_.first, name, manifest_header_format_.second);
+ manifest->setHeaders(core::ManifestType::INLINE_MANIFEST,
+ manifest_max_capacity_, hash_algo, false /* is_last */,
+ name);
+
+ // Set connection parameters
+ manifest->setParamsRTC(ParamsRTC{
+ .timestamp = now,
+ .prod_rate = bytes_production_rate_,
+ .prod_seg = current_seg_,
+ .fec_type = fec_type_,
});
- return 1;
+ return manifest;
}
void RTCProductionProtocol::produceInternal(
std::shared_ptr<ContentObject> &&content_object, const Name &content_name,
bool fec) {
+ uint64_t now = utils::SteadyTime::nowMs().count();
+
+ if (fec && (now - last_produced_data_ts_) < rtc::FEC_PACING_TIME) {
+ paced_fec_packets_.push(std::pair<uint64_t, ContentObject::Ptr>(
+ now, std::move(content_object)));
+ postponeFecPacket();
+ } else {
+ // need to check if there are FEC packets waiting to be sent
+ flushFecPkts(current_seg_);
+ producePktInternal(std::move(content_object), content_name, fec);
+ }
+}
+
+void RTCProductionProtocol::producePktInternal(
+ std::shared_ptr<ContentObject> &&content_object, const Name &content_name,
+ bool fec) {
+ bool is_manifest = content_object->getPayloadType() == PayloadType::MANIFEST;
+ uint64_t now = utils::SteadyTime::nowMs().count();
+
// set rtc header
- struct rtc::data_packet_t *data_pkt =
- (struct rtc::data_packet_t *)content_object->getPayload()->data();
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
- data_pkt->setTimestamp(now);
- data_pkt->setProductionRate(bytes_production_rate_);
+ if (!is_manifest) {
+ struct rtc::data_packet_t *data_pkt =
+ (struct rtc::data_packet_t *)content_object->getPayload()->data();
+ data_pkt->setTimestamp(now);
+ data_pkt->setProductionRate(bytes_production_rate_);
+ }
// set hicn stuff
Name n(content_name);
content_object->setName(n.setSuffix(current_seg_));
- content_object->setLifetime(500); // XXX this should be set by the APP
- content_object->setPathLabel(prod_label_);
- // sign packet
- if (signer_) {
- signer_->signPacket(content_object.get());
- }
+ uint32_t expiry_time = 0;
+ socket_->getSocketOption(
+ interface::GeneralTransportOptions::CONTENT_OBJECT_EXPIRY_TIME,
+ expiry_time);
+ if (expiry_time == interface::default_values::content_object_expiry_time)
+ expiry_time = 500; // the data expiration time should be set by the App. if
+ // the App does not specify it the default is 500ms
+ content_object->setLifetime(expiry_time);
+ content_object->setPathLabel(prod_label_);
// update stats
if (!fec) {
produced_bytes_ +=
content_object->headerSize() + content_object->payloadSize();
produced_packets_++;
- } else {
- produced_fec_packets_++;
}
- if (produced_packets_ >= max_packet_production_) {
+ if (!data_aggregation_ && produced_packets_ >= max_packet_production_) {
// in this case all the pending interests may be used to accomodate the
// sudden increase in the production rate. calling the updateStats we will
// notify all the clients
- round_timer_->cancel();
- updateStats();
+ updateStats(false);
}
DLOG_IF(INFO, VLOG_IS_ON(3))
@@ -240,8 +473,12 @@ void RTCProductionProtocol::produceInternal(
// pass packet to FEC encoder
if (fec_encoder_ && !fec) {
- fec_encoder_->onPacketProduced(
- *content_object, content_object->headerSize() + rtc::DATA_HEADER_SIZE);
+ uint32_t offset = is_manifest ? (uint32_t)content_object->headerSize()
+ : (uint32_t)content_object->headerSize() +
+ rtc::DATA_HEADER_SIZE;
+ uint32_t metadata = static_cast<uint32_t>(content_object->getPayloadType());
+
+ fec_encoder_->onPacketProduced(*content_object, offset, metadata);
}
output_buffer_.insert(content_object);
@@ -251,18 +488,15 @@ void RTCProductionProtocol::produceInternal(
*content_object);
}
- auto seq_it = seqs_map_.find(current_seg_);
- if (seq_it != seqs_map_.end()) {
- portal_->sendContentObject(*content_object);
- }
+ // TODO we may want to send FEC only if an interest is pending in the pit in
+ sendContentObject(content_object, false, fec);
if (*on_content_object_output_) {
on_content_object_output_->operator()(*socket_->getInterface(),
*content_object);
}
- // remove interests from the interest cache if it exists
- removeFromInterestQueue(current_seg_);
+ if (!fec) last_produced_data_ts_ = now;
// Update current segment
current_seg_ = (current_seg_ + 1) % rtc::MIN_PROBE_SEQ;
@@ -277,254 +511,169 @@ void RTCProductionProtocol::produceInternal(
}
}
-void RTCProductionProtocol::onInterest(Interest &interest) {
- if (*on_interest_input_) {
- on_interest_input_->operator()(*socket_->getInterface(), interest);
+void RTCProductionProtocol::flushFecPkts(uint32_t current_seq_num) {
+ // Currently we immediately send all the pending fec packets
+ // A pacing policy may be helpful, but we do not want to delay too much
+ // the packets at this moment.
+ while (paced_fec_packets_.size() > 0) {
+ producePktInternal(std::move(paced_fec_packets_.front().second), flow_name_,
+ true);
+ paced_fec_packets_.pop();
+ }
+ fec_pacing_timer_->cancel();
+ pending_fec_pace_ = false;
+ postponeFecPacket();
+}
+
+void RTCProductionProtocol::postponeFecPacket() {
+ if (paced_fec_packets_.size() == 0) return;
+ if (pending_fec_pace_) {
+ return;
}
- auto suffix = interest.firstSuffix();
- // numberOfSuffixes returns only the prefixes in the payalod
- // we add + 1 to count anche the seq in the name
- auto n_suffixes = interest.numberOfSuffixes() + 1;
- Name name = interest.getName();
- bool prev_consumer_state = consumer_in_sync_;
+ uint64_t produced_time = paced_fec_packets_.front().first;
+ uint64_t now = utils::SteadyTime::nowMs().count();
- for (uint32_t i = 0; i < n_suffixes; i++) {
- if (i > 0) {
- name.setSuffix(*(suffix + (i - 1)));
- }
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Received interest " << name;
+ uint64_t wait_time = 0;
+ if ((produced_time + rtc::FEC_PACING_TIME) > now)
+ wait_time = produced_time + rtc::FEC_PACING_TIME - now;
- const std::shared_ptr<ContentObject> content_object =
- output_buffer_.find(name);
+ fec_pacing_timer_->expires_from_now(std::chrono::milliseconds(wait_time));
+ pending_fec_pace_ = true;
- if (content_object) {
- if (*on_interest_satisfied_output_buffer_) {
- on_interest_satisfied_output_buffer_->operator()(
- *socket_->getInterface(), interest);
- }
+ std::weak_ptr<RTCProductionProtocol> self = shared_from_this();
+ fec_pacing_timer_->async_wait([self](const std::error_code &ec) {
+ if (ec) return;
- if (*on_content_object_output_) {
- on_content_object_output_->operator()(*socket_->getInterface(),
- *content_object);
- }
+ auto sp = self.lock();
+ if (sp && sp->isRunning()) {
+ if (!sp->pending_fec_pace_) return;
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "Send content %u (onInterest) " << content_object->getName();
- content_object->setPathLabel(cache_label_);
- portal_->sendContentObject(*content_object);
- } else {
- if (*on_interest_process_) {
- on_interest_process_->operator()(*socket_->getInterface(), interest);
+ if (sp->paced_fec_packets_.size() > 0) {
+ sp->producePktInternal(std::move(sp->paced_fec_packets_.front().second),
+ sp->flow_name_, true);
+ sp->paced_fec_packets_.pop();
}
- processInterest(name.getSuffix(), interest.getLifetime());
+ sp->pending_fec_pace_ = false;
+ sp->postponeFecPacket();
}
- }
-
- if (prev_consumer_state != consumer_in_sync_ && consumer_in_sync_)
- on_consumer_in_sync_(*socket_->getInterface(), interest);
+ });
}
-void RTCProductionProtocol::processInterest(uint32_t interest_seg,
- uint32_t lifetime) {
- if (interest_seg == 0) {
- // first packet from the consumer, reset sync state
- consumer_in_sync_ = false;
+void RTCProductionProtocol::onInterest(Interest &interest) {
+ if (*on_interest_input_) {
+ on_interest_input_->operator()(*socket_->getInterface(), interest);
}
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ if (!interest.isValid()) throw std::runtime_error("Bad interest format");
+ if (interest.hasManifest() &&
+ verifier_->verify(interest) != auth::VerificationPolicy::ACCEPT)
+ throw std::runtime_error("Interset manifest verification failed");
- if (interest_seg > rtc::MIN_PROBE_SEQ) {
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Received probe " << interest_seg;
- sendNack(interest_seg);
- return;
- }
-
- // if the production rate 0 use delayed nacks
- if (allow_delayed_nacks_ && interest_seg >= current_seg_) {
- uint64_t next_timer = ~0;
- if (!timers_map_.empty()) {
- next_timer = timers_map_.begin()->first;
- }
+ uint32_t *suffix = interest.firstSuffix();
+ uint32_t n_suffixes_in_manifest = interest.numberOfSuffixes();
+ hicn_uword *request_bitmap = interest.getRequestBitmap();
- uint64_t expiration = now + rtc::SENTINEL_TIMER_INTERVAL;
- addToInterestQueue(interest_seg, expiration);
-
- // here we have at least one interest in the queue, we need to start or
- // update the timer
- if (!queue_timer_on_) {
- // set timeout
- queue_timer_on_ = true;
- scheduleQueueTimer(timers_map_.begin()->first - now);
- } else {
- // re-schedule the timer because a new interest will expires sooner
- if (next_timer > timers_map_.begin()->first) {
- interests_queue_timer_->cancel();
- scheduleQueueTimer(timers_map_.begin()->first - now);
- }
- }
- return;
- }
+ Name name = interest.getName();
+ uint32_t pos = 0; // Position of current suffix in manifest
- if (queue_timer_on_) {
- // the producer is producing. Send nacks to packets that will expire before
- // the data production and remove the timer
- queue_timer_on_ = false;
- interests_queue_timer_->cancel();
- sendNacksForPendingInterests();
- }
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Received interest " << name << " (" << n_suffixes_in_manifest
+ << " suffixes in manifest)";
+
+ // Process the suffix in the interest header
+ // (first loop iteration), then suffixes in the manifest
+ do {
+ if (!interest.hasManifest() ||
+ bitmap_is_set_no_check(request_bitmap, pos)) {
+ const std::shared_ptr<ContentObject> content_object =
+ output_buffer_.find(name);
+
+ if (content_object) {
+ if (*on_interest_satisfied_output_buffer_) {
+ on_interest_satisfied_output_buffer_->operator()(
+ *socket_->getInterface(), interest);
+ }
- uint32_t max_gap = (uint32_t)floor(
- (double)((double)((double)lifetime *
- rtc::INTEREST_LIFETIME_REDUCTION_FACTOR /
- rtc::MILLI_IN_A_SEC) *
- (double)(packets_production_rate_ +
- fec_packets_production_rate_)));
+ if (*on_content_object_output_) {
+ on_content_object_output_->operator()(*socket_->getInterface(),
+ *content_object);
+ }
- if (interest_seg < current_seg_ || interest_seg > (max_gap + current_seg_)) {
- sendNack(interest_seg);
- } else {
- if (!consumer_in_sync_ && on_consumer_in_sync_) {
- // we consider the remote consumer to be in sync as soon as it covers 70%
- // of the production window with interests
- uint32_t perc = ceil((double)max_gap * 0.7);
- if (interest_seg > (perc + current_seg_)) {
- consumer_in_sync_ = true;
- // on_consumer_in_sync_(*socket_->getInterface(), interest);
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Send content %u (onInterest) " << content_object->getName();
+ content_object->setPathLabel(cache_label_);
+ sendContentObject(content_object);
+ } else {
+ if (*on_interest_process_) {
+ on_interest_process_->operator()(*socket_->getInterface(), interest);
+ }
+ processInterest(name.getSuffix(), interest.getLifetime());
}
}
- uint64_t expiration =
- now + floor((double)lifetime * rtc::INTEREST_LIFETIME_REDUCTION_FACTOR);
- addToInterestQueue(interest_seg, expiration);
- }
-}
-void RTCProductionProtocol::onError(std::error_code ec) {}
+ // Retrieve next suffix in the manifest
+ if (interest.hasManifest()) {
+ uint32_t seq = *suffix;
+ suffix++;
-void RTCProductionProtocol::scheduleQueueTimer(uint64_t wait) {
- interests_queue_timer_->expires_from_now(std::chrono::milliseconds(wait));
- interests_queue_timer_->async_wait([this](std::error_code ec) {
- if (ec) return;
- interestQueueTimer();
- });
+ name.setSuffix(seq);
+ interest.setName(name);
+ }
+ } while (pos++ < n_suffixes_in_manifest);
}
-void RTCProductionProtocol::addToInterestQueue(uint32_t interest_seg,
- uint64_t expiration) {
- // check if the seq number exists already
- auto it_seqs = seqs_map_.find(interest_seg);
- if (it_seqs != seqs_map_.end()) {
- // the seq already exists
- if (expiration < it_seqs->second) {
- // we need to update the timer becasue we got a smaller one
- // 1) remove the entry from the multimap
- // 2) update this entry
- auto range = timers_map_.equal_range(it_seqs->second);
- for (auto it_timers = range.first; it_timers != range.second;
- it_timers++) {
- if (it_timers->second == it_seqs->first) {
- timers_map_.erase(it_timers);
- break;
- }
- }
- timers_map_.insert(
- std::pair<uint64_t, uint32_t>(expiration, interest_seg));
- it_seqs->second = expiration;
- } else {
- // nothing to do here
+void RTCProductionProtocol::processInterest(uint32_t interest_seg,
+ uint32_t lifetime) {
+ switch (rtc::ProbeHandler::getProbeType(interest_seg)) {
+ case rtc::ProbeType::INIT:
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Received init probe " << interest_seg;
+ sendManifestProbe(interest_seg);
return;
- }
- } else {
- // add the new seq
- timers_map_.insert(std::pair<uint64_t, uint32_t>(expiration, interest_seg));
- seqs_map_.insert(std::pair<uint32_t, uint64_t>(interest_seg, expiration));
+ case rtc::ProbeType::RTT:
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Received RTT probe " << interest_seg;
+ sendNack(interest_seg);
+ return;
+ default:
+ break;
}
-}
-void RTCProductionProtocol::sendNacksForPendingInterests() {
- std::unordered_set<uint32_t> to_remove;
+ if (interest_seg < current_seg_) sendNack(interest_seg);
+}
- uint32_t packet_gap = 100000; // set it to a high value (100sec)
- if (packets_production_rate_ != 0)
- packet_gap = ceil(rtc::MILLI_IN_A_SEC / (double)packets_production_rate_);
+void RTCProductionProtocol::sendManifestProbe(uint32_t sequence) {
+ Name manifest_name(flow_name_);
+ manifest_name.setSuffix(sequence);
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ std::shared_ptr<core::ContentObjectManifest> manifest_probe =
+ createManifest(manifest_name);
+ auto manifest_probe_co =
+ std::dynamic_pointer_cast<ContentObject>(manifest_probe->getPacket());
- for (auto it = seqs_map_.begin(); it != seqs_map_.end(); it++) {
- if (it->first > current_seg_) {
- uint64_t production_time =
- ((it->first - current_seg_) * packet_gap) + now;
- if (production_time >= it->second) {
- sendNack(it->first);
- to_remove.insert(it->first);
- }
- }
- }
+ manifest_probe_co->setLifetime(0);
+ manifest_probe_co->setPathLabel(prod_label_);
+ manifest_probe->encode();
- // delete nacked interests
- for (auto it = to_remove.begin(); it != to_remove.end(); it++) {
- removeFromInterestQueue(*it);
- }
-}
-
-void RTCProductionProtocol::removeFromInterestQueue(uint32_t interest_seg) {
- auto seq_it = seqs_map_.find(interest_seg);
- if (seq_it != seqs_map_.end()) {
- auto range = timers_map_.equal_range(seq_it->second);
- for (auto it_timers = range.first; it_timers != range.second; it_timers++) {
- if (it_timers->second == seq_it->first) {
- timers_map_.erase(it_timers);
- break;
- }
- }
- seqs_map_.erase(seq_it);
+ if (*on_content_object_output_) {
+ on_content_object_output_->operator()(*socket_->getInterface(),
+ *manifest_probe_co);
}
-}
-void RTCProductionProtocol::interestQueueTimer() {
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
-
- for (auto it_timers = timers_map_.begin(); it_timers != timers_map_.end();) {
- uint64_t expire = it_timers->first;
- if (expire <= now) {
- uint32_t seq = it_timers->second;
- sendNack(seq);
- // remove the interest from the other map
- seqs_map_.erase(seq);
- it_timers = timers_map_.erase(it_timers);
- } else {
- // stop, we are done!
- break;
- }
- }
- if (timers_map_.empty()) {
- queue_timer_on_ = false;
- } else {
- queue_timer_on_ = true;
- scheduleQueueTimer(timers_map_.begin()->first - now);
- }
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send init probe " << sequence;
+ sendContentObject(manifest_probe_co, true, false);
}
void RTCProductionProtocol::sendNack(uint32_t sequence) {
auto nack = core::PacketManager<>::getInstance().getPacket<ContentObject>(
- signer_ ? Format::HF_INET6_TCP_AH : Format::HF_INET6_TCP,
- signer_ ? signer_->getSignatureFieldSize() : 0);
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ nack_header_format_.first, nack_header_format_.second);
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint32_t next_packet = current_seg_;
uint32_t prod_rate = bytes_production_rate_;
struct rtc::nack_packet_t header;
header.setTimestamp(now);
header.setProductionRate(prod_rate);
- header.setProductionSegement(next_packet);
+ header.setProductionSegment(next_packet);
nack->appendPayload((const uint8_t *)&header, rtc::NACK_HEADER_SIZE);
Name n(flow_name_);
@@ -533,33 +682,42 @@ void RTCProductionProtocol::sendNack(uint32_t sequence) {
nack->setLifetime(0);
nack->setPathLabel(prod_label_);
- if (signer_) {
- signer_->signPacket(nack.get());
+ if (*on_content_object_output_) {
+ on_content_object_output_->operator()(*socket_->getInterface(), *nack);
}
- if (!consumer_in_sync_ && on_consumer_in_sync_ &&
- sequence < rtc::MIN_PROBE_SEQ && sequence > next_packet) {
- consumer_in_sync_ = true;
- auto interest = core::PacketManager<>::getInstance().getPacket<Interest>();
- interest->setName(n);
- on_consumer_in_sync_(*socket_->getInterface(), *interest);
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send nack " << sequence;
+ sendContentObject(nack, true, false);
+}
+
+void RTCProductionProtocol::sendContentObject(
+ std::shared_ptr<ContentObject> content_object, bool nack, bool fec) {
+ bool is_ah = HICN_PACKET_FORMAT_IS_AH(content_object->getFormat());
+
+ // Compute signature
+ if (is_ah) {
+ signer_->signPacket(content_object.get());
}
- if (*on_content_object_output_) {
- on_content_object_output_->operator()(*socket_->getInterface(), *nack);
+ // Compute and save data packet digest
+ if (manifest_max_capacity_ && !is_ah) {
+ auth::CryptoHashType hash_algo;
+ socket_->getSocketOption(interface::GeneralTransportOptions::HASH_ALGORITHM,
+ hash_algo);
+ manifest_entries_.push({content_object->getName().getSuffix(),
+ content_object->computeDigest(hash_algo)});
}
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send nack " << sequence;
- portal_->sendContentObject(*nack);
+ portal_->sendContentObject(*content_object);
}
-void RTCProductionProtocol::onFecPackets(
- std::vector<std::pair<uint32_t, fec::buffer>> &packets) {
+void RTCProductionProtocol::onFecPackets(fec::BufferArray &packets) {
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Produced " << packets.size() << " FEC packets";
+
for (auto &packet : packets) {
auto content_object =
- std::static_pointer_cast<ContentObject>(packet.second);
+ std::static_pointer_cast<ContentObject>(packet.getBuffer());
content_object->prepend(content_object->headerSize() +
rtc::DATA_HEADER_SIZE);
pending_fec_packets_.push(std::move(content_object));
@@ -569,19 +727,21 @@ void RTCProductionProtocol::onFecPackets(
fec::buffer RTCProductionProtocol::getBuffer(std::size_t size) {
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Asked buffer for FEC symbol of size " << size;
+
auto ret = core::PacketManager<>::getInstance().getPacket<ContentObject>(
- signer_ ? Format::HF_INET6_TCP_AH : Format::HF_INET6_TCP,
- signer_ ? signer_->getSignatureFieldSize() : 0);
+ fec_header_format_.first, fec_header_format_.second);
+
ret->updateLength(rtc::DATA_HEADER_SIZE + size);
ret->append(rtc::DATA_HEADER_SIZE + size);
ret->trimStart(ret->headerSize() + rtc::DATA_HEADER_SIZE);
+
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Responding with buffer of length " << ret->length();
- assert(ret->length() >= size);
+ DCHECK(ret->length() >= size);
return ret;
}
} // namespace protocol
-} // end namespace transport
+} // namespace transport
diff --git a/libtransport/src/protocols/prod_protocol_rtc.h b/libtransport/src/protocols/prod_protocol_rtc.h
index 96ad5673d..285ccb646 100644
--- a/libtransport/src/protocols/prod_protocol_rtc.h
+++ b/libtransport/src/protocols/prod_protocol_rtc.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,6 +17,7 @@
#include <hicn/transport/core/name.h>
#include <protocols/production_protocol.h>
+#include <protocols/rtc/rtc_verifier.h>
#include <atomic>
#include <map>
@@ -32,6 +33,7 @@ class RTCProductionProtocol : public ProductionProtocol {
using ProductionProtocol::start;
using ProductionProtocol::stop;
+ void setProducerParam() override;
void produce(ContentObject &content_object) override;
uint32_t produceStream(const Name &content_name,
@@ -49,56 +51,69 @@ class RTCProductionProtocol : public ProductionProtocol {
buffer, buffer_size, buffer_size));
}
- void registerNamespaceWithNetwork(const Prefix &producer_namespace) override;
-
- void setConsumerInSyncCallback(
- interface::ProducerInterestCallback &&callback) {
- on_consumer_in_sync_ = std::move(callback);
- }
+ auto shared_from_this() { return utils::shared_from(this); }
private:
// packet handlers
void onInterest(Interest &interest) override;
- void onError(std::error_code ec) override;
+ void onError(const std::error_code &ec) override{};
void processInterest(uint32_t interest_seg, uint32_t lifetime);
+ void producePktInternal(std::shared_ptr<ContentObject> &&content_object,
+ const Name &content_name, bool fec = false);
void produceInternal(std::shared_ptr<ContentObject> &&content_object,
const Name &content_name, bool fec = false);
void sendNack(uint32_t sequence);
+ void sendContentObject(std::shared_ptr<ContentObject> content_object,
+ bool nac = false, bool fec = false);
+
+ // manifests
+ void sendManifestProbe(uint32_t sequence);
+ void sendManifest(const Name &content_name);
+ std::shared_ptr<core::ContentObjectManifest> createManifest(
+ const Name &name) const;
// stats
- void updateStats();
+ void updateStats(bool new_round);
void scheduleRoundTimer();
- // pending intersts functions
- void addToInterestQueue(uint32_t interest_seg, uint64_t expiration);
- void sendNacksForPendingInterests();
- void removeFromInterestQueue(uint32_t interest_seg);
- void scheduleQueueTimer(uint64_t wait);
- void interestQueueTimer();
-
// FEC functions
- void onFecPackets(std::vector<std::pair<uint32_t, fec::buffer>> &packets);
+ void onFecPackets(fec::BufferArray &packets);
fec::buffer getBuffer(std::size_t size);
+ void postponeFecPacket();
+ void dispatchFecPacket();
+ void flushFecPkts(uint32_t current_seq_num);
+ // aggregated data functions
+ void emptyQueue();
+ void addPacketToQueue(std::unique_ptr<utils::MemBuf> &&buffer);
core::Name flow_name_;
- uint32_t current_seg_; // seq id of the next packet produced
- uint32_t prod_label_; // path lable of the producer
- uint32_t cache_label_; // path lable for content from the producer cache
- uint16_t data_header_size_; // hicn data header size
+ std::pair<core::Packet::Format, size_t> data_header_format_;
+ std::pair<core::Packet::Format, size_t> manifest_header_format_;
+ std::pair<core::Packet::Format, size_t> fec_header_format_;
+ std::pair<core::Packet::Format, size_t> nack_header_format_;
+
+ uint32_t current_seg_; // seq id of the next packet produced
+ uint32_t prod_label_; // path label of the producer
+ uint32_t cache_label_; // path label for content from the producer cache
- uint32_t produced_bytes_; // bytes produced in the last round
- uint32_t produced_packets_; // packet produed in the last round
- uint32_t produced_fec_packets_; // fec packets produced last round
+ uint32_t prev_produced_bytes_; // XXX clearly explain all these new vars
+ uint32_t prev_produced_packets_;
+
+ uint32_t produced_bytes_; // bytes produced in the last round
+ uint32_t produced_packets_; // packet produed in the last round
uint32_t max_packet_production_; // never exceed this number of packets
// without update stats
- uint32_t bytes_production_rate_; // bytes per sec
- uint32_t packets_production_rate_; // pps
- uint32_t fec_packets_production_rate_; // pps
+ uint32_t bytes_production_rate_; // bytes per sec
+ uint32_t packets_production_rate_; // pps
+
+ uint64_t last_produced_data_ts_; // ms
std::unique_ptr<asio::steady_timer> round_timer_;
+ std::unique_ptr<asio::steady_timer> fec_pacing_timer_;
+
uint64_t last_round_;
// delayed nacks are used by the producer to avoid to send too
@@ -108,29 +123,26 @@ class RTCProductionProtocol : public ProductionProtocol {
// of the new rate.
bool allow_delayed_nacks_;
- // queue for the received interests
- // this map maps the expiration time of an interest to
- // its sequence number. the map is sorted by timeouts
- // the same timeout may be used for multiple sequence numbers
- // but for each sequence number we store only the smallest
- // expiry time. In this way the mapping from seqs_map_ to
- // timers_map_ is unique
- std::multimap<uint64_t, uint32_t> timers_map_;
-
- // this map does the opposite, this map is not ordered
- std::unordered_map<uint32_t, uint64_t> seqs_map_;
- bool queue_timer_on_;
- std::unique_ptr<asio::steady_timer> interests_queue_timer_;
-
- // this callback is called when the remote consumer is in sync with high
- // probability. it is called only the first time that the switch happen.
- // XXX this makes sense only in P2P mode, while in standard mode is
- // impossible to know the state of the consumers so it should not be used.
- bool consumer_in_sync_;
- interface::ProducerInterestCallback on_consumer_in_sync_;
-
// Save FEC packets here before sending them
std::queue<ContentObject::Ptr> pending_fec_packets_;
+ std::queue<std::pair<uint64_t, ContentObject::Ptr>> paced_fec_packets_;
+ bool pending_fec_pace_;
+
+ // Save application packets if they are small
+ std::queue<std::unique_ptr<utils::MemBuf>> waiting_app_packets_;
+ uint16_t max_len_; // len of the largest packet
+ uint16_t queue_len_; // total size of all packet in the queue
+ bool data_aggregation_; // turns on/off data aggregation
+ // timer to check the queue len
+ std::unique_ptr<asio::steady_timer> app_packets_timer_;
+ bool data_aggregation_timer_switch_; // bool to check if the timer is on
+
+ // Manifest
+ std::queue<std::pair<uint32_t, auth::CryptoHash>>
+ manifest_entries_; // map a packet suffix to a packet hash
+
+ // Verifier for aggregated interests
+ std::shared_ptr<rtc::RTCVerifier> verifier_;
};
} // namespace protocol
diff --git a/libtransport/src/protocols/production_protocol.cc b/libtransport/src/protocols/production_protocol.cc
index 6b317d47d..039a6a55a 100644
--- a/libtransport/src/protocols/production_protocol.cc
+++ b/libtransport/src/protocols/production_protocol.cc
@@ -24,8 +24,8 @@ using namespace interface;
ProductionProtocol::ProductionProtocol(
implementation::ProducerSocket *icn_socket)
- : socket_(icn_socket),
- is_running_(false),
+ : Protocol(),
+ socket_(icn_socket),
fec_encoder_(nullptr),
on_interest_input_(VOID_HANDLER),
on_interest_dropped_input_buffer_(VOID_HANDLER),
@@ -38,101 +38,92 @@ ProductionProtocol::ProductionProtocol(
on_content_object_output_(VOID_HANDLER),
on_content_object_evicted_from_output_buffer_(VOID_HANDLER),
on_content_produced_(VOID_HANDLER),
+ producer_callback_(VOID_HANDLER),
fec_type_(fec::FECType::UNKNOWN) {
socket_->getSocketOption(GeneralTransportOptions::PORTAL, portal_);
// TODO add statistics for producer
// socket_->getSocketOption(OtherOptions::STATISTICS, &stats_);
}
-ProductionProtocol::~ProductionProtocol() {
- if (!is_async_ && is_running_) {
- stop();
- }
+ProductionProtocol::~ProductionProtocol() {}
- if (listening_thread_.joinable()) {
- listening_thread_.join();
+int ProductionProtocol::start() {
+ if (isRunning()) {
+ return -1;
}
-}
-int ProductionProtocol::start() {
- socket_->getSocketOption(ProducerCallbacksOptions::INTEREST_INPUT,
- &on_interest_input_);
- socket_->getSocketOption(ProducerCallbacksOptions::INTEREST_DROP,
- &on_interest_dropped_input_buffer_);
- socket_->getSocketOption(ProducerCallbacksOptions::INTEREST_PASS,
- &on_interest_inserted_input_buffer_);
- socket_->getSocketOption(ProducerCallbacksOptions::CACHE_HIT,
- &on_interest_satisfied_output_buffer_);
- socket_->getSocketOption(ProducerCallbacksOptions::CACHE_MISS,
- &on_interest_process_);
- socket_->getSocketOption(ProducerCallbacksOptions::NEW_CONTENT_OBJECT,
- &on_new_segment_);
- socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_OBJECT_READY,
- &on_content_object_in_output_buffer_);
- socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_OBJECT_OUTPUT,
- &on_content_object_output_);
- socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_OBJECT_TO_SIGN,
- &on_content_object_to_sign_);
- socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_PRODUCED,
- &on_content_produced_);
-
- socket_->getSocketOption(GeneralTransportOptions::ASYNC_MODE, is_async_);
- socket_->getSocketOption(GeneralTransportOptions::SIGNER, signer_);
- socket_->getSocketOption(GeneralTransportOptions::MAKE_MANIFEST,
- making_manifest_);
-
- 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_->getThread().addAndWaitForExecution([this]() {
+ socket_->getSocketOption(ProducerCallbacksOptions::INTEREST_INPUT,
+ &on_interest_input_);
+ socket_->getSocketOption(ProducerCallbacksOptions::INTEREST_DROP,
+ &on_interest_dropped_input_buffer_);
+ socket_->getSocketOption(ProducerCallbacksOptions::INTEREST_PASS,
+ &on_interest_inserted_input_buffer_);
+ socket_->getSocketOption(ProducerCallbacksOptions::CACHE_HIT,
+ &on_interest_satisfied_output_buffer_);
+ socket_->getSocketOption(ProducerCallbacksOptions::CACHE_MISS,
+ &on_interest_process_);
+ socket_->getSocketOption(ProducerCallbacksOptions::NEW_CONTENT_OBJECT,
+ &on_new_segment_);
+ socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_OBJECT_READY,
+ &on_content_object_in_output_buffer_);
+ socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_OBJECT_OUTPUT,
+ &on_content_object_output_);
+ socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_OBJECT_TO_SIGN,
+ &on_content_object_to_sign_);
+ socket_->getSocketOption(ProducerCallbacksOptions::CONTENT_PRODUCED,
+ &on_content_produced_);
+ socket_->getSocketOption(ProducerCallbacksOptions::PRODUCER_CALLBACK,
+ &producer_callback_);
+
+ socket_->getSocketOption(GeneralTransportOptions::ASYNC_MODE, is_async_);
+ socket_->getSocketOption(GeneralTransportOptions::SIGNER, signer_);
+ socket_->getSocketOption(GeneralTransportOptions::MANIFEST_MAX_CAPACITY,
+ manifest_max_capacity_);
+
+ std::string fec_type_str = "";
+ socket_->getSocketOption(GeneralTransportOptions::FEC_TYPE, fec_type_str);
+ if (fec_type_str != "") {
+ fec_type_ = fec::FECUtils::fecTypeFromString(fec_type_str.c_str());
}
- }
- is_running_ = true;
+ portal_->registerTransportCallback(this);
+ setProducerParam();
- if (!is_async_) {
- listening_thread_ = std::thread([this]() { portal_->runEventsLoop(); });
- }
+ setRunning();
+ });
return 0;
}
-void ProductionProtocol::stop() {
- is_running_ = false;
-
- if (!is_async_) {
- portal_->stopEventsLoop();
- } else {
- portal_->clear();
- }
-}
-
void ProductionProtocol::produce(ContentObject &content_object) {
- if (*on_content_object_in_output_buffer_) {
- on_content_object_in_output_buffer_->operator()(*socket_->getInterface(),
- content_object);
- }
+ auto content_object_ptr = content_object.shared_from_this();
+ portal_->getThread().add([this, co = std::move(content_object_ptr)]() {
+ if (*on_content_object_in_output_buffer_) {
+ on_content_object_in_output_buffer_->operator()(*socket_->getInterface(),
+ *co);
+ }
- output_buffer_.insert(std::static_pointer_cast<ContentObject>(
- content_object.shared_from_this()));
+ output_buffer_.insert(co);
- if (*on_content_object_output_) {
- on_content_object_output_->operator()(*socket_->getInterface(),
- content_object);
- }
+ if (*on_content_object_output_) {
+ on_content_object_output_->operator()(*socket_->getInterface(), *co);
+ }
- portal_->sendContentObject(content_object);
+ portal_->sendContentObject(*co);
+ });
}
-void ProductionProtocol::registerNamespaceWithNetwork(
- const Prefix &producer_namespace) {
- served_namespaces_.push_back(producer_namespace);
+void ProductionProtocol::sendMapme() { portal_->sendMapme(); }
+
+void ProductionProtocol::onError(const std::error_code &ec) {
+ // Stop production protocol
+ stop();
+
+ // Call error callback
+ if (producer_callback_) {
+ producer_callback_->produceError(ec);
+ }
}
} // namespace protocol
diff --git a/libtransport/src/protocols/production_protocol.h b/libtransport/src/protocols/production_protocol.h
index 7366311eb..09718631f 100644
--- a/libtransport/src/protocols/production_protocol.h
+++ b/libtransport/src/protocols/production_protocol.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,6 +22,7 @@
#include <implementation/socket.h>
#include <protocols/fec_base.h>
#include <protocols/fec_utils.h>
+#include <protocols/protocol.h>
#include <utils/content_store.h>
#include <atomic>
@@ -33,17 +34,20 @@ namespace protocol {
using namespace core;
-class ProductionProtocol : public Portal::ProducerCallback {
+class ProductionProtocol
+ : public Protocol,
+ public std::enable_shared_from_this<ProductionProtocol> {
public:
ProductionProtocol(implementation::ProducerSocket *icn_socket);
virtual ~ProductionProtocol();
- bool isRunning() { return is_running_; }
-
virtual int start();
- virtual void stop();
+ using Protocol::stop;
+
+ virtual void setProducerParam(){};
virtual void produce(ContentObject &content_object);
+ virtual void sendMapme();
virtual uint32_t produceStream(const Name &content_name,
std::unique_ptr<utils::MemBuf> &&buffer,
bool is_last = true,
@@ -61,22 +65,21 @@ class ProductionProtocol : public Portal::ProducerCallback {
void setOutputBufferSize(std::size_t size) { output_buffer_.setLimit(size); }
std::size_t getOutputBufferSize() { return output_buffer_.getLimit(); }
- virtual void registerNamespaceWithNetwork(const Prefix &producer_namespace);
- const std::list<Prefix> &getNamespaces() const { return served_namespaces_; }
-
protected:
// Producer callback
virtual void onInterest(core::Interest &i) override = 0;
- virtual void onError(std::error_code ec) override{};
+ virtual void onError(const std::error_code &ec) override;
template <typename FECHandler, typename AllocatorHandler>
void enableFEC(FECHandler &&fec_handler,
AllocatorHandler &&allocator_handler) {
if (!fec_encoder_) {
// Try to get FEC from environment
- if (const char *fec_str = std::getenv("TRANSPORT_FEC_TYPE")) {
+ const char *fec_str = std::getenv("TRANSPORT_FEC_TYPE");
+ if (fec_str && (fec_type_ == fec::FECType::UNKNOWN)) {
LOG(INFO) << "Using FEC " << fec_str;
fec_type_ = fec::FECUtils::fecTypeFromString(fec_str);
+ CHECK(fec_type_ != fec::FECType::UNKNOWN);
}
if (fec_type_ == fec::FECType::UNKNOWN) {
@@ -95,11 +98,6 @@ class ProductionProtocol : public Portal::ProducerCallback {
// Thread pool responsible for IO operations (send data / receive interests)
std::vector<utils::EventThread> io_threads_;
-
- // TODO remove this thread
- std::thread listening_thread_;
- std::shared_ptr<Portal> portal_;
- std::atomic<bool> is_running_;
interface::ProductionStatistics *stats_;
std::unique_ptr<fec::ProducerFEC> fec_encoder_;
@@ -119,15 +117,14 @@ class ProductionProtocol : public Portal::ProducerCallback {
interface::ProducerContentCallback *on_content_produced_;
+ interface::ProducerSocket::Callback *producer_callback_;
+
// Output buffer
utils::ContentStore output_buffer_;
- // List ot routes served by current producer protocol
- std::list<Prefix> served_namespaces_;
-
// Signature and manifest
std::shared_ptr<auth::Signer> signer_;
- bool making_manifest_;
+ uint32_t manifest_max_capacity_;
bool is_async_;
fec::FECType fec_type_;
diff --git a/libtransport/src/protocols/protocol.h b/libtransport/src/protocols/protocol.h
new file mode 100644
index 000000000..a9f929db9
--- /dev/null
+++ b/libtransport/src/protocols/protocol.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <core/portal.h>
+#include <hicn/transport/errors/runtime_exception.h>
+#include <hicn/transport/utils/noncopyable.h>
+
+#include <random>
+
+namespace transport {
+
+namespace protocol {
+
+class Protocol : public core::Portal::TransportCallback, utils::NonCopyable {
+ public:
+ virtual void stop() {
+ portal_->getThread().addAndWaitForExecution([this]() {
+ unSetRunning();
+ portal_->unregisterTransportCallback();
+ portal_->clear();
+ });
+ }
+
+ virtual void onInterest(core::Interest &i) {
+ throw errors::RuntimeException("Not implemented");
+ }
+
+ virtual void onContentObject(core::Interest &i, core::ContentObject &c) {
+ throw errors::RuntimeException("Not implemented");
+ }
+
+ virtual void onTimeout(core::Interest::Ptr &i, const core::Name &n) {
+ throw errors::RuntimeException("Not implemented");
+ }
+
+ virtual void onError(const std::error_code &ec) {
+ throw errors::RuntimeException("Not implemented");
+ }
+
+ bool isRunning() { return is_running_; }
+ void setRunning() { is_running_ = true; }
+ void unSetRunning() { is_running_ = false; }
+
+ protected:
+ Protocol() : portal_(nullptr), is_running_(false), gen_(rd_()) {}
+ virtual ~Protocol() {}
+
+ protected:
+ std::shared_ptr<core::Portal> portal_;
+ std::atomic_bool is_running_;
+
+ // Random engine
+ std::random_device rd_;
+ std::mt19937 gen_;
+};
+
+} // namespace protocol
+
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/protocols/raaqm.cc b/libtransport/src/protocols/raaqm.cc
index 1247af400..bcbc15aef 100644
--- a/libtransport/src/protocols/raaqm.cc
+++ b/libtransport/src/protocols/raaqm.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -36,8 +36,9 @@ RaaqmTransportProtocol::RaaqmTransportProtocol(
current_window_size_(1),
interests_in_flight_(0),
cur_path_(nullptr),
- t0_(utils::SteadyClock::now()),
+ t0_(utils::SteadyTime::Clock::now()),
rate_estimator_(nullptr),
+ dis_(0, 1.0),
schedule_interests_(true) {
init();
}
@@ -60,7 +61,7 @@ void RaaqmTransportProtocol::reset() {
// Reset protocol variables
interests_in_flight_ = 0;
- t0_ = utils::SteadyClock::now();
+ t0_ = utils::SteadyTime::Clock::now();
// Optionally reset congestion window
bool reset_window;
@@ -370,7 +371,7 @@ void RaaqmTransportProtocol::onPacketDropped(Interest &interest,
}
interest_retransmissions_[segment & mask]++;
- interest_to_retransmit_.push(segment);
+ interest_to_retransmit_.push((unsigned int)segment);
} else {
LOG(ERROR) << "Stop: received not trusted packet "
<< interest_retransmissions_[segment & mask] << " times";
@@ -389,6 +390,8 @@ void RaaqmTransportProtocol::sendInterest(
uint32_t len) {
interests_in_flight_++;
interest_retransmissions_[interest_name.getSuffix() & mask]++;
+ interest_timepoints_[interest_name.getSuffix() & mask] =
+ utils::SteadyTime::Clock::now();
TransportProtocol::sendInterest(interest_name, additional_suffixes, len);
}
@@ -426,7 +429,7 @@ void RaaqmTransportProtocol::onInterestTimeout(Interest::Ptr &interest,
return;
}
- interest_to_retransmit_.push(segment);
+ interest_to_retransmit_.push((unsigned int)segment);
scheduleNextInterests();
} else {
LOG(ERROR) << "Stop: reached max retx limit.";
@@ -477,7 +480,7 @@ void RaaqmTransportProtocol::scheduleNextInterests() {
}
}
-void RaaqmTransportProtocol::onContentReassembled(std::error_code ec) {
+void RaaqmTransportProtocol::onContentReassembled(const std::error_code &ec) {
rate_estimator_->onDownloadFinished();
TransportProtocol::onContentReassembled(ec);
schedule_interests_ = false;
@@ -487,18 +490,18 @@ void RaaqmTransportProtocol::updateRtt(uint64_t segment) {
if (TRANSPORT_EXPECT_FALSE(!cur_path_)) {
throw std::runtime_error("RAAQM ERROR: no current path found, exit");
} else {
- auto now = utils::SteadyClock::now();
- utils::Microseconds rtt = std::chrono::duration_cast<utils::Microseconds>(
- now - interest_timepoints_[segment & mask]);
+ auto now = utils::SteadyTime::Clock::now();
+ auto rtt = utils::SteadyTime::getDurationUs(
+ interest_timepoints_[segment & mask], now);
// Update stats
- updateStats((uint32_t)segment, rtt.count(), now);
+ updateStats((uint32_t)segment, rtt, now);
if (rate_estimator_) {
- rate_estimator_->onRttUpdate((double)rtt.count());
+ rate_estimator_->onRttUpdate(rtt);
}
- cur_path_->insertNewRtt(rtt.count(), now);
+ cur_path_->insertNewRtt(rtt, now);
cur_path_->smoothTimer();
if (cur_path_->newPropagationDelayAvailable()) {
@@ -510,27 +513,27 @@ void RaaqmTransportProtocol::updateRtt(uint64_t segment) {
void RaaqmTransportProtocol::RAAQM() {
if (!cur_path_) {
throw errors::RuntimeException("ERROR: no current path found, exit");
- exit(EXIT_FAILURE);
} else {
// Change drop probability according to RTT statistics
cur_path_->updateDropProb();
- double coin = ((double)rand() / (RAND_MAX));
+ double coin = dis_(gen_);
if (coin <= cur_path_->getDropProb()) {
decreaseWindow();
}
}
}
-void RaaqmTransportProtocol::updateStats(uint32_t suffix, uint64_t rtt,
- utils::TimePoint &now) {
+void RaaqmTransportProtocol::updateStats(
+ uint32_t suffix, const utils::SteadyTime::Microseconds &rtt,
+ utils::SteadyTime::TimePoint &now) {
// Update RTT statistics
stats_->updateAverageRtt(rtt);
stats_->updateAverageWindowSize(current_window_size_);
// Call statistics callback
if (*stats_summary_) {
- auto dt = std::chrono::duration_cast<utils::Milliseconds>(now - t0_);
+ auto dt = utils::SteadyTime::getDurationMs(t0_, now);
uint32_t timer_interval_milliseconds = 0;
socket_->getSocketOption(GeneralTransportOptions::STATS_INTERVAL,
diff --git a/libtransport/src/protocols/raaqm.h b/libtransport/src/protocols/raaqm.h
index ffbb30d3a..a7ef23b68 100644
--- a/libtransport/src/protocols/raaqm.h
+++ b/libtransport/src/protocols/raaqm.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,6 +23,7 @@
#include <protocols/transport_protocol.h>
#include <queue>
+#include <random>
#include <vector>
namespace transport {
@@ -55,8 +56,9 @@ class RaaqmTransportProtocol : public TransportProtocol,
const ContentObject &content_object);
virtual void afterDataUnsatisfied(uint64_t segment);
- virtual void updateStats(uint32_t suffix, uint64_t rtt,
- utils::TimePoint &now);
+ virtual void updateStats(uint32_t suffix,
+ const utils::SteadyTime::Microseconds &rtt,
+ utils::SteadyTime::TimePoint &now);
private:
void init();
@@ -73,7 +75,7 @@ class RaaqmTransportProtocol : public TransportProtocol,
*additional_suffixes = nullptr,
uint32_t len = 0) override;
- void onContentReassembled(std::error_code ec) override;
+ void onContentReassembled(const std::error_code &ec) override;
void updateRtt(uint64_t segment);
void RAAQM();
void updatePathTable(const ContentObject &content_object);
@@ -81,13 +83,15 @@ class RaaqmTransportProtocol : public TransportProtocol,
void checkForStalePaths();
void printRtt();
+ auto shared_from_this() { return utils::shared_from(this); }
+
protected:
// Congestion window management
double current_window_size_;
// Protocol management
uint64_t interests_in_flight_;
std::array<std::uint32_t, buffer_size> interest_retransmissions_;
- std::array<utils::TimePoint, buffer_size> interest_timepoints_;
+ std::array<utils::SteadyTime::TimePoint, buffer_size> interest_timepoints_;
std::queue<uint32_t> interest_to_retransmit_;
private:
@@ -102,13 +106,16 @@ class RaaqmTransportProtocol : public TransportProtocol,
PathTable path_table_;
// TimePoints for statistic
- utils::TimePoint t0_;
+ utils::SteadyTime::TimePoint t0_;
bool set_interest_filter_;
// for rate-estimation at packet level
IcnRateEstimator *rate_estimator_;
+ // Real distribution
+ std::uniform_real_distribution<> dis_;
+
// params for autotuning
bool raaqm_autotune_;
double default_beta_;
diff --git a/libtransport/src/protocols/raaqm_data_path.cc b/libtransport/src/protocols/raaqm_data_path.cc
index f2c21b9ef..b8e6e6285 100644
--- a/libtransport/src/protocols/raaqm_data_path.cc
+++ b/libtransport/src/protocols/raaqm_data_path.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -23,16 +23,18 @@ namespace protocol {
RaaqmDataPath::RaaqmDataPath(double drop_factor,
double minimum_drop_probability,
unsigned new_timer, unsigned int samples,
- uint64_t new_rtt, uint64_t new_rtt_min,
- uint64_t new_rtt_max, unsigned new_pd)
+ const utils::SteadyTime::Milliseconds &new_rtt,
+ const utils::SteadyTime::Milliseconds &new_rtt_min,
+ const utils::SteadyTime::Milliseconds &new_rtt_max,
+ unsigned new_pd)
: drop_factor_(drop_factor),
minimum_drop_probability_(minimum_drop_probability),
timer_(new_timer),
samples_(samples),
- rtt_(new_rtt),
- rtt_min_(new_rtt_min),
- rtt_max_(new_rtt_max),
+ rtt_(new_rtt.count()),
+ rtt_min_(new_rtt_min.count()),
+ rtt_max_(new_rtt_max.count()),
prop_delay_(new_pd),
new_prop_delay_(false),
drop_prob_(0),
@@ -43,14 +45,15 @@ RaaqmDataPath::RaaqmDataPath(double drop_factor,
raw_data_bytes_received_(0),
last_raw_data_bytes_received_(0),
rtt_samples_(samples_),
- last_received_pkt_(utils::SteadyClock::now()),
+ last_received_pkt_(utils::SteadyTime::Clock::now()),
average_rtt_(0),
alpha_(ALPHA) {}
-RaaqmDataPath &RaaqmDataPath::insertNewRtt(uint64_t new_rtt,
- const utils::TimePoint &now) {
- rtt_ = new_rtt;
- rtt_samples_.pushBack(new_rtt);
+RaaqmDataPath &RaaqmDataPath::insertNewRtt(
+ const utils::SteadyTime::Microseconds &new_rtt,
+ const utils::SteadyTime::TimePoint &now) {
+ rtt_ = new_rtt.count() / 1000;
+ rtt_samples_.pushBack(rtt_);
rtt_max_ = rtt_samples_.rBegin();
rtt_min_ = rtt_samples_.begin();
@@ -143,10 +146,8 @@ unsigned int RaaqmDataPath::getPropagationDelay() {
}
bool RaaqmDataPath::isStale() {
- utils::TimePoint now = utils::SteadyClock::now();
- auto time =
- std::chrono::duration_cast<utils::Microseconds>(now - last_received_pkt_)
- .count();
+ utils::SteadyTime::TimePoint now = utils::SteadyTime::Clock::now();
+ auto time = utils::SteadyTime::getDurationUs(last_received_pkt_, now).count();
if (time > 2000000) {
return true;
}
diff --git a/libtransport/src/protocols/raaqm_data_path.h b/libtransport/src/protocols/raaqm_data_path.h
index c0b53a690..dd24dad51 100644
--- a/libtransport/src/protocols/raaqm_data_path.h
+++ b/libtransport/src/protocols/raaqm_data_path.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -34,8 +34,13 @@ class RaaqmDataPath {
public:
RaaqmDataPath(double drop_factor, double minimum_drop_probability,
unsigned new_timer, unsigned int samples,
- uint64_t new_rtt = 1000, uint64_t new_rtt_min = 1000,
- uint64_t new_rtt_max = 1000, unsigned new_pd = UINT_MAX);
+ const utils::SteadyTime::Milliseconds &new_rtt =
+ utils::SteadyTime::Milliseconds(1000),
+ const utils::SteadyTime::Milliseconds &new_rtt_min =
+ utils::SteadyTime::Milliseconds(1000),
+ const utils::SteadyTime::Milliseconds &new_rtt_max =
+ utils::SteadyTime::Milliseconds(1000),
+ unsigned new_pd = UINT_MAX);
public:
/*
@@ -44,7 +49,8 @@ class RaaqmDataPath {
* max of RTT.
* @param new_rtt is the value of the new RTT
*/
- RaaqmDataPath &insertNewRtt(uint64_t new_rtt, const utils::TimePoint &now);
+ RaaqmDataPath &insertNewRtt(const utils::SteadyTime::Microseconds &new_rtt,
+ const utils::SteadyTime::TimePoint &now);
/**
* @brief Update the path statistics
@@ -214,7 +220,7 @@ class RaaqmDataPath {
/**
* Time of the last call to the path reporter method
*/
- utils::TimePoint last_received_pkt_;
+ utils::SteadyTime::TimePoint last_received_pkt_;
double average_rtt_;
double alpha_;
diff --git a/libtransport/src/protocols/rate_estimation.cc b/libtransport/src/protocols/rate_estimation.cc
index 2337e18be..01c18c6cb 100644
--- a/libtransport/src/protocols/rate_estimation.cc
+++ b/libtransport/src/protocols/rate_estimation.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,6 +14,7 @@
*/
#include <glog/logging.h>
+#include <hicn/transport/errors/runtime_exception.h>
#include <hicn/transport/interfaces/socket_options_default_values.h>
#include <protocols/rate_estimation.h>
@@ -92,8 +93,8 @@ InterRttEstimator::InterRttEstimator(double alpha_arg) {
this->win_current_ = 1.0;
pthread_mutex_init(&(this->mutex_), NULL);
- this->start_time_ = std::chrono::steady_clock::now();
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->start_time_ = utils::SteadyTime::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
InterRttEstimator::~InterRttEstimator() {
@@ -105,33 +106,35 @@ InterRttEstimator::~InterRttEstimator() {
pthread_mutex_destroy(&(this->mutex_));
}
-void InterRttEstimator::onRttUpdate(double rtt) {
+void InterRttEstimator::onRttUpdate(
+ const utils::SteadyTime::Microseconds &rtt) {
pthread_mutex_lock(&(this->mutex_));
- this->rtt_ = rtt;
+ this->rtt_ = rtt.count() / 1000.0;
this->number_of_packets_++;
- this->avg_rtt_ += rtt;
+ this->avg_rtt_ += this->rtt_;
pthread_mutex_unlock(&(this->mutex_));
if (!thread_is_running_) {
my_th_ = (pthread_t *)malloc(sizeof(pthread_t));
if (!my_th_) {
- LOG(ERROR) << "Error allocating thread.";
- my_th_ = NULL;
+ throw errors::RuntimeException("Error allocating thread.");
}
- if (/*int err = */ pthread_create(my_th_, NULL, transport::protocol::Timer,
- (void *)this)) {
- LOG(ERROR) << "Error creating the thread";
+
+ if (pthread_create(my_th_, NULL, transport::protocol::Timer,
+ (void *)this)) {
+ free(my_th_);
my_th_ = NULL;
+ throw errors::RuntimeException("Error allocating thread.");
}
+
thread_is_running_ = true;
}
}
void InterRttEstimator::onWindowIncrease(double win_current) {
- TimePoint end = std::chrono::steady_clock::now();
+ auto end = utils::SteadyTime::now();
auto delay =
- std::chrono::duration_cast<Microseconds>(end - this->begin_batch_)
- .count();
+ utils::SteadyTime::getDurationUs(this->begin_batch_, end).count();
pthread_mutex_lock(&(this->mutex_));
this->avg_win_ += this->win_current_ * delay;
@@ -139,14 +142,13 @@ void InterRttEstimator::onWindowIncrease(double win_current) {
this->win_change_ += delay;
pthread_mutex_unlock(&(this->mutex_));
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
void InterRttEstimator::onWindowDecrease(double win_current) {
- TimePoint end = std::chrono::steady_clock::now();
+ auto end = utils::SteadyTime::now();
auto delay =
- std::chrono::duration_cast<Microseconds>(end - this->begin_batch_)
- .count();
+ utils::SteadyTime::getDurationUs(this->begin_batch_, end).count();
pthread_mutex_lock(&(this->mutex_));
this->avg_win_ += this->win_current_ * delay;
@@ -154,25 +156,24 @@ void InterRttEstimator::onWindowDecrease(double win_current) {
this->win_change_ += delay;
pthread_mutex_unlock(&(this->mutex_));
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
ALaTcpEstimator::ALaTcpEstimator() {
this->estimation_ = 0.0;
this->observer_ = NULL;
- this->start_time_ = std::chrono::steady_clock::now();
+ this->start_time_ = utils::SteadyTime::now();
this->totalSize_ = 0.0;
}
void ALaTcpEstimator::onStart() {
this->totalSize_ = 0.0;
- this->start_time_ = std::chrono::steady_clock::now();
+ this->start_time_ = utils::SteadyTime::now();
}
void ALaTcpEstimator::onDownloadFinished() {
- TimePoint end = std::chrono::steady_clock::now();
- auto delay =
- std::chrono::duration_cast<Microseconds>(end - this->start_time_).count();
+ auto end = utils::SteadyTime::now();
+ auto delay = utils::SteadyTime::getDurationUs(this->start_time_, end).count();
this->estimation_ = this->totalSize_ * 8 * 1000000 / delay;
if (observer_) {
observer_->notifyStats(this->estimation_);
@@ -192,22 +193,21 @@ SimpleEstimator::SimpleEstimator(double alphaArg, int batching_param) {
this->number_of_packets_ = 0;
this->base_alpha_ = alphaArg;
this->alpha_ = alphaArg;
- this->start_time_ = std::chrono::steady_clock::now();
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->start_time_ = utils::SteadyTime::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
void SimpleEstimator::onStart() {
this->estimated_ = false;
this->number_of_packets_ = 0;
this->total_size_ = 0.0;
- this->start_time_ = std::chrono::steady_clock::now();
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->start_time_ = utils::SteadyTime::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
void SimpleEstimator::onDownloadFinished() {
- TimePoint end = std::chrono::steady_clock::now();
- auto delay =
- std::chrono::duration_cast<Microseconds>(end - this->start_time_).count();
+ auto end = utils::SteadyTime::now();
+ auto delay = utils::SteadyTime::getDurationUs(this->start_time_, end).count();
if (observer_) {
observer_->notifyDownloadTime((double)delay);
}
@@ -229,8 +229,7 @@ void SimpleEstimator::onDownloadFinished() {
} else {
if (this->number_of_packets_ >=
(int)(75.0 * (double)this->batching_param_ / 100.0)) {
- delay = std::chrono::duration_cast<Microseconds>(end - this->begin_batch_)
- .count();
+ delay = utils::SteadyTime::getDurationUs(this->begin_batch_, end).count();
// Assuming all packets carry max_packet_size_ bytes of data
// (8*max_packet_size_ bits); 1000000 factor to convert us to seconds
if (this->estimation_) {
@@ -249,22 +248,21 @@ void SimpleEstimator::onDownloadFinished() {
}
this->number_of_packets_ = 0;
this->total_size_ = 0.0;
- this->start_time_ = std::chrono::steady_clock::now();
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->start_time_ = utils::SteadyTime::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
void SimpleEstimator::onDataReceived(int packet_size) {
this->total_size_ += packet_size;
}
-void SimpleEstimator::onRttUpdate(double rtt) {
+void SimpleEstimator::onRttUpdate(const utils::SteadyTime::Microseconds &rtt) {
this->number_of_packets_++;
if (this->number_of_packets_ == this->batching_param_) {
- TimePoint end = std::chrono::steady_clock::now();
+ auto end = utils::SteadyTime::now();
auto delay =
- std::chrono::duration_cast<Microseconds>(end - this->begin_batch_)
- .count();
+ utils::SteadyTime::getDurationUs(this->begin_batch_, end).count();
// Assuming all packets carry max_packet_size_ bytes of data
// (8*max_packet_size_ bits); 1000000 factor to convert us to seconds
if (this->estimation_) {
@@ -280,7 +278,7 @@ void SimpleEstimator::onRttUpdate(double rtt) {
this->alpha_ = this->base_alpha_;
this->number_of_packets_ = 0;
this->total_size_ = 0.0;
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
}
@@ -297,13 +295,14 @@ BatchingPacketsEstimator::BatchingPacketsEstimator(double alpha_arg,
this->max_packet_size_ = 0;
this->estimation_ = 0.0;
this->win_current_ = 1.0;
- this->begin_batch_ = std::chrono::steady_clock::now();
- this->start_time_ = std::chrono::steady_clock::now();
+ this->begin_batch_ = utils::SteadyTime::now();
+ this->start_time_ = utils::SteadyTime::now();
}
-void BatchingPacketsEstimator::onRttUpdate(double rtt) {
+void BatchingPacketsEstimator::onRttUpdate(
+ const utils::SteadyTime::Microseconds &rtt) {
this->number_of_packets_++;
- this->avg_rtt_ += rtt;
+ this->avg_rtt_ += rtt.count() / 1000.0;
if (number_of_packets_ == this->batching_param_) {
if (estimation_ == 0) {
@@ -329,25 +328,23 @@ void BatchingPacketsEstimator::onRttUpdate(double rtt) {
}
void BatchingPacketsEstimator::onWindowIncrease(double win_current) {
- TimePoint end = std::chrono::steady_clock::now();
+ auto end = utils::SteadyTime::now();
auto delay =
- std::chrono::duration_cast<Microseconds>(end - this->begin_batch_)
- .count();
+ utils::SteadyTime::getDurationUs(this->begin_batch_, end).count();
this->avg_win_ += this->win_current_ * delay;
this->win_current_ = win_current;
this->win_change_ += delay;
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
void BatchingPacketsEstimator::onWindowDecrease(double win_current) {
- TimePoint end = std::chrono::steady_clock::now();
+ auto end = utils::SteadyTime::now();
auto delay =
- std::chrono::duration_cast<Microseconds>(end - this->begin_batch_)
- .count();
+ utils::SteadyTime::getDurationUs(this->begin_batch_, end).count();
this->avg_win_ += this->win_current_ * delay;
this->win_current_ = win_current;
this->win_change_ += delay;
- this->begin_batch_ = std::chrono::steady_clock::now();
+ this->begin_batch_ = utils::SteadyTime::now();
}
} // end namespace protocol
diff --git a/libtransport/src/protocols/rate_estimation.h b/libtransport/src/protocols/rate_estimation.h
index 42ae74194..d809b2b7c 100644
--- a/libtransport/src/protocols/rate_estimation.h
+++ b/libtransport/src/protocols/rate_estimation.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,7 @@
#pragma once
#include <hicn/transport/interfaces/statistics.h>
+#include <hicn/transport/utils/noncopyable.h>
#include <protocols/raaqm_data_path.h>
#include <chrono>
@@ -24,16 +25,13 @@ namespace transport {
namespace protocol {
-class IcnRateEstimator {
+class IcnRateEstimator : utils::NonCopyable {
public:
- using TimePoint = std::chrono::steady_clock::time_point;
- using Microseconds = std::chrono::microseconds;
-
IcnRateEstimator(){};
virtual ~IcnRateEstimator(){};
- virtual void onRttUpdate(double rtt){};
+ virtual void onRttUpdate(const utils::SteadyTime::Microseconds &rtt){};
virtual void onDataReceived(int packetSize){};
@@ -48,9 +46,10 @@ class IcnRateEstimator {
virtual void setObserver(interface::IcnObserver *observer) {
this->observer_ = observer;
};
+
interface::IcnObserver *observer_;
- TimePoint start_time_;
- TimePoint begin_batch_;
+ utils::SteadyTime::TimePoint start_time_;
+ utils::SteadyTime::TimePoint begin_batch_;
double base_alpha_;
double alpha_;
double estimation_;
@@ -67,7 +66,7 @@ class InterRttEstimator : public IcnRateEstimator {
~InterRttEstimator();
- void onRttUpdate(double rtt);
+ void onRttUpdate(const utils::SteadyTime::Microseconds &rtt);
void onDataReceived(int packet_size) {
if (packet_size > this->max_packet_size_) {
@@ -102,7 +101,7 @@ class BatchingPacketsEstimator : public IcnRateEstimator {
public:
BatchingPacketsEstimator(double alpha_arg, int batchingParam);
- void onRttUpdate(double rtt);
+ void onRttUpdate(const utils::SteadyTime::Microseconds &rtt);
void onDataReceived(int packet_size) {
if (packet_size > this->max_packet_size_) {
@@ -149,7 +148,7 @@ class SimpleEstimator : public IcnRateEstimator {
public:
SimpleEstimator(double alpha, int batching_param);
- void onRttUpdate(double rtt);
+ void onRttUpdate(const utils::SteadyTime::Microseconds &rtt);
void onDataReceived(int packet_size);
diff --git a/libtransport/src/protocols/reassembly.cc b/libtransport/src/protocols/reassembly.cc
index ce24fce1b..065458f7e 100644
--- a/libtransport/src/protocols/reassembly.cc
+++ b/libtransport/src/protocols/reassembly.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/protocols/reassembly.h b/libtransport/src/protocols/reassembly.h
index e072ad123..c0c4de3d8 100644
--- a/libtransport/src/protocols/reassembly.h
+++ b/libtransport/src/protocols/reassembly.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -36,7 +36,7 @@ class Reassembly {
public:
class ContentReassembledCallback {
public:
- virtual void onContentReassembled(std::error_code ec) = 0;
+ virtual void onContentReassembled(const std::error_code &ec) = 0;
};
Reassembly(implementation::ConsumerSocket *icn_socket,
@@ -47,22 +47,16 @@ class Reassembly {
virtual ~Reassembly() = default;
/**
- * Hanle reassembly of content object.
+ * Handle reassembly of content object.
*/
virtual void reassemble(core::ContentObject &content_object) = 0;
/**
- * Hanle reassembly of content object.
+ * Handle reassembly of content object.
*/
virtual void reassemble(utils::MemBuf &buffer, uint32_t suffix) = 0;
/**
- * Handle reassembly of manifest
- */
- virtual void reassemble(
- std::unique_ptr<core::ContentObjectManifest> &&manifest) = 0;
-
- /**
* Reset reassembler for new round
*/
virtual void reInitialize() = 0;
diff --git a/libtransport/src/protocols/rtc/CMakeLists.txt b/libtransport/src/protocols/rtc/CMakeLists.txt
index 873b345d0..be8e0189c 100644
--- a/libtransport/src/protocols/rtc/CMakeLists.txt
+++ b/libtransport/src/protocols/rtc/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -16,22 +16,43 @@ list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/rtc.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_consts.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_data_path.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_forwarding_strategy.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_indexer.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_ldr.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_packet.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_rc.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rc_congestion_detection.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rc_iat.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_rc_queue.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_reassembly.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_recovery_strategy.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_delay.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_fec_only.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_low_rate.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_recovery_off.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_rtx_only.h
${CMAKE_CURRENT_SOURCE_DIR}/rtc_state.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_verifier.h
)
list(APPEND SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/probe_handler.cc
${CMAKE_CURRENT_SOURCE_DIR}/rtc.cc
${CMAKE_CURRENT_SOURCE_DIR}/rtc_data_path.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_forwarding_strategy.cc
${CMAKE_CURRENT_SOURCE_DIR}/rtc_ldr.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rc_congestion_detection.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rc_iat.cc
${CMAKE_CURRENT_SOURCE_DIR}/rtc_rc_queue.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_reassembly.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_recovery_strategy.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_delay.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_fec_only.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_low_rate.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_recovery_off.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_rs_rtx_only.cc
${CMAKE_CURRENT_SOURCE_DIR}/rtc_state.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/rtc_verifier.cc
)
set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE)
diff --git a/libtransport/src/protocols/rtc/probe_handler.cc b/libtransport/src/protocols/rtc/probe_handler.cc
index abaca6ad9..60eceeb19 100644
--- a/libtransport/src/protocols/rtc/probe_handler.cc
+++ b/libtransport/src/protocols/rtc/probe_handler.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,6 +13,8 @@
* limitations under the License.
*/
+#include <glog/logging.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <protocols/rtc/probe_handler.h>
#include <protocols/rtc/rtc_consts.h>
@@ -27,6 +29,7 @@ ProbeHandler::ProbeHandler(SendProbeCallback &&send_callback,
: probe_interval_(0),
max_probes_(0),
sent_probes_(0),
+ recv_probes_(0),
probe_timer_(std::make_unique<asio::steady_timer>(io_service)),
rand_eng_((std::random_device())()),
distr_(MIN_RTT_PROBE_SEQ, MAX_RTT_PROBE_SEQ),
@@ -34,22 +37,38 @@ ProbeHandler::ProbeHandler(SendProbeCallback &&send_callback,
ProbeHandler::~ProbeHandler() {}
-uint64_t ProbeHandler::getRtt(uint32_t seq) {
+uint64_t ProbeHandler::getRtt(uint32_t seq, bool is_valid) {
auto it = pending_probes_.find(seq);
if (it == pending_probes_.end()) return 0;
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ if (!is_valid) {
+ // delete the probe anyway
+ pending_probes_.erase(it);
+ valid_batch_ = false;
+ return 0;
+ }
+
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint64_t rtt = now - it->second;
if (rtt < 1) rtt = 1;
pending_probes_.erase(it);
+ recv_probes_++;
return rtt;
}
+double ProbeHandler::getProbeLossRate() {
+ if (!valid_batch_) return 1.0;
+ return 1.0 - ((double)recv_probes_ / (double)sent_probes_);
+}
+
+void ProbeHandler::setSuffixRange(uint32_t min, uint32_t max) {
+ DCHECK(min <= max && min >= MIN_PROBE_SEQ);
+ distr_ = std::uniform_int_distribution<uint32_t>(min, max);
+}
+
void ProbeHandler::setProbes(uint32_t probe_interval, uint32_t max_probes) {
stopProbes();
probe_interval_ = probe_interval;
@@ -60,16 +79,30 @@ void ProbeHandler::stopProbes() {
probe_interval_ = 0;
max_probes_ = 0;
sent_probes_ = 0;
+ recv_probes_ = 0;
+ valid_batch_ = true;
probe_timer_->cancel();
}
void ProbeHandler::sendProbes() {
if (probe_interval_ == 0) return;
+
+ std::weak_ptr<ProbeHandler> self(shared_from_this());
+ probe_timer_->expires_from_now(std::chrono::microseconds(probe_interval_));
+ probe_timer_->async_wait([self](const std::error_code &ec) {
+ if (ec) return;
+ auto s = self.lock();
+ if (s) {
+ s->generateProbe();
+ }
+ });
+}
+
+void ProbeHandler::generateProbe() {
+ if (probe_interval_ == 0) return;
if (max_probes_ != 0 && sent_probes_ >= max_probes_) return;
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint32_t seq = distr_(rand_eng_);
pending_probes_.insert(std::pair<uint32_t, uint64_t>(seq, now));
@@ -88,16 +121,17 @@ void ProbeHandler::sendProbes() {
}
}
- if (probe_interval_ == 0) return;
+ sendProbes();
+}
- std::weak_ptr<ProbeHandler> self(shared_from_this());
- probe_timer_->expires_from_now(std::chrono::microseconds(probe_interval_));
- probe_timer_->async_wait([self](std::error_code ec) {
- if (ec) return;
- if (auto s = self.lock()) {
- s->sendProbes();
- }
- });
+ProbeType ProbeHandler::getProbeType(uint32_t seq) {
+ if (MIN_INIT_PROBE_SEQ <= seq && seq <= MAX_INIT_PROBE_SEQ) {
+ return ProbeType::INIT;
+ }
+ if (MIN_RTT_PROBE_SEQ <= seq && seq <= MAX_RTT_PROBE_SEQ) {
+ return ProbeType::RTT;
+ }
+ return ProbeType::NOT_PROBE;
}
} // namespace rtc
diff --git a/libtransport/src/protocols/rtc/probe_handler.h b/libtransport/src/protocols/rtc/probe_handler.h
index e34b23df0..d989194d4 100644
--- a/libtransport/src/protocols/rtc/probe_handler.h
+++ b/libtransport/src/protocols/rtc/probe_handler.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -26,6 +26,12 @@ namespace protocol {
namespace rtc {
+enum class ProbeType {
+ NOT_PROBE,
+ INIT,
+ RTT,
+};
+
class ProbeHandler : public std::enable_shared_from_this<ProbeHandler> {
public:
using SendProbeCallback = std::function<void(uint32_t)>;
@@ -35,31 +41,45 @@ class ProbeHandler : public std::enable_shared_from_this<ProbeHandler> {
~ProbeHandler();
- // if the function returns 0 the probe is not valaid
- uint64_t getRtt(uint32_t seq);
+ // If the function returns 0 the probe is not valid.
+ uint64_t getRtt(uint32_t seq, bool is_valid);
+
+ // this function may return a residual loss rate higher than the real one if
+ // we don't wait enough time for the probes to come back
+ double getProbeLossRate();
+
+ // Set the probe suffix range [min, max]
+ void setSuffixRange(uint32_t min, uint32_t max);
- // reset the probes parameters. it stop the current probing.
- // to restar call sendProbes.
- // probe_interval = 0 means that no event will be scheduled
- // max_probe = 0 means no limit to the number of probe to send
+ // Reset the probes parameters and stops the current probing.
+ // probe_interval = 0 means that no event will be scheduled.
+ // max_probe = 0 means no limit to the number of probe to send.
void setProbes(uint32_t probe_interval, uint32_t max_probes);
- // stop to schedule probes
void stopProbes();
void sendProbes();
+ static ProbeType getProbeType(uint32_t seq);
+
private:
+ void generateProbe();
+
uint32_t probe_interval_; // us
uint32_t max_probes_; // packets
uint32_t sent_probes_; // packets
+ uint32_t recv_probes_; // packets
+
+ bool valid_batch_; // if at least one probe in a batch is considered not
+ // valid (e.g. prod rate == ~0) the full batch is invalid.
+ // the bool is set to true when sendProbe is called
std::unique_ptr<asio::steady_timer> probe_timer_;
- // map from seqnumber to timestamp
+ // Map from packet suffixes to timestamp
std::unordered_map<uint32_t, uint64_t> pending_probes_;
- // random generator
+ // Random generator
std::default_random_engine rand_eng_;
std::uniform_int_distribution<uint32_t> distr_;
diff --git a/libtransport/src/protocols/rtc/rtc.cc b/libtransport/src/protocols/rtc/rtc.cc
index 0cb4cda1d..9a56269f3 100644
--- a/libtransport/src/protocols/rtc/rtc.cc
+++ b/libtransport/src/protocols/rtc/rtc.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,7 +22,7 @@
#include <protocols/rtc/rtc.h>
#include <protocols/rtc/rtc_consts.h>
#include <protocols/rtc/rtc_indexer.h>
-#include <protocols/rtc/rtc_rc_queue.h>
+#include <protocols/rtc/rtc_rc_congestion_detection.h>
#include <algorithm>
@@ -37,13 +37,16 @@ using namespace interface;
RTCTransportProtocol::RTCTransportProtocol(
implementation::ConsumerSocket *icn_socket)
: TransportProtocol(icn_socket, new RtcIndexer<>(icn_socket, this),
- new DatagramReassembly(icn_socket, this)),
+ new RtcReassembly(icn_socket, this)),
+ max_aggregated_interest_(1),
number_(0) {
icn_socket->getSocketOption(PORTAL, portal_);
- round_timer_ = std::make_unique<asio::steady_timer>(portal_->getIoService());
+ round_timer_ =
+ std::make_unique<asio::steady_timer>(portal_->getThread().getIoService());
scheduler_timer_ =
- std::make_unique<asio::steady_timer>(portal_->getIoService());
- pacing_timer_ = std::make_unique<asio::steady_timer>(portal_->getIoService());
+ std::make_unique<asio::steady_timer>(portal_->getThread().getIoService());
+ pacing_timer_ =
+ std::make_unique<asio::steady_timer>(portal_->getThread().getIoService());
}
RTCTransportProtocol::~RTCTransportProtocol() {}
@@ -53,33 +56,75 @@ void RTCTransportProtocol::resume() {
TransportProtocol::resume();
}
-std::size_t RTCTransportProtocol::transportHeaderLength() {
+std::size_t RTCTransportProtocol::transportHeaderLength(bool isFEC) {
return DATA_HEADER_SIZE +
- (fec_decoder_ != nullptr ? fec_decoder_->getFecHeaderSize() : 0);
+ (fec_decoder_ != nullptr ? fec_decoder_->getFecHeaderSize(isFEC) : 0);
}
// private
void RTCTransportProtocol::initParams() {
TransportProtocol::reset();
+ std::weak_ptr<RTCTransportProtocol> self = shared_from_this();
- rc_ = std::make_shared<RTCRateControlQueue>();
+ fwd_strategy_.setCallback([self](notification::Strategy strategy) {
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ if (*ptr->on_fwd_strategy_) (*ptr->on_fwd_strategy_)(strategy);
+ }
+ });
+
+ std::shared_ptr<auth::Verifier> verifier;
+ socket_->getSocketOption(GeneralTransportOptions::VERIFIER, verifier);
+
+ uint32_t factor_relevant;
+ socket_->getSocketOption(GeneralTransportOptions::MANIFEST_FACTOR_RELEVANT,
+ factor_relevant);
+
+ uint32_t factor_alert;
+ socket_->getSocketOption(GeneralTransportOptions::MANIFEST_FACTOR_ALERT,
+ factor_alert);
+
+ rc_ = std::make_shared<RTCRateControlCongestionDetection>();
ldr_ = std::make_shared<RTCLossDetectionAndRecovery>(
- indexer_verifier_.get(),
- std::bind(&RTCTransportProtocol::sendRtxInterest, this,
- std::placeholders::_1),
- portal_->getIoService());
+ indexer_verifier_.get(), portal_->getThread().getIoService(),
+ interface::RtcTransportRecoveryStrategies::RTX_ONLY,
+ [self](uint32_t seq) {
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ ptr->sendRtxInterest(seq);
+ }
+ },
+ [self](notification::Strategy strategy) {
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ if (*ptr->on_rec_strategy_) (*ptr->on_rec_strategy_)(strategy);
+ }
+ });
+
+ verifier_ =
+ std::make_shared<RTCVerifier>(verifier, factor_relevant, factor_alert);
state_ = std::make_shared<RTCState>(
indexer_verifier_.get(),
- std::bind(&RTCTransportProtocol::sendProbeInterest, this,
- std::placeholders::_1),
- std::bind(&RTCTransportProtocol::discoveredRtt, this),
- portal_->getIoService());
+ [self](uint32_t seq) {
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ ptr->sendProbeInterest(seq);
+ }
+ },
+ [self]() {
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ ptr->discoveredRtt();
+ }
+ },
+ portal_->getThread().getIoService());
rc_->setState(state_);
- // TODO: for the moment we keep the congestion control disabled
- // rc_->tunrOnRateControl();
- ldr_->setState(state_);
+ rc_->turnOnRateControl();
+ ldr_->setState(state_.get());
+ ldr_->setRateControl(rc_.get());
+ verifier_->setState(state_);
// protocol state
start_send_interest_ = false;
@@ -94,15 +139,20 @@ void RTCTransportProtocol::initParams() {
last_interest_sent_time_ = 0;
last_interest_sent_seq_ = 0;
-#if 0
- if(portal_->isConnectedToFwd()){
- max_aggregated_interest_ = 1;
- }else{
- max_aggregated_interest_ = MAX_INTERESTS_IN_BATCH;
+ // Aggregated interests setup
+ bool aggregated_interests_on;
+ socket_->getSocketOption(RtcTransportOptions::AGGREGATED_INTERESTS,
+ aggregated_interests_on);
+ if (aggregated_interests_on) {
+ if (const char *max_aggr = std::getenv("MAX_AGGREGATED_INTERESTS"))
+ max_aggregated_interest_ = (uint32_t)std::stoul(std::string(max_aggr));
+ else
+ max_aggregated_interest_ = MAX_INTERESTS_IN_BATCH;
+
+ max_aggregated_interest_ = std::min<uint32_t>(max_aggregated_interest_,
+ 1 + MAX_SUFFIXES_IN_MANIFEST);
}
-#else
- max_aggregated_interest_ = 1;
-#endif
+ LOG(INFO) << "Max Aggregated: " << max_aggregated_interest_;
max_sent_int_ =
std::ceil((double)MAX_PACING_BATCH / (double)max_aggregated_interest_);
@@ -120,20 +170,8 @@ void RTCTransportProtocol::initParams() {
socket_->setSocketOption(GeneralTransportOptions::INTEREST_LIFETIME,
RTC_INTEREST_LIFETIME);
- // FEC
- using namespace std::placeholders;
- enableFEC(std::bind(&RTCTransportProtocol::onFecPackets, this, _1),
- /* We leave the buffer allocation to the fec decoder */
- fec::FECBase::BufferRequested(0));
-
- if (fec_decoder_) {
- indexer_verifier_->enableFec(fec_type_);
- indexer_verifier_->setNFec(0);
- ldr_->setFecParams(fec::FECUtils::getBlockSymbols(fec_type_),
- fec::FECUtils::getSourceSymbols(fec_type_));
- } else {
- indexer_verifier_->disableFec();
- }
+ // init state params
+ state_->initParams();
}
// private
@@ -162,61 +200,86 @@ void RTCTransportProtocol::inactiveProducer() {
void RTCTransportProtocol::newRound() {
round_timer_->expires_from_now(std::chrono::milliseconds(ROUND_LEN));
- // TODO pass weak_ptr here
- round_timer_->async_wait([this, n{number_}](std::error_code ec) {
- if (ec) return;
- if (n != number_) {
+ std::weak_ptr<RTCTransportProtocol> self = shared_from_this();
+ round_timer_->async_wait([self](const std::error_code &ec) {
+ if (ec) {
+ return;
+ }
+
+ auto ptr = self.lock();
+
+ if (!ptr || !ptr->isRunning()) {
return;
}
+ auto &state = ptr->state_;
+
// saving counters that will be reset on new round
- uint32_t sent_retx = state_->getSentRtxInRound();
- uint32_t received_bytes = state_->getReceivedBytesInRound();
- uint32_t sent_interest = state_->getSentInterestInRound();
- uint32_t lost_data = state_->getLostData();
- uint32_t definitely_lost = state_->getDefinitelyLostPackets();
- uint32_t recovered_losses = state_->getRecoveredLosses();
- uint32_t received_nacks = state_->getReceivedNacksInRound();
- uint32_t received_fec = state_->getReceivedFecPackets();
-
- bool in_sync = (current_state_ == SyncState::in_sync);
- ldr_->onNewRound(in_sync);
- state_->onNewRound((double)ROUND_LEN, in_sync);
- rc_->onNewRound((double)ROUND_LEN);
+ uint32_t sent_retx = state->getSentRtxInRound();
+ uint32_t received_bytes =
+ (state->getReceivedBytesInRound() + // data packets received
+ state->getReceivedFecBytesInRound()); // fec packets received
+ uint32_t sent_interest = state->getSentInterestInRound();
+ uint32_t lost_data = state->getLostData();
+ uint32_t definitely_lost = state->getDefinitelyLostPackets();
+ uint32_t recovered_losses = state->getRecoveredLosses();
+ uint32_t received_nacks = state->getReceivedNacksInRound();
+ uint32_t received_fec = state->getReceivedFecPackets();
// update sync state if needed
- if (current_state_ == SyncState::in_sync) {
- double cache_rate = state_->getPacketFromCacheRatio();
+ double cache_rate = state->getPacketFromCacheRatio();
+ uint32_t round_without_nacks = state->getRoundsWithoutNacks();
+
+ if (ptr->current_state_ == SyncState::in_sync) {
if (cache_rate > MAX_DATA_FROM_CACHE) {
- current_state_ = SyncState::catch_up;
+ ptr->current_state_ = SyncState::catch_up;
}
} else {
- double target_rate = state_->getProducerRate() * PRODUCTION_RATE_FRACTION;
- double received_rate = state_->getReceivedRate();
- uint32_t round_without_nacks = state_->getRoundsWithoutNacks();
- double cache_ratio = state_->getPacketFromCacheRatio();
if (round_without_nacks >= ROUNDS_IN_SYNC_BEFORE_SWITCH &&
- received_rate >= target_rate && cache_ratio < MAX_DATA_FROM_CACHE) {
- current_state_ = SyncState::in_sync;
+ cache_rate < MAX_DATA_FROM_CACHE) {
+ ptr->current_state_ = SyncState::in_sync;
}
}
+ bool in_sync = (ptr->current_state_ == SyncState::in_sync);
+ ptr->ldr_->onNewRound(in_sync);
+ ptr->state_->onNewRound((double)ROUND_LEN, in_sync);
+ ptr->rc_->onNewRound((double)ROUND_LEN);
+
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Calling updateSyncWindow in newRound function";
- updateSyncWindow();
+ ptr->updateSyncWindow();
- sendStatsToApp(sent_retx, received_bytes, sent_interest, lost_data,
- definitely_lost, recovered_losses, received_nacks,
- received_fec);
- newRound();
+ ptr->sendStatsToApp(sent_retx, received_bytes, sent_interest, lost_data,
+ definitely_lost, recovered_losses, received_nacks,
+ received_fec);
+ ptr->fwd_strategy_.checkStrategy();
+ ptr->newRound();
});
}
void RTCTransportProtocol::discoveredRtt() {
start_send_interest_ = true;
- ldr_->turnOnRTX();
+ uint32_t strategy;
+ socket_->getSocketOption(RtcTransportOptions::RECOVERY_STRATEGY, strategy);
+ ldr_->changeRecoveryStrategy(
+ (interface::RtcTransportRecoveryStrategies)strategy);
+
+ bool content_sharing_mode;
+ socket_->getSocketOption(RtcTransportOptions::CONTENT_SHARING_MODE,
+ content_sharing_mode);
+ if (content_sharing_mode) ldr_->setContentSharingMode();
+ ldr_->turnOnRecovery();
ldr_->onNewRound(false);
+
+ // set forwarding strategy switch if selected
+ Name *name = nullptr;
+ socket_->getSocketOption(GeneralTransportOptions::NETWORK_NAME, &name);
+ Prefix prefix(*name, 128);
+ fwd_strategy_.initFwdStrategy(
+ portal_, prefix, state_.get(),
+ (interface::RtcTransportRecoveryStrategies)strategy);
updateSyncWindow();
}
@@ -233,6 +296,12 @@ void RTCTransportProtocol::computeMaxSyncWindow() {
return;
}
+ bool content_sharing_mode;
+ socket_->getSocketOption(RtcTransportOptions::CONTENT_SHARING_MODE,
+ content_sharing_mode);
+ if (content_sharing_mode && (production_rate < MIN_PROD_RATE_SHARING_MODE))
+ production_rate = MIN_PROD_RATE_SHARING_MODE;
+
production_rate += (production_rate * indexer_verifier_->getMaxFecOverhead());
uint32_t lifetime = default_values::interest_lifetime;
@@ -244,7 +313,7 @@ void RTCTransportProtocol::computeMaxSyncWindow() {
(production_rate * lifetime_ms * INTEREST_LIFETIME_REDUCTION_FACTOR) /
packet_size);
- max_sync_win_ = std::min(max_sync_win_, rc_->getCongesionWindow());
+ max_sync_win_ = std::min(max_sync_win_, rc_->getCongestionWindow());
}
void RTCTransportProtocol::updateSyncWindow() {
@@ -259,25 +328,19 @@ void RTCTransportProtocol::updateSyncWindow() {
}
double prod_rate = state_->getProducerRate();
- double rtt = (double)state_->getRTT() / MILLI_IN_A_SEC;
+ double rtt = (double)state_->getMinRTT() / MILLI_IN_A_SEC;
double packet_size = state_->getAveragePacketSize();
+ bool content_sharing_mode;
+ socket_->getSocketOption(RtcTransportOptions::CONTENT_SHARING_MODE,
+ content_sharing_mode);
+ if (content_sharing_mode && (prod_rate < MIN_PROD_RATE_SHARING_MODE))
+ prod_rate = MIN_PROD_RATE_SHARING_MODE;
// if some of the info are not available do not update the current win
if (prod_rate != 0.0 && rtt != 0.0 && packet_size != 0.0) {
- double fec_interest_overhead = (double)state_->getPendingFecPackets() /
- (double)(state_->getPendingInterestNumber() -
- state_->getPendingFecPackets());
-
- double fec_overhead =
- std::max(indexer_verifier_->getFecOverhead(), fec_interest_overhead);
-
- prod_rate += (prod_rate * fec_overhead);
-
current_sync_win_ = (uint32_t)ceil(prod_rate * rtt / packet_size);
- uint32_t buffer = PRODUCER_BUFFER_MS;
- if (rtt > 150)
- buffer = buffer * 2; // if the RTT is too large we increase the
- // the size of the buffer
+ uint32_t buffer = PRODUCER_BUFFER_MS + ((double)state_->getMinRTT() / 2.0);
+
current_sync_win_ +=
ceil(prod_rate * (buffer / MILLI_IN_A_SEC) / packet_size);
@@ -285,22 +348,22 @@ void RTCTransportProtocol::updateSyncWindow() {
current_sync_win_ = current_sync_win_ * CATCH_UP_WIN_INCREMENT;
}
+ uint32_t min_win = WIN_MIN;
+ bool aggregated_data_on;
+ socket_->getSocketOption(RtcTransportOptions::AGGREGATED_DATA,
+ aggregated_data_on);
+ if (aggregated_data_on) {
+ min_win = WIN_MIN_WITH_AGGREGARED_DATA;
+ min_win += (min_win * (1 - (std::max(0.3, rtt) - rtt) / 0.3));
+ }
+
current_sync_win_ = std::min(current_sync_win_, max_sync_win_);
- current_sync_win_ = std::max(current_sync_win_, WIN_MIN);
+ current_sync_win_ = std::max(current_sync_win_, min_win);
}
scheduleNextInterests();
}
-void RTCTransportProtocol::decreaseSyncWindow() {
- // called on future nack
- // we have a new sample of the production rate, so update max win first
- computeMaxSyncWindow();
- current_sync_win_--;
- current_sync_win_ = std::max(current_sync_win_, WIN_MIN);
- scheduleNextInterests();
-}
-
void RTCTransportProtocol::sendRtxInterest(uint32_t seq) {
if (!isRunning() && !is_first_) return;
@@ -322,21 +385,39 @@ void RTCTransportProtocol::sendProbeInterest(uint32_t seq) {
socket_->getSocketOption(GeneralTransportOptions::NETWORK_NAME,
&interest_name);
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "send probe " << seq;
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send probe " << seq;
interest_name->setSuffix(seq);
sendInterest(*interest_name);
}
+void RTCTransportProtocol::sendInterestForTimeout(uint32_t seq) {
+ if (!isRunning() && !is_first_) return;
+
+ Name *interest_name = nullptr;
+ socket_->getSocketOption(GeneralTransportOptions::NETWORK_NAME,
+ &interest_name);
+
+ // we got a timeout for this packet so it is not pending anymore
+ interest_name->setSuffix(seq);
+ state_->onSendNewInterest(interest_name);
+ sendInterest(*interest_name);
+}
+
void RTCTransportProtocol::scheduleNextInterests() {
DLOG_IF(INFO, VLOG_IS_ON(3)) << "Schedule next interests";
- if (!isRunning() && !is_first_) return;
+ if (!isRunning() && !is_first_) {
+ return;
+ }
- if (pacing_timer_on_) return; // wait pacing timer for the next send
+ if (pacing_timer_on_) {
+ return; // wait pacing timer for the next send
+ }
- if (!start_send_interest_)
+ if (!start_send_interest_) {
return; // RTT discovering phase is not finished so
// do not start to send interests
+ }
if (TRANSPORT_EXPECT_FALSE(!state_->isProducerActive())) {
DLOG_IF(INFO, VLOG_IS_ON(3)) << "Inactive producer.";
@@ -352,7 +433,7 @@ void RTCTransportProtocol::scheduleNextInterests() {
&interest_name);
uint32_t next_seg = 0;
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "send interest " << next_seg;
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Send interest " << next_seg;
interest_name->setSuffix(next_seg);
if (portal_->interestIsPending(*interest_name)) {
@@ -370,28 +451,36 @@ void RTCTransportProtocol::scheduleNextInterests() {
<< " -- current_sync_win_: " << current_sync_win_;
uint32_t pending = state_->getPendingInterestNumber();
- if (pending >= current_sync_win_) return; // no space in the window
+ uint32_t pending_fec = state_->getPendingFecPackets();
- if ((current_sync_win_ - pending) < max_aggregated_interest_) {
+ if ((pending - pending_fec) >= current_sync_win_)
+ return; // no space in the window
+
+ // XXX double check if aggregated interests are still working here
+ if ((current_sync_win_ - (pending - pending_fec)) <
+ max_aggregated_interest_) {
if (scheduler_timer_on_) return; // timer already scheduled
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint64_t time = now - last_interest_sent_time_;
if (time < WAIT_FOR_INTEREST_BATCH) {
uint64_t next = WAIT_FOR_INTEREST_BATCH - time;
scheduler_timer_on_ = true;
scheduler_timer_->expires_from_now(std::chrono::milliseconds(next));
- scheduler_timer_->async_wait([this](std::error_code ec) {
+
+ std::weak_ptr<RTCTransportProtocol> self = shared_from_this();
+ scheduler_timer_->async_wait([self](const std::error_code &ec) {
if (ec) return;
- if (!scheduler_timer_on_) return;
- scheduler_timer_on_ = false;
- scheduleNextInterests();
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ if (!ptr->scheduler_timer_on_) return;
+ ptr->scheduler_timer_on_ = false;
+ ptr->scheduleNextInterests();
+ }
});
- return; // whait for the timer
+ return; // wait for the timer
}
}
@@ -403,10 +492,10 @@ void RTCTransportProtocol::scheduleNextInterests() {
indexer_verifier_->jumpToIndex(state_->getLastSeqNacked() + 1);
}
- // skipe received packets
- if (indexer_verifier_->checkNextSuffix() <=
- state_->getHighestSeqReceivedInOrder()) {
- indexer_verifier_->jumpToIndex(state_->getHighestSeqReceivedInOrder() + 1);
+ // skip received packets
+ uint32_t max_received = state_->getHighestSeqReceivedInOrder();
+ if (indexer_verifier_->checkNextSuffix() <= max_received) {
+ indexer_verifier_->jumpToIndex(max_received + 1);
}
uint32_t sent_interests = 0;
@@ -417,30 +506,31 @@ void RTCTransportProtocol::scheduleNextInterests() {
socket_->getSocketOption(GeneralTransportOptions::NETWORK_NAME, &name);
std::array<uint32_t, MAX_AGGREGATED_INTEREST> additional_suffixes;
- while ((state_->getPendingInterestNumber() < current_sync_win_) &&
+ while (((state_->getPendingInterestNumber() -
+ state_->getPendingFecPackets()) < current_sync_win_) &&
(sent_interests < max_sent_int_)) {
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "In while loop. Window size: " << current_sync_win_;
uint32_t next_seg = indexer_verifier_->getNextSuffix();
-
name->setSuffix(next_seg);
// send the packet only if:
// 1) it is not pending yet (not true for rtx)
- // 2) the packet is not received or lost
+ // 2) the packet is not received or def lost
// 3) is not in the rtx list
// 4) is fec and is not in order (!= last sent + 1)
+ PacketState packet_state = state_->getPacketState(next_seg);
if (portal_->interestIsPending(*name) ||
- state_->isReceivedOrLost(next_seg) != PacketState::UNKNOWN ||
- ldr_->isRtx(next_seg) ||
+ packet_state == PacketState::RECEIVED ||
+ packet_state == PacketState::DEFINITELY_LOST || ldr_->isRtx(next_seg) ||
(indexer_verifier_->isFec(next_seg) &&
next_seg != last_interest_sent_seq_ + 1)) {
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "skip interest " << next_seg << " because: pending "
- << portal_->interestIsPending(*name) << ", recv "
- << (state_->isReceivedOrLost(next_seg) != PacketState::UNKNOWN)
- << ", rtx " << (ldr_->isRtx(next_seg)) << ", is old fec "
+ << portal_->interestIsPending(*name) << ", recv or lost"
+ << (int)packet_state << ", rtx " << (ldr_->isRtx(next_seg))
+ << ", is old fec "
<< ((indexer_verifier_->isFec(next_seg) &&
next_seg != last_interest_sent_seq_ + 1));
continue;
@@ -462,10 +552,7 @@ void RTCTransportProtocol::scheduleNextInterests() {
sent_packets++;
sent_interests++;
sendInterest(interest_name, &additional_suffixes, aggregated_counter - 1);
- last_interest_sent_time_ =
- std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ last_interest_sent_time_ = utils::SteadyTime::nowMs().count();
aggregated_counter = 0;
}
}
@@ -473,25 +560,29 @@ void RTCTransportProtocol::scheduleNextInterests() {
// exiting the while we may have some pending interest to send
if (aggregated_counter != 0) {
sent_packets++;
- last_interest_sent_time_ =
- std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ last_interest_sent_time_ = utils::SteadyTime::nowMs().count();
sendInterest(interest_name, &additional_suffixes, aggregated_counter - 1);
}
- if (state_->getPendingInterestNumber() < current_sync_win_) {
+ if ((state_->getPendingInterestNumber() - state_->getPendingFecPackets()) <
+ current_sync_win_) {
// we still have space in the window but we already sent too many packets
// wait PACING_WAIT to avoid drops in the kernel
pacing_timer_on_ = true;
pacing_timer_->expires_from_now(std::chrono::microseconds(PACING_WAIT));
- scheduler_timer_->async_wait([this](std::error_code ec) {
+
+ std::weak_ptr<RTCTransportProtocol> self = shared_from_this();
+ scheduler_timer_->async_wait([self](const std::error_code &ec) {
if (ec) return;
- if (!pacing_timer_on_) return;
- pacing_timer_on_ = false;
- scheduleNextInterests();
+ auto ptr = self.lock();
+ if (ptr && ptr->isRunning()) {
+ if (!ptr->pacing_timer_on_) return;
+
+ ptr->pacing_timer_on_ = false;
+ ptr->scheduleNextInterests();
+ }
});
}
}
@@ -500,19 +591,18 @@ void RTCTransportProtocol::onInterestTimeout(Interest::Ptr &interest,
const Name &name) {
uint32_t segment_number = name.getSuffix();
- if (segment_number >= MIN_PROBE_SEQ) {
+ if (ProbeHandler::getProbeType(segment_number) != ProbeType::NOT_PROBE) {
// this is a timeout on a probe, do nothing
return;
}
- PacketState state = state_->isReceivedOrLost(segment_number);
- if (state != PacketState::UNKNOWN) {
+ PacketState state = state_->getPacketState(segment_number);
+ if (state == PacketState::RECEIVED || state == PacketState::DEFINITELY_LOST) {
// we may recover a packets using fec, ignore this timer
return;
}
timeouts_or_nacks_.insert(segment_number);
-
if (TRANSPORT_EXPECT_TRUE(state_->isProducerActive()) &&
segment_number <= state_->getHighestSeqReceived()) {
// we retransmit packets only if the producer is active, otherwise we
@@ -524,13 +614,18 @@ void RTCTransportProtocol::onInterestTimeout(Interest::Ptr &interest,
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "handle timeout for packet " << segment_number << " using rtx";
if (ldr_->isRtxOn()) {
- ldr_->onTimeout(segment_number);
- if (indexer_verifier_->isFec(segment_number))
+ if (indexer_verifier_->isFec(segment_number)) {
+ // if this is a fec packet we do not recover it with rtx so we consider
+ // the packet to be lost
+ ldr_->onTimeout(segment_number, true);
state_->onTimeout(segment_number, true);
- else
+ } else {
+ ldr_->onTimeout(segment_number, false);
state_->onTimeout(segment_number, false);
+ }
} else {
// in this case we wil never recover the timeout
+ ldr_->onTimeout(segment_number, true);
state_->onTimeout(segment_number, true);
}
scheduleNextInterests();
@@ -548,18 +643,18 @@ void RTCTransportProtocol::onInterestTimeout(Interest::Ptr &interest,
<< "On timeout next seg = " << indexer_verifier_->checkNextSuffix()
<< ", jump to " << segment_number;
// add an extra space in the window
- current_sync_win_++;
indexer_verifier_->jumpToIndex(segment_number);
}
state_->onTimeout(segment_number, false);
+ sendInterestForTimeout(segment_number);
scheduleNextInterests();
}
void RTCTransportProtocol::onNack(const ContentObject &content_object) {
struct nack_packet_t *nack =
(struct nack_packet_t *)content_object.getPayload()->data();
- uint32_t production_seg = nack->getProductionSegement();
+ uint32_t production_seg = nack->getProductionSegment();
uint32_t nack_segment = content_object.getName().getSuffix();
bool is_rtx = ldr_->isRtx(nack_segment);
@@ -592,12 +687,11 @@ void RTCTransportProtocol::onNack(const ContentObject &content_object) {
// remove the nack is it exists
if (tn_it != timeouts_or_nacks_.end()) timeouts_or_nacks_.erase(tn_it);
+ state_->onJumpForward(production_seg);
// the client is asking for content in the past
// switch to catch up state and increase the window
// this is true only if the packet is not an RTX
if (!is_rtx) current_state_ = SyncState::catch_up;
-
- updateSyncWindow();
} else {
// if production_seg == nack_segment we consider this a future nack, since
// production_seg is not yet created. this may happen in case of low
@@ -610,25 +704,50 @@ void RTCTransportProtocol::onNack(const ContentObject &content_object) {
// the client is asking for content in the future
// switch to in sync state and decrease the window
current_state_ = SyncState::in_sync;
- decreaseSyncWindow();
}
+ updateSyncWindow();
}
void RTCTransportProtocol::onProbe(const ContentObject &content_object) {
- bool valid = state_->onProbePacketReceived(content_object);
- if (!valid) return;
+ uint32_t suffix = content_object.getName().getSuffix();
+ ParamsRTC params = RTCState::getProbeParams(content_object);
+
+ if (ProbeHandler::getProbeType(suffix) == ProbeType::INIT) {
+ fec::FECType fec_type = params.fec_type;
+
+ if (fec_type != fec::FECType::UNKNOWN && !fec_decoder_) {
+ // Update FEC type
+ fec_type_ = fec_type;
+
+ // Enable FEC
+ enableFEC(std::bind(&RTCTransportProtocol::onFecPackets, this,
+ std::placeholders::_1),
+ fec::FECBase::BufferRequested(0));
+
+ // Update FEC parameters
+ indexer_verifier_->enableFec(fec_type);
+ indexer_verifier_->setNFec(0);
+ ldr_->setFecParams(fec::FECUtils::getBlockSymbols(fec_type),
+ fec::FECUtils::getSourceSymbols(fec_type));
+ fec_decoder_->setIOService(portal_->getThread().getIoService());
+ } else if (fec_type == fec::FECType::UNKNOWN) {
+ indexer_verifier_->disableFec();
+ }
+ }
- struct nack_packet_t *probe =
- (struct nack_packet_t *)content_object.getPayload()->data();
- uint32_t production_seg = probe->getProductionSegement();
+ if (!state_->onProbePacketReceived(content_object)) return;
- // as for the nacks set next_segment
+ // As for NACKs, set next_segment
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "on probe next seg = " << indexer_verifier_->checkNextSuffix()
- << ", jump to " << production_seg;
- indexer_verifier_->jumpToIndex(production_seg);
-
- ldr_->onProbePacketReceived(content_object);
+ << ", jump to " << params.prod_seg;
+ indexer_verifier_->jumpToIndex(params.prod_seg);
+
+ bool loss_detected = ldr_->onProbePacketReceived(content_object);
+ // we are not out of sync here but we are starting to download content from
+ // the cache, maybe beacuse the production rate increased suddenly. for this
+ // reason we put the state to catch up to increase the window
+ if (loss_detected) current_state_ = SyncState::catch_up;
updateSyncWindow();
}
@@ -636,12 +755,39 @@ void RTCTransportProtocol::onContentObjectReceived(
Interest &interest, ContentObject &content_object, std::error_code &ec) {
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Received content object of size: " << content_object.payloadSize();
- uint32_t payload_size = content_object.payloadSize();
+
uint32_t segment_number = content_object.getName().getSuffix();
+ PayloadType payload_type = content_object.getPayloadType();
+ PacketState state;
+
+ ContentObject *content_ptr = &content_object;
+ ContentObject::Ptr manifest_ptr = nullptr;
+
+ bool is_probe =
+ ProbeHandler::getProbeType(segment_number) != ProbeType::NOT_PROBE;
+ bool is_nack = !is_probe && content_object.payloadSize() == NACK_HEADER_SIZE;
+ bool is_fec = indexer_verifier_->isFec(segment_number);
+ bool is_manifest =
+ !is_probe && !is_nack && !is_fec && payload_type == PayloadType::MANIFEST;
+ bool is_data =
+ !is_probe && !is_nack && !is_fec && payload_type == PayloadType::DATA;
+ bool compute_stats = is_data || is_manifest;
ec = make_error_code(protocol_error::not_reassemblable);
- if (segment_number >= MIN_PROBE_SEQ) {
+ // A helper function to process manifests or data packets received
+ auto onDataPacketReceived = [this](ContentObject &content_object,
+ bool compute_stats) {
+ ldr_->onDataPacketReceived(content_object);
+ rc_->onDataPacketReceived(content_object, compute_stats);
+ updateSyncWindow();
+ };
+
+ // First verify the packet signature and apply the corresponding policy
+ auth::VerificationPolicy policy = verifier_->verify(content_object, is_fec);
+ indexer_verifier_->applyPolicy(interest, content_object, false, policy);
+
+ if (is_probe) {
DLOG_IF(INFO, VLOG_IS_ON(3)) << "Received probe " << segment_number;
if (*on_content_object_input_) {
(*on_content_object_input_)(*socket_->getInterface(), content_object);
@@ -650,7 +796,7 @@ void RTCTransportProtocol::onContentObjectReceived(
return;
}
- if (payload_size == NACK_HEADER_SIZE) {
+ if (is_nack) {
DLOG_IF(INFO, VLOG_IS_ON(3)) << "Received nack " << segment_number;
if (*on_content_object_input_) {
(*on_content_object_input_)(*socket_->getInterface(), content_object);
@@ -659,57 +805,115 @@ void RTCTransportProtocol::onContentObjectReceived(
return;
}
+ // content_ptr will point either to the input data packet or to a manifest
+ // whose FEC header has been removed
+ if (is_manifest) {
+ manifest_ptr = removeFecHeader(content_object);
+ if (manifest_ptr) {
+ content_ptr = manifest_ptr.get();
+ }
+ }
+
+ // From there, the packet is either a FEC, a manifest or a data packet.
DLOG_IF(INFO, VLOG_IS_ON(3)) << "Received content " << segment_number;
- bool compute_stats = true;
+ // Do not count timed out packets in stats
auto tn_it = timeouts_or_nacks_.find(segment_number);
if (tn_it != timeouts_or_nacks_.end()) {
compute_stats = false;
timeouts_or_nacks_.erase(tn_it);
}
- if (ldr_->isRtx(segment_number)) {
+
+ // Do not count retransmissions or losses in stats
+ if (ldr_->isRtx(segment_number) ||
+ ldr_->isPossibleLossWithNoRtx(segment_number)) {
compute_stats = false;
}
- // check if the packet was already received
- PacketState state = state_->isReceivedOrLost(segment_number);
+ // Fetch packet state
+ state = state_->getPacketState(segment_number);
- if (state != PacketState::RECEIVED) {
- // send packet to decoder
- if (fec_decoder_) {
- DLOG_IF(INFO, VLOG_IS_ON(4))
- << "send packet " << segment_number << " to FEC decoder";
- fec_decoder_->onDataPacket(
- content_object, content_object.headerSize() + rtc::DATA_HEADER_SIZE);
- }
- if (!indexer_verifier_->isFec(segment_number)) {
- // the packet may be alredy sent to the ap by the decoder, check again if
- // it is already received
- state = state_->isReceivedOrLost(segment_number);
- if (state != PacketState::RECEIVED) {
- DLOG_IF(INFO, VLOG_IS_ON(4)) << "Received content " << segment_number;
+ // Check if the packet is a retransmission
+ if (ldr_->isRtx(segment_number) && state != PacketState::RECEIVED) {
+ if (is_data || is_manifest) {
+ uint64_t rtt = ldr_->getRtxRtt(segment_number);
+ state_->onPacketRecoveredRtx(content_object, rtt);
- state_->onDataPacketReceived(content_object, compute_stats);
+ if (*on_content_object_input_) {
+ (*on_content_object_input_)(*socket_->getInterface(), content_object);
+ }
- if (*on_content_object_input_) {
- (*on_content_object_input_)(*socket_->getInterface(), content_object);
- }
- ec = make_error_code(protocol_error::success);
+ if (is_manifest) {
+ processManifest(interest, *content_ptr);
}
- } else {
- DLOG_IF(INFO, VLOG_IS_ON(4)) << "Received fec " << segment_number;
- state_->onFecPacketReceived(content_object);
+
+ ec = is_manifest ? make_error_code(protocol_error::not_reassemblable)
+ : make_error_code(protocol_error::success);
+
+ // The packet is considered received, return early
+ onDataPacketReceived(*content_ptr, compute_stats);
+ // this is a rtx but we may need to feed it in the decoder
+ decodePacket(content_object, is_manifest);
+ return;
}
- } else {
+
+ if (is_fec) {
+ state_->onFecPacketRecoveredRtx(content_object);
+ }
+ }
+
+ // Fetch packet state again; it may have changed
+ state = state_->getPacketState(segment_number);
+
+ // Check if the packet was already received
+ if (state == PacketState::RECEIVED || state == PacketState::TO_BE_RECEIVED) {
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "Received duplicated content " << segment_number << ", drop it";
ec = make_error_code(protocol_error::duplicated_content);
+ onDataPacketReceived(*content_ptr, compute_stats);
+ return;
}
- ldr_->onDataPacketReceived(content_object);
- rc_->onDataPacketReceived(content_object);
+ if (!is_fec) {
+ state_->dataToBeReceived(segment_number);
+ }
- updateSyncWindow();
+ // send packet to the decoder
+ decodePacket(content_object, is_manifest);
+
+ // We can return early if FEC
+ if (is_fec) {
+ DLOG_IF(INFO, VLOG_IS_ON(4)) << "Received FEC " << segment_number;
+ state_->onFecPacketReceived(content_object);
+ onDataPacketReceived(*content_ptr, compute_stats);
+ return;
+ }
+
+ // The packet may have been already sent to the app by the decoder, check
+ // again if it is already received
+ state = state_->getPacketState(
+ segment_number); // state == RECEIVED or TO_BE_RECEIVED
+
+ if (state != PacketState::RECEIVED) {
+ DLOG_IF(INFO, VLOG_IS_ON(4))
+ << (is_manifest ? "Received manifest " : "Received data ")
+ << segment_number;
+
+ if (is_manifest) {
+ processManifest(interest, *content_ptr);
+ }
+
+ state_->onDataPacketReceived(*content_ptr, compute_stats);
+
+ if (*on_content_object_input_) {
+ (*on_content_object_input_)(*socket_->getInterface(), content_object);
+ }
+
+ ec = is_manifest ? make_error_code(protocol_error::not_reassemblable)
+ : make_error_code(protocol_error::success);
+ }
+
+ onDataPacketReceived(*content_ptr, compute_stats);
}
void RTCTransportProtocol::sendStatsToApp(
@@ -729,33 +933,165 @@ void RTCTransportProtocol::sendStatsToApp(
stats_->updateReceivedNacks(received_nacks);
stats_->updateReceivedFEC(received_fec);
- stats_->updateAverageWindowSize(current_sync_win_);
- stats_->updateLossRatio(state_->getLossRate());
- stats_->updateAverageRtt(state_->getRTT());
+ stats_->updateAverageWindowSize(state_->getPendingInterestNumber());
+ stats_->updateLossRatio(state_->getPerSecondLossRate());
+ uint64_t rtt = state_->getAvgRTT();
+ stats_->updateAverageRtt(utils::SteadyTime::Microseconds(rtt * 1000));
+
stats_->updateQueuingDelay(state_->getQueuing());
stats_->updateLostData(lost_data);
stats_->updateDefinitelyLostData(definitely_lost);
stats_->updateRecoveredData(recovered_losses);
stats_->updateCCState((unsigned int)current_state_ ? 1 : 0);
(*stats_summary_)(*socket_->getInterface(), *stats_);
+ bool in_congestion = rc_->inCongestionState();
+ stats_->updateCongestionState(in_congestion);
+ double residual_losses = state_->getResidualLossRate();
+ stats_->updateResidualLossRate(residual_losses);
+ stats_->updateQualityScore(state_->getQualityScore());
+
+ // set alerts
+ if (rtt > MAX_RTT)
+ stats_->setAlert(interface::TransportStatistics::statsAlerts::LATENCY);
+ else
+ stats_->clearAlert(interface::TransportStatistics::statsAlerts::LATENCY);
+
+ if (in_congestion)
+ stats_->setAlert(interface::TransportStatistics::statsAlerts::CONGESTION);
+ else
+ stats_->clearAlert(
+ interface::TransportStatistics::statsAlerts::CONGESTION);
+
+ if (residual_losses > MAX_RESIDUAL_LOSSES)
+ stats_->setAlert(interface::TransportStatistics::statsAlerts::LOSSES);
+ else
+ stats_->clearAlert(interface::TransportStatistics::statsAlerts::LOSSES);
}
}
-void RTCTransportProtocol::onFecPackets(
- std::vector<std::pair<uint32_t, fec::buffer>> &packets) {
+void RTCTransportProtocol::decodePacket(ContentObject &content_object,
+ bool is_manifest) {
+ if (!fec_decoder_) return;
+
+ DLOG_IF(INFO, VLOG_IS_ON(4))
+ << "Send packet " << content_object.getName() << " to FEC decoder";
+
+ uint32_t offset =
+ is_manifest
+ ? (uint32_t)content_object.headerSize()
+ : (uint32_t)(content_object.headerSize() + rtc::DATA_HEADER_SIZE);
+ uint32_t metadata = static_cast<uint32_t>(content_object.getPayloadType());
+
+ fec_decoder_->onDataPacket(content_object, offset, metadata);
+}
+
+void RTCTransportProtocol::onFecPackets(fec::BufferArray &packets) {
+ Packet::Format format;
+ socket_->getSocketOption(interface::GeneralTransportOptions::PACKET_FORMAT,
+ format);
+
+ Name *name = nullptr;
+ socket_->getSocketOption(GeneralTransportOptions::NETWORK_NAME, &name);
+
for (auto &packet : packets) {
- PacketState state = state_->isReceivedOrLost(packet.first);
- if (state != PacketState::RECEIVED) {
- state_->onPacketRecoveredFec(packet.first);
- ldr_->onPacketRecoveredFec(packet.first);
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "Recovered packet " << packet.first << " through FEC.";
- reassembly_->reassemble(*packet.second, packet.first);
- } else {
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "Packet" << packet.first << "already received.";
+ uint32_t seq_number = packet.getIndex();
+ uint32_t metadata = packet.getMetadata();
+ fec::buffer buffer = packet.getBuffer();
+
+ PayloadType payload_type = static_cast<PayloadType>(metadata);
+ switch (payload_type) {
+ case PayloadType::DATA:
+ case PayloadType::MANIFEST:
+ break;
+ case PayloadType::UNSPECIFIED:
+ default:
+ payload_type = PayloadType::DATA;
+ break;
}
+
+ switch (state_->getPacketState(seq_number)) {
+ case PacketState::RECEIVED:
+ case PacketState::TO_BE_RECEIVED: {
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Packet " << seq_number << " already received";
+ break;
+ }
+ default: {
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Recovered packet " << seq_number << " through FEC";
+
+ if (payload_type == PayloadType::MANIFEST) {
+ name->setSuffix(seq_number);
+
+ auto interest =
+ core::PacketManager<>::getInstance().getPacket<Interest>(format);
+ interest->setName(*name);
+
+ auto content_object = toContentObject(
+ *name, format, payload_type, buffer->data(), buffer->length());
+
+ processManifest(*interest, *content_object);
+ }
+
+ state_->onPacketRecoveredFec(seq_number, (uint32_t)buffer->length());
+ ldr_->onPacketRecoveredFec(seq_number);
+
+ if (payload_type == PayloadType::DATA) {
+ verifier_->onDataRecoveredFec(seq_number);
+ reassembly_->reassemble(*buffer, seq_number);
+ }
+
+ break;
+ }
+ }
+ }
+}
+
+void RTCTransportProtocol::processManifest(Interest &interest,
+ ContentObject &manifest) {
+ auth::VerificationPolicy policy = verifier_->processManifest(manifest);
+ indexer_verifier_->applyPolicy(interest, manifest, false, policy);
+}
+
+ContentObject::Ptr RTCTransportProtocol::removeFecHeader(
+ const ContentObject &content_object) {
+ if (!fec_decoder_ || !fec_decoder_->getFecHeaderSize(false)) {
+ return nullptr;
}
+
+ size_t fec_header_size = fec_decoder_->getFecHeaderSize(false);
+ const uint8_t *payload =
+ content_object.data() + content_object.headerSize() + fec_header_size;
+ size_t payload_size = content_object.payloadSize() - fec_header_size;
+
+ ContentObject::Ptr co =
+ toContentObject(content_object.getName(), content_object.getFormat(),
+ content_object.getPayloadType(), payload, payload_size);
+
+ return co;
+}
+
+ContentObject::Ptr RTCTransportProtocol::toContentObject(
+ const Name &name, Packet::Format format, PayloadType payload_type,
+ const uint8_t *payload, std::size_t payload_size,
+ std::size_t additional_header_size) {
+ // Recreate ContentObject
+ ContentObject::Ptr co =
+ core::PacketManager<>::getInstance().getPacket<ContentObject>(
+ format, additional_header_size);
+ co->updateLength(payload_size);
+ co->append(payload_size);
+ co->trimStart(co->headerSize());
+
+ // Copy payload
+ std::memcpy(co->writableData(), payload, payload_size);
+
+ // Restore network headers and some fields
+ co->prepend(co->headerSize());
+ co->setName(name);
+ co->setPayloadType(payload_type);
+
+ return co;
}
} // end namespace rtc
diff --git a/libtransport/src/protocols/rtc/rtc.h b/libtransport/src/protocols/rtc/rtc.h
index e6431264d..a8a474216 100644
--- a/libtransport/src/protocols/rtc/rtc.h
+++ b/libtransport/src/protocols/rtc/rtc.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,10 +15,12 @@
#pragma once
-#include <protocols/datagram_reassembly.h>
+#include <protocols/rtc/rtc_forwarding_strategy.h>
#include <protocols/rtc/rtc_ldr.h>
#include <protocols/rtc/rtc_rc.h>
+#include <protocols/rtc/rtc_reassembly.h>
#include <protocols/rtc/rtc_state.h>
+#include <protocols/rtc/rtc_verifier.h>
#include <protocols/transport_protocol.h>
#include <unordered_set>
@@ -42,7 +44,9 @@ class RTCTransportProtocol : public TransportProtocol {
void resume() override;
- std::size_t transportHeaderLength() override;
+ std::size_t transportHeaderLength(bool isFEC) override;
+
+ auto shared_from_this() { return utils::shared_from(this); }
private:
enum class SyncState { catch_up = 0, in_sync = 1, last };
@@ -61,11 +65,11 @@ class RTCTransportProtocol : public TransportProtocol {
// window functions
void computeMaxSyncWindow();
void updateSyncWindow();
- void decreaseSyncWindow();
// packet functions
void sendRtxInterest(uint32_t seq);
void sendProbeInterest(uint32_t seq);
+ void sendInterestForTimeout(uint32_t seq);
void scheduleNextInterests() override;
void onInterestTimeout(Interest::Ptr &interest, const Name &name) override;
void onNack(const ContentObject &content_object);
@@ -76,6 +80,7 @@ class RTCTransportProtocol : public TransportProtocol {
void onPacketDropped(Interest &interest, ContentObject &content_object,
const std::error_code &reason) override {}
void onReassemblyFailed(std::uint32_t missing_segment) override {}
+ void processManifest(Interest &interest, ContentObject &manifest);
// interaction with app functions
void sendStatsToApp(uint32_t retx_count, uint32_t received_bytes,
@@ -84,11 +89,22 @@ class RTCTransportProtocol : public TransportProtocol {
uint32_t received_nacks, uint32_t received_fec);
// FEC functions
- void onFecPackets(std::vector<std::pair<uint32_t, fec::buffer>> &packets);
+ // send the received content object to the decoder
+ void decodePacket(ContentObject &content_object, bool is_manifest);
+ void onFecPackets(fec::BufferArray &packets);
+
+ // Utils
+ ContentObject::Ptr removeFecHeader(const ContentObject &content_object);
+ ContentObject::Ptr toContentObject(const Name &name, Packet::Format format,
+ PayloadType payload_type,
+ const uint8_t *payload,
+ std::size_t payload_size,
+ std::size_t additional_header_size = 0);
// protocol state
bool start_send_interest_;
SyncState current_state_;
+
// cwin vars
uint32_t current_sync_win_;
uint32_t max_sync_win_;
@@ -120,6 +136,10 @@ class RTCTransportProtocol : public TransportProtocol {
std::shared_ptr<RTCState> state_;
std::shared_ptr<RTCRateControl> rc_;
std::shared_ptr<RTCLossDetectionAndRecovery> ldr_;
+ std::shared_ptr<RTCVerifier> verifier_;
+
+ // forwarding strategy selection
+ RTCForwardingStrategy fwd_strategy_;
uint32_t number_;
};
diff --git a/libtransport/src/protocols/rtc/rtc_consts.h b/libtransport/src/protocols/rtc/rtc_consts.h
index d04bc1b1f..29b5a3a12 100644
--- a/libtransport/src/protocols/rtc/rtc_consts.h
+++ b/libtransport/src/protocols/rtc/rtc_consts.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -34,7 +34,7 @@ const double INTEREST_LIFETIME_REDUCTION_FACTOR = 0.8;
// increasing this number we increase the time that an
// interest will wait for the data packet to be produced
// at the producer socket
-const uint32_t PRODUCER_BUFFER_MS = 200; // ms
+const uint32_t PRODUCER_BUFFER_MS = 300; // ms
// interest scheduler
// const uint32_t MAX_INTERESTS_IN_BATCH = 5;
@@ -45,22 +45,22 @@ const uint32_t MAX_INTERESTS_IN_BATCH = 5; // number of seq numbers per
const uint32_t WAIT_FOR_INTEREST_BATCH = 20; // msec. timer that we wait to try
// to aggregate interest in the
// same packet
-const uint32_t MAX_PACING_BATCH = 5;
-// number of interest that we can send inside
-// the loop before they get dropped by the
-// kernel.
+const uint32_t MAX_PACING_BATCH = 5; // number of interest that we can send
+ // inside the loop before they get dropped
+ // by the kernel.
const uint32_t PACING_WAIT = 1000; // usec to wait betwing two pacing batch. As
// for MAX_PACING_BATCH this value was
// computed during tests
const uint32_t MAX_RTX_IN_BATCH = 10; // max rtx to send in loop
// packet const
-const uint32_t HICN_HEADER_SIZE = 40 + 20; // IPv6 + TCP bytes
-const uint32_t RTC_INTEREST_LIFETIME = 2000;
+const uint32_t RTC_INTEREST_LIFETIME = 4000;
// probes sequence range
const uint32_t MIN_PROBE_SEQ = 0xefffffff;
-const uint32_t MIN_RTT_PROBE_SEQ = MIN_PROBE_SEQ;
+const uint32_t MIN_INIT_PROBE_SEQ = MIN_PROBE_SEQ;
+const uint32_t MAX_INIT_PROBE_SEQ = 0xf7ffffff - 1;
+const uint32_t MIN_RTT_PROBE_SEQ = MAX_INIT_PROBE_SEQ + 1;
const uint32_t MAX_RTT_PROBE_SEQ = 0xffffffff - 1;
// RTT_PROBE_INTERVAL will be used during the section while
// INIT_RTT_PROBE_INTERVAL is used at the beginning to
@@ -72,25 +72,28 @@ const uint32_t INIT_RTT_PROBES = 40; // number of probes to init RTT
// to get an answer. we wait 100ms between each try
const uint32_t INIT_RTT_PROBE_RESTART = 100; // ms
// once we get the first probe we wait at most 60ms for the others
-const uint32_t INIT_RTT_PROBE_WAIT = 30; // ms
+const uint32_t INIT_RTT_PROBE_WAIT =
+ ((INIT_RTT_PROBES * INIT_RTT_PROBE_INTERVAL) / 1000) * 2; // ms
// we reuires at least 5 probes to be recevied
const uint32_t INIT_RTT_MIN_PROBES_TO_RECV = 5; // ms
const uint32_t MAX_PENDING_PROBES = 10;
// congestion
-const double MAX_QUEUING_DELAY = 100.0; // ms
+const double MAX_QUEUING_DELAY = 50.0; // ms
// data from cache
-const double MAX_DATA_FROM_CACHE = 0.25; // 25%
+const double MAX_DATA_FROM_CACHE = 0.10; // 10%
// window const
-const uint32_t INITIAL_WIN = 5; // pkts
-const uint32_t INITIAL_WIN_MAX = 1000000; // pkts
-const uint32_t WIN_MIN = 5; // pkts
+const uint32_t INITIAL_WIN = 5; // pkts
+const uint32_t INITIAL_WIN_MAX = 1000000; // pkts
+const uint32_t WIN_MIN = 5; // pkts
+const uint32_t WIN_MIN_WITH_AGGREGARED_DATA = 10; // pkts
const double CATCH_UP_WIN_INCREMENT = 1.2;
// used in rate control
const double WIN_DECREASE_FACTOR = 0.5;
const double WIN_INCREASE_FACTOR = 1.5;
+const uint32_t MIN_PROD_RATE_SHARING_MODE = 125000; // 1Mbps in bytes
// round in congestion
const double ROUNDS_BEFORE_TAKE_ACTION = 5;
@@ -105,10 +108,8 @@ const double MOVING_AVG_ALPHA = 0.8;
const double MILLI_IN_A_SEC = 1000.0;
const double MICRO_IN_A_SEC = 1000000.0;
-
-const double MAX_CACHED_PACKETS = 262144; // 2^18
- // about 50 sec of traffic at 50Mbps
- // with 1200 bytes packets
+const uint32_t ROUNDS_PER_SEC = (uint32_t)(MILLI_IN_A_SEC / ROUND_LEN);
+const uint32_t ROUNDS_PER_MIN = (uint32_t)ROUNDS_PER_SEC * 60;
const uint32_t MAX_ROUND_WHIOUT_PACKETS =
(20 * MILLI_IN_A_SEC) / ROUND_LEN; // 20 sec in rounds;
@@ -120,12 +121,91 @@ const uint64_t MAX_TIMER_RTX = ~0;
const uint32_t SENTINEL_TIMER_INTERVAL = 100; // ms
const uint32_t MAX_RTX_WITH_SENTINEL = 10; // packets
const double CATCH_UP_RTT_INCREMENT = 1.2;
+const double MAX_RESIDUAL_LOSS_RATE = 1.0; // %
+const uint32_t WAIT_BEFORE_FEC_UPDATE = ROUNDS_PER_SEC;
+const uint32_t MAX_RTT_BEFORE_FEC = 60; // ms
// used by producer
const uint32_t PRODUCER_STATS_INTERVAL = 200; // ms
-const uint32_t MIN_PRODUCTION_RATE = 10; // pps
- // min prod rate
- // set running several test
+const uint32_t MIN_PRODUCTION_RATE = 25; // pps, equal to min window *
+ // rounds in a second
+const uint32_t FEC_PACING_TIME = 5; // ms
+
+// aggregated data consts
+const uint16_t MAX_RTC_PAYLOAD_SIZE = 1200; // bytes
+const uint16_t MAX_AGGREGATED_PACKETS = 5; // pkt
+const uint32_t AGGREGATED_PACKETS_TIMER = 2; // ms
+
+// alert thresholds
+const uint32_t MAX_RTT = 200; // ms
+const double MAX_RESIDUAL_LOSSES = 0.05; // %
+
+const uint8_t FEC_MATRIX[64][10] = {
+ {1, 2, 2, 2, 3, 3, 4, 5, 5, 6}, // k = 1
+ {1, 2, 3, 3, 4, 5, 5, 6, 7, 9},
+ {2, 2, 3, 4, 5, 6, 7, 8, 9, 11},
+ {2, 3, 4, 5, 5, 7, 8, 9, 11, 13},
+ {2, 3, 4, 5, 6, 7, 9, 10, 12, 14}, // k = 5
+ {2, 3, 4, 6, 7, 8, 10, 12, 14, 16},
+ {2, 4, 5, 6, 8, 9, 11, 13, 15, 18},
+ {3, 4, 5, 7, 8, 10, 12, 14, 16, 19},
+ {3, 4, 6, 7, 9, 11, 13, 15, 18, 21},
+ {3, 4, 6, 8, 9, 11, 14, 16, 19, 23}, // k = 10
+ {3, 5, 6, 8, 10, 12, 14, 17, 20, 24},
+ {3, 5, 7, 8, 10, 13, 15, 18, 21, 26},
+ {3, 5, 7, 9, 11, 13, 16, 19, 23, 27},
+ {3, 5, 7, 9, 12, 14, 17, 20, 24, 28},
+ {4, 6, 8, 10, 12, 15, 18, 21, 25, 30}, // k = 15
+ {4, 6, 8, 10, 13, 15, 19, 22, 26, 31},
+ {4, 6, 8, 11, 13, 16, 19, 23, 27, 33},
+ {4, 6, 9, 11, 14, 17, 20, 24, 29, 34},
+ {4, 6, 9, 11, 14, 17, 21, 25, 30, 35},
+ {4, 7, 9, 12, 15, 18, 22, 26, 31, 37}, // k = 20
+ {4, 7, 9, 12, 15, 19, 22, 27, 32, 38},
+ {4, 7, 10, 13, 16, 19, 23, 28, 33, 40},
+ {5, 7, 10, 13, 16, 20, 24, 29, 34, 41},
+ {5, 7, 10, 13, 17, 20, 25, 30, 35, 42},
+ {5, 8, 11, 14, 17, 21, 26, 31, 37, 44}, // k = 25
+ {5, 8, 11, 14, 18, 22, 26, 31, 38, 45},
+ {5, 8, 11, 15, 18, 22, 27, 32, 39, 46},
+ {5, 8, 11, 15, 19, 23, 28, 33, 40, 48},
+ {5, 8, 12, 15, 19, 24, 28, 34, 41, 49},
+ {5, 9, 12, 16, 20, 24, 29, 35, 42, 50}, // k = 30
+ {5, 9, 12, 16, 20, 25, 30, 36, 43, 51},
+ {5, 9, 13, 16, 21, 25, 31, 37, 44, 53},
+ {6, 9, 13, 17, 21, 26, 31, 38, 45, 54},
+ {6, 9, 13, 17, 22, 26, 32, 39, 46, 55},
+ {6, 10, 13, 17, 22, 27, 33, 40, 47, 57}, // k = 35
+ {6, 10, 14, 18, 22, 28, 34, 40, 48, 58},
+ {6, 10, 14, 18, 23, 28, 34, 41, 49, 59},
+ {6, 10, 14, 19, 23, 29, 35, 42, 50, 60},
+ {6, 10, 14, 19, 24, 29, 36, 43, 52, 62},
+ {6, 10, 15, 19, 24, 30, 36, 44, 53, 63}, // k = 40
+ {6, 11, 15, 20, 25, 31, 37, 45, 54, 64},
+ {6, 11, 15, 20, 25, 31, 38, 46, 55, 65},
+ {7, 11, 15, 20, 26, 32, 39, 46, 56, 67},
+ {7, 11, 16, 21, 26, 32, 39, 47, 57, 68},
+ {7, 11, 16, 21, 27, 33, 40, 48, 58, 69}, // k = 45
+ {7, 11, 16, 21, 27, 33, 41, 49, 59, 70},
+ {7, 12, 16, 22, 27, 34, 41, 50, 60, 72},
+ {7, 12, 17, 22, 28, 34, 42, 51, 61, 73},
+ {7, 12, 17, 22, 28, 35, 43, 52, 62, 74},
+ {7, 12, 17, 23, 29, 36, 43, 52, 63, 75}, // k = 50
+ {7, 12, 17, 23, 29, 36, 44, 53, 64, 77},
+ {7, 12, 18, 23, 30, 37, 45, 54, 65, 78},
+ {7, 13, 18, 24, 30, 37, 45, 55, 66, 79},
+ {8, 13, 18, 24, 31, 38, 46, 56, 67, 80},
+ {8, 13, 18, 24, 31, 38, 47, 57, 68, 82}, // k = 55
+ {8, 13, 19, 25, 31, 39, 47, 57, 69, 83},
+ {8, 13, 19, 25, 32, 39, 48, 58, 70, 84},
+ {8, 13, 19, 25, 32, 40, 49, 59, 71, 85},
+ {8, 14, 19, 26, 33, 41, 50, 60, 72, 86},
+ {8, 14, 20, 26, 33, 41, 50, 61, 73, 88}, // k = 60
+ {8, 14, 20, 26, 34, 42, 51, 61, 74, 89},
+ {8, 14, 20, 27, 34, 42, 52, 62, 75, 90},
+ {8, 14, 20, 27, 34, 43, 52, 63, 76, 91},
+ {8, 14, 21, 27, 35, 43, 53, 64, 77, 92}, // k = 64
+};
} // namespace rtc
diff --git a/libtransport/src/protocols/rtc/rtc_data_path.cc b/libtransport/src/protocols/rtc/rtc_data_path.cc
index c098088a3..a421396b1 100644
--- a/libtransport/src/protocols/rtc/rtc_data_path.cc
+++ b/libtransport/src/protocols/rtc/rtc_data_path.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,14 +13,17 @@
* limitations under the License.
*/
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <protocols/rtc/rtc_data_path.h>
#include <stdlib.h>
#include <algorithm>
#include <cfloat>
#include <chrono>
+#include <cmath>
#define MAX_ROUNDS_WITHOUT_PKTS 10 // 2sec
+#define AVG_RTT_TIME 1000 // (ms) 1sec
namespace transport {
@@ -32,6 +35,8 @@ RTCDataPath::RTCDataPath(uint32_t path_id)
: path_id_(path_id),
min_rtt(UINT_MAX),
prev_min_rtt(UINT_MAX),
+ max_rtt(0),
+ prev_max_rtt(0),
min_owd(INT_MAX), // this is computed like in LEDBAT, so it is not the
// real OWD, but the measured one, that depends on the
// clock of sender and receiver. the only meaningful
@@ -46,20 +51,48 @@ RTCDataPath::RTCDataPath(uint32_t path_id)
largest_recv_seq_(0),
largest_recv_seq_time_(0),
avg_inter_arrival_(DBL_MAX),
+ rtt_sum_(0),
+ last_avg_rtt_compute_(0),
+ rtt_samples_(0),
+ avg_rtt_(0.0),
received_nacks_(false),
- received_packets_(false),
+ received_packets_(0),
rounds_without_packets_(0),
last_received_data_packet_(0),
- RTT_history_(HISTORY_LEN),
+ min_RTT_history_(HISTORY_LEN),
+ max_RTT_history_(HISTORY_LEN),
OWD_history_(HISTORY_LEN){};
-void RTCDataPath::insertRttSample(uint64_t rtt) {
- // for the rtt we only keep track of the min one
+void RTCDataPath::insertRttSample(
+ const utils::SteadyTime::Milliseconds& rtt_milliseconds, bool is_probe) {
+ // compute min rtt
+ uint64_t rtt = rtt_milliseconds.count();
if (rtt < min_rtt) min_rtt = rtt;
- last_received_data_packet_ =
- std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+
+ uint64_t now = utils::SteadyTime::nowMs().count();
+ last_received_data_packet_ = now;
+
+ // compute avg rtt
+ if (is_probe) {
+ // max rtt is computed only on probes to avoid to take into account the
+ // production time at the server
+ if (rtt > max_rtt) max_rtt = rtt;
+
+ rtt_sum_ += rtt;
+ rtt_samples_++;
+ }
+
+ if ((now - last_avg_rtt_compute_) >= AVG_RTT_TIME) {
+ // compute a new avg rtt
+ // if rtt_samples_ = 0 keep the same rtt
+ if (rtt_samples_ != 0) avg_rtt_ = (double)rtt_sum_ / (double)rtt_samples_;
+
+ rtt_sum_ = 0;
+ rtt_samples_ = 0;
+ last_avg_rtt_compute_ = now;
+ }
+
+ received_packets_++;
}
void RTCDataPath::insertOwdSample(int64_t owd) {
@@ -84,18 +117,12 @@ void RTCDataPath::insertOwdSample(int64_t owd) {
int64_t diff = std::abs(owd - last_owd_);
last_owd_ = owd;
jitter_ += (1.0 / 16.0) * ((double)diff - jitter_);
-
- // 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 segment_number) {
// got packet in sequence, compute gap
if (largest_recv_seq_ == (segment_number - 1)) {
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint64_t delta = now - largest_recv_seq_time_;
largest_recv_seq_ = segment_number;
largest_recv_seq_time_ = now;
@@ -110,10 +137,7 @@ void RTCDataPath::computeInterArrivalGap(uint32_t segment_number) {
// ooo packet, update the stasts if needed
if (largest_recv_seq_ <= segment_number) {
largest_recv_seq_ = segment_number;
- largest_recv_seq_time_ =
- std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ largest_recv_seq_time_ = utils::SteadyTime::nowMs().count();
}
}
@@ -124,12 +148,17 @@ double RTCDataPath::getInterArrivalGap() {
return avg_inter_arrival_;
}
-bool RTCDataPath::isActive() {
+bool RTCDataPath::isValidProducer() {
if (received_nacks_ && rounds_without_packets_ < MAX_ROUNDS_WITHOUT_PKTS)
return true;
return false;
}
+bool RTCDataPath::isActive() {
+ if (rounds_without_packets_ < MAX_ROUNDS_WITHOUT_PKTS) return true;
+ return false;
+}
+
bool RTCDataPath::pathToProducer() {
if (received_nacks_) return true;
return false;
@@ -146,10 +175,20 @@ void RTCDataPath::roundEnd() {
min_rtt = prev_min_rtt;
}
+ // same for max_rtt
+ if (max_rtt != 0) {
+ prev_max_rtt = max_rtt;
+ } else {
+ max_rtt = prev_max_rtt;
+ }
+
if (min_rtt == 0) min_rtt = 1;
+ if (max_rtt == 0) max_rtt = 1;
- RTT_history_.pushBack(min_rtt);
+ min_RTT_history_.pushBack(min_rtt);
+ max_RTT_history_.pushBack(max_rtt);
min_rtt = UINT_MAX;
+ max_rtt = 0;
// do the same for min owd
if (min_owd != INT_MAX) {
@@ -163,32 +202,47 @@ void RTCDataPath::roundEnd() {
min_owd = INT_MAX;
}
- if (!received_packets_)
+ if (received_packets_ == 0)
rounds_without_packets_++;
else
rounds_without_packets_ = 0;
- received_packets_ = false;
+ received_packets_ = 0;
}
uint32_t RTCDataPath::getPathId() { return path_id_; }
-double RTCDataPath::getQueuingDealy() { return queuing_delay; }
+double RTCDataPath::getQueuingDealy() {
+ if (queuing_delay == DBL_MAX) return 0;
+ return queuing_delay;
+}
uint64_t RTCDataPath::getMinRtt() {
- if (RTT_history_.size() != 0) return RTT_history_.begin();
+ if (min_RTT_history_.size() != 0) return min_RTT_history_.begin();
+ return 0;
+}
+
+uint64_t RTCDataPath::getAvgRtt() { return std::round(avg_rtt_); }
+
+uint64_t RTCDataPath::getMaxRtt() {
+ if (max_RTT_history_.size() != 0) return max_RTT_history_.begin();
return 0;
}
int64_t RTCDataPath::getMinOwd() {
if (OWD_history_.size() != 0) return OWD_history_.begin();
- return 0;
+ return INT_MAX;
}
double RTCDataPath::getJitter() { return jitter_; }
uint64_t RTCDataPath::getLastPacketTS() { return last_received_data_packet_; }
-void RTCDataPath::clearRtt() { RTT_history_.clear(); }
+uint32_t RTCDataPath::getPacketsLastRound() { return received_packets_; }
+
+void RTCDataPath::clearRtt() {
+ min_RTT_history_.clear();
+ max_RTT_history_.clear();
+}
} // end namespace rtc
diff --git a/libtransport/src/protocols/rtc/rtc_data_path.h b/libtransport/src/protocols/rtc/rtc_data_path.h
index c5c37fc0d..ba5201fe8 100644
--- a/libtransport/src/protocols/rtc/rtc_data_path.h
+++ b/libtransport/src/protocols/rtc/rtc_data_path.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,7 +15,9 @@
#pragma once
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <stdint.h>
+#include <utils/max_filter.h>
#include <utils/min_filter.h>
#include <climits>
@@ -34,19 +36,24 @@ class RTCDataPath {
RTCDataPath(uint32_t path_id);
public:
- void insertRttSample(uint64_t rtt);
+ void insertRttSample(const utils::SteadyTime::Milliseconds &rtt,
+ bool is_probe);
void insertOwdSample(int64_t owd);
void computeInterArrivalGap(uint32_t segment_number);
void receivedNack();
uint32_t getPathId();
uint64_t getMinRtt();
+ uint64_t getAvgRtt();
+ uint64_t getMaxRtt();
double getQueuingDealy();
double getInterArrivalGap();
double getJitter();
- bool isActive();
- bool pathToProducer();
+ bool isActive(); // pakets recevied from this path in the last rounds
+ bool pathToProducer(); // path from a producer
+ bool isValidProducer(); // path from a producer that is also active
uint64_t getLastPacketTS();
+ uint32_t getPacketsLastRound();
void clearRtt();
@@ -60,6 +67,9 @@ class RTCDataPath {
uint64_t min_rtt;
uint64_t prev_min_rtt;
+ uint64_t max_rtt;
+ uint64_t prev_max_rtt;
+
int64_t min_owd;
int64_t prev_min_owd;
@@ -74,19 +84,26 @@ class RTCDataPath {
uint64_t largest_recv_seq_time_;
double avg_inter_arrival_;
+ // compute the avg rtt over one sec
+ uint64_t rtt_sum_;
+ uint64_t last_avg_rtt_compute_;
+ uint32_t rtt_samples_;
+ double avg_rtt_;
+
// 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
bool received_nacks_;
- bool received_packets_;
- uint8_t rounds_without_packets_; // if we don't get any packet
+ uint32_t received_packets_;
+ uint32_t rounds_without_packets_; // if we don't get any packet
// for MAX_ROUNDS_WITHOUT_PKTS
// we consider the path inactive
uint64_t last_received_data_packet_; // timestamp for the last data received
// on this path
- utils::MinFilter<uint64_t> RTT_history_;
+ utils::MinFilter<uint64_t> min_RTT_history_;
+ utils::MaxFilter<uint64_t> max_RTT_history_;
utils::MinFilter<int64_t> OWD_history_;
};
diff --git a/libtransport/src/protocols/rtc/rtc_forwarding_strategy.cc b/libtransport/src/protocols/rtc/rtc_forwarding_strategy.cc
new file mode 100644
index 000000000..4bbd7eac0
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_forwarding_strategy.cc
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hicn/transport/interfaces/notification.h>
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_forwarding_strategy.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+using namespace transport::interface;
+
+const double FWD_MAX_QUEUE = 30.0; // ms
+const double FWD_MAX_RTT = MAX_RTT_BEFORE_FEC; // ms
+const double FWD_MAX_LOSS_RATE = 0.1;
+
+RTCForwardingStrategy::RTCForwardingStrategy()
+ : low_rate_app_(false),
+ init_(false),
+ forwarder_set_(false),
+ selected_strategy_(NONE),
+ current_strategy_(NONE),
+ rounds_since_last_set_(0),
+ portal_(nullptr),
+ state_(nullptr) {}
+
+RTCForwardingStrategy::~RTCForwardingStrategy() {}
+
+void RTCForwardingStrategy::setCallback(
+ interface::StrategyCallback&& callback) {
+ callback_ = std::move(callback);
+}
+
+void RTCForwardingStrategy::initFwdStrategy(
+ std::shared_ptr<core::Portal> portal, core::Prefix& prefix, RTCState* state,
+ interface::RtcTransportRecoveryStrategies strategy) {
+ switch (strategy) {
+ case interface::RtcTransportRecoveryStrategies::LOW_RATE_AND_BESTPATH:
+ init_ = true;
+ low_rate_app_ = true;
+ selected_strategy_ = BEST_PATH;
+ current_strategy_ = BEST_PATH;
+ break;
+ case interface::RtcTransportRecoveryStrategies::LOW_RATE_AND_REPLICATION:
+ init_ = true;
+ low_rate_app_ = true;
+ selected_strategy_ = REPLICATION;
+ current_strategy_ = REPLICATION;
+ break;
+ case interface::RtcTransportRecoveryStrategies::
+ LOW_RATE_AND_ALL_FWD_STRATEGIES:
+ init_ = true;
+ low_rate_app_ = true;
+ selected_strategy_ = BEST_PATH;
+ current_strategy_ = BEST_PATH;
+ break;
+ case interface::RtcTransportRecoveryStrategies::DELAY_AND_BESTPATH:
+ init_ = true;
+ low_rate_app_ = false;
+ selected_strategy_ = BEST_PATH;
+ current_strategy_ = BEST_PATH;
+ break;
+ case interface::RtcTransportRecoveryStrategies::DELAY_AND_REPLICATION:
+ init_ = true;
+ low_rate_app_ = false;
+ selected_strategy_ = REPLICATION;
+ current_strategy_ = REPLICATION;
+ break;
+ case interface::RtcTransportRecoveryStrategies::RECOVERY_OFF:
+ case interface::RtcTransportRecoveryStrategies::RTX_ONLY:
+ case interface::RtcTransportRecoveryStrategies::FEC_ONLY:
+ case interface::RtcTransportRecoveryStrategies::DELAY_BASED:
+ case interface::RtcTransportRecoveryStrategies::LOW_RATE:
+ case interface::RtcTransportRecoveryStrategies::FEC_ONLY_LOW_RES_LOSSES:
+ default:
+ // fwd strategies are not used
+ init_ = false;
+ }
+
+ if (init_) {
+ rounds_since_last_set_ = 0;
+ prefix_ = prefix;
+ portal_ = portal;
+ state_ = state;
+ }
+}
+
+void RTCForwardingStrategy::checkStrategy() {
+ strategy_t used_strategy = selected_strategy_;
+ if (used_strategy == BOTH) used_strategy = current_strategy_;
+ assert(used_strategy == BEST_PATH || used_strategy == REPLICATION ||
+ used_strategy == NONE);
+
+ notification::ForwardingStrategy strategy =
+ notification::ForwardingStrategy::NONE;
+ switch (used_strategy) {
+ case BEST_PATH:
+ strategy = notification::ForwardingStrategy::BEST_PATH;
+ break;
+ case REPLICATION:
+ strategy = notification::ForwardingStrategy::REPLICATION;
+ break;
+ default:
+ break;
+ }
+ callback_(strategy);
+
+ if (!init_) return;
+
+ if (selected_strategy_ == NONE) return;
+
+ if (selected_strategy_ == BEST_PATH) {
+ checkStrategyBestPath();
+ return;
+ }
+
+ if (selected_strategy_ == REPLICATION) {
+ checkStrategyReplication();
+ return;
+ }
+
+ checkStrategyBoth();
+}
+
+void RTCForwardingStrategy::checkStrategyBestPath() {
+ if (!forwarder_set_) {
+ setStrategy(BEST_PATH);
+ forwarder_set_ = true;
+ return;
+ }
+
+ if (low_rate_app_) {
+ // this is used for gaming
+ uint8_t qs = state_->getQualityScore();
+
+ if (qs >= 4 || rounds_since_last_set_ < 25) { // wait a least 5 sec
+ // between each switch
+ rounds_since_last_set_++;
+ return;
+ }
+
+ // try to switch path
+ setStrategy(BEST_PATH);
+ } else {
+ if (rounds_since_last_set_ < 25) { // wait a least 5 sec
+ // between each switch
+ rounds_since_last_set_++;
+ return;
+ }
+
+ double queue = state_->getQueuing();
+ double rtt = state_->getAvgRTT();
+ double loss_rate = state_->getPerSecondLossRate();
+
+ if (queue >= FWD_MAX_QUEUE || rtt >= FWD_MAX_RTT ||
+ loss_rate > FWD_MAX_LOSS_RATE) {
+ // try to switch path
+ setStrategy(BEST_PATH);
+ }
+ }
+}
+
+void RTCForwardingStrategy::checkStrategyReplication() {
+ if (!forwarder_set_) {
+ setStrategy(REPLICATION);
+ forwarder_set_ = true;
+ return;
+ }
+
+ // here we have nothing to do for the moment
+ return;
+}
+
+void RTCForwardingStrategy::checkStrategyBoth() {
+ if (!forwarder_set_) {
+ setStrategy(current_strategy_);
+ forwarder_set_ = true;
+ return;
+ }
+
+ checkStrategyBestPath();
+
+ // TODO
+ // for the moment we use only best path.
+ // for later:
+ // 1. if both paths are bad use replication
+ // 2. while using replication compute the effectiveness. if the majority of
+ // the packets are coming from a single path, try to use bestpath
+}
+
+void RTCForwardingStrategy::setStrategy(strategy_t strategy) {
+ rounds_since_last_set_ = 0;
+ current_strategy_ = strategy;
+ portal_->setForwardingStrategy(prefix_,
+ string_strategies_[current_strategy_]);
+}
+
+} // namespace rtc
+
+} // namespace protocol
+
+} // namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_forwarding_strategy.h b/libtransport/src/protocols/rtc/rtc_forwarding_strategy.h
new file mode 100644
index 000000000..c2227e09f
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_forwarding_strategy.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <core/portal.h>
+#include <hicn/transport/interfaces/callbacks.h>
+#include <protocols/rtc/rtc_state.h>
+
+#include <array>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RTCForwardingStrategy {
+ public:
+ enum strategy_t {
+ BEST_PATH,
+ REPLICATION,
+ BOTH,
+ NONE,
+ };
+
+ RTCForwardingStrategy();
+ ~RTCForwardingStrategy();
+
+ void initFwdStrategy(std::shared_ptr<core::Portal> portal,
+ core::Prefix& prefix, RTCState* state,
+ interface::RtcTransportRecoveryStrategies strategy);
+
+ void checkStrategy();
+ void setCallback(interface::StrategyCallback&& callback);
+
+ private:
+ void checkStrategyBestPath();
+ void checkStrategyReplication();
+ void checkStrategyBoth();
+
+ void setStrategy(strategy_t strategy);
+
+ std::array<std::string, 4> string_strategies_ = {"bestpath", "replication",
+ "both", "none"};
+
+ bool low_rate_app_; // if set to true the best path strategy will
+ // trigger a path switch based on the quality
+ // score, otherwise it will use the RTT,
+ // queuing delay and loss rate
+ bool init_; // true if all val are initializes
+ bool forwarder_set_; // true if the strategy is been set at least
+ // once
+ strategy_t selected_strategy_; // this is the strategy selected using socket
+ // options. this can also be equal to BOTH
+ strategy_t current_strategy_; // if both strategies can be used this
+ // indicates the one that is currently in use
+ // that can be only replication or best path
+ uint32_t rounds_since_last_set_;
+ core::Prefix prefix_;
+ std::shared_ptr<core::Portal> portal_;
+ RTCState* state_;
+ interface::StrategyCallback callback_;
+};
+
+} // namespace rtc
+
+} // namespace protocol
+
+} // namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_indexer.h b/libtransport/src/protocols/rtc/rtc_indexer.h
index 4aee242bb..f87fcaaa2 100644
--- a/libtransport/src/protocols/rtc/rtc_indexer.h
+++ b/libtransport/src/protocols/rtc/rtc_indexer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -18,8 +18,10 @@
#include <protocols/errors.h>
#include <protocols/fec_utils.h>
#include <protocols/indexer.h>
+#include <protocols/rtc/probe_handler.h>
#include <protocols/rtc/rtc_consts.h>
#include <protocols/transport_protocol.h>
+#include <utils/suffix_strategy.h>
#include <deque>
@@ -45,7 +47,7 @@ class RtcIndexer : public Indexer {
n_fec_(0),
n_current_fec_(n_fec_) {}
- RtcIndexer(RtcIndexer &&other) : Indexer(std::forward<Indexer>(other)) {}
+ RtcIndexer(RtcIndexer &&other) : Indexer(other) {}
~RtcIndexer() {}
@@ -54,7 +56,7 @@ class RtcIndexer : public Indexer {
n_fec_ = 0;
}
- uint32_t checkNextSuffix() override { return next_suffix_; }
+ uint32_t checkNextSuffix() const override { return next_suffix_; }
uint32_t getNextSuffix() override {
if (isFec(next_suffix_)) {
@@ -77,7 +79,7 @@ class RtcIndexer : public Indexer {
first_suffix_ = suffix % LIMIT;
}
- uint32_t getFirstSuffix() override { return first_suffix_; }
+ uint32_t getFirstSuffix() const override { return first_suffix_; }
uint32_t jumpToIndex(uint32_t index) override {
next_suffix_ = index % LIMIT;
@@ -87,30 +89,8 @@ class RtcIndexer : public Indexer {
void onContentObject(core::Interest &interest,
core::ContentObject &content_object,
bool reassembly) override {
- setVerifier();
- auto ret = verifier_->verifyPackets(&content_object);
-
- switch (ret) {
- case auth::VerificationPolicy::ACCEPT: {
- if (reassembly) {
- reassembly_->reassemble(content_object);
- }
- break;
- }
-
- case auth::VerificationPolicy::UNKNOWN:
- case auth::VerificationPolicy::DROP: {
- transport_->onPacketDropped(
- interest, content_object,
- make_error_code(protocol_error::verification_failed));
- break;
- }
-
- case auth::VerificationPolicy::ABORT: {
- transport_->onContentReassembled(
- make_error_code(protocol_error::session_aborted));
- break;
- }
+ if (reassembly) {
+ reassembly_->reassemble(content_object);
}
}
@@ -120,13 +100,12 @@ class RtcIndexer : public Indexer {
uint32_t getNextReassemblySegment() override {
throw errors::RuntimeException(
"Get reassembly segment called on rtc indexer. RTC indexer does not "
- "provide "
- "reassembly.");
+ "provide reassembly.");
}
bool isFinalSuffixDiscovered() override { return true; }
- uint32_t getFinalSuffix() override { return LIMIT; }
+ uint32_t getFinalSuffix() const override { return LIMIT; }
void enableFec(fec::FECType fec_type) override { fec_type_ = fec_type; }
@@ -137,13 +116,13 @@ class RtcIndexer : public Indexer {
n_current_fec_ = n_fec_;
}
- uint32_t getNFec() override { return n_fec_; }
+ uint32_t getNFec() const override { return n_fec_; }
bool isFec(uint32_t index) override {
return isFec(fec_type_, index, first_suffix_);
}
- double getFecOverhead() override {
+ double getFecOverhead() const override {
if (fec_type_ == fec::FECType::UNKNOWN) {
return 0;
}
@@ -152,7 +131,7 @@ class RtcIndexer : public Indexer {
return (double)n_fec_ / k;
}
- double getMaxFecOverhead() override {
+ double getMaxFecOverhead() const override {
if (fec_type_ == fec::FECType::UNKNOWN) {
return 0;
}
diff --git a/libtransport/src/protocols/rtc/rtc_ldr.cc b/libtransport/src/protocols/rtc/rtc_ldr.cc
index f0de48871..6e88a8636 100644
--- a/libtransport/src/protocols/rtc/rtc_ldr.cc
+++ b/libtransport/src/protocols/rtc/rtc_ldr.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,12 @@
#include <glog/logging.h>
#include <protocols/rtc/rtc_consts.h>
#include <protocols/rtc/rtc_ldr.h>
+#include <protocols/rtc/rtc_rs_delay.h>
+#include <protocols/rtc/rtc_rs_fec_only.h>
+#include <protocols/rtc/rtc_rs_low_rate.h>
+#include <protocols/rtc/rtc_rs_recovery_off.h>
+#include <protocols/rtc/rtc_rs_rtx_only.h>
+#include <protocols/rtc/rtc_state.h>
#include <algorithm>
#include <unordered_set>
@@ -27,483 +33,200 @@ namespace protocol {
namespace rtc {
RTCLossDetectionAndRecovery::RTCLossDetectionAndRecovery(
- Indexer *indexer, SendRtxCallback &&callback, asio::io_service &io_service)
- : rtx_on_(false),
- fec_on_(false),
- next_rtx_timer_(MAX_TIMER_RTX),
- last_event_(0),
- sentinel_timer_interval_(MAX_TIMER_RTX),
- indexer_(indexer),
- send_rtx_callback_(std::move(callback)) {
- timer_ = std::make_unique<asio::steady_timer>(io_service);
- sentinel_timer_ = std::make_unique<asio::steady_timer>(io_service);
+ Indexer *indexer, asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies type,
+ RecoveryStrategy::SendRtxCallback &&callback,
+ interface::StrategyCallback &&external_callback) {
+ if (type == interface::RtcTransportRecoveryStrategies::RECOVERY_OFF) {
+ rs_ = std::make_shared<RecoveryStrategyRecoveryOff>(
+ indexer, std::move(callback), io_service, type,
+ std::move(external_callback));
+ } else if (type == interface::RtcTransportRecoveryStrategies::DELAY_BASED ||
+ type == interface::RtcTransportRecoveryStrategies::
+ DELAY_AND_BESTPATH ||
+ type == interface::RtcTransportRecoveryStrategies::
+ DELAY_AND_REPLICATION) {
+ rs_ = std::make_shared<RecoveryStrategyDelayBased>(
+ indexer, std::move(callback), io_service, type,
+ std::move(external_callback));
+ } else if (type == interface::RtcTransportRecoveryStrategies::FEC_ONLY ||
+ type == interface::RtcTransportRecoveryStrategies::
+ FEC_ONLY_LOW_RES_LOSSES) {
+ rs_ = std::make_shared<RecoveryStrategyFecOnly>(
+ indexer, std::move(callback), io_service, type,
+ std::move(external_callback));
+ } else if (type == interface::RtcTransportRecoveryStrategies::LOW_RATE ||
+ type == interface::RtcTransportRecoveryStrategies::
+ LOW_RATE_AND_BESTPATH ||
+ type == interface::RtcTransportRecoveryStrategies::
+ LOW_RATE_AND_REPLICATION ||
+ type == interface::RtcTransportRecoveryStrategies::
+ LOW_RATE_AND_ALL_FWD_STRATEGIES) {
+ rs_ = std::make_shared<RecoveryStrategyLowRate>(
+ indexer, std::move(callback), io_service, type,
+ std::move(external_callback));
+ } else {
+ // default
+ type = interface::RtcTransportRecoveryStrategies::RTX_ONLY;
+ rs_ = std::make_shared<RecoveryStrategyRtxOnly>(
+ indexer, std::move(callback), io_service, type,
+ std::move(external_callback));
+ }
}
RTCLossDetectionAndRecovery::~RTCLossDetectionAndRecovery() {}
-void RTCLossDetectionAndRecovery::turnOnRTX() {
- rtx_on_ = true;
- scheduleSentinelTimer(state_->getRTT() * CATCH_UP_RTT_INCREMENT);
-}
-
-void RTCLossDetectionAndRecovery::turnOffRTX() {
- rtx_on_ = false;
- clear();
-}
-
-uint32_t RTCLossDetectionAndRecovery::computeFecPacketsToAsk(bool in_sync) {
- uint32_t current_fec = indexer_->getNFec();
- double current_loss_rate = state_->getLossRate();
- double last_loss_rate = state_->getLastRoundLossRate();
-
- // when in sync ask for fec only if there are losses for 2 rounds
- if (in_sync && current_fec == 0 &&
- (current_loss_rate == 0 || last_loss_rate == 0))
- return 0;
-
- double loss_rate = state_->getMaxLossRate() * 1.5;
-
- if (!in_sync && loss_rate == 0) loss_rate = 0.05;
- if (loss_rate > 0.5) loss_rate = 0.5;
-
- double exp_losses = (double)k_ * loss_rate;
- uint32_t fec_to_ask = ceil(exp_losses / (1 - loss_rate));
-
- if (fec_to_ask > (n_ - k_)) fec_to_ask = n_ - k_;
-
- return fec_to_ask;
+void RTCLossDetectionAndRecovery::changeRecoveryStrategy(
+ interface::RtcTransportRecoveryStrategies type) {
+ if (type == rs_->getType()) return;
+
+ rs_->updateType(type);
+ if (type == interface::RtcTransportRecoveryStrategies::RECOVERY_OFF) {
+ rs_ =
+ std::make_shared<RecoveryStrategyRecoveryOff>(std::move(*(rs_.get())));
+ } else if (type == interface::RtcTransportRecoveryStrategies::DELAY_BASED ||
+ type == interface::RtcTransportRecoveryStrategies::
+ DELAY_AND_BESTPATH ||
+ type == interface::RtcTransportRecoveryStrategies::
+ DELAY_AND_REPLICATION) {
+ rs_ = std::make_shared<RecoveryStrategyDelayBased>(std::move(*(rs_.get())));
+ } else if (type == interface::RtcTransportRecoveryStrategies::FEC_ONLY ||
+ type == interface::RtcTransportRecoveryStrategies::
+ FEC_ONLY_LOW_RES_LOSSES) {
+ rs_ = std::make_shared<RecoveryStrategyFecOnly>(std::move(*(rs_.get())));
+ } else if (type == interface::RtcTransportRecoveryStrategies::LOW_RATE ||
+ type == interface::RtcTransportRecoveryStrategies::
+ LOW_RATE_AND_BESTPATH ||
+ type == interface::RtcTransportRecoveryStrategies::
+ LOW_RATE_AND_REPLICATION ||
+ type == interface::RtcTransportRecoveryStrategies::
+ LOW_RATE_AND_ALL_FWD_STRATEGIES) {
+ rs_ = std::make_shared<RecoveryStrategyLowRate>(std::move(*(rs_.get())));
+ } else {
+ // default
+ rs_ = std::make_shared<RecoveryStrategyRtxOnly>(std::move(*(rs_.get())));
+ }
}
void RTCLossDetectionAndRecovery::onNewRound(bool in_sync) {
- uint64_t rtt = state_->getRTT();
- if (!fec_on_ && rtt >= 100) {
- // turn on fec, here we may have no info so ask for all packets
- fec_on_ = true;
- turnOffRTX();
- indexer_->setNFec(computeFecPacketsToAsk(in_sync));
- return;
- }
-
- if (fec_on_ && rtt > 80) {
- // keep using fec, maybe update it
- indexer_->setNFec(computeFecPacketsToAsk(in_sync));
- return;
- }
-
- if ((fec_on_ && rtt <= 80) || (!rtx_on_ && rtt <= 100)) {
- // turn on rtx
- fec_on_ = false;
- indexer_->setNFec(0);
- turnOnRTX();
- return;
- }
+ rs_->incRoundId();
+ rs_->onNewRound(in_sync);
}
-void RTCLossDetectionAndRecovery::onTimeout(uint32_t seq) {
- // always add timeouts to the RTX list to avoid to send the same packet as if
- // it was not a rtx
- addToRetransmissions(seq, seq + 1);
- last_event_ = getNow();
+bool RTCLossDetectionAndRecovery::onTimeout(uint32_t seq, bool lost) {
+ if (!lost) {
+ return detectLoss(seq, seq + 1, false);
+ } else {
+ rs_->onLostTimeout(seq);
+ }
+ return false;
}
-void RTCLossDetectionAndRecovery::onPacketRecoveredFec(uint32_t seq) {
- // if an RTX is scheduled for a packet recovered using FEC delete it
- deleteRtx(seq);
- recover_with_fec_.erase(seq);
+bool RTCLossDetectionAndRecovery::onPacketRecoveredFec(uint32_t seq) {
+ rs_->receivedPacket(seq);
+ return false;
}
-void RTCLossDetectionAndRecovery::onDataPacketReceived(
+bool RTCLossDetectionAndRecovery::onDataPacketReceived(
const core::ContentObject &content_object) {
- last_event_ = getNow();
-
uint32_t seq = content_object.getName().getSuffix();
- if (deleteRtx(seq)) {
- state_->onPacketRecoveredRtx(seq);
- } else {
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "received data. add from "
- << state_->getHighestSeqReceivedInOrder() + 1 << " to " << seq;
- addToRetransmissions(state_->getHighestSeqReceivedInOrder() + 1, seq);
- }
+ bool is_rtx = rs_->isRtx(seq);
+ rs_->receivedPacket(seq);
+ bool ret = false;
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "received data. add from "
+ << rs_->getState()->getHighestSeqReceived() + 1 << " to " << seq;
+ if (!is_rtx)
+ ret = detectLoss(rs_->getState()->getHighestSeqReceived() + 1, seq, false);
+
+ rs_->getState()->updateHighestSeqReceived(seq);
+ return ret;
}
-void RTCLossDetectionAndRecovery::onNackPacketReceived(
+bool RTCLossDetectionAndRecovery::onNackPacketReceived(
const core::ContentObject &nack) {
- last_event_ = getNow();
-
- uint32_t seq = nack.getName().getSuffix();
-
struct nack_packet_t *nack_pkt =
(struct nack_packet_t *)nack.getPayload()->data();
- uint32_t production_seq = nack_pkt->getProductionSegement();
+ uint32_t production_seq = nack_pkt->getProductionSegment();
+ uint32_t seq = nack.getName().getSuffix();
- if (production_seq > seq) {
- // this is a past nack, all data before productionSeq are lost. if
- // productionSeq > state_->getHighestSeqReceivedInOrder() is impossible to
- // recover any packet. If this is not the case we can try to recover the
- // packets between state_->getHighestSeqReceivedInOrder() and productionSeq.
- // e.g.: the client receives packets 8 10 11 9 where 9 is a nack with
- // productionSeq = 14. 9 is lost but we can try to recover packets 12 13 and
- // 14 that are not arrived yet
- deleteRtx(seq);
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "received past nack. add from "
- << state_->getHighestSeqReceivedInOrder() + 1
- << " to " << production_seq;
- addToRetransmissions(state_->getHighestSeqReceivedInOrder() + 1,
- production_seq);
- } else {
- // future nack. here there should be a gap between the last data received
- // and this packet and is it possible to recover the packets between the
- // last received data and the production seq. we should not use the seq
- // number of the nack since we know that is too early to ask for this seq
- // number
- // e.g.: // e.g.: the client receives packets 10 11 12 20 where 20 is a nack
- // with productionSeq = 18. this says that all the packets between 12 and 18
- // may got lost and we should ask them
- deleteRtx(seq);
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "received futrue nack. add from "
- << state_->getHighestSeqReceivedInOrder() + 1
- << " to " << production_seq;
- addToRetransmissions(state_->getHighestSeqReceivedInOrder() + 1,
- production_seq);
- }
+ // received a nack. we can try to recover all data packets between the last
+ // received data and the production seq in the nack. this is similar to the
+ // recption of a probe
+ // e.g.: the client receives packets 10 11 12 20 where 20 is a nack
+ // with productionSeq = 18. this says that all the packets between 12 and 18
+ // may got lost and we should ask them
+
+ rs_->receivedPacket(seq);
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "received nack. add from "
+ << rs_->getState()->getHighestSeqReceived() + 1
+ << " to " << production_seq;
+
+ // if it is a future nack store it in the list set of nacked seq
+ if (production_seq <= seq) rs_->receivedFutureNack(seq);
+
+ // call the detectLoss function using the probe flag = true. in fact the
+ // losses detected using nacks are the same as the one detected using probes,
+ // we should not increase the loss counter
+ return detectLoss(rs_->getState()->getHighestSeqReceived() + 1,
+ production_seq, true);
}
-void RTCLossDetectionAndRecovery::onProbePacketReceived(
+bool RTCLossDetectionAndRecovery::onProbePacketReceived(
const core::ContentObject &probe) {
// we don't log the reception of a probe packet for the sentinel timer because
// probes are not taken into account into the sync window. we use them as
// future nacks to detect possible packets lost
- struct nack_packet_t *probe_pkt =
- (struct nack_packet_t *)probe.getPayload()->data();
- uint32_t production_seq = probe_pkt->getProductionSegement();
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "received probe. add from "
- << state_->getHighestSeqReceivedInOrder() + 1 << " to " << production_seq;
- addToRetransmissions(state_->getHighestSeqReceivedInOrder() + 1,
- production_seq);
-}
+ uint32_t production_seq = RTCState::getProbeParams(probe).prod_seg;
-void RTCLossDetectionAndRecovery::clear() {
- rtx_state_.clear();
- rtx_timers_.clear();
- sentinel_timer_->cancel();
- if (next_rtx_timer_ != MAX_TIMER_RTX) {
- next_rtx_timer_ = MAX_TIMER_RTX;
- timer_->cancel();
- }
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "received probe. add from "
+ << rs_->getState()->getHighestSeqReceived() + 1
+ << " to " << production_seq;
+
+ return detectLoss(rs_->getState()->getHighestSeqReceived() + 1,
+ production_seq, true);
}
-void RTCLossDetectionAndRecovery::addToRetransmissions(uint32_t start,
- uint32_t stop) {
+bool RTCLossDetectionAndRecovery::detectLoss(uint32_t start, uint32_t stop,
+ bool recv_probe) {
+ if (start >= stop) return false;
+
// skip nacked packets
- if (start <= state_->getLastSeqNacked()) {
- start = state_->getLastSeqNacked() + 1;
+ if (start <= rs_->getState()->getLastSeqNacked()) {
+ start = rs_->getState()->getLastSeqNacked() + 1;
}
// skip received or lost packets
- if (start <= state_->getHighestSeqReceivedInOrder()) {
- start = state_->getHighestSeqReceivedInOrder() + 1;
+ if (start <= rs_->getState()->getHighestSeqReceived()) {
+ start = rs_->getState()->getHighestSeqReceived() + 1;
}
+ bool loss_detected = false;
for (uint32_t seq = start; seq < stop; seq++) {
- if (state_->isReceivedOrLost(seq) == PacketState::UNKNOWN) {
- if (rtx_on_) {
- if (!indexer_->isFec(seq)) {
- // handle it with rtx
- if (!isRtx(seq)) {
- state_->onLossDetected(seq);
- rtxState state;
- state.first_send_ = state_->getInterestSentTime(seq);
- if (state.first_send_ == 0) // this interest was never sent before
- state.first_send_ = getNow();
- state.next_send_ = computeNextSend(seq, true);
- state.rtx_count_ = 0;
- DLOG_IF(INFO, VLOG_IS_ON(4))
- << "Add " << seq << " to retransmissions. next rtx is %lu "
- << state.next_send_ - getNow();
- rtx_state_.insert(std::pair<uint32_t, rtxState>(seq, state));
- rtx_timers_.insert(
- std::pair<uint64_t, uint32_t>(state.next_send_, seq));
- }
+ if (rs_->getState()->getPacketState(seq) == PacketState::UNKNOWN) {
+ if (rs_->lossDetected(seq)) {
+ loss_detected = true;
+ if ((recv_probe || rs_->wasNacked(seq)) && !rs_->isFecOn()) {
+ // these losses were detected using a probe and fec is off.
+ // in this case most likelly the procotol is about to go out of sync
+ // and the packets are not really lost (e.g. increase in prod rate).
+ // for this reason we do not
+ // count the losses in the stats. Instead we do the following
+ // 1. send RTX for the packets in case they were really lost
+ // 2. return to the RTC protocol that a loss was detected using a
+ // probe. the protocol will switch to catch_up mode to increase the
+ // size of the window
+ rs_->requestPossibleLostPacket(seq);
} else {
- // is fec, do not send it
- auto it = recover_with_fec_.find(seq);
- if (it == recover_with_fec_.end()) {
- state_->onLossDetected(seq);
- recover_with_fec_.insert(seq);
- }
- }
- } else {
- // keep track of losses but recover with FEC
- auto it = recover_with_fec_.find(seq);
- if (it == recover_with_fec_.end()) {
- state_->onLossDetected(seq);
- recover_with_fec_.insert(seq);
+ // if fec is on we don't need to mask pontetial losses, so increase
+ // the loss rate
+ rs_->notifyNewLossDetedcted(seq);
}
}
}
}
- scheduleNextRtx();
-}
-
-uint64_t RTCLossDetectionAndRecovery::computeNextSend(uint32_t seq,
- bool new_rtx) {
- uint64_t now = getNow();
- if (new_rtx) {
- // for the new rtx we wait one estimated IAT after the loss detection. this
- // is bacause, assuming that packets arrive with a constant IAT, we should
- // get a new packet every IAT
- double prod_rate = state_->getProducerRate();
- uint32_t estimated_iat = SENTINEL_TIMER_INTERVAL;
- uint32_t jitter = 0;
-
- if (prod_rate != 0) {
- double packet_size = state_->getAveragePacketSize();
- estimated_iat = ceil(1000.0 / (prod_rate / packet_size));
- jitter = ceil(state_->getJitter());
- }
-
- uint32_t wait = estimated_iat + jitter;
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "first rtx for " << seq << " in " << wait
- << " ms, rtt = " << state_->getRTT() << " ait = " << estimated_iat
- << " jttr = " << jitter;
-
- return now + wait;
- } else {
- // wait one RTT
- // however if the IAT is larger than the RTT, wait one IAT
- uint32_t wait = SENTINEL_TIMER_INTERVAL;
-
- double prod_rate = state_->getProducerRate();
- if (prod_rate == 0) {
- return now + SENTINEL_TIMER_INTERVAL;
- }
-
- double packet_size = state_->getAveragePacketSize();
- uint32_t estimated_iat = ceil(1000.0 / (prod_rate / packet_size));
-
- uint64_t rtt = state_->getRTT();
- if (rtt == 0) rtt = SENTINEL_TIMER_INTERVAL;
- wait = rtt;
-
- if (estimated_iat > rtt) wait = estimated_iat;
-
- uint32_t jitter = ceil(state_->getJitter());
- wait += jitter;
-
- // it may happen that the channel is congested and we have some additional
- // queuing delay to take into account
- uint32_t queue = ceil(state_->getQueuing());
- wait += queue;
-
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "next rtx for " << seq << " in " << wait
- << " ms, rtt = " << state_->getRTT() << " ait = " << estimated_iat
- << " jttr = " << jitter << " queue = " << queue;
-
- return now + wait;
- }
-}
-
-void RTCLossDetectionAndRecovery::retransmit() {
- if (rtx_timers_.size() == 0) return;
-
- uint64_t now = getNow();
-
- auto it = rtx_timers_.begin();
- std::unordered_set<uint32_t> lost_pkt;
- uint32_t sent_counter = 0;
- while (it != rtx_timers_.end() && it->first <= now &&
- sent_counter < MAX_RTX_IN_BATCH) {
- uint32_t seq = it->second;
- auto rtx_it =
- rtx_state_.find(seq); // this should always return a valid iter
- if (rtx_it->second.rtx_count_ >= RTC_MAX_RTX ||
- (now - rtx_it->second.first_send_) >= RTC_MAX_AGE ||
- seq < state_->getLastSeqNacked()) {
- // max rtx reached or packet too old or packet nacked, this packet is lost
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "packet " << seq << " lost because 1) max rtx: "
- << (rtx_it->second.rtx_count_ >= RTC_MAX_RTX) << " 2) max age: "
- << ((now - rtx_it->second.first_send_) >= RTC_MAX_AGE)
- << " 3) nacked: " << (seq < state_->getLastSeqNacked());
- lost_pkt.insert(seq);
- it++;
- } else {
- // resend the packet
- state_->onRetransmission(seq);
- double prod_rate = state_->getProducerRate();
- if (prod_rate != 0) rtx_it->second.rtx_count_++;
- rtx_it->second.next_send_ = computeNextSend(seq, false);
- it = rtx_timers_.erase(it);
- rtx_timers_.insert(
- std::pair<uint64_t, uint32_t>(rtx_it->second.next_send_, seq));
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "send rtx for sequence " << seq << ", next send in "
- << (rtx_it->second.next_send_ - now);
- send_rtx_callback_(seq);
- sent_counter++;
- }
- }
-
- // remove packets if needed
- for (auto lost_it = lost_pkt.begin(); lost_it != lost_pkt.end(); lost_it++) {
- uint32_t seq = *lost_it;
- state_->onPacketLost(seq);
- deleteRtx(seq);
- }
-}
-
-void RTCLossDetectionAndRecovery::scheduleNextRtx() {
- if (rtx_timers_.size() == 0) {
- // all the rtx were removed, reset timer
- next_rtx_timer_ = MAX_TIMER_RTX;
- return;
- }
-
- // check if timer is alreay set
- if (next_rtx_timer_ != MAX_TIMER_RTX) {
- // a new check for rtx is already scheduled
- if (next_rtx_timer_ > rtx_timers_.begin()->first) {
- // we need to re-schedule it
- timer_->cancel();
- } else {
- // wait for the next timer
- return;
- }
- }
-
- // set a new timer
- next_rtx_timer_ = rtx_timers_.begin()->first;
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
- uint64_t wait = 1;
- if (next_rtx_timer_ != MAX_TIMER_RTX && next_rtx_timer_ > now)
- wait = next_rtx_timer_ - now;
-
- std::weak_ptr<RTCLossDetectionAndRecovery> self(shared_from_this());
- timer_->expires_from_now(std::chrono::milliseconds(wait));
- timer_->async_wait([self](std::error_code ec) {
- if (ec) return;
- if (auto s = self.lock()) {
- s->retransmit();
- s->next_rtx_timer_ = MAX_TIMER_RTX;
- s->scheduleNextRtx();
- }
- });
-}
-
-bool RTCLossDetectionAndRecovery::deleteRtx(uint32_t seq) {
- auto it_rtx = rtx_state_.find(seq);
- if (it_rtx == rtx_state_.end()) return false; // rtx not found
-
- uint64_t ts = it_rtx->second.next_send_;
- auto it_timers = rtx_timers_.find(ts);
- while (it_timers != rtx_timers_.end() && it_timers->first == ts) {
- if (it_timers->second == seq) {
- rtx_timers_.erase(it_timers);
- break;
- }
- it_timers++;
- }
-
- bool lost = it_rtx->second.rtx_count_ > 0;
- rtx_state_.erase(it_rtx);
-
- return lost;
-}
-
-void RTCLossDetectionAndRecovery::scheduleSentinelTimer(
- uint64_t expires_from_now) {
- std::weak_ptr<RTCLossDetectionAndRecovery> self(shared_from_this());
- sentinel_timer_->expires_from_now(
- std::chrono::milliseconds(expires_from_now));
- sentinel_timer_->async_wait([self](std::error_code ec) {
- if (ec) return;
- if (auto s = self.lock()) {
- s->sentinelTimer();
- }
- });
-}
-
-void RTCLossDetectionAndRecovery::sentinelTimer() {
- uint64_t now = getNow();
-
- bool expired = false;
- bool sent = false;
- if ((now - last_event_) >= sentinel_timer_interval_) {
- // at least a sentinel_timer_interval_ elapsed since last event
- expired = true;
- if (TRANSPORT_EXPECT_FALSE(!state_->isProducerActive())) {
- // this happens at the beginning (or if the producer stops for some
- // reason) we need to keep sending interest 0 until we get an answer
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "sentinel timer: the producer is not active, send packet 0";
- state_->onRetransmission(0);
- send_rtx_callback_(0);
- } else {
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "sentinel timer: the producer is active, "
- "send the 10 oldest packets";
- sent = true;
- uint32_t rtx = 0;
- auto it = state_->getPendingInterestsMapBegin();
- auto end = state_->getPendingInterestsMapEnd();
- while (it != end && rtx < MAX_RTX_WITH_SENTINEL) {
- uint32_t seq = it->first;
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "sentinel timer, add " << seq << " to the rtx list";
- addToRetransmissions(seq, seq + 1);
- rtx++;
- it++;
- }
- }
- } else {
- // sentinel timer did not expire because we registered at least one event
- }
-
- uint32_t next_timer;
- double prod_rate = state_->getProducerRate();
- if (TRANSPORT_EXPECT_FALSE(!state_->isProducerActive()) || prod_rate == 0) {
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "next timer in " << SENTINEL_TIMER_INTERVAL;
- next_timer = SENTINEL_TIMER_INTERVAL;
- } else {
- double prod_rate = state_->getProducerRate();
- double packet_size = state_->getAveragePacketSize();
- uint32_t estimated_iat = ceil(1000.0 / (prod_rate / packet_size));
- uint32_t jitter = ceil(state_->getJitter());
-
- // try to reduce the number of timers if the estimated IAT is too small
- next_timer = std::max((estimated_iat + jitter) * 20, (uint32_t)1);
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "next sentinel in " << next_timer
- << " ms, rate: " << ((prod_rate * 8.0) / 1000000.0)
- << ", iat: " << estimated_iat << ", jitter: " << jitter;
-
- if (!expired) {
- // discount the amout of time that is already passed
- uint32_t discount = now - last_event_;
- if (next_timer > discount) {
- next_timer = next_timer - discount;
- } else {
- // in this case we trigger the timer in 1 ms
- next_timer = 1;
- }
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "timer after discout: " << next_timer;
- } else if (sent) {
- // wait at least one producer stats interval + owd to check if the
- // production rate is reducing.
- uint32_t min_wait = PRODUCER_STATS_INTERVAL + ceil(state_->getQueuing());
- next_timer = std::max(next_timer, min_wait);
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "wait for updates from prod, next timer: " << next_timer;
- }
- }
-
- scheduleSentinelTimer(next_timer);
+ return loss_detected;
}
} // namespace rtc
diff --git a/libtransport/src/protocols/rtc/rtc_ldr.h b/libtransport/src/protocols/rtc/rtc_ldr.h
index 1b9f9afd6..24f22ffed 100644
--- a/libtransport/src/protocols/rtc/rtc_ldr.h
+++ b/libtransport/src/protocols/rtc/rtc_ldr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,16 +15,14 @@
#pragma once
#include <hicn/transport/config.h>
+#include <hicn/transport/interfaces/socket_options_keys.h>
+// RtcTransportRecoveryStrategies
#include <hicn/transport/core/asio_wrapper.h>
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/name.h>
-#include <protocols/indexer.h>
-#include <protocols/rtc/rtc_consts.h>
-#include <protocols/rtc/rtc_state.h>
+#include <protocols/rtc/rtc_recovery_strategy.h>
#include <functional>
-#include <map>
-#include <unordered_map>
namespace transport {
@@ -34,91 +32,50 @@ namespace rtc {
class RTCLossDetectionAndRecovery
: public std::enable_shared_from_this<RTCLossDetectionAndRecovery> {
- struct rtx_state_ {
- uint64_t first_send_;
- uint64_t next_send_;
- uint32_t rtx_count_;
- };
-
- using rtxState = struct rtx_state_;
- using SendRtxCallback = std::function<void(uint32_t)>;
-
public:
- RTCLossDetectionAndRecovery(Indexer *indexer, SendRtxCallback &&callback,
- asio::io_service &io_service);
+ RTCLossDetectionAndRecovery(Indexer *indexer, asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies type,
+ RecoveryStrategy::SendRtxCallback &&callback,
+ interface::StrategyCallback &&external_callback);
~RTCLossDetectionAndRecovery();
- void setState(std::shared_ptr<RTCState> state) { state_ = state; }
- void setFecParams(uint32_t n, uint32_t k) {
- n_ = n;
- k_ = k;
+ void setState(RTCState *state) { rs_->setState(state); }
+ void setRateControl(RTCRateControl *rateControl) {
+ rs_->setRateControl(rateControl);
}
- void turnOnRTX();
- void turnOffRTX();
- bool isRtxOn() { return rtx_on_; }
- void onNewRound(bool in_sync);
- void onTimeout(uint32_t seq);
- void onPacketRecoveredFec(uint32_t seq);
- void onDataPacketReceived(const core::ContentObject &content_object);
- void onNackPacketReceived(const core::ContentObject &nack);
- void onProbePacketReceived(const core::ContentObject &probe);
+ void setFecParams(uint32_t n, uint32_t k) { rs_->setFecParams(n, k); }
- void clear();
-
- bool isRtx(uint32_t seq) {
- if (rtx_state_.find(seq) != rtx_state_.end()) return true;
- return false;
- }
+ void setContentSharingMode() { rs_->setContentSharingMode(); }
+ void turnOnRecovery() { rs_->turnOnRecovery(); }
+ bool isRtxOn() { return rs_->isRtxOn(); }
- private:
- void addToRetransmissions(uint32_t start, uint32_t stop);
- uint64_t computeNextSend(uint32_t seq, bool new_rtx);
- void retransmit();
- void scheduleNextRtx();
- bool deleteRtx(uint32_t seq);
- void scheduleSentinelTimer(uint64_t expires_from_now);
- void sentinelTimer();
- uint32_t computeFecPacketsToAsk(bool in_sync);
-
- uint64_t getNow() {
- using namespace std::chrono;
- uint64_t now =
- duration_cast<milliseconds>(steady_clock::now().time_since_epoch())
- .count();
- return now;
- }
+ void changeRecoveryStrategy(interface::RtcTransportRecoveryStrategies type);
- // this map keeps track of the retransmitted interest, ordered from the oldest
- // to the newest one. the state contains the timer of the first send of the
- // interest (from pendingIntetests_), the timer of the next send (key of the
- // multimap) and the number of rtx
- std::map<uint32_t, rtxState> rtx_state_;
- // this map stored the rtx by timer. The key is the time at which the rtx
- // should be sent, and the val is the interest seq number
- std::multimap<uint64_t, uint32_t> rtx_timers_;
+ void onNewRound(bool in_sync);
- // lost packets that will be recovered with fec
- std::unordered_set<uint32_t> recover_with_fec_;
+ // the following functions return true if a loss is detected, false otherwise
+ bool onTimeout(uint32_t seq, bool lost);
+ bool onPacketRecoveredFec(uint32_t seq);
+ bool onDataPacketReceived(const core::ContentObject &content_object);
+ bool onNackPacketReceived(const core::ContentObject &nack);
+ bool onProbePacketReceived(const core::ContentObject &probe);
- bool rtx_on_;
- bool fec_on_;
- uint64_t next_rtx_timer_;
- uint64_t last_event_;
- uint64_t sentinel_timer_interval_;
+ void clear() { rs_->clear(); }
- // fec params
- uint32_t n_;
- uint32_t k_;
+ bool isRtx(uint32_t seq) { return rs_->isRtx(seq); }
+ bool isPossibleLossWithNoRtx(uint32_t seq) {
+ return rs_->isPossibleLossWithNoRtx(seq);
+ }
- std::unique_ptr<asio::steady_timer> timer_;
- std::unique_ptr<asio::steady_timer> sentinel_timer_;
- std::shared_ptr<RTCState> state_;
+ uint64_t getRtxRtt(uint32_t seq) { return rs_->getRtxRtt(seq); }
- Indexer *indexer_;
+ private:
+ // returns true if a loss is detected, false otherwise
+ bool detectLoss(uint32_t start, uint32_t stop, bool recv_probe);
- SendRtxCallback send_rtx_callback_;
+ std::shared_ptr<RecoveryStrategy> rs_;
};
} // end namespace rtc
diff --git a/libtransport/src/protocols/rtc/rtc_packet.h b/libtransport/src/protocols/rtc/rtc_packet.h
index 7dc2f82c3..ffbbd78fd 100644
--- a/libtransport/src/protocols/rtc/rtc_packet.h
+++ b/libtransport/src/protocols/rtc/rtc_packet.h
@@ -24,6 +24,27 @@
* +-----------------------------------------+
*/
+/* aggregated packets
+ * +---------------------------------+
+ * |c| #pkts | len1 | len2 | .... |
+ * +----------------------------------
+ *
+ * +---------------------------------+
+ * |c| #pkts | resv | len 1 |
+ * +----------------------------------
+ *
+ * aggregated packets header.
+ * header position. just after the data packet header
+ *
+ * c: 1 bit: 0 8bit encoding, 1 16bit encoding
+ * #pkts: 7 bits: number of application packets contained
+ * 8bits encoding:
+ * lenX: 8 bits: len in bites of packet X
+ * 16bits econding:
+ * resv: 8 bits: reserved field (unused)
+ * lenX: 16bits: len in bytes of packet X
+ */
+
#pragma once
#ifndef _WIN32
#include <arpa/inet.h>
@@ -31,30 +52,16 @@
#include <hicn/transport/portability/win_portability.h>
#endif
+#include <hicn/transport/portability/endianess.h>
+
+#include <cstring>
+
namespace transport {
namespace protocol {
namespace rtc {
-inline uint64_t _ntohll(const uint64_t *input) {
- uint64_t return_val;
- uint8_t *tmp = (uint8_t *)&return_val;
-
- tmp[0] = (uint8_t)(*input >> 56);
- tmp[1] = (uint8_t)(*input >> 48);
- tmp[2] = (uint8_t)(*input >> 40);
- tmp[3] = (uint8_t)(*input >> 32);
- tmp[4] = (uint8_t)(*input >> 24);
- tmp[5] = (uint8_t)(*input >> 16);
- tmp[6] = (uint8_t)(*input >> 8);
- tmp[7] = (uint8_t)(*input >> 0);
-
- return return_val;
-}
-
-inline uint64_t _htonll(const uint64_t *input) { return (_ntohll(input)); }
-
const uint32_t DATA_HEADER_SIZE = 12; // bytes
// XXX: sizeof(data_packet_t) is 16
// beacuse of padding
@@ -64,11 +71,19 @@ struct data_packet_t {
uint64_t timestamp;
uint32_t prod_rate;
- inline uint64_t getTimestamp() const { return _ntohll(&timestamp); }
- inline void setTimestamp(uint64_t time) { timestamp = _htonll(&time); }
+ inline uint64_t getTimestamp() const {
+ return portability::net_to_host(timestamp);
+ }
+ inline void setTimestamp(uint64_t time) {
+ timestamp = portability::host_to_net(time);
+ }
- inline uint32_t getProductionRate() const { return ntohl(prod_rate); }
- inline void setProductionRate(uint32_t rate) { prod_rate = htonl(rate); }
+ inline uint32_t getProductionRate() const {
+ return portability::net_to_host(prod_rate);
+ }
+ inline void setProductionRate(uint32_t rate) {
+ prod_rate = portability::host_to_net(rate);
+ }
};
struct nack_packet_t {
@@ -76,14 +91,162 @@ struct nack_packet_t {
uint32_t prod_rate;
uint32_t prod_seg;
- inline uint64_t getTimestamp() const { return _ntohll(&timestamp); }
- inline void setTimestamp(uint64_t time) { timestamp = _htonll(&time); }
+ inline uint64_t getTimestamp() const {
+ return portability::net_to_host(timestamp);
+ }
+ inline void setTimestamp(uint64_t time) {
+ timestamp = portability::host_to_net(time);
+ }
+
+ inline uint32_t getProductionRate() const {
+ return portability::net_to_host(prod_rate);
+ }
+ inline void setProductionRate(uint32_t rate) {
+ prod_rate = portability::host_to_net(rate);
+ }
+
+ inline uint32_t getProductionSegment() const {
+ return portability::net_to_host(prod_seg);
+ }
+ inline void setProductionSegment(uint32_t seg) {
+ prod_seg = portability::host_to_net(seg);
+ }
+};
+
+class AggrPktHeader {
+ public:
+ // XXX buf always point to the payload after the data header
+ AggrPktHeader(uint8_t *buf, uint16_t max_packet_len, uint16_t pkt_number)
+ : buf_(buf), pkt_num_(pkt_number) {
+ *buf_ = 0; // reset the first byte to correctly add the header
+ // encoding and the packet number
+ if (max_packet_len > 0xff) {
+ setAggrPktEncoding16bit();
+ } else {
+ setAggrPktEncoding8bit();
+ }
+ setAggrPktNUmber(pkt_number);
+ header_len_ = computeHeaderLen();
+ memset(buf_ + 1, 0, header_len_ - 1);
+ }
+
+ // XXX buf always point to the payload after the data header
+ AggrPktHeader(uint8_t *buf) : buf_(buf) {
+ encoding_ = getAggrPktEncoding();
+ pkt_num_ = getAggrPktNumber();
+ header_len_ = computeHeaderLen();
+ }
+
+ ~AggrPktHeader(){};
+
+ int addPacketToHeader(uint8_t index, uint16_t len) {
+ if (index > pkt_num_) return -1;
+
+ setAggrPktLen(index, len);
+ return 0;
+ }
+
+ int getPointerToPacket(uint8_t index, uint8_t **pkt_ptr, uint16_t *pkt_len) {
+ if (index > pkt_num_) return -1;
+
+ uint16_t len = 0;
+ for (int i = 0; i < index; i++)
+ len += getAggrPktLen(i); // sum the pkts len from 0 to index - 1
+
+ uint16_t offset = len + header_len_;
+ *pkt_ptr = buf_ + offset;
+ *pkt_len = getAggrPktLen(index);
+ return 0;
+ }
+
+ int getPacketOffsets(uint8_t index, uint16_t *pkt_offset, uint16_t *pkt_len) {
+ if (index > pkt_num_) return -1;
+
+ uint16_t len = 0;
+ for (int i = 0; i < index; i++)
+ len += getAggrPktLen(i); // sum the pkts len from 0 to index - 1
+
+ uint16_t offset = len + header_len_;
+ *pkt_offset = offset;
+ *pkt_len = getAggrPktLen(index);
+
+ return 0;
+ }
+
+ uint8_t *getPayloadAppendPtr() { return buf_ + header_len_; }
+
+ uint16_t getHeaderLen() { return header_len_; }
+
+ uint8_t getNumberOfPackets() { return pkt_num_; }
+
+ private:
+ inline uint16_t computeHeaderLen() const {
+ uint16_t len = 4; // min len in bytes
+ if (!encoding_) {
+ while (pkt_num_ >= len) {
+ len += 4;
+ }
+ } else {
+ while (pkt_num_ * 2 >= len) {
+ len += 4;
+ }
+ }
+ return len;
+ }
+
+ inline uint8_t getAggrPktEncoding() const {
+ // get the first bit of the first byte
+ return (*buf_ >> 7);
+ }
+
+ inline void setAggrPktEncoding8bit() {
+ // reset the first bit of the first byte
+ encoding_ = 0;
+ *buf_ &= 0x7f;
+ }
+
+ inline void setAggrPktEncoding16bit() {
+ // set the first bit of the first byte
+ encoding_ = 1;
+ *buf_ ^= 0x80;
+ }
+
+ inline uint8_t getAggrPktNumber() const {
+ // return the first byte with the first bit = 0
+ return (*buf_ & 0x7f);
+ }
+
+ inline void setAggrPktNUmber(uint8_t val) {
+ // set the val without modifying the first bit
+ *buf_ &= 0x80; // reset everithing but the first bit
+ val &= 0x7f; // reset the first bit
+ *buf_ |= val; // or the vals, done!
+ }
+
+ inline uint16_t getAggrPktLen(uint8_t pkt_index) const {
+ pkt_index++;
+ if (!encoding_) { // 8 bits
+ return (uint16_t) * (buf_ + pkt_index);
+ } else { // 16 bits
+ uint16_t *buf_16 = (uint16_t *)buf_;
+ return portability::net_to_host(*(buf_16 + pkt_index));
+ }
+ }
- inline uint32_t getProductionRate() const { return ntohl(prod_rate); }
- inline void setProductionRate(uint32_t rate) { prod_rate = htonl(rate); }
+ inline void setAggrPktLen(uint8_t pkt_index, uint16_t len) {
+ pkt_index++;
+ if (!encoding_) { // 8 bits
+ *(buf_ + pkt_index) = (uint8_t)len;
+ } else { // 16 bits
+ uint16_t *buf_16 = (uint16_t *)buf_;
+ *(buf_16 + pkt_index) = portability::host_to_net(len);
+ }
+ }
- inline uint32_t getProductionSegement() const { return ntohl(prod_seg); }
- inline void setProductionSegement(uint32_t seg) { prod_seg = htonl(seg); }
+ uint8_t *buf_;
+ uint8_t encoding_;
+ uint8_t pkt_num_;
+ uint16_t header_len_;
};
} // end namespace rtc
diff --git a/libtransport/src/protocols/rtc/rtc_rc.h b/libtransport/src/protocols/rtc/rtc_rc.h
index 34d090092..62636ce40 100644
--- a/libtransport/src/protocols/rtc/rtc_rc.h
+++ b/libtransport/src/protocols/rtc/rtc_rc.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -34,11 +34,15 @@ class RTCRateControl : public std::enable_shared_from_this<RTCRateControl> {
void turnOnRateControl() { rc_on_ = true; }
void setState(std::shared_ptr<RTCState> state) { protocol_state_ = state; };
- uint32_t getCongesionWindow() { return congestion_win_; };
+ uint32_t getCongestionWindow() { return congestion_win_; };
+ bool inCongestionState() {
+ if (congestion_state_ == CongestionState::Congested) return true;
+ return false;
+ }
virtual void onNewRound(double round_len) = 0;
- virtual void onDataPacketReceived(
- const core::ContentObject &content_object) = 0;
+ virtual void onDataPacketReceived(const core::ContentObject &content_object,
+ bool compute_stats) = 0;
protected:
enum class CongestionState { Normal = 0, Underuse = 1, Congested = 2, Last };
diff --git a/libtransport/src/protocols/rtc/rtc_rc_congestion_detection.cc b/libtransport/src/protocols/rtc/rtc_rc_congestion_detection.cc
new file mode 100644
index 000000000..6cd3094b5
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rc_congestion_detection.cc
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_rc_congestion_detection.h>
+
+#include <algorithm>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RTCRateControlCongestionDetection::RTCRateControlCongestionDetection()
+ : rounds_without_congestion_(4), last_queue_(0) {} // must be > 3
+
+RTCRateControlCongestionDetection::~RTCRateControlCongestionDetection() {}
+
+void RTCRateControlCongestionDetection::onNewRound(double round_len) {
+ if (!rc_on_) return;
+
+ double rtt = (double)protocol_state_->getMinRTT() / MILLI_IN_A_SEC;
+ double queue = protocol_state_->getQueuing();
+
+ if (rtt == 0.0) return; // no info from the producer
+
+ if (last_queue_ == queue) {
+ // if last_queue == queue the consumer didn't receive any
+ // packet from the producer. we do not change the current congestion state.
+ // we just increase the counter of rounds whithout congestion if needed
+ // (in case of congestion the counter is already set to 0)
+ if (congestion_state_ == CongestionState::Normal)
+ rounds_without_congestion_++;
+ } else {
+ if (queue > MAX_QUEUING_DELAY) {
+ // here we detect congestion.
+ congestion_state_ = CongestionState::Congested;
+ rounds_without_congestion_ = 0;
+ } else {
+ // wait 3 rounds before switch back to no congestion
+ if (rounds_without_congestion_ > 3) {
+ // nothing bad is happening
+ congestion_state_ = CongestionState::Normal;
+ }
+ rounds_without_congestion_++;
+ }
+ last_queue_ = queue;
+ }
+}
+
+void RTCRateControlCongestionDetection::onDataPacketReceived(
+ const core::ContentObject &content_object, bool compute_stats) {
+ // nothing to do
+ return;
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rc_congestion_detection.h b/libtransport/src/protocols/rtc/rtc_rc_congestion_detection.h
new file mode 100644
index 000000000..9afa6c39a
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rc_congestion_detection.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <hicn/transport/utils/shared_ptr_utils.h>
+#include <protocols/rtc/rtc_rc.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RTCRateControlCongestionDetection : public RTCRateControl {
+ public:
+ RTCRateControlCongestionDetection();
+
+ ~RTCRateControlCongestionDetection();
+
+ void onNewRound(double round_len);
+ void onDataPacketReceived(const core::ContentObject &content_object,
+ bool compute_stats);
+
+ auto shared_from_this() { return utils::shared_from(this); }
+
+ private:
+ uint32_t rounds_without_congestion_;
+ double last_queue_;
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rc_iat.cc b/libtransport/src/protocols/rtc/rtc_rc_iat.cc
new file mode 100644
index 000000000..f06f377f3
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rc_iat.cc
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_rc_iat.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RTCRateControlIAT::RTCRateControlIAT()
+ : rounds_since_last_drop_(0),
+ rounds_without_congestion_(0),
+ rounds_with_congestion_(0),
+ last_queue_(0),
+ last_rcv_time_(0),
+ last_prod_time_(0),
+ last_seq_number_(0),
+ target_rate_avg_(0),
+ round_index_(0),
+ congestion_cause_(CongestionCause::UNKNOWN) {}
+
+RTCRateControlIAT::~RTCRateControlIAT() {}
+
+void RTCRateControlIAT::onNewRound(double round_len) {
+ if (!rc_on_) return;
+
+ double received_rate = protocol_state_->getReceivedRate() +
+ protocol_state_->getRecoveredFecRate();
+
+ double target_rate =
+ protocol_state_->getProducerRate(); // * PRODUCTION_RATE_FRACTION;
+ double rtt = (double)protocol_state_->getMinRTT() / MILLI_IN_A_SEC;
+ // double packet_size = protocol_state_->getAveragePacketSize();
+ double queue = protocol_state_->getQueuing();
+
+ if (rtt == 0.0) return; // no info from the producer
+
+ CongestionState prev_congestion_state = congestion_state_;
+
+ target_rate_avg_ = target_rate_avg_ * (1 - MOVING_AVG_ALPHA) +
+ target_rate * MOVING_AVG_ALPHA;
+
+ if (prev_congestion_state == CongestionState::Congested) {
+ if (queue > MAX_QUEUING_DELAY || last_queue_ == queue) {
+ congestion_state_ = CongestionState::Congested;
+
+ received_rate_.push_back(received_rate);
+ target_rate_.push_back(target_rate);
+
+ // We assume the cause does not change
+ // Note that the first assumption about the cause could be wrong
+ // the cause of congestion could change
+ if (congestion_cause_ == CongestionCause::UNKNOWN)
+ if (rounds_with_congestion_ >= 1)
+ congestion_cause_ = apply_classification_tree(
+ rounds_with_congestion_ > ROUND_TO_WAIT_FORCE_DECISION);
+
+ rounds_with_congestion_++;
+ } else {
+ congestion_state_ = CongestionState::Normal;
+
+ // clear past history
+ reset_congestion_statistics();
+
+ // TODO maybe we can use some of these values for the stdev of the
+ // congestion mode
+ for (int i = 0; i < ROUND_HISTORY_SIZE; i++) {
+ iat_on_hold_[i].clear();
+ }
+ }
+ } else if (queue > MAX_QUEUING_DELAY) {
+ if (prev_congestion_state == CongestionState::Normal) {
+ rounds_with_congestion_ = 0;
+
+ if (rounds_without_congestion_ > ROUND_TO_RESET_CAUSE)
+ congestion_cause_ = CongestionCause::UNKNOWN;
+ }
+ congestion_state_ = CongestionState::Congested;
+ received_rate_.push_back(received_rate);
+ target_rate_.push_back(target_rate);
+ } else {
+ // nothing bad is happening
+ congestion_state_ = CongestionState::Normal;
+ reset_congestion_statistics();
+
+ int past_index = (round_index_ + 1) % ROUND_HISTORY_SIZE;
+ for (std::vector<double>::iterator it = iat_on_hold_[past_index].begin();
+ it != iat_on_hold_[past_index].end(); ++it) {
+ congestion_free_iat_.push_back(*it);
+ if (congestion_free_iat_.size() > 50) {
+ congestion_free_iat_.erase(congestion_free_iat_.begin());
+ }
+ }
+ iat_on_hold_[past_index].clear();
+ round_index_ = (round_index_ + 1) % ROUND_HISTORY_SIZE;
+ }
+
+ last_queue_ = queue;
+
+ if (congestion_state_ == CongestionState::Congested) {
+ if (prev_congestion_state == CongestionState::Normal) {
+ // init the congetion window using the received rate
+ // disabling for the moment the congestion window setup
+ // congestion_win_ = (uint32_t)ceil(received_rate * rtt / packet_size);
+ rounds_since_last_drop_ = ROUNDS_BEFORE_TAKE_ACTION + 1;
+ }
+
+ if (rounds_since_last_drop_ >= ROUNDS_BEFORE_TAKE_ACTION) {
+ // disabling for the moment the congestion window setup
+ // uint32_t win = congestion_win_ * WIN_DECREASE_FACTOR;
+ // congestion_win_ = std::max(win, WIN_MIN);
+ rounds_since_last_drop_ = 0;
+ return;
+ }
+
+ rounds_since_last_drop_++;
+ }
+
+ if (congestion_state_ == CongestionState::Normal) {
+ if (prev_congestion_state == CongestionState::Congested) {
+ rounds_without_congestion_ = 0;
+ }
+
+ rounds_without_congestion_++;
+ if (rounds_without_congestion_ < ROUNDS_BEFORE_TAKE_ACTION) return;
+
+ // disabling for the moment the congestion window setup
+ // congestion_win_ = congestion_win_ * WIN_INCREASE_FACTOR;
+ // congestion_win_ = std::min(congestion_win_, INITIAL_WIN_MAX);
+ }
+
+ if (received_rate_.size() > 1000)
+ received_rate_.erase(received_rate_.begin());
+ if (target_rate_.size() > 1000) target_rate_.erase(target_rate_.begin());
+}
+
+void RTCRateControlIAT::onDataPacketReceived(
+ const core::ContentObject &content_object, bool compute_stats) {
+ core::ParamsRTC params = RTCState::getDataParams(content_object);
+
+ uint64_t now = utils::SteadyTime::nowMs().count();
+
+ uint32_t segment_number = content_object.getName().getSuffix();
+
+ if (segment_number == (last_seq_number_ + 1) && compute_stats) {
+ uint64_t iat = now - last_rcv_time_;
+ uint64_t ist = params.timestamp - last_prod_time_;
+ if (now >= last_rcv_time_ && params.timestamp > last_prod_time_) {
+ if (iat >= ist && ist < MIN_IST_VALUE) {
+ if (congestion_state_ == CongestionState::Congested) {
+ iat_.push_back((iat - ist));
+ } else {
+ // no congestion, but we do not always add new values, but only when
+ // there is no sign of congestion
+ double queue = protocol_state_->getQueuing();
+ if (queue <= CONGESTION_FREE_QUEUEING_DELAY) {
+ iat_on_hold_[round_index_].push_back((iat - ist));
+ }
+ }
+ }
+ }
+ }
+
+ last_seq_number_ = segment_number;
+ last_rcv_time_ = now;
+ last_prod_time_ = params.timestamp;
+
+ if (iat_.size() > 1000) iat_.erase(iat_.begin());
+ return;
+}
+
+CongestionCause RTCRateControlIAT::apply_classification_tree(bool force_reply) {
+ if (iat_.size() <= 2 || received_rate_.size() < 2)
+ return CongestionCause::UNKNOWN;
+
+ double received_ratio = 0;
+ double iat_ratio = 0;
+ double iat_stdev = compute_iat_stdev(iat_);
+ double iat_congestion_free_stdev = compute_iat_stdev(congestion_free_iat_);
+
+ double iat_avg = 0.0;
+
+ double recv_avg = 0.0;
+ double recv_max = 0.0;
+
+ double target_rate_avg = 0.0;
+
+ int counter = 0;
+ std::vector<double>::reverse_iterator target_it = target_rate_.rbegin();
+ for (std::vector<double>::reverse_iterator it = received_rate_.rbegin();
+ it != received_rate_.rend(); ++it) {
+ recv_avg += *it;
+ target_rate_avg += *target_it;
+ if (counter < ROUND_HISTORY_SIZE)
+ if (recv_max < *it) {
+ recv_max = *it; // we consider only the last 2 seconds
+ }
+ counter++;
+ target_it++;
+ }
+ recv_avg = recv_avg / received_rate_.size();
+ target_rate_avg = target_rate_avg / target_rate_.size();
+
+ for (std::vector<double>::iterator it = iat_.begin(); it != iat_.end();
+ ++it) {
+ iat_avg += *it;
+ }
+ iat_avg = iat_avg / iat_.size();
+
+ double congestion_free_iat_avg = 0.0;
+ for (std::vector<double>::iterator it = congestion_free_iat_.begin();
+ it != congestion_free_iat_.end(); ++it) {
+ congestion_free_iat_avg += *it;
+ }
+ congestion_free_iat_avg =
+ congestion_free_iat_avg / congestion_free_iat_.size();
+
+ received_ratio = recv_avg / target_rate_avg;
+
+ iat_ratio = iat_stdev / iat_congestion_free_stdev;
+
+ CongestionCause congestion_cause = CongestionCause::UNKNOWN;
+ // applying classification tree model
+ if (received_ratio <= 0.87)
+ if (iat_stdev <= 6.48)
+ if (received_ratio <= 0.83)
+ congestion_cause = CongestionCause::LINK_CAPACITY;
+ else if (force_reply)
+ congestion_cause = CongestionCause::LINK_CAPACITY;
+ else
+ congestion_cause = CongestionCause::UNKNOWN; // accuracy is too low
+ else if (iat_ratio <= 2.46)
+ if (force_reply)
+ congestion_cause = CongestionCause::LINK_CAPACITY;
+ else
+ congestion_cause = CongestionCause::UNKNOWN; // accuracy is too low
+ else
+ congestion_cause = CongestionCause::COMPETING_CROSS_TRAFFIC;
+ else if (received_ratio <= 0.913 && iat_stdev <= 0.784)
+ congestion_cause = CongestionCause::LINK_CAPACITY;
+ else
+ congestion_cause = CongestionCause::COMPETING_CROSS_TRAFFIC;
+
+ return congestion_cause;
+}
+
+void RTCRateControlIAT::reset_congestion_statistics() {
+ iat_.clear();
+ received_rate_.clear();
+ target_rate_.clear();
+}
+
+double RTCRateControlIAT::compute_iat_stdev(std::vector<double> v) {
+ if (v.size() == 0) return 0;
+
+ float sum = 0.0, mean, standard_deviation = 0.0;
+ for (std::vector<double>::iterator it = v.begin(); it != v.end(); it++) {
+ sum += *it;
+ }
+
+ mean = sum / v.size();
+ for (std::vector<double>::iterator it = v.begin(); it != v.end(); it++) {
+ standard_deviation += pow(*it - mean, 2);
+ }
+ return sqrt(standard_deviation / v.size());
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rc_iat.h b/libtransport/src/protocols/rtc/rtc_rc_iat.h
new file mode 100644
index 000000000..715637807
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rc_iat.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <hicn/transport/utils/shared_ptr_utils.h>
+#include <protocols/rtc/rtc_rc.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+const int ROUND_HISTORY_SIZE = 10; // equivalent to two seconds
+const int ROUND_TO_WAIT_FORCE_DECISION = 5;
+
+// once congestion is gone, we need to wait for k rounds before changing the
+// congestion cause in the case it appears again
+const int ROUND_TO_RESET_CAUSE = 5;
+
+const int MIN_IST_VALUE = 150; // samples of ist larger than 150ms are
+ // discarded
+const double CONGESTION_FREE_QUEUEING_DELAY = 10;
+
+enum class CongestionCause : uint8_t {
+ COMPETING_CROSS_TRAFFIC,
+ FRIENDLY_CROSS_TRAFFIC,
+ UNKNOWN_CROSS_TRAFFIC,
+ LINK_CAPACITY,
+ UNKNOWN
+};
+
+class RTCRateControlIAT : public RTCRateControl {
+ public:
+ RTCRateControlIAT();
+
+ ~RTCRateControlIAT();
+
+ void onNewRound(double round_len);
+ void onDataPacketReceived(const core::ContentObject &content_object,
+ bool compute_stats);
+
+ auto shared_from_this() { return utils::shared_from(this); }
+
+ private:
+ void reset_congestion_statistics();
+
+ double compute_iat_stdev(std::vector<double> v);
+
+ CongestionCause apply_classification_tree(bool force_reply);
+
+ private:
+ uint32_t rounds_since_last_drop_;
+ uint32_t rounds_without_congestion_;
+ uint32_t rounds_with_congestion_;
+ double last_queue_;
+ uint64_t last_rcv_time_;
+ uint64_t last_prod_time_;
+ uint32_t last_seq_number_;
+ double target_rate_avg_;
+
+ // Iat values are not immediately added to the congestion free set of values
+ std::array<std::vector<double>, ROUND_HISTORY_SIZE> iat_on_hold_;
+ uint32_t round_index_;
+
+ // with congestion statistics
+ std::vector<double> iat_;
+ std::vector<double> received_rate_;
+ std::vector<double> target_rate_;
+
+ // congestion free statistics
+ std::vector<double> congestion_free_iat_;
+
+ CongestionCause congestion_cause_;
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rc_queue.cc b/libtransport/src/protocols/rtc/rtc_rc_queue.cc
index a1c89e329..ecabc5205 100644
--- a/libtransport/src/protocols/rtc/rtc_rc_queue.cc
+++ b/libtransport/src/protocols/rtc/rtc_rc_queue.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -37,7 +37,7 @@ void RTCRateControlQueue::onNewRound(double round_len) {
double received_rate = protocol_state_->getReceivedRate();
double target_rate =
protocol_state_->getProducerRate() * PRODUCTION_RATE_FRACTION;
- double rtt = (double)protocol_state_->getRTT() / MILLI_IN_A_SEC;
+ double rtt = (double)protocol_state_->getMinRTT() / MILLI_IN_A_SEC;
double packet_size = protocol_state_->getAveragePacketSize();
double queue = protocol_state_->getQueuing();
@@ -94,7 +94,7 @@ void RTCRateControlQueue::onNewRound(double round_len) {
}
void RTCRateControlQueue::onDataPacketReceived(
- const core::ContentObject &content_object) {
+ const core::ContentObject &content_object, bool compute_stats) {
// nothing to do
return;
}
diff --git a/libtransport/src/protocols/rtc/rtc_rc_queue.h b/libtransport/src/protocols/rtc/rtc_rc_queue.h
index 407354d43..cdf78fd47 100644
--- a/libtransport/src/protocols/rtc/rtc_rc_queue.h
+++ b/libtransport/src/protocols/rtc/rtc_rc_queue.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -30,7 +30,8 @@ class RTCRateControlQueue : public RTCRateControl {
~RTCRateControlQueue();
void onNewRound(double round_len);
- void onDataPacketReceived(const core::ContentObject &content_object);
+ void onDataPacketReceived(const core::ContentObject &content_object,
+ bool compute_stats);
auto shared_from_this() { return utils::shared_from(this); }
diff --git a/libtransport/src/protocols/rtc/rtc_reassembly.cc b/libtransport/src/protocols/rtc/rtc_reassembly.cc
new file mode 100644
index 000000000..b1b0fcaba
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_reassembly.cc
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hicn/transport/interfaces/socket_consumer.h>
+#include <implementation/socket_consumer.h>
+#include <protocols/rtc/rtc_reassembly.h>
+#include <protocols/transport_protocol.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RtcReassembly::RtcReassembly(implementation::ConsumerSocket* icn_socket,
+ TransportProtocol* transport_protocol)
+ : DatagramReassembly(icn_socket, transport_protocol) {
+ is_setup_ = false;
+}
+
+void RtcReassembly::reassemble(core::ContentObject& content_object) {
+ if (!is_setup_) {
+ is_setup_ = true;
+ reassembly_consumer_socket_->getSocketOption(
+ interface::RtcTransportOptions::AGGREGATED_DATA, data_aggregation_);
+ }
+
+ auto read_buffer = content_object.getPayload();
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Size of payload: " << read_buffer->length();
+
+ read_buffer->trimStart(transport_protocol_->transportHeaderLength(false));
+
+ if (data_aggregation_) {
+ rtc::AggrPktHeader hdr((uint8_t*)read_buffer->data());
+
+ for (uint8_t i = 0; i < hdr.getNumberOfPackets(); i++) {
+ std::unique_ptr<utils::MemBuf> segment = read_buffer->clone();
+
+ uint16_t pkt_start = 0;
+ uint16_t pkt_len = 0;
+ int res = hdr.getPacketOffsets(i, &pkt_start, &pkt_len);
+ if (res == -1) {
+ // this should not happen
+ break;
+ }
+
+ segment->trimStart(pkt_start);
+ segment->trimEnd(segment->length() - pkt_len);
+
+ Reassembly::read_buffer_ = std::move(segment);
+ Reassembly::notifyApplication();
+ }
+ } else {
+ Reassembly::read_buffer_ = std::move(read_buffer);
+ Reassembly::notifyApplication();
+ }
+}
+
+void RtcReassembly::reassemble(utils::MemBuf& buffer, uint32_t suffix) {
+ if (!is_setup_) {
+ is_setup_ = true;
+ reassembly_consumer_socket_->getSocketOption(
+ interface::RtcTransportOptions::AGGREGATED_DATA, data_aggregation_);
+ }
+
+ if (data_aggregation_) {
+ rtc::AggrPktHeader hdr((uint8_t*)buffer.data());
+
+ for (uint8_t i = 0; i < hdr.getNumberOfPackets(); i++) {
+ std::unique_ptr<utils::MemBuf> segment = buffer.clone();
+
+ uint16_t pkt_start = 0;
+ uint16_t pkt_len = 0;
+ int res = hdr.getPacketOffsets(i, &pkt_start, &pkt_len);
+ if (res == -1) {
+ // this should not happen
+ break;
+ }
+
+ segment->trimStart(pkt_start);
+ segment->trimEnd(segment->length() - pkt_len);
+
+ Reassembly::read_buffer_ = std::move(segment);
+ Reassembly::notifyApplication();
+ }
+
+ } else {
+ Reassembly::read_buffer_ = buffer.cloneOne();
+ Reassembly::notifyApplication();
+ }
+}
+
+} // namespace rtc
+
+} // namespace protocol
+
+} // namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_reassembly.h b/libtransport/src/protocols/rtc/rtc_reassembly.h
index 15722a6d5..132004605 100644
--- a/libtransport/src/protocols/rtc/rtc_reassembly.h
+++ b/libtransport/src/protocols/rtc/rtc_reassembly.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,17 +28,14 @@ namespace rtc {
class RtcReassembly : public DatagramReassembly {
public:
RtcReassembly(implementation::ConsumerSocket *icn_socket,
- TransportProtocol *transport_protocol)
- : DatagramReassembly(icn_socket, transport_protocol) {}
-
- void reassemble(core::ContentObject &content_object) override {
- auto read_buffer = content_object.getPayload();
- DLOG_IF(INFO, VLOG_IS_ON(3))
- << "Size of payload: " << read_buffer->length();
- read_buffer->trimStart(transport_protocol_->transportHeaderLength());
- Reassembly::read_buffer_ = std::move(read_buffer);
- Reassembly::notifyApplication();
- }
+ TransportProtocol *transport_protocol);
+
+ void reassemble(core::ContentObject &content_object) override;
+ void reassemble(utils::MemBuf &buffer, uint32_t suffix) override;
+
+ private:
+ bool is_setup_;
+ bool data_aggregation_;
};
} // namespace rtc
diff --git a/libtransport/src/protocols/rtc/rtc_recovery_strategy.cc b/libtransport/src/protocols/rtc/rtc_recovery_strategy.cc
new file mode 100644
index 000000000..257fdd09b
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_recovery_strategy.cc
@@ -0,0 +1,420 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <hicn/transport/interfaces/notification.h>
+#include <hicn/transport/interfaces/socket_options_keys.h>
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_recovery_strategy.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+using namespace transport::interface;
+
+RecoveryStrategy::RecoveryStrategy(
+ Indexer *indexer, SendRtxCallback &&callback, asio::io_service &io_service,
+ bool use_rtx, bool use_fec,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback)
+ : rs_type_(rs_type),
+ recovery_on_(false),
+ content_sharing_mode_(false),
+ rtx_during_fec_(0),
+ next_rtx_timer_(MAX_TIMER_RTX),
+ send_rtx_callback_(std::move(callback)),
+ indexer_(indexer),
+ round_id_(0),
+ last_fec_used_(0),
+ callback_(std::move(external_callback)) {
+ setRtxFec(use_rtx, use_fec);
+ timer_ = std::make_unique<asio::steady_timer>(io_service);
+}
+
+RecoveryStrategy::RecoveryStrategy(RecoveryStrategy &&rs)
+ : rs_type_(rs.rs_type_),
+ content_sharing_mode_(rs.content_sharing_mode_),
+ rtx_during_fec_(0),
+ rtx_state_(std::move(rs.rtx_state_)),
+ rtx_timers_(std::move(rs.rtx_timers_)),
+ recover_with_fec_(std::move(rs.recover_with_fec_)),
+ timer_(std::move(rs.timer_)),
+ next_rtx_timer_(std::move(rs.next_rtx_timer_)),
+ send_rtx_callback_(std::move(rs.send_rtx_callback_)),
+ n_(std::move(rs.n_)),
+ k_(std::move(rs.k_)),
+ indexer_(std::move(rs.indexer_)),
+ state_(std::move(rs.state_)),
+ rc_(std::move(rs.rc_)),
+ round_id_(std::move(rs.round_id_)),
+ last_fec_used_(std::move(rs.last_fec_used_)),
+ callback_(std::move(rs.callback_)) {
+ setFecParams(n_, k_);
+}
+
+RecoveryStrategy::~RecoveryStrategy() {}
+
+void RecoveryStrategy::setFecParams(uint32_t n, uint32_t k) {
+ // if rs_type == FEC_ONLY_LOW_RES_LOSSES max k == 64
+ n_ = n;
+ k_ = k;
+
+ // XXX for the moment we go in steps of 5% loss rate.
+ uint32_t i = 0;
+ for (uint32_t loss_rate = 5; loss_rate < 100; loss_rate += 5) {
+ uint32_t fec_to_ask = 0;
+ if (n_ != 0 && k_ != 0) {
+ if (rs_type_ ==
+ interface::RtcTransportRecoveryStrategies::FEC_ONLY_LOW_RES_LOSSES) {
+ // the max loss rate in the matrix is 50%
+ uint32_t index = i;
+ if (i > 9) index = 9;
+ fec_to_ask = FEC_MATRIX[k_ - 1][index];
+ } else {
+ double dec_loss_rate = (double)(loss_rate + 5);
+ if (dec_loss_rate == 100.0) dec_loss_rate = 95.0;
+ dec_loss_rate = dec_loss_rate / 100.0;
+ double exp_losses = ceil((double)k_ * dec_loss_rate);
+ fec_to_ask = ceil((exp_losses / (1 - dec_loss_rate)) * 1.25);
+ }
+ }
+ fec_to_ask = std::min(fec_to_ask, (n_ - k_));
+ fec_per_loss_rate_.push_back(fec_to_ask);
+
+ i++;
+ }
+}
+
+uint64_t RecoveryStrategy::getRtxRtt(uint32_t seq) {
+ auto it = rtx_state_.find(seq);
+
+ if (it == rtx_state_.end()) return 0;
+
+ // we can compute the RTT of an RTX only if it was send once. Infact if the
+ // RTX was sent twice or more the data may be alredy in flight and the RTT
+ // will be underestimated. This may happen also for packets that we
+ // retransmitted too soon. in that case the RTT will be filtered out by
+ // checking the path label
+ if (it->second.rtx_count_ != 1) return 0;
+
+ // this a potentialy valid packet, compute the RTT
+ return (utils::SteadyTime::nowMs().count() - it->second.last_send_);
+}
+
+bool RecoveryStrategy::lossDetected(uint32_t seq) {
+ if (isRtx(seq)) {
+ // this packet is already in the list of rtx
+ return false;
+ }
+
+ auto it_fec = recover_with_fec_.find(seq);
+ if (it_fec != recover_with_fec_.end()) {
+ // this packet is already in list of packets to recover with fec
+ // this list contians also fec packets that will not be recovered with rtx
+ return false;
+ }
+
+ auto it_nack = nacked_seq_.find(seq);
+ if (it_nack != nacked_seq_.end()) {
+ // this packet was nacked so we do not use it to determine the loss rate
+ return false;
+ }
+
+ return true;
+}
+
+void RecoveryStrategy::notifyNewLossDetedcted(uint32_t seq) {
+ // new loss detected
+ // first record the loss. second do what is needed to recover it
+ state_->onLossDetected(seq);
+ newPacketLoss(seq);
+}
+
+void RecoveryStrategy::requestPossibleLostPacket(uint32_t seq) {
+ // these are packets for which we send a RTX but we do not increase the loss
+ // counter beacuse we don't know if they are lost or not
+ addNewRtx(seq, false);
+}
+
+void RecoveryStrategy::receivedFutureNack(uint32_t seq) {
+ nacked_seq_.insert(seq);
+}
+
+void RecoveryStrategy::clear() {
+ rtx_state_.clear();
+ rtx_timers_.clear();
+ recover_with_fec_.clear();
+
+ if (next_rtx_timer_ != MAX_TIMER_RTX) {
+ next_rtx_timer_ = MAX_TIMER_RTX;
+ timer_->cancel();
+ }
+}
+
+// rtx functions
+void RecoveryStrategy::addNewRtx(uint32_t seq, bool force) {
+ if (!indexer_->isFec(seq) || force) {
+ // this packet needs to be re-transmitted
+ rtxState state;
+ state.first_send_ = state_->getInterestSentTime(seq);
+ if (state.first_send_ == 0) // this interest was never sent before
+ state.first_send_ = getNow();
+ state.last_send_ = state.first_send_; // we didn't send an RTX for this
+ // packet yet
+ state.rtx_count_ = 0;
+ state.next_send_ = computeNextSend(seq, state.rtx_count_);
+ DLOG_IF(INFO, VLOG_IS_ON(4))
+ << "Add " << seq << " to retransmissions. next rtx is in "
+ << state.next_send_ - getNow() << " ms";
+ rtx_state_.insert(std::pair<uint32_t, rtxState>(seq, state));
+ rtx_timers_.insert(std::pair<uint64_t, uint32_t>(state.next_send_, seq));
+
+ // if a new rtx is introduced, check the rtx timer
+ scheduleNextRtx();
+ } else {
+ // do not re-send fec packets but keep track of them
+ recover_with_fec_.insert(seq);
+ state_->onPossibleLossWithNoRtx(seq);
+ }
+}
+
+uint64_t RecoveryStrategy::computeNextSend(uint32_t seq, uint32_t rtx_counter) {
+ uint64_t now = getNow();
+ if (rtx_counter == 0) {
+ uint32_t wait = 1;
+ if (content_sharing_mode_) return now + wait;
+
+ uint32_t jitter = SENTINEL_TIMER_INTERVAL;
+ double prod_rate = state_->getProducerRate();
+ if (prod_rate != 0) jitter = ceil(state_->getJitter());
+
+ wait += jitter;
+
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "first rtx for " << seq << " in " << wait
+ << " ms, jitter = " << jitter;
+
+ return now + wait;
+ } else {
+ // wait one RTT. if an edge is known use the edge RTT for the first 5 rtx
+ double prod_rate = state_->getProducerRate();
+ if (prod_rate == 0) {
+ return now + SENTINEL_TIMER_INTERVAL;
+ }
+
+ uint64_t rtt = 0;
+ // if the transport detects an edge we try first to get the RTX from the
+ // edge. if no interest get a reply we move to the full RTT
+ if (rtx_counter < 5 && (state_->getEdgeRtt() != 0)) {
+ rtt = state_->getEdgeRtt();
+ } else {
+ rtt = state_->getAvgRTT();
+ }
+
+ if (rtt == 0) rtt = SENTINEL_TIMER_INTERVAL;
+
+ if (content_sharing_mode_) return now + rtt;
+
+ uint32_t wait = (uint32_t)rtt;
+
+ uint32_t jitter = ceil(state_->getJitter());
+ wait += jitter;
+
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "next rtx for " << seq << " in " << wait << " ms, rtt = " << rtt
+ << " jtter = " << jitter;
+
+ return now + wait;
+ }
+}
+
+void RecoveryStrategy::retransmit() {
+ if (rtx_timers_.size() == 0) return;
+
+ uint64_t now = getNow();
+
+ auto it = rtx_timers_.begin();
+ std::unordered_set<uint32_t> lost_pkt;
+ uint32_t sent_counter = 0;
+ while (it != rtx_timers_.end() && it->first <= now &&
+ sent_counter < MAX_RTX_IN_BATCH) {
+ uint32_t seq = it->second;
+ auto rtx_it =
+ rtx_state_.find(seq); // this should always return a valid iter
+ if (rtx_it->second.rtx_count_ >= RTC_MAX_RTX ||
+ (now - rtx_it->second.first_send_) >= RTC_MAX_AGE ||
+ seq < state_->getLastSeqNacked()) {
+ // max rtx reached or packet too old or packet nacked, this packet is lost
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "packet " << seq << " lost because 1) max rtx: "
+ << (rtx_it->second.rtx_count_ >= RTC_MAX_RTX) << " 2) max age: "
+ << ((now - rtx_it->second.first_send_) >= RTC_MAX_AGE)
+ << " 3) nacked: " << (seq < state_->getLastSeqNacked());
+ lost_pkt.insert(seq);
+ it++;
+ } else {
+ // resend the packet
+ state_->onRetransmission(seq);
+ double prod_rate = state_->getProducerRate();
+ if (prod_rate != 0) rtx_it->second.rtx_count_++;
+ rtx_it->second.last_send_ = now;
+ rtx_it->second.next_send_ =
+ computeNextSend(seq, rtx_it->second.rtx_count_);
+ it = rtx_timers_.erase(it);
+ rtx_timers_.insert(
+ std::pair<uint64_t, uint32_t>(rtx_it->second.next_send_, seq));
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "send rtx for sequence " << seq << ", next send in "
+ << (rtx_it->second.next_send_ - now);
+
+ // if fec is on increase the number of RTX send during fec
+ if (fec_on_) rtx_during_fec_++;
+ send_rtx_callback_(seq);
+ sent_counter++;
+ }
+ }
+
+ // remove packets if needed
+ for (auto lost_it = lost_pkt.begin(); lost_it != lost_pkt.end(); lost_it++) {
+ uint32_t seq = *lost_it;
+ state_->onPacketLost(seq);
+ deleteRtx(seq);
+ }
+}
+
+void RecoveryStrategy::scheduleNextRtx() {
+ if (rtx_timers_.size() == 0) {
+ // all the rtx were removed, reset timer
+ next_rtx_timer_ = MAX_TIMER_RTX;
+ return;
+ }
+
+ // check if timer is alreay set
+ if (next_rtx_timer_ != MAX_TIMER_RTX) {
+ // a new check for rtx is already scheduled
+ if (next_rtx_timer_ > rtx_timers_.begin()->first) {
+ // we need to re-schedule it
+ timer_->cancel();
+ } else {
+ // wait for the next timer
+ return;
+ }
+ }
+
+ // set a new timer
+ next_rtx_timer_ = rtx_timers_.begin()->first;
+ uint64_t now = utils::SteadyTime::nowMs().count();
+ uint64_t wait = 1;
+ if (next_rtx_timer_ != MAX_TIMER_RTX && next_rtx_timer_ > now)
+ wait = next_rtx_timer_ - now;
+
+ std::weak_ptr<RecoveryStrategy> self(shared_from_this());
+ timer_->expires_from_now(std::chrono::milliseconds(wait));
+ timer_->async_wait([self](const std::error_code &ec) {
+ if (ec) return;
+ if (auto s = self.lock()) {
+ s->retransmit();
+ s->next_rtx_timer_ = MAX_TIMER_RTX;
+ s->scheduleNextRtx();
+ }
+ });
+}
+
+void RecoveryStrategy::deleteRtx(uint32_t seq) {
+ auto it_rtx = rtx_state_.find(seq);
+ if (it_rtx == rtx_state_.end()) return; // rtx not found
+
+ // remove the rtx from the timers list
+ uint64_t ts = it_rtx->second.next_send_;
+ auto it_timers = rtx_timers_.find(ts);
+ while (it_timers != rtx_timers_.end() && it_timers->first == ts) {
+ if (it_timers->second == seq) {
+ rtx_timers_.erase(it_timers);
+ break;
+ }
+ it_timers++;
+ }
+
+ // remove rtx
+ rtx_state_.erase(it_rtx);
+}
+
+// fec functions
+uint32_t RecoveryStrategy::computeFecPacketsToAsk() {
+ double loss_rate = state_->getMaxLossRate() * 100; // use loss rate in %
+
+ if (loss_rate > 95) loss_rate = 95; // max loss rate
+
+ if (loss_rate == 0) return 0;
+
+ // keep track of the last used fec. if we use a new bin on this round reset
+ // consecutive use and avg loss in the prev bin
+ uint32_t bin = ceil(loss_rate / 5.0) - 1;
+ if (bin > fec_per_loss_rate_.size() - 1)
+ bin = (uint32_t)fec_per_loss_rate_.size() - 1;
+
+ return fec_per_loss_rate_[bin];
+}
+
+void RecoveryStrategy::setRtxFec(std::optional<bool> rtx_on,
+ std::optional<bool> fec_on) {
+ if (rtx_on) rtx_on_ = *rtx_on;
+ if (fec_on) {
+ if (fec_on_ == false && (*fec_on) == true) { // turn on fec
+ // reset the number of RTX sent during fec
+ rtx_during_fec_ = 0;
+ }
+ fec_on_ = *fec_on;
+ }
+
+ notification::RecoveryStrategy strategy =
+ notification::RecoveryStrategy::RECOVERY_OFF;
+
+ if (rtx_on_ && fec_on_)
+ strategy = notification::RecoveryStrategy::RTX_AND_FEC;
+ else if (rtx_on_)
+ strategy = notification::RecoveryStrategy::RTX_ONLY;
+ else if (fec_on_)
+ strategy = notification::RecoveryStrategy::FEC_ONLY;
+
+ callback_(strategy);
+}
+
+// common functions
+void RecoveryStrategy::onLostTimeout(uint32_t seq) { removePacketState(seq); }
+
+void RecoveryStrategy::removePacketState(uint32_t seq) {
+ auto it_fec = recover_with_fec_.find(seq);
+ if (it_fec != recover_with_fec_.end()) {
+ recover_with_fec_.erase(it_fec);
+ return;
+ }
+
+ auto it_nack = nacked_seq_.find(seq);
+ if (it_nack != nacked_seq_.end()) {
+ nacked_seq_.erase(it_nack);
+ return;
+ }
+
+ deleteRtx(seq);
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_recovery_strategy.h b/libtransport/src/protocols/rtc/rtc_recovery_strategy.h
new file mode 100644
index 000000000..405e1ebba
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_recovery_strategy.h
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <hicn/transport/interfaces/callbacks.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
+#include <protocols/indexer.h>
+#include <protocols/rtc/rtc_rc.h>
+#include <protocols/rtc/rtc_state.h>
+
+#include <map>
+#include <optional>
+#include <unordered_map>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RecoveryStrategy : public std::enable_shared_from_this<RecoveryStrategy> {
+ protected:
+ struct rtx_state_ {
+ uint64_t first_send_; // first time this interest was sent
+ uint64_t last_send_; // last time this rtx was sent
+ uint64_t next_send_; // next retransmission time
+ uint32_t rtx_count_; // number or rtx
+ };
+
+ using rtxState = struct rtx_state_;
+
+ public:
+ using SendRtxCallback = std::function<void(uint32_t)>;
+
+ RecoveryStrategy(Indexer *indexer, SendRtxCallback &&callback,
+ asio::io_service &io_service, bool use_rtx, bool use_fec,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback);
+
+ RecoveryStrategy(RecoveryStrategy &&rs);
+
+ virtual ~RecoveryStrategy();
+
+ void setRtxFec(std::optional<bool> rtx_on = {},
+ std::optional<bool> fec_on = {});
+ void setState(RTCState *state) { state_ = state; }
+ void setRateControl(RTCRateControl *rateControl) { rc_ = rateControl; }
+ void setFecParams(uint32_t n, uint32_t k);
+ void setContentSharingMode() { content_sharing_mode_ = true; }
+
+ bool isRtx(uint32_t seq) {
+ if (rtx_state_.find(seq) != rtx_state_.end()) return true;
+ return false;
+ }
+
+ bool isPossibleLossWithNoRtx(uint32_t seq) {
+ if (recover_with_fec_.find(seq) != recover_with_fec_.end()) return true;
+ return false;
+ }
+
+ bool wasNacked(uint32_t seq) {
+ if (nacked_seq_.find(seq) != nacked_seq_.end()) return true;
+ return false;
+ }
+
+ interface::RtcTransportRecoveryStrategies getType() {
+ return rs_type_;
+ }
+ void updateType(interface::RtcTransportRecoveryStrategies type) {
+ rs_type_ = type;
+ }
+ bool isRtxOn() { return rtx_on_; }
+ bool isFecOn() { return fec_on_; }
+
+ RTCState *getState() { return state_; }
+
+ // if the function returns 0 it means that the packet is not an RTX or it is
+ // not a valid packet to safely compute the RTT
+ uint64_t getRtxRtt(uint32_t seq);
+ bool lossDetected(uint32_t seq);
+ void notifyNewLossDetedcted(uint32_t seq);
+ void requestPossibleLostPacket(uint32_t seq);
+ void receivedFutureNack(uint32_t seq);
+ void clear();
+
+ virtual void turnOnRecovery() = 0;
+ virtual void onNewRound(bool in_sync) = 0;
+ virtual void newPacketLoss(uint32_t seq) = 0;
+ virtual void receivedPacket(uint32_t seq) = 0;
+ void onLostTimeout(uint32_t seq);
+
+ void incRoundId() { round_id_++; }
+
+ // utils
+ uint64_t getNow() {
+ uint64_t now = utils::SteadyTime::nowMs().count();
+ return now;
+ }
+
+ protected:
+ // rtx functions
+ void addNewRtx(uint32_t seq, bool force);
+ uint64_t computeNextSend(uint32_t seq, uint32_t rtx_counter);
+ void retransmit();
+ void scheduleNextRtx();
+ void deleteRtx(uint32_t seq);
+
+ // fec functions
+ uint32_t computeFecPacketsToAsk();
+
+ // common functons
+ void removePacketState(uint32_t seq);
+
+ interface::RtcTransportRecoveryStrategies rs_type_;
+ bool recovery_on_;
+ bool rtx_on_;
+ bool fec_on_;
+ bool content_sharing_mode_;
+
+ // number of RTX sent after fec turned on
+ // this is used to take into account jitter and out of order packets
+ // if we detect losses but we do not sent any RTX it means that the holes in
+ // the sequence are caused by the jitter
+ uint32_t rtx_during_fec_;
+
+ // this map keeps track of the retransmitted interest, ordered from the oldest
+ // to the newest one. the state contains the timer of the first send of the
+ // interest (from pendingIntetests_), the timer of the next send (key of the
+ // multimap) and the number of rtx
+ std::map<uint32_t, rtxState> rtx_state_;
+ // this map stored the rtx by timer. The key is the time at which the rtx
+ // should be sent, and the val is the interest seq number
+ std::multimap<uint64_t, uint32_t> rtx_timers_;
+
+ // lost packets that will be recovered with fec
+ std::unordered_set<uint32_t> recover_with_fec_;
+
+ // packet for which we recived a future nack
+ // in case we detect a loss for a nacked packet we send an RTX but we do not
+ // increase the loss counter. this is done because it may happen that the
+ // producer rate checkes over time and in flight interest may be satified by
+ // data packet after the reception of nacks
+ std::unordered_set<uint32_t> nacked_seq_;
+
+ // rtx vars
+ std::unique_ptr<asio::steady_timer> timer_;
+ uint64_t next_rtx_timer_;
+ SendRtxCallback send_rtx_callback_;
+
+ // fec vars
+ uint32_t n_;
+ uint32_t k_;
+ Indexer *indexer_;
+
+ RTCState *state_;
+ RTCRateControl *rc_;
+
+ private:
+ uint32_t round_id_; // number of rounds
+ uint32_t last_fec_used_;
+ std::vector<uint32_t> fec_per_loss_rate_;
+ interface::StrategyCallback callback_;
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_delay.cc b/libtransport/src/protocols/rtc/rtc_rs_delay.cc
new file mode 100644
index 000000000..7d7a01133
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_delay.cc
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_rs_delay.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RecoveryStrategyDelayBased::RecoveryStrategyDelayBased(
+ Indexer *indexer, SendRtxCallback &&callback, asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback)
+ : RecoveryStrategy(indexer, std::move(callback), io_service, true, false,
+ rs_type,
+ std::move(external_callback)), // start with rtx
+ congestion_state_(false),
+ probing_state_(false),
+ switch_rounds_(0) {}
+
+RecoveryStrategyDelayBased::RecoveryStrategyDelayBased(RecoveryStrategy &&rs)
+ : RecoveryStrategy(std::move(rs)) {
+ setRtxFec(true, false);
+ // we have to re-init congestion and
+ // probing
+ switch_rounds_ = 0;
+ congestion_state_ = false;
+ probing_state_ = false;
+}
+
+RecoveryStrategyDelayBased::~RecoveryStrategyDelayBased() {}
+
+void RecoveryStrategyDelayBased::turnOnRecovery() {
+ recovery_on_ = true;
+ uint64_t rtt = state_->getMinRTT();
+ uint32_t fec_to_ask = computeFecPacketsToAsk();
+ if (rtt > MAX_RTT_BEFORE_FEC && fec_to_ask > 0) {
+ // we need to start FEC (see fec only strategy for more details)
+ setRtxFec(true, true);
+ rtx_during_fec_ = 1; // avoid to stop fec
+ indexer_->setNFec(fec_to_ask);
+ } else {
+ // use RTX
+ setRtxFec(true, false);
+ switch_rounds_ = 0;
+ }
+}
+
+void RecoveryStrategyDelayBased::softSwitchToFec(uint32_t fec_to_ask) {
+ if (fec_to_ask == 0) {
+ setRtxFec(true, false);
+ switch_rounds_ = 0;
+ } else {
+ switch_rounds_++;
+ if (switch_rounds_ >= ((RTC_INTEREST_LIFETIME / ROUND_LEN) * 2) &&
+ rtx_during_fec_ != 0) { // go to fec only if it is needed (RTX are on)
+ setRtxFec(false, true);
+ } else {
+ setRtxFec(true, true);
+ }
+ }
+}
+
+void RecoveryStrategyDelayBased::onNewRound(bool in_sync) {
+ if (!recovery_on_) {
+ // disable fec so that no extra packet will be sent
+ // for rtx we check if recovery is on in newPacketLoss
+ setRtxFec(true, false);
+ indexer_->setNFec(0);
+ return;
+ }
+
+ uint64_t rtt = state_->getAvgRTT();
+
+ // XXX at the moment we are not looking at congestion events
+ // bool congestion = rc_->inCongestionState();
+
+ if ((!fec_on_ && rtt >= MAX_RTT_BEFORE_FEC) ||
+ (fec_on_ && rtt > (MAX_RTT_BEFORE_FEC - 10))) {
+ // switch from rtx to fec or keep use fec. Notice that if some rtx are
+ // waiting to be scheduled, they will be sent normally, but no new rtx will
+ // be created if the loss rate is 0 keep to use RTX.
+ uint32_t fec_to_ask = computeFecPacketsToAsk();
+ softSwitchToFec(fec_to_ask);
+ if (rtx_during_fec_ == 0) // if we do not send any RTX the losses
+ // registered may be due to jitter
+ indexer_->setNFec(0);
+ else
+ indexer_->setNFec(fec_to_ask);
+ return;
+ }
+
+ if ((fec_on_ && rtt <= (MAX_RTT_BEFORE_FEC - 10)) ||
+ (!rtx_on_ && rtt <= MAX_RTT_BEFORE_FEC)) {
+ // turn on rtx
+ softSwitchToFec(0);
+ indexer_->setNFec(0);
+ return;
+ }
+}
+
+void RecoveryStrategyDelayBased::newPacketLoss(uint32_t seq) {
+ if (rtx_on_ && recovery_on_) {
+ addNewRtx(seq, false);
+ } else {
+ if (!state_->isPending(seq) && !indexer_->isFec(seq)) {
+ addNewRtx(seq, true);
+ } else {
+ recover_with_fec_.insert(seq);
+ state_->onPossibleLossWithNoRtx(seq);
+ }
+ }
+}
+
+void RecoveryStrategyDelayBased::receivedPacket(uint32_t seq) {
+ removePacketState(seq);
+}
+
+void RecoveryStrategyDelayBased::probing() {
+ // TODO
+ // for the moment ask for all fec and exit the probing phase
+ probing_state_ = false;
+ setRtxFec(false, true);
+ indexer_->setNFec(computeFecPacketsToAsk());
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_delay.h b/libtransport/src/protocols/rtc/rtc_rs_delay.h
new file mode 100644
index 000000000..9e1c41388
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_delay.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <protocols/rtc/rtc_recovery_strategy.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RecoveryStrategyDelayBased : public RecoveryStrategy {
+ public:
+ RecoveryStrategyDelayBased(Indexer *indexer, SendRtxCallback &&callback,
+ asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback);
+
+ RecoveryStrategyDelayBased(RecoveryStrategy &&rs);
+
+ ~RecoveryStrategyDelayBased();
+
+ void turnOnRecovery();
+ void onNewRound(bool in_sync);
+ void newPacketLoss(uint32_t seq);
+ void receivedPacket(uint32_t seq);
+
+ private:
+ void softSwitchToFec(uint32_t fec_to_ask);
+
+ bool congestion_state_;
+ bool probing_state_;
+ uint32_t switch_rounds_;
+
+ void probing();
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_fec_only.cc b/libtransport/src/protocols/rtc/rtc_rs_fec_only.cc
new file mode 100644
index 000000000..5b10823ec
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_fec_only.cc
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_rs_fec_only.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RecoveryStrategyFecOnly::RecoveryStrategyFecOnly(
+ Indexer *indexer, SendRtxCallback &&callback, asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback)
+ : RecoveryStrategy(indexer, std::move(callback), io_service, true, false,
+ rs_type, std::move(external_callback)),
+ congestion_state_(false),
+ probing_state_(false),
+ switch_rounds_(0) {}
+
+RecoveryStrategyFecOnly::RecoveryStrategyFecOnly(RecoveryStrategy &&rs)
+ : RecoveryStrategy(std::move(rs)) {
+ setRtxFec(true, false);
+ switch_rounds_ = 0;
+ congestion_state_ = false;
+ probing_state_ = false;
+}
+
+RecoveryStrategyFecOnly::~RecoveryStrategyFecOnly() {}
+
+void RecoveryStrategyFecOnly::turnOnRecovery() {
+ recovery_on_ = true;
+ // init strategy
+ uint32_t fec_to_ask = computeFecPacketsToAsk();
+ if (fec_to_ask > 0) {
+ // the probing phase detected a lossy link. we immedialty start the fec and
+ // we disable the check to prevent to send fec packets before RTX. in fact
+ // here we know that we have losses and it is not a problem of OOO packets
+ setRtxFec(true, true);
+ rtx_during_fec_ = 1; // avoid to stop fec
+ indexer_->setNFec(fec_to_ask);
+ } else {
+ // keep only RTX on
+ setRtxFec(true, true);
+ }
+}
+
+void RecoveryStrategyFecOnly::onNewRound(bool in_sync) {
+ if (!recovery_on_) {
+ indexer_->setNFec(0);
+ return;
+ }
+
+ // XXX for the moment we are considering congestion events
+ // if(rc_->inCongestionState()){
+ // congestion_state_ = true;
+ // probing_state_ = false;
+ // indexer_->setNFec(0);
+ // return;
+ // }
+
+ // no congestion
+ if (congestion_state_) {
+ // this is the first round after congestion
+ // enter probing phase
+ probing_state_ = true;
+ congestion_state_ = false;
+ }
+
+ if (probing_state_) {
+ probing();
+ } else {
+ uint32_t fec_to_ask = computeFecPacketsToAsk();
+ // If fec_to_ask == 0 we use rtx even if in these strategy we use only fec.
+ // In this way the first packet loss that triggers the usage of fec can be
+ // recovered using rtx, otherwise it will always be lost
+ if (fec_to_ask == 0) {
+ setRtxFec(true, false);
+ switch_rounds_ = 0;
+ } else {
+ switch_rounds_++;
+ if (switch_rounds_ >= ((RTC_INTEREST_LIFETIME / ROUND_LEN) * 2) &&
+ rtx_during_fec_ !=
+ 0) { // go to fec only if it is needed (RTX are on)
+ setRtxFec(false, true);
+ } else {
+ setRtxFec(true, true); // keep both
+ }
+ }
+ if (rtx_during_fec_ == 0) // if we do not send any RTX the losses
+ // registered may be due to jitter
+ indexer_->setNFec(0);
+ else
+ indexer_->setNFec(fec_to_ask);
+ }
+}
+
+void RecoveryStrategyFecOnly::newPacketLoss(uint32_t seq) {
+ if (rtx_on_ && recovery_on_) {
+ addNewRtx(seq, false);
+ } else {
+ if (!state_->isPending(seq) && !indexer_->isFec(seq)) {
+ addNewRtx(seq, true);
+ } else {
+ // if not pending add to list to recover with fec
+ recover_with_fec_.insert(seq);
+ state_->onPossibleLossWithNoRtx(seq);
+ }
+ }
+}
+
+void RecoveryStrategyFecOnly::receivedPacket(uint32_t seq) {
+ removePacketState(seq);
+}
+
+void RecoveryStrategyFecOnly::probing() {
+ // TODO
+ // for the moment ask for all fec and exit the probing phase
+ probing_state_ = false;
+ uint32_t fec_to_ask = computeFecPacketsToAsk();
+ indexer_->setNFec(fec_to_ask);
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_fec_only.h b/libtransport/src/protocols/rtc/rtc_rs_fec_only.h
new file mode 100644
index 000000000..42df25bd9
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_fec_only.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <protocols/rtc/rtc_recovery_strategy.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RecoveryStrategyFecOnly : public RecoveryStrategy {
+ public:
+ RecoveryStrategyFecOnly(Indexer *indexer, SendRtxCallback &&callback,
+ asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback);
+
+ RecoveryStrategyFecOnly(RecoveryStrategy &&rs);
+
+ ~RecoveryStrategyFecOnly();
+
+ void turnOnRecovery();
+ void onNewRound(bool in_sync);
+ void newPacketLoss(uint32_t seq);
+ void receivedPacket(uint32_t seq);
+
+ private:
+ bool congestion_state_;
+ bool probing_state_;
+ uint32_t switch_rounds_;
+
+ void probing();
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_low_rate.cc b/libtransport/src/protocols/rtc/rtc_rs_low_rate.cc
new file mode 100644
index 000000000..dbad563cd
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_low_rate.cc
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_rs_low_rate.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RecoveryStrategyLowRate::RecoveryStrategyLowRate(
+ Indexer *indexer, SendRtxCallback &&callback, asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback)
+ : RecoveryStrategy(indexer, std::move(callback), io_service, false, true,
+ rs_type,
+ std::move(external_callback)), // start with fec
+ fec_consecutive_rounds_((MILLI_IN_A_SEC / ROUND_LEN) * 5), // 5 sec
+ rtx_allowed_consecutive_rounds_(0) {
+ initSwitchVector();
+}
+
+RecoveryStrategyLowRate::RecoveryStrategyLowRate(RecoveryStrategy &&rs)
+ : RecoveryStrategy(std::move(rs)),
+ fec_consecutive_rounds_((MILLI_IN_A_SEC / ROUND_LEN) * 5), // 5 sec
+ rtx_allowed_consecutive_rounds_(0) {
+ setRtxFec(false, true);
+ initSwitchVector();
+}
+
+RecoveryStrategyLowRate::~RecoveryStrategyLowRate() {}
+
+void RecoveryStrategyLowRate::initSwitchVector() {
+ // TODO adjust thresholds here when new data are collected
+ // see resutls in
+ // https://confluence-eng-gpk1.cisco.com/conf/display/SPT/dailyreports
+ thresholds_t t1;
+ t1.rtt = 15; // 15ms
+ t1.loss_rtx_to_fec = 15; // 15%
+ t1.loss_fec_to_rtx = 10; // 10%
+ thresholds_t t2;
+ t2.rtt = 35; // 35ms
+ t2.loss_rtx_to_fec = 5; // 5%
+ t2.loss_fec_to_rtx = 1; // 1%
+ switch_vector.push_back(t1);
+ switch_vector.push_back(t2);
+}
+
+void RecoveryStrategyLowRate::setRecoveryParameters(bool use_rtx, bool use_fec,
+ uint32_t fec_to_ask) {
+ setRtxFec(use_rtx, use_fec);
+ indexer_->setNFec(fec_to_ask);
+}
+
+void RecoveryStrategyLowRate::selectRecoveryStrategy(bool in_sync) {
+ uint32_t fec_to_ask = computeFecPacketsToAsk();
+ if (fec_to_ask == 0) {
+ // fec is off, turn on RTX immediatly to avoid packet losses
+ setRecoveryParameters(true, false, 0);
+ fec_consecutive_rounds_ = 0;
+ return;
+ }
+
+ uint32_t loss_rate = std::round(state_->getPerSecondLossRate() * 100);
+ uint32_t rtt = (uint32_t)state_->getAvgRTT();
+
+ bool use_rtx = false;
+ for (size_t i = 0; i < switch_vector.size(); i++) {
+ uint32_t max_loss_rate = 0;
+ if (fec_on_)
+ max_loss_rate = switch_vector[i].loss_fec_to_rtx;
+ else
+ max_loss_rate = switch_vector[i].loss_rtx_to_fec;
+
+ if (rtt < switch_vector[i].rtt && loss_rate < max_loss_rate) {
+ use_rtx = true;
+ rtx_allowed_consecutive_rounds_++;
+ break;
+ }
+ }
+
+ if (!use_rtx) rtx_allowed_consecutive_rounds_ = 0;
+
+ if (use_rtx) {
+ if (fec_on_) {
+ // here we should swtich from RTX to FEC
+ // wait 10sec where the switch is allowed before actually switch
+ if (rtx_allowed_consecutive_rounds_ >=
+ ((MILLI_IN_A_SEC / ROUND_LEN) * 10)) { // 10 sec
+ // use RTX
+ setRecoveryParameters(true, false, 0);
+ fec_consecutive_rounds_ = 0;
+ } else {
+ // keep using FEC (and maybe RTX)
+ setRecoveryParameters(true, true, fec_to_ask);
+ fec_consecutive_rounds_++;
+ }
+ } else {
+ // keep using RTX
+ setRecoveryParameters(true, false, 0);
+ fec_consecutive_rounds_ = 0;
+ }
+ } else {
+ // use FEC and RTX
+ setRecoveryParameters(true, true, fec_to_ask);
+ fec_consecutive_rounds_++;
+ }
+
+ // everytime that we anable FEC we keep also RTX on. in this way the first
+ // losses that are not covered by FEC are recovered using RTX. after 5 sec we
+ // disable fec
+ if (fec_consecutive_rounds_ >= ((MILLI_IN_A_SEC / ROUND_LEN) * 5)) {
+ // turn off RTX
+ setRtxFec(false);
+ }
+}
+
+void RecoveryStrategyLowRate::turnOnRecovery() {
+ recovery_on_ = 1;
+ // the stategy will be init in the new round function
+}
+
+void RecoveryStrategyLowRate::onNewRound(bool in_sync) {
+ if (!recovery_on_) {
+ // disable fec so that no extra packet will be sent
+ // for rtx we check if recovery is on in newPacketLoss
+ setRtxFec(true, false);
+ indexer_->setNFec(0);
+ return;
+ }
+
+ // XXX since this strategy will be used only for flow at low rate we do not
+ // consider congestion events like in other strategies
+
+ selectRecoveryStrategy(in_sync);
+}
+
+void RecoveryStrategyLowRate::newPacketLoss(uint32_t seq) {
+ if (rtx_on_ && recovery_on_) {
+ addNewRtx(seq, false);
+ } else {
+ if (!state_->isPending(seq) && !indexer_->isFec(seq)) {
+ addNewRtx(seq, true);
+ } else {
+ recover_with_fec_.insert(seq);
+ state_->onPossibleLossWithNoRtx(seq);
+ }
+ }
+}
+
+void RecoveryStrategyLowRate::receivedPacket(uint32_t seq) {
+ removePacketState(seq);
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_low_rate.h b/libtransport/src/protocols/rtc/rtc_rs_low_rate.h
new file mode 100644
index 000000000..0e76efaca
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_low_rate.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <protocols/rtc/rtc_recovery_strategy.h>
+
+#include <vector>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+struct thresholds_t {
+ uint32_t rtt;
+ uint32_t loss_rtx_to_fec; // loss rate used to move from rtx to fec
+ uint32_t loss_fec_to_rtx; // loss rate used to move from fec to rtx
+};
+
+class RecoveryStrategyLowRate : public RecoveryStrategy {
+ public:
+ RecoveryStrategyLowRate(Indexer *indexer, SendRtxCallback &&callback,
+ asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback);
+
+ RecoveryStrategyLowRate(RecoveryStrategy &&rs);
+
+ ~RecoveryStrategyLowRate();
+
+ void turnOnRecovery();
+ void onNewRound(bool in_sync);
+ void newPacketLoss(uint32_t seq);
+ void receivedPacket(uint32_t seq);
+
+ private:
+ void initSwitchVector();
+ void setRecoveryParameters(bool use_rtx, bool use_fec, uint32_t fec_to_ask);
+ void selectRecoveryStrategy(bool in_sync);
+
+ uint32_t fec_consecutive_rounds_;
+ uint32_t rtx_allowed_consecutive_rounds_;
+
+ // this table contains the thresholds that indicates when to switch from RTX
+ // to FEC and viceversa. values in the vector are detected with a set of
+ // experiments. the vector is used in the following way: if rtt and loss rate
+ // are less than one of the values in the in the vector, losses are
+ // recovered using RTX. otherwive losses are recovered using FEC. as for FEC
+ // only and delay based strategy, the swith from RTX to FEC is smooth,
+ // meaning that FEC and RTX are used together for some rounds
+ std::vector<thresholds_t> switch_vector;
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_recovery_off.cc b/libtransport/src/protocols/rtc/rtc_rs_recovery_off.cc
new file mode 100644
index 000000000..00c6a0504
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_recovery_off.cc
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_rs_recovery_off.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RecoveryStrategyRecoveryOff::RecoveryStrategyRecoveryOff(
+ Indexer *indexer, SendRtxCallback &&callback, asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback)
+ : RecoveryStrategy(indexer, std::move(callback), io_service, false, false,
+ rs_type, std::move(external_callback)) {}
+
+RecoveryStrategyRecoveryOff::RecoveryStrategyRecoveryOff(RecoveryStrategy &&rs)
+ : RecoveryStrategy(std::move(rs)) {
+ setRtxFec(false, false);
+}
+
+RecoveryStrategyRecoveryOff::~RecoveryStrategyRecoveryOff() {}
+
+void RecoveryStrategyRecoveryOff::turnOnRecovery() {
+ // nothing to do
+ return;
+}
+void RecoveryStrategyRecoveryOff::onNewRound(bool in_sync) {
+ // nothing to do
+ return;
+}
+
+void RecoveryStrategyRecoveryOff::newPacketLoss(uint32_t seq) {
+ // here we only keep track of the lost packets to avoid to
+ // count them multple times in the counters. for this we
+ // use the recover_with_fec_ set
+ recover_with_fec_.insert(seq);
+ state_->onPossibleLossWithNoRtx(seq);
+}
+
+void RecoveryStrategyRecoveryOff::receivedPacket(uint32_t seq) {
+ removePacketState(seq);
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_recovery_off.h b/libtransport/src/protocols/rtc/rtc_rs_recovery_off.h
new file mode 100644
index 000000000..3d59cc473
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_recovery_off.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <protocols/rtc/rtc_recovery_strategy.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RecoveryStrategyRecoveryOff : public RecoveryStrategy {
+ public:
+ RecoveryStrategyRecoveryOff(Indexer *indexer, SendRtxCallback &&callback,
+ asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback);
+
+ RecoveryStrategyRecoveryOff(RecoveryStrategy &&rs);
+
+ ~RecoveryStrategyRecoveryOff();
+
+ void turnOnRecovery();
+ void onNewRound(bool in_sync);
+ void newPacketLoss(uint32_t seq);
+ void receivedPacket(uint32_t seq);
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_rtx_only.cc b/libtransport/src/protocols/rtc/rtc_rs_rtx_only.cc
new file mode 100644
index 000000000..4d7cf7a82
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_rtx_only.cc
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <protocols/rtc/rtc_consts.h>
+#include <protocols/rtc/rtc_rs_rtx_only.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+RecoveryStrategyRtxOnly::RecoveryStrategyRtxOnly(
+ Indexer *indexer, SendRtxCallback &&callback, asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback)
+ : RecoveryStrategy(indexer, std::move(callback), io_service, true, false,
+ rs_type, std::move(external_callback)) {}
+
+RecoveryStrategyRtxOnly::RecoveryStrategyRtxOnly(RecoveryStrategy &&rs)
+ : RecoveryStrategy(std::move(rs)) {
+ setRtxFec(true, false);
+}
+
+RecoveryStrategyRtxOnly::~RecoveryStrategyRtxOnly() {}
+
+void RecoveryStrategyRtxOnly::turnOnRecovery() {
+ recovery_on_ = true;
+ setRtxFec(true, false);
+}
+
+void RecoveryStrategyRtxOnly::onNewRound(bool in_sync) {
+ // nothing to do
+ return;
+}
+
+void RecoveryStrategyRtxOnly::newPacketLoss(uint32_t seq) {
+ if (!recovery_on_) {
+ recover_with_fec_.insert(seq);
+ state_->onPossibleLossWithNoRtx(seq);
+ return;
+ }
+ addNewRtx(seq, false);
+}
+
+void RecoveryStrategyRtxOnly::receivedPacket(uint32_t seq) {
+ removePacketState(seq);
+}
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_rs_rtx_only.h b/libtransport/src/protocols/rtc/rtc_rs_rtx_only.h
new file mode 100644
index 000000000..03dbed1c7
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_rs_rtx_only.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#include <protocols/rtc/rtc_recovery_strategy.h>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+class RecoveryStrategyRtxOnly : public RecoveryStrategy {
+ public:
+ RecoveryStrategyRtxOnly(Indexer *indexer, SendRtxCallback &&callback,
+ asio::io_service &io_service,
+ interface::RtcTransportRecoveryStrategies rs_type,
+ interface::StrategyCallback &&external_callback);
+
+ RecoveryStrategyRtxOnly(RecoveryStrategy &&rs);
+
+ ~RecoveryStrategyRtxOnly();
+
+ void turnOnRecovery();
+ void onNewRound(bool in_sync);
+ void newPacketLoss(uint32_t seq);
+ void receivedPacket(uint32_t seq);
+};
+
+} // end namespace rtc
+
+} // end namespace protocol
+
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_state.cc b/libtransport/src/protocols/rtc/rtc_state.cc
index c99205a26..82ac0b9c1 100644
--- a/libtransport/src/protocols/rtc/rtc_state.cc
+++ b/libtransport/src/protocols/rtc/rtc_state.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -24,15 +24,15 @@ namespace protocol {
namespace rtc {
RTCState::RTCState(Indexer *indexer,
- ProbeHandler::SendProbeCallback &&rtt_probes_callback,
+ ProbeHandler::SendProbeCallback &&probe_callback,
DiscoveredRttCallback &&discovered_rtt_callback,
asio::io_service &io_service)
- : indexer_(indexer),
- rtt_probes_(std::make_shared<ProbeHandler>(std::move(rtt_probes_callback),
- io_service)),
+ : loss_history_(10), // log 10sec history
+ indexer_(indexer),
+ probe_handler_(std::make_shared<ProbeHandler>(std::move(probe_callback),
+ io_service)),
discovered_rtt_callback_(std::move(discovered_rtt_callback)) {
init_rtt_timer_ = std::make_unique<asio::steady_timer>(io_service);
- initParams();
}
RTCState::~RTCState() {}
@@ -55,9 +55,18 @@ void RTCState::initParams() {
highest_seq_received_in_order_ = 0;
last_seq_nacked_ = 0;
loss_rate_ = 0.0;
- avg_loss_rate_ = 0.0;
- max_loss_rate_ = 0.0;
+ avg_loss_rate_ = -1.0;
last_round_loss_rate_ = 0.0;
+
+ // loss rate per sec
+ lost_per_sec_ = 0;
+ total_expected_packets_ = 0;
+ per_sec_loss_rate_ = 0.0;
+
+ // residual losses counters
+ expected_packets_ = 0;
+ packets_sent_to_app_ = 0;
+ rounds_from_last_compute_ = 0;
residual_loss_rate_ = 0.0;
// fec counters
@@ -66,19 +75,22 @@ void RTCState::initParams() {
// bw counters
received_bytes_ = 0;
+ received_fec_bytes_ = 0;
+ recovered_bytes_with_fec_ = 0;
+
avg_packet_size_ = INIT_PACKET_SIZE;
production_rate_ = 0.0;
received_rate_ = 0.0;
+ fec_recovered_rate_ = 0.0;
// nack counter
- nack_on_last_round_ = false;
+ past_nack_on_last_round_ = false;
received_nacks_last_round_ = 0;
// packets counter
received_packets_last_round_ = 0;
received_data_last_round_ = 0;
received_data_from_cache_ = 0;
- data_from_cache_rate_ = 0;
sent_interests_last_round_ = 0;
sent_rtx_last_round_ = 0;
@@ -89,37 +101,37 @@ void RTCState::initParams() {
last_production_seq_ = 0;
producer_is_active_ = false;
- last_prod_update_ = 0;
+ last_prod_update_seq_ = 0;
// paths stats
path_table_.clear();
main_path_ = nullptr;
+ edge_path_ = nullptr;
- // packet received
- received_or_lost_packets_.clear();
+ // packet cache (not pending anymore)
+ packet_cache_.clear();
// pending interests
pending_interests_.clear();
- // skipped interest
+ // used to keep track of the skipped interest
last_interest_sent_ = 0;
- skipped_interests_.clear();
// init rtt
first_interest_sent_time_ = ~0;
first_interest_sent_seq_ = 0;
+ // start probing the producer
init_rtt_ = false;
- rtt_probes_->setProbes(INIT_RTT_PROBE_INTERVAL, INIT_RTT_PROBES);
- rtt_probes_->sendProbes();
+ probe_handler_->setSuffixRange(MIN_INIT_PROBE_SEQ, MAX_INIT_PROBE_SEQ);
+ probe_handler_->setProbes(INIT_RTT_PROBE_INTERVAL, INIT_RTT_PROBES);
+ probe_handler_->sendProbes();
setInitRttTimer(INIT_RTT_PROBE_RESTART);
}
// packet events
void RTCState::onSendNewInterest(const core::Name *interest_name) {
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint32_t seq = interest_name->getSuffix();
pending_interests_.insert(std::pair<uint32_t, uint64_t>(seq, now));
@@ -137,11 +149,12 @@ void RTCState::onSendNewInterest(const core::Name *interest_name) {
}
// TODO what happen in case of jumps?
- // look for skipped interests
- skipped_interests_.erase(seq); // remove seq if it is there
+ eraseFromPacketCache(
+ seq); // if we send this interest we don't know its state
for (uint32_t i = last_interest_sent_ + 1; i < seq; i++) {
if (indexer_->isFec(i)) {
- skipped_interests_.insert(i);
+ // only fec packets can be skipped
+ addToPacketCache(i, PacketState::SKIPPED);
}
}
@@ -155,6 +168,7 @@ void RTCState::onTimeout(uint32_t seq, bool lost) {
auto it = pending_interests_.find(seq);
if (it != pending_interests_.end()) {
pending_interests_.erase(it);
+ if (indexer_->isFec(seq)) pending_fec_pkt_--;
}
received_timeouts_++;
@@ -162,11 +176,14 @@ void RTCState::onTimeout(uint32_t seq, bool lost) {
}
void RTCState::onLossDetected(uint32_t seq) {
- if (!indexer_->isFec(seq)) {
- packets_lost_++;
- } else if (skipped_interests_.find(seq) == skipped_interests_.end() &&
- seq >= first_interest_sent_seq_) {
+ PacketState state = getPacketState(seq);
+
+ // if the packet is already marked with a state, do nothing
+ // to be considered lost the packet must be pending
+ if (state == PacketState::UNKNOWN &&
+ pending_interests_.find(seq) != pending_interests_.end()) {
packets_lost_++;
+ addToPacketCache(seq, PacketState::LOST);
}
}
@@ -178,38 +195,46 @@ void RTCState::onRetransmission(uint32_t seq) {
auto it = pending_interests_.find(seq);
if (it != pending_interests_.end()) {
pending_interests_.erase(it);
-#if 0
- packets_lost_++;
-#endif
+ if (indexer_->isFec(seq)) pending_fec_pkt_--;
}
sent_rtx_++;
sent_rtx_last_round_++;
}
+void RTCState::onPossibleLossWithNoRtx(uint32_t seq) {
+ // if fec is on or rtx is disable we don't need to do anything to recover a
+ // packet. however in both cases we need to remove possible missing packets
+ // from the window of pendinig interest in order to free space without wating
+ // for the timeout.
+ auto it = pending_interests_.find(seq);
+ if (it != pending_interests_.end()) {
+ pending_interests_.erase(it);
+ if (indexer_->isFec(seq)) pending_fec_pkt_--;
+ }
+}
+
void RTCState::onDataPacketReceived(const core::ContentObject &content_object,
bool compute_stats) {
uint32_t seq = content_object.getName().getSuffix();
+
if (compute_stats) {
updatePathStats(content_object, false);
received_data_last_round_++;
}
received_data_++;
+ packets_sent_to_app_++;
- struct data_packet_t *data_pkt =
- (struct data_packet_t *)content_object.getPayload()->data();
- uint64_t production_time = data_pkt->getTimestamp();
- if (last_prod_update_ < production_time) {
- last_prod_update_ = production_time;
- uint32_t production_rate = data_pkt->getProductionRate();
- production_rate_ = (double)production_rate;
+ core::ParamsRTC params = RTCState::getDataParams(content_object);
+
+ if (last_prod_update_seq_ < seq) {
+ last_prod_update_seq_ = seq;
+ production_rate_ = (double)params.prod_rate;
}
updatePacketSize(content_object);
- updateReceivedBytes(content_object);
+ updateReceivedBytes(content_object, false);
addRecvOrLost(seq, PacketState::RECEIVED);
- if (seq > highest_seq_received_) highest_seq_received_ = seq;
-
// the producer is responding
// it is generating valid data packets so we consider it active
producer_is_active_ = true;
@@ -219,9 +244,14 @@ void RTCState::onDataPacketReceived(const core::ContentObject &content_object,
void RTCState::onFecPacketReceived(const core::ContentObject &content_object) {
uint32_t seq = content_object.getName().getSuffix();
- updateReceivedBytes(content_object);
+ updateReceivedBytes(content_object, true);
+
+ PacketState state = getPacketState(seq);
+ if (state != PacketState::LOST) {
+ // increase only for not lost packets
+ received_fec_pkt_++;
+ }
addRecvOrLost(seq, PacketState::RECEIVED);
- received_fec_pkt_++;
// the producer is responding
// it is generating valid data packets so we consider it active
producer_is_active_ = true;
@@ -232,14 +262,12 @@ void RTCState::onNackPacketReceived(const core::ContentObject &nack,
uint32_t seq = nack.getName().getSuffix();
struct nack_packet_t *nack_pkt =
(struct nack_packet_t *)nack.getPayload()->data();
- uint64_t production_time = nack_pkt->getTimestamp();
- uint32_t production_seq = nack_pkt->getProductionSegement();
+ uint32_t production_seq = nack_pkt->getProductionSegment();
uint32_t production_rate = nack_pkt->getProductionRate();
if (TRANSPORT_EXPECT_FALSE(main_path_ == nullptr) ||
- last_prod_update_ < production_time) {
+ last_prod_update_seq_ < production_seq) {
// update production rate
- last_prod_update_ = production_time;
last_production_seq_ = production_seq;
production_rate_ = (double)production_rate;
}
@@ -247,7 +275,6 @@ void RTCState::onNackPacketReceived(const core::ContentObject &nack,
if (compute_stats) {
// this is not an RTX
updatePathStats(nack, true);
- nack_on_last_round_ = true;
}
// for statistics pourpose we log all nacks, also the one received for
@@ -255,83 +282,132 @@ void RTCState::onNackPacketReceived(const core::ContentObject &nack,
received_nacks_++;
received_nacks_last_round_++;
+ bool to_delete = false;
if (production_seq > seq) {
// old nack, seq is lost
// update last nacked
if (last_seq_nacked_ < seq) last_seq_nacked_ = seq;
DLOG_IF(INFO, VLOG_IS_ON(3))
<< "lost packet " << seq << " beacuse of a past nack";
+ if (compute_stats) past_nack_on_last_round_ = true;
onPacketLost(seq);
} else if (seq > production_seq) {
// future nack
// remove the nack from the pending interest map
// (the packet is not received/lost yet)
- if (indexer_->isFec(seq)) pending_fec_pkt_--;
- pending_interests_.erase(seq);
+ to_delete = true;
} else {
// this should be a quite rear event. simply remove the
// packet from the pending interest list
- pending_interests_.erase(seq);
+ to_delete = true;
}
- // the producer is responding
- // we consider it active only if the production rate is not 0
- // or the production sequence number is not 1
- if (production_rate_ != 0 || production_seq != 1) {
- producer_is_active_ = true;
+ if (to_delete) {
+ auto it = pending_interests_.find(seq);
+ if (it != pending_interests_.end()) {
+ pending_interests_.erase(it);
+ if (indexer_->isFec(seq)) pending_fec_pkt_--;
+ }
}
received_packets_last_round_++;
}
void RTCState::onPacketLost(uint32_t seq) {
-#if 0
- DLOG_IF(INFO, VLOG_IS_ON(3)) << "packet " << seq << " is lost";
- auto it = pending_interests_.find(seq);
- if (it != pending_interests_.end()) {
- // this packet was never retransmitted so it does
- // not appear in the loss count
- packets_lost_++;
- }
-#endif
if (!indexer_->isFec(seq)) {
- definitely_lost_pkt_++;
- DLOG_IF(INFO, VLOG_IS_ON(4)) << "packet " << seq << " is lost";
+ PacketState state = getPacketState(seq);
+ if (state == PacketState::LOST ||
+ (state == PacketState::UNKNOWN &&
+ pending_interests_.find(seq) != pending_interests_.end())) {
+ definitely_lost_pkt_++;
+ DLOG_IF(INFO, VLOG_IS_ON(4)) << "packet " << seq << " is lost";
+ }
}
- addRecvOrLost(seq, PacketState::LOST);
+
+ addRecvOrLost(seq, PacketState::DEFINITELY_LOST);
}
-void RTCState::onPacketRecoveredRtx(uint32_t seq) {
- losses_recovered_++;
+void RTCState::onPacketRecoveredRtx(const core::ContentObject &content_object,
+ uint64_t rtt) {
+ uint32_t seq = content_object.getName().getSuffix();
+ packets_sent_to_app_++;
+
+ // increase the recovered packet counter only if the packet was marked as LOST
+ // before.
+ PacketState state = getPacketState(seq);
+ if (state == PacketState::LOST) losses_recovered_++;
+
addRecvOrLost(seq, PacketState::RECEIVED);
+ updateReceivedBytes(content_object, false);
+
+ if (rtt == 0) return; // nothing to do
+
+ uint32_t path_label = content_object.getPathLabel();
+ auto path_it = path_table_.find(path_label);
+ if (path_it == path_table_.end()) {
+ // this is a new path and it must be a cache
+ std::shared_ptr<RTCDataPath> newPath =
+ std::make_shared<RTCDataPath>(path_label);
+ auto ret = path_table_.insert(
+ std::pair<uint32_t, std::shared_ptr<RTCDataPath>>(path_label, newPath));
+ path_it = ret.first;
+ }
+
+ auto path = path_it->second;
+ if (path->pathToProducer())
+ return; // this packet is coming from a producer
+ // even if we sent an RTX. this may happen
+ // for RTX that are sent too fast or in
+ // case of multipath
+
+ path->insertRttSample(utils::SteadyTime::Milliseconds(rtt), true);
}
-void RTCState::onPacketRecoveredFec(uint32_t seq) {
+void RTCState::onFecPacketRecoveredRtx(
+ const core::ContentObject &content_object) {
+ // This is the same as onPacketRecoveredRtx, but in this is case the
+ // pkt is also a FEC pkt, the addRecvOrLost will be called afterwards
losses_recovered_++;
+ updateReceivedBytes(content_object, true);
+}
+
+void RTCState::onPacketRecoveredFec(uint32_t seq, uint32_t size) {
+ losses_recovered_++;
+ packets_sent_to_app_++;
+ recovered_bytes_with_fec_ += size;
+
+ // adding header to the count
+ recovered_bytes_with_fec_ += 60; // XXX get header size some where
+
+ // the packet could be not marked as lost yet. onLossDetected checks if add in
+ // the packet in the lost count or not
+ onLossDetected(seq);
+
addRecvOrLost(seq, PacketState::RECEIVED);
}
bool RTCState::onProbePacketReceived(const core::ContentObject &probe) {
uint32_t seq = probe.getName().getSuffix();
- uint64_t rtt;
+ core::ParamsRTC params = RTCState::getProbeParams(probe);
- rtt = rtt_probes_->getRtt(seq);
+ bool is_valid = true;
+ uint32_t max = UINT32_MAX;
+ if (params.prod_rate == max) is_valid = false;
+ uint64_t rtt;
+ rtt = probe_handler_->getRtt(seq, is_valid);
if (rtt == 0) return false; // this is not a valid probe
- // like for data and nacks update the path stats. Here the RTT is computed
- // by the probe handler. Both probes for rtt and bw are good to esimate
- // info on the path
- uint32_t path_label = probe.getPathLabel();
+ if (!is_valid) return false; // not a valid probe
- auto path_it = path_table_.find(path_label);
+ // if we are here the producer is active
+ producer_is_active_ = true;
- // update production rate and last_seq_nacked like in case of a nack
- struct nack_packet_t *probe_pkt =
- (struct nack_packet_t *)probe.getPayload()->data();
- uint64_t sender_timestamp = probe_pkt->getTimestamp();
- uint32_t production_seq = probe_pkt->getProductionSegement();
- uint32_t production_rate = probe_pkt->getProductionRate();
+ // Like for data and nacks update the path stats. Here the RTT is computed
+ // by the probe handler. Both probes for rtt and bw are good to estimate
+ // info on the path.
+ uint32_t path_label = probe.getPathLabel();
+ auto path_it = path_table_.find(path_label);
if (path_it == path_table_.end()) {
// found a new path
@@ -344,27 +420,17 @@ bool RTCState::onProbePacketReceived(const core::ContentObject &probe) {
auto path = path_it->second;
- path->insertRttSample(rtt);
+ path->insertRttSample(utils::SteadyTime::Milliseconds(rtt), true);
path->receivedNack();
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ uint64_t now = utils::SteadyTime::nowMs().count();
- int64_t OWD = now - sender_timestamp;
+ int64_t OWD = now - params.timestamp;
path->insertOwdSample(OWD);
- if (last_prod_update_ < sender_timestamp) {
- last_production_seq_ = production_seq;
- last_prod_update_ = sender_timestamp;
- production_rate_ = (double)production_rate;
- }
-
- // the producer is responding
- // we consider it active only if the production rate is not 0
- // or the production sequence numner is not 1
- if (production_rate_ != 0 || production_seq != 1) {
- producer_is_active_ = true;
+ if (last_prod_update_seq_ < params.prod_seg) {
+ last_production_seq_ = params.prod_seg;
+ production_rate_ = (double)params.prod_rate;
}
// check for init RTT. if received_probes_ is equal to 0 schedule a timer to
@@ -375,7 +441,7 @@ bool RTCState::onProbePacketReceived(const core::ContentObject &probe) {
if (!init_rtt_ && received_probes_ <= INIT_RTT_PROBES) {
if (received_probes_ == 1) {
// we got the first probe, wait at most INIT_RTT_PROBE_WAIT sec for the
- // others
+ // others.
main_path_ = path;
setInitRttTimer(INIT_RTT_PROBE_WAIT);
}
@@ -393,11 +459,21 @@ bool RTCState::onProbePacketReceived(const core::ContentObject &probe) {
return true;
}
-void RTCState::onNewRound(double round_len, bool in_sync) {
- // XXX
- // here we take into account only the single path case so we assume that we
- // don't use two paths in parellel for this single flow
+void RTCState::onJumpForward(uint32_t next_seq) {
+ for (uint32_t seq = highest_seq_received_in_order_ + 1; seq < next_seq;
+ seq++) {
+ PacketState packet_state = getPacketState(seq);
+ if (packet_state != PacketState::RECEIVED &&
+ packet_state != PacketState::DEFINITELY_LOST) {
+ // here we considere the packet as definitely lost whitout increase the
+ // lost packet counter because this loss is not due to the network
+ // condition but the transport wants to skip the packet
+ onPacketLost(seq);
+ }
+ }
+}
+void RTCState::onNewRound(double round_len, bool in_sync) {
if (path_table_.empty()) return;
double bytes_per_sec =
@@ -407,33 +483,65 @@ void RTCState::onNewRound(double round_len, bool in_sync) {
else
received_rate_ = (received_rate_ * MOVING_AVG_ALPHA) +
((1 - MOVING_AVG_ALPHA) * bytes_per_sec);
+ double fec_bytes_per_sec =
+ ((double)received_fec_bytes_ * (MILLI_IN_A_SEC / round_len));
+
+ if (fec_received_rate_ == 0)
+ fec_received_rate_ = fec_bytes_per_sec;
+ else
+ fec_received_rate_ = (fec_received_rate_ * 0.8) + (0.2 * fec_bytes_per_sec);
- // search for an active path. There should be only one active path (meaning a
- // path that leads to the producer socket -no cache- and from which we are
- // currently getting data packets) at any time. However it may happen that
- // there are mulitple active paths in case of mobility (the old path will
- // remain active for a short ammount of time). The main path is selected as
- // the active path from where the consumer received the latest data packet
+ double fec_recovered_bytes_per_sec =
+ ((double)recovered_bytes_with_fec_ * (MILLI_IN_A_SEC / round_len));
- uint64_t last_packet_ts = 0;
+ if (fec_recovered_rate_ == 0)
+ fec_recovered_rate_ = fec_recovered_bytes_per_sec;
+ else
+ fec_recovered_rate_ =
+ (fec_recovered_rate_ * 0.8) + (0.2 * fec_recovered_bytes_per_sec);
+
+ // search for an active path. Is it possible to have multiple path that are
+ // used at the same time. We use as reference path the one from where we gets
+ // more packets. This means that the path should have better lantecy or less
+ // channel losses
+
+ uint32_t last_round_packets = 0;
+ uint64_t min_edge_rtt = UINT_MAX;
+ std::shared_ptr<RTCDataPath> old_main_path = main_path_;
main_path_ = nullptr;
+ edge_path_ = nullptr;
for (auto it = path_table_.begin(); it != path_table_.end(); it++) {
- it->second->roundEnd();
- if (it->second->isActive()) {
- uint64_t ts = it->second->getLastPacketTS();
- if (ts > last_packet_ts) {
- last_packet_ts = ts;
+ if (it->second->isValidProducer()) {
+ uint32_t pkt = it->second->getPacketsLastRound();
+ if (pkt > last_round_packets) {
+ last_round_packets = pkt;
main_path_ = it->second;
}
+ } else if (it->second->isActive() && !it->second->pathToProducer()) {
+ // this is a path to a cache from where we are receiving content
+ if (it->second->getMinRtt() < min_edge_rtt) {
+ min_edge_rtt = it->second->getMinRtt();
+ edge_path_ = it->second;
+ }
}
+ it->second->roundEnd();
}
- // if (in_sync) updateLossRate();
- updateLossRate();
+ if (main_path_ == nullptr) main_path_ = old_main_path;
+ if (edge_path_ == nullptr) edge_path_ = main_path_;
+ if (edge_path_->getMinRtt() >= main_path_->getMinRtt())
+ edge_path_ = main_path_;
+
+ // in case we get a new main path we reset the stats of the old one. this is
+ // beacuse, in case we need to switch back we don't what to take decisions on
+ // old stats that may be outdated.
+ if (main_path_ != old_main_path) old_main_path->clearRtt();
+
+ updateLossRate(in_sync);
// handle nacks
- if (!nack_on_last_round_ && received_bytes_ > 0) {
+ if (!past_nack_on_last_round_ && received_bytes_ > 0) {
rounds_without_nacks_++;
} else {
rounds_without_nacks_ = 0;
@@ -450,22 +558,16 @@ void RTCState::onNewRound(double round_len, bool in_sync) {
}
}
- // compute cache/producer ratio
- if (received_data_last_round_ != 0) {
- double new_rate =
- (double)received_data_from_cache_ / (double)received_data_last_round_;
- data_from_cache_rate_ = data_from_cache_rate_ * MOVING_AVG_ALPHA +
- (new_rate * (1 - MOVING_AVG_ALPHA));
- }
-
// reset counters
received_bytes_ = 0;
+ received_fec_bytes_ = 0;
+ recovered_bytes_with_fec_ = 0;
packets_lost_ = 0;
definitely_lost_pkt_ = 0;
losses_recovered_ = 0;
first_seq_in_round_ = highest_seq_received_;
- nack_on_last_round_ = false;
+ past_nack_on_last_round_ = false;
received_nacks_last_round_ = 0;
received_packets_last_round_ = 0;
@@ -479,9 +581,15 @@ void RTCState::onNewRound(double round_len, bool in_sync) {
rounds_++;
}
-void RTCState::updateReceivedBytes(const core::ContentObject &content_object) {
- received_bytes_ +=
- (uint32_t)(content_object.headerSize() + content_object.payloadSize());
+void RTCState::updateReceivedBytes(const core::ContentObject &content_object,
+ bool isFec) {
+ if (isFec) {
+ received_fec_bytes_ +=
+ (uint32_t)(content_object.headerSize() + content_object.payloadSize());
+ } else {
+ received_bytes_ +=
+ (uint32_t)(content_object.headerSize() + content_object.payloadSize());
+ }
}
void RTCState::updatePacketSize(const core::ContentObject &content_object) {
@@ -516,20 +624,16 @@ void RTCState::updatePathStats(const core::ContentObject &content_object,
// it means that we are processing an interest
// that is not pending
- uint64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
+ uint64_t now = utils::SteadyTime::nowMs().count();
uint64_t RTT = now - interest_sent_time;
- path->insertRttSample(RTT);
+ path->insertRttSample(utils::SteadyTime::Milliseconds(RTT), false);
// compute OWD (the first part of the nack and data packet header are the
// same, so we cast to data data packet)
- struct data_packet_t *packet =
- (struct data_packet_t *)content_object.getPayload()->data();
- uint64_t sender_timestamp = packet->getTimestamp();
- int64_t OWD = now - sender_timestamp;
+ core::ParamsRTC params = RTCState::getDataParams(content_object);
+ int64_t OWD = now - params.timestamp;
path->insertOwdSample(OWD);
// compute IAT or set path to producer
@@ -543,59 +647,110 @@ void RTCState::updatePathStats(const core::ContentObject &content_object,
}
}
-void RTCState::updateLossRate() {
+void RTCState::updateLossRate(bool in_sync) {
last_round_loss_rate_ = loss_rate_;
loss_rate_ = 0.0;
- residual_loss_rate_ = 0.0;
uint32_t number_theorically_received_packets_ =
highest_seq_received_ - first_seq_in_round_;
- // in this case no new packet was recevied after the previuos round, avoid
- // division by 0
- if (number_theorically_received_packets_ == 0) return;
-
// XXX this may be quite inefficient if the rate is high
// maybe is better to iterate over the set?
- for (uint32_t i = first_seq_in_round_; i < highest_seq_received_; i++) {
- auto it = skipped_interests_.find(i);
- if (it != skipped_interests_.end()) {
+
+ uint32_t fec_packets = 0;
+ for (uint32_t i = (first_seq_in_round_ + 1); i < highest_seq_received_; i++) {
+ PacketState state = getPacketState(i);
+ if (state == PacketState::SKIPPED) {
if (number_theorically_received_packets_ > 0)
number_theorically_received_packets_--;
- skipped_interests_.erase(it);
}
+ if (indexer_->isFec(i)) fec_packets++;
}
+ if (indexer_->isFec(highest_seq_received_)) fec_packets++;
- loss_rate_ = (double)((double)(packets_lost_) /
- (double)number_theorically_received_packets_);
+ // in this case no new packet was received after the previous round, avoid
+ // division by 0
+ if (number_theorically_received_packets_ == 0 && packets_lost_ == 0) return;
- if (rounds_ % 15 == 0) max_loss_rate_ = 0; // reset every 3 sec
- if (loss_rate_ > max_loss_rate_) max_loss_rate_ = loss_rate_;
+ if (number_theorically_received_packets_ != 0)
+ loss_rate_ = (double)((double)(packets_lost_) /
+ (double)number_theorically_received_packets_);
+ else
+ // we didn't receive anything except NACKs that triggered losses
+ loss_rate_ = 1.0;
- if (avg_loss_rate_ == 0)
+ if (avg_loss_rate_ == -1.0)
avg_loss_rate_ = loss_rate_;
else
avg_loss_rate_ =
avg_loss_rate_ * MOVING_AVG_ALPHA + loss_rate_ * (1 - MOVING_AVG_ALPHA);
- residual_loss_rate_ = (double)((double)(packets_lost_ - losses_recovered_) /
- (double)number_theorically_received_packets_);
+ // update counters for loss rate per second
+ total_expected_packets_ += number_theorically_received_packets_;
+ lost_per_sec_ += packets_lost_;
+
+ if (in_sync) {
+ // update counters for residual losses
+ // fec packets are not sent to the app so we don't want to count them here
+ expected_packets_ +=
+ ((highest_seq_received_ - first_seq_in_round_) - fec_packets);
+ } else {
+ expected_packets_ = 0;
+ packets_sent_to_app_ = 0;
+ }
+
+ if (rounds_from_last_compute_ >= (MILLI_IN_A_SEC / ROUND_LEN)) {
+ // compute loss rate per second
+ if (lost_per_sec_ > total_expected_packets_)
+ lost_per_sec_ = total_expected_packets_;
+
+ if (total_expected_packets_ == 0)
+ per_sec_loss_rate_ = 0;
+ else
+ per_sec_loss_rate_ =
+ (double)((double)(lost_per_sec_) / (double)total_expected_packets_);
+
+ loss_history_.pushBack(per_sec_loss_rate_);
+
+ if (in_sync && expected_packets_ != 0) {
+ // compute residual loss rate
+ if (packets_sent_to_app_ > expected_packets_) {
+ // this may happen if we get packet from the prev bin that get recovered
+ // on the current one
+ packets_sent_to_app_ = expected_packets_;
+ }
+
+ residual_loss_rate_ =
+ 1.0 - ((double)packets_sent_to_app_ / (double)expected_packets_);
+ if (residual_loss_rate_ < 0.0) residual_loss_rate_ = 0.0;
+ }
- if (residual_loss_rate_ < 0) residual_loss_rate_ = 0;
+ lost_per_sec_ = 0;
+ total_expected_packets_ = 0;
+ expected_packets_ = 0;
+ packets_sent_to_app_ = 0;
+ rounds_from_last_compute_ = 0;
+ }
+
+ rounds_from_last_compute_++;
+}
+
+void RTCState::dataToBeReceived(uint32_t seq) {
+ addToPacketCache(seq, PacketState::TO_BE_RECEIVED);
+}
+
+void RTCState::updateHighestSeqReceived(uint32_t seq) {
+ if (seq > highest_seq_received_) highest_seq_received_ = seq;
}
void RTCState::addRecvOrLost(uint32_t seq, PacketState state) {
- if (indexer_->isFec(seq)) {
- pending_fec_pkt_--;
+ auto it = pending_interests_.find(seq);
+ if (it != pending_interests_.end()) {
+ pending_interests_.erase(it);
+ if (indexer_->isFec(seq)) pending_fec_pkt_--;
}
- pending_interests_.erase(seq);
- if (received_or_lost_packets_.size() >= MAX_CACHED_PACKETS) {
- received_or_lost_packets_.erase(received_or_lost_packets_.begin());
- }
- // notice that it may happen that a packet that we consider lost arrives after
- // some time, in this case we simply overwrite the packet state.
- received_or_lost_packets_[seq] = state;
+ addToPacketCache(seq, state);
// keep track of the last packet received/lost
// without holes.
@@ -608,16 +763,27 @@ void RTCState::addRecvOrLost(uint32_t seq, PacketState state) {
} else if (seq <= highest_seq_received_in_order_) {
// here we do nothing
} else if (seq > highest_seq_received_in_order_) {
- // 1) there is a gap in the sequence so we do not update largest_in_seq_
- // 2) all the packets from largest_in_seq_ to seq are in
- // received_or_lost_packets_ an we upate largest_in_seq_
- // or are FEC packets
+ // 1) there is a gap in the sequence so we do not update
+ // highest_seq_received_in_order_
+ // 2) all the packets from highest_seq_received_in_order_ to seq are
+ // received or lost or are fec packetis. In this case we increase
+ // highest_seq_received_in_order_ until we find an hole in the sequence
for (uint32_t i = highest_seq_received_in_order_ + 1; i <= seq; i++) {
- if (received_or_lost_packets_.find(i) ==
- received_or_lost_packets_.end() &&
- !indexer_->isFec(i)) {
- break;
+ PacketState state = getPacketState(i);
+ if ((state == PacketState::UNKNOWN || state == PacketState::LOST)) {
+ if (indexer_->isFec(i)) {
+ // this is a fec packet and we don't care to receive it
+ // however we may need to increse the number or lost packets
+ // XXX: in case we want to use rtx to recover fec packets,
+ // this may prevent to detect a packet loss and no rtx will be sent
+ if (TRANSPORT_EXPECT_TRUE(i >= first_interest_sent_seq_)) {
+ onLossDetected(i);
+ }
+ } else {
+ // this is a data packet and we need to get it
+ break;
+ }
}
// this packet is in order so we can update the
// highest_seq_received_in_order_
@@ -629,36 +795,104 @@ void RTCState::addRecvOrLost(uint32_t seq, PacketState state) {
void RTCState::setInitRttTimer(uint32_t wait) {
init_rtt_timer_->cancel();
init_rtt_timer_->expires_from_now(std::chrono::milliseconds(wait));
- init_rtt_timer_->async_wait([this](std::error_code ec) {
+
+ std::weak_ptr<RTCState> self = shared_from_this();
+ init_rtt_timer_->async_wait([self](const std::error_code &ec) {
if (ec) return;
- checkInitRttTimer();
+
+ if (auto ptr = self.lock()) {
+ ptr->checkInitRttTimer();
+ }
});
}
void RTCState::checkInitRttTimer() {
- if (received_probes_ < INIT_RTT_MIN_PROBES_TO_RECV) {
- // we didn't received enough probes, restart
+ if (received_probes_ < INIT_RTT_MIN_PROBES_TO_RECV ||
+ probe_handler_->getProbeLossRate() == 1.0) {
+ // we didn't received enough probes or they were not valid, restart
received_probes_ = 0;
- rtt_probes_->setProbes(INIT_RTT_PROBE_INTERVAL, INIT_RTT_PROBES);
- rtt_probes_->sendProbes();
+ probe_handler_->setSuffixRange(MIN_INIT_PROBE_SEQ, MAX_INIT_PROBE_SEQ);
+ probe_handler_->setProbes(INIT_RTT_PROBE_INTERVAL, INIT_RTT_PROBES);
+ probe_handler_->sendProbes();
setInitRttTimer(INIT_RTT_PROBE_RESTART);
return;
}
+
init_rtt_ = true;
main_path_->roundEnd();
- rtt_probes_->setProbes(RTT_PROBE_INTERVAL, 0);
- rtt_probes_->sendProbes();
+ loss_history_.pushBack(probe_handler_->getProbeLossRate());
+
+ probe_handler_->setSuffixRange(MIN_RTT_PROBE_SEQ, MAX_RTT_PROBE_SEQ);
+ probe_handler_->setProbes(RTT_PROBE_INTERVAL, 0);
+ probe_handler_->sendProbes();
// init last_seq_nacked_. skip packets that may come from the cache
double prod_rate = getProducerRate();
- double rtt = (double)getRTT() / MILLI_IN_A_SEC;
+ double rtt = (double)getMinRTT() / MILLI_IN_A_SEC;
double packet_size = getAveragePacketSize();
- uint32_t pkt_in_rtt_ = std::floor(((prod_rate / packet_size) * rtt) * 0.8);
+ uint32_t pkt_in_rtt_ = std::floor(((prod_rate / packet_size) * rtt));
last_seq_nacked_ = last_production_seq_ + pkt_in_rtt_;
discovered_rtt_callback_();
}
+core::ParamsRTC RTCState::getProbeParams(const core::ContentObject &probe) {
+ uint32_t seq = probe.getName().getSuffix();
+ core::ParamsRTC params;
+
+ switch (ProbeHandler::getProbeType(seq)) {
+ case ProbeType::INIT: {
+ core::ContentObjectManifest manifest(
+ const_cast<core::ContentObject &>(probe).shared_from_this());
+ manifest.decode();
+ params = manifest.getParamsRTC();
+ break;
+ }
+ case ProbeType::RTT: {
+ struct nack_packet_t *probe_pkt =
+ (struct nack_packet_t *)probe.getPayload()->data();
+ params = core::ParamsRTC{
+ .timestamp = probe_pkt->getTimestamp(),
+ .prod_rate = probe_pkt->getProductionRate(),
+ .prod_seg = probe_pkt->getProductionSegment(),
+ };
+ break;
+ }
+ default:
+ break;
+ }
+
+ return params;
+}
+
+core::ParamsRTC RTCState::getDataParams(const core::ContentObject &data) {
+ core::ParamsRTC params;
+
+ switch (data.getPayloadType()) {
+ case core::PayloadType::DATA: {
+ struct data_packet_t *data_pkt =
+ (struct data_packet_t *)data.getPayload()->data();
+ params = core::ParamsRTC{
+ .timestamp = data_pkt->getTimestamp(),
+ .prod_rate = data_pkt->getProductionRate(),
+ .prod_seg = data.getName().getSuffix(),
+ };
+ break;
+ }
+ case core::PayloadType::MANIFEST: {
+ core::ContentObjectManifest manifest(
+ const_cast<core::ContentObject &>(data).shared_from_this());
+ manifest.decode();
+ params = manifest.getParamsRTC();
+ break;
+ }
+ default:
+ break;
+ }
+
+ return params;
+}
+
} // namespace rtc
} // namespace protocol
diff --git a/libtransport/src/protocols/rtc/rtc_state.h b/libtransport/src/protocols/rtc/rtc_state.h
index 729ba7a1b..ac3cc621f 100644
--- a/libtransport/src/protocols/rtc/rtc_state.h
+++ b/libtransport/src/protocols/rtc/rtc_state.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -14,13 +14,16 @@
*/
#pragma once
+#include <core/facade.h>
#include <hicn/transport/config.h>
#include <hicn/transport/core/asio_wrapper.h>
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/name.h>
+#include <hicn/transport/utils/rtc_quality_score.h>
#include <protocols/indexer.h>
#include <protocols/rtc/probe_handler.h>
#include <protocols/rtc/rtc_data_path.h>
+#include <utils/max_filter.h>
#include <map>
#include <set>
@@ -31,34 +34,62 @@ namespace protocol {
namespace rtc {
-enum class PacketState : uint8_t { RECEIVED, LOST, UNKNOWN };
+// packet state
+// RECEIVED: the packet was already received
+// LOST: the packet is marked as lost but can be recovered
+// DEFINITELY_LOST: the packet is lost and cannot be recovered
+// TO_BE_RECEIVED: when a packet is received is sent to the FEC decoder. the fec
+// decoder may decide to send the packet directly to the app. to avoid
+// duplicated the packet is marked with this state
+// SKIPPED: an interest that was not sent, only for FEC packets
+// UNKNOWN: unknown state
+enum class PacketState : uint8_t {
+ RECEIVED,
+ TO_BE_RECEIVED,
+ LOST,
+ DEFINITELY_LOST,
+ SKIPPED,
+ UNKNOWN
+};
+
+class RTCState : public std::enable_shared_from_this<RTCState> {
+ using PendingInterestsMap = std::map<uint32_t, uint64_t>;
+
+ private:
+ const double MAX_CACHED_PACKETS = 8192; // XXX this value may be too small
+ // for high rate apps
-class RTCState : std::enable_shared_from_this<RTCState> {
public:
using DiscoveredRttCallback = std::function<void()>;
public:
- RTCState(Indexer *indexer,
- ProbeHandler::SendProbeCallback &&rtt_probes_callback,
+ RTCState(Indexer *indexer, ProbeHandler::SendProbeCallback &&probe_callback,
DiscoveredRttCallback &&discovered_rtt_callback,
asio::io_service &io_service);
~RTCState();
+ // initialization
+ void initParams();
+
// packet events
void onSendNewInterest(const core::Name *interest_name);
void onTimeout(uint32_t seq, bool lost);
void onLossDetected(uint32_t seq);
void onRetransmission(uint32_t seq);
+ void onPossibleLossWithNoRtx(uint32_t seq);
void onDataPacketReceived(const core::ContentObject &content_object,
bool compute_stats);
void onFecPacketReceived(const core::ContentObject &content_object);
void onNackPacketReceived(const core::ContentObject &nack,
bool compute_stats);
void onPacketLost(uint32_t seq);
- void onPacketRecoveredRtx(uint32_t seq);
- void onPacketRecoveredFec(uint32_t seq);
+ void onPacketRecoveredRtx(const core::ContentObject &content_object,
+ uint64_t rtt);
+ void onFecPacketRecoveredRtx(const core::ContentObject &content_object);
+ void onPacketRecoveredFec(uint32_t seq, uint32_t size);
bool onProbePacketReceived(const core::ContentObject &probe);
+ void onJumpForward(uint32_t next_seq);
// protocol state
void onNewRound(double round_len, bool in_sync);
@@ -72,10 +103,26 @@ class RTCState : std::enable_shared_from_this<RTCState> {
// delay metrics
bool isRttDiscovered() const { return init_rtt_; }
- uint64_t getRTT() const {
+ uint64_t getMinRTT() const {
if (mainPathIsValid()) return main_path_->getMinRtt();
return 0;
}
+
+ uint64_t getAvgRTT() const {
+ if (mainPathIsValid()) return main_path_->getAvgRtt();
+ return 0;
+ }
+
+ uint64_t getMaxRTT() const {
+ if (mainPathIsValid()) return main_path_->getMaxRtt();
+ return 0;
+ }
+
+ uint64_t getEdgeRtt() const {
+ if (edge_path_ != nullptr) return edge_path_->getMinRtt();
+ return 0;
+ }
+
void resetRttStats() {
if (mainPathIsValid()) main_path_->clearRtt();
}
@@ -98,6 +145,7 @@ class RTCState : std::enable_shared_from_this<RTCState> {
uint64_t getInterestSentTime(uint32_t seq) {
auto it = pending_interests_.find(seq);
if (it != pending_interests_.end()) return it->second;
+
return 0;
}
@@ -107,19 +155,24 @@ class RTCState : std::enable_shared_from_this<RTCState> {
}
uint32_t getPendingInterestNumber() const {
- return pending_interests_.size();
+ return (uint32_t)pending_interests_.size();
}
- PacketState isReceivedOrLost(uint32_t seq) {
- auto it = received_or_lost_packets_.find(seq);
- if (it != received_or_lost_packets_.end()) return it->second;
+ PacketState getPacketState(uint32_t seq) {
+ auto it = packet_cache_.find(seq);
+ if (it != packet_cache_.end()) return it->second;
return PacketState::UNKNOWN;
}
// loss rate
- double getLossRate() const { return loss_rate_; }
+ double getPerRoundLossRate() const { return loss_rate_; }
+ double getPerSecondLossRate() const { return per_sec_loss_rate_; }
double getAvgLossRate() const { return avg_loss_rate_; }
- double getMaxLossRate() const { return max_loss_rate_; }
+ double getMaxLossRate() const {
+ if (loss_history_.size() != 0) return loss_history_.begin();
+ return 0;
+ }
+
double getLastRoundLossRate() const { return last_round_loss_rate_; }
double getResidualLossRate() const { return residual_loss_rate_; }
@@ -140,9 +193,14 @@ class RTCState : std::enable_shared_from_this<RTCState> {
// generic stats
uint32_t getReceivedBytesInRound() const { return received_bytes_; }
+ uint32_t getReceivedFecBytesInRound() const { return received_fec_bytes_; }
+ uint32_t getRecoveredFecBytesInRound() const {
+ return recovered_bytes_with_fec_;
+ }
uint32_t getReceivedNacksInRound() const {
return received_nacks_last_round_;
}
+ uint32_t getReceivedDataInRound() const { return received_data_last_round_; }
uint32_t getSentInterestInRound() const { return sent_interests_last_round_; }
uint32_t getSentRtxInRound() const { return sent_rtx_last_round_; }
@@ -150,6 +208,9 @@ class RTCState : std::enable_shared_from_this<RTCState> {
double getAvailableBw() const { return 0.0; }; // TODO
double getProducerRate() const { return production_rate_; }
double getReceivedRate() const { return received_rate_; }
+ double getReceivedFecRate() const { return fec_received_rate_; }
+ double getRecoveredFecRate() const { return fec_recovered_rate_; }
+
double getAveragePacketSize() const { return avg_packet_size_; }
// nacks
@@ -160,24 +221,57 @@ class RTCState : std::enable_shared_from_this<RTCState> {
bool isProducerActive() const { return producer_is_active_; }
// packets from cache
- double getPacketFromCacheRatio() const { return data_from_cache_rate_; }
+ // this should be called at the end of a round beacuse otherwise we may have
+ // not enough packets to get a good stat
+ double getPacketFromCacheRatio() const {
+ if (received_data_last_round_ == 0) return 0;
+ return (double)received_data_from_cache_ /
+ (double)received_data_last_round_;
+ }
- std::map<uint32_t, uint64_t>::iterator getPendingInterestsMapBegin() {
+ PendingInterestsMap::iterator getPendingInterestsMapBegin() {
return pending_interests_.begin();
}
- std::map<uint32_t, uint64_t>::iterator getPendingInterestsMapEnd() {
+ PendingInterestsMap::iterator getPendingInterestsMapEnd() {
return pending_interests_.end();
}
+ // quality
+ uint8_t getQualityScore() {
+ uint8_t qs = quality_score_.getQualityScore(
+ getMaxRTT(), std::round(getResidualLossRate() * 100));
+ return qs;
+ }
+
+ // We received a data pkt that will be set to RECEIVED, but first we have to
+ // go through FEC. We do not want to consider this pkt as recovered, thus we
+ // set it as TO_BE_RECEIVED.
+ void dataToBeReceived(uint32_t seq);
+
+ void updateHighestSeqReceived(uint32_t seq);
+
+ // Extract RTC parameters from probes (init or RTT probes) and data packets.
+ static core::ParamsRTC getProbeParams(const core::ContentObject &probe);
+ static core::ParamsRTC getDataParams(const core::ContentObject &data);
+
private:
- void initParams();
+ void addToPacketCache(uint32_t seq, PacketState state) {
+ // this function adds or updates the current state
+ if (packet_cache_.size() >= MAX_CACHED_PACKETS) {
+ packet_cache_.erase(packet_cache_.begin());
+ }
+ packet_cache_[seq] = state;
+ }
+
+ void eraseFromPacketCache(uint32_t seq) { packet_cache_.erase(seq); }
// update stats
void updateState();
- void updateReceivedBytes(const core::ContentObject &content_object);
+ void updateReceivedBytes(const core::ContentObject &content_object,
+ bool isFec);
void updatePacketSize(const core::ContentObject &content_object);
void updatePathStats(const core::ContentObject &content_object, bool is_nack);
- void updateLossRate();
+ void updateLossRate(bool in_sycn);
void addRecvOrLost(uint32_t seq, PacketState state);
@@ -209,36 +303,51 @@ class RTCState : std::enable_shared_from_this<RTCState> {
uint32_t last_seq_nacked_; // segment for which we got an oldNack
double loss_rate_;
double avg_loss_rate_;
- double max_loss_rate_;
double last_round_loss_rate_;
+ utils::MaxFilter<double> loss_history_;
+
+ // per second loss rate
+ uint32_t lost_per_sec_;
+ uint32_t total_expected_packets_;
+ double per_sec_loss_rate_;
+
+ // conunters for residual losses
+ // residual losses are computed every second and are used
+ // as feedback to the upper levels (e.g application)
+ uint32_t expected_packets_;
+ uint32_t packets_sent_to_app_;
+ uint32_t rounds_from_last_compute_;
double residual_loss_rate_;
// bw counters
uint32_t received_bytes_;
+ uint32_t received_fec_bytes_;
+ uint32_t recovered_bytes_with_fec_;
double avg_packet_size_;
- double production_rate_; // rate communicated by the producer using nacks
- double received_rate_; // rate recevied by the consumer
-
- // nack counter
- // the bool takes tracks only about the valid nacks (no rtx) and it is used to
- // switch between the states. Instead received_nacks_last_round_ logs all the
- // nacks for statistics
- bool nack_on_last_round_;
+ double production_rate_; // rate communicated by the producer using nacks
+ double received_rate_; // rate recevied by the consumer (only data)
+ double fec_received_rate_; // fec rate recevied by the consumer
+ double fec_recovered_rate_; // rate recovered using fec
+
+ // nack counters
+ // the bool takes tracks only about the valid past nacks (no rtx) and it is
+ // used to switch between the states. Instead received_nacks_last_round_ logs
+ // all the nacks for statistics
+ bool past_nack_on_last_round_;
uint32_t received_nacks_last_round_;
- // packets counter
+ // packets counters
uint32_t received_packets_last_round_;
uint32_t received_data_last_round_;
uint32_t received_data_from_cache_;
- double data_from_cache_rate_;
uint32_t sent_interests_last_round_;
uint32_t sent_rtx_last_round_;
- // fec counter
+ // fec counters
uint32_t received_fec_pkt_;
uint32_t pending_fec_pkt_;
- // round conunters
+ // round counters
uint32_t rounds_;
uint32_t rounds_without_nacks_;
uint32_t rounds_without_packets_;
@@ -250,34 +359,46 @@ class RTCState : std::enable_shared_from_this<RTCState> {
// producer state
bool
producer_is_active_; // the prodcuer is active if we receive some packets
- uint32_t
- last_production_seq_; // last production seq received by the producer
- uint64_t last_prod_update_; // timestamp of the last packets used to update
- // stats from the producer
+ uint32_t last_production_seq_; // last production seq received by the
+ // producer used to init the sync protcol
+ uint32_t last_prod_update_seq_; // seq number of the last packet used to
+ // update the update from the producer.
+ // assumption: the highest seq number carries
+ // the most up to date info. in case of
+ // probes we look at the produced seq number
// paths stats
std::unordered_map<uint32_t, std::shared_ptr<RTCDataPath>> path_table_;
- std::shared_ptr<RTCDataPath> main_path_;
+ std::shared_ptr<RTCDataPath> main_path_; // this is the path that connects
+ // the consumer to the producer. in
+ // case of multipath the trasnport
+ // uses the most active path
+ std::shared_ptr<RTCDataPath> edge_path_; // path to the closest cache if it
+ // exists
// packet received
// cache where to store info about the last MAX_CACHED_PACKETS
- std::map<uint32_t, PacketState> received_or_lost_packets_;
+ // these are packets that are received or lost or definitely lost and are not
+ // anymore in the pending intetest list
+ std::map<uint32_t, PacketState> packet_cache_;
// pending interests
- std::map<uint32_t, uint64_t> pending_interests_;
+ PendingInterestsMap pending_interests_;
// indexer
Indexer *indexer_;
- // skipped interests
+ // used to keep track of the skipped interests
uint32_t last_interest_sent_;
- std::unordered_set<uint32_t> skipped_interests_;
// probes
- std::shared_ptr<ProbeHandler> rtt_probes_;
+ std::shared_ptr<ProbeHandler> probe_handler_;
bool init_rtt_;
std::unique_ptr<asio::steady_timer> init_rtt_timer_;
+ // quality score
+ RTCQualityScore quality_score_;
+
// callbacks
DiscoveredRttCallback discovered_rtt_callback_;
};
diff --git a/libtransport/src/protocols/rtc/rtc_verifier.cc b/libtransport/src/protocols/rtc/rtc_verifier.cc
new file mode 100644
index 000000000..60fce92a5
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_verifier.cc
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2017-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <core/facade.h>
+#include <protocols/rtc/rtc_packet.h>
+#include <protocols/rtc/rtc_verifier.h>
+
+namespace transport {
+namespace protocol {
+namespace rtc {
+
+RTCVerifier::RTCVerifier(std::shared_ptr<auth::Verifier> verifier,
+ uint32_t factor_relevant, uint32_t factor_alert)
+ : verifier_(verifier),
+ factor_relevant_(factor_relevant),
+ factor_alert_(factor_alert),
+ manifest_max_capacity_(std::numeric_limits<uint8_t>::max()) {}
+
+void RTCVerifier::setState(std::shared_ptr<RTCState> rtc_state) {
+ rtc_state_ = rtc_state;
+}
+
+void RTCVerifier::setVerifier(std::shared_ptr<auth::Verifier> verifier) {
+ verifier_ = verifier;
+}
+
+void RTCVerifier::setFactorRelevant(uint32_t factor_relevant) {
+ factor_relevant_ = factor_relevant;
+}
+
+void RTCVerifier::setFactorAlert(uint32_t factor_alert) {
+ factor_alert_ = factor_alert;
+}
+
+auth::VerificationPolicy RTCVerifier::verify(core::Interest &interest) {
+ return verifier_->verifyPackets(&interest);
+}
+
+auth::VerificationPolicy RTCVerifier::verify(
+ core::ContentObject &content_object, bool is_fec) {
+ auth::Suffix suffix = content_object.getName().getSuffix();
+ auth::VerificationPolicy default_policy = auth::VerificationPolicy::ABORT;
+
+ core::PayloadType payload_type = content_object.getPayloadType();
+ bool is_probe = ProbeHandler::getProbeType(suffix) != ProbeType::NOT_PROBE;
+ bool is_nack = !is_probe && content_object.payloadSize() == NACK_HEADER_SIZE;
+ bool is_manifest = !is_probe && !is_nack && !is_fec &&
+ payload_type == core::PayloadType::MANIFEST;
+ bool is_data = !is_probe && !is_nack && !is_fec &&
+ payload_type == core::PayloadType::DATA;
+
+ if (is_probe) return verifyProbe(content_object);
+ if (is_nack) return verifyNack(content_object);
+ if (is_fec) return verifyFec(content_object);
+ if (is_data) return verifyData(content_object);
+ if (is_manifest) return verifyManifest(content_object);
+
+ verifier_->callVerificationFailedCallback(suffix, default_policy);
+ return default_policy;
+}
+
+auth::VerificationPolicy RTCVerifier::verifyProbe(
+ core::ContentObject &content_object) {
+ auth::Suffix suffix = content_object.getName().getSuffix();
+ auth::VerificationPolicy policy = auth::VerificationPolicy::ABORT;
+
+ switch (ProbeHandler::getProbeType(suffix)) {
+ case ProbeType::INIT:
+ policy = verifyManifest(content_object);
+ if (policy == auth::VerificationPolicy::ACCEPT) {
+ policy = processManifest(content_object);
+ }
+ break;
+ case ProbeType::RTT:
+ policy = verifyNack(content_object);
+ break;
+ default:
+ verifier_->callVerificationFailedCallback(suffix, policy);
+ break;
+ }
+
+ return policy;
+}
+
+auth::VerificationPolicy RTCVerifier::verifyNack(
+ core::ContentObject &content_object) {
+ return verifier_->verifyPackets(&content_object);
+}
+
+auth::VerificationPolicy RTCVerifier::verifyFec(
+ core::ContentObject &content_object) {
+ return verifier_->verifyPackets(&content_object);
+}
+
+auth::VerificationPolicy RTCVerifier::verifyData(
+ core::ContentObject &content_object) {
+ if (HICN_PACKET_FORMAT_IS_AH(content_object.getFormat())) {
+ return verifier_->verifyPackets(&content_object);
+ }
+
+ auth::Suffix suffix = content_object.getName().getSuffix();
+ auth::VerificationPolicy policy = auth::VerificationPolicy::ABORT;
+
+ uint32_t threshold_relevant = factor_relevant_ * manifest_max_capacity_;
+ uint32_t threshold_alert = factor_alert_ * manifest_max_capacity_;
+
+ // Flush packets outside relevance window
+ for (auto it = packets_unverif_.set().begin();
+ it != packets_unverif_.set().end();) {
+ if (it->first > current_index_ - threshold_relevant) {
+ break;
+ }
+ packets_unverif_erased_.insert((unsigned int)it->first);
+ it = packets_unverif_.remove(it);
+ }
+
+ // Add packet to set of unverified packets
+ packets_unverif_.add({current_index_, suffix},
+ content_object.computeDigest(manifest_hash_algo_));
+ current_index_++;
+
+ // Check that the number of unverified packets is below the alert threshold
+ if (packets_unverif_.set().size() <= threshold_alert) {
+ policy = auth::VerificationPolicy::ACCEPT;
+ }
+
+ verifier_->callVerificationFailedCallback(suffix, policy);
+ return policy;
+}
+
+auth::VerificationPolicy RTCVerifier::verifyManifest(
+ core::ContentObject &content_object) {
+ return verifier_->verifyPackets(&content_object);
+}
+
+auth::VerificationPolicy RTCVerifier::processManifest(
+ core::ContentObject &content_object) {
+ auth::Suffix suffix = content_object.getName().getSuffix();
+ auth::VerificationPolicy accept_policy = auth::VerificationPolicy::ACCEPT;
+
+ // Decode manifest
+ core::ContentObjectManifest manifest(content_object.shared_from_this());
+ manifest.decode();
+
+ // Extract manifest data
+ manifest_max_capacity_ = manifest.getMaxCapacity();
+ manifest_hash_algo_ = manifest.getHashAlgorithm();
+ auth::Verifier::SuffixMap suffix_map = manifest.getSuffixMap();
+
+ // Return early if the manifest is empty
+ if (suffix_map.empty()) {
+ verifier_->callVerificationFailedCallback(suffix, accept_policy);
+ return accept_policy;
+ }
+
+ // Add hashes to map of all manifest hashes
+ manifest_digests_.insert(suffix_map.begin(), suffix_map.end());
+
+ // Remove discarded and definitely lost packets from digest map
+ for (auto it = manifest_digests_.begin(); it != manifest_digests_.end();) {
+ auto it_erased = packets_unverif_erased_.find(it->first);
+
+ if (it_erased != packets_unverif_erased_.end()) {
+ packets_unverif_erased_.erase(it_erased);
+ it = manifest_digests_.erase(it);
+ continue;
+ }
+
+ if (rtc_state_->getPacketState(it->first) == PacketState::DEFINITELY_LOST) {
+ it = manifest_digests_.erase(it);
+ continue;
+ }
+
+ ++it;
+ }
+
+ // Verify packets
+ auth::Verifier::PolicyMap policies =
+ verifier_->verifyHashes(packets_unverif_.suffixMap(), manifest_digests_);
+
+ for (const auto &p : policies) {
+ switch (p.second) {
+ case auth::VerificationPolicy::ACCEPT: {
+ packets_unverif_.remove(packets_unverif_.packet(p.first));
+ manifest_digests_.erase(p.first);
+ break;
+ }
+ case auth::VerificationPolicy::UNKNOWN:
+ break;
+ case auth::VerificationPolicy::DROP:
+ case auth::VerificationPolicy::ABORT:
+ return p.second;
+ }
+ }
+
+ verifier_->callVerificationFailedCallback(suffix, accept_policy);
+ return accept_policy;
+}
+
+void RTCVerifier::onDataRecoveredFec(uint32_t suffix) {
+ manifest_digests_.erase(suffix);
+}
+
+std::pair<RTCVerifier::PacketSet::iterator, bool> RTCVerifier::Packets::add(
+ const Packet &packet, const auth::CryptoHash &digest) {
+ auto inserted = packets_.insert(packet);
+ if (inserted.second) {
+ packets_map_[packet.second] = inserted.first;
+ suffix_map_[packet.second] = digest;
+ }
+ return inserted;
+}
+
+RTCVerifier::PacketSet::iterator RTCVerifier::Packets::remove(
+ PacketSet::iterator packet_it) {
+ packets_map_.erase(packet_it->second);
+ suffix_map_.erase(packet_it->second);
+ return packets_.erase(packet_it);
+}
+
+const std::set<RTCVerifier::Packet> &RTCVerifier::Packets::set() const {
+ return packets_;
+};
+
+RTCVerifier::PacketSet::iterator RTCVerifier::Packets::packet(
+ auth::Suffix suffix) {
+ return packets_map_.at(suffix);
+};
+
+const auth::Verifier::SuffixMap &RTCVerifier::Packets::suffixMap() const {
+ return suffix_map_;
+}
+
+} // end namespace rtc
+} // end namespace protocol
+} // end namespace transport
diff --git a/libtransport/src/protocols/rtc/rtc_verifier.h b/libtransport/src/protocols/rtc/rtc_verifier.h
new file mode 100644
index 000000000..c83faf08a
--- /dev/null
+++ b/libtransport/src/protocols/rtc/rtc_verifier.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2017-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <core/facade.h>
+#include <hicn/transport/auth/verifier.h>
+#include <hicn/transport/core/content_object.h>
+#include <protocols/rtc/rtc_state.h>
+
+namespace transport {
+namespace protocol {
+namespace rtc {
+
+class RTCVerifier {
+ public:
+ explicit RTCVerifier(std::shared_ptr<auth::Verifier> verifier,
+ uint32_t factor_relevant, uint32_t factor_alert);
+
+ virtual ~RTCVerifier() = default;
+
+ void setState(std::shared_ptr<RTCState> rtc_state);
+ void setVerifier(std::shared_ptr<auth::Verifier> verifier);
+ void setFactorRelevant(uint32_t factor_relevant);
+ void setFactorAlert(uint32_t factor_alert);
+
+ auth::VerificationPolicy verify(core::Interest &interest);
+ auth::VerificationPolicy verify(core::ContentObject &content_object,
+ bool is_fec = false);
+ auth::VerificationPolicy verifyProbe(core::ContentObject &content_object);
+ auth::VerificationPolicy verifyNack(core::ContentObject &content_object);
+ auth::VerificationPolicy verifyFec(core::ContentObject &content_object);
+ auth::VerificationPolicy verifyData(core::ContentObject &content_object);
+ auth::VerificationPolicy verifyManifest(core::ContentObject &content_object);
+
+ auth::VerificationPolicy processManifest(core::ContentObject &content_object);
+
+ void onDataRecoveredFec(uint32_t suffix);
+
+ protected:
+ using Index = uint64_t;
+ using Packet = std::pair<Index, auth::Suffix>;
+ using PacketSet = std::set<Packet>;
+
+ class Packets {
+ public:
+ std::pair<PacketSet::iterator, bool> add(const Packet &packet,
+ const auth::CryptoHash &digest);
+ PacketSet::iterator remove(PacketSet::iterator packet_it);
+ const PacketSet &set() const;
+ PacketSet::iterator packet(auth::Suffix suffix);
+ const auth::Verifier::SuffixMap &suffixMap() const;
+
+ private:
+ PacketSet packets_;
+ std::unordered_map<auth::Suffix, PacketSet::iterator> packets_map_;
+ auth::Verifier::SuffixMap suffix_map_;
+ };
+
+ // The RTC state.
+ std::shared_ptr<RTCState> rtc_state_;
+ // The verifier instance.
+ std::shared_ptr<auth::Verifier> verifier_;
+ // Used to compute the relevance windows size (in packets).
+ uint32_t factor_relevant_;
+ // Used to compute the alert threshold (in packets).
+ uint32_t factor_alert_;
+ // The maximum number of entries a manifest can contain.
+ uint8_t manifest_max_capacity_;
+ // Hash algorithm used by manifests.
+ auth::CryptoHashType manifest_hash_algo_;
+ // Digests extracted from all manifests received.
+ auth::Verifier::SuffixMap manifest_digests_;
+ // The number of data packets processed.
+ Index current_index_;
+ // Unverified packets with index in relevance window.
+ Packets packets_unverif_;
+ // Unverified erased packets with index outside relevance window.
+ std::unordered_set<auth::Suffix> packets_unverif_erased_;
+};
+
+} // namespace rtc
+} // namespace protocol
+} // namespace transport
diff --git a/libtransport/src/protocols/transport_protocol.cc b/libtransport/src/protocols/transport_protocol.cc
index d6954ac37..29d140454 100644
--- a/libtransport/src/protocols/transport_protocol.cc
+++ b/libtransport/src/protocols/transport_protocol.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -25,7 +25,8 @@ using namespace interface;
TransportProtocol::TransportProtocol(implementation::ConsumerSocket *icn_socket,
Indexer *indexer, Reassembly *reassembly)
- : socket_(icn_socket),
+ : Protocol(),
+ socket_(icn_socket),
indexer_verifier_(indexer),
reassembly_(reassembly),
fec_decoder_(nullptr),
@@ -36,90 +37,77 @@ TransportProtocol::TransportProtocol(implementation::ConsumerSocket *icn_socket,
on_interest_satisfied_(VOID_HANDLER),
on_content_object_input_(VOID_HANDLER),
stats_summary_(VOID_HANDLER),
+ on_fwd_strategy_(VOID_HANDLER),
+ on_rec_strategy_(VOID_HANDLER),
on_payload_(VOID_HANDLER),
- fec_type_(fec::FECType::UNKNOWN),
- is_running_(false) {
+ fec_type_(fec::FECType::UNKNOWN) {
socket_->getSocketOption(GeneralTransportOptions::PORTAL, portal_);
socket_->getSocketOption(OtherOptions::STATISTICS, &stats_);
- // Set this transport protocol as portal's consumer callback
- portal_->setConsumerCallback(this);
-
indexer_verifier_->setReassembly(reassembly_.get());
reassembly->setIndexer(indexer_verifier_.get());
}
+TransportProtocol::~TransportProtocol() {}
+
int TransportProtocol::start() {
// If the protocol is already running, return otherwise set as running
- if (is_running_) return -1;
-
- // Get all callbacks references
- socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_RETRANSMISSION,
- &on_interest_retransmission_);
- socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_OUTPUT,
- &on_interest_output_);
- socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_EXPIRED,
- &on_interest_timeout_);
- socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_SATISFIED,
- &on_interest_satisfied_);
- socket_->getSocketOption(ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT,
- &on_content_object_input_);
- socket_->getSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY,
- &stats_summary_);
- socket_->getSocketOption(ConsumerCallbacksOptions::READ_CALLBACK,
- &on_payload_);
-
- socket_->getSocketOption(GeneralTransportOptions::ASYNC_MODE, is_async_);
-
- // Set it is the first time we schedule an interest
- is_first_ = true;
-
- // Reset the protocol state machine
- reset();
-
- // Schedule next interests
- scheduleNextInterests();
-
- is_first_ = false;
-
- // Set the protocol as running
- is_running_ = true;
-
- if (!is_async_) {
- // Start Event loop
- portal_->runEventsLoop();
-
- // Not running anymore
- is_running_ = false;
+ if (isRunning()) {
+ return -1;
}
- return 0;
-}
-
-void TransportProtocol::stop() {
- is_running_ = false;
+ // Start protocol on its own thread
+ portal_->getThread().add([this]() {
+ // Get all callbacks references
+ socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_RETRANSMISSION,
+ &on_interest_retransmission_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_OUTPUT,
+ &on_interest_output_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_EXPIRED,
+ &on_interest_timeout_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::INTEREST_SATISFIED,
+ &on_interest_satisfied_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::CONTENT_OBJECT_INPUT,
+ &on_content_object_input_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY,
+ &stats_summary_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::FWD_STRATEGY_CHANGE,
+ &on_fwd_strategy_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::REC_STRATEGY_CHANGE,
+ &on_rec_strategy_);
+ socket_->getSocketOption(ConsumerCallbacksOptions::READ_CALLBACK,
+ &on_payload_);
+
+ socket_->getSocketOption(GeneralTransportOptions::ASYNC_MODE, is_async_);
+ socket_->getSocketOption(GeneralTransportOptions::SIGNER, signer_);
+
+ // Set it is the first time we schedule an interest
+ is_first_ = true;
+
+ // Reset the protocol state machine
+ reset();
+
+ // Set this transport protocol as portal's consumer callback
+ portal_->registerTransportCallback(this);
+
+ // Schedule next interests
+ scheduleNextInterests();
+
+ is_first_ = false;
+
+ // Set the protocol as running
+ setRunning();
+ });
- if (!is_async_) {
- portal_->stopEventsLoop();
- } else {
- portal_->clear();
- }
+ return 0;
}
void TransportProtocol::resume() {
if (isRunning()) return;
- is_running_ = true;
-
- scheduleNextInterests();
-
- if (!is_async_) {
- // Start Event loop
- portal_->runEventsLoop();
+ setRunning();
- // Not running anymore
- is_running_ = false;
- }
+ portal_->getThread().tryRunHandlerNow([this]() { scheduleNextInterests(); });
}
void TransportProtocol::reset() {
@@ -130,7 +118,7 @@ void TransportProtocol::reset() {
}
}
-void TransportProtocol::onContentReassembled(std::error_code ec) {
+void TransportProtocol::onContentReassembled(const std::error_code &ec) {
stop();
if (!on_payload_) {
@@ -153,7 +141,19 @@ void TransportProtocol::sendInterest(
uint32_t len) {
DLOG_IF(INFO, VLOG_IS_ON(3)) << "Sending interest for name " << interest_name;
- auto interest = core::PacketManager<>::getInstance().getPacket<Interest>();
+ Packet::Format format;
+ socket_->getSocketOption(interface::GeneralTransportOptions::PACKET_FORMAT,
+ format);
+ size_t signature_size = 0;
+
+ // If aggregated interest, add spapce for signature
+ if (len > 0) {
+ format = Packet::toAHFormat(format);
+ signature_size = signer_->getSignatureFieldSize();
+ }
+
+ auto interest = core::PacketManager<>::getInstance().getPacket<Interest>(
+ format, signature_size);
interest->setName(interest_name);
for (uint32_t i = 0; i < len; i++) {
@@ -173,7 +173,24 @@ void TransportProtocol::sendInterest(
return;
}
- portal_->sendInterest(std::move(interest));
+ bool content_sharing_mode;
+ socket_->getSocketOption(RtcTransportOptions::CONTENT_SHARING_MODE,
+ content_sharing_mode);
+ if (content_sharing_mode) lifetime = ceil((double)lifetime * 0.9);
+
+ // Compute signature
+ bool is_ah = HICN_PACKET_FORMAT_IS_AH(interest->getFormat());
+ if (is_ah) signer_->signPacket(interest.get());
+
+ portal_->sendInterest(interest, lifetime);
+}
+
+void TransportProtocol::onError(const std::error_code &ec) {
+ // error from portal: stop socket
+ stop();
+
+ // signal error to application
+ on_payload_->readError(ec);
}
void TransportProtocol::onTimeout(Interest::Ptr &i, const Name &n) {
diff --git a/libtransport/src/protocols/transport_protocol.h b/libtransport/src/protocols/transport_protocol.h
index 1008a238b..e71992561 100644
--- a/libtransport/src/protocols/transport_protocol.h
+++ b/libtransport/src/protocols/transport_protocol.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -19,10 +19,10 @@
#include <hicn/transport/interfaces/socket_consumer.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/fec_base.h>
#include <protocols/indexer.h>
+#include <protocols/protocol.h>
#include <protocols/reassembly.h>
#include <array>
@@ -38,8 +38,10 @@ class IndexVerificationManager;
using ReadCallback = interface::ConsumerSocket::ReadCallback;
-class TransportProtocol : public core::Portal::ConsumerCallback,
- public ContentObjectProcessingEventCallback {
+class TransportProtocol
+ : public ContentObjectProcessingEventCallback,
+ public Protocol,
+ public std::enable_shared_from_this<TransportProtocol> {
static constexpr std::size_t interest_pool_size = 4096;
friend class ManifestIndexManager;
@@ -48,13 +50,11 @@ class TransportProtocol : public core::Portal::ConsumerCallback,
TransportProtocol(implementation::ConsumerSocket *icn_socket,
Indexer *indexer, Reassembly *reassembly);
- virtual ~TransportProtocol() = default;
-
- TRANSPORT_ALWAYS_INLINE bool isRunning() { return is_running_; }
+ virtual ~TransportProtocol();
virtual int start();
- virtual void stop();
+ using Protocol::stop;
virtual void resume();
@@ -64,12 +64,12 @@ class TransportProtocol : public core::Portal::ConsumerCallback,
*
* @return The header length in bytes.
*/
- virtual std::size_t transportHeaderLength() { return 0; }
+ virtual std::size_t transportHeaderLength(bool isFEC) { return 0; }
virtual void scheduleNextInterests() = 0;
// Events generated by the indexing
- virtual void onContentReassembled(std::error_code ec);
+ virtual void onContentReassembled(const std::error_code &ec);
virtual void onPacketDropped(Interest &interest,
ContentObject &content_object,
const std::error_code &ec) override = 0;
@@ -90,7 +90,8 @@ class TransportProtocol : public core::Portal::ConsumerCallback,
AllocatorHandler &&allocator_handler) {
if (!fec_decoder_) {
// Try to get FEC from environment
- if (const char *fec_str = std::getenv("TRANSPORT_FEC_TYPE")) {
+ const char *fec_str = std::getenv("TRANSPORT_FEC_TYPE");
+ if (fec_str && (fec_type_ == fec::FECType::UNKNOWN)) {
LOG(INFO) << "Using FEC " << fec_str;
fec_type_ = fec::FECUtils::fecTypeFromString(fec_str);
}
@@ -114,14 +115,13 @@ class TransportProtocol : public core::Portal::ConsumerCallback,
// Consumer Callback
void onContentObject(Interest &i, ContentObject &c) override;
void onTimeout(Interest::Ptr &i, const Name &n) override;
- void onError(std::error_code ec) override {}
+ void onError(const std::error_code &ec) override;
protected:
implementation::ConsumerSocket *socket_;
std::unique_ptr<Indexer> indexer_verifier_;
std::unique_ptr<Reassembly> reassembly_;
std::unique_ptr<fec::ConsumerFEC> fec_decoder_;
- std::shared_ptr<core::Portal> portal_;
// True if it si the first time we schedule an interest
std::atomic<bool> is_first_;
interface::TransportStatistics *stats_;
@@ -134,14 +134,16 @@ class TransportProtocol : public core::Portal::ConsumerCallback,
interface::ConsumerContentObjectCallback *on_content_object_input_;
interface::ConsumerContentObjectCallback *on_content_object_;
interface::ConsumerTimerCallback *stats_summary_;
+ interface::StrategyCallback *on_fwd_strategy_;
+ interface::StrategyCallback *on_rec_strategy_;
ReadCallback *on_payload_;
bool is_async_;
fec::FECType fec_type_;
- private:
- std::atomic<bool> is_running_;
+ // Signer for aggregated interests
+ std::shared_ptr<auth::Signer> signer_;
};
} // end namespace protocol
diff --git a/libtransport/src/test/CMakeLists.txt b/libtransport/src/test/CMakeLists.txt
index 26fe7aee1..56edcd102 100644
--- a/libtransport/src/test/CMakeLists.txt
+++ b/libtransport/src/test/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,42 +11,71 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-include(BuildMacros)
-
+##############################################################
+# Test sources
+##############################################################
list(APPEND TESTS_SRC
main.cc
+ test_aggregated_header.cc
test_auth.cc
test_consumer_producer_rtc.cc
test_core_manifest.cc
- test_event_thread.cc
+ # test_event_thread.cc
+ test_fec_base_rs.cc
test_fec_reedsolomon.cc
+ test_fixed_block_allocator.cc
test_indexer.cc
test_interest.cc
test_packet.cc
+ test_packet_allocator.cc
+ test_quality_score.cc
+ test_sessions.cc
+ test_thread_pool.cc
+ test_quadloop.cc
+ test_prefix.cc
+ test_traffic_generator.cc
)
if (ENABLE_RELY)
list(APPEND TESTS_SRC
test_fec_rely_wrapper.cc
+ test_fec_base_rely.cc
)
endif()
-build_executable(unit_tests
+#if (UNIX AND NOT APPLE)
+# list(APPEND TESTS_SRC
+# test_memif_connector.cc
+# )
+#endif()
+
+
+##############################################################
+# Link libraries
+##############################################################
+set(MEMIF_MODULE_LIBRARIES
+ ${LIBRARIES}
+ ${LIBTRANSPORT_SHARED}
+ ${GTEST_LIBRARIES}
+)
+
+
+##############################################################
+# Build single unit test executable and add it to test list
+##############################################################
+build_executable(libtransport_tests
NO_INSTALL
SOURCES ${TESTS_SRC}
LINK_LIBRARIES
- ${LIBRARIES}
- ${LIBTRANSPORT_STATIC}
- ${GTEST_LIBRARIES}
+ ${MEMIF_MODULE_LIBRARIES}
INCLUDE_DIRS
- ${LIBTRANSPORT_INCLUDE_DIRS}
- ${LIBHICN_INCLUDE_DIRS}
- ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
+ $<TARGET_PROPERTY:${LIBTRANSPORT_SHARED},INCLUDE_DIRECTORIES>
${GTEST_INCLUDE_DIRS}
DEPENDS gtest ${LIBTRANSPORT_SHARED}
COMPONENT ${LIBTRANSPORT_COMPONENT}
- DEFINITIONS "${COMPILER_DEFINITIONS}"
+ DEFINITIONS ${COMPILER_DEFINITIONS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
LINK_FLAGS ${LINK_FLAGS}
)
-add_test_internal(unit_tests)
+add_test_internal(libtransport_tests)
diff --git a/libtransport/src/test/main.cc b/libtransport/src/test/main.cc
index a4d7ce1b3..591ed0d5b 100644
--- a/libtransport/src/test/main.cc
+++ b/libtransport/src/test/main.cc
@@ -16,7 +16,6 @@
#include <gtest/gtest.h>
int main(int argc, char **argv) {
- srand(time(0));
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} \ No newline at end of file
diff --git a/libtransport/src/test/packet_samples.h b/libtransport/src/test/packet_samples.h
index e98d06a18..216ac7f9f 100644
--- a/libtransport/src/test/packet_samples.h
+++ b/libtransport/src/test/packet_samples.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -56,3 +56,16 @@
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+
+#define SIGNATURE \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
diff --git a/libtransport/src/test/test_aggregated_header.cc b/libtransport/src/test/test_aggregated_header.cc
new file mode 100644
index 000000000..4dd71f60d
--- /dev/null
+++ b/libtransport/src/test/test_aggregated_header.cc
@@ -0,0 +1,624 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <hicn/transport/errors/not_implemented_exception.h>
+#include <protocols/rtc/rtc_packet.h>
+#include <test/packet_samples.h>
+
+#include <climits>
+#include <random>
+#include <vector>
+
+namespace transport {
+
+namespace core {
+
+namespace {
+// The fixture for testing class Foo.
+class AggregatedPktHeaderTest : public ::testing::Test {
+ protected:
+ AggregatedPktHeaderTest() {
+ // You can do set-up work for each test here.
+ }
+
+ virtual ~AggregatedPktHeaderTest() {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void SetUp() {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ }
+
+ virtual void TearDown() {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ }
+};
+
+} // namespace
+
+#if 0
+TEST_F(AggregatedPktHeaderTest, Add2Packets8bit) {
+ uint8_t buf[1500];
+ std::vector<uint8_t> pkt1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
+ uint16_t pkt1_len = 14;
+
+ std::vector<uint8_t> pkt2 = {11, 12, 13, 14, 15, 16, 17};
+ uint16_t pkt2_len = 7;
+
+ for (uint16_t i = 0; i < 1500; i++) {
+ buf[i] = 0;
+ }
+
+ // skip protocol::rtc::DATA_HEADER_SIZE that will be the rtc header
+ protocol::rtc::AggrPktHeader hdr(buf + protocol::rtc::DATA_HEADER_SIZE,
+ pkt1_len, 2);
+ hdr.addPacketToHeader(0, pkt1_len);
+ hdr.addPacketToHeader(1, pkt2_len);
+ uint8_t* ptr = hdr.getPayloadAppendPtr();
+
+ // copy packet 1
+ for (uint16_t i = 0; i < pkt1_len; i++) {
+ *(ptr + i) = pkt1[i];
+ }
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt2_len; i++) {
+ *(ptr + i + pkt1_len) = pkt2[i];
+ }
+
+ // print
+ // for (uint16_t i = 0; i < 40; i++){
+ // std::cout << (int) i << " " << (int) buf[i] << std::endl;
+ //}
+
+ uint8_t* pkt_ptr = nullptr;
+ uint16_t pkt_len = 0;
+
+ hdr.getPointerToPacket(0, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt1_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt1[i]);
+ }
+
+ hdr.getPointerToPacket(1, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt2_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt2[i]);
+ }
+}
+#endif
+
+TEST_F(AggregatedPktHeaderTest, Add2Packets8bit255) {
+ uint8_t buf[1500];
+
+ std::vector<uint8_t> pkt1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
+ uint16_t pkt1_len = 14;
+
+ std::vector<uint8_t> pkt2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 20
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 40
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 60
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 80
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 100
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 120
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 140
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 160
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 180
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 200
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 220
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 240
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14}; // 255
+ uint16_t pkt2_len = 255;
+
+ for (uint16_t i = 0; i < 1500; i++) {
+ buf[i] = 0;
+ }
+
+ // skip protocol::rtc::DATA_HEADER_SIZE that will be the rtc header
+ protocol::rtc::AggrPktHeader hdr(buf + protocol::rtc::DATA_HEADER_SIZE,
+ pkt2_len, 2);
+ hdr.addPacketToHeader(0, pkt1_len);
+ hdr.addPacketToHeader(1, pkt2_len);
+ uint8_t* ptr = hdr.getPayloadAppendPtr();
+
+ // copy packet 1
+ for (uint16_t i = 0; i < pkt1_len; i++) {
+ *(ptr + i) = pkt1[i];
+ }
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt2_len; i++) {
+ *(ptr + i + pkt1_len) = pkt2[i];
+ }
+
+ uint8_t* pkt_ptr = nullptr;
+ uint16_t pkt_len = 0;
+
+ hdr.getPointerToPacket(0, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt1_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt1[i]);
+ }
+
+ hdr.getPointerToPacket(1, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt2_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt2[i]);
+ }
+}
+
+TEST_F(AggregatedPktHeaderTest, Add2Packets8bit256) {
+ uint8_t buf[1500];
+
+ std::vector<uint8_t> pkt1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
+ uint16_t pkt1_len = 14;
+
+ std::vector<uint8_t> pkt2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 20
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 40
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 60
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 80
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 100
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 120
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 140
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 160
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 180
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 200
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 220
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 240
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15}; // 256
+ uint16_t pkt2_len = 256;
+
+ for (uint16_t i = 0; i < 1500; i++) {
+ buf[i] = 0;
+ }
+
+ // skip protocol::rtc::DATA_HEADER_SIZE that will be the rtc header
+ protocol::rtc::AggrPktHeader hdr(buf + protocol::rtc::DATA_HEADER_SIZE,
+ pkt2_len, 2);
+ hdr.addPacketToHeader(0, pkt1_len);
+ hdr.addPacketToHeader(1, pkt2_len);
+ uint8_t* ptr = hdr.getPayloadAppendPtr();
+
+ // copy packet 1
+ for (uint16_t i = 0; i < pkt1_len; i++) {
+ *(ptr + i) = pkt1[i];
+ }
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt2_len; i++) {
+ *(ptr + i + pkt1_len) = pkt2[i];
+ }
+
+ uint8_t* pkt_ptr = nullptr;
+ uint16_t pkt_len = 0;
+
+ hdr.getPointerToPacket(0, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt1_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt1[i]);
+ }
+
+ hdr.getPointerToPacket(1, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt2_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt2[i]);
+ }
+}
+
+TEST_F(AggregatedPktHeaderTest, Add4Packets8bit) {
+ uint8_t buf[1500];
+
+ std::vector<uint8_t> pkt1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
+ uint16_t pkt1_len = 14;
+
+ std::vector<uint8_t> pkt2 = {11, 12, 13, 14, 15, 16, 17};
+ uint16_t pkt2_len = 7;
+
+ std::vector<uint8_t> pkt3 = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
+ uint16_t pkt3_len = 10;
+
+ std::vector<uint8_t> pkt4 = {100, 110};
+ uint16_t pkt4_len = 2;
+
+ for (uint16_t i = 0; i < 1500; i++) {
+ buf[i] = 0;
+ }
+
+ // skip protocol::rtc::DATA_HEADER_SIZE that will be the rtc header
+ protocol::rtc::AggrPktHeader hdr(buf + protocol::rtc::DATA_HEADER_SIZE,
+ pkt1_len, 4);
+ hdr.addPacketToHeader(0, pkt1_len);
+ hdr.addPacketToHeader(1, pkt2_len);
+ hdr.addPacketToHeader(2, pkt3_len);
+ hdr.addPacketToHeader(3, pkt4_len);
+ uint8_t* ptr = hdr.getPayloadAppendPtr();
+
+ // copy packet 1
+ for (uint16_t i = 0; i < pkt1_len; i++) {
+ *(ptr + i) = pkt1[i];
+ }
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt2_len; i++) {
+ *(ptr + i + pkt1_len) = pkt2[i];
+ }
+
+ // copy packet 3
+ for (uint16_t i = 0; i < pkt3_len; i++) {
+ *(ptr + i + pkt1_len + pkt2_len) = pkt3[i];
+ }
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt4_len; i++) {
+ *(ptr + i + pkt1_len + pkt2_len + pkt3_len) = pkt4[i];
+ }
+
+ uint8_t* pkt_ptr = nullptr;
+ uint16_t pkt_len = 0;
+
+ hdr.getPointerToPacket(0, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt1_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt1[i]);
+ }
+
+ hdr.getPointerToPacket(1, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt2_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt2[i]);
+ }
+
+ hdr.getPointerToPacket(2, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt3_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt3[i]);
+ }
+
+ hdr.getPointerToPacket(3, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt4_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt4[i]);
+ }
+}
+
+TEST_F(AggregatedPktHeaderTest, Add4Packets16bit) {
+ uint8_t buf[1500];
+
+ std::vector<uint8_t> pkt1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
+ uint16_t pkt1_len = 14;
+
+ std::vector<uint8_t> pkt2 = {11, 12, 13, 14, 15, 16, 17};
+ uint16_t pkt2_len = 7;
+
+ std::vector<uint8_t> pkt3 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 20
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 40
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 60
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 80
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 100
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 120
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 140
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 160
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 180
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 200
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 220
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 240
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; // 260
+ uint16_t pkt3_len = 260;
+
+ std::vector<uint8_t> pkt4 = {100, 110};
+ uint16_t pkt4_len = 2;
+
+ for (uint16_t i = 0; i < 1500; i++) {
+ buf[i] = 0;
+ }
+
+ // skip protocol::rtc::DATA_HEADER_SIZE that will be the rtc header
+ protocol::rtc::AggrPktHeader hdr(buf + protocol::rtc::DATA_HEADER_SIZE,
+ pkt3_len, 4);
+ hdr.addPacketToHeader(0, pkt1_len);
+ hdr.addPacketToHeader(1, pkt2_len);
+ hdr.addPacketToHeader(2, pkt3_len);
+ hdr.addPacketToHeader(3, pkt4_len);
+ uint8_t* ptr = hdr.getPayloadAppendPtr();
+
+ // copy packet 1
+ for (uint16_t i = 0; i < pkt1_len; i++) {
+ *(ptr + i) = pkt1[i];
+ }
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt2_len; i++) {
+ *(ptr + i + pkt1_len) = pkt2[i];
+ }
+
+ // copy packet 3
+ for (uint16_t i = 0; i < pkt3_len; i++) {
+ *(ptr + i + pkt1_len + pkt2_len) = pkt3[i];
+ }
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt4_len; i++) {
+ *(ptr + i + pkt1_len + pkt2_len + pkt3_len) = pkt4[i];
+ }
+
+ uint8_t* pkt_ptr = nullptr;
+ uint16_t pkt_len = 0;
+
+ hdr.getPointerToPacket(0, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt1_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt1[i]);
+ }
+
+ hdr.getPointerToPacket(1, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt2_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt2[i]);
+ }
+
+ hdr.getPointerToPacket(2, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt3_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt3[i]);
+ }
+
+ hdr.getPointerToPacket(3, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt4_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt4[i]);
+ }
+}
+
+TEST_F(AggregatedPktHeaderTest, Defrag4Packets8bit) {
+ uint8_t buf[1500];
+
+ std::vector<uint8_t> pkt1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
+ uint16_t pkt1_len = 14;
+
+ std::vector<uint8_t> pkt2 = {11, 12, 13, 14, 15, 16, 17};
+ uint16_t pkt2_len = 7;
+
+ std::vector<uint8_t> pkt3 = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
+ uint16_t pkt3_len = 10;
+
+ std::vector<uint8_t> pkt4 = {100, 110};
+ uint16_t pkt4_len = 2;
+
+ for (uint16_t i = 0; i < 1500; i++) {
+ buf[i] = 0;
+ }
+
+ // skip protocol::rtc::DATA_HEADER_SIZE that will be the rtc header
+ protocol::rtc::AggrPktHeader hdr(buf + protocol::rtc::DATA_HEADER_SIZE,
+ pkt1_len, 4);
+ hdr.addPacketToHeader(0, pkt1_len);
+ hdr.addPacketToHeader(1, pkt2_len);
+ hdr.addPacketToHeader(2, pkt3_len);
+ hdr.addPacketToHeader(3, pkt4_len);
+
+ uint16_t offset = protocol::rtc::DATA_HEADER_SIZE + 8; // 8 = aggr hdr
+
+ // copy packet 1
+ for (uint16_t i = 0; i < pkt1_len; i++) {
+ buf[i + offset] = pkt1[i];
+ }
+ offset += pkt1_len;
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt2_len; i++) {
+ buf[i + offset] = pkt2[i];
+ }
+ offset += pkt2_len;
+
+ // copy packet 3
+ for (uint16_t i = 0; i < pkt3_len; i++) {
+ buf[i + offset] = pkt3[i];
+ }
+ offset += pkt3_len;
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt4_len; i++) {
+ buf[i + offset] = pkt4[i];
+ }
+
+ protocol::rtc::AggrPktHeader hdr2(buf + protocol::rtc::DATA_HEADER_SIZE);
+
+ uint8_t* pkt_ptr = nullptr;
+ uint16_t pkt_len = 0;
+
+ uint8_t packet_number = hdr2.getNumberOfPackets();
+ EXPECT_EQ(packet_number, 4);
+
+ hdr2.getPointerToPacket(0, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt1_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt1[i]);
+ }
+
+ hdr2.getPointerToPacket(1, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt2_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt2[i]);
+ }
+
+ hdr2.getPointerToPacket(2, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt3_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt3[i]);
+ }
+
+ hdr2.getPointerToPacket(3, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt4_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt4[i]);
+ }
+}
+
+TEST_F(AggregatedPktHeaderTest, Defrag4Packets16bit) {
+ uint8_t buf[1500];
+
+ std::vector<uint8_t> pkt1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
+ uint16_t pkt1_len = 14;
+
+ std::vector<uint8_t> pkt2 = {11, 12, 13, 14, 15, 16, 17};
+ uint16_t pkt2_len = 7;
+
+ std::vector<uint8_t> pkt3 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 20
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 40
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 60
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 80
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 100
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 120
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 140
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 160
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 180
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 200
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 220
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, // 240
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; // 260
+ uint16_t pkt3_len = 260;
+
+ std::vector<uint8_t> pkt4 = {100, 110};
+ uint16_t pkt4_len = 2;
+
+ for (uint16_t i = 0; i < 1500; i++) {
+ buf[i] = 0;
+ }
+
+ // skip protocol::rtc::DATA_HEADER_SIZE that will be the rtc header
+ protocol::rtc::AggrPktHeader hdr(buf + protocol::rtc::DATA_HEADER_SIZE,
+ pkt3_len, 4);
+ hdr.addPacketToHeader(0, pkt1_len);
+ hdr.addPacketToHeader(1, pkt2_len);
+ hdr.addPacketToHeader(2, pkt3_len);
+ hdr.addPacketToHeader(3, pkt4_len);
+
+ uint16_t offset = protocol::rtc::DATA_HEADER_SIZE + 12; // 12 = aggr hdr
+
+ // copy packet 1
+ for (uint16_t i = 0; i < pkt1_len; i++) {
+ buf[i + offset] = pkt1[i];
+ }
+ offset += pkt1_len;
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt2_len; i++) {
+ buf[i + offset] = pkt2[i];
+ }
+ offset += pkt2_len;
+
+ // copy packet 3
+ for (uint16_t i = 0; i < pkt3_len; i++) {
+ buf[i + offset] = pkt3[i];
+ }
+ offset += pkt3_len;
+
+ // copy packet 2
+ for (uint16_t i = 0; i < pkt4_len; i++) {
+ buf[i + offset] = pkt4[i];
+ }
+
+ protocol::rtc::AggrPktHeader hdr2(buf + protocol::rtc::DATA_HEADER_SIZE);
+
+ uint8_t* pkt_ptr = nullptr;
+ uint16_t pkt_len = 0;
+
+ uint8_t packet_number = hdr2.getNumberOfPackets();
+ EXPECT_EQ(packet_number, 4);
+
+ hdr2.getPointerToPacket(0, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt1_len);
+ for (uint16_t i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt1[i]);
+ }
+
+ hdr2.getPointerToPacket(1, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt2_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt2[i]);
+ }
+
+ hdr2.getPointerToPacket(2, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt3_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt3[i]);
+ }
+
+ hdr2.getPointerToPacket(3, &pkt_ptr, &pkt_len);
+ EXPECT_EQ(pkt_len, pkt4_len);
+ for (int i = 0; i < pkt_len; i++) {
+ EXPECT_EQ(*(pkt_ptr + i), pkt4[i]);
+ }
+}
+
+} // namespace core
+} // namespace transport
diff --git a/libtransport/src/test/test_auth.cc b/libtransport/src/test/test_auth.cc
index db1c3b52f..5440d3741 100644
--- a/libtransport/src/test/test_auth.cc
+++ b/libtransport/src/test/test_auth.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,10 +15,15 @@
#include <gtest/gtest.h>
#include <hicn/transport/auth/crypto_hash.h>
-#include <hicn/transport/auth/identity.h>
#include <hicn/transport/auth/signer.h>
#include <hicn/transport/auth/verifier.h>
#include <hicn/transport/core/content_object.h>
+#include <openssl/rand.h>
+
+using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>;
+using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;
+using EC_KEY_ptr = std::unique_ptr<EC_KEY, decltype(&::EC_KEY_free)>;
+using DSA_ptr = std::unique_ptr<DSA, decltype(&::DSA_free)>;
namespace transport {
namespace auth {
@@ -37,7 +42,7 @@ class AuthTest : public ::testing::Test {
TEST_F(AuthTest, VoidVerifier) {
// Create a content object
- core::ContentObject packet(HF_INET6_TCP_AH);
+ core::ContentObject packet(HICN_PACKET_FORMAT_IPV6_TCP_AH);
// Fill it with bogus data
uint8_t buffer[256] = {0};
@@ -50,14 +55,27 @@ TEST_F(AuthTest, VoidVerifier) {
}
TEST_F(AuthTest, AsymmetricRSA) {
- // Create the RSA signer from an Identity object
- Identity identity("test_rsa.p12", PASSPHRASE, CryptoSuite::RSA_SHA256, 1024u,
- 30, "RSAVerifier");
-
- std::shared_ptr<Signer> signer = identity.getSigner();
+ // Create the RSA keys
+ std::shared_ptr<EVP_PKEY> privateKey(EVP_PKEY_new(), EVP_PKEY_free);
+ std::shared_ptr<EVP_PKEY> pubKey(EVP_PKEY_new(), EVP_PKEY_free);
+ RSA_ptr rsa(RSA_new(), ::RSA_free);
+ BN_ptr pub_exp(BN_new(), ::BN_free);
+
+ BN_set_word(pub_exp.get(), RSA_F4);
+ if (1 != RSA_generate_key_ex(rsa.get(), 2048u, pub_exp.get(), NULL))
+ throw errors::RuntimeException("can't generate the key");
+ RSA_ptr rsa_pub(RSAPublicKey_dup(rsa.get()), ::RSA_free);
+ RSA_ptr rsa_priv(RSAPrivateKey_dup(rsa.get()), ::RSA_free);
+ if (1 != EVP_PKEY_set1_RSA(pubKey.get(), rsa_pub.get()))
+ throw errors::RuntimeException("can't generate the key");
+ if (1 != EVP_PKEY_set1_RSA(privateKey.get(), rsa_priv.get()))
+ throw errors::RuntimeException("can't generate the key");
+ std::shared_ptr<AsymmetricSigner> signer = std::make_shared<AsymmetricSigner>(
+ CryptoSuite::RSA_SHA256, privateKey, pubKey);
// Create a content object
- core::ContentObject packet(HF_INET6_TCP_AH, signer->getSignatureSize());
+ core::ContentObject packet(HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ signer->getSignatureSize());
// Fill it with bogus data
uint8_t buffer[256] = {0};
@@ -68,64 +86,112 @@ TEST_F(AuthTest, AsymmetricRSA) {
// Create the RSA verifier
std::shared_ptr<Verifier> verifier =
- std::make_shared<AsymmetricVerifier>(identity.getCertificate());
+ std::make_shared<AsymmetricVerifier>(pubKey);
- EXPECT_EQ(packet.getFormat(), HF_INET6_TCP_AH);
+ EXPECT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_IPV6_TCP_AH);
EXPECT_EQ(signer->getHashType(), CryptoHashType::SHA256);
EXPECT_EQ(signer->getSuite(), CryptoSuite::RSA_SHA256);
- EXPECT_EQ(signer->getSignatureSize(), 128u);
+ EXPECT_EQ(signer->getSignatureSize(), 256u);
EXPECT_EQ(verifier->verifyPackets(&packet), VerificationPolicy::ACCEPT);
}
TEST_F(AuthTest, AsymmetricBufferRSA) {
- // Create the RSA signer from an Identity object
- Identity identity("test_rsa.p12", PASSPHRASE, CryptoSuite::RSA_SHA256, 1024u,
- 30, "RSAVerifier");
+ // Create the RSA keys
+ std::shared_ptr<EVP_PKEY> privateKey(EVP_PKEY_new(), EVP_PKEY_free);
+ std::shared_ptr<EVP_PKEY> pubKey(EVP_PKEY_new(), EVP_PKEY_free);
+ RSA_ptr rsa(RSA_new(), ::RSA_free);
+ BN_ptr pub_exp(BN_new(), ::BN_free);
+
+ BN_set_word(pub_exp.get(), RSA_F4);
+ if (1 != RSA_generate_key_ex(rsa.get(), 2048u, pub_exp.get(), NULL))
+ throw errors::RuntimeException("can't generate the key");
+ RSA_ptr rsa_pub(RSAPublicKey_dup(rsa.get()), ::RSA_free);
+ RSA_ptr rsa_priv(RSAPrivateKey_dup(rsa.get()), ::RSA_free);
+ if (1 != EVP_PKEY_set1_RSA(pubKey.get(), rsa_pub.get()))
+ throw errors::RuntimeException("can't generate the key");
+ if (1 != EVP_PKEY_set1_RSA(privateKey.get(), rsa_priv.get()))
+ throw errors::RuntimeException("can't generate the key");
+ std::shared_ptr<AsymmetricSigner> signer = std::make_shared<AsymmetricSigner>(
+ CryptoSuite::RSA_SHA256, privateKey, pubKey);
- std::shared_ptr<AsymmetricSigner> signer = identity.getSigner();
std::string payload = "bonjour";
std::vector<uint8_t> buffer(payload.begin(), payload.end());
signer->signBuffer(buffer);
- std::vector<uint8_t> sig = signer->getSignature();
+ utils::MemBuf::Ptr sig = signer->getSignature();
- std::shared_ptr<X509> cert = identity.getCertificate();
- AsymmetricVerifier verif(cert);
- bool res = verif.verifyBuffer(
- buffer, std::vector<uint8_t>(sig.data(), sig.data() + sig.size()),
- CryptoHashType::SHA256);
+ std::shared_ptr<AsymmetricVerifier> verif =
+ std::make_shared<AsymmetricVerifier>(pubKey);
+ bool res = verif->verifyBuffer(buffer, sig, CryptoSuite::RSA_SHA256);
EXPECT_EQ(res, true);
}
TEST_F(AuthTest, AsymmetricBufferDSA) {
- // Create the DSA signer from an Identity object
- Identity identity("test_dsa.p12", PASSPHRASE, CryptoSuite::DSA_SHA256, 1024u,
- 30, "DSAVerifier");
+ // Create the DSA keys
+
+ std::shared_ptr<EVP_PKEY> privateKey(EVP_PKEY_new(), EVP_PKEY_free);
+
+ DSA_ptr dsa(DSA_new(), ::DSA_free);
+ unsigned char buf[32];
+ if (RAND_bytes(buf, sizeof(buf)) != 1) {
+ throw errors::RuntimeException("can't generate the key");
+ }
+ if (DSA_generate_parameters_ex(dsa.get(), 1024u, buf, sizeof(buf), NULL, NULL,
+ NULL) != 1)
+ throw errors::RuntimeException("can't generate the key");
+ if (DSA_generate_key(dsa.get()) != 1)
+ throw errors::RuntimeException("can't generate the key");
+ if (EVP_PKEY_set1_DSA(privateKey.get(), dsa.get()) != 1)
+ throw errors::RuntimeException("can't generate the key");
+ if (1 != EVP_PKEY_set1_DSA(privateKey.get(), dsa.get()))
+ throw errors::RuntimeException("can't generate the key");
+
+ std::shared_ptr<X509> cert(X509_new(), ::X509_free);
+ X509_set_pubkey(cert.get(), privateKey.get());
+ std::shared_ptr<EVP_PKEY> pubKey(X509_get_pubkey(cert.get()), EVP_PKEY_free);
+ std::shared_ptr<AsymmetricSigner> signer = std::make_shared<AsymmetricSigner>(
+ CryptoSuite::DSA_SHA256, privateKey, pubKey);
- std::shared_ptr<AsymmetricSigner> signer = identity.getSigner();
std::string payload = "bonjour";
std::vector<uint8_t> buffer(payload.begin(), payload.end());
signer->signBuffer(buffer);
- std::vector<uint8_t> sig = signer->getSignature();
+ utils::MemBuf::Ptr sig = signer->getSignature();
- std::shared_ptr<X509> cert = identity.getCertificate();
- AsymmetricVerifier verif(cert);
- bool res = verif.verifyBuffer(
- buffer, std::vector<uint8_t>(sig.data(), sig.data() + sig.size()),
- CryptoHashType::SHA256);
+ std::shared_ptr<AsymmetricVerifier> verif =
+ std::make_shared<AsymmetricVerifier>(pubKey);
+ bool res = verif->verifyBuffer(buffer, sig, CryptoSuite::RSA_SHA256);
EXPECT_EQ(res, true);
}
TEST_F(AuthTest, AsymmetricVerifierDSA) {
- // Create the DSA signer from an Identity object
- Identity identity("test_dsa.p12", PASSPHRASE, CryptoSuite::DSA_SHA256, 1024u,
- 30, "DSAVerifier");
+ // Create the DSA keys
+ std::shared_ptr<EVP_PKEY> privateKey(EVP_PKEY_new(), EVP_PKEY_free);
- std::shared_ptr<Signer> signer = identity.getSigner();
+ DSA_ptr dsa(DSA_new(), ::DSA_free);
+ unsigned char buf[32];
+ if (RAND_bytes(buf, sizeof(buf)) != 1) {
+ throw errors::RuntimeException("can't generate the key");
+ }
+ if (DSA_generate_parameters_ex(dsa.get(), 1024u, buf, sizeof(buf), NULL, NULL,
+ NULL) != 1)
+ throw errors::RuntimeException("can't generate the key");
+ if (DSA_generate_key(dsa.get()) != 1)
+ throw errors::RuntimeException("can't generate the key");
+ if (EVP_PKEY_set1_DSA(privateKey.get(), dsa.get()) != 1)
+ throw errors::RuntimeException("can't generate the key");
+ if (1 != EVP_PKEY_set1_DSA(privateKey.get(), dsa.get()))
+ throw errors::RuntimeException("can't generate the key");
+
+ std::shared_ptr<X509> cert(X509_new(), ::X509_free);
+ X509_set_pubkey(cert.get(), privateKey.get());
+ std::shared_ptr<EVP_PKEY> pubKey(X509_get_pubkey(cert.get()), EVP_PKEY_free);
+ std::shared_ptr<AsymmetricSigner> signer = std::make_shared<AsymmetricSigner>(
+ CryptoSuite::DSA_SHA256, privateKey, pubKey);
// Create a content object
- core::ContentObject packet(HF_INET6_TCP_AH, signer->getSignatureSize());
+ core::ContentObject packet(HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ signer->getSignatureSize());
// Fill it with bogus data
uint8_t buffer[256] = {0};
@@ -134,51 +200,76 @@ TEST_F(AuthTest, AsymmetricVerifierDSA) {
// EXPECT_EQ(signer->getSignatureSize(), 256u);
signer->signPacket(&packet);
std::shared_ptr<Verifier> verifier =
- std::make_shared<AsymmetricVerifier>(identity.getCertificate());
+ std::make_shared<AsymmetricVerifier>(cert);
- EXPECT_EQ(packet.getFormat(), HF_INET6_TCP_AH);
+ EXPECT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_IPV6_TCP_AH);
EXPECT_EQ(signer->getHashType(), CryptoHashType::SHA256);
EXPECT_EQ(signer->getSuite(), CryptoSuite::DSA_SHA256);
EXPECT_EQ(verifier->verifyPackets(&packet), VerificationPolicy::ACCEPT);
}
TEST_F(AuthTest, AsymmetricBufferECDSA) {
- // Create the ECDSA signer from an Identity object
- Identity identity("test_ecdsa.p12", PASSPHRASE, CryptoSuite::ECDSA_SHA256,
- 256u, 30, "ECDSAVerifier");
+ // Create the ECDSA keys
+ std::shared_ptr<EVP_PKEY> privateKey(EVP_PKEY_new(), EVP_PKEY_free);
+ std::shared_ptr<EVP_PKEY> pubKey(EVP_PKEY_new(), EVP_PKEY_free);
+ EC_KEY_ptr ec_priv(EC_KEY_new_by_curve_name(NID_secp256k1), ::EC_KEY_free);
+ EC_KEY_ptr ec_pub(EC_KEY_new(), ::EC_KEY_free);
+ EC_KEY_set_asn1_flag(ec_priv.get(), OPENSSL_EC_NAMED_CURVE);
+ if (EC_KEY_generate_key(ec_priv.get()) == 0)
+ throw errors::RuntimeException("can't generate the ecdsa key");
+ if (1 != EVP_PKEY_set1_EC_KEY(privateKey.get(), ec_priv.get()))
+ throw errors::RuntimeException("can't generate the key");
+ EC_KEY_set_group(ec_pub.get(), EC_KEY_get0_group(ec_priv.get()));
+ EC_KEY_set_public_key(ec_pub.get(), EC_KEY_get0_public_key(ec_priv.get()));
+ if (1 != EVP_PKEY_set1_EC_KEY(pubKey.get(), ec_pub.get()))
+ throw errors::RuntimeException("can't generate the key");
+
+ std::shared_ptr<AsymmetricSigner> signer = std::make_shared<AsymmetricSigner>(
+ CryptoSuite::ECDSA_SHA256, privateKey, pubKey);
- std::shared_ptr<AsymmetricSigner> signer = identity.getSigner();
std::string payload = "bonjour";
std::vector<uint8_t> buffer(payload.begin(), payload.end());
signer->signBuffer(buffer);
- std::vector<uint8_t> sig = signer->getSignature();
+ utils::MemBuf::Ptr sig = signer->getSignature();
- std::shared_ptr<X509> cert = identity.getCertificate();
- AsymmetricVerifier verif(cert);
- bool res = verif.verifyBuffer(
- buffer, std::vector<uint8_t>(sig.data(), sig.data() + sig.size()),
- CryptoHashType::SHA256);
+ std::shared_ptr<AsymmetricVerifier> verif =
+ std::make_shared<AsymmetricVerifier>(pubKey);
+ bool res = verif->verifyBuffer(buffer, sig, CryptoSuite::RSA_SHA256);
EXPECT_EQ(res, true);
-}
+} // namespace auth
TEST_F(AuthTest, AsymmetricVerifierECDSA) {
- Identity identity("test_ecdsa.p12", PASSPHRASE, CryptoSuite::ECDSA_SHA256,
- 256u, 30, "ECDSAVerifier");
-
- std::shared_ptr<Signer> signer = identity.getSigner();
- std::shared_ptr<Verifier> verifier =
- std::make_shared<AsymmetricVerifier>(identity.getCertificate());
- // Create a content object
+ // Create the ECDSA keys
+ std::shared_ptr<EVP_PKEY> privateKey(EVP_PKEY_new(), EVP_PKEY_free);
+ std::shared_ptr<EVP_PKEY> pubKey(EVP_PKEY_new(), EVP_PKEY_free);
+ EC_KEY_ptr ec_priv(EC_KEY_new_by_curve_name(NID_secp256k1), ::EC_KEY_free);
+ EC_KEY_ptr ec_pub(EC_KEY_new(), ::EC_KEY_free);
+ EC_KEY_set_asn1_flag(ec_priv.get(), OPENSSL_EC_NAMED_CURVE);
+ if (EC_KEY_generate_key(ec_priv.get()) == 0)
+ throw errors::RuntimeException("can't generate the ecdsa key");
+ if (1 != EVP_PKEY_set1_EC_KEY(privateKey.get(), ec_priv.get()))
+ throw errors::RuntimeException("can't generate the key");
+ EC_KEY_set_group(ec_pub.get(), EC_KEY_get0_group(ec_priv.get()));
+ EC_KEY_set_public_key(ec_pub.get(), EC_KEY_get0_public_key(ec_priv.get()));
+ if (1 != EVP_PKEY_set1_EC_KEY(pubKey.get(), ec_pub.get()))
+ throw errors::RuntimeException("can't generate the key");
+
+ std::shared_ptr<AsymmetricSigner> signer = std::make_shared<AsymmetricSigner>(
+ CryptoSuite::ECDSA_SHA256, privateKey, pubKey);
+
+ std::shared_ptr<AsymmetricVerifier> verifier =
+ std::make_shared<AsymmetricVerifier>(pubKey);
for (int i = 0; i < 100; i++) {
- core::ContentObject packet(HF_INET6_TCP_AH, signer->getSignatureSize());
+ core::ContentObject packet(HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ signer->getSignatureSize());
// Fill it with bogus data
uint8_t buffer[256] = {0};
packet.appendPayload(buffer, 256);
signer->signPacket(&packet);
- EXPECT_EQ(packet.getFormat(), HF_INET6_TCP_AH);
+ EXPECT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_IPV6_TCP_AH);
EXPECT_EQ(signer->getHashType(), CryptoHashType::SHA256);
EXPECT_EQ(signer->getSuite(), CryptoSuite::ECDSA_SHA256);
EXPECT_EQ(verifier->verifyPackets(&packet), VerificationPolicy::ACCEPT);
@@ -191,16 +282,15 @@ TEST_F(AuthTest, HMACbuffer) {
std::make_shared<SymmetricSigner>(CryptoSuite::HMAC_SHA256, PASSPHRASE);
// Create a content object
- core::ContentObject packet(HF_INET6_TCP_AH, signer->getSignatureSize());
+ core::ContentObject packet(HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ signer->getSignatureSize());
std::string payload = "bonjour";
std::vector<uint8_t> buffer(payload.begin(), payload.end());
signer->signBuffer(buffer);
- std::vector<uint8_t> sig = signer->getSignature();
+ utils::MemBuf::Ptr sig = signer->getSignature();
SymmetricVerifier hmac(PASSPHRASE);
- bool res = hmac.verifyBuffer(
- buffer, std::vector<uint8_t>(sig.data(), sig.data() + sig.size()),
- CryptoHashType::SHA256);
+ bool res = hmac.verifyBuffer(buffer, sig, CryptoSuite::RSA_SHA256);
EXPECT_EQ(res, true);
}
@@ -210,7 +300,8 @@ TEST_F(AuthTest, HMACVerifier) {
std::make_shared<SymmetricSigner>(CryptoSuite::HMAC_SHA256, PASSPHRASE);
// Create a content object
- core::ContentObject packet(HF_INET6_TCP_AH, signer->getSignatureSize());
+ core::ContentObject packet(HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ signer->getSignatureSize());
// Fill it with bogus data
uint8_t buffer[256] = {0};
@@ -223,7 +314,7 @@ TEST_F(AuthTest, HMACVerifier) {
std::shared_ptr<Verifier> verifier =
std::make_shared<SymmetricVerifier>(PASSPHRASE);
- EXPECT_EQ(packet.getFormat(), HF_INET6_TCP_AH);
+ EXPECT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_IPV6_TCP_AH);
EXPECT_EQ(signer->getHashType(), CryptoHashType::SHA256);
EXPECT_EQ(signer->getSuite(), CryptoSuite::HMAC_SHA256);
EXPECT_EQ(signer->getSignatureSize(), 32u);
diff --git a/libtransport/src/test/test_consumer_producer_rtc.cc b/libtransport/src/test/test_consumer_producer_rtc.cc
index 8541a9e1a..d7378fc72 100644
--- a/libtransport/src/test/test_consumer_producer_rtc.cc
+++ b/libtransport/src/test/test_consumer_producer_rtc.cc
@@ -25,6 +25,17 @@ namespace interface {
namespace {
+class IoModuleInit {
+ public:
+ IoModuleInit() {
+ global_config::IoModuleConfiguration config;
+ config.name = "forwarder_module";
+ config.set();
+ }
+};
+
+static IoModuleInit init;
+
class ConsumerProducerTest : public ::testing::Test,
public ConsumerSocket::ReadCallback {
static const constexpr char prefix[] = "b001::1/128";
@@ -40,16 +51,12 @@ class ConsumerProducerTest : public ::testing::Test,
: io_service_(),
rtc_timer_(io_service_),
stop_timer_(io_service_),
- consumer_(TransportProtocolAlgorithms::RTC, io_service_),
- producer_(ProductionProtocolAlgorithms::RTC_PROD, io_service_),
+ consumer_(TransportProtocolAlgorithms::RTC),
+ producer_(ProductionProtocolAlgorithms::RTC_PROD),
producer_prefix_(prefix),
consumer_name_(name),
packets_sent_(0),
- packets_received_(0) {
- global_config::IoModuleConfiguration config;
- config.name = "loopback_module";
- config.set();
- }
+ packets_received_(0) {}
virtual ~ConsumerProducerTest() {
// You can do clean-up work that doesn't throw exceptions here.
@@ -69,6 +76,7 @@ class ConsumerProducerTest : public ::testing::Test,
consumer_.connect();
producer_.registerPrefix(producer_prefix_);
producer_.connect();
+ producer_.start();
}
virtual void TearDown() override {
@@ -116,19 +124,18 @@ class ConsumerProducerTest : public ::testing::Test,
*max_length = receive_buffer_size;
}
- void readDataAvailable(std::size_t length) noexcept override {}
+ void readDataAvailable(std::size_t length) noexcept override {
+ packets_received_++;
+ }
size_t maxBufferSize() const override { return receive_buffer_size; }
- void readError(const std::error_code ec) noexcept override {
- FAIL() << "Error while reading from RTC socket";
+ void readError(const std::error_code &ec) noexcept override {
io_service_.stop();
+ FAIL() << "Error while reading from RTC socket";
}
- void readSuccess(std::size_t total_size) noexcept override {
- packets_received_++;
- std::cout << "Received something" << std::endl;
- }
+ void readSuccess(std::size_t total_size) noexcept override {}
asio::io_service io_service_;
asio::steady_timer rtc_timer_;
@@ -149,7 +156,7 @@ const char ConsumerProducerTest::name[];
} // namespace
-TEST_F(ConsumerProducerTest, DISABLED_EndToEnd) {
+TEST_F(ConsumerProducerTest, EndToEnd) {
produceRTCPacket(std::error_code());
consumer_.consume(consumer_name_);
setStopTimer();
diff --git a/libtransport/src/test/test_core_manifest.cc b/libtransport/src/test/test_core_manifest.cc
index 93f4e87cb..99c71a56c 100644
--- a/libtransport/src/test/test_core_manifest.cc
+++ b/libtransport/src/test/test_core_manifest.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,10 +13,12 @@
* limitations under the License.
*/
+#include <core/manifest.h>
#include <core/manifest_format_fixed.h>
-#include <core/manifest_inline.h>
#include <gtest/gtest.h>
#include <hicn/transport/auth/crypto_hash.h>
+#include <hicn/transport/auth/signer.h>
+#include <hicn/transport/auth/verifier.h>
#include <test/packet_samples.h>
#include <climits>
@@ -31,10 +33,14 @@ namespace {
// The fixture for testing class Foo.
class ManifestTest : public ::testing::Test {
protected:
- using ContentObjectManifest = ManifestInline<ContentObject, Fixed>;
-
- ManifestTest() : name_("b001::123|321"), manifest1_(name_) {
- // You can do set-up work for each test here.
+ using ContentObjectManifest = Manifest<Fixed>;
+
+ ManifestTest()
+ : format_(HICN_PACKET_FORMAT_IPV6_TCP_AH),
+ name_("b001::123|321"),
+ signature_size_(0) {
+ manifest_ = ContentObjectManifest::createContentManifest(format_, name_,
+ signature_size_);
}
virtual ~ManifestTest() {
@@ -54,10 +60,11 @@ class ManifestTest : public ::testing::Test {
// before the destructor).
}
+ Packet::Format format_;
Name name_;
- ContentObjectManifest manifest1_;
-
- std::vector<uint8_t> manifest_payload = {
+ std::size_t signature_size_;
+ std::shared_ptr<ContentObjectManifest> manifest_;
+ std::vector<uint8_t> manifest_payload_ = {
0x11, 0x11, 0x01, 0x00, 0xb0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xde, 0xad // , 0x00, 0x00,
// 0x00, 0x45, 0xa3,
@@ -73,106 +80,200 @@ class ManifestTest : public ::testing::Test {
} // namespace
-TEST_F(ManifestTest, MoveConstructor) {
+TEST_F(ManifestTest, ManifestConstructor) {
// Create content object with manifest in payload
- ContentObject co(HF_INET6_TCP_AH, 128);
- co.appendPayload(&manifest_payload[0], manifest_payload.size());
- uint8_t buffer[256];
- co.appendPayload(buffer, 256);
+ ContentObject::Ptr co =
+ core::PacketManager<>::getInstance().getPacket<ContentObject>(
+ format_, signature_size_);
+ co->setName(name_);
+ co->appendPayload(manifest_payload_.data(), manifest_payload_.size());
+
+ uint8_t buffer[256] = {0};
+ co->appendPayload(buffer, 256);
// Copy packet payload
uint8_t packet[1500];
- auto length = co.getPayload()->length();
- std::memcpy(packet, co.getPayload()->data(), length);
+ auto length = co->getPayload()->length();
+ std::memcpy(packet, co->getPayload()->data(), length);
// Create manifest
- ContentObjectManifest m(std::move(co));
+ ContentObjectManifest manifest(co);
// Check manifest payload is exactly the same of content object
- ASSERT_EQ(length, m.getPayload()->length());
- auto ret = std::memcmp(packet, m.getPayload()->data(), length);
+ ASSERT_EQ(length, manifest.getPacket()->getPayload()->length());
+ auto ret =
+ std::memcmp(packet, manifest.getPacket()->getPayload()->data(), length);
ASSERT_EQ(ret, 0);
}
-TEST_F(ManifestTest, SetLastManifest) {
- manifest1_.clear();
-
- manifest1_.setFinalManifest(true);
- bool fcn = manifest1_.isFinalManifest();
-
- ASSERT_TRUE(fcn == true);
-}
-
TEST_F(ManifestTest, SetManifestType) {
- manifest1_.clear();
+ manifest_->Encoder::clear();
ManifestType type1 = ManifestType::INLINE_MANIFEST;
ManifestType type2 = ManifestType::FLIC_MANIFEST;
- manifest1_.setManifestType(type1);
- ManifestType type_returned1 = manifest1_.getManifestType();
+ manifest_->setType(type1);
+ ManifestType type_returned1 = manifest_->getType();
- manifest1_.clear();
+ manifest_->Encoder::clear();
- manifest1_.setManifestType(type2);
- ManifestType type_returned2 = manifest1_.getManifestType();
+ manifest_->setType(type2);
+ ManifestType type_returned2 = manifest_->getType();
ASSERT_EQ(type1, type_returned1);
ASSERT_EQ(type2, type_returned2);
}
+TEST_F(ManifestTest, SetMaxCapacity) {
+ manifest_->Encoder::clear();
+
+ uint8_t max_capacity1 = 0;
+ uint8_t max_capacity2 = 20;
+
+ manifest_->setMaxCapacity(max_capacity1);
+ uint8_t max_capacity_returned1 = manifest_->getMaxCapacity();
+
+ manifest_->Encoder::clear();
+
+ manifest_->setMaxCapacity(max_capacity2);
+ uint8_t max_capacity_returned2 = manifest_->getMaxCapacity();
+
+ ASSERT_EQ(max_capacity1, max_capacity_returned1);
+ ASSERT_EQ(max_capacity2, max_capacity_returned2);
+}
+
TEST_F(ManifestTest, SetHashAlgorithm) {
- manifest1_.clear();
+ manifest_->Encoder::clear();
- auth::CryptoHashType hash1 = auth::CryptoHashType::SHA512;
- auth::CryptoHashType hash2 = auth::CryptoHashType::BLAKE2B512;
- auth::CryptoHashType hash3 = auth::CryptoHashType::SHA256;
+ auth::CryptoHashType hash1 = auth::CryptoHashType::SHA256;
+ auth::CryptoHashType hash2 = auth::CryptoHashType::SHA512;
+ auth::CryptoHashType hash3 = auth::CryptoHashType::BLAKE2B512;
- manifest1_.setHashAlgorithm(hash1);
- auto type_returned1 = manifest1_.getHashAlgorithm();
+ manifest_->setHashAlgorithm(hash1);
+ auto type_returned1 = manifest_->getHashAlgorithm();
- manifest1_.clear();
+ manifest_->Encoder::clear();
- manifest1_.setHashAlgorithm(hash2);
- auto type_returned2 = manifest1_.getHashAlgorithm();
+ manifest_->setHashAlgorithm(hash2);
+ auto type_returned2 = manifest_->getHashAlgorithm();
- manifest1_.clear();
+ manifest_->Encoder::clear();
- manifest1_.setHashAlgorithm(hash3);
- auto type_returned3 = manifest1_.getHashAlgorithm();
+ manifest_->setHashAlgorithm(hash3);
+ auto type_returned3 = manifest_->getHashAlgorithm();
ASSERT_EQ(hash1, type_returned1);
ASSERT_EQ(hash2, type_returned2);
ASSERT_EQ(hash3, type_returned3);
}
-TEST_F(ManifestTest, SetNextSegmentCalculationStrategy) {
- manifest1_.clear();
-
- NextSegmentCalculationStrategy strategy1 =
- NextSegmentCalculationStrategy::INCREMENTAL;
+TEST_F(ManifestTest, SetLastManifest) {
+ manifest_->Encoder::clear();
- manifest1_.setNextSegmentCalculationStrategy(strategy1);
- NextSegmentCalculationStrategy type_returned1 =
- manifest1_.getNextSegmentCalculationStrategy();
+ manifest_->setIsLast(true);
+ bool is_last = manifest_->getIsLast();
- ASSERT_EQ(strategy1, type_returned1);
+ ASSERT_TRUE(is_last);
}
TEST_F(ManifestTest, SetBaseName) {
- manifest1_.clear();
+ manifest_->Encoder::clear();
core::Name base_name("b001::dead");
- manifest1_.setBaseName(base_name);
- core::Name ret_name = manifest1_.getBaseName();
+
+ manifest_->setBaseName(base_name);
+ core::Name ret_name = manifest_->getBaseName();
ASSERT_EQ(base_name, ret_name);
}
-TEST_F(ManifestTest, SetSuffixList) {
- manifest1_.clear();
+TEST_F(ManifestTest, setParamsBytestream) {
+ manifest_->Encoder::clear();
- core::Name base_name("b001::dead");
+ ParamsBytestream params{
+ .final_segment = 0x0a,
+ };
+
+ manifest_->setParamsBytestream(params);
+ auth::CryptoHash hash(auth::CryptoHashType::SHA256);
+ hash.computeDigest({0x01, 0x02, 0x03, 0x04});
+ manifest_->addEntry(1, hash);
+
+ manifest_->encode();
+ manifest_->decode();
+
+ auto transport_type_returned = manifest_->getTransportType();
+ auto params_returned = manifest_->getParamsBytestream();
+
+ ASSERT_EQ(interface::ProductionProtocolAlgorithms::BYTE_STREAM,
+ transport_type_returned);
+ ASSERT_EQ(params, params_returned);
+}
+
+TEST_F(ManifestTest, SetParamsRTC) {
+ manifest_->Encoder::clear();
+
+ ParamsRTC params{
+ .timestamp = 0x0a,
+ .prod_rate = 0x0b,
+ .prod_seg = 0x0c,
+ .fec_type = protocol::fec::FECType::UNKNOWN,
+ };
+
+ manifest_->setParamsRTC(params);
+ auth::CryptoHash hash(auth::CryptoHashType::SHA256);
+ hash.computeDigest({0x01, 0x02, 0x03, 0x04});
+ manifest_->addEntry(1, hash);
+
+ manifest_->encode();
+ manifest_->decode();
+
+ auto transport_type_returned = manifest_->getTransportType();
+ auto params_returned = manifest_->getParamsRTC();
+
+ ASSERT_EQ(interface::ProductionProtocolAlgorithms::RTC_PROD,
+ transport_type_returned);
+ ASSERT_EQ(params, params_returned);
+}
+
+TEST_F(ManifestTest, SignManifest) {
+ auto signer = std::make_shared<auth::SymmetricSigner>(
+ auth::CryptoSuite::HMAC_SHA256, "hunter2");
+ auto verifier = std::make_shared<auth::SymmetricVerifier>("hunter2");
+
+ // Instantiate manifest
+ uint8_t max_capacity = 30;
+ std::shared_ptr<ContentObjectManifest> manifest =
+ ContentObjectManifest::createContentManifest(
+ format_, name_, signer->getSignatureFieldSize());
+ manifest->setHeaders(ManifestType::INLINE_MANIFEST, max_capacity,
+ signer->getHashType(), false /* is_last */, name_);
+
+ // Add manifest entry
+ auth::CryptoHash hash(signer->getHashType());
+ hash.computeDigest({0x01, 0x02, 0x03, 0x04});
+ manifest->addEntry(1, hash);
+
+ // Encode manifest
+ manifest->encode();
+ auto manifest_co =
+ std::dynamic_pointer_cast<ContentObject>(manifest->getPacket());
+
+ // Sign manifest
+ signer->signPacket(manifest_co.get());
+
+ // Check size
+ ASSERT_EQ(manifest_co->payloadSize(), manifest->Encoder::manifestSize());
+ ASSERT_EQ(manifest_co->length(),
+ manifest_co->headerSize() + manifest_co->payloadSize());
+
+ // Verify manifest
+ auth::VerificationPolicy policy = verifier->verifyPackets(manifest_co.get());
+ ASSERT_EQ(auth::VerificationPolicy::ACCEPT, policy);
+}
+
+TEST_F(ManifestTest, SetSuffixList) {
+ manifest_->Encoder::clear();
using random_bytes_engine =
std::independent_bits_engine<std::default_random_engine, CHAR_BIT,
@@ -194,27 +295,13 @@ TEST_F(ManifestTest, SetSuffixList) {
entries[i] = std::make_pair(suffixes[i],
auth::CryptoHash(data[i].data(), data[i].size(),
auth::CryptoHashType::SHA256));
- manifest1_.addSuffixHash(entries[i].first, entries[i].second);
+ manifest_->addEntry(entries[i].first, entries[i].second);
}
- manifest1_.setBaseName(base_name);
-
- core::Name ret_name = manifest1_.getBaseName();
-
- // auto & hash_list = manifest1_.getSuffixHashList();
-
- // bool cond;
- // int i = 0;
-
- // for (auto & item : manifest1_.getSuffixList()) {
- // auto hash = manifest1_.getHash(suffixes[i]);
- // cond = auth::CryptoHash::compareBinaryDigest(hash,
- // entries[i].second.getDigest<uint8_t>().data(),
- // entries[i].second.getType());
- // ASSERT_TRUE(cond);
- // i++;
- // }
+ core::Name base_name("b001::dead");
+ manifest_->setBaseName(base_name);
+ core::Name ret_name = manifest_->getBaseName();
ASSERT_EQ(base_name, ret_name);
delete[] entries;
diff --git a/libtransport/src/test/test_event_thread.cc b/libtransport/src/test/test_event_thread.cc
index 549ff9c1a..324250717 100644
--- a/libtransport/src/test/test_event_thread.cc
+++ b/libtransport/src/test/test_event_thread.cc
@@ -14,6 +14,7 @@
*/
#include <gtest/gtest.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <hicn/transport/utils/event_thread.h>
#include <cmath>
@@ -48,7 +49,7 @@ class EventThreadTest : public ::testing::Test {
utils::EventThread event_thread_;
};
-double average(const unsigned long samples[], int size) {
+inline double average(const unsigned long samples[], int size) {
double sum = 0;
for (int i = 0; i < size; i++) {
@@ -58,7 +59,7 @@ double average(const unsigned long samples[], int size) {
return sum / size;
}
-double stdDeviation(const unsigned long samples[], int size) {
+inline double stdDeviation(const unsigned long samples[], int size) {
double avg = average(samples, size);
double var = 0;
@@ -72,26 +73,23 @@ double stdDeviation(const unsigned long samples[], int size) {
} // namespace
TEST_F(EventThreadTest, DISABLED_SchedulingDelay) {
- using namespace std::chrono;
- const size_t size = 1000000;
- std::vector<unsigned long> samples(size);
-
- for (unsigned int i = 0; i < size; i++) {
- auto t0 = steady_clock::now();
- event_thread_.add([t0, &samples, i]() {
- auto t1 = steady_clock::now();
- samples[i] = duration_cast<nanoseconds>(t1 - t0).count();
- });
- }
+ // using namespace std::chrono;
+ // const size_t size = 1000000;
+ // std::vector<unsigned long> samples(size);
+
+ // for (unsigned int i = 0; i < size; i++) {
+ // event_thread_.add([t0, &samples, i]() {
+ // });
+ // }
- event_thread_.stop();
+ // event_thread_.stop();
- auto avg = average(&samples[0], size);
- auto sd = stdDeviation(&samples[0], size);
- (void)sd;
+ // auto avg = average(&samples[0], size);
+ // auto sd = stdDeviation(&samples[0], size);
+ // (void)sd;
- // Expect average to be less that 1 ms
- EXPECT_LT(avg, 1000000);
+ // // Expect average to be less that 1 ms
+ // EXPECT_LT(avg, 1000000);
}
} // namespace utils
diff --git a/libtransport/src/test/test_fec_base_rely.cc b/libtransport/src/test/test_fec_base_rely.cc
new file mode 100644
index 000000000..2ee00e25e
--- /dev/null
+++ b/libtransport/src/test/test_fec_base_rely.cc
@@ -0,0 +1,454 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <hicn/transport/core/content_object.h>
+#include <hicn/transport/core/global_object_pool.h>
+#include <protocols/fec_base.h>
+#include <protocols/fec_utils.h>
+#include <protocols/rtc/rtc_consts.h>
+
+#include <algorithm>
+#include <iostream>
+#include <queue>
+#include <random>
+
+namespace transport {
+namespace protocol {
+
+class PacketFactory {
+ public:
+ PacketFactory(){};
+
+ ~PacketFactory(){};
+
+ std::shared_ptr<transport::core::ContentObject> createData(
+ core::Name &name, uint32_t suffix, uint32_t payload_size,
+ uint32_t payload_filler) {
+ auto &packet_manager = core::PacketManager<>::getInstance();
+
+ // create payload
+ auto buff = packet_manager.getMemBuf();
+ buff->append(payload_size);
+ std::fill(buff->writableData(), buff->writableTail(), payload_filler);
+
+ // create data packet
+ auto data = packet_manager.getPacket<transport::core::ContentObject>(
+ HICN_PACKET_FORMAT_IPV6_TCP, 0);
+ struct rtc::data_packet_t header;
+ header.setTimestamp(1000);
+ header.setProductionRate(1);
+ data->appendPayload((const uint8_t *)&header, rtc::DATA_HEADER_SIZE);
+ data->appendPayload(buff->data(), buff->length());
+ data->setName(name.setSuffix(suffix));
+ data->setLifetime(500);
+ data->setPathLabel(12);
+
+ return data;
+ }
+
+ std::shared_ptr<transport::core::ContentObject> createData(
+ core::Name &name, uint32_t suffix, fec::buffer payload) {
+ auto &packet_manager = core::PacketManager<>::getInstance();
+
+ auto data = packet_manager.getPacket<transport::core::ContentObject>(
+ HICN_PACKET_FORMAT_IPV6_TCP, 0);
+ struct rtc::data_packet_t header;
+ header.setTimestamp(1000);
+ header.setProductionRate(1);
+ data->appendPayload((const uint8_t *)&header, rtc::DATA_HEADER_SIZE);
+ data->appendPayload(payload->data(), payload->length());
+ data->setName(name.setSuffix(suffix));
+ data->setLifetime(500);
+ data->setPathLabel(12);
+
+ return data;
+ }
+};
+
+class Encoder {
+ public:
+ Encoder(std::string fec_str) {
+ fec_type_ = fec::FECUtils::fecTypeFromString(fec_str.c_str());
+ if (fec_type_ == fec::FECType::UNKNOWN)
+ std::cout << "x" << fec_str << "x" << std::endl;
+ encoder_ = fec::FECUtils::getEncoder(fec_type_, 1);
+ encoder_->setFECCallback(
+ std::bind(&Encoder::onFecPackets, this, std::placeholders::_1));
+ encoder_->setBufferCallback(
+ std::bind(&Encoder::getBuffer, this, std::placeholders::_1));
+ };
+
+ ~Encoder(){};
+
+ void onFecPackets(fec::BufferArray &packets) {
+ for (auto &packet : packets) {
+ fec_packets_.push(packet.getBuffer());
+ }
+ }
+
+ fec::buffer getBuffer(std::size_t size) {
+ auto ret = core::PacketManager<>::getInstance()
+ .getPacket<transport::core::ContentObject>(
+ HICN_PACKET_FORMAT_IPV6_TCP, 0);
+ ret->updateLength(rtc::DATA_HEADER_SIZE + size);
+ ret->append(rtc::DATA_HEADER_SIZE + size);
+ ret->trimStart(ret->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ return ret;
+ }
+
+ void onPacketProduced(core::ContentObject &content_object, uint32_t offset,
+ uint32_t metadata) {
+ encoder_->onPacketProduced(content_object, offset, metadata);
+ }
+
+ public:
+ std::queue<fec::buffer> fec_packets_;
+
+ private:
+ std::unique_ptr<fec::ProducerFEC> encoder_;
+ fec::FECType fec_type_;
+};
+
+class Decoder {
+ public:
+ Decoder(std::string fec_str) {
+ fec_type_ = fec::FECUtils::fecTypeFromString(fec_str.c_str());
+ decoder_ = fec::FECUtils::getDecoder(fec_type_, 1);
+ decoder_->setFECCallback(
+ std::bind(&Decoder::onFecPackets, this, std::placeholders::_1));
+ decoder_->setBufferCallback(fec::FECBase::BufferRequested(0));
+ };
+
+ ~Decoder(){};
+
+ void onFecPackets(fec::BufferArray &packets) {
+ for (auto &packet : packets) {
+ hicn_packet_dump(packet.getBuffer()->data(),
+ packet.getBuffer()->length());
+ recovered_packets_.push(packet.getBuffer());
+ }
+ }
+
+ void onPacketReceived(core::ContentObject &content_object, uint32_t offset) {
+ decoder_->onDataPacket(content_object, offset);
+ }
+
+ public:
+ std::queue<fec::buffer> recovered_packets_;
+
+ private:
+ std::unique_ptr<fec::ConsumerFEC> decoder_;
+ fec::FECType fec_type_;
+};
+
+TEST(FECtestRely, RelyTestInOrder1) {
+ // use Rely k = 2 N = 6
+ std::string fec_str = "Rely_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ // we cannot use the original data 1 to check it we recovered the packet
+ // correclty because Rely modifies the packet so here we create a copy
+ auto data1_copy = pf.createData(name, 1, 50, 1);
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // decode in order, data 1 is lost
+ decoder.onPacketReceived(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // check recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)2);
+ auto recovered = pf.createData(name, 1, decoder.recovered_packets_.front());
+
+ bool eq_len = (data1_copy->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data1_copy->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+TEST(FECtestRely, RelyTestInOrder2) {
+ // use Rely k = 2 N = 6
+ std::string fec_str = "Rely_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+ auto data2_copy = pf.createData(name, 2, 45, 2);
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // decode in order, data 2 is lost
+ decoder.onPacketReceived(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // check recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)2);
+ decoder.recovered_packets_.pop(); // pop data 1
+ auto recovered = pf.createData(name, 2, decoder.recovered_packets_.front());
+
+ bool eq_len = (data2_copy->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data2_copy->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+#if 0
+TEST(FECtestRely, RelyTestOutOfOrder1) {
+ //use Rely k = 2 N = 6
+ std::string fec_str = "Rely_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ auto data1_copy = pf.createData(name, 1, 50, 1);
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+
+ std::cout << "dump packet 2" << std::endl;
+ hicn_packet_dump(data2->data(), data2->length());
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ std::cout << "dump packet 2" << std::endl;
+ hicn_packet_dump(data2->data(), data2->length());
+
+ std::cout << "dump packet 3" << std::endl;
+ hicn_packet_dump(data3->data(), data3->length());
+
+ // decoding ooo packets. data 1 is lost.
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // get recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t) 2);
+ auto recovered = pf.createData(name, 1, decoder.recovered_packets_.front());
+ bool eq_len = (data1_copy->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if(eq_len)
+ ret = memcmp(data1_copy->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int) 0);
+}
+#endif
+
+TEST(FECtestRely, RelyTestOutOfOrder2) {
+ // use Rely k = 2 N = 6
+ std::string fec_str = "Rely_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+ auto data2_copy = pf.createData(name, 2, 45, 2);
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // decoding ooo packets. data 2 is lost.
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data1, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // get recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)2);
+ decoder.recovered_packets_.pop(); // pop data 1
+ auto recovered = pf.createData(name, 2, decoder.recovered_packets_.front());
+ bool eq_len = (data2_copy->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data2_copy->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+TEST(FECtestRely, RelyTestLargerBlocks) {
+ // use Rely k = 4 N = 7
+ std::string fec_str = "Rely_K4_N7";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+
+ auto data3 = pf.createData(name, 3, 12, 3);
+ auto data3_copy = pf.createData(name, 3, 12, 3);
+
+ auto data4 = pf.createData(name, 4, 20, 4);
+ auto data4_copy = pf.createData(name, 4, 20, 4);
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data4, data4->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data5 = pf.createData(name, 5, encoder.fec_packets_.front());
+ encoder.fec_packets_.pop(); // pop 5
+ encoder.fec_packets_.pop(); // pop 6
+ auto data7 = pf.createData(name, 7, encoder.fec_packets_.front());
+
+ // decoding packets: lost data 3 and data 4
+ decoder.onPacketReceived(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data7, data7->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data5, data5->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // get recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)4);
+ decoder.recovered_packets_.pop(); // pop data 1
+ decoder.recovered_packets_.pop(); // pop data 2
+ auto recovered3 = pf.createData(name, 3, decoder.recovered_packets_.front());
+ decoder.recovered_packets_.pop();
+ auto recovered4 = pf.createData(name, 4, decoder.recovered_packets_.front());
+
+ bool eq_len = (data3_copy->length() == recovered3->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data3_copy->data(), recovered3->data(), recovered3->length());
+ EXPECT_EQ(ret, (int)0);
+
+ eq_len = (data4_copy->length() == recovered4->length());
+ EXPECT_TRUE(eq_len);
+ ret = -1;
+ if (eq_len)
+ ret = memcmp(data4_copy->data(), recovered4->data(), recovered4->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+TEST(FECtestRely, RelyTestK1_N3) {
+ // use Rely k = 1 N = 3
+ std::string fec_str = "Rely_K1_N3";
+ Encoder encoder(fec_str);
+ Decoder decoder1(fec_str); // recv 2
+ Decoder decoder2(fec_str); // recv 3
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ auto data1_copy = pf.createData(name, 1, 50, 1);
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packets
+ EXPECT_TRUE(encoder.fec_packets_.size() == 2);
+ auto data2 = pf.createData(name, 2, encoder.fec_packets_.front());
+ encoder.fec_packets_.pop(); // pop 2
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // test1: recv data 2
+ decoder1.onPacketReceived(*data2,
+ data2->headerSize() + rtc::DATA_HEADER_SIZE);
+ EXPECT_EQ(decoder1.recovered_packets_.size(), (size_t)1);
+
+ auto recovered = pf.createData(name, 1, decoder1.recovered_packets_.front());
+ bool eq_len = (data1_copy->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data1_copy->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+
+ // test2: recv data 3
+ decoder2.onPacketReceived(*data3,
+ data3->headerSize() + rtc::DATA_HEADER_SIZE);
+ EXPECT_EQ(decoder2.recovered_packets_.size(), (size_t)1);
+
+ recovered = pf.createData(name, 1, decoder2.recovered_packets_.front());
+ eq_len = (data1_copy->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ ret = -1;
+ if (eq_len)
+ ret = memcmp(data1_copy->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+} // namespace protocol
+} // namespace transport
diff --git a/libtransport/src/test/test_fec_base_rs.cc b/libtransport/src/test/test_fec_base_rs.cc
new file mode 100644
index 000000000..549bb3f08
--- /dev/null
+++ b/libtransport/src/test/test_fec_base_rs.cc
@@ -0,0 +1,413 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <hicn/transport/core/content_object.h>
+#include <hicn/transport/core/global_object_pool.h>
+#include <protocols/fec_base.h>
+#include <protocols/fec_utils.h>
+#include <protocols/rtc/rtc_consts.h>
+
+#include <algorithm>
+#include <iostream>
+#include <queue>
+#include <random>
+
+namespace transport {
+namespace protocol {
+
+class PacketFactory {
+ public:
+ PacketFactory(){};
+
+ ~PacketFactory(){};
+
+ std::shared_ptr<transport::core::ContentObject> createData(
+ core::Name &name, uint32_t suffix, uint32_t payload_size,
+ uint32_t payload_filler) {
+ auto &packet_manager = core::PacketManager<>::getInstance();
+
+ // create payload
+ auto buff = packet_manager.getMemBuf();
+ buff->append(payload_size);
+ std::fill(buff->writableData(), buff->writableTail(), payload_filler);
+
+ // create data packet
+ auto data = packet_manager.getPacket<transport::core::ContentObject>(
+ HICN_PACKET_FORMAT_IPV6_TCP, 0);
+ struct rtc::data_packet_t header;
+ header.setTimestamp(1000);
+ header.setProductionRate(1);
+ data->appendPayload((const uint8_t *)&header, rtc::DATA_HEADER_SIZE);
+ data->appendPayload(buff->data(), buff->length());
+ data->setName(name.setSuffix(suffix));
+ data->setLifetime(500);
+ data->setPathLabel(12);
+
+ return data;
+ }
+
+ std::shared_ptr<transport::core::ContentObject> createData(
+ core::Name &name, uint32_t suffix, fec::buffer payload) {
+ auto &packet_manager = core::PacketManager<>::getInstance();
+
+ auto data = packet_manager.getPacket<transport::core::ContentObject>(
+ HICN_PACKET_FORMAT_IPV6_TCP, 0);
+ struct rtc::data_packet_t header;
+ header.setTimestamp(1000);
+ header.setProductionRate(1);
+ data->appendPayload((const uint8_t *)&header, rtc::DATA_HEADER_SIZE);
+ data->appendPayload(payload->data(), payload->length());
+ data->setName(name.setSuffix(suffix));
+ data->setLifetime(500);
+ data->setPathLabel(12);
+
+ return data;
+ }
+};
+
+class Encoder {
+ public:
+ Encoder(std::string fec_str) {
+ fec_type_ = fec::FECUtils::fecTypeFromString(fec_str.c_str());
+ encoder_ = fec::FECUtils::getEncoder(fec_type_, 1);
+ encoder_->setFECCallback(
+ std::bind(&Encoder::onFecPackets, this, std::placeholders::_1));
+ encoder_->setBufferCallback(
+ std::bind(&Encoder::getBuffer, this, std::placeholders::_1));
+ };
+
+ ~Encoder(){};
+
+ void onFecPackets(fec::BufferArray &packets) {
+ for (auto &packet : packets) {
+ fec_packets_.push(packet.getBuffer());
+ }
+ }
+
+ fec::buffer getBuffer(std::size_t size) {
+ auto ret = core::PacketManager<>::getInstance()
+ .getPacket<transport::core::ContentObject>(
+ HICN_PACKET_FORMAT_IPV6_TCP, 0);
+ ret->updateLength(rtc::DATA_HEADER_SIZE + size);
+ ret->append(rtc::DATA_HEADER_SIZE + size);
+ ret->trimStart(ret->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ return ret;
+ }
+
+ void onPacketProduced(core::ContentObject &content_object, uint32_t offset,
+ uint32_t metadata) {
+ encoder_->onPacketProduced(content_object, offset, metadata);
+ }
+
+ public:
+ std::queue<fec::buffer> fec_packets_;
+
+ private:
+ std::unique_ptr<fec::ProducerFEC> encoder_;
+ fec::FECType fec_type_;
+};
+
+class Decoder {
+ public:
+ Decoder(std::string fec_str) {
+ fec_type_ = fec::FECUtils::fecTypeFromString(fec_str.c_str());
+ decoder_ = fec::FECUtils::getDecoder(fec_type_, 1);
+ decoder_->setFECCallback(
+ std::bind(&Decoder::onFecPackets, this, std::placeholders::_1));
+ decoder_->setBufferCallback(fec::FECBase::BufferRequested(0));
+ };
+
+ ~Decoder(){};
+
+ void onFecPackets(fec::BufferArray &packets) {
+ for (auto &packet : packets) {
+ recovered_packets_.push(packet.getBuffer());
+ }
+ }
+
+ void onPacketReceived(core::ContentObject &content_object, uint32_t offset) {
+ decoder_->onDataPacket(content_object, offset);
+ }
+
+ public:
+ std::queue<fec::buffer> recovered_packets_;
+
+ private:
+ std::unique_ptr<fec::ConsumerFEC> decoder_;
+ fec::FECType fec_type_;
+};
+
+TEST(FECtestRS, RSTestInOrder1) {
+ // use RS k = 2 N = 6
+ std::string fec_str = "RS_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ const uint8_t *data1_ptr = data1->data();
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+ const uint8_t *data2_ptr = data2->data();
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // decode in order, data 1 is lost
+ decoder.onPacketReceived(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // test payload pointers off the original packets
+ EXPECT_EQ((const uint8_t *)data1->data(), data1_ptr);
+ EXPECT_EQ((const uint8_t *)data2->data(), data2_ptr);
+
+ // check recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)2);
+ auto recovered = pf.createData(name, 1, decoder.recovered_packets_.front());
+ bool eq_len = (data1->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data1->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+TEST(FECtestRS, RSTestInOrder2) {
+ // use RS k = 2 N = 6
+ std::string fec_str = "RS_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ const uint8_t *data1_ptr = data1->data();
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+ const uint8_t *data2_ptr = data2->data();
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // decode in order, data 2 is lost
+ decoder.onPacketReceived(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // test payload pointers off the original packets
+ EXPECT_EQ((const uint8_t *)data1->data(), data1_ptr);
+ EXPECT_EQ((const uint8_t *)data2->data(), data2_ptr);
+
+ // check recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)2);
+ decoder.recovered_packets_.pop(); // pop data packet 1
+ auto recovered = pf.createData(name, 2, decoder.recovered_packets_.front());
+
+ bool eq_len = (data2->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data2->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+TEST(FECtestRS, RSTestOutOfOrder1) {
+ // use RS k = 2 N = 6
+ std::string fec_str = "RS_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ const uint8_t *data1_ptr = data1->data();
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+ const uint8_t *data2_ptr = data2->data();
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // decoding ooo packets. data 1 is lost.
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // test payload pointers off the original packets
+ EXPECT_EQ((const uint8_t *)data1->data(), data1_ptr);
+ EXPECT_EQ((const uint8_t *)data2->data(), data2_ptr);
+
+ // get recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)2);
+ auto recovered = pf.createData(name, 1, decoder.recovered_packets_.front());
+ bool eq_len = (data1->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data1->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+TEST(FECtestRS, RSTestOutOfOrder2) {
+ // use RS k = 2 N = 6
+ std::string fec_str = "RS_K2_N6";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ const uint8_t *data1_ptr = data1->data();
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+ const uint8_t *data2_ptr = data2->data();
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data3 = pf.createData(name, 3, encoder.fec_packets_.front());
+
+ // decoding ooo packets. data 2 is lost.
+ decoder.onPacketReceived(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data1, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // test payload pointers off the original packets
+ EXPECT_EQ((const uint8_t *)data1->data(), data1_ptr);
+ EXPECT_EQ((const uint8_t *)data2->data(), data2_ptr);
+
+ // get recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)2);
+ decoder.recovered_packets_.pop(); // pop data packet 1
+
+ auto recovered = pf.createData(name, 2, decoder.recovered_packets_.front());
+ bool eq_len = (data2->length() == recovered->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data2->data(), recovered->data(), recovered->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+TEST(FECtestRS, RSTestLargerBlocks) {
+ // use RS k = 4 N = 7
+ std::string fec_str = "RS_K4_N7";
+ Encoder encoder(fec_str);
+ Decoder decoder(fec_str);
+
+ PacketFactory pf;
+
+ core::Name name("b001::");
+
+ auto data1 = pf.createData(name, 1, 50, 1);
+ const uint8_t *data1_ptr = data1->data();
+
+ auto data2 = pf.createData(name, 2, 45, 2);
+ const uint8_t *data2_ptr = data2->data();
+
+ auto data3 = pf.createData(name, 3, 12, 3);
+ const uint8_t *data3_ptr = data3->data();
+
+ auto data4 = pf.createData(name, 4, 20, 4);
+ const uint8_t *data4_ptr = data4->data();
+
+ // encoding
+ uint32_t metadata = static_cast<uint32_t>(data1->getPayloadType());
+ encoder.onPacketProduced(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data3, data3->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+ encoder.onPacketProduced(*data4, data4->headerSize() + rtc::DATA_HEADER_SIZE,
+ metadata);
+
+ // create fec packet
+ auto data5 = pf.createData(name, 5, encoder.fec_packets_.front());
+ encoder.fec_packets_.pop(); // pop 5
+ encoder.fec_packets_.pop(); // pop 6
+ auto data7 = pf.createData(name, 7, encoder.fec_packets_.front());
+
+ // decoding packets: lost data 3 and data 4
+ decoder.onPacketReceived(*data2, data2->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data7, data7->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data1, data1->headerSize() + rtc::DATA_HEADER_SIZE);
+ decoder.onPacketReceived(*data5, data5->headerSize() + rtc::DATA_HEADER_SIZE);
+
+ // test payload pointers off the original packets
+ EXPECT_EQ((const uint8_t *)data1->data(), data1_ptr);
+ EXPECT_EQ((const uint8_t *)data2->data(), data2_ptr);
+ EXPECT_EQ((const uint8_t *)data3->data(), data3_ptr);
+ EXPECT_EQ((const uint8_t *)data4->data(), data4_ptr);
+
+ // get recovered packet
+ EXPECT_EQ(decoder.recovered_packets_.size(), (size_t)4);
+ decoder.recovered_packets_.pop(); // pop data 1
+ decoder.recovered_packets_.pop(); // pop data 2
+ auto recovered3 = pf.createData(name, 3, decoder.recovered_packets_.front());
+ decoder.recovered_packets_.pop(); // pop data 3
+ auto recovered4 = pf.createData(name, 4, decoder.recovered_packets_.front());
+
+ bool eq_len = (data3->length() == recovered3->length());
+ EXPECT_TRUE(eq_len);
+ int ret = -1;
+ if (eq_len)
+ ret = memcmp(data3->data(), recovered3->data(), recovered3->length());
+ EXPECT_EQ(ret, (int)0);
+
+ eq_len = (data4->length() == recovered4->length());
+ EXPECT_TRUE(eq_len);
+ ret = -1;
+ if (eq_len)
+ ret = memcmp(data4->data(), recovered4->data(), recovered4->length());
+ EXPECT_EQ(ret, (int)0);
+}
+
+} // namespace protocol
+} // namespace transport
diff --git a/libtransport/src/test/test_fec_reedsolomon.cc b/libtransport/src/test/test_fec_reedsolomon.cc
index c7e10d111..0973069b1 100644
--- a/libtransport/src/test/test_fec_reedsolomon.cc
+++ b/libtransport/src/test/test_fec_reedsolomon.cc
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+#include <glog/logging.h>
#include <gtest/gtest.h>
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/global_object_pool.h>
@@ -30,28 +31,35 @@ double ReedSolomonTest(int k, int n, int seq_offset, int size) {
fec::RSEncoder encoder(k, n, seq_offset);
fec::RSDecoder decoder(k, n, seq_offset);
- std::vector<fec::buffer> tx_block(k);
- std::vector<fec::buffer> rx_block(k);
+ using BufferMetadata = std::pair<fec::buffer, uint32_t>;
+
+ std::vector<BufferMetadata> tx_block(k);
+ std::vector<BufferMetadata> rx_block(k);
int count = 0;
int run = 0;
+ // Setup random engine
+ std::random_device
+ rd; // Will be used to obtain a seed for the random number engine
+ std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
+ std::uniform_int_distribution<> dis(0, 99);
+
int iterations = 100;
auto &packet_manager = core::PacketManager<>::getInstance();
- encoder.setFECCallback(
- [&tx_block](
- std::vector<std::pair<uint32_t, fec::buffer>> &repair_packets) {
- for (auto &p : repair_packets) {
- // Append repair symbols to tx_block
- tx_block.emplace_back(std::move(p).second);
- }
- });
+ encoder.setFECCallback([&tx_block](fec::BufferArray &repair_packets) {
+ for (auto &p : repair_packets) {
+ // Append repair symbols to tx_block
+ tx_block.emplace_back(p.getBuffer(), p.getMetadata());
+ }
+ });
decoder.setFECCallback(
- [&](std::vector<std::pair<uint32_t, fec::buffer>> &source_packets) {
+ [&tx_block, &count, &k](fec::BufferArray &source_packets) {
for (int i = 0; i < k; i++) {
// Compare decoded source packets with original transmitted packets.
- if (*tx_block[i] != *source_packets[i].second) {
+ if (*tx_block[i].first != *source_packets[i].getBuffer() ||
+ tx_block[i].second != source_packets[i].getMetadata()) {
count++;
}
}
@@ -60,7 +68,7 @@ double ReedSolomonTest(int k, int n, int seq_offset, int size) {
do {
// Discard eventual packet appended in previous callback call
tx_block.erase(tx_block.begin() + k, tx_block.end());
- auto _seq_offet = seq_offset;
+ uint32_t _seq_offset = seq_offset;
// Initialization. Feed encoder with first k source packets
for (int i = 0; i < k; i++) {
@@ -69,45 +77,46 @@ double ReedSolomonTest(int k, int n, int seq_offset, int size) {
// Let's append a bit less than size, so that the FEC class will take care
// of filling the rest with zeros
- auto cur_size = size - (rand() % 100);
+ auto cur_size = size - dis(gen);
// Set payload, saving 2 bytes at the beginning of the buffer for encoding
// the length
packet->append(cur_size);
- packet->trimStart(2);
- std::generate(packet->writableData(), packet->writableTail(), rand);
std::fill(packet->writableData(), packet->writableTail(), i + 1);
// Set first byte of payload to seq_offset, to reorder at receiver side
- packet->writableData()[0] = uint8_t(_seq_offet++);
+ uint32_t *pkt_head = (uint32_t *)packet->writableData();
+ *pkt_head = _seq_offset++;
+
+ // Set a metadata integer
+ uint32_t metadata = dis(gen);
// Store packet in tx buffer and clear rx buffer
- tx_block[i] = std::move(packet);
+ tx_block[i] = std::make_pair(std::move(packet), metadata);
}
// Create the repair packets
for (auto &tx : tx_block) {
- encoder.consume(tx, tx->writableBuffer()[0]);
+ encoder.consume(tx.first, tx.first->writableBuffer()[0], 0, tx.second);
}
// Simulate transmission on lossy channel
- unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::vector<bool> losses(n, false);
for (int i = 0; i < n - k; i++) losses[i] = true;
int rxi = 0;
- std::shuffle(losses.begin(), losses.end(),
- std::default_random_engine(seed));
+ std::shuffle(losses.begin(), losses.end(), gen);
for (int i = 0; i < n && rxi < k; i++)
if (losses[i] == false) {
rx_block[rxi++] = tx_block[i];
if (i < k) {
// Source packet
- decoder.consumeSource(rx_block[rxi - 1],
- rx_block[rxi - 1]->data()[0]);
+ uint32_t index = *((uint32_t *)rx_block[rxi - 1].first->data());
+ decoder.consumeSource(rx_block[rxi - 1].first, index, 0,
+ rx_block[rxi - 1].second);
} else {
// Repair packet
- decoder.consumeRepair(rx_block[rxi - 1]);
+ decoder.consumeRepair(rx_block[rxi - 1].first);
}
}
@@ -126,6 +135,12 @@ void ReedSolomonMultiBlockTest(int n_sourceblocks) {
fec::RSEncoder encoder(k, n);
fec::RSDecoder decoder(k, n);
+ // Setup random engine
+ std::random_device
+ rd; // Will be used to obtain a seed for the random number engine
+ std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
+ std::uniform_int_distribution<> dis(0, 99);
+
auto &packet_manager = core::PacketManager<>::getInstance();
std::vector<std::pair<fec::buffer, uint32_t>> tx_block;
@@ -136,33 +151,39 @@ void ReedSolomonMultiBlockTest(int n_sourceblocks) {
// Receiver will receive packet for n_sourceblocks in a random order.
int total_packets = n * n_sourceblocks;
int tx_packets = k * n_sourceblocks;
- unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
- encoder.setFECCallback(
- [&](std::vector<std::pair<uint32_t, fec::buffer>> &repair_packets) {
- for (auto &p : repair_packets) {
- // Append repair symbols to tx_block
- tx_block.emplace_back(std::move(p.second), ++i);
- }
+ encoder.setFECCallback([&tx_block, &rx_block, &i, &n, &k,
+ &encoder](fec::BufferArray &repair_packets) {
+ for (auto &p : repair_packets) {
+ // Append repair symbols to tx_block
+ ++i;
+ tx_block.emplace_back(std::move(p.getBuffer()), i);
+ }
- EXPECT_EQ(tx_block.size(), size_t(n));
+ EXPECT_EQ(tx_block.size(), size_t(n));
- // Select k packets to send, including at least one symbol. We start
- // from the end for this reason.
- for (int j = n - 1; j > n - k - 1; j--) {
- rx_block.emplace_back(std::move(tx_block[j]));
- }
+ // Select k packets to send, including at least one symbol. We start
+ // from the end for this reason.
+ for (int j = n - 1; j > n - k - 1; j--) {
+ rx_block.emplace_back(std::move(tx_block[j]));
+ }
- // Clear tx block for next source block
- tx_block.clear();
- encoder.clear();
- });
+ // Clear tx block for next source block
+ tx_block.clear();
+ encoder.clear();
+ });
// The decode callback must be called exactly n_sourceblocks times
- decoder.setFECCallback(
- [&](std::vector<std::pair<uint32_t, fec::buffer>> &source_packets) {
- count++;
- });
+ decoder.setFECCallback([&count](fec::BufferArray &source_packets) {
+ // Check buffers
+ for (auto &packet : source_packets) {
+ auto packet_index = ((uint32_t *)packet.getBuffer()->writableData())[0];
+ EXPECT_EQ(packet_index, packet.getIndex())
+ << "Packet index: " << packet_index
+ << " -- FEC Index: " << packet.getIndex();
+ }
+ count++;
+ });
// Produce n * n_sourceblocks
// - ( k ) * n_sourceblocks source packets
@@ -173,7 +194,7 @@ void ReedSolomonMultiBlockTest(int n_sourceblocks) {
// Let's append a bit less than size, so that the FEC class will take care
// of filling the rest with zeros
- auto cur_size = size - (rand() % 100);
+ auto cur_size = size - dis(gen);
// Set payload, saving 2 bytes at the beginning of the buffer for encoding
// the length
@@ -182,7 +203,7 @@ void ReedSolomonMultiBlockTest(int n_sourceblocks) {
std::fill(packet->writableData(), packet->writableTail(), i + 1);
// Set first byte of payload to i, to reorder at receiver side
- packet->writableData()[0] = uint8_t(i);
+ ((uint32_t *)packet->writableData())[0] = uint32_t(i);
// Store packet in tx buffer
tx_block.emplace_back(packet, i);
@@ -195,8 +216,7 @@ void ReedSolomonMultiBlockTest(int n_sourceblocks) {
EXPECT_EQ(size_t(tx_packets), size_t(rx_block.size()));
// Lets shuffle the rx_block before starting feeding the decoder.
- std::shuffle(rx_block.begin(), rx_block.end(),
- std::default_random_engine(seed));
+ std::shuffle(rx_block.begin(), rx_block.end(), gen);
for (auto &p : rx_block) {
int index = p.second % n;
@@ -231,7 +251,7 @@ foreach_rs_fec_type
#undef _
TEST(ReedSolomonMultiBlockTest, RSMB10) {
- int blocks = 10;
+ int blocks = 1;
ReedSolomonMultiBlockTest(blocks);
}
diff --git a/libtransport/src/test/test_fec_rely_wrapper.cc b/libtransport/src/test/test_fec_rely_wrapper.cc
index c5b73f8d2..764e4dd2d 100644
--- a/libtransport/src/test/test_fec_rely_wrapper.cc
+++ b/libtransport/src/test/test_fec_rely_wrapper.cc
@@ -13,18 +13,23 @@
* limitations under the License.
*/
+#include <glog/logging.h>
#include <gtest/gtest.h>
#include <hicn/transport/core/global_object_pool.h>
+#include <hicn/transport/interfaces/socket_options_default_values.h>
#include <hicn/transport/utils/log.h>
#include <protocols/fec/rely.h>
#include <queue>
+#include <random>
namespace transport {
namespace protocol {
-std::string printMissing(
- const std::map<uint32_t, core::ContentObject::Ptr> &missing) {
+using SavedPacketMap =
+ std::map<uint32_t, std::pair<core::ContentObject::Ptr, uint32_t>>;
+
+std::string printMissing(const SavedPacketMap &missing) {
std::stringstream stream;
for (auto &[seq, packet] : missing) {
@@ -48,14 +53,15 @@ std::string printMissing(
* @param loss_rate The loss rate
*/
void testRelyEncoderDecoder(uint32_t k, uint32_t n, size_t max_packet_size,
- int64_t timeout, uint32_t max_iterations,
+ int64_t /* timeout */, uint32_t max_iterations,
int loss_rate) {
// Create 1 encoder and 1 decoder
fec::RelyEncoder _encoder(k, n);
fec::RelyDecoder _decoder(k, n);
// Seed the pseudo-random with known value to always get same loss pattern
- srand(k * n);
+ std::mt19937 gen(k *
+ n); // Standard mersenne_twister_engine seeded with rd();
// We will interact with rely encoder/decoder using the interface
fec::ProducerFEC &encoder = _encoder;
@@ -68,73 +74,78 @@ void testRelyEncoderDecoder(uint32_t k, uint32_t n, size_t max_packet_size,
auto &packet_manager = core::PacketManager<>::getInstance();
// Store packets to verify them in the decoder callback
- std::map<uint32_t, core::ContentObject::Ptr> saved_packets;
+ SavedPacketMap saved_packets;
// Save repair packets here in encoder callback
std::queue<fec::buffer> pending_repair_packets;
// Set callback called by encoder when a buffer is required.
- encoder.setBufferCallback([](std::size_t size) -> fec::buffer {
+ encoder.setBufferCallback([](std::size_t size) {
auto ret =
- core::PacketManager<>::getInstance().getPacket<core::ContentObject>();
+ core::PacketManager<>::getInstance().getPacket<core::ContentObject>(
+ transport::interface::default_values::packet_format);
ret->updateLength(size);
ret->append(size);
ret->trimStart(ret->headerSize());
- assert(ret->length() >= size);
+ DCHECK(ret->length() >= size);
return ret;
});
// Set callback to be called by encoder when repair packets are ready
- encoder.setFECCallback(
- [&](std::vector<std::pair<uint32_t, fec::buffer>> &packets) {
- // We must get n - k symbols
- EXPECT_EQ(packets.size(), n - k);
- // TRANSPORT_LOGD("Got %zu symbols", packets.size());
-
- // Save symbols in pending_repair_packets queue and increment iterations
- for (auto &packet : packets) {
- ++iterations;
- pending_repair_packets.push(packet.second);
- }
- });
+ encoder.setFECCallback([&iterations, &pending_repair_packets, &n,
+ &k](fec::BufferArray &packets) {
+ // We must get n - k symbols
+ EXPECT_EQ(packets.size(), n - k);
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Got " << packets.size() << " symbols";
+
+ // Save symbols in pending_repair_packets queue and increment iterations
+ for (auto &packet : packets) {
+ ++iterations;
+ pending_repair_packets.push(packet.getBuffer());
+ }
+ });
// Set callback to be called when decoder recover a packet
- decoder.setFECCallback(
- [&](std::vector<std::pair<uint32_t, fec::buffer>> &packets) {
- for (auto &packet : packets) {
- // TRANSPORT_LOGD("Recovering packet %u", packet.first);
+ decoder.setFECCallback([&saved_packets](fec::BufferArray &packets) {
+ for (auto &packet : packets) {
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Recovering packet " << packet.getIndex();
+
+ // Ensure recovered packet is in packets actually produced by encoder
+ auto original = saved_packets.find(packet.getIndex());
+ ASSERT_TRUE(original != saved_packets.end());
+ auto &original_packet = *original->second.first;
- // Ensure recovered packet is in packets actually produced by encoder
- auto original = saved_packets.find(packet.first);
- ASSERT_TRUE(original != saved_packets.end());
- auto &original_packet = *original->second;
+ // Remove additional headers at the beginning of the packet. This may
+ // change in the future.
+ original_packet.trimStart(60 /* Ip + TCP */ + 32 /* Rely header */ +
+ 4 /* Packet size */);
- // Remove additional headers at the beginning of the packet. This may
- // change in the future.
- original_packet.trimStart(60 /* Ip + TCP */ + 28 /* Rely header */ +
- 4 /* Packet size */);
+ // Recovered packet should be equal to the original one
+ EXPECT_TRUE(original_packet == *packet.getBuffer());
- // Recovered packet should be equal to the original one
- EXPECT_TRUE(original_packet == *packet.second);
+ // Also metadata should correspond
+ EXPECT_TRUE(original->second.second == packet.getMetadata());
- // Restore removed headers
- original_packet.prepend(60 + 28 + 4);
+ // Restore removed headers
+ original_packet.prepend(60 + 32 + 4);
- // Erase packet from saved packet list
- saved_packets.erase(original);
- }
- });
+ // Erase packet from saved packet list
+ saved_packets.erase(original);
+ }
+ });
// Send max_iterations packets from encoder to decoder
+ std::uniform_int_distribution<> dis(0, 1299);
while (iterations < max_iterations) {
// Create a payload, the size is between 50 and 1350 bytes.
- auto payload_size = 50 + (rand() % 1300);
+ auto payload_size = 50 + (dis(gen));
uint8_t payload[max_packet_size];
- std::generate(payload, payload + payload_size, rand);
+ std::generate(payload, payload + payload_size, gen);
// Get a packet from global pool and set name
- auto buffer = packet_manager.getPacket<core::ContentObject>();
+ auto buffer = packet_manager.getPacket<core::ContentObject>(
+ transport::interface::default_values::packet_format);
buffer->setName(core::Name("b001::abcd", iterations));
// Get offset
@@ -145,20 +156,23 @@ void testRelyEncoderDecoder(uint32_t k, uint32_t n, size_t max_packet_size,
// its own header).
buffer->appendPayload(payload, payload_size);
+ // Set an u32 metadata to pass altogether with the buffer
+ uint32_t metadata = dis(gen);
+
// Save packet in the saving_packets list
- // TRANSPORT_LOGD("Saving packet with index %lu", iterations);
- saved_packets.emplace(iterations, buffer);
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Saving packet with index " << iterations;
+ saved_packets.emplace(iterations, std::make_pair(buffer, metadata));
// Feed buffer into the encoder. This will eventually trigger a call to the
// FEC callback as soon as k packets are fed into the endocer.
- encoder.onPacketProduced(*buffer, offset);
+ encoder.onPacketProduced(*buffer, offset, metadata);
// Check returned packet. We calculate the difference in size and we compare
// only the part of the returned packet corresponding to the original
// payload. Rely should only add a header and should not modify the actual
// payload content. If it does it, this check will fail.
auto diff = buffer->length() - payload_size - offset;
- // TRANSPORT_LOGD("Difference is %zu", diff);
+ DLOG_IF(INFO, VLOG_IS_ON(3)) << "Difference is " << diff;
auto cmp =
std::memcmp(buffer->data() + offset + diff, payload, payload_size);
EXPECT_FALSE(cmp);
@@ -170,29 +184,33 @@ void testRelyEncoderDecoder(uint32_t k, uint32_t n, size_t max_packet_size,
// using future packets that are not created in the test. For this reason,
// we ensure the test ends without losses.
#define DROP_CONDITION(loss_rate, max_iterations) \
- (rand() % 100) >= loss_rate || iterations >= max_iterations * 0.9
+ (dis(gen)) >= loss_rate || iterations >= max_iterations * 0.9
// Handle the source packet to the decoder, id drop condition returns true
if (DROP_CONDITION(loss_rate, max_iterations)) {
// Pass packet to decoder
- // TRANSPORT_LOGD("Passing packet %u to decoder",
- // buffer->getName().getSuffix());
- decoder.onDataPacket(*buffer, offset);
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Passing packet " << buffer->getName().getSuffix()
+ << " to decoder";
+ decoder.onDataPacket(*buffer, offset, metadata);
} else {
- // TRANSPORT_LOGD("Packet %u, dropped", buffer->getName().getSuffix());
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Packet " << buffer->getName().getSuffix() << " dropped";
}
- // Check if previous call to encoder.consumer() generated repair packets,
+ // Check if previous call to encoder.consume() generated repair packets,
// and if yes, feed them to the decoder.
while (pending_repair_packets.size()) {
// Also repair packets can be lost
if (DROP_CONDITION(loss_rate, max_iterations)) {
auto &packet = pending_repair_packets.front();
- // TRANSPORT_LOGD("Passing packet %u to decoder", iterations);
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Passing packet " << iterations << " to decoder";
core::ContentObject &co = (core::ContentObject &)(*packet);
decoder.onDataPacket(co, 0);
} else {
- // TRANSPORT_LOGD("Packet (repair) %u dropped", iterations);
+ DLOG_IF(INFO, VLOG_IS_ON(3))
+ << "Packet (repair) " << iterations << " dropped";
}
// Remove packet from the queue
@@ -206,9 +224,6 @@ void testRelyEncoderDecoder(uint32_t k, uint32_t n, size_t max_packet_size,
// 0.001 residual losses
EXPECT_LE(saved_packets.size(), iterations * 0.001)
<< printMissing(saved_packets);
-
- // Reset seed
- srand(time(0));
}
/**
diff --git a/libtransport/src/test/test_fixed_block_allocator.cc b/libtransport/src/test/test_fixed_block_allocator.cc
new file mode 100644
index 000000000..33e048031
--- /dev/null
+++ b/libtransport/src/test/test_fixed_block_allocator.cc
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/core/global_object_pool.h>
+#include <hicn/transport/utils/event_thread.h>
+#include <hicn/transport/utils/fixed_block_allocator.h>
+
+namespace utils {
+
+class FixedBlockAllocatorTest : public ::testing::Test {
+ protected:
+ static inline const std::size_t default_size = 2048;
+ static inline const std::size_t default_n_buffer = 1024;
+
+ // Get fixed block allocator_ of 1024 buffers of size 2048 bytes
+ FixedBlockAllocatorTest()
+ : allocator_(
+ ::utils::FixedBlockAllocator<default_size,
+ default_n_buffer>::getInstance()) {
+ // You can do set-up work for each test here.
+ }
+
+ virtual ~FixedBlockAllocatorTest() {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void SetUp() {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ allocator_.reset();
+ }
+
+ virtual void TearDown() {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ allocator_.reset();
+ }
+
+ static bool pointerIsAligned(const void *pointer, size_t byte_count) {
+ // Sanity check
+ EXPECT_THAT(reinterpret_cast<std::uintptr_t>(pointer) &
+ (alignof(std::max_align_t) - 1),
+ testing::Eq(std::uintptr_t(0)));
+
+ return uintptr_t(pointer) % byte_count == 0;
+ }
+
+ ::utils::FixedBlockAllocator<default_size, default_n_buffer> &allocator_;
+};
+
+TEST_F(FixedBlockAllocatorTest, DefaultChecks) {
+ EXPECT_EQ(allocator_.blockSize(), default_size);
+ EXPECT_EQ(allocator_.blockCount(), default_n_buffer);
+ EXPECT_EQ(allocator_.allocations(), 0UL);
+ EXPECT_EQ(allocator_.deallocations(), 0UL);
+ EXPECT_EQ(allocator_.blocksInUse(), 0UL);
+
+ // Allocate one single block of memory
+ auto block = allocator_.allocateBlock();
+
+ ASSERT_THAT(block, testing::NotNull());
+
+ // Check statistics
+ EXPECT_EQ(allocator_.allocations(), 1UL);
+ EXPECT_EQ(allocator_.deallocations(), 0UL);
+ EXPECT_EQ(allocator_.blocksInUse(), 1UL);
+
+ // Deallocate it
+ allocator_.deallocateBlock(block);
+
+ // check statistics
+ EXPECT_EQ(allocator_.allocations(), 1UL);
+ EXPECT_EQ(allocator_.deallocations(), 1UL);
+ EXPECT_EQ(allocator_.blocksInUse(), 0UL);
+
+ // Test reset
+ allocator_.reset();
+
+ EXPECT_EQ(allocator_.blockSize(), default_size);
+ EXPECT_EQ(allocator_.blockCount(), default_n_buffer);
+ EXPECT_EQ(allocator_.allocations(), 0UL);
+ EXPECT_EQ(allocator_.deallocations(), 0UL);
+ EXPECT_EQ(allocator_.blocksInUse(), 0UL);
+}
+
+TEST_F(FixedBlockAllocatorTest, CheckMemoryIsReused) {
+ // Get one block. As it is the first one, it will be retrieved from the pool
+ auto block = allocator_.allocateBlock();
+
+ // Make sure block is valid
+ ASSERT_THAT(block, testing::NotNull());
+
+ // Release block
+ allocator_.deallocateBlock(block);
+
+ // Get same memory block again
+ auto block2 = allocator_.allocateBlock();
+
+ // Make sure memory is reused
+ ASSERT_EQ(block, block2);
+
+ // Get a third block
+ auto block3 = allocator_.allocateBlock();
+
+ // Make sure is different memory
+ ASSERT_NE(block2, block3);
+
+ // Deallocate both and check we get back the laso one
+ allocator_.deallocateBlock(block2);
+ allocator_.deallocateBlock(block3);
+
+ auto block4 = allocator_.allocateBlock();
+ ASSERT_EQ(block3, block4);
+}
+
+TEST_F(FixedBlockAllocatorTest, CheckMemoryIsContiguous) {
+ // Get one block. As it is the first one, it will be retrieved from the pool
+ auto block = reinterpret_cast<uint8_t *>(allocator_.allocateBlock());
+
+ // Make sure block is valid
+ ASSERT_THAT(block, testing::NotNull());
+
+ // Get another block
+ auto block2 = reinterpret_cast<uint8_t *>(allocator_.allocateBlock());
+
+ // Make sure block is valid
+ ASSERT_THAT(block2, testing::NotNull());
+
+ // Check the 2 blocks come from contiguous memory
+ ASSERT_THAT(std::size_t(block2 - block), testing::Eq(default_size));
+}
+
+TEST_F(FixedBlockAllocatorTest, CheckPoolExpansion) {
+ // Get all the blocks we setup when constructing the allocator
+ std::array<uint8_t *, default_n_buffer> blocks;
+ blocks[0] = reinterpret_cast<uint8_t *>(allocator_.allocateBlock());
+ for (std::size_t i = 1; i < default_n_buffer; i++) {
+ blocks[i] = reinterpret_cast<uint8_t *>(allocator_.allocateBlock());
+ ASSERT_THAT(std::size_t(blocks[i] - blocks[i - 1]),
+ testing::Eq(default_size));
+ }
+
+ ASSERT_THAT(allocator_.blockCount(), testing::Eq(default_n_buffer));
+
+ // We should have finished all the blocks belonging to first pool. Let's get
+ // one additional block
+ auto new_block = reinterpret_cast<uint8_t *>(allocator_.allocateBlock());
+
+ // Make sure the block count doubled its size
+ ASSERT_THAT(allocator_.blockCount(), testing::Eq(2 * default_n_buffer));
+
+ // Check the new block is not contiguous with respect last block in blocks
+ ASSERT_THAT(std::size_t(new_block - blocks[default_n_buffer - 1]),
+ testing::Ne(default_size));
+}
+
+TEST_F(FixedBlockAllocatorTest, CheckMemoryIsAligned) {
+ for (std::size_t i = 0; i < default_n_buffer; i++) {
+ auto block = reinterpret_cast<uint8_t *>(allocator_.allocateBlock());
+ ASSERT_THAT(pointerIsAligned(block, alignof(std::max_align_t)),
+ testing::IsTrue);
+ }
+}
+
+TEST_F(FixedBlockAllocatorTest, Multithreading) {
+ // Create 4 threads
+ utils::EventThread threads[4];
+ ::utils::FixedBlockAllocator<default_size, default_n_buffer>
+ *allocator_addresses[4] = {nullptr, nullptr, nullptr, nullptr};
+ int i = 0;
+ for (auto &t : threads) {
+ t.add([&allocator_addresses, i]() {
+ auto &allocator =
+ ::utils::FixedBlockAllocator<default_size,
+ default_n_buffer>::getInstance();
+ allocator_addresses[i] = &allocator;
+ });
+ i++;
+ }
+
+ // Stop threads
+ for (auto &t : threads) {
+ t.stop();
+ }
+
+ // Check the instance of allocator was different for each thread
+ for (int i = 0; i < 4; i++) {
+ for (int j = i + 1; j < 4; j++) {
+ ASSERT_NE(allocator_addresses[i], allocator_addresses[j]);
+ }
+ }
+}
+
+} // namespace utils \ No newline at end of file
diff --git a/libtransport/src/test/test_interest.cc b/libtransport/src/test/test_interest.cc
index 8853563b0..22dc01455 100644
--- a/libtransport/src/test/test_interest.cc
+++ b/libtransport/src/test/test_interest.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -30,7 +30,8 @@ namespace {
// The fixture for testing class Foo.
class InterestTest : public ::testing::Test {
protected:
- InterestTest() : name_("b001::123|321"), interest_() {
+ InterestTest()
+ : name_("b001::123|321"), interest_(HICN_PACKET_FORMAT_IPV6_TCP) {
// You can do set-up work for each test here.
}
@@ -63,15 +64,18 @@ class InterestTest : public ::testing::Test {
PAYLOAD};
};
-void testFormatConstructor(Packet::Format format = HF_UNSPEC) {
+void testFormatConstructor(
+ hicn_packet_format_t format = HICN_PACKET_FORMAT_NONE) {
try {
Interest interest(format, 0);
} catch (...) {
- FAIL() << "ERROR: Unexpected exception thrown for " << format;
+ char buf[MAXSZ_HICN_PACKET_FORMAT];
+ FAIL() << "ERROR: Unexpected exception thrown for " << buf;
}
}
-void testFormatConstructorException(Packet::Format format = HF_UNSPEC) {
+void testFormatConstructorException(
+ Packet::Format format = HICN_PACKET_FORMAT_NONE) {
try {
Interest interest(format, 0);
FAIL() << "We expected an exception here";
@@ -86,29 +90,29 @@ void testFormatConstructorException(Packet::Format format = HF_UNSPEC) {
TEST_F(InterestTest, ConstructorWithFormat) {
/**
- * Without arguments it should be format = HF_UNSPEC.
+ * Without arguments it should be format = HICN_PACKET_FORMAT_NONE.
* We expect a crash.
*/
- testFormatConstructor(Packet::Format::HF_INET_TCP);
- testFormatConstructor(Packet::Format::HF_INET6_TCP);
- testFormatConstructorException(Packet::Format::HF_INET_ICMP);
- testFormatConstructorException(Packet::Format::HF_INET6_ICMP);
- testFormatConstructor(Packet::Format::HF_INET_TCP_AH);
- testFormatConstructor(Packet::Format::HF_INET6_TCP_AH);
- testFormatConstructorException(Packet::Format::HF_INET_ICMP_AH);
- testFormatConstructorException(Packet::Format::HF_INET6_ICMP_AH);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV4_TCP);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV6_TCP);
+ testFormatConstructorException(HICN_PACKET_FORMAT_IPV4_ICMP);
+ testFormatConstructorException(HICN_PACKET_FORMAT_IPV6_ICMP);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV4_TCP_AH);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV6_TCP_AH);
+ testFormatConstructorException(HICN_PACKET_FORMAT_IPV4_ICMP_AH);
+ testFormatConstructorException(HICN_PACKET_FORMAT_IPV6_ICMP_AH);
}
TEST_F(InterestTest, ConstructorWithName) {
/**
- * Without arguments it should be format = HF_UNSPEC.
+ * Without arguments it should be format = HICN_PACKET_FORMAT_NONE.
* We expect a crash.
*/
Name n("b001::1|123");
try {
- Interest interest(n);
+ Interest interest(HICN_PACKET_FORMAT_IPV6_TCP, n);
} catch (...) {
FAIL() << "ERROR: Unexpected exception thrown";
}
@@ -116,8 +120,10 @@ TEST_F(InterestTest, ConstructorWithName) {
TEST_F(InterestTest, ConstructorWithBuffer) {
// Ensure buffer is interest
+#if 0
auto ret = Interest::isInterest(&buffer_[0]);
EXPECT_TRUE(ret);
+#endif
// Create interest from buffer
try {
@@ -175,28 +181,28 @@ TEST_F(InterestTest, SetGetLocator) {
// Get locator
auto l = interest.getLocator();
- ip_address_t address;
- ip_address_pton("b006::ab:cdab:cdef", &address);
- auto ret = !std::memcmp(&l, &address, sizeof(address));
+ hicn_ip_address_t address;
+ inet_pton(AF_INET6, "b006::ab:cdab:cdef", &address);
+ auto ret = !hicn_ip_address_cmp(&l, &address);
EXPECT_TRUE(ret);
// Set different locator
- ip_address_pton("2001::1234::4321::abcd::", &address);
+ inet_pton(AF_INET6, "2001::1234::4321::abcd::", &address);
// Set it on interest
interest.setLocator(address);
// Check it was set
l = interest.getLocator();
- ret = !std::memcmp(&l, &address, sizeof(address));
+ ret = !hicn_ip_address_cmp(&l, &address);
EXPECT_TRUE(ret);
}
TEST_F(InterestTest, SetGetLifetime) {
// Create interest from buffer
- Interest interest;
+ Interest interest(HICN_PACKET_FORMAT_IPV6_TCP);
const constexpr uint32_t lifetime = 10000;
// Set lifetime
@@ -211,7 +217,7 @@ TEST_F(InterestTest, SetGetLifetime) {
TEST_F(InterestTest, HasManifest) {
// Create interest from buffer
- Interest interest;
+ Interest interest(HICN_PACKET_FORMAT_IPV6_TCP);
// Let's expect anexception here
try {
@@ -232,7 +238,7 @@ TEST_F(InterestTest, HasManifest) {
TEST_F(InterestTest, AppendSuffixesEncodeAndIterate) {
// Create interest from buffer
- Interest interest;
+ Interest interest(HICN_PACKET_FORMAT_IPV6_TCP);
// Appenad some suffixes, with some duplicates
interest.appendSuffix(1);
@@ -250,13 +256,53 @@ TEST_F(InterestTest, AppendSuffixesEncodeAndIterate) {
interest.encodeSuffixes();
// Iterate over them. They should be in order and without repetitions
+
auto suffix = interest.firstSuffix();
auto n_suffixes = interest.numberOfSuffixes();
for (uint32_t i = 0; i < n_suffixes; i++) {
- EXPECT_EQ(*(suffix + i), (i + 1));
+ EXPECT_EQ(*(suffix + i), i);
}
}
+TEST_F(InterestTest, AppendSuffixesWithGaps) {
+ // Create interest from buffer
+ Interest interest(HICN_PACKET_FORMAT_IPV6_TCP);
+
+ // Appenad some suffixes, out of order and with gaps
+ interest.appendSuffix(6);
+ interest.appendSuffix(2);
+ interest.appendSuffix(5);
+ interest.appendSuffix(1);
+
+ // Encode them in wire format
+ interest.encodeSuffixes();
+ EXPECT_TRUE(interest.hasManifest());
+
+ // Check first suffix correctness
+ auto suffix = interest.firstSuffix();
+ EXPECT_NE(suffix, nullptr);
+ EXPECT_EQ(*suffix, 0U);
+
+ // Iterate over them. They should be in order and without repetitions
+ std::vector<uint32_t> expected = {interest.getName().getSuffix(), 1, 2, 5, 6};
+ EXPECT_EQ(interest.numberOfSuffixes(), expected.size());
+
+ for (uint32_t seq : expected) {
+ EXPECT_EQ(*suffix, seq);
+ suffix++;
+ }
+}
+
+TEST_F(InterestTest, InterestWithoutManifest) {
+ // Create interest without manifest
+ Interest interest(HICN_PACKET_FORMAT_IPV6_TCP);
+ auto suffix = interest.firstSuffix();
+
+ EXPECT_FALSE(interest.hasManifest());
+ EXPECT_EQ(interest.numberOfSuffixes(), 0U);
+ EXPECT_EQ(suffix, nullptr);
+}
+
} // namespace core
} // namespace transport
diff --git a/libtransport/src/test/test_memif_connector.cc b/libtransport/src/test/test_memif_connector.cc
new file mode 100644
index 000000000..40f4df927
--- /dev/null
+++ b/libtransport/src/test/test_memif_connector.cc
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <core/memif_connector.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/core/global_object_pool.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
+
+namespace transport {
+namespace core {
+
+namespace {
+
+using namespace std::placeholders;
+
+/**
+ * Master memif connector
+ */
+template <int Master>
+class Memif {
+ static inline std::size_t counter = 256;
+ static inline std::size_t total_packets = counter * 4096;
+ static inline std::size_t packet_size = 64;
+
+ public:
+ Memif(asio::io_service &io_service)
+ : io_service_(io_service),
+ memif_connector_(std::make_shared<MemifConnector>(
+ std::bind(&Memif::onPacketReceived, this, _1, _2, _3),
+ std::bind(&Memif::onPacketSent, this, _1, _2),
+ std::bind(&Memif::onClose, this, _1),
+ std::bind(&Memif::onReconnect, this, _1, _2), io_service_,
+ Master ? "test_master" : "test_slave")),
+ recv_counter_(0),
+ sent_counter_(0) {
+ memif_connector_->connect(0 /* Memif ID */, Master /* Is Master */,
+ "@hicntransport/test/memif");
+ }
+
+ void setStart() { t0_ = utils::SteadyTime::now(); }
+
+ void startTest() {
+ if constexpr (!Master) {
+ auto &packet_manager = core::PacketManager<>::getInstance();
+
+ // Send in busrt of 256 packet per time
+ for (std::size_t i = 0; i < counter; i++) {
+ auto packet = packet_manager.getMemBuf();
+ packet->append(packet_size);
+ memif_connector_->send(packet);
+ sent_counter_++;
+ }
+
+ if (sent_counter_ < total_packets) {
+ asio::post(io_service_, std::bind(&Memif::startTest, this));
+ }
+ } else {
+ setStart();
+ }
+ }
+
+ auto getRecvCounter() { return recv_counter_; }
+ auto getSentCounter() { return sent_counter_; }
+
+ private:
+ void onPacketReceived(Connector *c,
+ const std::vector<utils::MemBuf::Ptr> &buffers,
+ const std::error_code &ec) {
+ if constexpr (Master) {
+ recv_counter_ += buffers.size();
+ if (recv_counter_ == total_packets) {
+ auto t1 = utils::SteadyTime::now();
+ auto delta = utils::SteadyTime::getDurationUs(t0_, t1);
+ double rate = double(recv_counter_) * 1.0e6 / double(delta.count());
+ LOG(INFO) << "rate: " << rate << " packets/s";
+ io_service_.stop();
+ }
+ } else {
+ FAIL() << "Slave should not receive packets";
+ }
+ }
+ void onPacketSent(Connector *c, const std::error_code &ec) {}
+ void onClose(Connector *c) {}
+ void onReconnect(Connector *c, const std::error_code &ec) {}
+
+ private:
+ asio::io_service &io_service_;
+ std::shared_ptr<MemifConnector> memif_connector_;
+ std::size_t recv_counter_;
+ std::size_t sent_counter_;
+ utils::SteadyTime::TimePoint t0_;
+};
+
+using MemifMaster = Memif<1>;
+using MemifSlave = Memif<0>;
+
+} // namespace
+
+class MemifTest : public ::testing::Test {
+ protected:
+ MemifTest() : io_service_(), master_(io_service_), slave_(io_service_) {
+ // You can do set-up work for each test here.
+ }
+
+ void run() {
+ asio::post(io_service_, std::bind(&MemifSlave::startTest, &slave_));
+ master_.startTest();
+ io_service_.run();
+
+ EXPECT_THAT(master_.getRecvCounter(),
+ ::testing::Eq(slave_.getSentCounter()));
+ }
+
+ virtual ~MemifTest() {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void SetUp() {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ }
+
+ virtual void TearDown() {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ }
+
+ protected:
+ asio::io_service io_service_;
+ MemifMaster master_;
+ MemifSlave slave_;
+};
+
+TEST_F(MemifTest, Test) { run(); }
+} // namespace core
+} // namespace transport
diff --git a/libtransport/src/test/test_packet.cc b/libtransport/src/test/test_packet.cc
index 76ad352d6..f2f658932 100644
--- a/libtransport/src/test/test_packet.cc
+++ b/libtransport/src/test/test_packet.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,12 +16,15 @@
#include <gtest/gtest.h>
#include <hicn/transport/core/packet.h>
#include <hicn/transport/errors/not_implemented_exception.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <test/packet_samples.h>
#include <climits>
#include <random>
#include <vector>
+#include "../../lib/src/protocol.h"
+
namespace transport {
namespace core {
@@ -33,7 +36,7 @@ namespace core {
class PacketForTest : public Packet {
public:
template <typename... Args>
- PacketForTest(Args &&... args) : Packet(std::forward<Args>(args)...) {}
+ PacketForTest(Args &&...args) : Packet(std::forward<Args>(args)...) {}
virtual ~PacketForTest() {}
@@ -55,13 +58,13 @@ class PacketForTest : public Packet {
throw errors::NotImplementedException();
}
- void setLocator(const ip_address_t &locator) override {
+ void setLocator(const hicn_ip_address_t &locator) override {
throw errors::NotImplementedException();
}
void resetForHash() override { throw errors::NotImplementedException(); }
- ip_address_t getLocator() const override {
+ hicn_ip_address_t getLocator() const override {
throw errors::NotImplementedException();
}
};
@@ -72,8 +75,9 @@ class PacketTest : public ::testing::Test {
protected:
PacketTest()
: name_("b001::123|321"),
- packet(Packet::COPY_BUFFER, &raw_packets_[HF_INET6_TCP][0],
- raw_packets_[HF_INET6_TCP].size()) {
+ packet(Packet::COPY_BUFFER,
+ &raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size()) {
// You can do set-up work for each test here.
}
@@ -98,7 +102,7 @@ class PacketTest : public ::testing::Test {
PacketForTest packet;
- static std::map<Packet::Format, std::vector<uint8_t>> raw_packets_;
+ static std::map<uint32_t, std::vector<uint8_t>> raw_packets_;
std::vector<uint8_t> payload = {
0x11, 0x11, 0x01, 0x00, 0xb0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -114,8 +118,8 @@ class PacketTest : public ::testing::Test {
};
};
-std::map<Packet::Format, std::vector<uint8_t>> PacketTest::raw_packets_ = {
- {Packet::Format::HF_INET6_TCP,
+std::map<uint32_t, std::vector<uint8_t>> PacketTest::raw_packets_ = {
+ {HICN_PACKET_FORMAT_IPV6_TCP,
{// IPv6 src=b001::ab:cdab:cdef, dst=b002::ca
IPV6_HEADER(TCP_PROTO, 20 + PAYLOAD_SIZE),
@@ -124,7 +128,7 @@ std::map<Packet::Format, std::vector<uint8_t>> PacketTest::raw_packets_ = {
// Payload
PAYLOAD}},
- {Packet::Format::HF_INET_TCP,
+ {HICN_PACKET_FORMAT_IPV4_TCP,
{// IPv4 src=3.13.127.8, dst=192.168.1.92
IPV4_HEADER(TCP_PROTO, 20 + PAYLOAD_SIZE),
// TCP src=0x1234 dst=0x4321, seq=0x0001
@@ -132,64 +136,68 @@ std::map<Packet::Format, std::vector<uint8_t>> PacketTest::raw_packets_ = {
// Other
PAYLOAD}},
- {Packet::Format::HF_INET_ICMP,
+ {HICN_PACKET_FORMAT_IPV4_ICMP,
{// IPv4 src=3.13.127.8, dst=192.168.1.92
IPV4_HEADER(ICMP_PROTO, 64),
// ICMP echo request
ICMP_ECHO_REQUEST}},
- {Packet::Format::HF_INET6_ICMP,
+ {HICN_PACKET_FORMAT_IPV6_ICMP,
{// IPv6 src=b001::ab:cdab:cdef, dst=b002::ca
IPV6_HEADER(ICMP6_PROTO, 60),
// ICMP6 echo request
ICMP6_ECHO_REQUEST}},
- {Packet::Format::HF_INET6_TCP_AH,
+ {HICN_PACKET_FORMAT_IPV6_TCP_AH,
{// IPv6 src=b001::ab:cdab:cdef, dst=b002::ca
IPV6_HEADER(TCP_PROTO, 20 + 44 + 128),
// ICMP6 echo request
TCP_HEADER(0x18),
// hICN AH header
- AH_HEADER}},
+ AH_HEADER, SIGNATURE}},
- {Packet::Format::HF_INET_TCP_AH,
+ {HICN_PACKET_FORMAT_IPV4_TCP_AH,
{// IPv6 src=b001::ab:cdab:cdef, dst=b002::ca
IPV4_HEADER(TCP_PROTO, 20 + 44 + 128),
// ICMP6 echo request
TCP_HEADER(0x18),
// hICN AH header
- AH_HEADER}},
+ AH_HEADER, SIGNATURE}},
// XXX No flag defined in ICMP header to signal AH header.
- {Packet::Format::HF_INET_ICMP_AH,
+ {HICN_PACKET_FORMAT_IPV4_ICMP_AH,
{// IPv6 src=b001::ab:cdab:cdef, dst=b002::ca
IPV4_HEADER(ICMP_PROTO, 64 + 44),
// ICMP6 echo request
ICMP_ECHO_REQUEST,
// hICN AH header
- AH_HEADER}},
+ AH_HEADER, SIGNATURE}},
- {Packet::Format::HF_INET6_ICMP_AH,
+ {HICN_PACKET_FORMAT_IPV6_ICMP_AH,
{// IPv6 src=b001::ab:cdab:cdef, dst=b002::ca
IPV6_HEADER(ICMP6_PROTO, 60 + 44),
// ICMP6 echo request
ICMP6_ECHO_REQUEST,
// hICN AH header
- AH_HEADER}},
+ AH_HEADER, SIGNATURE}},
};
-void testFormatConstructor(Packet::Format format = HF_UNSPEC) {
+void testFormatConstructor(Packet::Format format = HICN_PACKET_FORMAT_NONE) {
try {
- PacketForTest packet(format);
+ PacketForTest packet(HICN_PACKET_TYPE_INTEREST, format);
} catch (...) {
- FAIL() << "ERROR: Unexpected exception thrown for " << format;
+ char buf[MAXSZ_HICN_PACKET_FORMAT];
+ int rc = hicn_packet_format_snprintf(buf, MAXSZ_HICN_PACKET_FORMAT, format);
+ if (rc < 0 || rc >= MAXSZ_HICN_PACKET_FORMAT)
+ snprintf(buf, MAXSZ_HICN_PACKET_FORMAT, "%s", "(error");
+ FAIL() << "ERROR: Unexpected exception thrown for " << buf;
}
}
void testFormatAndAdditionalHeaderConstructor(Packet::Format format,
std::size_t additional_header) {
- PacketForTest packet(format, additional_header);
+ PacketForTest packet(HICN_PACKET_TYPE_INTEREST, format, additional_header);
// Packet length should be the one of the normal header + the
// additional_header
@@ -228,17 +236,19 @@ void testRawBufferConstructor(std::vector<uint8_t> packet,
PacketForTest p(Packet::WRAP_BUFFER, &packet[0], packet.size(),
packet.size());
- // Format should fallback to HF_UNSPEC
- EXPECT_EQ(p.getFormat(), HF_UNSPEC);
+ // Format should fallback to HICN_PACKET_FORMAT_NONE
+ EXPECT_EQ(p.getFormat(), HICN_PACKET_FORMAT_NONE);
+ } catch (errors::MalformedPacketException &exc) {
+ // Ok right exception
} catch (...) {
FAIL() << "ERROR: Unexpected exception thrown.";
}
}
-void getHeaderSizeFromBuffer(Packet::Format format,
- std::vector<uint8_t> &packet,
+void getHeaderSizeFromBuffer(std::vector<uint8_t> &packet,
std::size_t expected) {
- auto header_size = PacketForTest::getHeaderSizeFromBuffer(format, &packet[0]);
+ auto header_size =
+ PacketForTest::getHeaderSizeFromBuffer(&packet[0], packet.size());
EXPECT_EQ(header_size, expected);
}
@@ -247,11 +257,10 @@ void getHeaderSizeFromFormat(Packet::Format format, std::size_t expected) {
EXPECT_EQ(header_size, expected);
}
-void getPayloadSizeFromBuffer(Packet::Format format,
- std::vector<uint8_t> &packet,
+void getPayloadSizeFromBuffer(std::vector<uint8_t> &packet,
std::size_t expected) {
auto payload_size =
- PacketForTest::getPayloadSizeFromBuffer(format, &packet[0]);
+ PacketForTest::getPayloadSizeFromBuffer(&packet[0], packet.size());
EXPECT_EQ(payload_size, expected);
}
@@ -274,137 +283,148 @@ void testGetFormat(Packet::Format expected, const Packet &packet) {
} // namespace
TEST_F(PacketTest, ConstructorWithFormat) {
- testFormatConstructor(Packet::Format::HF_INET_TCP);
- testFormatConstructor(Packet::Format::HF_INET6_TCP);
- testFormatConstructor(Packet::Format::HF_INET_ICMP);
- testFormatConstructor(Packet::Format::HF_INET6_ICMP);
- testFormatConstructor(Packet::Format::HF_INET_TCP_AH);
- testFormatConstructor(Packet::Format::HF_INET6_TCP_AH);
- testFormatConstructor(Packet::Format::HF_INET_ICMP_AH);
- testFormatConstructor(Packet::Format::HF_INET6_ICMP_AH);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV4_TCP);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV6_TCP);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV4_ICMP);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV6_ICMP);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV4_TCP_AH);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV6_TCP_AH);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV4_ICMP_AH);
+ testFormatConstructor(HICN_PACKET_FORMAT_IPV6_ICMP_AH);
}
TEST_F(PacketTest, ConstructorWithFormatAndAdditionalHeader) {
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET_TCP, 123);
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET6_TCP, 360);
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET_ICMP, 21);
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET6_ICMP, 444);
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET_TCP_AH, 555);
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET6_TCP_AH,
- 321);
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET_ICMP_AH,
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV4_TCP, 123);
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV6_TCP, 360);
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV4_ICMP, 21);
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV6_ICMP, 444);
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV4_TCP_AH, 555);
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV6_TCP_AH, 321);
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV4_ICMP_AH,
123);
- testFormatAndAdditionalHeaderConstructor(Packet::Format::HF_INET6_ICMP_AH,
- 44);
+ testFormatAndAdditionalHeaderConstructor(HICN_PACKET_FORMAT_IPV6_ICMP_AH, 44);
}
TEST_F(PacketTest, ConstructorWithNew) {
- auto &_packet = raw_packets_[HF_INET6_TCP];
+ auto &_packet = raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP];
auto packet_ptr = new PacketForTest(Packet::WRAP_BUFFER, &_packet[0],
_packet.size(), _packet.size());
- (void)packet_ptr;
+ delete packet_ptr;
}
TEST_F(PacketTest, ConstructorWithRawBufferInet6Tcp) {
- auto format = Packet::Format::HF_INET6_TCP;
+ auto format = HICN_PACKET_FORMAT_IPV6_TCP;
testRawBufferConstructor(raw_packets_[format], format);
}
TEST_F(PacketTest, ConstructorWithRawBufferInetTcp) {
- auto format = Packet::Format::HF_INET_TCP;
+ auto format = HICN_PACKET_FORMAT_IPV4_TCP;
testRawBufferConstructor(raw_packets_[format], format);
}
TEST_F(PacketTest, ConstructorWithRawBufferInetIcmp) {
- auto format = Packet::Format::HF_INET_ICMP;
+ auto format = HICN_PACKET_FORMAT_IPV4_ICMP;
testRawBufferConstructor(raw_packets_[format], format);
}
TEST_F(PacketTest, ConstructorWithRawBufferInet6Icmp) {
- auto format = Packet::Format::HF_INET6_ICMP;
+ auto format = HICN_PACKET_FORMAT_IPV6_ICMP;
testRawBufferConstructor(raw_packets_[format], format);
}
TEST_F(PacketTest, ConstructorWithRawBufferInet6TcpAh) {
- auto format = Packet::Format::HF_INET6_TCP_AH;
+ auto format = HICN_PACKET_FORMAT_IPV6_TCP_AH;
testRawBufferConstructor(raw_packets_[format], format);
}
TEST_F(PacketTest, ConstructorWithRawBufferInetTcpAh) {
- auto format = Packet::Format::HF_INET_TCP_AH;
+ auto format = HICN_PACKET_FORMAT_IPV4_TCP_AH;
testRawBufferConstructor(raw_packets_[format], format);
}
TEST_F(PacketTest, MoveConstructor) {
- PacketForTest p0(Packet::Format::HF_INET6_TCP);
+ PacketForTest p0(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP);
PacketForTest p1(std::move(p0));
- EXPECT_EQ(p0.getFormat(), Packet::Format::HF_UNSPEC);
- EXPECT_EQ(p1.getFormat(), Packet::Format::HF_INET6_TCP);
+ EXPECT_EQ(p0.getFormat(), HICN_PACKET_FORMAT_NONE);
+ EXPECT_EQ(p1.getFormat(), HICN_PACKET_FORMAT_IPV6_TCP);
}
TEST_F(PacketTest, TestGetHeaderSizeFromBuffer) {
- getHeaderSizeFromBuffer(HF_INET6_TCP, raw_packets_[HF_INET6_TCP],
- HICN_V6_TCP_HDRLEN);
- getHeaderSizeFromBuffer(HF_INET_TCP, raw_packets_[HF_INET_TCP],
- HICN_V4_TCP_HDRLEN);
- getHeaderSizeFromBuffer(HF_INET6_ICMP, raw_packets_[HF_INET6_ICMP],
+ getHeaderSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP],
+ IPV6_HDRLEN + TCP_HDRLEN);
+ getHeaderSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP],
+ IPV4_HDRLEN + TCP_HDRLEN);
+ getHeaderSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP],
IPV6_HDRLEN + 4);
- getHeaderSizeFromBuffer(HF_INET_ICMP, raw_packets_[HF_INET_ICMP],
+ getHeaderSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV4_ICMP],
IPV4_HDRLEN + 4);
- getHeaderSizeFromBuffer(HF_INET6_TCP_AH, raw_packets_[HF_INET6_TCP_AH],
- HICN_V6_TCP_AH_HDRLEN + 128);
- getHeaderSizeFromBuffer(HF_INET_TCP_AH, raw_packets_[HF_INET_TCP_AH],
- HICN_V4_TCP_AH_HDRLEN + 128);
+ getHeaderSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP_AH],
+ IPV6_HDRLEN + TCP_HDRLEN + AH_HDRLEN + 128);
+ getHeaderSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP_AH],
+ IPV4_HDRLEN + TCP_HDRLEN + AH_HDRLEN + 128);
}
TEST_F(PacketTest, TestGetHeaderSizeFromFormat) {
- getHeaderSizeFromFormat(HF_INET6_TCP, HICN_V6_TCP_HDRLEN);
- getHeaderSizeFromFormat(HF_INET_TCP, HICN_V4_TCP_HDRLEN);
- getHeaderSizeFromFormat(HF_INET6_ICMP, IPV6_HDRLEN + 4);
- getHeaderSizeFromFormat(HF_INET_ICMP, IPV4_HDRLEN + 4);
- getHeaderSizeFromFormat(HF_INET6_TCP_AH, HICN_V6_TCP_AH_HDRLEN);
- getHeaderSizeFromFormat(HF_INET_TCP_AH, HICN_V4_TCP_AH_HDRLEN);
+ getHeaderSizeFromFormat(HICN_PACKET_FORMAT_IPV6_TCP,
+ IPV6_HDRLEN + TCP_HDRLEN);
+ getHeaderSizeFromFormat(HICN_PACKET_FORMAT_IPV4_TCP,
+ IPV4_HDRLEN + TCP_HDRLEN);
+ getHeaderSizeFromFormat(HICN_PACKET_FORMAT_IPV6_ICMP, IPV6_HDRLEN + 4);
+ getHeaderSizeFromFormat(HICN_PACKET_FORMAT_IPV4_ICMP, IPV4_HDRLEN + 4);
+ getHeaderSizeFromFormat(HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ IPV6_HDRLEN + TCP_HDRLEN + AH_HDRLEN);
+ getHeaderSizeFromFormat(HICN_PACKET_FORMAT_IPV4_TCP_AH,
+ IPV4_HDRLEN + TCP_HDRLEN + AH_HDRLEN);
}
TEST_F(PacketTest, TestGetPayloadSizeFromBuffer) {
- getPayloadSizeFromBuffer(HF_INET6_TCP, raw_packets_[HF_INET6_TCP], 12);
- getPayloadSizeFromBuffer(HF_INET_TCP, raw_packets_[HF_INET_TCP], 12);
- getPayloadSizeFromBuffer(HF_INET6_ICMP, raw_packets_[HF_INET6_ICMP], 56);
- getPayloadSizeFromBuffer(HF_INET_ICMP, raw_packets_[HF_INET_ICMP], 60);
- getPayloadSizeFromBuffer(HF_INET6_TCP_AH, raw_packets_[HF_INET6_TCP_AH], 0);
- getPayloadSizeFromBuffer(HF_INET_TCP_AH, raw_packets_[HF_INET_TCP_AH], 0);
+ getPayloadSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP], 12);
+ getPayloadSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP], 12);
+ getPayloadSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP], 56);
+ getPayloadSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV4_ICMP], 60);
+ getPayloadSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP_AH], 0);
+ getPayloadSizeFromBuffer(raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP_AH], 0);
}
+#if 0
TEST_F(PacketTest, TestIsInterest) {
- auto ret = PacketForTest::isInterest(&raw_packets_[HF_INET6_TCP][0]);
+ auto ret = PacketForTest::isInterest(&raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP][0]);
EXPECT_TRUE(ret);
}
+#endif
TEST_F(PacketTest, TestGetFormatFromBuffer) {
- getFormatFromBuffer(HF_INET6_TCP, raw_packets_[HF_INET6_TCP]);
- getFormatFromBuffer(HF_INET_TCP, raw_packets_[HF_INET_TCP]);
- getFormatFromBuffer(HF_INET6_ICMP, raw_packets_[HF_INET6_ICMP]);
- getFormatFromBuffer(HF_INET_ICMP, raw_packets_[HF_INET_ICMP]);
- getFormatFromBuffer(HF_INET6_TCP_AH, raw_packets_[HF_INET6_TCP_AH]);
- getFormatFromBuffer(HF_INET_TCP_AH, raw_packets_[HF_INET_TCP_AH]);
+ getFormatFromBuffer(HICN_PACKET_FORMAT_IPV6_TCP,
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP]);
+ getFormatFromBuffer(HICN_PACKET_FORMAT_IPV4_TCP,
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP]);
+ getFormatFromBuffer(HICN_PACKET_FORMAT_IPV6_ICMP,
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP]);
+ getFormatFromBuffer(HICN_PACKET_FORMAT_IPV4_ICMP,
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_ICMP]);
+ getFormatFromBuffer(HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP_AH]);
+ getFormatFromBuffer(HICN_PACKET_FORMAT_IPV4_TCP_AH,
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP_AH]);
}
// TEST_F(PacketTest, TestReplace) {
-// PacketForTest packet(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_TCP][0],
-// raw_packets_[HF_INET6_TCP].size());
+// PacketForTest packet(Packet::WRAP_BUFFER,
+// &raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP][0],
+// raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size());
// // Replace current packet with another one
-// packet.replace(&raw_packets_[HF_INET_TCP][0],
-// raw_packets_[HF_INET_TCP].size());
+// packet.replace(&raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP][0],
+// raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP].size());
// // Check new format
-// ASSERT_EQ(packet.getFormat(), HF_INET_TCP);
+// ASSERT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_IPV4_TCP);
// }
TEST_F(PacketTest, TestPayloadSize) {
// Check payload size of existing packet
- auto &_packet = raw_packets_[HF_INET6_TCP];
+ auto &_packet = raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP];
PacketForTest packet(Packet::WRAP_BUFFER, &_packet[0], _packet.size(),
_packet.size());
@@ -414,7 +434,7 @@ TEST_F(PacketTest, TestPayloadSize) {
std::string payload0(1024, 'X');
// Create the packet
- PacketForTest packet2(HF_INET6_TCP);
+ PacketForTest packet2(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP);
// Payload size should now be zero
EXPECT_EQ(packet2.payloadSize(), std::size_t(0));
@@ -441,22 +461,29 @@ TEST_F(PacketTest, TestPayloadSize) {
}
TEST_F(PacketTest, TestHeaderSize) {
- getHeaderSize(HICN_V6_TCP_HDRLEN,
- PacketForTest(Packet::Format::HF_INET6_TCP));
- getHeaderSize(HICN_V4_TCP_HDRLEN, PacketForTest(Packet::Format::HF_INET_TCP));
- getHeaderSize(HICN_V6_ICMP_HDRLEN,
- PacketForTest(Packet::Format::HF_INET6_ICMP));
- getHeaderSize(HICN_V4_ICMP_HDRLEN,
- PacketForTest(Packet::Format::HF_INET_ICMP));
- getHeaderSize(HICN_V6_TCP_AH_HDRLEN,
- PacketForTest(Packet::Format::HF_INET6_TCP_AH));
- getHeaderSize(HICN_V4_TCP_AH_HDRLEN,
- PacketForTest(Packet::Format::HF_INET_TCP_AH));
+ getHeaderSize(
+ IPV6_HDRLEN + TCP_HDRLEN,
+ PacketForTest(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP));
+ getHeaderSize(
+ IPV4_HDRLEN + TCP_HDRLEN,
+ PacketForTest(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV4_TCP));
+ getHeaderSize(
+ IPV6_HDRLEN + ICMP_HDRLEN,
+ PacketForTest(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_ICMP));
+ getHeaderSize(
+ IPV4_HDRLEN + ICMP_HDRLEN,
+ PacketForTest(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV4_ICMP));
+ getHeaderSize(
+ IPV6_HDRLEN + TCP_HDRLEN + AH_HDRLEN,
+ PacketForTest(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP_AH));
+ getHeaderSize(
+ IPV4_HDRLEN + TCP_HDRLEN + AH_HDRLEN,
+ PacketForTest(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV4_TCP_AH));
}
TEST_F(PacketTest, TestMemBufReference) {
// Create packet
- auto &_packet = raw_packets_[HF_INET6_TCP];
+ auto &_packet = raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP];
// Packet was not created as a shared_ptr. If we try to get a membuf shared
// ptr we should get an exception.
@@ -497,16 +524,16 @@ TEST_F(PacketTest, TestMemBufReference) {
TEST_F(PacketTest, TestReset) {
// Check everything is ok
- EXPECT_EQ(packet.getFormat(), HF_INET6_TCP);
- EXPECT_EQ(packet.length(), raw_packets_[HF_INET6_TCP].size());
- EXPECT_EQ(packet.headerSize(), HICN_V6_TCP_HDRLEN);
+ EXPECT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_IPV6_TCP);
+ EXPECT_EQ(packet.length(), raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size());
+ EXPECT_EQ(packet.headerSize(), IPV6_HDRLEN + TCP_HDRLEN);
EXPECT_EQ(packet.payloadSize(), packet.length() - packet.headerSize());
// Reset the packet
packet.reset();
// Rerun test
- EXPECT_EQ(packet.getFormat(), HF_UNSPEC);
+ EXPECT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_NONE);
EXPECT_EQ(packet.length(), std::size_t(0));
EXPECT_EQ(packet.headerSize(), std::size_t(0));
EXPECT_EQ(packet.payloadSize(), std::size_t(0));
@@ -547,7 +574,7 @@ TEST_F(PacketTest, TestAppendPayload) {
// There should be no more bufferls left in the chain
EXPECT_EQ(&packet, packet.next());
- EXPECT_EQ(packet.getFormat(), HF_UNSPEC);
+ EXPECT_EQ(packet.getFormat(), HICN_PACKET_FORMAT_NONE);
EXPECT_EQ(packet.length(), std::size_t(0));
EXPECT_EQ(packet.headerSize(), std::size_t(0));
EXPECT_EQ(packet.payloadSize(), std::size_t(0));
@@ -556,6 +583,7 @@ TEST_F(PacketTest, TestAppendPayload) {
TEST_F(PacketTest, GetPayload) {
// Append payload with raw buffer
uint8_t raw_buffer[2048];
+ memset(raw_buffer, 0, sizeof(raw_buffer));
auto original_payload_length = packet.payloadSize();
packet.appendPayload(raw_buffer, 2048);
@@ -620,61 +648,61 @@ TEST_F(PacketTest, SetGetPayloadType) {
TEST_F(PacketTest, GetFormat) {
{
PacketForTest p0(Packet::WRAP_BUFFER,
- &raw_packets_[Packet::Format::HF_INET_TCP][0],
- raw_packets_[Packet::Format::HF_INET_TCP].size(),
- raw_packets_[Packet::Format::HF_INET_TCP].size());
- testGetFormat(Packet::Format::HF_INET_TCP, p0);
+ &raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP].size(),
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP].size());
+ testGetFormat(HICN_PACKET_FORMAT_IPV4_TCP, p0);
PacketForTest p1(Packet::WRAP_BUFFER,
- &raw_packets_[Packet::Format::HF_INET6_TCP][0],
- raw_packets_[Packet::Format::HF_INET6_TCP].size(),
- raw_packets_[Packet::Format::HF_INET6_TCP].size());
- testGetFormat(Packet::Format::HF_INET6_TCP, p1);
+ &raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size(),
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size());
+ testGetFormat(HICN_PACKET_FORMAT_IPV6_TCP, p1);
PacketForTest p2(Packet::WRAP_BUFFER,
- &raw_packets_[Packet::Format::HF_INET_ICMP][0],
- raw_packets_[Packet::Format::HF_INET_ICMP].size(),
- raw_packets_[Packet::Format::HF_INET_ICMP].size());
- testGetFormat(Packet::Format::HF_INET_ICMP, p2);
+ &raw_packets_[HICN_PACKET_FORMAT_IPV4_ICMP][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_ICMP].size(),
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_ICMP].size());
+ testGetFormat(HICN_PACKET_FORMAT_IPV4_ICMP, p2);
PacketForTest p3(Packet::WRAP_BUFFER,
- &raw_packets_[Packet::Format::HF_INET6_ICMP][0],
- raw_packets_[Packet::Format::HF_INET6_ICMP].size(),
- raw_packets_[Packet::Format::HF_INET6_ICMP].size());
- testGetFormat(Packet::Format::HF_INET6_ICMP, p3);
+ &raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP].size(),
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP].size());
+ testGetFormat(HICN_PACKET_FORMAT_IPV6_ICMP, p3);
PacketForTest p4(Packet::WRAP_BUFFER,
- &raw_packets_[Packet::Format::HF_INET_TCP_AH][0],
- raw_packets_[Packet::Format::HF_INET_TCP_AH].size(),
- raw_packets_[Packet::Format::HF_INET_TCP_AH].size());
- testGetFormat(Packet::Format::HF_INET_TCP_AH, p4);
+ &raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP_AH][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP_AH].size(),
+ raw_packets_[HICN_PACKET_FORMAT_IPV4_TCP_AH].size());
+ testGetFormat(HICN_PACKET_FORMAT_IPV4_TCP_AH, p4);
PacketForTest p5(Packet::WRAP_BUFFER,
- &raw_packets_[Packet::Format::HF_INET6_TCP_AH][0],
- raw_packets_[Packet::Format::HF_INET6_TCP_AH].size(),
- raw_packets_[Packet::Format::HF_INET6_TCP_AH].size());
- testGetFormat(Packet::Format::HF_INET6_TCP_AH, p5);
+ &raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP_AH][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP_AH].size(),
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP_AH].size());
+ testGetFormat(HICN_PACKET_FORMAT_IPV6_TCP_AH, p5);
}
// Let's try now creating empty packets
{
- PacketForTest p0(Packet::Format::HF_INET_TCP);
- testGetFormat(Packet::Format::HF_INET_TCP, p0);
+ PacketForTest p0(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV4_TCP);
+ testGetFormat(HICN_PACKET_FORMAT_IPV4_TCP, p0);
- PacketForTest p1(Packet::Format::HF_INET6_TCP);
- testGetFormat(Packet::Format::HF_INET6_TCP, p1);
+ PacketForTest p1(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP);
+ testGetFormat(HICN_PACKET_FORMAT_IPV6_TCP, p1);
- PacketForTest p2(Packet::Format::HF_INET_ICMP);
- testGetFormat(Packet::Format::HF_INET_ICMP, p2);
+ PacketForTest p2(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV4_ICMP);
+ testGetFormat(HICN_PACKET_FORMAT_IPV4_ICMP, p2);
- PacketForTest p3(Packet::Format::HF_INET6_ICMP);
- testGetFormat(Packet::Format::HF_INET6_ICMP, p3);
+ PacketForTest p3(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_ICMP);
+ testGetFormat(HICN_PACKET_FORMAT_IPV6_ICMP, p3);
- PacketForTest p4(Packet::Format::HF_INET_TCP_AH);
- testGetFormat(Packet::Format::HF_INET_TCP_AH, p4);
+ PacketForTest p4(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV4_TCP_AH);
+ testGetFormat(HICN_PACKET_FORMAT_IPV4_TCP_AH, p4);
- PacketForTest p5(Packet::Format::HF_INET6_TCP_AH);
- testGetFormat(Packet::Format::HF_INET6_TCP_AH, p5);
+ PacketForTest p5(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP_AH);
+ testGetFormat(HICN_PACKET_FORMAT_IPV6_TCP_AH, p5);
}
}
@@ -682,9 +710,7 @@ TEST_F(PacketTest, SetGetTestSignatureTimestamp) {
// Let's try to set the signature timestamp in a packet without AH header. We
// expect an exception.
using namespace std::chrono;
- uint64_t now =
- duration_cast<milliseconds>(system_clock::now().time_since_epoch())
- .count();
+ uint64_t now = utils::SteadyTime::nowMs().count();
try {
packet.setSignatureTimestamp(now);
@@ -708,7 +734,7 @@ TEST_F(PacketTest, SetGetTestSignatureTimestamp) {
}
// Now let's construct a AH packet, with no additional space for signature
- PacketForTest p(HF_INET6_TCP_AH);
+ PacketForTest p(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP_AH);
p.setSignatureTimestamp(now);
uint64_t now_get = p.getSignatureTimestamp();
@@ -742,7 +768,7 @@ TEST_F(PacketTest, TestSetGetValidationAlgorithm) {
}
// Now let's construct a AH packet, with no additional space for signature
- PacketForTest p(HF_INET6_TCP_AH);
+ PacketForTest p(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP_AH);
p.setValidationAlgorithm(auth::CryptoSuite::RSA_SHA256);
auto v_get = p.getValidationAlgorithm();
@@ -752,6 +778,7 @@ TEST_F(PacketTest, TestSetGetValidationAlgorithm) {
TEST_F(PacketTest, TestSetGetKeyId) {
uint8_t key[32];
+ memset(key, 0, sizeof(key));
auth::KeyId key_id = std::make_pair(key, sizeof(key));
try {
@@ -763,7 +790,7 @@ TEST_F(PacketTest, TestSetGetKeyId) {
FAIL() << "Unexpected exception";
}
- // Same fot get method
+ // Same for get method
try {
auto k = packet.getKeyId();
// Let's make compiler happy
@@ -776,7 +803,7 @@ TEST_F(PacketTest, TestSetGetKeyId) {
}
// Now let's construct a AH packet, with no additional space for signature
- PacketForTest p(HF_INET6_TCP_AH);
+ PacketForTest p(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP_AH);
p.setKeyId(key_id);
auto p_get = p.getKeyId();
@@ -800,7 +827,8 @@ TEST_F(PacketTest, DISABLED_TestChecksum) {
EXPECT_TRUE(integrity);
// Check with AH header and 300 bytes signature
- PacketForTest p(HF_INET6_TCP_AH, 300);
+ PacketForTest p(HICN_PACKET_TYPE_INTEREST, HICN_PACKET_FORMAT_IPV6_TCP_AH,
+ 300);
std::string payload(5000, 'X');
p.appendPayload((const uint8_t *)payload.c_str(), payload.size() / 2);
p.appendPayload((const uint8_t *)(payload.c_str() + payload.size() / 2),
@@ -811,203 +839,72 @@ TEST_F(PacketTest, DISABLED_TestChecksum) {
EXPECT_TRUE(integrity);
}
-TEST_F(PacketTest, TestSetSyn) {
- // Test syn of non-tcp format and check exception is thrown
- try {
- auto p = PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_ICMP][0],
- raw_packets_[HF_INET6_ICMP].size(),
- raw_packets_[HF_INET6_ICMP].size());
- // Let's make compiler happy
- p.setSyn();
- FAIL() << "We should not reach this point.";
- } catch (const errors::RuntimeException &exc) {
- /* ok right exception*/
- } catch (...) {
- FAIL() << "Unexpected exception";
- }
-
- packet.setSyn();
- EXPECT_TRUE(packet.testSyn());
-
- packet.resetSyn();
- EXPECT_FALSE(packet.testSyn());
-}
-
-TEST_F(PacketTest, TestSetFin) {
- // Test syn of non-tcp format and check exception is thrown
- try {
- auto p = PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_ICMP][0],
- raw_packets_[HF_INET6_ICMP].size(),
- raw_packets_[HF_INET6_ICMP].size());
- // Let's make compiler happy
- p.setFin();
- FAIL() << "We should not reach this point.";
- } catch (const errors::RuntimeException &exc) {
- /* ok right exception*/
- } catch (...) {
- FAIL() << "Unexpected exception";
- }
-
- packet.setFin();
- EXPECT_TRUE(packet.testFin());
-
- packet.resetFin();
- EXPECT_FALSE(packet.testFin());
-}
-
-TEST_F(PacketTest, TestSetAck) {
- // Test syn of non-tcp format and check exception is thrown
- try {
- auto p = PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_ICMP][0],
- raw_packets_[HF_INET6_ICMP].size(),
- raw_packets_[HF_INET6_ICMP].size());
- // Let's make compiler happy
- p.setAck();
- FAIL() << "We should not reach this point.";
- } catch (const errors::RuntimeException &exc) {
- /* ok right exception*/
- } catch (...) {
- FAIL() << "Unexpected exception";
- }
-
- packet.setAck();
- EXPECT_TRUE(packet.testAck());
-
- packet.resetAck();
- EXPECT_FALSE(packet.testAck());
-}
-
-TEST_F(PacketTest, TestSetRst) {
- // Test syn of non-tcp format and check exception is thrown
- try {
- auto p = PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_ICMP][0],
- raw_packets_[HF_INET6_ICMP].size(),
- raw_packets_[HF_INET6_ICMP].size());
- // Let's make compiler happy
- p.setRst();
- FAIL() << "We should not reach this point.";
- } catch (const errors::RuntimeException &exc) {
- /* ok right exception*/
- } catch (...) {
- FAIL() << "Unexpected exception";
- }
-
- packet.setRst();
- EXPECT_TRUE(packet.testRst());
-
- packet.resetRst();
- EXPECT_FALSE(packet.testRst());
-}
-
-TEST_F(PacketTest, TestResetFlags) {
- packet.setRst();
- packet.setSyn();
- packet.setAck();
- packet.setFin();
- EXPECT_TRUE(packet.testRst());
- EXPECT_TRUE(packet.testAck());
- EXPECT_TRUE(packet.testFin());
- EXPECT_TRUE(packet.testSyn());
-
- packet.resetFlags();
- EXPECT_FALSE(packet.testRst());
- EXPECT_FALSE(packet.testAck());
- EXPECT_FALSE(packet.testFin());
- EXPECT_FALSE(packet.testSyn());
-}
-
-TEST_F(PacketTest, TestSetGetSrcPort) {
- try {
- auto p = PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_ICMP][0],
- raw_packets_[HF_INET6_ICMP].size(),
- raw_packets_[HF_INET6_ICMP].size());
- // Let's make compiler happy
- p.setSrcPort(12345);
- FAIL() << "We should not reach this point.";
- } catch (const errors::RuntimeException &exc) {
- /* ok right exception*/
- } catch (...) {
- FAIL() << "Unexpected exception";
- }
-
- packet.setSrcPort(12345);
- EXPECT_EQ(packet.getSrcPort(), 12345);
-}
-
-TEST_F(PacketTest, TestSetGetDstPort) {
- try {
- auto p = PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_ICMP][0],
- raw_packets_[HF_INET6_ICMP].size(),
- raw_packets_[HF_INET6_ICMP].size());
- // Let's make compiler happy
- p.setDstPort(12345);
- FAIL() << "We should not reach this point.";
- } catch (const errors::RuntimeException &exc) {
- /* ok right exception*/
- } catch (...) {
- FAIL() << "Unexpected exception";
- }
-
- packet.setDstPort(12345);
- EXPECT_EQ(packet.getDstPort(), 12345);
-}
-
TEST_F(PacketTest, TestEnsureCapacity) {
PacketForTest &p = packet;
// This shoul be false
- auto ret = p.ensureCapacity(raw_packets_[HF_INET6_TCP].size() + 10);
+ auto ret =
+ p.ensureCapacity(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size() + 10);
EXPECT_FALSE(ret);
// This should be true
- ret = p.ensureCapacity(raw_packets_[HF_INET6_TCP].size());
+ ret = p.ensureCapacity(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size());
EXPECT_TRUE(ret);
// This should be true
- ret = p.ensureCapacity(raw_packets_[HF_INET6_TCP].size() - 10);
+ ret = p.ensureCapacity(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size() - 10);
EXPECT_TRUE(ret);
// Try to trim the packet start
p.trimStart(10);
// Now this should be false
- ret = p.ensureCapacity(raw_packets_[HF_INET6_TCP].size());
+ ret = p.ensureCapacity(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size());
EXPECT_FALSE(ret);
// Create a new packet
- auto p2 = PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_ICMP][0],
- raw_packets_[HF_INET6_ICMP].size(),
- raw_packets_[HF_INET6_ICMP].size());
+ auto p2 = PacketForTest(Packet::WRAP_BUFFER,
+ &raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP].size(),
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_ICMP].size());
p2.appendPayload(utils::MemBuf::createCombined(2000));
// This should be false, since the buffer is chained
- ret = p2.ensureCapacity(raw_packets_[HF_INET6_TCP].size() - 10);
+ ret =
+ p2.ensureCapacity(raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size() - 10);
EXPECT_FALSE(ret);
}
-TEST_F(PacketTest, TestEnsureCapacityAndFillUnused) {
+//
+// This test is disabled as it manipulates a ipv6 header with the wrong payload
+// length inside.
+//
+TEST_F(PacketTest, DISABLED_TestEnsureCapacityAndFillUnused) {
// Create packet by excluding the payload (So only L3 + L4 headers). The
// payload will be trated as unused tailroom
- PacketForTest p =
- PacketForTest(Packet::WRAP_BUFFER, &raw_packets_[HF_INET6_TCP][0],
- raw_packets_[HF_INET6_TCP].size() - PAYLOAD_SIZE,
- raw_packets_[HF_INET6_TCP].size());
+ PacketForTest p = PacketForTest(
+ Packet::WRAP_BUFFER, &raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP][0],
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size() - PAYLOAD_SIZE,
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size());
// Copy original packet payload, which is here trated as a unused tailroom
uint8_t original_payload[PAYLOAD_SIZE];
- uint8_t *payload = &raw_packets_[HF_INET6_TCP][0] +
- raw_packets_[HF_INET6_TCP].size() - PAYLOAD_SIZE;
+ uint8_t *payload = &raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP][0] +
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size() -
+ PAYLOAD_SIZE;
std::memcpy(original_payload, payload, PAYLOAD_SIZE);
// This should be true and the unused tailroom should be unmodified
auto ret = p.ensureCapacityAndFillUnused(
- raw_packets_[HF_INET6_TCP].size() - (PAYLOAD_SIZE + 10), 0);
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size() - (PAYLOAD_SIZE + 10),
+ 0);
EXPECT_TRUE(ret);
ret = std::memcmp(original_payload, payload, PAYLOAD_SIZE);
EXPECT_EQ(ret, 0);
// This should fill the payload with zeros
- ret = p.ensureCapacityAndFillUnused(raw_packets_[HF_INET6_TCP].size(), 0);
+ ret = p.ensureCapacityAndFillUnused(
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size(), 0);
EXPECT_TRUE(ret);
uint8_t zeros[PAYLOAD_SIZE];
std::memset(zeros, 0, PAYLOAD_SIZE);
@@ -1015,7 +912,8 @@ TEST_F(PacketTest, TestEnsureCapacityAndFillUnused) {
EXPECT_EQ(ret, 0);
// This should fill the payload with ones
- ret = p.ensureCapacityAndFillUnused(raw_packets_[HF_INET6_TCP].size(), 1);
+ ret = p.ensureCapacityAndFillUnused(
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size(), 1);
EXPECT_TRUE(ret);
uint8_t ones[PAYLOAD_SIZE];
std::memset(ones, 1, PAYLOAD_SIZE);
@@ -1023,16 +921,12 @@ TEST_F(PacketTest, TestEnsureCapacityAndFillUnused) {
EXPECT_EQ(ret, 0);
// This should return false and the payload should be unmodified
- ret = p.ensureCapacityAndFillUnused(raw_packets_[HF_INET6_TCP].size() + 1, 1);
+ ret = p.ensureCapacityAndFillUnused(
+ raw_packets_[HICN_PACKET_FORMAT_IPV6_TCP].size() + 1, 1);
EXPECT_FALSE(ret);
ret = std::memcmp(payload, ones, PAYLOAD_SIZE);
EXPECT_EQ(ret, 0);
}
-TEST_F(PacketTest, TestSetGetTTL) {
- packet.setTTL(128);
- EXPECT_EQ(packet.getTTL(), 128);
-}
-
} // namespace core
} // namespace transport
diff --git a/libtransport/src/test/test_packet_allocator.cc b/libtransport/src/test/test_packet_allocator.cc
new file mode 100644
index 000000000..0de35a817
--- /dev/null
+++ b/libtransport/src/test/test_packet_allocator.cc
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2021-2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * 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 <glog/logging.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/core/content_object.h>
+#include <hicn/transport/core/interest.h>
+#define ALLOCATION_CHECKS
+#include <hicn/transport/core/global_object_pool.h>
+#undef ALLOCATION_CHECKS
+#include <hicn/transport/utils/chrono_typedefs.h>
+#include <hicn/transport/utils/event_thread.h>
+
+namespace transport {
+namespace core {
+
+class PacketAllocatorTest : public ::testing::Test {
+ protected:
+ static inline const std::size_t default_size = 2048;
+ static inline const std::size_t default_n_buffer = 1024;
+ static inline const std::size_t counter = 1024;
+ static inline const std::size_t total_packets = 1024 * counter;
+
+ // Get fixed block allocator_ of 1024 buffers of size 2048 bytes
+ PacketAllocatorTest() : allocator_(PacketManager<>::getInstance()) {
+ // You can do set-up work for each test here.
+ }
+
+ virtual ~PacketAllocatorTest() {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void SetUp() {}
+
+ virtual void TearDown() {}
+
+ static bool pointerIsAligned(const void *pointer, size_t byte_count) {
+ return uintptr_t(pointer) % byte_count == 0;
+ }
+
+ template <typename T, typename... Args>
+ void allocationTest(Args &&...args) {
+ // Create packet
+ auto packet = allocator_.getPacket<T>(std::forward<Args>(args)...);
+
+ // Check boundaries
+ LOG(INFO) << "packet size: " << sizeof(*packet) + sizeof(packet)
+ << std::endl;
+ EXPECT_LE(sizeof(*packet) + sizeof(packet) + sizeof(std::max_align_t),
+ sizeof(PacketManager<>::PacketStorage::packet_and_shared_ptr));
+ }
+
+ PacketManager<> &allocator_;
+};
+
+TEST_F(PacketAllocatorTest, ContentObjectAllocation) {
+ allocationTest<core::ContentObject>(HICN_PACKET_FORMAT_IPV4_TCP);
+}
+
+TEST_F(PacketAllocatorTest, InterestAllocation) {
+ allocationTest<core::Interest>(HICN_PACKET_FORMAT_IPV4_TCP);
+}
+
+// TEST_F(PacketAllocatorTest, MemBufAllocation) {
+// allocationTest<::utils::MemBuf>();
+// }
+
+TEST_F(PacketAllocatorTest, CheckAllocationIsCorrect) {
+ // Create packet
+ auto packet =
+ allocator_.getPacket<core::ContentObject>(HICN_PACKET_FORMAT_IPV4_TCP);
+
+ // Address of actual buffer
+ uint8_t *buffer_address = packet->writableData();
+
+ // Address of packet
+ uint8_t *packet_address = reinterpret_cast<uint8_t *>(packet.get());
+
+ uint8_t *start_address =
+ buffer_address -
+ sizeof(PacketManager<>::PacketStorage::packet_and_shared_ptr);
+
+ // Check memory was allocated on correct positions
+ EXPECT_TRUE(pointerIsAligned(start_address, alignof(std::max_align_t)));
+ EXPECT_TRUE(packet_address > start_address &&
+ packet_address < buffer_address);
+ EXPECT_TRUE(pointerIsAligned(buffer_address, alignof(std::max_align_t)));
+ EXPECT_THAT(std::size_t(buffer_address - start_address),
+ testing::Eq(sizeof(
+ PacketManager<>::PacketStorage::packet_and_shared_ptr)));
+}
+
+TEST_F(PacketAllocatorTest, CheckAllocationSpeed) {
+ // Check time needed to allocate 1 million packeauto &packet_manager =
+ auto &packet_manager = core::PacketManager<>::getInstance();
+
+ // Send 1 million packets
+ std::array<utils::MemBuf::Ptr, counter> packets;
+ auto t0 = utils::SteadyTime::now();
+ std::size_t sum = 0;
+ for (std::size_t j = 0; j < counter; j++) {
+ for (std::size_t i = 0; i < counter; i++) {
+ packets[i] = packet_manager.getMemBuf();
+ sum++;
+ }
+ }
+ auto t1 = utils::SteadyTime::now();
+
+ auto delta = utils::SteadyTime::getDurationUs(t0, t1);
+ auto rate = double(sum) * 1000000.0 / double(delta.count());
+
+ LOG(INFO) << "rate: " << rate << " packets/s";
+}
+
+} // namespace core
+} // namespace transport
diff --git a/libtransport/src/test/test_prefix.cc b/libtransport/src/test/test_prefix.cc
new file mode 100644
index 000000000..3eab72bcb
--- /dev/null
+++ b/libtransport/src/test/test_prefix.cc
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/core/prefix.h>
+#include <hicn/transport/errors/invalid_ip_address_exception.h>
+#include <hicn/transport/portability/endianess.h>
+
+#include <cstring>
+#include <memory>
+#include <vector>
+
+namespace transport {
+namespace core {
+
+namespace {
+class PrefixTest : public ::testing::Test {
+ protected:
+ static inline const char prefix_str0[] = "2001:db8:1::/64";
+ static inline const char prefix_str1[] = "10.11.12.0/24";
+ static inline const char prefix_str2[] = "2001:db8:1::abcd/64";
+ static inline const char prefix_str3[] = "10.11.12.245/27";
+ static inline const char wrong_prefix_str0[] = "10.11.12.245/45";
+ static inline const char wrong_prefix_str1[] = "10.400.12.13/8";
+ static inline const char wrong_prefix_str2[] = "2001:db8:1::/640";
+ static inline const char wrong_prefix_str3[] = "20011::db8:1::/16";
+ static inline const char wrong_prefix_str4[] = "2001::db8:1::fffff/96";
+
+ PrefixTest() = default;
+
+ ~PrefixTest() override = default;
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ void SetUp() override {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ }
+
+ void TearDown() override {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ }
+};
+
+TEST_F(PrefixTest, ConstructorRightString) {
+ // Create empty prefix
+ Prefix p;
+
+ // Create prefix from string
+ Prefix p0(prefix_str0);
+ // Reconstruct string and check it is equal to original address
+ std::string network = p0.getNetwork();
+ std::uint16_t prefix_length = p0.getPrefixLength();
+ EXPECT_THAT(network + "/" + std::to_string(prefix_length),
+ ::testing::StrEq(prefix_str0));
+
+ // Create prefix from string
+ Prefix p1(prefix_str1);
+ // Reconstruct string and check it is equal to original address
+ network = p1.getNetwork();
+ prefix_length = p1.getPrefixLength();
+ EXPECT_THAT(network + "/" + std::to_string(prefix_length),
+ ::testing::StrEq(prefix_str1));
+
+ // Create prefix from string
+ Prefix p2(prefix_str2);
+ // Reconstruct string and check it is equal to original address
+ network = p2.getNetwork();
+ prefix_length = p2.getPrefixLength();
+ EXPECT_THAT(network + "/" + std::to_string(prefix_length),
+ ::testing::StrEq(prefix_str2));
+
+ // Create prefix from string
+ Prefix p3(prefix_str3);
+ // Reconstruct string and check it is equal to original address
+ network = p3.getNetwork();
+ prefix_length = p3.getPrefixLength();
+ EXPECT_THAT(network + "/" + std::to_string(prefix_length),
+ ::testing::StrEq(prefix_str3));
+
+ // Create prefix from string and prefix length
+ Prefix p4("2001::1234", 66);
+ // Reconstruct string and check it is equal to original address
+ network = p4.getNetwork();
+ prefix_length = p4.getPrefixLength();
+ auto af = p4.getAddressFamily();
+ EXPECT_THAT(network, ::testing::StrEq("2001::1234"));
+ EXPECT_THAT(prefix_length, ::testing::Eq(66));
+ EXPECT_THAT(af, ::testing::Eq(AF_INET6));
+}
+
+TEST_F(PrefixTest, ConstructorWrongString) {
+ try {
+ Prefix p0(wrong_prefix_str0);
+ FAIL() << "Expected exception";
+ } catch (const errors::InvalidIpAddressException &) {
+ // Expected exception
+ }
+
+ try {
+ Prefix p1(wrong_prefix_str1);
+ FAIL() << "Expected exception";
+ } catch (const errors::InvalidIpAddressException &) {
+ // Expected exception
+ }
+
+ try {
+ Prefix p2(wrong_prefix_str2);
+ FAIL() << "Expected exception";
+ } catch (const errors::InvalidIpAddressException &) {
+ // Expected exception
+ }
+
+ try {
+ Prefix p3(wrong_prefix_str3);
+ FAIL() << "Expected exception";
+ } catch (const errors::InvalidIpAddressException &) {
+ // Expected exception
+ }
+
+ try {
+ Prefix p4(wrong_prefix_str4);
+ FAIL() << "Expected exception";
+ } catch (const errors::InvalidIpAddressException &) {
+ // Expected exception
+ }
+}
+
+TEST_F(PrefixTest, Comparison) {
+ Prefix p0(prefix_str0);
+ Prefix p1(prefix_str1);
+
+ // Expect they are different
+ EXPECT_THAT(p0, ::testing::Ne(p1));
+
+ auto p2 = p1;
+ // Expect they are equal
+ EXPECT_THAT(p1, ::testing::Eq(p2));
+}
+
+TEST_F(PrefixTest, ToSockAddress) {
+ Prefix p0(prefix_str3);
+
+ auto ret = p0.toSockaddr();
+ auto sockaddr = reinterpret_cast<sockaddr_in *>(ret.get());
+
+ EXPECT_THAT(sockaddr->sin_family, ::testing::Eq(AF_INET));
+ EXPECT_THAT(sockaddr->sin_addr.s_addr, portability::host_to_net(0x0a0b0cf5));
+}
+
+TEST_F(PrefixTest, GetPrefixLength) {
+ Prefix p0(prefix_str3);
+ EXPECT_THAT(p0.getPrefixLength(), ::testing::Eq(27));
+}
+
+TEST_F(PrefixTest, SetPrefixLength) {
+ Prefix p0(prefix_str3);
+ EXPECT_THAT(p0.getPrefixLength(), ::testing::Eq(27));
+ p0.setPrefixLength(20);
+ EXPECT_THAT(p0.getPrefixLength(), ::testing::Eq(20));
+
+ try {
+ p0.setPrefixLength(33);
+ FAIL() << "Expected exception";
+ } catch ([[maybe_unused]] const errors::InvalidIpAddressException &) {
+ // Expected exception
+ }
+}
+
+TEST_F(PrefixTest, SetGetNetwork) {
+ Prefix p0(prefix_str0);
+ EXPECT_THAT(p0.getPrefixLength(), ::testing::Eq(64));
+ p0.setNetwork("b001::1234");
+ EXPECT_THAT(p0.getNetwork(), ::testing::StrEq("b001::1234"));
+ EXPECT_THAT(p0.getPrefixLength(), ::testing::Eq(64));
+}
+
+TEST_F(PrefixTest, Contains) {
+ // IPv6 prefix
+ Prefix p0(prefix_str0);
+ hicn_ip_address_t ip0, ip1;
+
+ hicn_ip_address_pton("2001:db8:1::1234", &ip0);
+ hicn_ip_address_pton("2001:db9:1::1234", &ip1);
+
+ EXPECT_TRUE(p0.contains(ip0));
+ EXPECT_FALSE(p0.contains(ip1));
+
+ Prefix p1(prefix_str1);
+ hicn_ip_address_pton("10.11.12.12", &ip0);
+ hicn_ip_address_pton("10.12.12.13", &ip1);
+
+ EXPECT_TRUE(p1.contains(ip0));
+ EXPECT_FALSE(p1.contains(ip1));
+
+ Prefix p2(prefix_str2);
+ hicn_ip_address_pton("2001:db8:1::dbca", &ip0);
+ hicn_ip_address_pton("10.12.12.12", &ip1);
+
+ EXPECT_TRUE(p2.contains(ip0));
+ EXPECT_FALSE(p2.contains(ip1));
+
+ Prefix p3(prefix_str3);
+ hicn_ip_address_pton("10.11.12.245", &ip0);
+ hicn_ip_address_pton("10.11.12.1", &ip1);
+
+ EXPECT_TRUE(p3.contains(ip0));
+ EXPECT_FALSE(p3.contains(ip1));
+
+ // Corner cases
+ Prefix p4("::/0");
+ hicn_ip_address_pton("7001:db8:1::1234", &ip0);
+ hicn_ip_address_pton("8001:db8:1::1234", &ip1);
+
+ EXPECT_TRUE(p4.contains(ip0));
+ EXPECT_TRUE(p4.contains(ip1));
+
+ // Corner cases
+ Prefix p5("b001:a:b:c:d:e:f:1/128");
+ hicn_ip_address_pton("b001:a:b:c:d:e:f:1", &ip0);
+ hicn_ip_address_pton("b001:a:b:c:d:e:f:2", &ip1);
+
+ EXPECT_TRUE(p5.contains(ip0));
+ EXPECT_FALSE(p5.contains(ip1));
+}
+
+TEST_F(PrefixTest, GetAddressFamily) {
+ Prefix p0(prefix_str0);
+ auto af = p0.getAddressFamily();
+ EXPECT_THAT(af, ::testing::Eq(AF_INET6));
+
+ Prefix p1(prefix_str1);
+ af = p1.getAddressFamily();
+ EXPECT_THAT(af, ::testing::Eq(AF_INET));
+}
+
+TEST_F(PrefixTest, MakeName) {
+ Prefix p0(prefix_str0);
+ auto name0 = p0.makeName();
+ EXPECT_THAT(name0.toString(), ::testing::StrEq("2001:db8:1::|0"));
+
+ Prefix p1(prefix_str1);
+ auto name1 = p1.makeName();
+ EXPECT_THAT(name1.toString(), ::testing::StrEq("10.11.12.0|0"));
+
+ Prefix p2(prefix_str2);
+ auto name2 = p2.makeName();
+ EXPECT_THAT(name2.toString(), ::testing::StrEq("2001:db8:1::|0"));
+
+ Prefix p3(prefix_str3);
+ auto name3 = p3.makeName();
+ EXPECT_THAT(name3.toString(), ::testing::StrEq("10.11.12.224|0"));
+
+ Prefix p4("b001:a:b:c:d:e:f:1/128");
+ auto name4 = p4.makeName();
+ EXPECT_THAT(name4.toString(), ::testing::StrEq("b001:a:b:c:d:e:f:1|0"));
+}
+
+TEST_F(PrefixTest, MakeRandomName) {
+ Prefix p0(prefix_str0);
+ auto name0 = p0.makeRandomName();
+ auto name1 = p0.makeRandomName();
+ auto name2 = p0.makeRandomName();
+ auto name3 = p0.makeRandomName();
+
+ EXPECT_THAT(name0, ::testing::Not(::testing::Eq(name1)));
+ EXPECT_THAT(name0, ::testing::Not(::testing::Eq(name2)));
+ EXPECT_THAT(name0, ::testing::Not(::testing::Eq(name3)));
+ EXPECT_THAT(name1, ::testing::Not(::testing::Eq(name2)));
+ EXPECT_THAT(name1, ::testing::Not(::testing::Eq(name3)));
+ EXPECT_THAT(name2, ::testing::Not(::testing::Eq(name3)));
+
+ // Corner case
+ Prefix p2("b001:a:b:c:d:e:f:1/128");
+ name0 = p2.makeRandomName();
+ name1 = p2.makeRandomName();
+ name2 = p2.makeRandomName();
+ name3 = p2.makeRandomName();
+
+ EXPECT_THAT(name0, ::testing::Eq(name1));
+ EXPECT_THAT(name0, ::testing::Eq(name2));
+ EXPECT_THAT(name0, ::testing::Eq(name3));
+ EXPECT_THAT(name1, ::testing::Eq(name2));
+ EXPECT_THAT(name1, ::testing::Eq(name3));
+ EXPECT_THAT(name2, ::testing::Eq(name3));
+}
+
+TEST_F(PrefixTest, MakeNameWithIndex) {
+ Prefix p0(prefix_str0);
+ auto name0 = p0.makeNameWithIndex(0);
+ EXPECT_THAT(name0.toString(), ::testing::StrEq("2001:db8:1::|0"));
+ auto name1 = p0.makeNameWithIndex(1);
+ EXPECT_THAT(name1.toString(), ::testing::StrEq("2001:db8:1::1|0"));
+ auto name2 = p0.makeNameWithIndex(2);
+ EXPECT_THAT(name2.toString(), ::testing::StrEq("2001:db8:1::2|0"));
+ auto name3 = p0.makeNameWithIndex(3);
+ EXPECT_THAT(name3.toString(), ::testing::StrEq("2001:db8:1::3|0"));
+
+ Prefix p1(prefix_str1);
+ name0 = p1.makeNameWithIndex(0);
+ EXPECT_THAT(name0.toString(), ::testing::StrEq("10.11.12.0|0"));
+ name1 = p1.makeNameWithIndex(1);
+ EXPECT_THAT(name1.toString(), ::testing::StrEq("10.11.12.1|0"));
+ name2 = p1.makeNameWithIndex(2);
+ EXPECT_THAT(name2.toString(), ::testing::StrEq("10.11.12.2|0"));
+ name3 = p1.makeNameWithIndex(3);
+ EXPECT_THAT(name3.toString(), ::testing::StrEq("10.11.12.3|0"));
+
+ // Test truncation
+ Prefix p2("b001::/96");
+ name0 = p2.makeNameWithIndex(0xffffffffffffffff);
+ EXPECT_THAT(name0.toString(), ::testing::StrEq("b001::ffff:ffff|0"));
+}
+
+} // namespace
+
+} // namespace core
+} // namespace transport
diff --git a/libtransport/src/test/test_quadloop.cc b/libtransport/src/test/test_quadloop.cc
new file mode 100644
index 000000000..6a08033aa
--- /dev/null
+++ b/libtransport/src/test/test_quadloop.cc
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <glog/logging.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/portability/cache.h>
+
+#include <array>
+#include <cstring>
+#include <memory>
+#include <vector>
+
+namespace utils {
+
+class LoopTest : public ::testing::Test {
+ protected:
+ static inline const std::size_t size = 256;
+
+ LoopTest() = default;
+
+ ~LoopTest() override = default;
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ void SetUp() override {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ }
+
+ void TearDown() override {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ }
+};
+
+// 1 cache line struct (64 bytes)
+struct Data {
+ std::array<uint64_t, 8> data;
+};
+
+TEST_F(LoopTest, QuadLoopTest) {
+ // Create 2 arrays of 256 elements
+ std::vector<std::unique_ptr<Data>> _from;
+ std::vector<std::unique_ptr<Data>> _to_next;
+ _from.reserve(size);
+ _to_next.reserve(size);
+
+ int n_left_from = size;
+ int n_left_to_next = size;
+
+ // Initialize the arrays
+ for (std::size_t i = 0; i < size; i++) {
+ _from.push_back(std::make_unique<Data>());
+ _to_next.push_back(std::make_unique<Data>());
+
+ for (int j = 0; j < 8; j++) {
+ _from[i]->data[j] = j;
+ _to_next[i]->data[j] = 0;
+ }
+ }
+
+ const std::unique_ptr<Data> *from = &_from[0];
+ const std::unique_ptr<Data> *to_next = &_to_next[0];
+
+ clock_t start;
+ clock_t end;
+ double clocks;
+
+ start = clock();
+ // Create a quad loop
+ while (n_left_from > 0) {
+ while (n_left_from >= 4 && n_left_to_next >= 4) {
+ {
+ using namespace transport::portability::cache;
+ Data *d2;
+ Data *d3;
+
+ d2 = from[2].get();
+ d3 = from[3].get();
+
+ prefetch<Data, READ>(d2, sizeof(Data));
+ prefetch<Data, READ>(d3, sizeof(Data));
+
+ d2 = to_next[2].get();
+ d3 = to_next[3].get();
+
+ prefetch<Data, WRITE>(d2, sizeof(Data));
+ prefetch<Data, WRITE>(d3, sizeof(Data));
+ }
+
+ // Do 4 iterations
+ std::memcpy(to_next[0].get()->data.data(), from[0].get()->data.data(),
+ sizeof(Data));
+ std::memcpy(to_next[1].get()->data.data(), from[1].get()->data.data(),
+ sizeof(Data));
+ n_left_from -= 2;
+ n_left_to_next -= 2;
+ from += 2;
+ to_next += 2;
+ }
+
+ while (n_left_from > 0 && n_left_to_next > 0) {
+ std::memcpy(to_next[0].get()->data.data(), from[0].get()->data.data(),
+ sizeof(Data));
+ n_left_from -= 1;
+ n_left_to_next -= 1;
+ from += 1;
+ to_next += 1;
+ }
+ }
+ end = clock();
+ clocks = (double)(end - start);
+
+ LOG(INFO) << "Time with quad loop: " << clocks << std::endl;
+}
+
+TEST_F(LoopTest, NormalLoopTest) {
+ // Create 2 arrays of 256 elements
+ std::vector<std::unique_ptr<Data>> _from;
+ std::vector<std::unique_ptr<Data>> _to_next;
+ _from.reserve(size);
+ _to_next.reserve(size);
+
+ int n_left_from = size;
+ int n_left_to_next = size;
+
+ // Initialize the arrays
+ for (std::size_t i = 0; i < size; i++) {
+ _from.push_back(std::make_unique<Data>());
+ _to_next.push_back(std::make_unique<Data>());
+
+ for (int j = 0; j < 8; j++) {
+ _from[i]->data[j] = j;
+ _to_next[i]->data[j] = 0;
+ }
+ }
+
+ const std::unique_ptr<Data> *from = &_from[0];
+ const std::unique_ptr<Data> *to_next = &_to_next[0];
+
+ clock_t start;
+ clock_t end;
+ double clocks;
+
+ start = clock();
+ while (n_left_from > 0) {
+ while (n_left_from > 0 && n_left_to_next > 0) {
+ std::memcpy(to_next[0].get()->data.data(), from[0].get()->data.data(),
+ sizeof(Data));
+ n_left_from -= 1;
+ n_left_to_next -= 1;
+ from += 1;
+ to_next += 1;
+ }
+ }
+ end = clock();
+ clocks = ((double)(end - start));
+
+ LOG(INFO) << "Time with normal loop: " << clocks << std::endl;
+}
+
+} // namespace utils \ No newline at end of file
diff --git a/libtransport/src/test/test_quality_score.cc b/libtransport/src/test/test_quality_score.cc
new file mode 100644
index 000000000..9513c94a6
--- /dev/null
+++ b/libtransport/src/test/test_quality_score.cc
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <hicn/transport/utils/rtc_quality_score.h>
+
+#include <climits>
+#include <random>
+#include <vector>
+
+namespace transport {
+
+namespace protocol {
+
+namespace rtc {
+
+TEST(QualityScoreTest, testQS) {
+ RTCQualityScore qs;
+ uint8_t score;
+
+ // 0 losses
+ score = qs.getQualityScore(0, 0);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(98, 0);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(188, 0);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(398, 0);
+ EXPECT_EQ(score, (uint8_t)4);
+
+ score = qs.getQualityScore(400, 0);
+ EXPECT_EQ(score, (uint8_t)3);
+
+ score = qs.getQualityScore(598, 0);
+ EXPECT_EQ(score, (uint8_t)3);
+
+ score = qs.getQualityScore(600, 0);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ score = qs.getQualityScore(700, 0);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ score = qs.getQualityScore(50000, 0);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ // 0 delay
+ score = qs.getQualityScore(0, 2);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(0, 9);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(0, 29);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(0, 30);
+ EXPECT_EQ(score, (uint8_t)4);
+
+ score = qs.getQualityScore(0, 39);
+ EXPECT_EQ(score, (uint8_t)4);
+
+ score = qs.getQualityScore(0, 40);
+ EXPECT_EQ(score, (uint8_t)3);
+
+ score = qs.getQualityScore(0, 50);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ score = qs.getQualityScore(0, 5000);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ // loss < 10
+ score = qs.getQualityScore(0, 3);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(98, 9);
+ EXPECT_EQ(score, (uint8_t)4);
+
+ score = qs.getQualityScore(100, 9);
+ EXPECT_EQ(score, (uint8_t)3);
+
+ score = qs.getQualityScore(398, 5);
+ EXPECT_EQ(score, (uint8_t)2);
+
+ score = qs.getQualityScore(400, 5);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ score = qs.getQualityScore(4000, 5);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ // loss < 20
+ score = qs.getQualityScore(0, 10);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(30, 10);
+ EXPECT_EQ(score, (uint8_t)3);
+
+ score = qs.getQualityScore(198, 15);
+ EXPECT_EQ(score, (uint8_t)2);
+
+ score = qs.getQualityScore(200, 19);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ score = qs.getQualityScore(300, 10);
+ EXPECT_EQ(score, (uint8_t)1);
+
+ // loss < 30
+
+ score = qs.getQualityScore(0, 29);
+ EXPECT_EQ(score, (uint8_t)5);
+
+ score = qs.getQualityScore(10, 29);
+ EXPECT_EQ(score, (uint8_t)2);
+
+ score = qs.getQualityScore(0, 100);
+ EXPECT_EQ(score, (uint8_t)1);
+}
+
+} // namespace rtc
+} // namespace protocol
+} // namespace transport
diff --git a/libtransport/src/test/test_sessions.cc b/libtransport/src/test/test_sessions.cc
new file mode 100644
index 000000000..d2e8c27bb
--- /dev/null
+++ b/libtransport/src/test/test_sessions.cc
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/interfaces/global_conf_interface.h>
+#include <hicn/transport/interfaces/socket_consumer.h>
+#include <hicn/transport/interfaces/socket_options_keys.h>
+#include <hicn/transport/interfaces/socket_producer.h>
+
+namespace transport {
+namespace interface {
+
+class SessionsTest : public ::testing::Test {
+ protected:
+ static inline const std::size_t default_size = 2048;
+ static inline const std::size_t default_n_buffer = 1024;
+
+ // Get fixed block allocator_ of 1024 buffers of size 2048 bytes
+ SessionsTest() {
+ // You can do set-up work for each test here.
+ // Set io_module to local forwarder with no external connections
+ global_config::IoModuleConfiguration config;
+ config.name = "forwarder_module";
+ config.set();
+ }
+
+ virtual ~SessionsTest() {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void SetUp() {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ }
+
+ virtual void TearDown() {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ }
+
+ std::vector<ConsumerSocket> consumers_;
+ std::vector<ProducerSocket> producers_;
+};
+
+TEST_F(SessionsTest, SessionAllocations) {
+ // Create 1000 consumer sockets and 1000 producer sockets
+ int cprotocol = TransportProtocolAlgorithms::RAAQM;
+ int pprotocol = ProductionProtocolAlgorithms::BYTE_STREAM;
+ int offset = 0;
+
+ for (int i = 0; i < 1000; i++) {
+ auto &c = consumers_.emplace_back(cprotocol + (offset % 3));
+ auto &p = producers_.emplace_back(pprotocol + (offset % 2));
+ c.connect();
+ p.connect();
+ offset++;
+ }
+}
+
+} // namespace interface
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/test/test_thread_pool.cc b/libtransport/src/test/test_thread_pool.cc
new file mode 100644
index 000000000..1b6b4cc81
--- /dev/null
+++ b/libtransport/src/test/test_thread_pool.cc
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/utils/thread_pool.h>
+
+namespace utils {
+
+class ThreadPoolTest : public ::testing::Test {
+ protected:
+ ThreadPoolTest() : thread_pool_() {
+ // You can do set-up work for each test here.
+ }
+
+ virtual ~ThreadPoolTest() {
+ // You can do clean-up work that doesn't throw exceptions here.
+ }
+
+ // If the constructor and destructor are not enough for setting up
+ // and cleaning up each test, you can define the following methods:
+
+ virtual void SetUp() {
+ // Code here will be called immediately after the constructor (right
+ // before each test).
+ }
+
+ virtual void TearDown() {
+ // Code here will be called immediately after each test (right
+ // before the destructor).
+ }
+
+ ::utils::ThreadPool thread_pool_;
+};
+
+TEST_F(ThreadPoolTest, DefaultConstructor) {
+ // EXPECT_EQ(thread_pool_.GetNumThreads(), 0);
+ // EXPECT_EQ(thread_pool_.GetNumIdleThreads(), 0);
+ // EXPECT_EQ(thread_pool_.GetNumBusyThreads(), 0);
+}
+
+TEST_F(ThreadPoolTest, GetNThreads) {
+ auto n_threads = thread_pool_.getNThreads();
+ EXPECT_GT(n_threads, std::size_t(0));
+ EXPECT_EQ(n_threads, std::thread::hardware_concurrency());
+
+ ::utils::ThreadPool pool(64);
+ n_threads = pool.getNThreads();
+ EXPECT_GT(n_threads, std::size_t(0));
+ EXPECT_NE(n_threads, std::thread::hardware_concurrency());
+ EXPECT_EQ(n_threads, std::size_t(64));
+
+ // EXPECT_EQ(thread_pool_.GetNumThreads(), 0);
+ // EXPECT_EQ(thread_pool_.GetNumIdleThreads(), 0);
+ // EXPECT_EQ(thread_pool_.GetNumBusyThreads(), 0);
+}
+
+} // namespace utils \ No newline at end of file
diff --git a/libtransport/src/test/test_traffic_generator.cc b/libtransport/src/test/test_traffic_generator.cc
new file mode 100644
index 000000000..733acbb74
--- /dev/null
+++ b/libtransport/src/test/test_traffic_generator.cc
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <hicn/transport/utils/traffic_generator.h>
+
+static constexpr int NUM_PINGS = 10;
+static constexpr char PREFIX[] = "b001:1:2:3::";
+static constexpr uint32_t FIRST_SUFFIX = 5;
+
+namespace utils {
+
+using transport::IncrSuffixTrafficGenerator;
+using transport::RandomTrafficGenerator;
+
+class TrafficGeneratorTest : public ::testing::Test {
+ protected:
+ TrafficGeneratorTest() {}
+ virtual ~TrafficGeneratorTest() {}
+};
+
+TEST_F(TrafficGeneratorTest, IncrSuffixGetPrefixAndSuffix) {
+ auto traffic_generator_ = std::make_unique<IncrSuffixTrafficGenerator>(
+ PREFIX, FIRST_SUFFIX, NUM_PINGS);
+
+ std::string prefix = traffic_generator_->getPrefix();
+ EXPECT_EQ(prefix, PREFIX);
+ uint32_t suffix = traffic_generator_->getSuffix();
+ EXPECT_EQ(suffix, FIRST_SUFFIX);
+}
+
+TEST_F(TrafficGeneratorTest, IncrSuffixGetMultipleSuffixes) {
+ auto traffic_generator_ = std::make_unique<IncrSuffixTrafficGenerator>(
+ PREFIX, FIRST_SUFFIX, NUM_PINGS);
+
+ std::string prefix = traffic_generator_->getPrefix();
+ EXPECT_EQ(prefix, PREFIX);
+ EXPECT_EQ(prefix, traffic_generator_->getPrefix());
+
+ for (int i = 0; i < NUM_PINGS; i++)
+ EXPECT_EQ(traffic_generator_->getSuffix(), FIRST_SUFFIX + i);
+}
+
+TEST_F(TrafficGeneratorTest, IncrSuffixReset) {
+ auto traffic_generator_ = std::make_unique<IncrSuffixTrafficGenerator>(
+ PREFIX, FIRST_SUFFIX, NUM_PINGS);
+
+ for (int i = 0; i < NUM_PINGS; i++) traffic_generator_->getSuffix();
+
+ traffic_generator_->reset();
+ EXPECT_EQ(traffic_generator_->getPrefix(), PREFIX);
+ EXPECT_EQ(traffic_generator_->getSuffix(), FIRST_SUFFIX);
+ EXPECT_EQ(traffic_generator_->getSuffix(), FIRST_SUFFIX + 1);
+}
+
+TEST_F(TrafficGeneratorTest, IncrSuffixRequestTooManySuffixes) {
+ auto traffic_generator_ = std::make_unique<IncrSuffixTrafficGenerator>(
+ PREFIX, FIRST_SUFFIX, NUM_PINGS);
+
+ for (int i = 0; i < NUM_PINGS; i++) traffic_generator_->getSuffix();
+ EXPECT_THROW(traffic_generator_->getSuffix(), std::runtime_error);
+}
+
+TEST_F(TrafficGeneratorTest, IncrSuffixGetPrefixAndSuffixTogether) {
+ auto traffic_generator_ = std::make_unique<IncrSuffixTrafficGenerator>(
+ PREFIX, FIRST_SUFFIX, NUM_PINGS);
+
+ auto [prefix, suffix] = traffic_generator_->getPrefixAndSuffix();
+ EXPECT_EQ(prefix, PREFIX);
+ EXPECT_EQ(suffix, FIRST_SUFFIX);
+}
+
+TEST_F(TrafficGeneratorTest, IncrSuffixCheckSentCount) {
+ auto traffic_generator_ = std::make_unique<IncrSuffixTrafficGenerator>(
+ PREFIX, FIRST_SUFFIX, NUM_PINGS);
+
+ for (int i = 0; i < NUM_PINGS; i++) {
+ EXPECT_EQ(traffic_generator_->getSentCount(), (uint32_t)i);
+ EXPECT_FALSE(traffic_generator_->hasFinished());
+ traffic_generator_->getSuffix();
+ }
+ EXPECT_TRUE(traffic_generator_->hasFinished());
+}
+
+TEST_F(TrafficGeneratorTest, RandomGetPrefixAndSuffix) {
+ auto traffic_generator_ = std::make_unique<RandomTrafficGenerator>(NUM_PINGS);
+
+ std::string prefix1 = traffic_generator_->getPrefix();
+ std::string prefix2 = traffic_generator_->getPrefix();
+ EXPECT_NE(prefix1, prefix2);
+
+ uint32_t suffix1 = traffic_generator_->getSuffix();
+ uint32_t suffix2 = traffic_generator_->getSuffix();
+ EXPECT_NE(suffix1, suffix2);
+}
+
+TEST_F(TrafficGeneratorTest, RandomGetPrefixAndSuffixWithNetPrefix) {
+ auto traffic_generator_ = std::make_unique<RandomTrafficGenerator>(
+ NUM_PINGS, std::string(PREFIX) + "/64");
+
+ for (int i = 0; i < NUM_PINGS; i++)
+ EXPECT_THAT(traffic_generator_->getPrefix(),
+ testing::StartsWith(std::string(PREFIX)));
+}
+
+} // namespace utils \ No newline at end of file
diff --git a/libtransport/src/transport.config b/libtransport/src/transport.config
index 89db204d5..d5c2918a6 100644
--- a/libtransport/src/transport.config
+++ b/libtransport/src/transport.config
@@ -17,7 +17,7 @@ forwarder = {
remote_port = 33436;
}
};
-
+
listeners = {
l0 = {
local_address = "127.0.0.1";
diff --git a/libtransport/src/utils/CMakeLists.txt b/libtransport/src/utils/CMakeLists.txt
index a85ab16bf..e7c1c03ea 100644
--- a/libtransport/src/utils/CMakeLists.txt
+++ b/libtransport/src/utils/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -17,12 +17,14 @@ list(APPEND SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/log.cc
${CMAKE_CURRENT_SOURCE_DIR}/membuf.cc
${CMAKE_CURRENT_SOURCE_DIR}/content_store.cc
+ ${CMAKE_CURRENT_SOURCE_DIR}/traffic_generator.cc
)
list(APPEND HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/event_reactor.h
${CMAKE_CURRENT_SOURCE_DIR}/min_filter.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/max_filter.h
${CMAKE_CURRENT_SOURCE_DIR}/stream_buffer.h
${CMAKE_CURRENT_SOURCE_DIR}/suffix_strategy.h
${CMAKE_CURRENT_SOURCE_DIR}/content_store.h
@@ -34,10 +36,6 @@ if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
${CMAKE_CURRENT_SOURCE_DIR}/epoll_event_reactor.h
${CMAKE_CURRENT_SOURCE_DIR}/fd_deadline_timer.h
)
-
- list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/epoll_event_reactor.cc
- )
endif()
if(NOT WIN32)
diff --git a/libtransport/src/utils/content_store.cc b/libtransport/src/utils/content_store.cc
index 8ae7fd4d4..d9d4147f7 100644
--- a/libtransport/src/utils/content_store.cc
+++ b/libtransport/src/utils/content_store.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -17,6 +17,7 @@
#include <hicn/transport/core/content_object.h>
#include <hicn/transport/core/interest.h>
#include <hicn/transport/core/name.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <utils/content_store.h>
namespace utils {
@@ -56,7 +57,7 @@ void ContentStore::insert(
fifo_list_.push_front(std::cref(content_object->getName()));
auto pos = fifo_list_.begin();
content_store_hash_table_[content_object->getName()] = ContentStoreEntry(
- ObjectTimeEntry(content_object, std::chrono::steady_clock::now()), pos);
+ ObjectTimeEntry(content_object, utils::SteadyTime::now()), pos);
}
std::shared_ptr<ContentObject> ContentStore::find(const Name &name) {
@@ -67,8 +68,8 @@ std::shared_ptr<ContentObject> ContentStore::find(const Name &name) {
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>(
- std::chrono::steady_clock::now() - it->second.first.second)
+ utils::SteadyTime::getDurationMs(it->second.first.second,
+ utils::SteadyTime::now())
.count();
if (time_passed_since_creation > content_lifetime) {
diff --git a/libtransport/src/utils/content_store.h b/libtransport/src/utils/content_store.h
index abe5e7f6c..ecd62cc2c 100644
--- a/libtransport/src/utils/content_store.h
+++ b/libtransport/src/utils/content_store.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -35,8 +35,7 @@ using Name = transport::core::Name;
using ContentObject = transport::core::ContentObject;
using Interest = transport::core::Interest;
-typedef std::pair<std::shared_ptr<ContentObject>,
- std::chrono::steady_clock::time_point>
+typedef std::pair<std::shared_ptr<ContentObject>, utils::SteadyTime::TimePoint>
ObjectTimeEntry;
typedef std::pair<ObjectTimeEntry,
std::list<std::reference_wrapper<const Name>>::iterator>
diff --git a/libtransport/src/utils/daemonizator.cc b/libtransport/src/utils/daemonizator.cc
index 6cb7d16ba..4c17aa96b 100644
--- a/libtransport/src/utils/daemonizator.cc
+++ b/libtransport/src/utils/daemonizator.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/utils/deadline_timer.h b/libtransport/src/utils/deadline_timer.h
index 5187754f0..6c105ed3d 100644
--- a/libtransport/src/utils/deadline_timer.h
+++ b/libtransport/src/utils/deadline_timer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -22,61 +22,6 @@
#include <cstring>
#include <utility>
-namespace std {
-namespace chrono {
-namespace detail {
-
-template <typename From, typename To>
-struct posix_duration_cast;
-
-// chrono -> timespec caster
-template <typename Rep, typename Period>
-struct posix_duration_cast<std::chrono::duration<Rep, Period>,
- struct timespec> {
- static struct timespec cast(std::chrono::duration<Rep, Period> const &d) {
- struct timespec tv;
-
- std::chrono::seconds const sec =
- std::chrono::duration_cast<std::chrono::seconds>(d);
-
- tv.tv_sec = sec.count();
- tv.tv_nsec =
- std::chrono::duration_cast<std::chrono::nanoseconds>(d - sec).count();
-
- return tv;
- }
-};
-
-// timespec -> chrono caster
-template <typename Rep, typename Period>
-struct posix_duration_cast<struct timespec,
- std::chrono::duration<Rep, Period>> {
- static std::chrono::duration<Rep, Period> cast(struct timespec const &tv) {
- return std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(
- std::chrono::seconds(tv.tv_sec) + std::chrono::nanoseconds(tv.tv_nsec));
- }
-};
-
-} // namespace detail
-
-// chrono -> timespec
-template <typename T, typename Rep, typename Period>
-auto duration_cast(std::chrono::duration<Rep, Period> const &d) ->
- typename std::enable_if<std::is_same<T, struct timespec>::value,
- struct timespec>::type {
- return detail::posix_duration_cast<std::chrono::duration<Rep, Period>,
- timespec>::cast(d);
-}
-
-// timespec -> chrono
-template <typename Duration>
-Duration duration_cast(struct timespec const &tv) {
- return detail::posix_duration_cast<struct timespec, Duration>::cast(tv);
-}
-
-} // namespace chrono
-} // namespace std
-
namespace utils {
template <typename Implementation>
diff --git a/libtransport/src/utils/epoll_event_reactor.cc b/libtransport/src/utils/epoll_event_reactor.cc
deleted file mode 100644
index 457727bbe..000000000
--- a/libtransport/src/utils/epoll_event_reactor.cc
+++ /dev/null
@@ -1,190 +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 <glog/logging.h>
-#include <hicn/transport/utils/branch_prediction.h>
-#include <signal.h>
-#include <unistd.h>
-#include <utils/epoll_event_reactor.h>
-#include <utils/fd_deadline_timer.h>
-
-#include <iostream>
-
-namespace utils {
-
-EpollEventReactor::EpollEventReactor()
- : epoll_fd_(epoll_create(20000)), run_event_loop_(true) {}
-
-EpollEventReactor::~EpollEventReactor() { close(epoll_fd_); }
-
-int EpollEventReactor::addFileDescriptor(int fd, uint32_t events) {
- if (TRANSPORT_EXPECT_FALSE(fd < 0)) {
- LOG(ERROR) << "invalid fd " << fd;
- return -1;
- }
-
- struct epoll_event evt;
- std::memset(&evt, 0, sizeof(evt));
- evt.events = events;
- evt.data.fd = fd;
-
- if (TRANSPORT_EXPECT_FALSE(epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &evt) <
- 0)) {
- LOG(ERROR) << "epoll_ctl: " << strerror(errno) << " fd " << fd;
- return -1;
- }
-
- return 0;
-}
-
-int EpollEventReactor::modFileDescriptor(int fd, uint32_t events) {
- if (TRANSPORT_EXPECT_FALSE(fd < 0)) {
- LOG(ERROR) << "invalid fd " << fd;
- return -1;
- }
-
- struct epoll_event evt;
- memset(&evt, 0, sizeof(evt));
- evt.events = events;
- evt.data.fd = fd;
-
- if (TRANSPORT_EXPECT_FALSE(epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &evt) <
- 0)) {
- LOG(ERROR) << "epoll_ctl: " << strerror(errno) << " fd " << fd;
- return -1;
- }
-
- return 0;
-}
-
-std::size_t EpollEventReactor::mapSize() { return event_callback_map_.size(); }
-
-int EpollEventReactor::delFileDescriptor(int fd) {
- if (TRANSPORT_EXPECT_FALSE(fd < 0)) {
- LOG(ERROR) << "invalid fd " << fd;
- return -1;
- }
-
- struct epoll_event evt;
- memset(&evt, 0, sizeof(evt));
-
- if (TRANSPORT_EXPECT_FALSE(epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &evt) <
- 0)) {
- LOG(ERROR) << "epoll_ctl: " << strerror(errno) << " fd " << fd;
- return -1;
- }
-
- utils::SpinLock::Acquire locked(event_callback_map_lock_);
- event_callback_map_.erase(fd);
-
- return 0;
-}
-
-void EpollEventReactor::runEventLoop(int timeout) {
- Event evt[128];
- int en = 0;
- EventCallbackMap::iterator it;
- EventCallback callback;
-
- // evt.events = EPOLLIN | EPOLLOUT;
- sigset_t sigset;
- sigemptyset(&sigset);
-
- while (run_event_loop_) {
- memset(&evt, 0, sizeof(evt));
- en = epoll_pwait(epoll_fd_, evt, 128, timeout, &sigset);
-
- if (TRANSPORT_EXPECT_FALSE(en < 0)) {
- LOG(ERROR) << "epoll_pwait: " << strerror(errno);
- if (errno == EINTR) {
- continue;
- } else {
- return;
- }
- }
-
- for (int i = 0; i < en; i++) {
- if (evt[i].data.fd > 0) {
- {
- utils::SpinLock::Acquire locked(event_callback_map_lock_);
- it = event_callback_map_.find(evt[i].data.fd);
- }
-
- if (TRANSPORT_EXPECT_FALSE(it == event_callback_map_.end())) {
- LOG(ERROR) << "unexpected event. fd " << evt[i].data.fd;
- } else {
- {
- utils::SpinLock::Acquire locked(event_callback_map_lock_);
- callback = event_callback_map_[evt[i].data.fd];
- }
-
- callback(evt[i]);
-
- // In the callback the epoll event reactor could have been stopped,
- // then we need to check whether the event loop is still running.
- if (TRANSPORT_EXPECT_FALSE(!run_event_loop_)) {
- return;
- }
- }
- } else {
- LOG(ERROR) << "unexpected event. fd " << evt[i].data.fd;
- }
- }
- }
-}
-
-void EpollEventReactor::runOneEvent() {
- Event evt;
- int en = 0;
- EventCallbackMap::iterator it;
- EventCallback callback;
-
- // evt.events = EPOLLIN | EPOLLOUT;
- sigset_t sigset;
- sigemptyset(&sigset);
-
- memset(&evt, 0, sizeof(evt));
-
- en = epoll_pwait(epoll_fd_, &evt, 1, -1, &sigset);
-
- if (TRANSPORT_EXPECT_FALSE(en < 0)) {
- LOG(ERROR) << "epoll_pwait: " << strerror(errno);
- return;
- }
-
- if (TRANSPORT_EXPECT_TRUE(evt.data.fd > 0)) {
- {
- utils::SpinLock::Acquire locked(event_callback_map_lock_);
- it = event_callback_map_.find(evt.data.fd);
- }
-
- if (TRANSPORT_EXPECT_FALSE(it == event_callback_map_.end())) {
- LOG(ERROR) << "unexpected event. fd " << evt.data.fd;
- } else {
- {
- utils::SpinLock::Acquire locked(event_callback_map_lock_);
- callback = event_callback_map_[evt.data.fd];
- }
-
- callback(evt);
- }
- } else {
- LOG(ERROR) << "unexpected event. fd " << evt.data.fd;
- }
-}
-
-void EpollEventReactor::stop() { run_event_loop_ = false; }
-
-} // namespace utils \ No newline at end of file
diff --git a/libtransport/src/utils/epoll_event_reactor.h b/libtransport/src/utils/epoll_event_reactor.h
index 9ebfca937..32d99c837 100644
--- a/libtransport/src/utils/epoll_event_reactor.h
+++ b/libtransport/src/utils/epoll_event_reactor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,6 +15,7 @@
#pragma once
+#include <glog/logging.h>
#include <hicn/transport/utils/spinlock.h>
#include <sys/epoll.h>
#include <utils/event_reactor.h>
@@ -35,9 +36,10 @@ typedef std::unordered_map<int, EventCallback> EventCallbackMap;
class EpollEventReactor : public EventReactor {
public:
- explicit EpollEventReactor();
+ explicit EpollEventReactor()
+ : epoll_fd_(epoll_create(20000)), run_event_loop_(true) {}
- ~EpollEventReactor();
+ ~EpollEventReactor() { close(epoll_fd_); }
template <typename EventHandler>
int addFileDescriptor(int fd, uint32_t events, EventHandler &&callback) {
@@ -47,7 +49,7 @@ class EpollEventReactor : public EventReactor {
if (it == event_callback_map_.end()) {
{
utils::SpinLock::Acquire locked(event_callback_map_lock_);
- event_callback_map_[fd] = std::forward<EventHandler &&>(callback);
+ event_callback_map_[fd] = std::forward<EventHandler>(callback);
}
ret = addFileDescriptor(fd, events);
@@ -56,20 +58,163 @@ class EpollEventReactor : public EventReactor {
return ret;
}
- int delFileDescriptor(int fd);
+ int delFileDescriptor(int fd) {
+ if (TRANSPORT_EXPECT_FALSE(fd < 0)) {
+ LOG(ERROR) << "invalid fd " << fd;
+ return -1;
+ }
+
+ struct epoll_event evt;
+ memset(&evt, 0, sizeof(evt));
+
+ if (TRANSPORT_EXPECT_FALSE(epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &evt) <
+ 0)) {
+ return -1;
+ }
+
+ utils::SpinLock::Acquire locked(event_callback_map_lock_);
+ event_callback_map_.erase(fd);
+
+ return 0;
+ }
+
+ int modFileDescriptor(int fd, uint32_t events) {
+ if (TRANSPORT_EXPECT_FALSE(fd < 0)) {
+ LOG(ERROR) << "invalid fd " << fd;
+ return -1;
+ }
+
+ struct epoll_event evt;
+ memset(&evt, 0, sizeof(evt));
+ evt.events = events;
+ evt.data.fd = fd;
+
+ if (TRANSPORT_EXPECT_FALSE(epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &evt) <
+ 0)) {
+ LOG(ERROR) << "epoll_ctl: " << strerror(errno) << " fd " << fd;
+ return -1;
+ }
+
+ return 0;
+ }
+
+ void runEventLoop(int timeout = -1) override {
+ Event evt[128];
+ int en = 0;
+ EventCallbackMap::iterator it;
+ EventCallback callback;
+
+ // evt.events = EPOLLIN | EPOLLOUT;
+ sigset_t sigset;
+ sigemptyset(&sigset);
+
+ while (run_event_loop_) {
+ memset(&evt, 0, sizeof(evt));
+ en = epoll_pwait(epoll_fd_, evt, 128, timeout, &sigset);
+
+ if (TRANSPORT_EXPECT_FALSE(en < 0)) {
+ LOG(ERROR) << "epoll_pwait: " << strerror(errno);
+ if (errno == EINTR) {
+ continue;
+ } else {
+ return;
+ }
+ }
+
+ for (int i = 0; i < en; i++) {
+ if (evt[i].data.fd > 0) {
+ {
+ utils::SpinLock::Acquire locked(event_callback_map_lock_);
+ it = event_callback_map_.find(evt[i].data.fd);
+ }
+
+ if (TRANSPORT_EXPECT_FALSE(it == event_callback_map_.end())) {
+ LOG(ERROR) << "unexpected event. fd " << evt[i].data.fd;
+ } else {
+ {
+ utils::SpinLock::Acquire locked(event_callback_map_lock_);
+ callback = event_callback_map_[evt[i].data.fd];
+ }
+
+ callback(evt[i]);
+
+ // In the callback the epoll event reactor could have been stopped,
+ // then we need to check whether the event loop is still running.
+ if (TRANSPORT_EXPECT_FALSE(!run_event_loop_)) {
+ return;
+ }
+ }
+ } else {
+ LOG(ERROR) << "unexpected event. fd " << evt[i].data.fd;
+ }
+ }
+ }
+ }
+
+ void runOneEvent() override {
+ Event evt;
+ int en = 0;
+ EventCallbackMap::iterator it;
+ EventCallback callback;
- int modFileDescriptor(int fd, uint32_t events);
+ // evt.events = EPOLLIN | EPOLLOUT;
+ sigset_t sigset;
+ sigemptyset(&sigset);
- void runEventLoop(int timeout = -1) override;
+ memset(&evt, 0, sizeof(evt));
- void runOneEvent() override;
+ en = epoll_pwait(epoll_fd_, &evt, 1, -1, &sigset);
- void stop() override;
+ if (TRANSPORT_EXPECT_FALSE(en < 0)) {
+ LOG(ERROR) << "epoll_pwait: " << strerror(errno);
+ return;
+ }
+
+ if (TRANSPORT_EXPECT_TRUE(evt.data.fd > 0)) {
+ {
+ utils::SpinLock::Acquire locked(event_callback_map_lock_);
+ it = event_callback_map_.find(evt.data.fd);
+ }
- std::size_t mapSize();
+ if (TRANSPORT_EXPECT_FALSE(it == event_callback_map_.end())) {
+ LOG(ERROR) << "unexpected event. fd " << evt.data.fd;
+ } else {
+ {
+ utils::SpinLock::Acquire locked(event_callback_map_lock_);
+ callback = event_callback_map_[evt.data.fd];
+ }
+
+ callback(evt);
+ }
+ } else {
+ LOG(ERROR) << "unexpected event. fd " << evt.data.fd;
+ }
+ }
+
+ void stop() override { run_event_loop_ = false; }
+
+ std::size_t mapSize() { return event_callback_map_.size(); }
private:
- int addFileDescriptor(int fd, uint32_t events);
+ int addFileDescriptor(int fd, uint32_t events) {
+ if (TRANSPORT_EXPECT_FALSE(fd < 0)) {
+ LOG(ERROR) << "invalid fd " << fd;
+ return -1;
+ }
+
+ struct epoll_event evt;
+ std::memset(&evt, 0, sizeof(evt));
+ evt.events = events;
+ evt.data.fd = fd;
+
+ if (TRANSPORT_EXPECT_FALSE(epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &evt) <
+ 0)) {
+ LOG(ERROR) << "epoll_ctl: " << strerror(errno) << " fd " << fd;
+ return -1;
+ }
+
+ return 0;
+ }
int epoll_fd_;
std::atomic_bool run_event_loop_;
diff --git a/libtransport/src/utils/event_reactor.h b/libtransport/src/utils/event_reactor.h
index 4f8b58296..09af6f84c 100644
--- a/libtransport/src/utils/event_reactor.h
+++ b/libtransport/src/utils/event_reactor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/utils/fd_deadline_timer.h b/libtransport/src/utils/fd_deadline_timer.h
index 22c13a763..7ecbba69b 100644
--- a/libtransport/src/utils/fd_deadline_timer.h
+++ b/libtransport/src/utils/fd_deadline_timer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -16,6 +16,7 @@
#pragma once
#include <hicn/transport/errors/runtime_exception.h>
+#include <hicn/transport/utils/chrono_typedefs.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <utils/deadline_timer.h>
@@ -37,6 +38,11 @@ class FdDeadlineTimer : public DeadlineTimer<FdDeadlineTimer> {
}
}
+ FdDeadlineTimer(const FdDeadlineTimer &other)
+ : reactor_(other.reactor_),
+ timer_fd_(other.timer_fd_),
+ flags_(other.flags_) {}
+
~FdDeadlineTimer() { close(timer_fd_); }
template <typename WaitHandler>
@@ -51,8 +57,8 @@ class FdDeadlineTimer : public DeadlineTimer<FdDeadlineTimer> {
reactor_.addFileDescriptor(
timer_fd_, events,
- [callback = std::forward<WaitHandler &&>(callback)](
- const Event &event) -> int {
+ [callback =
+ std::forward<WaitHandler>(callback)](const Event &event) -> int {
uint64_t s = 0;
std::error_code ec;
@@ -86,8 +92,7 @@ class FdDeadlineTimer : public DeadlineTimer<FdDeadlineTimer> {
template <typename T, typename R>
void expiresFromNowImpl(std::chrono::duration<T, R> &&duration) {
std::memset(&new_value_, 0, sizeof(new_value_));
- new_value_.it_value = std::chrono::duration_cast<struct timespec>(
- std::forward<std::chrono::duration<T, R>>(duration));
+ new_value_.it_value = std::chrono::duration_cast<struct timespec>(duration);
}
template <typename TimePoint,
diff --git a/libtransport/src/utils/log.cc b/libtransport/src/utils/log.cc
index 755d5bafa..44acf4595 100644
--- a/libtransport/src/utils/log.cc
+++ b/libtransport/src/utils/log.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2021 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -36,7 +36,7 @@ foreach_log_level
static constexpr char log_config_section[] = "log";
#define LOG_NAME \
"Libhicntransport-" HICNTRANSPORT_VERSION_MAJOR \
- "." HICNTRANSPORT_VERSION_MINOR "." HICNTRANSPORT_VERSION_REVISION
+ "." HICNTRANSPORT_VERSION_MINOR "." HICNTRANSPORT_VERSION_PATCH
static constexpr char log_name[] = LOG_NAME;
#define foreach_log_config \
diff --git a/libtransport/src/utils/max_filter.h b/libtransport/src/utils/max_filter.h
new file mode 100644
index 000000000..db1a1a565
--- /dev/null
+++ b/libtransport/src/utils/max_filter.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2021 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.sudo make instamake install
+ */
+
+#pragma once
+
+#include <deque>
+#include <iostream>
+#include <set>
+#include <type_traits>
+#include <vector>
+
+namespace utils {
+
+template <typename T>
+class MaxFilter {
+ public:
+ MaxFilter(std::size_t size) : size_(size) {}
+
+ std::size_t size() const { return by_arrival_.size(); }
+
+ template <typename R>
+ void pushBack(R&& value) {
+ if (by_arrival_.size() >= size_) {
+ by_order_.erase(by_arrival_.back());
+ by_arrival_.pop_back();
+ }
+
+ by_arrival_.push_front(by_order_.insert(std::forward<R>(value)));
+ }
+
+ void clear() {
+ by_arrival_.clear();
+ by_order_.clear();
+ }
+
+ const T& begin() const { return *by_order_.crbegin(); }
+
+ const T& rBegin() const { return *by_order_.rbegin(); }
+
+ private:
+ std::multiset<T> by_order_;
+ std::deque<typename std::multiset<T>::const_iterator> by_arrival_;
+ std::size_t size_;
+};
+
+} // namespace utils
diff --git a/libtransport/src/utils/membuf.cc b/libtransport/src/utils/membuf.cc
index 73c45cf6d..952116bb7 100644
--- a/libtransport/src/utils/membuf.cc
+++ b/libtransport/src/utils/membuf.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* 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.
@@ -22,6 +22,7 @@
#include <hicn/transport/portability/win_portability.h>
#endif
+#include <glog/logging.h>
#include <hicn/transport/utils/membuf.h>
#include <cassert>
@@ -209,7 +210,7 @@ MemBuf::MemBuf(CopyBufferOp /* op */, const void* buf, std::size_t size,
: MemBuf(CREATE, headroom + size + min_tailroom) {
advance(headroom);
if (size > 0) {
- assert(buf != nullptr);
+ DCHECK(buf != nullptr);
memcpy(writableData(), buf, size);
append(size);
}
@@ -369,8 +370,8 @@ MemBuf::MemBuf(InternalConstructor, uintptr_t flagsAndSharedInfo, uint8_t* buf,
length_(length),
capacity_(capacity),
flags_and_shared_info_(flagsAndSharedInfo) {
- assert(data >= buf);
- assert(data + length <= buf + capacity);
+ DCHECK(data >= buf);
+ DCHECK(data + length <= buf + capacity);
}
MemBuf::~MemBuf() {
@@ -559,7 +560,7 @@ void MemBuf::unshareOneSlow() {
// minimum capacity we also maintain at least the same amount of tailroom.
std::size_t headlen = headroom();
if (length_ > 0) {
- assert(data_ != nullptr);
+ DCHECK(data_ != nullptr);
memcpy(buf + headlen, data_, length_);
}
@@ -576,7 +577,7 @@ void MemBuf::unshareOneSlow() {
void MemBuf::unshareChained() {
// unshareChained() should only be called if we are part of a chain of
// multiple MemBufs. The caller should have already verified this.
- assert(isChained());
+ DCHECK(isChained());
MemBuf* current = this;
while (true) {
@@ -606,7 +607,7 @@ void MemBuf::markExternallyShared() {
}
void MemBuf::makeManagedChained() {
- assert(isChained());
+ DCHECK(isChained());
MemBuf* current = this;
while (true) {
@@ -677,15 +678,15 @@ void MemBuf::coalesceAndReallocate(size_t new_headroom, size_t new_length,
size_t remaining = new_length;
do {
if (current->length_ > 0) {
- assert(current->length_ <= remaining);
- assert(current->data_ != nullptr);
+ DCHECK(current->length_ <= remaining);
+ DCHECK(current->data_ != nullptr);
remaining -= current->length_;
memcpy(p, current->data_, current->length_);
p += current->length_;
}
current = current->next_;
} while (current != end);
- assert(remaining == 0);
+ DCHECK(remaining == 0);
// Point at the new buffer
decrementRefcount();
@@ -799,7 +800,7 @@ void MemBuf::reserveSlow(std::size_t min_headroom, std::size_t min_tailroom) {
new_allocated_capacity = goodExtBufferSize(new_capacity);
new_buffer = static_cast<uint8_t*>(malloc(new_allocated_capacity));
if (length_ > 0) {
- assert(data_ != nullptr);
+ DCHECK(data_ != nullptr);
memcpy(new_buffer + min_headroom, data_, length_);
}
if (sharedInfo()) {
diff --git a/libtransport/src/utils/memory_pool_allocator.h b/libtransport/src/utils/memory_pool_allocator.h
index a960b91bb..c2b34e7aa 100644
--- a/libtransport/src/utils/memory_pool_allocator.h
+++ b/libtransport/src/utils/memory_pool_allocator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/utils/min_filter.h b/libtransport/src/utils/min_filter.h
index 092555ce0..4a3882601 100644
--- a/libtransport/src/utils/min_filter.h
+++ b/libtransport/src/utils/min_filter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -28,7 +28,7 @@ class MinFilter {
public:
MinFilter(std::size_t size) : size_(size) {}
- std::size_t size() { return by_arrival_.size(); }
+ std::size_t size() const { return by_arrival_.size(); }
template <typename R>
void pushBack(R&& value) {
@@ -45,9 +45,9 @@ class MinFilter {
by_order_.clear();
}
- const T& begin() { return *by_order_.cbegin(); }
+ const T& begin() const { return *by_order_.cbegin(); }
- const T& rBegin() { return *by_order_.crbegin(); }
+ const T& rBegin() const { return *by_order_.crbegin(); }
private:
std::multiset<T> by_order_;
diff --git a/libtransport/src/utils/stream_buffer.h b/libtransport/src/utils/stream_buffer.h
index adfb696f2..dde769a55 100644
--- a/libtransport/src/utils/stream_buffer.h
+++ b/libtransport/src/utils/stream_buffer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/utils/string_tokenizer.cc b/libtransport/src/utils/string_tokenizer.cc
index a280a3c43..cb0a4a3ad 100644
--- a/libtransport/src/utils/string_tokenizer.cc
+++ b/libtransport/src/utils/string_tokenizer.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/utils/suffix_strategy.h b/libtransport/src/utils/suffix_strategy.h
index ee016308e..4b3ddbc74 100644
--- a/libtransport/src/utils/suffix_strategy.h
+++ b/libtransport/src/utils/suffix_strategy.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -15,72 +15,88 @@
#pragma once
-#include <core/manifest_format.h>
+#include <hicn/transport/core/name.h>
+#include <hicn/transport/errors/runtime_exception.h>
namespace utils {
-using transport::core::NextSegmentCalculationStrategy;
+/**
+ * INCREMENTAL: Manifests will be received inline with the data with no specific
+ * assumption regarding the manifest capacity. Consumers can send interests
+ * using a +1 heuristic.
+ *
+ * MANIFEST_CAPACITY_BASED: manifests with capacity N have a suffix multiple of
+ * N+1: 0, N+1, 2(N+1) etc. Contents have a suffix incremented by 1 except when
+ * it conflicts with a manifest: 1, 2, ..., N, N+2, N+3, ..., 2N+1, 2N+3
+ */
+enum class NextSuffixStrategy : uint8_t {
+ INCREMENTAL = 1,
+};
class SuffixStrategy {
public:
- static constexpr uint32_t INVALID_SUFFIX =
- std::numeric_limits<uint32_t>::max();
+ static constexpr uint32_t MAX_SUFFIX = std::numeric_limits<uint32_t>::max();
+ static constexpr uint8_t MANIFEST_MAX_CAPACITY =
+ std::numeric_limits<uint8_t>::max();
- SuffixStrategy(NextSegmentCalculationStrategy strategy)
+ SuffixStrategy(NextSuffixStrategy strategy, uint32_t offset = 0,
+ uint32_t manifest_capacity = MANIFEST_MAX_CAPACITY)
: suffix_stragegy_(strategy),
+ next_suffix_(offset),
+ manifest_capacity_(manifest_capacity),
total_count_(0),
- final_suffix_(INVALID_SUFFIX) {}
+ final_suffix_(MAX_SUFFIX) {}
virtual ~SuffixStrategy() = default;
- virtual uint32_t checkNextSuffix() = 0;
-
+ virtual uint32_t checkNextSuffix() const = 0;
virtual uint32_t getNextSuffix() = 0;
- virtual uint32_t getFinalSuffix() { return final_suffix_; }
-
- virtual void setFinalSuffix(std::uint32_t final_suffix) {
- if (final_suffix != INVALID_SUFFIX) {
- final_suffix_ = final_suffix;
- }
- }
-
- virtual uint32_t checkNextManifestSuffix() = 0;
-
+ virtual uint32_t checkNextManifestSuffix() const = 0;
virtual uint32_t getNextManifestSuffix() = 0;
- virtual uint32_t checkNextContentSuffix() = 0;
-
+ virtual uint32_t checkNextContentSuffix() const = 0;
virtual uint32_t getNextContentSuffix() = 0;
- virtual void reset(uint32_t offset = 0) = 0;
+ virtual void reset(uint32_t offset = 0) {
+ next_suffix_ = offset;
+ total_count_ = 0;
+ }
- virtual uint32_t getManifestCapacity() = 0;
+ virtual uint32_t getManifestCapacity() const { return manifest_capacity_; };
- virtual void setManifestCapacity(uint32_t capacity) = 0;
+ virtual void setManifestCapacity(uint8_t capacity) {
+ manifest_capacity_ = capacity;
+ }
- virtual uint32_t getTotalCount() { return total_count_; };
+ virtual uint32_t getFinalSuffix() const { return final_suffix_; }
- NextSegmentCalculationStrategy getSuffixStrategy() {
- return suffix_stragegy_;
+ virtual void setFinalSuffix(std::uint32_t final_suffix) {
+ if (final_suffix != MAX_SUFFIX) {
+ final_suffix_ = final_suffix;
+ }
}
- protected:
- inline void incrementTotalCount() { total_count_++; };
+ NextSuffixStrategy getSuffixStrategy() const { return suffix_stragegy_; }
+
+ virtual uint32_t getTotalCount() const { return total_count_; }
protected:
- NextSegmentCalculationStrategy suffix_stragegy_;
+ NextSuffixStrategy suffix_stragegy_;
+ std::uint32_t next_suffix_;
+ std::uint8_t manifest_capacity_;
std::uint32_t total_count_;
std::uint32_t final_suffix_;
+
+ inline void incrementTotalCount() { total_count_++; };
};
class IncrementalSuffixStrategy : public SuffixStrategy {
public:
IncrementalSuffixStrategy(std::uint32_t start_offset)
- : SuffixStrategy(NextSegmentCalculationStrategy::INCREMENTAL),
- next_suffix_(start_offset) {}
+ : SuffixStrategy(NextSuffixStrategy::INCREMENTAL, start_offset) {}
- TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextSuffix() override {
+ TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextSuffix() const override {
return next_suffix_;
}
@@ -89,7 +105,8 @@ class IncrementalSuffixStrategy : public SuffixStrategy {
return next_suffix_++;
}
- TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextContentSuffix() override {
+ TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextContentSuffix()
+ const override {
return checkNextSuffix();
}
@@ -97,7 +114,8 @@ class IncrementalSuffixStrategy : public SuffixStrategy {
return getNextSuffix();
}
- TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextManifestSuffix() override {
+ TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextManifestSuffix()
+ const override {
return checkNextSuffix();
}
@@ -105,90 +123,20 @@ class IncrementalSuffixStrategy : public SuffixStrategy {
return getNextSuffix();
}
- uint32_t getManifestCapacity() override {
- throw errors::RuntimeException(
- "No manifest capacity in IncrementalSuffixStrategy.");
- }
-
- void setManifestCapacity(uint32_t capacity) override {
- throw errors::RuntimeException(
- "No manifest capacity in IncrementalSuffixStrategy.");
- }
-
void reset(std::uint32_t offset = 0) override { next_suffix_ = offset; }
-
- protected:
- std::uint32_t next_suffix_;
-};
-
-class CapacityBasedSuffixStrategy : public SuffixStrategy {
- public:
- CapacityBasedSuffixStrategy(std::uint32_t start_offset,
- std::uint32_t manifest_capacity)
- : SuffixStrategy(NextSegmentCalculationStrategy::INCREMENTAL),
- next_suffix_(start_offset),
- segments_in_manifest_(manifest_capacity),
- current_manifest_iteration_(0) {}
-
- TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextSuffix() override {
- return next_suffix_;
- }
-
- TRANSPORT_ALWAYS_INLINE std::uint32_t getNextSuffix() override {
- incrementTotalCount();
- return next_suffix_++;
- }
-
- TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextContentSuffix() override {
- return next_suffix_ % segments_in_manifest_ == 0 ? next_suffix_
- : (next_suffix_ + 1);
- }
-
- TRANSPORT_ALWAYS_INLINE std::uint32_t getNextContentSuffix() override {
- incrementTotalCount();
- return next_suffix_ % segments_in_manifest_ == 0 ? next_suffix_++
- : ++next_suffix_;
- }
-
- TRANSPORT_ALWAYS_INLINE std::uint32_t checkNextManifestSuffix() override {
- return (current_manifest_iteration_ + 1) * (segments_in_manifest_ + 1);
- }
-
- TRANSPORT_ALWAYS_INLINE std::uint32_t getNextManifestSuffix() override {
- incrementTotalCount();
- return (current_manifest_iteration_++) * (segments_in_manifest_ + 1);
- }
-
- TRANSPORT_ALWAYS_INLINE uint32_t getManifestCapacity() override {
- return segments_in_manifest_;
- }
-
- TRANSPORT_ALWAYS_INLINE void setManifestCapacity(uint32_t capacity) override {
- segments_in_manifest_ = capacity;
- }
-
- void reset(std::uint32_t offset = 0) override { next_suffix_ = offset; }
-
- protected:
- std::uint32_t next_suffix_;
- std::uint32_t segments_in_manifest_;
- std::uint32_t current_manifest_iteration_;
};
class SuffixStrategyFactory {
public:
static std::unique_ptr<SuffixStrategy> getSuffixStrategy(
- NextSegmentCalculationStrategy strategy, uint32_t start_offset,
- uint32_t manifest_capacity = 0) {
+ NextSuffixStrategy strategy, uint32_t start_offset = 0,
+ uint32_t manifest_capacity = SuffixStrategy::MANIFEST_MAX_CAPACITY) {
switch (strategy) {
- case NextSegmentCalculationStrategy::INCREMENTAL:
+ case NextSuffixStrategy::INCREMENTAL:
return std::make_unique<IncrementalSuffixStrategy>(start_offset);
- case NextSegmentCalculationStrategy::MANIFEST_CAPACITY_BASED:
- return std::make_unique<CapacityBasedSuffixStrategy>(start_offset,
- manifest_capacity);
default:
throw errors::RuntimeException(
- "No valid NextSegmentCalculationStrategy specified.");
+ "No valid NextSuffixStrategy specified.");
}
}
};
diff --git a/libtransport/src/utils/test.h b/libtransport/src/utils/test.h
index e3dd619ac..b91c8cb1f 100644
--- a/libtransport/src/utils/test.h
+++ b/libtransport/src/utils/test.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/src/utils/traffic_generator.cc b/libtransport/src/utils/traffic_generator.cc
new file mode 100644
index 000000000..a617e3dc9
--- /dev/null
+++ b/libtransport/src/utils/traffic_generator.cc
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hicn/transport/core/prefix.h>
+#include <hicn/transport/utils/traffic_generator.h>
+
+#include <iostream>
+
+namespace transport {
+
+/* TrafficGenerator */
+
+TrafficGenerator::TrafficGenerator(uint32_t count) : count_(count), sent_(0) {}
+
+bool TrafficGenerator::hasFinished() { return sent_ >= count_; }
+
+uint32_t TrafficGenerator::getSentCount() { return sent_; }
+
+std::pair<std::string, uint32_t> TrafficGenerator::getPrefixAndSuffix() {
+ return std::make_pair(getPrefix(), getSuffix());
+}
+
+void TrafficGenerator::reset() { sent_ = 0; };
+
+void TrafficGenerator::onSuffixGenerated() {
+ if (hasFinished()) throw std::runtime_error("Too many pings");
+ sent_++;
+};
+
+/* IncrSuffixTrafficGenerator */
+
+IncrSuffixTrafficGenerator::IncrSuffixTrafficGenerator(std::string prefix,
+ uint32_t suffix,
+ uint32_t count)
+ : TrafficGenerator(count),
+ prefix_(prefix),
+ suffix_(suffix),
+ initial_suffix_(suffix) {}
+
+std::string IncrSuffixTrafficGenerator::getPrefix() { return prefix_; }
+
+uint32_t IncrSuffixTrafficGenerator::getSuffix() {
+ TrafficGenerator::onSuffixGenerated();
+ return suffix_++;
+}
+
+void IncrSuffixTrafficGenerator::reset() {
+ TrafficGenerator::reset();
+ suffix_ = initial_suffix_;
+};
+
+/* RandomTrafficGenerator */
+
+RandomTrafficGenerator::RandomTrafficGenerator(uint32_t count,
+ std::string net_prefix)
+ : TrafficGenerator(count),
+ net_prefix_(net_prefix),
+ rand_engine_((std::random_device())()),
+ uniform_distribution_(0, std::numeric_limits<uint32_t>::max()) {}
+
+std::string RandomTrafficGenerator::getPrefix() {
+ // Generate random prefix
+ core::Prefix prefix(net_prefix_);
+ core::Name name = prefix.makeRandomName();
+ return name.getPrefix();
+}
+
+uint32_t RandomTrafficGenerator::getSuffix() {
+ TrafficGenerator::onSuffixGenerated();
+
+ // Generate random suffix
+ return uniform_distribution_(rand_engine_);
+}
+
+} // namespace transport \ No newline at end of file
diff --git a/libtransport/src/utils/uri.cc b/libtransport/src/utils/uri.cc
index 33eb8b45b..12b11641c 100644
--- a/libtransport/src/utils/uri.cc
+++ b/libtransport/src/utils/uri.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017-2019 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
diff --git a/libtransport/third-party/CMakeLists.txt b/libtransport/third-party/CMakeLists.txt
index 46a4c0f23..25c6f7c20 100644
--- a/libtransport/third-party/CMakeLists.txt
+++ b/libtransport/third-party/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,8 +11,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-include(FetchContent)
-
set (THIRD_PARTY_INSTALL_PREFIX ${CMAKE_CURRENT_BINARY_DIR})
option(ENABLE_RELY "Enable download/build of rely library" OFF)
@@ -20,21 +18,34 @@ option(ENABLE_RELY "Enable download/build of rely library" OFF)
if (ENABLE_RELY)
##################################
# Download librely
-
- if(DEFINED ENV{BITBUCKET_USERNAME} AND DEFINED ENV{BITBUCKET_PASSWORD})
- set(GIT_REPO https://$ENV{BITBUCKET_USERNAME}:$ENV{BITBUCKET_PASSWORD}@bitbucket-eng-gpk1.cisco.com/bitbucket/scm/icn/rely.git)
+
+ if (INTERNAL_ENVIRONMENT)
+ include(SetRelyGitRepo)
+ SetRelyGitRepo()
else()
- set(GIT_REPO ssh://git@bitbucket-eng-gpk1.cisco.com:7999/icn/rely.git)
+ if(DEFINED ENV{GITHUB_USERNAME} AND DEFINED ENV{GITHUB_PASSWORD})
+ set(GIT_REPO https://$ENV{GITHUB_USERNAME}:$ENV{GITHUB_PASSWORD}@github.com/steinwurf/rely.git)
+ else()
+ set(GIT_REPO ssh://github.com/steinwurf/rely.git)
+ endif()
endif()
FetchContent_Declare(
rely
GIT_REPOSITORY ${GIT_REPO}
GIT_TAG release/latest
+ GIT_SHALLOW
+ GIT_PROGRESS
+ EXCLUDE_FROM_ALL
)
set(ENABLE_PIC ON)
- FetchContent_MakeAvailable(rely)
+ FetchContent_GetProperties(rely)
+ if(NOT rely_POPULATED)
+ pr("Download and build" "rely")
+ FetchContent_Populate(rely)
+ add_subdirectory(${rely_SOURCE_DIR} ${rely_BINARY_DIR} EXCLUDE_FROM_ALL)
+ endif()
list(APPEND THIRD_PARTY_INCLUDE_DIRS
${rely_BINARY_DIR}
@@ -44,7 +55,7 @@ if (ENABLE_RELY)
# Get rely libraries
get_property(steinwurf_object_libraries GLOBAL
PROPERTY steinwurf::object_libraries)
-
+
foreach(rely_library ${steinwurf_object_libraries})
list(APPEND THIRD_PARTY_OBJECT_LIBRARIES
$<TARGET_OBJECTS:${rely_library}>
@@ -56,13 +67,28 @@ if (ENABLE_RELY)
)
endif()
+# Avoid warning about DOWNLOAD_EXTRACT_TIMESTAMP in CMake 3.24:
+if (CMAKE_VERSION VERSION_GREATER_EQUAL "3.24.0")
+ cmake_policy(SET CMP0135 NEW)
+endif()
+
FetchContent_Declare(
glog
URL https://github.com/google/glog/archive/refs/tags/v0.5.0.zip
PATCH_COMMAND patch -p1 CMakeLists.txt ${CMAKE_CURRENT_SOURCE_DIR}/glog.patch
+ EXCLUDE_FROM_ALL
)
-FetchContent_MakeAvailable(glog)
+FetchContent_GetProperties(glog)
+if(NOT glog_POPULATED)
+ pr("Download and build" "glog")
+ FetchContent_Populate(glog)
+ option(WITH_GFLAGS OFF)
+ option(WITH_GTEST OFF)
+ option(WITH_UNWIND OFF)
+ option(BUILD_TESTING OFF)
+ add_subdirectory(${glog_SOURCE_DIR} ${glog_BINARY_DIR} EXCLUDE_FROM_ALL)
+endif()
list(APPEND THIRD_PARTY_INCLUDE_DIRS
${glog_BINARY_DIR}
@@ -77,6 +103,42 @@ list(APPEND THIRD_PARTY_DEPENDENCIES
glog
)
+if(UNIX AND (NOT APPLE) AND (NOT ${CMAKE_SYSTEM_NAME} MATCHES Android))
+ ##############################################################
+ # Get memif version
+ ##############################################################
+ list(GET LIBMEMIF_DEFAULT_VERSION 0 MEMIF_VERSION)
+
+ FetchContent_Declare(
+ memif
+ GIT_REPOSITORY https://github.com/FDio/vpp
+ GIT_TAG v${MEMIF_VERSION}
+ GIT_SHALLOW
+ GIT_PROGRESS
+ PATCH_COMMAND git apply ${CMAKE_CURRENT_SOURCE_DIR}/memif.patch || true
+ EXCLUDE_FROM_ALL
+ )
+
+ FetchContent_GetProperties(memif)
+ if(NOT memif_POPULATED)
+ FetchContent_Populate(memif)
+ add_subdirectory(${memif_SOURCE_DIR}/extras/libmemif ${memif_BINARY_DIR} EXCLUDE_FROM_ALL)
+ endif()
+
+ list(APPEND THIRD_PARTY_INCLUDE_DIRS
+ ${memif_BINARY_DIR}
+ ${memif_SOURCE_DIR}/extras/libmemif/src
+ )
+
+ list(APPEND THIRD_PARTY_OBJECT_LIBRARIES
+ $<TARGET_OBJECTS:memif>
+ )
+
+ list(APPEND THIRD_PARTY_DEPENDENCIES
+ memif
+ )
+endif()
+
set (THIRD_PARTY_LIBRARIES ${THIRD_PARTY_LIBRARIES} PARENT_SCOPE)
set (THIRD_PARTY_OBJECT_LIBRARIES ${THIRD_PARTY_OBJECT_LIBRARIES} PARENT_SCOPE)
set (THIRD_PARTY_INCLUDE_DIRS ${THIRD_PARTY_INCLUDE_DIRS} PARENT_SCOPE)
diff --git a/libtransport/third-party/CMakeLists.txt.orig b/libtransport/third-party/CMakeLists.txt.orig
deleted file mode 100644
index 84db8cb4c..000000000
--- a/libtransport/third-party/CMakeLists.txt.orig
+++ /dev/null
@@ -1,85 +0,0 @@
-# Copyright (c) 2021 Cisco and/or its affiliates.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at:
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-include(FetchContent)
-
-set (THIRD_PARTY_INSTALL_PREFIX ${CMAKE_CURRENT_BINARY_DIR})
-
-option(ENABLE_RELY "Enable download/build of rely library" OFF)
-
-if (ENABLE_RELY)
- ##################################
- # Download librely
-
- if(DEFINED ENV{BITBUCKET_USERNAME} AND DEFINED ENV{BITBUCKET_PASSWORD})
- set(GIT_REPO https://$ENV{BITBUCKET_USERNAME}:$ENV{BITBUCKET_PASSWORD}@bitbucket-eng-gpk1.cisco.com/bitbucket/scm/icn/rely.git)
- else()
- set(GIT_REPO ssh://git@bitbucket-eng-gpk1.cisco.com:7999/icn/rely.git)
- endif()
-
- FetchContent_Declare(
- rely
- GIT_REPOSITORY ${GIT_REPO}
- GIT_TAG release/latest
- FETCHCONTENT_QUIET
- )
-
- set(ENABLE_PIC ON)
- FetchContent_MakeAvailable(rely)
-
- list(APPEND THIRD_PARTY_INCLUDE_DIRS
- ${rely_BINARY_DIR}
- ${rely_SOURCE_DIR}/src
- )
-
- # Get rely libraries
- get_property(steinwurf_object_libraries GLOBAL
- PROPERTY steinwurf::object_libraries)
-
- foreach(rely_library ${steinwurf_object_libraries})
- list(APPEND THIRD_PARTY_OBJECT_LIBRARIES
- $<TARGET_OBJECTS:${rely_library}>
- )
- endforeach()
-
- list(APPEND THIRD_PARTY_DEPENDENCIES
- rely
- )
-endif()
-
-FetchContent_Declare(
- glog
- URL https://github.com/google/glog/archive/refs/tags/v0.5.0.zip
- PATCH_COMMAND patch -p1 CMakeLists.txt ${CMAKE_CURRENT_SOURCE_DIR}/glog.patch
- FETCHCONTENT_QUIET
-)
-
-FetchContent_MakeAvailable(glog)
-
-list(APPEND THIRD_PARTY_INCLUDE_DIRS
- ${glog_BINARY_DIR}
- ${glog_SOURCE_DIR}/src
-)
-
-list(APPEND THIRD_PARTY_OBJECT_LIBRARIES
- $<TARGET_OBJECTS:glog>
-)
-
-list(APPEND THIRD_PARTY_DEPENDENCIES
- glog
-)
-
-set (THIRD_PARTY_LIBRARIES ${THIRD_PARTY_LIBRARIES} PARENT_SCOPE)
-set (THIRD_PARTY_OBJECT_LIBRARIES ${THIRD_PARTY_OBJECT_LIBRARIES} PARENT_SCOPE)
-set (THIRD_PARTY_INCLUDE_DIRS ${THIRD_PARTY_INCLUDE_DIRS} PARENT_SCOPE)
-set (THIRD_PARTY_DEPENDENCIES ${THIRD_PARTY_DEPENDENCIES} PARENT_SCOPE)
diff --git a/libtransport/third-party/CMakeLists.txt.rej b/libtransport/third-party/CMakeLists.txt.rej
deleted file mode 100644
index 4ebaf9061..000000000
--- a/libtransport/third-party/CMakeLists.txt.rej
+++ /dev/null
@@ -1,21 +0,0 @@
---- CMakeLists.txt
-+++ CMakeLists.txt
-@@ -41,9 +41,6 @@ if (NOT WITH_THREADS)
- set (CMAKE_DISABLE_FIND_PACKAGE_Threads ON)
- endif (NOT WITH_THREADS)
-
--set (CMAKE_C_VISIBILITY_PRESET hidden)
--set (CMAKE_CXX_VISIBILITY_PRESET hidden)
--set (CMAKE_VISIBILITY_INLINES_HIDDEN 1)
- list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
-
- include (CheckCXXSourceCompiles)
-@@ -570,7 +567,7 @@ if (_glog_CMake_MODULES)
- )
- endif (_glog_CMake_MODULES)
-
--add_library (glog
-+add_library (glog OBJECT
- ${GLOG_SRCS}
- ${_glog_BINARY_CMake_MODULES}
- )
diff --git a/libtransport/third-party/glog.patch b/libtransport/third-party/glog.patch
index 9d6e46df0..4f4d440eb 100644
--- a/libtransport/third-party/glog.patch
+++ b/libtransport/third-party/glog.patch
@@ -20,4 +20,4 @@ index 62ebbcc..7d92fa5 100644
+add_library (glog OBJECT
${GLOG_SRCS}
${_glog_BINARY_CMake_MODULES}
- )
+ ) \ No newline at end of file
diff --git a/libtransport/third-party/memif.patch b/libtransport/third-party/memif.patch
new file mode 100644
index 000000000..0fb4588bb
--- /dev/null
+++ b/libtransport/third-party/memif.patch
@@ -0,0 +1,52 @@
+diff --git a/extras/libmemif/CMakeLists.txt b/extras/libmemif/CMakeLists.txt
+index b6b658c2d..e5f5ffd9d 100644
+--- a/extras/libmemif/CMakeLists.txt
++++ b/extras/libmemif/CMakeLists.txt
+@@ -24,7 +24,7 @@ if (NOT CMAKE_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE "Release")
+ endif ()
+
+-set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -DMEMIF_DBG -DICMP_DBG")
++set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -DICMP_DBG")
+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
+ set(CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib)
+ set(CMAKE_INSTALL_MESSAGE NEVER)
+@@ -59,7 +59,7 @@ endforeach()
+ # extract version from git
+ execute_process(
+ COMMAND git describe --long --match v*
+- WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
++ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ OUTPUT_VARIABLE VER
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+diff --git a/extras/libmemif/src/CMakeLists.txt b/extras/libmemif/src/CMakeLists.txt
+index ddb8a52f8..b52566e5c 100644
+--- a/extras/libmemif/src/CMakeLists.txt
++++ b/extras/libmemif/src/CMakeLists.txt
+@@ -32,22 +32,7 @@ list(APPEND MEMIF_SOURCES
+
+ include_directories(${HEADERS_DIR})
+
+-add_library(memif SHARED ${MEMIF_SOURCES})
+-target_link_libraries(memif ${CMAKE_THREAD_LIBS_INIT})
++add_library(memif OBJECT ${MEMIF_SOURCES})
++set_property(TARGET memif PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+-find_library(LIB_BSD bsd)
+-if(LIB_BSD)
+- add_compile_definitions(HAS_LIB_BSD)
+- target_link_libraries(memif ${LIB_BSD})
+-endif()
+-
+-foreach(file ${MEMIF_HEADERS})
+- get_filename_component(dir ${file} DIRECTORY)
+- install(
+- FILES ${file}
+- DESTINATION include/${lib}/${dir}
+- COMPONENT libmemif-dev
+- )
+-endforeach()
+-
+-install(TARGETS memif DESTINATION lib COMPONENT libmemif)
++target_link_libraries(memif ${CMAKE_THREAD_LIBS_INIT})
diff --git a/scripts/Dockerfile.sonarcloud b/scripts/Dockerfile.sonarcloud
new file mode 100644
index 000000000..e1f40a789
--- /dev/null
+++ b/scripts/Dockerfile.sonarcloud
@@ -0,0 +1,20 @@
+FROM --platform=linux/amd64 ubuntu:focal
+
+ENV DEBIAN_FRONTEND=noninteractive
+WORKDIR /workspace
+COPY Makefile versions.cmake ./
+COPY scripts scripts/
+
+RUN apt update && apt-get install -y \
+ make \
+ sudo \
+ curl \
+ git
+
+RUN curl -sL https://deb.nodesource.com/setup_18.x | sudo bash -
+
+RUN apt update && apt-get install -y \
+ nodejs \
+ unzip
+
+RUN make deps debug-tools \ No newline at end of file
diff --git a/scripts/build-packages.sh b/scripts/build-packages.sh
index bc386c398..dddc98deb 100644
--- a/scripts/build-packages.sh
+++ b/scripts/build-packages.sh
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -17,6 +17,20 @@ set -euxo pipefail
SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE}")" ; pwd -P )
source ${SCRIPT_PATH}/functions.sh
+BUILD_PATH="${SCRIPT_PATH}/../packages"
+TEST_REPORT_DIR="${BUILD_PATH}/reports"
+BUILD_ROOT_DIR="${BUILD_PATH}/build-root/bin"
+MAKE_FOLDER="${SCRIPT_PATH}/.."
+
+function execute_tests() {
+ mkdir -p "${TEST_REPORT_DIR}"
+ pushd "${BUILD_ROOT_DIR}"
+ for component in "${TEST_COMPONENTS[@]}"; do
+ GTEST_OUTPUT="xml:${TEST_REPORT_DIR}/${component}-report.xml" "./${component}_tests"
+ done
+ popd
+}
+
# Parameters:
# $1 = Package name
#
@@ -27,22 +41,18 @@ function build_package() {
echo "********************* STARTING PACKAGE BUILD **********************"
echo "*******************************************************************"
- # Make the package
- mkdir -p ${SCRIPT_PATH}/../build && pushd ${SCRIPT_PATH}/../build
- rm -rf *
-
- cmake -G Ninja -DCMAKE_INSTALL_PREFIX=/usr \
- -DBUILD_HICNPLUGIN=ON \
- -DBUILD_LIBTRANSPORT=ON \
- -DBUILD_APPS=ON \
- -DBUILD_HICNLIGHT=ON \
- -DBUILD_TELEMETRY=ON \
- ${SCRIPT_PATH}/..
+ # Run unit tests and make the package
+ make -C "${MAKE_FOLDER}" BUILD_PATH="${BUILD_PATH}" INSTALL_PREFIX=/usr package-release
- ninja -j8 package
+ execute_tests
- find . -not -name '*.deb' -not -name '*.rpm' -print0 | xargs -0 rm -rf -- || true
- rm *Unspecified* *Development* *development* || true
+ pushd "${BUILD_PATH}"
+ find . -not -name '*.deb' \
+ -not -name '*.rpm' \
+ -not -name 'reports' \
+ -not -name '*report.xml' \
+ -print0 | xargs -0 rm -rf -- || true
+ rm ./*Unspecified* ./*Development* ./*development* || true
popd
echo "*******************************************************************"
@@ -57,30 +67,15 @@ build_sphinx() {
echo "********************* STARTING DOC BUILD **************************"
echo "*******************************************************************"
- # Make the package
- pip3 install -r ${SCRIPT_PATH}/../docs/etc/requirements.txt
- pushd ${SCRIPT_PATH}/../docs
- make html
-
- popd
+ make doc
echo "*******************************************************************"
echo "***************** BUILD COMPLETED SUCCESSFULLY *******************"
echo "*******************************************************************"
}
-build_doxygen() {
- setup
-
- mkdir -p ${SCRIPT_PATH}/../build-doxygen
- pushd ${SCRIPT_PATH}/../build-doxygen
- cmake -DBUILD_HICNPLUGIN=On -DBUILD_HICNLIGHT=OFF -DBUILD_LIBTRANSPORT=OFF -DBUILD_UTILS=OFF -DBUILD_APPS=OFF -DBUILD_CTRL=OFF ..
- make doc
- popd
-}
-
function usage() {
- echo "Usage: ${0} [sphinx|doxygen|packages]"
+ echo "Usage: ${0} [sphinx|packages]"
exit 1
}
@@ -92,14 +87,14 @@ case "${1}" in
sphinx)
build_sphinx
;;
- doxygen)
- build_doxygen
- ;;
packages)
build_package
;;
+ vpp_master)
+ ;;
*)
usage
+ exit 1
esac
exit 0
diff --git a/scripts/build-sonar.sh b/scripts/build-sonar.sh
new file mode 100644
index 000000000..eb6f0f5f2
--- /dev/null
+++ b/scripts/build-sonar.sh
@@ -0,0 +1,26 @@
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+#!/bin/bash
+
+set -euxo pipefail
+
+# Download docker compose
+sudo curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
+sudo chmod +x /usr/local/bin/docker-compose
+
+# Update/Init submodules
+git submodule update --init --recursive
+
+# Run sonarscanner
+docker-compose -f docker-compose-sonar.yml up
diff --git a/scripts/checkstyle.sh b/scripts/checkstyle.sh
index ae775aca9..4d3413c67 100644
--- a/scripts/checkstyle.sh
+++ b/scripts/checkstyle.sh
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,4 +11,104 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-exit 0 \ No newline at end of file
+#!/bin/bash
+
+set -eEo pipefail
+
+sudo apt-get install -y clang-format-12
+sudo pip3 install -U Commitizen
+
+CLANG_FORMAT_VER_REGEX='([0-9]+)\.[0-9]+\.[0-9]+'
+CLANG_FORMAT_DIFF="/usr/share/clang/clang-format-diff.py"
+
+if [[ -z ${CHANGE_TARGET} ]]; then
+ DIFF_TARGET="HEAD~1"
+else
+ DIFF_TARGET="origin/${CHANGE_TARGET}...HEAD"
+fi
+
+###############################################
+# Check commit mesage
+###############################################
+
+cz check --rev-range HEAD~1...HEAD
+
+###############################################
+# Check code style
+###############################################
+
+CLANG_FORMAT_VER=${CLANG_FORMAT_VER:-12}
+GIT_DIFF_ARGS="-U0 --no-color --relative ${DIFF_TARGET}"
+CLANG_FORMAT_DIFF_ARGS="-style file -p1"
+SUFFIX="-${CLANG_FORMAT_VER}"
+
+# Attempt to find clang-format to confirm Clang version.
+if command -v clang-format${SUFFIX} &>/dev/null; then
+ CLANG_FORMAT=clang-format${SUFFIX}
+elif command -v clang-format &>/dev/null; then
+ CLANG_FORMAT=clang-format
+fi
+
+CLANG_FORMAT_VERSION=$(${CLANG_FORMAT} --version)
+echo $CLANG_FORMAT_VERSION
+
+# Confirm that Clang is the expected version.
+if [[ ! $CLANG_FORMAT_VERSION =~ $CLANG_FORMAT_VER_REGEX ]]; then
+ echo "*******************************************************************"
+ echo "* CHECKSTYLE VERSION REGEX CHECK FAILED"
+ echo "* $CLANG_FORMAT_VERSION"
+ echo "*******************************************************************"
+ exit 1
+fi
+
+if [[ ! $CLANG_FORMAT_VER == "${BASH_REMATCH[1]}" ]]; then
+ echo "*******************************************************************"
+ echo "* CHECKSTYLE VERSION CHECK FAILED"
+ echo "* Expected major version $CLANG_FORMAT_VER, found ${BASH_REMATCH[1]}"
+ echo "*******************************************************************"
+ exit 1
+fi
+
+# Attempt to find clang-format-diff.
+if command -v clang-format-diff${SUFFIX} &>/dev/null; then
+ CLANG_FORMAT_DIFF=clang-format-diff${SUFFIX}
+elif command -v clang-format-diff &>/dev/null; then
+ CLANG_FORMAT=clang-format-diff
+elif [ ! -f $CLANG_FORMAT_DIFF ]; then
+ echo "*******************************************************************"
+ echo "* CHECKSTYLE FAILED"
+ echo "* Could not locate the clang-format-diff script"
+ echo "*******************************************************************"
+ exit 1
+fi
+
+in=$(mktemp)
+git diff ${GIT_DIFF_ARGS} ':!*.patch' >${in}
+
+out=$(mktemp)
+cat ${in} | ${CLANG_FORMAT_DIFF} ${CLANG_FORMAT_DIFF_ARGS} >${out}
+rm ${in}
+
+line_count=$(cat ${out} | wc -l)
+
+if [ -t 1 ] && [ -n $(tput colors) ] && [ $(tput colors) -ge 1 ] &&
+ command -v highlight &>/dev/null; then
+ highlight --syntax diff -O ansi ${out}
+else
+ cat ${out}
+fi
+
+rm ${out}
+
+if [ ${line_count} -gt 0 ]; then
+ echo "*******************************************************************"
+ echo "* CHECKSTYLE FAILED"
+ echo "* CONSULT DIFF ABOVE"
+ echo "*******************************************************************"
+ exit 1
+else
+ echo "*******************************************************************"
+ echo "* CHECKSTYLE SUCCESSFULLY COMPLETED"
+ echo "*******************************************************************"
+ exit 0
+fi
diff --git a/scripts/docker-compose-sonar.yml b/scripts/docker-compose-sonar.yml
new file mode 100644
index 000000000..198490546
--- /dev/null
+++ b/scripts/docker-compose-sonar.yml
@@ -0,0 +1,18 @@
+version: "3"
+services:
+ sonar:
+ build:
+ context: ../
+ dockerfile: scripts/Dockerfile.sonarcloud
+ container_name: sonarcloud
+ hostname: sonarcloud
+ environment:
+ API_TOKEN: $API_TOKEN
+ SONAR_HOST_URL: $SONAR_HOST_URL
+ PROJECT_KEY: $PROJECT_KEY
+ PROJECT_ORGANIZATION: $PROJECT_ORGANIZATION
+ volumes:
+ - ..:/workspace:z
+ command:
+ - |
+ /workspace/scripts/run-sonar.sh \ No newline at end of file
diff --git a/scripts/functional-tests.sh b/scripts/functional-tests.sh
new file mode 100644
index 000000000..05cc4193b
--- /dev/null
+++ b/scripts/functional-tests.sh
@@ -0,0 +1,35 @@
+# Copyright (c) 2017-2022 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+#!/bin/bash
+
+set -euxo pipefail
+
+SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE}")" ; pwd -P )
+source "${SCRIPT_PATH}/functions.sh"
+
+echo "---------------------------------------------------------"
+echo "----- INSTALLING FUNCTIONAL TEST DEPENDENCIES ---------"
+echo "---------------------------------------------------------"
+
+# This docker compose version is well supported also in CentOS.
+# Versions >= 2.0.0 do not seem to work.
+DOCKER_COMPOSE_VERSION=1.29.2
+
+sudo curl -L "https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
+sudo chmod +x /usr/local/bin/docker-compose
+sudo pip3 install robotframework
+
+functional_test
+
+exit 0
diff --git a/scripts/functions.sh b/scripts/functions.sh
index abb34fb7b..66235cf5f 100644
--- a/scripts/functions.sh
+++ b/scripts/functions.sh
@@ -1,4 +1,4 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
+# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -14,121 +14,141 @@
#!/bin/bash
set -euxo pipefail
-APT_PATH=`which apt-get` || true
+APT_PATH=$(which apt-get) || true
apt_get=${APT_PATH:-"/usr/local/bin/apt-get"}
# Cmake executable
CMAKE_INSTALL_DIR="/opt/cmake"
export PATH=:${CMAKE_INSTALL_DIR}/bin:${PATH}
-PACKAGECLOUD_RELEASE_REPO_DEB="https://packagecloud.io/install/repositories/fdio/release/script.deb.sh"
-PACKAGECLOUD_RELEASE_REPO_RPM="https://packagecloud.io/install/repositories/fdio/release/script.rpm.sh"
-PACKAGECLOUD_HICN_REPO_DEB="https://packagecloud.io/install/repositories/fdio/hicn/script.deb.sh"
-PACKAGECLOUD_HICN_REPO_RPM="https://packagecloud.io/install/repositories/fdio/hicn/script.rpm.sh"
-
-VPP_GIT_REPO="https://github.com/FDio/vpp"
-VPP_BRANCH="stable/2005"
-
- # Figure out what system we are running on
+# Figure out what system we are running on
if [ -f /etc/os-release ]; then
- . /etc/os-release
+ . /etc/os-release
else
- echo "ERROR: System configuration not recognized. Build failed"
- exit 1
+ echo "ERROR: System configuration not recognized. Build failed"
+ exit 1
fi
-VERSION_REGEX="s/v([0-9]+).([0-9]+)(.*)?-([0-9]+)-(g[0-9a-f]+)/\1.\2-release/g"
-VPP_VERSION_DEB=$(git describe --long --match "v*" | sed -E ${VERSION_REGEX})
-VPP_VERSION_RPM="${VPP_VERSION_DEB}.x86_64"
-
-DEPS_UBUNTU=("build-essential"
- "doxygen"
- "curl"
- "cmake"
- "libasio-dev"
- "libconfig-dev"
- "libconfig++-dev"
- "libcurl4-openssl-dev"
- "libevent-dev"
- "libssl-dev"
- "ninja-build"
- "python3-ply")
-
-DEPS_UBUNTU_PKGCLOUD=("libparc-dev"
- "libmemif-dev"
- "libmemif"
- "vpp=${VPP_VERSION_DEB}"
- "vpp-dev=${VPP_VERSION_DEB}"
- "libvppinfra=${VPP_VERSION_DEB}"
- "libvppinfra-dev=${VPP_VERSION_DEB}"
- "vpp-plugin-core=${VPP_VERSION_DEB}"
- "libparc-dev")
-
COLLECTD_SOURCE="https://github.com/collectd/collectd/releases/download/collectd-5.12.0/collectd-5.12.0.tar.bz2"
+declare -a TEST_COMPONENTS=(
+ "libtransport"
+ "lib"
+ "hicn_light"
+ "hicnplugin"
+ "libhicnctrl"
+)
+
function install_collectd_headers() {
- curl -OL ${COLLECTD_SOURCE}
- tar -xf collectd-5.12.0.tar.bz2
+ curl -OL ${COLLECTD_SOURCE}
+ tar -xf collectd-5.12.0.tar.bz2
- pushd collectd-5.12.0
- ./configure && make -j$(nproc)
- popd
+ pushd collectd-5.12.0
+ ./configure && make -j$(nproc)
+ popd
- export COLLECTD_HOME=${PWD}/collectd-5.12.0/src
+ export COLLECTD_HOME=${PWD}/collectd-5.12.0/src
}
-function setup_fdio_repo() {
- DISTRIB_ID=${ID}
-
- if [ "${DISTRIB_ID}" == "ubuntu" ]; then
- curl -s ${PACKAGECLOUD_RELEASE_REPO_DEB} | sudo bash
- curl -s ${PACKAGECLOUD_HICN_REPO_DEB} | sudo bash
- elif [ "${DISTRIB_ID}" == "centos" ]; then
- curl -s ${PACKAGECLOUD_RELEASE_REPO_RPM} | sudo bash
- curl -s ${PACKAGECLOUD_HICN_REPO_RPM} | sudo bash
- else
- echo "Distribution ${DISTRIB_ID} is not supported"
- exit 1
- fi
+# Call a function once
+function call_once() {
+ # OP_NAME is the name of the function
+ OP_NAME=${1}
+ # If function was already called return
+ [[ -f /tmp/${OP_NAME} ]] && return 0
+ # Otherwise call the function
+ ${@}
+ # And mark the function as called if no error occurred
+ echo ${OP_NAME} >/tmp/${OP_NAME}
}
# Install dependencies
function install_deps() {
- DISTRIB_ID=${ID}
- echo ${DEPS_UBUNTU[@]} | xargs sudo ${apt_get} install -y --allow-unauthenticated --no-install-recommends
+ make -C ${SCRIPT_PATH}/.. deps
}
-function install_pkgcloud_deps() {
- DISTRIB_ID=${ID}
- echo ${DEPS_UBUNTU_PKGCLOUD[@]} | xargs sudo ${apt_get} install -y --allow-unauthenticated --no-install-recommends
+function setup() {
+ echo DISTRIBUTION: ${PRETTY_NAME}
+ # export variables depending on the platform we are running
+ call_once install_deps
+ call_once install_collectd_headers
}
-# Call a function once
-function call_once() {
- # OP_NAME is the name of the function
- OP_NAME=${1}
- # If function was already called return
- [[ -f /tmp/${OP_NAME} ]] && return 0
- # Otherwise call the function
- ${@}
- # And mark the function as called if no error occurred
- echo ${OP_NAME} > /tmp/${OP_NAME}
+function setup_extras() {
+ echo DISTRIBUTION: ${PRETTY_NAME}
+ # export variables depending on the platform we are running
+
+ call_once install_deps
+ call_once install_collectd_headers
}
-function setup() {
- echo DISTRIBUTION: ${PRETTY_NAME}
- # export variables depending on the platform we are running
+# Download artifacts of this patchset from jenkins
+function download_artifacts() {
+ if [[ -n ${GERRIT_HOST:-} ]] &&
+ [[ -n ${GERRIT_CHANGE_NUMBER:-} ]] &&
+ [[ -n ${GERRIT_PATCHSET_NUMBER:-} ]] &&
+ [[ -n ${GERRIT_BRANCH:-} ]]; then
+
+ PC_STREAM="${GERRIT_BRANCH#'stable/'}"
+
+ # Retrieve the Jenkins URL of the build relative to this PATCHSET
+ JENKINS_URLS=$(
+ curl -s "https://${GERRIT_HOST}/r/changes/${GERRIT_CHANGE_NUMBER}/detail" |
+ tail -n +2 | jq '.messages[].message?' |
+ grep -E "Patch Set ${GERRIT_PATCHSET_NUMBER}:.*hicn-verify-build.*build_success-${PC_STREAM}-ubuntu2004-$(uname -m)" |
+ grep -Eo "https?://jenkins.fd.io/job/hicn-verify-build-${PC_STREAM}-ubuntu2004-$(uname -m)[^ ]+"
+ )
+
+ # Transform string to array and get last
+ JENKINS_URLS_ARRAY=(${JENKINS_URLS})
+ ARTIFACTS_URL="${JENKINS_URLS_ARRAY[-1]}/artifact/packages/*zip*/packages.zip"
+
+ # Download artifacts
+ curl -o "${SCRIPT_PATH}/../packages.zip" -L "${ARTIFACTS_URL}"
+
+ # Unzip them
+ unzip "${SCRIPT_PATH}/../packages.zip" -d "${SCRIPT_PATH}/.."
+
+ return 0
+ fi
- call_once setup_fdio_repo
- call_once install_deps
- call_once install_pkgcloud_deps
- call_once install_collectd_headers
+ # Fall back to image re-build if artifacts cannot be downloaded
+ echo "GERRIT_* environment is not set. Image will be rebuilt from scratch" >&2
+ return 1
}
-function setup_extras() {
- echo DISTRIBUTION: ${PRETTY_NAME}
- # export variables depending on the platform we are running
+function is_selinuxenabled() {
+ sudo selinuxenabled && return 1 || return 0
+}
+
+# Run functional tests
+function functional_test() {
+ echo "*******************************************************************"
+ echo "********************* STARTING FUNCTIONAL TESTS *******************"
+ echo "*******************************************************************"
+
+ if download_artifacts; then
+ local build_sw=0
+ local dockerfile_path="tests/Dockerfile.ci"
+ else
+ local build_sw=1
+ local dockerfile_path="Dockerfile.dev"
+ fi
+
+ # Run functional tests
+ pushd "${SCRIPT_PATH}/../tests"
+ # If selinux, let's run the tests with a privileged container to bypass
+ # the checks, which cost also in performance
+ if is_selinuxenabled; then
+ local privileged=false
+ else
+ local privileged=true
+ fi
+
+ BUILD_SOFTWARE=${build_sw} DOCKERFILE=${dockerfile_path} TEST_PRIVILEGED=${privileged} bash ./run-functional.sh
+ popd
- call_once install_deps
- call_once install_collectd_headers
+ echo "*******************************************************************"
+ echo "********** FUNCTIONAL TESTS COMPLETED SUCCESSFULLY ***************"
+ echo "*******************************************************************"
}
diff --git a/scripts/install-vpp.sh b/scripts/install-vpp.sh
new file mode 100644
index 000000000..30e560d39
--- /dev/null
+++ b/scripts/install-vpp.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+# Copyright (c) 2022-2023 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.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.
+
+set -euxo pipefail
+
+################################################################
+# Install defined VPP version
+################################################################
+
+VPP_VERSION=2210
+
+if [[ -z ${VERSION_PATH-} ]]; then
+ echo >&2 "No version path provided. Using version ${VPP_VERSION}"
+else
+ VPP_VERSION=$(grep VPP_DEFAULT_VERSION "${VERSION_PATH}" | cut -d ' ' -f 2 | tr -d '"' | grep -Po '\d\d.\d\d')
+ VPP_VERSION=${VPP_VERSION//./}
+fi
+
+# Prevent vpp to set sysctl
+export VPP_INSTALL_SKIP_SYSCTL=1
+
+apt-get update
+apt-get install -y curl
+
+curl -s https://packagecloud.io/install/repositories/fdio/${VPP_VERSION}/script.deb.sh | bash
+curl -L https://packagecloud.io/fdio/${VPP_VERSION}/gpgkey | apt-key add -
+sed -E -i 's/(deb.*)(\[.*\])(.*)/\1\3/g' /etc/apt/sources.list.d/fdio_"${VPP_VERSION}".list
+
+# create apt pinning
+cat << EOF | tee /etc/apt/preferences.d/vpp-pin
+Package: vpp*
+Pin: release o=packagecloud.io/fdio/${VPP_VERSION}
+Pin-Priority: 1000
+
+Package: libvpp*
+Pin: release o=packagecloud.io/fdio/${VPP_VERSION}
+Pin-Priority: 1000
+EOF
+
+apt-get update
+
+apt-get install -y \
+ vpp-dev \
+ libvppinfra-dev \
+ vpp-plugin-core \
+ vpp \
+ libvppinfra
diff --git a/scripts/run-sonar.sh b/scripts/run-sonar.sh
new file mode 100755
index 000000000..87a94b592
--- /dev/null
+++ b/scripts/run-sonar.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+
+set -euxo pipefail
+
+# SONAR_HOST_URL=https://sonarcloud.io
+# PROJECT_KEY=fdio-hicn
+# PROJECT_ORGANIZATION=fdio
+
+SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE}")" ; pwd -P )
+source "${SCRIPT_PATH}/functions.sh"
+
+export SONAR_TOKEN=$API_TOKEN
+export SONAR_SCANNER_VERSION=4.7.0.2747
+export SONAR_SCANNER_HOME=$HOME/.sonar/sonar-scanner-$SONAR_SCANNER_VERSION-linux
+curl --create-dirs -sSLo $HOME/.sonar/sonar-scanner.zip https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-$SONAR_SCANNER_VERSION-linux.zip
+unzip -o $HOME/.sonar/sonar-scanner.zip -d $HOME/.sonar/
+export PATH=$SONAR_SCANNER_HOME/bin:$PATH
+export SONAR_SCANNER_OPTS="-server"
+curl --create-dirs -sSLo $HOME/.sonar/build-wrapper-linux-x86.zip https://sonarcloud.io/static/cpp/build-wrapper-linux-x86.zip
+unzip -o $HOME/.sonar/build-wrapper-linux-x86.zip -d $HOME/.sonar/
+export PATH=$HOME/.sonar/build-wrapper-linux-x86:$PATH
+
+cd /workspace
+
+git config --global --add safe.directory /workspace
+git config --global --add safe.directory /workspace/cmake
+
+BUILD_PATH=${PWD}/build-debug
+TEST_PATH="${BUILD_PATH}/build-root/bin"
+
+make SONAR_BUILD_WRAPPER=${HOME}/.sonar/build-wrapper-linux-x86/build-wrapper-linux-x86-64 SONAR_OUT_DIR=bw-output BUILD_PATH=${BUILD_PATH} wipe build-coverage
+
+# Run tests to compute test coverage
+pushd ${BUILD_PATH}
+
+# Save first test executable
+FIRST_COMPONENT="${TEST_COMPONENTS[0]}"
+FIRST_TEST="${TEST_PATH}/${FIRST_COMPONENT}_tests"
+
+# Iterate over all tests: build parameters for next tests and get .profraw data
+extension=".profraw"
+PROFRAW_FILES=""
+REMAINING_TESTS=""
+for component in "${TEST_COMPONENTS[@]}"; do
+ # Build PROFRAW parameters for next command
+ PROFRAW_FILES="${PROFRAW_FILES}${component}${extension} "
+
+ # Save if not first binary
+ [[ "${component}" != "${FIRST_COMPONENT}" ]] && REMAINING_TESTS="${REMAINING_TESTS} -object ${TEST_PATH}/${component}_tests"
+
+ # Generate profraw data
+ LLVM_PROFILE_FILE="${BUILD_PATH}/${component}${extension}" ${TEST_PATH}/${component}_tests
+done
+
+# Merge profraw files
+llvm-profdata-11 merge -sparse ${PROFRAW_FILES} -o hicn.profdata
+
+# Generate coverage report
+llvm-cov-11 show ${FIRST_TEST} ${REMAINING_TESTS} -instr-profile=hicn.profdata --format=text > ${BUILD_PATH}/coverage.txt
+
+popd
+
+$SONAR_SCANNER_HOME/bin/sonar-scanner \
+ -Dsonar.organization=$PROJECT_ORGANIZATION \
+ -Dsonar.projectKey=$PROJECT_KEY \
+ -Dsonar.sources=/workspace \
+ -Dsonar.cfamily.build-wrapper-output=bw-output \
+ -Dsonar.host.url=$SONAR_HOST_URL \
+ -Dsonar.cfamily.llvm-cov.reportPath=${BUILD_PATH}/coverage.txt
diff --git a/telemetry/.clang-format b/telemetry/.clang-format
new file mode 100644
index 000000000..0043ea3d0
--- /dev/null
+++ b/telemetry/.clang-format
@@ -0,0 +1,3 @@
+# Copyright (c) 2022 Cisco and/or its affiliates.
+
+BasedOnStyle: Google \ No newline at end of file
diff --git a/telemetry/CMakeLists.txt b/telemetry/CMakeLists.txt
index fbb929529..181e726f1 100644
--- a/telemetry/CMakeLists.txt
+++ b/telemetry/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,11 +11,68 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-
+##############################################################
+# Project and cmake version
+##############################################################
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
+project(telemetry)
+
+
+##############################################################
+# C Standard
+##############################################################
+set(CMAKE_C_STANDARD 11)
+
+
+##############################################################
+# Cmake modules
+##############################################################
+include("${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake")
+set(CMAKE_MODULE_PATH
+ ${CMAKE_MODULE_PATH}
+ ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/Modules
+)
+
+
+##############################################################
+# Libs and Bins names
+##############################################################
+set(COLLECTD_PLUGINS hicn-collectd-plugins CACHE INTERNAL "" FORCE)
+set(HICN_LIGHT_TELEMETRY hicn_light)
+set(KAFKA_TELEMETRY write_kafka_line_protocol)
+set(VPP_TELEMETRY vpp)
+set(VPP_HICN_TELEMETRY vpp_hicn)
+
+
+##############################################################
+# Dependencies and third party libs
+##############################################################
+find_package(Collectd ${COLLECTD_DEFAULT_VERSION} REQUIRED)
+add_subdirectory(third-party)
+
+
+##############################################################
+# Check if building as subproject or as root project
+##############################################################
+if(NOT (CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) AND
+ NOT (BUILD_HICNPLUGIN AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux"))
+ return()
+endif()
+include(CommonSetup)
+
+# Include config.h in all collectd plugins
+set(COLLECTD_COMPILER_OPTIONS -include config.h)
+
+# ##############################################################
+# # Packaging and versioning
+# ##############################################################
+include(${CMAKE_CURRENT_SOURCE_DIR}/../versions.cmake)
+include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/packaging.cmake)
-if ((CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) OR
- (BUILD_HICNPLUGIN AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux"))
- add_subdirectory(vpp-collectd)
-endif ()
+##############################################################
+# Subdirectories
+##############################################################
+add_subdirectory(hicn-light-collectd)
+add_subdirectory(kafka-collectd)
+add_subdirectory(vpp-collectd) \ No newline at end of file
diff --git a/telemetry/vpp-collectd/cmake/Modules/Packaging.cmake b/telemetry/cmake/packaging.cmake
index 72da05d02..d5d2264ce 100644
--- a/telemetry/vpp-collectd/cmake/Modules/Packaging.cmake
+++ b/telemetry/cmake/packaging.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -21,11 +21,11 @@ set(${COLLECTD_PLUGINS}_DESCRIPTION
)
set(${COLLECTD_PLUGINS}_DEB_DEPENDENCIES
- "collectd, hicn-plugin-dev"
+ "collectd, hicn-plugin-dev (= stable_version) libhicnctrl (= stable_version) libyajl-dev"
CACHE STRING "Dependencies for deb/rpm package."
)
set(${COLLECTD_PLUGINS}_RPM_DEPENDENCIES
- "collectd, hicn-plugin-dev"
+ "collectd, hicn-plugin-dev (= stable_version) libhicnctrl (= stable_version) libyajl-dev"
CACHE STRING "Dependencies for deb/rpm package."
) \ No newline at end of file
diff --git a/telemetry/collectd.conf b/telemetry/collectd.conf
new file mode 100644
index 000000000..225c161c6
--- /dev/null
+++ b/telemetry/collectd.conf
@@ -0,0 +1,54 @@
+##############################################################################
+# Global #
+##############################################################################
+FQDNLookup true
+#Interval 10
+
+# Limit the size of the write queue. Default is no limit. Setting up a limit
+# is recommended for servers handling a high volume of traffic.
+#WriteQueueLimitHigh 1000000
+#WriteQueueLimitLow 800000
+
+##############################################################################
+# Logging #
+##############################################################################
+LoadPlugin logfile
+
+<Plugin logfile>
+ LogLevel "info"
+ File STDOUT
+ Timestamp true
+ PrintSeverity true
+</Plugin>
+
+##############################################################################
+# LoadPlugin section #
+##############################################################################
+LoadPlugin write_log
+
+<LoadPlugin hicn_light>
+ Globals true # Required to find libhicnctrl symbols
+ Interval 5
+</LoadPlugin>
+
+<LoadPlugin write_kafka_line_protocol>
+ Interval 10
+</LoadPlugin>
+
+##############################################################################
+# Plugin configuration #
+##############################################################################
+<Plugin write_kafka_line_protocol>
+ Property "bootstrap.servers" "localhost:8081"
+ Property "security.protocol" "sasl_plaintext"
+ Property "sasl.mechanism" "SCRAM-SHA-256"
+ Property "sasl.username" "eloparco"
+ Property "sasl.password" "password"
+
+ <Topic "stream">
+ Format InfluxDB
+ </Topic>
+ # <Topic "metadata">
+ # Format hicnJSON
+ # </Topic>
+</Plugin>
diff --git a/telemetry/data_model.h b/telemetry/data_model.h
new file mode 100644
index 000000000..b1c4ae7e5
--- /dev/null
+++ b/telemetry/data_model.h
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ */
+
+#include "utils/common/common.h"
+
+#define KAFKA_TOPIC_KEY "_TOPIC"
+#define KAFKA_STREAM_TOPIC "stream"
+#define KAFKA_METADATA_TOPIC "metadata"
+
+/************** DATA SOURCES ******************************/
+data_source_t packets_dsrc[1] = {
+ {"packets", DS_TYPE_GAUGE, 0, NAN},
+};
+
+data_source_t interests_dsrc[1] = {
+ {"interests", DS_TYPE_GAUGE, 0, NAN},
+};
+
+data_source_t data_dsrc[1] = {
+ {"data", DS_TYPE_GAUGE, 0, NAN},
+};
+
+data_source_t combined_dsrc[2] = {
+ {"packets", DS_TYPE_DERIVE, 0, NAN},
+ {"bytes", DS_TYPE_DERIVE, 0, NAN},
+};
+
+/************** DATA SETS NODE ****************************/
+data_set_t pkts_processed_ds = {
+ "pkts_processed",
+ STATIC_ARRAY_SIZE(packets_dsrc),
+ packets_dsrc,
+};
+
+data_set_t pkts_interest_count_ds = {
+ "pkts_interest_count",
+ STATIC_ARRAY_SIZE(packets_dsrc),
+ packets_dsrc,
+};
+
+data_set_t pkts_data_count_ds = {
+ "pkts_data_count",
+ STATIC_ARRAY_SIZE(packets_dsrc),
+ packets_dsrc,
+};
+
+data_set_t pkts_from_cache_count_ds = {
+ "pkts_from_cache_count",
+ STATIC_ARRAY_SIZE(packets_dsrc),
+ packets_dsrc,
+};
+
+data_set_t pkts_no_pit_count_ds = {
+ "pkts_no_pit_count",
+ STATIC_ARRAY_SIZE(packets_dsrc),
+ packets_dsrc,
+};
+
+data_set_t pit_expired_count_ds = {
+ "pit_expired_count",
+ STATIC_ARRAY_SIZE(interests_dsrc),
+ interests_dsrc,
+};
+
+data_set_t cs_expired_count_ds = {
+ "cs_expired_count",
+ STATIC_ARRAY_SIZE(data_dsrc),
+ data_dsrc,
+};
+
+data_set_t cs_lru_count_ds = {
+ "cs_lru_count",
+ STATIC_ARRAY_SIZE(data_dsrc),
+ data_dsrc,
+};
+
+data_set_t pkts_drop_no_buf_ds = {
+ "pkts_drop_no_buf",
+ STATIC_ARRAY_SIZE(packets_dsrc),
+ packets_dsrc,
+};
+
+data_set_t interests_aggregated_ds = {
+ "interests_aggregated",
+ STATIC_ARRAY_SIZE(interests_dsrc),
+ interests_dsrc,
+};
+
+data_set_t interests_retx_ds = {
+ "interests_retx",
+ STATIC_ARRAY_SIZE(interests_dsrc),
+ interests_dsrc,
+};
+
+data_set_t interests_hash_collision_ds = {
+ "interests_hash_collision",
+ STATIC_ARRAY_SIZE(interests_dsrc),
+ interests_dsrc,
+};
+
+data_set_t pit_entries_count_ds = {
+ "pit_entries_count",
+ STATIC_ARRAY_SIZE(interests_dsrc),
+ interests_dsrc,
+};
+
+data_set_t cs_entries_count_ds = {
+ "cs_entries_count",
+ STATIC_ARRAY_SIZE(data_dsrc),
+ data_dsrc,
+};
+
+data_set_t cs_entries_ntw_count_ds = {
+ "cs_entries_ntw_count",
+ STATIC_ARRAY_SIZE(data_dsrc),
+ data_dsrc,
+};
+
+/************** DATA SETS FACE ****************************/
+data_set_t irx_ds = {
+ "irx",
+ STATIC_ARRAY_SIZE(combined_dsrc),
+ combined_dsrc,
+};
+
+data_set_t itx_ds = {
+ "itx",
+ STATIC_ARRAY_SIZE(combined_dsrc),
+ combined_dsrc,
+};
+
+data_set_t drx_ds = {
+ "drx",
+ STATIC_ARRAY_SIZE(combined_dsrc),
+ combined_dsrc,
+};
+
+data_set_t dtx_ds = {
+ "dtx",
+ STATIC_ARRAY_SIZE(combined_dsrc),
+ combined_dsrc,
+};
diff --git a/telemetry/hicn-light-collectd/CMakeLists.txt b/telemetry/hicn-light-collectd/CMakeLists.txt
new file mode 100644
index 000000000..984d7076c
--- /dev/null
+++ b/telemetry/hicn-light-collectd/CMakeLists.txt
@@ -0,0 +1,65 @@
+# Copyright (c) 2022 Cisco and/or its affiliates.
+
+##############################################################
+# Source files
+##############################################################
+list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light.c
+)
+
+
+##############################################################
+# Include dirs
+##############################################################
+list(APPEND INCLUDE_DIRS
+ ${COLLECTD_INCLUDE_DIRS}
+ ${THIRD_PARTY_INCLUDE_DIRS}
+)
+
+
+##############################################################
+# Libraries
+##############################################################
+find_package(Libhicn ${CURRENT_VERSION} REQUIRED NO_MODULE)
+find_package(Libhicnctrl ${CURRENT_VERSION} REQUIRED NO_MODULE)
+
+if (DISABLE_SHARED_LIBRARIES)
+ set(LIBTYPE static)
+else()
+ set(LIBTYPE shared)
+endif()
+
+list(APPEND LIBHICN_LIBRARIES hicn::hicn.${LIBTYPE})
+list(APPEND LIBHICNCTRL_LIBRARIES hicn::hicnctrl.${LIBTYPE})
+
+list (APPEND LIBRARIES
+ PRIVATE ${LIBHICNCTRL_LIBRARIES}
+ PRIVATE ${LIBHICN_LIBRARIES}
+)
+
+
+##############################################################
+# Compiler options
+##############################################################
+list(APPEND COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ ${COLLECTD_COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Build library
+##############################################################
+build_library(${HICN_LIGHT_TELEMETRY}
+ SHARED
+ EMPTY_PREFIX
+ SOURCES ${SOURCE_FILES}
+ LINK_LIBRARIES ${LIBRARIES}
+ INCLUDE_DIRS
+ PRIVATE ${INCLUDE_DIRS}
+ INSTALL_FULL_PATH_DIR ${COLLECTD_PLUGIN_DIR}
+ COMPONENT ${COLLECTD_PLUGINS}
+ DEPENDS ${DEPENDENCIES}
+ LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+) \ No newline at end of file
diff --git a/telemetry/hicn-light-collectd/hicn_light.c b/telemetry/hicn-light-collectd/hicn_light.c
new file mode 100644
index 000000000..bb4eb571c
--- /dev/null
+++ b/telemetry/hicn-light-collectd/hicn_light.c
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2022 Cisco and/or its affiliates.
+ */
+
+#define ntohll hicn_ntohll // Rename to avoid collision
+#include <hicn/ctrl/api.h>
+#include <hicn/ctrl/hicn-light-ng.h>
+#include <hicn/util/sstrncpy.h>
+#undef ntohll
+
+#include "../data_model.h"
+#include "collectd.h"
+#include "plugin.h"
+#include "utils/common/common.h"
+
+#define PLUGIN_NAME "hicn_light"
+
+static hc_sock_t *s = NULL;
+
+static void submit(const char *type, value_t *values, size_t values_len,
+ meta_data_t *meta) {
+ assert(type != NULL && values != NULL && values_len != 0);
+
+ value_list_t vl = {.values = values, .values_len = values_len};
+ if (meta) vl.meta = meta;
+
+ int rc = strcpy_s(vl.plugin, sizeof(vl.plugin), PLUGIN_NAME);
+ _ASSERT(rc == EOK);
+ rc = strcpy_s(vl.type, sizeof(vl.type), type);
+ _ASSERT(rc == EOK);
+ rc = strcpy_s(vl.host, sizeof(vl.host), hostname_g);
+ _ASSERT(rc == EOK);
+
+ plugin_dispatch_values(&vl);
+}
+
+static int read_forwarder_global_stats(hc_data_t **pdata, meta_data_t *meta) {
+ // Retrieve global stats from forwarder
+ int rc = hc_stats_get(s, pdata);
+ if (rc < 0) {
+ plugin_log(LOG_ERR, "Could not read global stats from forwarder");
+ return -1;
+ }
+ hicn_light_stats_t stats = *((hicn_light_stats_t *)(*pdata)->buffer);
+
+ // Submit values
+ value_t values[1];
+ values[0] = (value_t){.gauge = stats.forwarder.countReceived};
+ submit(pkts_processed_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countInterestsReceived};
+ submit(pkts_interest_count_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countObjectsReceived};
+ submit(pkts_data_count_ds.type, values, 1, meta);
+ values[0] =
+ (value_t){.gauge = stats.forwarder.countInterestsSatisfiedFromStore};
+ submit(pkts_from_cache_count_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countDroppedNoReversePath};
+ submit(pkts_no_pit_count_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countInterestsExpired};
+ submit(pit_expired_count_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countDataExpired};
+ submit(cs_expired_count_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.pkt_cache.n_lru_evictions};
+ submit(cs_lru_count_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countDropped};
+ submit(pkts_drop_no_buf_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countInterestsAggregated};
+ submit(interests_aggregated_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.forwarder.countInterestsRetransmitted};
+ submit(interests_retx_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.pkt_cache.n_pit_entries};
+ submit(pit_entries_count_ds.type, values, 1, meta);
+ values[0] = (value_t){.gauge = stats.pkt_cache.n_cs_entries};
+ submit(cs_entries_count_ds.type, values, 1, meta);
+
+ return 0;
+}
+
+static int read_forwarder_per_face_stats(hc_data_t **pdata, meta_data_t *meta) {
+ // Retrieve per-face stats from forwarder
+ int rc = hc_stats_list(s, pdata);
+ if (rc < 0) {
+ plugin_log(LOG_ERR, "Could not read face stats from forwarder");
+ return -1;
+ }
+ hc_data_t *data = *pdata;
+ cmd_stats_list_item_t *conn_stats = (cmd_stats_list_item_t *)data->buffer;
+ cmd_stats_list_item_t *end =
+ (cmd_stats_list_item_t *)(data->buffer +
+ data->size * data->out_element_size);
+
+ // Submit values
+ while (conn_stats < end) {
+ rc = meta_data_add_unsigned_int(meta, "face_id", conn_stats->id);
+ assert(rc == 0);
+
+ value_t values[2];
+ values[0] = (value_t){.derive = conn_stats->stats.interests.rx_pkts};
+ values[1] = (value_t){.derive = conn_stats->stats.interests.rx_bytes};
+ submit(irx_ds.type, values, 2, meta);
+ values[0] = (value_t){.derive = conn_stats->stats.interests.tx_pkts};
+ values[1] = (value_t){.derive = conn_stats->stats.interests.tx_bytes};
+ submit(itx_ds.type, values, 2, meta);
+ values[0] = (value_t){.derive = conn_stats->stats.data.rx_pkts};
+ values[1] = (value_t){.derive = conn_stats->stats.data.rx_bytes};
+ submit(drx_ds.type, values, 2, meta);
+ values[0] = (value_t){.derive = conn_stats->stats.data.tx_pkts};
+ values[1] = (value_t){.derive = conn_stats->stats.data.tx_bytes};
+ submit(dtx_ds.type, values, 2, meta);
+
+ conn_stats++;
+ }
+
+ return 0;
+}
+
+static int read_forwarder_stats() {
+ // Create metadata
+ meta_data_t *meta = meta_data_create();
+ int rc = meta_data_add_string(meta, KAFKA_TOPIC_KEY, KAFKA_STREAM_TOPIC);
+ assert(rc == 0);
+
+ hc_data_t *data = NULL;
+ rc = read_forwarder_global_stats(&data, meta);
+ if (rc < 0) goto READ_ERROR;
+ rc = read_forwarder_per_face_stats(&data, meta);
+
+READ_ERROR:
+ meta_data_destroy(meta);
+ hc_data_free(data);
+ return rc;
+}
+
+static int connect_to_forwarder() {
+ plugin_log(LOG_INFO, "Connecting to forwarder");
+ s = hc_sock_create_forwarder(HICNLIGHT_NG);
+ if (!s) {
+ plugin_log(LOG_ERR, "Could not create socket");
+ return -1;
+ }
+
+ int rc = hc_sock_connect(s);
+ if (rc < 0) {
+ plugin_log(LOG_ERR, "Could not establish connection to forwarder");
+ hc_sock_free(s);
+ s = NULL;
+ return -1;
+ }
+
+ return 0;
+}
+
+static int disconnect_from_forwarder() {
+ plugin_log(LOG_INFO, "Disconnecting from forwarder");
+
+ if (s == NULL) {
+ plugin_log(LOG_ERR, "Forwarder not connected");
+ return -1;
+ }
+
+ hc_command_t command = {0};
+ command.object.connection.id = 0;
+ int rc = strcpy_s(command.object.connection.name,
+ sizeof(command.object.connection.name), "SELF");
+ if (rc != EOK || hc_connection_delete(s, &command.object.connection) < 0) {
+ rc = -1;
+ plugin_log(LOG_ERR, "Error removing local connection to forwarder");
+ }
+
+ hc_sock_free(s);
+ return rc;
+}
+
+void module_register() {
+ // Data sets
+ plugin_register_data_set(&pkts_processed_ds);
+ plugin_register_data_set(&pkts_interest_count_ds);
+ plugin_register_data_set(&pkts_data_count_ds);
+ plugin_register_data_set(&pkts_from_cache_count_ds);
+ plugin_register_data_set(&pkts_no_pit_count_ds);
+ plugin_register_data_set(&pit_expired_count_ds);
+ plugin_register_data_set(&cs_expired_count_ds);
+ plugin_register_data_set(&cs_lru_count_ds);
+ plugin_register_data_set(&pkts_drop_no_buf_ds);
+ plugin_register_data_set(&interests_aggregated_ds);
+ plugin_register_data_set(&interests_retx_ds);
+ plugin_register_data_set(&interests_hash_collision_ds);
+ plugin_register_data_set(&pit_entries_count_ds);
+ plugin_register_data_set(&cs_entries_count_ds);
+ plugin_register_data_set(&cs_entries_ntw_count_ds);
+ plugin_register_data_set(&irx_ds);
+ plugin_register_data_set(&itx_ds);
+ plugin_register_data_set(&drx_ds);
+ plugin_register_data_set(&dtx_ds);
+
+ // Callbacks
+ plugin_register_init(PLUGIN_NAME, connect_to_forwarder);
+ plugin_register_read(PLUGIN_NAME, read_forwarder_stats);
+ plugin_register_shutdown(PLUGIN_NAME, disconnect_from_forwarder);
+} \ No newline at end of file
diff --git a/telemetry/kafka-collectd/CMakeLists.txt b/telemetry/kafka-collectd/CMakeLists.txt
new file mode 100644
index 000000000..f1ff81117
--- /dev/null
+++ b/telemetry/kafka-collectd/CMakeLists.txt
@@ -0,0 +1,62 @@
+# Copyright (c) 2022 Cisco and/or its affiliates.
+
+##############################################################
+# Source files
+##############################################################
+file(GLOB_RECURSE COLLECTD_UTILS_SOURCES "${THIRD_PARTY_INCLUDE_DIRS}/utils/cmds/*.c")
+
+list(APPEND SOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/write_kafka_line_protocol.c
+ ${THIRD_PARTY_INCLUDE_DIRS}/utils/format_json/format_json.c
+ ${THIRD_PARTY_INCLUDE_DIRS}/utils/format_graphite/format_graphite.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/format_influxdb.c
+ ${COLLECTD_UTILS_SOURCES}
+)
+
+
+##############################################################
+# Include dirs
+##############################################################
+list(APPEND INCLUDE_DIRS
+ PRIVATE ${COLLECTD_INCLUDE_DIRS}
+ PRIVATE ${THIRD_PARTY_INCLUDE_DIRS}
+)
+
+
+##############################################################
+# Libraries
+##############################################################
+find_package(RdKafka ${RDKAFKA_DEFAULT_VERSION} REQUIRED)
+find_library(YAJL_LIB libyajl.so REQUIRED)
+
+list (APPEND LIBRARIES
+ ${YAJL_LIB}
+ ${RdKafka_LIBRARY_PATH}
+)
+
+
+##############################################################
+# Compiler options
+##############################################################
+list(APPEND COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ ${COLLECTD_COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Build library
+##############################################################
+build_library(${KAFKA_TELEMETRY}
+ SHARED
+ EMPTY_PREFIX
+ SOURCES ${SOURCE_FILES}
+ LINK_LIBRARIES ${LIBRARIES}
+ INCLUDE_DIRS
+ PRIVATE ${INCLUDE_DIRS}
+ INSTALL_FULL_PATH_DIR ${COLLECTD_PLUGIN_DIR}
+ COMPONENT ${COLLECTD_PLUGINS}
+ DEPENDS ${DEPENDENCIES}
+ LINK_FLAGS ${LINK_FLAGS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
diff --git a/telemetry/kafka-collectd/format_influxdb.c b/telemetry/kafka-collectd/format_influxdb.c
new file mode 100644
index 000000000..f7ff29501
--- /dev/null
+++ b/telemetry/kafka-collectd/format_influxdb.c
@@ -0,0 +1,190 @@
+/**
+ * collectd - src/utils_format_influxdb.c
+ * Copyright (C) 2007-2009 Florian octo Forster
+ * Copyright (C) 2009 Aman Gupta
+ * Copyright (C) 2019 Carlos Peon Costa
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Authors:
+ * Florian octo Forster <octo at collectd.org>
+ * Aman Gupta <aman at tmm1.net>
+ * Carlos Peon Costa <carlospeon at gmail.com>
+ * multiple Server directives by:
+ * Paul (systemcrash) <newtwen thatfunny_at_symbol gmail.com>
+ **/
+
+#include "format_influxdb.h"
+
+#include "collectd.h"
+#include "plugin.h"
+#include "utils/common/common.h"
+#include "utils/metadata/meta_data.h"
+#include "utils_cache.h"
+
+static int format_influxdb_escape_string(char *buffer, size_t buffer_size,
+ const char *string) {
+ if ((buffer == NULL) || (string == NULL)) return -EINVAL;
+
+ if (buffer_size < 3) return -ENOMEM;
+
+ int dst_pos = 0;
+
+#define BUFFER_ADD(c) \
+ do { \
+ if (dst_pos >= (buffer_size - 1)) { \
+ buffer[buffer_size - 1] = '\0'; \
+ return -ENOMEM; \
+ } \
+ buffer[dst_pos] = (c); \
+ dst_pos++; \
+ } while (0)
+
+ /* Escape special characters */
+ for (int src_pos = 0; string[src_pos] != 0; src_pos++) {
+ if ((string[src_pos] == '\\') || (string[src_pos] == ' ') ||
+ (string[src_pos] == ',') || (string[src_pos] == '=') ||
+ (string[src_pos] == '"')) {
+ BUFFER_ADD('\\');
+ BUFFER_ADD(string[src_pos]);
+ } else
+ BUFFER_ADD(string[src_pos]);
+ } /* for */
+ buffer[dst_pos] = 0;
+
+#undef BUFFER_ADD
+
+ return dst_pos;
+} /* int format_influxdb_escape_string */
+
+int format_influxdb_value_list(
+ char *buffer, int buffer_len, const data_set_t *ds, const value_list_t *vl,
+ bool store_rates, format_influxdb_time_precision_t time_precision) {
+ int status;
+ int offset = 0;
+ gauge_t *rates = NULL;
+ bool have_values = false;
+
+ assert(0 == strcmp(ds->type, vl->type));
+
+#define BUFFER_ADD_ESCAPE(...) \
+ do { \
+ status = format_influxdb_escape_string(buffer + offset, \
+ buffer_len - offset, __VA_ARGS__); \
+ if (status < 0) return status; \
+ offset += status; \
+ } while (0)
+
+#define BUFFER_ADD(...) \
+ do { \
+ status = snprintf(buffer + offset, buffer_len - offset, __VA_ARGS__); \
+ if ((status < 0) || (status >= (buffer_len - offset))) { \
+ sfree(rates); \
+ return -ENOMEM; \
+ } \
+ offset += status; \
+ } while (0)
+
+ assert(vl->type);
+ BUFFER_ADD_ESCAPE(vl->type);
+ BUFFER_ADD(",host=");
+ BUFFER_ADD_ESCAPE(vl->host);
+ if (vl->meta) {
+ char **toc;
+ int n = meta_data_toc(vl->meta, &toc);
+
+ for (int i = 0; i < n; i++) {
+ char *key = toc[i];
+ char *value;
+
+ if (meta_data_as_string(vl->meta, key, &value) == 0) {
+ BUFFER_ADD(",");
+ BUFFER_ADD_ESCAPE(key);
+ BUFFER_ADD("=");
+ BUFFER_ADD_ESCAPE(value);
+ free(value);
+ }
+ free(toc[i]);
+ }
+
+ if (n != 0) free(toc);
+ }
+
+ BUFFER_ADD(" ");
+ for (size_t i = 0; i < ds->ds_num; i++) {
+ if ((ds->ds[i].type != DS_TYPE_COUNTER) &&
+ (ds->ds[i].type != DS_TYPE_GAUGE) &&
+ (ds->ds[i].type != DS_TYPE_DERIVE) &&
+ (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
+ sfree(rates);
+ return -EINVAL;
+ }
+
+ if (ds->ds[i].type == DS_TYPE_GAUGE) {
+ if (isnan(vl->values[i].gauge)) continue;
+ if (have_values) BUFFER_ADD(",");
+ BUFFER_ADD("%s=%lf", ds->ds[i].name, vl->values[i].gauge);
+ have_values = true;
+ } else if (store_rates) {
+ if (rates == NULL) rates = uc_get_rate(ds, vl);
+ if (rates == NULL) {
+ WARNING(
+ "format_influxdb: "
+ "uc_get_rate failed.");
+ return -EINVAL;
+ }
+ if (isnan(rates[i])) continue;
+ if (have_values) BUFFER_ADD(",");
+ BUFFER_ADD("%s=%lf", ds->ds[i].name, rates[i]);
+ have_values = true;
+ } else if (ds->ds[i].type == DS_TYPE_COUNTER) {
+ if (have_values) BUFFER_ADD(",");
+ BUFFER_ADD("%s=%" PRIu64 "i", ds->ds[i].name,
+ (uint64_t)vl->values[i].counter);
+ have_values = true;
+ } else if (ds->ds[i].type == DS_TYPE_DERIVE) {
+ if (have_values) BUFFER_ADD(",");
+ BUFFER_ADD("%s=%" PRIi64 "i", ds->ds[i].name, vl->values[i].derive);
+ have_values = true;
+ } else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) {
+ if (have_values) BUFFER_ADD(",");
+ BUFFER_ADD("%s=%" PRIu64 "i", ds->ds[i].name, vl->values[i].absolute);
+ have_values = true;
+ }
+
+ } /* for ds->ds_num */
+ sfree(rates);
+
+ if (!have_values) return 0;
+
+ uint64_t influxdb_time = 0;
+ switch (time_precision) {
+ case NS:
+ influxdb_time = CDTIME_T_TO_NS(vl->time);
+ break;
+ case US:
+ influxdb_time = CDTIME_T_TO_US(vl->time);
+ break;
+ case MS:
+ influxdb_time = CDTIME_T_TO_MS(vl->time);
+ break;
+ }
+
+ BUFFER_ADD(" %" PRIu64 "\n", influxdb_time);
+
+#undef BUFFER_ADD_ESCAPE
+#undef BUFFER_ADD
+
+ return offset;
+} /* int format_influxdb_value_list */
diff --git a/telemetry/kafka-collectd/format_influxdb.h b/telemetry/kafka-collectd/format_influxdb.h
new file mode 100644
index 000000000..fd298f11b
--- /dev/null
+++ b/telemetry/kafka-collectd/format_influxdb.h
@@ -0,0 +1,45 @@
+/**
+ * collectd - src/utils_format_influxdb.h
+ * Copyright (C) 2007-2009 Florian octo Forster
+ * Copyright (C) 2009 Aman Gupta
+ * Copyright (C) 2019 Carlos Peon Costa
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; only version 2 of the License is applicable.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Authors:
+ * Florian octo Forster <octo at collectd.org>
+ * Aman Gupta <aman at tmm1.net>
+ * Carlos Peon Costa <carlospeon at gmail.com>
+ * multiple Server directives by:
+ * Paul (systemcrash) <newtwen thatfunny_at_symbol gmail.com>
+ **/
+
+#ifndef UTILS_FORMAT_INFLUXDB_H
+#define UTILS_FORMAT_INFLUXDB_H 1
+
+#include "collectd.h"
+#include "plugin.h"
+
+typedef enum {
+ NS,
+ US,
+ MS,
+} format_influxdb_time_precision_t;
+
+int format_influxdb_value_list(char *buffer, int buffer_len,
+ const data_set_t *ds, const value_list_t *vl,
+ bool store_rates,
+ format_influxdb_time_precision_t time_precision);
+
+#endif /* UTILS_FORMAT_INFLUXDB_H */
diff --git a/telemetry/kafka-collectd/write_kafka_line_protocol.c b/telemetry/kafka-collectd/write_kafka_line_protocol.c
new file mode 100644
index 000000000..5eb7b520d
--- /dev/null
+++ b/telemetry/kafka-collectd/write_kafka_line_protocol.c
@@ -0,0 +1,526 @@
+/**
+ * collectd - src/write_kafka.c
+ * Copyright (C) 2014 Pierre-Yves Ritschard
+ *
+ * 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.
+ *
+ * Authors:
+ * Pierre-Yves Ritschard <pyr at spootnik.org>
+ */
+
+#include <errno.h>
+#include <librdkafka/rdkafka.h>
+#include <stdint.h>
+
+#include "../data_model.h"
+#include "collectd.h"
+#include "format_influxdb.h"
+#include "plugin.h"
+#include "utils/cmds/putval.h"
+#include "utils/common/common.h"
+#include "utils/format_graphite/format_graphite.h"
+#include "utils/format_json/format_json.h"
+#include "utils_random.h"
+
+struct kafka_topic_context {
+#define KAFKA_FORMAT_JSON 0
+#define KAFKA_FORMAT_COMMAND 1
+#define KAFKA_FORMAT_GRAPHITE 2
+#define KAFKA_FORMAT_INFLUXDB 3
+ uint8_t format;
+ unsigned int graphite_flags;
+ bool store_rates;
+ rd_kafka_topic_conf_t *conf;
+ rd_kafka_topic_t *topic;
+ rd_kafka_conf_t *kafka_conf;
+ rd_kafka_t *kafka;
+ char *key;
+ char *prefix;
+ char *postfix;
+ char escape_char;
+ char *topic_name;
+ pthread_mutex_t lock;
+};
+
+static int kafka_handle(struct kafka_topic_context *);
+static int kafka_write(const data_set_t *, const value_list_t *, user_data_t *);
+static int32_t kafka_partition(const rd_kafka_topic_t *, const void *, size_t,
+ int32_t, void *, void *);
+
+/* Version 0.9.0 of librdkafka deprecates rd_kafka_set_logger() in favor of
+ * rd_kafka_conf_set_log_cb(). This is to make sure we're not using the
+ * deprecated function. */
+#ifdef HAVE_LIBRDKAFKA_LOG_CB
+#undef HAVE_LIBRDKAFKA_LOGGER
+#endif
+
+#if defined(HAVE_LIBRDKAFKA_LOGGER) || defined(HAVE_LIBRDKAFKA_LOG_CB)
+static void kafka_log(const rd_kafka_t *, int, const char *, const char *);
+
+static void kafka_log(const rd_kafka_t *rkt, int level, const char *fac,
+ const char *msg) {
+ plugin_log(level, "%s", msg);
+}
+#endif
+
+static rd_kafka_resp_err_t kafka_error() {
+#if RD_KAFKA_VERSION >= 0x000b00ff
+ return rd_kafka_last_error();
+#else
+ return rd_kafka_errno2err(errno);
+#endif
+}
+
+static uint32_t kafka_hash(const char *keydata, size_t keylen) {
+ uint32_t hash = 5381;
+ for (; keylen > 0; keylen--)
+ hash = ((hash << 5) + hash) + keydata[keylen - 1];
+ return hash;
+}
+
+/* 31 bit -> 4 byte -> 8 byte hex string + null byte */
+#define KAFKA_RANDOM_KEY_SIZE 9
+#define KAFKA_RANDOM_KEY_BUFFER \
+ (char[KAFKA_RANDOM_KEY_SIZE]) { "" }
+static char *kafka_random_key(char buffer[static KAFKA_RANDOM_KEY_SIZE]) {
+ ssnprintf(buffer, KAFKA_RANDOM_KEY_SIZE, "%08" PRIX32, cdrand_u());
+ return buffer;
+}
+
+static int32_t kafka_partition(const rd_kafka_topic_t *rkt, const void *keydata,
+ size_t keylen, int32_t partition_cnt, void *p,
+ void *m) {
+ uint32_t key = kafka_hash(keydata, keylen);
+ uint32_t target = key % partition_cnt;
+ int32_t i = partition_cnt;
+
+ while (--i > 0 && !rd_kafka_topic_partition_available(rkt, target)) {
+ target = (target + 1) % partition_cnt;
+ }
+ return target;
+}
+
+static int kafka_handle(struct kafka_topic_context *ctx) /* {{{ */
+{
+ char errbuf[1024];
+ rd_kafka_conf_t *conf;
+ rd_kafka_topic_conf_t *topic_conf;
+
+ if (ctx->kafka != NULL && ctx->topic != NULL) return 0;
+
+ if (ctx->kafka == NULL) {
+ if ((conf = rd_kafka_conf_dup(ctx->kafka_conf)) == NULL) {
+ ERROR("write_kafka plugin: cannot duplicate kafka config");
+ return 1;
+ }
+
+ if ((ctx->kafka = rd_kafka_new(RD_KAFKA_PRODUCER, conf, errbuf,
+ sizeof(errbuf))) == NULL) {
+ ERROR("write_kafka plugin: cannot create kafka handle.");
+ return 1;
+ }
+
+ rd_kafka_conf_destroy(ctx->kafka_conf);
+ ctx->kafka_conf = NULL;
+
+ INFO("write_kafka plugin: created KAFKA handle : %s",
+ rd_kafka_name(ctx->kafka));
+
+#if defined(HAVE_LIBRDKAFKA_LOGGER) && !defined(HAVE_LIBRDKAFKA_LOG_CB)
+ rd_kafka_set_logger(ctx->kafka, kafka_log);
+#endif
+ }
+
+ if (ctx->topic == NULL) {
+ if ((topic_conf = rd_kafka_topic_conf_dup(ctx->conf)) == NULL) {
+ ERROR("write_kafka plugin: cannot duplicate kafka topic config");
+ return 1;
+ }
+
+ if ((ctx->topic = rd_kafka_topic_new(ctx->kafka, ctx->topic_name,
+ topic_conf)) == NULL) {
+ ERROR("write_kafka plugin: cannot create topic : %s\n",
+ rd_kafka_err2str(kafka_error()));
+ return errno;
+ }
+
+ rd_kafka_topic_conf_destroy(ctx->conf);
+ ctx->conf = NULL;
+
+ INFO("write_kafka plugin: handle created for topic : %s",
+ rd_kafka_topic_name(ctx->topic));
+ }
+
+ return 0;
+
+} /* }}} int kafka_handle */
+
+static int kafka_write(const data_set_t *ds, /* {{{ */
+ const value_list_t *vl, user_data_t *ud) {
+ int status = 0;
+ void *key;
+ size_t keylen = 0;
+ char buffer[8192];
+ size_t bfree = sizeof(buffer);
+ size_t bfill = 0;
+ size_t blen = 0;
+ struct kafka_topic_context *ctx = ud->data;
+
+ if ((ds == NULL) || (vl == NULL) || (ctx == NULL)) return EINVAL;
+
+ pthread_mutex_lock(&ctx->lock);
+ status = kafka_handle(ctx);
+ pthread_mutex_unlock(&ctx->lock);
+ if (status != 0) return status;
+
+ bzero(buffer, sizeof(buffer));
+
+ switch (ctx->format) {
+ case KAFKA_FORMAT_COMMAND:
+ status = cmd_create_putval(buffer, sizeof(buffer), ds, vl);
+ if (status != 0) {
+ ERROR("write_kafka plugin: cmd_create_putval failed with status %i.",
+ status);
+ return status;
+ }
+ blen = strlen(buffer);
+ break;
+ case KAFKA_FORMAT_JSON:
+ format_json_initialize(buffer, &bfill, &bfree);
+ format_json_value_list(buffer, &bfill, &bfree, ds, vl, ctx->store_rates);
+ format_json_finalize(buffer, &bfill, &bfree);
+ blen = strlen(buffer);
+ break;
+ case KAFKA_FORMAT_GRAPHITE:
+ status =
+ format_graphite(buffer, sizeof(buffer), ds, vl, ctx->prefix,
+ ctx->postfix, ctx->escape_char, ctx->graphite_flags);
+ if (status != 0) {
+ ERROR("write_kafka plugin: format_graphite failed with status %i.",
+ status);
+ return status;
+ }
+ blen = strlen(buffer);
+ break;
+ case KAFKA_FORMAT_INFLUXDB: {
+ // Decide format depending on the topic
+ // (to handle multilple topics w/ different formats);
+ // Comment this part to use the stream topic as default for other
+ // collectd plugins (e.g. cpu, mem)
+ char *topic = NULL;
+ int rc = meta_data_get_string(vl->meta, KAFKA_TOPIC_KEY, &topic);
+ if (rc != 0 || topic == NULL) return 0;
+ if (strcasecmp(KAFKA_STREAM_TOPIC, topic) != 0) {
+ free(topic);
+ return 0;
+ }
+ meta_data_delete(vl->meta, KAFKA_TOPIC_KEY);
+
+ status =
+ format_influxdb_value_list(buffer, sizeof(buffer), ds, vl, false, NS);
+ if (status <= 0) {
+ ERROR("write_kafka plugin: format_influxdb failed with status %i.",
+ status);
+ return status;
+ }
+ blen = strlen(buffer);
+
+ // Print without newline
+ buffer[blen - 1] = 0;
+ INFO("%s", buffer);
+ buffer[blen - 1] = '\n';
+
+ break;
+ }
+ default:
+ ERROR("write_kafka plugin: invalid format %i.", ctx->format);
+ return -1;
+ }
+
+ key =
+ (ctx->key != NULL) ? ctx->key : kafka_random_key(KAFKA_RANDOM_KEY_BUFFER);
+ keylen = strlen(key);
+
+ rd_kafka_produce(ctx->topic, RD_KAFKA_PARTITION_UA, RD_KAFKA_MSG_F_COPY,
+ buffer, blen, key, keylen, NULL);
+
+ return status;
+} /* }}} int kafka_write */
+
+static void kafka_topic_context_free(void *p) /* {{{ */
+{
+ struct kafka_topic_context *ctx = p;
+
+ if (ctx == NULL) return;
+
+ if (ctx->topic_name != NULL) sfree(ctx->topic_name);
+ if (ctx->topic != NULL) rd_kafka_topic_destroy(ctx->topic);
+ if (ctx->conf != NULL) rd_kafka_topic_conf_destroy(ctx->conf);
+ if (ctx->kafka_conf != NULL) rd_kafka_conf_destroy(ctx->kafka_conf);
+ if (ctx->kafka != NULL) rd_kafka_destroy(ctx->kafka);
+
+ sfree(ctx);
+} /* }}} void kafka_topic_context_free */
+
+static void kafka_config_topic(rd_kafka_conf_t *conf,
+ oconfig_item_t *ci) /* {{{ */
+{
+ int status;
+ struct kafka_topic_context *tctx;
+ char *key = NULL;
+ char *val;
+ char callback_name[DATA_MAX_NAME_LEN];
+ char errbuf[1024];
+ oconfig_item_t *child;
+ rd_kafka_conf_res_t ret;
+
+ if ((tctx = calloc(1, sizeof(*tctx))) == NULL) {
+ ERROR("write_kafka plugin: calloc failed.");
+ return;
+ }
+
+ tctx->escape_char = '.';
+ tctx->store_rates = true;
+ tctx->format = KAFKA_FORMAT_JSON;
+ tctx->key = NULL;
+
+ if ((tctx->kafka_conf = rd_kafka_conf_dup(conf)) == NULL) {
+ sfree(tctx);
+ ERROR("write_kafka plugin: cannot allocate memory for kafka config");
+ return;
+ }
+
+#ifdef HAVE_LIBRDKAFKA_LOG_CB
+ rd_kafka_conf_set_log_cb(tctx->kafka_conf, kafka_log);
+#endif
+
+ if ((tctx->conf = rd_kafka_topic_conf_new()) == NULL) {
+ rd_kafka_conf_destroy(tctx->kafka_conf);
+ sfree(tctx);
+ ERROR("write_kafka plugin: cannot create topic configuration.");
+ return;
+ }
+
+ if (ci->values_num != 1) {
+ WARNING("kafka topic name needed.");
+ goto errout;
+ }
+
+ if (ci->values[0].type != OCONFIG_TYPE_STRING) {
+ WARNING("kafka topic needs a string argument.");
+ goto errout;
+ }
+
+ if ((tctx->topic_name = strdup(ci->values[0].value.string)) == NULL) {
+ ERROR("write_kafka plugin: cannot copy topic name.");
+ goto errout;
+ }
+
+ for (int i = 0; i < ci->children_num; i++) {
+ /*
+ * The code here could be simplified but makes room
+ * for easy adding of new options later on.
+ */
+ child = &ci->children[i];
+ status = 0;
+
+ if (strcasecmp("Property", child->key) == 0) {
+ if (child->values_num != 2) {
+ WARNING("kafka properties need both a key and a value.");
+ goto errout;
+ }
+ if (child->values[0].type != OCONFIG_TYPE_STRING ||
+ child->values[1].type != OCONFIG_TYPE_STRING) {
+ WARNING("kafka properties needs string arguments.");
+ goto errout;
+ }
+ key = child->values[0].value.string;
+ val = child->values[1].value.string;
+ ret =
+ rd_kafka_topic_conf_set(tctx->conf, key, val, errbuf, sizeof(errbuf));
+ if (ret != RD_KAFKA_CONF_OK) {
+ WARNING("cannot set kafka topic property %s to %s: %s.", key, val,
+ errbuf);
+ goto errout;
+ }
+
+ } else if (strcasecmp("Key", child->key) == 0) {
+ if (cf_util_get_string(child, &tctx->key) != 0) continue;
+ if (strcasecmp("Random", tctx->key) == 0) {
+ sfree(tctx->key);
+ tctx->key = strdup(kafka_random_key(KAFKA_RANDOM_KEY_BUFFER));
+ }
+ } else if (strcasecmp("Format", child->key) == 0) {
+ status = cf_util_get_string(child, &key);
+ if (status != 0) goto errout;
+
+ assert(key != NULL);
+
+ if (strcasecmp(key, "Command") == 0) {
+ tctx->format = KAFKA_FORMAT_COMMAND;
+
+ } else if (strcasecmp(key, "Graphite") == 0) {
+ tctx->format = KAFKA_FORMAT_GRAPHITE;
+
+ } else if (strcasecmp(key, "Json") == 0) {
+ tctx->format = KAFKA_FORMAT_JSON;
+
+ } else if (strcasecmp(key, "InfluxDB") == 0) {
+ tctx->format = KAFKA_FORMAT_INFLUXDB;
+
+ } else {
+ WARNING("write_kafka plugin: Invalid format string: %s", key);
+ }
+
+ sfree(key);
+
+ } else if (strcasecmp("StoreRates", child->key) == 0) {
+ status = cf_util_get_boolean(child, &tctx->store_rates);
+ (void)cf_util_get_flag(child, &tctx->graphite_flags,
+ GRAPHITE_STORE_RATES);
+
+ } else if (strcasecmp("GraphiteSeparateInstances", child->key) == 0) {
+ status = cf_util_get_flag(child, &tctx->graphite_flags,
+ GRAPHITE_SEPARATE_INSTANCES);
+
+ } else if (strcasecmp("GraphiteAlwaysAppendDS", child->key) == 0) {
+ status = cf_util_get_flag(child, &tctx->graphite_flags,
+ GRAPHITE_ALWAYS_APPEND_DS);
+
+ } else if (strcasecmp("GraphitePreserveSeparator", child->key) == 0) {
+ status = cf_util_get_flag(child, &tctx->graphite_flags,
+ GRAPHITE_PRESERVE_SEPARATOR);
+
+ } else if (strcasecmp("GraphiteUseTags", child->key) == 0) {
+ status =
+ cf_util_get_flag(child, &tctx->graphite_flags, GRAPHITE_USE_TAGS);
+
+ } else if (strcasecmp("GraphitePrefix", child->key) == 0) {
+ status = cf_util_get_string(child, &tctx->prefix);
+ } else if (strcasecmp("GraphitePostfix", child->key) == 0) {
+ status = cf_util_get_string(child, &tctx->postfix);
+ } else if (strcasecmp("GraphiteEscapeChar", child->key) == 0) {
+ char *tmp_buff = NULL;
+ status = cf_util_get_string(child, &tmp_buff);
+ if (strlen(tmp_buff) > 1)
+ WARNING(
+ "write_kafka plugin: The option \"GraphiteEscapeChar\" handles "
+ "only one character. Others will be ignored.");
+ tctx->escape_char = tmp_buff[0];
+ sfree(tmp_buff);
+ } else {
+ WARNING("write_kafka plugin: Invalid directive: %s.", child->key);
+ }
+
+ if (status != 0) break;
+ }
+
+ rd_kafka_topic_conf_set_partitioner_cb(tctx->conf, kafka_partition);
+ rd_kafka_topic_conf_set_opaque(tctx->conf, tctx);
+
+ ssnprintf(callback_name, sizeof(callback_name), "write_kafka/%s",
+ tctx->topic_name);
+
+ status = plugin_register_write(callback_name, kafka_write,
+ &(user_data_t){
+ .data = tctx,
+ .free_func = kafka_topic_context_free,
+ });
+ if (status != 0) {
+ WARNING(
+ "write_kafka plugin: plugin_register_write (\"%s\") "
+ "failed with status %i.",
+ callback_name, status);
+ goto errout;
+ }
+
+ pthread_mutex_init(&tctx->lock, /* attr = */ NULL);
+
+ return;
+errout:
+ if (tctx->topic_name != NULL) free(tctx->topic_name);
+ if (tctx->conf != NULL) rd_kafka_topic_conf_destroy(tctx->conf);
+ if (tctx->kafka_conf != NULL) rd_kafka_conf_destroy(tctx->kafka_conf);
+ sfree(tctx);
+} /* }}} int kafka_config_topic */
+
+static int kafka_config(oconfig_item_t *ci) /* {{{ */
+{
+ oconfig_item_t *child;
+ rd_kafka_conf_t *conf;
+ rd_kafka_conf_res_t ret;
+ char errbuf[1024];
+
+ if ((conf = rd_kafka_conf_new()) == NULL) {
+ WARNING("cannot allocate kafka configuration.");
+ return -1;
+ }
+ for (int i = 0; i < ci->children_num; i++) {
+ child = &ci->children[i];
+
+ if (strcasecmp("Topic", child->key) == 0) {
+ kafka_config_topic(conf, child);
+ } else if (strcasecmp(child->key, "Property") == 0) {
+ char *key = NULL;
+ char *val = NULL;
+
+ if (child->values_num != 2) {
+ WARNING("kafka properties need both a key and a value.");
+ goto errout;
+ }
+ if (child->values[0].type != OCONFIG_TYPE_STRING ||
+ child->values[1].type != OCONFIG_TYPE_STRING) {
+ WARNING("kafka properties needs string arguments.");
+ goto errout;
+ }
+ if ((key = strdup(child->values[0].value.string)) == NULL) {
+ WARNING("cannot allocate memory for attribute key.");
+ goto errout;
+ }
+ if ((val = strdup(child->values[1].value.string)) == NULL) {
+ WARNING("cannot allocate memory for attribute value.");
+ sfree(key);
+ goto errout;
+ }
+ ret = rd_kafka_conf_set(conf, key, val, errbuf, sizeof(errbuf));
+ if (ret != RD_KAFKA_CONF_OK) {
+ WARNING("cannot set kafka property %s to %s: %s", key, val, errbuf);
+ sfree(key);
+ sfree(val);
+ goto errout;
+ }
+ sfree(key);
+ sfree(val);
+ } else {
+ WARNING(
+ "write_kafka plugin: Ignoring unknown "
+ "configuration option \"%s\" at top level.",
+ child->key);
+ }
+ }
+ if (conf != NULL) rd_kafka_conf_destroy(conf);
+ return 0;
+errout:
+ if (conf != NULL) rd_kafka_conf_destroy(conf);
+ return -1;
+} /* }}} int kafka_config */
+
+void module_register(void) {
+ plugin_register_complex_config("write_kafka_line_protocol", kafka_config);
+}
diff --git a/telemetry/third-party/CMakeLists.txt b/telemetry/third-party/CMakeLists.txt
new file mode 100644
index 000000000..26d305d62
--- /dev/null
+++ b/telemetry/third-party/CMakeLists.txt
@@ -0,0 +1,18 @@
+# Copyright (c) 2022 Cisco and/or its affiliates.
+
+set(THIRD_PARTY_INSTALL_PREFIX ${CMAKE_CURRENT_BINARY_DIR})
+
+include(FetchContent)
+set(FETCHCONTENT_QUIET off)
+FetchContent_Declare(collectd
+ URL https://github.com/collectd/collectd/archive/refs/tags/collectd-${COLLECTD_VERSION}.zip
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ""
+ INSTALL_COMMAND ""
+)
+FetchContent_Populate(collectd)
+
+list(APPEND THIRD_PARTY_INCLUDE_DIRS
+ ${collectd_SOURCE_DIR}/src
+)
+set(THIRD_PARTY_INCLUDE_DIRS ${THIRD_PARTY_INCLUDE_DIRS} PARENT_SCOPE)
diff --git a/telemetry/vpp-collectd/CMakeLists.txt b/telemetry/vpp-collectd/CMakeLists.txt
index 7afb3f432..4ce357f63 100644
--- a/telemetry/vpp-collectd/CMakeLists.txt
+++ b/telemetry/vpp-collectd/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,18 +11,26 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-set(COLLECTD_PLUGINS hicn-collectd-plugins)
-project(hicn-collectd-plugins)
+##############################################################
+# Dependencies
+##############################################################
+find_package(Vpp ${VPP_DEFAULT_VERSION} REQUIRED)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/" "${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/Modules/")
-include(BuildMacros)
+##############################################################
+# Compiler Options
+##############################################################
+set(COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+)
+
+##############################################################
+# Subdirectories
+##############################################################
add_subdirectory(vpp)
add_subdirectory(vpp-hicn)
-include(Packaging)
if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- include(Packager)
- make_packages()
+ make_packages()
endif()
diff --git a/telemetry/vpp-collectd/common/README.md b/telemetry/vpp-collectd/common/README.md
deleted file mode 100644
index e3b9c74f6..000000000
--- a/telemetry/vpp-collectd/common/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Headers for collectd plugins
-
-These headers are required for plugin development but are not shipped with the
-`collectd` Ubuntu 20.04 package (as of May 2021):
-
-* [common.h](https://github.com/collectd/collectd/blob/main/src/utils/common/common.h)
-* [plugin.h](https://github.com/collectd/collectd/blob/main/src/daemon/plugin.h)
-* [meta_data.h](https://github.com/collectd/collectd/blob/main/src/utils/metadata/meta_data.h)
-
-Related issues:
-* [GitHub](https://github.com/collectd/collectd/issues/3881)
-* [Ubuntu](https://bugs.launchpad.net/ubuntu/+source/collectd/+bug/1929079)
diff --git a/telemetry/vpp-collectd/common/common.h b/telemetry/vpp-collectd/common/common.h
deleted file mode 100644
index fce2d12bb..000000000
--- a/telemetry/vpp-collectd/common/common.h
+++ /dev/null
@@ -1,405 +0,0 @@
-/**
- * collectd - src/common.h
- * Copyright (C) 2005-2014 Florian octo Forster
- *
- * 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.
- *
- * Authors:
- * Florian octo Forster <octo at collectd.org>
- * Niki W. Waibel <niki.waibel@gmx.net>
- **/
-
-#ifndef COMMON_H
-#define COMMON_H
-
-#include "collectd.h"
-
-#include "plugin.h"
-
-#if HAVE_PWD_H
-#include <pwd.h>
-#endif
-
-#define sfree(ptr) \
- do { \
- free(ptr); \
- (ptr) = NULL; \
- } while (0)
-
-#define STATIC_ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
-
-#define IS_TRUE(s) \
- ((strcasecmp("true", (s)) == 0) || (strcasecmp("yes", (s)) == 0) || \
- (strcasecmp("on", (s)) == 0))
-#define IS_FALSE(s) \
- ((strcasecmp("false", (s)) == 0) || (strcasecmp("no", (s)) == 0) || \
- (strcasecmp("off", (s)) == 0))
-
-struct rate_to_value_state_s {
- value_t last_value;
- cdtime_t last_time;
- gauge_t residual;
-};
-typedef struct rate_to_value_state_s rate_to_value_state_t;
-
-struct value_to_rate_state_s {
- value_t last_value;
- cdtime_t last_time;
-};
-typedef struct value_to_rate_state_s value_to_rate_state_t;
-
-char *sstrncpy(char *dest, const char *src, size_t n);
-
-__attribute__((format(printf, 3, 4))) int ssnprintf(char *str, size_t size,
- char const *format, ...);
-
-__attribute__((format(printf, 1, 2))) char *ssnprintf_alloc(char const *format,
- ...);
-
-char *sstrdup(const char *s);
-size_t sstrnlen(const char *s, size_t n);
-char *sstrndup(const char *s, size_t n);
-void *smalloc(size_t size);
-char *sstrerror(int errnum, char *buf, size_t buflen);
-
-#ifndef ERRBUF_SIZE
-#define ERRBUF_SIZE 256
-#endif
-
-#define STRERROR(e) sstrerror((e), (char[ERRBUF_SIZE]){0}, ERRBUF_SIZE)
-#define STRERRNO STRERROR(errno)
-
-/*
- * NAME
- * sread
- *
- * DESCRIPTION
- * Reads exactly `n' bytes or fails. Syntax and other behavior is analogous
- * to `read(2)'.
- *
- * PARAMETERS
- * `fd' File descriptor to write to.
- * `buf' Buffer that is to be written.
- * `count' Number of bytes in the buffer.
- *
- * RETURN VALUE
- * Zero upon success or non-zero if an error occurred. `errno' is set in this
- * case.
- */
-int sread(int fd, void *buf, size_t count);
-
-/*
- * NAME
- * swrite
- *
- * DESCRIPTION
- * Writes exactly `n' bytes or fails. Syntax and other behavior is analogous
- * to `write(2)'.
- *
- * PARAMETERS
- * `fd' File descriptor to write to.
- * `buf' Buffer that is to be written.
- * `count' Number of bytes in the buffer.
- *
- * RETURN VALUE
- * Zero upon success or non-zero if an error occurred. `errno' is set in this
- * case.
- */
-int swrite(int fd, const void *buf, size_t count);
-
-/*
- * NAME
- * strsplit
- *
- * DESCRIPTION
- * Splits a string into parts and stores pointers to the parts in `fields'.
- * The characters split at are: " ", "\t", "\r", and "\n".
- *
- * PARAMETERS
- * `string' String to split. This string will be modified. `fields' will
- * contain pointers to parts of this string, so free'ing it
- * will destroy `fields' as well.
- * `fields' Array of strings where pointers to the parts will be stored.
- * `size' Number of elements in the array. No more than `size'
- * pointers will be stored in `fields'.
- *
- * RETURN VALUE
- * Returns the number of parts stored in `fields'.
- */
-int strsplit(char *string, char **fields, size_t size);
-
-/*
- * NAME
- * strjoin
- *
- * DESCRIPTION
- * Joins together several parts of a string using `sep' as a separator. This
- * is equivalent to the Perl built-in `join'.
- *
- * PARAMETERS
- * `dst' Buffer where the result is stored. Can be NULL if you need to
- * determine the required buffer size only.
- * `dst_len' Length of the destination buffer. No more than this many
- * bytes will be written to the memory pointed to by `dst',
- * including the trailing null-byte. Must be zero if dst is
- * NULL.
- * `fields' Array of strings to be joined.
- * `fields_num' Number of elements in the `fields' array.
- * `sep' String to be inserted between any two elements of `fields'.
- * This string is neither prepended nor appended to the result.
- * Instead of passing "" (empty string) one can pass NULL.
- *
- * RETURN VALUE
- * Returns the number of characters in the resulting string, excluding a
- * tailing null byte. If this value is greater than or equal to "dst_len", the
- * result in "dst" is truncated (but still null terminated). On error a
- * negative value is returned.
- */
-int strjoin(char *dst, size_t dst_len, char **fields, size_t fields_num,
- const char *sep);
-
-/*
- * NAME
- * escape_slashes
- *
- * DESCRIPTION
- * Removes slashes ("/") from "buffer". If buffer contains a single slash,
- * the result will be "root". Leading slashes are removed. All other slashes
- * are replaced with underscores ("_").
- * This function is used by plugin_dispatch_values() to escape all parts of
- * the identifier.
- *
- * PARAMETERS
- * `buffer' String to be escaped.
- * `buffer_size' Size of the buffer. No more then this many bytes will be
- * written to `buffer', including the trailing null-byte.
- *
- * RETURN VALUE
- * Returns zero upon success and a value smaller than zero upon failure.
- */
-int escape_slashes(char *buffer, size_t buffer_size);
-
-/**
- * NAME
- * escape_string
- *
- * DESCRIPTION
- * escape_string quotes and escapes a string to be usable with collectd's
- * plain text protocol. "simple" strings are left as they are, for example if
- * buffer is 'simple' before the call, it will remain 'simple'. However, if
- * buffer contains 'more "complex"' before the call, the returned buffer will
- * contain '"more \"complex\""'.
- *
- * If the buffer is too small to contain the escaped string, the string will
- * be truncated. However, leading and trailing double quotes, as well as an
- * ending null byte are guaranteed.
- *
- * RETURN VALUE
- * Returns zero on success, even if the string was truncated. Non-zero on
- * failure.
- */
-int escape_string(char *buffer, size_t buffer_size);
-
-/*
- * NAME
- * replace_special
- *
- * DESCRIPTION
- * Replaces any special characters (anything that's not alpha-numeric or a
- * dash) with an underscore.
- *
- * E.g. "foo$bar&" would become "foo_bar_".
- *
- * PARAMETERS
- * `buffer' String to be handled.
- * `buffer_size' Length of the string. The function returns after
- * encountering a null-byte or reading this many bytes.
- */
-void replace_special(char *buffer, size_t buffer_size);
-
-/*
- * NAME
- * strunescape
- *
- * DESCRIPTION
- * Replaces any escaped characters in a string with the appropriate special
- * characters. The following escaped characters are recognized:
- *
- * \t -> <tab>
- * \n -> <newline>
- * \r -> <carriage return>
- *
- * For all other escacped characters only the backslash will be removed.
- *
- * PARAMETERS
- * `buf' String to be unescaped.
- * `buf_len' Length of the string, including the terminating null-byte.
- *
- * RETURN VALUE
- * Returns zero upon success, a value less than zero else.
- */
-int strunescape(char *buf, size_t buf_len);
-
-/**
- * Removed trailing newline characters (CR and LF) from buffer, which must be
- * null terminated. Returns the length of the resulting string.
- */
-__attribute__((nonnull(1))) size_t strstripnewline(char *buffer);
-
-/*
- * NAME
- * timeval_cmp
- *
- * DESCRIPTION
- * Compare the two time values `tv0' and `tv1' and store the absolut value
- * of the difference in the time value pointed to by `delta' if it does not
- * equal NULL.
- *
- * RETURN VALUE
- * Returns an integer less than, equal to, or greater than zero if `tv0' is
- * less than, equal to, or greater than `tv1' respectively.
- */
-int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta);
-
-/* make sure tv_usec stores less than a second */
-#define NORMALIZE_TIMEVAL(tv) \
- do { \
- (tv).tv_sec += (tv).tv_usec / 1000000; \
- (tv).tv_usec = (tv).tv_usec % 1000000; \
- } while (0)
-
-/* make sure tv_sec stores less than a second */
-#define NORMALIZE_TIMESPEC(tv) \
- do { \
- (tv).tv_sec += (tv).tv_nsec / 1000000000; \
- (tv).tv_nsec = (tv).tv_nsec % 1000000000; \
- } while (0)
-
-int check_create_dir(const char *file_orig);
-
-#ifdef HAVE_LIBKSTAT
-#if HAVE_KSTAT_H
-#include <kstat.h>
-#endif
-int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name);
-long long get_kstat_value(kstat_t *ksp, char *name);
-#endif
-
-#ifndef HAVE_HTONLL
-unsigned long long ntohll(unsigned long long n);
-unsigned long long htonll(unsigned long long n);
-#endif
-
-#if FP_LAYOUT_NEED_NOTHING
-#define ntohd(d) (d)
-#define htond(d) (d)
-#elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
-double ntohd(double d);
-double htond(double d);
-#else
-#error \
- "Don't know how to convert between host and network representation of doubles."
-#endif
-
-int format_name(char *ret, int ret_len, const char *hostname,
- const char *plugin, const char *plugin_instance,
- const char *type, const char *type_instance);
-#define FORMAT_VL(ret, ret_len, vl) \
- format_name(ret, ret_len, (vl)->host, (vl)->plugin, (vl)->plugin_instance, \
- (vl)->type, (vl)->type_instance)
-int format_values(char *ret, size_t ret_len, const data_set_t *ds,
- const value_list_t *vl, bool store_rates);
-
-int parse_identifier(char *str, char **ret_host, char **ret_plugin,
- char **ret_plugin_instance, char **ret_type,
- char **ret_type_instance, char *default_host);
-int parse_identifier_vl(const char *str, value_list_t *vl);
-int parse_value(const char *value, value_t *ret_value, int ds_type);
-int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds);
-
-/* parse_value_file reads "path" and parses its content as an integer or
- * floating point, depending on "ds_type". On success, the value is stored in
- * "ret_value" and zero is returned. On failure, a non-zero value is returned.
- */
-int parse_value_file(char const *path, value_t *ret_value, int ds_type);
-
-#if !HAVE_GETPWNAM_R
-struct passwd;
-int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
- struct passwd **pwbufp);
-#endif
-
-int notification_init(notification_t *n, int severity, const char *message,
- const char *host, const char *plugin,
- const char *plugin_instance, const char *type,
- const char *type_instance);
-#define NOTIFICATION_INIT_VL(n, vl) \
- notification_init(n, NOTIF_FAILURE, NULL, (vl)->host, (vl)->plugin, \
- (vl)->plugin_instance, (vl)->type, (vl)->type_instance)
-
-typedef int (*dirwalk_callback_f)(const char *dirname, const char *filename,
- void *user_data);
-int walk_directory(const char *dir, dirwalk_callback_f callback,
- void *user_data, int hidden);
-/* Returns the number of bytes read or negative on error. */
-ssize_t read_file_contents(char const *filename, void *buf, size_t bufsize);
-/* Writes the contents of the file into the buffer with a trailing NUL.
- * Returns the number of bytes written to the buffer or negative on error. */
-ssize_t read_text_file_contents(char const *filename, char *buf,
- size_t bufsize);
-
-counter_t counter_diff(counter_t old_value, counter_t new_value);
-
-/* Convert a rate back to a value_t. When converting to a derive_t, counter_t
- * or absolute_t, take fractional residuals into account. This is important
- * when scaling counters, for example.
- * Returns zero on success. Returns EAGAIN when called for the first time; in
- * this case the value_t is invalid and the next call should succeed. Other
- * return values indicate an error. */
-int rate_to_value(value_t *ret_value, gauge_t rate,
- rate_to_value_state_t *state, int ds_type, cdtime_t t);
-
-int value_to_rate(gauge_t *ret_rate, value_t value, int ds_type, cdtime_t t,
- value_to_rate_state_t *state);
-
-/* Converts a service name (a string) to a port number
- * (in the range [1-65535]). Returns less than zero on error. */
-int service_name_to_port_number(const char *service_name);
-
-/* Sets various, non-default, socket options */
-void set_sock_opts(int sockfd);
-
-/** Parse a string to a derive_t value. Returns zero on success or non-zero on
- * failure. If failure is returned, ret_value is not touched. */
-int strtoderive(const char *string, derive_t *ret_value);
-
-/** Parse a string to a gauge_t value. Returns zero on success or non-zero on
- * failure. If failure is returned, ret_value is not touched. */
-int strtogauge(const char *string, gauge_t *ret_value);
-
-int strarray_add(char ***ret_array, size_t *ret_array_len, char const *str);
-void strarray_free(char **array, size_t array_len);
-
-/** Check if the current process benefits from the capability passed in
- * argument. Returns zero if it does, less than zero if it doesn't or on error.
- * See capabilities(7) for the list of possible capabilities.
- * */
-int check_capability(int arg);
-
-#endif /* COMMON_H */
diff --git a/telemetry/vpp-collectd/common/meta_data.h b/telemetry/vpp-collectd/common/meta_data.h
deleted file mode 100644
index 203b14607..000000000
--- a/telemetry/vpp-collectd/common/meta_data.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * collectd - src/meta_data.h
- * Copyright (C) 2008-2011 Florian octo Forster
- *
- * 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.
- *
- * Authors:
- * Florian octo Forster <octo at collectd.org>
- **/
-
-#ifndef META_DATA_H
-#define META_DATA_H
-
-#include "collectd.h"
-
-/*
- * Defines
- */
-#define MD_TYPE_STRING 1
-#define MD_TYPE_SIGNED_INT 2
-#define MD_TYPE_UNSIGNED_INT 3
-#define MD_TYPE_DOUBLE 4
-#define MD_TYPE_BOOLEAN 5
-
-struct meta_data_s;
-typedef struct meta_data_s meta_data_t;
-
-meta_data_t *meta_data_create(void);
-meta_data_t *meta_data_clone(meta_data_t *orig);
-int meta_data_clone_merge(meta_data_t **dest, meta_data_t *orig);
-void meta_data_destroy(meta_data_t *md);
-
-int meta_data_exists(meta_data_t *md, const char *key);
-int meta_data_type(meta_data_t *md, const char *key);
-int meta_data_toc(meta_data_t *md, char ***toc);
-int meta_data_delete(meta_data_t *md, const char *key);
-
-int meta_data_add_string(meta_data_t *md, const char *key, const char *value);
-int meta_data_add_signed_int(meta_data_t *md, const char *key, int64_t value);
-int meta_data_add_unsigned_int(meta_data_t *md, const char *key,
- uint64_t value);
-int meta_data_add_double(meta_data_t *md, const char *key, double value);
-int meta_data_add_boolean(meta_data_t *md, const char *key, bool value);
-
-int meta_data_get_string(meta_data_t *md, const char *key, char **value);
-int meta_data_get_signed_int(meta_data_t *md, const char *key, int64_t *value);
-int meta_data_get_unsigned_int(meta_data_t *md, const char *key,
- uint64_t *value);
-int meta_data_get_double(meta_data_t *md, const char *key, double *value);
-int meta_data_get_boolean(meta_data_t *md, const char *key, bool *value);
-
-/* Returns the value as a string, regardless of the type. */
-int meta_data_as_string(meta_data_t *md, const char *key, char **value);
-
-#endif /* META_DATA_H */
diff --git a/telemetry/vpp-collectd/common/plugin.h b/telemetry/vpp-collectd/common/plugin.h
deleted file mode 100644
index 0e75adc9b..000000000
--- a/telemetry/vpp-collectd/common/plugin.h
+++ /dev/null
@@ -1,485 +0,0 @@
-/**
- * collectd - src/daemon/plugin.h
- * Copyright (C) 2005-2014 Florian octo Forster
- *
- * 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.
- *
- * Authors:
- * Florian octo Forster <octo at collectd.org>
- * Sebastian Harl <sh at tokkee.org>
- **/
-
-#ifndef PLUGIN_H
-#define PLUGIN_H
-
-#include "collectd.h"
-
-#include "configfile.h"
-#include "meta_data.h"
-#include "utils_time.h"
-
-#include <inttypes.h>
-#include <pthread.h>
-
-#define DS_TYPE_COUNTER 0
-#define DS_TYPE_GAUGE 1
-#define DS_TYPE_DERIVE 2
-#define DS_TYPE_ABSOLUTE 3
-
-#define DS_TYPE_TO_STRING(t) \
- (t == DS_TYPE_COUNTER) \
- ? "counter" \
- : (t == DS_TYPE_GAUGE) \
- ? "gauge" \
- : (t == DS_TYPE_DERIVE) \
- ? "derive" \
- : (t == DS_TYPE_ABSOLUTE) ? "absolute" : "unknown"
-
-#ifndef LOG_ERR
-#define LOG_ERR 3
-#endif
-#ifndef LOG_WARNING
-#define LOG_WARNING 4
-#endif
-#ifndef LOG_NOTICE
-#define LOG_NOTICE 5
-#endif
-#ifndef LOG_INFO
-#define LOG_INFO 6
-#endif
-#ifndef LOG_DEBUG
-#define LOG_DEBUG 7
-#endif
-
-#define NOTIF_MAX_MSG_LEN 256
-
-#define NOTIF_FAILURE 1
-#define NOTIF_WARNING 2
-#define NOTIF_OKAY 4
-
-#define plugin_interval (plugin_get_ctx().interval)
-
-/*
- * Public data types
- */
-struct identifier_s {
- char *host;
- char *plugin;
- char *plugin_instance;
- char *type;
- char *type_instance;
-};
-typedef struct identifier_s identifier_t;
-
-typedef unsigned long long counter_t;
-typedef double gauge_t;
-typedef int64_t derive_t;
-typedef uint64_t absolute_t;
-
-union value_u {
- counter_t counter;
- gauge_t gauge;
- derive_t derive;
- absolute_t absolute;
-};
-typedef union value_u value_t;
-
-struct value_list_s {
- value_t *values;
- size_t values_len;
- cdtime_t time;
- cdtime_t interval;
- char host[DATA_MAX_NAME_LEN];
- char plugin[DATA_MAX_NAME_LEN];
- char plugin_instance[DATA_MAX_NAME_LEN];
- char type[DATA_MAX_NAME_LEN];
- char type_instance[DATA_MAX_NAME_LEN];
- meta_data_t *meta;
-};
-typedef struct value_list_s value_list_t;
-
-#define VALUE_LIST_INIT \
- { .values = NULL, .meta = NULL }
-
-struct data_source_s {
- char name[DATA_MAX_NAME_LEN];
- int type;
- double min;
- double max;
-};
-typedef struct data_source_s data_source_t;
-
-struct data_set_s {
- char type[DATA_MAX_NAME_LEN];
- size_t ds_num;
- data_source_t *ds;
-};
-typedef struct data_set_s data_set_t;
-
-enum notification_meta_type_e {
- NM_TYPE_STRING,
- NM_TYPE_SIGNED_INT,
- NM_TYPE_UNSIGNED_INT,
- NM_TYPE_DOUBLE,
- NM_TYPE_BOOLEAN
-};
-
-typedef struct notification_meta_s {
- char name[DATA_MAX_NAME_LEN];
- enum notification_meta_type_e type;
- union {
- const char *nm_string;
- int64_t nm_signed_int;
- uint64_t nm_unsigned_int;
- double nm_double;
- bool nm_boolean;
- } nm_value;
- struct notification_meta_s *next;
-} notification_meta_t;
-
-typedef struct notification_s {
- int severity;
- cdtime_t time;
- char message[NOTIF_MAX_MSG_LEN];
- char host[DATA_MAX_NAME_LEN];
- char plugin[DATA_MAX_NAME_LEN];
- char plugin_instance[DATA_MAX_NAME_LEN];
- char type[DATA_MAX_NAME_LEN];
- char type_instance[DATA_MAX_NAME_LEN];
- notification_meta_t *meta;
-} notification_t;
-
-struct user_data_s {
- void *data;
- void (*free_func)(void *);
-};
-typedef struct user_data_s user_data_t;
-
-enum cache_event_type_e { CE_VALUE_NEW, CE_VALUE_UPDATE, CE_VALUE_EXPIRED };
-
-typedef struct cache_event_s {
- enum cache_event_type_e type;
- const value_list_t *value_list;
- const char *value_list_name;
- int ret;
-} cache_event_t;
-
-struct plugin_ctx_s {
- char *name;
- cdtime_t interval;
- cdtime_t flush_interval;
- cdtime_t flush_timeout;
-};
-typedef struct plugin_ctx_s plugin_ctx_t;
-
-/*
- * Callback types
- */
-typedef int (*plugin_init_cb)(void);
-typedef int (*plugin_read_cb)(user_data_t *);
-typedef int (*plugin_write_cb)(const data_set_t *, const value_list_t *,
- user_data_t *);
-typedef int (*plugin_flush_cb)(cdtime_t timeout, const char *identifier,
- user_data_t *);
-/* "missing" callback. Returns less than zero on failure, zero if other
- * callbacks should be called, greater than zero if no more callbacks should be
- * called. */
-typedef int (*plugin_missing_cb)(const value_list_t *, user_data_t *);
-/* "cache event" callback. CE_VALUE_NEW events are sent to all registered
- * callbacks. Callback should check if it interested in further CE_VALUE_UPDATE
- * and CE_VALUE_EXPIRED events for metric and set event->ret = 1 if so.
- */
-typedef int (*plugin_cache_event_cb)(cache_event_t *, user_data_t *);
-typedef void (*plugin_log_cb)(int severity, const char *message, user_data_t *);
-typedef int (*plugin_shutdown_cb)(void);
-typedef int (*plugin_notification_cb)(const notification_t *, user_data_t *);
-/*
- * NAME
- * plugin_set_dir
- *
- * DESCRIPTION
- * Sets the current `plugindir'
- *
- * ARGUMENTS
- * `dir' Path to the plugin directory
- *
- * NOTES
- * If `dir' is NULL the compiled in default `PLUGINDIR' is used.
- */
-void plugin_set_dir(const char *dir);
-
-/*
- * NAME
- * plugin_load
- *
- * DESCRIPTION
- * Searches the current `plugindir' (see `plugin_set_dir') for the plugin
- * named $type and loads it. Afterwards the plugin's `module_register'
- * function is called, which then calls `plugin_register' to register callback
- * functions.
- *
- * ARGUMENTS
- * `name' Name of the plugin to load.
- * `global' Make this plugins symbols available for other shared libraries.
- *
- * RETURN VALUE
- * Returns zero upon success, a value greater than zero if no plugin was found
- * and a value below zero if an error occurs.
- *
- * NOTES
- * Re-loading an already loaded module is detected and zero is returned in
- * this case.
- */
-int plugin_load(const char *name, bool global);
-bool plugin_is_loaded(char const *name);
-
-int plugin_init_all(void);
-void plugin_read_all(void);
-int plugin_read_all_once(void);
-int plugin_shutdown_all(void);
-
-/*
- * NAME
- * plugin_write
- *
- * DESCRIPTION
- * Calls the write function of the given plugin with the provided data set and
- * value list. It differs from `plugin_dispatch_values' in that it does not
- * update the cache, does not do threshold checking, call the chain subsystem
- * and so on. It looks up the requested plugin and invokes the function, end
- * of story.
- *
- * ARGUMENTS
- * plugin Name of the plugin. If NULL, the value is sent to all registered
- * write functions.
- * ds Pointer to the data_set_t structure. If NULL, the data set is
- * looked up according to the `type' member in the `vl' argument.
- * vl The actual value to be processed. Must not be NULL.
- *
- * RETURN VALUE
- * Returns zero upon success or non-zero if an error occurred. If `plugin' is
- * NULL and more than one plugin is called, an error is only returned if *all*
- * plugins fail.
- *
- * NOTES
- * This is the function used by the `write' built-in target. May be used by
- * other target plugins.
- */
-int plugin_write(const char *plugin, const data_set_t *ds,
- const value_list_t *vl);
-
-int plugin_flush(const char *plugin, cdtime_t timeout, const char *identifier);
-
-/*
- * The `plugin_register_*' functions are used to make `config', `init',
- * `read', `write' and `shutdown' functions known to the plugin
- * infrastructure. Also, the data-formats are made public like this.
- */
-int plugin_register_config(const char *name,
- int (*callback)(const char *key, const char *val),
- const char **keys, int keys_num);
-int plugin_register_complex_config(const char *type,
- int (*callback)(oconfig_item_t *));
-int plugin_register_init(const char *name, plugin_init_cb callback);
-int plugin_register_read(const char *name, int (*callback)(void));
-/* "user_data" will be freed automatically, unless
- * "plugin_register_complex_read" returns an error (non-zero). */
-int plugin_register_complex_read(const char *group, const char *name,
- plugin_read_cb callback, cdtime_t interval,
- user_data_t const *user_data);
-int plugin_register_write(const char *name, plugin_write_cb callback,
- user_data_t const *user_data);
-int plugin_register_flush(const char *name, plugin_flush_cb callback,
- user_data_t const *user_data);
-int plugin_register_missing(const char *name, plugin_missing_cb callback,
- user_data_t const *user_data);
-int plugin_register_cache_event(const char *name,
- plugin_cache_event_cb callback,
- user_data_t const *ud);
-int plugin_register_shutdown(const char *name, plugin_shutdown_cb callback);
-int plugin_register_data_set(const data_set_t *ds);
-int plugin_register_log(const char *name, plugin_log_cb callback,
- user_data_t const *user_data);
-int plugin_register_notification(const char *name,
- plugin_notification_cb callback,
- user_data_t const *user_data);
-
-int plugin_unregister_config(const char *name);
-int plugin_unregister_complex_config(const char *name);
-int plugin_unregister_init(const char *name);
-int plugin_unregister_read(const char *name);
-int plugin_unregister_read_group(const char *group);
-int plugin_unregister_write(const char *name);
-int plugin_unregister_flush(const char *name);
-int plugin_unregister_missing(const char *name);
-int plugin_unregister_cache_event(const char *name);
-int plugin_unregister_shutdown(const char *name);
-int plugin_unregister_data_set(const char *name);
-int plugin_unregister_log(const char *name);
-int plugin_unregister_notification(const char *name);
-
-/*
- * NAME
- * plugin_log_available_writers
- *
- * DESCRIPTION
- * This function can be called to output a list of _all_ registered
- * writers to the logfacility.
- * Since some writers dynamically build their name it can be hard for
- * the configuring person to know it. This function will fill this gap.
- */
-void plugin_log_available_writers(void);
-
-/*
- * NAME
- * plugin_dispatch_values
- *
- * DESCRIPTION
- * This function is called by reading processes with the values they've
- * aquired. The function fetches the data-set definition (that has been
- * registered using `plugin_register_data_set') and calls _all_ registered
- * write-functions.
- *
- * ARGUMENTS
- * `vl' Value list of the values that have been read by a `read'
- * function.
- */
-int plugin_dispatch_values(value_list_t const *vl);
-
-/*
- * NAME
- * plugin_dispatch_multivalue
- *
- * SYNOPSIS
- * plugin_dispatch_multivalue (vl, true, DS_TYPE_GAUGE,
- * "free", 42.0,
- * "used", 58.0,
- * NULL);
- *
- * DESCRIPTION
- * Takes a list of type instances and values and dispatches that in a batch,
- * making sure that all values have the same time stamp. If "store_percentage"
- * is set to true, the "type" is set to "percent" and a percentage is
- * calculated and dispatched, rather than the absolute values. Values that are
- * NaN are dispatched as NaN and will not influence the total.
- *
- * The variadic arguments is a list of type_instance / type pairs, that are
- * interpreted as type "char const *" and type, encoded by their corresponding
- * "store_type":
- *
- * - "gauge_t" when "DS_TYPE_GAUGE"
- * - "absolute_t" when "DS_TYPE_ABSOLUTE"
- * - "derive_t" when "DS_TYPE_DERIVE"
- * - "counter_t" when "DS_TYPE_COUNTER"
- *
- * The last argument must be
- * a NULL pointer to signal end-of-list.
- *
- * RETURNS
- * The number of values it failed to dispatch (zero on success).
- */
-__attribute__((sentinel)) int plugin_dispatch_multivalue(value_list_t const *vl,
- bool store_percentage,
- int store_type, ...);
-
-int plugin_dispatch_missing(const value_list_t *vl);
-void plugin_dispatch_cache_event(enum cache_event_type_e event_type,
- unsigned long callbacks_mask, const char *name,
- const value_list_t *vl);
-
-int plugin_dispatch_notification(const notification_t *notif);
-
-void plugin_log(int level, const char *format, ...)
- __attribute__((format(printf, 2, 3)));
-
-/* These functions return the parsed severity or less than zero on failure. */
-int parse_log_severity(const char *severity);
-int parse_notif_severity(const char *severity);
-
-#define ERROR(...) plugin_log(LOG_ERR, __VA_ARGS__)
-#define WARNING(...) plugin_log(LOG_WARNING, __VA_ARGS__)
-#define NOTICE(...) plugin_log(LOG_NOTICE, __VA_ARGS__)
-#define INFO(...) plugin_log(LOG_INFO, __VA_ARGS__)
-#if COLLECT_DEBUG
-#define DEBUG(...) plugin_log(LOG_DEBUG, __VA_ARGS__)
-#else /* COLLECT_DEBUG */
-#define DEBUG(...) /* noop */
-#endif /* ! COLLECT_DEBUG */
-
-/* This will log messages, prefixed by plugin name */
-void daemon_log(int level, const char *format, ...)
- __attribute__((format(printf, 2, 3)));
-
-#define P_ERROR(...) daemon_log(LOG_ERR, __VA_ARGS__)
-#define P_WARNING(...) daemon_log(LOG_WARNING, __VA_ARGS__)
-#define P_NOTICE(...) daemon_log(LOG_NOTICE, __VA_ARGS__)
-#define P_INFO(...) daemon_log(LOG_INFO, __VA_ARGS__)
-
-const data_set_t *plugin_get_ds(const char *name);
-
-int plugin_notification_meta_add_string(notification_t *n, const char *name,
- const char *value);
-int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
- int64_t value);
-int plugin_notification_meta_add_unsigned_int(notification_t *n,
- const char *name, uint64_t value);
-int plugin_notification_meta_add_double(notification_t *n, const char *name,
- double value);
-int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
- bool value);
-
-int plugin_notification_meta_copy(notification_t *dst,
- const notification_t *src);
-
-int plugin_notification_meta_free(notification_meta_t *n);
-
-/*
- * Plugin context management.
- */
-
-void plugin_init_ctx(void);
-
-plugin_ctx_t plugin_get_ctx(void);
-plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx);
-
-/*
- * NAME
- * plugin_get_interval
- *
- * DESCRIPTION
- * This function returns the current value of the plugin's interval. The
- * return value will be strictly greater than zero in all cases. If
- * everything else fails, it will fall back to 10 seconds.
- */
-cdtime_t plugin_get_interval(void);
-
-/*
- * Context-aware thread management.
- */
-
-int plugin_thread_create(pthread_t *thread, void *(*start_routine)(void *),
- void *arg, char const *name);
-
-/*
- * Plugins need to implement this
- */
-
-void module_register(void);
-
-#endif /* PLUGIN_H */
diff --git a/telemetry/vpp-collectd/vpp-hicn/CMakeLists.txt b/telemetry/vpp-collectd/vpp-hicn/CMakeLists.txt
index 9db20be38..85dd51577 100644
--- a/telemetry/vpp-collectd/vpp-hicn/CMakeLists.txt
+++ b/telemetry/vpp-collectd/vpp-hicn/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,45 +11,63 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
-
+##############################################################
# Dependencies
-find_package(Collectd REQUIRED)
-find_package(Vpp REQUIRED)
-
-if(${CMAKE_SOURCE_DIR}/vpp-collectd STREQUAL ${PROJECT_SOURCE_DIR})
- message (STATUS "not compiling in the same folder")
- find_package(HicnPlugin REQUIRED)
- find_package(VapiSafe REQUIRED)
-else()
- message (STATUS "compiling in the same folder")
- list(APPEND DEPENDENCIES
- hicn_plugin
- )
-endif()
+##############################################################
+find_package(HicnPlugin ${CURRENT_VERSION} REQUIRED)
+find_package(Libsafevapi ${CURRENT_VERSION} REQUIRED NO_MODULE)
+
+##############################################################
+# Source files
+##############################################################
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/vpp_hicn.c)
+ ${CMAKE_CURRENT_SOURCE_DIR}/vpp_hicn.c
+)
+
+##############################################################
+# Include dirs
+##############################################################
list(APPEND INCLUDE_DIRS
- ${COLLECTD_INCLUDE_DIRS}
- ${HICNPLUGIN_INCLUDE_DIRS}
- ${SAFE_VAPI_INCLUDE_DIRS}
- ${VPP_INCLUDE_DIRS}
- ${CMAKE_CURRENT_SOURCE_DIR}
- "${CMAKE_CURRENT_SOURCE_DIR}/../common")
+ ${COLLECTD_INCLUDE_DIRS}
+ ${THIRD_PARTY_INCLUDE_DIRS}
+ ${HICNPLUGIN_INCLUDE_DIRS}
+ ${Libsafe_vapi_INCLUDE_DIRS}
+ ${VPP_INCLUDE_DIRS}
+)
+
+##############################################################
+# Libraries
+##############################################################
list(APPEND LIBRARIES
- ${VPP_LIBRARY_VAPICLIENT}
- ${SAFE_VAPI_LIBRARIES})
-
-build_library(vpp_hicn
- SHARED
- SOURCES ${SOURCE_FILES}
- LINK_LIBRARIES ${LIBRARIES}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- INSTALL_FULL_PATH_DIR ${CMAKE_INSTALL_PREFIX}/lib/collectd
- COMPONENT "${COLLECTD_PLUGINS}"
- DEPENDS ${DEPENDENCIES}
- EMPTY_PREFIX true
- )
+ ${VPP_LIBRARY_VAPICLIENT}
+ hicn::safevapi.shared
+)
+
+
+##############################################################
+# Compiler options
+##############################################################
+list(APPEND COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ ${COLLECTD_COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Build library
+##############################################################
+build_library(${VPP_HICN_TELEMETRY}
+ SHARED
+ EMPTY_PREFIX
+ SOURCES ${SOURCE_FILES}
+ LINK_LIBRARIES ${LIBRARIES}
+ INCLUDE_DIRS
+ PRIVATE ${INCLUDE_DIRS}
+ INSTALL_FULL_PATH_DIR ${COLLECTD_PLUGIN_DIR}
+ COMPONENT ${COLLECTD_PLUGINS}
+ DEPENDS ${DEPENDENCIES}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
diff --git a/telemetry/vpp-collectd/vpp-hicn/vpp_hicn.c b/telemetry/vpp-collectd/vpp-hicn/vpp_hicn.c
index b6bc3af49..a20bcbcd0 100644
--- a/telemetry/vpp-collectd/vpp-hicn/vpp_hicn.c
+++ b/telemetry/vpp-collectd/vpp-hicn/vpp_hicn.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,13 +13,14 @@
* limitations under the License.
*/
-/* Keep order as it is */
-#include <config.h>
-#include "common.h"
+#include "../../data_model.h"
+#include "collectd.h"
+#include "plugin.h"
+#include "utils/common/common.h"
#define counter_t vpp_counter_t
+#include <hicn/vapi/vapi_safe.h>
#include <vapi/hicn.api.vapi.h>
-#include <vapi/vapi_safe.h>
#undef counter_t
DEFINE_VAPI_MSG_IDS_HICN_API_JSON
@@ -34,140 +35,6 @@ static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
static bool verbose = false;
static char *tag = NULL;
-/************** DATA SOURCES ******************************/
-static data_source_t packets_dsrc[1] = {
- {"packets", DS_TYPE_GAUGE, 0, NAN},
-};
-
-static data_source_t interests_dsrc[1] = {
- {"interests", DS_TYPE_GAUGE, 0, NAN},
-};
-
-static data_source_t data_dsrc[1] = {
- {"data", DS_TYPE_GAUGE, 0, NAN},
-};
-
-static data_source_t combined_dsrc[2] = {
- {"packets", DS_TYPE_DERIVE, 0, NAN},
- {"bytes", DS_TYPE_DERIVE, 0, NAN},
-};
-
-/************** DATA SETS NODE ****************************/
-static data_set_t pkts_processed_ds = {
- "pkts_processed",
- STATIC_ARRAY_SIZE(packets_dsrc),
- packets_dsrc,
-};
-
-static data_set_t pkts_interest_count_ds = {
- "pkts_interest_count",
- STATIC_ARRAY_SIZE(packets_dsrc),
- packets_dsrc,
-};
-
-static data_set_t pkts_data_count_ds = {
- "pkts_data_count",
- STATIC_ARRAY_SIZE(packets_dsrc),
- packets_dsrc,
-};
-
-static data_set_t pkts_from_cache_count_ds = {
- "pkts_from_cache_count",
- STATIC_ARRAY_SIZE(packets_dsrc),
- packets_dsrc,
-};
-
-static data_set_t pkts_no_pit_count_ds = {
- "pkts_no_pit_count",
- STATIC_ARRAY_SIZE(packets_dsrc),
- packets_dsrc,
-};
-
-static data_set_t pit_expired_count_ds = {
- "pit_expired_count",
- STATIC_ARRAY_SIZE(interests_dsrc),
- interests_dsrc,
-};
-
-static data_set_t cs_expired_count_ds = {
- "cs_expired_count",
- STATIC_ARRAY_SIZE(data_dsrc),
- data_dsrc,
-};
-
-static data_set_t cs_lru_count_ds = {
- "cs_lru_count",
- STATIC_ARRAY_SIZE(data_dsrc),
- data_dsrc,
-};
-
-static data_set_t pkts_drop_no_buf_ds = {
- "pkts_drop_no_buf",
- STATIC_ARRAY_SIZE(packets_dsrc),
- packets_dsrc,
-};
-
-static data_set_t interests_aggregated_ds = {
- "interests_aggregated",
- STATIC_ARRAY_SIZE(interests_dsrc),
- interests_dsrc,
-};
-
-static data_set_t interests_retx_ds = {
- "interests_retx",
- STATIC_ARRAY_SIZE(interests_dsrc),
- interests_dsrc,
-};
-
-static data_set_t interests_hash_collision_ds = {
- "interests_hash_collision",
- STATIC_ARRAY_SIZE(interests_dsrc),
- interests_dsrc,
-};
-
-static data_set_t pit_entries_count_ds = {
- "pit_entries_count",
- STATIC_ARRAY_SIZE(interests_dsrc),
- interests_dsrc,
-};
-
-static data_set_t cs_entries_count_ds = {
- "cs_entries_count",
- STATIC_ARRAY_SIZE(data_dsrc),
- data_dsrc,
-};
-
-static data_set_t cs_entries_ntw_count_ds = {
- "cs_entries_ntw_count",
- STATIC_ARRAY_SIZE(data_dsrc),
- data_dsrc,
-};
-
-/************** DATA SETS FACE ****************************/
-static data_set_t irx_ds = {
- "irx",
- STATIC_ARRAY_SIZE(combined_dsrc),
- combined_dsrc,
-};
-
-static data_set_t itx_ds = {
- "itx",
- STATIC_ARRAY_SIZE(combined_dsrc),
- combined_dsrc,
-};
-
-static data_set_t drx_ds = {
- "drx",
- STATIC_ARRAY_SIZE(combined_dsrc),
- combined_dsrc,
-};
-
-static data_set_t dtx_ds = {
- "dtx",
- STATIC_ARRAY_SIZE(combined_dsrc),
- combined_dsrc,
-};
-
/**********************************************************/
/********** UTILITY FUNCTIONS *****************************/
/**********************************************************/
@@ -189,8 +56,7 @@ static int submit(const char *plugin_instance, const char *type,
sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
sstrncpy(vl.type, type, sizeof(vl.type));
- if (tag != NULL)
- sstrncpy(vl.type_instance, tag, sizeof(vl.type_instance));
+ if (tag != NULL) sstrncpy(vl.type_instance, tag, sizeof(vl.type_instance));
return plugin_dispatch_values(&vl);
}
@@ -223,15 +89,12 @@ static int vpp_hicn_config(const char *key, const char *value) {
/*
* Callback called by the hICN plugin API when node stats are ready.
*/
-static vapi_error_e
-parse_node_stats(vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_node_stats_get_reply *reply) {
- if (reply == NULL || rv != VAPI_OK)
- return rv;
+static vapi_error_e parse_node_stats(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_hicn_api_node_stats_get_reply *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
- if (reply->retval != VAPI_OK)
- return reply->retval;
+ if (reply->retval != VAPI_OK) return reply->retval;
char *node_name = "node";
value_t values[1];
@@ -277,15 +140,12 @@ parse_node_stats(vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv,
/*
* Callback called by the hICN plugin API when face stats are ready.
*/
-static vapi_error_e
-parse_face_stats(vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv,
- bool is_last,
- vapi_payload_hicn_api_face_stats_details *reply) {
- if (reply == NULL || rv != VAPI_OK)
- return rv;
+static vapi_error_e parse_face_stats(
+ vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv, bool is_last,
+ vapi_payload_hicn_api_face_stats_details *reply) {
+ if (reply == NULL || rv != VAPI_OK) return rv;
- if (reply->retval != VAPI_OK)
- return reply->retval;
+ if (reply->retval != VAPI_OK) return reply->retval;
char face_name[10];
snprintf(face_name, 10, "face%u", reply->faceid);
@@ -314,8 +174,7 @@ parse_face_stats(vapi_ctx_t ctx, void *callback_ctx, vapi_error_e rv,
static int vpp_hicn_init(void) {
int ret = vapi_connect_safe(&vapi_ctx, 0);
- if (ret)
- plugin_log(LOG_ERR, "vpp_hicn plugin: vapi_connect_safe failed");
+ if (ret) plugin_log(LOG_ERR, "vpp_hicn plugin: vapi_connect_safe failed");
return ret;
}
diff --git a/telemetry/vpp-collectd/vpp/CMakeLists.txt b/telemetry/vpp-collectd/vpp/CMakeLists.txt
index c36787355..e1cf55553 100644
--- a/telemetry/vpp-collectd/vpp/CMakeLists.txt
+++ b/telemetry/vpp-collectd/vpp/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2020 Cisco and/or its affiliates.
+# Copyright (c) 2021-2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,29 +11,53 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# Dependencies
-find_package(Vpp REQUIRED)
-find_package(Collectd REQUIRED)
-
+##############################################################
+# Sources
+##############################################################
list(APPEND SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/vpp.c)
+ ${CMAKE_CURRENT_SOURCE_DIR}/vpp.c
+)
+
+##############################################################
+# Include dirs
+##############################################################
list(APPEND INCLUDE_DIRS
- ${COLLECTD_INCLUDE_DIRS}
- ${VPP_INCLUDE_DIRS}
- ${CMAKE_CURRENT_SOURCE_DIR}
- "${CMAKE_CURRENT_SOURCE_DIR}/../common")
+ ${COLLECTD_INCLUDE_DIRS}
+ ${THIRD_PARTY_INCLUDE_DIRS}
+ ${VPP_INCLUDE_DIRS}
+)
+
+##############################################################
+# Libraries
+##############################################################
list(APPEND LIBRARIES
- ${VPP_LIBRARY_VPPAPICLIENT}
- ${VPP_LIBRARY_INFRA})
-
-build_library(vpp
- SHARED
- SOURCES ${SOURCE_FILES}
- LINK_LIBRARIES ${LIBRARIES}
- INCLUDE_DIRS ${INCLUDE_DIRS}
- INSTALL_FULL_PATH_DIR ${CMAKE_INSTALL_PREFIX}/lib/collectd
- COMPONENT ${COLLECTD_PLUGINS}
- EMPTY_PREFIX true
- )
+ ${VPP_LIBRARY_VPPAPICLIENT}
+ ${VPP_LIBRARY_INFRA}
+)
+
+
+##############################################################
+# Compiler options
+##############################################################
+list(APPEND COMPILER_OPTIONS
+ ${DEFAULT_COMPILER_OPTIONS}
+ ${COLLECTD_COMPILER_OPTIONS}
+)
+
+
+##############################################################
+# Build library
+##############################################################
+build_library(${VPP_TELEMETRY}
+ SHARED
+ EMPTY_PREFIX
+ SOURCES ${SOURCE_FILES}
+ LINK_LIBRARIES ${LIBRARIES}
+ INCLUDE_DIRS
+ PRIVATE ${INCLUDE_DIRS}
+ INSTALL_FULL_PATH_DIR ${COLLECTD_PLUGIN_DIR}
+ COMPONENT ${COLLECTD_PLUGINS}
+ COMPILE_OPTIONS ${COMPILER_OPTIONS}
+)
diff --git a/telemetry/vpp-collectd/vpp/vpp.c b/telemetry/vpp-collectd/vpp/vpp.c
index dcf956c93..ff70f3503 100644
--- a/telemetry/vpp-collectd/vpp/vpp.c
+++ b/telemetry/vpp-collectd/vpp/vpp.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020 Cisco and/or its affiliates.
+ * Copyright (c) 2021 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
@@ -13,9 +13,9 @@
* limitations under the License.
*/
-/* Keep order as it is */
-#include <config.h>
-#include "common.h"
+#include "collectd.h"
+#include "plugin.h"
+#include "utils/common/common.h"
#define counter_t vpp_counter_t
#include <vpp-api/client/stat_client.h>
@@ -165,8 +165,7 @@ static int submit(const char *plugin_instance, const char *type,
sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
sstrncpy(vl.type, type, sizeof(vl.type));
- if (tag != NULL)
- sstrncpy(vl.type_instance, tag, sizeof(vl.type_instance));
+ if (tag != NULL) sstrncpy(vl.type_instance, tag, sizeof(vl.type_instance));
return plugin_dispatch_values(&vl);
}
@@ -261,8 +260,7 @@ static int vpp_init(void) {
u8 *stat_segment_name = (u8 *)STAT_SEGMENT_SOCKET_FILE;
int ret = stat_segment_connect((char *)stat_segment_name);
- if (ret)
- plugin_log(LOG_ERR, "vpp plugin: connecting to segment failed");
+ if (ret) plugin_log(LOG_ERR, "vpp plugin: connecting to segment failed");
return ret;
}
@@ -296,66 +294,65 @@ static int vpp_read(void) {
/* Collect results for each interface and submit them */
for (int i = 0; i < vec_len(res); i++) {
switch (res[i].type) {
- case STAT_DIR_TYPE_COUNTER_VECTOR_SIMPLE:
- for (int k = 0; k < vec_len(res[i].simple_counter_vec); k++) {
- for (int j = 0; j < vec_len(res[i].simple_counter_vec[k]); j++) {
- if (!interfaces[j]) {
- continue;
- }
+ case STAT_DIR_TYPE_COUNTER_VECTOR_SIMPLE:
+ for (int k = 0; k < vec_len(res[i].simple_counter_vec); k++) {
+ for (int j = 0; j < vec_len(res[i].simple_counter_vec[k]); j++) {
+ if (!interfaces[j]) {
+ continue;
+ }
- if (get_data_set(res[i].name, &data_set)) {
- continue;
- }
+ if (get_data_set(res[i].name, &data_set)) {
+ continue;
+ }
- value_t values[1] = {
- (value_t){.derive = res[i].simple_counter_vec[k][j]}};
+ value_t values[1] = {
+ (value_t){.derive = res[i].simple_counter_vec[k][j]}};
- err = submit(interfaces[j], data_set.type, values, 1, &timestamp);
+ err = submit(interfaces[j], data_set.type, values, 1, &timestamp);
- if (err)
- goto END;
+ if (err) goto END;
+ }
}
- }
- break;
+ break;
- case STAT_DIR_TYPE_COUNTER_VECTOR_COMBINED:
- for (int k = 0; k < vec_len(res[i].combined_counter_vec); k++) {
- for (int j = 0; j < vec_len(res[i].combined_counter_vec[k]); j++) {
- if (!interfaces[j]) {
- continue;
- }
+ case STAT_DIR_TYPE_COUNTER_VECTOR_COMBINED:
+ for (int k = 0; k < vec_len(res[i].combined_counter_vec); k++) {
+ for (int j = 0; j < vec_len(res[i].combined_counter_vec[k]); j++) {
+ if (!interfaces[j]) {
+ continue;
+ }
- if (get_data_set(res[i].name, &data_set)) {
- continue;
- }
+ if (get_data_set(res[i].name, &data_set)) {
+ continue;
+ }
- value_t values[2] = {
- (value_t){.derive = res[i].combined_counter_vec[k][j].packets},
- (value_t){.derive = res[i].combined_counter_vec[k][j].bytes},
- };
+ value_t values[2] = {
+ (value_t){.derive = res[i].combined_counter_vec[k][j].packets},
+ (value_t){.derive = res[i].combined_counter_vec[k][j].bytes},
+ };
- err = submit(interfaces[j], data_set.type, values, 2, &timestamp);
+ err = submit(interfaces[j], data_set.type, values, 2, &timestamp);
- if (err)
- goto END;
+ if (err) goto END;
+ }
}
- }
- break;
+ break;
- case STAT_DIR_TYPE_SCALAR_INDEX:
- plugin_log(LOG_INFO, "vpp plugin: %.2f %s", res[i].scalar_value,
- res[i].name);
- break;
+ case STAT_DIR_TYPE_SCALAR_INDEX:
+ plugin_log(LOG_INFO, "vpp plugin: %.2f %s", res[i].scalar_value,
+ res[i].name);
+ break;
- case STAT_DIR_TYPE_NAME_VECTOR:
- break;
+ case STAT_DIR_TYPE_NAME_VECTOR:
+ break;
- case STAT_DIR_TYPE_ERROR_INDEX:
- break;
+ case STAT_DIR_TYPE_ERROR_INDEX:
+ break;
- default:
- plugin_log(LOG_WARNING, "vpp plugin: unknown stat type %d", res[i].type);
- break;
+ default:
+ plugin_log(LOG_WARNING, "vpp plugin: unknown stat type %d",
+ res[i].type);
+ break;
}
}
diff --git a/tests/.env b/tests/.env
new file mode 100644
index 000000000..1e06ca0c8
--- /dev/null
+++ b/tests/.env
@@ -0,0 +1,36 @@
+# Topologies
+TOPOLOGY_1_NODE=1-node
+TOPOLOGY_2_NODES=2-nodes
+
+# Container names
+TEST_LIGHT=hicn-light
+TEST_VPP_BRIDGE=vpp-bridge
+TEST_VPP_MEMIF=vpp-memif
+TEST_VPP_MEMIF_REPLICATION=vpp-memif-replication
+TEST_VPP_MEMIF_LOCALREMOTE=vpp-memif-local-remote
+
+# Names
+RTC_PRODUCER=b002:0:0:0:abcd::/80
+RAAQM_PRODUCER=b002::2
+PING_PRODUCER=b002::3
+RAAQM_PRODUCER_NEW=b002::4
+
+# Test keys
+HMAC_KEY="hunter2"
+
+# Log
+FORWARDER_LOG_PATH=/tmp/forwarder.log
+
+# IP addresses
+TOPOLOGY_2_NODES_IP_NETWORK=192.168.1.0/24
+TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT=192.168.1.2
+TOPOLOGY_2_NODES_IP_ADDRESS_SERVER=192.168.1.3
+TOPOLOGY_2_NODES_IP_GATEWAY=192.168.1.254
+
+TOPOLOGY_2_NODES_IP6_NETWORK=2001::/64
+TOPOLOGY_2_NODES_IP6_ADDRESS_CLIENT=2001::1
+TOPOLOGY_2_NODES_IP6_ADDRESS_SERVER=2001::2
+
+TOPOLOGY_1_NODE_IP_NETWORK=192.168.2.0/24
+TOPOLOGY_1_NODE_IP_ADDRESS=192.168.2.2
+TOPOLOGY_1_NODE_IP_GATEWAY=192.168.2.254
diff --git a/tests/1-node.yml b/tests/1-node.yml
new file mode 100644
index 000000000..9e496d7b8
--- /dev/null
+++ b/tests/1-node.yml
@@ -0,0 +1,32 @@
+version: "3"
+services:
+ client:
+ build:
+ context: ..
+ dockerfile: ${DOCKERFILE}
+ args:
+ - BASE_IMAGE
+ image: hicn-base
+ container_name: forwarder
+ working_dir: /workspace
+ volumes:
+ - ..:/workspace:z
+ networks:
+ the-network:
+ ipv4_address: ${TOPOLOGY_1_NODE_IP_ADDRESS}
+ entrypoint: [/bin/bash, -ex, -c]
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo hicn-light-daemon --log-file /tmp/lite_client.log
+
+networks:
+ the-network:
+ driver: bridge
+ ipam:
+ config:
+ - subnet: ${TOPOLOGY_1_NODE_IP_NETWORK}
+ gateway: ${TOPOLOGY_1_NODE_IP_GATEWAY}
diff --git a/tests/2-nodes-hicn-light.yml b/tests/2-nodes-hicn-light.yml
new file mode 100644
index 000000000..849432464
--- /dev/null
+++ b/tests/2-nodes-hicn-light.yml
@@ -0,0 +1,53 @@
+version: "3"
+services:
+ client:
+ container_name: ${TEST_LIGHT}-client
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ tee -a /tmp/hicn-light.conf <<EOF
+ add listener udp local0 ${TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT} 9199 eth0
+ add connection udp conn0 ${TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT} 9199 ${TOPOLOGY_2_NODES_IP_ADDRESS_SERVER} 9199
+ add route conn0 b002::/64 1
+ EOF
+
+ rm -f ${FORWARDER_LOG_PATH}
+
+ sudo hicn-light-daemon \
+ --daemon \
+ --log-file ${FORWARDER_LOG_PATH} \
+ --config /tmp/hicn-light.conf
+
+ tail -f /dev/null
+
+ server:
+ container_name: ${TEST_LIGHT}-server
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ tee -a /tmp/hicn-light.conf <<EOF
+ add listener udp local0 ${TOPOLOGY_2_NODES_IP_ADDRESS_SERVER} 9199 eth0
+ add connection udp conn0 ${TOPOLOGY_2_NODES_IP_ADDRESS_SERVER} 9199 ${TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT} 9199
+ EOF
+
+ rm -f ${FORWARDER_LOG_PATH}
+
+ sudo hicn-light-daemon \
+ --daemon \
+ --log-file ${FORWARDER_LOG_PATH} \
+ --config /tmp/hicn-light.conf --capacity 0
+
+ sleep 4
+
+ hiperf -q -z hicnlight_module -S -R -B 4000kbps ${RTC_PRODUCER} -P 2 -k ${HMAC_KEY} &
+ hiperf -q -z hicnlight_module -S ${RAAQM_PRODUCER}/128 &
+ hiperf -q -z hicnlight_module -S ${RAAQM_PRODUCER_NEW}/128 &
+ hicn-ping-server -z hicnlight_module -s 0 -n ${PING_PRODUCER}/128 &
+
+ tail -f /dev/null
diff --git a/tests/2-nodes-vpp-bridge.yml b/tests/2-nodes-vpp-bridge.yml
new file mode 100644
index 000000000..e9d0cf809
--- /dev/null
+++ b/tests/2-nodes-vpp-bridge.yml
@@ -0,0 +1,114 @@
+version: "3"
+services:
+ client:
+ container_name: ${TEST_VPP_BRIDGE}-client
+ cap_add:
+ - NET_ADMIN
+ devices:
+ - /dev/net/tun:/dev/net/tun
+ - /dev/vhost-net:/dev/vhost-net
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo ip link add br0 type bridge
+ sudo ip link set br0 up
+ sudo ip link set eth0 master br0
+ sudo ip addr del ${TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT}/24 dev eth0
+
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 1 }
+ plugins {
+ path /usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+ unix {
+ startup-config /etc/vpp/client-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+
+ EOF
+
+ sudo tee /etc/vpp/client-up.txt <<EOF
+ create tap id 0 host-bridge br0
+ set int state tap0 up
+ set int ip addr tap0 ${TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT}/24
+ set int ip addr tap0 ${TOPOLOGY_2_NODES_IP6_ADDRESS_CLIENT}/64
+ ip route add b002::1/64 via ${TOPOLOGY_2_NODES_IP6_ADDRESS_SERVER} tap0
+ EOF
+
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 5
+ sudo vppctl hicn enable b002::1/64
+
+ tail -f /dev/null
+
+ server:
+ container_name: ${TEST_VPP_BRIDGE}-server
+ cap_add:
+ - NET_ADMIN
+ devices:
+ - /dev/net/tun:/dev/net/tun
+ - /dev/vhost-net:/dev/vhost-net
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo ip link add br0 type bridge
+ sudo ip link set br0 up
+ sudo ip link set eth0 master br0
+ sudo ip addr del ${TOPOLOGY_2_NODES_IP_ADDRESS_SERVER}/24 dev eth0
+
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 2 }
+ plugins {
+ path /usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+ unix {
+ startup-config /etc/vpp/server-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+ EOF
+
+ sudo tee /etc/vpp/server-up.txt <<EOF
+ create tap id 0 host-bridge br0
+ set int state tap0 up
+ set int ip addr tap0 ${TOPOLOGY_2_NODES_IP_ADDRESS_SERVER}/24
+ set int ip addr tap0 ${TOPOLOGY_2_NODES_IP6_ADDRESS_SERVER}/64
+ EOF
+
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 5
+
+ sudo hiperf -q -S -R -B 4000kbps -z memif_module ${RTC_PRODUCER} -P 2 -k ${HMAC_KEY} &
+ sleep 1
+ sudo hiperf -q -S -z memif_module ${RAAQM_PRODUCER}/128 &
+ sleep 1
+ sudo hicn-ping-server -s 0 -n ${PING_PRODUCER}/128 -z memif_module &
+
+ tail -f /dev/null
diff --git a/tests/2-nodes-vpp-memif-local-remote.yml b/tests/2-nodes-vpp-memif-local-remote.yml
new file mode 100644
index 000000000..90f4b9ebc
--- /dev/null
+++ b/tests/2-nodes-vpp-memif-local-remote.yml
@@ -0,0 +1,116 @@
+version: "3"
+version: "3"
+services:
+ client:
+ container_name: ${TEST_VPP_MEMIF}-client
+ networks: []
+ volumes:
+ - /tmp/memif:/memif:z
+ - ..:/workspace:z
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo mkdir -p /var/log/vpp
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 1 }
+ buffers { buffers-per-numa 600000 }
+ plugins {
+ path /usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+
+ unix {
+ startup-config /etc/vpp/client-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+ EOF
+
+ sudo tee /etc/vpp/client-up.txt <<EOF
+ comment { Creating memif }
+ create memif socket id 1 filename /memif/memif1.sock
+ create interface memif id 0 socket-id 1 mode ip master
+ set int state memif1/0 up
+ comment { Configuring memif }
+ set int ip addr memif1/0 ${TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT}/24
+ set int ip addr memif1/0 ${TOPOLOGY_2_NODES_IP6_ADDRESS_CLIENT}/64
+ comment { Add route }
+ ip route add ${RAAQM_PRODUCER}/128 via ${TOPOLOGY_2_NODES_IP6_ADDRESS_SERVER} memif1/0
+ EOF
+
+ sudo rm /memif/memif1.sock
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 5
+
+ sudo hiperf -q -S -z memif_module ${RAAQM_PRODUCER}/128 &
+ sleep 1
+
+ sudo vppctl hicn strategy set 3 prefix ${RAAQM_PRODUCER}/128
+
+ tail -f /dev/null
+
+ server:
+ container_name: ${TEST_VPP_MEMIF}-server
+ networks: []
+ volumes:
+ - /tmp/memif:/memif:z
+ - ..:/workspace:z
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo mkdir -p /var/log/vpp
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 2 }
+ buffers { buffers-per-numa 600000 }
+
+ plugins {
+ path /usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+ unix {
+ startup-config /etc/vpp/server-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+ EOF
+
+ sudo tee /etc/vpp/server-up.txt <<EOF
+ comment { Creating memif }
+ create memif socket id 1 filename /memif/memif1.sock
+ create interface memif id 0 socket-id 1 mode ip slave
+ set int state memif1/0 up
+ comment { Configuring memif }
+ set int ip addr memif1/0 ${TOPOLOGY_2_NODES_IP_ADDRESS_SERVER}/24
+ set int ip addr memif1/0 ${TOPOLOGY_2_NODES_IP6_ADDRESS_SERVER}/64
+ EOF
+
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 5
+
+ sudo hiperf -q -S -z memif_module ${RAAQM_PRODUCER}/128 &
+
+ tail -f /dev/null
diff --git a/tests/2-nodes-vpp-memif-replication.yml b/tests/2-nodes-vpp-memif-replication.yml
new file mode 100644
index 000000000..f74757aac
--- /dev/null
+++ b/tests/2-nodes-vpp-memif-replication.yml
@@ -0,0 +1,124 @@
+version: "3"
+services:
+ client:
+ container_name: ${TEST_VPP_MEMIF_REPLICATION}-client
+ networks: []
+ volumes:
+ - /tmp/memif:/memif:z
+ - ..:/workspace:z
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo mkdir -p /var/log/vpp
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 1 }
+ buffers { buffers-per-numa 600000 }
+ plugins {
+ path /hicn-root/lib/vpp_plugins:/usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+ unix {
+ startup-config /etc/vpp/client-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+ EOF
+
+ sudo tee /etc/vpp/client-up.txt <<EOF
+ create memif socket id 1 filename /memif/memif1.sock
+ create interface memif id 0 socket-id 1 hw-addr aa:bb:cc:dd:ee:01 master
+ set int state memif1/0 up
+ set int ip addr memif1/0 192.168.1.1/24
+ set int ip addr memif1/0 2001::1/64
+ set ip neighbor memif1/0 2001::2 aa:bb:cc:dd:ee:02 static
+ ip route add b002::1/64 via 2001::2 memif1/0
+ create interface memif id 1 socket-id 1 hw-addr aa:bb:bb:bb:ee:01 master
+ set int state memif1/1 up
+ set int ip addr memif1/1 192.168.2.1/24
+ set int ip addr memif1/1 2002::1/64
+ set ip neighbor memif1/1 2002::2 aa:bb:bb:bb:ee:02 static
+ ip route add b002::1/64 via 2002::2 memif1/1
+ EOF
+
+ sudo rm /memif/memif1.sock
+
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 5
+
+ sudo vppctl hicn enable b002::1/64
+ sudo vppctl hicn strategy set 2 prefix b002::/64
+
+ tail -f /dev/null
+ server:
+ container_name: ${TEST_VPP_MEMIF_REPLICATION}-server
+ networks: []
+ volumes:
+ - /tmp/memif:/memif:z
+ - ..:/workspace:z
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo mkdir -p /var/log/vpp
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 2 }
+ buffers { buffers-per-numa 600000 }
+
+ plugins {
+ path /hicn-root/lib/vpp_plugins:/usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+ unix {
+ startup-config /etc/vpp/server-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+ EOF
+
+ sudo tee /etc/vpp/server-up.txt <<EOF
+ create memif socket id 1 filename /memif/memif1.sock
+ create interface memif id 0 socket-id 1 hw-addr aa:bb:cc:dd:ee:02 slave
+ set int state memif1/0 up
+ set int ip addr memif1/0 192.168.1.2/24
+ set int ip addr memif1/0 2001::2/64
+ set ip neighbor memif1/0 2001::1 aa:bb:cc:dd:ee:01 static
+ create interface memif id 1 socket-id 1 hw-addr aa:bb:bb:bb:ee:02 slave
+ set int state memif1/1 up
+ set int ip addr memif1/1 192.168.2.2/24
+ set int ip addr memif1/1 2002::2/64
+ set ip neighbor memif1/1 2002::1 aa:bb:bb:bb:ee:01 static
+ EOF
+
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 10
+
+ sudo hiperf -q -S -R -B 4000kbps -z memif_module ${RTC_PRODUCER} -P 2 -k ${HMAC_KEY} &
+ sleep 5
+ sudo hiperf -q -S -z memif_module ${RAAQM_PRODUCER}/128 &
+ sleep 5
+ sudo hicn-ping-server -s 0 -n ${PING_PRODUCER}/128 -z memif_module &
+
+ tail -f /dev/null
diff --git a/tests/2-nodes-vpp-memif.yml b/tests/2-nodes-vpp-memif.yml
new file mode 100644
index 000000000..7240f8b2c
--- /dev/null
+++ b/tests/2-nodes-vpp-memif.yml
@@ -0,0 +1,116 @@
+version: "3"
+services:
+ client:
+ container_name: ${TEST_VPP_MEMIF}-client
+ networks: []
+ volumes:
+ - /tmp/memif:/memif:z
+ - ..:/workspace:z
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo mkdir -p /var/log/vpp
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 1 }
+ buffers { buffers-per-numa 600000 }
+ plugins {
+ path /usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+
+ unix {
+ startup-config /etc/vpp/client-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+ EOF
+
+ sudo tee /etc/vpp/client-up.txt <<EOF
+ comment { Creating memif }
+ create memif socket id 1 filename /memif/memif1.sock
+ create interface memif id 0 socket-id 1 mode ip master
+ set int state memif1/0 up
+ comment { Configuring memif }
+ set int ip addr memif1/0 192.168.1.1/24
+ set int ip addr memif1/0 2001::1/64
+ comment { Add route }
+ ip route add b002::1/64 via 2001::2 memif1/0
+ EOF
+
+ sudo rm /memif/memif1.sock
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 5
+
+ sudo vppctl hicn enable b002::1/64
+
+ tail -f /dev/null
+
+ server:
+ container_name: ${TEST_VPP_MEMIF}-server
+ networks: []
+ volumes:
+ - /tmp/memif:/memif:z
+ - ..:/workspace:z
+ command:
+ - |
+ if [ -d /workspace/build-dev ]; then
+ sudo ninja -C /workspace/build-dev install
+ fi
+
+ sudo mkdir -p /var/log/vpp
+ sudo tee /etc/vpp/startup.conf <<EOF
+ cpu { main-core 2 }
+ buffers { buffers-per-numa 600000 }
+
+ plugins {
+ path /usr/lib/$$(arch)-linux-gnu/vpp_plugins:/usr/lib/vpp_plugins
+ plugin default { disable }
+ plugin acl_plugin.so { enable }
+ plugin nat_plugin.so { enable }
+ plugin dhcp_plugin.so { enable }
+ plugin dpdk_plugin.so { enable }
+ plugin dns_plugin.so { enable }
+ plugin ping_plugin.so { enable }
+ plugin memif_plugin.so { enable }
+ plugin nsim_plugin.so { enable }
+ plugin hicn_plugin.so { enable }
+ }
+ unix {
+ startup-config /etc/vpp/server-up.txt
+ cli-listen /run/vpp/cli.sock
+ log ${FORWARDER_LOG_PATH}
+ }
+ EOF
+
+ sudo tee /etc/vpp/server-up.txt <<EOF
+ comment { Creating memif }
+ create memif socket id 1 filename /memif/memif1.sock
+ create interface memif id 0 socket-id 1 mode ip slave
+ set int state memif1/0 up
+ comment { Configuring memif }
+ set int ip addr memif1/0 192.168.1.2/24
+ set int ip addr memif1/0 2001::2/64
+ EOF
+
+ sudo vpp -c /etc/vpp/startup.conf
+ sleep 10
+
+ sudo hiperf -q -S -R -B 4000kbps -z memif_module ${RTC_PRODUCER} -P 2 -k ${HMAC_KEY} &
+ sleep 5
+ sudo hiperf -q -S -z memif_module ${RAAQM_PRODUCER}/128 &
+ sleep 5
+ sudo hicn-ping-server -s 0 -n ${PING_PRODUCER}/128 -z memif_module &
+
+ tail -f /dev/null
diff --git a/tests/2-nodes.yml b/tests/2-nodes.yml
new file mode 100644
index 000000000..51b9aeb89
--- /dev/null
+++ b/tests/2-nodes.yml
@@ -0,0 +1,45 @@
+version: "3"
+services:
+ client:
+ build:
+ context: ..
+ dockerfile: ${DOCKERFILE}
+ args:
+ - BASE_IMAGE
+ hostname: client
+ privileged: false
+ working_dir: /workspace
+ networks:
+ p2p-link:
+ ipv4_address: ${TOPOLOGY_2_NODES_IP_ADDRESS_CLIENT}
+ volumes:
+ - ..:/workspace:z
+ entrypoint: [/bin/bash, -x, -c]
+ command:
+ - tail -f /dev/null
+
+ server:
+ build:
+ context: ..
+ dockerfile: ${DOCKERFILE}
+ args:
+ - BASE_IMAGE
+ hostname: server
+ privileged: false
+ working_dir: /workspace
+ networks:
+ p2p-link:
+ ipv4_address: ${TOPOLOGY_2_NODES_IP_ADDRESS_SERVER}
+ volumes:
+ - ..:/workspace:z
+ entrypoint: [/bin/bash, -x, -c]
+ command:
+ - tail -f /dev/null
+
+networks:
+ p2p-link:
+ driver: bridge
+ ipam:
+ config:
+ - subnet: ${TOPOLOGY_2_NODES_IP_NETWORK}
+ gateway: ${TOPOLOGY_2_NODES_IP_GATEWAY}
diff --git a/tests/Dockerfile.ci b/tests/Dockerfile.ci
new file mode 100644
index 000000000..b4c03f7e3
--- /dev/null
+++ b/tests/Dockerfile.ci
@@ -0,0 +1,40 @@
+FROM ubuntu:focal
+
+ARG DEBIAN_FRONTEND=noninteractive
+ARG DEB_FOLDER="./packages"
+
+WORKDIR /hicn-release
+
+################################################################
+# Copy DEB files
+################################################################
+COPY ${DEB_FOLDER} deb
+
+################################################################
+# Install VPP and hicn debs
+################################################################
+ARG VERSION_PATH=/tmp/versions.cmake
+COPY versions.cmake ${VERSION_PATH}
+ARG INSTALL_VPP_SCRIPT=/tmp/install-vpp.sh
+COPY scripts/install-vpp.sh ${INSTALL_VPP_SCRIPT}
+
+RUN bash -x ${INSTALL_VPP_SCRIPT} \
+ && cd deb \
+ && apt-get install -y \
+ iproute2 sudo \
+ ./libhicn_*.deb \
+ ./hicn-light_*.deb \
+ ./hicn-plugin_*.deb \
+ ./libhicnctrl_*.deb \
+ ./libhicnctrl-modules_*.deb \
+ ./libhicntransport-io-modules_*.deb \
+ ./libhicntransport_*.deb \
+ ./facemgr_*.deb \
+ ./hicn-apps_*.deb \
+ && rm ${VERSION_PATH} \
+ && rm -rf deb \
+ && rm -rf /var/lib/apt/lists/* \
+ && apt-get autoremove -y \
+ && apt-get clean
+
+WORKDIR /
diff --git a/tests/Makefile b/tests/Makefile
new file mode 100644
index 000000000..a31a6f1a6
--- /dev/null
+++ b/tests/Makefile
@@ -0,0 +1,42 @@
+# Use when building for the first time,
+# then `make test` forces a rebuild if local changes
+build:
+ DOCKERFILE=Dockerfile.dev BUILD_SOFTWARE=1 \
+ docker-compose -f build.yml up --force-recreate --remove-orphans
+
+# Rebuild from scratch (to avoid cmake cache)
+rebuild:
+ DOCKERFILE=Dockerfile.dev BUILD_SOFTWARE=1 \
+ REBUILD=1 \
+ docker-compose -f build.yml up --force-recreate --remove-orphans
+
+# Force base image creation from scratch
+rebase:
+ DOCKERFILE=Dockerfile.dev \
+ docker-compose -f build.yml build --pull --no-cache
+
+# If local changes, hicn is re-built
+test:
+ docker-compose -f 1-node.yml up --force-recreate --remove-orphans -d
+
+log:
+ docker exec forwarder tail -f -n +1 /tmp/lite_client.log
+
+shell:
+ docker exec -it forwarder bash
+
+down:
+ docker-compose -f 1-node.yml down
+
+functional-ctrl:
+ sleep 1 # Wait for the forwarder to be ready
+ bash config.sh ctrl listeners
+ bash config.sh ctrl connections
+ bash config.sh ctrl routes
+
+functional-ping-manifest:
+ bash config.sh ping manifest
+functional-ping-signature:
+ bash config.sh ping signature
+functional-ping-timeout:
+ bash config.sh ping timeout \ No newline at end of file
diff --git a/tests/build.yml b/tests/build.yml
new file mode 100644
index 000000000..859262632
--- /dev/null
+++ b/tests/build.yml
@@ -0,0 +1,41 @@
+version: "3"
+services:
+ dev:
+ build:
+ context: ..
+ dockerfile: ${DOCKERFILE}
+ image: hicn-base
+ stdin_open: true
+ tty: true
+ working_dir: /workspace
+ container_name: dev
+ hostname: dev
+ environment:
+ - BUILD_SOFTWARE
+ volumes:
+ - ..:/workspace:z
+ entrypoint: [/bin/bash, -ex, -c]
+ command:
+ - |
+ whoami
+
+ if [[ "${BUILD_SOFTWARE}" -ne 1 ]]; then
+ exit 0
+ fi
+
+ if [[ ! -z "${REBUILD}" ]]; then
+ rm -fr build-dev
+ fi
+
+ git config --global --add safe.directory \*
+
+ mkdir -p build-dev
+ cd build-dev
+ cmake -G Ninja \
+ -DCMAKE_INSTALL_PREFIX=/usr \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DBUILD_APPS=ON \
+ -DBUILD_TESTS=ON \
+ -DENABLE_RELY=OFF \
+ -DBUILD_HICNPLUGIN=ON ..
+ sudo ninja install
diff --git a/tests/channel.sh b/tests/channel.sh
new file mode 100755
index 000000000..59335da65
--- /dev/null
+++ b/tests/channel.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+
+set -e
+
+DEV=$2
+RATE=$3mbit
+DELAY=$4ms
+JITTER=$5ms
+LOSS=$6
+
+if [[ $1 -eq "set" ]]; then
+ tc qdisc add dev "$DEV" root handle 1:0 htb default 1
+ tc class add dev "$DEV" parent 1:0 classid 1:1 htb rate "$RATE"
+ tc qdisc add dev "$DEV" parent 1:1 handle 2:0 netem delay "$DELAY"
+ "$JITTER" loss random "$LOSS"
+ echo "Dev: $DEV, rate: $RATE, delay: $DELAY, jitter: $JITTER, loss: $LOSS%"
+elif [[ $1 -eq "change" ]]; then
+ tc qdisc change dev "$DEV" parent 1:1 handle 2:0 netem delay "$DELAY" "$JITTER" loss random "$LOSS"
+ echo "Dev: $DEV, rate: $RATE, delay: $DELAY, jitter: $JITTER, loss: $LOSS%"
+else
+ echo "set or change"
+fi
diff --git a/tests/config.sh b/tests/config.sh
new file mode 100755
index 000000000..00d148e42
--- /dev/null
+++ b/tests/config.sh
@@ -0,0 +1,700 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+SCRIPT_PATH=$(
+ cd "$(dirname "${BASH_SOURCE}")"
+ pwd -P
+)
+
+# Import test configurations and names
+source ${SCRIPT_PATH}/.env
+
+set -a
+DOCKERFILE=${DOCKERFILE:-Dockerfile.dev}
+BUILD_SOFTWARE=${BUILD_SOFTWARE:-1}
+PRIVILEGED=${TEST_PRIVILEGED:-false}
+set +a
+
+HIPERF_CMD_RTC="ENABLE_LOG_PREFIX=OFF /usr/bin/hiperf -q -n 50 -C -H -R ${RTC_PRODUCER} -P 2 -k ${HMAC_KEY}"
+HIPERF_CMD_MEMIF_RTC="${HIPERF_CMD_RTC} -z memif_module"
+POSTPROCESS_COMMAND_RAAQM_RTC='tail -n +3 | \
+ tr -s " " | \
+ cut -f 4 -d " " | \
+ sort -n | \
+ tail -n 40 | \
+ head -n 35 | \
+ awk "BEGIN { \
+ c=0; \
+ s=0; \
+ }{ \
+ a[n++]=\$1; \
+ s+=\$1; \
+ } END { \
+ print int(a[0]), int(a[n-1]), int(s/n) \
+ }"'
+
+HIPERF_CMD_RAAQM="ENABLE_LOG_PREFIX=OFF /usr/bin/hiperf -q -n 50 -i 200 -C -H ${RAAQM_PRODUCER}"
+HIPERF_CMD_RAAQM_NEW="ENABLE_LOG_PREFIX=OFF /usr/bin/hiperf -q -n 50 -i 200 -C -H ${RAAQM_PRODUCER_NEW} -w new"
+HIPERF_CMD_CBR="${HIPERF_CMD_RAAQM} -W 350 -M 0"
+HIPERF_CMD_CBR_NEW="${HIPERF_CMD_RAAQM_NEW} -W 350 -M 0"
+HIPERF_CMD_MEMIF_RAAQM="${HIPERF_CMD_RAAQM} -z memif_module"
+HIPERF_CMD_MEMIF_CBR="${HIPERF_CMD_CBR} -z memif_module"
+
+PING_CMD="ENABLE_LOG_PREFIX=OFF LOG_LEVEL=1 hicn-ping-client -m 50 -i 200000 -n ${PING_PRODUCER}"
+PING_CMD_NEW="ENABLE_LOG_PREFIX=OFF LOG_LEVEL=1 hicn-ping-client -m 50 -i 200000 -n ${PING_PRODUCER} -w new"
+PING_CMD_MEMIF="${PING_CMD} -z memif_module"
+POSTPROCESS_COMMAND_PING='grep trip | \
+ cut -f 4 -d " " | \
+ sort -n | \
+ tail -n 40 | \
+ head -n 35 | \
+ awk "BEGIN { \
+ c=0; \
+ s=0; \
+ }{ \
+ a[n++]=\$1; \
+ s+=\$1; \
+ } END { \
+ print int(a[0]), int(a[n-1]), int(s/n) \
+ }"'
+
+declare -a topologies
+declare -a configurations
+
+# Fill topology array using the same values in the .env file
+for topology in $(compgen -A variable | grep TOPOLOGY_); do
+ topologies+=("${!topology}")
+done
+
+# Fill configurations array using the same values in the .env file
+for test in $(compgen -A variable | grep TEST_); do
+ configurations+=("${!test}")
+done
+
+declare -A tests=(
+ ["hicn-light-rtc"]="${HIPERF_CMD_RTC} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-bridge-rtc"]="${HIPERF_CMD_MEMIF_RTC} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-memif-rtc"]="${HIPERF_CMD_MEMIF_RTC} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-memif-replication-rtc"]="${HIPERF_CMD_MEMIF_RTC} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+
+ ["hicn-light-requin"]="${HIPERF_CMD_RAAQM} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["hicn-light-requin-new-packet-format"]="${HIPERF_CMD_RAAQM_NEW} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-bridge-requin"]="${HIPERF_CMD_MEMIF_RAAQM} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-memif-requin"]="${HIPERF_CMD_MEMIF_RAAQM} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-memif-replication-requin"]="${HIPERF_CMD_MEMIF_RAAQM} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+
+ ["hicn-light-cbr"]="${HIPERF_CMD_CBR} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["hicn-light-cbr-new-packet-format"]="${HIPERF_CMD_CBR_NEW} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-bridge-cbr"]="${HIPERF_CMD_MEMIF_CBR} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-memif-cbr"]="${HIPERF_CMD_MEMIF_CBR} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+ ["vpp-memif-replication-cbr"]="${HIPERF_CMD_MEMIF_CBR} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_RAAQM_RTC}"
+
+ ["hicn-light-latency"]="${PING_CMD} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_PING}"
+ ["vpp-bridge-latency"]="${PING_CMD_MEMIF} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_PING}"
+ ["vpp-memif-latency"]="${PING_CMD_MEMIF} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_PING}"
+ ["vpp-memif-replication-latency"]="${PING_CMD_MEMIF} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_PING}"
+ ["hicn-light-latency-new-packet-format"]="${PING_CMD_NEW} 2>&1 | tee >(>&2 cat) | ${POSTPROCESS_COMMAND_PING}"
+)
+
+declare -A link_model=(
+ ["500-0-0-0"]="500 0 0 0"
+ ["500-1-0-0"]="500 1 0 0"
+ ["500-5-0-0"]="500 5 0 0"
+ ["500-200-0-0"]="500 200 0 0"
+ ["100-1-0-0"]="100 1 0 0"
+ ["100-10-0-0"]="100 10 0 0"
+ ["100-15-0-0"]="100 15 0 0"
+ ["200-5-0-0"]="200 5 0 0"
+ ["300-5-0-0"]="300 5 0 0"
+ ["400-5-0-0"]="400 5 0 0"
+ ["1000-1-0-0"]="1000 1 0 0"
+ ["10-50-1-10"]="10 50 1 10"
+)
+
+function topology_exists() {
+ [[ "${topologies[*]}" =~ ${1} ]] && return 0 || return 1
+}
+
+function test_exists() {
+ [[ "${!tests[*]}" =~ ${1} ]] && return 0 || return 1
+}
+
+function conf_exists() {
+ [[ "${configurations[*]}" =~ ${1} ]] && return 0 || return 1
+}
+
+# test-name client/server link-model
+function setchannel() {
+ topology=${1}
+ configuration=${2}
+ service=${3}
+ device=${4}
+
+ if ! conf_exists "${configuration}"; then
+ error "Error: topology does not exist."
+ fi
+
+ local DOCKER_COMMAND="docker-compose -f ${topology}.yml -f ${topology}-${configuration}.yml exec -T"
+ ${DOCKER_COMMAND} "${service}" bash -c "/workspace/tests/config.sh link set ${device} ${link_model[${3}]}"
+}
+
+# test-name client/server link-model
+function changechannel() {
+ topology=${1}
+ configuration=${2}
+ service=${3}
+ device=${4}
+
+ if ! conf_exists "${configuration}"; then
+ error "Error: topology does not exist."
+ fi
+
+ local DOCKER_COMMAND="docker-compose -f ${topology}.yml -f ${topology}-${configuration}.yml exec -T"
+ ${DOCKER_COMMAND} "${service}" bash -c "/workspace/tests/config.sh link change ${device} ${link_model[${3}]}"
+}
+
+# channel set/change dev rate delay jitter lossrate
+function channel() {
+ DEV=${2}
+ RATE=${3}mbit
+ DELAY=${4}ms
+ JITTER=${5}ms
+ LOSS=${6}
+ if [[ $1 == set ]]; then
+ sudo tc qdisc add dev "${DEV}" root handle 1:0 htb default 1
+ sudo tc class add dev "${DEV}" parent 1:0 classid 1:1 htb rate "$RATE"
+ sudo tc qdisc add dev "${DEV}" parent 1:1 handle 2:0 netem delay "${DELAY}" \
+ "${JITTER}" loss random "${LOSS}"
+ echo "Dev: ${DEV}, rate: ${RATE}, delay: ${DELAY}, jitter: ${JITTER}, loss: ${LOSS}%"
+ elif [[ ${1} == change ]]; then
+ sudo tc qdisc change dev "$DEV" parent 1:1 handle 2:0 netem delay "$DELAY" \
+ "${JITTER}" loss random "${LOSS}"
+ echo "Dev: ${DEV}, rate: ${RATE}, delay: ${DELAY}, jitter: ${JITTER}, loss: ${LOSS}%"
+ else
+ sudo tc qdisc del dev "${DEV}" root
+ echo "set or change"
+ fi
+}
+
+function error() {
+ echo >&2 "${@}"
+ return 1
+}
+
+function build() {
+ docker-compose -f build.yml build
+ docker-compose -f build.yml up --force-recreate --remove-orphans
+}
+
+function setup() {
+ topology=${1}
+ conf=${2}
+
+ if ! topology_exists "${topology}"; then
+ error "Error: topology does not exist."
+ fi
+
+ if [[ "${topology}" == "1-node" && "${conf}" == "None" ]]; then
+ docker-compose -f "${topology}".yml build
+ docker-compose -f "${topology}".yml up --remove-orphans --force-recreate -d
+
+ sleep 1
+ return
+ fi
+
+ if ! conf_exists "${conf}"; then
+ error "Error: topology conf does not exist."
+ fi
+
+ docker-compose -f "${topology}".yml -f "${topology}-${conf}".yml build
+ docker-compose -f "${topology}".yml -f "${topology}-${conf}".yml up --remove-orphans --force-recreate -d
+
+ sleep 10
+
+ # Check logs
+ docker-compose -f "${topology}".yml -f "${topology}-${conf}".yml logs
+}
+
+function start() {
+ topology=${1}
+ conf=${2}
+ test=${3}
+
+ if ! conf_exists "${conf}"; then
+ error "Error: configuration does not exist."
+ fi
+
+ TESTNAME="${conf}-${test}"
+
+ if ! test_exists "${TESTNAME}"; then
+ error "Error: test does not exist."
+ fi
+
+ local DOCKER_COMMAND="docker-compose -f ${topology}.yml -f ${topology}-${conf}.yml exec -T"
+
+ ${DOCKER_COMMAND} client bash -x /workspace/tests/config.sh runtest "${tests[${TESTNAME}]}"
+
+ # Print also forwader log
+ echo "Forwarder Log - CLIENT"
+ ${DOCKER_COMMAND} client sudo cat "${FORWARDER_LOG_PATH}"
+
+ echo
+
+ echo "Forwarder Log - SERVER"
+ ${DOCKER_COMMAND} server sudo cat "${FORWARDER_LOG_PATH}"
+}
+
+function stop() {
+ topology="${1}"
+ conf="${2}"
+
+ if ! topology_exists "${topology}"; then
+ error "Error: topology does not exist."
+ fi
+
+ if [[ "${topology}" == "1-node" && "${conf}" == "None" ]]; then
+ docker-compose -f "${topology}".yml down || true
+ return
+ fi
+
+ if ! conf_exists "${conf}"; then
+ error "Error: tect configuration does not exist."
+ fi
+
+ LOG_FILE="${SCRIPT_PATH}/${topology}-${conf}.log"
+ rm -f "${LOG_FILE}"
+ docker-compose -f "${topology}".yml -f "${topology}-${conf}".yml down || true
+}
+
+function stopall() {
+ for topology in "${topologies[@]}"; do
+ for conf in "${configurations[@]}"; do
+ stop "${topology}" "${conf}"
+ done
+ done
+}
+
+function runtest() {
+ echo "${@}" | sudo -i
+}
+
+################################################################
+# Test commands (hicn-light-control)
+################################################################
+INTERFACE="eth0"
+ADDRESS="${TOPOLOGY_1_NODE_IP_ADDRESS}"
+LISTENER_NAME="udp0"
+LISTENER_NAME_2="udp1"
+CONN_NAME="conn0"
+CONN_NAME_2="conn1"
+PREFIX="b001::/16"
+COST=1
+
+#---------------------------------------------------------------
+# Helpers
+#---------------------------------------------------------------
+
+DOCKER_COMMAND="docker-compose -f 1-node.yml exec -T client"
+
+function exec_command() {
+ command=$1
+
+ output=$(${DOCKER_COMMAND} hicn-light-control "$command" 2>&1)
+ echo "$output"
+}
+
+function assert_cmd_success() {
+ command=$1
+ output=$(exec_command "${command}")
+
+ if [[ -z "$output" ]]; then
+ echo "OK"
+ else
+ echo "FAILED"
+ exit 0
+ fi
+}
+
+function assert_cmd_failure() {
+ command=$1
+ output=$(exec_command "${command}")
+
+ if [[ ! -z "$output" ]]; then
+ echo "OK"
+ else
+ echo "FAILED"
+ exit 0
+ fi
+}
+
+#---------------------------------------------------------------
+# Tests for listeners, connections, routes
+#---------------------------------------------------------------
+function test_listeners() {
+ echo -n "Add listeners: "
+ command="add listener udp $LISTENER_NAME $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add listener udp $LISTENER_NAME_2 127.0.0.1 12345 $INTERFACE"
+ assert_cmd_success "${command}"
+
+ echo -n "List listeners: "
+ command="list listener"
+ output=$(exec_command "${command}")
+
+ if [[ "${output}" =~ "udp0 inet4://${ADDRESS}:9695" &&
+ "${output}" =~ "udp1 inet4://127.0.0.1:12345" &&
+ "${output}" =~ "interface=lo" &&
+ "${output}" =~ "interface=$INTERFACE" &&
+ ! "${output}" =~ "ERROR" ]]; then
+ echo "OK"
+ else
+ echo "FAILED"
+ echo $output
+ exit 0
+ fi
+
+ echo -n "Remove listener using symbolic: "
+ command="remove listener $LISTENER_NAME"
+ assert_cmd_success "${command}"
+
+ echo -n "Remove listener using ID: "
+ command="remove listener 2"
+ assert_cmd_success "${command}"
+
+ echo -n "Remove non-existing listener using symbolic: "
+ command="remove listener $LISTENER_NAME_2"
+ assert_cmd_failure "${command}"
+
+ echo -n "Remove non-existing listener using ID: "
+ command="remove listener 5"
+ assert_cmd_failure "${command}"
+
+ echo -n "Add duplicated listener (same symbolic): "
+ command="add listener udp $LISTENER_NAME $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add listener udp $LISTENER_NAME 127.0.0.1 12345 $INTERFACE"
+ assert_cmd_failure "${command}"
+
+ echo -n "Add duplicated listener (same endpoints): "
+ command="add listener udp $LISTENER_NAME $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add listener udp $LISTENER_NAME_2 $ADDRESS 9695 $INTERFACE"
+ assert_cmd_failure "${command}"
+}
+
+function test_connections() {
+ echo -n "Add connections: "
+ command="add listener udp $LISTENER_NAME $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add connection udp $CONN_NAME $ADDRESS 9695 $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add connection udp $CONN_NAME_2 $ADDRESS 9695 $ADDRESS 12345 $INTERFACE"
+ assert_cmd_success "${command}"
+
+ echo -n "List connections: "
+ command="list connection"
+ output=$(exec_command "${command}")
+
+ if [[ "${output}" =~ "inet4://${ADDRESS}:12345" &&
+ "${output}" =~ "inet4://${ADDRESS}:9695" &&
+ "${output}" =~ "conn0" && "${output}" =~ "conn1" &&
+ ! "${output}" =~ "ERROR" ]]; then
+ echo "OK"
+ else
+ echo "FAILED"
+ echo $output
+ exit 0
+ fi
+
+ echo -n "Remove connection using symbolic: "
+ command="remove connection $CONN_NAME"
+ assert_cmd_success "${command}"
+
+ echo -n "Remove connection using ID: "
+ command="remove connection 2"
+ assert_cmd_success "${command}"
+
+ echo -n "Remove non-existing connection using symbolic: "
+ command="remove connection $CONN_NAME"
+ assert_cmd_failure "${command}"
+
+ echo -n "Remove non-existing connection using ID: "
+ command="remove connection 5"
+ assert_cmd_failure "${command}"
+
+ echo -n "Add duplicated connection (same symbolic): "
+ command="add connection udp $CONN_NAME $ADDRESS 9695 $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add connection udp $CONN_NAME $ADDRESS 12345 $ADDRESS 9695 $INTERFACE"
+ assert_cmd_failure "${command}"
+
+ # This case is allowed, success code is returned and symbolic is not updated
+ echo -n "Add duplicated connection (different symbolic, same endpoints): "
+ command="add connection udp $CONN_NAME_2 $ADDRESS 9695 $ADDRESS 9695 $INTERFACE"
+ assert_cmd_success "${command}"
+}
+
+function test_routes() {
+ echo -n "Add route: "
+ command="add listener udp $LISTENER_NAME $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add connection udp $CONN_NAME $ADDRESS 9695 $ADDRESS 9695 $INTERFACE"
+ _=$(exec_command "${command}")
+ command="add route $CONN_NAME $PREFIX $COST"
+ assert_cmd_success "${command}"
+
+ echo -n "List routes: "
+ command="list route"
+ output=$(exec_command "${command}")
+
+ if [[ "${output}" =~ "b001::" && "${output}" =~ "16" &&
+ ! "${output}" =~ "ERROR" ]]; then
+ echo "OK"
+ else
+ echo "FAILED"
+ echo "$output"
+ exit 0
+ fi
+
+ echo -n "Remove route using symbolic: "
+ command="remove route $CONN_NAME $PREFIX"
+ assert_cmd_success "${command}"
+
+ echo -n "Remove route using ID: "
+ command="add route $CONN_NAME $PREFIX $COST"
+ _=$(exec_command "${command}")
+ command="remove route 1 $PREFIX"
+ assert_cmd_success "${command}"
+
+ echo -n "Remove non-existing route using symbolic: "
+ command="remove connection $CONN_NAME $PREFIX"
+ assert_cmd_failure "${command}"
+
+ echo -n "Remove non-existing route using ID: "
+ command="remove route 5 $PREFIX"
+ assert_cmd_failure "${command}"
+
+ echo -n "Add route and face without interface"
+ command="add route $PREFIX $COST udp $ADDRESS 9695 127.0.0.1 9695 $INTERFACE"
+ assert_cmd_success "${command}"
+
+ echo -n "Add route and face without interface"
+ command="add route $PREFIX $COST udp $ADDRESS 9695 127.0.0.1 9695"
+ assert_cmd_success "${command}"
+}
+
+declare -A ctrl_tests=(
+ ["listeners"]="test_listeners"
+ ["connections"]="test_connections"
+ ["routes"]="test_routes"
+)
+
+function ctrl_test_exists() {
+ [[ "${!ctrl_tests[*]}" =~ ${1} ]] && return 0 || return 1
+}
+
+function ctrl() {
+ type=$1
+ if ! ctrl_test_exists "${type}"; then
+ error "Error: hicn-light-contrl test does not exist."
+ exit 1
+ fi
+
+ ${ctrl_tests[${type}]}
+}
+
+################################################################
+# Test ping
+################################################################
+function test_ping_manifest() {
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-server -a intmanifest >/tmp/ping_server.log 2>&1 &'
+ sleep 1
+
+ # 2 interests w/ 3 suffixes each (1 in header + 2 in manifest)
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-client -m 6 -a 2 intmanifest 2>&1 | grep "Sent" >>/tmp/ping_client.log'
+ sleep 1
+
+ # 2 interests w/ 3 suffixes each + 1 single interest
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-client -m 7 -a 2 intmanifest 2>&1 | grep "Sent" >>/tmp/ping_client.log'
+ sleep 1
+
+ # 2 interests w/ 3 suffixes each + 1 interest w/ 2 suffixes
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-client -m 8 -a 2 intmanifest 2>&1 | grep "Sent" >>/tmp/ping_client.log'
+ sleep 1
+
+ # 2 interests w/ 3 suffixes each + 1 single interest,
+ # using random prefix/suffix generation
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-client -m 7 -a 2 intmanifest -b RANDOM 2>&1 | grep "Sent" >>/tmp/ping_client.log'
+
+ # No 'failed' expected
+ ping_server_logs=$(${DOCKER_COMMAND} cat /tmp/ping_server.log)
+ if [[ $(echo $ping_server_logs | grep failed | wc -l) -ne 0 ]]; then
+ echo "******** Server logs (ping) ********"
+ echo "$ping_server_logs"
+ exit 1
+ fi
+
+ # No 'Timeouts: 0' expected
+ ping_client_logs=$(${DOCKER_COMMAND} cat /tmp/ping_client.log)
+ if [[ $(echo $ping_client_logs | grep -v "Timeouts: 0" | wc -l) -ne 0 ]]; then
+ echo "******** Client logs (ping) ********"
+ echo "$ping_client_logs"
+ exit 1
+ fi
+}
+
+function test_ping_wrong_signature() {
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-server -a intmanifest >/tmp/ping_server.log 2>&1 &'
+ sleep 1
+
+ # Signature mismatch ('intmamifest' on server vs 'wrong_sign' on client)
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-client -m 6 -a 2 wrong_sig'
+
+ # 'failed' expected
+ ping_server_logs=$(${DOCKER_COMMAND} cat /tmp/ping_server.log)
+ if [[ $(echo $ping_server_logs | grep "failed" | wc -l) -eq 0 ]]; then
+ echo "******** Server logs (signature fail) ********"
+ echo "$ping_server_logs"
+ exit 1
+ fi
+}
+
+function test_ping_no_server() {
+ # Server not started to check for ping client timeout
+ ${DOCKER_COMMAND} bash -c 'hicn-ping-client -m 6 2>&1 | grep "Sent" >/tmp/ping_client.log'
+
+ # 'Timeouts: 6' expected
+ ping_client_logs=$(${DOCKER_COMMAND} cat /tmp/ping_client.log)
+ if [[ $(echo $ping_client_logs | grep "Timeouts: 6" | wc -l) -eq 0 ]]; then
+ echo "******** Client logs (timeout) ********"
+ echo "$ping_client_logs"
+ exit 1
+ fi
+}
+
+declare -A ping_tests=(
+ ["manifest"]="test_ping_manifest"
+ ["signature"]="test_ping_wrong_signature"
+ ["timeout"]="test_ping_no_server"
+)
+
+function ping_test_exists() {
+ [[ "${!ping_tests[*]}" =~ ${1} ]] && return 0 || return 1
+}
+
+function ping() {
+ type=$1
+ if ! ping_test_exists "${type}"; then
+ error "Error: hicn-ping test does not exist."
+ exit 1
+ fi
+
+ ${ping_tests[${type}]}
+}
+
+#---------------------------------------------------------------
+# Tests for local-remote strategy
+#---------------------------------------------------------------
+
+function localremote() {
+ local DOCKER_COMMAND="docker-compose -f 2-nodes.yml -f 2-nodes-vpp-memif-local-remote.yml exec -T"
+
+ ${DOCKER_COMMAND} "client" sudo bash -c "${HIPERF_CMD_MEMIF_CBR}"
+ ${DOCKER_COMMAND} "client" sudo /usr/bin/vppctl hicn face show > /tmp/output
+
+ # Check that producer face has received 0 packets
+ INTEREST_TX="$(cat /tmp/output | grep -A 9 producer | grep "Interest tx" | awk '{print $4}')"
+ INTEREST_TX="${INTEREST_TX%%[[:cntrl:]]}"
+ if [[ ${INTEREST_TX} != "0" ]]; then
+ echo "Received interest on local interface."
+ exit 1
+ fi
+
+ # Check that producer face has sent 0 packets
+ DATA_RX="$(cat /tmp/output | grep -A 9 producer | grep "Data rx" | awk '{print $4}')"
+ DATA_RX="${DATA_RX%%[[:cntrl:]]}"
+ if [[ ${DATA_RX} != "0" ]]; then
+ echo "Received data on local interface."
+ exit 1
+ fi
+
+ # Check that remote face has sent > 0 packets
+ DATA_RX="$(cat /tmp/output | grep -A 9 ${TOPOLOGY_2_NODES_IP6_ADDRESS_CLIENT} | grep "Data rx" | awk '{print $4}')"
+ DATA_RX="${DATA_RX%%[[:cntrl:]]}"
+ if [[ ${DATA_RX} == "0" ]]; then
+ echo "No data received on remote interface."
+ exit 1
+ fi
+
+ # Check that remote face has sent > 0 packets
+ INTEREST_TX="$(cat /tmp/output | grep -A 9 ${TOPOLOGY_2_NODES_IP6_ADDRESS_CLIENT} | grep "Interest tx" | awk '{print $4}')"
+ INTEREST_TX="${INTEREST_TX%%[[:cntrl:]]}"
+ if [[ ${INTEREST_TX} == "0" ]]; then
+ echo "No interest sent on remote interface."
+ exit 1
+ fi
+}
+
+#--------------------------------------------------------------#
+
+while (("${#}")); do
+ case "$1" in
+ 'build')
+ build
+ shift
+ ;;
+ 'link')
+ shift
+ channel "$@"
+ shift 6
+ ;;
+ 'setchannel')
+ shift
+ setchannel "$@"
+ shift 5
+ ;;
+ 'changechannel')
+ shift
+ changechannel "$@"
+ shift 5
+ ;;
+ 'setup')
+ setup "${2}" "${3}"
+ shift 3
+ ;;
+ 'start')
+ start "${2}" "${3}" "${4}"
+ shift 4
+ ;;
+ 'stop')
+ stop "${2}" "${3}"
+ shift 3
+ ;;
+ 'stopall')
+ stopall
+ shift
+ ;;
+ 'runtest')
+ runtest "${@:2}"
+ break
+ ;;
+ 'ctrl')
+ ctrl "${2}"
+ break
+ ;;
+ 'ping')
+ ping "${2}"
+ break
+ ;;
+ 'localremote')
+ localremote
+ break
+ ;;
+ *)
+ exit 1
+ ;;
+ esac
+done
+
+exit 0
diff --git a/tests/functional-tests/2-nodes-hicn-light.robot b/tests/functional-tests/2-nodes-hicn-light.robot
new file mode 100644
index 000000000..1686ca9e6
--- /dev/null
+++ b/tests/functional-tests/2-nodes-hicn-light.robot
@@ -0,0 +1,84 @@
+*** Settings ***
+Resource ../resources/libraries/robot/runtest.robot
+Resource ../resources/libraries/robot/common.robot
+
+Suite Setup Run Keywords
+... Build Topology
+... 2-nodes
+... hicn-light
+... AND
+... Check Environment
+Suite Teardown Run Keywords
+... Destroy Topology
+
+
+*** Test Cases ***
+Throughput Testing Raaqm Mobile
+ Run Throughput Test Raaqm
+ ... 2-nodes
+ ... hicn-light
+ ... 200
+ ... 500
+ ... 400
+
+Throughput Testing Raaqm Mobile New Packet Format
+ Run Throughput Test Raaqm New Packet Format
+ ... 2-nodes
+ ... hicn-light
+ ... 200
+ ... 500
+ ... 400
+
+Throughput Testing CBR Mobile
+ Run Throughput Test CBR
+ ... 2-nodes
+ ... hicn-light
+ ... 20
+ ... 500
+ ... 400
+
+Throughput Testing CBR Mobile New Packet Format
+ Run Throughput Test CBR New Packet Format
+ ... 2-nodes
+ ... hicn-light
+ ... 200
+ ... 500
+ ... 400
+
+RTC Testing Mobile
+ Run RTC Test
+ ... 2-nodes
+ ... hicn-light
+ ... 4
+ ... 4
+ ... 4
+
+Latency Testing Mobile
+ Set Link
+ ... 2-nodes
+ ... hicn-light
+ ... 500
+ ... 1
+ ... 0
+ ... 0
+ Run Latency Test
+ ... 2-nodes
+ ... hicn-light
+ ... 3000
+ ... 3000
+ ... 3000
+
+Latency Testing Mobile New Packet Format
+ Set Link
+ ... 2-nodes
+ ... hicn-light
+ ... 500
+ ... 1
+ ... 0
+ ... 0
+ Run Latency Test New Packet Format
+ ... 2-nodes
+ ... hicn-light
+ ... 3000
+ ... 3000
+ ... 3000
diff --git a/tests/functional-tests/2-nodes-vpp-bridge.robot b/tests/functional-tests/2-nodes-vpp-bridge.robot
new file mode 100644
index 000000000..fd3d42fe0
--- /dev/null
+++ b/tests/functional-tests/2-nodes-vpp-bridge.robot
@@ -0,0 +1,53 @@
+*** Settings ***
+Resource ../resources/libraries/robot/runtest.robot
+Resource ../resources/libraries/robot/common.robot
+
+Suite Setup Run Keywords
+... Build Topology
+... 2-nodes
+... vpp-bridge
+... AND
+... Check Environment
+Suite Teardown Run Keywords
+... Destroy Topology
+
+
+*** Test Cases ***
+Throughput Testing Raaqm Server VPP bridge
+ Run Throughput Test Raaqm
+ ... 2-nodes
+ ... vpp-bridge
+ ... 500
+ ... 500
+ ... 500
+
+Throughput Testing CBR Server VPP bridge
+ Run Throughput Test CBR
+ ... 2-nodes
+ ... vpp-bridge
+ ... 1000
+ ... 1300
+ ... 1200
+
+RTC Testing Server VPP bridge
+ Run RTC Test
+ ... 2-nodes
+ ... vpp-bridge
+ ... 4
+ ... 4
+ ... 4
+
+Latency Testing Server VPP bridge
+ Set Link
+ ... 2-nodes
+ ... hicn-light
+ ... 500
+ ... 1
+ ... 0
+ ... 0
+ Run Latency Test
+ ... 2-nodes
+ ... vpp-bridge
+ ... 3000
+ ... 3000
+ ... 3000
diff --git a/tests/functional-tests/2-nodes-vpp-memif-replication.robot b/tests/functional-tests/2-nodes-vpp-memif-replication.robot
new file mode 100644
index 000000000..186eb5c94
--- /dev/null
+++ b/tests/functional-tests/2-nodes-vpp-memif-replication.robot
@@ -0,0 +1,46 @@
+*** Settings ***
+Resource ../resources/libraries/robot/runtest.robot
+Resource ../resources/libraries/robot/common.robot
+
+Suite Setup Run Keywords
+... Build Topology
+... 2-nodes
+... vpp-memif-replication
+... AND
+... Check Environment
+Suite Teardown Run Keywords
+... Destroy Topology
+
+
+*** Test Cases ***
+Throughput Testing Raaqm Server VPP memif replication
+ Run Throughput Test Raaqm
+ ... 2-nodes
+ ... vpp-memif-replication
+ ... 500
+ ... 500
+ ... 500
+
+Throughput Testing CBR Server VPP memif
+ Run Throughput Test CBR
+ ... 2-nodes
+ ... vpp-memif-replication
+ ... 2000
+ ... 2000
+ ... 2000
+
+RTC Testing Server VPP memif replication
+ Run RTC Test
+ ... 2-nodes
+ ... vpp-memif-replication
+ ... 4
+ ... 4
+ ... 4
+
+Latency Testing Server VPP memif replication
+ Run Latency Test
+ ... 2-nodes
+ ... vpp-memif-replication
+ ... 3000
+ ... 3000
+ ... 3000
diff --git a/tests/functional-tests/2-nodes-vpp-memif.robot b/tests/functional-tests/2-nodes-vpp-memif.robot
new file mode 100644
index 000000000..ed9ab1143
--- /dev/null
+++ b/tests/functional-tests/2-nodes-vpp-memif.robot
@@ -0,0 +1,46 @@
+*** Settings ***
+Resource ../resources/libraries/robot/runtest.robot
+Resource ../resources/libraries/robot/common.robot
+
+Suite Setup Run Keywords
+... Build Topology
+... 2-nodes
+... vpp-memif
+... AND
+... Check Environment
+Suite Teardown Run Keywords
+... Destroy Topology
+
+
+*** Test Cases ***
+Throughput Testing Raaqm Server VPP memif
+ Run Throughput Test Raaqm
+ ... 2-nodes
+ ... vpp-memif
+ ... 500
+ ... 500
+ ... 500
+
+Throughput Testing CBR Server VPP memif
+ Run Throughput Test CBR
+ ... 2-nodes
+ ... vpp-memif
+ ... 2000
+ ... 2000
+ ... 2000
+
+RTC Testing Server VPP memif
+ Run RTC Test
+ ... 2-nodes
+ ... vpp-memif
+ ... 4
+ ... 4
+ ... 4
+
+Latency Testing Server VPP memif
+ Run Latency Test
+ ... 2-nodes
+ ... vpp-memif
+ ... 3000
+ ... 3000
+ ... 3000
diff --git a/tests/functional-tests/hicn-light-control.robot b/tests/functional-tests/hicn-light-control.robot
new file mode 100644
index 000000000..147226188
--- /dev/null
+++ b/tests/functional-tests/hicn-light-control.robot
@@ -0,0 +1,48 @@
+*** Settings ***
+Resource ../resources/libraries/robot/common.robot
+
+Test Setup Run Keywords
+... Build Topology
+... 1-node
+... AND
+... Check Environment
+Test Teardown Run Keywords
+... Destroy Topology
+
+
+*** Test Cases ***
+Listeners
+ Log to console Test listeners
+ ${result} = Run Process
+ ... bash
+ ... -x
+ ... ${EXECDIR}/config.sh
+ ... ctrl
+ ... listeners
+ Log Many stdout: ${result.stdout}
+ Should Be Equal As Integers ${result.rc} 0
+ Should Not Contain ${result.stdout} FAILED
+
+Connections
+ Log to console Test connections
+ ${result} = Run Process
+ ... bash
+ ... -x
+ ... ${EXECDIR}/config.sh
+ ... ctrl
+ ... connections
+ Log Many stdout: ${result.stdout}
+ Should Be Equal As Integers ${result.rc} 0
+ Should Not Contain ${result.stdout} FAILED
+
+Routes
+ Log to console Test routes
+ ${result} = Run Process
+ ... bash
+ ... -x
+ ... ${EXECDIR}/config.sh
+ ... ctrl
+ ... routes
+ Log Many stdout: ${result.stdout}
+ Should Be Equal As Integers ${result.rc} 0
+ Should Not Contain ${result.stdout} FAILED
diff --git a/tests/functional-tests/hicn-light-ping.robot b/tests/functional-tests/hicn-light-ping.robot
new file mode 100644
index 000000000..ba6beed42
--- /dev/null
+++ b/tests/functional-tests/hicn-light-ping.robot
@@ -0,0 +1,30 @@
+*** Settings ***
+Resource ../resources/libraries/robot/common.robot
+
+Test Setup Run Keywords
+... Build Topology
+... 1-node
+... AND
+... Check Environment
+Test Teardown Run Keywords
+... Destroy Topology
+
+
+*** Test Cases ***
+Ping with manifest
+ Log to console Test ping with manifest
+ ${result} = Run Process bash -x ${EXECDIR}/config.sh ping manifest
+ Log Many stdout: ${result.stdout}
+ Should Be Equal As Integers ${result.rc} 0
+
+Ping wrong signature
+ Log to console Test ping with wrong signature
+ ${result} = Run Process bash -x ${EXECDIR}/config.sh ping signature
+ Log Many stdout: ${result.stdout}
+ Should Be Equal As Integers ${result.rc} 0
+
+Ping timeout
+ Log to console Test ping timeout
+ ${result} = Run Process bash -x ${EXECDIR}/config.sh ping timeout
+ Log Many stdout: ${result.stdout}
+ Should Be Equal As Integers ${result.rc} 0
diff --git a/tests/hiperf-local.sh b/tests/hiperf-local.sh
new file mode 100644
index 000000000..1ef11eb72
--- /dev/null
+++ b/tests/hiperf-local.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+set -eo pipefail
+
+if [[ "$(basename $(pwd))" != build* ]]; then
+ echo "Error: launch script from build dir"
+ exit 1
+fi
+
+# Stop forwarder and hiperf if already running
+sudo killall -9 hicn-light-daemon hiperf 2>/dev/null || true
+
+# Start forwarder and hiperf server in background
+ninja && sudo ./build-root/bin/hicn-light-daemon --daemon --log-file /tmp/lite_client.log >/dev/null
+./build-root/bin/hiperf -z hicnlightng_module -S b001::/16 &
+
+# Run hiperf client for 20 seconds
+sleep 1
+./build-root/bin/hiperf -z hicnlightng_module -C b001:: -W 50 -n 20
+
+# Clean up
+sudo killall -9 hicn-light-daemon hiperf
diff --git a/tests/resources/libraries/robot/common.robot b/tests/resources/libraries/robot/common.robot
new file mode 100644
index 000000000..921d79b4d
--- /dev/null
+++ b/tests/resources/libraries/robot/common.robot
@@ -0,0 +1,39 @@
+*** Settings ***
+Library OperatingSystem
+Library Process
+Library String
+
+
+*** Keywords ***
+Build Topology
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_CONFIGURATION}=${NONE}
+ Log to console
+ ... Building topology ${TEST_TOPOLOGY} ${TEST_CONFIGURATION}
+ ${result_setup} = Run Process
+ ... ${EXECDIR}/config.sh
+ ... build
+ ... setup
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_CONFIGURATION}
+ ... stdout=${TEMPDIR}/stdout.txt
+ ... stderr=${TEMPDIR}/stderr.txt
+ Log to console Done
+ Log Many
+ ... stdout: ${result_setup.stdout}
+ ... stderr: ${result_setup.stderr}
+ Should Be Equal As Integers ${result_setup.rc} 0
+
+Check Environment
+ ${result} = Run Process docker ps
+ Log Many
+ ... stdout: ${result.stdout}
+ ... stderr: ${result.stderr}
+
+Destroy Topology
+ ${result_teardown} = Run Process ${EXECDIR}/config.sh stopall
+ Log Many
+ ... stdout: ${result_teardown.stdout}
+ ... stderr: ${result_teardown.stderr}
+ Should Be Equal As Integers ${result_teardown.rc} 0
diff --git a/tests/resources/libraries/robot/runtest.robot b/tests/resources/libraries/robot/runtest.robot
new file mode 100644
index 000000000..5ce4787f6
--- /dev/null
+++ b/tests/resources/libraries/robot/runtest.robot
@@ -0,0 +1,293 @@
+*** Settings ***
+Library OperatingSystem
+Library Process
+Library String
+
+
+*** Keywords ***
+Infra ${VALUE}
+ Run Process ${EXECDIR}/config.sh ${VALUE}
+
+Run Test
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${TESTID}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ ${result_test} = Run Process
+ ... ${EXECDIR}/config.sh
+ ... start
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... ${TESTID}
+ ... stdout=${TEMPDIR}/stdout.txt
+ ... stderr=${TEMPDIR}/stderr.txt
+ Log Many stdout: ${result_test.stdout} stderr: ${result_test.stderr}
+ ${min_max_avg_line} = Get Line ${result_test.stdout} 0
+ @{min_max_avg} = Split String ${min_max_avg_line.strip()}
+ Log To Console Min Max Average Array: @{min_max_avg}
+ IF '${TESTID}' == 'rtc'
+ Should Be True
+ ... ${min_max_avg}[0] == ${EXPECTED_MIN}
+ ... msg="Min does not match (${min_max_avg}[0] != ${EXPECTED_MIN})"
+ Should Be True
+ ... ${min_max_avg}[1] == ${EXPECTED_MAX}
+ ... msg="Max does not match (${min_max_avg}[1] != ${EXPECTED_MAX})"
+ Should Be True
+ ... ${min_max_avg}[2] == ${EXPECTED_AVG}
+ ... msg="Avg does not match (${min_max_avg}[2] != ${EXPECTED_AVG})"
+ ELSE IF '${TESTID}' == 'requin'
+ Should Be True
+ ... ${min_max_avg}[0] >= ${EXPECTED_MIN}
+ ... msg="Min does not match (${min_max_avg}[0] < ${EXPECTED_MIN})"
+ Should Be True
+ ... ${min_max_avg}[1] >= ${EXPECTED_MAX}
+ ... msg="Max does not match (${min_max_avg}[1] < ${EXPECTED_MAX})"
+ Should Be True
+ ... ${min_max_avg}[2] >= ${EXPECTED_AVG}
+ ... msg="Avg does not match (${min_max_avg}[2] < ${EXPECTED_AVG})"
+ ELSE IF '${TESTID}' == 'requin-new-packet-format'
+ Should Be True
+ ... ${min_max_avg}[0] >= ${EXPECTED_MIN}
+ ... msg="Min does not match (${min_max_avg}[0] < ${EXPECTED_MIN})"
+ Should Be True
+ ... ${min_max_avg}[1] >= ${EXPECTED_MAX}
+ ... msg="Max does not match (${min_max_avg}[1] < ${EXPECTED_MAX})"
+ Should Be True
+ ... ${min_max_avg}[2] >= ${EXPECTED_AVG}
+ ... msg="Avg does not match (${min_max_avg}[2] < ${EXPECTED_AVG})"
+ ELSE IF '${TESTID}' == 'latency'
+ Should Be True
+ ... ${min_max_avg}[0] <= ${EXPECTED_MIN}
+ ... msg="Min does not match (${min_max_avg}[0] > ${EXPECTED_MIN})"
+ Should Be True
+ ... ${min_max_avg}[1] <= ${EXPECTED_MAX}
+ ... msg="Max does not match (${min_max_avg}[1] > ${EXPECTED_MAX})"
+ Should Be True
+ ... ${min_max_avg}[2] <= ${EXPECTED_AVG}
+ ... msg="Avg does not match (${min_max_avg}[2] > ${EXPECTED_AVG})"
+ ELSE IF '${TESTID}' == 'latency-new-packet-format'
+ Should Be True
+ ... ${min_max_avg}[0] <= ${EXPECTED_MIN}
+ ... msg="Min does not match (${min_max_avg}[0] > ${EXPECTED_MIN})"
+ Should Be True
+ ... ${min_max_avg}[1] <= ${EXPECTED_MAX}
+ ... msg="Max does not match (${min_max_avg}[1] > ${EXPECTED_MAX})"
+ Should Be True
+ ... ${min_max_avg}[2] <= ${EXPECTED_AVG}
+ ... msg="Avg does not match (${min_max_avg}[2] > ${EXPECTED_AVG})"
+ ELSE IF '${TESTID}' == 'cbr'
+ Should Be True
+ ... ${min_max_avg}[0] >= ${EXPECTED_MIN}
+ ... msg="Min does not match (${min_max_avg}[0] < ${EXPECTED_MIN})"
+ Should Be True
+ ... ${min_max_avg}[1] >= ${EXPECTED_MAX}
+ ... msg="Max does not match (${min_max_avg}[1] < ${EXPECTED_MAX})"
+ Should Be True
+ ... ${min_max_avg}[2] >= ${EXPECTED_AVG}
+ ... msg="Avg does not match (${min_max_avg}[2] < ${EXPECTED_AVG})"
+ ELSE IF '${TESTID}' == 'cbr-new-packet-format'
+ Should Be True
+ ... ${min_max_avg}[0] >= ${EXPECTED_MIN}
+ ... msg="Min does not match (${min_max_avg}[0] < ${EXPECTED_MIN})"
+ Should Be True
+ ... ${min_max_avg}[1] >= ${EXPECTED_MAX}
+ ... msg="Max does not match (${min_max_avg}[1] < ${EXPECTED_MAX})"
+ Should Be True
+ ... ${min_max_avg}[2] >= ${EXPECTED_AVG}
+ ... msg="Avg does not match (${min_max_avg}[2] < ${EXPECTED_AVG})"
+ ELSE
+ Fail "Provided Test ID does not exist"
+ END
+
+Set Link
+ [Documentation]
+ ... Configure link rate/delay/jitter/loss
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${RATE} Rate of the link
+ ... ${DELAY} Delay of the link
+ ... ${JITTER} Jitter of the link
+ ... ${LOSS} Loss of the link
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${RATE}=${NONE}
+ ... ${DELAY}=${NONE}
+ ... ${JITTER}=${NONE}
+ ... ${LOSS}=${NONE}
+ ${result_link} = Run Process
+ ... ${EXECDIR}/config.sh
+ ... setchannel
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... server
+ ... eth0
+ ... ${RATE}-${DELAY}-${JITTER}-${LOSS}
+ Log Many stdout: ${result_link.stdout} stderr: ${result_link.stderr}
+
+Run Latency Test
+ [Documentation]
+ ... Run hicn-ping on the \${TEST_SETUP} topology and measure latency.
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${TEST_SETUP} The setup of the test.
+ ... ${EXPECTED_MIN} The expected min latency
+ ... ${EXPECTED_MAX} The expected max latency
+ ... ${EXPECTED_AVG} The expected avg latency
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ Run Test
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... latency
+ ... ${EXPECTED_MIN}
+ ... ${EXPECTED_MAX}
+ ... ${EXPECTED_AVG}
+
+Run Throughput Test Raaqm
+ [Documentation]
+ ... Run hiperf on the \${TEST_TOPOLOGY}-\${TEST_SETUP} topology
+ ... and measure throughput.
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${TEST_SETUP} The setup of the test.
+ ... ${EXPECTED_MIN} The expected min throughput
+ ... ${EXPECTED_MAX} The expected max throughput
+ ... ${EXPECTED_AVG} The expected avg throughput
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ Run Test
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... requin
+ ... ${EXPECTED_MIN}
+ ... ${EXPECTED_MAX}
+ ... ${EXPECTED_AVG}
+
+Run Throughput Test Raaqm New Packet Format
+ [Documentation]
+ ... Run hiperf on the \${TEST_SETUP} topology and measure throughput.
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${TEST_SETUP} The setup of the test.
+ ... ${EXPECTED_MIN} The expected min throughput
+ ... ${EXPECTED_MAX} The expected max throughput
+ ... ${EXPECTED_AVG} The expected avg throughput
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ Run Test
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... requin-new-packet-format
+ ... ${EXPECTED_MIN}
+ ... ${EXPECTED_MAX}
+ ... ${EXPECTED_AVG}
+
+Run Throughput Test CBR
+ [Documentation]
+ ... Run hiperf on the \${TEST_SETUP} topology and measure throughput.
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${TEST_SETUP} The setup of the test.
+ ... ${EXPECTED_MIN} The expected min throughput
+ ... ${EXPECTED_MAX} The expected max throughput
+ ... ${EXPECTED_AVG} The expected avg throughput
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ Run Test
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... cbr
+ ... ${EXPECTED_MIN}
+ ... ${EXPECTED_MAX}
+ ... ${EXPECTED_AVG}
+
+Run Throughput Test CBR New Packet Format
+ [Documentation]
+ ... Run hiperf on the \${TEST_SETUP} topology and measure throughput.
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${TEST_SETUP} The setup of the test.
+ ... ${EXPECTED_MIN} The expected min throughput
+ ... ${EXPECTED_MAX} The expected max throughput
+ ... ${EXPECTED_AVG} The expected avg throughput
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ Run Test
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... cbr-new-packet-format
+ ... ${EXPECTED_MIN}
+ ... ${EXPECTED_MAX}
+ ... ${EXPECTED_AVG}
+
+Run RTC Test
+ [Documentation]
+ ... Run hiperf RTC on the \${TEST_SETUP} topology and check consumer syncs to
+ ... producer bitrate.
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${TEST_SETUP} The setup of the test.
+ ... ${EXPECTED_MIN} The expected min bitrate
+ ... ${EXPECTED_MAX} The expected max bitrate
+ ... ${EXPECTED_AVG} The expected avg bitrate
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ Run Test
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... rtc
+ ... ${EXPECTED_MIN}
+ ... ${EXPECTED_MAX}
+ ... ${EXPECTED_AVG}
+
+Run Latency Test New Packet Format
+ [Documentation]
+ ... Run hicn-ping on the \${TEST_SETUP} topology with the new
+ ... packet format and measure latency.
+ ... Arguments:
+ ... ${TEST_TOPOLOGY} The topology of the test.
+ ... ${TEST_SETUP} The setup of the test.
+ ... ${EXPECTED_MIN} The expected min latency
+ ... ${EXPECTED_MAX} The expected max latency
+ ... ${EXPECTED_AVG} The expected avg latency
+ [Arguments]
+ ... ${TEST_TOPOLOGY}=${NONE}
+ ... ${TEST_SETUP}=${NONE}
+ ... ${EXPECTED_MIN}=${NONE}
+ ... ${EXPECTED_MAX}=${NONE}
+ ... ${EXPECTED_AVG}=${NONE}
+ Run Test
+ ... ${TEST_TOPOLOGY}
+ ... ${TEST_SETUP}
+ ... latency-new-packet-format
+ ... ${EXPECTED_MIN}
+ ... ${EXPECTED_MAX}
+ ... ${EXPECTED_AVG}
diff --git a/libtransport/src/io_modules/loopback/CMakeLists.txt b/tests/run-functional.sh
index b5ae0b7f7..34515ac85 100644
--- a/libtransport/src/io_modules/loopback/CMakeLists.txt
+++ b/tests/run-functional.sh
@@ -11,20 +11,30 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-list(APPEND MODULE_HEADER_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/loopback_module.h
+SCRIPT_PATH=$(
+ cd "$(dirname "${BASH_SOURCE}")"
+ pwd -P
)
-list(APPEND MODULE_SOURCE_FILES
- ${CMAKE_CURRENT_SOURCE_DIR}/loopback_module.cc
-)
+pushd "${SCRIPT_PATH}" || exit 1
-build_module(loopback_module
- SHARED
- SOURCES ${MODULE_SOURCE_FILES}
- DEPENDS ${DEPENDENCIES}
- COMPONENT ${LIBTRANSPORT_COMPONENT}
- INCLUDE_DIRS ${LIBTRANSPORT_INCLUDE_DIRS} ${LIBTRANSPORT_INTERNAL_INCLUDE_DIRS}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- COMPILE_OPTIONS ${COMPILE_FLAGS}
-)
+declare -a REPORTS
+
+for t in functional-tests/*; do
+ [[ -e "$t" ]] || break # handle the case of no test files
+
+ test=$(basename "$t")
+
+ robot --NoStatusRC \
+ --outputdir report_"${test}" \
+ functional-tests/"${test}"
+
+ REPORTS+=(report_"${test}"/output.xml)
+done
+
+rebot --output output.xml \
+ -l log.html -r report.html \
+ --nostatusrc \
+ "${REPORTS[@]}"
+
+popd || exit 1
diff --git a/hicn-light/src/hicn/command_line/daemon/CMakeLists.txt b/versions.cmake
index a86826f09..1ee36a0d4 100644
--- a/hicn-light/src/hicn/command_line/daemon/CMakeLists.txt
+++ b/versions.cmake
@@ -1,4 +1,4 @@
-# Copyright (c) 2017-2019 Cisco and/or its affiliates.
+# Copyright (c) 2023 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
@@ -11,20 +11,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-list(APPEND DAEMON_SRC
- hicnLightDaemon_main.c
-)
-
-if (WIN32)
- set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:\"LIBCMT\"")
-endif()
-
-if(NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Android")
- build_executable(${HICN_LIGHT_DAEMON}
- SOURCES ${DAEMON_SRC}
- LINK_LIBRARIES ${LIBHICN_LIGHT_STATIC}
- DEPENDS ${LIBHICN_LIGHT_STATIC}
- COMPONENT ${HICN_LIGHT}
- DEFINITIONS ${COMPILER_DEFINITIONS}
- )
-endif ()
+set(OPENSSL_DEFAULT_VERSION "1.1.1" "EXACT")
+set(LIBEVENT_DEFAULT_VERSION "2.1.11")
+set(ASIO_DEFAULT_VERSION "1.12.2")
+set(VPP_DEFAULT_VERSION "22.10.0" "EXACT")
+set(LIBMEMIF_DEFAULT_VERSION "22.10" "EXACT")
+set(LIBCONFIG_DEFAULT_VERSION "1.5.0")
+set(COLLECTD_DEFAULT_VERSION "5.9.2" "EXACT")
+set(RDKAFKA_DEFAULT_VERSION "1.8.2" "EXACT")
+set(ANDORID_SDK_DEP_DEFAULT_VERSION "2.1.2" "EXACT")
+set(IOS_TOOLCHAIN_DEP_DEFAULT_VERSION "1.0.2" "EXACT")