From dd94977c3106b399c78d3306c76f0ccfde229787 Mon Sep 17 00:00:00 2001 From: dboling-ericsson <73494641+dboling-ericsson@users.noreply.github.com> Date: Thu, 26 Jan 2023 16:54:41 -0800 Subject: [PATCH 1/4] 9160 Socket Network Support Adds non-secure network support for nrf9160 --- CMake/binutils.Nordic.cmake | 2 +- CMakePresets.json | 24 +- targets/Nordic/ARDESCO/CMakeLists.txt | 1 - .../ARDESCO/nrf9160_ard0022B_ns.overlay | 2 +- targets/Nordic/ARDESCO/prj.conf | 38 +- targets/Nordic/CMakeLists.txt | 2 +- targets/Nordic/NRF52840_DK/CMakeLists.txt | 1 - targets/Nordic/NRF52840_DK/prj.conf | 6 +- targets/Nordic/NRF9160_DK/CMakeLists.txt | 4 +- .../NRF9160_DK/cert/GlobalSign-Root-CA-R2 | 90 ++ .../NRF9160_DK/nrf9160dk_nrf9160_ns.overlay | 4 +- targets/Nordic/NRF9160_DK/prj.conf | 25 +- targets/Nordic/_include/nrf9160_lte.h | 51 + targets/Nordic/_include/sockets_nrf9160.h | 276 ++++++ targets/Nordic/_include/ssl_sockets_nrf9160.h | 20 + targets/Nordic/_include/targetHAL.h | 4 +- targets/Nordic/_nanoCLR/targetHAL_Time.cpp | 114 ++- .../_nanoCLR_module/nf_lib/CMakeLists.txt | 58 +- .../_nanoCLR_module/nf_lib/nflib_main.c | 3 +- .../_netCellular/Nordic_Sockets_functions.cpp | 935 ++++++++++++++++++ targets/Nordic/_netCellular/nrf9160_lte.c | 501 ++++++++++ targets/Nordic/_netCellular/socket_api.cpp | 735 ++++++++++++++ .../Nordic/_netCellular/ssl_socket_api.cpp | 401 ++++++++ .../targetHAL_ConfigurationManager.cpp | 471 +++++++++ .../arm/nrf9160_ard0022B/board_nonsecure.c | 24 - 25 files changed, 3625 insertions(+), 167 deletions(-) create mode 100644 targets/Nordic/NRF9160_DK/cert/GlobalSign-Root-CA-R2 create mode 100644 targets/Nordic/_include/nrf9160_lte.h create mode 100644 targets/Nordic/_include/sockets_nrf9160.h create mode 100644 targets/Nordic/_include/ssl_sockets_nrf9160.h create mode 100644 targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp create mode 100644 targets/Nordic/_netCellular/nrf9160_lte.c create mode 100644 targets/Nordic/_netCellular/socket_api.cpp create mode 100644 targets/Nordic/_netCellular/ssl_socket_api.cpp create mode 100644 targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp diff --git a/CMake/binutils.Nordic.cmake b/CMake/binutils.Nordic.cmake index db5c9a5094..ce66359e71 100644 --- a/CMake/binutils.Nordic.cmake +++ b/CMake/binutils.Nordic.cmake @@ -153,7 +153,7 @@ macro(nf_setup_target_build) zephyr_compile_definitions(PROJECT_NAME=nanoCLR) - zephyr_compile_definitions(APP_VERSION=${BUILD_VERSION}) + #zephyr_compile_definitions(APP_VERSION=${BUILD_VERSION}) ####################################################### # the following are nanoCLR common compile definitions diff --git a/CMakePresets.json b/CMakePresets.json index 4b95478931..0c4f50e257 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -1476,15 +1476,16 @@ "SWO_OUTPUT": "OFF", "NF_BUILD_RTM": "OFF", "NF_FEATURE_DEBUGGER": "ON", - "NF_FEATURE_RTC": "OFF", - "NF_FEATURE_HAS_CONFIG_BLOCK": "OFF", + "NF_FEATURE_RTC": "ON", + "NF_FEATURE_HAS_CONFIG_BLOCK": "ON", "NF_FEATURE_HAS_SDCARD": "OFF", "NF_FEATURE_HAS_USB_MSD": "OFF", "NF_NETWORKING_SNTP": "OFF", + "NF_SECURITY_MBEDTLS": "ON", "API_nanoFramework.Device.Can": "OFF", "API_nanoFramework.Device.OneWire": "OFF", "API_System.Math": "ON", - "API_System.Net": "OFF", + "API_System.Net": "ON", "API_System.Device.Adc": "OFF", "API_Windows.Devices.Gpio": "ON", "API_System.Device.Gpio": "ON", @@ -1492,7 +1493,10 @@ "API_System.Device.Pwm": "OFF", "API_System.IO.Ports": "OFF", "API_System.Device.Spi": "OFF", - "API_Windows.Storage": "OFF" + "API_Windows.Storage": "OFF", + "API_nanoFramework.ResourceManager": "ON", + "API_nanoFramework.System.Collections": "ON", + "API_nanoFramework.System.Text": "ON" } }, { @@ -1510,15 +1514,16 @@ "SWO_OUTPUT": "OFF", "NF_BUILD_RTM": "OFF", "NF_FEATURE_DEBUGGER": "ON", - "NF_FEATURE_RTC": "OFF", - "NF_FEATURE_HAS_CONFIG_BLOCK": "OFF", + "NF_FEATURE_RTC": "ON", + "NF_FEATURE_HAS_CONFIG_BLOCK": "ON", "NF_FEATURE_HAS_SDCARD": "OFF", "NF_FEATURE_HAS_USB_MSD": "OFF", "NF_NETWORKING_SNTP": "OFF", + "NF_SECURITY_MBEDTLS": "ON", "API_nanoFramework.Device.Can": "OFF", "API_nanoFramework.Device.OneWire": "OFF", "API_System.Math": "ON", - "API_System.Net": "OFF", + "API_System.Net": "ON", "API_System.Device.Adc": "OFF", "API_Windows.Devices.Gpio": "ON", "API_System.Device.Gpio": "ON", @@ -1526,7 +1531,10 @@ "API_System.Device.Pwm": "OFF", "API_System.IO.Ports": "OFF", "API_System.Device.Spi": "OFF", - "API_Windows.Storage": "OFF" + "API_Windows.Storage": "OFF", + "API_nanoFramework.ResourceManager": "ON", + "API_nanoFramework.System.Collections": "ON", + "API_nanoFramework.System.Text": "ON" } }, { diff --git a/targets/Nordic/ARDESCO/CMakeLists.txt b/targets/Nordic/ARDESCO/CMakeLists.txt index ebbe4c9338..189508b2b4 100644 --- a/targets/Nordic/ARDESCO/CMakeLists.txt +++ b/targets/Nordic/ARDESCO/CMakeLists.txt @@ -14,5 +14,4 @@ endif() nf_setup_target_build() target_sources(app PRIVATE main.c ) - nf_copy_zephyr_build_artifacts() diff --git a/targets/Nordic/ARDESCO/nrf9160_ard0022B_ns.overlay b/targets/Nordic/ARDESCO/nrf9160_ard0022B_ns.overlay index 0f49a0424f..7ede797fec 100644 --- a/targets/Nordic/ARDESCO/nrf9160_ard0022B_ns.overlay +++ b/targets/Nordic/ARDESCO/nrf9160_ard0022B_ns.overlay @@ -10,7 +10,7 @@ // set UART1 out the Grove Connector &uart1 { compatible = "nordic,nrf-uarte"; - current-speed = <921600>; + current-speed = <115200>; status = "okay"; pinctrl-0 = <&uart1_default>; pinctrl-1 = <&uart1_sleep>; diff --git a/targets/Nordic/ARDESCO/prj.conf b/targets/Nordic/ARDESCO/prj.conf index dcae05b19f..a42d7311ea 100644 --- a/targets/Nordic/ARDESCO/prj.conf +++ b/targets/Nordic/ARDESCO/prj.conf @@ -5,7 +5,6 @@ #CONFIG_REQUIRES_FULL_LIBC=y # NEWLIB C (needed by math lib) CONFIG_NEWLIB_LIBC=y -#CONFIG_MINIMAL_LIBC_RAND=y CONFIG_CPLUSPLUS=y CONFIG_REBOOT=y @@ -37,36 +36,31 @@ CONFIG_UART_0_NRF_TX_BUFFER_SIZE=1024 CONFIG_UART_0_GPIO_MANAGEMENT=y # Need power management for uart -#Change for v2.0 -#CONFIG_DEVICE_POWER_MANAGEMENT=y CONFIG_PM_DEVICE=y CONFIG_POLL=y -# # 9160 specifc config -# CONFIG_NRF_MODEM_LIB=y - -# # Modem info (used by ard_lte) -# CONFIG_MODEM_INFO=y -# CONFIG_MODEM_INFO_ADD_SIM_ICCID=y -# CONFIG_NEWLIB_LIBC_FLOAT_PRINTF=y - CONFIG_UART_1_INTERRUPT_DRIVEN=y CONFIG_UART_1_ENHANCED_POLL_OUT=y CONFIG_UART_1_NRF_TX_BUFFER_SIZE=1024 CONFIG_UART_1_GPIO_MANAGEMENT=y # # Disable Modem traces, since we need UART1 for netnf debug uart -# CONFIG_NRF_MODEM_LIB_TRACE_ENABLED=n +CONFIG_NRF_MODEM_LIB_TRACE_ENABLED=n + +# Network support +CONFIG_NETWORKING=y +CONFIG_NET_SOCKETS=y +CONFIG_NET_NATIVE=n +CONFIG_NET_SOCKETS_POSIX_NAMES=y +CONFIG_NET_SOCKETS_OFFLOAD=y +CONFIG_NET_SOCKETS_OFFLOAD_TLS=y -# # Network support -# CONFIG_NETWORKING=y -# CONFIG_NET_SOCKETS=y -# CONFIG_NET_NATIVE=n -# CONFIG_NET_SOCKETS_POSIX_NAMES=y -# CONFIG_NET_SOCKETS_OFFLOAD=y -# CONFIG_NET_SOCKETS_OFFLOAD_TLS=y +# LTE support +CONFIG_LTE_LINK_CONTROL=y +CONFIG_LTE_AUTO_INIT_AND_CONNECT=n -# # LTE support -# CONFIG_LTE_LINK_CONTROL=y -# CONFIG_LTE_AUTO_INIT_AND_CONNECT=n +# Modem info (used by ard_lte) +CONFIG_MODEM_INFO=y +CONFIG_MODEM_INFO_ADD_SIM_ICCID=y +CONFIG_DATE_TIME=y diff --git a/targets/Nordic/CMakeLists.txt b/targets/Nordic/CMakeLists.txt index 6b376cf3d8..52aeec3da8 100644 --- a/targets/Nordic/CMakeLists.txt +++ b/targets/Nordic/CMakeLists.txt @@ -96,7 +96,7 @@ else() endif() if (NOT "v${NRF_CONNECT_SDK_FOUND_VERSION}" STREQUAL ${NRF_CONNECT_SDK_VERSION}) - message(FATAL_ERROR "\n\nFound nRF Connect SDK ${NRF_CONNECT_SDK_FOUND_VERSION}.\nExpecting ${NRF_CONNECT_SDK_VERSION}.\n\n") + message(WARNING "\n\nFound nRF Connect SDK ${NRF_CONNECT_SDK_FOUND_VERSION}.\nExpecting ${NRF_CONNECT_SDK_VERSION}.\n\n") endif() # save path for later diff --git a/targets/Nordic/NRF52840_DK/CMakeLists.txt b/targets/Nordic/NRF52840_DK/CMakeLists.txt index a257e78fe7..0537b7ba7a 100644 --- a/targets/Nordic/NRF52840_DK/CMakeLists.txt +++ b/targets/Nordic/NRF52840_DK/CMakeLists.txt @@ -12,5 +12,4 @@ endif() nf_setup_target_build() target_sources(app PRIVATE main.c ) - nf_copy_zephyr_build_artifacts() diff --git a/targets/Nordic/NRF52840_DK/prj.conf b/targets/Nordic/NRF52840_DK/prj.conf index 8792326578..5432c0fce5 100644 --- a/targets/Nordic/NRF52840_DK/prj.conf +++ b/targets/Nordic/NRF52840_DK/prj.conf @@ -2,14 +2,10 @@ # Portions Copyright (c) Ericsson AB 2020, all rights reserved # See LICENSE file in the project root for full license information. -#CONFIG_REQUIRES_FULL_LIBC=y -# NEWLIB C (needed by math lib) CONFIG_NEWLIB_LIBC=y +CONFIG_REBOOT=y -# 9160 specifc config -CONFIG_NEWLIB_LIBC_FLOAT_PRINTF=y CONFIG_CPLUSPLUS=y -CONFIG_REBOOT=y CONFIG_BUILD_WITH_TFM=n diff --git a/targets/Nordic/NRF9160_DK/CMakeLists.txt b/targets/Nordic/NRF9160_DK/CMakeLists.txt index 4baa7574d8..e4369734e5 100644 --- a/targets/Nordic/NRF9160_DK/CMakeLists.txt +++ b/targets/Nordic/NRF9160_DK/CMakeLists.txt @@ -2,6 +2,7 @@ # Copyright (c) .NET Foundation and Contributors # See LICENSE file in the project root for full license information. # +include(binutils.Nordic) # If board not specified set it now... if(NOT BOARD) @@ -11,6 +12,5 @@ endif() # invoke the Zephyr build nf_setup_target_build() -target_sources(app PRIVATE main.c) - +target_sources(app PRIVATE main.c ) nf_copy_zephyr_build_artifacts() diff --git a/targets/Nordic/NRF9160_DK/cert/GlobalSign-Root-CA-R2 b/targets/Nordic/NRF9160_DK/cert/GlobalSign-Root-CA-R2 new file mode 100644 index 0000000000..86d41ee5dc --- /dev/null +++ b/targets/Nordic/NRF9160_DK/cert/GlobalSign-Root-CA-R2 @@ -0,0 +1,90 @@ +/* +Certificate: + Data: + Version: 3 (0x2) + Serial Number: + 04:00:00:00:00:01:0f:86:26:e6:0d + Signature Algorithm: sha1WithRSAEncryption + Issuer: OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign + Validity + Not Before: Dec 15 08:00:00 2006 GMT + Not After : Dec 15 08:00:00 2021 GMT + Subject: OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:a6:cf:24:0e:be:2e:6f:28:99:45:42:c4:ab:3e: + 21:54:9b:0b:d3:7f:84:70:fa:12:b3:cb:bf:87:5f: + c6:7f:86:d3:b2:30:5c:d6:fd:ad:f1:7b:dc:e5:f8: + 60:96:09:92:10:f5:d0:53:de:fb:7b:7e:73:88:ac: + 52:88:7b:4a:a6:ca:49:a6:5e:a8:a7:8c:5a:11:bc: + 7a:82:eb:be:8c:e9:b3:ac:96:25:07:97:4a:99:2a: + 07:2f:b4:1e:77:bf:8a:0f:b5:02:7c:1b:96:b8:c5: + b9:3a:2c:bc:d6:12:b9:eb:59:7d:e2:d0:06:86:5f: + 5e:49:6a:b5:39:5e:88:34:ec:bc:78:0c:08:98:84: + 6c:a8:cd:4b:b4:a0:7d:0c:79:4d:f0:b8:2d:cb:21: + ca:d5:6c:5b:7d:e1:a0:29:84:a1:f9:d3:94:49:cb: + 24:62:91:20:bc:dd:0b:d5:d9:cc:f9:ea:27:0a:2b: + 73:91:c6:9d:1b:ac:c8:cb:e8:e0:a0:f4:2f:90:8b: + 4d:fb:b0:36:1b:f6:19:7a:85:e0:6d:f2:61:13:88: + 5c:9f:e0:93:0a:51:97:8a:5a:ce:af:ab:d5:f7:aa: + 09:aa:60:bd:dc:d9:5f:df:72:a9:60:13:5e:00:01: + c9:4a:fa:3f:a4:ea:07:03:21:02:8e:82:ca:03:c2: + 9b:8f + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Key Usage: critical + Certificate Sign, CRL Sign + X509v3 Basic Constraints: critical + CA:TRUE + X509v3 Subject Key Identifier: + 9B:E2:07:57:67:1C:1E:C0:6A:06:DE:59:B4:9A:2D:DF:DC:19:86:2E + X509v3 CRL Distribution Points: + + Full Name: + URI:http://crl.globalsign.net/root-r2.crl + + X509v3 Authority Key Identifier: + keyid:9B:E2:07:57:67:1C:1E:C0:6A:06:DE:59:B4:9A:2D:DF:DC:19:86:2E + + Signature Algorithm: sha1WithRSAEncryption + 99:81:53:87:1c:68:97:86:91:ec:e0:4a:b8:44:0b:ab:81:ac: + 27:4f:d6:c1:b8:1c:43:78:b3:0c:9a:fc:ea:2c:3c:6e:61:1b: + 4d:4b:29:f5:9f:05:1d:26:c1:b8:e9:83:00:62:45:b6:a9:08: + 93:b9:a9:33:4b:18:9a:c2:f8:87:88:4e:db:dd:71:34:1a:c1: + 54:da:46:3f:e0:d3:2a:ab:6d:54:22:f5:3a:62:cd:20:6f:ba: + 29:89:d7:dd:91:ee:d3:5c:a2:3e:a1:5b:41:f5:df:e5:64:43: + 2d:e9:d5:39:ab:d2:a2:df:b7:8b:d0:c0:80:19:1c:45:c0:2d: + 8c:e8:f8:2d:a4:74:56:49:c5:05:b5:4f:15:de:6e:44:78:39: + 87:a8:7e:bb:f3:79:18:91:bb:f4:6f:9d:c1:f0:8c:35:8c:5d: + 01:fb:c3:6d:b9:ef:44:6d:79:46:31:7e:0a:fe:a9:82:c1:ff: + ef:ab:6e:20:c4:50:c9:5f:9d:4d:9b:17:8c:0c:e5:01:c9:a0: + 41:6a:73:53:fa:a5:50:b4:6e:25:0f:fb:4c:18:f4:fd:52:d9: + 8e:69:b1:e8:11:0f:de:88:d8:fb:1d:49:f7:aa:de:95:cf:20: + 78:c2:60:12:db:25:40:8c:6a:fc:7e:42:38:40:64:12:f7:9e: + 81:e1:93:2e +*/ + +"-----BEGIN CERTIFICATE-----\n" +"MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G\n" +"A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp\n" +"Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1\n" +"MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG\n" +"A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI\n" +"hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL\n" +"v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8\n" +"eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq\n" +"tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd\n" +"C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa\n" +"zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB\n" +"mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH\n" +"V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n\n" +"bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG\n" +"3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs\n" +"J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO\n" +"291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS\n" +"ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd\n" +"AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7\n" +"TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==\n" +"-----END CERTIFICATE-----\n" diff --git a/targets/Nordic/NRF9160_DK/nrf9160dk_nrf9160_ns.overlay b/targets/Nordic/NRF9160_DK/nrf9160dk_nrf9160_ns.overlay index 94c1b8635b..aaabd4b488 100644 --- a/targets/Nordic/NRF9160_DK/nrf9160dk_nrf9160_ns.overlay +++ b/targets/Nordic/NRF9160_DK/nrf9160dk_nrf9160_ns.overlay @@ -5,8 +5,10 @@ // // Enable uart1 -// compatible = "nordic,nrf-uarte"; +// It appears that only 115200 works when piping through the 52840 // current-speed = <921600>; &uart1 { + compatible = "nordic,nrf-uarte"; + current-speed = <115200>; status = "okay"; }; diff --git a/targets/Nordic/NRF9160_DK/prj.conf b/targets/Nordic/NRF9160_DK/prj.conf index 4422eac3fe..34d2aeaac5 100644 --- a/targets/Nordic/NRF9160_DK/prj.conf +++ b/targets/Nordic/NRF9160_DK/prj.conf @@ -2,8 +2,6 @@ # Portions Copyright (c) Ericsson AB 2020, all rights reserved # See LICENSE file in the project root for full license information. -#CONFIG_REQUIRES_FULL_LIBC=y -# NEWLIB C (needed by math lib) CONFIG_NEWLIB_LIBC=y # 9160 specifc config @@ -28,6 +26,10 @@ CONFIG_HEAP_MEM_POOL_SIZE=98304 CONFIG_FLASH=y CONFIG_FLASH_PAGE_LAYOUT=y +# for debugging +CONFIG_DEBUG_OPTIMIZATIONS=y +CONFIG_DEBUG_THREAD_INFO=y + # for serial CONFIG_SERIAL=y CONFIG_UART_ASYNC_API=n @@ -47,9 +49,28 @@ CONFIG_UART_1_INTERRUPT_DRIVEN=y CONFIG_UART_1_ENHANCED_POLL_OUT=y CONFIG_UART_1_NRF_TX_BUFFER_SIZE=1024 CONFIG_UART_1_GPIO_MANAGEMENT=y +CONFIG_MODEM_KEY_MGMT=y # Disable Modem traces, since we need UART1 for netnf debug uart CONFIG_NRF_MODEM_LIB_TRACE_ENABLED=n CONFIG_I2C=y +# Network support +CONFIG_NETWORKING=y +CONFIG_NET_SOCKETS=y +CONFIG_NET_NATIVE=n +CONFIG_NET_SOCKETS_POSIX_NAMES=y +CONFIG_NET_SOCKETS_OFFLOAD=y +CONFIG_NET_SOCKETS_OFFLOAD_TLS=y +CONFIG_NET_SOCKETS_SOCKOPT_TLS=y + +# LTE support +CONFIG_LTE_LINK_CONTROL=y +CONFIG_LTE_AUTO_INIT_AND_CONNECT=n + +# Modem info (used by ard_lte) +CONFIG_MODEM_INFO=y +CONFIG_MODEM_INFO_ADD_SIM_ICCID=y + +CONFIG_DATE_TIME=y diff --git a/targets/Nordic/_include/nrf9160_lte.h b/targets/Nordic/_include/nrf9160_lte.h new file mode 100644 index 0000000000..a0708e3c2b --- /dev/null +++ b/targets/Nordic/_include/nrf9160_lte.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) Ericsson AB 2020, all rights reserved + */ +#ifndef NRF9610_LTE_H__ +#define NRF9610_LTE_H__ + +// Include basic operating system dependencies + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) +#include +#define TLS_SEC_TAG 42 +#endif + +// Default connection timeout +#define NETWORK_TIMEOUT 120 +#define IMxI_LEN 16 +#define ICCID_LEN 22 +#define IP_ADDR_LEN 17 +#define FW_VER_LEN 32 +#define APN_LEN 64 + +#define DEFAULT_TIMEOUT -1 + +// Connect State values +#define CONN_STATE_DISCONNECTED 0 +#define CONN_STATE_CONN_HOME 1 +#define CONN_STATE_CONN_ROAM 2 + +// Initialize the LTE library +int nrf9160_lte_init(uint16_t timeout); + +// Connect to the network. +int nrf9160_lte_connect(uint16_t timeout); + +// Disconnect to the network. +int nrf9160_lte_offline(void); + +// Turn off the modem. +int nrf9160_lte_power_off(void); + + +#ifdef __cplusplus +} +#endif + +#endif /* NRF9610_LTE_H__ */ + diff --git a/targets/Nordic/_include/sockets_nrf9160.h b/targets/Nordic/_include/sockets_nrf9160.h new file mode 100644 index 0000000000..1cf497fa4f --- /dev/null +++ b/targets/Nordic/_include/sockets_nrf9160.h @@ -0,0 +1,276 @@ +// +// Copyright (c) .NET Foundation and Contributors +// Portions Copyright (c) Microsoft Corporation. All rights reserved. +// See LICENSE file in the project root for full license information. +// + +#ifndef SOCKETS_H +#define SOCKETS_H + +//--// + +#include "nanoHAL.h" + +#include + +//#include +#include +#include +#ifndef restrict +#define restrict +#endif +#include + +int GetAvailBytes (SOCK_SOCKET socket); +extern "C" int signal_nf_stack(void); + +//--// + +#define SOCKET_CHECK_ENTER() \ + int32_t ret=0 \ + +#define SOCKET_CLEANUP() \ + goto RETURN_OK; \ + SOCKET_CHECK_RETURN: \ + +#define SOCKET_CHECK_EXIT_CLEANUP() \ + RETURN_OK: \ + ASSERT(ret != SOCK_SOCKET_ERROR); \ + return ret; \ + +#define SOCKET_CHECK_EXIT() \ + SOCKET_CLEANUP() \ + RETURN_OK: \ + ASSERT(ret != SOCK_SOCKET_ERROR); \ + return ret; \ + +#define SOCKET_CHECK_EXIT_bool() \ + SOCKET_CLEANUP() \ + RETURN_OK: \ + return ret != SOCK_SOCKET_ERROR; \ + +#define SOCKET_CHECK_EXIT_bool_CLEANUP()\ + RETURN_OK: \ + return ret != SOCK_SOCKET_ERROR; \ + +#define SOCKET_CHECK_RESULT(x) \ + if((ret = (x)) == SOCK_SOCKET_ERROR)\ + { \ + goto SOCKET_CHECK_RETURN; \ + } \ + +#define SOCKET_CHECK_bool(x) \ + if(!(x)) \ + { \ + ret = SOCK_SOCKET_ERROR; \ + goto SOCKET_CHECK_RETURN; \ + } \ + +#define SOCKET_CHECK_EXIT_NORETURN() \ + RETURN_OK: \ + +struct Sockets_nrf9160_Driver +{ + static SOCK_SOCKET Socket( int32_t family, int32_t type, int32_t protocol, bool fDebug ); + static int Connect(SOCK_SOCKET socket, const struct SOCK_sockaddr* address, int32_t addressLen) ; + static int Send(SOCK_SOCKET socket, const char* buf, int32_t len, int32_t flags) ; + static int Recv(SOCK_SOCKET socket, char* buf, int32_t len, int32_t flags); + static int Close(SOCK_SOCKET socket); + static int Listen( SOCK_SOCKET socket, int32_t backlog ); + static SOCK_SOCKET Accept( SOCK_SOCKET socket, struct SOCK_sockaddr* address, int* addressLen, bool fDebug ); + static int Select( int32_t nfds, SOCK_fd_set* readfds, SOCK_fd_set* writefds, SOCK_fd_set* except, const struct SOCK_timeval* timeout ); + static int RecvFrom( SOCK_SOCKET s, char* buf, int32_t len, int32_t flags, struct SOCK_sockaddr* from, int* fromlen ); + static int SendTo( SOCK_SOCKET s, const char* buf, int32_t len, int32_t flags, const struct SOCK_sockaddr* to, int32_t tolen ); + static int Shutdown( SOCK_SOCKET s, int32_t how); + + static bool Initialize(); + static bool Uninitialize(); + static void CloseConnections(bool fCloseDbg); + + static void SaveConfig(int32_t index, HAL_Configuration_NetworkInterface *cfg); + + // Debugger methods ( socket_debugger.cpp ) + static void Debugger_Initialize(); + static void Debugger_Uninitialize(); + static void Debugger_Abort(); + + static bool InitializeDbgListener( int ComPortNum ); + static bool UninitializeDbgListener( int ComPortNum ); + static int Write( int ComPortNum, const char* Data, size_t size ); + static int Read ( int ComPortNum, char* Data, size_t size ); + static bool UpgradeToSsl( int ComPortNum, const int8_t* pCACert, uint32_t caCertLen, const int8_t* pDeviceCert, uint32_t deviceCertLen, const char* szTargetHost ); + static bool IsUsingSsl( int ComPortNum ); + + //(db) TODO: reduce the code below with a single lookup + //struct Sockets_nrf9160_Driver::SocketRegisterMap *GetSockRegMap(SOCK_SOCKET socket) + uint32_t *GetSockFlags(SOCK_SOCKET socket) + { + for(int i=m_cntSockets-1; i>=0; i--) + { + if(socket == m_socketHandles[i].m_socket) + return &m_socketHandles[i].m_flags; + } + printk ("***** ERROR socket %d not found in SocketRegisterMap\n", socket); + ASSERT(FALSE); + return 0; + } + + void* GetSocketSslData(SOCK_SOCKET socket) + { + int32_t tmp; + + return GetSocketSslData(socket, tmp); + } + + void* GetSocketSslData(SOCK_SOCKET socket, int32_t &sockIndex) + { + GLOBAL_LOCK_SOCKETS(x); + + for(int i=m_cntSockets-1; i>=0; i--) + { + if(socket == m_socketHandles[i].m_socket) + { + sockIndex = i; + return m_socketHandles[i].m_sslData; + } + } + + return NULL; + } + + void SetSocketSslData(SOCK_SOCKET socket, void* sslObj) + { + GLOBAL_LOCK_SOCKETS(x); + + for(int i=m_cntSockets-1; i>=0; i--) + { + if(socket == m_socketHandles[i].m_socket) + { + m_socketHandles[i].m_sslData = sslObj; + + break; + } + } + } + +#ifdef PERRADDR_WORKAROUND + int GetSocketAddrData(SOCK_SOCKET socket, void *addr, int *len) + { + GLOBAL_LOCK_SOCKETS(x); + + for(int i=m_cntSockets-1; i>=0; i--) + { + if(socket == m_socketHandles[i].m_socket) + { + int addrlen = m_socketHandles[i].peeraddr_len; + if (*len >= addrlen) + { + memcpy (addr, &m_socketHandles[i].peeraddr, addrlen); + *len = addrlen; + } + return 0; + } + } + printk ("GetSocketAddrData sock %d. data not found %p %d\n", socket, addr, *len); + return -1; + } + + int SetSocketAddrData(SOCK_SOCKET socket, const void* data, int len) + { + GLOBAL_LOCK_SOCKETS(x); + + for(int i=m_cntSockets-1; i>=0; i--) + { + if(socket == m_socketHandles[i].m_socket) + { + //printk ("SetSocketAddrData sock found %d\n", i); + if (len <= (int)sizeof (m_socketHandles[i].peeraddr)) + { + //printk ("SetSocketAddrData copy data\n"); + memcpy (&m_socketHandles[i].peeraddr, data, len); + m_socketHandles[i].peeraddr_len = len; + } + else + printk ("SetSocketAddrData sockaddr too long %d %d\n", len, sizeof (m_socketHandles[i].peeraddr)); + + return 0; + } + } + printk ("SetSocketAddrData sock %d. data not found %p %d\n", socket, data, len); + return -1; + } +#endif + // required by SSL + static void UnregisterSocket( int index ); + + + static void ClearStatusBitsForSocket(SOCK_SOCKET sock, bool fWrite); + static bool InitializeMulticastDiscovery(); + +private: + + static void SockMonitorThread(void *a, void *b, void *c); + + static void RegisterSocket( SOCK_SOCKET sock, bool selectable, bool fDebug ); + + struct SocketRegisterMap + { + SOCK_SOCKET m_socket; + uint32_t m_flags; + void* m_sslData; +#ifdef PERRADDR_WORKAROUND + // Workaround for getpeeraddr + struct SOCK_sockaddr peeraddr; + int peeraddr_len; +#endif + + static const uint32_t c_SelectableSocket = 0x0001; + static const uint32_t c_DebugSocket = 0x0002; + static const uint32_t c_CloseSocket = 0x0004; + + static const uint32_t c_SelRdSocket = 0x0010; + static const uint32_t c_SelWrSocket = 0x0020; + static const uint32_t c_SelErSocket = 0x0040; + static const uint32_t c_SelSocketMask = 0x0070; + }; + + enum DebuggerState + { + DbgSock_Uninitialized = 0, + DbgSock_Listening = 1, + DbgSock_Connected = 2, + } m_stateDebugSocket; + + bool m_usingSSL; + + static void MulticastDiscoveryRespond(void* arg); + static void MulticastDiscoverySchedule(); + + static void CloseDebuggerSocket(); + static void OnDebuggerTimeout(void* arg); + + static HAL_COMPLETION s_DebuggerTimeoutCompletion; + + SOCK_SOCKET m_SocketDebugListener; + SOCK_SOCKET m_SocketDebugStream; + SOCK_SOCKET m_multicastSocket; + + bool m_fShuttingDown; + + //(db) + struct k_sem sem_sockmon; + + int32_t m_cntSockets; + struct SocketRegisterMap m_socketHandles[SOCKETS_MAX_COUNT]; + + static bool s_initialized; + static bool s_initializedDbg; + static const int32_t c_WellKnownDebugPort = DEBUG_SOCKET_PORT; + static bool s_wirelessInitialized; + static bool s_discoveryInitialized; +}; + +extern Sockets_nrf9160_Driver g_Sockets_nrf9160_Driver; + +#endif // SOCKETS_H + diff --git a/targets/Nordic/_include/ssl_sockets_nrf9160.h b/targets/Nordic/_include/ssl_sockets_nrf9160.h new file mode 100644 index 0000000000..6c03c36898 --- /dev/null +++ b/targets/Nordic/_include/ssl_sockets_nrf9160.h @@ -0,0 +1,20 @@ +// +// Copyright (c) .NET Foundation and Contributors +// See LICENSE file in the project root for full license information. +// + +#ifndef SSL_NRF9160_H +#define SSL_NRF9160_H + +struct nrf91ssl_Context +{ + //SlNetSockSecAttrib_t* SecurityAttributes; + uint32_t securityMethod; + uint32_t peer_verify; + int sec_tag; + + uint32_t SocketFd; + bool IsServer; +}; + +#endif //SSL_NRF9160_H diff --git a/targets/Nordic/_include/targetHAL.h b/targets/Nordic/_include/targetHAL.h index 866f74f1ca..5492bcfc5e 100644 --- a/targets/Nordic/_include/targetHAL.h +++ b/targets/Nordic/_include/targetHAL.h @@ -29,8 +29,8 @@ extern "C" // Definitions for Sockets/Network #define GLOBAL_LOCK_SOCKETS(x) -// get number of sockets from lwIP options -#define PLATFORM_DEPENDENT__SOCKETS_MAX_COUNT MEMP_NUM_NETCONN +// get number of sockets from zephyr config process +#define PLATFORM_DEPENDENT__SOCKETS_MAX_COUNT CONFIG_NET_MAX_CONN #define LPCSTR const char * diff --git a/targets/Nordic/_nanoCLR/targetHAL_Time.cpp b/targets/Nordic/_nanoCLR/targetHAL_Time.cpp index e4953d46c6..03e59886e6 100644 --- a/targets/Nordic/_nanoCLR/targetHAL_Time.cpp +++ b/targets/Nordic/_nanoCLR/targetHAL_Time.cpp @@ -9,46 +9,64 @@ #include #include #include +#include + +/* + * Amazingly, the 'new lib' doesn't convert longlong vals using %lld + * So, I need this routine. + */ +// char *my_longlong2str(uint64_t *num_ptr) +// { +// static char longnum[64]; +// uint64_t num = *num_ptr; +// memset(longnum, sizeof(longnum), 0); +// char *p = &longnum[sizeof(longnum) - 2]; +// do +// { +// *p-- = num % 10 + '0'; +// num = num / 10; +// } while (num != 0); +// p++; +// return p; +// } +// char *my_time_to_str(uint64_t *time_val, char *sz, int len) +// { +// struct tm st_tim; +// time_t corrected = *time_val / 1000; + +// sz[0] = '\0'; +// if (corrected < 100000) +// return sz; + +// const struct tm *p = gmtime_r(&corrected, &st_tim); +// if (p != 0) +// { +// sprintf( +// sz, +// "%d/%d/%d %2d:%02d:%02d", +// p->tm_mon + 1, +// p->tm_mday, +// p->tm_year + 1900, +// p->tm_hour, +// p->tm_min, +// p->tm_sec); +// } +// return sz; +// } // Returns the current date time from the system tick or from the RTC if it's available (this depends on the respective // configuration option) uint64_t HAL_Time_CurrentDateTime(bool datePartOnly) { + // printk ("HAL_Time_CurrentDateTime++ %d\n", datePartOnly); #if (HAL_USE_RTC == TRUE) + uint64_t epoc; // epoch time, seconds since 1/1/1970 + date_time_now((int64_t *)&epoc); - // use RTC to get date time - SYSTEMTIME st; - RTCDateTime _dateTime; - - rtcGetTime(&RTCD1, &_dateTime); - - st.wDay = (unsigned short)_dateTime.day; - st.wMonth = (unsigned short)_dateTime.month; - st.wYear = (unsigned short)(_dateTime.year + 1980); // ChibiOS is counting years since 1980 - st.wDayOfWeek = (unsigned short)_dateTime.dayofweek; - - // zero 'time' fields if date part only is required - if (datePartOnly) - { - st.wMilliseconds = 0; - st.wSecond = 0; - st.wMinute = 0; - st.wHour = 0; - } - else - { - // full date&time required, fill in 'time' fields too - - st.wMilliseconds = (unsigned short)(_dateTime.millisecond % 1000); - _dateTime.millisecond /= 1000; - st.wSecond = (unsigned short)(_dateTime.millisecond % 60); - _dateTime.millisecond /= 60; - st.wMinute = (unsigned short)(_dateTime.millisecond % 60); - _dateTime.millisecond /= 60; - st.wHour = (unsigned short)(_dateTime.millisecond % 24); - } - - return HAL_Time_ConvertFromSystemTime(&st); + // msec between 1/1/1601 and 1/1/1970 = 11644473600000 + uint64_t nf_epoc = epoc + (11644473600000); + nf_epoc = nf_epoc * 10000; // Convert to 100nS + return nf_epoc; #else @@ -75,24 +93,24 @@ uint64_t HAL_Time_CurrentDateTime(bool datePartOnly) void HAL_Time_SetUtcTime(uint64_t utcTime) { SYSTEMTIME systemTime; + printk("HAL_Time_SetUtcTime++ NEED TO TEST\n"); HAL_Time_ToSystemTime(utcTime, &systemTime); #if (HAL_USE_RTC == TRUE) - - // set RTC - RTCDateTime newTime; - - newTime.year = systemTime.wYear - 1980; // ChibiOS time base is 1980-01-01 - newTime.month = systemTime.wMonth; - newTime.day = systemTime.wDay; - newTime.dayofweek = systemTime.wDayOfWeek; - newTime.millisecond = - ((((uint32_t)systemTime.wHour * 3600) + ((uint32_t)systemTime.wMinute * 60) + (uint32_t)systemTime.wSecond) * - 1000); - - // set RTC time - rtcSetTime(&RTCD1, &newTime); + struct tm st; + st.tm_hour = systemTime.wHour; + st.tm_sec = systemTime.wSecond; // seconds after the minute - [0, 60] including leap second + st.tm_min = systemTime.wMinute; // minutes after the hour - [0, 59] + st.tm_hour = systemTime.wHour; // hours since midnight - [0, 23] + st.tm_mday = systemTime.wDay; // day of the month - [1, 31] + st.tm_mon = systemTime.wMonth; // months since January - [0, 11] + st.tm_year = systemTime.wYear; // years since 1900 + st.tm_wday = 0; // Unused. + st.tm_yday = 0; // Unused. + st.tm_isdst = 0; + + date_time_set(&st); #else @@ -147,6 +165,7 @@ bool HAL_Time_TimeSpanToStringEx(const int64_t &ticks, char *&buf, size_t &len) bool DateTimeToString(const uint64_t &time, char *&buf, size_t &len) { SYSTEMTIME st; + printk("DateTimeToString++\n"); HAL_Time_ToSystemTime(time, &st); @@ -176,6 +195,7 @@ char *DateTimeToString(const uint64_t &time) const char *HAL_Time_CurrentDateTimeToString() { + //printk("HAL_Time_CurrentDateTimeToString++\n"); return DateTimeToString(HAL_Time_CurrentDateTime(false)); } diff --git a/targets/Nordic/_nanoCLR_module/nf_lib/CMakeLists.txt b/targets/Nordic/_nanoCLR_module/nf_lib/CMakeLists.txt index 74cfe11500..f5df206b65 100644 --- a/targets/Nordic/_nanoCLR_module/nf_lib/CMakeLists.txt +++ b/targets/Nordic/_nanoCLR_module/nf_lib/CMakeLists.txt @@ -44,20 +44,6 @@ endif() # source files for nanoFramework Networking set(NF_Network_SRCS "") -set(NF_Network_SRCS - -# #pal Socket - sockets_lwip.cpp - -# #Lwip -# lwIP_Sockets.cpp -# lwIP_Sockets_functions.cpp - -# # platform specific -# Target_Network.cpp -# targetHAL_Network.cpp -) - # need a conditional include because of ESP32 building network as a library if(NOT USE_SECURITY_MBEDTLS_OPTION) list(APPEND NF_Network_SRCS ssl_stubs.cpp) @@ -67,25 +53,12 @@ endif() set(NF_Network_Security_SRCS ssl.cpp - ssl_accept_internal.cpp - ssl_add_cert_auth_internal.cpp - ssl_close_socket_internal.cpp - ssl_connect_internal.cpp - ssl_decode_private_key_internal.cpp - ssl_exit_context_internal.cpp - ssl_generic.cpp - ssl_generic_init_internal.cpp - ssl_initialize_internal.cpp - ssl_parse_certificate_internal.cpp - ssl_available_internal.cpp - ssl_read_internal.cpp - ssl_uninitialize_internal.cpp - ssl_write_internal.cpp + ssl_socket_api.cpp ) -if(NF_FEATURE_DEBUGGER) - list(APPEND NF_Network_SRCS Sockets_debugger.cpp) -endif() +#if(NF_FEATURE_DEBUGGER) +# list(APPEND NF_Network_SRCS Sockets_debugger.cpp) +#endif() # add Enc28j60source files in two steps if(USE_ENC28J60_DRIVER_OPTION) @@ -112,7 +85,7 @@ foreach(SRC_FILE ${NF_Network_SRCS}) ${CMAKE_SOURCE_DIR}/src/PAL/COM/sockets/ssl/mbedTLS ${CMAKE_SOURCE_DIR}/src/PAL/Lwip ${CMAKE_SOURCE_DIR}/targets/${RTOS}/_common - ${CMAKE_SOURCE_DIR}/targets/${RTOS}/_Network + ${CMAKE_SOURCE_DIR}/targets/${RTOS}/_netCellular ${BASE_PATH_FOR_CLASS_LIBRARIES_MODULES} @@ -140,6 +113,7 @@ if(USE_SECURITY_MBEDTLS_OPTION) PATHS ${CMAKE_SOURCE_DIR}/src/PAL/COM/sockets/ssl + ${CMAKE_SOURCE_DIR}/targets/${RTOS}/_netCellular ${NF_Security_Search_Path} CMAKE_FIND_ROOT_PATH_BOTH @@ -187,10 +161,8 @@ endmacro() # add platform dirs add_subdirectory($ENV{PLATFORM_NORDIC_ROOT}/_include nordic__include) add_subdirectory($ENV{PLATFORM_NORDIC_ROOT}/_common nordic__common) -#add_subdirectory(${TARGET_RTOS_ROOT}/_nanoBooter ${TARGET_RTOS_BINDIR}/_nanoBooter) add_subdirectory($ENV{PLATFORM_NORDIC_ROOT}/_nanoCLR nordic__nanoCLR) - # (binutils.zephyr.cmake) Calls FindPackage for platform specific needs. Nop right now. nf_add_platform_packages(TARGET ${NANOCLR_PROJECT_NAME}) @@ -228,14 +200,11 @@ endif() if(USE_NETWORKING_OPTION) nordic_add_network() - #zephyr_include_directories(${ZEPHYR_CURRENT_LIBRARY} PUBLIC z_include_directories(${ZEPHYR_CURRENT_LIBRARY} PUBLIC ${NF_Network_INCLUDE_DIRS} -# "C:/_dev/ardesco/v1.8.0/modules/lib/matter/third_party/lwip/repo/lwip/src/include" ) endif() - # zephyr-centric adding source files zephyr_library_sources( ${NF_CoreCLR_SOURCES} @@ -259,19 +228,12 @@ if(NF_FEATURE_DEBUGGER) ) endif() -if(0) -if(USE_NETWORKING_OPTION) - zephyr_library_sources(${NF_Network_SOURCES}) -endif() -else() if(USE_NETWORKING_OPTION) zephyr_library_sources( ${NORDIC_Network_SOURCES} - ${TARGET_BASE_LOCATION}/../_network/nrf9160_lte.c - #${TARGET_BASE_LOCATION}/../_network/sockets_Nordic.cpp - ${TARGET_BASE_LOCATION}/../_network/Nordic_Sockets_functions.cpp - ${TARGET_BASE_LOCATION}/../_network/targetHAL_ConfigurationManager.cpp - + ${TARGET_BASE_LOCATION}/../_netCellular/nrf9160_lte.c + ${TARGET_BASE_LOCATION}/../_netCellular/socket_api.cpp + ${TARGET_BASE_LOCATION}/../_netCellular/Nordic_Sockets_functions.cpp + ${TARGET_BASE_LOCATION}/../_netCellular/targetHAL_ConfigurationManager.cpp ) endif() -endif() diff --git a/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c b/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c index d8e0736ae8..6cd837511f 100644 --- a/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c +++ b/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c @@ -40,7 +40,8 @@ int start_nf(const char *wire_uart_name) printk("nf_lib entry\n"); // g_heapsize = (0x8000-32) * 2; //64k - overhead - g_heapsize = (0x8000 - 32); // 32k - overhead + g_heapsize = (0x8800 - 32); // 48k - overhead + //g_heapsize = (0x8000 - 32); // 32k - overhead g_heapbase = k_malloc(g_heapsize); if (g_heapbase != 0) diff --git a/targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp b/targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp new file mode 100644 index 0000000000..e94e09ef6f --- /dev/null +++ b/targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp @@ -0,0 +1,935 @@ +// +// Copyright (c) .NET Foundation and Contributors +// Portions Copyright (c) Microsoft Corporation. All rights reserved. +// See LICENSE file in the project root for full license information. +// + +// #include "lwIP_Sockets.h" + +#include + +#include +#include + +#include + +extern char connect_state; + + +static int last_sock_error = 0; + +bool HAL_SOCK_Initialize() +{ + NATIVE_PROFILE_PAL_NETWORK(); + // Start up the nrf modem +#ifdef CONFIG_SOC_SERIES_NRF91X + nrf9160_lte_init(180); +#endif + + printk("HAL_SOCK_Initialize-- Connect state %d\n", connect_state); + return true; +} + +bool HAL_SOCK_Uninitialize() +{ + NATIVE_PROFILE_PAL_NETWORK(); + return true; +} + +int net_family_2z(int netfam) +{ + if (netfam == SOCK_AF_INET) + netfam = AF_INET; + else if (netfam == SOCK_AF_INET6) + netfam = AF_INET6; + else + printk("**** Unknown .net af_family type %d\n", netfam); + return netfam; +} +int z_family_2net(int zfam) +{ + if (zfam == AF_INET) + zfam = SOCK_AF_INET; + else if (zfam == AF_INET6) + zfam = SOCK_AF_INET6; + else + printk("**** Unknown z af_family type %d\n", zfam); + return zfam; +} + +struct sockaddr *net_saddr_2z(const struct SOCK_sockaddr *address, struct sockaddr *zaddr) +{ + zaddr->sa_family = net_family_2z(address->sa_family); + memcpy(zaddr->data, address->sa_data, sizeof(address->sa_data)); + return zaddr; +} + +SOCK_SOCKET HAL_SOCK_socket(int family, int type, int protocol) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("socket fam %d type %d protocol %d\n", family, type, protocol); + + // Translate network family + family = net_family_2z(family); + + printk("socket x fam %d type %d protocol %d\n", family, type, protocol); + int sock = socket(family, type, protocol); + if (sock < 0) + printk("***** socket fail\n"); + return sock; +} +int HAL_SOCK_bind(SOCK_SOCKET socket, const struct SOCK_sockaddr *address, int addressLen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("bind: sock %d fam: %d\n", socket, address->sa_family); + + // Translate address into something zephyr knows about + struct sockaddr addr; + int rc = bind(socket, net_saddr_2z(address, &addr), addressLen); + if (rc < 0) + printk("***** bind fail. %d\n", errno); + last_sock_error = errno; + return rc; +} +int HAL_SOCK_connect(SOCK_SOCKET socket, const struct SOCK_sockaddr *address, int addressLen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("connect: sock %d fam: %d len %d\n", socket, address->sa_family, addressLen); + + // Translate address into something zephyr knows about + struct sockaddr addr; + // int rc = connect(socket, net_saddr_2z (address, &addr), addressLen); + net_saddr_2z(address, &addr); + + printk("connect: xlate: sock %d fam: %d len %d\n", socket, addr.sa_family, addressLen); + //printk("connect: old errno %d\n", errno); + int rc = connect(socket, &addr, addressLen); + if (rc != 0) + { + if (errno == EINPROGRESS) + { + printk("### connect returned EINPROGRESS\n"); + rc = 0; + } + else + printk("***** connect fail. %d\n", errno); + } + last_sock_error = errno; + return rc; +} +int HAL_SOCK_send(SOCK_SOCKET socket, const char *buf, int len, int flags) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("HAL_SOCK_send soc %d len %d flags %x\n", socket, len, flags); + int rc = send(socket, buf, len, flags); + if (rc < 0) + { + printk("send failed %d %d\n", rc, errno); + } + last_sock_error = errno; + return rc; +} +int HAL_SOCK_recv(SOCK_SOCKET socket, char *buf, int len, int flags) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("HAL_SOCK_recv soc %d len %d flags %x\n", socket, len, flags); + int rc = recv(socket, buf, len, flags); + if (rc < 0) + { + printk("recv failed %d %d\n", rc, errno); + } + last_sock_error = errno; + return rc; +} +int HAL_SOCK_close(SOCK_SOCKET socket) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("HAL_SOCK_close soc %d\n", socket); + int rc = close(socket); + if (rc) + { + printk("close failed %d %d\n", rc, errno); + } + last_sock_error = errno; + return rc; +} +int HAL_SOCK_listen(SOCK_SOCKET socket, int backlog) +{ + NATIVE_PROFILE_PAL_NETWORK(); + int rc = listen(socket, backlog); + if (rc) + { + printk("listen failed %d %d\n", rc, errno); + } + last_sock_error = errno; + return rc; +} +SOCK_SOCKET HAL_SOCK_accept(SOCK_SOCKET socket, struct SOCK_sockaddr *address, int *addressLen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + int rc = accept(socket, (struct sockaddr *)address, (unsigned int *)addressLen); + if (rc) + { + printk("accept failed %d %d\n", rc, errno); + } + last_sock_error = errno; + return rc; +} +int HAL_SOCK_shutdown(SOCK_SOCKET socket, int how) +{ + NATIVE_PROFILE_PAL_NETWORK(); + return shutdown(socket, how); +} +struct nf_addrinfo +{ + struct SOCK_addrinfo res; + struct SOCK_sockaddr sa; + struct zsock_addrinfo *z_res; +}; + +void rep_zsockaddr_to_sockaddr(struct zsock_addrinfo *z, struct SOCK_addrinfo *a) +{ + a->ai_flags = z->ai_flags; + a->ai_family = z->ai_family; + a->ai_socktype = z->ai_socktype; + a->ai_protocol = z->ai_protocol; + a->ai_addrlen = z->ai_addrlen; + if (z->ai_canonname) + hal_strcpy_s(a->ai_canonname, sizeof(a->ai_canonname), z->ai_canonname); + else + a->ai_canonname = 0; + + if (z->ai_addr != 0) + { + if (a->ai_addr != 0) + { + memcpy(a->ai_addr, z->ai_addr, sizeof(SOCK_sockaddr)); + + // Translate this into flags .net nf knows about + if (a->ai_addr->sa_family == AF_INET) + a->ai_addr->sa_family = SOCK_AF_INET; + else if (a->ai_addr->sa_family == AF_INET6) + a->ai_addr->sa_family = SOCK_AF_INET6; + } + else + printk("********** rep_zsockaddr_to_sockaddr a->ai_addr zero while z->ai_addr nonzero\n"); + } + else + a->ai_addr = 0; + a->ai_next = 0; + + /* + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + size_t ai_addrlen; + char *ai_canonname; + struct SOCK_sockaddr *ai_addr; + struct SOCK_addrinfo *ai_next; + + + zsock + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + socklen_t ai_addrlen; + struct sockaddr *ai_addr; + char *ai_canonname; + + struct sockaddr _ai_addr; + char _ai_canonname[DNS_MAX_NAME_SIZE + 1]; + */ +} + +void rep_sockaddr_to_zsockaddr(const struct SOCK_addrinfo *a, struct zsock_addrinfo *z) +{ + z->ai_flags = a->ai_flags; + z->ai_family = a->ai_family; + z->ai_socktype = a->ai_socktype; + z->ai_protocol = a->ai_protocol; + z->ai_addrlen = a->ai_addrlen; + if (a->ai_canonname) + hal_strcpy_s(z->ai_canonname, sizeof(z->ai_canonname), a->ai_canonname); + else + z->ai_canonname = 0; + + if (a->ai_addr != 0) + { + if (z->ai_addr != 0) + { + memcpy(z->ai_addr, a->ai_addr, sizeof(SOCK_sockaddr)); + } + else + printk("********** rep_zsockaddr_sockaddr ai_addr zero but a->ai_addr non-zero\n"); + } + else + z->ai_addr = 0; +} +char *ipaddr2str (uint32_t addr) +{ + static char sz[48]; + sprintf (sz, "%d.%d.%d.%d", (addr && 0xff000000) >> 24, (addr && 0xff0000) >> 16, + (addr && 0xff00) >> 8, (addr && 0xff)); + return sz; +} +int HAL_SOCK_getaddrinfo( + const char *nodename, + char *servname, + const struct SOCK_addrinfo *hints, + struct SOCK_addrinfo **res) +{ + NATIVE_PROFILE_PAL_NETWORK(); + int rc; + // used to convert hints to zsock hints + struct zsock_addrinfo ai; + + // Covert hints to zsock hints + rep_sockaddr_to_zsockaddr(hints, &ai); + + // Alloc a compatible structure + struct nf_addrinfo *internal_res = (struct nf_addrinfo *)platform_malloc(sizeof(struct nf_addrinfo)); + internal_res->res.ai_addr = &internal_res->sa; + + if (servname != 0) + { + if ((*servname > ' ') && (*servname < 0x7e)) + { + for (int q = 0; q < 16; q++) + { + printk ("%x ", *(servname + q)); + } + printk ("\n"); + } + else + printk ("servname unreadable %p\n", servname); + } + else + printk ("servname zero\n"); + + //printk ("server >%s<\n", servname); + //printk("addr internal_res %x\n", (uint32_t)internal_res); + + // Fetch the zsock version + rc = getaddrinfo(nodename, servname, &ai, &internal_res->z_res); + if (rc == 0) + { + // Copy the zsock data to the SOCK_addrinfo data + rep_zsockaddr_to_sockaddr(internal_res->z_res, &internal_res->res); + *res = (SOCK_addrinfo *)internal_res; + printk("addr res %s \n", ipaddr2str((uint32_t)(*res)->ai_addr->sa_data)); + } + last_sock_error = errno; + return rc; +} +void HAL_SOCK_freeaddrinfo(struct SOCK_addrinfo *ai) +{ + NATIVE_PROFILE_PAL_NETWORK(); + + // First, have the stack release it's block + freeaddrinfo(((struct nf_addrinfo *)ai)->z_res); + + // Now, release ours. + platform_free(ai); +} +int HAL_SOCK_ioctl(SOCK_SOCKET socket, int cmd, int *data) +{ + NATIVE_PROFILE_PAL_NETWORK(); + int rc = -1; + int flags; + printk("ioctl sock %d cmd 0x%x \n", socket, cmd); + switch ((uint32_t)cmd) + { + case SOCK_FIONBIO: + printk("Set blocking %d\n", *data); + flags = fcntl(socket, F_GETFL, 0); + + if (*data == 1) + { + fcntl(socket, F_SETFL, flags | (int)O_NONBLOCK); + } + else + { + fcntl(socket, F_SETFL, flags & ~(int)O_NONBLOCK); + } + rc = 0; + break; + case SOCK_FIONREAD: + printk("SOCK_FIONREAD "); + // Fake this ioctl by peeking at socket and seeing how + // much data returned. This is non-optimal but should work. + rc = GetAvailBytes (socket); + *data = rc; + break; + default: + printk("**********************************\n"); + printk("******* ERROR unsupported HAL_SOCK_ioct cmd %d\n", cmd); + printk("**********************************\n"); + last_sock_error = errno; + break; + } + return rc; +} +//static char tmpbuf[256]; +static char tmpbuf[1520]; +int GetAvailBytes (SOCK_SOCKET socket) +{ + int rc; + printk ("GetAvailBytes soc %d available:", socket); + rc = recv(socket, tmpbuf, sizeof(tmpbuf), MSG_DONTWAIT | MSG_PEEK); + if (rc >= 0) + { + printk("%d bytes\n", rc); + last_sock_error = 0; + } + else + { + if (errno == EAGAIN) + { + printk("0 bytes\n"); + rc = 0; + last_sock_error = 0; + } + else + { + printk("\n error %d %d\n", rc, errno); + last_sock_error = errno; + } + } + return rc; +} + +static int GetNativeError(int error) +{ + NATIVE_PROFILE_PAL_NETWORK(); + int ret; + + switch (error) + { + case EINTR: + ret = SOCK_EINTR; + break; + + case EACCES: + ret = SOCK_EACCES; + break; + + case EFAULT: + ret = SOCK_EFAULT; + break; + + case EINVAL: + ret = SOCK_EINVAL; + break; + + case EMFILE: + ret = SOCK_EMFILE; + break; + + case EAGAIN: + case EBUSY: + /* case EWOULDBLOCK: same as EINPROGRESS */ + case EINPROGRESS: + ret = SOCK_EWOULDBLOCK; + break; + + case EALREADY: + ret = SOCK_EALREADY; + break; + + case ENOTSOCK: + ret = SOCK_ENOTSOCK; + break; + + case EDESTADDRREQ: + ret = SOCK_EDESTADDRREQ; + break; + + case EMSGSIZE: + ret = SOCK_EMSGSIZE; + break; + + case EPROTOTYPE: + ret = SOCK_EPROTOTYPE; + break; + + case ENOPROTOOPT: + ret = SOCK_ENOPROTOOPT; + break; + + case EPROTONOSUPPORT: + ret = SOCK_EPROTONOSUPPORT; + break; + // TODO nanoframework check why missing + // case ESOCKTNOSUPPORT: + // ret = SOCK_ESOCKTNOSUPPORT; + // break; + + case EPFNOSUPPORT: + ret = SOCK_EPFNOSUPPORT; + break; + + case EAFNOSUPPORT: + ret = SOCK_EAFNOSUPPORT; + break; + + case EADDRINUSE: + ret = SOCK_EADDRINUSE; + break; + + case EADDRNOTAVAIL: + ret = SOCK_EADDRNOTAVAIL; + break; + + case ENETDOWN: + ret = SOCK_ENETDOWN; + break; + + case ENETUNREACH: + ret = SOCK_ENETUNREACH; + break; + + case ENETRESET: + ret = SOCK_ENETRESET; + break; + + case ECONNABORTED: + ret = SOCK_ECONNABORTED; + break; + + case ECONNRESET: + ret = SOCK_ECONNRESET; + break; + + case ENOBUFS: + case ENOMEM: + ret = SOCK_ENOBUFS; + break; + + case EISCONN: + ret = SOCK_EISCONN; + break; + + case ENOTCONN: + ret = SOCK_EISCONN; + break; + +#if !defined(__GNUC__) // same as ENOTSOCK for GCC + case ESHUTDOWN: + ret = SOCK_ESHUTDOWN; + break; +#endif + + case ETIMEDOUT: + ret = SOCK_ETIMEDOUT; + break; + + case ECONNREFUSED: + ret = SOCK_ECONNREFUSED; + break; + + case EHOSTDOWN: + ret = SOCK_EHOSTDOWN; + break; + + case EHOSTUNREACH: + ret = SOCK_EHOSTUNREACH; + break; + + case ENODATA: + ret = SOCK_NO_DATA; + break; + + default: + ret = error; + break; + } + + return (ret); +} + +int HAL_SOCK_getlasterror() +{ + NATIVE_PROFILE_PAL_NETWORK(); + int rc = GetNativeError(last_sock_error); + printk("last error %d xlate: %d\n", last_sock_error, rc); + return rc; +} +int HAL_SOCK_getsocklasterror(SOCK_SOCKET socket) +{ + NATIVE_PROFILE_PAL_NETWORK(); + return HAL_SOCK_getlasterror(); +} + +static int MARSHAL_SOCK_FDSET_TO_FDSET(SOCK_fd_set *sf, fd_set *f) +{ + if (f != NULL && sf != NULL) + { + FD_ZERO(f); + + for (unsigned int i = 0; i < sf->fd_count; i++) + { + FD_SET(sf->fd_array[i], f); + } + return sf->fd_count; + } + + return 0; +} + +static void MARSHAL_FDSET_TO_SOCK_FDSET(SOCK_fd_set *sf, fd_set *f) +{ + if (sf != NULL && f != NULL) + { + int cnt = sf->fd_count; + sf->fd_count = 0; + for (int i = 0; i < cnt; i++) + { + if (FD_ISSET(sf->fd_array[i], f)) + { + sf->fd_array[sf->fd_count] = sf->fd_array[i]; + sf->fd_count++; + } + } + } +} + +int HAL_SOCK_select( + int nfds, + SOCK_fd_set *readfds, + SOCK_fd_set *writefds, + SOCK_fd_set *except, + const struct SOCK_timeval *timeout) +{ + (void)nfds; + + NATIVE_PROFILE_PAL_NETWORK(); + int ret = 0; + fd_set read; + fd_set write; + fd_set excpt; + + fd_set *pR = (readfds != NULL) ? &read : NULL; + fd_set *pW = (writefds != NULL) ? &write : NULL; + fd_set *pE = (except != NULL) ? &excpt : NULL; + + int r = 0, w = 0, e = 0; + if (readfds != 0) + r += readfds->fd_count; + if (writefds != 0) + w += writefds->fd_count; + if (except != 0) + e += except->fd_count; + if (r || w || e) + { + printk("select: r %d w %d e %d ", r, w, e); + if (timeout != 0) + printk("no wait "); + else + printk("wait "); + } + + // // If the network goes down then we should alert any pending socket actions + // if (except != NULL && except->fd_count > 0) + // { + // struct netif *networkInterface = + // netif_find_interface(g_LWIP_SOCKETS_Driver.m_interfaces[0].m_interfaceNumber); + + // if (networkInterface != NULL) + // { + // if (!netif_is_up(networkInterface)) + // { + // if (readfds != NULL) + // readfds->fd_count = 0; + // if (writefds != NULL) + // writefds->fd_count = 0; + + // last_sock_error = ENETDOWN; + + // return exceptfds->fd_count; + // } + // } + // } + + MARSHAL_SOCK_FDSET_TO_FDSET(readfds, pR); + MARSHAL_SOCK_FDSET_TO_FDSET(writefds, pW); + MARSHAL_SOCK_FDSET_TO_FDSET(except, pE); + + // int max_sd = MEMP_NUM_NETCONN; + int max_sd = CONFIG_NET_MAX_CONN; + + // developer note: + // our declaration of SOCK_timeval is dependent of "long" type which is platform dependent + // so it's not safe to cast it to "timeval" + timeval timeoutCopy; + timeoutCopy.tv_sec = timeout->tv_sec; + timeoutCopy.tv_usec = timeout->tv_usec; + + bool noblock = false; + if ((timeout->tv_sec == 0) && (timeout->tv_usec == 0)) + noblock = true; + + if (noblock) + { + // if (to_first) + // { + // // schedule work func. + // k_work_init_delayable(&select_delayed_work, select_delayed_work_fn); + // to_first = false; + // } + } + + ret = select(max_sd, pR, pW, pE, &timeoutCopy); + printk("select returned %d %d\n", ret, errno); + + // ENOBUFS=119 + // EAGAIN=11 + if (noblock && (ret == 0) && ((errno == 119) || (errno == 11))) + { + // printk ("Scheduling delayed work.\n"); + // k_work_reschedule(&select_delayed_work, K_MSEC(1000)); + } + + MARSHAL_FDSET_TO_SOCK_FDSET(readfds, pR); + MARSHAL_FDSET_TO_SOCK_FDSET(writefds, pW); + MARSHAL_FDSET_TO_SOCK_FDSET(except, pE); + printk ("HAL_SOCK_select-- ret %d\n", ret); + return ret; +} +int translate_opt_net_to_z(int *level, int *netopt) +{ + int rc = 0; + if (*level == 0xffff) //.net socket level + { + *level = SOL_SOCKET; + } + else if (*level == 6) + { + // See if 'debug' option + if (*netopt == 1) + { + printk("********** setsockopt: TCP / Debug option unsupported but fake it.\n"); + return -2; // Ignore + } + + printk("********** setsockopt: TCP level unsupported\n"); + return -1; + } + else + { + printk("********** setsockopt: Unknown level %d\n", *level); + return -1; + } + if (*level == SOL_SOCKET) + { + switch (*netopt) + { + case 4: // reuse addr + *netopt = SO_REUSEADDR; + break; + + // Not supported in zephyr + case 8: // keepAlive + printk("Opt 8 (keepalive) not supported\n"); + rc = -2; // Ignore + break; + + case 1: // NoDelay + printk("Opt 1 (NoDelay) not supported\n"); + rc = -2; // Ignore + break; + + default: + printk("********** setsockopt: Unknown option %d\n", *netopt); + rc = -1; + break; + } + } + return rc; +} +int HAL_SOCK_setsockopt(SOCK_SOCKET socket, int level, int optname, const char *optval, int optlen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("setsockopt++ sock %d level %x optname %d len %d\n", socket, level, optname, optlen); + int org_level, org_optname; + org_level = level; + org_optname = optname; + // Translate to something zephyr understands. + int rc = translate_opt_net_to_z(&level, &optname); + if (rc == 0) + { + rc = setsockopt(socket, level, optname, optval, optlen); + if (rc != 0) + { + printk("***** setsockopt %d %d %d fail err %d\n", socket, level, optname, errno); + last_sock_error = errno; + } + } + else if (rc == -2) + { + return 0; + } + else + { + printk("***** Error. Unknown translation lev 0x%x opt:%d\n", org_level, org_optname); + } + return rc; +} +int HAL_SOCK_getsockopt(SOCK_SOCKET socket, int level, int optname, char *optval, int *optlen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("HAL_SOCK_getsockopt++ sock %d level %d optname %d\n", socket, level, optname); + int rc = getsockopt(socket, level, optname, optval, (unsigned int *)optlen); + if (rc != 0) + { + printk(" ********* getsockopt failure %d level %d opt %d\n", rc, level, optname); + last_sock_error = errno; + } + return rc; +} +int HAL_SOCK_getpeername(SOCK_SOCKET socket, struct SOCK_sockaddr *name, int *namelen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + int rc; + printk("HAL_SOCK_getpeername %d \n", socket); + + // Translate address into something zephyr knows about + struct sockaddr addr; + memset(&addr, 0, sizeof(addr)); + uint32_t len = sizeof(addr); + addr.sa_family = AF_UNSPEC; + rc = getpeername(socket, &addr, &len); + if (rc == 0) + { + name->sa_family = z_family_2net(addr.sa_family); + memcpy(&name->sa_data, &addr.data, sizeof(name->sa_data)); + } + else + { + last_sock_error = errno; + printk("Error callling getpeername rc %d errno %d\n", rc, last_sock_error); + } + return rc; +} +int HAL_SOCK_getsockname(SOCK_SOCKET socket, struct SOCK_sockaddr *name, int *namelen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + + // Translate address into something zephyr knows about + struct sockaddr addr; + return getsockname(socket, net_saddr_2z(name, &addr), (unsigned int *)namelen); +} +int HAL_SOCK_recvfrom(SOCK_SOCKET s, char *buf, int len, int flags, struct SOCK_sockaddr *from, int *fromlen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + + // Translate address into something zephyr knows about + struct sockaddr addr; + return recvfrom(s, buf, len, flags, net_saddr_2z(from, &addr), (unsigned int *)fromlen); +} +int HAL_SOCK_sendto(SOCK_SOCKET s, const char *buf, int len, int flags, const struct SOCK_sockaddr *to, int tolen) +{ + NATIVE_PROFILE_PAL_NETWORK(); + + // Translate address into something zephyr knows about + struct sockaddr addr; + return sendto(s, buf, len, flags, net_saddr_2z(to, &addr), (unsigned int)tolen); +} + +HRESULT HAL_SOCK_CONFIGURATION_LoadAdapterConfiguration( + HAL_Configuration_NetworkInterface *config, + uint32_t interfaceIndex) +{ + NATIVE_PROFILE_PAL_NETWORK(); + // return LWIP_SOCKETS_Driver::LoadAdapterConfiguration(config, interfaceIndex); + // printk ("**********************************\n"); + // printk ("HAL_SOCK_CONFIGURATION_LoadAdapterConfiguration NOT IMPLIMENTED\n"); + // printk ("**********************************\n"); + + if (ConfigurationManager_GetConfigurationBlock(config, DeviceConfigurationOption_Network, interfaceIndex)) + { + return 0; + } + return -1; +} + +HRESULT HAL_SOCK_CONFIGURATION_UpdateAdapterConfiguration( + HAL_Configuration_NetworkInterface *config, + uint32_t interfaceIndex, + uint32_t updateFlags) +{ + NATIVE_PROFILE_PAL_NETWORK(); + // printk ("**********************************\n"); + // printk ("HAL_SOCK_CONFIGURATION_UpdateAdapterConfiguration NOT IMPLIMENTED\n"); + // printk ("**********************************\n"); + // return LWIP_SOCKETS_Driver::UpdateAdapterConfiguration(interfaceIndex, updateFlags, config); + + if (ConfigurationManager_UpdateConfigurationBlock(config, DeviceConfigurationOption_Network, interfaceIndex)) + { + return 0; + } + return -1; +} + +HRESULT HAL_SOCK_CONFIGURATION_Link_status(uint32_t interfaceIndex, bool *status) +{ + NATIVE_PROFILE_PAL_NETWORK(); + // printk ("HAL_SOCK_CONFIGURATION_Link_status++ interface %d\n", interfaceIndex); + if (connect_state == CONN_STATE_DISCONNECTED) + { + *status = false; + } + else + { + *status = true; + } + return S_OK; +} + +HRESULT HAL_SOCK_IPAddressFromString(const char *ipString, uint64_t *address) +{ + NATIVE_PROFILE_PAL_NETWORK(); + + // printk ("HAL_SOCK_IPAddressFromString++\n"); + int rc = inet_pton(AF_INET, ipString, address); + if (rc == 0) + return S_OK; + return -1; +} +static char *str; +const char *HAL_SOCK_IPAddressToString(uint32_t address) +{ + NATIVE_PROFILE_PAL_NETWORK(); + printk("HAL_SOCK_IPAddressToString++ %x\n", address); + static char buff[INET_ADDRSTRLEN] = {0}; +#if 0 + return inet_ntop(AF_INET, (const void *)&address, buff, sizeof (buff)); +#else + { + str = inet_ntop(AF_INET, (const void *)&address, buff, sizeof(buff)); + printk("inet_ntop ret >%s<\n", str); + return str; + } +#endif +} + +void HAL_SOCK_EventsSet(uint32_t events) +{ + NATIVE_PROFILE_PAL_NETWORK(); + ASSERT((events == SOCKET_EVENT_FLAG_SOCKET) || (events == SOCKET_EVENT_FLAG_SOCKETS_READY)); + + Events_Set(SYSTEM_EVENT_FLAG_SOCKET); +} + +void *HAL_SOCK_GlobalLockContext() +{ + NATIVE_PROFILE_PAL_NETWORK(); + return NULL; +} +int signal_nf_stack(void) +{ + printk ("Signal NF Stack++\n"); + Events_Set(SYSTEM_EVENT_FLAG_NETWORK); + return 0; +} \ No newline at end of file diff --git a/targets/Nordic/_netCellular/nrf9160_lte.c b/targets/Nordic/_netCellular/nrf9160_lte.c new file mode 100644 index 0000000000..719426e566 --- /dev/null +++ b/targets/Nordic/_netCellular/nrf9160_lte.c @@ -0,0 +1,501 @@ +/* + * Copyright (c) Ericsson AB 2020, all rights reserved + ++CGCONTRDP: 0,,"internet.cxn","","","193.181.246.58","193.181.246.57",,,,,1500 + */ + +#include +#include +#include +#include +//#include +#include + +#include + +#include +#include +#include + +#include + +//#include +//#include + +int signal_nf_stack(void); + +BUILD_ASSERT( + !IS_ENABLED(CONFIG_LTE_AUTO_INIT_AND_CONNECT), + "The nrf9160_lte library does not support LTE auto-init and connect"); + +static struct k_work_delayable connect_work; + +void lte_evt_handler(const struct lte_lc_evt *const evt); + +static int query_modem(const char *cmd, char *buf, size_t buf_len); +int nrf9160_lte_connect(uint16_t timeout); +int get_ip_info(uint32_t *ip_addr, uint32_t *dns1, uint32_t *dns2); + +#if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) +/* Certificate for TLS */ +static const char cert[] = { +#include "cert/GlobalSign-Root-CA-R2" +}; + +BUILD_ASSERT(sizeof(cert) < KB(4), "Certificate too large"); + +int cert_provision(void); + +#endif // CONFIG_NET_SOCKETS_SOCKOPT_TLS + +int handle_new_connection(int); + +//static struct modem_param_info modem_param; + +bool fconnected = false; +char szIMEI[IMxI_LEN]; +char szModemVer[FW_VER_LEN]; + +uint32_t ip4_addr; +uint32_t ip4_dns1_addr; +uint32_t ip4_dns2_addr; + +char connect_state = CONN_STATE_DISCONNECTED; + +// struct lte_defs defs; +/* + * nrf9160_lte_init - Initialize LTE and connect with the network. + */ +int nrf9160_lte_init(uint16_t timeout) +{ + int rc; + + // Init the Nordic LTE library + rc = lte_lc_init(); + +#if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) + /* Provision certificates before connecting to the LTE network */ + rc = cert_provision(); + if (rc) + { + printk("***********************************************\n"); + printk("Failed to privision TLS cert. %d\nLTE init failed.\n", rc); + printk("***********************************************\n"); + return -1; + } + +#endif // CONFIG_NET_SOCKETS_SOCKOPT_TLS + + rc = nrf9160_lte_connect(timeout); + if (rc != 0) + { + printk("nrf9160_lte_connect fail. rc %d\n", rc); + } + return rc; +} + +/* + * handles events from the LTE lib + */ +void lte_evt_handler(const struct lte_lc_evt *const evt) +{ + char sz[128]; + bool flag_error = false; + switch (evt->type) + { + case LTE_LC_EVT_NW_REG_STATUS: + strcpy(sz, "******* "); + switch (evt->nw_reg_status) + { + case LTE_LC_NW_REG_NOT_REGISTERED: + strcat(sz, "Not Registered"); + if (fconnected) + { + fconnected = false; + connect_state = CONN_STATE_DISCONNECTED; + // TODO:: Notify of disconnect. + } + break; + case LTE_LC_NW_REG_REGISTERED_HOME: + strcat(sz, "Registered Home"); + if (!fconnected) + { + fconnected = true; + connect_state = CONN_STATE_CONN_HOME; + // TODO:: Notify of connect. + k_work_schedule(&connect_work, K_NO_WAIT); + //handle_new_connection (0); + } + break; + case LTE_LC_NW_REG_SEARCHING: + strcat(sz, "Searching.."); + break; + case LTE_LC_NW_REG_REGISTRATION_DENIED: + strcat(sz, "Registration denied"); + flag_error = true; + fconnected = false; + break; + case LTE_LC_NW_REG_UNKNOWN: + strcat(sz, "Registration unknown"); + break; + case LTE_LC_NW_REG_REGISTERED_ROAMING: + strcat(sz, "Registered Roaming"); + if (!fconnected) + { + fconnected = true; + connect_state = CONN_STATE_CONN_HOME; + // TODO:: Notify of connect. + k_work_schedule(&connect_work, K_NO_WAIT); + } + break; + case LTE_LC_NW_REG_REGISTERED_EMERGENCY: + strcat(sz, "Registered Emergency"); + flag_error = true; + break; + case LTE_LC_NW_REG_UICC_FAIL: + strcat(sz, "UICC Fail"); + flag_error = true; + fconnected = false; + break; + default: + strcat(sz, "Unknown network status"); + break; + } + if (flag_error) + { + printk("!!!!!! %s. !!!!!!\n", sz); + } + else + { + printk("%s.\n", sz); + } + break; + + break; + default: + break; + } +} +/* + * date_time sync stuff. + */ +#ifdef CONFIG_DATE_TIME +#define DATE_TIME_TIMEOUT_S 10 +K_SEM_DEFINE(date_time_obtained, 0, 1); +/* + * date_time_event_handler - callback function recording time query + */ +static void date_time_event_handler(const struct date_time_evt *evt) +{ + switch (evt->type) + { + case DATE_TIME_OBTAINED_MODEM: + printk("date_time obtained (modem)\n"); + break; + case DATE_TIME_OBTAINED_NTP: + printk("date_time obtained (ntp)\n"); + break; + case DATE_TIME_OBTAINED_EXT: + printk("date_time obtained (ext)\n"); + break; + case DATE_TIME_NOT_OBTAINED: + printk("date_time read failed\n"); + break; + default: + break; + } + + /** Do not depend on obtained time, continue upon any event from the + * date time library. + */ + k_sem_give(&date_time_obtained); +} +#endif +/* + * Triggered by the LTE status callback when a connection is detected. + */ +static void connect_work_fn(struct k_work *work) +{ + int rc = -1; + printk("LTE Network connected.\n"); + + // Get the IP addresses + rc = get_ip_info(&ip4_addr, &ip4_dns1_addr, &ip4_dns2_addr); + //printk ("get_ip_info returned %x %x %x\n", ip4_addr, ip4_dns1_addr, ip4_dns2_addr); + +#ifdef CONFIG_DATE_TIME + date_time_update_async(date_time_event_handler); + // printk("Waiting for date_time..."); + // rc = k_sem_take(&date_time_obtained, K_SECONDS(DATE_TIME_TIMEOUT_S)); + // if (rc) + // { + // printk("Date time, no callback event within %d seconds\n", DATE_TIME_TIMEOUT_S); + // } +#endif + signal_nf_stack(); + return; +} + +// /* +// * collect_modem_info - Collects connection info and writes to the database +// */ +// static int collect_modem_info(int attempts, int wait_interval) +// { +// int rc = -1; + +// printk("Get modem parameters\n"); +// rc = modem_info_params_get(&modem_param); +// while ((rc < 0) && (attempts-- > 0)) +// { +// k_sleep(K_MSEC(wait_interval)); +// printk("Get modem parameters re-attempt\n"); +// rc = modem_info_params_get(&modem_param); +// } +// if (rc < 0) +// { +// printk("Unable to obtain all modem parameters: %d\n", rc); +// } +// return rc; +// } + +int comma_parse (char *buf, int inlen, int find_comma, char *outbuf, int outlen) +{ + int i, j, k = 0, rc = 0; + int comma_cnt = 0; + +// printk ("comma_parse++ %d >%s<\n", find_comma, buf); + + for (i = 0; (i < inlen) && (rc == 0); i++) + { + if (buf[i] == '\0') + { + rc = -1; + break; + } + if (buf[i] == ',') + { + comma_cnt++; + // printk ("Comma at %d\n", i); + } + if (comma_cnt == find_comma) + { + // We expect the string to have a starting quote. + if (buf[i + 1] != '\"') + { + //printk("i %d char %c\n", i, buf[i + 1]); + rc = -2; + } + // Find closing quote + for (j = i + 2; j < inlen; j++) + { + // Unexpected end of input buf + if (buf[j] == '\0') + { + rc = -3; + break; + } + // Found closing quote. + if (buf[j] == '\"') + { + outbuf[k] = '\0'; // zero terminate + rc = k; // Copy length + break; + } + else + { + // Copy char if room. + if (k >= outlen - 1) + { + outbuf[k] = '\0'; + rc = -4; + break; + } + outbuf[k++] = buf[j]; + } + } + } + } + // printk ("comma_parse-- %d", rc); + // if (rc > 0) + // printk (">%s<\n", outbuf); + // else + // printk ("\n"); + return rc; +} +/* + * +CGPADDR: 1,"10.0.0.130","1050:0000:0000:0000:0005:0600:300c:326b" + * +CGCONTRDP: 0,,"ibasis.iot","","","216.168.184.184","62.93.146.209",,,,,1430 + */ +int get_ip_info(uint32_t *ip_addr, uint32_t *dns1, uint32_t *dns2) +{ + int rc; + char buf[128]; + char outbuf[96]; + struct sockaddr_in sa; + + *ip_addr = 0; + *dns1 = 0; + *dns2 = 0; + + // First, convert IP address. + memset (buf, 0, sizeof (buf)); + // Use specific cmd to get the IP addresses + rc = query_modem("AT+CGPADDR=0", buf, sizeof(buf)); + //printk ("query_modem ret %d >%s<\n", rc, buf); + if (rc == 0) + { + //printk ("IP addr: %s\n", buf); + rc = comma_parse (buf, strlen (buf), 1, outbuf, sizeof (outbuf)); + if (rc > 0) + { + rc = inet_pton(AF_INET, outbuf, &sa.sin_addr); + if (rc) + { + *ip_addr = sa.sin_addr.s_addr; + printk("device ip: %x\n", *ip_addr); + } + } + } + else + { + printk ("Failed to get ip address from modem. %d\n", rc); + } + // Now use cmd to get the DNS addresses + rc = query_modem("AT+CGCONTRDP=0", buf, sizeof(buf)); + if (rc == 0) + { + //printk ("modem string: %s\n", buf); + // DNS 1 + rc = comma_parse (buf, strlen (buf), 5, outbuf, sizeof (outbuf)); + if (rc > 0) + { + rc = inet_pton(AF_INET, outbuf, &sa.sin_addr); + if (rc) + *dns1 = sa.sin_addr.s_addr; + } + // DNS 2 + rc = comma_parse (buf, strlen (buf), 6, outbuf, sizeof (outbuf)); + if (rc > 0) + { + rc = inet_pton(AF_INET, outbuf, &sa.sin_addr); + if (rc) + *dns2 = sa.sin_addr.s_addr; + } + } + else + { + printk("Failed to read DNS %d\n", rc); + } + return rc; +} + +/* + * nrf9160_lte_connect - Connect to the network. + */ +int nrf9160_lte_connect(uint16_t timeout) +{ + int rc = 0; + k_work_init_delayable(&connect_work, connect_work_fn); + + printk("Calling lte_lc_connect_async\n"); + rc = lte_lc_connect_async(lte_evt_handler); + return rc; +} + +#if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) +/* Provision certificate to modem */ +int cert_provision(void) +{ + int rc; + bool exists; + + rc = modem_key_mgmt_exists(TLS_SEC_TAG, MODEM_KEY_MGMT_CRED_TYPE_CA_CHAIN, &exists); + if (rc) + { + printk("Failed to check for certificates rc %d\n", rc); + return rc; + } + + if (exists) + { + /* For the sake of simplicity we delete what is provisioned + * with our security tag and reprovision our certificate. + */ + rc = modem_key_mgmt_delete(TLS_SEC_TAG, MODEM_KEY_MGMT_CRED_TYPE_CA_CHAIN); + if (rc) + { + printk("Failed to delete existing certificate, rc %d\n", rc); + } + } + + printk("Provisioning certificate\n"); + + /* Provision certificate to the modem */ + rc = modem_key_mgmt_write(TLS_SEC_TAG, MODEM_KEY_MGMT_CRED_TYPE_CA_CHAIN, cert, sizeof(cert) - 1); + if (rc) + { + printk("Failed to provision certificate, rc %d\n", rc); + return rc; + } + return 0; +} + +#endif // CONFIG_NET_SOCKETS_SOCKOPT_TLS +/* + * remove_whitespace - helper for query_modem below. + */ +static int remove_whitespace(char *buf) +{ + size_t i, j = 0, len; + + len = strlen(buf); + for (i = 0; i < len; i++) + { + if (buf[i] >= 32 && buf[i] <= 126) + { + if (j != i) + { + buf[j] = buf[i]; + } + j++; + } + } + if (j < len) + { + buf[j] = '\0'; + } + + return 0; +} +/* + * query_modem - simpler way to send a cmd to the modem. + */ +static int query_modem(const char *cmd, char *buf, size_t buf_len) +{ + int rc; + rc = nrf_modem_at_cmd(buf, buf_len, cmd); + if (rc) + { + printk("nrf_modem_at_cmd [%s] error:%d\n", cmd, rc); + return rc; + } + + remove_whitespace(buf); + return 0; +} + +/* + * nrf9160_lte_offline - Disconnect from the network. + */ +int nrf9160_lte_offline(void) +{ + return lte_lc_offline(); +} +/* + * nrf9160_lte_power_off - Turn off the modem. + */ +int nrf9160_lte_power_off(void) +{ + // TODO: check this is signaled by LTE callback. + return lte_lc_power_off(); +} diff --git a/targets/Nordic/_netCellular/socket_api.cpp b/targets/Nordic/_netCellular/socket_api.cpp new file mode 100644 index 0000000000..2c19a84b49 --- /dev/null +++ b/targets/Nordic/_netCellular/socket_api.cpp @@ -0,0 +1,735 @@ +// +// Copyright (c) .NET Foundation and Contributors +// Portions Copyright (c) Microsoft Corporation. All rights reserved. +// See LICENSE file in the project root for full license information. +// + +// Need this until 9160 supports getpeeraddr +#define PERRADDR_WORKAROUND 1 + +#include "sockets_nrf9160.h" + +//--// +// TODO: Check stack size. +static K_THREAD_STACK_DEFINE(sock_thread_stack, 1024); +static struct k_thread sock_thread_data; + +Sockets_nrf9160_Driver g_Sockets_nrf9160_Driver; + +SOCK_SOCKET SOCK_socket(int family, int type, int protocol) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Socket(family, type, protocol, FALSE); +} +int SOCK_bind(SOCK_SOCKET socket, const struct SOCK_sockaddr *address, int addressLen) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_bind(socket, address, addressLen); +} +int SOCK_connect(SOCK_SOCKET socket, const struct SOCK_sockaddr *address, int addressLen) +{ + NATIVE_PROFILE_PAL_COM(); + int rc; + rc = Sockets_nrf9160_Driver::Connect(socket, address, addressLen); + return rc; +} +int SOCK_send(SOCK_SOCKET socket, const char *buf, int len, int flags) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Send(socket, buf, len, flags); +} +int SOCK_recv(SOCK_SOCKET socket, char *buf, int len, int flags) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Recv(socket, buf, len, flags); +} +int SOCK_close(SOCK_SOCKET socket) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Close(socket); +} +int SOCK_listen(SOCK_SOCKET socket, int backlog) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Listen(socket, backlog); +} +SOCK_SOCKET SOCK_accept(SOCK_SOCKET socket, struct SOCK_sockaddr *address, int *addressLen) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Accept(socket, address, addressLen, FALSE); +} +int SOCK_shutdown(SOCK_SOCKET socket, int how) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_shutdown(socket, how); +} +int SOCK_getaddrinfo( + const char *nodename, + char *servname, + const struct SOCK_addrinfo *hints, + struct SOCK_addrinfo **res) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_getaddrinfo(nodename, servname, hints, res); +} +void SOCK_freeaddrinfo(struct SOCK_addrinfo *ai) +{ + NATIVE_PROFILE_PAL_COM(); + HAL_SOCK_freeaddrinfo(ai); +} +int SOCK_ioctl(SOCK_SOCKET socket, int cmd, int *data) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_ioctl(socket, cmd, data); +} +int SOCK_getlasterror() +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_getlasterror(); +} +int SOCK_getsocklasterror(SOCK_SOCKET socket) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_getsocklasterror(socket); +} +int SOCK_select( + int nfds, + SOCK_fd_set *readfds, + SOCK_fd_set *writefds, + SOCK_fd_set *except, + const struct SOCK_timeval *timeout) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Select(nfds, readfds, writefds, except, timeout); +} +int SOCK_setsockopt(SOCK_SOCKET socket, int level, int optname, const char *optval, int optlen) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_setsockopt(socket, level, optname, optval, optlen); +} +int SOCK_getsockopt(SOCK_SOCKET socket, int level, int optname, char *optval, int *optlen) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_getsockopt(socket, level, optname, optval, optlen); +} +int SOCK_getpeername(SOCK_SOCKET socket, struct SOCK_sockaddr *name, int *namelen) +{ + NATIVE_PROFILE_PAL_COM(); + int rc; +#ifdef PERRADDR_WORKAROUND + //printk("getpeername workaround\n"); + rc = g_Sockets_nrf9160_Driver.GetSocketAddrData(socket, name, namelen); + if (rc) + printk("### GetSocketAddrData ret %d\n", rc); +#else + rc = HAL_SOCK_getpeername(socket, name, namelen); +#endif + return rc; +} +int SOCK_getsockname(SOCK_SOCKET socket, struct SOCK_sockaddr *name, int *namelen) +{ + NATIVE_PROFILE_PAL_COM(); + return HAL_SOCK_getsockname(socket, name, namelen); +} +int SOCK_recvfrom(SOCK_SOCKET s, char *buf, int len, int flags, struct SOCK_sockaddr *from, int *fromlen) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::RecvFrom(s, buf, len, flags, from, fromlen); +} +int SOCK_sendto(SOCK_SOCKET s, const char *buf, int len, int flags, const struct SOCK_sockaddr *to, int tolen) +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::SendTo(s, buf, len, flags, to, tolen); +} + +bool Network_Initialize() +{ + NATIVE_PROFILE_PAL_COM(); + return Sockets_nrf9160_Driver::Initialize(); +} + +bool Network_Uninitialize() +{ + NATIVE_PROFILE_PAL_COM(); + + return Sockets_nrf9160_Driver::Uninitialize(); +} + +void SOCKETS_CloseConnections() +{ + NATIVE_PROFILE_PAL_COM(); + Sockets_nrf9160_Driver::CloseConnections(FALSE); +} + +HRESULT SOCK_CONFIGURATION_LoadAdapterConfiguration(HAL_Configuration_NetworkInterface *config, uint32_t interfaceIndex) +{ + NATIVE_PROFILE_PAL_COM(); + // printk ("SOCK_CONFIGURATION_LoadAdapterConfiguration++ %d\n", interfaceIndex); + + return HAL_SOCK_CONFIGURATION_LoadAdapterConfiguration(config, interfaceIndex); +} + +HRESULT SOCK_CONFIGURATION_UpdateAdapterConfiguration( + HAL_Configuration_NetworkInterface *config, + uint32_t interfaceIndex, + uint32_t updateFlags) +{ + NATIVE_PROFILE_PAL_COM(); + HRESULT hr = S_OK; + bool success = FALSE; + + const uint32_t c_reInitFlag = NetworkInterface_UpdateOperation_Dhcp | NetworkInterface_UpdateOperation_DhcpRenew | + NetworkInterface_UpdateOperation_Mac; + + const uint32_t c_uninitFlag = c_reInitFlag | NetworkInterface_UpdateOperation_DhcpRelease; + + if (0 != (updateFlags & c_uninitFlag)) + { + success = SOCKETS_DbgUninitialize(COM_SOCKET_DBG); + } + + hr = HAL_SOCK_CONFIGURATION_UpdateAdapterConfiguration(config, interfaceIndex, updateFlags); + + if (!SUCCEEDED(hr)) + { + return S_FALSE; + } + + if (0 != (updateFlags & c_reInitFlag)) + { + if (success) + SOCKETS_DbgInitialize(COM_SOCKET_DBG); + } + + return hr; +} + +HRESULT SOCK_CONFIGURATION_LoadConfiguration(HAL_Configuration_NetworkInterface *config, uint32_t interfaceIndex) +{ + NATIVE_PROFILE_PAL_COM(); + HRESULT hr = S_OK; + + // printk ("SOCK_CONFIGURATION_LoadConfiguration++\n"); + // load current DCHP settings + hr = SOCK_CONFIGURATION_LoadAdapterConfiguration(config, interfaceIndex); + + return hr; +} + +HRESULT SOCK_CONFIGURATION_LinkStatus(uint32_t interfaceIndex, bool *status) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_CONFIGURATION_Link_status(interfaceIndex, status); +} + +HRESULT SOCK_IPAddressFromString(const char *ipString, uint64_t *address) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_IPAddressFromString(ipString, address); +} + +const char *SOCK_IPAddressToString(uint32_t address) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_IPAddressToString(address); +} + +#define SOCKET_SHUTDOWN_READ 0 +#define SOCKET_SHUTDOWN_WRITE 1 +#define SOCKET_SHUTDOWN_READ_WRITE 2 + +#define ISSET_SOCKET_FLAG(x, y) ((y) == ((y) & (x).m_flags)) +#define SET_SOCKET_FLAG(x, y) (x).m_flags |= (y) +#define CLEAR_SOCKET_FLAG(x, y) (x).m_flags &= ~(y) + +//----------------------------------------------------------------------------- +// +// CloseConnections - close all connections with the option of leaving the debugger sockets open. +// debugger sockets are left open on CLR reboot so that communication with the debugger is not +// lost. +// +//----------------------------------------------------------------------------- +void Sockets_nrf9160_Driver::CloseConnections(bool fCloseDbg) +{ + NATIVE_PROFILE_PAL_COM(); + + int32_t cnt = g_Sockets_nrf9160_Driver.m_cntSockets; + int32_t idx = 0; + + // round one - close all SSL sockets + for (int32_t i = cnt - 1; i >= 0; i--) + { + struct SocketRegisterMap &entry = g_Sockets_nrf9160_Driver.m_socketHandles[i]; + + if (entry.m_socket != SOCK_SOCKET_ERROR && entry.m_sslData != NULL) + { + SSL_CloseSocket(entry.m_socket); + } + } + + // round two - close all non-SSL sockets + cnt = g_Sockets_nrf9160_Driver.m_cntSockets; + + for (int32_t i = 0; i < cnt; i++) + { + struct SocketRegisterMap &entry = g_Sockets_nrf9160_Driver.m_socketHandles[i]; + + if (entry.m_socket != SOCK_SOCKET_ERROR) + { + if (fCloseDbg || !ISSET_SOCKET_FLAG(entry, SocketRegisterMap::c_DebugSocket)) + { + // use the HAL method so we don't unregister the socket since we handle that here + HAL_SOCK_close(entry.m_socket); + + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_socket = SOCK_SOCKET_ERROR; + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags = 0; + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_sslData = NULL; + g_Sockets_nrf9160_Driver.m_cntSockets--; + } + else if (i > 0) + { + memcpy( + &g_Sockets_nrf9160_Driver.m_socketHandles[i], + &g_Sockets_nrf9160_Driver.m_socketHandles[idx++], + sizeof(g_Sockets_nrf9160_Driver.m_socketHandles[i])); + } + } + } +} + +//--// + +SOCK_SOCKET Sockets_nrf9160_Driver::Socket(int32_t family, int32_t type, int32_t protocol, bool fDebug) +{ + NATIVE_PROFILE_PAL_COM(); + + int ret = HAL_SOCK_socket(family, type, protocol); + + if (ret != SOCK_SOCKET_ERROR) + { + RegisterSocket(ret, (protocol != SOCK_IPPROTO_TCP), fDebug); + } + return ret; +} +int Sockets_nrf9160_Driver::Connect(SOCK_SOCKET socket, const struct SOCK_sockaddr *address, int32_t addressLen) +{ + NATIVE_PROFILE_PAL_COM(); + int rc; + rc = HAL_SOCK_connect(socket, address, addressLen); +#ifdef PERRADDR_WORKAROUND + if (rc == 0) + { + printk("calling SetSocketAddrData %d %p %d\n", socket, address, addressLen); + g_Sockets_nrf9160_Driver.SetSocketAddrData(socket, address, addressLen); + } +#endif + return rc; +} +int Sockets_nrf9160_Driver::Send(SOCK_SOCKET socket, const char *buf, int32_t len, int32_t flags) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_send(socket, buf, len, flags); +} +int Sockets_nrf9160_Driver::Recv(SOCK_SOCKET socket, char *buf, int32_t len, int32_t flags) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_recv(socket, buf, len, flags); +} + +int Sockets_nrf9160_Driver::Shutdown(SOCK_SOCKET sock, int32_t how) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_shutdown(sock, how); +} + +//----------------------------------------------------------------------------- +// +// Close - The close method marks a socket to be closed by the select thread. Close is handled +// in this way because (at least for one implementation) the select method can not be set for a +// closed socket. Therfore in the select thread the socket is closed. +// +//----------------------------------------------------------------------------- +int Sockets_nrf9160_Driver::Close(SOCK_SOCKET sock) +{ + NATIVE_PROFILE_PAL_COM(); + UnregisterSocket(sock); + return HAL_SOCK_close(sock); +} +int Sockets_nrf9160_Driver::Listen(SOCK_SOCKET socket, int32_t backlog) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_listen(socket, backlog); +} +SOCK_SOCKET Sockets_nrf9160_Driver::Accept( + SOCK_SOCKET socket, + struct SOCK_sockaddr *address, + int *addressLen, + bool fDebug) +{ + NATIVE_PROFILE_PAL_COM(); + + int ret = HAL_SOCK_accept(socket, address, addressLen); + + if (ret != SOCK_SOCKET_ERROR) + { + RegisterSocket(ret, TRUE, fDebug); +#ifdef PERRADDR_WORKAROUND + g_Sockets_nrf9160_Driver.SetSocketAddrData(socket, address, *addressLen); +#endif + } + + return ret; +} + +int Sockets_nrf9160_Driver::Select( + int32_t nfds, + SOCK_fd_set *readfds, + SOCK_fd_set *writefds, + SOCK_fd_set *exceptfds, + const SOCK_timeval *timeout) +{ + NATIVE_PROFILE_PAL_COM(); + int rc; + uint32_t i; + uint32_t *sock_flgs; + + // Clean the select flags + for (i = 0; i < (uint32_t)g_Sockets_nrf9160_Driver.m_cntSockets; i++) + { + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags &= ~SocketRegisterMap::c_SelSocketMask; + } + if (readfds) + { + for (i = 0; i < readfds->fd_count; i++) + { + sock_flgs = g_Sockets_nrf9160_Driver.GetSockFlags(readfds->fd_array[i]); + if (sock_flgs) + *sock_flgs |= SocketRegisterMap::c_SelRdSocket; + } + } + if (writefds) + { + for (i = 0; i < writefds->fd_count; i++) + { + sock_flgs = g_Sockets_nrf9160_Driver.GetSockFlags(writefds->fd_array[i]); + if (sock_flgs) + *sock_flgs |= SocketRegisterMap::c_SelWrSocket; + } + } + if (exceptfds) + { + for (i = 0; i < exceptfds->fd_count; i++) + { + sock_flgs = g_Sockets_nrf9160_Driver.GetSockFlags(exceptfds->fd_array[i]); + if (sock_flgs) + *sock_flgs |= SocketRegisterMap::c_SelErSocket; + } + } + k_sem_give(&g_Sockets_nrf9160_Driver.sem_sockmon); + + rc = HAL_SOCK_select(nfds, readfds, writefds, exceptfds, timeout); + return rc; +} + +int Sockets_nrf9160_Driver::RecvFrom( + SOCK_SOCKET s, + char *buf, + int32_t len, + int32_t flags, + struct SOCK_sockaddr *from, + int *fromlen) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_recvfrom(s, buf, len, flags, from, fromlen); +} + +int Sockets_nrf9160_Driver::SendTo( + SOCK_SOCKET s, + const char *buf, + int32_t len, + int32_t flags, + const struct SOCK_sockaddr *to, + int32_t tolen) +{ + NATIVE_PROFILE_PAL_COM(); + + return HAL_SOCK_sendto(s, buf, len, flags, to, tolen); +} + +bool Sockets_nrf9160_Driver::Initialize() +{ + NATIVE_PROFILE_PAL_COM(); + SOCKET_CHECK_ENTER(); + +printk ("Sockets_nrf9160_Driver::Initialize++ %d\n", s_initialized); + if (!s_initialized) + { + +printk ("Sockets_nrf9160_Driver::Initialize 1\n"); + + g_Sockets_nrf9160_Driver.m_fShuttingDown = FALSE; + g_Sockets_nrf9160_Driver.m_cntSockets = 0; + + for (int32_t i = 0; i < SOCKETS_MAX_COUNT; i++) + { + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_socket = SOCK_SOCKET_ERROR; + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags = 0; + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_sslData = NULL; + } + k_sem_init(&g_Sockets_nrf9160_Driver.sem_sockmon, 0, 1); +printk ("Sockets_nrf9160_Driver::Initialize 2\n"); + k_thread_create( + &sock_thread_data, + sock_thread_stack, + K_THREAD_STACK_SIZEOF(sock_thread_stack), + g_Sockets_nrf9160_Driver.SockMonitorThread, + NULL, + NULL, + NULL, + K_PRIO_COOP(5), + 0, + K_NO_WAIT); + + SOCKET_CHECK_bool(HAL_SOCK_Initialize()); + + SSL_Initialize(); + + s_initialized = TRUE; + } + + SOCKET_CHECK_EXIT_bool(); +} + +// Dummy methods in case Debbuger is not installed +__nfweak void Sockets_nrf9160_Driver::Debugger_Abort() +{ +} +__nfweak void Sockets_nrf9160_Driver::Debugger_Uninitialize() +{ +} + +bool Sockets_nrf9160_Driver::Uninitialize() +{ + NATIVE_PROFILE_PAL_COM(); + bool ret = TRUE; + + if (s_initialized) + { + Debugger_Abort(); + + // close all connections (including debugger sockets) + CloseConnections(TRUE); + + SSL_Uninitialize(); + + Debugger_Uninitialize(); + + ret = HAL_SOCK_Uninitialize(); + + s_initialized = FALSE; + s_wirelessInitialized = FALSE; + s_discoveryInitialized = FALSE; + } + + return ret; +} + +//----------------------------------------------------------------------------- +// +// RegisterSocket - socket tracking. This method is used to track sockets +// opened by this driver. It does not include the fake socket. Register +// should be called after a socket is opened (via socket or accept methods). +// The selectable parameter should only be true if the socket is in the +// listening or connected state +// +//----------------------------------------------------------------------------- +void Sockets_nrf9160_Driver::RegisterSocket(SOCK_SOCKET sock, bool selectable, bool fDebug) +{ + (void)selectable; + + NATIVE_PROFILE_PAL_COM(); + if (sock == SOCK_SOCKET_ERROR) + { + ASSERT(FALSE); + return; + } + + if (g_Sockets_nrf9160_Driver.m_cntSockets >= SOCKETS_MAX_COUNT) + return; + + GLOBAL_LOCK_SOCKETS(lock); + + g_Sockets_nrf9160_Driver.m_socketHandles[g_Sockets_nrf9160_Driver.m_cntSockets].m_socket = sock; + g_Sockets_nrf9160_Driver.m_socketHandles[g_Sockets_nrf9160_Driver.m_cntSockets].m_flags = 0; + g_Sockets_nrf9160_Driver.m_socketHandles[g_Sockets_nrf9160_Driver.m_cntSockets].m_sslData = NULL; + + if (fDebug) + SET_SOCKET_FLAG( + g_Sockets_nrf9160_Driver.m_socketHandles[g_Sockets_nrf9160_Driver.m_cntSockets], + SocketRegisterMap::c_DebugSocket); + + g_Sockets_nrf9160_Driver.m_cntSockets++; + + // Signal the monitor thread about the new socket. + k_sem_give(&g_Sockets_nrf9160_Driver.sem_sockmon); +} + +//----------------------------------------------------------------------------- +// +// UnregisterSocket - No longer track a given socket for clean up and selection. +// This method should only be called immediately before closing down a socket. +// +//----------------------------------------------------------------------------- +void Sockets_nrf9160_Driver::UnregisterSocket(SOCK_SOCKET sock) +{ + int32_t index = -1; + + NATIVE_PROFILE_PAL_COM(); + GLOBAL_LOCK_SOCKETS(lock); + + g_Sockets_nrf9160_Driver.GetSocketSslData(sock, index); + + if (index == -1) + return; + + g_Sockets_nrf9160_Driver.m_cntSockets--; + + if (index != g_Sockets_nrf9160_Driver.m_cntSockets) + { + memcpy( + &g_Sockets_nrf9160_Driver.m_socketHandles[index], + &g_Sockets_nrf9160_Driver.m_socketHandles[g_Sockets_nrf9160_Driver.m_cntSockets], + sizeof(g_Sockets_nrf9160_Driver.m_socketHandles[index])); + } + + g_Sockets_nrf9160_Driver.m_socketHandles[g_Sockets_nrf9160_Driver.m_cntSockets].m_socket = SOCK_SOCKET_ERROR; + g_Sockets_nrf9160_Driver.m_socketHandles[g_Sockets_nrf9160_Driver.m_cntSockets].m_flags = 0; +} + +//----------------------------------------------------------------------------- +// +// SockMonitorThread - Thread to monitor open sockets with non-blocking +// select/poll calls. +// +//----------------------------------------------------------------------------- +void Sockets_nrf9160_Driver::SockMonitorThread(void *arg1, void *arg2, void *arg3) +{ + int rc, i, sock_cnt = 0; + struct pollfd fd[SOCKETS_MAX_COUNT]; + int r, w, e, c, b; + + printk ("**** SockMonitorThread++\n"); + + NATIVE_PROFILE_PAL_COM(); + while (true) + { + // Set poll for each socket. For now, watch everything. + r = 0, w = 0, e = 0; + sock_cnt = 0; + for (i = 0; i < g_Sockets_nrf9160_Driver.m_cntSockets; i++) + { + fd[sock_cnt].fd = g_Sockets_nrf9160_Driver.m_socketHandles[i].m_socket; + fd[sock_cnt].events = 0; + if (g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags & SocketRegisterMap::c_SelRdSocket) + { + fd[sock_cnt].events |= POLLIN; + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags &= ~SocketRegisterMap::c_SelRdSocket; + r++; + } + if (g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags & SocketRegisterMap::c_SelWrSocket) + { + fd[sock_cnt].events |= POLLOUT; + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags &= ~SocketRegisterMap::c_SelWrSocket; + w++; + } + + if (g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags & SocketRegisterMap::c_SelErSocket) + { + fd[sock_cnt].events |= POLLERR; + g_Sockets_nrf9160_Driver.m_socketHandles[i].m_flags &= ~SocketRegisterMap::c_SelErSocket; + e++; + } + + // fd[sock_cnt].events = POLLIN | POLLOUT | POLLERR; + fd[sock_cnt].revents = 0; + + if (fd[sock_cnt].events != 0) + { + sock_cnt++; + } + } + // If no socks have flags, just wait. + if (sock_cnt == 0) + { + printk ("**** SockMonitorThread zero socket wait\n"); + k_sem_reset(&g_Sockets_nrf9160_Driver.sem_sockmon); + + // Wait for a new socket + k_sem_take(&g_Sockets_nrf9160_Driver.sem_sockmon, K_FOREVER); + printk ("**** SockMonitorThread triggered\n"); + continue; + } + + // Now monitor the open sockets. + printk ("**** SockMonitorThread poll cnt:%d %d %d %d\n", g_Sockets_nrf9160_Driver.m_cntSockets, r, w, e); + rc = poll(fd, g_Sockets_nrf9160_Driver.m_cntSockets, 1000); + printk ("**** SockMonitorThread poll return %d %x ", rc, fd[0].revents); + if (rc < 0) + { + printk("poll error %d %d\n", rc, errno); + k_sleep(K_MSEC(500)); + continue; + } + // If timeout, try again. + if (rc == 0) + { + printk("\n"); + continue; + } + // Set poll for each socket. For now, watch everything. + r = w = e = c = b = 0; + for (i = 0; i < g_Sockets_nrf9160_Driver.m_cntSockets; i++) + { + if (fd[i].revents & POLLIN) + r++; + if (fd[i].revents & POLLOUT) + w++; + if (fd[i].revents & POLLERR) + e++; + if (fd[i].revents & POLLHUP) + c++; + if (fd[i].revents & POLLNVAL) + b++; + } + printk("cnt %d r %d w %d err %d close %d Inv %d\n", + g_Sockets_nrf9160_Driver.m_cntSockets, r, w, e, c, b); + // signal the nf stack. + Events_Set(SYSTEM_EVENT_FLAG_SOCKET); + + // printk ("Sockets_nrf9160_Driver::SockMonitorThread Ping stack!\n"); + // k_sleep(K_MSEC(100)); + + // k_sleep(K_MSEC(1000)); + } + printk("Sockets_nrf9160_Driver::SockMonitorThread EXIT\n"); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// weak implementations of the functions (to be replaced with _strong_ implementations if and when required) // +// C++ version +// __nfweak void debug_printf( const char* format, ... ) +// { +// return; +// } + +bool Sockets_nrf9160_Driver::s_initialized = FALSE; +bool Sockets_nrf9160_Driver::s_wirelessInitialized = FALSE; +bool Sockets_nrf9160_Driver::s_discoveryInitialized = FALSE; diff --git a/targets/Nordic/_netCellular/ssl_socket_api.cpp b/targets/Nordic/_netCellular/ssl_socket_api.cpp new file mode 100644 index 0000000000..35951ba008 --- /dev/null +++ b/targets/Nordic/_netCellular/ssl_socket_api.cpp @@ -0,0 +1,401 @@ +// +// Copyright (c) .NET Foundation and Contributors +// Portions Copyright (c) Texas Instruments Incorporated. All rights reserved. +// See LICENSE file in the project root for full license information. +// + +#include "nanoHAL.h" + +#include +#include +#ifndef restrict +#define restrict +#endif + +// #include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define SSL_TAG_NO_SEC -1 +//--// + +// TODO +//bool ssl_parse_certificate_internal(void *buf, size_t size, void *pwd, void *x509) +bool ssl_parse_certificate_internal(void *buf, size_t size, void *x509) +{ + (void)buf; + (void)size; + (void)x509; + NATIVE_PROFILE_PAL_NETWORK(); + + return true; +} + +int ssl_decode_private_key_internal( + const unsigned char *key, + size_t keyLength, + const unsigned char *password, + size_t passwordLength) +{ + (void)key; + (void)keyLength; + (void)password; + (void)passwordLength; + NATIVE_PROFILE_PAL_NETWORK(); + + return 0; +} + +int ssl_accept_internal(int socket, int contextHandle) +{ + (void)socket; + (void)contextHandle; + NATIVE_PROFILE_PAL_NETWORK(); + return 0; +} + +//bool ssl_add_cert_auth_internal(int contextHandle, const char *certificate, int certLength, const char *certPassword) +bool ssl_add_cert_auth_internal(int contextHandle, const char *certificate, int certLength) +{ + (void)contextHandle; + (void)certificate; + (void)certLength; + NATIVE_PROFILE_PAL_NETWORK(); + return true; +} + +bool ssl_initialize_internal() +{ + NATIVE_PROFILE_PAL_NETWORK(); + memset(&g_SSL_Driver, 0, sizeof(g_SSL_Driver)); + + return true; +} + +bool ssl_generic_init_internal( + int sslMode, + int sslVerify, + const char *certificate, + int certLength, + const uint8_t *privateKey, + int privateKeyLength, + const char *password, + int passwordLength, + int &contextHandle, + bool useDeviceCertificate, + bool isServer) +{ + (void)password; + (void)passwordLength; + (void)privateKey; + (void)privateKeyLength; + NATIVE_PROFILE_PAL_NETWORK(); + + int sslContexIndex = -1; + + struct nrf91ssl_Context *context; + + /////////////////////// + for (uint32_t i = 0; i < ARRAYSIZE(g_SSL_Driver.ContextArray); i++) + { + if (g_SSL_Driver.ContextArray[i].Context == NULL) + { + sslContexIndex = i; + break; + } + } + + if (sslContexIndex == -1) + return false; + + // create and init nanoFramework Simple Link context + // this needs to be freed in ssl_exit_context_internal + context = (struct nrf91ssl_Context *)platform_malloc(sizeof(struct nrf91ssl_Context)); + if (context == NULL) + { + goto error; + } + + // // create security attribute + // // this is the equivalent of SSL context in mbedTLS + // // it needs to be freed in ssl_exit_context_internal + // context->SecurityAttributes = SlNetSock_secAttribCreate(); + // if (context->SecurityAttributes == NULL) + // { + // goto error; + // } + + context->IsServer = isServer; + + // configure protocol + switch ((SslProtocols)sslMode) + { + case SslProtocols_TLSv1: + context->securityMethod = IPPROTO_TLS_1_0; + break; + + case SslProtocols_TLSv11: + context->securityMethod = IPPROTO_TLS_1_1; + break; + + case SslProtocols_TLSv12: + context->securityMethod = IPPROTO_TLS_1_2; + break; + + default: + // shouldn't reach here! + goto error; + } + // default to no security + //context->sec_tag = SSL_TAG_NO_SEC; + context->sec_tag = TLS_SEC_TAG; + + // CA root certs are taken from Simple Link trusted root-certificate catalog, so nothing to do here + + // // parse "own" certificate if passed + // if(certificate != NULL && certLength > 0) + // { + // // TODO + // // this isn't required for client authentication + + // // mbedtls_x509_crt_init( &clicert ); + + // // ///////////////////////////////////////////////////////////////////////////////////////////////// + // // // developer notes: // + // // // this call parses certificates in both string and binary formats // + // // // when the formart is a string it has to include the terminator otherwise the parse will fail // + // // ///////////////////////////////////////////////////////////////////////////////////////////////// + // // if(mbedtls_x509_crt_parse( &clicert, (const unsigned char*)certificate, certLength ) != 0) + // // { + // // // x509_crt_parse_failed + // // goto error; + // // } + + // // if( mbedtls_pk_parse_key( &pkey, (const unsigned char *) mbedtls_test_cli_key, mbedtls_test_cli_key_len, + // NULL, 0 ) != 0) + // // { + // // // failed parsing the + // // } + + // // if( mbedtls_tls_conf_own_cert( &conf, &clicert, &pkey ) != 0 ) + // // { + // // // configuring own certificate failed + // // goto error; + // // } + // } + + switch (sslVerify) + { + case SslVerification_NoVerification: + context->peer_verify = TLS_PEER_VERIFY_NONE; + break; + + case SslVerification_VerifyPeer: + context->peer_verify = TLS_PEER_VERIFY_REQUIRED; + break; + + // case SslVerification_NoVerification: + default: + context->peer_verify = TLS_PEER_VERIFY_OPTIONAL; + break; + } + // // set certificate verification + // // the current options provided by Simple Link API are only verify or don't verify + // if ((SslVerification)sslVerify == SslVerification_NoVerification) + // { + // status = SlNetSock_secAttribSet( + // context->SecurityAttributes, + // SLNETSOCK_SEC_ATTRIB_DISABLE_CERT_STORE, + // (void *)&dummyVal, + // sizeof(dummyVal)); + // if (status < 0) + // { + // goto error; + // } + // } + + ////////////////////////////////////// + + // the equivalent of SSL contex in Simple Link is the Security Attribute that we've been building + g_SSL_Driver.ContextArray[sslContexIndex].Context = context; + g_SSL_Driver.ContextCount++; + + contextHandle = sslContexIndex; + + return true; + +error: + + // check for any memory allocation that needs to be freed before exiting + if (context != NULL) + { + platform_free(context); + } + + // if (context->SecurityAttributes != NULL) + // { + // SlNetSock_secAttribDelete(context->SecurityAttributes); + // } + + return false; +} + +bool ssl_exit_context_internal(int contextHandle) +{ + struct nrf91ssl_Context *context = NULL; + NATIVE_PROFILE_PAL_NETWORK(); + + // Check contextHandle range + if ((contextHandle >= (int)ARRAYSIZE(g_SSL_Driver.ContextArray)) || (contextHandle < 0) || + (g_SSL_Driver.ContextArray[contextHandle].Context == NULL)) + { + return false; + } + + context = (nrf91ssl_Context *)g_SSL_Driver.ContextArray[contextHandle].Context; + if (context == NULL) + { + return false; + } + + platform_free(context); + + memset(&g_SSL_Driver.ContextArray[contextHandle], 0, sizeof(g_SSL_Driver.ContextArray[contextHandle])); + + g_SSL_Driver.ContextCount--; + + return true; +} + +int ssl_connect_internal(int sd, const char *szTargetHost, int contextHandle) +{ + int rc; + //int cache; + nrf91ssl_Context *context; + + //TODO:: expect we need to move this + struct addrinfo *res; + struct addrinfo hints = { + .ai_family = AF_INET, + .ai_socktype = SOCK_STREAM, + }; + + NATIVE_PROFILE_PAL_NETWORK(); + + // Check contextHandle range + if ((contextHandle >= (int)ARRAYSIZE(g_SSL_Driver.ContextArray)) || (contextHandle < 0)) + { + return SOCK_SOCKET_ERROR; + } + + // Retrieve SSL context from g_SSL_Driver + // sd should already have been created + // Now do the SSL negotiation + context = (nrf91ssl_Context *)g_SSL_Driver.ContextArray[contextHandle].Context; + if (context == NULL) + { + return SOCK_SOCKET_ERROR; + } + + // set socket in network context + context->SocketFd = sd; + + // TODO:: get this info from the getaddrinfo call + rc = getaddrinfo(szTargetHost, NULL, &hints, &res); + if (rc) { + printk("getaddrinfo() failed, err %d\n", errno); + return -1; + } + + //TODO:: + ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(443); + + + context->peer_verify = 2; +printk ("calling setsockopt verify %d\n", context->peer_verify); + rc = setsockopt(sd, SOL_TLS, TLS_PEER_VERIFY, &context->peer_verify, sizeof(uint32_t)); + if (rc) + { + printk("*** Failed to setup peer verification, error: %d\n", errno); + return rc; + } + +// sec_tag_t sec_tag_list[1] = {context->sec_tag}; +// rc = setsockopt(sd, SOL_TLS, TLS_SEC_TAG_LIST, sec_tag_list, sizeof(sec_tag_list)); + const sec_tag_t tls_sec_tag[] = { + TLS_SEC_TAG, + }; + rc = setsockopt(sd, SOL_TLS, TLS_SEC_TAG_LIST, tls_sec_tag, sizeof(tls_sec_tag)); + if (rc) + { + printk("Failed to setup TLS sec tag, error: %d\n", errno); + return rc; + } + + // if (IS_ENABLED(CONFIG_REST_CLIENT_SCKT_TLS_SESSION_CACHE_IN_USE)) + // { + // cache = TLS_SESSION_CACHE_ENABLED; + // } + // else + // { + // cache = TLS_SESSION_CACHE_DISABLED; + // } + + // rc = setsockopt(sd, SOL_TLS, TLS_SESSION_CACHE, &cache, sizeof(cache)); + // if (rc) + // { + // printk("Unable to set session cache, errno %d\n", errno); + // return rc; + // } + + if (szTargetHost != NULL && szTargetHost[0] != 0) + { + printk ("target host %d >%s<\n", hal_strlen_s(szTargetHost), szTargetHost); + rc = setsockopt(sd, SOL_TLS, TLS_HOSTNAME, szTargetHost, hal_strlen_s(szTargetHost)); + if (rc) + { + printk("Failed to setup TLS hostname, error: %d\n", errno); + return rc; + } + } + printk ("server >%s<\n", szTargetHost); + + rc = connect (sd, res->ai_addr, sizeof(struct sockaddr_in)); + printk ("connect ret %d %d\n", rc, errno); + freeaddrinfo(res); + + return 0; +} + +int ssl_available_internal(int sd) +{ + NATIVE_PROFILE_PAL_NETWORK(); + return GetAvailBytes (sd); +} + +int ssl_write_internal(int sd, const char *data, size_t req_len) +{ + NATIVE_PROFILE_PAL_NETWORK(); + return SOCK_send(sd, data, req_len, 0); +} + +int ssl_read_internal(int sd, char *data, size_t size) +{ + NATIVE_PROFILE_PAL_NETWORK(); + return SOCK_recv(sd, data, size, 0); +} + +int ssl_close_socket_internal(int sd) +{ + NATIVE_PROFILE_PAL_NETWORK(); + SOCK_close(sd); + return true; +} diff --git a/targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp b/targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp new file mode 100644 index 0000000000..53d57b32da --- /dev/null +++ b/targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp @@ -0,0 +1,471 @@ +// +// Copyright (c) .NET Foundation and Contributors +// See LICENSE file in the project root for full license information. +// + +#include +#include +#include +#include + +extern uint32_t ip4_addr; +extern uint32_t ip4_dns1_addr; +extern uint32_t ip4_dns2_addr; + +uint32_t GetExistingConfigSize() +{ + uint32_t currentConfigSize = 0; + + currentConfigSize = + g_TargetConfiguration.NetworkInterfaceConfigs->Count * sizeof(HAL_Configuration_NetworkInterface); + currentConfigSize += g_TargetConfiguration.Wireless80211Configs->Count * sizeof(HAL_Configuration_Wireless80211); + + return currentConfigSize; +} + +// Need these alignment attributes given the 'odd' size of the strutures. +__attribute__((aligned(32))) HAL_CONFIGURATION_NETWORK spfNetwork; +__attribute__((aligned(32))) HAL_CONFIGURATION_NETWORK_WIRELESS80211 spfWireless; +__attribute__((aligned(32))) HAL_CONFIGURATION_NETWORK_WIRELESSAP spfWirelessAP; +__attribute__((aligned(32))) HAL_CONFIGURATION_X509_CERTIFICATE spfCertificateStore; +__attribute__((aligned(32))) HAL_CONFIGURATION_X509_DEVICE_CERTIFICATE spfDeviceCertificates; + +// #define STATOC_ALLOC 1 +#ifdef STATOC_ALLOC +HAL_Configuration_NetworkInterface nrf9160_lte; +#else +HAL_Configuration_NetworkInterface *nrf9160_lte; +#endif + +// initialization of configuration manager +// provided as weak so it can be replaced at target level, if required because of the target implementing the storage +// with a mechanism other then saving to flash +__nfweak void ConfigurationManager_Initialize() +{ + // init g_TargetConfiguration + memset(&g_TargetConfiguration, 0, sizeof(HAL_TARGET_CONFIGURATION)); + + // enumerate the blocks + ConfigurationManager_EnumerateConfigurationBlocks(); +}; + +void dumpNetInfo(HAL_Configuration_NetworkInterface *net1, HAL_Configuration_NetworkInterface *net2) +{ +#if 1 + if (net2 != 0) + { + printk("AutomaticDNS %d %d\n", net1->AutomaticDNS, net2->AutomaticDNS); + printk("InterfaceType %d %d\n", net1->InterfaceType, net2->InterfaceType); + printk("IPv4Address %x %x\n", net1->IPv4Address, net2->IPv4Address); + printk("IPv4DNSAddress1 %x %x\n", net1->IPv4DNSAddress1, net2->IPv4DNSAddress1); + printk("IPv4GatewayAddress %x %x\n", net1->IPv4GatewayAddress, net2->IPv4GatewayAddress); + } + else + { + printk("AutomaticDNS %d\n", net1->AutomaticDNS); + printk("InterfaceType %d\n", net1->InterfaceType); + printk("IPv4Address %x\n", net1->IPv4Address); + printk("IPv4DNSAddress1 %x\n", net1->IPv4DNSAddress1); + printk("IPv4GatewayAddress %x\n", net1->IPv4GatewayAddress); + } +#endif +} + +// Enumerates the configuration blocks from the configuration flash sector +// it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is +// used +__nfweak void ConfigurationManager_EnumerateConfigurationBlocks() +{ + printk("ConfigurationManager_EnumerateConfigurationBlocks++\n"); + // Spoof up a single network config and no certs. + if (g_TargetConfiguration.NetworkInterfaceConfigs == 0) + { +#if 1 + +#ifdef STATIC_ALLOC + memcpy(&nrf9160_lte.Marker, c_MARKER_CONFIGURATION_NETWORK_V1, sizeof(nrf9160_lte.Marker)); + nrf9160_lte.InterfaceType = NetworkInterfaceType_Ethernet; + nrf9160_lte.StartupAddressMode = AddressMode_DHCP; + nrf9160_lte.AutomaticDNS = 1; + nrf9160_lte.SpecificConfigId = UINT32_MAX; + nrf9160_lte.IPv4Address = 0; + nrf9160_lte.IPv4DNSAddress1 = 0; + nrf9160_lte.IPv4DNSAddress2 = 0; + // printk ("0addr of blk %x\n", (uint32_t)&nrf9160_lte); +#else + nrf9160_lte = (HAL_Configuration_NetworkInterface *)platform_malloc(sizeof(HAL_Configuration_NetworkInterface)); + memset(nrf9160_lte, 0, sizeof(HAL_Configuration_NetworkInterface)); + + memcpy(&nrf9160_lte->Marker, c_MARKER_CONFIGURATION_NETWORK_V1, sizeof(nrf9160_lte->Marker)); + nrf9160_lte->InterfaceType = NetworkInterfaceType_Ethernet; + nrf9160_lte->StartupAddressMode = AddressMode_DHCP; + nrf9160_lte->AutomaticDNS = 1; + nrf9160_lte->SpecificConfigId = UINT32_MAX; + nrf9160_lte->IPv4Address = 0; + nrf9160_lte->IPv4DNSAddress1 = 0; + nrf9160_lte->IPv4DNSAddress2 = 0; + // printk ("0addr of blk %x\n", (uint32_t)nrf9160_lte); +#endif + +#else + spfNetwork.Configs[0] = + (HAL_Configuration_NetworkInterface *)platform_malloc(sizeof(HAL_Configuration_NetworkInterface)); + memset(spfNetwork.Configs, 0, sizeof(HAL_Configuration_NetworkInterface)); + memcpy( + &spfNetwork.Configs[0]->Marker, + c_MARKER_CONFIGURATION_NETWORK_V1, + sizeof(spfNetwork.Configs[0]->Marker)); + // TODO:: Fix the network type + spfNetwork.Configs[0]->InterfaceType = NetworkInterfaceType_Ethernet; + spfNetwork.Configs[0]->StartupAddressMode = AddressMode_DHCP; +#endif + spfNetwork.Count = 1; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Warray-bounds" + +#ifdef STATIC_ALLOC + spfNetwork.Configs[0] = &nrf9160_lte; +#else + spfNetwork.Configs[0] = nrf9160_lte; +#endif +#pragma GCC diagnostic pop + g_TargetConfiguration.NetworkInterfaceConfigs = &spfNetwork; + + spfWireless.Count = 0; + g_TargetConfiguration.Wireless80211Configs = &spfWireless; + + spfWirelessAP.Count = 0; + g_TargetConfiguration.WirelessAPConfigs = &spfWirelessAP; + + spfCertificateStore.Count = 0; + g_TargetConfiguration.CertificateStore = &spfCertificateStore; + + spfDeviceCertificates.Count = 0; + g_TargetConfiguration.DeviceCertificates = &spfDeviceCertificates; + } + dumpNetInfo(spfNetwork.Configs[0], 0); + + // printk ("ConfigurationManager_EnumerateConfigurationBlocks-- blk %x\n", (uint32_t)spfNetwork.Configs[0]); +} + +// Gets the network configuration block from the configuration flash sector +// it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism is +// used +static int cnt = 0; +__nfweak bool ConfigurationManager_GetConfigurationBlock( + void *configurationBlock, + DeviceConfigurationOption configuration, + uint32_t configurationIndex) +{ + int sizeOfBlock = 0; + uint8_t *blockAddress = NULL; + + printk( + "ConfigurationManager_GetConfigurationBlock++ cfg %d idx:%d cnt:%d\n", + configuration, + configurationIndex, + cnt); + + // printk ("ConfigurationManager_GetConfigurationBlock count %d idx %d %x\n", + // g_TargetConfiguration.NetworkInterfaceConfigs->Count, configurationIndex, + // (uint32_t)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[0]); + + // validate if the requested block exists + // Count has to be non zero + // requested Index has to exist (array index starts at zero, so need to add one) + if (configuration == DeviceConfigurationOption_Network) + { + if (g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 || + (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count) + { + // the requested config block is beyond the available count + return false; + } + // See if it's the 9160 modem. + if (configurationIndex == 0) + { + // if (cnt++ > 2) + { + // Update the ip info. +#ifdef STATIC_ALLOC + nrf9160_lte.IPv4Address = ip4_addr; + nrf9160_lte.IPv4DNSAddress1 = ip4_dns1_addr; + nrf9160_lte.IPv4DNSAddress2 = ip4_dns2_addr; +#else + nrf9160_lte->IPv4Address = ip4_addr; + nrf9160_lte->IPv4NetMask = 0xffffffff; + nrf9160_lte->IPv4DNSAddress1 = ip4_dns1_addr; + nrf9160_lte->IPv4DNSAddress2 = ip4_dns2_addr; + // The LTE network doesn't supply a gateway address. + nrf9160_lte->IPv4GatewayAddress = ip4_addr; +#endif + } + + // set block size + sizeOfBlock = sizeof(HAL_Configuration_NetworkInterface); + + // get block address + blockAddress = (uint8_t *)g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex]; + + dumpNetInfo(g_TargetConfiguration.NetworkInterfaceConfigs->Configs[configurationIndex], 0); + } + } + else if (configuration == DeviceConfigurationOption_Wireless80211Network) + { + if (g_TargetConfiguration.Wireless80211Configs->Count == 0 || + (configurationIndex + 1) > g_TargetConfiguration.Wireless80211Configs->Count) + { + return FALSE; + } + + // set block size + sizeOfBlock = sizeof(HAL_Configuration_Wireless80211); + + // get block address + blockAddress = (uint8_t *)g_TargetConfiguration.Wireless80211Configs->Configs[configurationIndex]; + } + else if (configuration == DeviceConfigurationOption_X509CaRootBundle) + { + if (g_TargetConfiguration.CertificateStore->Count == 0 || + (configurationIndex + 1) > g_TargetConfiguration.CertificateStore->Count) + { + return FALSE; + } + + // get block address + blockAddress = (uint8_t *)g_TargetConfiguration.CertificateStore->Certificates[configurationIndex]; + + // set block size + // because X509 certificate has a variable length need to compute the block size in two steps + sizeOfBlock = offsetof(HAL_Configuration_X509CaRootBundle, Certificate); + sizeOfBlock += ((HAL_Configuration_X509CaRootBundle *)blockAddress)->CertificateSize; + } + else if (configuration == DeviceConfigurationOption_X509CaRootBundle) + { + if (g_TargetConfiguration.DeviceCertificates->Count == 0 || + (configurationIndex + 1) > g_TargetConfiguration.DeviceCertificates->Count) + { + return FALSE; + } + + // get block address + blockAddress = (uint8_t *)g_TargetConfiguration.DeviceCertificates->Certificates[configurationIndex]; + + // set block size + // because X509 certificate has a variable length need to compute the block size in two steps + sizeOfBlock = offsetof(HAL_Configuration_X509DeviceCertificate, Certificate); + sizeOfBlock += ((HAL_Configuration_X509DeviceCertificate *)blockAddress)->CertificateSize; + } + else + { + printk("Unknown configuration %d requested.\n", configuration); + return false; + } + // copy the config block content to the pointer in the argument + memcpy(configurationBlock, blockAddress, sizeOfBlock); + + // printk ("ConfigurationManager_GetConfigurationBlock-- %x\n", (uint32_t)blockAddress); + return TRUE; +} + +void DumpBuf (uint8_t *buf, int size) +{ + int i; + int cnt = 0; + char sz[64]; + char sz1[32]; + while (cnt < size) + { + sz[0]='\0'; + sz1[0]='\0'; + for (i = 0; (i < 16) && (cnt < size); i++) + { + sprintf (&sz[hal_strlen_s(sz)], "%02x ", buf[cnt]); + if ((buf[cnt] >=' ') && (buf[cnt] < 0x7e)) + { + sz1[i] = buf[cnt]; + } + else + { + sz1[i] = '.'; + } + cnt++; + } + printk ("%s %s\n", sz, sz1); + } +} + +// Stores the configuration block to the configuration flash sector +// NOTE: because inserting or removing a configuration block it's very 'RAM expensive' we choose not to support +// those operations the host debugger will have to be used to manage these operations on the device configuration +// collection it's implemented with 'weak' attribute so it can be replaced at target level if a different +// persistance mechanism is used +__nfweak bool ConfigurationManager_StoreConfigurationBlock( + void *configurationBlock, + DeviceConfigurationOption configuration, + uint32_t configurationIndex, + uint32_t blockSize, + uint32_t offset, + bool done) +{ + // ByteAddress storageAddress = 0; + // bool requiresEnumeration = FALSE; + bool success = FALSE; + printk("ConfigurationManager_StoreConfigurationBlock++ idx: %d ptr %p blksiz: %d off %d\n", configurationIndex, configurationBlock, blockSize, offset); + + if (g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 || + (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count) + { + printk("ConfigurationManager_StoreConfigurationBlock-- fail 1\n"); + // the requested config block is beyond the available count + return false; + } + // We only support the 9160 modem for now + if (configurationIndex != 0) + { + printk("ConfigurationManager_StoreConfigurationBlock-- fail 2\n"); + // the requested config block is beyond the available count + return false; + } + + printk ("################################ >>>\n"); + HAL_CONFIGURATION_NETWORK *pnet; + HAL_CONFIGURATION_NETWORK_WIRELESS80211 *p802; + // HAL_CONFIGURATION_NETWORK_WIRELESSAP *pAP; + HAL_CONFIGURATION_X509_CERTIFICATE *pCACert; + HAL_CONFIGURATION_X509_DEVICE_CERTIFICATE *pDevCert; + uint32_t start, end; + start = (uint32_t)configurationBlock+offset; + end = start+blockSize; + { + pnet = (HAL_CONFIGURATION_NETWORK *)ConfigurationManager_FindNetworkConfigurationBlocks(start, end); + if (pnet && (pnet->Count > 0)) + printk ("NetworkConfiguration at %p cnt %d\n", pnet, pnet->Count); + platform_free (pnet); + + p802 = (HAL_CONFIGURATION_NETWORK_WIRELESS80211 *)ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks(start, end); + if (p802 && (p802->Count > 0)) + printk ("NetworkWireless80211Configuration at %p cnt %d\n", p802, p802->Count); + platform_free (p802); + + // pAP = (HAL_CONFIGURATION_NETWORK_WIRELESSAP *)ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks(start, end); + // if (pAP && (pAP->Count > 0)) + // printk ("NetworkWirelessAPConfiguration at %p cnt %d\n", pAP, pAP->Count); + // platform_free (pAP); + + pCACert = (HAL_CONFIGURATION_X509_CERTIFICATE *)ConfigurationManager_FindX509CertificateConfigurationBlocks(start, end); + if (pCACert && (pCACert->Count > 0)) + { + printk ("X509CertificateConfiguration at %p ", pCACert); + printk ("cnt %d ", pCACert->Count); + if ((pCACert->Count > 0) && (pCACert->Certificates)) + { + printk ("size %d\n", pCACert->Certificates[0]->CertificateSize); + DumpBuf (pCACert->Certificates[0]->Certificate, pCACert->Certificates[0]->CertificateSize); + } + printk ("\n"); + } + platform_free (pCACert); + pDevCert = (HAL_CONFIGURATION_X509_DEVICE_CERTIFICATE *)ConfigurationManager_FindX509DeviceCertificatesConfigurationBlocks(start, end); + if (pDevCert && (pDevCert->Count > 0)) + { + printk ("DeviceCertificatesConfiguration at %p ", pDevCert); + printk ("cnt %d ", pDevCert->Count); + if ((pDevCert->Count > 0) && (pDevCert->Certificates)) + { + printk ("size %d", pDevCert->Certificates[0]->CertificateSize); + } + printk ("\n"); + } + platform_free (pDevCert); + } + printk ("################################ <<<\n"); + switch (configuration) + { + case DeviceConfigurationOption_Network: + { + printk("ConfigurationManager_StoreConfigurationBlock-- 2\n"); + HAL_Configuration_NetworkInterface *newcfg = (HAL_Configuration_NetworkInterface *)configurationBlock; + dumpNetInfo(newcfg, nrf9160_lte); + printk("Store configuration \"DeviceConfigurationOption_Network\" not supported at this time."); + + + printk("ConfigurationManager_StoreConfigurationBlock-- 3\n"); + success = TRUE; + } + case DeviceConfigurationOption_X509CaRootBundle: + printk("ConfigurationManager_StoreConfigurationBlock DeviceConfigurationOption_X509CaRootBundle\n"); + success = TRUE; + break; + case DeviceConfigurationOption_X509DeviceCertificates: + printk("ConfigurationManager_StoreConfigurationBlock DeviceConfigurationOption_X509DeviceCertificates\n"); + success = TRUE; + break; + case DeviceConfigurationOption_All: + printk("ConfigurationManager_StoreConfigurationBlock DeviceConfigurationOption_All\n"); + success = TRUE; + break; + + default: + printk("Unknown configuration %d\n", configuration); + break; + } + printk("ConfigurationManager_StoreConfigurationBlock-- %d\n", success); + return success; +} + +// Updates a configuration block in the configuration flash sector +// The flash sector has to be erased before writing the updated block +// it's implemented with 'weak' attribute so it can be replaced at target level if a different persistance mechanism +// is used +__nfweak bool ConfigurationManager_UpdateConfigurationBlock( + void *configurationBlock, + DeviceConfigurationOption configuration, + uint32_t configurationIndex) +{ + bool success = FALSE; + + printk("ConfigurationManager_UpdateConfigurationBlock++\n"); + if (configuration == DeviceConfigurationOption_Network) + { + if (g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 || + (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count) + { + // the requested config block is beyond the available count + return false; + } + // See if it's the 9160 modem. + if (configurationIndex == 0) + { + HAL_Configuration_NetworkInterface *newcfg = (HAL_Configuration_NetworkInterface *)configurationBlock; + dumpNetInfo(newcfg, nrf9160_lte); + } + success = TRUE; + } + return success; +} + +// Default initialisation for wireless config block +// it's implemented with 'weak' attribute so it can be replaced at target level if different configurations are +// intended +__nfweak void InitialiseWirelessDefaultConfig(HAL_Configuration_Wireless80211 *pconfig, uint32_t configurationIndex) +{ + (void)pconfig; + (void)configurationIndex; + printk("InitialiseWirelessDefaultConfig++\n"); + + // currently empty as no Zephyr target has Wireless 802.11 interface +} + +// Default initialisation for Network interface config blocks +// it's implemented with 'weak' attribute so it can be replaced at target level if different configurations are +// intended +__nfweak bool InitialiseNetworkDefaultConfig(HAL_Configuration_NetworkInterface *pconfig, uint32_t configurationIndex) +{ + (void)pconfig; + (void)configurationIndex; + printk("InitialiseNetworkDefaultConfig++\n"); + + // can't create a "default" network config because we are lacking definition of a MAC address + return FALSE; +} diff --git a/targets/Nordic/_zephyr_boards/boards/arm/nrf9160_ard0022B/board_nonsecure.c b/targets/Nordic/_zephyr_boards/boards/arm/nrf9160_ard0022B/board_nonsecure.c index b33a2ae0bb..ea4097b6f8 100644 --- a/targets/Nordic/_zephyr_boards/boards/arm/nrf9160_ard0022B/board_nonsecure.c +++ b/targets/Nordic/_zephyr_boards/boards/arm/nrf9160_ard0022B/board_nonsecure.c @@ -58,12 +58,7 @@ static int ard_ns_grove_ctrl_init(const struct device *dev) { int ret; - // While this file is typically board specific, keeping this file - // consistent between the Combi and Combi Dev simplifies support. - -#if defined CONFIG_BOARD_NRF9160_ARD0022BNS ret = gpio_pin_configure(dev, BOARD_NS_GROVE_SELECT_PIN, GPIO_OUTPUT | GPIO_ACTIVE_HIGH); - if (ret) { LOG_ERR("Error configuring pin %d!", BOARD_NS_GROVE_SELECT_PIN); @@ -71,23 +66,10 @@ static int ard_ns_grove_ctrl_init(const struct device *dev) bool sel_digital = BOARD_NS_SEL_GROVEDIGITAL; ret = gpio_pin_set_raw(dev, BOARD_NS_GROVE_SELECT_PIN, sel_digital); - if (ret) { LOG_ERR("Error setting pin %d!", BOARD_NS_GROVE_SELECT_PIN); } - -#else - - ret = gpio_pin_configure(dev, BOARD_NS_GROVE_SELECT_PIN, GPIO_DISCONNECTED); - - if (ret) - { - LOG_ERR("Error configuring pin %d!", BOARD_NS_GROVE_SELECT_PIN); - } - -#endif - return ret; } @@ -96,9 +78,7 @@ static int ard_ns_board_init(const struct device *dev) { int err; const struct device *gpio_out_dev; - gpio_out_dev = device_get_binding(GPIO_DRIVER_NAME); - if (!gpio_out_dev) { LOG_ERR("Cannot find %s!", GPIO_DRIVER_NAME); @@ -106,19 +86,15 @@ static int ard_ns_board_init(const struct device *dev) } err = ard_ns_sim_ctrl_init(gpio_out_dev); - if (err) { LOG_ERR("ard_ns_sim_ctrl_init failed with error: %d", err); - // return err; } err = ard_ns_grove_ctrl_init(gpio_out_dev); - if (err) { LOG_ERR("ard_ns_grove_ctrl_init failed with error: %d", err); - // return err; } return 0; From 8ce266470aa7240d09d97297906a567248d5fc39 Mon Sep 17 00:00:00 2001 From: nfbot Date: Fri, 27 Jan 2023 01:00:04 +0000 Subject: [PATCH 2/4] Code style fixes Automated fixes for code style. --- targets/Nordic/_include/nrf9160_lte.h | 27 +- targets/Nordic/_include/sockets_nrf9160.h | 269 +++++++++--------- targets/Nordic/_include/ssl_sockets_nrf9160.h | 4 +- targets/Nordic/_nanoCLR/targetHAL_Time.cpp | 2 +- .../_nanoCLR_module/nf_lib/nflib_main.c | 2 +- .../_netCellular/Nordic_Sockets_functions.cpp | 38 +-- targets/Nordic/_netCellular/nrf9160_lte.c | 38 +-- targets/Nordic/_netCellular/socket_api.cpp | 21 +- .../Nordic/_netCellular/ssl_socket_api.cpp | 60 ++-- .../targetHAL_ConfigurationManager.cpp | 72 ++--- 10 files changed, 278 insertions(+), 255 deletions(-) diff --git a/targets/Nordic/_include/nrf9160_lte.h b/targets/Nordic/_include/nrf9160_lte.h index a0708e3c2b..3dd0b2698b 100644 --- a/targets/Nordic/_include/nrf9160_lte.h +++ b/targets/Nordic/_include/nrf9160_lte.h @@ -7,7 +7,8 @@ // Include basic operating system dependencies #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) @@ -26,26 +27,24 @@ extern "C" { #define DEFAULT_TIMEOUT -1 // Connect State values -#define CONN_STATE_DISCONNECTED 0 -#define CONN_STATE_CONN_HOME 1 -#define CONN_STATE_CONN_ROAM 2 +#define CONN_STATE_DISCONNECTED 0 +#define CONN_STATE_CONN_HOME 1 +#define CONN_STATE_CONN_ROAM 2 -// Initialize the LTE library -int nrf9160_lte_init(uint16_t timeout); + // Initialize the LTE library + int nrf9160_lte_init(uint16_t timeout); -// Connect to the network. -int nrf9160_lte_connect(uint16_t timeout); + // Connect to the network. + int nrf9160_lte_connect(uint16_t timeout); -// Disconnect to the network. -int nrf9160_lte_offline(void); - -// Turn off the modem. -int nrf9160_lte_power_off(void); + // Disconnect to the network. + int nrf9160_lte_offline(void); + // Turn off the modem. + int nrf9160_lte_power_off(void); #ifdef __cplusplus } #endif #endif /* NRF9610_LTE_H__ */ - diff --git a/targets/Nordic/_include/sockets_nrf9160.h b/targets/Nordic/_include/sockets_nrf9160.h index 1cf497fa4f..ddd37045b6 100644 --- a/targets/Nordic/_include/sockets_nrf9160.h +++ b/targets/Nordic/_include/sockets_nrf9160.h @@ -13,7 +13,7 @@ #include -//#include +// #include #include #include #ifndef restrict @@ -21,71 +21,81 @@ #endif #include -int GetAvailBytes (SOCK_SOCKET socket); +int GetAvailBytes(SOCK_SOCKET socket); extern "C" int signal_nf_stack(void); //--// -#define SOCKET_CHECK_ENTER() \ - int32_t ret=0 \ - -#define SOCKET_CLEANUP() \ - goto RETURN_OK; \ - SOCKET_CHECK_RETURN: \ - -#define SOCKET_CHECK_EXIT_CLEANUP() \ - RETURN_OK: \ - ASSERT(ret != SOCK_SOCKET_ERROR); \ - return ret; \ - -#define SOCKET_CHECK_EXIT() \ - SOCKET_CLEANUP() \ - RETURN_OK: \ - ASSERT(ret != SOCK_SOCKET_ERROR); \ - return ret; \ - -#define SOCKET_CHECK_EXIT_bool() \ - SOCKET_CLEANUP() \ - RETURN_OK: \ - return ret != SOCK_SOCKET_ERROR; \ - -#define SOCKET_CHECK_EXIT_bool_CLEANUP()\ - RETURN_OK: \ - return ret != SOCK_SOCKET_ERROR; \ - -#define SOCKET_CHECK_RESULT(x) \ - if((ret = (x)) == SOCK_SOCKET_ERROR)\ - { \ - goto SOCKET_CHECK_RETURN; \ - } \ - -#define SOCKET_CHECK_bool(x) \ - if(!(x)) \ - { \ - ret = SOCK_SOCKET_ERROR; \ - goto SOCKET_CHECK_RETURN; \ - } \ - -#define SOCKET_CHECK_EXIT_NORETURN() \ - RETURN_OK: \ +#define SOCKET_CHECK_ENTER() int32_t ret = 0 + +#define SOCKET_CLEANUP() \ + goto RETURN_OK; \ + SOCKET_CHECK_RETURN: + +#define SOCKET_CHECK_EXIT_CLEANUP() \ + RETURN_OK: \ + ASSERT(ret != SOCK_SOCKET_ERROR); \ + return ret; + +#define SOCKET_CHECK_EXIT() \ + SOCKET_CLEANUP() \ + RETURN_OK: \ + ASSERT(ret != SOCK_SOCKET_ERROR); \ + return ret; + +#define SOCKET_CHECK_EXIT_bool() \ + SOCKET_CLEANUP() \ + RETURN_OK: \ + return ret != SOCK_SOCKET_ERROR; + +#define SOCKET_CHECK_EXIT_bool_CLEANUP() \ + RETURN_OK: \ + return ret != SOCK_SOCKET_ERROR; + +#define SOCKET_CHECK_RESULT(x) \ + if ((ret = (x)) == SOCK_SOCKET_ERROR) \ + { \ + goto SOCKET_CHECK_RETURN; \ + } + +#define SOCKET_CHECK_bool(x) \ + if (!(x)) \ + { \ + ret = SOCK_SOCKET_ERROR; \ + goto SOCKET_CHECK_RETURN; \ + } + +#define SOCKET_CHECK_EXIT_NORETURN() \ + RETURN_OK: struct Sockets_nrf9160_Driver { - static SOCK_SOCKET Socket( int32_t family, int32_t type, int32_t protocol, bool fDebug ); - static int Connect(SOCK_SOCKET socket, const struct SOCK_sockaddr* address, int32_t addressLen) ; - static int Send(SOCK_SOCKET socket, const char* buf, int32_t len, int32_t flags) ; - static int Recv(SOCK_SOCKET socket, char* buf, int32_t len, int32_t flags); + static SOCK_SOCKET Socket(int32_t family, int32_t type, int32_t protocol, bool fDebug); + static int Connect(SOCK_SOCKET socket, const struct SOCK_sockaddr *address, int32_t addressLen); + static int Send(SOCK_SOCKET socket, const char *buf, int32_t len, int32_t flags); + static int Recv(SOCK_SOCKET socket, char *buf, int32_t len, int32_t flags); static int Close(SOCK_SOCKET socket); - static int Listen( SOCK_SOCKET socket, int32_t backlog ); - static SOCK_SOCKET Accept( SOCK_SOCKET socket, struct SOCK_sockaddr* address, int* addressLen, bool fDebug ); - static int Select( int32_t nfds, SOCK_fd_set* readfds, SOCK_fd_set* writefds, SOCK_fd_set* except, const struct SOCK_timeval* timeout ); - static int RecvFrom( SOCK_SOCKET s, char* buf, int32_t len, int32_t flags, struct SOCK_sockaddr* from, int* fromlen ); - static int SendTo( SOCK_SOCKET s, const char* buf, int32_t len, int32_t flags, const struct SOCK_sockaddr* to, int32_t tolen ); - static int Shutdown( SOCK_SOCKET s, int32_t how); - - static bool Initialize(); - static bool Uninitialize(); - static void CloseConnections(bool fCloseDbg); + static int Listen(SOCK_SOCKET socket, int32_t backlog); + static SOCK_SOCKET Accept(SOCK_SOCKET socket, struct SOCK_sockaddr *address, int *addressLen, bool fDebug); + static int Select( + int32_t nfds, + SOCK_fd_set *readfds, + SOCK_fd_set *writefds, + SOCK_fd_set *except, + const struct SOCK_timeval *timeout); + static int RecvFrom(SOCK_SOCKET s, char *buf, int32_t len, int32_t flags, struct SOCK_sockaddr *from, int *fromlen); + static int SendTo( + SOCK_SOCKET s, + const char *buf, + int32_t len, + int32_t flags, + const struct SOCK_sockaddr *to, + int32_t tolen); + static int Shutdown(SOCK_SOCKET s, int32_t how); + + static bool Initialize(); + static bool Uninitialize(); + static void CloseConnections(bool fCloseDbg); static void SaveConfig(int32_t index, HAL_Configuration_NetworkInterface *cfg); @@ -94,183 +104,186 @@ struct Sockets_nrf9160_Driver static void Debugger_Uninitialize(); static void Debugger_Abort(); - static bool InitializeDbgListener( int ComPortNum ); - static bool UninitializeDbgListener( int ComPortNum ); - static int Write( int ComPortNum, const char* Data, size_t size ); - static int Read ( int ComPortNum, char* Data, size_t size ); - static bool UpgradeToSsl( int ComPortNum, const int8_t* pCACert, uint32_t caCertLen, const int8_t* pDeviceCert, uint32_t deviceCertLen, const char* szTargetHost ); - static bool IsUsingSsl( int ComPortNum ); + static bool InitializeDbgListener(int ComPortNum); + static bool UninitializeDbgListener(int ComPortNum); + static int Write(int ComPortNum, const char *Data, size_t size); + static int Read(int ComPortNum, char *Data, size_t size); + static bool UpgradeToSsl( + int ComPortNum, + const int8_t *pCACert, + uint32_t caCertLen, + const int8_t *pDeviceCert, + uint32_t deviceCertLen, + const char *szTargetHost); + static bool IsUsingSsl(int ComPortNum); //(db) TODO: reduce the code below with a single lookup - //struct Sockets_nrf9160_Driver::SocketRegisterMap *GetSockRegMap(SOCK_SOCKET socket) + // struct Sockets_nrf9160_Driver::SocketRegisterMap *GetSockRegMap(SOCK_SOCKET socket) uint32_t *GetSockFlags(SOCK_SOCKET socket) { - for(int i=m_cntSockets-1; i>=0; i--) + for (int i = m_cntSockets - 1; i >= 0; i--) { - if(socket == m_socketHandles[i].m_socket) + if (socket == m_socketHandles[i].m_socket) return &m_socketHandles[i].m_flags; } - printk ("***** ERROR socket %d not found in SocketRegisterMap\n", socket); + printk("***** ERROR socket %d not found in SocketRegisterMap\n", socket); ASSERT(FALSE); return 0; } - void* GetSocketSslData(SOCK_SOCKET socket) + void *GetSocketSslData(SOCK_SOCKET socket) { int32_t tmp; return GetSocketSslData(socket, tmp); } - void* GetSocketSslData(SOCK_SOCKET socket, int32_t &sockIndex) + void *GetSocketSslData(SOCK_SOCKET socket, int32_t &sockIndex) { GLOBAL_LOCK_SOCKETS(x); - - for(int i=m_cntSockets-1; i>=0; i--) + + for (int i = m_cntSockets - 1; i >= 0; i--) { - if(socket == m_socketHandles[i].m_socket) + if (socket == m_socketHandles[i].m_socket) { sockIndex = i; return m_socketHandles[i].m_sslData; } } - + return NULL; } - void SetSocketSslData(SOCK_SOCKET socket, void* sslObj) + void SetSocketSslData(SOCK_SOCKET socket, void *sslObj) { GLOBAL_LOCK_SOCKETS(x); - for(int i=m_cntSockets-1; i>=0; i--) + for (int i = m_cntSockets - 1; i >= 0; i--) { - if(socket == m_socketHandles[i].m_socket) + if (socket == m_socketHandles[i].m_socket) { m_socketHandles[i].m_sslData = sslObj; - + break; } } } -#ifdef PERRADDR_WORKAROUND +#ifdef PERRADDR_WORKAROUND int GetSocketAddrData(SOCK_SOCKET socket, void *addr, int *len) { GLOBAL_LOCK_SOCKETS(x); - - for(int i=m_cntSockets-1; i>=0; i--) + + for (int i = m_cntSockets - 1; i >= 0; i--) { - if(socket == m_socketHandles[i].m_socket) + if (socket == m_socketHandles[i].m_socket) { int addrlen = m_socketHandles[i].peeraddr_len; if (*len >= addrlen) { - memcpy (addr, &m_socketHandles[i].peeraddr, addrlen); + memcpy(addr, &m_socketHandles[i].peeraddr, addrlen); *len = addrlen; } return 0; } } - printk ("GetSocketAddrData sock %d. data not found %p %d\n", socket, addr, *len); + printk("GetSocketAddrData sock %d. data not found %p %d\n", socket, addr, *len); return -1; } - int SetSocketAddrData(SOCK_SOCKET socket, const void* data, int len) + int SetSocketAddrData(SOCK_SOCKET socket, const void *data, int len) { GLOBAL_LOCK_SOCKETS(x); - for(int i=m_cntSockets-1; i>=0; i--) + for (int i = m_cntSockets - 1; i >= 0; i--) { - if(socket == m_socketHandles[i].m_socket) + if (socket == m_socketHandles[i].m_socket) { - //printk ("SetSocketAddrData sock found %d\n", i); - if (len <= (int)sizeof (m_socketHandles[i].peeraddr)) + // printk ("SetSocketAddrData sock found %d\n", i); + if (len <= (int)sizeof(m_socketHandles[i].peeraddr)) { - //printk ("SetSocketAddrData copy data\n"); - memcpy (&m_socketHandles[i].peeraddr, data, len); + // printk ("SetSocketAddrData copy data\n"); + memcpy(&m_socketHandles[i].peeraddr, data, len); m_socketHandles[i].peeraddr_len = len; } else - printk ("SetSocketAddrData sockaddr too long %d %d\n", len, sizeof (m_socketHandles[i].peeraddr)); + printk("SetSocketAddrData sockaddr too long %d %d\n", len, sizeof(m_socketHandles[i].peeraddr)); return 0; } } - printk ("SetSocketAddrData sock %d. data not found %p %d\n", socket, data, len); + printk("SetSocketAddrData sock %d. data not found %p %d\n", socket, data, len); return -1; } #endif // required by SSL - static void UnregisterSocket( int index ); - + static void UnregisterSocket(int index); static void ClearStatusBitsForSocket(SOCK_SOCKET sock, bool fWrite); static bool InitializeMulticastDiscovery(); -private: - + private: static void SockMonitorThread(void *a, void *b, void *c); - static void RegisterSocket( SOCK_SOCKET sock, bool selectable, bool fDebug ); - + static void RegisterSocket(SOCK_SOCKET sock, bool selectable, bool fDebug); + struct SocketRegisterMap { SOCK_SOCKET m_socket; - uint32_t m_flags; - void* m_sslData; -#ifdef PERRADDR_WORKAROUND + uint32_t m_flags; + void *m_sslData; +#ifdef PERRADDR_WORKAROUND // Workaround for getpeeraddr struct SOCK_sockaddr peeraddr; int peeraddr_len; #endif - + static const uint32_t c_SelectableSocket = 0x0001; - static const uint32_t c_DebugSocket = 0x0002; - static const uint32_t c_CloseSocket = 0x0004; + static const uint32_t c_DebugSocket = 0x0002; + static const uint32_t c_CloseSocket = 0x0004; - static const uint32_t c_SelRdSocket = 0x0010; - static const uint32_t c_SelWrSocket = 0x0020; - static const uint32_t c_SelErSocket = 0x0040; - static const uint32_t c_SelSocketMask = 0x0070; + static const uint32_t c_SelRdSocket = 0x0010; + static const uint32_t c_SelWrSocket = 0x0020; + static const uint32_t c_SelErSocket = 0x0040; + static const uint32_t c_SelSocketMask = 0x0070; }; enum DebuggerState { DbgSock_Uninitialized = 0, - DbgSock_Listening = 1, - DbgSock_Connected = 2, + DbgSock_Listening = 1, + DbgSock_Connected = 2, } m_stateDebugSocket; bool m_usingSSL; - - static void MulticastDiscoveryRespond(void* arg); - static void MulticastDiscoverySchedule(); + + static void MulticastDiscoveryRespond(void *arg); + static void MulticastDiscoverySchedule(); static void CloseDebuggerSocket(); - static void OnDebuggerTimeout(void* arg); - + static void OnDebuggerTimeout(void *arg); + static HAL_COMPLETION s_DebuggerTimeoutCompletion; - SOCK_SOCKET m_SocketDebugListener; - SOCK_SOCKET m_SocketDebugStream; - SOCK_SOCKET m_multicastSocket; + SOCK_SOCKET m_SocketDebugListener; + SOCK_SOCKET m_SocketDebugStream; + SOCK_SOCKET m_multicastSocket; - bool m_fShuttingDown; + bool m_fShuttingDown; //(db) - struct k_sem sem_sockmon; + struct k_sem sem_sockmon; - int32_t m_cntSockets; + int32_t m_cntSockets; struct SocketRegisterMap m_socketHandles[SOCKETS_MAX_COUNT]; - static bool s_initialized; - static bool s_initializedDbg; - static const int32_t c_WellKnownDebugPort = DEBUG_SOCKET_PORT; - static bool s_wirelessInitialized; - static bool s_discoveryInitialized; + static bool s_initialized; + static bool s_initializedDbg; + static const int32_t c_WellKnownDebugPort = DEBUG_SOCKET_PORT; + static bool s_wirelessInitialized; + static bool s_discoveryInitialized; }; extern Sockets_nrf9160_Driver g_Sockets_nrf9160_Driver; #endif // SOCKETS_H - diff --git a/targets/Nordic/_include/ssl_sockets_nrf9160.h b/targets/Nordic/_include/ssl_sockets_nrf9160.h index 6c03c36898..649af40d0a 100644 --- a/targets/Nordic/_include/ssl_sockets_nrf9160.h +++ b/targets/Nordic/_include/ssl_sockets_nrf9160.h @@ -8,7 +8,7 @@ struct nrf91ssl_Context { - //SlNetSockSecAttrib_t* SecurityAttributes; + // SlNetSockSecAttrib_t* SecurityAttributes; uint32_t securityMethod; uint32_t peer_verify; int sec_tag; @@ -17,4 +17,4 @@ struct nrf91ssl_Context bool IsServer; }; -#endif //SSL_NRF9160_H +#endif // SSL_NRF9160_H diff --git a/targets/Nordic/_nanoCLR/targetHAL_Time.cpp b/targets/Nordic/_nanoCLR/targetHAL_Time.cpp index 03e59886e6..c4bdd2fe66 100644 --- a/targets/Nordic/_nanoCLR/targetHAL_Time.cpp +++ b/targets/Nordic/_nanoCLR/targetHAL_Time.cpp @@ -195,7 +195,7 @@ char *DateTimeToString(const uint64_t &time) const char *HAL_Time_CurrentDateTimeToString() { - //printk("HAL_Time_CurrentDateTimeToString++\n"); + // printk("HAL_Time_CurrentDateTimeToString++\n"); return DateTimeToString(HAL_Time_CurrentDateTime(false)); } diff --git a/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c b/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c index 6cd837511f..97efedb708 100644 --- a/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c +++ b/targets/Nordic/_nanoCLR_module/nf_lib/nflib_main.c @@ -41,7 +41,7 @@ int start_nf(const char *wire_uart_name) // g_heapsize = (0x8000-32) * 2; //64k - overhead g_heapsize = (0x8800 - 32); // 48k - overhead - //g_heapsize = (0x8000 - 32); // 32k - overhead + // g_heapsize = (0x8000 - 32); // 32k - overhead g_heapbase = k_malloc(g_heapsize); if (g_heapbase != 0) diff --git a/targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp b/targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp index e94e09ef6f..b805f81b8f 100644 --- a/targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp +++ b/targets/Nordic/_netCellular/Nordic_Sockets_functions.cpp @@ -15,7 +15,6 @@ extern char connect_state; - static int last_sock_error = 0; bool HAL_SOCK_Initialize() @@ -102,7 +101,7 @@ int HAL_SOCK_connect(SOCK_SOCKET socket, const struct SOCK_sockaddr *address, in net_saddr_2z(address, &addr); printk("connect: xlate: sock %d fam: %d len %d\n", socket, addr.sa_family, addressLen); - //printk("connect: old errno %d\n", errno); + // printk("connect: old errno %d\n", errno); int rc = connect(socket, &addr, addressLen); if (rc != 0) { @@ -267,11 +266,16 @@ void rep_sockaddr_to_zsockaddr(const struct SOCK_addrinfo *a, struct zsock_addri else z->ai_addr = 0; } -char *ipaddr2str (uint32_t addr) +char *ipaddr2str(uint32_t addr) { static char sz[48]; - sprintf (sz, "%d.%d.%d.%d", (addr && 0xff000000) >> 24, (addr && 0xff0000) >> 16, - (addr && 0xff00) >> 8, (addr && 0xff)); + sprintf( + sz, + "%d.%d.%d.%d", + (addr && 0xff000000) >> 24, + (addr && 0xff0000) >> 16, + (addr && 0xff00) >> 8, + (addr && 0xff)); return sz; } int HAL_SOCK_getaddrinfo( @@ -298,18 +302,18 @@ int HAL_SOCK_getaddrinfo( { for (int q = 0; q < 16; q++) { - printk ("%x ", *(servname + q)); + printk("%x ", *(servname + q)); } - printk ("\n"); + printk("\n"); } else - printk ("servname unreadable %p\n", servname); + printk("servname unreadable %p\n", servname); } else - printk ("servname zero\n"); + printk("servname zero\n"); - //printk ("server >%s<\n", servname); - //printk("addr internal_res %x\n", (uint32_t)internal_res); + // printk ("server >%s<\n", servname); + // printk("addr internal_res %x\n", (uint32_t)internal_res); // Fetch the zsock version rc = getaddrinfo(nodename, servname, &ai, &internal_res->z_res); @@ -359,7 +363,7 @@ int HAL_SOCK_ioctl(SOCK_SOCKET socket, int cmd, int *data) printk("SOCK_FIONREAD "); // Fake this ioctl by peeking at socket and seeing how // much data returned. This is non-optimal but should work. - rc = GetAvailBytes (socket); + rc = GetAvailBytes(socket); *data = rc; break; default: @@ -371,12 +375,12 @@ int HAL_SOCK_ioctl(SOCK_SOCKET socket, int cmd, int *data) } return rc; } -//static char tmpbuf[256]; +// static char tmpbuf[256]; static char tmpbuf[1520]; -int GetAvailBytes (SOCK_SOCKET socket) +int GetAvailBytes(SOCK_SOCKET socket) { int rc; - printk ("GetAvailBytes soc %d available:", socket); + printk("GetAvailBytes soc %d available:", socket); rc = recv(socket, tmpbuf, sizeof(tmpbuf), MSG_DONTWAIT | MSG_PEEK); if (rc >= 0) { @@ -694,7 +698,7 @@ int HAL_SOCK_select( MARSHAL_FDSET_TO_SOCK_FDSET(readfds, pR); MARSHAL_FDSET_TO_SOCK_FDSET(writefds, pW); MARSHAL_FDSET_TO_SOCK_FDSET(except, pE); - printk ("HAL_SOCK_select-- ret %d\n", ret); + printk("HAL_SOCK_select-- ret %d\n", ret); return ret; } int translate_opt_net_to_z(int *level, int *netopt) @@ -929,7 +933,7 @@ void *HAL_SOCK_GlobalLockContext() } int signal_nf_stack(void) { - printk ("Signal NF Stack++\n"); + printk("Signal NF Stack++\n"); Events_Set(SYSTEM_EVENT_FLAG_NETWORK); return 0; } \ No newline at end of file diff --git a/targets/Nordic/_netCellular/nrf9160_lte.c b/targets/Nordic/_netCellular/nrf9160_lte.c index 719426e566..3bff7c07f5 100644 --- a/targets/Nordic/_netCellular/nrf9160_lte.c +++ b/targets/Nordic/_netCellular/nrf9160_lte.c @@ -8,7 +8,7 @@ #include #include #include -//#include +// #include #include #include @@ -19,8 +19,8 @@ #include -//#include -//#include +// #include +// #include int signal_nf_stack(void); @@ -50,7 +50,7 @@ int cert_provision(void); int handle_new_connection(int); -//static struct modem_param_info modem_param; +// static struct modem_param_info modem_param; bool fconnected = false; char szIMEI[IMxI_LEN]; @@ -124,7 +124,7 @@ void lte_evt_handler(const struct lte_lc_evt *const evt) connect_state = CONN_STATE_CONN_HOME; // TODO:: Notify of connect. k_work_schedule(&connect_work, K_NO_WAIT); - //handle_new_connection (0); + // handle_new_connection (0); } break; case LTE_LC_NW_REG_SEARCHING: @@ -221,7 +221,7 @@ static void connect_work_fn(struct k_work *work) // Get the IP addresses rc = get_ip_info(&ip4_addr, &ip4_dns1_addr, &ip4_dns2_addr); - //printk ("get_ip_info returned %x %x %x\n", ip4_addr, ip4_dns1_addr, ip4_dns2_addr); + // printk ("get_ip_info returned %x %x %x\n", ip4_addr, ip4_dns1_addr, ip4_dns2_addr); #ifdef CONFIG_DATE_TIME date_time_update_async(date_time_event_handler); @@ -258,12 +258,12 @@ static void connect_work_fn(struct k_work *work) // return rc; // } -int comma_parse (char *buf, int inlen, int find_comma, char *outbuf, int outlen) +int comma_parse(char *buf, int inlen, int find_comma, char *outbuf, int outlen) { int i, j, k = 0, rc = 0; int comma_cnt = 0; -// printk ("comma_parse++ %d >%s<\n", find_comma, buf); + // printk ("comma_parse++ %d >%s<\n", find_comma, buf); for (i = 0; (i < inlen) && (rc == 0); i++) { @@ -282,7 +282,7 @@ int comma_parse (char *buf, int inlen, int find_comma, char *outbuf, int outlen) // We expect the string to have a starting quote. if (buf[i + 1] != '\"') { - //printk("i %d char %c\n", i, buf[i + 1]); + // printk("i %d char %c\n", i, buf[i + 1]); rc = -2; } // Find closing quote @@ -298,7 +298,7 @@ int comma_parse (char *buf, int inlen, int find_comma, char *outbuf, int outlen) if (buf[j] == '\"') { outbuf[k] = '\0'; // zero terminate - rc = k; // Copy length + rc = k; // Copy length break; } else @@ -338,14 +338,14 @@ int get_ip_info(uint32_t *ip_addr, uint32_t *dns1, uint32_t *dns2) *dns2 = 0; // First, convert IP address. - memset (buf, 0, sizeof (buf)); + memset(buf, 0, sizeof(buf)); // Use specific cmd to get the IP addresses rc = query_modem("AT+CGPADDR=0", buf, sizeof(buf)); - //printk ("query_modem ret %d >%s<\n", rc, buf); + // printk ("query_modem ret %d >%s<\n", rc, buf); if (rc == 0) { - //printk ("IP addr: %s\n", buf); - rc = comma_parse (buf, strlen (buf), 1, outbuf, sizeof (outbuf)); + // printk ("IP addr: %s\n", buf); + rc = comma_parse(buf, strlen(buf), 1, outbuf, sizeof(outbuf)); if (rc > 0) { rc = inet_pton(AF_INET, outbuf, &sa.sin_addr); @@ -358,15 +358,15 @@ int get_ip_info(uint32_t *ip_addr, uint32_t *dns1, uint32_t *dns2) } else { - printk ("Failed to get ip address from modem. %d\n", rc); + printk("Failed to get ip address from modem. %d\n", rc); } // Now use cmd to get the DNS addresses rc = query_modem("AT+CGCONTRDP=0", buf, sizeof(buf)); if (rc == 0) { - //printk ("modem string: %s\n", buf); - // DNS 1 - rc = comma_parse (buf, strlen (buf), 5, outbuf, sizeof (outbuf)); + // printk ("modem string: %s\n", buf); + // DNS 1 + rc = comma_parse(buf, strlen(buf), 5, outbuf, sizeof(outbuf)); if (rc > 0) { rc = inet_pton(AF_INET, outbuf, &sa.sin_addr); @@ -374,7 +374,7 @@ int get_ip_info(uint32_t *ip_addr, uint32_t *dns1, uint32_t *dns2) *dns1 = sa.sin_addr.s_addr; } // DNS 2 - rc = comma_parse (buf, strlen (buf), 6, outbuf, sizeof (outbuf)); + rc = comma_parse(buf, strlen(buf), 6, outbuf, sizeof(outbuf)); if (rc > 0) { rc = inet_pton(AF_INET, outbuf, &sa.sin_addr); diff --git a/targets/Nordic/_netCellular/socket_api.cpp b/targets/Nordic/_netCellular/socket_api.cpp index 2c19a84b49..6453c7961a 100644 --- a/targets/Nordic/_netCellular/socket_api.cpp +++ b/targets/Nordic/_netCellular/socket_api.cpp @@ -117,7 +117,7 @@ int SOCK_getpeername(SOCK_SOCKET socket, struct SOCK_sockaddr *name, int *namele NATIVE_PROFILE_PAL_COM(); int rc; #ifdef PERRADDR_WORKAROUND - //printk("getpeername workaround\n"); + // printk("getpeername workaround\n"); rc = g_Sockets_nrf9160_Driver.GetSocketAddrData(socket, name, namelen); if (rc) printk("### GetSocketAddrData ret %d\n", rc); @@ -469,11 +469,11 @@ bool Sockets_nrf9160_Driver::Initialize() NATIVE_PROFILE_PAL_COM(); SOCKET_CHECK_ENTER(); -printk ("Sockets_nrf9160_Driver::Initialize++ %d\n", s_initialized); + printk("Sockets_nrf9160_Driver::Initialize++ %d\n", s_initialized); if (!s_initialized) { -printk ("Sockets_nrf9160_Driver::Initialize 1\n"); + printk("Sockets_nrf9160_Driver::Initialize 1\n"); g_Sockets_nrf9160_Driver.m_fShuttingDown = FALSE; g_Sockets_nrf9160_Driver.m_cntSockets = 0; @@ -485,7 +485,7 @@ printk ("Sockets_nrf9160_Driver::Initialize 1\n"); g_Sockets_nrf9160_Driver.m_socketHandles[i].m_sslData = NULL; } k_sem_init(&g_Sockets_nrf9160_Driver.sem_sockmon, 0, 1); -printk ("Sockets_nrf9160_Driver::Initialize 2\n"); + printk("Sockets_nrf9160_Driver::Initialize 2\n"); k_thread_create( &sock_thread_data, sock_thread_stack, @@ -626,7 +626,7 @@ void Sockets_nrf9160_Driver::SockMonitorThread(void *arg1, void *arg2, void *arg struct pollfd fd[SOCKETS_MAX_COUNT]; int r, w, e, c, b; - printk ("**** SockMonitorThread++\n"); + printk("**** SockMonitorThread++\n"); NATIVE_PROFILE_PAL_COM(); while (true) @@ -669,19 +669,19 @@ void Sockets_nrf9160_Driver::SockMonitorThread(void *arg1, void *arg2, void *arg // If no socks have flags, just wait. if (sock_cnt == 0) { - printk ("**** SockMonitorThread zero socket wait\n"); + printk("**** SockMonitorThread zero socket wait\n"); k_sem_reset(&g_Sockets_nrf9160_Driver.sem_sockmon); // Wait for a new socket k_sem_take(&g_Sockets_nrf9160_Driver.sem_sockmon, K_FOREVER); - printk ("**** SockMonitorThread triggered\n"); + printk("**** SockMonitorThread triggered\n"); continue; } // Now monitor the open sockets. - printk ("**** SockMonitorThread poll cnt:%d %d %d %d\n", g_Sockets_nrf9160_Driver.m_cntSockets, r, w, e); + printk("**** SockMonitorThread poll cnt:%d %d %d %d\n", g_Sockets_nrf9160_Driver.m_cntSockets, r, w, e); rc = poll(fd, g_Sockets_nrf9160_Driver.m_cntSockets, 1000); - printk ("**** SockMonitorThread poll return %d %x ", rc, fd[0].revents); + printk("**** SockMonitorThread poll return %d %x ", rc, fd[0].revents); if (rc < 0) { printk("poll error %d %d\n", rc, errno); @@ -709,8 +709,7 @@ void Sockets_nrf9160_Driver::SockMonitorThread(void *arg1, void *arg2, void *arg if (fd[i].revents & POLLNVAL) b++; } - printk("cnt %d r %d w %d err %d close %d Inv %d\n", - g_Sockets_nrf9160_Driver.m_cntSockets, r, w, e, c, b); + printk("cnt %d r %d w %d err %d close %d Inv %d\n", g_Sockets_nrf9160_Driver.m_cntSockets, r, w, e, c, b); // signal the nf stack. Events_Set(SYSTEM_EVENT_FLAG_SOCKET); diff --git a/targets/Nordic/_netCellular/ssl_socket_api.cpp b/targets/Nordic/_netCellular/ssl_socket_api.cpp index 35951ba008..ce737f18f0 100644 --- a/targets/Nordic/_netCellular/ssl_socket_api.cpp +++ b/targets/Nordic/_netCellular/ssl_socket_api.cpp @@ -28,7 +28,7 @@ //--// // TODO -//bool ssl_parse_certificate_internal(void *buf, size_t size, void *pwd, void *x509) +// bool ssl_parse_certificate_internal(void *buf, size_t size, void *pwd, void *x509) bool ssl_parse_certificate_internal(void *buf, size_t size, void *x509) { (void)buf; @@ -62,7 +62,7 @@ int ssl_accept_internal(int socket, int contextHandle) return 0; } -//bool ssl_add_cert_auth_internal(int contextHandle, const char *certificate, int certLength, const char *certPassword) +// bool ssl_add_cert_auth_internal(int contextHandle, const char *certificate, int certLength, const char *certPassword) bool ssl_add_cert_auth_internal(int contextHandle, const char *certificate, int certLength) { (void)contextHandle; @@ -155,7 +155,7 @@ bool ssl_generic_init_internal( goto error; } // default to no security - //context->sec_tag = SSL_TAG_NO_SEC; + // context->sec_tag = SSL_TAG_NO_SEC; context->sec_tag = TLS_SEC_TAG; // CA root certs are taken from Simple Link trusted root-certificate catalog, so nothing to do here @@ -278,15 +278,15 @@ bool ssl_exit_context_internal(int contextHandle) int ssl_connect_internal(int sd, const char *szTargetHost, int contextHandle) { int rc; - //int cache; + // int cache; nrf91ssl_Context *context; - //TODO:: expect we need to move this - struct addrinfo *res; - struct addrinfo hints = { - .ai_family = AF_INET, - .ai_socktype = SOCK_STREAM, - }; + // TODO:: expect we need to move this + struct addrinfo *res; + struct addrinfo hints = { + .ai_family = AF_INET, + .ai_socktype = SOCK_STREAM, + }; NATIVE_PROFILE_PAL_NETWORK(); @@ -308,19 +308,19 @@ int ssl_connect_internal(int sd, const char *szTargetHost, int contextHandle) // set socket in network context context->SocketFd = sd; - // TODO:: get this info from the getaddrinfo call - rc = getaddrinfo(szTargetHost, NULL, &hints, &res); - if (rc) { - printk("getaddrinfo() failed, err %d\n", errno); - return -1; - } - - //TODO:: - ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(443); + // TODO:: get this info from the getaddrinfo call + rc = getaddrinfo(szTargetHost, NULL, &hints, &res); + if (rc) + { + printk("getaddrinfo() failed, err %d\n", errno); + return -1; + } + // TODO:: + ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(443); context->peer_verify = 2; -printk ("calling setsockopt verify %d\n", context->peer_verify); + printk("calling setsockopt verify %d\n", context->peer_verify); rc = setsockopt(sd, SOL_TLS, TLS_PEER_VERIFY, &context->peer_verify, sizeof(uint32_t)); if (rc) { @@ -328,11 +328,11 @@ printk ("calling setsockopt verify %d\n", context->peer_verify); return rc; } -// sec_tag_t sec_tag_list[1] = {context->sec_tag}; -// rc = setsockopt(sd, SOL_TLS, TLS_SEC_TAG_LIST, sec_tag_list, sizeof(sec_tag_list)); - const sec_tag_t tls_sec_tag[] = { - TLS_SEC_TAG, - }; + // sec_tag_t sec_tag_list[1] = {context->sec_tag}; + // rc = setsockopt(sd, SOL_TLS, TLS_SEC_TAG_LIST, sec_tag_list, sizeof(sec_tag_list)); + const sec_tag_t tls_sec_tag[] = { + TLS_SEC_TAG, + }; rc = setsockopt(sd, SOL_TLS, TLS_SEC_TAG_LIST, tls_sec_tag, sizeof(tls_sec_tag)); if (rc) { @@ -358,7 +358,7 @@ printk ("calling setsockopt verify %d\n", context->peer_verify); if (szTargetHost != NULL && szTargetHost[0] != 0) { - printk ("target host %d >%s<\n", hal_strlen_s(szTargetHost), szTargetHost); + printk("target host %d >%s<\n", hal_strlen_s(szTargetHost), szTargetHost); rc = setsockopt(sd, SOL_TLS, TLS_HOSTNAME, szTargetHost, hal_strlen_s(szTargetHost)); if (rc) { @@ -366,10 +366,10 @@ printk ("calling setsockopt verify %d\n", context->peer_verify); return rc; } } - printk ("server >%s<\n", szTargetHost); + printk("server >%s<\n", szTargetHost); - rc = connect (sd, res->ai_addr, sizeof(struct sockaddr_in)); - printk ("connect ret %d %d\n", rc, errno); + rc = connect(sd, res->ai_addr, sizeof(struct sockaddr_in)); + printk("connect ret %d %d\n", rc, errno); freeaddrinfo(res); return 0; @@ -378,7 +378,7 @@ printk ("calling setsockopt verify %d\n", context->peer_verify); int ssl_available_internal(int sd) { NATIVE_PROFILE_PAL_NETWORK(); - return GetAvailBytes (sd); + return GetAvailBytes(sd); } int ssl_write_internal(int sd, const char *data, size_t req_len) diff --git a/targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp b/targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp index 53d57b32da..0d0d5d8d46 100644 --- a/targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp +++ b/targets/Nordic/_netCellular/targetHAL_ConfigurationManager.cpp @@ -268,7 +268,7 @@ __nfweak bool ConfigurationManager_GetConfigurationBlock( return TRUE; } -void DumpBuf (uint8_t *buf, int size) +void DumpBuf(uint8_t *buf, int size) { int i; int cnt = 0; @@ -276,12 +276,12 @@ void DumpBuf (uint8_t *buf, int size) char sz1[32]; while (cnt < size) { - sz[0]='\0'; - sz1[0]='\0'; + sz[0] = '\0'; + sz1[0] = '\0'; for (i = 0; (i < 16) && (cnt < size); i++) { - sprintf (&sz[hal_strlen_s(sz)], "%02x ", buf[cnt]); - if ((buf[cnt] >=' ') && (buf[cnt] < 0x7e)) + sprintf(&sz[hal_strlen_s(sz)], "%02x ", buf[cnt]); + if ((buf[cnt] >= ' ') && (buf[cnt] < 0x7e)) { sz1[i] = buf[cnt]; } @@ -291,7 +291,7 @@ void DumpBuf (uint8_t *buf, int size) } cnt++; } - printk ("%s %s\n", sz, sz1); + printk("%s %s\n", sz, sz1); } } @@ -311,7 +311,12 @@ __nfweak bool ConfigurationManager_StoreConfigurationBlock( // ByteAddress storageAddress = 0; // bool requiresEnumeration = FALSE; bool success = FALSE; - printk("ConfigurationManager_StoreConfigurationBlock++ idx: %d ptr %p blksiz: %d off %d\n", configurationIndex, configurationBlock, blockSize, offset); + printk( + "ConfigurationManager_StoreConfigurationBlock++ idx: %d ptr %p blksiz: %d off %d\n", + configurationIndex, + configurationBlock, + blockSize, + offset); if (g_TargetConfiguration.NetworkInterfaceConfigs->Count == 0 || (configurationIndex + 1) > g_TargetConfiguration.NetworkInterfaceConfigs->Count) @@ -328,58 +333,62 @@ __nfweak bool ConfigurationManager_StoreConfigurationBlock( return false; } - printk ("################################ >>>\n"); + printk("################################ >>>\n"); HAL_CONFIGURATION_NETWORK *pnet; HAL_CONFIGURATION_NETWORK_WIRELESS80211 *p802; // HAL_CONFIGURATION_NETWORK_WIRELESSAP *pAP; HAL_CONFIGURATION_X509_CERTIFICATE *pCACert; HAL_CONFIGURATION_X509_DEVICE_CERTIFICATE *pDevCert; uint32_t start, end; - start = (uint32_t)configurationBlock+offset; - end = start+blockSize; + start = (uint32_t)configurationBlock + offset; + end = start + blockSize; { pnet = (HAL_CONFIGURATION_NETWORK *)ConfigurationManager_FindNetworkConfigurationBlocks(start, end); if (pnet && (pnet->Count > 0)) - printk ("NetworkConfiguration at %p cnt %d\n", pnet, pnet->Count); - platform_free (pnet); + printk("NetworkConfiguration at %p cnt %d\n", pnet, pnet->Count); + platform_free(pnet); - p802 = (HAL_CONFIGURATION_NETWORK_WIRELESS80211 *)ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks(start, end); + p802 = (HAL_CONFIGURATION_NETWORK_WIRELESS80211 *) + ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks(start, end); if (p802 && (p802->Count > 0)) - printk ("NetworkWireless80211Configuration at %p cnt %d\n", p802, p802->Count); - platform_free (p802); + printk("NetworkWireless80211Configuration at %p cnt %d\n", p802, p802->Count); + platform_free(p802); - // pAP = (HAL_CONFIGURATION_NETWORK_WIRELESSAP *)ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks(start, end); - // if (pAP && (pAP->Count > 0)) + // pAP = (HAL_CONFIGURATION_NETWORK_WIRELESSAP + // *)ConfigurationManager_FindNetworkWireless80211ConfigurationBlocks(start, end); if (pAP && (pAP->Count > 0)) // printk ("NetworkWirelessAPConfiguration at %p cnt %d\n", pAP, pAP->Count); // platform_free (pAP); - pCACert = (HAL_CONFIGURATION_X509_CERTIFICATE *)ConfigurationManager_FindX509CertificateConfigurationBlocks(start, end); + pCACert = (HAL_CONFIGURATION_X509_CERTIFICATE *)ConfigurationManager_FindX509CertificateConfigurationBlocks( + start, + end); if (pCACert && (pCACert->Count > 0)) { - printk ("X509CertificateConfiguration at %p ", pCACert); - printk ("cnt %d ", pCACert->Count); + printk("X509CertificateConfiguration at %p ", pCACert); + printk("cnt %d ", pCACert->Count); if ((pCACert->Count > 0) && (pCACert->Certificates)) { - printk ("size %d\n", pCACert->Certificates[0]->CertificateSize); - DumpBuf (pCACert->Certificates[0]->Certificate, pCACert->Certificates[0]->CertificateSize); + printk("size %d\n", pCACert->Certificates[0]->CertificateSize); + DumpBuf(pCACert->Certificates[0]->Certificate, pCACert->Certificates[0]->CertificateSize); } - printk ("\n"); + printk("\n"); } - platform_free (pCACert); - pDevCert = (HAL_CONFIGURATION_X509_DEVICE_CERTIFICATE *)ConfigurationManager_FindX509DeviceCertificatesConfigurationBlocks(start, end); + platform_free(pCACert); + pDevCert = (HAL_CONFIGURATION_X509_DEVICE_CERTIFICATE *) + ConfigurationManager_FindX509DeviceCertificatesConfigurationBlocks(start, end); if (pDevCert && (pDevCert->Count > 0)) { - printk ("DeviceCertificatesConfiguration at %p ", pDevCert); - printk ("cnt %d ", pDevCert->Count); + printk("DeviceCertificatesConfiguration at %p ", pDevCert); + printk("cnt %d ", pDevCert->Count); if ((pDevCert->Count > 0) && (pDevCert->Certificates)) { - printk ("size %d", pDevCert->Certificates[0]->CertificateSize); + printk("size %d", pDevCert->Certificates[0]->CertificateSize); } - printk ("\n"); + printk("\n"); } - platform_free (pDevCert); + platform_free(pDevCert); } - printk ("################################ <<<\n"); + printk("################################ <<<\n"); switch (configuration) { case DeviceConfigurationOption_Network: @@ -389,7 +398,6 @@ __nfweak bool ConfigurationManager_StoreConfigurationBlock( dumpNetInfo(newcfg, nrf9160_lte); printk("Store configuration \"DeviceConfigurationOption_Network\" not supported at this time."); - printk("ConfigurationManager_StoreConfigurationBlock-- 3\n"); success = TRUE; } From 23e2e0acd7262207e598f4227df4b555552f3d9f Mon Sep 17 00:00:00 2001 From: dboling-ericsson <73494641+dboling-ericsson@users.noreply.github.com> Date: Fri, 27 Jan 2023 11:24:43 -0800 Subject: [PATCH 3/4] Build fix fixes build problem due to NATIVE_PROFILE_PAL_NETWORK() being defined outside commit --- .gitignore | 1 + targets/Nordic/_include/sockets_nrf9160.h | 3 +++ 2 files changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index d47caf0d9d..e1a7be8761 100644 --- a/.gitignore +++ b/.gitignore @@ -378,3 +378,4 @@ sdkconfig # CMake user presets CMakeUserPresets.json +g.cmd diff --git a/targets/Nordic/_include/sockets_nrf9160.h b/targets/Nordic/_include/sockets_nrf9160.h index 1cf497fa4f..3ef7587148 100644 --- a/targets/Nordic/_include/sockets_nrf9160.h +++ b/targets/Nordic/_include/sockets_nrf9160.h @@ -21,6 +21,9 @@ #endif #include +#define NATIVE_PROFILE_PAL_NETWORK() +//#define NATIVE_PROFILE_PAL_NETWORK() printk("%s++\n", __func__); + int GetAvailBytes (SOCK_SOCKET socket); extern "C" int signal_nf_stack(void); From bbc5ffd92fc59711267caec0e55704c9f34fb475 Mon Sep 17 00:00:00 2001 From: nfbot Date: Fri, 27 Jan 2023 19:34:19 +0000 Subject: [PATCH 4/4] Code style fixes Automated fixes for code style. --- targets/Nordic/_include/sockets_nrf9160.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/targets/Nordic/_include/sockets_nrf9160.h b/targets/Nordic/_include/sockets_nrf9160.h index 27db630515..ea3a8d7fde 100644 --- a/targets/Nordic/_include/sockets_nrf9160.h +++ b/targets/Nordic/_include/sockets_nrf9160.h @@ -22,9 +22,9 @@ #include #define NATIVE_PROFILE_PAL_NETWORK() -//#define NATIVE_PROFILE_PAL_NETWORK() printk("%s++\n", __func__); +// #define NATIVE_PROFILE_PAL_NETWORK() printk("%s++\n", __func__); -int GetAvailBytes (SOCK_SOCKET socket); +int GetAvailBytes(SOCK_SOCKET socket); int GetAvailBytes(SOCK_SOCKET socket); extern "C" int signal_nf_stack(void);