diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db903f8a..0c7508bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -310,7 +310,7 @@ jobs: image: "debian:13", pkg-setup: "apt-get update -q", pkg-cmd: "apt-get install -yq", - pkg-packages: "pipx cmake git debhelper pkg-config libcmocka-dev libpcre2-dev libcbor-dev libxxhash-dev zlib1g-dev libssh-dev libssl-dev libpam0g-dev libcurl4-openssl-dev", + pkg-packages: "pipx cmake git debhelper libcmocka-dev libpcre2-dev libcbor-dev libxxhash-dev zlib1g-dev libssh-dev libssl-dev libpam0g-dev libcurl4-openssl-dev", pipx-install: "" } container: @@ -331,9 +331,11 @@ jobs: $HOME/.local/bin/apkg build $HOME/.local/bin/apkg install + - uses: actions/checkout@main + - name: Build-and-install-package run: | - git clone -b ${{ needs.git-branch.outputs.branch-name }} https://github.com/CESNET/libnetconf2.git - cd libnetconf2 + # the container runs as root, the checked out workspace belongs to the runner user + git config --global --add safe.directory $GITHUB_WORKSPACE $HOME/.local/bin/apkg build $HOME/.local/bin/apkg install diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f5cce86..97f96d45 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5...3.28.1) +cmake_minimum_required(VERSION 3.12...3.28.1) project(libnetconf2 C) @@ -9,16 +9,14 @@ include(GNUInstallDirs) include(CheckFunctionExists) include(CheckCSourceCompiles) include(CheckIncludeFile) +include(CheckLibraryExists) include(CheckSymbolExists) include(UseCompat) include(ABICheck) include(SourceFormat) include(GenDoc) include(GenCoverage) - -if(POLICY CMP0075) - cmake_policy(SET CMP0075 NEW) -endif() +include(GenConfigPackage) # set default build type if not specified by user if(NOT CMAKE_BUILD_TYPE) @@ -71,10 +69,11 @@ set(LIBNETCONF2_MICRO_SOVERSION 7) set(LIBNETCONF2_SOVERSION_FULL ${LIBNETCONF2_MAJOR_SOVERSION}.${LIBNETCONF2_MINOR_SOVERSION}.${LIBNETCONF2_MICRO_SOVERSION}) set(LIBNETCONF2_SOVERSION ${LIBNETCONF2_MAJOR_SOVERSION}) -# Version of libyang library that this project depends on -set(LIBYANG_DEP_VERSION 6.3.0) +# SO version of libyang library that this project depends on set(LIBYANG_DEP_SOVERSION 5.9.2) -set(LIBYANG_DEP_SOVERSION_MAJOR 5) + +# Version of libssh library that this project depends on +set(LIBSSH_DEP_VERSION 0.9.5) # global C flags set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -fvisibility=hidden -std=c99") @@ -251,14 +250,20 @@ endif() # targets # -# use compat -use_compat() - # netconf2 sourceless target - need it for linking libs, but the required sources will be added later add_library(netconf2) +# private dependencies of a static build, for Libs.private of libnetconf2.pc +set(PC_LIBS_PRIVATE "") + +# use compat, may add a private dependency +use_compat() + # set the shared library version set_target_properties(netconf2 PROPERTIES VERSION ${LIBNETCONF2_SOVERSION_FULL} SOVERSION ${LIBNETCONF2_SOVERSION}) +target_include_directories(netconf2 PUBLIC + $ + $) # include repository files with highest priority include_directories(${PROJECT_BINARY_DIR}/src) @@ -267,7 +272,11 @@ include_directories(${PROJECT_BINARY_DIR}/include) # dependencies - pthread set(CMAKE_THREAD_PREFER_PTHREAD TRUE) find_package(Threads REQUIRED) -target_link_libraries(netconf2 ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(netconf2 PRIVATE Threads::Threads) +if(CMAKE_THREAD_LIBS_INIT) + # the thread library flag for the .pc file + string(APPEND PC_LIBS_PRIVATE " ${CMAKE_THREAD_LIBS_INIT}") +endif() # check availability for some pthread functions set(CMAKE_REQUIRED_LIBRARIES pthread) @@ -285,7 +294,8 @@ endif() if(ENABLE_DNSSEC) find_package(LibVAL REQUIRED) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_DNSSEC") - target_link_libraries(netconf2 ${LIBVAL_LIBRARIES}) + target_link_libraries(netconf2 PRIVATE ${LIBVAL_LIBRARIES}) + string(APPEND PC_LIBS_PRIVATE " -lval-threads -lsres") include_directories(${LIBVAL_INCLUDE_DIRS}) endif() @@ -297,28 +307,33 @@ if(ENABLE_SSH OR ENABLE_TLS) if(MBEDTLS_FOUND) # dependencies - mbedtls set(HAVE_MBEDTLS TRUE) + set(TLS_BACKEND MbedTLS) list(APPEND libsrc src/session_crypto_mbedtls.c) include_directories(${MBEDTLS_INCLUDE_DIRS}) - target_link_libraries(netconf2 ${MBEDTLS_LIBRARIES}) + target_link_libraries(netconf2 PRIVATE ${MBEDTLS_LIBRARIES}) + string(APPEND PC_LIBS_PRIVATE " -lmbedtls -lmbedx509 -lmbedcrypto") list(APPEND CMAKE_REQUIRED_LIBRARIES ${MBEDTLS_LIBRARIES}) else() # dependencies - openssl find_package(OpenSSL 3.0.0 REQUIRED) + set(TLS_BACKEND OpenSSL) list(APPEND libsrc src/session_crypto_openssl.c) include_directories(${OPENSSL_INCLUDE_DIR}) - target_link_libraries(netconf2 ${OPENSSL_LIBRARIES}) + target_link_libraries(netconf2 PRIVATE ${OPENSSL_LIBRARIES}) + string(APPEND PC_LIBS_PRIVATE " -lssl -lcrypto") list(APPEND CMAKE_REQUIRED_LIBRARIES ${OPENSSL_LIBRARIES}) endif() endif() if(ENABLE_SSH) # dependencies - libssh - find_package(LibSSH 0.9.5 REQUIRED) - target_link_libraries(netconf2 ${LIBSSH_LIBRARIES}) - list(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBSSH_LIBRARIES}) - include_directories(${LIBSSH_INCLUDE_DIRS}) + find_package(libssh ${LIBSSH_DEP_VERSION} CONFIG REQUIRED) + message(STATUS "Found libssh ${libssh_VERSION}: ${libssh_DIR}") + # public, the public headers include libssh + target_link_libraries(netconf2 PUBLIC ssh) + list(APPEND CMAKE_REQUIRED_LIBRARIES ssh) - if(LIBSSH_VERSION VERSION_GREATER_EQUAL "0.12.0") + if(libssh_VERSION VERSION_GREATER_EQUAL "0.12.0") list(APPEND libsrc src/session_server_ssh_auth_callback.c) else () list(APPEND libsrc src/session_server_ssh_auth_message.c) @@ -336,7 +351,8 @@ if(ENABLE_SSH) if(NOT HAVE_LIBCRYPT) message(FATAL_ERROR "Could NOT find Lib${LIBCRYPT} (library implementing crypt(3))") endif() - target_link_libraries(netconf2 ${LIBCRYPT}) + target_link_libraries(netconf2 PRIVATE ${LIBCRYPT}) + string(APPEND PC_LIBS_PRIVATE " -l${LIBCRYPT}") list(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBCRYPT}) endif() @@ -347,7 +363,8 @@ if(ENABLE_SSH) if(LibPAM_FOUND) set(HAVE_LIBPAM TRUE) - target_link_libraries(netconf2 ${LIBPAM_LIBRARIES}) + target_link_libraries(netconf2 PRIVATE ${LIBPAM_LIBRARIES}) + string(APPEND PC_LIBS_PRIVATE " -lpam") list(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBPAM_LIBRARIES}) include_directories(${LIBPAM_INCLUDE_DIRS}) @@ -364,48 +381,55 @@ if(ENABLE_TLS AND ENABLE_CRL) find_package(CURL 7.30.0) if(CURL_FOUND) set(HAVE_CURL TRUE) - if(TARGET CURL::libcurl) - target_link_libraries(netconf2 CURL::libcurl) - else() - target_link_libraries(netconf2 ${CURL_LIBRARIES}) - list(APPEND CMAKE_REQUIRED_LIBRARIES ${CURL_LIBRARY}) - include_directories(${CURL_INCLUDE_DIRS}) - endif() + target_link_libraries(netconf2 PRIVATE CURL::libcurl) + string(APPEND PC_LIBS_PRIVATE " -lcurl") else() message(WARNING "CRL certificate verification disabled (LibCURL not found)") endif() endif() # dependencies - libyang -find_package(LibYANG ${LIBYANG_DEP_SOVERSION} REQUIRED) -target_link_libraries(netconf2 ${LIBYANG_LIBRARIES}) -include_directories(${LIBYANG_INCLUDE_DIRS}) +find_package(LibYANG ${LIBYANG_DEP_SOVERSION} CONFIG REQUIRED) +message(STATUS "Found LibYANG ${LibYANG_VERSION}: ${LibYANG_DIR}") +target_link_libraries(netconf2 PUBLIC LibYANG::yang) -# set compiler flags +# public headers with SSH and TLS functions, also when included directly instead of nc_client.h/nc_server.h if(ENABLE_SSH) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DNC_SSH") + target_compile_definitions(netconf2 PUBLIC NC_SSH) + string(APPEND PC_CFLAGS " -DNC_SSH") endif() if(ENABLE_TLS) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DNC_TLS") + target_compile_definitions(netconf2 PUBLIC NC_TLS) + string(APPEND PC_CFLAGS " -DNC_TLS") endif() # set sources -target_sources(netconf2 PRIVATE ${libsrc} ${compatsrc}) +target_sources(netconf2 PRIVATE ${libsrc}) +target_link_libraries(netconf2 PRIVATE nccompat) + +# netconf2 for the executables and tests of this project. They call compat and pthread functions +# directly and need their own compat objects, because those in netconf2 are hidden. +add_library(ncbin INTERFACE) +target_sources(ncbin INTERFACE $) +target_link_libraries(ncbin INTERFACE netconf2 Threads::Threads) # generate config file configure_file("${PROJECT_SOURCE_DIR}/src/config.h.in" "${PROJECT_BINARY_DIR}/src/config.h" ESCAPE_QUOTES @ONLY) -# generate and copy public header files +# generate and copy public headers, configure_file() refreshes the copies whenever they change configure_file("${PROJECT_SOURCE_DIR}/nc_client.h.in" "${PROJECT_BINARY_DIR}/include/nc_client.h") configure_file("${PROJECT_SOURCE_DIR}/nc_server.h.in" "${PROJECT_BINARY_DIR}/include/nc_server.h") configure_file("${PROJECT_SOURCE_DIR}/nc_version.h.in" "${PROJECT_BINARY_DIR}/include/nc_version.h") -file(COPY ${headers} DESTINATION "${PROJECT_BINARY_DIR}/include/libnetconf2") +foreach(h IN LISTS headers) + get_filename_component(h_name ${h} NAME) + configure_file(${PROJECT_SOURCE_DIR}/${h} ${PROJECT_BINARY_DIR}/include/libnetconf2/${h_name} COPYONLY) +endforeach() # install YANG modules install(DIRECTORY "${PROJECT_SOURCE_DIR}/modules/" DESTINATION ${YANG_MODULE_DIR} FILES_MATCHING PATTERN "*.yang") # install library -install(TARGETS netconf2 DESTINATION ${CMAKE_INSTALL_LIBDIR}) +install(TARGETS netconf2 EXPORT LibNETCONF2Targets DESTINATION ${CMAKE_INSTALL_LIBDIR}) # install headers install(FILES ${PROJECT_BINARY_DIR}/include/nc_client.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) @@ -413,21 +437,50 @@ install(FILES ${PROJECT_BINARY_DIR}/include/nc_server.h DESTINATION ${CMAKE_INST install(FILES ${PROJECT_BINARY_DIR}/include/nc_version.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(DIRECTORY ${PROJECT_BINARY_DIR}/include/libnetconf2 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) -# install pkg-config file -find_package(PkgConfig) -if(PKG_CONFIG_FOUND) - configure_file("libnetconf2.pc.in" "libnetconf2.pc" @ONLY) - install(FILES "${PROJECT_BINARY_DIR}/libnetconf2.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") - # check that pkg-config includes the used path - execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable pc_path pkg-config RESULT_VARIABLE RETURN OUTPUT_VARIABLE PC_PATH ERROR_QUIET) - if(RETURN EQUAL 0) - string(REGEX MATCH "${CMAKE_INSTALL_LIBDIR}/pkgconfig" SUBSTR "${PC_PATH}") - string(LENGTH "${SUBSTR}" SUBSTR_LEN) - if(SUBSTR_LEN EQUAL 0) - message(WARNING "pkg-config will not detect the new package after installation, adjust PKG_CONFIG_PATH using \"export PKG_CONFIG_PATH=\${PKG_CONFIG_PATH}:${CMAKE_INSTALL_LIBDIR}/pkgconfig\".") - endif() +# CMake config package, for the build tree and the installation +if(BUILD_SHARED_LIBS) + # libyang for the installed package, under the same prefix + set(NC_LIBYANG_HINT ${CMAKE_INSTALL_LIBDIR}/cmake/LibYANG) + # libyang for the build tree package, the one libnetconf2 was built with + set(NC_LIBYANG_HINT_BUILD ${LibYANG_DIR}) + + # the build tree uses the YANG modules from the source tree + set(YANG_MODULE_DIR_BUILD ${PROJECT_SOURCE_DIR}/modules) + set(NC_PATH_VARS NC_LIBYANG_HINT YANG_MODULE_DIR) + + if(ENABLE_SSH) + # libssh the same way as libyang + set(NC_LIBSSH_HINT ${CMAKE_INSTALL_LIBDIR}/cmake/libssh) + set(NC_LIBSSH_HINT_BUILD ${libssh_DIR}) + list(APPEND NC_PATH_VARS NC_LIBSSH_HINT) endif() + + # the package version is the SO version, which all the dependent projects check + gen_config_package(LibNETCONF2 ${LIBNETCONF2_SOVERSION_FULL} PATH_VARS ${NC_PATH_VARS}) +else() + message(STATUS "Static build, CMake config package is not installed") +endif() + +# generate and install pkg-config file, the install directories in its paths may be absolute +if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") + set(PC_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}") +else() + set(PC_INCLUDEDIR "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") +endif() +if(IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}") + set(PC_LIBDIR "${CMAKE_INSTALL_LIBDIR}") +else() + set(PC_LIBDIR "\${prefix}/${CMAKE_INSTALL_LIBDIR}") +endif() +# libyang and libssh are public, the public headers include them +set(PC_REQUIRES "libyang") +if(ENABLE_SSH) + string(APPEND PC_REQUIRES " libssh") endif() +# the other dependencies only in Libs.private, Requires.private would need their .pc files even for dynamic linking +string(STRIP "${PC_LIBS_PRIVATE}" PC_LIBS_PRIVATE) +configure_file("libnetconf2.pc.in" "libnetconf2.pc" @ONLY) +install(FILES "${PROJECT_BINARY_DIR}/libnetconf2.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") # examples if(ENABLE_EXAMPLES) diff --git a/CMakeModules/FindCMocka.cmake b/CMakeModules/FindCMocka.cmake index 39dd46fb..b2d55b7e 100644 --- a/CMakeModules/FindCMocka.cmake +++ b/CMakeModules/FindCMocka.cmake @@ -64,5 +64,5 @@ endif (CMOCKA_LIBRARY) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(CMocka DEFAULT_MSG CMOCKA_LIBRARIES CMOCKA_INCLUDE_DIR) -# show the CMOCKA_INCLUDE_DIR and CMOCKA_LIBRARIES variables only in the advanced view -mark_as_advanced(CMOCKA_INCLUDE_DIR CMOCKA_LIBRARIES) +# show the CMOCKA_INCLUDE_DIR and CMOCKA_LIBRARY variables only in the advanced view +mark_as_advanced(CMOCKA_INCLUDE_DIR CMOCKA_LIBRARY) diff --git a/CMakeModules/FindLibPAM.cmake b/CMakeModules/FindLibPAM.cmake index acf04758..a6d30f5d 100644 --- a/CMakeModules/FindLibPAM.cmake +++ b/CMakeModules/FindLibPAM.cmake @@ -80,7 +80,7 @@ else() include(FindPackageHandleStandardArgs) find_package_handle_standard_args(LibPAM DEFAULT_MSG LIBPAM_LIBRARIES LIBPAM_INCLUDE_DIRS) - # show the LIBPAM_INCLUDE_DIRS and LIBPAM_LIBRARIES variables only in the advanced view - mark_as_advanced(LIBPAM_INCLUDE_DIRS LIBPAM_LIBRARIES) + # show the LIBPAM_INCLUDE_DIR and LIBPAM_LIBRARY variables only in the advanced view + mark_as_advanced(LIBPAM_INCLUDE_DIR LIBPAM_LIBRARY) endif() diff --git a/CMakeModules/FindLibSSH.cmake b/CMakeModules/FindLibSSH.cmake deleted file mode 100644 index 8ef0ac49..00000000 --- a/CMakeModules/FindLibSSH.cmake +++ /dev/null @@ -1,117 +0,0 @@ -# - Try to find LibSSH -# Once done this will define -# -# LIBSSH_FOUND - system has LibSSH -# LIBSSH_INCLUDE_DIRS - the LibSSH include directory -# LIBSSH_LIBRARIES - link these to use LibSSH -# LIBSSH_VERSION - -# -# Author Michal Vasko -# Copyright (c) 2020 CESNET, z.s.p.o. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -include(FindPackageHandleStandardArgs) - -if(LIBSSH_LIBRARIES AND LIBSSH_INCLUDE_DIRS) - # in cache already - set(LIBSSH_FOUND TRUE) -else() - find_path(LIBSSH_INCLUDE_DIR - NAMES - libssh/libssh.h - PATHS - /usr/include - /usr/local/include - /opt/local/include - /sw/include - ${CMAKE_INCLUDE_PATH} - ${CMAKE_INSTALL_PREFIX}/include - ) - - find_library(LIBSSH_LIBRARY - NAMES - ssh.so - libssh.so - libssh.dylib - PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - /sw/lib - ${CMAKE_LIBRARY_PATH} - ${CMAKE_INSTALL_PREFIX}/lib - ) - - if(LIBSSH_INCLUDE_DIR AND LIBSSH_LIBRARY) - # learn libssh version - if(EXISTS ${LIBSSH_INCLUDE_DIR}/libssh/libssh_version.h) - set(LIBSSH_HEADER_PATH ${LIBSSH_INCLUDE_DIR}/libssh/libssh_version.h) - else() - set(LIBSSH_HEADER_PATH ${LIBSSH_INCLUDE_DIR}/libssh/libssh.h) - endif() - file(STRINGS ${LIBSSH_HEADER_PATH} LIBSSH_VERSION_MAJOR - REGEX "#define[ ]+LIBSSH_VERSION_MAJOR[ ]+[0-9]+") - if(NOT LIBSSH_VERSION_MAJOR) - message(STATUS "LIBSSH_VERSION_MAJOR not found, assuming libssh is too old and cannot be used!") - set(LIBSSH_INCLUDE_DIR "LIBSSH_INCLUDE_DIR-NOTFOUND") - set(LIBSSH_LIBRARY "LIBSSH_LIBRARY-NOTFOUND") - else() - string(REGEX MATCH "[0-9]+" LIBSSH_VERSION_MAJOR ${LIBSSH_VERSION_MAJOR}) - file(STRINGS ${LIBSSH_HEADER_PATH} LIBSSH_VERSION_MINOR - REGEX "#define[ ]+LIBSSH_VERSION_MINOR[ ]+[0-9]+") - string(REGEX MATCH "[0-9]+" LIBSSH_VERSION_MINOR ${LIBSSH_VERSION_MINOR}) - file(STRINGS ${LIBSSH_HEADER_PATH} LIBSSH_VERSION_PATCH - REGEX "#define[ ]+LIBSSH_VERSION_MICRO[ ]+[0-9]+") - string(REGEX MATCH "[0-9]+" LIBSSH_VERSION_PATCH ${LIBSSH_VERSION_PATCH}) - - set(LIBSSH_VERSION ${LIBSSH_VERSION_MAJOR}.${LIBSSH_VERSION_MINOR}.${LIBSSH_VERSION_PATCH}) - - if(LIBSSH_VERSION VERSION_LESS 0.8.0) - # libssh_threads also needs to be linked for these versions - string(REPLACE "libssh.so" "libssh_threads.so" - LIBSSH_THREADS_LIBRARY - ${LIBSSH_LIBRARY} - ) - string(REPLACE "libssh.dylib" "libssh_threads.dylib" - LIBSSH_THREADS_LIBRARY - ${LIBSSH_THREADS_LIBRARY} - ) - string(REPLACE "ssh.so" "ssh_threads.so" - LIBSSH_THREADS_LIBRARY - ${LIBSSH_THREADS_LIBRARY} - ) - endif() - endif() - endif() - - set(LIBSSH_INCLUDE_DIRS ${LIBSSH_INCLUDE_DIR}) - set(LIBSSH_LIBRARIES ${LIBSSH_LIBRARY} ${LIBSSH_THREADS_LIBRARY}) - mark_as_advanced(LIBSSH_INCLUDE_DIRS LIBSSH_LIBRARIES) - - find_package_handle_standard_args(LibSSH FOUND_VAR LIBSSH_FOUND - REQUIRED_VARS LIBSSH_INCLUDE_DIRS LIBSSH_LIBRARIES - VERSION_VAR LIBSSH_VERSION) -endif() - diff --git a/CMakeModules/FindLibVAL.cmake b/CMakeModules/FindLibVAL.cmake index 26d4ea28..29fc4c90 100644 --- a/CMakeModules/FindLibVAL.cmake +++ b/CMakeModules/FindLibVAL.cmake @@ -95,8 +95,8 @@ else() include(FindPackageHandleStandardArgs) find_package_handle_standard_args(LibVAL DEFAULT_MSG LIBVAL_LIBRARIES LIBVAL_INCLUDE_DIRS) - # show the LIBVAL_INCLUDE_DIRS and LIBVAL_LIBRARIES variables only in the advanced view - mark_as_advanced(LIBVAL_INCLUDE_DIRS LIBVAL_LIBRARIES) + # show the LIBVAL_INCLUDE_DIR, LIBVAL_LIBRARY and LIBSRES_LIBRARY variables only in the advanced view + mark_as_advanced(LIBVAL_INCLUDE_DIR LIBVAL_LIBRARY LIBSRES_LIBRARY) endif() diff --git a/CMakeModules/FindLibYANG.cmake b/CMakeModules/FindLibYANG.cmake deleted file mode 100644 index 89cd93ad..00000000 --- a/CMakeModules/FindLibYANG.cmake +++ /dev/null @@ -1,89 +0,0 @@ -# - Try to find LibYANG -# Once done this will define -# -# LIBYANG_FOUND - system has LibYANG -# LIBYANG_INCLUDE_DIRS - the LibYANG include directory -# LIBYANG_LIBRARIES - Link these to use LibYANG -# LIBYANG_VERSION - SO version of the found libyang library -# -# Author Michal Vasko -# Copyright (c) 2021 CESNET, z.s.p.o. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -include(FindPackageHandleStandardArgs) - -if(LIBYANG_LIBRARIES AND LIBYANG_INCLUDE_DIRS) - # in cache already - set(LIBYANG_FOUND TRUE) -else() - find_path(LIBYANG_INCLUDE_DIR - NAMES - libyang/libyang.h - PATHS - /usr/include - /usr/local/include - /opt/local/include - /sw/include - ${CMAKE_INCLUDE_PATH} - ${CMAKE_INSTALL_PREFIX}/include - ) - - find_library(LIBYANG_LIBRARY - NAMES - yang - libyang - PATHS - /usr/lib - /usr/lib64 - /usr/local/lib - /usr/local/lib64 - /opt/local/lib - /sw/lib - ${CMAKE_LIBRARY_PATH} - ${CMAKE_INSTALL_PREFIX}/lib - ) - - if(LIBYANG_INCLUDE_DIR) - find_path(LY_VERSION_PATH "libyang/version.h" HINTS ${LIBYANG_INCLUDE_DIR}) - if(LY_VERSION_PATH) - file(READ "${LY_VERSION_PATH}/libyang/version.h" LY_VERSION_FILE) - else() - find_path(LY_HEADER_PATH "libyang/libyang.h" HINTS ${LIBYANG_INCLUDE_DIR}) - file(READ "${LY_HEADER_PATH}/libyang/libyang.h" LY_VERSION_FILE) - endif() - string(REGEX MATCH "#define LY_VERSION \"[0-9]+\\.[0-9]+\\.[0-9]+\"" LY_VERSION_MACRO "${LY_VERSION_FILE}") - string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" LIBYANG_VERSION "${LY_VERSION_MACRO}") - endif() - - set(LIBYANG_INCLUDE_DIRS ${LIBYANG_INCLUDE_DIR}) - set(LIBYANG_LIBRARIES ${LIBYANG_LIBRARY}) - mark_as_advanced(LIBYANG_INCLUDE_DIRS LIBYANG_LIBRARIES) - - # handle the QUIETLY and REQUIRED arguments and set LIBYANG_FOUND to TRUE - # if all listed variables are TRUE - find_package_handle_standard_args(LibYANG FOUND_VAR LIBYANG_FOUND - REQUIRED_VARS LIBYANG_LIBRARY LIBYANG_INCLUDE_DIR - VERSION_VAR LIBYANG_VERSION) -endif() diff --git a/CMakeModules/FindMbedTLS.cmake b/CMakeModules/FindMbedTLS.cmake index 17b96d7c..97371a5b 100644 --- a/CMakeModules/FindMbedTLS.cmake +++ b/CMakeModules/FindMbedTLS.cmake @@ -105,6 +105,6 @@ else() REQUIRED_VARS MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARIES VERSION_VAR MBEDTLS_VERSION) - # show the MBEDTLS_INCLUDE_DIR and MBEDTLS_LIBRARIES variables only in the advanced view - mark_as_advanced(MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARIES) + # show the MBEDTLS_INCLUDE_DIR, MBEDTLS_LIBRARY, MBEDX509_LIBRARY and MBEDCRYPTO_LIBRARY variables only in the advanced view + mark_as_advanced(MBEDTLS_INCLUDE_DIR MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY) endif() diff --git a/CMakeModules/GenConfigPackage.cmake b/CMakeModules/GenConfigPackage.cmake new file mode 100644 index 00000000..7e136836 --- /dev/null +++ b/CMakeModules/GenConfigPackage.cmake @@ -0,0 +1,42 @@ +# Generate the CMake config package of a library for the build tree and the installation +# +# gen_config_package(LIB_NAME LIB_SOVERSION_FULL [EXPORTS ...] [PATH_VARS ...]) +# LIB_NAME package name, the template is Config.cmake.in in the source root +# LIB_SOVERSION_FULL package version, the full SO version of the library +# EXPORTS optional, export sets installed besides Targets +# PATH_VARS optional, template variables with installed paths, _BUILD holds the build tree path +# +# The template reads its other variables from the scope of the caller. +include(CMakePackageConfigHelpers) + +function(gen_config_package LIB_NAME LIB_SOVERSION_FULL) + # the optional arguments into LIB_EXPORTS and LIB_PATH_VARS + cmake_parse_arguments(PARSE_ARGV 2 LIB "" "" "EXPORTS;PATH_VARS") + set(LIB_CONFIG_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/${LIB_NAME}) + set(LIB_TEMPLATE ${PROJECT_SOURCE_DIR}/${LIB_NAME}Config.cmake.in) + + # create the version file + write_basic_package_version_file(${PROJECT_BINARY_DIR}/${LIB_NAME}ConfigVersion.cmake + VERSION ${LIB_SOVERSION_FULL} COMPATIBILITY SameMajorVersion) + install(FILES ${PROJECT_BINARY_DIR}/${LIB_NAME}ConfigVersion.cmake DESTINATION ${LIB_CONFIG_DIR}) + + # the targets file of each export set, for the build tree and the installation + foreach(LIB_EXPORT IN ITEMS ${LIB_NAME}Targets ${LIB_EXPORTS}) + export(EXPORT ${LIB_EXPORT} NAMESPACE ${LIB_NAME}:: FILE ${PROJECT_BINARY_DIR}/${LIB_EXPORT}.cmake) + install(EXPORT ${LIB_EXPORT} NAMESPACE ${LIB_NAME}:: DESTINATION ${LIB_CONFIG_DIR}) + endforeach() + + # the installed config, generated aside so that it does not replace the build tree one + configure_package_config_file(${LIB_TEMPLATE} ${PROJECT_BINARY_DIR}/CMakeFiles/${LIB_NAME}Config.cmake + INSTALL_DESTINATION ${LIB_CONFIG_DIR} PATH_VARS ${LIB_PATH_VARS}) + install(FILES ${PROJECT_BINARY_DIR}/CMakeFiles/${LIB_NAME}Config.cmake DESTINATION ${LIB_CONFIG_DIR}) + + # each path variable set to its _BUILD value + foreach(LIB_VAR IN LISTS LIB_PATH_VARS) + set(${LIB_VAR} ${${LIB_VAR}_BUILD}) + endforeach() + + # the build tree config, the build directory is both its location and its prefix + configure_package_config_file(${LIB_TEMPLATE} ${PROJECT_BINARY_DIR}/${LIB_NAME}Config.cmake + INSTALL_DESTINATION ${PROJECT_BINARY_DIR} INSTALL_PREFIX ${PROJECT_BINARY_DIR} PATH_VARS ${LIB_PATH_VARS}) +endfunction() diff --git a/CMakeModules/UseCompat.cmake b/CMakeModules/UseCompat.cmake index 55e67e08..ff922c1a 100644 --- a/CMakeModules/UseCompat.cmake +++ b/CMakeModules/UseCompat.cmake @@ -1,7 +1,7 @@ # - Use compat library providing various functions and macros that may be missing on some systems # Once done this will define # -# compatsrc - sources to add to compilation +# nccompat - OBJECT library with the compat functions # # Additionally, "compat.h" include directory is added and can be included. # @@ -17,9 +17,6 @@ include(CheckSymbolExists) include(CheckIncludeFile) include(TestBigEndian) -if(POLICY CMP0075) - cmake_policy(SET CMP0075 NEW) -endif() macro(USE_COMPAT) # compatibility checks @@ -34,7 +31,9 @@ macro(USE_COMPAT) set(CMAKE_THREAD_PREFER_PTHREAD TRUE) find_package(Threads) - list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) + if(CMAKE_THREAD_LIBS_INIT) + list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) + endif() check_symbol_exists(pthread_mutex_timedlock "pthread.h" HAVE_PTHREAD_MUTEX_TIMEDLOCK) check_symbol_exists(pthread_mutex_clocklock "pthread.h" HAVE_PTHREAD_MUTEX_CLOCKLOCK) @@ -87,7 +86,8 @@ macro(USE_COMPAT) check_symbol_exists(SO_PEERCRED "sys/socket.h" HAVE_SO_PEERCRED) if(NOT HAVE_SO_PEERCRED) if(${CMAKE_SYSTEM_NAME} MATCHES "QNX") - target_link_libraries(netconf2 -lsocket) + target_link_libraries(netconf2 PRIVATE -lsocket) + string(APPEND PC_LIBS_PRIVATE " -lsocket") list(APPEND CMAKE_REQUIRED_LIBRARIES socket) list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES pthread) list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_QNX_SOURCE) @@ -103,10 +103,15 @@ macro(USE_COMPAT) list(REMOVE_ITEM CMAKE_REQUIRED_DEFINITIONS -D_POSIX_C_SOURCE=200809L) list(REMOVE_ITEM CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE) list(REMOVE_ITEM CMAKE_REQUIRED_DEFINITIONS -D__BSD_VISIBLE=1) - list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) + if(CMAKE_THREAD_LIBS_INIT) + list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) + endif() - # header and source file (adding the source directly allows for hiding its symbols) + # compat.h configure_file(${PROJECT_SOURCE_DIR}/compat/compat.h.in ${PROJECT_BINARY_DIR}/compat/compat.h @ONLY) include_directories(${PROJECT_BINARY_DIR}/compat) - set(compatsrc ${PROJECT_SOURCE_DIR}/compat/compat.c) + + # compat functions, hidden by the global -fvisibility=hidden so that a shared library does not export them + add_library(nccompat OBJECT ${PROJECT_SOURCE_DIR}/compat/compat.c) + set_target_properties(nccompat PROPERTIES POSITION_INDEPENDENT_CODE ON) endmacro() diff --git a/FindLibNETCONF2.cmake b/FindLibNETCONF2.cmake deleted file mode 100644 index f4a446b2..00000000 --- a/FindLibNETCONF2.cmake +++ /dev/null @@ -1,100 +0,0 @@ -# - Try to find LibNETCONF2 -# Once done this will define -# -# LIBNETCONF2_FOUND - system has LibNETCONF2 -# LIBNETCONF2_INCLUDE_DIRS - the LibNETCONF2 include directory -# LIBNETCONF2_LIBRARIES - Link these to use LibNETCONF2 -# LIBNETCONF2_VERSION - SO version of the found libNETCONF2 library -# LIBNETCONF2_SSH - LibNETCONF2 was compiled with SSH support -# LIBNETCONF2_TLS - LibNETCONF2 was compiled with TLS support -# -# Author Michal Vasko -# Copyright (c) 2021 - 2026 CESNET, z.s.p.o. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -include(FindPackageHandleStandardArgs) - -if(LIBNETCONF2_LIBRARIES AND LIBNETCONF2_INCLUDE_DIRS) - # in cache already - set(LIBNETCONF2_FOUND TRUE) -else() - find_path(LIBNETCONF2_INCLUDE_DIR - NAMES - nc_client.h - nc_server.h - PATHS - /usr/include - /usr/local/include - /opt/local/include - /sw/include - ${CMAKE_INCLUDE_PATH} - ${CMAKE_INSTALL_PREFIX}/include - ) - - find_library(LIBNETCONF2_LIBRARY - NAMES - netconf2 - libnetconf2 - PATHS - /usr/lib - /usr/lib64 - /usr/local/lib - /usr/local/lib64 - /opt/local/lib - /sw/lib - ${CMAKE_LIBRARY_PATH} - ${CMAKE_INSTALL_PREFIX}/lib - ) - - if(LIBNETCONF2_INCLUDE_DIR) - find_path(NC_VERSION_PATH "nc_version.h" HINTS ${LIBNETCONF2_INCLUDE_DIR}) - if(NOT NC_VERSION_PATH) - message(STATUS "libnetconf2 version header not found, assuming libnetconf2 is too old and cannot be used!") - set(LIBNETCONF2_INCLUDE_DIR "LIBNETCONF2_INCLUDE_DIR-NOTFOUND") - set(LIBNETCONF2_LIBRARY "LIBNETCONF2_LIBRARY-NOTFOUND") - else() - file(READ "${NC_VERSION_PATH}/nc_version.h" NC_VERSION_FILE) - string(REGEX MATCH "#define NC_VERSION \"[0-9]+\\.[0-9]+\\.[0-9]+\"" NC_VERSION_MACRO "${NC_VERSION_FILE}") - string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" LIBNETCONF2_VERSION "${NC_VERSION_MACRO}") - endif() - endif() - - set(LIBNETCONF2_INCLUDE_DIRS ${LIBNETCONF2_INCLUDE_DIR}) - set(LIBNETCONF2_LIBRARIES ${LIBNETCONF2_LIBRARY}) - mark_as_advanced(LIBNETCONF2_INCLUDE_DIRS LIBNETCONF2_LIBRARIES) - - # handle the QUIETLY and REQUIRED arguments and set SYSREPO_FOUND to TRUE - # if all listed variables are TRUE - find_package_handle_standard_args(LibNETCONF2 FOUND_VAR LIBNETCONF2_FOUND - REQUIRED_VARS LIBNETCONF2_LIBRARY LIBNETCONF2_INCLUDE_DIR - VERSION_VAR LIBNETCONF2_VERSION) - - # check the configured options and make them available through cmake - list(INSERT CMAKE_REQUIRED_INCLUDES 0 "${LIBNETCONF2_INCLUDE_DIR}") - check_symbol_exists("NC_SSH" "nc_client.h" LIBNETCONF2_SSH) - check_symbol_exists("NC_TLS" "nc_client.h" LIBNETCONF2_TLS) - list(REMOVE_AT CMAKE_REQUIRED_INCLUDES 0) -endif() - diff --git a/LibNETCONF2Config.cmake.in b/LibNETCONF2Config.cmake.in new file mode 100644 index 00000000..b7c93edd --- /dev/null +++ b/LibNETCONF2Config.cmake.in @@ -0,0 +1,30 @@ +# CMake config package of libnetconf2 +# +# Imported target: +# LibNETCONF2::netconf2 the libnetconf2 library +# +# Variables: +# LibNETCONF2_VERSION SO version of the library, compared by find_package() +# LibNETCONF2_PROJECT_VERSION version of the libnetconf2 project +# LibNETCONF2_YANG_MODULE_DIR directory with the YANG modules of libnetconf2 +# LibNETCONF2_SSH libnetconf2 supports NETCONF over SSH (NC_SSH) +# LibNETCONF2_TLS libnetconf2 supports NETCONF over TLS (NC_TLS) +# LibNETCONF2_TLS_BACKEND crypto library used for SSH and TLS, OpenSSL or MbedTLS, empty without both + +@PACKAGE_INIT@ + +set(LibNETCONF2_PROJECT_VERSION "@LIBNETCONF2_VERSION@") +set(LibNETCONF2_YANG_MODULE_DIR "@PACKAGE_YANG_MODULE_DIR@") +set(LibNETCONF2_SSH @ENABLE_SSH@) +set(LibNETCONF2_TLS @ENABLE_TLS@) +set(LibNETCONF2_TLS_BACKEND "@TLS_BACKEND@") + +include(CMakeFindDependencyMacro) +find_dependency(LibYANG @LIBYANG_DEP_SOVERSION@ CONFIG HINTS "@PACKAGE_NC_LIBYANG_HINT@") +if(LibNETCONF2_SSH) + find_dependency(libssh @LIBSSH_DEP_VERSION@ CONFIG HINTS "@PACKAGE_NC_LIBSSH_HINT@") +endif() + +# the LibNETCONF2::netconf2 target, generated by CMake next to this file +include("${CMAKE_CURRENT_LIST_DIR}/LibNETCONF2Targets.cmake") +check_required_components(LibNETCONF2) diff --git a/README.md b/README.md index 8652259d..5ee26e77 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ the `distro` directory. ## Requirements * C compiler (gcc >= 4.8.4, clang >= 3.0, ...) -* cmake >= 3.5.0 +* cmake >= 3.12 * crypt(3) * [libyang](https://github.com/CESNET/libyang) * libssh >= 0.9.5 (for SSH support) @@ -218,6 +218,25 @@ following linker parameters: -lnetconf2 ``` +A CMake project finds libnetconf2 by its CMake package, installed into `LIBDIR/cmake/LibNETCONF2` +(`LIBDIR` is the library directory under the install prefix, e.g. `/usr/local/lib`): +``` +find_package(LibNETCONF2 5 CONFIG REQUIRED) +target_link_libraries(myapp PRIVATE LibNETCONF2::netconf2) +``` + +The version passed to `find_package()` is the SO version of the library (`NC_VERSION`). The +package also defines the following variables, holding the values libnetconf2 was built with: + +* `LibNETCONF2_PROJECT_VERSION` - project version of libnetconf2, +* `LibNETCONF2_YANG_MODULE_DIR` - directory with the libnetconf2 YANG modules, +* `LibNETCONF2_SSH` - whether libnetconf2 supports NETCONF over SSH, +* `LibNETCONF2_TLS` - whether libnetconf2 supports NETCONF over TLS, +* `LibNETCONF2_TLS_BACKEND` - crypto library used for SSH and TLS, `OpenSSL` or `MbedTLS`. + +To use libnetconf2 from its build directory, pass `-DLibNETCONF2_DIR=`. +Static builds and older libnetconf2 releases provide no CMake package, use `pkg-config` with them. + ## Examples See [examples](examples) directory for an example client and server. diff --git a/distro/pkg/deb/control b/distro/pkg/deb/control index 0e1d2fe2..205cd368 100644 --- a/distro/pkg/deb/control +++ b/distro/pkg/deb/control @@ -10,7 +10,7 @@ Build-Depends: cmake, libssl-dev (>= 3.0.0), libssh-dev (>= 0.9.5), libpam0g-dev, - pkg-config, + libcrypt-dev, libcurl4-openssl-dev (>= 7.30.0) Vcs-Browser: https://github.com/CESNET/libnetconf2/tree/master Vcs-Git: https://github.com/CESNET/libnetconf2.git @@ -30,6 +30,7 @@ Description: library implementing NETCONF protocol - runtime Package: libnetconf2-dev Depends: libyang-dev, + libssh-dev (>= 0.9.5), libnetconf5 (= ${binary:Version}), ${misc:Depends} Section: libdevel @@ -41,5 +42,5 @@ Description: library implementing NETCONF protocol - development files . Both server and client-side functionality is provided. . - This package contains the C headers, a pkgconfig file, and .so entry - point for libnetconf2. + This package contains the C headers, a pkgconfig file, a CMake package, + and .so entry point for libnetconf2. diff --git a/distro/pkg/deb/libnetconf2-dev.install b/distro/pkg/deb/libnetconf2-dev.install index c8a621f5..4101b63f 100644 --- a/distro/pkg/deb/libnetconf2-dev.install +++ b/distro/pkg/deb/libnetconf2-dev.install @@ -1,5 +1,6 @@ usr/lib/*/libnetconf2.so usr/lib/*/pkgconfig/libnetconf2.pc +usr/lib/*/cmake/LibNETCONF2 usr/include/libnetconf2/* usr/include/nc_client.h usr/include/nc_server.h diff --git a/distro/pkg/deb/rules b/distro/pkg/deb/rules index 58f845de..5339ca9e 100755 --- a/distro/pkg/deb/rules +++ b/distro/pkg/deb/rules @@ -10,3 +10,7 @@ include /usr/share/dpkg/default.mk override_dh_auto_configure: dh_auto_configure -- \ -DCMAKE_BUILD_TYPE:String="Release" + +# fail on installed files that no package lists +override_dh_missing: + dh_missing --fail-missing diff --git a/distro/pkg/rpm/libnetconf2.spec b/distro/pkg/rpm/libnetconf2.spec index 4b9d77ca..4373b76c 100644 --- a/distro/pkg/rpm/libnetconf2.spec +++ b/distro/pkg/rpm/libnetconf2.spec @@ -50,6 +50,7 @@ servers. NETCONF is the NETwork CONFiguration protocol introduced by IETF. %doc CODINGSTYLE.md %{_libdir}/libnetconf2.so %{_libdir}/pkgconfig/libnetconf2.pc +%{_libdir}/cmake/LibNETCONF2/ %{_includedir}/*.h %{_includedir}/libnetconf2/*.h %dir %{_includedir}/libnetconf2/ diff --git a/distro/tests/control b/distro/tests/control deleted file mode 100644 index 3f1aeba0..00000000 --- a/distro/tests/control +++ /dev/null @@ -1 +0,0 @@ -Tests: test-pkg-config.sh diff --git a/distro/tests/test-pkg-config.sh b/distro/tests/test-pkg-config.sh deleted file mode 100755 index abad2be7..00000000 --- a/distro/tests/test-pkg-config.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -set -ex - -version=`pkg-config --modversion libnetconf2` -echo "$version" | grep '2\.[0-9.]\+' diff --git a/libnetconf2.pc.in b/libnetconf2.pc.in index f81cf2b2..305b2a88 100644 --- a/libnetconf2.pc.in +++ b/libnetconf2.pc.in @@ -1,11 +1,13 @@ prefix=@CMAKE_INSTALL_PREFIX@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ +includedir=@PC_INCLUDEDIR@ +libdir=@PC_LIBDIR@ Name: @PROJECT_NAME@ Description: @LIBNETCONF2_DESCRIPTION@ Version: @LIBNETCONF2_VERSION@ +Requires: @PC_REQUIRES@ Libs: -L${libdir} -lnetconf2 -Cflags: -I${includedir} +Libs.private: @PC_LIBS_PRIVATE@ +Cflags: -I${includedir}@PC_CFLAGS@ LN2_SCHEMAS_DIR=@YANG_MODULE_DIR@ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 68db9799..e75061ad 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,14 +7,20 @@ if(${SOURCE_FORMAT_ENABLED}) add_test(NAME format WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND cmake --build ${CMAKE_BINARY_DIR} --target format-check) endif() -foreach(src IN LISTS libsrc) - list(APPEND test_srcs "../${src}") -endforeach() -add_library(testobj OBJECT ${test_srcs} ${compatsrc}) - set(TEST_SRC "ln2_test.c") set(NEXT_TEST_PORT 10050) +# libraries some tests call directly, netconf2 links them only privately +set(TEST_DIRECT_LIBS ${CMAKE_DL_LIBS}) +if(HAVE_MBEDTLS) + list(APPEND TEST_DIRECT_LIBS ${MBEDTLS_LIBRARIES}) +elseif(ENABLE_SSH OR ENABLE_TLS) + list(APPEND TEST_DIRECT_LIBS ${OPENSSL_LIBRARIES}) +endif() +if(HAVE_LIBPAM) + list(APPEND TEST_DIRECT_LIBS ${LIBPAM_LIBRARIES}) +endif() + macro(get_test_ports PORT_COUNT PORT_DEFINITIONS) if (NOT ${PORT_COUNT}) set(${PORT_COUNT} 1) @@ -30,21 +36,12 @@ macro(get_test_ports PORT_COUNT PORT_DEFINITIONS) endmacro() function(libnetconf2_test) - cmake_parse_arguments(TEST "" "NAME;PORT_COUNT" "WRAP_FUNCS" ${ARGN}) + cmake_parse_arguments(TEST "" "NAME;PORT_COUNT" "" ${ARGN}) - add_executable(${TEST_NAME} $ ${TEST_SRC} ${TEST_NAME}.c) - target_link_libraries(${TEST_NAME} ${CMOCKA_LIBRARIES} ${LIBYANG_LIBRARIES} netconf2) + add_executable(${TEST_NAME} ${TEST_SRC} ${TEST_NAME}.c) + target_link_libraries(${TEST_NAME} ${CMOCKA_LIBRARIES} ncbin ${TEST_DIRECT_LIBS}) target_include_directories(${TEST_NAME} PRIVATE ${CMOCKA_INCLUDE_DIR}) - # wrap functions - if(TEST_WRAP_FUNCS) - set(wrap_link_flags "-Wl") - foreach(mock_func IN LISTS TEST_WRAP_FUNCS) - set(wrap_link_flags "${wrap_link_flags},--wrap=${mock_func}") - endforeach() - set_target_properties(${TEST_NAME} PROPERTIES LINK_FLAGS "${wrap_link_flags}") - endif() - # create a test, generate port numbers and set them as env vars for the test add_test(NAME ${TEST_NAME} COMMAND $) get_test_ports(TEST_PORT_COUNT TEST_PORT_DEFINITIONS) @@ -61,6 +58,7 @@ endfunction() # all the tests that don't require SSH and TLS libnetconf2_test(NAME test_client_messages) +libnetconf2_test(NAME test_client_monitoring) libnetconf2_test(NAME test_client_thread) libnetconf2_test(NAME test_fd_comm) libnetconf2_test(NAME test_io) @@ -73,18 +71,17 @@ if(ENABLE_SSH AND ENABLE_TLS) libnetconf2_test(NAME test_authkeys) libnetconf2_test(NAME test_cert_exp_notif) libnetconf2_test(NAME test_ch PORT_COUNT 2) - libnetconf2_test(NAME test_client_monitoring) libnetconf2_test(NAME test_config PORT_COUNT 6) libnetconf2_test(NAME test_endpt_share_clients PORT_COUNT 4) libnetconf2_test(NAME test_ks_ts) if (LIBPAM_HAVE_CONFDIR) - libnetconf2_test(NAME test_pam WRAP_FUNCS pam_start) + libnetconf2_test(NAME test_pam) endif() libnetconf2_test(NAME test_replace) libnetconf2_test(NAME test_runtime_changes PORT_COUNT 2) libnetconf2_test(NAME test_server_thread) - libnetconf2_test(NAME test_ssh WRAP_FUNCS ssh_get_issue_banner) - libnetconf2_test(NAME test_system_users WRAP_FUNCS getpwnam_r) + libnetconf2_test(NAME test_ssh) + libnetconf2_test(NAME test_system_users) libnetconf2_test(NAME test_tls) libnetconf2_test(NAME test_two_channels) endif() diff --git a/tests/data/modules/ietf-netconf-nmda@2019-01-07.yang b/tests/data/modules/ietf-netconf-nmda@2019-01-07.yang new file mode 100644 index 00000000..31dce50a --- /dev/null +++ b/tests/data/modules/ietf-netconf-nmda@2019-01-07.yang @@ -0,0 +1,385 @@ + module ietf-netconf-nmda { + yang-version 1.1; + namespace "urn:ietf:params:xml:ns:yang:ietf-netconf-nmda"; + prefix ncds; + + import ietf-yang-types { + prefix yang; + reference + "RFC 6991: Common YANG Data Types"; + } + import ietf-inet-types { + prefix inet; + reference + "RFC 6991: Common YANG Data Types"; + } + import ietf-datastores { + prefix ds; + reference + "RFC 8342: Network Management Datastore Architecture + (NMDA)"; + } + import ietf-origin { + prefix or; + reference + "RFC 8342: Network Management Datastore Architecture + (NMDA)"; + } + import ietf-netconf { + prefix nc; + reference + "RFC 6241: Network Configuration Protocol (NETCONF)"; + } + import ietf-netconf-with-defaults { + prefix ncwd; + reference + "RFC 6243: With-defaults Capability for NETCONF"; + } + + organization + "IETF NETCONF Working Group"; + + contact + "WG Web: + + WG List: + + Author: Martin Bjorklund + + + Author: Juergen Schoenwaelder + + + Author: Phil Shafer + + + Author: Kent Watsen + + + Author: Robert Wilton + "; + description + "This YANG module defines a set of NETCONF operations to support + the Network Management Datastore Architecture (NMDA). + + The key words 'MUST', 'MUST NOT', 'REQUIRED', 'SHALL', 'SHALL + NOT', 'SHOULD', 'SHOULD NOT', 'RECOMMENDED', 'NOT RECOMMENDED', + 'MAY', and 'OPTIONAL' in this document are to be interpreted as + described in BCP 14 (RFC 2119) (RFC 8174) when, and only when, + they appear in all capitals, as shown here. + + Copyright (c) 2019 IETF Trust and the persons identified as + authors of the code. All rights reserved. + + Redistribution and use in source and binary forms, with or + without modification, is permitted pursuant to, and subject to + the license terms contained in, the Simplified BSD License set + forth in Section 4.c of the IETF Trust's Legal Provisions + Relating to IETF Documents + (https://trustee.ietf.org/license-info). + + This version of this YANG module is part of RFC 8526; see + the RFC itself for full legal notices."; + + revision 2019-01-07 { + description + "Initial revision."; + reference + "RFC 8526: NETCONF Extensions to Support the Network Management + Datastore Architecture"; + } + + feature origin { + description + "Indicates that the server supports the 'origin' annotation."; + reference + "RFC 8342: Network Management Datastore Architecture (NMDA)"; + } + + feature with-defaults { + description + "NETCONF :with-defaults capability. If the server advertises + the :with-defaults capability for a session, then this + feature must also be enabled for that session. Otherwise, + this feature must not be enabled."; + reference + "RFC 6243: With-defaults Capability for NETCONF, Section 4; and + RFC 8526: NETCONF Extensions to Support the Network Management + Datastore Architecture, Section 3.1.1.2"; + } + + rpc get-data { + description + "Retrieve data from an NMDA datastore. The content returned + by get-data must satisfy all filters, i.e., the filter + criteria are logically ANDed. + + Any ancestor nodes (including list keys) of nodes selected by + the filters are included in the response. + + The 'with-origin' parameter is only valid for an operational + datastore. If 'with-origin' is used with an invalid + datastore, then the server MUST return an element + with an value of 'invalid-value'. + + The 'with-defaults' parameter only applies to the operational + datastore if the NETCONF :with-defaults and + :with-operational-defaults capabilities are both advertised. + If the 'with-defaults' parameter is present in a request for + which it is not supported, then the server MUST return an + element with an value of + 'invalid-value'."; + input { + leaf datastore { + type ds:datastore-ref; + mandatory true; + description + "Datastore from which to retrieve data. + + If the datastore is not supported by the server, then the + server MUST return an element with an + value of 'invalid-value'."; + } + choice filter-spec { + description + "The content filter specification for this request."; + anydata subtree-filter { + description + "This parameter identifies the portions of the + target datastore to retrieve."; + reference + "RFC 6241: Network Configuration Protocol (NETCONF), + Section 6"; + } + leaf xpath-filter { + if-feature "nc:xpath"; + type yang:xpath1.0; + description + "This parameter contains an XPath expression identifying + the portions of the target datastore to retrieve. + + If the expression returns a node-set, all nodes in the + node-set are selected by the filter. Otherwise, if the + expression does not return a node-set, then the + operation fails. + + The expression is evaluated in the following XPath + context: + + o The set of namespace declarations are those in + scope on the 'xpath-filter' leaf element. + + o The set of variable bindings is empty. + + o The function library is the core function library, + and the XPath functions are defined in Section 10 + of RFC 7950. + + o The context node is the root node of the target + datastore."; + } + } + leaf config-filter { + type boolean; + description + "Filter for nodes with the given value for their 'config' + property. When this leaf is set to 'true', only 'config + true' nodes are selected, and when set to 'false', only + 'config false' nodes are selected. If this leaf is not + present, no nodes are filtered."; + } + choice origin-filters { + when 'derived-from-or-self(datastore, "ds:operational")'; + if-feature "origin"; + description + "Filters configuration nodes based on the 'origin' + annotation. Configuration nodes that do not have an + 'origin' annotation are treated as if they have the + 'origin' annotation 'or:unknown'. + + System state nodes are not affected by origin-filters and + thus not filtered. Note that system state nodes can be + filtered with the 'config-filter' leaf."; + + leaf-list origin-filter { + type or:origin-ref; + description + "Filter based on the 'origin' annotation. A + configuration node matches the filter if its 'origin' + annotation is derived from or equal to any of the given + filter values."; + } + leaf-list negated-origin-filter { + type or:origin-ref; + description + "Filter based on the 'origin' annotation. A + configuration node matches the filter if its 'origin' + annotation is neither derived from nor equal to any of + the given filter values."; + } + } + leaf max-depth { + type union { + type uint16 { + range "1..65535"; + } + type enumeration { + enum unbounded { + description + "All descendant nodes are included."; + } + } + } + default "unbounded"; + description + "For each node selected by the filters, this parameter + selects how many conceptual subtree levels should be + returned in the reply. If the depth is 1, the reply + includes just the selected nodes but no children. If the + depth is 'unbounded', all descendant nodes are included."; + } + leaf with-origin { + when 'derived-from-or-self(../datastore, "ds:operational")'; + if-feature "origin"; + type empty; + description + "If this parameter is present, the server will return + the 'origin' annotation for the nodes that have one."; + } + uses ncwd:with-defaults-parameters { + if-feature "with-defaults"; + } + } + output { + anydata data { + description + "Copy of the source datastore subset that matched + the filter criteria (if any). An empty data + container indicates that the request did not + produce any results."; + } + } + } + + rpc edit-data { + description + "Edit data in an NMDA datastore. + + If an error condition occurs such that an error severity + element is generated, the server will stop + processing the operation and restore the + specified configuration to its complete state at + the start of this operation."; + input { + leaf datastore { + type ds:datastore-ref; + mandatory true; + description + "Datastore that is the target of the operation. + + If the target datastore is not writable, or is not + supported by the server, then the server MUST return an + element with an value of + 'invalid-value'."; + } + leaf default-operation { + type enumeration { + enum merge { + description + "The default operation is merge."; + } + enum replace { + description + "The default operation is replace."; + } + enum none { + description + "There is no default operation."; + } + } + default "merge"; + description + "The default operation to use."; + } + choice edit-content { + mandatory true; + description + "The content for the edit operation."; + anydata config { + description + "Inline config content."; + } + leaf url { + if-feature "nc:url"; + type inet:uri; + description + "URL-based config content."; + } + } + } + } + + /* + * Augment the and operations with a + * "datastore" parameter. + */ + + augment "/nc:lock/nc:input/nc:target/nc:config-target" { + description + "Add NMDA datastore as target."; + leaf datastore { + type ds:datastore-ref; + description + "Datastore to lock. + + The operation is only supported on writable + datastores. + + If the operation is not supported by the server on + the specified target datastore, then the server MUST return + an element with an value of + 'invalid-value'."; + } + } + + augment "/nc:unlock/nc:input/nc:target/nc:config-target" { + description + "Add NMDA datastore as target."; + leaf datastore { + type ds:datastore-ref; + description + "Datastore to unlock. + + The operation is only supported on writable + datastores. + + If the operation is not supported by the server on + the specified target datastore, then the server MUST return + an element with an value of + 'invalid-value'."; + } + } + + /* + * Augment the operation with a + * "datastore" parameter. + */ + + augment "/nc:validate/nc:input/nc:source/nc:config-source" { + description + "Add NMDA datastore as source."; + leaf datastore { + type ds:datastore-ref; + description + "Datastore to validate. + + The operation is supported only on configuration + datastores. + + If the operation is not supported by the server + on the specified target datastore, then the server MUST + return an element with an value of + 'invalid-value'."; + } + } + } diff --git a/tests/data/modules/ietf-origin@2018-02-14.yang b/tests/data/modules/ietf-origin@2018-02-14.yang new file mode 100644 index 00000000..7c8f2915 --- /dev/null +++ b/tests/data/modules/ietf-origin@2018-02-14.yang @@ -0,0 +1,147 @@ + module ietf-origin { + yang-version 1.1; + namespace "urn:ietf:params:xml:ns:yang:ietf-origin"; + prefix or; + + import ietf-yang-metadata { + prefix md; + } + + organization + "IETF Network Modeling (NETMOD) Working Group"; + + contact + "WG Web: + + WG List: + + Author: Martin Bjorklund + + + Author: Juergen Schoenwaelder + + + Author: Phil Shafer + + + Author: Kent Watsen + + + Author: Rob Wilton + "; + + description + "This YANG module defines an 'origin' metadata annotation and a + set of identities for the origin value. + + Copyright (c) 2018 IETF Trust and the persons identified as + authors of the code. All rights reserved. + + Redistribution and use in source and binary forms, with or + without modification, is permitted pursuant to, and subject to + the license terms contained in, the Simplified BSD License set + forth in Section 4.c of the IETF Trust's Legal Provisions + Relating to IETF Documents + (https://trustee.ietf.org/license-info). + + This version of this YANG module is part of RFC 8342 + (https://www.rfc-editor.org/info/rfc8342); see the RFC itself + for full legal notices."; + + revision 2018-02-14 { + description + "Initial revision."; + reference + "RFC 8342: Network Management Datastore Architecture (NMDA)"; + } + + /* + * Identities + */ + + identity origin { + description + "Abstract base identity for the origin annotation."; + } + + identity intended { + base origin; + description + "Denotes configuration from the intended configuration + datastore."; + } + + identity dynamic { + base origin; + description + "Denotes configuration from a dynamic configuration + datastore."; + } + + identity system { + base origin; + description + "Denotes configuration originated by the system itself. + + Examples of system configuration include applied configuration + for an always-existing loopback interface, or interface + configuration that is auto-created due to the hardware + currently present in the device."; + } + + identity learned { + base origin; + description + "Denotes configuration learned from protocol interactions with + other devices, instead of via either the intended + configuration datastore or any dynamic configuration + datastore. + + Examples of protocols that provide learned configuration + include link-layer negotiations, routing protocols, and + DHCP."; + } + + identity default { + base origin; + description + "Denotes configuration that does not have a configured or + learned value but has a default value in use. Covers both + values defined in a 'default' statement and values defined + via an explanation in a 'description' statement."; + } + + identity unknown { + base origin; + description + "Denotes configuration for which the system cannot identify the + origin."; + } + + /* + * Type definitions + */ + + typedef origin-ref { + type identityref { + base origin; + } + description + "An origin identity reference."; + } + + /* + * Metadata annotations + */ + + md:annotation origin { + type origin-ref; + description + "The 'origin' annotation can be present on any configuration + data node in the operational state datastore. It specifies + from where the node originated. If not specified for a given + configuration data node, then the origin is the same as the + origin of its parent node in the data tree. The origin for + any top-level configuration data nodes must be specified."; + } + } diff --git a/tests/library_valgrind.supp b/tests/library_valgrind.supp index 2e52ea86..20af41c2 100644 --- a/tests/library_valgrind.supp +++ b/tests/library_valgrind.supp @@ -9,11 +9,11 @@ fun:ly_ctx_new } { - test_pam:__wrap_pam_start_leak + test_pam:pam_start_leak Memcheck:Leak match-leak-kinds: definite fun:malloc ... - fun:__wrap_pam_start + fun:pam_start ... } diff --git a/tests/ln2_test.c b/tests/ln2_test.c index 0c7327d0..a0794b2c 100644 --- a/tests/ln2_test.c +++ b/tests/ln2_test.c @@ -17,10 +17,16 @@ #include #include +#include #include +#include #include #include #include +#include +#include + +#include #include "ln2_test.h" @@ -76,7 +82,7 @@ ln2_glob_test_server_thread(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* accept a session and add it to the poll session structure */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); if (msgtype != NC_MSG_HELLO) { SETUP_FAIL_LOG; nc_ps_free(ps); @@ -88,7 +94,7 @@ ln2_glob_test_server_thread(void *arg) /* poll until the session is terminated by the client */ do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); assert(ret & NC_PSPOLL_RPC); } while (!(ret & NC_PSPOLL_SESSION_TERM)); @@ -109,7 +115,7 @@ ln2_glob_test_server_thread_fail(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* try to accept a session, but we expect it to fail */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); assert(msgtype == NC_MSG_ERROR); (void)msgtype; assert(!session); @@ -202,3 +208,71 @@ ln2_glob_test_free_test_data(void *test_data) { free(test_data); } + +/** + * @brief Write a \ message advertising a single NETCONF base version. + * + * @param[in] fd File descriptor to write to. + * @param[in] version NETCONF version, 0 for 1.0, 1 for 1.1. + * @param[in] server Whether it is a server \, with a session ID. + * @return 0 on success, -1 on error. + */ +static int +ln2_test_write_hello(int fd, int version, int server) +{ + char *hello; + int len, rc = 0; + + len = asprintf(&hello, "" + "urn:ietf:params:netconf:base:1.%d%s]]>]]>", + version, server ? "1" : ""); + if (len == -1) { + return -1; + } + + if (write(fd, hello, len) != len) { + rc = -1; + } + free(hello); + return rc; +} + +void +ln2_glob_test_fd_sessions(struct ly_ctx *ctx, int version, struct nc_session **server, struct nc_session **client, + int fds[2]) +{ + int link[2], peer[2]; + + /* the sessions communicate over this socketpair */ + assert_int_equal(socketpair(AF_UNIX, SOCK_STREAM, 0, link), 0); + fds[0] = link[0]; + fds[1] = link[1]; + + if (client) { + /* handshake with a fake server on its own socketpair, which also gets the client hello */ + assert_int_equal(socketpair(AF_UNIX, SOCK_STREAM, 0, peer), 0); + assert_int_equal(ln2_test_write_hello(peer[0], version, 1), 0); + + /* the fake server provides no YANG modules, the client uses the context as it is */ + nc_client_set_new_session_context_autofill(0); + *client = nc_connect_inout(peer[1], peer[1], ctx); + assert_non_null(*client); + assert_int_equal(nc_session_get_version(*client), version); + + /* switch the client to its end of the link */ + assert_int_not_equal(dup2(link[1], peer[1]), -1); + close(peer[0]); + close(link[1]); + fds[1] = peer[1]; + } + + /* the same for the server with a fake client */ + assert_int_equal(socketpair(AF_UNIX, SOCK_STREAM, 0, peer), 0); + assert_int_equal(ln2_test_write_hello(peer[1], version, 0), 0); + assert_int_equal(nc_accept_inout(peer[0], peer[0], "test", ctx, server), NC_MSG_HELLO); + assert_int_equal(nc_session_get_version(*server), version); + assert_int_not_equal(dup2(link[0], peer[0]), -1); + close(peer[1]); + close(link[0]); + fds[0] = peer[0]; +} diff --git a/tests/ln2_test.h b/tests/ln2_test.h index efcec05c..b0745cdf 100644 --- a/tests/ln2_test.h +++ b/tests/ln2_test.h @@ -21,8 +21,14 @@ #include "tests/config.h" -#define NC_ACCEPT_TIMEOUT 4000 -#define NC_PS_POLL_TIMEOUT 2000 +/* timeout of accepting a new session */ +#define NC_ACCEPT_TIMEOUT_MS 4000 + +/* timeout of a single poll of the sessions */ +#define NC_PS_POLL_TIMEOUT_MS 2000 + +/* timeout of sending or receiving a single message */ +#define NC_MSG_TIMEOUT_MS 1000 #define SETUP_FAIL_LOG \ fprintf(stderr, "Setup fail in %s:%d.\n", __FILE__, __LINE__) @@ -85,4 +91,20 @@ int ln2_glob_test_teardown(void **state); */ void ln2_glob_test_free_test_data(void *test_data); +/** + * @brief Create NETCONF sessions on both ends of a new socketpair. + * + * Each session makes its handshake with a fake peer on a separate socketpair, which chooses the NETCONF + * version, and is then switched to its end of the shared socketpair. Disables the client context autofill, + * the fake server provides no YANG modules. + * + * @param[in] ctx libyang context of the sessions. + * @param[in] version NETCONF version, 0 for 1.0, 1 for 1.1, as returned by ::nc_session_get_version(). + * @param[out] server Created server session. + * @param[out] client Created client session, NULL if not needed. + * @param[out] fds Socketpair, the server end first, the caller closes both after freeing the sessions. + */ +void ln2_glob_test_fd_sessions(struct ly_ctx *ctx, int version, struct nc_session **server, struct nc_session **client, + int fds[2]); + #endif diff --git a/tests/test_authkeys.c b/tests/test_authkeys.c index 138a3c32..e1d90b2b 100644 --- a/tests/test_authkeys.c +++ b/tests/test_authkeys.c @@ -51,7 +51,7 @@ server_thread(void *arg) /* accept a session and add it to the poll session structure */ pthread_barrier_wait(&test_ctx->barrier); - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); /* only continue if we expect to authenticate successfully */ if (test_data->expect_ok) { @@ -66,7 +66,7 @@ server_thread(void *arg) assert_int_equal(ret, 0); do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); assert_int_equal(ret & NC_PSPOLL_RPC, NC_PSPOLL_RPC); } while (!(ret & NC_PSPOLL_SESSION_TERM)); diff --git a/tests/test_cert_exp_notif.c b/tests/test_cert_exp_notif.c index 7673a6c0..1ef7f93d 100644 --- a/tests/test_cert_exp_notif.c +++ b/tests/test_cert_exp_notif.c @@ -327,7 +327,7 @@ server_thread(void *arg) /* wait until the client is ready to connect */ pthread_barrier_wait(&state->barrier); - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, server_ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, server_ctx, &session); assert_int_equal(msgtype, NC_MSG_HELLO); /* add sess to ps */ @@ -336,7 +336,7 @@ server_thread(void *arg) /* serve all the RPCs */ do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, NULL); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, NULL); } while (ret & NC_PSPOLL_RPC); /* increase session notification subscription flag count */ diff --git a/tests/test_ch.c b/tests/test_ch.c index 704c4304..066148c2 100644 --- a/tests/test_ch.c +++ b/tests/test_ch.c @@ -122,7 +122,7 @@ server_thread_ssh(void *arg) /* poll */ new_msg = 0; do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); if (ret & NC_PSPOLL_SESSION_TERM) { /* the session was removed from ps and we own it now */ nc_session_free(session, NULL); @@ -175,7 +175,7 @@ client_thread_ssh(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* connect */ - ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT, NULL, &session); + ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT_MS, NULL, &session); assert_int_equal(ret, 1); ret = nc_client_ssh_ch_del_bind("127.0.0.1", TEST_PORT); @@ -291,7 +291,7 @@ server_thread_tls(void *arg) /* poll */ do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); if (ret & NC_PSPOLL_SESSION_TERM) { /* the session was removed from ps and we own it now */ nc_session_free(session, NULL); @@ -334,7 +334,7 @@ client_thread_tls(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* connect */ - ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT, NULL, &session); + ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT_MS, NULL, &session); assert_int_equal(ret, 1); ret = nc_client_tls_ch_del_bind("127.0.0.1", TEST_PORT_2); @@ -464,7 +464,7 @@ server_thread_delete_while_session(void *arg) } do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); if (ret & NC_PSPOLL_SESSION_TERM) { /* the session was removed from ps and we own it now */ nc_session_free(session, NULL); @@ -510,7 +510,7 @@ client_thread_delete_while_session(void *arg) pthread_barrier_wait(&test_ctx->barrier); - ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT, NULL, &session); + ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT_MS, NULL, &session); assert_int_equal(ret, 1); /* wait until the server deletes the client */ @@ -642,7 +642,7 @@ server_thread_two_ch(void *arg) } pthread_mutex_unlock(&session_count_mutex); - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); if (ret & NC_PSPOLL_SESSION_TERM) { /* the session was removed from ps and we own it now */ nc_session_free(session, NULL); @@ -678,7 +678,7 @@ client_thread_two_ch(void *arg) pthread_barrier_wait(&ch_arg->test_ctx->barrier); - ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT, NULL, &session); + ret = nc_accept_callhome(NC_ACCEPT_TIMEOUT_MS, NULL, &session); assert_int_equal(ret, 1); ret = nc_client_ssh_ch_del_bind("127.0.0.1", ch_arg->port); diff --git a/tests/test_client_messages.c b/tests/test_client_messages.c index a38c1c11..a4294558 100644 --- a/tests/test_client_messages.c +++ b/tests/test_client_messages.c @@ -14,684 +14,487 @@ #define _GNU_SOURCE -#include #include -#include +#include +#include +#include #include #include -#include -#include +#include #include -#include +#include #include "ln2_test.h" -static int -setup_f(void **state) -{ - (void)state; +/* subtree content used in the filters and edits */ +#define TEST_SUBTREE "val" - nc_verbosity(NC_VERB_VERBOSE); +/* URLs in the RPCs, the server never accesses them */ +#define TEST_URL "file:/nonexistent.xml" +#define TEST_SRC_URL "file:/nonexistent-src.xml" - return 0; -} +/* XPath used in the filters and how the server prints it */ +#define TEST_XPATH "/ietf-netconf-server:netconf-server" +#define TEST_XPATH_NS "xmlns:ncs=\"urn:ietf:params:xml:ns:yang:ietf-netconf-server\"" +#define TEST_XPATH_PRINTED "/ncs:netconf-server" -static int -teardown_f(void **state) +/* opening tag of with-defaults */ +#define TEST_WD "" + +struct test_state { + struct nc_session *server; + struct nc_session *client; + int fds[2]; + struct nc_pollsession *ps; +}; + +/* context shared by all the tests */ +static struct ln2_test_ctx *test_ctx; + +/* the last RPC received by the server */ +static struct lyd_node *recv_rpc; + +/** + * @brief Global RPC callback, remembers the received RPC. + */ +static struct nc_server_reply * +test_rpc_clb(struct lyd_node *rpc, struct nc_session *UNUSED(session)) { - (void)state; + lyd_free_tree(recv_rpc); + recv_rpc = NULL; + if (lyd_dup_single(rpc, NULL, LYD_DUP_RECURSIVE, &recv_rpc)) { + return NULL; + } - return 0; + return nc_server_reply_ok(); } +/** + * @brief Send an RPC and check the RPC received by the server. + * + * @param[in] st Test state. + * @param[in] rpc RPC to send, it is freed. + * @param[in] expected Expected XML of the received RPC. + */ static void -test_nc_rpc_act_generic_xml(void **state) +test_send_rpc(struct test_state *st, struct nc_rpc *rpc, const char *expected) { - (void)state; - struct nc_rpc *rpc = NULL; - struct nc_rpc_act_generic *generic_rpc = NULL; - - /* create generic rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_act_generic_xml("xml", NC_PARAMTYPE_CONST); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC); - generic_rpc = (struct nc_rpc_act_generic *)rpc; - assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC); - assert_int_equal(generic_rpc->has_data, 0); - assert_string_equal(generic_rpc->content.xml_str, "xml"); - nc_rpc_free(rpc); + uint64_t msgid; + struct lyd_node *envp, *op; + char *xml; - /* create generic rpc with NC_PARAMTYPE_FREE */ - char *str = strdup("str"); + assert_non_null(rpc); + assert_int_equal(nc_send_rpc(st->client, rpc, NC_MSG_TIMEOUT_MS, &msgid), NC_MSG_RPC); - rpc = nc_rpc_act_generic_xml(str, NC_PARAMTYPE_FREE); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC); - generic_rpc = (struct nc_rpc_act_generic *)rpc; - assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC); - assert_int_equal(generic_rpc->has_data, 0); - assert_string_equal(generic_rpc->content.xml_str, str); + /* the server receives the RPC and replies */ + assert_int_equal(nc_ps_poll(st->ps, NC_PS_POLL_TIMEOUT_MS, NULL), NC_PSPOLL_RPC); + assert_int_equal(nc_recv_reply(st->client, rpc, msgid, NC_MSG_TIMEOUT_MS, &envp, &op), NC_MSG_REPLY); + assert_null(op); + assert_string_equal(LYD_NAME(lyd_child(envp)), "ok"); + lyd_free_tree(envp); nc_rpc_free(rpc); - /* create generic rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_act_generic_xml("xml", NC_PARAMTYPE_DUP_AND_FREE); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC); - generic_rpc = (struct nc_rpc_act_generic *)rpc; - assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC); - assert_int_equal(generic_rpc->has_data, 0); - assert_string_equal(generic_rpc->content.xml_str, "xml"); - nc_rpc_free(rpc); + /* compare the received RPC */ + assert_non_null(recv_rpc); + assert_int_equal(lyd_print_mem(&xml, recv_rpc, LYD_XML, LYD_PRINT_SHRINK), LY_SUCCESS); + assert_string_equal(xml, expected); + free(xml); + lyd_free_tree(recv_rpc); + recv_rpc = NULL; } static void -test_nc_rpc_act_generic(void **state) +test_nc_rpc_act_generic_xml(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; - struct nc_rpc_act_generic *generic_rpc = NULL; - struct lyd_node node; - - node.next = NULL; - node.prev = &node; + struct test_state *st = *state; + const char *xml = ""; - rpc = nc_rpc_act_generic(&node, NC_PARAMTYPE_CONST); - assert_non_null(rpc); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC); - generic_rpc = (struct nc_rpc_act_generic *)rpc; - assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC); - assert_int_equal(generic_rpc->has_data, 1); - assert_ptr_equal(generic_rpc->content.data, &node); - nc_rpc_free(rpc); + test_send_rpc(st, nc_rpc_act_generic_xml(xml, NC_PARAMTYPE_CONST), xml); + test_send_rpc(st, nc_rpc_act_generic_xml(strdup(xml), NC_PARAMTYPE_FREE), xml); + test_send_rpc(st, nc_rpc_act_generic_xml(xml, NC_PARAMTYPE_DUP_AND_FREE), xml); } -/* function to check if values of getconfig rpc are set correctly */ -void -check_getconfig(struct nc_rpc *rpc, NC_DATASTORE source, char *filter, NC_WD_MODE wd_mode) +static void +test_nc_rpc_act_generic(void **state) { - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GETCONFIG); - struct nc_rpc_getconfig *getconfig_rpc = (struct nc_rpc_getconfig *)rpc; + struct test_state *st = *state; + const char *xml = ""; + struct lyd_node *data; + + assert_int_equal(lyd_new_path(NULL, test_ctx->ctx, "/ietf-netconf:lock/target/candidate", NULL, 0, &data), + LY_SUCCESS); - assert_int_equal(getconfig_rpc->type, NC_RPC_GETCONFIG); - assert_int_equal(getconfig_rpc->source, source); - assert_string_equal(getconfig_rpc->filter, filter); - assert_int_equal(getconfig_rpc->wd_mode, wd_mode); + test_send_rpc(st, nc_rpc_act_generic(data, NC_PARAMTYPE_CONST), xml); + test_send_rpc(st, nc_rpc_act_generic(data, NC_PARAMTYPE_DUP_AND_FREE), xml); + test_send_rpc(st, nc_rpc_act_generic(data, NC_PARAMTYPE_FREE), xml); } static void test_nc_rpc_getconfig(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; + struct test_state *st = *state; - /* create getconfig rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_getconfig(NC_DATASTORE_CANDIDATE, "filter-string", NC_WD_UNKNOWN, NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_getconfig(rpc, NC_DATASTORE_CANDIDATE, "filter-string", NC_WD_UNKNOWN); - nc_rpc_free(rpc); + /* subtree filter */ + test_send_rpc(st, nc_rpc_getconfig(NC_DATASTORE_CANDIDATE, TEST_SUBTREE, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST), + "" + "" TEST_SUBTREE ""); - /* create getconfig rpc with NC_PARAMTYPE_FREE */ - char *filter = strdup("string"); + /* XPath filter */ + test_send_rpc(st, nc_rpc_getconfig(NC_DATASTORE_RUNNING, strdup(TEST_XPATH), NC_WD_EXPLICIT, + NC_PARAMTYPE_FREE), + "" + "" + TEST_WD "explicit" + ""); - rpc = nc_rpc_getconfig(NC_DATASTORE_CONFIG, filter, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_getconfig(rpc, NC_DATASTORE_CONFIG, filter, NC_WD_EXPLICIT); - nc_rpc_free(rpc); - - /* create getconfig rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_getconfig(NC_DATASTORE_RUNNING, "filter", NC_WD_ALL, NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_getconfig(rpc, NC_DATASTORE_RUNNING, "filter", NC_WD_ALL); - nc_rpc_free(rpc); -} - -/* function to check if values of edit rpc are set correctly */ -void -check_edit(struct nc_rpc *rpc, NC_DATASTORE target, NC_RPC_EDIT_DFLTOP default_op, NC_RPC_EDIT_TESTOPT test_opt, - NC_RPC_EDIT_ERROPT error_opt, const char *edit_content) -{ - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_EDIT); - struct nc_rpc_edit *edit_rpc = (struct nc_rpc_edit *)rpc; - - assert_int_equal(edit_rpc->type, NC_RPC_EDIT); - assert_int_equal(edit_rpc->target, target); - assert_int_equal(edit_rpc->default_op, default_op); - assert_int_equal(edit_rpc->test_opt, test_opt); - assert_int_equal(edit_rpc->error_opt, error_opt); - assert_string_equal(edit_rpc->edit_cont, edit_content); + /* no filter */ + test_send_rpc(st, nc_rpc_getconfig(NC_DATASTORE_STARTUP, NULL, NC_WD_ALL, NC_PARAMTYPE_DUP_AND_FREE), + "" + TEST_WD "report-all" + ""); } static void test_nc_rpc_edit(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; + struct test_state *st = *state; - /* create edit rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_edit(NC_DATASTORE_RUNNING, NC_RPC_EDIT_DFLTOP_REPLACE, NC_RPC_EDIT_TESTOPT_TESTSET, - NC_RPC_EDIT_ERROPT_STOP, "url", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_edit(rpc, NC_DATASTORE_RUNNING, NC_RPC_EDIT_DFLTOP_REPLACE, - NC_RPC_EDIT_TESTOPT_TESTSET, NC_RPC_EDIT_ERROPT_STOP, "url"); - nc_rpc_free(rpc); + /* config */ + test_send_rpc(st, nc_rpc_edit(NC_DATASTORE_RUNNING, NC_RPC_EDIT_DFLTOP_REPLACE, NC_RPC_EDIT_TESTOPT_TESTSET, + NC_RPC_EDIT_ERROPT_ROLLBACK, TEST_SUBTREE, NC_PARAMTYPE_CONST), + "" + "replacetest-then-set" + "rollback-on-error" TEST_SUBTREE ""); - /* create edit rpc with NC_PARAMTYPE_FREE */ - char *str = strdup("string"); - - rpc = nc_rpc_edit(NC_DATASTORE_CANDIDATE, NC_RPC_EDIT_DFLTOP_MERGE, NC_RPC_EDIT_TESTOPT_SET, - NC_RPC_EDIT_ERROPT_ROLLBACK, str, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_edit(rpc, NC_DATASTORE_CANDIDATE, NC_RPC_EDIT_DFLTOP_MERGE, - NC_RPC_EDIT_TESTOPT_SET, NC_RPC_EDIT_ERROPT_ROLLBACK, str); - nc_rpc_free(rpc); - - /* create edit rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_edit(NC_DATASTORE_CONFIG, NC_RPC_EDIT_DFLTOP_NONE, NC_RPC_EDIT_TESTOPT_TEST, - NC_RPC_EDIT_ERROPT_CONTINUE, "url1", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_edit(rpc, NC_DATASTORE_CONFIG, NC_RPC_EDIT_DFLTOP_NONE, - NC_RPC_EDIT_TESTOPT_TEST, NC_RPC_EDIT_ERROPT_CONTINUE, "url1"); - nc_rpc_free(rpc); -} + /* URL */ + test_send_rpc(st, nc_rpc_edit(NC_DATASTORE_CANDIDATE, NC_RPC_EDIT_DFLTOP_MERGE, NC_RPC_EDIT_TESTOPT_SET, + NC_RPC_EDIT_ERROPT_STOP, strdup(TEST_URL), NC_PARAMTYPE_FREE), + "" + "mergeset" + "stop-on-error" TEST_URL ""); -/* function to check if values of copy rpc are set correctly */ -void -check_copy(struct nc_rpc *rpc, NC_DATASTORE target, const char *url_trg, NC_DATASTORE source, - const char *url_or_config_src, NC_WD_MODE wd_mode) -{ - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_COPY); - struct nc_rpc_copy *copy_rpc = (struct nc_rpc_copy *)rpc; - - assert_int_equal(copy_rpc->type, NC_RPC_COPY); - assert_int_equal(copy_rpc->target, target); - assert_string_equal(copy_rpc->url_trg, url_trg); - assert_int_equal(copy_rpc->source, source); - assert_string_equal(copy_rpc->url_config_src, url_or_config_src); - assert_int_equal(copy_rpc->wd_mode, wd_mode); + /* no options */ + test_send_rpc(st, nc_rpc_edit(NC_DATASTORE_CANDIDATE, NC_RPC_EDIT_DFLTOP_UNKNOWN, NC_RPC_EDIT_TESTOPT_UNKNOWN, + NC_RPC_EDIT_ERROPT_UNKNOWN, TEST_SUBTREE, NC_PARAMTYPE_DUP_AND_FREE), + "" + "" TEST_SUBTREE ""); } static void test_nc_rpc_copy(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; - - /* create copy rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_copy(NC_DATASTORE_RUNNING, "target-url", NC_DATASTORE_RUNNING, "src-url", - NC_WD_ALL, NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_copy(rpc, NC_DATASTORE_RUNNING, "target-url", NC_DATASTORE_RUNNING, "src-url", NC_WD_ALL); - nc_rpc_free(rpc); - - /* create copy rpc with NC_PARAMTYPE_FREE */ - char *target = strdup("target"); - char *src = strdup("src"); + struct test_state *st = *state; - rpc = nc_rpc_copy(NC_DATASTORE_STARTUP, target, NC_DATASTORE_RUNNING, src, - NC_WD_ALL_TAG, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_copy(rpc, NC_DATASTORE_STARTUP, target, NC_DATASTORE_RUNNING, src, NC_WD_ALL_TAG); - nc_rpc_free(rpc); + /* datastores */ + test_send_rpc(st, nc_rpc_copy(NC_DATASTORE_STARTUP, NULL, NC_DATASTORE_RUNNING, NULL, NC_WD_TRIM, + NC_PARAMTYPE_CONST), + "" + "" + TEST_WD "trim" + ""); - /* create copy rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_copy(NC_DATASTORE_STARTUP, "url", NC_DATASTORE_CANDIDATE, "url", - NC_WD_TRIM, NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_copy(rpc, NC_DATASTORE_STARTUP, "url", NC_DATASTORE_CANDIDATE, "url", NC_WD_TRIM); - nc_rpc_free(rpc); -} - -/* function to check if values of delete rpc are set correctly */ -void -check_delete(struct nc_rpc *rpc, NC_DATASTORE target, const char *url) -{ - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_DELETE); - struct nc_rpc_delete *delete_rpc = (struct nc_rpc_delete *)rpc; + /* URLs */ + test_send_rpc(st, nc_rpc_copy(NC_DATASTORE_URL, strdup(TEST_URL), NC_DATASTORE_URL, + strdup(TEST_SRC_URL), NC_WD_UNKNOWN, NC_PARAMTYPE_FREE), + "" + "" TEST_URL "" TEST_SRC_URL "" + ""); - assert_int_equal(delete_rpc->type, NC_RPC_DELETE); - assert_int_equal(delete_rpc->target, target); - assert_string_equal(delete_rpc->url, url); + /* config */ + test_send_rpc(st, nc_rpc_copy(NC_DATASTORE_CANDIDATE, NULL, NC_DATASTORE_CONFIG, TEST_SUBTREE, NC_WD_UNKNOWN, + NC_PARAMTYPE_DUP_AND_FREE), + "" + "" TEST_SUBTREE ""); } static void test_nc_rpc_delete(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; - - /* create delete rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_delete(NC_DATASTORE_RUNNING, "target-url", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_delete(rpc, NC_DATASTORE_RUNNING, "target-url"); - nc_rpc_free(rpc); + struct test_state *st = *state; - /* create delete rpc with NC_PARAMTYPE_FREE */ - char *url = strdup("url"); - - rpc = nc_rpc_delete(NC_DATASTORE_CANDIDATE, url, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_delete(rpc, NC_DATASTORE_CANDIDATE, url); - nc_rpc_free(rpc); - - /* create delete rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_delete(NC_DATASTORE_CONFIG, "target", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_delete(rpc, NC_DATASTORE_CONFIG, "target"); - nc_rpc_free(rpc); + test_send_rpc(st, nc_rpc_delete(NC_DATASTORE_STARTUP, NULL, NC_PARAMTYPE_CONST), + "" + ""); + test_send_rpc(st, nc_rpc_delete(NC_DATASTORE_URL, strdup(TEST_URL), NC_PARAMTYPE_FREE), + "" + "" TEST_URL ""); + test_send_rpc(st, nc_rpc_delete(NC_DATASTORE_URL, TEST_URL, NC_PARAMTYPE_DUP_AND_FREE), + "" + "" TEST_URL ""); } static void test_nc_rpc_lock(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; - struct nc_rpc_lock *lock_rpc = NULL; - - rpc = nc_rpc_lock(NC_DATASTORE_RUNNING); - assert_non_null(rpc); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_LOCK); - - lock_rpc = (struct nc_rpc_lock *)rpc; - assert_int_equal(lock_rpc->type, NC_RPC_LOCK); - assert_int_equal(lock_rpc->target, NC_DATASTORE_RUNNING); - - nc_rpc_free(rpc); -} - -static void -test_nc_rpc_unlock(void **state) -{ - (void)state; - struct nc_rpc *rpc = NULL; - struct nc_rpc_lock *unlock_rpc = NULL; - - rpc = nc_rpc_unlock(NC_DATASTORE_RUNNING); - assert_non_null(rpc); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_UNLOCK); + struct test_state *st = *state; - unlock_rpc = (struct nc_rpc_lock *)rpc; - assert_int_equal(unlock_rpc->type, NC_RPC_UNLOCK); - assert_int_equal(unlock_rpc->target, NC_DATASTORE_RUNNING); - nc_rpc_free(rpc); -} - -/* function to check if values of get rpc are set correctly */ -void -check_get_rpc(struct nc_rpc *rpc, const char *filter, NC_WD_MODE wd_mode) -{ - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GET); - struct nc_rpc_get *get_rpc = (struct nc_rpc_get *)rpc; - - assert_int_equal(get_rpc->type, NC_RPC_GET); - assert_string_equal(get_rpc->filter, filter); - assert_int_equal(get_rpc->wd_mode, wd_mode); + test_send_rpc(st, nc_rpc_lock(NC_DATASTORE_RUNNING), + ""); + test_send_rpc(st, nc_rpc_unlock(NC_DATASTORE_CANDIDATE), + ""); } static void test_nc_rpc_get(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; + struct test_state *st = *state; - /* create get rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_get("filter", NC_WD_ALL, NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_get_rpc(rpc, "filter", NC_WD_ALL); - nc_rpc_free(rpc); + /* subtree filter */ + test_send_rpc(st, nc_rpc_get(TEST_SUBTREE, NC_WD_ALL_TAG, NC_PARAMTYPE_CONST), + "" TEST_SUBTREE "" + TEST_WD "report-all-tagged"); - /* create get rpc with NC_PARAMTYPE_FREE */ - char *str = strdup("string"); - - rpc = nc_rpc_get(str, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_get_rpc(rpc, str, NC_WD_EXPLICIT); - nc_rpc_free(rpc); + /* XPath filter */ + test_send_rpc(st, nc_rpc_get(strdup(TEST_XPATH), NC_WD_UNKNOWN, NC_PARAMTYPE_FREE), + "" + "" + ""); - /* create get rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_get("filter-string", NC_WD_UNKNOWN, NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_get_rpc(rpc, "filter-string", NC_WD_UNKNOWN); - nc_rpc_free(rpc); + /* no filter */ + test_send_rpc(st, nc_rpc_get(NULL, NC_WD_UNKNOWN, NC_PARAMTYPE_DUP_AND_FREE), + ""); } static void test_nc_rpc_kill(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; - struct nc_rpc_kill *kill_rpc = NULL; - - rpc = nc_rpc_kill(10); - assert_non_null(rpc); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_KILL); - - kill_rpc = (struct nc_rpc_kill *)rpc; - assert_int_equal(kill_rpc->type, NC_RPC_KILL); - assert_int_equal(kill_rpc->sid, 10); + struct test_state *st = *state; - nc_rpc_free(rpc); -} - -/* function to check if values of commit rpc are set correctly */ -void -check_commit_rpc(struct nc_rpc *rpc, int confirmed, uint32_t confirm_timeout, const char *persist, const char *persist_id) -{ - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_COMMIT); - struct nc_rpc_commit *commit_rpc = (struct nc_rpc_commit *)rpc; - - assert_int_equal(commit_rpc->type, NC_RPC_COMMIT); - assert_int_equal(commit_rpc->confirmed, confirmed); - assert_int_equal(commit_rpc->confirm_timeout, confirm_timeout); - assert_string_equal(commit_rpc->persist, persist); - assert_string_equal(commit_rpc->persist_id, persist_id); + test_send_rpc(st, nc_rpc_kill(10), + "10" + ""); } static void test_nc_rpc_commit(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; - - /* create commit rpc with NC_PARAMTYPE_CONST*/ - rpc = nc_rpc_commit(1, 100, "persist", "persist-id", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_commit_rpc(rpc, 1, 100, "persist", "persist-id"); - nc_rpc_free(rpc); + struct test_state *st = *state; - /* create commit rpc with NC_PARAMTYPE_FREE*/ - char *str1 = strdup("str1"); - char *str2 = strdup("str2"); + /* confirmed */ + test_send_rpc(st, nc_rpc_commit(1, 100, "persist", NULL, NC_PARAMTYPE_CONST), + "" + "100persist"); - rpc = nc_rpc_commit(2, 5, str1, str2, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_commit_rpc(rpc, 2, 5, str1, str2); - nc_rpc_free(rpc); + /* confirming */ + test_send_rpc(st, nc_rpc_commit(0, 0, NULL, strdup("persist"), NC_PARAMTYPE_FREE), + "persist"); - /* create commit rpc with NC_PARAMTYPE_DUP_AND_FREE*/ - rpc = nc_rpc_commit(10, 200, "persistent", "persistent-id", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_commit_rpc(rpc, 10, 200, "persistent", "persistent-id"); - nc_rpc_free(rpc); + /* plain */ + test_send_rpc(st, nc_rpc_commit(0, 0, NULL, NULL, NC_PARAMTYPE_DUP_AND_FREE), + ""); } static void test_nc_rpc_discard(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; + struct test_state *st = *state; - rpc = nc_rpc_discard(); - assert_non_null(rpc); - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_DISCARD); - - nc_rpc_free(rpc); + test_send_rpc(st, nc_rpc_discard(), ""); } -/* function to check if values of cancel rpc are set correctly */ -void -check_cancel_rpc(struct nc_rpc *rpc, const char *persist_id) +static void +test_nc_rpc_cancel(void **state) { - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_CANCEL); - struct nc_rpc_cancel *cancel_rpc = (struct nc_rpc_cancel *)rpc; + struct test_state *st = *state; - assert_int_equal(cancel_rpc->type, NC_RPC_CANCEL); - assert_string_equal(cancel_rpc->persist_id, persist_id); + test_send_rpc(st, nc_rpc_cancel("persist", NC_PARAMTYPE_CONST), + "persist" + ""); + test_send_rpc(st, nc_rpc_cancel(strdup("persist"), NC_PARAMTYPE_FREE), + "persist" + ""); + test_send_rpc(st, nc_rpc_cancel(NULL, NC_PARAMTYPE_DUP_AND_FREE), + ""); } static void -test_nc_rpc_cancel(void **state) +test_nc_rpc_validate(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; - - /* create cancel rpc with NC_PARAMTYPE_CONST*/ - rpc = nc_rpc_cancel("persist-id", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_cancel_rpc(rpc, "persist-id"); - nc_rpc_free(rpc); - - /* create cancel rpc with NC_PARAMTYPE_FREE*/ - char *str = strdup("string"); - - rpc = nc_rpc_cancel(str, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_cancel_rpc(rpc, str); - nc_rpc_free(rpc); + struct test_state *st = *state; - /* create cancel rpc with NC_PARAMTYPE_DUP_AND_FREE*/ - rpc = nc_rpc_cancel("id", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_cancel_rpc(rpc, "id"); - nc_rpc_free(rpc); + test_send_rpc(st, nc_rpc_validate(NC_DATASTORE_CANDIDATE, NULL, NC_PARAMTYPE_CONST), + ""); + test_send_rpc(st, nc_rpc_validate(NC_DATASTORE_URL, strdup(TEST_URL), NC_PARAMTYPE_FREE), + "" + "" TEST_URL ""); + test_send_rpc(st, nc_rpc_validate(NC_DATASTORE_CONFIG, TEST_SUBTREE, NC_PARAMTYPE_DUP_AND_FREE), + "" + "" TEST_SUBTREE ""); } -/* function to check if values of validate rpc are set correctly */ -void -check_validate_rpc(struct nc_rpc *rpc, NC_DATASTORE source, const char *url_or_config) +static void +test_nc_rpc_getschema(void **state) { - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_VALIDATE); - struct nc_rpc_validate *validate_rpc = (struct nc_rpc_validate *)rpc; + struct test_state *st = *state; - assert_int_equal(validate_rpc->type, NC_RPC_VALIDATE); - assert_int_equal(validate_rpc->source, source); - assert_string_equal(validate_rpc->url_config_src, url_or_config); + test_send_rpc(st, nc_rpc_getschema("ietf-netconf", "2013-09-29", "yang", NC_PARAMTYPE_CONST), + "" + "ietf-netconf2013-09-29yang"); + test_send_rpc(st, nc_rpc_getschema(strdup("ietf-netconf"), NULL, strdup("yin"), NC_PARAMTYPE_FREE), + "" + "ietf-netconfyin"); + test_send_rpc(st, nc_rpc_getschema("ietf-netconf", NULL, NULL, NC_PARAMTYPE_DUP_AND_FREE), + "" + "ietf-netconf"); } static void -test_nc_rpc_validate(void **state) +test_nc_rpc_subscribe(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; + struct test_state *st = *state; - /* create validate rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_validate(NC_DATASTORE_RUNNING, "url", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_validate_rpc(rpc, NC_DATASTORE_RUNNING, "url"); - nc_rpc_free(rpc); + /* subtree filter and times */ + test_send_rpc(st, nc_rpc_subscribe("stream", TEST_SUBTREE, "2026-01-01T00:00:00Z", "2026-01-02T00:00:00Z", + NC_PARAMTYPE_CONST), + "stream" + "" TEST_SUBTREE "2026-01-01T00:00:00Z" + "2026-01-02T00:00:00Z"); - /* create validate rpc with NC_PARAMTYPE_FREE */ - char *str = strdup("string"); + /* XPath filter */ + test_send_rpc(st, nc_rpc_subscribe(strdup("stream"), strdup(TEST_XPATH), NULL, NULL, NC_PARAMTYPE_FREE), + "stream" + "" + ""); - rpc = nc_rpc_validate(NC_DATASTORE_CANDIDATE, str, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_validate_rpc(rpc, NC_DATASTORE_CANDIDATE, str); - nc_rpc_free(rpc); - - /* create validate rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_validate(NC_DATASTORE_CONFIG, "url1", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_validate_rpc(rpc, NC_DATASTORE_CONFIG, "url1"); - nc_rpc_free(rpc); + /* defaults */ + test_send_rpc(st, nc_rpc_subscribe(NULL, NULL, NULL, NULL, NC_PARAMTYPE_DUP_AND_FREE), + ""); } -/* function to check if values of getschema rpc are set correctly */ -void -check_getschema_rpc(struct nc_rpc *rpc, const char *identifier, const char *version, const char *format) +static void +test_nc_rpc_getdata(void **state) { - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GETSCHEMA); - struct nc_rpc_getschema *getchema_rpc = (struct nc_rpc_getschema *)rpc; - - assert_int_equal(getchema_rpc->type, NC_RPC_GETSCHEMA); - assert_string_equal(getchema_rpc->identifier, identifier); - assert_string_equal(getchema_rpc->version, version); - assert_string_equal(getchema_rpc->format, format); + struct test_state *st = *state; + char *origin_filter = (char *)"ietf-origin:intended"; + char **origin_filters; + + /* XPath filter, origin */ + test_send_rpc(st, nc_rpc_getdata("ietf-datastores:operational", TEST_XPATH, "true", &origin_filter, + 1, 0, 3, 1, NC_WD_EXPLICIT, NC_PARAMTYPE_CONST), + "" + "ds:operational" + "" TEST_XPATH_PRINTED "" + "true" + "or:intended" + "3explicit"); + + /* subtree filter, negated origin */ + origin_filters = malloc(sizeof *origin_filters); + assert_non_null(origin_filters); + origin_filters[0] = strdup(origin_filter); + test_send_rpc(st, nc_rpc_getdata(strdup("ietf-datastores:operational"), strdup(TEST_SUBTREE), NULL, + origin_filters, 1, 1, 0, 0, NC_WD_UNKNOWN, NC_PARAMTYPE_FREE), + "" + "ds:operational" + "" TEST_SUBTREE "" + "or:intended" + ""); + + /* no filter */ + test_send_rpc(st, nc_rpc_getdata("ietf-datastores:running", NULL, "false", NULL, 0, 0, 0, 0, NC_WD_UNKNOWN, + NC_PARAMTYPE_DUP_AND_FREE), + "" + "ds:running" + "false"); } static void -test_nc_rpc_getschema(void **state) +test_nc_rpc_editdata(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; + struct test_state *st = *state; + + test_send_rpc(st, nc_rpc_editdata("ietf-datastores:candidate", NC_RPC_EDIT_DFLTOP_MERGE, TEST_SUBTREE, + NC_PARAMTYPE_CONST), + "" + "ds:candidate" + "merge" TEST_SUBTREE ""); + test_send_rpc(st, nc_rpc_editdata(strdup("ietf-datastores:running"), NC_RPC_EDIT_DFLTOP_UNKNOWN, + strdup(TEST_URL), NC_PARAMTYPE_FREE), + "" + "ds:running" + "" TEST_URL ""); + test_send_rpc(st, nc_rpc_editdata("ietf-datastores:running", NC_RPC_EDIT_DFLTOP_REPLACE, TEST_SUBTREE, + NC_PARAMTYPE_DUP_AND_FREE), + "" + "ds:running" + "replace" TEST_SUBTREE ""); +} - /* create getchema with NC_PARAMTYPE_CONST*/ - rpc = nc_rpc_getschema("id", "version", "format", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_getschema_rpc(rpc, "id", "version", "format"); - nc_rpc_free(rpc); +static int +setup_f(void **state) +{ + struct test_state *st; - /* create getchema with NC_PARAMTYPE_FREE*/ - char *str1 = strdup("str1"); - char *str2 = strdup("str2"); - char *str3 = strdup("str3"); + st = calloc(1, sizeof *st); + if (!st) { + SETUP_FAIL_LOG; + return 1; + } + *state = st; - rpc = nc_rpc_getschema(str1, str2, str3, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_getschema_rpc(rpc, str1, str2, str3); - nc_rpc_free(rpc); + ln2_glob_test_fd_sessions(test_ctx->ctx, 1, &st->server, &st->client, st->fds); - /* create getchema with NC_PARAMTYPE_DUP_AND_FREE*/ - rpc = nc_rpc_getschema("id1", "version1", "format1", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_getschema_rpc(rpc, "id1", "version1", "format1"); - nc_rpc_free(rpc); -} + st->ps = nc_ps_new(); + if (!st->ps || nc_ps_add_session(st->ps, st->server)) { + SETUP_FAIL_LOG; + return 1; + } -/* function to check if values of subscribe rpc are set correctly */ -void -check_subscribe_rpc(struct nc_rpc *rpc, const char *stream_name, const char *filter, - const char *start_time, const char *stop_time) -{ - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_SUBSCRIBE); - struct nc_rpc_subscribe *subscribe_rpc = (struct nc_rpc_subscribe *)rpc; - - assert_int_equal(subscribe_rpc->type, NC_RPC_SUBSCRIBE); - assert_string_equal(subscribe_rpc->stream, stream_name); - assert_string_equal(subscribe_rpc->filter, filter); - assert_string_equal(subscribe_rpc->start, start_time); - assert_string_equal(subscribe_rpc->stop, stop_time); + return 0; } -static void -test_nc_rpc_subscribe(void **state) +static int +teardown_f(void **state) { - (void)state; - struct nc_rpc *rpc = NULL; + struct test_state *st = *state; - /* create subscribe rpc with NC_PARAMTYPE_CONST*/ - rpc = nc_rpc_subscribe("stream-name", "filter", "start-time", "stop-time", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_subscribe_rpc(rpc, "stream-name", "filter", "start-time", "stop-time"); - nc_rpc_free(rpc); + nc_ps_free(st->ps); - /* create subscribe rpc with NC_PARAMTYPE_FREE*/ - char *str1 = strdup("str1"); - char *str2 = strdup("str2"); - char *str3 = strdup("str3"); - char *str4 = strdup("str4"); + /* close the socketpair first so that the client does not wait for a reply */ + close(st->fds[0]); + close(st->fds[1]); + nc_session_free(st->server, NULL); + nc_session_free(st->client, NULL); + free(st); - rpc = nc_rpc_subscribe(str1, str2, str3, str4, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_subscribe_rpc(rpc, str1, str2, str3, str4); - nc_rpc_free(rpc); - - /* create subscribe rpc with NC_PARAMTYPE_DUP_AND_FREE*/ - rpc = nc_rpc_subscribe("name", "filter-str", "start", "stop", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_subscribe_rpc(rpc, "name", "filter-str", "start", "stop"); - nc_rpc_free(rpc); + return 0; } -/* function to check if values of getdata rpc are set correctly */ -void -check_getdata(struct nc_rpc *rpc, char *datastore, const char *filter, const char *config_filter, - char **origin_filter, int origin_filter_count, int negated_origin_filter, uint16_t max_depth, - int with_origin, NC_WD_MODE wd_mode) +static int +setup_glob(void **state) { - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GETDATA); - struct nc_rpc_getdata *rpc_getdata = (struct nc_rpc_getdata *)rpc; - - assert_int_equal(rpc_getdata->type, NC_RPC_GETDATA); - assert_string_equal(rpc_getdata->datastore, datastore); - assert_string_equal(rpc_getdata->filter, filter); - assert_string_equal(rpc_getdata->config_filter, config_filter); - assert_string_equal(*rpc_getdata->origin_filter, *origin_filter); - assert_int_equal(rpc_getdata->origin_filter_count, origin_filter_count); - assert_int_equal(rpc_getdata->negated_origin_filter, negated_origin_filter); - assert_int_equal(rpc_getdata->max_depth, max_depth); - assert_int_equal(rpc_getdata->with_origin, with_origin); - assert_int_equal(rpc_getdata->wd_mode, wd_mode); -} + const char *nmda_features[] = {"origin", "with-defaults", NULL}; -static void -test_nc_rpc_getdata(void **state) -{ (void)state; - struct nc_rpc *rpc = NULL; - /* create getdata rpc with NC_PARAMTYPE_CONST */ - char *origin_filters = "origin_filter"; - - rpc = nc_rpc_getdata("candidate", "filter", "true", &origin_filters, 1, 1, 3, 1, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_getdata(rpc, "candidate", "filter", "true", &origin_filters, 1, 1, 3, 1, NC_WD_UNKNOWN); - nc_rpc_free(rpc); - - /* create getdata rpc with NC_PARAMTYPE_FREE */ - char *datastore = strdup("running"); - char *filter = strdup("filter"); - char *config_filter = strdup("true"); - char buf[20] = {0}; - char **origin_filter; - int origin_filter_count = 2; - - origin_filter = calloc(origin_filter_count, sizeof *origin_filter); - assert_non_null(origin_filter); - for (int i = 0; i < origin_filter_count; i++) { - snprintf(buf, sizeof(buf) - 1, "origin_filter%d", i + 1); - origin_filter[i] = strdup(buf); + if (ln2_glob_test_setup(&test_ctx)) { + return 1; } - rpc = nc_rpc_getdata(datastore, filter, config_filter, origin_filter, origin_filter_count, 2, 3, 1, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_getdata(rpc, datastore, filter, config_filter, origin_filter, origin_filter_count, 2, 3, 1, NC_WD_EXPLICIT); - nc_rpc_free(rpc); - - /* create getdata rpc with NC_PARAMTYPE_DUP_AND_FREE */ - char *origin_filter1 = "origin_filter1"; - - rpc = nc_rpc_getdata("startup", "filter1", "false", &origin_filter1, 1, 0, 3, 1, NC_WD_ALL, NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_getdata(rpc, "startup", "filter1", "false", &origin_filter1, 1, 0, 3, 1, NC_WD_ALL); - nc_rpc_free(rpc); -} + /* modules of all the RPCs */ + ly_ctx_set_searchdir(test_ctx->ctx, TESTS_DIR "/data/modules"); + if (!ly_ctx_load_module(test_ctx->ctx, "ietf-netconf-with-defaults", NULL, NULL) || + !ly_ctx_load_module(test_ctx->ctx, "notifications", NULL, NULL) || + !ly_ctx_load_module(test_ctx->ctx, "ietf-origin", NULL, NULL) || + !ly_ctx_load_module(test_ctx->ctx, "ietf-netconf-nmda", NULL, nmda_features)) { + SETUP_FAIL_LOG; + return 1; + } -/* function to check if values of editdata rpc are set correctly */ -void -check_editdata(struct nc_rpc *rpc, char *datastore, NC_RPC_EDIT_DFLTOP default_op, const char *edit_content) -{ - assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_EDITDATA); - struct nc_rpc_editdata *rpc_editdata = (struct nc_rpc_editdata *)rpc; + /* the server only remembers the RPCs */ + nc_set_global_rpc_clb(test_rpc_clb); - assert_int_equal(rpc_editdata->type, NC_RPC_EDITDATA); - assert_string_equal(rpc_editdata->datastore, datastore); - assert_int_equal(rpc_editdata->default_op, default_op); - assert_string_equal(rpc_editdata->edit_cont, edit_content); + return 0; } -static void -test_nc_rpc_editdata(void **state) +static int +teardown_glob(void **state) { (void)state; - struct nc_rpc *rpc = NULL; - - /* create editdata rpc with NC_PARAMTYPE_CONST */ - rpc = nc_rpc_editdata("candidate", NC_RPC_EDIT_DFLTOP_UNKNOWN, "edit", NC_PARAMTYPE_CONST); - assert_non_null(rpc); - check_editdata(rpc, "candidate", NC_RPC_EDIT_DFLTOP_UNKNOWN, "edit"); - nc_rpc_free(rpc); - /* create editdata rpc with NC_PARAMTYPE_FREE */ - char *datastore = strdup("running"); - char *edit_cont = strdup("edit_data"); - - rpc = nc_rpc_editdata(datastore, NC_RPC_EDIT_DFLTOP_MERGE, edit_cont, NC_PARAMTYPE_FREE); - assert_non_null(rpc); - check_editdata(rpc, datastore, NC_RPC_EDIT_DFLTOP_MERGE, edit_cont); - nc_rpc_free(rpc); - - /* create editdata rpc with NC_PARAMTYPE_DUP_AND_FREE */ - rpc = nc_rpc_editdata("startup", NC_RPC_EDIT_DFLTOP_REPLACE, "edit_cont", NC_PARAMTYPE_DUP_AND_FREE); - assert_non_null(rpc); - check_editdata(rpc, "startup", NC_RPC_EDIT_DFLTOP_REPLACE, "edit_cont"); - nc_rpc_free(rpc); + nc_set_global_rpc_clb(NULL); + return ln2_glob_test_teardown((void **)&test_ctx); } int @@ -705,7 +508,6 @@ main(void) cmocka_unit_test_setup_teardown(test_nc_rpc_copy, setup_f, teardown_f), cmocka_unit_test_setup_teardown(test_nc_rpc_delete, setup_f, teardown_f), cmocka_unit_test_setup_teardown(test_nc_rpc_lock, setup_f, teardown_f), - cmocka_unit_test_setup_teardown(test_nc_rpc_unlock, setup_f, teardown_f), cmocka_unit_test_setup_teardown(test_nc_rpc_get, setup_f, teardown_f), cmocka_unit_test_setup_teardown(test_nc_rpc_kill, setup_f, teardown_f), cmocka_unit_test_setup_teardown(test_nc_rpc_commit, setup_f, teardown_f), @@ -718,5 +520,5 @@ main(void) cmocka_unit_test_setup_teardown(test_nc_rpc_editdata, setup_f, teardown_f), }; - return cmocka_run_group_tests(tests, NULL, NULL); + return cmocka_run_group_tests(tests, setup_glob, teardown_glob); } diff --git a/tests/test_client_monitoring.c b/tests/test_client_monitoring.c index c398777d..7f42acdd 100644 --- a/tests/test_client_monitoring.c +++ b/tests/test_client_monitoring.c @@ -15,200 +15,84 @@ #define _GNU_SOURCE -#include #include #include #include -#include -#include -#include +#include +#include +#include #include #include "ln2_test.h" -#include "session_p.h" -#include +/* how long to wait for the monitoring callback */ +#define TEST_CLB_TIMEOUT_S 5 -int TEST_PORT = 10050; -const char *TEST_PORT_STR = "10050"; +/* the session passed to the monitoring callback, guarded by clb_lock */ +static pthread_mutex_t clb_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t clb_cond = PTHREAD_COND_INITIALIZER; +static struct nc_session *clb_session; -void -monitoring_clb(struct nc_session *sess, void *user_data) -{ - pthread_barrier_t *barrier = user_data; - - /* signal the main thread that the monitoring callback was called */ - pthread_barrier_wait(barrier); - printf("Session with ID %d disconnected by the server.\n", nc_session_get_id(sess)); - nc_session_free(sess, NULL); -} - -static void * -client_thread(void *arg) -{ - int ret; - struct nc_session *session = NULL; - struct ln2_test_ctx *test_ctx = arg; - pthread_barrier_t monitoring_barrier; - - /* initialize the barrier */ - ret = pthread_barrier_init(&monitoring_barrier, NULL, 2); - assert_int_equal(ret, 0); - - /* start the monitoring thread */ - ret = nc_client_monitoring_thread_start(monitoring_clb, &monitoring_barrier, NULL); - assert_int_equal(ret, 0); - - /* skip all hostkey and known_hosts checks */ - nc_client_ssh_set_knownhosts_mode(NC_SSH_KNOWNHOSTS_SKIP); - - /* set the search path for the schemas */ - ret = nc_client_set_schema_searchpath(MODULES_DIR); - assert_int_equal(ret, 0); - - /* set the client's username */ - ret = nc_client_ssh_set_username("test_client_monitoring"); - assert_int_equal(ret, 0); - - /* add the client's key pair */ - ret = nc_client_ssh_add_keypair(TESTS_DIR "/data/key_rsa.pub", TESTS_DIR "/data/key_rsa"); - assert_int_equal(ret, 0); - - /* wait for the server to be ready and connect */ - pthread_barrier_wait(&test_ctx->barrier); - session = nc_connect_ssh("127.0.0.1", TEST_PORT, NULL); - assert_non_null(session); - - /* wait for the monitoring thread callback to be called */ - pthread_barrier_wait(&monitoring_barrier); - - /* stop the monitoring thread */ - nc_client_monitoring_thread_stop(); - - pthread_barrier_destroy(&monitoring_barrier); - return NULL; -} - -void * -server_thread(void *arg) +/** + * @brief Monitoring callback, remembers the disconnected session. + */ +static void +test_monitoring_clb(struct nc_session *session, void *UNUSED(user_data)) { - int ret; - NC_MSG_TYPE msgtype; - struct nc_session *session = NULL; - struct nc_pollsession *ps = NULL; - struct ln2_test_ctx *test_ctx = arg; - int fd; - struct linger ling = {1, 0}; - const char *cpb; - - ps = nc_ps_new(); - assert_non_null(ps); - - /* wait for the client to be ready to connect */ - pthread_barrier_wait(&test_ctx->barrier); - - /* accept a session and add it to the poll session structure */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); - assert_int_equal(msgtype, NC_MSG_HELLO); - - /* just check capabilities function on the client */ - cpb = nc_session_cpblt(session, "urn:ietf:params:netconf:base:1.1"); - assert_non_null(cpb); - - /* get the session's fd */ - fd = ssh_get_fd(session->ti.libssh.session); - assert_int_not_equal(fd, -1); - - /* set the socket to close immediately */ - ret = setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)); - assert_int_equal(ret, 0); - - /* add the session to the poll session */ - ret = nc_ps_add_session(ps, session); - assert_int_equal(ret, 0); - - /* poll until the client stops sending messages */ - do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); - if (ret & NC_PSPOLL_SESSION_TERM) { - /* the session was removed from ps and we own it now */ - break; - } - } while ((ret & NC_PSPOLL_RPC)); - - /* free the session (it will close the socket -> client needs to detect this) */ - if (ret & NC_PSPOLL_SESSION_TERM) { - nc_session_free(session, NULL); - } else { - nc_ps_clear(ps, 1, NULL); - } - nc_ps_free(ps); - return NULL; + pthread_mutex_lock(&clb_lock); + clb_session = session; + pthread_cond_signal(&clb_cond); + pthread_mutex_unlock(&clb_lock); } static void test_nc_client_monitoring(void **state) { - int ret, i; - pthread_t tids[2]; + struct ln2_test_ctx *test_ctx = *state; + struct nc_session *server, *client, *sess; + struct timespec ts; + int fds[2], r = 0; + + /* the monitoring thread watches only the sessions created after it started */ + assert_int_equal(nc_client_monitoring_thread_start(test_monitoring_clb, NULL, NULL), 0); + ln2_glob_test_fd_sessions(test_ctx->ctx, 1, &server, &client, fds); + + /* the server end disappears */ + close(fds[0]); + + /* wait for the callback */ + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += TEST_CLB_TIMEOUT_S; + pthread_mutex_lock(&clb_lock); + while (!clb_session && !r) { + r = pthread_cond_timedwait(&clb_cond, &clb_lock, &ts); + } + sess = clb_session; + pthread_mutex_unlock(&clb_lock); - ret = pthread_create(&tids[0], NULL, client_thread, *state); - assert_int_equal(ret, 0); - ret = pthread_create(&tids[1], NULL, server_thread, *state); - assert_int_equal(ret, 0); + assert_ptr_equal(sess, client); + assert_int_equal(nc_session_get_status(client), NC_STATUS_INVALID); + assert_int_equal(nc_session_get_term_reason(client), NC_SESSION_TERM_DROPPED); - for (i = 0; i < 2; i++) { - pthread_join(tids[i], NULL); - } + nc_client_monitoring_thread_stop(); + nc_session_free(client, NULL); + nc_session_free(server, NULL); + close(fds[1]); } static int -setup(void **state) +setup_glob(void **state) { - int ret; - struct lyd_node *tree = NULL; - struct ln2_test_ctx *test_ctx; - - /* global setup */ - ret = ln2_glob_test_setup(&test_ctx); - assert_int_equal(ret, 0); - - *state = test_ctx; - - /* add endpoint */ - ret = nc_server_config_add_address_port(test_ctx->ctx, "endpt", NC_TI_SSH, "127.0.0.1", TEST_PORT, &tree); - assert_int_equal(ret, 0); - - /* add hostkey */ - ret = nc_server_config_add_ssh_hostkey(test_ctx->ctx, "endpt", "hostkey", TESTS_DIR "/data/key_ecdsa", NULL, &tree); - assert_int_equal(ret, 0); - - /* add the test client */ - ret = nc_server_config_add_ssh_user_pubkey(test_ctx->ctx, "endpt", "test_client_monitoring", "pubkey", TESTS_DIR "/data/key_rsa.pub", &tree); - assert_int_equal(ret, 0); - - /* configure the server based on the data */ - ret = nc_server_config_setup_data(tree); - assert_int_equal(ret, 0); - - lyd_free_all(tree); - - return 0; + return ln2_glob_test_setup((struct ln2_test_ctx **)state); } int main(void) { const struct CMUnitTest tests[] = { - cmocka_unit_test_setup_teardown(test_nc_client_monitoring, setup, ln2_glob_test_teardown) + cmocka_unit_test(test_nc_client_monitoring), }; - /* try to get ports from the environment, otherwise use the default */ - if (ln2_glob_test_get_ports(1, &TEST_PORT, &TEST_PORT_STR)) { - return 1; - } - - setenv("CMOCKA_TEST_ABORT", "1", 1); - return cmocka_run_group_tests(tests, NULL, NULL); + return cmocka_run_group_tests(tests, setup_glob, ln2_glob_test_teardown); } diff --git a/tests/test_config.c b/tests/test_config.c index 1e70e998..defba833 100644 --- a/tests/test_config.c +++ b/tests/test_config.c @@ -480,7 +480,7 @@ conn_preserve_server_thread(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* accept a session and add it to the poll session structure */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); assert_int_equal(msgtype, NC_MSG_HELLO); ret = nc_ps_add_session(ps, session); @@ -488,7 +488,7 @@ conn_preserve_server_thread(void *arg) /* poll until the session is fully established */ do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, NULL); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, NULL); } while (ret & NC_PSPOLL_RPC); /* print port number into the new data */ @@ -513,7 +513,7 @@ conn_preserve_server_thread(void *arg) /* poll until we receive the rpc from the client */ do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, NULL); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, NULL); } while (!(ret & NC_PSPOLL_RPC)); /* wait for the client */ @@ -1467,7 +1467,7 @@ test_stall_auth_server_thread(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* the client never authenticates, so this is expected to fail after the stall */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); assert_int_not_equal(msgtype, NC_MSG_HELLO); nc_session_free(session, NULL); diff --git a/tests/test_fd_comm.c b/tests/test_fd_comm.c index 883e8afc..bde949af 100644 --- a/tests/test_fd_comm.c +++ b/tests/test_fd_comm.c @@ -31,9 +31,6 @@ #include #include -#include -#include - #include "ln2_test.h" struct state { @@ -43,6 +40,7 @@ struct state { pthread_mutex_t state_lock; pthread_barrier_t barrier; int glob_state; + int fds[2]; }; static struct nc_server_reply * @@ -60,7 +58,7 @@ my_getconfig_rpc_clb(struct lyd_node *rpc, struct nc_session *session) assert_string_equal(rpc->schema->name, "get-config"); - lyd_new_path(NULL, session->ctx, "/ietf-netconf:get-config/data", NULL, LYD_NEW_VAL_OUTPUT, &data); + lyd_new_path(NULL, nc_session_get_ctx(session), "/ietf-netconf:get-config/data", NULL, LYD_NEW_VAL_OUTPUT, &data); assert_non_null(data); return nc_server_reply_data(data, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE); @@ -134,6 +132,7 @@ setup_f(void **state) node->priv = my_commit_rpc_clb; nc_server_init(); + nc_client_init(); *state = st; return 0; @@ -144,6 +143,7 @@ teardown_f(void **state) { struct state *st = *state; + nc_client_destroy(); nc_server_destroy(); ly_ctx_destroy(st->ctx); pthread_mutex_destroy(&st->state_lock); @@ -153,77 +153,37 @@ teardown_f(void **state) return 0; } -static struct nc_session * -test_new_session(NC_SIDE side) +/** + * @brief Create the server and client sessions. + * + * @param[in] state Test state. + * @param[in] version NETCONF version, 0 for 1.0, 1 for 1.1. + * @return 0 on success, non-zero on error. + */ +static int +setup_sessions(void **state, int version) { - struct nc_session *sess; - struct timespec ts; - - sess = calloc(1, sizeof *sess); - if (!sess) { - return NULL; - } - - sess->side = side; - - if (side == NC_SERVER) { - pthread_mutex_init(&sess->opts.server.ntf_status_lock, NULL); - pthread_mutex_init(&sess->opts.server.rpc_lock, NULL); - pthread_cond_init(&sess->opts.server.rpc_cond, NULL); - sess->opts.server.rpc_inuse = 0; - - nc_timeouttime_get(&ts, 0); - sess->opts.server.last_rpc = ts.tv_sec; - } + struct state *st = *state; - sess->io_lock = malloc(sizeof *sess->io_lock); - if (!sess->io_lock) { - goto error; - } - pthread_mutex_init(sess->io_lock, NULL); + ln2_glob_test_fd_sessions(st->ctx, version, &st->server_session, &st->client_session, st->fds); + fcntl(st->fds[0], F_SETFL, O_NONBLOCK); + fcntl(st->fds[1], F_SETFL, O_NONBLOCK); - return sess; + nc_session_set_data(st->server_session, st); -error: - free(sess); - return NULL; + return 0; } static int -setup_sessions(void **state) +setup_sessions_10(void **state) { - struct state *st = *state; - int sock[2]; - - /* create communication channel */ - socketpair(AF_UNIX, SOCK_STREAM, 0, sock); - fcntl(sock[0], F_SETFL, O_NONBLOCK); - fcntl(sock[1], F_SETFL, O_NONBLOCK); - - /* create server session */ - st->server_session = test_new_session(NC_SERVER); - NC_SESSION_STATUS_SET(st->server_session, NC_STATUS_RUNNING); - st->server_session->id = 1; - st->server_session->ti_type = NC_TI_FD; - st->server_session->ti.fd.in = sock[0]; - st->server_session->ti.fd.out = sock[0]; - st->server_session->ctx = st->ctx; - st->server_session->flags = NC_SESSION_SHAREDCTX; - - nc_session_set_data(st->server_session, st); - - /* create client session */ - st->client_session = test_new_session(NC_CLIENT); - NC_SESSION_STATUS_SET(st->client_session, NC_STATUS_RUNNING); - st->client_session->id = 1; - st->client_session->ti_type = NC_TI_FD; - st->client_session->ti.fd.in = sock[1]; - st->client_session->ti.fd.out = sock[1]; - st->client_session->ctx = st->ctx; - st->client_session->flags = NC_SESSION_SHAREDCTX; - st->client_session->opts.client.msgid = 50; + return setup_sessions(state, 0); +} - return 0; +static int +setup_sessions_11(void **state) +{ + return setup_sessions(state, 1); } static int @@ -231,20 +191,19 @@ teardown_sessions(void **state) { struct state *st = *state; - close(st->server_session->ti.fd.in); - st->server_session->ti.fd.in = -1; + /* close the socketpair first so that the client does not wait for a reply */ + close(st->fds[0]); + close(st->fds[1]); nc_session_free(st->server_session, NULL); - - close(st->client_session->ti.fd.in); - st->client_session->ti.fd.in = -1; nc_session_free(st->client_session, NULL); return 0; } static void -test_send_recv_ok(struct state *st) +test_send_recv_ok(void **state) { + struct state *st = *state; int ret; uint64_t msgid; NC_MSG_TYPE msgtype; @@ -259,9 +218,9 @@ test_send_recv_ok(struct state *st) msgtype = nc_send_rpc(st->client_session, rpc, 0, &msgid); assert_int_equal(msgtype, NC_MSG_RPC); - if (st->client_session->version == NC_PROT_VERSION_10) { + if (!nc_session_get_version(st->client_session)) { /* send also some WS characters that should be ignored */ - ret = write(st->client_session->ti.fd.out, " \f\n\r\t\v", 6); + ret = write(st->fds[1], " \f\n\r\t\v", 6); assert_int_equal(ret, 6); } @@ -291,30 +250,9 @@ test_send_recv_ok(struct state *st) } static void -test_send_recv_ok_10(void **state) +test_send_recv_error(void **state) { struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_10; - st->client_session->version = NC_PROT_VERSION_10; - - test_send_recv_ok(st); -} - -static void -test_send_recv_ok_11(void **state) -{ - struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_11; - st->client_session->version = NC_PROT_VERSION_11; - - test_send_recv_ok(st); -} - -static void -test_send_recv_error(struct state *st) -{ int ret; uint64_t msgid; NC_MSG_TYPE msgtype; @@ -356,30 +294,9 @@ test_send_recv_error(struct state *st) } static void -test_send_recv_error_10(void **state) +test_send_recv_data(void **state) { struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_10; - st->client_session->version = NC_PROT_VERSION_10; - - test_send_recv_error(st); -} - -static void -test_send_recv_error_11(void **state) -{ - struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_11; - st->client_session->version = NC_PROT_VERSION_11; - - test_send_recv_error(st); -} - -static void -test_send_recv_data(struct state *st) -{ int ret; uint64_t msgid; NC_MSG_TYPE msgtype; @@ -416,28 +333,6 @@ test_send_recv_data(struct state *st) lyd_free_tree(op); } -static void -test_send_recv_data_10(void **state) -{ - struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_10; - st->client_session->version = NC_PROT_VERSION_10; - - test_send_recv_data(st); -} - -static void -test_send_recv_data_11(void **state) -{ - struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_11; - st->client_session->version = NC_PROT_VERSION_11; - - test_send_recv_data(st); -} - static void * server_send_notif_thread(void *arg) { @@ -487,7 +382,7 @@ thread_recv_notif(void *arg) NC_MSG_TYPE msgtype; pthread_barrier_wait(&st->barrier); - msgtype = nc_recv_notif(st->client_session, 1000, &envp, &op); + msgtype = nc_recv_notif(st->client_session, NC_MSG_TIMEOUT_MS, &envp, &op); assert_int_equal(msgtype, NC_MSG_NOTIF); assert_string_equal(op->schema->name, "notificationComplete"); @@ -502,8 +397,9 @@ thread_recv_notif(void *arg) } static void -test_send_recv_notif(struct state *st) +test_send_recv_notif(void **state) { + struct state *st = *state; int ret; pthread_t tid[2]; uint64_t msgid; @@ -560,28 +456,6 @@ test_send_recv_notif(struct state *st) assert_null(op); } -static void -test_send_recv_notif_10(void **state) -{ - struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_10; - st->client_session->version = NC_PROT_VERSION_10; - - test_send_recv_notif(st); -} - -static void -test_send_recv_notif_11(void **state) -{ - struct state *st = *state; - - st->server_session->version = NC_PROT_VERSION_11; - st->client_session->version = NC_PROT_VERSION_11; - - test_send_recv_notif(st); -} - static void test_send_recv_malformed_10(void **state) { @@ -594,16 +468,13 @@ test_send_recv_malformed_10(void **state) NC_MSG_TYPE msgtype; const char *msg; - st->server_session->version = NC_PROT_VERSION_10; - st->client_session->version = NC_PROT_VERSION_10; - /* write malformed message */ msg = "" " " "" "]]>]]>"; - assert_int_equal(write(st->client_session->ti.fd.out, msg, strlen(msg)), strlen(msg)); + assert_int_equal(write(st->fds[1], msg, strlen(msg)), strlen(msg)); rpc = nc_rpc_commit(0, 0, NULL, NULL, 0); assert_non_null(rpc); @@ -636,15 +507,15 @@ int main(void) { const struct CMUnitTest comm[] = { - cmocka_unit_test_setup_teardown(test_send_recv_ok_10, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_error_10, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_data_10, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_notif_10, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_malformed_10, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_ok_11, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_error_11, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_data_11, setup_sessions, teardown_sessions), - cmocka_unit_test_setup_teardown(test_send_recv_notif_11, setup_sessions, teardown_sessions), + {"test_send_recv_ok_10", test_send_recv_ok, setup_sessions_10, teardown_sessions, NULL}, + {"test_send_recv_error_10", test_send_recv_error, setup_sessions_10, teardown_sessions, NULL}, + {"test_send_recv_data_10", test_send_recv_data, setup_sessions_10, teardown_sessions, NULL}, + {"test_send_recv_notif_10", test_send_recv_notif, setup_sessions_10, teardown_sessions, NULL}, + cmocka_unit_test_setup_teardown(test_send_recv_malformed_10, setup_sessions_10, teardown_sessions), + {"test_send_recv_ok_11", test_send_recv_ok, setup_sessions_11, teardown_sessions, NULL}, + {"test_send_recv_error_11", test_send_recv_error, setup_sessions_11, teardown_sessions, NULL}, + {"test_send_recv_data_11", test_send_recv_data, setup_sessions_11, teardown_sessions, NULL}, + {"test_send_recv_notif_11", test_send_recv_notif, setup_sessions_11, teardown_sessions, NULL}, }; return cmocka_run_group_tests(comm, setup_f, teardown_f); diff --git a/tests/test_io.c b/tests/test_io.c index 55d1ea96..e9c8bbe4 100644 --- a/tests/test_io.c +++ b/tests/test_io.c @@ -14,85 +14,85 @@ #define _GNU_SOURCE -#include -#include #include #include #include #include #include -#include -#include -#include #include #include #include -#include -#include - #include "ln2_test.h" struct wr { - struct nc_session *session; + struct ln2_test_ctx *test_ctx; + struct nc_session *server; + struct nc_session *client; + int fds[2]; struct nc_rpc *rpc; }; +/** + * @brief Create the sessions and the RPC to write. + * + * @param[in] state Test state. + * @param[in] version NETCONF version, 0 for 1.0, 1 for 1.1. + * @return 0 on success, non-zero on error. + */ static int -setup_write(void **state) +setup_write(void **state, int version) { - (void) state; /* unused */ - int fd, pipes[2]; struct wr *w; - w = malloc(sizeof *w); - w->session = calloc(1, sizeof *w->session); - ly_ctx_new(ly_yang_module_dir(), 0, &w->session->ctx); - ly_ctx_set_searchdir(w->session->ctx, TESTS_DIR "/data/modules"); - - /* ietf-netconf */ - fd = open(TESTS_DIR "/data/modules/ietf-netconf.yin", O_RDONLY); - if (fd == -1) { - free(w->session); - free(w); - return -1; + w = calloc(1, sizeof *w); + if (!w) { + return 1; } + *state = w; - lys_parse_fd(w->session->ctx, fd, LYS_IN_YIN, NULL); - close(fd); - - assert_return_code(pipe(pipes), errno); + if (ln2_glob_test_setup(&w->test_ctx)) { + return 1; + } - NC_SESSION_STATUS_SET(w->session, NC_STATUS_RUNNING); - w->session->version = NC_PROT_VERSION_10; - w->session->opts.client.msgid = 999; - w->session->ti_type = NC_TI_FD; - w->session->io_lock = malloc(sizeof *w->session->io_lock); - pthread_mutex_init(w->session->io_lock, NULL); - w->session->ti.fd.in = pipes[0]; - w->session->ti.fd.out = pipes[1]; + ln2_glob_test_fd_sessions(w->test_ctx->ctx, version, &w->server, &w->client, w->fds); /* get rpc to write */ w->rpc = nc_rpc_lock(NC_DATASTORE_RUNNING); - assert_non_null(w->rpc); - - *state = w; + if (!w->rpc) { + return 1; + } return 0; } +static int +setup_write_10(void **state) +{ + return setup_write(state, 0); +} + +static int +setup_write_11(void **state) +{ + return setup_write(state, 1); +} + static int teardown_write(void **state) { - struct wr *w = (struct wr *)*state; + struct wr *w = *state; nc_rpc_free(w->rpc); - close(w->session->ti.fd.in); - w->session->ti.fd.in = -1; - close(w->session->ti.fd.out); - w->session->ti.fd.out = -1; - nc_session_free(w->session, NULL); + + /* close the socketpair first so that the client does not wait for a reply */ + close(w->fds[0]); + close(w->fds[1]); + nc_session_free(w->server, NULL); + nc_session_free(w->client, NULL); + + ln2_glob_test_teardown((void **)&w->test_ctx); free(w); *state = NULL; @@ -102,88 +102,42 @@ teardown_write(void **state) static void test_write_rpc(void **state) { - struct wr *w = (struct wr *)*state; + struct wr *w = *state; uint64_t msgid; NC_MSG_TYPE type; - w->session->side = NC_CLIENT; - do { - type = nc_send_rpc(w->session, w->rpc, 1000, &msgid); + type = nc_send_rpc(w->client, w->rpc, NC_MSG_TIMEOUT_MS, &msgid); } while (type == NC_MSG_WOULDBLOCK); assert_int_equal(type, NC_MSG_RPC); - assert_int_equal(write(w->session->ti.fd.out, "\n", 1), 1); -} - -static void -test_write_rpc_10(void **state) -{ - struct wr *w = (struct wr *)*state; - - w->session->version = NC_PROT_VERSION_10; - - return test_write_rpc(state); -} - -static void -test_write_rpc_11(void **state) -{ - struct wr *w = (struct wr *)*state; - - w->session->version = NC_PROT_VERSION_11; - - return test_write_rpc(state); + assert_int_equal(write(w->fds[1], "\n", 1), 1); } static void test_write_rpc_bad(void **state) { - struct wr *w = (struct wr *)*state; + struct wr *w = *state; uint64_t msgid; NC_MSG_TYPE type; - w->session->side = NC_SERVER; - pthread_mutex_init(&w->session->opts.server.rpc_lock, NULL); - pthread_cond_init(&w->session->opts.server.rpc_cond, NULL); - w->session->opts.server.rpc_inuse = 0; - + /* only a client can send an RPC */ do { - type = nc_send_rpc(w->session, w->rpc, 1000, &msgid); + type = nc_send_rpc(w->server, w->rpc, NC_MSG_TIMEOUT_MS, &msgid); } while (type == NC_MSG_WOULDBLOCK); assert_int_equal(type, NC_MSG_ERROR); } -static void -test_write_rpc_10_bad(void **state) -{ - struct wr *w = (struct wr *)*state; - - w->session->version = NC_PROT_VERSION_10; - - return test_write_rpc_bad(state); -} - -static void -test_write_rpc_11_bad(void **state) -{ - struct wr *w = (struct wr *)*state; - - w->session->version = NC_PROT_VERSION_11; - - return test_write_rpc_bad(state); -} - int main(void) { const struct CMUnitTest io[] = { - cmocka_unit_test_setup_teardown(test_write_rpc_10, setup_write, teardown_write), - cmocka_unit_test_setup_teardown(test_write_rpc_10_bad, setup_write, teardown_write), - cmocka_unit_test_setup_teardown(test_write_rpc_11, setup_write, teardown_write), - cmocka_unit_test_setup_teardown(test_write_rpc_11_bad, setup_write, teardown_write) + {"test_write_rpc_10", test_write_rpc, setup_write_10, teardown_write, NULL}, + {"test_write_rpc_10_bad", test_write_rpc_bad, setup_write_10, teardown_write, NULL}, + {"test_write_rpc_11", test_write_rpc, setup_write_11, teardown_write, NULL}, + {"test_write_rpc_11_bad", test_write_rpc_bad, setup_write_11, teardown_write, NULL}, }; return cmocka_run_group_tests(io, NULL, NULL); diff --git a/tests/test_pam.c b/tests/test_pam.c index 2d4ac206..fbc1cff6 100644 --- a/tests/test_pam.c +++ b/tests/test_pam.c @@ -32,10 +32,9 @@ int TEST_PORT = 10050; const char *TEST_PORT_STR = "10050"; -/* mock pam_start to just call pam_start_confdir instead */ -int __real_pam_start(const char *service_name, const char *user, const struct pam_conv *pam_conversation, pam_handle_t **pamh); -int -__wrap_pam_start(const char *service_name, const char *user, const struct pam_conv *pam_conversation, pam_handle_t **pamh) +/* mock pam_start to just call pam_start_confdir instead, exported to replace the one called by libnetconf2 */ +__attribute__((visibility("default"))) int +pam_start(const char *service_name, const char *user, const struct pam_conv *pam_conversation, pam_handle_t **pamh) { return pam_start_confdir(service_name, user, pam_conversation, BUILD_DIR "/tests", pamh); } diff --git a/tests/test_ps_poll.c b/tests/test_ps_poll.c index b4afcbb9..8576a41d 100644 --- a/tests/test_ps_poll.c +++ b/tests/test_ps_poll.c @@ -22,25 +22,30 @@ #include #include #include -#include +#include #include #include #include -#include - +#include "compat.h" #include "ln2_test.h" /* long enough that a poll thread holding its turn for the whole timeout is unmistakable */ -#define TEST_POLL_TIMEOUT 1000 +#define TEST_POLL_TIMEOUT_MS 1000 -/* more threads than the queue was sized for, it has to grow */ -#define TEST_POLLER_COUNT (NC_PS_QUEUE_INIT_SIZE + 4) +/* more threads than the initial size of the pollsession queue (NC_PS_QUEUE_INIT_SIZE, 6), it has to grow */ +#define TEST_POLLER_COUNT 10 /* a high priority operation must get the turn within one session scan of the polling thread, * not within one or more poll timeouts */ -#define TEST_ADD_LIMIT 250 +#define TEST_ADD_LIMIT_MS 250 + +/* idle timeout of the sessions in seconds */ +#define TEST_IDLE_TIMEOUT_S 2 + +/* poll timeout longer than the idle timeout */ +#define TEST_IDLE_POLL_TIMEOUT_MS (TEST_IDLE_TIMEOUT_S * 1000 + 500) struct test_state { struct nc_pollsession *ps; @@ -49,131 +54,93 @@ struct test_state { ATOMIC_T stop; }; -/* socketpair peer ends of the created sessions, kept open so that the sessions are not - * reported as hung up, closed together with their session */ +/* context shared by all the tests */ +static struct ln2_test_ctx *test_ctx; + +/* socketpair ends of the created sessions, the peer ends are kept open so that the sessions are + * not reported as hung up, closed together with their session */ static struct { struct nc_session *sess; - int fd; -} test_peers[8]; + int fds[2]; +} test_socks[8]; /** - * @brief Remember the socketpair peer end of a session. + * @brief Create a server session on a socketpair. * - * @param[in] sess Session the peer end belongs to. - * @param[in] fd Peer end of the session socketpair. - * @return 0 on success, -1 on error. + * @return Created session, NULL on error. */ -static int -test_peer_store(struct nc_session *sess, int fd) +static struct nc_session * +test_new_session(void) { uint32_t i; - for (i = 0; i < sizeof test_peers / sizeof *test_peers; ++i) { - if (!test_peers[i].sess) { - test_peers[i].sess = sess; - test_peers[i].fd = fd; - return 0; + for (i = 0; i < sizeof test_socks / sizeof *test_socks; ++i) { + if (!test_socks[i].sess) { + break; } } + if (i == sizeof test_socks / sizeof *test_socks) { + return NULL; + } - return -1; + ln2_glob_test_fd_sessions(test_ctx->ctx, 1, &test_socks[i].sess, NULL, test_socks[i].fds); + return test_socks[i].sess; } /** - * @brief Close the socketpair peer end of a session. + * @brief Free a session created by ::test_new_session() and close its socketpair. * - * @param[in] sess Session being freed. + * @param[in] sess Session to free. */ static void -test_peer_close(struct nc_session *sess) +test_free_session(struct nc_session *sess) { uint32_t i; - for (i = 0; i < sizeof test_peers / sizeof *test_peers; ++i) { - if (test_peers[i].sess == sess) { - close(test_peers[i].fd); - test_peers[i].sess = NULL; - test_peers[i].fd = -1; + for (i = 0; i < sizeof test_socks / sizeof *test_socks; ++i) { + if (test_socks[i].sess == sess) { + nc_session_free(sess, NULL); + close(test_socks[i].fds[0]); + close(test_socks[i].fds[1]); + test_socks[i].sess = NULL; return; } } - fail_msg("Session %" PRIu32 " has no stored socketpair peer end.", sess->id); + fail_msg("Session %" PRIu32 " was not created by the test.", nc_session_get_id(sess)); } /** - * @brief Create a bare server session on a socketpair, without any transport handshake. + * @brief Set the server idle timeout. * - * @param[in] id Session ID to use. - * @return Created session, NULL on error. + * @param[in] idle_timeout Idle timeout in seconds, 0 for none. */ -static struct nc_session * -test_new_session(uint32_t id) +static void +test_set_idle_timeout(uint16_t idle_timeout) { - struct nc_session *sess; - struct timespec ts; - int sock[2]; - - if (socketpair(AF_UNIX, SOCK_STREAM, 0, sock)) { - return NULL; - } - - sess = calloc(1, sizeof *sess); - if (!sess) { - close(sock[0]); - close(sock[1]); - return NULL; - } - - sess->side = NC_SERVER; - pthread_mutex_init(&sess->opts.server.ntf_status_lock, NULL); - pthread_mutex_init(&sess->opts.server.rpc_lock, NULL); - pthread_cond_init(&sess->opts.server.rpc_cond, NULL); - nc_timeouttime_get(&ts, 0); - sess->opts.server.last_rpc = ts.tv_sec; - - sess->io_lock = malloc(sizeof *sess->io_lock); - if (!sess->io_lock) { - free(sess); - close(sock[0]); - close(sock[1]); - return NULL; - } - pthread_mutex_init(sess->io_lock, NULL); - - NC_SESSION_STATUS_SET(sess, NC_STATUS_RUNNING); - sess->id = id; - sess->ti_type = NC_TI_FD; - sess->ti.fd.in = sock[0]; - sess->ti.fd.out = sock[0]; - - /* remember the socketpair peer end so that it can be closed with the session */ - if (test_peer_store(sess, sock[1])) { - pthread_mutex_destroy(&sess->opts.server.ntf_status_lock); - pthread_mutex_destroy(&sess->opts.server.rpc_lock); - pthread_cond_destroy(&sess->opts.server.rpc_cond); - pthread_mutex_destroy(sess->io_lock); - free(sess->io_lock); - free(sess); - close(sock[0]); - close(sock[1]); - return NULL; - } - - return sess; + struct lyd_node *tree = NULL; + char buf[8]; + + sprintf(buf, "%" PRIu16, idle_timeout); + assert_int_equal(lyd_new_path(NULL, test_ctx->ctx, "/ietf-netconf-server:netconf-server/listen/idle-timeout", buf, + 0, &tree), LY_SUCCESS); + assert_int_equal(nc_server_config_setup_data(tree), 0); + lyd_free_all(tree); } -static void -test_free_session(struct nc_session *sess) +/** + * @brief Get the milliseconds elapsed since a time. + * + * @param[in] ts_start Monotonic time to measure from. + * @return Elapsed milliseconds. + */ +static int32_t +test_elapsed(const struct timespec *ts_start) { - close(sess->ti.fd.in); - test_peer_close(sess); - pthread_mutex_destroy(&sess->opts.server.ntf_status_lock); - pthread_mutex_destroy(&sess->opts.server.rpc_lock); - pthread_cond_destroy(&sess->opts.server.rpc_cond); - pthread_mutex_destroy(sess->io_lock); - free(sess->io_lock); - free(sess); + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return (ts.tv_sec - ts_start->tv_sec) * 1000 + (ts.tv_nsec - ts_start->tv_nsec) / 1000000; } /** @@ -188,7 +155,7 @@ test_poller_thread(void *arg) struct test_state *st = arg; while (!ATOMIC_LOAD_RELAXED(st->stop)) { - nc_ps_poll(st->ps, TEST_POLL_TIMEOUT, NULL); + nc_ps_poll(st->ps, TEST_POLL_TIMEOUT_MS, NULL); } return NULL; @@ -215,7 +182,7 @@ setup_f(void **state) } /* an already established, idle session, otherwise the pollers would just return no-sessions */ - sess = test_new_session(1); + sess = test_new_session(); if (!sess) { SETUP_FAIL_LOG; return 1; @@ -270,9 +237,9 @@ teardown_f(void **state) * @brief Adding a session must not wait for the poll threads to time out. * * Session addition used to queue up behind all the poll threads in the same FIFO queue, so a - * newly established session waited poller_count * TEST_POLL_TIMEOUT before it was polled for + * newly established session waited poller_count * TEST_POLL_TIMEOUT_MS before it was polled for * the first time. It now queues up in front of them and the polling thread hands the turn over. - * Also verifies that the queue grows past NC_PS_QUEUE_INIT_SIZE instead of dropping the session. + * Also verifies that the queue grows past its initial size instead of dropping the session. */ static void test_add_session_not_blocked(void **state) @@ -282,15 +249,15 @@ test_add_session_not_blocked(void **state) struct timespec ts_start; int32_t elapsed; - sess = test_new_session(2); + sess = test_new_session(); assert_non_null(sess); - nc_timeouttime_get(&ts_start, 0); + clock_gettime(CLOCK_MONOTONIC, &ts_start); assert_int_equal(nc_ps_add_session(st->ps, sess), 0); - elapsed = -nc_timeouttime_cur_diff(&ts_start); + elapsed = test_elapsed(&ts_start); assert_int_equal(nc_ps_session_count(st->ps), 2); - assert_true(elapsed < TEST_ADD_LIMIT); + assert_true(elapsed < TEST_ADD_LIMIT_MS); } /** @@ -307,13 +274,13 @@ test_del_session_not_blocked(void **state) sess = nc_ps_get_session(st->ps, 0); assert_non_null(sess); - nc_timeouttime_get(&ts_start, 0); + clock_gettime(CLOCK_MONOTONIC, &ts_start); assert_int_equal(nc_ps_del_session(st->ps, sess), 0); - elapsed = -nc_timeouttime_cur_diff(&ts_start); + elapsed = test_elapsed(&ts_start); assert_int_equal(nc_ps_session_count(st->ps), 0); test_free_session(sess); - assert_true(elapsed < TEST_ADD_LIMIT); + assert_true(elapsed < TEST_ADD_LIMIT_MS); } /** @@ -328,7 +295,7 @@ test_idle_timeout(void **state) { struct nc_pollsession *ps; struct nc_session *sess, *term_sess; - struct timespec ts, ts_start; + struct timespec ts_start; int ret; int32_t elapsed; @@ -336,23 +303,23 @@ test_idle_timeout(void **state) ps = nc_ps_new(); assert_non_null(ps); + test_set_idle_timeout(TEST_IDLE_TIMEOUT_S); - sess = test_new_session(1); + /* the session was active just now, so it must survive for the idle timeout, even though the + * poll deadline is further away than that */ + sess = test_new_session(); assert_non_null(sess); assert_int_equal(nc_ps_add_session(ps, sess), 0); - /* the session was active just now, so with an idle timeout of 2s it must survive for 2s, - * even though the poll deadline is further away than that */ - ATOMIC_STORE_RELAXED(server_opts.idle_timeout, 2); - - nc_timeouttime_get(&ts_start, 0); - ret = nc_ps_poll(ps, 2500, &term_sess); - elapsed = -nc_timeouttime_cur_diff(&ts_start); + clock_gettime(CLOCK_MONOTONIC, &ts_start); + ret = nc_ps_poll(ps, TEST_IDLE_POLL_TIMEOUT_MS, &term_sess); + elapsed = test_elapsed(&ts_start); assert_int_equal(ret, NC_PSPOLL_SESSION_TERM | NC_PSPOLL_SESSION_ERROR); - assert_int_equal(NC_SESSION_STATUS_GET(sess), NC_STATUS_INVALID); - assert_int_equal(NC_SESSION_TERM_REASON_GET(sess), NC_SESSION_TERM_TIMEOUT); - assert_true(elapsed >= 1000); + assert_int_equal(nc_session_get_status(sess), NC_STATUS_INVALID); + assert_int_equal(nc_session_get_term_reason(sess), NC_SESSION_TERM_TIMEOUT); + /* the idle time is counted in whole seconds */ + assert_true(elapsed >= (TEST_IDLE_TIMEOUT_S - 1) * 1000); /* the session was handed over to us, it is no longer in ps */ assert_ptr_equal(term_sess, sess); @@ -361,22 +328,21 @@ test_idle_timeout(void **state) test_free_session(sess); /* a session that really has been idle for too long is terminated right away */ - sess = test_new_session(2); + sess = test_new_session(); assert_non_null(sess); - nc_timeouttime_get(&ts, 0); - sess->opts.server.last_rpc = ts.tv_sec - 3; + sleep(TEST_IDLE_TIMEOUT_S); assert_int_equal(nc_ps_add_session(ps, sess), 0); - nc_timeouttime_get(&ts_start, 0); - ret = nc_ps_poll(ps, 2500, &term_sess); - elapsed = -nc_timeouttime_cur_diff(&ts_start); + clock_gettime(CLOCK_MONOTONIC, &ts_start); + ret = nc_ps_poll(ps, TEST_IDLE_POLL_TIMEOUT_MS, &term_sess); + elapsed = test_elapsed(&ts_start); assert_int_equal(ret, NC_PSPOLL_SESSION_TERM | NC_PSPOLL_SESSION_ERROR); - assert_int_equal(NC_SESSION_STATUS_GET(sess), NC_STATUS_INVALID); - assert_int_equal(NC_SESSION_TERM_REASON_GET(sess), NC_SESSION_TERM_TIMEOUT); + assert_int_equal(nc_session_get_status(sess), NC_STATUS_INVALID); + assert_int_equal(nc_session_get_term_reason(sess), NC_SESSION_TERM_TIMEOUT); assert_true(elapsed < 500); - ATOMIC_STORE_RELAXED(server_opts.idle_timeout, 0); + test_set_idle_timeout(0); assert_ptr_equal(term_sess, sess); assert_int_equal(nc_ps_session_count(ps), 0); @@ -396,7 +362,6 @@ test_term_last_session(void **state) { struct nc_pollsession *ps; struct nc_session *sess[3], *term_sess; - struct timespec ts; uint16_t i; int ret; @@ -404,19 +369,19 @@ test_term_last_session(void **state) ps = nc_ps_new(); assert_non_null(ps); + test_set_idle_timeout(TEST_IDLE_TIMEOUT_S); - for (i = 0; i < 3; ++i) { - sess[i] = test_new_session(i + 1); + /* the last session in the array has been idle for too long, the other two are fine */ + sess[2] = test_new_session(); + assert_non_null(sess[2]); + sleep(TEST_IDLE_TIMEOUT_S); + for (i = 0; i < 2; ++i) { + sess[i] = test_new_session(); assert_non_null(sess[i]); } - - /* the last session in the array has been idle for too long, the other two are fine */ - nc_timeouttime_get(&ts, 0); - sess[2]->opts.server.last_rpc = ts.tv_sec - 3; for (i = 0; i < 3; ++i) { assert_int_equal(nc_ps_add_session(ps, sess[i]), 0); } - ATOMIC_STORE_RELAXED(server_opts.idle_timeout, 2); /* the last session is terminated, removed and handed over */ ret = nc_ps_poll(ps, 0, &term_sess); @@ -430,7 +395,7 @@ test_term_last_session(void **state) assert_int_equal(ret, NC_PSPOLL_TIMEOUT); assert_int_equal(nc_ps_session_count(ps), 2); - ATOMIC_STORE_RELAXED(server_opts.idle_timeout, 0); + test_set_idle_timeout(0); for (i = 0; i < 2; ++i) { assert_int_equal(nc_ps_del_session(ps, sess[i]), 0); @@ -439,6 +404,22 @@ test_term_last_session(void **state) nc_ps_free(ps); } +static int +setup_glob(void **state) +{ + (void)state; + + return ln2_glob_test_setup(&test_ctx); +} + +static int +teardown_glob(void **state) +{ + (void)state; + + return ln2_glob_test_teardown((void **)&test_ctx); +} + int main(void) { @@ -449,5 +430,5 @@ main(void) cmocka_unit_test(test_term_last_session), }; - return cmocka_run_group_tests(tests, NULL, NULL); + return cmocka_run_group_tests(tests, setup_glob, teardown_glob); } diff --git a/tests/test_runtime_changes.c b/tests/test_runtime_changes.c index 7a5cd531..46cefd2e 100644 --- a/tests/test_runtime_changes.c +++ b/tests/test_runtime_changes.c @@ -66,7 +66,7 @@ server_thread(void *arg) while (1) { /* config ready, wait for client/server to be ready */ pthread_barrier_wait(&state->start_barrier); - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, ctx, &session); if (expect_ok) { assert_int_equal(msgtype, NC_MSG_HELLO); @@ -74,7 +74,7 @@ server_thread(void *arg) assert_int_equal(ret, 0); do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); assert_int_equal(ret & NC_PSPOLL_RPC, NC_PSPOLL_RPC); } while (!(ret & NC_PSPOLL_SESSION_TERM)); diff --git a/tests/test_server_thread.c b/tests/test_server_thread.c index 2f2b25bf..b843ac94 100644 --- a/tests/test_server_thread.c +++ b/tests/test_server_thread.c @@ -235,7 +235,7 @@ test_parallel_accept_nonblocking(void **state) static void test_parallel_accept_timed(void **state) { - run_parallel_accept(state, NC_ACCEPT_TIMEOUT); + run_parallel_accept(state, NC_ACCEPT_TIMEOUT_MS); } static void diff --git a/tests/test_ssh.c b/tests/test_ssh.c index 278bed7e..f6db8cdb 100644 --- a/tests/test_ssh.c +++ b/tests/test_ssh.c @@ -15,6 +15,7 @@ #define _GNU_SOURCE +#include #include #include #include @@ -45,18 +46,20 @@ const char *TEST_PORT_STR = "10050"; static char banner_buffer[512]; static const char *expected_banner_text = "This is a test SSH banner message"; -char *__real_ssh_get_issue_banner(ssh_session session); - /** * @brief Wrapper for ssh_get_issue_banner to store the banner for later checks. + * + * Exported to replace the one called by libnetconf2. */ -char * -__wrap_ssh_get_issue_banner(ssh_session session) +__attribute__((visibility("default"))) char * +ssh_get_issue_banner(ssh_session session) { + char *(*real_get_issue_banner)(ssh_session session); char *banner; /* get the real banner */ - banner = __real_ssh_get_issue_banner(session); + real_get_issue_banner = (char *(*)(ssh_session))dlsym(RTLD_NEXT, "ssh_get_issue_banner"); + banner = real_get_issue_banner(session); if (banner) { /* store the banner for later checks */ strncpy(banner_buffer, banner, sizeof(banner_buffer) - 1); diff --git a/tests/test_system_users.c b/tests/test_system_users.c index 6a3104ac..03268764 100644 --- a/tests/test_system_users.c +++ b/tests/test_system_users.c @@ -15,6 +15,7 @@ #define _GNU_SOURCE +#include #include #include #include @@ -48,13 +49,16 @@ int TEST_PORT = 10050; const char *TEST_PORT_STR = "10050"; /* mock getpwnam_r to make SYS_USER a system user with its password hash stored directly in its passwd entry, - * linked shared libraries reference getpwnam_r too, so the wrapper must not be hidden for the linker to accept it */ -int __real_getpwnam_r(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result); + * exported to replace the one called by libnetconf2 */ __attribute__((visibility("default"))) int -__wrap_getpwnam_r(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) +getpwnam_r(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) { + int (*real_getpwnam_r)(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result); + if (strcmp(name, SYS_USER)) { - return __real_getpwnam_r(name, pwd, buf, buflen, result); + real_getpwnam_r = (int (*)(const char *, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, + "getpwnam_r"); + return real_getpwnam_r(name, pwd, buf, buflen, result); } memset(pwd, 0, sizeof *pwd); diff --git a/tests/test_tls.c b/tests/test_tls.c index 2f9fea4a..4a4ec6f9 100644 --- a/tests/test_tls.c +++ b/tests/test_tls.c @@ -997,7 +997,7 @@ server_thread_ctn_san(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* accept a session and add it to the poll session structure */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); assert_int_equal(msgtype, NC_MSG_HELLO); /* the username should be resolved from the client cert's SAN rfc822Name field */ @@ -1009,7 +1009,7 @@ server_thread_ctn_san(void *arg) /* poll until the session is terminated by the client */ do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); assert_int_equal(ret & NC_PSPOLL_RPC, NC_PSPOLL_RPC); } while (!(ret & NC_PSPOLL_SESSION_TERM)); @@ -1129,7 +1129,7 @@ server_thread_ctn(void *arg) /* wait for the client to be ready to connect */ pthread_barrier_wait(&test_ctx->barrier); - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); if (!test_data->username) { /* no username can be resolved, the client must not be authenticated */ assert_int_equal(msgtype, NC_MSG_ERROR); @@ -1146,7 +1146,7 @@ server_thread_ctn(void *arg) /* poll until the session is terminated by the client */ do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); assert_int_equal(ret & NC_PSPOLL_RPC, NC_PSPOLL_RPC); } while (!(ret & NC_PSPOLL_SESSION_TERM)); diff --git a/tests/test_two_channels.c b/tests/test_two_channels.c index 4b8c15a4..c437ea9c 100644 --- a/tests/test_two_channels.c +++ b/tests/test_two_channels.c @@ -64,7 +64,7 @@ server_thread(void *arg) ret = nc_ps_add_session(ps, new_session); assert_int_equal(ret, 0); } - } else if (ret & NC_PS_POLL_TIMEOUT) { + } else if (ret & NC_PSPOLL_TIMEOUT) { usleep(BACKOFF_TIMEOUT_USECS); sleep_count++; assert_int_not_equal(sleep_count, 50000); diff --git a/tests/test_unix_socket.c b/tests/test_unix_socket.c index eb6cc485..fb4fc0c3 100644 --- a/tests/test_unix_socket.c +++ b/tests/test_unix_socket.c @@ -302,11 +302,11 @@ auth_server_thread(void *arg) pthread_barrier_wait(&test_ctx->barrier); /* session of the process user is not accepted */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); assert_int_equal(msgtype, NC_MSG_ERROR); /* session with the correct username is accepted */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); assert_int_equal(msgtype, NC_MSG_HELLO); /* session closed */ @@ -315,7 +315,7 @@ auth_server_thread(void *arg) ret = nc_ps_add_session(ps, session); assert_int_equal(ret, 0); do { - ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, &session); + ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT_MS, &session); assert_true(ret & NC_PSPOLL_RPC); } while (!(ret & NC_PSPOLL_SESSION_TERM)); @@ -402,7 +402,7 @@ test_unix_server_thread_fail(void *arg) /* try to accept a session, but expect it to time out, as the client should fail to connect, but * not cause an error on the server side */ - msgtype = nc_accept(NC_ACCEPT_TIMEOUT, test_ctx->ctx, &session); + msgtype = nc_accept(NC_ACCEPT_TIMEOUT_MS, test_ctx->ctx, &session); assert_int_equal(msgtype, NC_MSG_WOULDBLOCK); assert_null(session);