Get OnNetwork commissioning working (#34978)

* Update Zephyr platform to get working commissioning for onnetwork purposes

* Restyled by whitespace

* Remove unwanted and unnecessary comments

Signed-off-by: Caldeira, Quentin <QuentinCaldeira@eaton.com>

* Bring Openthread default config back

* Bring back udp and tcp configurations

---------

Signed-off-by: Caldeira, Quentin <QuentinCaldeira@eaton.com>
Co-authored-by: Restyled.io <commits@restyled.io>
diff --git a/config/zephyr/chip-module/CMakeLists.txt b/config/zephyr/chip-module/CMakeLists.txt
index 575e4ff..8449398 100644
--- a/config/zephyr/chip-module/CMakeLists.txt
+++ b/config/zephyr/chip-module/CMakeLists.txt
@@ -1,140 +1,142 @@
 #
-#   Copyright (c) 2022-2023 Project CHIP Authors
+# Copyright (c) 2022-2023 Project CHIP Authors
 #
-#   Licensed under the Apache License, Version 2.0 (the "License");
-#   you may not use this file except in compliance with the License.
-#   You may obtain a copy of the License at
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
 #
-#       http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
 #
-#   Unless required by applicable law or agreed to in writing, software
-#   distributed under the License is distributed on an "AS IS" BASIS,
-#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#   See the License for the specific language governing permissions and
-#   limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
 #
 
 #
-#   @file
-#     CMake sub-project defining 'chip' target which represents CHIP library
-#     Since CHIP doesn't provide native CMake support, ExternalProject
-#     module is used to build the required artifacts with GN meta-build
-#     system. It is assumed that find_package(Zephyr) has been called before
-#     including this file.
+# @file
+# CMake sub-project defining 'chip' target which represents CHIP library
+# Since CHIP doesn't provide native CMake support, ExternalProject
+# module is used to build the required artifacts with GN meta-build
+# system. It is assumed that find_package(Zephyr) has been called before
+# including this file.
 #
 
-if (CONFIG_CHIP)
+if(CONFIG_CHIP)
+    include(ExternalProject)
+    include(../zephyr-util.cmake)
 
-include(ExternalProject)
-include(../zephyr-util.cmake)
+    #
+    # ==============================================================================
+    # Prepare CHIP configuration based on the project Kconfig configuration
+    # ==============================================================================
+    # Set paths
+    if(NOT CHIP_ROOT)
+        get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../.. REALPATH)
+    endif()
 
-#
-# ==============================================================================
-# Prepare CHIP configuration based on the project Kconfig configuration
-# ==============================================================================
-# Set paths
-if (NOT CHIP_ROOT)
-    get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../.. REALPATH)
-endif()
-get_filename_component(GN_ROOT_TARGET ${CHIP_ROOT}/config/zephyr/chip-gn REALPATH)
-get_filename_component(COMMON_CMAKE_SOURCE_DIR ${CHIP_ROOT}/config/common/cmake REALPATH)
+    get_filename_component(GN_ROOT_TARGET ${CHIP_ROOT}/config/zephyr/chip-gn REALPATH)
+    get_filename_component(COMMON_CMAKE_SOURCE_DIR ${CHIP_ROOT}/config/common/cmake REALPATH)
 
+    # Get common Cmake sources
+    include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn_args.cmake)
+    include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn.cmake)
 
-# Get common Cmake sources
-include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn_args.cmake)
-include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn.cmake)
+    if(CONFIG_POSIX_API)
+        matter_add_flags(-D_DEFAULT_SOURCE)
+        matter_add_flags(-isystem${ZEPHYR_BASE}/include/zephyr/posix)
+    endif()
 
-if (CONFIG_POSIX_API)
-    matter_add_flags(-D_DEFAULT_SOURCE)
-    matter_add_flags(-isystem${ZEPHYR_BASE}/include/zephyr/posix)
-endif()
+    if(CONFIG_MBEDTLS)
+        zephyr_include_directories($<TARGET_PROPERTY:mbedTLS,INTERFACE_INCLUDE_DIRECTORIES>)
+        zephyr_compile_definitions($<TARGET_PROPERTY:mbedTLS,INTERFACE_COMPILE_DEFINITIONS>)
+    endif()
 
-if(CONFIG_MBEDTLS)
-    zephyr_include_directories($<TARGET_PROPERTY:mbedTLS,INTERFACE_INCLUDE_DIRECTORIES>)
-    zephyr_compile_definitions($<TARGET_PROPERTY:mbedTLS,INTERFACE_COMPILE_DEFINITIONS>)
-endif()
+    zephyr_get_compile_flags(ZEPHYR_CFLAGS_C C)
+    matter_add_cflags("${ZEPHYR_CFLAGS_C}")
+    zephyr_get_compile_flags(ZEPHYR_CFLAGS_CC CXX)
+    matter_add_cxxflags("${ZEPHYR_CFLAGS_CC}")
+    zephyr_get_gnu_cpp_standard(ZEPHYR_GNU_CPP_STD)
+    matter_add_cxxflags("${ZEPHYR_GNU_CPP_STD}")
 
-zephyr_get_compile_flags(ZEPHYR_CFLAGS_C C)
-matter_add_cflags("${ZEPHYR_CFLAGS_C}")
-zephyr_get_compile_flags(ZEPHYR_CFLAGS_CC CXX)
-matter_add_cxxflags("${ZEPHYR_CFLAGS_CC}")
-zephyr_get_gnu_cpp_standard(ZEPHYR_GNU_CPP_STD)
-matter_add_cxxflags("${ZEPHYR_GNU_CPP_STD}")
+    # Set up custom OpenThread configuration
+    if(CONFIG_CHIP_OPENTHREAD_CONFIG)
+        get_filename_component(CHIP_OPENTHREAD_CONFIG
+            ${CONFIG_CHIP_OPENTHREAD_CONFIG}
+            REALPATH
+            BASE_DIR ${CMAKE_SOURCE_DIR}
+        )
+        zephyr_set_openthread_config(${CHIP_OPENTHREAD_CONFIG})
+    endif()
 
-# Set up custom OpenThread configuration
-
-if (CONFIG_CHIP_OPENTHREAD_CONFIG)
-    get_filename_component(CHIP_OPENTHREAD_CONFIG
-        ${CONFIG_CHIP_OPENTHREAD_CONFIG}
-        REALPATH
-        BASE_DIR ${CMAKE_SOURCE_DIR}
+    # ==============================================================================
+    # Generate configuration for CHIP GN build system
+    # ==============================================================================
+    matter_common_gn_args(
+        DEBUG CONFIG_DEBUG
+        LIB_SHELL CONFIG_CHIP_LIB_SHELL
+        LIB_TESTS CONFIG_CHIP_BUILD_TESTS
+        PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG}
     )
-    zephyr_set_openthread_config(${CHIP_OPENTHREAD_CONFIG})
-endif()
 
-# ==============================================================================
-# Generate configuration for CHIP GN build system
-# ==============================================================================
-matter_common_gn_args(
-    DEBUG           CONFIG_DEBUG
-    LIB_SHELL       CONFIG_CHIP_LIB_SHELL
-    LIB_TESTS       CONFIG_CHIP_BUILD_TESTS
-    PROJECT_CONFIG  ${CONFIG_CHIP_PROJECT_CONFIG}
-)
+    matter_add_gn_arg_string("zephyr_ar" ${CMAKE_AR})
+    matter_add_gn_arg_string("zephyr_cc" ${CMAKE_C_COMPILER})
+    matter_add_gn_arg_string("zephyr_cxx" ${CMAKE_CXX_COMPILER})
+    matter_add_gn_arg_bool("chip_logging" CONFIG_LOG)
+    matter_add_gn_arg_bool("chip_error_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 1)
+    matter_add_gn_arg_bool("chip_progress_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 3)
+    matter_add_gn_arg_bool("chip_detail_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 4)
+    matter_add_gn_arg_bool("chip_automation_logging" FALSE)
+    matter_add_gn_arg_bool("chip_enable_openthread" CONFIG_NET_L2_OPENTHREAD)
+    matter_add_gn_arg_bool("chip_openthread_ftd" CONFIG_OPENTHREAD_FTD)
+    matter_add_gn_arg_bool("chip_inet_config_enable_ipv4" CONFIG_CHIP_IPV4)
+    matter_add_gn_arg_bool("chip_enable_wifi" CONFIG_WIFI)
+    matter_add_gn_arg_bool("chip_config_network_layer_ble" CONFIG_BT)
+    matter_add_gn_arg_bool("chip_mdns_minimal" CONFIG_WIFI)
+    matter_add_gn_arg_bool("chip_mdns_minimal" CONFIG_NET_L2_ETHERNET)
+    matter_add_gn_arg_bool("chip_mdns_platform" CONFIG_NET_L2_OPENTHREAD)
+    matter_add_gn_arg_bool("chip_inet_config_enable_tcp_endpoint" CONFIG_CHIP_BUILD_TESTS)
+    matter_add_gn_arg_bool("chip_malloc_sys_heap" CONFIG_CHIP_MALLOC_SYS_HEAP)
+    matter_add_gn_arg_bool("chip_inet_config_enable_tcp_endpoint" FALSE)
+    matter_add_gn_arg_bool("chip_enable_read_client" CONFIG_CHIP_ENABLE_READ_CLIENT)
 
-matter_add_gn_arg_string("zephyr_ar"                                ${CMAKE_AR})
-matter_add_gn_arg_string("zephyr_cc"                                ${CMAKE_C_COMPILER})
-matter_add_gn_arg_string("zephyr_cxx"                               ${CMAKE_CXX_COMPILER})
-matter_add_gn_arg_bool  ("chip_logging"                             CONFIG_LOG)
-matter_add_gn_arg_bool  ("chip_error_logging"                       CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 1)
-matter_add_gn_arg_bool  ("chip_progress_logging"                    CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 3)
-matter_add_gn_arg_bool  ("chip_detail_logging"                      CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 4)
-matter_add_gn_arg_bool  ("chip_automation_logging"                  FALSE)
-matter_add_gn_arg_bool  ("chip_enable_openthread"                   CONFIG_NET_L2_OPENTHREAD)
-matter_add_gn_arg_bool  ("chip_openthread_ftd"                      CONFIG_OPENTHREAD_FTD)
-matter_add_gn_arg_bool  ("chip_inet_config_enable_ipv4"             CONFIG_CHIP_IPV4)
-matter_add_gn_arg_bool  ("chip_enable_wifi"                         CONFIG_WIFI)
-matter_add_gn_arg_bool  ("chip_config_network_layer_ble"            CONFIG_BT)
-matter_add_gn_arg_bool  ("chip_mdns_minimal"                        CONFIG_WIFI)
-matter_add_gn_arg_bool  ("chip_mdns_minimal"                        CONFIG_NET_L2_ETHERNET)
-matter_add_gn_arg_bool  ("chip_mdns_platform"                       CONFIG_NET_L2_OPENTHREAD)
-matter_add_gn_arg_bool  ("chip_inet_config_enable_tcp_endpoint"     CONFIG_CHIP_BUILD_TESTS)
-matter_add_gn_arg_bool  ("chip_inet_config_enable_udp_endpoint"     CONFIG_NET_UDP)
-matter_add_gn_arg_bool  ("chip_inet_config_enable_tcp_endpoint"     CONFIG_NET_TCP)
-matter_add_gn_arg_bool  ("chip_malloc_sys_heap"                     CONFIG_CHIP_MALLOC_SYS_HEAP)
+    if(BOARD STREQUAL "native_posix")
+        matter_add_gn_arg_string("target_cpu" "x86")
+    elseif(BOARD STREQUAL "native_posix_64")
+        matter_add_gn_arg_string("target_cpu" "x64")
+    endif()
 
+    if(CONFIG_CHIP_ENABLE_DNSSD_SRP)
+        matter_add_gn_arg_string("chip_mdns" "platform")
+    endif()
 
-if (CONFIG_CHIP_ENABLE_DNSSD_SRP)
-    matter_add_gn_arg_string("chip_mdns" "platform")
-endif()
+    if(CONFIG_WIFI)
+        matter_add_gn_arg_string("chip_mdns" "minimal")
+    elseif(CONFIG_NET_L2_ETHERNET)
+        matter_add_gn_arg_string("chip_mdns" "minimal")
+    elseif(CONFIG_NET_L2_OPENTHREAD)
+        matter_add_gn_arg_string("chip_mdns" "platform")
+    else()
+        matter_add_gn_arg_string("chip_mdns" "none")
+    endif()
 
-if(CONFIG_WIFI)
-    matter_add_gn_arg_string("chip_mdns" "minimal")
-elseif (CONFIG_NET_L2_ETHERNET)
-    matter_add_gn_arg_string("chip_mdns" "minimal")
-elseif (CONFIG_NET_L2_OPENTHREAD)
-    matter_add_gn_arg_string("chip_mdns" "platform")
-else()
-    matter_add_gn_arg_string("chip_mdns" "none")
-endif()
+    if(CONFIG_CHIP_PW_RPC)
+        set(PIGWEED_DIR "//third_party/pigweed/repo")
+        matter_add_gn_arg_string("pw_assert_BACKEND" ${PIGWEED_DIR}/pw_assert_log:check_backend)
+        matter_add_gn_arg_string("pw_log_BACKEND" ${PIGWEED_DIR}/pw_log_basic)
+        matter_add_gn_arg("pw_build_LINK_DEPS" [\"${PIGWEED_DIR}/pw_assert:impl\",\ \"${PIGWEED_DIR}/pw_log:impl\"])
+    endif()
 
-if (CONFIG_CHIP_PW_RPC)
-    set(PIGWEED_DIR "//third_party/pigweed/repo")
-    matter_add_gn_arg_string("pw_assert_BACKEND" ${PIGWEED_DIR}/pw_assert_log:check_backend)
-    matter_add_gn_arg_string("pw_log_BACKEND" ${PIGWEED_DIR}/pw_log_basic)
-    matter_add_gn_arg("pw_build_LINK_DEPS" [\"${PIGWEED_DIR}/pw_assert:impl\",\ \"${PIGWEED_DIR}/pw_log:impl\"])
-endif()
+    matter_generate_args_tmp_file()
 
-matter_generate_args_tmp_file()
-
-# ==============================================================================
-# Build chip library
-# ==============================================================================
-matter_build(chip
-    LIB_SHELL   ${CONFIG_CHIP_LIB_SHELL}
-    LIB_TESTS   ${CONFIG_CHIP_BUILD_TESTS}
-    GN_DEPENDENCIES kernel
-)
-set_property(GLOBAL APPEND PROPERTY ZEPHYR_INTERFACE_LIBS chip)
-
+    # ==============================================================================
+    # Build chip library
+    # ==============================================================================
+    matter_build(chip
+        LIB_SHELL ${CONFIG_CHIP_LIB_SHELL}
+        LIB_TESTS ${CONFIG_CHIP_BUILD_TESTS}
+        GN_DEPENDENCIES kernel
+    )
+    set_property(GLOBAL APPEND PROPERTY ZEPHYR_INTERFACE_LIBS chip)
 endif() # CONFIG_CHIP
\ No newline at end of file
diff --git a/config/zephyr/chip-module/Kconfig.mbedtls b/config/zephyr/chip-module/Kconfig.mbedtls
index 3e4fdc1..72b1563 100644
--- a/config/zephyr/chip-module/Kconfig.mbedtls
+++ b/config/zephyr/chip-module/Kconfig.mbedtls
@@ -61,4 +61,11 @@
 config MBEDTLS_ECDSA_C
     default y
 
-endif #CHIP
\ No newline at end of file
+config MBEDTLS_X509_CSR_WRITE_C
+    default y
+
+config MBEDTLS_PK_WRITE_C
+    default y
+
+endif #CHIP
+
diff --git a/src/platform/Zephyr/BUILD.gn b/src/platform/Zephyr/BUILD.gn
index f1d9bdb..035c13a 100644
--- a/src/platform/Zephyr/BUILD.gn
+++ b/src/platform/Zephyr/BUILD.gn
@@ -40,6 +40,7 @@
     "DiagnosticDataProviderImpl.h",
     "DiagnosticDataProviderImplGetter.cpp",
     "InetPlatformConfig.h",
+    "InetUtils.cpp",
     "KeyValueStoreManagerImpl.cpp",
     "KeyValueStoreManagerImpl.h",
     "PlatformManagerImpl.cpp",
diff --git a/src/platform/Zephyr/ConnectivityManagerImpl.cpp b/src/platform/Zephyr/ConnectivityManagerImpl.cpp
index 17cdf46..d13a4ce 100644
--- a/src/platform/Zephyr/ConnectivityManagerImpl.cpp
+++ b/src/platform/Zephyr/ConnectivityManagerImpl.cpp
@@ -17,11 +17,16 @@
 
 #include <platform/internal/CHIPDeviceLayerInternal.h>
 
-#include <platform/ConnectivityManager.h>
-#include <platform/internal/BLEManager.h>
-
+#include <inet/UDPEndPointImplSockets.h>
 #include <lib/support/CodeUtils.h>
 #include <lib/support/logging/CHIPLogging.h>
+#include <platform/ConnectivityManager.h>
+#include <platform/Zephyr/InetUtils.h>
+#include <platform/internal/BLEManager.h>
+
+#ifndef CONFIG_ARCH_POSIX
+#include <zephyr/net/net_if.h>
+#endif
 
 #include <platform/internal/GenericConnectivityManagerImpl_UDP.ipp>
 
@@ -34,15 +39,62 @@
 #endif
 
 #if CHIP_DEVICE_CONFIG_ENABLE_THREAD
+#include <platform/OpenThread/OpenThreadUtils.h>
 #include <platform/internal/GenericConnectivityManagerImpl_Thread.ipp>
 #endif
 
-using namespace ::chip;
+using namespace ::chip::Inet;
 using namespace ::chip::DeviceLayer::Internal;
 
 namespace chip {
 namespace DeviceLayer {
 
+namespace {
+CHIP_ERROR JoinLeaveMulticastGroup(net_if * iface, const Inet::IPAddress & address,
+                                   UDPEndPointImplSockets::MulticastOperation operation)
+{
+#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
+    if (net_if_l2(iface) == &NET_L2_GET_NAME(OPENTHREAD))
+    {
+        const otIp6Address otAddress = ToOpenThreadIP6Address(address);
+        const auto handler = operation == UDPEndPointImplSockets::MulticastOperation::kJoin ? otIp6SubscribeMulticastAddress
+                                                                                            : otIp6UnsubscribeMulticastAddress;
+        otError error;
+
+        ThreadStackMgr().LockThreadStack();
+        error = handler(openthread_get_default_instance(), &otAddress);
+        ThreadStackMgr().UnlockThreadStack();
+
+        return MapOpenThreadError(error);
+    }
+#endif
+
+#if CHIP_DEVICE_CONFIG_ENABLE_WIFI || CHIP_DEVICE_CONFIG_ENABLE_ETHERNET
+    const in6_addr in6Addr = InetUtils::ToZephyrAddr(address);
+
+    if (operation == UDPEndPointImplSockets::MulticastOperation::kJoin)
+    {
+        net_if_mcast_addr * maddr = net_if_ipv6_maddr_add(iface, &in6Addr);
+
+        if (maddr && !net_if_ipv6_maddr_is_joined(maddr))
+        {
+            net_if_ipv6_maddr_join(iface, maddr);
+        }
+    }
+    else if (operation == UDPEndPointImplSockets::MulticastOperation::kLeave)
+    {
+        VerifyOrReturnError(net_if_ipv6_maddr_rm(iface, &in6Addr), CHIP_ERROR_INVALID_ADDRESS);
+    }
+    else
+    {
+        return CHIP_ERROR_INCORRECT_STATE;
+    }
+#endif
+
+    return CHIP_NO_ERROR;
+}
+} // namespace
+
 ConnectivityManagerImpl ConnectivityManagerImpl::sInstance;
 
 CHIP_ERROR ConnectivityManagerImpl::_Init()
@@ -50,6 +102,30 @@
 #if CHIP_DEVICE_CONFIG_ENABLE_THREAD
     GenericConnectivityManagerImpl_Thread<ConnectivityManagerImpl>::_Init();
 #endif
+#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
+    ReturnErrorOnFailure(InitWiFi());
+#endif
+
+#if CHIP_DEVICE_CONFIG_ENABLE_THREAD || CHIP_DEVICE_CONFIG_ENABLE_WIFI || CHIP_DEVICE_CONFIG_ENABLE_ETHERNET
+    UDPEndPointImplSockets::SetMulticastGroupHandler(
+        [](InterfaceId interfaceId, const IPAddress & address, UDPEndPointImplSockets::MulticastOperation operation) {
+            if (interfaceId.IsPresent())
+            {
+                net_if * iface = InetUtils::GetInterface(interfaceId);
+                VerifyOrReturnError(iface != nullptr, INET_ERROR_UNKNOWN_INTERFACE);
+
+                return JoinLeaveMulticastGroup(iface, address, operation);
+            }
+
+            // If the interface is not specified, join or leave the multicast group on all interfaces.
+            for (int i = 1; net_if * iface = net_if_get_by_index(i); i++)
+            {
+                ReturnErrorOnFailure(JoinLeaveMulticastGroup(iface, address, operation));
+            }
+
+            return CHIP_NO_ERROR;
+        });
+#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD || CHIP_DEVICE_CONFIG_ENABLE_WIFI
 
     return CHIP_NO_ERROR;
 }
diff --git a/src/platform/Zephyr/ConnectivityManagerImpl.h b/src/platform/Zephyr/ConnectivityManagerImpl.h
index 4c003f2..0a60770 100644
--- a/src/platform/Zephyr/ConnectivityManagerImpl.h
+++ b/src/platform/Zephyr/ConnectivityManagerImpl.h
@@ -100,7 +100,7 @@
  * Returns the platform-specific implementation of the ConnectivityManager singleton object.
  *
  * chip applications can use this to gain access to features of the ConnectivityManager
- * that are specific to the ESP32 platform.
+ * that are specific to the Zephyr platform.
  */
 inline ConnectivityManagerImpl & ConnectivityMgrImpl(void)
 {