diff options
Diffstat (limited to 'ctrl')
114 files changed, 16372 insertions, 15652 deletions
diff --git a/ctrl/.clang-format b/ctrl/.clang-format new file mode 100644 index 000000000..2f629734d --- /dev/null +++ b/ctrl/.clang-format @@ -0,0 +1,15 @@ +# Copyright (c) 2021 Cisco and/or its affiliates. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at: +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +BasedOnStyle: Google +SortIncludes: false diff --git a/ctrl/CMakeLists.txt b/ctrl/CMakeLists.txt index 331ae9078..d6fe72d3e 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) +############################################################## +# Subdirectories +############################################################## +add_subdirectory(libhicnctrl) +if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux" OR "${CMAKE_SYSTEM_NAME}" STREQUAL "Android") + add_subdirectory(facemgr) endif ()
\ No newline at end of file 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..3fe049c06 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; + 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..fee38daf1 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,70 @@ #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, + 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); /* 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, + 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); /* Log */ @@ -107,57 +109,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, 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); #endif /* FACEMGR_CFG_H */ diff --git a/ctrl/facemgr/includes/hicn/facemgr/facelet.h b/ctrl/facemgr/includes/hicn/facemgr/facelet.h index cfdc5540e..d9c986731 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,62 @@ 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) +#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) +#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_event \ + _(UNDEFINED) \ + _(GET) \ + _(CREATE) \ + _(UPDATE) \ + _(DELETE) \ + _(SET_UP) \ + _(SET_DOWN) \ + _(N) #define MAXSZ_EVENT__ 10 #define MAXSZ_EVENT_ MAXSZ_EVENT_ + 1 @@ -212,37 +212,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 +251,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..d030abd1f 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,17 +21,9 @@ #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) @@ -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,421 @@ 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 */ + 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); + } - 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; - - interface_map_data_t * interface_map_data = NULL; +int facemgr_delete_interface(facemgr_t *facemgr, interface_t *interface) { + int rc; - DEBUG("Removing interface %s", interface->name); - rc = interface_map_remove(facemgr->interface_map, interface->name, &interface_map_data); - if (rc < 0) - return -1; + /* + * 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; - 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); - } + interface_map_data_t *interface_map_data = NULL; - free(interface_map_data); + DEBUG("Removing interface %s", interface->name); + rc = interface_map_remove(facemgr->interface_map, interface->name, + &interface_map_data); + if (rc < 0) return -1; - interface_finalize(interface); - interface_free(interface); + if (!interface_map_data) return -1; - 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); + } - DEBUG("sending event to bonjour interface"); + free(interface_map_data); - /* Send an event to the interface (GET ?) */ - // XXX error handling - return interface_on_event(bj, NULL); + interface_finalize(interface); + interface_free(interface); + + 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 +540,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 +579,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 +674,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 +747,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 +804,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)) { + 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(" - 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... + */ + 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"); + } 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; +int facemgr_complement_facelet(facemgr_t *facemgr, facelet_t *facelet) { + int rc; - DEBUG("[facemgr_complement_facelet]"); - if (!facelet_has_key(facelet)) - return -2; - -#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 +914,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 +967,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 +1073,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 +1178,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 +1407,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; + 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; + } } - 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 +1506,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 +1552,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 +1569,159 @@ 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"); + 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; } - /* 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 +1731,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; +int facemgr_on_event(facemgr_t *facemgr, facelet_t *facelet_in) { + bool remove_facelet = true; #if WITH_DUMP - bool dump = true; + 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 +1766,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; - 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; + 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; + 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("----------------------------------"); - } + 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..9c374388a 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,643 @@ /* 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; + ip_address_t local_addr; + bool is_remote_port; + uint16_t remote_port; + bool is_remote_addr; + 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]; + ip_address_snprintf(buf, MAXSZ_IP_ADDRESS, + &rule->override.overlays.v4->local_addr, AF_INET); + 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]; + 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.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]; + 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.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]; + 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) { - 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, + 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; - } - 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); } - 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); + 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; } + 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; +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; + } + 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]; + ip_address_snprintf(buf, MAXSZ_IP_ADDRESS, &overlay->local_addr, AF_INET); + DEBUG(" <local_addr>%s</local_addr>", buf); } - if (IS_VALID_PORT(local_port)) { - overlay->is_local_port = true; - overlay->local_port = local_port; + if (overlay->is_local_port) { + DEBUG(" <local_port>%d</local_port>", overlay->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; + 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); } - - 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 +661,476 @@ 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; + } + + 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; + } - if ((override) && (override->is_face_type)) { - *face_type = override->face_type; - return 0; - } - - *face_type = cfg->global.is_face_type - ? cfg->global.face_type - : FACEMGR_FACE_TYPE_DEFAULT; - - 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; - } - - *discovery = cfg->global.is_discovery - ? cfg->global.discovery - : FACEMGR_CFG_DEFAULT_DISCOVERY; - 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; + *override = NULL; - if ((override) && (override->is_ipv4)) { - *ipv4 = override->ipv4; - return 0; - } - - *ipv4 = cfg->global.is_ipv4 - ? cfg->global.ipv4 - : FACEMGR_CFG_DEFAULT_IPV4; - 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; +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_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; + *face_type = cfg->global.is_face_type ? cfg->global.face_type + : FACEMGR_FACE_TYPE_DEFAULT; - 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); - - return 0; + 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; - } +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; - *addr = IP_ADDRESS_EMPTY; + if ((override) && (override->is_discovery)) { + *discovery = override->discovery; 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; + *discovery = cfg->global.is_discovery ? cfg->global.discovery + : FACEMGR_CFG_DEFAULT_DISCOVERY; + 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; - } +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; - DEBUG("remote addr empty"); - *addr = IP_ADDRESS_EMPTY; + if ((override) && (override->is_ipv4)) { + *ipv4 = override->ipv4; 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; + *ipv4 = cfg->global.is_ipv4 ? cfg->global.ipv4 : FACEMGR_CFG_DEFAULT_IPV4; + 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; -} +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; -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; + if ((override) && (override->is_ipv6)) { + *ipv6 = override->ipv6; 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; + *ipv6 = cfg->global.is_ipv6 ? cfg->global.ipv6 : FACEMGR_CFG_DEFAULT_IPV6; + 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_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; -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; + if ((override) && (override->is_ignore)) { + *ignore = override->ignore; 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; -} + assert(!cfg->global.is_ignore); -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, 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, 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, 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, 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_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); } diff --git a/ctrl/facemgr/src/cfg_file.c b/ctrl/facemgr/src/cfg_file.c index cb1ded1c9..966e35816 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; + 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; } - /* - 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; + 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; } - - /* 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 (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; + 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; } - /* - 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)) { + ip_address_pton(remote_addr_str, &remote_addr); + remote_addr_p = &remote_addr; + } - } /* overlay */ + 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; + 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; - /* Add newly created rule */ + 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; + } - rc = facemgr_cfg_add_rule(cfg, rule); - if (rc < 0) - goto ERR; - } - return 0; + 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; + } + + } /* 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; + 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 (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; + 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; } - /* 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..2fda668c8 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 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.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,58 @@ /* Dump with indent */ #define INDENT(n, fmt) "%*s" fmt, n, "" -#define printfi(n, fmt, ...) printf(INDENT(n*4, fmt), ##__VA_ARGS__) +#define printfi(n, fmt, ...) printf(INDENT(n * 4, fmt), ##__VA_ARGS__) #define _unused(x) ((void)(x)) /* 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..609950f75 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,132 @@ 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->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; +facelet_t *facelet_create() { + facelet_t *facelet = calloc(1, sizeof(facelet_t)); + if (!facelet) goto ERR_MALLOC; + + 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; + facelet->priority_status = FACELET_ATTR_STATUS_UNSET; #endif /* WITH_POLICY */ - facelet->face_type_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 +166,339 @@ 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) { +#ifdef WITH_POLICY + 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; +#endif /* WITH_POLICY */ + 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; + /* 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->netdevice_status = FACELET_ATTR_STATUS_UNSET; + facelet->local_addr_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; + /* 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->netdevice_type = NETDEVICE_TYPE_UNDEFINED; - facelet->netdevice_type_status = FACELET_ATTR_STATUS_UNSET; + facelet->local_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 (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 : 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->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->remote_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 : 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->admin_state_status = FACELET_ATTR_STATUS_UNSET; + facelet->remote_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; - } else { - facelet->state_status = FACELET_ATTR_STATUS_UNSET; - } + } 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; + } #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; - } + /* 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; - } else { - facelet->face_type_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; + } - /* Status */ - facelet->status = FACELET_STATUS_CLEAN; - facelet->error = 0; + /* Status */ + facelet->status = FACELET_STATUS_CLEAN; + facelet->error = 0; - /* 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; - } + /* 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; + } - facelet->bj_done = false; - facelet->au_done = false; + facelet->bj_done = false; - facelet->event = FACELET_EVENT_UNDEFINED; + facelet->event = FACELET_EVENT_UNDEFINED; - /* 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; + /* 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; + 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"); + } 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 +508,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 +616,630 @@ 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); - - /* 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; - } +int facelet_get_face(const facelet_t *facelet, face_t **pface) { + assert(pface); - 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; - } - } else { - face->admin_state = FACE_STATE_UP; + /* 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_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->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; } + } else { + face->state = FACE_STATE_UP; + } #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; + /* 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; + } + + /* 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; + } + face->tags = tags; #endif /* WITH_POLICY */ - *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_unset_bj_done(facelet_t * facelet) -{ - facelet->bj_done = false; -} - -bool -facelet_is_bj_done(const facelet_t * facelet) -{ - return facelet->bj_done; -} +void facelet_set_bj_done(facelet_t *facelet) { facelet->bj_done = true; } -void -facelet_set_au_done(facelet_t * facelet) -{ - facelet->au_done = true; -} +void facelet_unset_bj_done(facelet_t *facelet) { facelet->bj_done = false; } -bool -facelet_is_au_done(const facelet_t * facelet) -{ - return facelet->au_done; -} +bool facelet_is_bj_done(const facelet_t *facelet) { return facelet->bj_done; } -facelet_event_t -facelet_get_event(const facelet_t * facelet) -{ - return facelet->event; +facelet_event_t facelet_get_event(const facelet_t *facelet) { + return facelet->event; } -void -facelet_set_event(facelet_t * facelet, facelet_event_t event) -{ - facelet->event = event; +void facelet_set_event(facelet_t *facelet, facelet_event_t event) { + facelet->event = event; } -int -facelet_add_route(facelet_t * facelet, hicn_route_t * route) -{ - return route_set_add(facelet->routes, route); +int facelet_add_route(facelet_t *facelet, hicn_route_t *route) { + return route_set_add(facelet->routes, route); } -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_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_clear_routes(facelet_t * facelet) -{ - return route_set_clear(facelet->routes); +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_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; +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); - - /* 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); - } + 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 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); - } + } 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); + } - /* 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); - } + /* 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 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); - } + 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); + } - /* 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); - } + /* 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 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); - } + /* 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); - /* 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); - } + 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); + } - /* 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); - } + /* 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); + } #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); - } + /* 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); - } - - /* Routes */ - rc = snprintf(cur, s + size - cur, " routes={ "); - if (rc < 0) - return rc; + /* 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); - - 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); - } + 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); + } + free(route_array); - rc = snprintf(cur, s + size - cur, "}>"); - 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); - return (int)(cur - s); + return (int)(cur - s); } -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; +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); - - /* 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); + + } 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); - - /* 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); + } + + /* 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); - - /* 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); + } + + /* 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); - - /* 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); - } + 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); - } + 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); - /* 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); - } + 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); - /* 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); - } + 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); - /* 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); - } + 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); - } + /* 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 (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); + if (cur >= s + size) return (int)(cur - s); + } - /* Routes */ - // TODO + /* 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); - rc = snprintf(cur, s + size - cur, "%*s%s", 4 * indent, "", "}"); - 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; + if (cur >= s + size) return (int)(cur - s); - return (int)(cur - s); + 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..4e084d76d --- /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; + } + + ip_address_t local_addr = IP_ADDRESS_EMPTY; + if (ip_address) { + if (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..90f18c299 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,357 @@ #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 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 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; } -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 = + 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; + } - 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: { + 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_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 +400,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, ¶m); + unsigned long param = 1; + ioctlsocket(sock, FIONBIO, ¶m); #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..b396782f5 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 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.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,8 +19,8 @@ */ #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/facemgr.h> @@ -38,578 +38,636 @@ #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] 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: + 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); } - -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; - } - - if (hc_sock_connect(data->s) < 0) { - DEBUG("[hc_connect] Could not connect control socket"); - goto ERR_CONNECT; - } - - return 0; - +/* + * 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(); + 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(); + 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; + hc_sock_free(data->s); + data->s = NULL; ERR_SOCK: - return -1; - + return -1; } -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_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 (data->poll_timer_fd > 0) - interface_unregister_timer(interface, data->poll_timer_fd); + stop_poll_timer(interface); - if (data->polled_routes) - hc_data_free(data->polled_routes); + if (data->polled_routes) hc_data_free(data->polled_routes); - if (data->s) { - interface_unregister_fd(interface, hc_sock_get_fd(data->s)); - hc_sock_free(data->s); - } + if (data->s) { + hc_sock_free(data->s); + data->s = NULL; + } - return 0; + if (data->sp) { + interface_unregister_fd(interface, hc_sock_get_fd(data->sp)); + hc_sock_free(data->sp); + data->sp = NULL; + } + + return 0; } -int -hl_connect(interface_t * interface) -{ - hl_data_t * data = interface->data; +/* 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); + 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; - } + /* 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; + 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; - } - - data->s = NULL; - data->reconnect_timer_fd = 0; - data->poll_timer_fd = 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; + } - interface->data = data; + 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 (hl_connect(interface) < 0) { - ERROR("[hl_initialize] Error during connection to forwarder"); - goto ERR_CONNECT; - } + interface->data = data; - data->polled_routes = NULL; + /* 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); + free(data); ERR_MALLOC: - return -1; + return -1; } -int hl_finalize(interface_t * interface) -{ - hl_data_t * data = (hl_data_t *) interface->data; +int hl_finalize(interface_t *interface) { + hl_data_t *data = (hl_data_t *)interface->data; - hl_disconnect(interface); + hl_disconnect(interface); - if (data->polled_routes) - hc_data_free(data->polled_routes); + if (data->polled_routes) hc_data_free(data->polled_routes); - free(data); + free(data); - return 0; + return 0; } -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; +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 (!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); + + 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 (!data->s) { - /* We are not connected to the forwarder */ - ret = -FACELET_ERROR_REASON_FORWARDER_OFFLINE; + 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; + } - 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); - } + 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; + } - 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("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, + .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); + + 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, 1); + if (rc < 0) { + ERROR("Failed to delete face\n"); + ret = -FACELET_ERROR_REASON_UNSPECIFIED_ERROR; + goto ERR; + } + + 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; + } - 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]); - } + 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; + 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; + } - default: - ERROR("Unknown event %s\n", facelet_event_str[facelet_get_event(facelet)]); - /* Unsupported events */ - ret = -FACELET_ERROR_REASON_INTERNAL_ERROR; + /* 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; + + 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_callback(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); - /* Process returned data */ - switch(data->state) { + hc_sock_free(data->s); + data->s = NULL; + hc_sock_free(data->sp); + data->sp = NULL; - case HL_STATE_ROUTES_SENT: - //DEBUG("[hl_callback] Processing routes"); - data->polled_routes = results; + hl_connect(interface); + return ret; + } + + /* Shall we wait for more data ? */ + if (!results->complete) { + INFO("[hl_callback] results incomplete"); + return ret; + } + + /* 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 +680,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 +702,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->face); + 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 +723,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; - } + 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..11738d7ac 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) { + 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; 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..3adba0969 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,144 +69,147 @@ /* 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) -{ + 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, "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_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); + 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); + dump_endpoint(remote, indent + 1); nw_release(remote); -} + } -void -dump_connection(nw_connection_t connection, int indent) -{ + 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); + dump_endpoint(remote, indent + 1); printfi(indent, "Path:\n"); - dump_path(path, indent+1); + dump_path(path, indent + 1); /* nw_connection_copy_protocol_metadata(); @@ -216,34 +218,34 @@ dump_connection(nw_connection_t connection, int indent) 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) -{ + 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; + 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; - }); -} + 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; + facelet_t *facelet_create_from_connection(nw_connection_t connection) { + facelet_t *facelet; ip_address_t local_addr, remote_addr; uint16_t remote_port; @@ -252,34 +254,36 @@ facelet_create_from_connection(nw_connection_t connection) 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; + 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); + 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); @@ -287,25 +291,24 @@ facelet_create_from_connection(nw_connection_t connection) 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; - + 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); @@ -313,8 +316,7 @@ facelet_create_from_connection(nw_connection_t connection) nw_release(path); facelet = facelet_create(); - if (!facelet) - return NULL; + if (!facelet) return NULL; facelet_set_netdevice(facelet, netdevice); facelet_set_netdevice_type(facelet, netdevice_type); @@ -324,20 +326,21 @@ facelet_create_from_connection(nw_connection_t connection) 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); - printf("NAME=%s\n", name); - return true; - }); + 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 @@ -346,84 +349,71 @@ on_connection_state_event(interface_t * interface, nw_interface_t iface, 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; - - case nw_connection_state_preparing: - break; - - case nw_connection_state_ready: - { - printf("info:\n"); - warn("connection ready"); + 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_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; + } + 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); - }); + WITH_DEBUG({ dump_connection(cnx, 1); }); #endif - /* redundant *//* - DEBUG(1, "Path:\n"); - dump_path(path, 2); - */ -} - -/** - * Enumerate main path interfaces - * - * We need to create specific dummy connections for each newly discovered - * interface - * - * 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) -{ + /* redundant */ /* + DEBUG(1, "Path:\n"); + dump_path(path, 2); + */ + } + + /** + * Enumerate main path interfaces + * + * We need to create specific dummy connections for each newly discovered + * interface + * + * 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 @@ -452,11 +442,10 @@ void on_interface_event(interface_t * interface, nw_interface_t iface) /* 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 */); + NW_PARAMETERS_DISABLE_PROTOCOL, /* no (d)tls */ + NW_PARAMETERS_DEFAULT_CONFIGURATION /* default udp/tcp */); - if (!parameters) - goto ERR_PARAMETERS; + if (!parameters) goto ERR_PARAMETERS; nw_parameters_require_interface(parameters, iface); nw_parameters_set_reuse_local_address(parameters, true); @@ -467,49 +456,60 @@ void on_interface_event(interface_t * interface, nw_interface_t iface) * 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); + 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; + 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_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); @@ -524,20 +524,20 @@ void on_interface_event(interface_t * interface, nw_interface_t iface) nw_endpoint_t endpoint; DEBUG("Creating bonjour service towards NAME=%s TYPE=%s DOMAIN=%s", - BONJOUR_SERVICE_NAME, BONJOUR_SERVICE_TYPE, BONJOUR_SERVICE_DOMAIN); + BONJOUR_SERVICE_NAME, BONJOUR_SERVICE_TYPE, BONJOUR_SERVICE_DOMAIN); endpoint = nw_endpoint_create_bonjour_service( - BONJOUR_SERVICE_NAME, - BONJOUR_SERVICE_TYPE, - BONJOUR_SERVICE_DOMAIN); + 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; + 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; + if (!connection) goto ERR_CONNECTION; nw_release(endpoint); nw_release(parameters); @@ -547,108 +547,98 @@ void on_interface_event(interface_t * interface, nw_interface_t iface) /* Setup connection handlers */ - 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_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); + on_connection_path_event(interface, iface, connection, path); }); 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) { #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_set_queue(connection, dispatch_get_main_queue()); - nw_retain(connection); // Hold a reference until cancelled + nw_retain(connection); // Hold a reference until cancelled #if 1 DEBUG("Created Bonjour cnx on interface:"); - WITH_DEBUG({ - dump_interface(iface, 1); - }); + WITH_DEBUG({ dump_interface(iface, 1); }); #endif return; - nw_release(connection); -ERR_CONNECTION: + nw_release(connection); + ERR_CONNECTION: nw_release(endpoint); -ERR_ENDPOINT: + ERR_ENDPOINT: #if defined(MAC_OS_X_VERSION_10_15) nw_release(descriptor); -ERR_DESCRIPTOR: + ERR_DESCRIPTOR: #endif /* defined(MAC_OS_X_VERSION_10_15) */ nw_release(parameters); -ERR_PARAMETERS: + ERR_PARAMETERS: return; -} + } -void on_path_event(interface_t * interface, nw_path_t path) -{ + 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); - }); + 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; + 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_cancel_handler(data->pm, ^(){ + }); nw_path_monitor_set_update_handler(data->pm, ^(nw_path_t path) { - on_path_event(interface, path); - }); + on_path_event(interface, path); + }); // XXX NEEDED ? nw_retain(data->pm); @@ -659,25 +649,24 @@ int nf_initialize(interface_t * interface, void * cfg) interface->data = data; return 0; -ERR_PM: + ERR_PM: free(data); -ERR_MALLOC: + ERR_MALLOC: return -1; -} + } -int nf_finalize(interface_t * interface) -{ - nf_data_t * data = (nf_data_t*)interface->data; + 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; + nw_path_monitor_cancel(data->pm); + data->pm = NULL; } return 0; -} - -const interface_ops_t network_framework_ops = { - .type = "network_framework", - .initialize = nf_initialize, - .finalize = nf_finalize, - .on_event = NULL, -}; + } + + const interface_ops_t network_framework_ops = { + .type = "network_framework", + .initialize = nf_initialize, + .finalize = nf_finalize, + .on_event = NULL, + }; 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..ed4540f5c 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: @@ -33,52 +33,36 @@ #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/create_face.c b/ctrl/libhicnctrl/examples/create_face.c index 5f92f5906..ebd451de1 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,122 @@ */ #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 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 main() { - char remote_ip_str[INET_ADDRSTRLEN] = "1.1.1.1"; + int fd = socket(AF_INET, SOCK_DGRAM, 0); - ip_address_t local_ip; - ip_address_t remote_ip; - char if_name[IFNAMSIZ]; + getifaddrs(&addrs); - /* Retrieving local info */ + 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 (get_local_info(if_name, &local_ip) < 0) { - DEBUG("Error getting local information"); - goto ERR_INIT; + snprintf(ifr.ifr_name, IFNAMSIZ, "%s", tmp->ifa_name); + if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) { + // perror("ioctl"); + continue; } - 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); + *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; - if (ip_address_pton (remote_ip_str, &remote_ip) < 0){ - DEBUG("Error parsing remote IP address"); - goto ERR_INIT; - } + ret = 0; + break; + } + + freeifaddrs(addrs); + close(fd); + return ret; +} - /* 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, +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]; + + /* 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]; + 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); + + if (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 = { + .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, + .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; - } + }, + }; + if (netdevice_set_name(&face.face.netdevice, if_name) < 0) { + DEBUG("Error setting face netdevice name"); + goto ERR_INIT; + } - /* Connecting to socket and creating face */ + /* Connecting to socket and creating face */ - hc_sock_t * socket = hc_sock_create(); - if (!socket){ - DEBUG("Error creating libhicnctrl socket"); - goto ERR_SOCK; - } + 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_sock_connect(socket) < 0) { + DEBUG("Error connecting to forwarder"); + goto ERR; + } - if (hc_face_create(socket, &face) < 0){ - DEBUG("Error creating face"); - goto ERR; - } + if (hc_face_create(socket, &face) < 0) { + DEBUG("Error creating face"); + goto ERR; + } - DEBUG("Face created successfully"); + DEBUG("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..bbe174c2f 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(); + 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..1a90690a4 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,24 @@ # 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/hicn-light.h + ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/hicn-light-ng.h ${CMAKE_CURRENT_SOURCE_DIR}/hicn/ctrl/route.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..477afd152 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: diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/api.h b/ctrl/libhicnctrl/includes/hicn/ctrl/api.h index b5a968800..8a59cf4d8 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 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -67,15 +67,24 @@ #include <stdbool.h> #include <stdint.h> +#include <stddef.h> // object_offset_t #include <hicn/util/ip_address.h> -#include <hicn/ctrl/commands.h> -#include "face.h" +#include <hicn/face.h> +#include <hicn/strategy.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 #define HICN_DEFAULT_PORT 9695 #define HOTFIXMARGIN 0 +#define INVALID_FACE_ID ~0 +#define INVALID_NETDEVICE_ID ~0 + /** * \brief Defines the default size for the allocated data arrays holding the * results of API calls. @@ -99,26 +108,70 @@ * Message helper types and aliases ******************************************************************************/ -#define foreach_command \ - _(UNDEFINED) \ - _(CREATE) \ - _(UPDATE) \ - _(DELETE) \ - _(LIST) \ - _(SET) \ +/* Action */ + +#define foreach_action \ + _(UNDEFINED) \ + _(CREATE) \ + _(UPDATE) \ + _(DELETE) \ + _(LIST) \ + _(SET) \ + _(SERVE) \ + _(STORE) \ + _(CLEAR) \ _(N) typedef enum { #define _(x) ACTION_##x, - foreach_command + 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); + +/* Object type */ + +#define foreach_object \ + _(UNDEFINED) \ + _(CONNECTION) \ + _(LISTENER) \ + _(ROUTE) \ + _(FACE) \ + _(STRATEGY) \ + _(PUNTING) \ + _(POLICY) \ + _(CACHE) \ + _(MAPME) \ + _(LOCAL_PREFIX) \ + _(PROBE) \ + _(SUBSCRIPTION) \ + _(N) + +typedef enum { +#define _(x) OBJECT_##x, + foreach_object +#undef _ +} hc_object_type_t; + +extern const char *object_str[]; + +#define object_str(x) object_str[x] + +hc_object_type_t object_from_str(const char *object_str); + +#define IS_VALID_OBJECT_TYPE(x) IS_VALID_ENUM_TYPE(OBJECT, x) +#define IS_VALID_ACTION(x) IS_VALID_ENUM_TYPE(ACTION, x) + /** * \brief hICN control message header */ typedef struct hc_msg_s hc_msg_t; - +typedef struct hc_result_s hc_result_t; /****************************************************************************** * Control Data ******************************************************************************/ @@ -140,7 +193,8 @@ typedef struct hc_data_s { bool complete; /* Callbacks */ - data_callback_t complete_cb; // XXX int (*complete_cb)(struct hc_data_s * data); + data_callback_t + complete_cb; // XXX int (*complete_cb)(struct hc_data_s * data); void *complete_cb_data; int ret; } hc_data_t; @@ -149,7 +203,8 @@ typedef struct hc_data_s { * 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); +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. @@ -214,38 +269,49 @@ int hc_data_reset(hc_data_t *data); * \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; \ -} +#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 +/* 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) \ + _(HICNLIGHT_NG) \ + _(VPP) \ + _(N) typedef enum { - HICNLIGHT, - VPP, - UNDEFINED -} forwarder_t; +#define _(x) x, + foreach_forwarder_type +#undef _ +} forwarder_type_t; /** * \brief Holds the state of an hICN control socket @@ -257,22 +323,26 @@ typedef struct hc_sock_s hc_sock_t; * \param [in] url - The URL to connect to. * \return an hICN control socket */ -hc_sock_t * -hc_sock_create_url(const char * url); +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); +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. * \return an hICN control socket */ -hc_sock_t * -hc_sock_create(void); +hc_sock_t *hc_sock_create(void); /** * \brief Frees an hICN control socket @@ -324,7 +394,7 @@ int hc_sock_get_available(hc_sock_t *s, u8 **buffer, size_t *size); * \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); +int hc_sock_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, uint32_t seq); /** * \brief Helper for reading socket contents @@ -356,6 +426,13 @@ int hc_sock_callback(hc_sock_t *s, hc_data_t **data); */ int hc_sock_reset(hc_sock_t *s); +void hc_sock_increment_woff(hc_sock_t *s, size_t bytes); + +int hc_sock_prepare_send(hc_sock_t *s, hc_result_t *result, + data_callback_t complete_cb, void *complete_cb_data); + +int hc_sock_set_recv_timeout_ms(hc_sock_t *s, long timeout_ms); + /****************************************************************************** * Command-specific structures and functions ******************************************************************************/ @@ -420,50 +497,11 @@ int hc_sock_reset(hc_sock_t *s); 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) - -typedef enum { -#define _(x) HC_CONNECTION_STATE_##x, - foreach_connection_state -#undef _ -} hc_connection_state_t; - -#define MAXSZ_HC_CONNECTION_STATE_ 9 -#define MAXSZ_HC_CONNECTION_STATE MAXSZ_HC_CONNECTION_STATE_ + NULLTERM - -extern const char *connection_state_str[]; - typedef int (*HC_PARSE)(const u8 *, u8 *); +#define INPUT_ERROR -2 +#define UNSUPPORTED_CMD_ERROR -3 + /*----------------------------------------------------------------------------* * Listeners *----------------------------------------------------------------------------*/ @@ -473,27 +511,28 @@ 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 */ + face_type_t type; /* .rw */ + int family; /* .rw */ + ip_address_t local_addr; /* .rw */ + u16 local_port; /* .rw */ } hc_listener_t; int hc_listener_create(hc_sock_t *s, hc_listener_t *listener); /* listener_found might eventually be allocated, and needs to be freed */ +hc_result_t *hc_listener_create_conf(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_list(hc_sock_t *s, hc_data_t **pdata); +hc_result_t *hc_listener_list_conf(hc_sock_t *s); 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_ + INTERFACE_LEN + SPACE + MAXSZ_URL_ + SPACE + MAXSZ_FACE_TYPE_ #define MAXSZ_HC_LISTENER MAXSZ_HC_LISTENER_ + NULLTERM GENERATE_FIND_HEADER(listener); @@ -506,28 +545,30 @@ int hc_listener_snprintf(char *s, size_t size, hc_listener_t *listener); /* * NOTE : - * - interface_name is mainly used to derive listeners from connections, but is - * not itself used to create connections. + * - 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 */ + face_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 */ + face_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. */ + uint32_t priority; /* .rw */ + policy_tags_t tags; /* .rw */ +#endif /* WITH_POLICY */ + face_state_t state; /* .r. */ } hc_connection_t; int hc_connection_create(hc_sock_t *s, hc_connection_t *connection); +hc_result_t *hc_connection_create_conf(hc_sock_t *s, + hc_connection_t *connection); /* connection_found will be allocated, and must be freed */ int hc_connection_get(hc_sock_t *s, hc_connection_t *connection, hc_connection_t **connection_found); @@ -536,6 +577,8 @@ int hc_connection_update_by_id(hc_sock_t *s, int hc_connection_id, 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); +hc_result_t *hc_connection_delete_conf(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); @@ -544,19 +587,21 @@ 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); +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); +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_FACE_STATE_ + INTERFACE_LEN + SPACE + 2 * MAXSZ_URL_ + \ + MAXSZ_FACE_TYPE_ + SPACES(3) #define MAXSZ_HC_CONNECTION MAXSZ_HC_CONNECTION_ + NULLTERM GENERATE_FIND_HEADER(connection); @@ -591,14 +636,17 @@ typedef struct { */ 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_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); +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); +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) @@ -609,7 +657,8 @@ int hc_face_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t #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_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); @@ -619,20 +668,20 @@ int hc_face_snprintf(char *s, size_t size, hc_face_t *face); *----------------------------------------------------------------------------*/ 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; + face_id_t face_id; /* Kr. use when name == NULL */ + char name[SYMBOLIC_NAME_LEN]; /* Kr. use by default vs face_id */ + int family; /* Krw */ + ip_address_t remote_addr; /* krw */ + u8 len; /* krw */ + u16 cost; /* .rw */ + hc_face_t face; /* TODO remove, used by hicn_plugin_api */ } 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_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); #define foreach_route(VAR, data) foreach_type(hc_route_t, VAR, data) @@ -646,6 +695,7 @@ int hc_route_list_async(hc_sock_t * s); #define MAXSZ_HC_ROUTE MAXSZ_HC_ROUTE_ + NULLTERM int hc_route_snprintf(char *s, size_t size, hc_route_t *route); +int hc_route_validate(const hc_route_t *route); /*----------------------------------------------------------------------------* * Punting @@ -653,9 +703,9 @@ int hc_route_snprintf(char *s, size_t size, hc_route_t *route); 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 */ + int family; /* Krw */ + ip_address_t prefix; /* krw */ + u8 prefix_len; /* krw */ } hc_punting_t; int hc_punting_create(hc_sock_t *s, hc_punting_t *punting); @@ -666,7 +716,6 @@ 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) @@ -681,8 +730,23 @@ 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); +typedef struct { + uint8_t serve; // 1 = on, 0 = off + uint8_t store; // 1 = on, 0 = off +} hc_cache_t; + +typedef struct { + bool store; + bool serve; + size_t cs_size; + size_t num_stale_entries; +} hc_cache_info_t; + +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); +int hc_cache_snprintf(char *s, size_t size, const hc_cache_info_t *cache_info); /*----------------------------------------------------------------------------* * Strategy @@ -691,7 +755,13 @@ int hc_cache_set_serve(hc_sock_t *s, int enabled); #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; + ip_address_t address, local_address; + int family, local_family; + u8 len, local_len; } hc_strategy_t; int hc_strategy_list(hc_sock_t *s, hc_data_t **data); @@ -704,8 +774,11 @@ 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); // per prefix -int hc_strategy_set(hc_sock_t *s /* XXX */); - +int hc_strategy_set(hc_sock_t *s, hc_strategy_t *strategy); +hc_result_t *hc_strategy_set_conf(hc_sock_t *s, hc_strategy_t *strategy); +int hc_strategy_add_local_prefix(hc_sock_t *s, hc_strategy_t *strategy); +hc_result_t *hc_strategy_add_local_prefix_conf(hc_sock_t *s, + hc_strategy_t *strategy); /*----------------------------------------------------------------------------* * WLDR *----------------------------------------------------------------------------*/ @@ -717,10 +790,45 @@ 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); +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 + + ip_address_t address; + int family; + u8 len; +} hc_mapme_t; + +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_send_update(hc_sock_t *s, hc_mapme_t *mapme); /*----------------------------------------------------------------------------* * Policies @@ -732,11 +840,9 @@ typedef struct { int family; /* Krw */ ip_address_t remote_addr; /* krw */ u8 len; /* krw */ - hicn_policy_t policy; /* .rw */ + 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); @@ -748,7 +854,114 @@ int hc_policy_list(hc_sock_t *s, hc_data_t **pdata); #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 /* WITH_POLICY */ +/*----------------------------------------------------------------------------* + * Subscription + *----------------------------------------------------------------------------*/ +// Topics + +#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 +#undef _ +} object_offset_t; + +// Flags for topic subscriptions +typedef enum { +#define _(x) TOPIC_##x = (1 << offsetof(object_offset_t, x)), + foreach_object +#undef _ +} hc_topic_t; + +static inline hc_object_type_t object_from_topic(hc_topic_t topic) { +#define _(x) \ + if (topic == TOPIC_##x) return OBJECT_##x; + foreach_object +#undef _ + return OBJECT_UNDEFINED; +} + +#define NUM_TOPICS OBJECT_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; + +int hc_subscription_create(hc_sock_t *s, hc_subscription_t *subscription); +int hc_subscription_delete(hc_sock_t *s, hc_subscription_t *subscription); +hc_result_t *hc_subscription_create_conf(hc_sock_t *s, + hc_subscription_t *subscription); +hc_result_t *hc_subscription_delete_conf(hc_sock_t *s, + hc_subscription_t *subscription); + +/*----------------------------------------------------------------------------* + * Events + *----------------------------------------------------------------------------*/ +#define foreach_event_type \ + _(UNDEFINED) \ + _(INTERFACE_UPDATE) \ + _(N) +typedef enum { +#define _(x) EVENT_##x, + foreach_event_type +#undef _ +} event_type_t; + +extern const char *event_str[]; +#define event_str(x) event_str[x] + +typedef enum { + FLAG_INTERFACE_TYPE_WIRED = 0x1, + FLAG_INTERFACE_TYPE_WIFI = 0x2, + FLAG_INTERFACE_TYPE_CELLULAR = 0x4, +} flag_interface_type_t; + +typedef struct { + flag_interface_type_t interface_type; +} hc_event_interface_update_t; + +/* Result */ + +hc_msg_t *hc_result_get_msg(hc_sock_t *s, hc_result_t *result); +int hc_result_get_cmd_id(hc_sock_t *s, hc_result_t *result); +bool hc_result_get_success(hc_sock_t *s, hc_result_t *result); +void hc_result_free(hc_result_t *result); + +/* Object */ + +typedef struct { + hc_object_type_t type; + 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_strategy_t strategy; +#ifdef WITH_POLICY + hc_policy_t policy; +#endif /* WITH_POLICY */ + hc_subscription_t subscription; + hc_cache_t cache; + hc_mapme_t mapme; + uint8_t as_uint8; + }; +} hc_object_t; + +typedef struct { + hc_action_t action; + hc_object_t object; +} hc_command_t; + #endif /* HICNTRL_API */ 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/hicn-light-ng.h b/ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light-ng.h new file mode 100644 index 000000000..7d105a84b --- /dev/null +++ b/ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light-ng.h @@ -0,0 +1,427 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 HICN_CTRL_HICNLIGHTNG_H +#define HICN_CTRL_HICNLIGHTNG_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> + +#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_set_admin_state, CONNECTION_SET_ADMIN_STATE) \ + _(connection_update, CONNECTION_UPDATE) \ + _(connection_set_priority, CONNECTION_SET_PRIORITY) \ + _(connection_set_tags, CONNECTION_SET_TAGS) \ + _(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_send_update, MAPME_SEND_UPDATE) \ + _(policy_add, POLICY_ADD) \ + _(policy_remove, POLICY_REMOVE) \ + _(policy_list, POLICY_LIST) \ + _(subscription_add, SUBSCRIPTION_ADD) \ + _(subscription_remove, SUBSCRIPTION_REMOVE) + +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]; + 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; + +// Sync this struct with `hc_listener_t` in `api.h` +typedef struct { + char name[SYMBOLIC_NAME_LEN]; + char interface_name[SYMBOLIC_NAME_LEN]; + uint32_t id; + uint8_t type; + uint8_t family; + ip_address_t address; + uint16_t port; +} cmd_listener_list_item_t; + +/* Connection */ + +typedef struct { + char symbolic[SYMBOLIC_NAME_LEN]; + // char interface_name[SYMBOLIC_NAME_LEN]; + ip_address_t remote_ip; + ip_address_t local_ip; + uint16_t remote_port; + uint16_t local_port; + uint8_t family; + uint8_t type; + uint8_t admin_state; +#ifdef WITH_POLICY + uint32_t priority; + policy_tags_t tags; +#endif /* WITH_POLICY */ +} cmd_connection_add_t; + +typedef struct { + char symbolic_or_connid[SYMBOLIC_NAME_LEN]; +} cmd_connection_remove_t; + +typedef struct { + void *_; +} cmd_connection_list_t; + +// Sync this struct with `hc_connection_t` in `api.h` +typedef struct { + uint32_t id; + char name[SYMBOLIC_NAME_LEN]; + char interface_name[SYMBOLIC_NAME_LEN]; + uint8_t type; + uint8_t family; + ip_address_t local_addr; + uint16_t local_port; + ip_address_t remote_addr; + uint16_t remote_port; + uint8_t admin_state; +#ifdef WITH_POLICY + uint32_t priority; + policy_tags_t tags; +#endif /* WITH_POLICY */ + uint8_t state; +} cmd_connection_list_item_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; +#ifdef WITH_POLICY + uint32_t priority; + policy_tags_t tags; +#endif /* WITH_POLICY */ +} 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]; + 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]; + ip_address_t address; + uint8_t family; + uint8_t len; +} cmd_route_remove_t; + +typedef struct { + void *_; +} cmd_route_list_t; + +// Sync this struct with `hc_route_t` in `api.h` +typedef struct { + ip_address_t address; + uint32_t connection_id; + uint16_t cost; + uint8_t family; + uint8_t len; +} cmd_route_list_item_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 { + ip_address_t address; + uint8_t family; + uint8_t len; + uint8_t type; + uint8_t related_prefixes; + union { + struct { + 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; + ip_address_t address; + uint8_t family; + uint8_t len; + 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]; + 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 { + void *_; +} cmd_mapme_send_update_t; + +/* Policy */ + +typedef struct { + ip_address_t address; + uint8_t family; + uint8_t len; + hicn_policy_t policy; +} cmd_policy_add_t; + +typedef struct { + ip_address_t address; + uint8_t family; + uint8_t len; +} cmd_policy_remove_t; + +typedef struct { + void *_; +} cmd_policy_list_t; + +typedef struct { + ip_address_t address; + uint8_t family; + uint8_t len; + hicn_policy_t policy; +} cmd_policy_list_item_t; + +/* Subscription */ + +typedef struct { + uint32_t topics; +} cmd_subscription_add_t; + +typedef struct { + uint32_t topics; +} cmd_subscription_remove_t; + +/* Full messages */ + +#define _(l, u) \ + typedef struct { \ + cmd_header_t header; \ + cmd_##l##_t payload; \ + } msg_##l##_t; +foreach_command_type +#undef _ + + typedef struct { + cmd_header_t header; + cmd_listener_list_item_t payload; +} msg_listener_list_reply_t; + +typedef struct { + cmd_header_t header; + cmd_connection_list_item_t payload; +} msg_connection_list_reply_t; + +typedef struct { + cmd_header_t header; + cmd_route_list_item_t payload; +} msg_route_list_reply_t; + +typedef struct { + cmd_header_t header; + cmd_policy_list_item_t payload; +} msg_policy_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; + } +} +#endif /* HICN_CTRL_HICNLIGHTNG_H */ diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/commands.h b/ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light.h index 3758f0f41..69ede1985 100644 --- a/ctrl/libhicnctrl/includes/hicn/ctrl/commands.h +++ b/ctrl/libhicnctrl/includes/hicn/ctrl/hicn-light.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,8 +20,8 @@ * Header and payload in binary format. */ -#ifndef commands_h -#define commands_h +#ifndef HICN_CTRL_HICNLIGHT_H +#define HICN_CTRL_HICNLIGHT_H #ifndef _WIN32 #include <netinet/in.h> @@ -43,7 +43,7 @@ typedef struct in6_addr ipv6_addr_t; typedef uint32_t ipv4_addr_t; typedef enum { - REQUEST_LIGHT = 0xc0, // this is a command + REQUEST_LIGHT = 0xc0, // this is a command RESPONSE_LIGHT, ACK_LIGHT, NACK_LIGHT, @@ -133,7 +133,7 @@ typedef struct { typedef struct { char symbolic[SYMBOLIC_NAME_LEN]; - //char interfaceName[SYMBOLIC_NAME_LEN]; + // char interfaceName[SYMBOLIC_NAME_LEN]; ip_address_t remoteIp; ip_address_t localIp; uint16_t remotePort; @@ -415,7 +415,7 @@ static inline int payloadLengthDaemon(command_id id) { case ADD_POLICY: return sizeof(add_policy_command); case LIST_POLICIES: - return 0; // list policies: payload always 0 + return 0; // list policies: payload always 0 case REMOVE_POLICY: return sizeof(remove_policy_command); case UPDATE_CONNECTION: @@ -431,4 +431,4 @@ static inline int payloadLengthDaemon(command_id id) { return 0; } } -#endif +#endif /* HICN_CTRL_HICNLIGHT_H */ diff --git a/ctrl/libhicnctrl/includes/hicn/ctrl/route.h b/ctrl/libhicnctrl/includes/hicn/ctrl/route.h index d7ef6a26f..81f011d4d 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(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, ip_prefix_t* prefix); +int hicn_route_set_prefix(hicn_route_t* route, const 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/src/CMakeLists.txt b/ctrl/libhicnctrl/src/CMakeLists.txt index f9934d70e..c8a93c56c 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-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,80 +11,127 @@ # 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 + route.c + api.c ) set(HEADER_FILES - api_private.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 () + +############################################################## +# Do not use modules if Android +############################################################## if (${CMAKE_SYSTEM_NAME} MATCHES Android) - list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light_api.c - ) + list(APPEND SOURCE_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light_common.c + ${CMAKE_CURRENT_SOURCE_DIR}/modules/hicn_light_ng_api.c + ) else() - add_subdirectory(modules) + add_subdirectory(modules) endif() + +############################################################## +# Compiler options +############################################################## +set(COMPILER_OPTIONS + ${DEFAULT_COMPILER_OPTIONS} +) + + +############################################################## +# 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} +) + + +############################################################## +# 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/api.c b/ctrl/libhicnctrl/src/api.c index 4bb66c784..4156ceff9 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 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.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,22 +18,26 @@ * \brief Implementation of hICN control library API */ +#include <assert.h> +#include <dlfcn.h> // dlopen +#include <hicn/strategy.h> #include <hicn/util/log.h> -#include "api_private.h" +#include <hicn/ctrl/route.h> +#include <math.h> // log2 -#include <math.h> // log2 -#include <dlfcn.h> // dlopen +#include "api_private.h" +#if 0 /* /!\ Please update constants in public header file upon changes */ const char * connection_state_str[] = { -#define _(x) [HC_CONNECTION_STATE_ ## x] = STRINGIZE(x), +#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), +#define _(x) [CONNECTION_TYPE_##x] = STRINGIZE(x), foreach_connection_type #undef _ }; @@ -48,151 +52,72 @@ connection_type_from_str(const char * str) else if (strcasecmp(str, "HICN") == 0) return CONNECTION_TYPE_HICN; else - return CONNECTION_TYPE_UNDEFINED; + 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, -}; +#endif /****************************************************************************** * 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; +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; + data->current = 0; + + return data; ERR_BUFFER: - hc_data_free(data); + hc_data_free(data); ERR_MALLOC: - return NULL; + return NULL; } -void -hc_data_free(hc_data_t * data) -{ - if (data->buffer) - free(data->buffer); - free(data); +void hc_data_free(hc_data_t *data) { + if (data) 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; - } +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; + return 0; } -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; +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; - memcpy(data->buffer + data->size * data->out_element_size, elements, - count * data->out_element_size); - data->size += count; + memcpy(data->buffer + data->size * data->out_element_size, elements, + count * data->out_element_size); + data->size += count; - return 0; + return 0; } -int -hc_data_push(hc_data_t * data, const void * element) -{ - return hc_data_push_many(data, element, 1); +int hc_data_push(hc_data_t *data, const void *element) { + return hc_data_push_many(data, element, 1); } /** @@ -200,61 +125,48 @@ hc_data_push(hc_data_t * data, const void * element) * 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; +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; + 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; +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; } -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; +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; } -int -hc_data_set_error(hc_data_t * data) -{ - data->ret = -1; - return 0; +int hc_data_set_error(hc_data_t *data) { + data->ret = -1; + return 0; } -int -hc_data_reset(hc_data_t * data) -{ - data->size = 0; - return 0; +int hc_data_reset(hc_data_t *data) { + data->size = 0; + return 0; } -static hc_sock_t * _open_module(const char *name) -{ +static hc_sock_t *_open_module(const char *name, const char *url) { char complete_name[128]; #ifdef __APPLE__ - sprintf(complete_name, "%s.dylib", name); + snprintf(complete_name, 128, "%s.dylib", name); #elif defined(__linux__) - sprintf(complete_name, "%s.so", name); + snprintf(complete_name, 128, "%s.so", name); #else - #error "System not supported for dynamic lynking" +#error "System not supported for dynamic lynking" #endif void *handle = 0; const char *error = 0; - hc_sock_t *(*creator)(void) = 0; + hc_sock_t *(*creator)(const char *) = 0; hc_sock_t *ret = 0; // open module @@ -263,307 +175,305 @@ static hc_sock_t * _open_module(const char *name) if ((error = dlerror()) != 0) { ERROR("%s", error); } - return 0; } // get factory method - creator = (hc_sock_t * (*)(void)) dlsym(handle, "_hc_sock_create"); + creator = + (hc_sock_t * (*)(const char *)) dlsym(handle, "_hc_sock_create_url"); if (!creator) { if ((error = dlerror()) != 0) { ERROR("%s", error); - return 0; } + return 0; } - ret = (*creator)(); + ret = (*creator)(NULL); 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; - } +hc_sock_t *hc_sock_create_forwarder_url(forwarder_type_t forwarder, + const char *url) { + switch (forwarder) { + case HICNLIGHT: + return _open_module("hicnlightctrl_module", url); + case HICNLIGHT_NG: + return _open_module("hicnlightngctrl_module", url); + case VPP: + return _open_module("vppctrl_module", url); + default: + return NULL; + } } #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(); +extern hc_sock_t *_hc_sock_create_url(const char *url); #endif -hc_sock_t *hc_sock_create(void) -{ +hc_sock_t *hc_sock_create_forwarder(forwarder_type_t forwarder) { #ifdef ANDROID - hc_sock_t *ret = _hc_sock_create(); - ret->handle = NULL; - return ret; + assert(forwarder == HICNLIGHT_NG); + hc_sock_t *ret = _hc_sock_create_url(NULL); + ret->handle = NULL; + return ret; #else - return hc_sock_create_forwarder(HICNLIGHT); + return hc_sock_create_forwarder_url(forwarder, NULL); #endif } -void hc_sock_free(hc_sock_t *s) -{ - void *handle = s->handle; - s->hc_sock_free(s); - - if (handle) { - dlclose(handle); - } +hc_sock_t *hc_sock_create(void) { + return hc_sock_create_forwarder(HICNLIGHT_NG); } -int hc_sock_get_next_seq(hc_sock_t *s) -{ - return s->hc_sock_get_next_seq(s); -} +void hc_sock_free(hc_sock_t *s) { + void *handle = s->handle; + s->hc_sock_free(s); -int hc_sock_set_nonblocking(hc_sock_t *s) -{ - return s->hc_sock_get_next_seq(s); + if (handle) { + dlclose(handle); + } } -int hc_sock_get_fd(hc_sock_t *s) -{ - return s->hc_sock_get_fd(s); +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_connect(hc_sock_t *s) -{ - return s->hc_sock_connect(s); +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_get_available(hc_sock_t *s, u8 **buffer, size_t *size) -{ - return s->hc_sock_get_available(s, buffer, size); +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_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_callback(hc_sock_t *s, hc_data_t **data) { + return s->hc_sock_callback(s, data); } -int hc_sock_recv(hc_sock_t *s) -{ - return s->hc_sock_recv(s); +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_process(hc_sock_t *s, hc_data_t **data) -{ - return s->hc_sock_process(s, data); +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_callback(hc_sock_t *s, hc_data_t **data) -{ - return s->hc_sock_callback(s, 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); } -int hc_sock_reset(hc_sock_t *s) -{ - return s->hc_sock_reset(s); +/*----------------------------------------------------------------------------* + * LISTENER + *----------------------------------------------------------------------------*/ + +int hc_listener_create(hc_sock_t *s, hc_listener_t *listener) { + return s->hc_listener_create(s, listener); } -int hc_listener_create(hc_sock_t *s, hc_listener_t *listener) -{ - return s->hc_listener_create(s, listener); +hc_result_t *hc_listener_create_conf(hc_sock_t *s, hc_listener_t *listener) { + return s->hc_listener_create_conf(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); + 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_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); +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; +int hc_listener_validate(const hc_listener_t *listener) { + if (!IS_VALID_NAME(listener->name)) { + ERROR("[hc_listener_validate] Invalid name specified"); + return -1; + } + if (!IS_VALID_INTERFACE_NAME(listener->interface_name)) { + ERROR("[hc_listener_validate] Invalid interface_name specified"); + return -1; + } + if (!IS_VALID_TYPE(listener->type)) { + ERROR("[hc_listener_validate] Invalid type specified"); + return -1; + } + if (!IS_VALID_FAMILY(listener->family)) { + ERROR("[hc_listener_validate] Invalid family specified"); + return -1; + } + if (!IS_VALID_ADDRESS(&listener->local_addr, listener->family)) { + ERROR("[hc_listener_validate] Invalid local_addr specified"); + return -1; + } + if (!IS_VALID_PORT(listener->local_port)) { + ERROR("[hc_listener_validate] Invalid local_port specified"); + return -1; + } - return 0; + 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; +int hc_listener_cmp(const hc_listener_t *l1, const hc_listener_t *l2) { + int rc; - rc = strncmp(l1->interface_name, l2->interface_name, INTERFACE_LEN); - if (rc != 0) - return rc; + rc = INT_CMP(l1->type, l2->type); + 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->family, l2->family); + if (rc != 0) return rc; - rc = INT_CMP(l1->local_port, l2->local_port); - if (rc != 0) - return rc; + rc = strncmp(l1->interface_name, l2->interface_name, INTERFACE_LEN); + if (rc != 0) return rc; - return rc; -} + rc = ip_address_cmp(&l1->local_addr, &l2->local_addr, l1->family); + if (rc != 0) return rc; -/* LISTENER PARSE */ + rc = INT_CMP(l1->local_port, l2->local_port); + if (rc != 0) return rc; -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; + return rc; } /* 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; +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]); + return snprintf(s, size, "%s %s %s interface=%s", listener->name, local, + face_type_str(listener->type), listener->interface_name); } -int hc_connection_create(hc_sock_t *s, hc_connection_t *connection) -{ - return s->hc_connection_create(s, connection); +/*----------------------------------------------------------------------------* + * CONNECTION + *----------------------------------------------------------------------------*/ + +int hc_connection_create(hc_sock_t *s, hc_connection_t *connection) { + return s->hc_connection_create(s, connection); +} + +hc_result_t *hc_connection_create_conf(hc_sock_t *s, + hc_connection_t *connection) { + return s->hc_connection_create_conf(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); + 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); + 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); + 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_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); +hc_result_t *hc_connection_delete_conf(hc_sock_t *s, + hc_connection_t *connection) { + return s->hc_connection_delete_conf(s, connection); } -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); +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_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); +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 +#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; - - /* TODO assert both local and remote have the right family */ +int hc_connection_validate(const hc_connection_t *connection) { + if (!IS_VALID_NAME(connection->name)) { + ERROR("[hc_connection_validate] Invalid name specified"); + return -1; + } + if (!IS_VALID_INTERFACE_NAME(connection->interface_name)) { + ERROR("[hc_connection_validate] Invalid interface_name specified"); + return -1; + } + if (!IS_VALID_TYPE(connection->type)) { + ERROR("[hc_connection_validate] Invalid type specified"); + return -1; + } + if (!IS_VALID_FAMILY(connection->family)) { + ERROR("[hc_connection_validate] Invalid family specified"); + return -1; + } + if (!IS_VALID_ADDRESS(&connection->local_addr, connection->family)) { + ERROR("[hc_connection_validate] Invalid local_addr specified"); + return -1; + } + if (!IS_VALID_PORT(connection->local_port)) { + ERROR("[hc_connection_validate] Invalid local_port specified"); + return -1; + } + if (!IS_VALID_ADDRESS(&connection->remote_addr, connection->family)) { + ERROR("[hc_connection_validate] Invalid remote_addr specified"); + return -1; + } + if (!IS_VALID_PORT(connection->remote_port)) { + ERROR("[hc_connection_validate] Invalid remote_port specified"); + return -1; + } - return 0; + return 0; } /* CONNECTION CMP */ @@ -573,719 +483,692 @@ hc_connection_validate(const hc_connection_t * connection) * 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; +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->type, c2->type); + if (rc != 0) return rc; - rc = INT_CMP(c1->family, c2->family); - 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 = 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 = 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 = 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 = 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; + 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; - - 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; + return rc; } /* 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_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->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", connection->name, local, remote, + face_type_str(connection->type)); } -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_create(hc_sock_t *s, hc_face_t *face) { + return s->hc_face_create(s, face); } -int hc_face_delete(hc_sock_t *s, hc_face_t *face) -{ - return s->hc_face_delete(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_list(hc_sock_t *s, hc_data_t **pdata) -{ - return s->hc_face_list(s, pdata); +int hc_face_delete(hc_sock_t *s, hc_face_t *face, uint8_t delete_listener) { + return s->hc_face_delete(s, face, delete_listener); } -int hc_face_list_async(hc_sock_t *s) -{ - return s->hc_face_list_async(s); +int hc_face_list(hc_sock_t *s, hc_data_t **pdata) { + return s->hc_face_list(s, pdata); } -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); +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_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); +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]; +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]; + 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; - } + 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); + 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]); + 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; - } +/*----------------------------------------------------------------------------* + * ROUTE + *----------------------------------------------------------------------------*/ - 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_create(hc_sock_t * s, hc_route_t * route) -{ - return s->hc_route_create(s, route); +hc_result_t *hc_route_create_conf(hc_sock_t *s, hc_route_t *route) { + return s->hc_route_create_conf(s, route); } -int hc_route_delete(hc_sock_t * s, hc_route_t * route) -{ - return s->hc_route_delete(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(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); -} +int hc_route_list_async(hc_sock_t *s) { return s->hc_route_list_async(s); } -/* ROUTE PARSE */ +/* ROUTE SNPRINTF */ -int -hc_route_parse(void * in, hc_route_t * route) -{ - list_routes_command * cmd = (list_routes_command *) in; +/* /!\ 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 */ - if (!IS_VALID_ADDR_TYPE(cmd->addressType)) { - ERROR("[hc_route_parse] Invalid address type"); - return -1; - } + char prefix[MAXSZ_IP_ADDRESS]; + int rc; - int family = map_from_addr_type[cmd->addressType]; - if (!IS_VALID_FAMILY(family)) { - ERROR("[hc_route_parse] Invalid address family"); - return -1; - } + rc = ip_address_snprintf(prefix, MAXSZ_IP_ADDRESS, &route->remote_addr, + route->family); + if (rc >= MAXSZ_IP_ADDRESS) + ; + if (rc < 0) return rc; - *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; + return snprintf(s, size, "%s %*d %s %*d conn_id=%d", route->name, MAXSZ_COST, + route->cost, prefix, MAXSZ_LEN, route->len, route->face_id); } -/* 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; +int hc_route_validate(const hc_route_t *route) { + if (!IS_VALID_ID(route->connection_id)) { + ERROR("[hc_route_validate] Invalid connection id"); + return -1; + } + if (!IS_VALID_NAME(route->name) && !IS_VALID_STR_ID(route->name)) { + ERROR("[hc_route_validate] Invalid name specified"); + return -1; + } + if (!IS_VALID_FAMILY(route->family)) { + ERROR("[hc_route_validate] Invalid family specified"); + return -1; + } + if (!IS_VALID_ADDRESS(&route->remote_addr, route->family)) { + ERROR("[hc_route_validate] Invalid remote_addr specified"); + return -1; + } + if (!IS_VALID_ROUTE_COST(route->cost)) { + ERROR("[hc_route_validate] Invalid cost"); + return -1; + } + if (!IS_VALID_PREFIX_LEN(route->len)) { + ERROR("[hc_route_validate] Invalid len"); + return -1; + } - return snprintf(s, size, "%*d %*d %s %*d", MAXSZ_FACE_ID, route->face_id, - MAXSZ_COST, route->cost, prefix, MAXSZ_LEN, route->len); + return 0; } +/*----------------------------------------------------------------------------* + * FACE + *----------------------------------------------------------------------------*/ + /* 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; - } - return -1; /* XXX Not implemented */ +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; + } + 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 */ +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), +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 = FACE_TYPE_HICN, + .family = f->family, + .local_addr = f->local_addr, + .local_port = 0, + .remote_addr = f->remote_addr, + .remote_port = 0, + .admin_state = f->admin_state, + .state = f->state, #ifdef WITH_POLICY - .priority = f->priority, - .tags = f->tags, + .priority = f->priority, + .tags = f->tags, #endif /* WITH_POLICY */ - }; - rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "%s", + }; + 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), + 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 = f->family, + .local_addr = f->local_addr, + .local_port = f->local_port, + .remote_addr = f->remote_addr, + .remote_port = f->remote_port, + .admin_state = f->admin_state, + .state = f->state, #ifdef WITH_POLICY - .priority = f->priority, - .tags = f->tags, + .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), + }; + 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 = f->family, + .local_addr = f->local_addr, + .local_port = f->local_port, + .remote_addr = f->remote_addr, + .remote_port = f->remote_port, + .admin_state = f->admin_state, + .state = f->state, #ifdef WITH_POLICY - .priority = f->priority, - .tags = f->tags, + .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; - } + }; + 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; + } - 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"); + connection->id = face->id; + 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; } /* 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), +int hc_connection_to_face(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, + .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->admin_state, + .state = connection->state, #ifdef WITH_POLICY - .priority = connection->priority, - .tags = connection->tags, + .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), + }, + }; + break; + case FACE_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->admin_state, + .state = connection->state, #ifdef WITH_POLICY - .priority = connection->priority, - .tags = connection->tags, + .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), + }, + }; + break; + case FACE_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->admin_state, + .state = connection->state, #ifdef WITH_POLICY - .priority = connection->priority, - .tags = connection->tags, + .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; + }, + }; + 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; } /* 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"); +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; + } - return 0; + *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; +} + +/*----------------------------------------------------------------------------* + * Punting + *----------------------------------------------------------------------------*/ + +int hc_punting_create(hc_sock_t *s, hc_punting_t *punting) { + return s->hc_punting_create(s, punting); } -int hc_punting_create(hc_sock_t *s, hc_punting_t *punting) -{ - return s->hc_punting_create(s, punting); +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); } -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); +int hc_punting_delete(hc_sock_t *s, hc_punting_t *punting) { + return s->hc_punting_delete(s, punting); } -int hc_punting_delete(hc_sock_t *s, hc_punting_t *punting) -{ - return s->hc_punting_delete(s, punting); +int hc_punting_list(hc_sock_t *s, hc_data_t **pdata) { + return s->hc_punting_list(s, pdata); } -int hc_punting_list(hc_sock_t *s, hc_data_t **pdata) -{ - return s->hc_punting_list(s, pdata); +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; + } + + return 0; } -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_punting_cmp(const hc_punting_t *p1, const hc_punting_t *p2) { + int rc; - return 0; + 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_cmp(const hc_punting_t * p1, const hc_punting_t * p2) -{ - int rc; +int hc_punting_parse(void *in, hc_punting_t *punting) { + ERROR("hc_punting_parse not (yet) implemented."); + return -1; +} - rc = INT_CMP(p1->face_id, p2->face_id); - if (rc != 0) - return rc; +int hc_punting_snprintf(char *s, size_t size, hc_punting_t *punting) { + ERROR("hc_punting_snprintf not (yet) implemented."); + return -1; +} - rc = INT_CMP(p1->family, p2->family); - if (rc != 0) - return rc; +/*----------------------------------------------------------------------------* + * Cache + *----------------------------------------------------------------------------*/ - rc = ip_address_cmp(&p1->prefix, &p2->prefix, p1->family); - if (rc != 0) - return rc; +int hc_cache_set_store(hc_sock_t *s, hc_cache_t *cache) { + return s->hc_cache_set_store(s, cache); +} - rc = INT_CMP(p1->prefix_len, p2->prefix_len); - if (rc != 0) - return rc; +int hc_cache_set_serve(hc_sock_t *s, hc_cache_t *cache) { + return s->hc_cache_set_serve(s, cache); +} - return rc; +int hc_cache_clear(hc_sock_t *s, hc_cache_t *cache) { + return s->hc_cache_clear(s, cache); } -int hc_punting_parse(void * in, hc_punting_t * punting) -{ - ERROR("hc_punting_parse not (yet) implemented."); - return -1; +int hc_cache_list(hc_sock_t *s, hc_data_t **pdata) { + return s->hc_cache_list(s, pdata); } -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_snprintf(char *s, size_t size, const hc_cache_info_t *cache_info) { + return snprintf( + s, size, "Cache set_store=%s set_serve=%s size=%lu stale_entries=%lu", + cache_info->store ? "true" : "false", + cache_info->serve ? "true" : "false", (unsigned long)cache_info->cs_size, + (unsigned long)cache_info->num_stale_entries); } -int hc_cache_set_store(hc_sock_t *s, int enabled) -{ - return s->hc_cache_set_store(s, enabled); +/*----------------------------------------------------------------------------* + * Strategy + *----------------------------------------------------------------------------*/ + +int hc_strategy_list(hc_sock_t *s, hc_data_t **data) { + return s->hc_strategy_list(s, data); } -int hc_cache_set_serve(hc_sock_t *s, int enabled) -{ - return s->hc_cache_set_serve(s, enabled); +int hc_strategy_set(hc_sock_t *s, hc_strategy_t *strategy) { + return s->hc_strategy_set(s, strategy); } -int hc_strategy_list(hc_sock_t *s, hc_data_t **data) -{ - return s->hc_strategy_list(s, data); +int hc_strategy_add_local_prefix(hc_sock_t *s, hc_strategy_t *strategy) { + return s->hc_strategy_add_local_prefix(s, strategy); } -int hc_strategy_set(hc_sock_t *s /* XXX */) -{ - return s->hc_strategy_set(s); +hc_result_t *hc_strategy_set_conf(hc_sock_t *s, hc_strategy_t *strategy) { + return s->hc_strategy_set_conf(s, strategy); +} + +hc_result_t *hc_strategy_add_local_prefix_conf(hc_sock_t *s, + hc_strategy_t *strategy) { + return s->hc_strategy_add_local_prefix_conf(s, strategy); } /* /!\ 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_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); +/*----------------------------------------------------------------------------* + * WLDR + *----------------------------------------------------------------------------*/ + +int hc_wldr_set(hc_sock_t *s /* XXX */) { return s->hc_wldr_set(s); } + +/*----------------------------------------------------------------------------* + * MAP-Me + *----------------------------------------------------------------------------*/ + +int hc_mapme_set(hc_sock_t *s, hc_mapme_t *mapme) { + return s->hc_mapme_set(s, mapme->enabled); } -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, hc_mapme_t *mapme) { + return s->hc_mapme_set_discovery(s, mapme->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, hc_mapme_t *mapme) { + return s->hc_mapme_set_timescale(s, mapme->timescale); } -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, hc_mapme_t *mapme) { + return s->hc_mapme_set_retx(s, mapme->timescale); } -int hc_mapme_set_retx(hc_sock_t *s, double timescale) -{ - return s->hc_mapme_set_retx(s, timescale); +int hc_mapme_send_update(hc_sock_t *s, hc_mapme_t *mapme) { + return s->hc_mapme_send_update(s, mapme); } +/*----------------------------------------------------------------------------* + * Policy + *----------------------------------------------------------------------------*/ + #ifdef WITH_POLICY -/* POLICY PARSE */ +/* POLICY SNPRINTF */ -int -hc_policy_parse(void * in, hc_policy_t * policy) -{ - list_policies_command * cmd = (list_policies_command *) in; +/* /!\ Please update constants in header file upon changes */ +int hc_policy_snprintf(char *s, size_t size, hc_policy_t *policy) { return 0; } - if (!IS_VALID_ADDR_TYPE(cmd->addressType)) - return -1; +int hc_policy_validate(const hc_policy_t *policy) { + if (!IS_VALID_FAMILY(policy->family)) return -1; - int family = map_from_addr_type[cmd->addressType]; - if (!IS_VALID_FAMILY(family)) - return -1; + return 0; +} - *policy = (hc_policy_t) { - .family = family, - .remote_addr = UNION_CAST(cmd->address, ip_address_t), - .len = cmd->len, - .policy = cmd->policy, - }; - return 0; +#endif /* WITH_POLICY */ + +/*----------------------------------------------------------------------------* + * SUBSCRIPTION + *----------------------------------------------------------------------------*/ +int hc_subscription_create(hc_sock_t *s, hc_subscription_t *subscription) { + return s->hc_subscription_create(s, subscription); } -/* POLICY SNPRINTF */ +int hc_subscription_delete(hc_sock_t *s, hc_subscription_t *subscription) { + return s->hc_subscription_delete(s, subscription); +} -/* /!\ Please update constants in header file upon changes */ -int -hc_policy_snprintf(char * s, size_t size, hc_policy_t * policy) -{ - return 0; +hc_result_t *hc_subscription_create_conf(hc_sock_t *s, + hc_subscription_t *subscription) { + return s->hc_subscription_create_conf(s, subscription); +} + +hc_result_t *hc_subscription_delete_conf(hc_sock_t *s, + hc_subscription_t *subscription) { + return s->hc_subscription_delete_conf(s, subscription); +} + +/*----------------------------------------------------------------------------* + * Result + *----------------------------------------------------------------------------*/ + +hc_msg_t *hc_result_get_msg(hc_sock_t *s, hc_result_t *result) { + return s->hc_result_get_msg(result); +} + +int hc_result_get_cmd_id(hc_sock_t *s, hc_result_t *result) { + return s->hc_result_get_cmd_id(result); +} + +bool hc_result_get_success(hc_sock_t *s, hc_result_t *result) { + return s->hc_result_get_success(result); } -#endif /* WITH_POLICY */
\ No newline at end of file +void hc_result_free(hc_result_t *result) { free(result); } diff --git a/ctrl/libhicnctrl/src/api_private.h b/ctrl/libhicnctrl/src/api_private.h index 3922e1f3c..11cb2e00e 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,10 +17,12 @@ #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> +#include <hicn/util/sstrncpy.h> +#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)) @@ -34,57 +36,64 @@ #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 ip_address_t *addr, int family) { + char addr_str[INET6_ADDRSTRLEN]; + return !ip_address_empty(addr) && + 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_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_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_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_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_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_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); +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); @@ -92,17 +101,21 @@ struct hc_sock_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_send)(hc_sock_t *s, hc_msg_t *msg, size_t msglen, uint32_t 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); - + void (*hc_sock_increment_woff)(hc_sock_t *s, size_t bytes); + int (*hc_sock_prepare_send)(hc_sock_t *s, hc_result_t *result, + data_callback_t complete_cb, + void *complete_cb_data); + int (*hc_sock_set_recv_timeout_ms)(hc_sock_t *s, long timeout_ms); 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); + 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); @@ -114,81 +127,105 @@ struct hc_sock_s { 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); + hc_connection_t **connection_found); int (*hc_connection_update_by_id)(hc_sock_t *s, int hc_connection_id, - hc_connection_t *connection); + hc_connection_t *connection); int (*hc_connection_update)(hc_sock_t *s, hc_connection_t *connection_current, - hc_connection_t *connection_updated); + 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_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); + 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_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); + 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_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); - 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); + 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_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_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); + 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_cache_parse)(void *in, hc_cache_info_t *cache_info); + 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); + int (*hc_cache_set_store_async)(hc_sock_t *s, hc_cache_t *cache); + int (*hc_cache_set_serve_async)(hc_sock_t *s, hc_cache_t *cache); + int (*hc_cache_snprintf)(char *s, size_t size, + const hc_cache_info_t *cache_info); 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_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_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); + int (*hc_mapme_set_timescale)(hc_sock_t *s, uint32_t timescale); + int (*hc_mapme_set_retx)(hc_sock_t *s, uint32_t timescale); + int (*hc_mapme_send_update)(hc_sock_t *s, hc_mapme_t *mapme); #ifdef WITH_POLICY int (*hc_policy_parse)(void *in, hc_policy_t *policy); @@ -199,10 +236,34 @@ struct hc_sock_s { 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 +#endif // WITH_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); + + hc_result_t *(*hc_listener_create_conf)(hc_sock_t *s, + hc_listener_t *listener); + hc_result_t *(*hc_listener_list_conf)(hc_sock_t *s, hc_data_t **pdata); + hc_result_t *(*hc_connection_create_conf)(hc_sock_t *s, + hc_connection_t *connection); + hc_result_t *(*hc_connection_delete_conf)(hc_sock_t *s, + hc_connection_t *connection); + hc_result_t *(*hc_route_create_conf)(hc_sock_t *s, hc_route_t *route); + hc_result_t *(*hc_strategy_set_conf)(hc_sock_t *s, hc_strategy_t *strategy); + hc_result_t *(*hc_strategy_add_local_prefix_conf)(hc_sock_t *s, + hc_strategy_t *strategy); + hc_result_t *(*hc_subscription_create_conf)(hc_sock_t *s, + hc_subscription_t *subscription); + hc_result_t *(*hc_subscription_delete_conf)(hc_sock_t *s, + hc_subscription_t *subscription); + + hc_msg_t *(*hc_result_get_msg)(hc_result_t *result); + bool (*hc_result_get_success)(hc_result_t *result); + int (*hc_result_get_cmd_id)(hc_result_t *result); + void (*hc_result_free)(hc_result_t *result); // Reference to module containing the implementation void *handle; }; -#endif // HICN_API_PRIVATE_H
\ No newline at end of file +#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/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/hicnctrl.c b/ctrl/libhicnctrl/src/hicnctrl.c new file mode 100644 index 000000000..99d67b19f --- /dev/null +++ b/ctrl/libhicnctrl/src/hicnctrl.c @@ -0,0 +1,805 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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> +#include <hicn/validation.h> + +#define die(LABEL, MESSAGE) \ + do { \ + printf(MESSAGE "\n"); \ + rc = -1; \ + goto ERR_##LABEL; \ + } while (0) + +const char HICNLIGHT_PARAM[] = "hicnlight"; +const char HICNLIGHT_NG_PARAM[] = "hicnlightng"; +const char 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); +} + +#if 0 +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; +#endif + +int parse_options(int argc, char *argv[], hc_command_t *command, + forwarder_type_t *forwarder) { + command->object.type = 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 if (strncmp(optarg, HICNLIGHT_NG_PARAM, + strlen(HICNLIGHT_NG_PARAM))) { + *forwarder = HICNLIGHT_NG; + } else { + usage(argv[0]); + exit(EXIT_FAILURE); + } + break; + case 'd': + command->action = ACTION_DELETE; + break; + case 'f': + command->object.type = OBJECT_FACE; + break; + case 'c': + command->object.type = OBJECT_CONNECTION; + break; + case 'F': + command->action = ACTION_LIST; + command->object.type = OBJECT_FACE; + break; + case 'L': + command->action = ACTION_LIST; + command->object.type = OBJECT_LISTENER; + break; + case 'C': + command->action = ACTION_LIST; + command->object.type = OBJECT_CONNECTION; + break; + case 'R': + command->action = ACTION_LIST; + command->object.type = OBJECT_ROUTE; + break; + case 'S': + command->action = ACTION_LIST; + command->object.type = OBJECT_STRATEGY; + break; + default: /* "h" */ + usage(argv[0]); + exit(EXIT_SUCCESS); + } + } + + if (command->object.type == OBJECT_UNDEFINED) { + fprintf(stderr, + "Missing object specification: connection | listener | route\n"); + return -1; + } + + /* Parse and validate parameters for add/delete */ + switch (command->object.type) { + 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->object.face.face.type = face_type_from_str(argv[optind++]); + if (command->object.face.face.type == FACE_TYPE_UNDEFINED) + goto ERR_PARAM; + command->object.face.face.family = + ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(command->object.face.face.family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.face.face.local_addr) < 0) + goto ERR_PARAM; + command->object.face.face.local_port = atoi(argv[optind++]); + family = ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(family) || + (command->object.face.face.family != family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.face.face.remote_addr) < 0) + goto ERR_PARAM; + command->object.face.face.remote_port = atoi(argv[optind++]); + if (argc != optind) { + // netdevice_set_name(&command->object.face.face.netdevice, + // argv[optind++]); + command->object.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], SYMBOLIC_NAME_LEN)) { + command->object.face.id = atoi(argv[optind++]); + snprintf(command->object.face.name, SYMBOLIC_NAME_LEN, "%s", + argv[optind++]); + //} else if (is_symbolic_name(argv[optind])) { + // snprintf(command->object.face.name, SYMBOLIC_NAME_LEN, "%s", + // argv[optind++]); + } else { + fprintf(stderr, "Invalid argument\n"); + goto ERR_PARAM; + } + } else { + command->object.face.face.type = face_type_from_str(argv[optind++]); + if (command->object.face.face.type == FACE_TYPE_UNDEFINED) + goto ERR_PARAM; + command->object.face.face.family = + ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(command->object.face.face.family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.face.face.local_addr) < 0) + goto ERR_PARAM; + command->object.face.face.local_port = atoi(argv[optind++]); + family = ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(family) || + (command->object.face.face.family != family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.face.face.remote_addr) < 0) + goto ERR_PARAM; + command->object.face.face.remote_port = atoi(argv[optind++]); + if (argc != optind) { + command->object.face.face.netdevice.index = atoi(argv[optind++]); + // netdevice_set_name(&command->object.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; + + 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->object.route.face_id = atoi(argv[optind++]); + + { + ip_prefix_t prefix; + ip_prefix_pton(argv[optind++], &prefix); + command->object.route.family = prefix.family; + command->object.route.remote_addr = prefix.address; + command->object.route.len = prefix.len; + } + + if (argc != optind) { + printf("parse cost\n"); + command->object.route.cost = atoi(argv[optind++]); + } + break; + + case ACTION_DELETE: + if (argc - optind != 2) { + usage_route_delete(argv[0], true, false); + goto ERR_PARAM; + } + + command->object.route.face_id = atoi(argv[optind++]); + + { + ip_prefix_t prefix; + ip_prefix_pton(argv[optind++], &prefix); + command->object.route.family = prefix.family; + command->object.route.remote_addr = prefix.address; + command->object.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; + + 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; + + 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->object.listener.name, SYMBOLIC_NAME_LEN, "%s", + argv[optind++]); + command->object.listener.type = face_type_from_str(argv[optind++]); + if (command->object.listener.type == FACE_TYPE_UNDEFINED) + goto ERR_PARAM; + command->object.listener.family = ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(command->object.listener.family)) goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.listener.local_addr) < 0) + goto ERR_PARAM; + command->object.listener.local_port = atoi(argv[optind++]); + if (argc != optind) { + snprintf(command->object.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], SYMBOLIC_NAME_LEN)) { + command->object.listener.id = atoi(argv[optind++]); + snprintf(command->object.listener.name, SYMBOLIC_NAME_LEN, "%s", + argv[optind++]); + } else if (is_symbolic_name(argv[optind], SYMBOLIC_NAME_LEN)) { + snprintf(command->object.listener.name, SYMBOLIC_NAME_LEN, "%s", + argv[optind++]); + } else { + fprintf(stderr, "Invalid argument\n"); + goto ERR_PARAM; + } + } else { + command->object.listener.type = face_type_from_str(argv[optind++]); + if (command->object.listener.type == FACE_TYPE_UNDEFINED) + goto ERR_PARAM; + command->object.listener.family = + ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(command->object.listener.family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.listener.local_addr) < 0) + goto ERR_PARAM; + command->object.listener.local_port = atoi(argv[optind++]); + if (argc != optind) { + snprintf(command->object.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; + + 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->object.connection.name, SYMBOLIC_NAME_LEN, "%s", + argv[optind++]); + command->object.connection.type = face_type_from_str(argv[optind++]); + if (command->object.connection.type == FACE_TYPE_UNDEFINED) + goto ERR_PARAM; + command->object.connection.family = + ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(command->object.connection.family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.connection.local_addr) < 0) + goto ERR_PARAM; + command->object.connection.local_port = atoi(argv[optind++]); + family = ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(family) || + (command->object.connection.family != family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.connection.remote_addr) < 0) + goto ERR_PARAM; + command->object.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], SYMBOLIC_NAME_LEN)) { + command->object.connection.id = atoi(argv[optind++]); + snprintf(command->object.connection.name, SYMBOLIC_NAME_LEN, "%s", + argv[optind++]); + } else if (is_symbolic_name(argv[optind], SYMBOLIC_NAME_LEN)) { + snprintf(command->object.connection.name, SYMBOLIC_NAME_LEN, "%s", + argv[optind++]); + } else { + fprintf(stderr, "Invalid argument\n"); + goto ERR_PARAM; + } + } else { + command->object.connection.type = + face_type_from_str(argv[optind++]); + if (command->object.connection.type == FACE_TYPE_UNDEFINED) + goto ERR_PARAM; + command->object.connection.family = + ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(command->object.connection.family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.connection.local_addr) < 0) + goto ERR_PARAM; + command->object.connection.local_port = atoi(argv[optind++]); + family = ip_address_get_family(argv[optind]); + if (!IS_VALID_FAMILY(family) || + (command->object.connection.family != family)) + goto ERR_PARAM; + if (ip_address_pton(argv[optind++], + &command->object.connection.remote_addr) < 0) + goto ERR_PARAM; + command->object.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; + + default: + goto ERR_COMMAND; + } + + 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_type_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.type) { + case OBJECT_FACE: + switch (command.action) { + case ACTION_CREATE: + if (hc_face_create(s, &command.object.face) < 0) + die(COMMAND, "Error creating face"); + printf("OK\n"); + break; + + case ACTION_DELETE: + if (hc_face_delete(s, &command.object.face, 1) < 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.object.route) < 0) + die(COMMAND, "Error creating route"); + printf("OK\n"); + break; + + case ACTION_DELETE: + if (hc_route_delete(s, &command.object.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.object.listener) < 0) + die(COMMAND, "Error creating listener"); + printf("OK\n"); + break; + case ACTION_DELETE: + if (hc_listener_delete(s, &command.object.listener) < 0) + die(COMMAND, "Error deleting listener"); + printf("OK\n"); + 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.object.connection) < 0) + die(COMMAND, "Error creating connection"); + printf("OK\n"); + break; + case ACTION_DELETE: + if (hc_connection_delete(s, &command.object.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/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/modules/CMakeLists.txt b/ctrl/libhicnctrl/src/modules/CMakeLists.txt index e07ab8c99..8f7916d14 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-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,38 +11,53 @@ # See the License for the specific language governing permissions and # limitations under the License. -cmake_minimum_required(VERSION 3.5 FATAL_ERROR) - - -list(APPEND HICNLIGHT_MODULE_SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light_api.c +############################################################## +# Hicn Light NG Module +############################################################## +list(APPEND HICNLIGHTNG_MODULE_SOURCE_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light_common.c + ${CMAKE_CURRENT_SOURCE_DIR}/hicn_light_ng_api.c ) -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} +build_module(hicnlightngctrl_module + SOURCES ${HICNLIGHTNG_MODULE_SOURCE_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_api.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" + SOURCES ${HICN_PLUGIN_SOURCE_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} ${MARCH_COMPILER_OPTIONS} ) - -endif()
\ No newline at end of file +endif() 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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), ¶ms, 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_light_common.c b/ctrl/libhicnctrl/src/modules/hicn_light_common.c new file mode 100644 index 000000000..bc04404bf --- /dev/null +++ b/ctrl/libhicnctrl/src/modules/hicn_light_common.c @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_common.h" + +TYPEDEF_MAP(hc_sock_map, int, hc_sock_request_t *, int_cmp, int_snprintf, + generic_snprintf); + +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); } diff --git a/ctrl/libhicnctrl/src/modules/hicn_light_common.h b/ctrl/libhicnctrl/src/modules/hicn_light_common.h new file mode 100644 index 000000000..4749474c8 --- /dev/null +++ b/ctrl/libhicnctrl/src/modules/hicn_light_common.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. + */ +#ifndef HICNCTRL_HICN_LIGHT_COMMON +#define HICNCTRL_HICN_LIGHT_COMMON + +#include <assert.h> // assert + +#include "api_private.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; + 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 *); + +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); + +void hc_sock_light_request_free(hc_sock_request_t *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) + +static const struct in6_addr loopback_addr = IN6ADDR_LOOPBACK_INIT; + +#endif /* HICNCTRL_HICN_LIGHT_COMMON */ diff --git a/ctrl/libhicnctrl/src/modules/hicn_light_ng_api.c b/ctrl/libhicnctrl/src/modules/hicn_light_ng_api.c new file mode 100644 index 000000000..a58ee909e --- /dev/null +++ b/ctrl/libhicnctrl/src/modules/hicn_light_ng_api.c @@ -0,0 +1,3111 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 <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 +#include <unistd.h> // getpid + +#include "api_private.h" +#ifdef __linux__ +#include <sys/syscall.h> +#define gettid() syscall(SYS_gettid) +#endif /* __linux__ */ +#include <hicn/ctrl/hicn-light-ng.h> +#include <strings.h> + +#include "hicn_light_common.h" +#include <hicn/util/sstrncpy.h> + +#pragma GCC diagnostic ignored "-Warray-bounds" + +#if 0 +#ifdef __APPLE__ +#define RANDBYTE() (u8)(arc4random() & 0xFF) +#else +#define RANDBYTE() (u8)(random() & 0xFF) +#endif +#endif +#define RANDBYTE() (u8)(rand() & 0xFF) + +/** + * \brief Defines the default size for the allocated data arrays holding the + * results of API calls. + * + * This size should not be too small to avoid wasting memoyy, but also not too + * big to avoid unnecessary realloc's. Later on this size is doubled at each + * reallocation. + */ +#define DEFAULT_SIZE_LOG 3 + +#define connection_state_to_face_state(x) ((face_state_t)(x)) +#define face_state_to_connection_state(x) ((hc_connection_state_t)(x)) + +/****************************************************************************** + * Message helper types and aliases + ******************************************************************************/ + +#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) + +const char *command_type_str[] = { +#define _(l, u) [COMMAND_TYPE_##u] = STRINGIZE(u), + foreach_command_type +#undef _ +}; + +typedef cmd_header_t hc_msg_header_t; + +typedef union { +#define _(x) cmd_##x##_t 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 + ******************************************************************************/ + +#define AVAILABLE(s) ((s)->woff - (s)->roff) +#define DEFAULT_SOCK_RECV_TIMEOUT_MS 100 + +/** + * \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 _hcng_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 _hcng_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 _hcng_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 void _hcng_sock_increment_woff(hc_sock_t *socket, size_t bytes) { + hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket); + s->woff += bytes; +} + +static int _hcng_sock_light_get_next_seq(hc_sock_t *socket) { + hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket); + return s->seq++; +} + +static int _hcng_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 _hcng_sock_light_get_fd(hc_sock_t *socket) { + hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket); + return s->fd; +} + +static int _hcng_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 (_hcng_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) { + perror("connect error"); + goto ERR_CONNECT; + } + return 0; + +ERR_CONNECT: +ERR_PARSE: + return -1; +} + +static int _hcng_sock_light_send(hc_sock_t *socket, hc_msg_t *msg, + size_t msglen, uint32_t seq) { + hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket); + int rc; + msg->hdr.seq_num = seq; + rc = (int)send(s->fd, msg, msglen, 0); + if (rc < 0) { + perror("hc_sock_light_send"); + return -1; + } + return 0; +} + +static int _hcng_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 _hcng_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. 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) return -1; + if (errno == EINTR) { + WARN("recv has been stopped by signal"); + return -1; + } + perror("hc_sock_light_recv"); + return -1; + } + s->woff += rc; + return rc; +} + +static void _hcng_sock_light_mark_complete(hc_sock_light_t *s, + hc_data_t **pdata) { + hc_data_t *data = s->cur_request->data; + + if (hc_sock_map_remove(s->map, s->cur_request->seq, NULL) < 0) { + ERROR("[hc_sock_light_mark_complete] Error removing request from map"); + } + hc_data_set_complete(data); + if (pdata) *pdata = data; + + /* Free current request */ + hc_sock_light_request_free(s->cur_request); + s->cur_request = NULL; +} + +static int _hcng_sock_light_process_notification(hc_sock_light_t *s, + hc_data_t **pdata) { + /* For now, notifications are not associated to requests */ + assert(!s->cur_request); + + /* + * Assumption: the whole notification data is returned in a single read and we + * immediately parse it. + * + * XXX This is only valid for UDP sockets. + */ + size_t notification_size = AVAILABLE(s); + + *pdata = hc_data_create(0, /* in_element_size, 0 = no parsing */ + notification_size, /* out_element_size */ + NULL); /* complete_cb */ + + /* Copy the packet payload as the single entry in hc_data_t */ + hc_data_push_many(*pdata, s->buf + s->roff, 1); + + return notification_size; +} + +/* + * Notifications have no sequence number and are not linked to any request + */ +static hc_sock_request_t *_hcng_sock_light_get_request(hc_sock_light_t *s, + int seq) { + hc_sock_request_t *request; + /* Retrieve request from sock map */ + if (hc_sock_map_get(s->map, seq, &request) < 0) { + ERROR("[hc_sock_light_process] Error searching for matching request"); + return NULL; + } + if (!request) { + ERROR("[hc_sock_light_process] No request matching sequence number"); + return NULL; + } + return request; +} + +/* + * Return codes: + * 0 success, or not enough data yet to do something + * > 0 : notification type + * -99 invalid buffer data -> flush + */ +static int _hcng_sock_light_process_header(hc_sock_light_t *s, + hc_data_t **pdata) { + int rc; + + /* 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); + + if (msg->hdr.message_type != NOTIFICATION_LIGHT) { + s->cur_request = _hcng_sock_light_get_request(s, msg->hdr.seq_num); + if (!s->cur_request) return -99; + } + + /* How many elements are we expecting in the reply ? */ + s->remaining = msg->hdr.length; + hc_data_t *request_data; + + switch (msg->hdr.message_type) { + case ACK_LIGHT: + assert(s->remaining == 1); // sic + assert(!pdata); + _hcng_sock_light_mark_complete(s, pdata); + break; + + case NACK_LIGHT: + assert(!pdata); + assert(s->remaining == 1); // sic + request_data = s->cur_request->data; + _hcng_sock_light_mark_complete(s, pdata); + hc_data_set_error(request_data); + break; + + case RESPONSE_LIGHT: + assert(pdata); + + if (s->remaining == 0) { + /* Empty response (i.e. containing 0 elements) */ + _hcng_sock_light_mark_complete(s, pdata); + return 0; + } + + /* Make room in hc_data_t... to avoid multiple calls */ + rc = hc_data_ensure_available(s->cur_request->data, s->remaining); + if (rc < 0) { + ERROR("[hc_sock_light_process] Error in hc_data_ensure_available"); + return -99; + } + break; + + case NOTIFICATION_LIGHT: { + assert(pdata); + assert(s->remaining == 0); + + /* This returns the notification size */ + size_t notification_size = + _hcng_sock_light_process_notification(s, pdata); + s->roff += notification_size; + return msg->hdr.command_id; + } + + default: + ERROR("[hc_sock_light_process] Invalid response received"); + return -99; + } + + return 0; +} + +static int _hcng_sock_light_process_payload(hc_sock_light_t *s, + hc_data_t **pdata) { + int err = 0; + int rc; + + hc_data_t *data = s->cur_request->data; + + /* We only process full elements (size is stored in data) */ + size_t num_chunks = AVAILABLE(s) / data->in_element_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( + "[_hcng_sock_light_process_payload] Unexpected 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(data, s->buf + s->roff, num_chunks); + } else { + /* Iterate on chunks of data */ + for (int i = 0; i < num_chunks; i++) { + /* Get storage offset in hc_data_t */ + u8 *dst = hc_data_get_next(data); + if (!dst) { + ERROR("[hc_sock_light_process] Error in hc_data_get_next"); + err = -2; + break; + } + + /* Parse element #i */ + rc = s->cur_request->parse(s->buf + s->roff + i * data->in_element_size, + dst); + if (rc < 0) { + ERROR("[hc_sock_light_process] Error in parse"); + err = -1; + /* In this case we let the loop complete to collect other results */ + } + data->size++; + } + } + + s->roff += num_chunks * data->in_element_size; + + /* + * If we are not expecting any more data, mark the reply as complete + */ + s->remaining -= num_chunks; + if (s->remaining == 0) _hcng_sock_light_mark_complete(s, pdata); + + return err; +} + +/* + * Process messages as they are received in the ring buffer. There can be + * interleaved queries and replies (they are identified by sequence number), + * and the assumption is that a reply can arrive over mutiple packets (in + * other terms, it is possible that not all data from the reply is available + * in the buffer at a given time). However, we assume that a full query is + * received at once. + */ +static int _hcng_sock_light_process(hc_sock_t *socket, hc_data_t **data) { + hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket); + int rc = 0; + + /* + * We loop consuming messages until there is no more data in the 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->cur_request) { + rc = _hcng_sock_light_process_header(s, data); + } else { + rc = _hcng_sock_light_process_payload(s, data); + } + 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; +} + +static int _hcng_sock_light_callback(hc_sock_t *socket, hc_data_t **pdata) { + hc_data_t *data = NULL; + int rc = 0; + + for (;;) { + int n = _hcng_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; + case EINTR: + WARN("callback has been stopped by signal"); + goto ERR; + default: + perror("hc_sock_light_callback"); + goto ERR; + } + } + rc = _hcng_sock_light_process(socket, &data); + if (rc < 0) goto ERR; + if (rc > 0) // i.e. rc = notification type + goto END; + } +END: + if (pdata) + *pdata = data; + else + hc_data_free(data); + return rc; + +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_type_t cmd_id; + size_t size_in; + size_t size_out; + HC_PARSE parse; +} hc_command_params_t; + +typedef struct hc_result_s { + hc_msg_t msg; + hc_command_params_t params; + bool async; + bool success; +} hc_result_t; + +int _hcng_sock_prepare_send(hc_sock_t *socket, hc_result_t *result, + data_callback_t complete_cb, + void *complete_cb_data) { + hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket); + + // Prepare data + hc_data_t *data = + hc_data_create(result->params.size_in, result->params.size_out, NULL); + if (!data) { + ERROR("[_hcng_execute_command] Could not create data storage"); + goto ERR_DATA; + } + hc_data_set_callback(data, complete_cb, complete_cb_data); + + // Update the sequence number + int seq = _hcng_sock_light_get_next_seq(socket); + result->msg.hdr.seq_num = seq; // Like in _hcng_sock_light_send + + // Create state used to process the request + hc_sock_request_t *request = NULL; + request = hc_sock_request_create(seq, data, result->params.parse); + if (!request) { + ERROR("[_hcng_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("[_hcng_execute_command] Error adding request state to map"); + goto ERR_MAP; + } + + return sizeof(result->msg); + +ERR_MAP: + hc_sock_light_request_free(request); +ERR_REQUEST: + hc_data_free(data); +ERR_DATA: + return -99; +} + +int _hcng_sock_set_recv_timeout_ms(hc_sock_t *socket, long timeout_ms) { + hc_sock_light_t *s = TO_HC_SOCK_LIGHT(socket); + + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = timeout_ms * 1000; // Convert ms into us + if (setsockopt(s->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { + perror("setsockopt"); + return -1; + } + + return 0; +} + +static int _hcng_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: + case ACTION_SERVE: + case ACTION_STORE: + case ACTION_UPDATE: + assert(params->size_in != 0); + assert(params->size_out == 0); + assert(params->parse == NULL); + break; + case ACTION_CLEAR: + 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("[_hcng_execute_command] Could not create data storage"); + goto ERR_DATA; + } + + int seq = _hcng_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("[_hcng_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("[_hcng_execute_command] Error adding request state to map"); + goto ERR_MAP; + } + + if (_hcng_sock_light_send(socket, msg, msg_len, seq) < 0) { + ERROR("[_hcng_execute_command] Error sending message"); + goto ERR_PROCESS; + } + + if (async) return 0; + + /* + * Dangerous zone, we might be doing blocking operations on a non-blocking + * UDP socket + */ + int retries = 0; + while (!data->complete) { + /* + * As the socket is non blocking it might happen that we need to read + * several times before success... + */ + int n = _hcng_sock_light_recv(socket); + if (n == 0) goto ERR_EOF; + if (n < 0) { + if ((errno == EWOULDBLOCK) && (retries < 10)) { /* Max 500ms */ + DEBUG("read = EWOULDBLOCK... sleeping for 50ms (max 500ms)"); + usleep(50000); /* 50ms */ + retries++; + continue; + } + break; + } + int rc = _hcng_sock_light_process(socket, pdata); + switch (rc) { + case 0: + case -1: + break; + case -99: + ERROR("[_hcng_execute_command] Error processing socket results"); + goto ERR; + default: + ERROR("[_hcng_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 hc_result_t *_listener_create_serialize(hc_sock_t *s, + hc_listener_t *listener, + bool async) { + hc_result_t *res = malloc(sizeof(*res)); + char listener_s[MAXSZ_HC_LISTENER]; + int rc = hc_listener_snprintf(listener_s, MAXSZ_HC_LISTENER, listener); + if (rc >= MAXSZ_HC_LISTENER) + WARN("[_hcng_listener_create] Unexpected truncation of listener string"); + DEBUG("[_hcng_listener_create] listener=%s async=%s", listener_s, + BOOLSTR(async)); + + if (hc_listener_validate(listener) < 0) { + res->success = false; + return res; + } + + msg_listener_add_t msg = {.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 = listener->family, + .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.interface_name, 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 = COMMAND_TYPE_LISTENER_ADD, + .size_in = sizeof(cmd_listener_add_t), + .size_out = 0, + .parse = NULL, + }; + + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.listener_add = msg.payload, + }, + .params = params, + .async = async, + .success = true, + }; + return res; +} + +static hc_result_t *_hcng_listener_create_conf(hc_sock_t *s, + hc_listener_t *listener) { + return _listener_create_serialize(s, listener, false); +} + +static int _hcng_listener_create_internal(hc_sock_t *socket, + hc_listener_t *listener, bool async) { + hc_result_t *result = _listener_create_serialize(socket, listener, async); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + free(result); + DEBUG("[_hcng_listener_create] done or error"); + return ret; +} + +static int _hcng_listener_create(hc_sock_t *s, hc_listener_t *listener) { + DEBUG("[_hcng_listener_create]"); + return _hcng_listener_create_internal(s, listener, false); +} + +static int _hcng_listener_create_async(hc_sock_t *s, hc_listener_t *listener) { + DEBUG("[_hcng_listener_create_async]"); + return _hcng_listener_create_internal(s, listener, true); +} + +/* LISTENER PARSE */ + +static int hc_listener_parse(void *in, hc_listener_t *listener) { + int rc; + cmd_listener_list_item_t *item = (cmd_listener_list_item_t *)in; + + if (!IS_VALID_ID(item->id)) { + ERROR("[hc_listener_parse] Invalid id received"); + return -1; + } + + *listener = (hc_listener_t){ + .id = item->id, + .type = item->type, + .family = item->family, + .local_addr = UNION_CAST(item->address, ip_address_t), + .local_port = ntohs(item->port), + }; + rc = snprintf(listener->name, SYMBOLIC_NAME_LEN, "%s", item->name); + if (rc >= SYMBOLIC_NAME_LEN) + WARN("[hc_listener_parse] Unexpected truncation of symbolic name string"); + rc = snprintf(listener->interface_name, INTERFACE_LEN, "%s", + item->interface_name); + if (rc >= INTERFACE_LEN) + WARN("[hc_listener_parse] Unexpected truncation of interface name string"); + + if (hc_listener_validate(listener) < 0) return -1; + return 0; +} + +/* LISTENER LIST */ + +static hc_result_t *_hcng_listener_list_serialize(hc_sock_t *socket, + hc_data_t **pdata, + bool async) { + hc_result_t *res = malloc(sizeof(*res)); + DEBUG("[hc_listener_list] async=%s", BOOLSTR(async)); + + msg_listener_list_t msg = {.header = { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_LISTENER_LIST, + .length = 0, + .seq_num = 0, + }}; + + hc_command_params_t params = { + .cmd = ACTION_LIST, + .cmd_id = COMMAND_TYPE_LISTENER_LIST, + .size_in = sizeof(cmd_listener_list_item_t), + .size_out = sizeof(hc_listener_t), + .parse = (HC_PARSE)hc_listener_parse, + }; + + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.listener_list = msg.payload, + }, + .params = params, + .async = async, + .success = true, + }; + return res; +} + +static hc_result_t *_hcng_listener_list_conf(hc_sock_t *s, hc_data_t **pdata) { + return _hcng_listener_list_serialize(s, pdata, false); +} + +static int _hcng_listener_list_internal(hc_sock_t *socket, hc_data_t **pdata, + bool async) { + hc_result_t *result = _hcng_listener_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); + DEBUG("[_hcng_listener_list] done or error"); + return ret; +} + +static int _hcng_listener_list(hc_sock_t *s, hc_data_t **pdata) { + DEBUG("[_hcng_listener_list]"); + return _hcng_listener_list_internal(s, pdata, false); +} + +static int _hcng_listener_list_async(hc_sock_t *s, hc_data_t **pdata) { + DEBUG("[_hcng_listener_list_as-nc]"); + return _hcng_listener_list_internal(s, pdata, true); +} + +/* LISTENER GET */ + +static int _hcng_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 (_hcng_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 _hcng_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("[_hcng_listener_delete] Unexpected truncation of listener string"); + DEBUG("[_hcng_listener_delete] listener=%s async=%s", listener_s, + BOOLSTR(async)); + + msg_listener_remove_t msg = {.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); + 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 (_hcng_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 = COMMAND_TYPE_LISTENER_REMOVE, + .size_in = sizeof(cmd_listener_remove_t), + .size_out = 0, + .parse = NULL, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, async); +} + +static int _hcng_listener_delete(hc_sock_t *s, hc_listener_t *listener) { + return _hcng_listener_delete_internal(s, listener, false); +} + +static int _hcng_listener_delete_async(hc_sock_t *s, hc_listener_t *listener) { + return _hcng_listener_delete_internal(s, listener, true); +} + +/*----------------------------------------------------------------------------* + * CONNECTION + *----------------------------------------------------------------------------*/ + +/* CONNECTION CREATE */ + +static hc_result_t *_connection_create_serialize(hc_sock_t *socket, + hc_connection_t *connection, + bool async) { + hc_result_t *res = malloc(sizeof(*res)); + char connection_s[MAXSZ_HC_CONNECTION]; + int rc = + hc_connection_snprintf(connection_s, MAXSZ_HC_CONNECTION, connection); + if (rc >= MAXSZ_HC_CONNECTION) + WARN( + "[_hcng_connection_create] Unexpected truncation of connection " + "string"); + DEBUG("[_hcng_connection_create] connection=%s async=%s", connection_s, + BOOLSTR(async)); + + if (hc_connection_validate(connection) < 0) { + res->success = false; + return res; + } + + msg_connection_add_t msg = {.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 = connection->family, + .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.interface_name, INTERFACE_NAME_LEN, "%s", + // connection->interface_name); + + hc_command_params_t params = { + .cmd = ACTION_CREATE, + .cmd_id = COMMAND_TYPE_CONNECTION_ADD, + .size_in = sizeof(cmd_connection_add_t), + .size_out = 0, + .parse = NULL, + }; + + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.connection_add = msg.payload, + }, + .params = params, + .async = async, + .success = true, + }; + return res; +} + +static hc_result_t *_hcng_connection_create_conf(hc_sock_t *s, + hc_connection_t *connection) { + return _connection_create_serialize(s, connection, false); +} + +static int _hcng_connection_create_internal(hc_sock_t *socket, + hc_connection_t *connection, + bool async) { + hc_result_t *result = _connection_create_serialize(socket, connection, async); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + hc_result_free(result); + DEBUG("[_hcng_connection_create] done or error"); + return ret; +} + +static int _hcng_connection_create(hc_sock_t *s, hc_connection_t *connection) { + DEBUG("[_hcng_connection_create]"); + return _hcng_connection_create_internal(s, connection, false); +} + +static int _hcng_connection_create_async(hc_sock_t *s, + hc_connection_t *connection) { + DEBUG("[_hcng_connection_create_async]"); + return _hcng_connection_create_internal(s, connection, true); +} + +/* CONNECTION PARSE */ + +static int hc_connection_parse(void *in, hc_connection_t *connection) { + int rc; + cmd_connection_list_item_t *item = (cmd_connection_list_item_t *)in; + + if (!IS_VALID_ID(item->id)) { + ERROR("[hc_connection_parse] Invalid id received"); + return -1; + } + + *connection = (hc_connection_t){ + .id = item->id, + .type = item->type, + .family = 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 = item->admin_state, +#ifdef WITH_POLICY + .priority = item->priority, + .tags = item->tags, +#endif /* WITH_POLICY */ + .state = item->state, + }; + rc = snprintf(connection->name, SYMBOLIC_NAME_LEN, "%s", item->name); + if (rc >= SYMBOLIC_NAME_LEN) + WARN( + "[hc_connection_parse] Unexpected truncation of symbolic name " + "string"); + rc = snprintf(connection->interface_name, INTERFACE_LEN, "%s", + item->interface_name); + if (rc >= INTERFACE_LEN) + WARN( + "[hc_connection_parse] Unexpected truncation of interface name " + "string"); + + if (hc_connection_validate(connection) < 0) return -1; + return 0; +} + +/* CONNECTION LIST */ + +static int _hcng_connection_list_internal(hc_sock_t *socket, hc_data_t **pdata, + bool async) { + DEBUG("[hc_connection_list] async=%s", BOOLSTR(async)); + + msg_connection_list_t msg = {.header = { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_CONNECTION_LIST, + .length = 0, + .seq_num = 0, + }}; + + hc_command_params_t params = { + .cmd = ACTION_LIST, + .cmd_id = COMMAND_TYPE_CONNECTION_LIST, + .size_in = sizeof(cmd_connection_list_item_t), + .size_out = sizeof(hc_connection_t), + .parse = (HC_PARSE)hc_connection_parse, + }; + + int ret = _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), + ¶ms, pdata, async); + + DEBUG("[hc_connection_list] done or error"); + return ret; +} + +static int _hcng_connection_list(hc_sock_t *s, hc_data_t **pdata) { + DEBUG("[hc_connection_list]"); + return _hcng_connection_list_internal(s, pdata, false); +} + +static int _hcng_connection_list_async(hc_sock_t *s, hc_data_t **pdata) { + DEBUG("[hc_connection_list_async]"); + return _hcng_connection_list_internal(s, pdata, true); +} + +/* CONNECTION GET */ + +static int _hcng_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 (_hcng_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 hc_result_t *_hcng_connection_delete_serialize( + hc_sock_t *socket, hc_connection_t *connection, bool async) { + hc_result_t *res = malloc(sizeof(*res)); + res->success = false; + + char connection_s[MAXSZ_HC_CONNECTION]; + int rc = + hc_connection_snprintf(connection_s, MAXSZ_HC_CONNECTION, connection); + if (rc >= MAXSZ_HC_CONNECTION) + WARN( + "[_hcng_connection_delete] Unexpected truncation of connection " + "string"); + DEBUG("[_hcng_connection_delete] connection=%s async=%s", connection_s, + BOOLSTR(async)); + + msg_connection_remove_t msg = { + .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); + 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); + 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 res; + if (!connection_found) return res; + rc = snprintf(msg.payload.symbolic_or_connid, 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 = COMMAND_TYPE_CONNECTION_REMOVE, + .size_in = sizeof(cmd_connection_remove_t), + .size_out = 0, + .parse = NULL, + }; + + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.connection_remove = msg.payload, + }, + .params = params, + .async = async, + .success = true, + }; + return res; +} + +static hc_result_t *_hcng_connection_delete_conf(hc_sock_t *s, + hc_connection_t *connection) { + return _hcng_connection_delete_serialize(s, connection, false); +} + +static int _hcng_connection_delete_internal(hc_sock_t *socket, + hc_connection_t *connection, + bool async) { + hc_result_t *result = + _hcng_connection_delete_serialize(socket, connection, async); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + hc_result_free(result); + return ret; +} + +static int _hcng_connection_delete(hc_sock_t *s, hc_connection_t *connection) { + return _hcng_connection_delete_internal(s, connection, false); +} + +static int _hcng_connection_delete_async(hc_sock_t *s, + hc_connection_t *connection) { + return _hcng_connection_delete_internal(s, connection, true); +} + +/* CONNECTION UPDATE */ + +static int _hcng_connection_update_by_id(hc_sock_t *s, int hc_connection_id, + hc_connection_t *connection) { + // Not implemented + return -1; +} + +static int _hcng_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 _hcng_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 _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, async); +} + +static int _hcng_connection_set_admin_state(hc_sock_t *s, + const char *conn_id_or_name, + face_state_t state) { + return _hcng_connection_set_admin_state_internal(s, conn_id_or_name, state, + false); +} + +static int _hcng_connection_set_admin_state_async(hc_sock_t *s, + const char *conn_id_or_name, + face_state_t state) { + return _hcng_connection_set_admin_state_internal(s, conn_id_or_name, state, + true); +} + +#ifdef WITH_POLICY + +static int _hcng_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 _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, async); +} + +static int _hcng_connection_set_priority(hc_sock_t *s, + const char *conn_id_or_name, + uint32_t priority) { + return _hcng_connection_set_priority_internal(s, conn_id_or_name, priority, + false); +} + +static int _hcng_connection_set_priority_async(hc_sock_t *s, + const char *conn_id_or_name, + uint32_t priority) { + return _hcng_connection_set_priority_internal(s, conn_id_or_name, priority, + true); +} + +#endif // WITH_POLICY + +static int _hcng_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 _hcng_execute_command(s, (hc_msg_t *)&msg, sizeof(msg), ¶ms, NULL, + async); +} + +static int _hcng_connection_set_tags(hc_sock_t *s, const char *conn_id_or_name, + policy_tags_t tags) { + return _hcng_connection_set_tags_internal(s, conn_id_or_name, tags, false); +} + +static int _hcng_connection_set_tags_async(hc_sock_t *s, + const char *conn_id_or_name, + policy_tags_t tags) { + return _hcng_connection_set_tags_internal(s, conn_id_or_name, tags, true); +} + +/*----------------------------------------------------------------------------* + * Routes + *----------------------------------------------------------------------------*/ + +/* ROUTE CREATE */ + +static hc_result_t *_route_create_serialize(hc_sock_t *socket, + hc_route_t *route, bool async) { + hc_result_t *res = malloc(sizeof(*res)); + 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 (hc_route_validate(route) < 0) { + res->success = false; + return res; + } + + msg_route_add_t msg = {.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->name[0] != '\0') { + rc = snprintf(msg.payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s", + route->name); + } else { + rc = snprintf(msg.payload.symbolic_or_connid, 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 = COMMAND_TYPE_ROUTE_ADD, + .size_in = sizeof(cmd_route_add_t), + .size_out = 0, + .parse = NULL, + }; + + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.route_add = msg.payload, + }, + .params = params, + .async = async, + .success = true, + }; + return res; +} + +static hc_result_t *_hcng_route_create_conf(hc_sock_t *s, hc_route_t *route) { + return _route_create_serialize(s, route, false); +} + +static int _hcng_route_create_internal(hc_sock_t *socket, hc_route_t *route, + bool async) { + hc_result_t *result = _route_create_serialize(socket, route, async); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + hc_result_free(result); + return ret; +} + +static int _hcng_route_create(hc_sock_t *s, hc_route_t *route) { + return _hcng_route_create_internal(s, route, false); +} + +static int _hcng_route_create_async(hc_sock_t *s, hc_route_t *route) { + return _hcng_route_create_internal(s, route, true); +} + +/* ROUTE DELETE */ + +static int _hcng_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 { + cmd_header_t hdr; + cmd_route_remove_t payload; + } msg = {.hdr = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_ROUTE_REMOVE, + .length = 1, + .seq_num = 0, + }, + .payload = { + .address = route->remote_addr, + .family = route->family, + .len = route->len, + }}; + + /* + * The route commands expects the ID or name as part of the + * symbolic_or_connid attribute. + */ + if (route->name[0] != '\0') { + rc = snprintf(msg.payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%s", + route->name); + } else { + rc = snprintf(msg.payload.symbolic_or_connid, SYMBOLIC_NAME_LEN, "%d", + route->face_id); + } + + hc_command_params_t params = { + .cmd = ACTION_DELETE, + .cmd_id = COMMAND_TYPE_ROUTE_REMOVE, + .size_in = sizeof(cmd_route_remove_t), + .size_out = 0, + .parse = NULL, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, async); +} + +static int _hcng_route_delete(hc_sock_t *s, hc_route_t *route) { + return _hcng_route_delete_internal(s, route, false); +} + +static int _hcng_route_delete_async(hc_sock_t *s, hc_route_t *route) { + return _hcng_route_delete_internal(s, route, true); +} + +/* ROUTE PARSE */ + +static int hc_route_parse(void *in, hc_route_t *route) { + cmd_route_list_item_t *item = (cmd_route_list_item_t *)in; + + *route = (hc_route_t){ + .name = "", /* This is not reported back */ + .face_id = item->connection_id, + .family = item->family, + .remote_addr = item->address, + .len = item->len, + .cost = item->cost, + }; + + if (hc_route_validate(route) < 0) return -1; + return 0; +} + +/* ROUTE LIST */ + +static int _hcng_route_list_internal(hc_sock_t *socket, hc_data_t **pdata, + bool async) { + // DEBUG("[hc_route_list] async=%s", BOOLSTR(async)); + msg_route_list_t msg = {.header = { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_ROUTE_LIST, + .length = 0, + .seq_num = 0, + }}; + + hc_command_params_t params = { + .cmd = ACTION_LIST, + .cmd_id = COMMAND_TYPE_ROUTE_LIST, + .size_in = sizeof(cmd_route_list_item_t), + .size_out = sizeof(hc_route_t), + .parse = (HC_PARSE)hc_route_parse, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + pdata, async); +} + +static int _hcng_route_list(hc_sock_t *s, hc_data_t **pdata) { + return _hcng_route_list_internal(s, pdata, false); +} + +static int _hcng_route_list_async(hc_sock_t *s) { + return _hcng_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 _hcng_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 (_hcng_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 (_hcng_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 (_hcng_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; + } + break; + default: + ERROR("[hc_face_create] Unknwon face type."); + + return -1; + }; + + return 0; +} + +static int _hcng_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 (_hcng_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 (_hcng_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 _hcng_face_delete(hc_sock_t *socket, hc_face_t *face, + uint8_t delete_listener) { + 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 (_hcng_connection_delete(socket, &connection) < 0) { + ERROR("[hc_face_delete] Error removing connection"); + return -1; + } + + if (!delete_listener) { + return 0; + } + + /* 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 (_hcng_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 (_hcng_listener_delete(socket, &listener) < 0) { + ERROR("[hc_face_delete] Error removing listener"); + return -1; + } + } + + hc_data_free(connections); + + return 0; +} + +/* FACE LIST */ + +static int _hcng_face_list(hc_sock_t *socket, hc_data_t **pdata) { + hc_data_t *connection_data; + hc_face_t face; + + DEBUG("[hc_face_list]"); + + if (_hcng_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); + DEBUG("[hc_face_list] done"); + return 0; + +ERR: + hc_data_free(connection_data); + DEBUG("[hc_face_list] error"); + return -1; +} + +static 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; +} + +static int _hcng_face_list_async(hc_sock_t *socket) { + struct { + cmd_header_t hdr; + } msg = { + .hdr = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_CONNECTION_LIST, + .length = 0, + .seq_num = 0, + }, + }; + + hc_command_params_t params = { + .cmd = ACTION_LIST, + .cmd_id = COMMAND_TYPE_CONNECTION_LIST, + .size_in = sizeof(cmd_connection_list_item_t), + .size_out = sizeof(hc_face_t), + .parse = (HC_PARSE)hc_connection_parse_to_face, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, true); +} + +static int _hcng_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 _hcng_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 _hcng_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 _hcng_punting_create_internal(hc_sock_t *socket, + hc_punting_t *punting, bool async) { + 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), ¶ms, + NULL, async); +} + +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; +} + +/*----------------------------------------------------------------------------* + * Cache + *----------------------------------------------------------------------------*/ + +/* CACHE SET STORE */ + +static int _hcng_cache_set_store_internal(hc_sock_t *socket, hc_cache_t *cache, + bool async) { + 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), ¶ms, + NULL, async); +} + +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) { + 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), ¶ms, + NULL, async); +} + +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) { + 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), ¶ms, + NULL, async); +} + +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){ + .hdr = 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) { + 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; +} + +static int _hcng_cache_list(hc_sock_t *s, hc_data_t **pdata) { + return _hcng_cache_list_internal(s, pdata, false); +} + +/*----------------------------------------------------------------------------* + * Strategy + *----------------------------------------------------------------------------*/ + +// per prefix +static hc_result_t *_strategy_set_serialize(hc_sock_t *socket, + hc_strategy_t *strategy) { + hc_result_t *res = malloc(sizeof(*res)); + + char strategy_s[MAXSZ_HC_STRATEGY]; + int rc = strcpy_s(strategy->name, MAXSZ_STRATEGY_NAME, + strategy_str(strategy->type)); + if (rc != EOK) goto ERR; + rc = hc_strategy_snprintf(strategy_s, MAXSZ_HC_STRATEGY, strategy); + if (rc >= MAXSZ_HC_STRATEGY) + WARN("[_hcng_strategy_create] Unexpected truncation of strategy string"); + DEBUG("[_hcng_strategy_create] strategy=%s", strategy_s); + + if (!IS_VALID_FAMILY(strategy->family) || + !IS_VALID_STRATEGY_TYPE(strategy->type)) { + goto ERR; + } + + msg_strategy_set_t msg = {.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, + }}; + + hc_command_params_t params = { + .cmd = ACTION_SET, + .cmd_id = COMMAND_TYPE_STRATEGY_SET, + .size_in = sizeof(cmd_strategy_set_t), + .size_out = 0, + .parse = NULL, + }; + + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.strategy_set = msg.payload, + }, + .params = params, + .async = false, + .success = true, + }; + return res; + +ERR: + res->success = false; + return res; +} + +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]; + int rc = strcpy_s(strategy->name, MAXSZ_STRATEGY_NAME, + strategy_str(strategy->type)); + if (rc != EOK) goto ERR; + rc = hc_strategy_snprintf(strategy_s, MAXSZ_HC_STRATEGY, strategy); + if (rc >= MAXSZ_HC_STRATEGY) + WARN("[_hcng_strategy_create] Unexpected truncation of strategy string"); + DEBUG("[_hcng_strategy_create] strategy=%s", strategy_s); + + if (!IS_VALID_FAMILY(strategy->family) || + !IS_VALID_STRATEGY_TYPE(strategy->type) || + !IS_VALID_FAMILY(strategy->local_family)) { + goto ERR; + } + + 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){ + .hdr = msg.header, + .payload.strategy_add_local_prefix = msg.payload, + }, + .params = params, + .async = false, + .success = true, + }; + return res; + +ERR: + res->success = false; + return res; +} + +static hc_result_t *_hcng_strategy_set_conf(hc_sock_t *s, + hc_strategy_t *strategy) { + return _strategy_set_serialize(s, strategy); +} + +static int _hcng_strategy_set(hc_sock_t *socket, hc_strategy_t *strategy) { + hc_result_t *result = _strategy_set_serialize(socket, strategy); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + hc_result_free(result); + return ret; +} + +static hc_result_t *_hcng_strategy_add_local_prefix_conf( + hc_sock_t *s, hc_strategy_t *strategy) { + return _strategy_add_local_prefix_serialize(s, strategy); +} + +static int _hcng_strategy_add_local_prefix(hc_sock_t *socket, + hc_strategy_t *strategy) { + hc_result_t *result = _strategy_add_local_prefix_serialize(socket, strategy); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + hc_result_free(result); + return ret; +} + +/* How to retrieve that from the forwarder ? */ +static const char *strategies[] = { + "random", + "load_balancer", +}; + +#define ARRAY_SIZE(array) (sizeof(array) / sizeof(*array)) + +static int _hcng_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 0; +} + +/*----------------------------------------------------------------------------* + * WLDR + *----------------------------------------------------------------------------*/ + +// per connection +static int _hcng_wldr_set(hc_sock_t *s /* XXX */) { return 0; } + +/*----------------------------------------------------------------------------* + * MAP-Me + *----------------------------------------------------------------------------*/ + +static int _hcng_mapme_set(hc_sock_t *socket, int enabled) { + msg_mapme_enable_t msg = {.header = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_MAPME_ENABLE, + .length = 1, + .seq_num = 0, + }, + .payload = { + .activate = enabled, + }}; + + hc_command_params_t params = { + .cmd = ACTION_SET, + .cmd_id = COMMAND_TYPE_MAPME_ENABLE, + .size_in = sizeof(cmd_mapme_enable_t), + .size_out = 0, + .parse = NULL, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, false); +} + +static int _hcng_mapme_set_discovery(hc_sock_t *socket, int enabled) { + msg_mapme_enable_t msg = { + .header = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_MAPME_SET_DISCOVERY, + .length = 1, + .seq_num = 0, + }, + .payload = { + .activate = enabled, + }}; + + hc_command_params_t params = { + .cmd = ACTION_SET, + .cmd_id = COMMAND_TYPE_MAPME_SET_DISCOVERY, + .size_in = sizeof(cmd_mapme_set_discovery_t), + .size_out = 0, + .parse = NULL, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, false); +} + +static int _hcng_mapme_set_timescale(hc_sock_t *socket, uint32_t timescale) { + msg_mapme_set_timescale_t msg = { + .header = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_MAPME_SET_TIMESCALE, + .length = 1, + .seq_num = 0, + }, + .payload = { + .timePeriod = timescale, + }}; + + hc_command_params_t params = { + .cmd = ACTION_SET, + .cmd_id = COMMAND_TYPE_MAPME_SET_TIMESCALE, + .size_in = sizeof(cmd_mapme_set_timescale_t), + .size_out = 0, + .parse = NULL, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, false); +} + +static int _hcng_mapme_set_retx(hc_sock_t *socket, uint32_t timescale) { + msg_mapme_set_retx_t msg = {.header = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_MAPME_SET_RETX, + .length = 1, + .seq_num = 0, + }, + .payload = { + .timePeriod = timescale, + }}; + + hc_command_params_t params = { + .cmd = ACTION_SET, + .cmd_id = COMMAND_TYPE_MAPME_SET_RETX, + .size_in = sizeof(msg_mapme_set_retx_t), + .size_out = 0, + .parse = NULL, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, false); +} + +static int _hcng_mapme_send_update(hc_sock_t *socket, hc_mapme_t *mapme) { + if (!IS_VALID_FAMILY(mapme->family)) return -1; + + msg_mapme_send_update_t msg = { + .header = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_MAPME_SEND_UPDATE, + .length = 1, + .seq_num = 0, + }, + }; + + hc_command_params_t params = { + .cmd = ACTION_UPDATE, + .cmd_id = COMMAND_TYPE_MAPME_SEND_UPDATE, + .size_in = sizeof(msg_mapme_send_update_t), + .size_out = 0, + .parse = NULL, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + NULL, false); +} + +/*----------------------------------------------------------------------------* + * Policy + *----------------------------------------------------------------------------*/ + +#ifdef WITH_POLICY + +/* POLICY CREATE */ + +static int _hcng_policy_create_internal(hc_sock_t *socket, hc_policy_t *policy, + bool async) { + 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), ¶ms, + NULL, async); +} + +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 (!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), ¶ms, + NULL, async); +} + +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) { + cmd_policy_list_item_t *item = (cmd_policy_list_item_t *)in; + + if (!IS_VALID_ADDRESS(&item->address, item->family)) { + 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->address, + .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) { + 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(cmd_policy_list_item_t), + .size_out = sizeof(hc_policy_t), + .parse = (HC_PARSE)hc_policy_parse, + }; + + return _hcng_execute_command(socket, (hc_msg_t *)&msg, sizeof(msg), ¶ms, + pdata, async); +} + +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); +} + +#endif /* WITH_POLICY */ + +/*----------------------------------------------------------------------------* + * Subscriptioins + *----------------------------------------------------------------------------*/ + +/* SUBSCRIPTION CREATE */ + +static hc_result_t *_subscription_create_serialize( + hc_sock_t *s, hc_subscription_t *subscription) { + msg_subscription_add_t msg = { + .header = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_SUBSCRIPTION_ADD, + .length = 1, + .seq_num = 0, + }, + .payload = {.topics = subscription->topics}}; + + hc_command_params_t params = { + .cmd = ACTION_CREATE, + .cmd_id = COMMAND_TYPE_SUBSCRIPTION_ADD, + .size_in = sizeof(cmd_subscription_add_t), + .size_out = 0, + .parse = NULL, + }; + + hc_result_t *res = malloc(sizeof(*res)); + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.subscription_add = msg.payload, + }, + .params = params, + .async = false, + .success = true, + }; + return res; +} + +static hc_result_t *_hcng_subscription_create_conf( + hc_sock_t *s, hc_subscription_t *subscription) { + return _subscription_create_serialize(s, subscription); +} + +static int _hcng_subscription_create(hc_sock_t *socket, + hc_subscription_t *subscriiption) { + hc_result_t *result = _subscription_create_serialize(socket, subscriiption); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + hc_result_free(result); + return ret; +} + +/* SUBSCRIPTION DELETE */ + +static hc_result_t *_subscription_delete_serialize( + hc_sock_t *s, hc_subscription_t *subscription) { + msg_subscription_remove_t msg = { + .header = + { + .message_type = REQUEST_LIGHT, + .command_id = COMMAND_TYPE_SUBSCRIPTION_REMOVE, + .length = 1, + .seq_num = 0, + }, + .payload = {.topics = subscription->topics}}; + + hc_command_params_t params = { + .cmd = ACTION_DELETE, + .cmd_id = COMMAND_TYPE_SUBSCRIPTION_REMOVE, + .size_in = sizeof(cmd_subscription_remove_t), + .size_out = 0, + .parse = NULL, + }; + + hc_result_t *res = malloc(sizeof(*res)); + *res = (hc_result_t){ + .msg = + (hc_msg_t){ + .hdr = msg.header, + .payload.subscription_remove = msg.payload, + }, + .params = params, + .async = false, + .success = true, + }; + return res; +} + +static hc_result_t *_hcng_subscription_delete_conf( + hc_sock_t *s, hc_subscription_t *subscription) { + return _subscription_delete_serialize(s, subscription); +} + +static int _hcng_subscription_delete(hc_sock_t *socket, + hc_subscription_t *subscriiption) { + hc_result_t *result = _subscription_delete_serialize(socket, subscriiption); + + int ret = INPUT_ERROR; + if (result->success) { + ret = _hcng_execute_command(socket, (hc_msg_t *)&result->msg, + sizeof(result->msg), &result->params, NULL, + result->async); + } + + hc_result_free(result); + return ret; +} + +/* RESULT */ +hc_msg_t *_hcng_result_get_msg(hc_result_t *result) { return &result->msg; } +int _hcng_result_get_cmd_id(hc_result_t *result) { + return result->params.cmd_id; +} +bool _hcng_result_get_success(hc_result_t *result) { return result->success; } + +static hc_sock_t hc_sock_light_ng_interface = (hc_sock_t){ + .hc_sock_get_next_seq = _hcng_sock_light_get_next_seq, + .hc_sock_set_nonblocking = _hcng_sock_light_set_nonblocking, + .hc_sock_get_fd = _hcng_sock_light_get_fd, + .hc_sock_connect = _hcng_sock_light_connect, + .hc_sock_get_available = _hcng_sock_light_get_available, + .hc_sock_send = _hcng_sock_light_send, + .hc_sock_recv = _hcng_sock_light_recv, + .hc_sock_process = _hcng_sock_light_process, + .hc_sock_callback = _hcng_sock_light_callback, + .hc_sock_reset = _hcng_sock_light_reset, + .hc_sock_free = _hcng_sock_light_free, + .hc_sock_increment_woff = _hcng_sock_increment_woff, + .hc_sock_prepare_send = _hcng_sock_prepare_send, + .hc_sock_set_recv_timeout_ms = _hcng_sock_set_recv_timeout_ms, + .hc_listener_create = _hcng_listener_create, + .hc_listener_create_async = _hcng_listener_create_async, + .hc_listener_get = _hcng_listener_get, + .hc_listener_delete = _hcng_listener_delete, + .hc_listener_delete_async = _hcng_listener_delete_async, + .hc_listener_list = _hcng_listener_list, + .hc_listener_list_async = _hcng_listener_list_async, + .hc_connection_create = _hcng_connection_create, + .hc_connection_create_async = _hcng_connection_create_async, + .hc_connection_get = _hcng_connection_get, + .hc_connection_update_by_id = _hcng_connection_update_by_id, + .hc_connection_update = _hcng_connection_update, + .hc_connection_delete = _hcng_connection_delete, + .hc_connection_delete_async = _hcng_connection_delete_async, + .hc_connection_list = _hcng_connection_list, + .hc_connection_list_async = _hcng_connection_list_async, + .hc_connection_set_admin_state = _hcng_connection_set_admin_state, + .hc_connection_set_admin_state_async = + _hcng_connection_set_admin_state_async, + +#ifdef WITH_POLICY + .hc_connection_set_priority = _hcng_connection_set_priority, + .hc_connection_set_priority_async = _hcng_connection_set_priority_async, + .hc_connection_set_tags = _hcng_connection_set_tags, + .hc_connection_set_tags_async = _hcng_connection_set_tags_async, +#endif // WITH_POLICY + + .hc_face_create = _hcng_face_create, + .hc_face_get = _hcng_face_get, + .hc_face_delete = _hcng_face_delete, + .hc_face_list = _hcng_face_list, + .hc_face_list_async = _hcng_face_list_async, + .hc_face_set_admin_state = _hcng_face_set_admin_state, + +#ifdef WITH_POLICY + .hc_face_set_priority = _hcng_face_set_priority, + .hc_face_set_tags = _hcng_face_set_tags, +#endif // WITH_POLICY + .hc_subscription_create = _hcng_subscription_create, + .hc_subscription_delete = _hcng_subscription_delete, + + .hc_route_create = _hcng_route_create, + .hc_route_create_async = _hcng_route_create_async, + .hc_route_delete = _hcng_route_delete, + .hc_route_delete_async = _hcng_route_delete_async, + .hc_route_list = _hcng_route_list, + .hc_route_list_async = _hcng_route_list_async, + + .hc_punting_create = _hcng_punting_create, + .hc_punting_create_async = _hcng_punting_create_async, + .hc_punting_get = _hcng_punting_get, + .hc_punting_delete = _hcng_punting_delete, + .hc_punting_list = _hcng_punting_list, + + .hc_cache_set_store = _hcng_cache_set_store, + .hc_cache_set_store_async = _hcng_cache_set_store_async, + .hc_cache_set_serve = _hcng_cache_set_serve, + .hc_cache_set_serve_async = _hcng_cache_set_serve_async, + .hc_cache_clear = _hcng_cache_clear, + .hc_cache_list = _hcng_cache_list, + + .hc_strategy_list = _hcng_strategy_list, + .hc_strategy_set = _hcng_strategy_set, + .hc_strategy_add_local_prefix = _hcng_strategy_add_local_prefix, + .hc_wldr_set = _hcng_wldr_set, + + .hc_mapme_set = _hcng_mapme_set, + .hc_mapme_set_discovery = _hcng_mapme_set_discovery, + .hc_mapme_set_timescale = _hcng_mapme_set_timescale, + .hc_mapme_set_retx = _hcng_mapme_set_retx, + .hc_mapme_send_update = _hcng_mapme_send_update, + +#ifdef WITH_POLICY + .hc_policy_create = _hcng_policy_create, + .hc_policy_create_async = _hcng_policy_create_async, + .hc_policy_delete = _hcng_policy_delete, + .hc_policy_delete_async = _hcng_policy_delete_async, + .hc_policy_list = _hcng_policy_list, + .hc_policy_list_async = _hcng_policy_list_async, +#endif // WITH_POLICY + + .hc_listener_create_conf = _hcng_listener_create_conf, + .hc_listener_list_conf = _hcng_listener_list_conf, + .hc_connection_create_conf = _hcng_connection_create_conf, + .hc_connection_delete_conf = _hcng_connection_delete_conf, + .hc_route_create_conf = _hcng_route_create_conf, + .hc_strategy_set_conf = _hcng_strategy_set_conf, + .hc_strategy_add_local_prefix_conf = _hcng_strategy_add_local_prefix_conf, + .hc_subscription_create_conf = _hcng_subscription_create_conf, + .hc_subscription_delete_conf = _hcng_subscription_delete_conf, + + .hc_result_get_msg = _hcng_result_get_msg, + .hc_result_get_cmd_id = _hcng_result_get_cmd_id, + .hc_result_get_success = _hcng_result_get_success, +}; + +// 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_ng_interface; + s->url = url ? strdup(url) : NULL; + + s->fd = socket(AF_INET, SOCK_DGRAM, 0); + if (s->fd < 0) goto ERR_SOCKET; + + if (_hcng_sock_set_recv_timeout_ms((hc_sock_t *)s, + DEFAULT_SOCK_RECV_TIMEOUT_MS) < 0) + goto ERR_SOCKET; + + if (_hcng_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; +} diff --git a/ctrl/libhicnctrl/src/modules/hicn_plugin_api.c b/ctrl/libhicnctrl/src/modules/hicn_plugin_api.c index e59a2e41e..6d1baa786 100644 --- a/ctrl/libhicnctrl/src/modules/hicn_plugin_api.c +++ b/ctrl/libhicnctrl/src/modules/hicn_plugin_api.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: @@ -18,8 +18,6 @@ * \brief Implementation of hICN control library API */ -#include "api_private.h" - #include <assert.h> // assert #include <fcntl.h> // fcntl #include <math.h> // log2 @@ -29,40 +27,10 @@ #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 +#include <vppinfra/clib.h> +#include <vpp_plugins/hicn/error.h> -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, -}; +#include "api_private.h" /** * Messages to the forwarder might be multiplexed thanks to the seqNum fields in @@ -81,7 +49,6 @@ struct hc_sock_vpp_s { vapi_ctx_t g_vapi_ctx_instance; char *url; - int fd; size_t roff; /**< Read offset */ size_t woff; /**< Write offset */ @@ -94,43 +61,42 @@ struct hc_sock_vpp_s { typedef struct hc_sock_vpp_s hc_sock_vpp_t; -#define TO_HC_SOCK_VPP(s) (hc_sock_vpp_t*)(s) +#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) \ +#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; +#define _(a) vapi_payload_##a a; foreach_hc_command #undef _ } hc_msg_payload_t; -typedef struct __attribute__ ((__packed__)) { +typedef struct __attribute__((__packed__)) { hc_msg_header_t hdr; hc_msg_payload_t payload; } hc_hicnp_t; -typedef void (* NTOH)(void *msg); +typedef void (*NTOH)(void *msg); typedef struct __attribute__((__packed__)) { hc_data_t *data; @@ -138,7 +104,7 @@ typedef struct __attribute__((__packed__)) { } callback_ctx_t; typedef struct __attribute__((__packed__)) { - hc_hicnp_t * hicnp_msg; + hc_hicnp_t *hicnp_msg; vapi_cb_t callback; callback_ctx_t *callback_ctx; NTOH ntoh; @@ -151,11 +117,9 @@ typedef struct __attribute__((__packed__)) { 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) { @@ -174,8 +138,7 @@ 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; + if (rv != VAPI_OK) goto ERR_CONNECT; return 0; @@ -184,7 +147,8 @@ ERR_CONNECT: return -1; } -static int _hc_sock_vpp_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, int seq) { +static int _hc_sock_vpp_send(hc_sock_t *s, hc_msg_t *msg, size_t msglen, + uint32_t seq) { return -1; } @@ -199,16 +163,16 @@ static int _hc_sock_vpp_recv(hc_sock_t *s) { } static int _hc_sock_vpp_process(hc_sock_t *s, hc_data_t **pdata) { - //NOT IMPLEMENTED + // NOT IMPLEMENTED return -1; } -static int _hc_sock_vpp_callback(hc_sock_t * socket, hc_data_t ** pdata) { +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) { +static int _hc_sock_vpp_reset(hc_sock_t *socket) { // NOT IMPLEMENTED return -1; } @@ -217,7 +181,6 @@ static int _hc_sock_vpp_reset(hc_sock_t * socket) { * Command-specific structures and functions ******************************************************************************/ - /*----------------------------------------------------------------------------* * Listeners *----------------------------------------------------------------------------*/ @@ -236,7 +199,7 @@ static int _hc_listener_create_async(hc_sock_t *s, hc_listener_t *listener) { /* LISTENER GET */ static int _hc_listener_get(hc_sock_t *s, hc_listener_t *listener, - hc_listener_t **listener_found) { + hc_listener_t **listener_found) { // NOT IMPLEMENTED return -1; } @@ -253,33 +216,32 @@ static int _hc_listener_delete_async(hc_sock_t *s, hc_listener_t *listener) { return -1; } -static vapi_error_e process_ip_info(struct vapi_ctx_s *ctx, - void *callback_ctx, - vapi_error_e rv, - bool is_last, +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; + 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); + data->buffer = + realloc(data->buffer, sizeof(hc_listener_t) * data->size * 2); - if (!data->buffer) - return VAPI_ENOMEM; + if (!data->buffer) return VAPI_ENOMEM; - data->size *=2; + data->size *= 2; } - hc_listener_t * listener = (hc_listener_t *)(data->buffer + data->current * sizeof(hc_listener_t)); + hc_listener_t *listener = + (hc_listener_t *)(data->buffer + data->current * sizeof(hc_listener_t)); + memset(listener, 0, 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); + 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); + } else { + memcpy(listener->local_addr.v6.as_u8, reply->prefix.address.un.ip6, + IPV6_ADDR_LEN); listener->family = AF_INET6; } @@ -293,31 +255,26 @@ typedef struct { 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) { +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 (reply == NULL || rv != VAPI_OK) - return rv; - - if (is_last) - return 0; + 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); + data->buffer = + realloc(data->buffer, sizeof(hc_vapi_interface_t) * data->size * 2); - if (!data->buffer) - return VAPI_ENOMEM; + if (!data->buffer) return VAPI_ENOMEM; - data->size *=2; + data->size *= 2; } - hc_vapi_interface_t *swif = &((hc_vapi_interface_t*)data->buffer)[data->current]; + 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); @@ -327,7 +284,6 @@ static vapi_error_e listener_list_complete_cb ( 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); @@ -344,14 +300,14 @@ static int _hc_listener_list(hc_sock_t *socket, hc_data_t **pdata) { 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); + 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); + hc_data_t *data2 = hc_data_create(0, 1, NULL); if (!data2) { retval = -1; @@ -362,12 +318,13 @@ static int _hc_listener_list(hc_sock_t *socket, hc_data_t **pdata) { data->size = 1; if (!data->buffer) { - free (data); + 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); + 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); @@ -381,28 +338,34 @@ static int _hc_listener_list(hc_sock_t *socket, hc_data_t **pdata) { data2->out_element_size = 1; if (!data2->buffer) { - free (data2->buffer); - retval =1 -1; + free(data2->buffer); + retval = -1; goto CLEAN; } /* Query the forwarder for each interface */ - for(int i = 0; i < data->current; i++) { + 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); + 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); + 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); + 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; + 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 = FACE_TYPE_HICN; } if (retval) goto CLEAN; @@ -417,7 +380,7 @@ FREE_DATA: data2->size = data2->current; data2->out_element_size = sizeof(hc_listener_t); *pdata = data2; - END: +END: vapi_unlock(); return retval; } @@ -438,7 +401,8 @@ static int _hc_connection_create(hc_sock_t *s, hc_connection_t *connection) { return -1; } -static int _hc_connection_create_async(hc_sock_t *s, hc_connection_t *connection) { +static int _hc_connection_create_async(hc_sock_t *s, + hc_connection_t *connection) { // NOT IMPLEMENTED return -1; } @@ -446,17 +410,20 @@ static int _hc_connection_create_async(hc_sock_t *s, hc_connection_t *connection /* CONNECTION GET */ static int _hc_connection_get(hc_sock_t *s, hc_connection_t *connection, - hc_connection_t **connection_found) { + 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) { +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) { +static int _hc_connection_update(hc_sock_t *s, + hc_connection_t *connection_current, + hc_connection_t *connection_updated) { // Not implemented return -1; } @@ -468,7 +435,8 @@ static int _hc_connection_delete(hc_sock_t *s, hc_connection_t *connection) { return -1; } -static int _hc_connection_delete_async(hc_sock_t *s, hc_connection_t *connection) { +static int _hc_connection_delete_async(hc_sock_t *s, + hc_connection_t *connection) { // NOT IMPLEMENTED return -1; } @@ -487,39 +455,47 @@ static int _hc_connection_list_async(hc_sock_t *s, hc_data_t **pdata) { /* 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) { +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) { + 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) { +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) { +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 +#endif // WITH_POLICY -static int _hc_connection_set_tags(hc_sock_t * s, const char * conn_id_or_name, policy_tags_t tags) { +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) { +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; } @@ -528,66 +504,65 @@ static int _hc_connection_set_tags_async(hc_sock_t * s, const char * conn_id_or_ * 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; +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; + if (reply->retval != VAPI_OK) return reply->retval; - u32 * uei = (u32*) callback_ctx; + 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; +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; + 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; +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 _hc_route_create_internal(hc_sock_t *socket, hc_route_t *route, bool async) { +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; + int ret = -1; vapi_lock(); - vapi_msg_ip_route_add_del *hicnp_msg = vapi_alloc_ip_route_add_del(s->g_vapi_ctx_instance, 1); + 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); + 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.paths[0].proto = FIB_API_PATH_NH_PROTO_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.paths[0].proto = FIB_API_PATH_NH_PROTO_IP6; } hicnp_msg->payload.route.prefix.len = route->len; @@ -596,87 +571,101 @@ static int _hc_route_create_internal(hc_sock_t *socket, hc_route_t *route, bool 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; + face->face.netdevice.index = ~0; + face->id = INVALID_FACE_ID; - memcpy(msg->payload.dst_addr.un.ip4, &face->face.remote_addr.v4, sizeof(ip4_address_t)); - msg->payload.dst_addr.af = ADDRESS_IP4; + switch (face->face.type) { + case FACE_TYPE_HICN: { + if (ip_address_is_v4((ip_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; + } - } 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)))) { + hicnp_msg->payload.route.paths[0].type = FIB_API_PATH_TYPE_NORMAL; + hicnp_msg->payload.route.paths[0].flags = FIB_API_PATH_FLAG_NONE; - 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; + break; + } + case FACE_TYPE_UDP: { + vapi_msg_hicn_api_udp_tunnel_add_del *msg = NULL; + u32 uei = ~0; + + if (ip_address_is_v4((ip_address_t *)(&(face->face.remote_addr))) && + ip_address_is_v4((ip_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 (!ip_address_is_v4( + (ip_address_t *)(&(route->face.face.remote_addr))) && + !ip_address_is_v4( + (ip_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_IP6; + + 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; + } - memcpy(msg->payload.dst_addr.un.ip6, &face->face.remote_addr.v6, sizeof(ip6_address_t)); - msg->payload.dst_addr.af = ADDRESS_IP6; + msg->payload.src_port = face->face.local_port; + msg->payload.dst_port = face->face.remote_port; + msg->payload.is_add = 1; - } else { - //NOT IMPLEMENTED - ret = -1; - goto done; - } + int ret = vapi_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance, msg, + create_udp_tunnel_cb, &uei); - msg->payload.src_port = face->face.local_port; - msg->payload.dst_port = face->face.remote_port; - msg->payload.is_add = 1; + if (ret) { + ERROR("Error in vapi_hicn_api_udp_tunnel_add_del"); + vapi_msg_free(s->g_vapi_ctx_instance, hicnp_msg); + goto done; + } - int ret = vapi_hicn_api_udp_tunnel_add_del(s->g_vapi_ctx_instance, msg, create_udp_tunnel_cb, &uei); + 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; - if(ret) { - vapi_msg_free(s->g_vapi_ctx_instance, hicnp_msg); - goto done; - } + face->face.netdevice.index = uei; - 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; - } + break; + } default: ret = -1; goto done; } - ret = vapi_ip_route_add_del(s->g_vapi_ctx_instance, hicnp_msg, parse_route_create, NULL); + ret = vapi_ip_route_add_del(s->g_vapi_ctx_instance, hicnp_msg, + parse_route_create, NULL); - if (ret) + if (ret) { + ERROR("Error in vapi_ip_route_add_del"); goto done; + } - vapi_msg_hicn_api_enable_disable *msg = vapi_alloc_hicn_api_enable_disable(s->g_vapi_ctx_instance); + 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 { + } else { memcpy(&msg->payload.prefix.address.un.ip6[0], &route->remote_addr.v6, 16); msg->payload.prefix.address.af = ADDRESS_IP6; } @@ -684,7 +673,13 @@ static int _hc_route_create_internal(hc_sock_t *socket, hc_route_t *route, bool 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); + ret = vapi_hicn_api_enable_disable(s->g_vapi_ctx_instance, msg, + hicn_enable_cb, &face->id); + + if (ret) { + ERROR("Error in vapi_hicn_api_enable_disable"); + } + done: vapi_unlock(); return ret; @@ -699,32 +694,63 @@ static int _hc_route_create_async(hc_sock_t *s, hc_route_t *route) { } /* 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; +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 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 int _hc_route_delete_internal(hc_sock_t *socket, hc_route_t *route, bool async) { +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); + + 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 *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); + 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); + } 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; } @@ -735,34 +761,41 @@ static int _hc_route_delete_internal(hc_sock_t *socket, hc_route_t *route, bool 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; + case FACE_TYPE_HICN: { + if (ip_address_is_v4((ip_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_TYPE_NORMAL; + 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); + ret = vapi_ip_route_add_del(s->g_vapi_ctx_instance, hicnp_msg, + parse_route_delete, NULL); + + if (ret) { + ERROR("Error in vapi_ip_route_add_del in route delete"); + goto done; + } + +done: vapi_unlock(); return ret; @@ -776,33 +809,31 @@ 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; +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; + 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)); + 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)); + 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; + break; } face->face.local_port = reply->udp_encap.src_port; @@ -811,35 +842,35 @@ static vapi_error_e parse_udp_encap_list( vapi_ctx_t ctx, 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: - { +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){ + 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; + 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; + memcpy(&face->face.remote_addr.v6, &(path->nh.address.ip6), + sizeof(ip6_address_t)); + break; default: - break; + break; } face->face.netdevice.index = path->sw_if_index; - } - break; - case FIB_API_PATH_TYPE_UDP_ENCAP: - { + } 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; + // 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; } @@ -852,32 +883,33 @@ typedef struct hicn_route_socket_s { 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; +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 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; + hc_route_t *route = &((hc_route_t *)(data->buffer))[i]; + + if (ip_address_is_v4((ip_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; } } } @@ -885,14 +917,10 @@ static vapi_error_e parse_route_list( vapi_ctx_t ctx, 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; +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; @@ -900,43 +928,41 @@ static vapi_error_e parse_hicn_route_list( vapi_ctx_t ctx, 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; + if (!data->buffer) return VAPI_ENOMEM; - data->size =new_size; + data->size = new_size; } for (int i = 0; i < reply->nfaces; i++) { - hc_route_t * route = &((hc_route_t*)(data->buffer))[data->current]; + 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; + 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) { +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); + hc_data_t *data = hc_data_create(0, sizeof(hc_route_t), NULL); int ret = VAPI_OK; - if (!data){ + if (!data) { ret = -1; goto err; } @@ -949,10 +975,10 @@ static int _hc_route_list_internal(hc_sock_t *socket, hc_data_t **pdata, bool as goto err_free; } - ret = vapi_hicn_api_routes_dump(s->g_vapi_ctx_instance, msg, parse_hicn_route_list, data); + ret = vapi_hicn_api_routes_dump(s->g_vapi_ctx_instance, msg, + parse_hicn_route_list, data); - if (ret != VAPI_OK) - goto err_free; + 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); @@ -960,29 +986,30 @@ static int _hc_route_list_internal(hc_sock_t *socket, hc_data_t **pdata, bool as hicnp_msg->payload.table.is_ip6 = 1; hicn_route_socket_t ctx = { - .data = data, - .s = socket, + .data = data, + .s = socket, }; - ret = vapi_ip_route_dump(s->g_vapi_ctx_instance, hicnp_msg, parse_route_list, &ctx); + 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); + ret = vapi_ip_route_dump(s->g_vapi_ctx_instance, hicnp_msg, parse_route_list, + &ctx); - if (ret != VAPI_OK) - goto err_free; + if (ret != VAPI_OK) goto err_free; *pdata = data; vapi_unlock(); return ret; - err_free: +err_free: free(data); - err: +err: vapi_unlock(); return ret; } @@ -1008,17 +1035,19 @@ static int _hc_route_list_async(hc_sock_t *s) { * *----------------------------------------------------------------------------*/ -static int _hc_face_create(hc_sock_t *s, hc_face_t *face) { - ERROR("Face creation implemented."); +static int _hc_face_create(hc_sock_t *socket, hc_face_t *face) { + ERROR("Face creation not implemented."); return -1; } -static int _hc_face_get(hc_sock_t * socket, hc_face_t * face, hc_face_t ** face_found) { +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) { +static int _hc_face_delete(hc_sock_t *s, hc_face_t *face, + uint8_t delete_listener) { ERROR("Face deletion not implemented."); return -1; } @@ -1030,9 +1059,7 @@ static int _hc_face_list(hc_sock_t *s, hc_data_t **pdata) { return -1; } -static int _hc_face_list_async(hc_sock_t *s) { - return 0; -} +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 @@ -1041,22 +1068,25 @@ static int _hc_face_set_admin_state( } #ifdef WITH_POLICY -static int _hc_face_set_priority(hc_sock_t * s, const char * conn_id_or_name, uint32_t priority) { +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) { +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 +#endif // WITH_POLICY /*----------------------------------------------------------------------------* * Punting *----------------------------------------------------------------------------*/ -static int _hc_punting_create_internal(hc_sock_t *s, hc_punting_t *punting, bool async) { +static int _hc_punting_create_internal(hc_sock_t *s, hc_punting_t *punting, + bool async) { return -1; } @@ -1069,7 +1099,7 @@ static int _hc_punting_create_async(hc_sock_t *s, hc_punting_t *punting) { } static int _hc_punting_get(hc_sock_t *s, hc_punting_t *punting, - hc_punting_t **punting_found) { + hc_punting_t **punting_found) { ERROR("hc_punting_get not (yet) implemented."); return -1; } @@ -1088,28 +1118,30 @@ static int _hc_punting_list(hc_sock_t *s, hc_data_t **pdata) { * Cache *----------------------------------------------------------------------------*/ -static int _hc_cache_set_store_internal(hc_sock_t *s, int enabled, bool async) { +static int _hc_cache_set_store_internal(hc_sock_t *s, hc_cache_t *cache, + 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(hc_sock_t *s, hc_cache_t *cache) { + return _hc_cache_set_store_internal(s, cache, 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_store_async(hc_sock_t *s, hc_cache_t *cache) { + return _hc_cache_set_store_internal(s, cache, true); } -static int _hc_cache_set_serve_internal(hc_sock_t *s, int enabled, bool async) { +static int _hc_cache_set_serve_internal(hc_sock_t *s, hc_cache_t *cache, + 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(hc_sock_t *s, hc_cache_t *cache) { + return _hc_cache_set_serve_internal(s, cache, false); } -static int _hc_cache_set_serve_async(hc_sock_t *s, int enabled) { - return _hc_cache_set_serve_internal(s, enabled, true); +static int _hc_cache_set_serve_async(hc_sock_t *s, hc_cache_t *cache) { + return _hc_cache_set_serve_internal(s, cache, true); } /*----------------------------------------------------------------------------* @@ -1117,12 +1149,15 @@ static int _hc_cache_set_serve_async(hc_sock_t *s, int enabled) { *----------------------------------------------------------------------------*/ // per prefix -static int _hc_strategy_set(hc_sock_t *s /* XXX */) { return 0; } +static int _hc_strategy_set(hc_sock_t *s, hc_strategy_t *strategy) { return 0; } -static int _hc_strategy_list(hc_sock_t *s, hc_data_t **data) { +static int _hc_strategy_add_local_prefix(hc_sock_t *s, + hc_strategy_t *strategy) { return 0; } +static int _hc_strategy_list(hc_sock_t *s, hc_data_t **data) { return 0; } + /*----------------------------------------------------------------------------* * WLDR *----------------------------------------------------------------------------*/ @@ -1138,9 +1173,11 @@ 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_timescale(hc_sock_t *s, uint32_t timescale) { + return 0; +} -static int _hc_mapme_set_retx(hc_sock_t *s, double timescale) { return 0; } +static int _hc_mapme_set_retx(hc_sock_t *s, uint32_t timescale) { return 0; } /*----------------------------------------------------------------------------* * Policy @@ -1150,51 +1187,99 @@ static int _hc_mapme_set_retx(hc_sock_t *s, double timescale) { return 0; } /* POLICY CREATE */ -static int _hc_policy_create_internal(hc_sock_t * socket, hc_policy_t * policy, bool async) { +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) { +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) { +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) { +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) { +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) { +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) { +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) { +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) { +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) { +/*----------------------------------------------------------------------------* + * Configuration + *----------------------------------------------------------------------------*/ + +typedef struct hc_result_s { + void *_; +} hc_result_t; + +static hc_result_t *_hc_listener_create_conf(hc_sock_t *s, + hc_listener_t *listener) { + ERROR("Not implemented."); + return NULL; +} +static hc_result_t *_hc_connection_create_conf(hc_sock_t *s, + hc_connection_t *connection) { + ERROR("Not implemented."); + return NULL; +} +static hc_result_t *_hc_route_create_conf(hc_sock_t *s, hc_route_t *route) { + ERROR("Not implemented."); + return NULL; +} +static hc_result_t *_hc_strategy_set_conf(hc_sock_t *s, + hc_strategy_t *strategy) { + ERROR("Not implemented."); + return NULL; +} +static hc_result_t *_hc_strategy_add_local_prefix_conf( + hc_sock_t *s, hc_strategy_t *strategy) { + ERROR("Not implemented."); + return NULL; +} + +hc_msg_t *_hc_result_get_msg(hc_result_t *result) { + ERROR("Not implemented."); + return NULL; +} +int _hc_result_get_cmd_id(hc_result_t *result) { + ERROR("Not implemented."); + return -1; +} +bool _hc_result_get_success(hc_result_t *result) { + ERROR("Not implemented."); + return false; +} +void _hc_result_free(hc_result_t *result) { free(result); } + +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, @@ -1230,7 +1315,7 @@ static hc_sock_t hc_sock_vpp_interface = (hc_sock_t) { .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 +#endif // WITH_POLICY .hc_face_create = _hc_face_create, .hc_face_get = _hc_face_get, @@ -1242,7 +1327,7 @@ static hc_sock_t hc_sock_vpp_interface = (hc_sock_t) { #ifdef WITH_POLICY .hc_face_set_priority = _hc_face_set_priority, .hc_face_set_tags = _hc_face_set_tags, -#endif // WITH_POLICY +#endif // WITH_POLICY .hc_route_create = _hc_route_create, .hc_route_create_async = _hc_route_create_async, @@ -1264,6 +1349,7 @@ static hc_sock_t hc_sock_vpp_interface = (hc_sock_t) { .hc_strategy_list = _hc_strategy_list, .hc_strategy_set = _hc_strategy_set, + .hc_strategy_add_local_prefix = _hc_strategy_add_local_prefix, .hc_wldr_set = _hc_wldr_set, .hc_mapme_set = _hc_mapme_set, @@ -1277,16 +1363,27 @@ static hc_sock_t hc_sock_vpp_interface = (hc_sock_t) { .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_policy_list_async = _hc_policy_list_async, +#endif // WITH_POLICY + + .hc_listener_create_conf = _hc_listener_create_conf, + .hc_connection_create_conf = _hc_connection_create_conf, + .hc_route_create_conf = _hc_route_create_conf, + .hc_strategy_set_conf = _hc_strategy_set_conf, + .hc_strategy_add_local_prefix_conf = _hc_strategy_add_local_prefix_conf, + + .hc_result_get_msg = _hc_result_get_msg, + .hc_result_get_cmd_id = _hc_result_get_cmd_id, + .hc_result_get_success = _hc_result_get_success, + .hc_result_free = _hc_result_free, }; hc_sock_t *_hc_sock_create_url(const char *url) { - // NOT IMPLEMENTED - return NULL; -} + if (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; @@ -1302,4 +1399,4 @@ hc_sock_t *_hc_sock_create(void) { ERR_SOCK: return NULL; -}
\ No newline at end of file +} diff --git a/ctrl/libhicnctrl/src/route.c b/ctrl/libhicnctrl/src/route.c index 703b4763f..f59dbce7c 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 */ + 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(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 = 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, 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 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]; + 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/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/CMakeLists.txt b/ctrl/sysrepo-plugins/CMakeLists.txt index 2412d5688..0765f75d8 100644 --- a/ctrl/sysrepo-plugins/CMakeLists.txt +++ b/ctrl/sysrepo-plugins/CMakeLists.txt @@ -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: @@ -41,13 +41,13 @@ 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) +find_package(Vpp ${VPP_DEFAULT_VERSION} REQUIRED) if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) - find_package(HicnPlugin REQUIRED) + find_package(HicnPlugin ${CURRENT_VERSION} REQUIRED) else() list(APPEND DEPENDENCIES - hicn_plugin + ${HICNPLUGIN_SHARED} ) endif() diff --git a/ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake b/ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake index 323c9d01a..cba9adf1f 100644 --- a/ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake +++ b/ctrl/sysrepo-plugins/cmake/Modules/Packaging.cmake @@ -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,17 +15,22 @@ # Packages section ###################### +############################################################## +# Get VPP version +############################################################## +list(GET VPP_DEFAULT_VERSION 0 VPP_VERSION) + 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)" + "hicn-plugin (= ${VPP_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" + "hicn-plugin = ${VPP_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 index 5ba7045c1..f8a1e64aa 100644 --- a/ctrl/sysrepo-plugins/hicn-light/CMakeLists.txt +++ b/ctrl/sysrepo-plugins/hicn-light/CMakeLists.txt @@ -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/ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt b/ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt index 85da0d3e9..b5faab705 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/CMakeLists.txt @@ -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/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c index 6cfc0b52b..b2495f730 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.c @@ -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: @@ -21,8 +21,6 @@ #include "hicn_light.h" #include "model/hicn_model.h" - - sr_subscription_ctx_t *subscription = NULL; volatile int exit_application = 0; @@ -37,7 +35,6 @@ int sr_plugin_init_cb(sr_session_ctx_t *session, void **private_ctx) { hicn_subscribe_events(session, &subscription); - /* set subscription as our private context */ *private_ctx = subscription; return SR_ERR_OK; diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.h b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.h index 16f65e5c4..cea2851c9 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.h +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light.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/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c index 6c4f938ce..08551b470 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.c @@ -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: @@ -14,20 +14,17 @@ */ #include "hicn_light_comm.h" -hc_sock_t * hsocket; +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; - + 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); + 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 index ca67cf0b7..c03d59c30 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.h +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/hicn_light_comm.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: @@ -18,7 +18,6 @@ #include <sysrepo.h> #include <sysrepo/values.h> - #include <hicn/ctrl/api.h> #ifndef HICN_THIS_FUNC @@ -37,23 +36,20 @@ } \ } while (0) - - #define ARG_CHECK2(retval, arg1, arg2) \ - ARG_CHECK(retval, arg1); \ - ARG_CHECK(retval, 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) - + 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; +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 index 47e07d196..d32fd55ef 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.c +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.c @@ -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: @@ -22,72 +22,67 @@ #include "tlock.h" #include "../hicn_light.h" #include "../hicn_light_comm.h" - - +#include <hicn/util/sstrncpy.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) { - +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")){ - + 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.family = AF_INET6; face.face.local_addr.v6.as_in6addr = *dst; - }else{ - SRP_LOG_DBGMSG("Invalid local IP address"); - return SR_ERR_OPERATION_FAILED; + } 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")){ + 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.family = AF_INET6; face.face.remote_addr.v6.as_in6addr = *dst; - }else{ - SRP_LOG_DBGMSG("Invalid local IP address"); - return SR_ERR_OPERATION_FAILED; + } 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; + face.face.netdevice.index = + input[4].data.uint32_val; // This is the idx number of interface int rc; + face.id = 0; // can be empty + rc = strcpy_s(face.name, sizeof(face.name), "hicn_face"); + if (rc != EOK) return SR_ERR_OPERATION_FAILED; + face.face.type = 1; + rc = hc_face_create(hsocket, &face); if (rc > 0) { - SRP_LOG_DBGMSG("Face added successfully"); - return SR_ERR_OK; + SRP_LOG_DBGMSG("Face added successfully"); + return SR_ERR_OK; } SRP_LOG_DBGMSG("Operation Failed"); @@ -97,92 +92,84 @@ static int hicn_face_ip_add_cb(sr_session_ctx_t *session, const char *path, cons /** * @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) { - +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_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) { +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"); - SRP_LOG_DBG_MSG("hicn route add received successfully"); + hc_route_t * route; - hc_route_t * route; + if(strcmp(input[0].data.string_val,"-1")){ - 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; - 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")){ - }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; - 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; - } + }else{ + SRP_LOG_DBG_MSG("Invalid local IP address"); + return SR_ERR_OPERATION_FAILED; + } -hc_route_create(hsocket, route); -*/ - return SR_ERR_OK; + 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: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: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; - } + 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; @@ -191,5 +178,4 @@ 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 index e6e857bff..be70bc711 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.h +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/model/hicn_model.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: @@ -18,7 +18,6 @@ #include "../hicn_light_comm.h" - #define MEM_ALIGN 4096 // Number of locks is equal to number of nodes in hicn-state @@ -27,8 +26,7 @@ #define NLOCKS 5 #define LOCK_INIT 0 - -enum locks_name {lstate, lstrategy, lstrategies, lroute, lface_ip_params}; +enum locks_name { lstate, lstrategy, lstrategies, lroute, lface_ip_params }; #define NSTATE_LEAVES 15 #define NSTRATEGY_LEAVES 1 diff --git a/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c b/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c index 2f7b11efa..ba788d3a0 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.c @@ -1,21 +1,16 @@ -#include"tlock.h" +#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_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_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]++; -} +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 index 36698115a..6840be1c0 100644 --- a/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.h +++ b/ctrl/sysrepo-plugins/hicn-light/plugin/model/tlock.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,19 +13,17 @@ * 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 -// 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 - +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 ); +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 index 10e106f51..9204e2766 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/CMakeLists.txt +++ b/ctrl/sysrepo-plugins/hicn-plugin/CMakeLists.txt @@ -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/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c index bbcc2e9bf..fe2e6350f 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019-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,12 +22,10 @@ #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(); @@ -38,11 +36,10 @@ int sr_plugin_init_cb(sr_session_ctx_t *session, void **private_ctx) { // HICN subscribe hicn_subscribe_events(session, &subscription); - //sr_subscription_ctx_t *subscription2 = NULL; + // sr_subscription_ctx_t *subscription2 = NULL; // IETF subscribe - //ietf_subscribe_events(session, &subscription2); - + // ietf_subscribe_events(session, &subscription2); /* set subscription as our private context */ *private_ctx = subscription; @@ -51,7 +48,6 @@ 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) { - /* subscription was set as our private context */ sr_unsubscribe(private_ctx); hicn_disconnect_vpp(); diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.h index 0890c3f03..15aea72d6 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.h +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_plugin.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: @@ -23,7 +23,6 @@ #include "hicn_vpp_comm.h" - /** * @brief initialize function for sysrepo plugin, * In this function we connect to vpp from one side diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c index 73eab66ea..41ab3d057 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.c @@ -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: @@ -19,15 +19,9 @@ #define MAX_OUTSTANDING_REQUESTS 4 #define RESPONSE_QUEUE_SIZE 2 - -vapi_ctx_t g_vapi_ctx_instance=NULL; - - - - +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, diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.h index 9abe4e5d4..cb5eefcbe 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.h +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/hicn_vpp_comm.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,13 +13,11 @@ * 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> @@ -40,7 +38,6 @@ extern vapi_ctx_t g_vapi_ctx_instance; - /** * @brief This macro is interface.c to communicate with vpp */ @@ -48,36 +45,34 @@ extern vapi_ctx_t g_vapi_ctx_instance; #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 + * @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); \ - } \ +#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) + 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) + 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 diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c index 3e0c90cf9..9a74e6280 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016-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: @@ -29,11 +29,9 @@ #include "ietf_interface.h" #include "../hicn_vpp_comm.h" - DEFINE_VAPI_MSG_IDS_INTERFACE_API_JSON; -typedef struct hicn_interface_ -{ +typedef struct hicn_interface_ { u32 sw_if_index; char interface_name[VPP_INTFC_NAME_LEN]; u8 l2_address[VPP_MAC_ADDRESS_LEN]; @@ -44,207 +42,202 @@ typedef struct hicn_interface_ u8 link_up_down; } hicnIntfc; -typedef struct _ietf_sw_interface_dump_ctx -{ +typedef struct _ietf_sw_interface_dump_ctx { u8 last_called; int num_ifs; int capacity; - hicnIntfc * intfcArray; + 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_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); +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; +static uint8_t netmask_to_prefix(const char *netmask) { + in_addr_t n = 0; + uint8_t i = 0; - inet_pton(AF_INET, netmask, &n); + inet_pton(AF_INET, netmask, &n); - while (n > 0) { - n = n >> 1; - i++; - } + while (n > 0) { + n = n >> 1; + i++; + } - return i; + return i; } /** - * @brief Helper function for converting IPv4/IPv6 address string into binary representation. + * @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)); - } +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; + 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; - } +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; - } + /* 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_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; +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. + * @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; - } +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; - } + /* 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); + /* 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_free_change_iter(iter); + 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; + 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; - } +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; - } + /* 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; +int ietf_initSwInterfaceDumpCTX(ietf_sw_interface_dump_ctx *dctx) { + if (dctx == NULL) return -1; dctx->intfcArray = NULL; dctx->last_called = false; @@ -252,66 +245,56 @@ int ietf_initSwInterfaceDumpCTX(ietf_sw_interface_dump_ctx * dctx) 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); - } +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) -{ +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; + 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); } - 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]; + 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; + 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; - } + 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; + thisIntfc->link_mtu = reply->link_mtu; + thisIntfc->flags = reply->flags; - dctx->num_ifs += 1; - } + dctx->num_ifs += 1; + } return VAPI_OK; } -static i32 ietf_interface_name2index(const char *name, u32* if_index) -{ +static i32 ietf_interface_name2index(const char *name, u32 *if_index) { ARG_CHECK2(-1, name, if_index); i32 ret = -1; @@ -324,14 +307,14 @@ static i32 ietf_interface_name2index(const char *name, u32* if_index) 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))) + 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) - { + 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; @@ -342,11 +325,12 @@ static i32 ietf_interface_name2index(const char *name, u32* if_index) 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 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); + 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; @@ -354,7 +338,9 @@ i32 ietf_interface_add_del_addr( u32 sw_if_index, u8 is_add, u8 is_ipv6, u8 del_ 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){ + 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; } @@ -362,246 +348,274 @@ i32 ietf_interface_add_del_addr( u32 sw_if_index, u8 is_add, u8 is_ipv6, u8 del_ return ret; } -i32 ietf_setInterfaceFlags(u32 sw_if_index, u8 admin_up_down) -{ +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); + 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; + 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){ + 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); - } +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; + } - /* 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; - } + /* 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". + * @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; - } +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); + /* 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; - } + /* 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; + /* 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 */); + } } - if (SR_ERR_INVAL_ARG == op_rc) { - sr_set_error(session, "Invalid interface name.", new_val ? new_val->xpath : old_val->xpath); + 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 */); + } } - free(if_name); - sr_free_val(old_val); - sr_free_val(new_val); + 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); } - sr_free_change_iter(iter); + free(if_name); + sr_free_val(old_val); + sr_free_val(new_val); + } + sr_free_change_iter(iter); - return op_rc; + 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. + * @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; +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; - } + 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/ietf-ip:ipv6/address", ietf_interface_ipv46_address_change_cb, - // NULL, - // 98, SR_SUBSCR_CTX_REUSE | SR_SUBSCR_ENABLED, subscription); + 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; + } - if (rc != SR_ERR_OK) { - SRP_LOG_DBGMSG("Problem in subscription /ietf-interfaces:interfaces/interface/ietf-ip:ipv6/address\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_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"); + // 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: +error: SRP_LOG_ERRMSG("Error by initialization of the ietf."); return rc; } diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.h index 0f6c7f8b4..cf5430464 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.h +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/ietf/ietf_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 HUACHENTEL and/or its affiliates. + * Copyright (c) 2021 HUACHENTEL and/or its affiliates. * Licensed under the Apache License, Version 2.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,5 +19,4 @@ int ietf_subscribe_events(sr_session_ctx_t *session, sr_subscription_ctx_t **subscription); - #endif /* __IETF_INTERFACE_H__ */ diff --git a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c index 63685e10a..f1b804267 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019-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/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h index 62fb15340..866eafd5e 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/hicn_model.h @@ -1,21 +1,22 @@ /* -* 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. -*/ + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 + * @brief This file contains main calls for hICN events coresponding to the hICN + * yang models */ #ifndef __IETF_HICN_H__ @@ -55,12 +56,10 @@ /** * @brief enumeration for the locks */ -enum locks_name {lstate, lstrategy, lstrategies, lroute, lfaces}; - +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 */ @@ -78,61 +77,60 @@ enum locks_name {lstate, lstrategy, lstrategies, lroute, lfaces}; */ #define MAX_FACE_POOL 100 /** - * @brief This indicates the maximum routes which can be read as operational data + * @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*/ +#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; +#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; +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; +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__)) { +typedef struct __attribute__((__packed__)) { u32 route_id; vapi_type_prefix prefix; u32 faceids[5]; @@ -143,29 +141,27 @@ typedef struct __attribute__ ((__packed__)) { /** * @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; +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; +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; +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; +typedef struct __attribute__((__packed__)) { + uint32_t nroute; + struct hicn_routes_s *next; } hicn_routes_t; /** @@ -173,6 +169,6 @@ typedef struct __attribute__ ((__packed__)) { * as well as operational data */ int hicn_subscribe_events(sr_session_ctx_t *session, - sr_subscription_ctx_t **subscription); + 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 index d27ae6492..c3c225ef7 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.c +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.c @@ -1,21 +1,16 @@ -#include"tlock.h" +#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_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 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]++; -} +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 index a871705a3..be3342d3f 100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.h +++ b/ctrl/sysrepo-plugins/hicn-plugin/plugin/model/tlock.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,8 +13,6 @@ * limitations under the License. */ - - /** * @file tlock.h * @brief This file contains ticket lock APIs. @@ -23,42 +21,40 @@ #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 +#define MAX_LOCK_SIZE 5 /** * @brief Ticket lock counters */ -volatile long int En[MAX_LOCK_SIZE] ; +volatile long int En[MAX_LOCK_SIZE]; /** * @brief Ticket lock counters */ -volatile long int De[MAX_LOCK_SIZE] ; - +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 ); +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 ); +void tlock(int Lock_Number); /** * @briefthis function release the lock * @param Lock_Number lock number */ -void tunlock(int 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/vapi-test/test.c b/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/test.c index f7b92c3c5..d3e47c970 100755..100644 --- a/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/test.c +++ b/ctrl/sysrepo-plugins/hicn-plugin/test/vapi-test/test.c @@ -5,177 +5,149 @@ #include <signal.h> #include <inttypes.h> -#include<vapi/hicn.api.vapi.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"); +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_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_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 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_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; +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_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 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){ +int main(int argc, char **argv) { + if (argc < 2) { usage(); return 1; } - /* connect to vpp */ + /* connect to vpp */ int rc = hicn_connect_vpp(); - if (-1 == rc){ + if (-1 == rc) { perror("vpp connect error"); return -1; } - if (!strcmp(argv[1],"route_add")){ + 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")){ + 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); + 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{ + } 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); + 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; } @@ -189,97 +161,93 @@ int main(int argc, char **argv) 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){ + 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")){ - + } 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")){ + 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); + 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)); + 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); + memcpy(&fmsg->payload.face.remote_addr.un.ip4[0], tmp, 4); fmsg->payload.face.remote_addr.af = ADDRESS_IP4; - }else{ - + } 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); + 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); + 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 + 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; + 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 + } 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); + 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 + } 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_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")){ + 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); + 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{ - + } 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); + 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; + 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 - { + } else { usage(); return 1; } diff --git a/ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang b/ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang index f66c205ce..a9251d14d 100644 --- a/ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang +++ b/ctrl/sysrepo-plugins/yang/ietf/ietf-interfaces.yang @@ -21,7 +21,7 @@ module ietf-interfaces { "This module contains a collection of YANG definitions for managing network interfaces. - Copyright (c) 2018 IETF Trust and the persons identified as + Copyright (c) 2021 IETF Trust and the persons identified as authors of the code. All rights reserved. Redistribution and use in source and binary forms, with or |