From e1daa7906dbf79e71fdd598e09a6ffd02f25c70a Mon Sep 17 00:00:00 2001 From: Kimmo Vaisanen Date: Tue, 24 Mar 2020 13:56:25 +0200 Subject: [PATCH 1/2] Remove deprecated netsocket Icetea tests --- TEST_APPS/device/socket_app/cmd_ifconfig.cpp | 158 -- TEST_APPS/device/socket_app/cmd_ifconfig.h | 34 - TEST_APPS/device/socket_app/cmd_socket.cpp | 1349 ----------------- TEST_APPS/device/socket_app/cmd_socket.h | 25 - TEST_APPS/device/socket_app/main.cpp | 69 - TEST_APPS/device/socket_app/mbed_app.json | 18 - TEST_APPS/device/socket_app/strconv.c | 242 --- TEST_APPS/device/socket_app/strconv.h | 98 -- TEST_APPS/testcases/README.md | 1 - TEST_APPS/testcases/netsocket/README.md | 113 -- .../testcases/netsocket/SOCKET_BIND_PORT.py | 73 - .../testcases/netsocket/TCPSERVER_ACCEPT.py | 105 -- .../testcases/netsocket/TCPSOCKET_ACCEPT.py | 108 -- .../TCPSOCKET_ECHOTEST_BURST_SHORT.py | 79 - TEST_APPS/testcases/netsocket/__init__.py | 16 - TEST_APPS/testcases/netsocket/interface.py | 45 - 16 files changed, 2533 deletions(-) delete mode 100644 TEST_APPS/device/socket_app/cmd_ifconfig.cpp delete mode 100644 TEST_APPS/device/socket_app/cmd_ifconfig.h delete mode 100644 TEST_APPS/device/socket_app/cmd_socket.cpp delete mode 100644 TEST_APPS/device/socket_app/cmd_socket.h delete mode 100644 TEST_APPS/device/socket_app/main.cpp delete mode 100644 TEST_APPS/device/socket_app/mbed_app.json delete mode 100644 TEST_APPS/device/socket_app/strconv.c delete mode 100644 TEST_APPS/device/socket_app/strconv.h delete mode 100644 TEST_APPS/testcases/netsocket/README.md delete mode 100644 TEST_APPS/testcases/netsocket/SOCKET_BIND_PORT.py delete mode 100644 TEST_APPS/testcases/netsocket/TCPSERVER_ACCEPT.py delete mode 100644 TEST_APPS/testcases/netsocket/TCPSOCKET_ACCEPT.py delete mode 100644 TEST_APPS/testcases/netsocket/TCPSOCKET_ECHOTEST_BURST_SHORT.py delete mode 100644 TEST_APPS/testcases/netsocket/__init__.py delete mode 100644 TEST_APPS/testcases/netsocket/interface.py diff --git a/TEST_APPS/device/socket_app/cmd_ifconfig.cpp b/TEST_APPS/device/socket_app/cmd_ifconfig.cpp deleted file mode 100644 index cb55e3bedf..0000000000 --- a/TEST_APPS/device/socket_app/cmd_ifconfig.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2018 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "NetworkStack.h" -#include "NetworkInterface.h" - -#include "mbed-client-cli/ns_cmdline.h" -#include "mbed-trace/mbed_trace.h" - -#include "ip4string.h" - -#define WIFI 2 -#if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \ - (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID)) -#error [NOT_SUPPORTED] No network configuration found for this target. -#endif - -#include - -#define TRACE_GROUP "Aifc" - -NetworkInterface *net; - -NetworkInterface *get_interface(void) -{ - return net; -} - -int cmd_ifup(int argc, char *argv[]); -int cmd_ifdown(int argc, char *argv[]); -int cmd_ifconfig(int argc, char *argv[]); - -const char *MAN_IFCONFIG = " ifup interface up\r\n"\ - " ifdown interface down\r\n"; - -static void ifconfig_print() -{ - if (!net) { - cmd_printf("No interface configured\r\n"); - return; - } - const char *str = net->get_ip_address(); - if (str) { - uint8_t buf[4]; - if (stoip4(str, strlen(str), buf)) { - cmd_printf("IPv4 if addr: %s\r\n", str); - } else { - cmd_printf("IPv6 if addr:\r\n [0]: %s\r\n", str); - } - } else { - cmd_printf("No IP address\r\n"); - } - str = net->get_mac_address(); - if (str) { - cmd_printf("MAC-48: %s\r\n", str); - } else { - cmd_printf("MAC-48: unknown\r\n"); - } -} - - -void cmd_ifconfig_init(void) -{ - cmd_add("ifup", cmd_ifup, "ifconfig up", MAN_IFCONFIG); - cmd_add("ifdown", cmd_ifdown, "ifconfig down", MAN_IFCONFIG); - cmd_add("ifconfig", cmd_ifconfig, "ifconfig", MAN_IFCONFIG); -} - -int cmd_ifconfig(int argc, char *argv[]) -{ - ifconfig_print(); - return CMDLINE_RETCODE_SUCCESS; -} - -int cmd_ifup(int argc, char *argv[]) -{ - if (!net) { - net = NetworkInterface::get_default_instance(); - } - int err = net->connect(); - if (err != NSAPI_ERROR_OK) { - return CMDLINE_RETCODE_FAIL; - } - - ifconfig_print(); - return CMDLINE_RETCODE_SUCCESS; -} - -int cmd_ifdown(int argc, char *argv[]) -{ - if (!net) { - return CMDLINE_RETCODE_FAIL; - } - int err = net->disconnect(); - if (err != NSAPI_ERROR_OK) { - return CMDLINE_RETCODE_FAIL; - } - - return CMDLINE_RETCODE_SUCCESS; -} - - - -const char *networkstack_error_to_str(int errorcode) -{ - switch (errorcode) { - case NSAPI_ERROR_OK: - return "NSAPI_ERROR_OK"; - case NSAPI_ERROR_WOULD_BLOCK: - return "NSAPI_ERROR_WOULD_BLOCK"; - case NSAPI_ERROR_UNSUPPORTED: - return "NSAPI_ERROR_UNSUPPORTED"; - case NSAPI_ERROR_PARAMETER: - return "NSAPI_ERROR_PARAMETER"; - case NSAPI_ERROR_NO_CONNECTION: - return "NSAPI_ERROR_NO_CONNECTION"; - case NSAPI_ERROR_NO_SOCKET: - return "NSAPI_ERROR_NO_SOCKET"; - case NSAPI_ERROR_NO_ADDRESS: - return "NSAPI_ERROR_NO_ADDRESS"; - case NSAPI_ERROR_NO_MEMORY: - return "NSAPI_ERROR_NO_MEMORY"; - case NSAPI_ERROR_NO_SSID: - return "NSAPI_ERROR_NO_SSID"; - case NSAPI_ERROR_DNS_FAILURE: - return "NSAPI_ERROR_DNS_FAILURE"; - case NSAPI_ERROR_DHCP_FAILURE: - return "NSAPI_ERROR_DHCP_FAILURE"; - case NSAPI_ERROR_AUTH_FAILURE: - return "NSAPI_ERROR_AUTH_FAILURE"; - case NSAPI_ERROR_DEVICE_ERROR: - return "NSAPI_ERROR_DEVICE_ERROR"; - case NSAPI_ERROR_IN_PROGRESS: - return "NSAPI_ERROR_IN_PROGRESS"; - case NSAPI_ERROR_ALREADY: - return "NSAPI_ERROR_ALREADY"; - case NSAPI_ERROR_IS_CONNECTED: - return "NSAPI_ERROR_IS_CONNECTED"; - case NSAPI_ERROR_CONNECTION_LOST: - return "NSAPI_ERROR_CONNECTION_LOST"; - case NSAPI_ERROR_CONNECTION_TIMEOUT: - return "NSAPI_ERROR_CONNECTION_TIMEOUT"; - default: - return "unknown error code"; - } -} diff --git a/TEST_APPS/device/socket_app/cmd_ifconfig.h b/TEST_APPS/device/socket_app/cmd_ifconfig.h deleted file mode 100644 index 37d50b942b..0000000000 --- a/TEST_APPS/device/socket_app/cmd_ifconfig.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2018 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CMD_IFCONFIG_H -#define CMD_IFCONFIG_H - -#include "NetworkInterface.h" -#include "NetworkStack.h" - -/** Get a pointer to a network interface instance - * - * Allowed interface types (depend on application configurations): - * cell0, wlan0, eth0, mesh0 - * - * @return pointer to the network interface, or NULL if unrecognized or ambiguous - */ -NetworkInterface *get_interface(void); - -void cmd_ifconfig_init(void); -const char *networkstack_error_to_str(int errorcode); - -#endif diff --git a/TEST_APPS/device/socket_app/cmd_socket.cpp b/TEST_APPS/device/socket_app/cmd_socket.cpp deleted file mode 100644 index 454bab8fa2..0000000000 --- a/TEST_APPS/device/socket_app/cmd_socket.cpp +++ /dev/null @@ -1,1349 +0,0 @@ -/* - * Copyright (c) 2018 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "mbed.h" -#include "NetworkStack.h" -#include "UDPSocket.h" -#include "TCPSocket.h" -#include "TCPServer.h" -#include "TLSSocket.h" -#include "NetworkInterface.h" -#include "SocketAddress.h" -#include "Queue.h" - -#include -#include -#include -#ifndef __STDC_FORMAT_MACROS -#define __STDC_FORMAT_MACROS -#endif -#include - -#include "mbed-client-cli/ns_cmdline.h" -#include "mbed-trace/mbed_trace.h" -#include "strconv.h" - -#define TRACE_GROUP "Asck" - -#include "cmd_ifconfig.h" -#include "cmd_socket.h" - -#define SIGNAL_SIGIO 0x1 -#define PACKET_SIZE_ARRAY_LEN 5 -#define CERT_BUFFER_SIZE 1648 - - -#define MAN_SOCKET "\r\nSOCKET API\r\n"\ - "\r\n"\ - "socket [options]\r\n\r\n"\ - " new \r\n" \ - " type: UDPSocket|TCPSocket|TCPServer|TLSSocket [--cert_file |--cert_default]\r\n"\ - " return socket id\r\n"\ - " delete\r\n"\ - " remote the space allocated for Socket\r\n"\ - " open [--if ] \r\n"\ - " interface (or use default interface) \r\n"\ - " close\r\n"\ - " bind [port] [addr ]\r\n"\ - " set_blocking \r\n"\ - " set_timeout \r\n"\ - " register_sigio_cb\r\n"\ - " set_RFC_864_pattern_check \r\n"\ - " set_root_ca_cert --cert_url |--cert_file |--cert_default\r\n"\ - " sendto (\"msg\" | --data_len )\r\n"\ - " \"msg\" Send packet with defined string content\r\n"\ - " --data_len Send packet with random content with size \r\n"\ - " recvfrom \r\n"\ - " start_udp_receiver_thread --max_data_len [--packets ]\r\n"\ - " --max_data_len Size of input buffer to fill up\r\n"\ - " --packets Receive N number of packets, default 1\r\n"\ - " connect \r\n"\ - " send (\"msg\" | --data_len )\r\n"\ - " recv \r\n"\ - " start_tcp_receiver_thread --data_len [--max_recv_len ] [--repeat ]\r\n"\ - " --data_len Size of input buffer to fill up\r\n"\ - " --max_recv_len Read maximum of L bytes in at a time. Default full buffer \r\n"\ - " --repeat Repeat buffer filling N times, default 1\r\n"\ - " join_tcp_receiver_thread\r\n"\ - " start_bg_traffic_thread\r\n"\ - " join_bg_traffic_thread\r\n"\ - " setsockopt_keepalive \r\n"\ - " getsockopt_keepalive\r\n"\ - " listen [backlog]\r\n"\ - " accept\r\n" \ - " accept new connection and returns new socket ID\r\n" \ - "\r\nFor TCPServer\r\n"\ - " accept \r\n"\ - " accept new connection into socket. Requires to be pre-allocated.\r\n"\ - "\r\nOther options\r\n"\ - " print-mode [--string|--hex|--disabled] [--col-width ]" - - - -const char *cert = \ - "-----BEGIN CERTIFICATE-----\n" \ - "MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \ - "MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \ - "DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \ - "SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \ - "GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \ - "AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \ - "q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \ - "SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \ - "Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \ - "a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \ - "/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \ - "AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \ - "CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \ - "bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \ - "c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \ - "VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \ - "ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \ - "MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \ - "Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \ - "AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \ - "uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \ - "wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \ - "X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \ - "PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \ - "KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \ - "-----END CERTIFICATE-----\n"; - -class SInfo { -public: - enum SocketType { - IP, - TCP_SERVER, - OTHER, -#if defined(MBEDTLS_SSL_CLI_C) - TLS -#endif - }; - SInfo(InternetSocket *sock, bool delete_on_exit = true): - _id(id_count++), - _sock(sock), - _type(SInfo::IP), - _blocking(true), - _dataLen(0), - _maxRecvLen(0), - _repeatBufferFill(1), - _receivedTotal(0), - _receiverThread(NULL), - _receiveBuffer(NULL), - _senderThreadId(NULL), - _receiverThreadId(NULL), - _packetSizes(NULL), - _check_pattern(false), - _delete_on_exit(delete_on_exit) - { - MBED_ASSERT(sock); - } - SInfo(TCPServer *sock, bool delete_on_exit = true): - _id(id_count++), - _sock(sock), - _type(SInfo::TCP_SERVER), - _blocking(true), - _dataLen(0), - _maxRecvLen(0), - _repeatBufferFill(1), - _receivedTotal(0), - _receiverThread(NULL), - _receiveBuffer(NULL), - _senderThreadId(NULL), - _receiverThreadId(NULL), - _packetSizes(NULL), - _check_pattern(false), - _delete_on_exit(delete_on_exit) - { - MBED_ASSERT(sock); - } - SInfo(Socket *sock, bool delete_on_exit = true): - _id(id_count++), - _sock(sock), - _type(SInfo::OTHER), - _blocking(true), - _dataLen(0), - _maxRecvLen(0), - _repeatBufferFill(1), - _receivedTotal(0), - _receiverThread(NULL), - _receiveBuffer(NULL), - _senderThreadId(NULL), - _receiverThreadId(NULL), - _packetSizes(NULL), - _check_pattern(false), - _delete_on_exit(delete_on_exit) - { - MBED_ASSERT(sock); - } -#if defined(MBEDTLS_SSL_CLI_C) - SInfo(TLSSocket *sock, bool delete_on_exit = true): - _id(id_count++), - _sock(sock), - _type(SInfo::TLS), - _blocking(true), - _dataLen(0), - _maxRecvLen(0), - _repeatBufferFill(1), - _receivedTotal(0), - _receiverThread(NULL), - _receiveBuffer(NULL), - _senderThreadId(NULL), - _receiverThreadId(NULL), - _packetSizes(NULL), - _check_pattern(false), - _delete_on_exit(delete_on_exit) - { - MBED_ASSERT(sock); - } -#endif - ~SInfo() - { - this->_sock->sigio(Callback()); - if (this->_receiverThread) { - this->_receiverThread->terminate(); - delete this->_receiverThread; - } - if (this->_receiveBuffer) { - delete this->_receiveBuffer; - } - if (_delete_on_exit) { - delete this->_sock; - } - } - int id() const - { - return this->_id; - } - Socket &socket() - { - return *(this->_sock); - } - Socket &socket() const - { - return *(this->_sock); - } - InternetSocket *internetsocket() - { - return this->_type == SInfo::IP ? static_cast(this->_sock) : NULL; - } - TCPServer *tcp_server() - { - return this->_type == SInfo::TCP_SERVER ? static_cast(this->_sock) : NULL; - } -#if defined(MBEDTLS_SSL_CLI_C) - TLSSocket *tls_socket() - { - return this->_type == SInfo::TLS ? static_cast(this->_sock) : NULL; - } -#endif - SInfo::SocketType type() const - { - return this->_type; - } - void setDataCount(int dataCount) - { - this->_dataLen = dataCount; - } - int getDataCount() - { - return this->_dataLen; - } - void setReceiverThread(Thread *receiverThread) - { - this->_receiverThread = receiverThread; - } - Thread *getReceiverThread() - { - return this->_receiverThread; - } - void setReceiveBuffer(uint8_t *receiveBuffer) - { - this->_receiveBuffer = receiveBuffer; - } - uint8_t *getReceiveBuffer() - { - return this->_receiveBuffer; - } - void setMaxRecvLen(int recvLen) - { - this->_maxRecvLen = recvLen; - } - int getMaxRecvLen() - { - return this->_maxRecvLen; - } - void setRepeatBufferFill(int n) - { - this->_repeatBufferFill = n; - } - int getRepeatBufferFill() - { - return this->_repeatBufferFill; - } - void setRecvTotal(int n) - { - this->_receivedTotal = n; - } - int getRecvTotal() - { - return this->_receivedTotal; - } - void setSenderThreadId(osThreadId threadID) - { - this->_senderThreadId = threadID; - } - void setReceiverThreadId(osThreadId threadID) - { - this->_receiverThreadId = threadID; - } - osThreadId getSenderThreadId() - { - return this->_senderThreadId; - } - osThreadId getReceiverThreadId() - { - return this->_receiverThreadId; - } - void setPacketSizeArray(int *ptr) - { - this->_packetSizes = ptr; - } - int *getPacketSizeArray() - { - return this->_packetSizes; - } - void setUnavailable() - { - this->_available = false; - } - void setAvailable() - { - this->_available = true; - } - bool available() - { - return this->_available; - } - void set_pattern_check(bool enabled) - { - _check_pattern = enabled; - }; - bool check_pattern(void *buffer, size_t len); - - const char *type_str() const - { - const char *str; - switch (this->_type) { - case SInfo::IP: - str = "InternetSocket"; - break; - case SInfo::TCP_SERVER: - str = "TCPServer"; - break; - case SInfo::OTHER: - str = "Socket"; - break; -#if defined(MBEDTLS_SSL_CLI_C) - case SInfo::TLS: - str = "TLSSocket"; - break; -#endif - default: - MBED_ASSERT(0); - break; - } - return str; - } - bool blocking() const - { - return this->_blocking; - } - void set_blocking(bool blocking) - { - socket().set_blocking(blocking); - this->_blocking = blocking; - } -private: - static int id_count; - const int _id; - Socket *_sock; - const SInfo::SocketType _type; - bool _blocking; - int _dataLen; - int _maxRecvLen; - int _repeatBufferFill; - int _receivedTotal; - Thread *_receiverThread; - uint8_t *_receiveBuffer; - osThreadId _senderThreadId; - osThreadId _receiverThreadId; - int *_packetSizes; - bool _available; - bool _check_pattern; - bool _delete_on_exit; - - SInfo(); -}; -int SInfo::id_count = 0; - -static std::vector m_sockets; - -static enum { - PRINT_DISABLED, - PRINT_STRING, - PRINT_HEX -} printing_mode = PRINT_STRING; -static int printing_col_width = 20; - -static int cmd_socket(int argc, char *argv[]); -static void print_data(const uint8_t *buf, int len); -static void print_data_as_string(const uint8_t *buf, int len, int col_width); -static void print_data_as_hex(const uint8_t *buf, int len, int col_width); - -/** Generate RFC 864 example pattern. - * - * Pattern is 72 chraracter lines of the ASCII printing characters ending with "\r\n". - * There are 95 printing characters in the ASCII character set. - * Example: `nc echo.mbedcloudtesting.com 19 | dd bs=1 count=222` - * !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg - * !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefgh - * "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi - * - * NOTE: Pattern starts with space, not ! - * - * \param offset Start pattern from offset - * \param len Length of pattern to generate. - */ -static void generate_RFC_864_pattern(size_t offset, uint8_t *buf, size_t len, bool is_xinetd) -{ - const int row_size = 74; // Number of chars in single row - const int row_count = 95; // Number of rows in pattern after which pattern start from beginning - const int chars_scope = is_xinetd ? 93 : 95; // Number of chars from ASCII table used in pattern - const char first_char = is_xinetd ? '!' : ' '; // First char from ASCII table used in pattern - while (len--) { - if (offset % row_size == (row_size - 2)) { - *buf++ = '\r'; - } else if (offset % row_size == (row_size - 1)) { - *buf++ = '\n'; - } else { - *buf++ = first_char + (offset % row_size + ((offset / row_size) % row_count)) % chars_scope; - } - offset++; - } -} - -static int get_cert_from_file(const char *filename, char **cert) -{ - int filedesc = open(filename, O_RDONLY); - if (filedesc < 0) { - cmd_printf("Cannot open file: %s\r\n", filename); - return CMDLINE_RETCODE_FAIL; - } - - if (read(filedesc, *cert, CERT_BUFFER_SIZE) != CERT_BUFFER_SIZE) { - cmd_printf("Cannot read from file %s\r\n", filename); - return CMDLINE_RETCODE_FAIL; - } - - return CMDLINE_RETCODE_SUCCESS; -} - -bool SInfo::check_pattern(void *buffer, size_t len) -{ - static bool is_xinetd = false; - if (!_check_pattern) { - return true; - } - void *buf = malloc(len); - if (!buf) { - return false; - } - - size_t offset = _receivedTotal; - - if (offset == 0) { - is_xinetd = ((uint8_t *)buffer)[0] == '!'; - } - - generate_RFC_864_pattern(offset, (uint8_t *)buf, len, is_xinetd); - bool match = memcmp(buf, buffer, len) == 0; - if (!match) { - cmd_printf("Pattern check failed\r\nWAS:%.*s\r\nREF:%.*s\r\n", len, (char *)buffer, len, (char *)buf); - } - free(buf); - return match; -} - -static void sigio_handler(SInfo *info) -{ - if (info->getReceiverThreadId()) { - osSignalSet(info->getReceiverThreadId(), SIGNAL_SIGIO); - } - if (info->getSenderThreadId()) { - osSignalSet(info->getSenderThreadId(), SIGNAL_SIGIO); - } -} - -void cmd_socket_init(void) -{ - cmd_add("socket", cmd_socket, "socket", MAN_SOCKET); - cmd_alias_add("socket help", "socket -h"); - cmd_alias_add("socket --help", "socket -h"); - cmd_alias_add("ping server start", "socket echo-server new start"); -} - -int handle_nsapi_error(const char *function, nsapi_error_t ret) -{ - if (ret != NSAPI_ERROR_OK) { - cmd_printf("%s returned: %d -> %s\r\n", function, ret, networkstack_error_to_str(ret)); - return CMDLINE_RETCODE_FAIL; - } - return CMDLINE_RETCODE_SUCCESS; -} - -int handle_nsapi_size_or_error(const char *function, nsapi_size_or_error_t ret) -{ - if (ret < 0) { - return handle_nsapi_error(function, ret); - } else { - cmd_printf("%s returned: %d\r\n", function, ret); - } - return CMDLINE_RETCODE_SUCCESS; -} - -static SInfo *get_sinfo(int id) -{ - - for (std::vector::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) { - if ((*it)->id() == id) { - return *it; - } - } - return NULL; -} - -static int del_sinfo(SInfo *info) -{ - for (std::vector::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) { - if ((*it) == info) { - delete info; - m_sockets.erase(it); - return CMDLINE_RETCODE_SUCCESS; - } - } - return CMDLINE_RETCODE_FAIL; -} - -#if defined(MBEDTLS_SSL_CLI_C) -static int tls_set_cert(int argc, char *argv[], SInfo *info) -{ - static char read_cert[CERT_BUFFER_SIZE]; - char *ptr_cert = NULL; - char *src = NULL; - if (cmd_parameter_val(argc, argv, "--cert_file", &src)) { - tr_debug("Root ca certificate read from file: %s", src); - ptr_cert = read_cert; - if (get_cert_from_file(src, &ptr_cert) == CMDLINE_RETCODE_FAIL) { - cmd_printf("Cannot read from url: %s\r\n", src); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - } else if (cmd_parameter_index(argc, argv, "--cert_default") != -1) { - cmd_printf("Using default certificate\r\n"); - ptr_cert = (char *)cert; - } else { - cmd_printf("No cert specified. Use set_root_ca_cert to set it.\r\n"); - // Do not return error, allow the certificate not to be set. - return CMDLINE_RETCODE_SUCCESS; - } - - int ret = info->tls_socket()->set_root_ca_cert(ptr_cert); - if (ret != NSAPI_ERROR_OK) { - cmd_printf("Invalid root certificate\r\n"); - return CMDLINE_RETCODE_FAIL; - } - - return CMDLINE_RETCODE_SUCCESS; -} -#endif - -static int cmd_socket_new(int argc, char *argv[]) -{ - const char *s; - SInfo *info; - nsapi_error_t ret; - - if (argc > 2) { - s = argv[2]; - if (strcmp(s, "UDPSocket") == 0) { - tr_debug("Creating a new UDPSocket"); - info = new SInfo(new UDPSocket); - } else if (strcmp(s, "TCPSocket") == 0) { - tr_debug("Creating a new TCPSocket"); - info = new SInfo(new TCPSocket); - } else if (strcmp(s, "TCPServer") == 0) { - tr_debug("Creating a new TCPServer"); - info = new SInfo(new TCPServer); -#if defined(MBEDTLS_SSL_CLI_C) - } else if (strcmp(s, "TLSSocket") == 0) { - tr_debug("Creating a new TLSSocket"); - info = new SInfo(new TLSSocket); - ret = tls_set_cert(argc, argv, info); - if (ret) { - delete info; - return ret; - } -#endif - } else { - cmd_printf("unsupported protocol: %s\r\n", s); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - } else { - cmd_printf("Must specify socket type\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - // Note, this cannot fail. We either succeed or "new" woud call exit(1) in failure. - // We did not ask no_throw version of it. - cmd_printf("new socket. sid: %d\r\n", info->id()); - m_sockets.push_back(info); - return CMDLINE_RETCODE_SUCCESS; -} - -static void udp_receiver_thread(SInfo *info) -{ - SocketAddress addr; - int i = 0, received = 0; - int n = info->getRepeatBufferFill(); - int *packetSizes = info->getPacketSizeArray(); - nsapi_size_or_error_t ret = 0; - - info->setReceiverThreadId(ThisThread::get_id()); - - while (i < n) { - ret = info->socket().recvfrom(&addr, info->getReceiveBuffer() + received, info->getDataCount() - received); - if (ret > 0) { - if (!info->check_pattern(info->getReceiveBuffer() + received, ret)) { - return; - } - received += ret; - packetSizes[i % PACKET_SIZE_ARRAY_LEN] = ret; - i++; - info->setRecvTotal(info->getRecvTotal() + ret); - } else if (ret == NSAPI_ERROR_WOULD_BLOCK) { - ThisThread::flags_wait_any(SIGNAL_SIGIO); - } else { - handle_nsapi_size_or_error("Thread: Socket::recvfrom()", ret); - return; - } - } -} - -static nsapi_size_or_error_t start_udp_receiver_thread(SInfo *info, int argc, char *argv[]) -{ - int32_t max_size; - int32_t n = 1; - - if (!cmd_parameter_int(argc, argv, "--max_data_len", &max_size)) { - cmd_printf("Need data max data size\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - if (cmd_parameter_index(argc, argv, "--packets") > 0) { - if (!cmd_parameter_int(argc, argv, "--packets", &n)) { - cmd_printf("Need number of packets\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - } - uint8_t *dataIn = (uint8_t *)malloc(max_size + 1); - if (!dataIn) { - cmd_printf("malloc() failed\r\n"); - return CMDLINE_RETCODE_FAIL; - } - int *packetSizes = new (nothrow) int[PACKET_SIZE_ARRAY_LEN]; - if (!packetSizes) { - cmd_printf("Allocation failed\r\n"); - free(dataIn); - return CMDLINE_RETCODE_FAIL; - } - for (int i = 0; i < PACKET_SIZE_ARRAY_LEN; i++) { - packetSizes[i] = 0; - } - memset(dataIn, 0x00, max_size + 1); - info->setReceiveBuffer(dataIn); - info->setDataCount(max_size); - info->setRepeatBufferFill(n); - info->setPacketSizeArray(packetSizes); - info->setReceiverThread(new Thread()); - info->getReceiverThread()->start(callback(udp_receiver_thread, info)); - return CMDLINE_RETCODE_SUCCESS; -} - -static nsapi_size_or_error_t udp_sendto_command_handler(SInfo *info, int argc, char *argv[]) -{ - char *host; - int32_t port; - - if (!cmd_parameter_val(argc, argv, "sendto", &host)) { - cmd_printf("Need host name\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - if (!cmd_parameter_int(argc, argv, host, &port)) { - cmd_printf("Need port number\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - // Replace NULL-strings with NULL - host = strcmp(host, "NULL") ? host : NULL; - - int32_t len; - void *data; - if (cmd_parameter_int(argc, argv, "--data_len", &len)) { - data = malloc(len); - if (!data) { - cmd_printf("Failed to allocate memory\r\n"); - return CMDLINE_RETCODE_FAIL; - } - } else { - // Replace NULL-strings with NULL - if (strcmp(argv[5], "NULL") == 0) { - data = NULL; - len = 0; - } else { - data = argv[5]; - len = strlen(argv[5]); - } - } - - SocketAddress addr(NULL, port); - nsapi_size_or_error_t ret = get_interface()->gethostbyname(host, &addr); - if (ret) { - return handle_nsapi_size_or_error("NetworkInterface::gethostbyname()", ret); - } - ret = info->socket().sendto(addr, data, len); - if (ret > 0) { - cmd_printf("sent: %d bytes\r\n", ret); - } - if (data != argv[5]) { - free(data); - } - - return handle_nsapi_size_or_error("Socket::sendto()", ret); -} - -static nsapi_size_or_error_t udp_recvfrom_command_handler(SInfo *info, int argc, char *argv[]) -{ - SocketAddress addr; - int32_t len; - - if (!cmd_parameter_int(argc, argv, "recvfrom", &len)) { - cmd_printf("Need len\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - - void *data = malloc(len); - if (!data) { - cmd_printf("malloc() failed\r\n"); - return CMDLINE_RETCODE_FAIL; - } - nsapi_size_or_error_t ret = info->socket().recvfrom(&addr, data, len); - if (ret > 0) { - cmd_printf("Socket::recvfrom, addr=%s port=%d\r\n", addr.get_ip_address(), addr.get_port()); - cmd_printf("received: %d bytes\r\n", ret); - print_data((const uint8_t *)data, len); - if (!info->check_pattern(data, len)) { - ret = -1; - } - info->setRecvTotal(info->getRecvTotal() + ret); - } - free(data); - return handle_nsapi_size_or_error("Socket::recvfrom()", ret); -} - -static void tcp_receiver_thread(SInfo *info) -{ - int i, received; - int n = info->getRepeatBufferFill(); - int recv_len = info->getMaxRecvLen(); - int bufferSize = info->getDataCount(); - nsapi_size_or_error_t ret = 0; - - info->setReceiverThreadId(ThisThread::get_id()); - - for (i = 0; i < n; i++) { - received = 0; - while (received < bufferSize) { - ret = info->socket().recv(info->getReceiveBuffer() + received, recv_len - received); - if (ret > 0) { - if (!info->check_pattern(info->getReceiveBuffer() + received, ret)) { - return; - } - received += ret; - info->setRecvTotal(info->getRecvTotal() + ret); - } else if (ret == NSAPI_ERROR_WOULD_BLOCK) { - ThisThread::flags_wait_all(SIGNAL_SIGIO); - } else { - handle_nsapi_size_or_error("Thread: Socket::recv()", ret); - return; - } - } - } -} - -static nsapi_size_or_error_t start_tcp_receiver_thread(SInfo *info, int argc, char *argv[]) -{ - int32_t len; - int32_t recv_len; - int32_t n = 1; - - if (!cmd_parameter_int(argc, argv, "--data_len", &len)) { - cmd_printf("Need data len\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - recv_len = len; - - if (cmd_parameter_index(argc, argv, "--max_recv_len") > 0) { - if (!cmd_parameter_int(argc, argv, "--max_recv_len", &recv_len)) { - cmd_printf("Need max recv len\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - } - - if (cmd_parameter_index(argc, argv, "--repeat") > 0) { - if (!cmd_parameter_int(argc, argv, "--repeat", &n)) { - cmd_printf("Need repeat number\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - } - - uint8_t *dataIn = (uint8_t *)malloc(len + 1); - if (!dataIn) { - cmd_printf("malloc() failed\r\n"); - return CMDLINE_RETCODE_FAIL; - } - - info->setReceiveBuffer(dataIn); - info->setDataCount(len); - info->setMaxRecvLen(recv_len); - info->setRepeatBufferFill(n); - info->setReceiverThread(new Thread()); - info->getReceiverThread()->start(callback(tcp_receiver_thread, info)); - return CMDLINE_RETCODE_SUCCESS; -} - -static nsapi_size_or_error_t tcp_send_command_handler(SInfo *info, int argc, char *argv[]) -{ - int32_t len; - void *data; - nsapi_size_or_error_t ret = 0; - - info->setSenderThreadId(ThisThread::get_id()); - - if (cmd_parameter_int(argc, argv, "--data_len", &len)) { - data = malloc(len); - if (!data) { - cmd_printf("Failed to allocate memory\r\n"); - return CMDLINE_RETCODE_FAIL; - } - } else { - data = argv[3]; - len = strlen(argv[3]); - } - - ret = info->socket().send(data, len); - - if (ret > 0) { - cmd_printf("sent: %d bytes\r\n", ret); - } - if (data != argv[3]) { - free(data); - } - return handle_nsapi_size_or_error("Socket::send()", ret); -} - -static nsapi_size_or_error_t tcp_recv_command_handler(SInfo *info, int argc, char *argv[]) -{ - int32_t len; - - if (!cmd_parameter_int(argc, argv, "recv", &len)) { - cmd_printf("Need length\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - - void *data = malloc(len); - if (!data) { - cmd_printf("malloc() failed\r\n"); - return CMDLINE_RETCODE_FAIL; - } - - nsapi_size_or_error_t ret = info->socket().recv(data, len); - if (ret > 0) { - cmd_printf("received: %d bytes\r\n", ret); - print_data((const uint8_t *)data, ret); - if (!info->check_pattern(data, ret)) { - ret = -1; - } - info->setRecvTotal(info->getRecvTotal() + ret); - } - free(data); - return handle_nsapi_size_or_error("Socket::recv()", ret); -} - -static nsapi_size_or_error_t recv_all(char *const rbuffer, const int expt_len, SInfo *const info) -{ - int rtotal, rbytes; - char *rhead; - - rtotal = 0; - rhead = rbuffer; - - while (rtotal < expt_len) { - rbytes = info->socket().recv(rhead, expt_len); - if (rbytes <= 0) { // Connection closed abruptly - rbuffer[rtotal] = '\0'; - return rbytes; - } - rtotal += rbytes; - rhead = rbuffer + rtotal; - } - rbuffer[rtotal] = '\0'; - info->setRecvTotal(info->getRecvTotal() + rtotal); - return rtotal; -} - -static void bg_traffic_thread(SInfo *info) -{ - static const int data_len = 10; - char sbuffer[data_len + 1] = "dummydata_"; - char rbuffer[data_len + 1]; - int scount, rtotal = 0; - info->setSenderThreadId(ThisThread::get_id()); - - for (;;) { - if (!info->available()) { - (void)handle_nsapi_size_or_error(__func__, rtotal); - break; - } - sbuffer[data_len - 1] = 'A' + (rand() % 26); - scount = info->socket().send(sbuffer, data_len); - rtotal = recv_all(rbuffer, data_len, info); - - if (scount != rtotal || (strcmp(sbuffer, rbuffer) != 0)) { - info->setUnavailable(); - - tr_err("Background received data does not match to sent data"); - tr_err("Background sent: \"%s\"", sbuffer); - tr_err("Background received: \"%s\"", rbuffer); - } - ThisThread::sleep_for(10); - } -} - -static nsapi_size_or_error_t start_bg_traffic_thread(SInfo *info, int argc, char *argv[]) -{ - info->setReceiverThread(new Thread()); - info->setAvailable(); - info->getReceiverThread()->start(callback(bg_traffic_thread, info)); - return CMDLINE_RETCODE_SUCCESS; -} - -static void thread_clean_up(SInfo *info) -{ - if (info->getReceiverThread()) { - delete info->getReceiverThread(); - info->setReceiverThread(NULL); - } - if (info->getReceiveBuffer()) { - delete info->getReceiveBuffer(); - info->setReceiveBuffer(NULL); - } - if (info->getPacketSizeArray()) { - delete[] info->getPacketSizeArray(); - info->setPacketSizeArray(NULL); - } -} - -static int cmd_socket(int argc, char *argv[]) -{ - if (cmd_parameter_index(argc, argv, "new") == 1) { - return cmd_socket_new(argc, argv); - } else if (cmd_parameter_index(argc, argv, "print-mode") > 0) { - if (cmd_parameter_index(argc, argv, "--string") > 0) { - printing_mode = PRINT_STRING; - } else if (cmd_parameter_index(argc, argv, "--hex") > 0) { - printing_mode = PRINT_HEX; - } else if (cmd_parameter_index(argc, argv, "--disabled") > 0) { - printing_mode = PRINT_DISABLED; - } - int32_t parsed_col_width = 0; - if (cmd_parameter_int(argc, argv, "--col-width", &parsed_col_width)) { - if (parsed_col_width <= 0) { - cmd_printf("Printing column width must be > 0"); - return CMDLINE_RETCODE_FAIL; - } - if (printing_mode == PRINT_HEX && parsed_col_width > 42) { - cmd_printf("Maximum column width for hex data is 42 bytes"); - return CMDLINE_RETCODE_FAIL; - } - printing_col_width = (int)parsed_col_width; - } - // Allow print-mode to be used as a parameter to other commands - if (cmd_parameter_index(argc, argv, "print-mode") == 1) { - return CMDLINE_RETCODE_SUCCESS; - } - } - - // Rest of the commands require Socket - SInfo *info = get_sinfo(strtol(argv[1], NULL, 10)); - if (!info) { - cmd_printf("Invalid socket id %s\r\n", argv[1]); - return CMDLINE_RETCODE_FAIL; - } - - bool enable_pattern_check; - if (cmd_parameter_bool(argc, argv, "set_RFC_864_pattern_check", &enable_pattern_check)) { - info->set_pattern_check(enable_pattern_check); - return CMDLINE_RETCODE_SUCCESS; - } - - // Helper macro for checking the which command was given -#define COMMAND_IS(cmd) (cmd_parameter_index(argc, argv, cmd) == 2) - - /* - * Generic Socket commands: - * delete, open, close, bind, set_blocking, set_timeout - */ - - if (COMMAND_IS("delete")) { - return del_sinfo(info); - - } else if (COMMAND_IS("open")) { - NetworkInterface *interface; - - interface = get_interface(); // get default interface - - if (!interface) { - cmd_printf("Invalid interface\r\n"); - return CMDLINE_RETCODE_FAIL; - } - - switch (info->type()) { - case SInfo::IP: - return handle_nsapi_error("Socket::open()", info->internetsocket()->open(interface)); - case SInfo::TCP_SERVER: - return handle_nsapi_error("TCPServer::open()", info->tcp_server()->open(interface)); -#if defined(MBEDTLS_SSL_CLI_C) - case SInfo::TLS: - return handle_nsapi_error("Socket::open()", info->tls_socket()->open(interface)); -#endif - default: - cmd_printf("Not a IP socket\r\n"); - return CMDLINE_RETCODE_FAIL; - } - } else if (COMMAND_IS("close")) { - return handle_nsapi_error("Socket::close()", info->socket().close()); - - } else if (COMMAND_IS("bind")) { - int32_t port = 0; - char *addr; - - if (!cmd_parameter_int(argc, argv, "port", &port) && !cmd_parameter_int(argc, argv, "bind", &port) && port <= 0 && port > 65535) { - printf("Missing or invalid port number\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - - if (cmd_parameter_val(argc, argv, "addr", &addr)) { - // Replace NULL-strings with NULL - addr = strcmp(addr, "NULL") ? addr : NULL; - cmd_printf("Socket::bind(%s, %" PRId32 ")\r\n", addr, port); - SocketAddress tmp(addr, port); - return handle_nsapi_error("Socket::bind(addr, port)", info->socket().bind(tmp)); - } else { - cmd_printf("Socket::bind(%" PRId32 ")\r\n", port); - SocketAddress tmp(NULL, port); - return handle_nsapi_error("Socket::bind(port)", info->socket().bind(tmp)); - } - - } else if (COMMAND_IS("set_blocking")) { - bool val; - if (!cmd_parameter_bool(argc, argv, "set_blocking", &val)) { - cmd_printf("Need boolean value"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - info->set_blocking(val); - return CMDLINE_RETCODE_SUCCESS; - - } else if (COMMAND_IS("set_timeout")) { - int32_t ms; - if (!cmd_parameter_int(argc, argv, "set_timeout", &ms)) { - cmd_printf("Need timeout value"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - if (ms == -1) { - info->set_blocking(true); - } else { - info->set_blocking(false); - } - - info->socket().set_timeout(ms); - return CMDLINE_RETCODE_SUCCESS; - - } else if (COMMAND_IS("register_sigio_cb")) { - info->socket().sigio(callback(sigio_handler, info)); - return CMDLINE_RETCODE_SUCCESS; - } - - - /* - * Commands related to UDPSocket: - * sendto, recvfrom - */ - if (COMMAND_IS("sendto")) { - return udp_sendto_command_handler(info, argc, argv); - } else if (COMMAND_IS("recvfrom")) { - return udp_recvfrom_command_handler(info, argc, argv); - } else if (COMMAND_IS("start_udp_receiver_thread")) { - return start_udp_receiver_thread(info, argc, argv); - } else if (COMMAND_IS("last_data_received")) { - print_data((const uint8_t *)info->getReceiveBuffer(), info->getDataCount()); - if (info->getPacketSizeArray()) { - int *packetSizes = info->getPacketSizeArray(); - cmd_printf("packet_sizes: "); - for (int i = 0; i < PACKET_SIZE_ARRAY_LEN; i++) { - cmd_printf("%d ", packetSizes[i]); - } - cmd_printf("\r\n"); - } - if (info->getReceiverThread()) { - info->getReceiverThread()->terminate(); - } - thread_clean_up(info); - - return handle_nsapi_error("Socket::last_data_received()", NSAPI_ERROR_OK); - } - - /* - * Commands related to TCPSocket, TLSSocket - * connect, send, recv - */ - if (COMMAND_IS("connect")) { - char *host; - int32_t port; - - if (!cmd_parameter_val(argc, argv, "connect", &host)) { - cmd_printf("Need host name\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - if (!cmd_parameter_int(argc, argv, host, &port)) { - cmd_printf("Need port number\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - if (strcmp(host, "NULL") == 0) { - host = NULL; - } - - cmd_printf("Host name: %s port: %" PRId32 "\r\n", host, port); - if (info->type() == SInfo::IP) { - SocketAddress addr(NULL, port); - nsapi_error_t ret = get_interface()->gethostbyname(host, &addr); - if (ret) { - return handle_nsapi_error("NetworkInterface::gethostbyname()", ret); - } - return handle_nsapi_error("Socket::connect()", info->socket().connect(addr)); -#if defined(MBEDTLS_SSL_CLI_C) - } else if (info->type() == SInfo::TLS) { - return handle_nsapi_error("TLSSocket::connect()", static_cast(info->socket()).connect(host, port)); -#endif - } - - } else if (COMMAND_IS("send")) { - return tcp_send_command_handler(info, argc, argv); - - } else if (COMMAND_IS("recv")) { - return tcp_recv_command_handler(info, argc, argv); - - } else if (COMMAND_IS("start_tcp_receiver_thread")) { - return start_tcp_receiver_thread(info, argc, argv); - - } else if (COMMAND_IS("join_tcp_receiver_thread")) { - info->getReceiverThread()->join(); - print_data((const uint8_t *)info->getReceiveBuffer(), info->getDataCount()); - cmd_printf("received: %d bytes\r\n", info->getRecvTotal()); - - thread_clean_up(info); - - return CMDLINE_RETCODE_SUCCESS; - - } else if (COMMAND_IS("start_bg_traffic_thread")) { - return start_bg_traffic_thread(info, argc, argv); - - } else if (COMMAND_IS("join_bg_traffic_thread")) { - int bg_thread_success = CMDLINE_RETCODE_SUCCESS; - - if (!info->available()) { // Tells that background thread stumbled to an issue and stopped prematurely - bg_thread_success = CMDLINE_RETCODE_FAIL; - } - - info->setUnavailable(); - info->getReceiverThread()->join(); - thread_clean_up(info); - - return bg_thread_success; - } else if (COMMAND_IS("setsockopt_keepalive")) { - int32_t seconds; - nsapi_error_t ret; - if (!cmd_parameter_int(argc, argv, "setsockopt_keepalive", &seconds)) { - cmd_printf("Need keep-alive value(0-7200seconds)"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - - ret = info->socket().setsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &seconds, sizeof(seconds)); - - return handle_nsapi_error("Socket::setsockopt()", ret); - } else if (COMMAND_IS("getsockopt_keepalive")) { - int32_t optval; - unsigned optlen = sizeof(optval); - nsapi_error_t ret; - - ret = info->socket().getsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &optval, &optlen); - - if (optlen != sizeof(int)) { - return CMDLINE_RETCODE_FAIL; - } - if (ret < 0) { - return handle_nsapi_error("Socket::getsockopt()", ret); - } - return handle_nsapi_size_or_error("Socket::getsockopt()", optval); - } - - /* - * Commands for TCPServer - * listen, accept - */ - if (COMMAND_IS("listen")) { - int32_t backlog; - if (cmd_parameter_int(argc, argv, "listen", &backlog)) { - return handle_nsapi_error("TCPServer::listen()", info->socket().listen(backlog)); - } else { - return handle_nsapi_error("TCPServer::listen()", info->socket().listen()); - } - - } else if (COMMAND_IS("accept")) { - nsapi_error_t ret; - - if (info->type() != SInfo::TCP_SERVER) { - Socket *new_sock = info->socket().accept(&ret); - if (ret == NSAPI_ERROR_OK) { - SInfo *new_info = new SInfo(new_sock, false); - m_sockets.push_back(new_info); - cmd_printf("Socket::accept() new socket sid: %d\r\n", new_info->id()); - } - return handle_nsapi_error("Socket::accept()", ret); - } else { // Old TCPServer API - int32_t id; - SocketAddress addr; - - if (!cmd_parameter_int(argc, argv, "accept", &id)) { - cmd_printf("Need new socket id\r\n"); - return CMDLINE_RETCODE_INVALID_PARAMETERS; - } - SInfo *new_info = get_sinfo(id); - if (!new_info) { - cmd_printf("Invalid socket id\r\n"); - return CMDLINE_RETCODE_FAIL; - } - TCPSocket *new_sock = static_cast(&new_info->socket()); - nsapi_error_t ret = static_cast(info->socket()).accept(new_sock, &addr); - if (ret == NSAPI_ERROR_OK) { - cmd_printf("TCPServer::accept() new socket sid: %d connection from %s port %d\r\n", - new_info->id(), addr.get_ip_address(), addr.get_port()); - } - return handle_nsapi_error("TCPServer::accept()", ret); - } - } - - - /* - * Commands for TLSSocket - * set_root_ca_cert - */ -#if defined(MBEDTLS_SSL_CLI_C) - if (COMMAND_IS("set_root_ca_cert")) { - if (info->type() != SInfo::TLS) { - cmd_printf("Not a TLS socket.\r\n"); - return CMDLINE_RETCODE_FAIL; - } - return handle_nsapi_error("TLSSocket::tls_set_cert", tls_set_cert(argc, argv, info)); - } -#endif - - return CMDLINE_RETCODE_INVALID_PARAMETERS; -} - -void print_data(const uint8_t *buf, int len) -{ - switch (printing_mode) { - case PRINT_STRING: - print_data_as_string(buf, len, printing_col_width); - break; - case PRINT_HEX: - print_data_as_hex(buf, len, printing_col_width); - break; - case PRINT_DISABLED: - break; - default: - MBED_ASSERT(0); - } -} - -void print_data_as_string(const uint8_t *buf, int len, int col_width) -{ - int printable_bytes; - for (printable_bytes = 0; printable_bytes < len; printable_bytes++) { - if (!isprint(buf[printable_bytes])) { - break; - } - } - - cmd_mutex_lock(); - cmd_printf("string data, printing %d bytes:\r\n", len); - for (int i = 0; i < printable_bytes; i += col_width) { - if (printable_bytes - i > col_width) { - cmd_printf("%04d: %.*s\r\n", i, col_width, buf + i); - } else { - cmd_printf("%04d: %.*s\r\n", i, printable_bytes - i, buf + i); - } - } - cmd_printf("Printed %d bytes\r\n", printable_bytes); - - if (len != printable_bytes) { - cmd_printf("Error! Couldn't print all data. " - "Unprintable character: 0x%02x found at index: %d\r\n", - buf[printable_bytes], printable_bytes); - } - cmd_mutex_unlock(); -} - -void print_data_as_hex(const uint8_t *buf, int len, int col_width) -{ - cmd_mutex_lock(); - cmd_printf("hex data, printing %d bytes:\r\n", len); - for (int i = 0; i < len; i += col_width) { - if (len - i > col_width) { - cmd_printf("%04d: %s:\r\n", i, print_array(buf + i, col_width)); - } else { - cmd_printf("%04d: %s\r\n", i, print_array(buf + i, len - i)); - } - } - cmd_printf("Printed %d bytes\r\n", len); - cmd_mutex_unlock(); -} diff --git a/TEST_APPS/device/socket_app/cmd_socket.h b/TEST_APPS/device/socket_app/cmd_socket.h deleted file mode 100644 index 9e2239c790..0000000000 --- a/TEST_APPS/device/socket_app/cmd_socket.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2018 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CMD_SOCKET_H_ -#define CMD_SOCKET_H_ - -#include "nsapi_types.h" - -int handle_nsapi_error(const char *function, nsapi_error_t ret); -int handle_nsapi_size_or_error(const char *function, nsapi_size_or_error_t ret); -void cmd_socket_init(void); - -#endif diff --git a/TEST_APPS/device/socket_app/main.cpp b/TEST_APPS/device/socket_app/main.cpp deleted file mode 100644 index 7c24bdc33a..0000000000 --- a/TEST_APPS/device/socket_app/main.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2018 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "mbed.h" -#include "mbed-client-cli/ns_cmdline.h" -#include "cmd_ifconfig.h" -#include "cmd_socket.h" - -/** - * Macros for setting console flow control. - */ -#define CONSOLE_FLOWCONTROL_RTS 1 -#define CONSOLE_FLOWCONTROL_CTS 2 -#define CONSOLE_FLOWCONTROL_RTSCTS 3 -#define mbed_console_concat_(x) CONSOLE_FLOWCONTROL_##x -#define mbed_console_concat(x) mbed_console_concat_(x) -#define CONSOLE_FLOWCONTROL mbed_console_concat(MBED_CONF_TARGET_CONSOLE_UART_FLOW_CONTROL) - -#define SERIAL_CONSOLE_BAUD_RATE 115200 - -void cmd_ready_cb(int retcode) -{ - cmd_next(retcode); -} - -void wrap_printf(const char *f, va_list a) -{ - vprintf(f, a); -} - -int main() -{ - cmd_init(&wrap_printf); - cmd_ifconfig_init(); - cmd_socket_init(); - - int c; - while ((c = getchar()) != EOF) { - cmd_char_input(c); - } - return 0; -} - -FileHandle *mbed::mbed_override_console(int) -{ - static BufferedSerial console(STDIO_UART_TX, STDIO_UART_RX, SERIAL_CONSOLE_BAUD_RATE); -#if CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTS - console.set_flow_control(SerialBase::RTS, STDIO_UART_RTS, NC); -#elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_CTS - console.set_flow_control(SerialBase::CTS, NC, STDIO_UART_CTS); -#elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTSCTS - console.set_flow_control(SerialBase::RTSCTS, STDIO_UART_RTS, STDIO_UART_CTS); -#endif - return &console; -} diff --git a/TEST_APPS/device/socket_app/mbed_app.json b/TEST_APPS/device/socket_app/mbed_app.json deleted file mode 100644 index 1f697c529f..0000000000 --- a/TEST_APPS/device/socket_app/mbed_app.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "macros": [ - "MEM_ALLOC=malloc", - "MEM_FREE=free", - "MBED_HEAP_STATS_ENABLED=1", - "MBED_MEM_TRACING_ENABLED" - ], - "target_overrides": { - "*": { - "mbed-trace.enable": 1, - "platform.stdio-baud-rate": 115200, - "platform.stdio-convert-newlines": true, - "platform.stdio-buffered-serial": true, - "platform.stdio-flush-at-exit": true, - "drivers.uart-serial-rxbuf-size": 768 - } - } -} diff --git a/TEST_APPS/device/socket_app/strconv.c b/TEST_APPS/device/socket_app/strconv.c deleted file mode 100644 index 720cf44683..0000000000 --- a/TEST_APPS/device/socket_app/strconv.c +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2018 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include -#include - -#include "ip6string.h" -#include "strconv.h" - - -int8_t strtohex(uint8_t *out, const char *str, int8_t max_length) -{ - int8_t i = 0; - char *rd = (char *)str; - uint8_t *wr = out; - while (*rd != 0) { - if (i > max_length) { - break; - } - *wr++ = strtoul(rd, &rd, 16); - while (!isxdigit((int)*rd) && *rd != 0) { - rd++; //skip some invalid characters - } - i++; - } - return i; -} - -int hexstr_to_bytes_inplace(char *str) -{ - int16_t len, i, j; - if (str == NULL) { - return -1; - } - len = strlen(str); - if (len < 2 || (len + 1) % 3 != 0) { - return -1; - } - for (i = 0, j = 0; i < len; i += 3, ++j) { - str[j] = (char)strtol(str + i, 0, 16); - } - return j; -} - -// convert hex string (eg. "76 ab ff") to binary array -int string_to_bytes(const char *str, uint8_t *buf, int bytes) -{ - int len = strlen(str); - if (len <= (3 * bytes - 1)) { - int i; - for (i = 0; i < bytes; i++) { - if (i * 3 < len) { - buf[i] = (uint8_t)strtoul(str + i * 3, 0, 16); - } else { - buf[i] = 0; - } - } - return 0; - } - return -1; -} - -int16_t hextostr(const uint8_t *buf, uint16_t buf_length, char *out, int16_t out_length, char delimiter) -{ - int16_t outLeft = out_length; - int16_t arrLeft = buf_length; - const uint8_t *rd = buf; - int retcode = 0; - char *wr = out; - while (arrLeft > 0 && outLeft > 0) { - retcode = snprintf(wr, outLeft, "%02x", *rd); - - if (retcode <= 0 || retcode >= outLeft) { - break; - } - outLeft -= retcode; - wr += retcode; - arrLeft --; - rd++; - if (delimiter && arrLeft > 0 && outLeft > 0) { - *wr++ = delimiter; - outLeft--; - *wr = 0; - } - } - return (int16_t)(wr - out); -} -int replace_hexdata(char *str) -{ - char *ptr = str; - if (str == NULL) { - return 0; - } - while (*ptr) { - if (ptr[0] == '\\') { - if (ptr[1] == 'n') { - ptr[0] = 0x0a; - memmove(ptr + 1, ptr + 2, strlen(ptr + 2) + 1); - } else if (ptr[1] == 'r') { - ptr[0] = 0x0d; - memmove(ptr + 1, ptr + 2, strlen(ptr + 2) + 1); - } else if (ptr[1] == 'x') { - char *end; - ptr[0] = (char)strtoul(ptr + 2, &end, 16); - memmove(ptr + 1, end, strlen(end) + 1); - } else if (isdigit((int)ptr[1])) { - char *end; - ptr[0] = strtoul(ptr + 1, &end, 10); - memmove(ptr + 1, end, strlen(end) + 1); - } - } - ptr++; - } - return ptr - str; -} -bool is_visible(uint8_t *buf, int len) -{ - while (len--) { - if (!isalnum(*buf) && *buf != ' ') { - return false; - } - buf++; - } - return true; -} - -char *strdupl(const char *str) -{ - if (!str) { - return NULL; - } - char *p = malloc(strlen(str) + 1); - if (!p) { - return p; - } - strcpy(p, str); - return p; -} -int strnlen_(const char *s, int n) -{ - char *end = memchr(s, 0, n); - return end ? end - s : n; -} -char *strndupl(const char *s, int n) -{ - char *p = NULL; - int len = strnlen_(s, n); - p = malloc(len + 1); - if (!p) { - return p; - } - p[len] = 0; - return memcpy(p, s, len); -} -int strnicmp_(char const *a, char const *b, int n) -{ - for (; (n > 0 && *a != 0 && *b != 0) ; a++, b++, n--) { - int d = tolower((int) * a) - tolower((int) * b); - if (d != 0 || !*a) { - return d; - } - } - return 0; -} - - -/* HELPING PRINT FUNCTIONS for cmd_printf */ - -static inline uint8_t context_split_mask(uint_fast8_t split_value) -{ - return (uint8_t) - (0x100u >> split_value); -} - -static uint8_t *bitcopy(uint8_t *restrict dst, const uint8_t *restrict src, uint_fast8_t bits) -{ - uint_fast8_t bytes = bits / 8; - bits %= 8; - - if (bytes) { - dst = (uint8_t *) memcpy(dst, src, bytes) + bytes; - src += bytes; - } - - if (bits) { - uint_fast8_t split_bit = context_split_mask(bits); - *dst = (*src & split_bit) | (*dst & ~ split_bit); - } - - return dst; -} - -char tmp_print_buffer[128] = {0}; - -char *print_ipv6(const void *addr_ptr) -{ - ip6tos(addr_ptr, tmp_print_buffer); - return tmp_print_buffer; -} -char *print_ipv6_prefix(const uint8_t *prefix, uint8_t prefix_len) -{ - char *str = tmp_print_buffer; - int retval; - char tmp[40]; - uint8_t addr[16] = {0}; - - if (prefix_len != 0) { - if (prefix == NULL || prefix_len > 128) { - return ""; - } - bitcopy(addr, prefix, prefix_len); - } - - ip6tos(addr, tmp); - retval = snprintf(str, 128, "%s/%u", tmp, prefix_len); - if (retval <= 0) { - return ""; - } - return str; -} -char *print_array(const uint8_t *buf, uint16_t len) -{ - int16_t retcode = hextostr(buf, len, tmp_print_buffer, 128, ':'); - if (retcode > 0) { - //yeah, something is converted - } - return tmp_print_buffer; -} - diff --git a/TEST_APPS/device/socket_app/strconv.h b/TEST_APPS/device/socket_app/strconv.h deleted file mode 100644 index 4d0511c086..0000000000 --- a/TEST_APPS/device/socket_app/strconv.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2018 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STRCONVERSION_H -#define STRCONVERSION_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "ns_types.h" - -/** Convert hex string to binary array - * e.g. - * char str[] = {30, 31, 32, 33}; - * uint8_t buffer[4]; - * strtohex( buffer, str, 4 ); - */ -int8_t strtohex(uint8_t *out, const char *str, int8_t max_length); - -/** Convert space separated hex string (eg. "76 ab ff") to binary array. - */ -int string_to_bytes(const char *str, uint8_t *buf, int bytes); - -/** Convert a colon/space separated hex string (eg. "76:ab:ff") to binary - * array (inplace) returning the number of the bytes in the array. - */ -int hexstr_to_bytes_inplace(char *str); - -/** Convert hex array to string - */ -int16_t hextostr(const uint8_t *buf, uint16_t buf_length, char *out, int16_t out_length, char delimiter); -/** Replace hex characters from string - * e.g. - * "hello\\n" -> "hello\n" - * "hello\\r" -> "hello\r" - * "val: \\10" -> "val: \x0a" //integer - * "val: \\x10" -> "val: \x10" //hex value - * @param str string that will be replaced - * @return length - */ -int replace_hexdata(char *str); -/** - * check if array contains only visible characters - * = isalpha | isdigit - */ -bool is_visible(uint8_t *buf, int len); - -/** Convert ipv6 address to string format - */ -char *print_ipv6(const void *addr_ptr); -/** Convert ipv6 prefix to string format - */ -char *print_ipv6_prefix(const uint8_t *prefix, uint8_t prefix_len); -/** Convert binary array to string format and return static results - */ -char *print_array(const uint8_t *buf, uint16_t len); -/** The strdupl() function shall return a pointer to a new string, - * which is a duplicate of the string pointed to by s1. The returned pointer can be passed to free(). - * A null pointer is returned if the new string cannot be created. - * strdupl are same than linux strdup, but this way we avoid to duplicate reference in linux - */ -char *strdupl(const char *str); -/** The strdup() function returns a pointer to a new string which is a duplicate of the string. - * Memory for the new string is obtained with malloc(3), and can be freed with free(3). - * The strndup() function is similar, but only copies at most n bytes. If s is longer than n, - * only n bytes are copied, and a terminating null byte ('\0') is added. - */ -char *strndupl(const char *s, int n); -/** strnlen - determine the length of a fixed-size string - * The strnlen() function returns the number of bytes in the string pointed to by s, excluding the terminating null bye ('\0'), but at most maxlen. - * In doing this, strnlen() looks only at the first maxlen bytes at s and never beyond s+maxlen. - * The strnlen() function returns strlen(s), if that is less than maxlen, or maxlen if there is no null byte ('\0') - * among the first maxlen bytes pointed to by s. - */ -int strnlen_(const char *s, int n); -/** strnicmp compares a and b without sensitivity to case. - * All alphabetic characters in the two arguments a and b are converted to lowercase before the comparison. - */ -int strnicmp_(char const *a, char const *b, int n); - -#ifdef __cplusplus -} -#endif -#endif - diff --git a/TEST_APPS/testcases/README.md b/TEST_APPS/testcases/README.md index 3066f33339..a3aec02ff4 100644 --- a/TEST_APPS/testcases/README.md +++ b/TEST_APPS/testcases/README.md @@ -10,6 +10,5 @@ Testcases Current testcases: -- [`netsocket`](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/testcases/netsocket) - [`example`](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/testcases/example) - [`nanostack_mac_tester`](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/testcases/nanostack_mac_tester) diff --git a/TEST_APPS/testcases/netsocket/README.md b/TEST_APPS/testcases/netsocket/README.md deleted file mode 100644 index 8906ab05ea..0000000000 --- a/TEST_APPS/testcases/netsocket/README.md +++ /dev/null @@ -1,113 +0,0 @@ -##Netsocket tests - -This folder contains netsocket tests for Icetea -The tests located in this folder are dependent of the application [`socket_app`](https://github.com/ARMmbed/mbed-os/blob/master/TEST_APPS/device/socket_app) - -The test cases in this folder are similar to [Network Socket test plan](https://github.com/ARMmbed/mbed-os/blob/master/TESTS/netsocket/README.md). - -Icetea test cases are processed by passing commands through the `mbed-client-cli` command line. It is possible to manually replicate most test cases by following the instructions below. - -In test cases with more than one device under test (DUT) the target device is given in the instructions as DUT1, DUT2 or DUT3. - -## Test cases - -### `SOCKET_BIND_PORT` - -**Description:** - -Open and bind port. - -**Preconditions:** - -1. Network interface and stack are initialized. -2. Network connection is up. - -**Test steps:** - -1. Create a object by calling `socket new TCPSocket` on device -2. Call `socket TCPSocket open` -3. Call `socket TCPSocket bind port ` -4. Destroy socket `socket TCPSocket delete` -5. Create a object by calling `socket new UDPSocket` on device -6. Call `socket UDPSocket open` -7. Call `socket UDPSocket bind port ` -8. Destroy socket `socket UDPSocket delete` - -**Expected result:** - -The test exits with status `PASS` without timeouts. - -### `TCPSERVER_ACCEPT` - -**Description:** - -Test that `TCPServer::bind()`, `TCPServer::listen()` -and `TCPServer::accept()` works. - -Requires 2 devices. - -**Preconditions:** - -1. Network interface and stack are initialized. -2. Network connection is up. - -**Test steps:** - -1. DUT1: `socket new TCPServer` - Command returns server base socket ID -2. DUT1: `socket open)` -3. DUT1: `socket bind port )` -4. DUT1: `socket listen)` -5. DUT1: Create a new TCPSocket `socket new TCPSocket` - Command returns server socket ID -6. DUT1: `socket open` -7. DUT2: Create a new TCPSocket `socket new TCPSocket` - Command returns client socket ID -8. DUT2: `socket open` -9. DUT2: `socket connect ` -10. DUT1: `socket accept ` - Command should return new socket ID -11. DUT1: `socket send hello` -12. DUT2: `socket recv 5` -13. DUT2: Verify that it received "hello" -14. Destroy all sockets. - -**Expected result:** - -On DUT1 accept() call blocks until connection is received. Duration -of call verified to be within threshold. - -The test exits with status `PASS` without timeouts. - -### `TCPSOCKET_ECHOTEST_BURST_SHORT` - -**Description:** - -Send burst of packets to echo server and read incoming packets back. - -**Preconditions:** - -1. Network interface and stack are initialized. -2. Network connection is up. -3. TCPSocket is open. - -**Test steps:** - -1. Call `socket open` -2. Call `socket connect echo.mbedcloudtesting.com 7` - 1. Create 5 randomized strings - (100, 200, 300, 120 and 500 characters) - 2. Send each string `socket send ` - 3. Receive total size of sent data - `socket recv ` - 4. Verify that received data is identical to sent data -3. Repeat 2 times -4. Destroy the socket - -**Expected result:** - -All send() calls should return the packet size. - -The received data matches the sent data. - -The test exits with status `PASS` without timeouts. diff --git a/TEST_APPS/testcases/netsocket/SOCKET_BIND_PORT.py b/TEST_APPS/testcases/netsocket/SOCKET_BIND_PORT.py deleted file mode 100644 index d7d9d199d9..0000000000 --- a/TEST_APPS/testcases/netsocket/SOCKET_BIND_PORT.py +++ /dev/null @@ -1,73 +0,0 @@ -""" -Copyright 2018 ARM Limited -SPDX-License-Identifier: Apache-2.0 - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -""" -from icetea_lib.bench import Bench -from icetea_lib.tools import test_case - - -class MultipleTestcase(Bench): - def __init__(self, **kwargs): - testcase_args = { - 'status': "released", - 'component': ["mbed-os", "netsocket"], - 'type': "smoke", - 'subtype': "socket", - 'requirements': { - "duts": { - "*": { - "count": 1, - "type": "hardware", - "application": {"name": "TEST_APPS-device-socket_app"} - }, - "1": {"nick": "dut1"}, - } - } - } - - testcase_args.update(kwargs) - Bench.__init__(self, **testcase_args) - - def setup(self): - self.command("dut1", "ifup") - - def socket_bind_port(self, socket_type): - response = self.command("dut1", "socket new " + socket_type) - self.socket_id = int(response.parsed['socket_id']) - - self.command("dut1", "socket " + str(self.socket_id) + " open") - - self.command("dut1", "socket " + str(self.socket_id) + " bind port 1024") - - def teardown(self): - self.command("dut1", "socket " + str(self.socket_id) + " delete") - - self.command("dut1", "ifdown") - - -@test_case(MultipleTestcase, - name="TCPSOCKET_BIND_PORT", - title="tcpsocket open and bind port", - purpose="Verify TCPSocket can be created, opened and port binded") -def test1(self): - self.socket_bind_port("TCPSocket") - - -@test_case(MultipleTestcase, - name="UDPSOCKET_BIND_PORT", - title="udpsocket open and bind port", - purpose="Verify UDPSocket can be created, opened and port binded") -def test2(self): - self.socket_bind_port("UDPSocket") diff --git a/TEST_APPS/testcases/netsocket/TCPSERVER_ACCEPT.py b/TEST_APPS/testcases/netsocket/TCPSERVER_ACCEPT.py deleted file mode 100644 index e8080bd591..0000000000 --- a/TEST_APPS/testcases/netsocket/TCPSERVER_ACCEPT.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -Copyright 2018 ARM Limited -SPDX-License-Identifier: Apache-2.0 - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -""" - -import threading -import time - -from icetea_lib.TestStepError import TestStepFail -from icetea_lib.bench import Bench -from interface import interfaceUp, interfaceDown - - -class Testcase(Bench): - def __init__(self): - Bench.__init__(self, - name="TCPSERVER_ACCEPT", - title="TCPSERVER_ACCEPT", - purpose="Test that TCPServer::bind(), TCPServer::listen() and TCPServer::accept() works", - status="released", - component=["mbed-os", "netsocket"], - author="Juha Ylinen ", - type="smoke", - subtype="socket", - requirements={ - "duts": { - '*': { # requirements for all nodes - "count": 2, - "type": "hardware", - "application": {"name": "TEST_APPS-device-socket_app"} - }, - "1": {"nick": "dut1"}, - "2": {"nick": "dut2"} - } - } - ) - - def setup(self): - interface = interfaceUp(self, ["dut1"]) - self.server_ip = interface["dut1"]["ip"] - interface = interfaceUp(self, ["dut2"]) - self.client_ip = interface["dut2"]["ip"] - - def clientThread(self): - self.logger.info("Starting") - time.sleep(5) # wait accept from server - self.command("dut2", "socket " + str(self.client_socket_id) + " open") - self.command("dut2", "socket " + str(self.client_socket_id) + " connect " + str(self.server_ip) + " " + str( - self.used_port)) - - def case(self): - self.used_port = 2000 - - response = self.command("dut1", "socket new TCPServer") - self.server_base_socket_id = int(response.parsed['socket_id']) - - self.command("dut1", "socket " + str(self.server_base_socket_id) + " open") - self.command("dut1", "socket " + str(self.server_base_socket_id) + " bind port " + str(self.used_port)) - self.command("dut1", "socket " + str(self.server_base_socket_id) + " listen") - - response = self.command("dut1", "socket new TCPSocket") - self.server_socket_id = int(response.parsed['socket_id']) - self.command("dut1", "socket " + str(self.server_socket_id) + " open") - - response = self.command("dut2", "socket new TCPSocket") - zero = response.timedelta - self.client_socket_id = int(response.parsed['socket_id']) - - # Create a thread which calls client connect() - t = threading.Thread(name='clientThread', target=self.clientThread) - t.start() - - wait = 5 - response = self.command("dut1", "socket " + str(self.server_base_socket_id) + " accept " + str(self.server_socket_id)) - response.verify_response_duration(expected=wait, zero=zero, threshold_percent=10, break_in_fail=True) - socket_id = int(response.parsed['socket_id']) - - t.join() - self.command("dut1", "socket " + str(socket_id) + " send hello") - - response = self.command("dut2", "socket " + str(self.client_socket_id) + " recv 5") - data = response.parsed['data'].replace(":", "") - - if data != "hello": - raise TestStepFail("Received data doesn't match the sent data") - - def teardown(self): - self.command("dut1", "socket " + str(self.server_socket_id) + " delete") - self.command("dut1", "socket " + str(self.server_base_socket_id) + " delete") - self.command("dut2", "socket " + str(self.client_socket_id) + " delete") - - interfaceDown(self, ["dut1"]) - interfaceDown(self, ["dut2"]) diff --git a/TEST_APPS/testcases/netsocket/TCPSOCKET_ACCEPT.py b/TEST_APPS/testcases/netsocket/TCPSOCKET_ACCEPT.py deleted file mode 100644 index e002b35ee2..0000000000 --- a/TEST_APPS/testcases/netsocket/TCPSOCKET_ACCEPT.py +++ /dev/null @@ -1,108 +0,0 @@ -""" -Copyright 2018 ARM Limited -SPDX-License-Identifier: Apache-2.0 - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -""" - -import threading -import time - -from icetea_lib.bench import Bench -from interface import interfaceUp, interfaceDown -#from mbed_clitest.tools import test_case -#from mbed_clitest.TestStepError import SkippedTestcaseException -from icetea_lib.TestStepError import TestStepFail - -class Testcase(Bench): - def __init__(self): - Bench.__init__(self, - name="TCPSOCKET_ACCEPT", - title = "TCPSOCKET_ACCEPT", - purpose = "Test that TCPSocket::bind(), TCPSocket::listen() and TCPSocket::accept() works", - status = "released", - component= ["mbed-os", "netsocket"], - type="smoke", - subtype="socket", - requirements={ - "duts": { - '*': { #requirements for all nodes - "count":2, - "type": "hardware", - "application": { - "name": "TEST_APPS-device-socket_app" - } - }, - "1": {"nick": "dut1"}, - "2": {"nick": "dut2"} - } - } - ) - - def setup(self): - interface = interfaceUp(self, ["dut1"]) - self.server_ip = interface["dut1"]["ip"] - interface = interfaceUp(self, ["dut2"]) - self.client_ip = interface["dut2"]["ip"] - - def clientThread(self): - self.logger.info("Starting") - time.sleep(5) #wait accept from server - self.command("dut2", "socket " + str(self.client_socket_id) + " open") - self.command("dut2", "socket " + str(self.client_socket_id) + " connect " + str(self.server_ip) + " " + str(self.used_port)) - - - def case(self): - self.used_port = 2000 - - response = self.command("dut1", "socket new TCPSocket") - self.server_base_socket_id = int(response.parsed['socket_id']) - - self.command("dut1", "socket " + str(self.server_base_socket_id) + " open") - response = self.command("dut1", "socket " + str(self.server_base_socket_id) + " bind port " + str(self.used_port), report_cmd_fail = False) - if response.retcode == -1: - if (response.verify_trace("NSAPI_ERROR_UNSUPPORTED", break_in_fail = False)): - raise SkippedTestcaseException("UNSUPPORTED") - else: - TestStepFail("Bind port failed") - self.command("dut1", "socket " + str(self.server_base_socket_id) + " listen") - - response = self.command("dut2", "socket new TCPSocket") - self.client_socket_id = int(response.parsed['socket_id']) - - #Create a thread which calls client connect() - t = threading.Thread(name='clientThread', target=self.clientThread) - t.start() - - response = self.command("dut1", "socket " + str(self.server_base_socket_id) + " accept") - - t.join() - self.accept_socket_id = int(response.parsed['socket_id']) - if response.timedelta < 5.0: # Check that socket accept call blocks - raise TestStepFail("Longer response time expected") - - self.command("dut1", "socket " + str(self.accept_socket_id) + " send hello") - - response = self.command("dut2", "socket " + str(self.client_socket_id) + " recv 5") - data = response.parsed['data'].replace(":","") - - if data != "hello": - raise TestStepFail("Received data doesn't match the sent data") - - def teardown(self): - response = self.command("dut2", "socket " + str(self.client_socket_id) + " delete") - response = self.command("dut1", "socket " + str(self.server_base_socket_id) + " delete") - response = self.command("dut1", "socket " + str(self.accept_socket_id) + " close") - - interfaceDown(self, ["dut1"]) - interfaceDown(self, ["dut2"]) diff --git a/TEST_APPS/testcases/netsocket/TCPSOCKET_ECHOTEST_BURST_SHORT.py b/TEST_APPS/testcases/netsocket/TCPSOCKET_ECHOTEST_BURST_SHORT.py deleted file mode 100644 index 1acb656e7a..0000000000 --- a/TEST_APPS/testcases/netsocket/TCPSOCKET_ECHOTEST_BURST_SHORT.py +++ /dev/null @@ -1,79 +0,0 @@ -""" -Copyright 2018 ARM Limited -SPDX-License-Identifier: Apache-2.0 - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -""" -import string - -from icetea_lib.Randomize.randomize import Randomize -from icetea_lib.bench import Bench, TestStepFail - - -class Testcase(Bench): - def __init__(self): - Bench.__init__(self, - name="TCPSOCKET_ECHOTEST_BURST_SHORT", - title="TCPSOCKET_ECHOTEST_BURST_SHORT", - purpose="Verify that TCPSocket can send burst of packets to echo server and read incoming packets", - status="released", - component=["mbed-os", "netsocket"], - author="Juha Ylinen ", - type="smoke", - subtype="socket", - requirements={ - "duts": { - '*': { # requirements for all nodes - "count": 1, - "type": "hardware", - "application": { - "name": "TEST_APPS-device-socket_app" - } - }, - "1": {"nick": "dut1"}, - } - } - ) - - def setup(self): - self.command("dut1", "ifup") - - def case(self): - response = self.command("dut1", "socket new TCPSocket") - self.socket_id = int(response.parsed['socket_id']) - - self.command("dut1", "socket " + str(self.socket_id) + " open") - self.command("dut1", "socket " + str(self.socket_id) + " connect echo.mbedcloudtesting.com 7") - - for i in range(2): - sentData = "" - for size in (100, 200, 300, 120, 500): - packet = Randomize.random_string(max_len=size, min_len=size, chars=string.ascii_uppercase) - sentData += packet - response = self.command("dut1", "socket " + str(self.socket_id) + " send " + str(packet)) - response.verify_trace("Socket::send() returned: " + str(size)) - - received = 0 - data = "" - totalSize = 1220 - while received < totalSize: - response = self.command("dut1", "socket " + str(self.socket_id) + " recv " + str(totalSize)) - data += response.parsed['data'].replace(":", "") - received += int(response.parsed['received_bytes']) - - if data != sentData: - raise TestStepFail("Received data doesn't match the sent data") - - def teardown(self): - self.command("dut1", "socket " + str(self.socket_id) + " delete") - self.command("dut1", "ifdown") diff --git a/TEST_APPS/testcases/netsocket/__init__.py b/TEST_APPS/testcases/netsocket/__init__.py deleted file mode 100644 index b09b705cde..0000000000 --- a/TEST_APPS/testcases/netsocket/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -""" -Copyright (c) 2020 Arm Limited -SPDX-License-Identifier: Apache-2.0 - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -""" diff --git a/TEST_APPS/testcases/netsocket/interface.py b/TEST_APPS/testcases/netsocket/interface.py deleted file mode 100644 index 1bf6670994..0000000000 --- a/TEST_APPS/testcases/netsocket/interface.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -Copyright 2018 ARM Limited -SPDX-License-Identifier: Apache-2.0 - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -""" -from icetea_lib.TestStepError import TestStepFail - -''' -This interface script is intended to be a common library to be used in testcase scripts by testers. -It delegates setUp and tearDown functions with different provided network interface types using setUp() and tearDown() methods. -''' - - -def interfaceUp(tc, duts): - interfaces = {} - for dut in duts: - interface = {dut: {"ipv4": None, "ipv6": None}} - - resp = tc.command("%s" % dut, "ifup") - - ip = interface[dut]["ip"] = interface[dut]["ipv4"] = resp.parsed["address"]["ipv4"] - if not ip: - if resp.parsed["address"]["ipv6"]: - ip = interface[dut]["ip"] = interface[dut]["ipv6"] = resp.parsed["address"]["ipv6"][0] - if not ip: - raise TestStepFail("Failed to parse IP address") - - interfaces.update(interface) - return interfaces - - -def interfaceDown(tc, duts): - for dut in duts: - tc.command(dut, "ifdown") From 236054175b772c457b5432fa984c3bf209789763 Mon Sep 17 00:00:00 2001 From: Kimmo Vaisanen Date: Tue, 24 Mar 2020 14:40:15 +0200 Subject: [PATCH 2/2] Netsocket: Remove deprecated TCPServer TCPSocket should be used instead. --- .../netsocket/TCPServer/test_TCPServer.cpp | 98 ------------------- .../netsocket/TCPServer/unittest.cmake | 35 ------- .../netsocket/TCPSocket/test_TCPSocket.cpp | 63 ++++++++++-- features/lwipstack/lwipopts.h | 4 +- features/lwipstack/mbed_lib.json | 4 +- features/netsocket/NetworkStack.h | 1 - features/netsocket/TCPServer.cpp | 75 -------------- features/netsocket/TCPServer.h | 81 --------------- features/netsocket/TCPSocket.h | 1 - features/netsocket/nsapi.h | 1 - 10 files changed, 58 insertions(+), 305 deletions(-) delete mode 100644 UNITTESTS/features/netsocket/TCPServer/test_TCPServer.cpp delete mode 100644 UNITTESTS/features/netsocket/TCPServer/unittest.cmake delete mode 100644 features/netsocket/TCPServer.cpp delete mode 100644 features/netsocket/TCPServer.h diff --git a/UNITTESTS/features/netsocket/TCPServer/test_TCPServer.cpp b/UNITTESTS/features/netsocket/TCPServer/test_TCPServer.cpp deleted file mode 100644 index e2240f3900..0000000000 --- a/UNITTESTS/features/netsocket/TCPServer/test_TCPServer.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2018, Arm Limited and affiliates - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "gtest/gtest.h" -#include "features/netsocket/TCPSocket.h" -#include "features/netsocket/TCPServer.h" -#include "NetworkStack_stub.h" - -// Control the rtos EventFlags stub. See EventFlags_stub.cpp -extern std::list eventFlagsStubNextRetval; - -class TestTCPServer : public testing::Test { -public: - unsigned int dataSize = 10; - char dataBuf[10]; -protected: - TCPSocket *socket; - TCPServer *server; - NetworkStackstub stack; - - virtual void SetUp() - { - server = new TCPServer(); - socket = new TCPSocket(); - } - - virtual void TearDown() - { - stack.return_values.clear(); - eventFlagsStubNextRetval.clear(); - delete socket; - delete server; - } -}; - -TEST_F(TestTCPServer, constructor) -{ - EXPECT_TRUE(server); -} - -TEST_F(TestTCPServer, constructor_parameters) -{ - TCPServer serverParam(&stack); - const SocketAddress a("127.0.0.1", 1024); - EXPECT_EQ(serverParam.connect(a), NSAPI_ERROR_OK); -} - -TEST_F(TestTCPServer, accept) -{ - const SocketAddress a("127.0.0.1", 1024); - EXPECT_EQ(socket->open(&stack), NSAPI_ERROR_OK); - EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); - nsapi_error_t error; - EXPECT_EQ(server->open(&stack), NSAPI_ERROR_OK); - EXPECT_EQ(server->bind(a), NSAPI_ERROR_OK); - server->listen(1); - SocketAddress client_addr; - EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_OK); -} - -TEST_F(TestTCPServer, accept_no_socket) -{ - SocketAddress client_addr; - EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_NO_SOCKET); -} - -TEST_F(TestTCPServer, accept_error) -{ - SocketAddress client_addr; - EXPECT_EQ(server->open(&stack), NSAPI_ERROR_OK); - stack.return_value = NSAPI_ERROR_AUTH_FAILURE; - EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_AUTH_FAILURE); -} - -TEST_F(TestTCPServer, accept_error_would_block) -{ - SocketAddress client_addr; - EXPECT_EQ(server->open(&stack), NSAPI_ERROR_OK); - stack.return_value = NSAPI_ERROR_WOULD_BLOCK; - eventFlagsStubNextRetval.push_back(0); - eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop - - EXPECT_EQ(server->accept(socket, &client_addr), NSAPI_ERROR_WOULD_BLOCK); -} diff --git a/UNITTESTS/features/netsocket/TCPServer/unittest.cmake b/UNITTESTS/features/netsocket/TCPServer/unittest.cmake deleted file mode 100644 index 482b8ae061..0000000000 --- a/UNITTESTS/features/netsocket/TCPServer/unittest.cmake +++ /dev/null @@ -1,35 +0,0 @@ - -#################### -# UNIT TESTS -#################### - -# Unit test suite name -set(TEST_SUITE_NAME "features_netsocket_TCPServer") - -set(unittest-sources - ../features/netsocket/SocketAddress.cpp - ../features/netsocket/NetworkStack.cpp - ../features/netsocket/InternetSocket.cpp - ../features/netsocket/TCPSocket.cpp - ../features/netsocket/TCPServer.cpp - ../features/frameworks/nanostack-libservice/source/libip4string/ip4tos.c - ../features/frameworks/nanostack-libservice/source/libip6string/ip6tos.c - ../features/frameworks/nanostack-libservice/source/libip4string/stoip4.c - ../features/frameworks/nanostack-libservice/source/libip6string/stoip6.c - ../features/frameworks/nanostack-libservice/source/libBits/common_functions.c -) - -set(unittest-test-sources - stubs/Mutex_stub.cpp - stubs/mbed_assert_stub.cpp - stubs/mbed_atomic_stub.c - stubs/mbed_critical_stub.c - stubs/equeue_stub.c - stubs/EventQueue_stub.cpp - stubs/mbed_error.c - stubs/mbed_shared_queues_stub.cpp - stubs/nsapi_dns_stub.cpp - stubs/EventFlags_stub.cpp - features/netsocket/TCPServer/test_TCPServer.cpp - stubs/SocketStats_Stub.cpp -) diff --git a/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp b/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp index bf42d51472..f05d930b6b 100644 --- a/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp +++ b/UNITTESTS/features/netsocket/TCPSocket/test_TCPSocket.cpp @@ -49,6 +49,33 @@ protected: } }; +// Control the rtos EventFlags stub. See EventFlags_stub.cpp +extern std::list eventFlagsStubNextRetval; + +class TestTCPServer : public testing::Test { +public: + unsigned int dataSize = 10; + char dataBuf[10]; +protected: + TCPSocket *socket; + TCPSocket *server; + NetworkStackstub stack; + + virtual void SetUp() + { + server = new TCPSocket(); + socket = new TCPSocket(); + } + + virtual void TearDown() + { + stack.return_values.clear(); + eventFlagsStubNextRetval.clear(); + delete socket; + delete server; + } +}; + TEST_F(TestTCPSocket, get_proto) { TCPSocketFriend tcpFriend; @@ -231,6 +258,12 @@ TEST_F(TestTCPSocket, recv_from_null) EXPECT_EQ(socket->recvfrom(NULL, dataBuf, dataSize), NSAPI_ERROR_OK); } +TEST_F(TestTCPSocket, unsupported_api) +{ + SocketAddress addr; + EXPECT_EQ(socket->join_multicast_group(addr), NSAPI_ERROR_UNSUPPORTED); +} + /* listen */ TEST_F(TestTCPSocket, listen_no_open) @@ -246,9 +279,9 @@ TEST_F(TestTCPSocket, listen) EXPECT_EQ(socket->listen(1), NSAPI_ERROR_OK); } -/* these tests will have to be readjusted after TCPServer is deprecated. */ +/* TCP server */ -TEST_F(TestTCPSocket, accept_no_open) +TEST_F(TestTCPServer, accept_no_open) { nsapi_error_t error; stack.return_value = NSAPI_ERROR_OK; @@ -256,12 +289,17 @@ TEST_F(TestTCPSocket, accept_no_open) EXPECT_EQ(error, NSAPI_ERROR_NO_SOCKET); } -TEST_F(TestTCPSocket, accept) +TEST_F(TestTCPServer, accept) { + const SocketAddress a("127.0.0.1", 1024); + EXPECT_EQ(socket->open(&stack), NSAPI_ERROR_OK); + EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); nsapi_error_t error; - stack.return_value = NSAPI_ERROR_OK; + EXPECT_EQ(server->open(&stack), NSAPI_ERROR_OK); + EXPECT_EQ(server->bind(a), NSAPI_ERROR_OK); + server->listen(1); socket->open(&stack); - TCPSocket *sock = socket->accept(&error); + TCPSocket *sock = server->accept(&error); EXPECT_NE(sock, nullptr); EXPECT_EQ(error, NSAPI_ERROR_OK); if (sock) { @@ -269,19 +307,26 @@ TEST_F(TestTCPSocket, accept) } } -TEST_F(TestTCPSocket, accept_would_block) +TEST_F(TestTCPServer, accept_would_block) { nsapi_error_t error; socket->open(&stack); + EXPECT_EQ(server->open(&stack), NSAPI_ERROR_OK); + stack.return_value = NSAPI_ERROR_WOULD_BLOCK; eventFlagsStubNextRetval.push_back(0); eventFlagsStubNextRetval.push_back(osFlagsError); // Break the wait loop + EXPECT_EQ(socket->accept(&error), nullptr); EXPECT_EQ(error, NSAPI_ERROR_WOULD_BLOCK); } -TEST_F(TestTCPSocket, unsupported_api) +TEST_F(TestTCPServer, accept_error) { - SocketAddress addr; - EXPECT_EQ(socket->join_multicast_group(addr), NSAPI_ERROR_UNSUPPORTED); + nsapi_error_t error; + EXPECT_EQ(server->open(&stack), NSAPI_ERROR_OK); + stack.return_value = NSAPI_ERROR_AUTH_FAILURE; + TCPSocket *sock = server->accept(&error); + EXPECT_EQ(server->accept(&error), nullptr); + EXPECT_EQ(error, NSAPI_ERROR_AUTH_FAILURE); } diff --git a/features/lwipstack/lwipopts.h b/features/lwipstack/lwipopts.h index 929abba150..628ae49822 100644 --- a/features/lwipstack/lwipopts.h +++ b/features/lwipstack/lwipopts.h @@ -153,7 +153,7 @@ #define MEM_SIZE MBED_CONF_LWIP_MEM_SIZE -// One tcp_pcb_listen is needed for each TCPServer. +// One tcp_pcb_listen is needed for each TCP server. // Each requires 72 bytes of RAM. #define MEMP_NUM_TCP_PCB_LISTEN MBED_CONF_LWIP_TCP_SERVER_MAX @@ -172,7 +172,7 @@ // Each netbuf requires 64 bytes of RAM. #define MEMP_NUM_NETBUF MBED_CONF_LWIP_NUM_NETBUF -// One netconn is needed for each UDPSocket, TCPSocket or TCPServer. +// One netconn is needed for each UDPSocket or TCPSocket. // Each requires 236 bytes of RAM (total rounded to multiple of 512). #define MEMP_NUM_NETCONN MBED_CONF_LWIP_SOCKET_MAX diff --git a/features/lwipstack/mbed_lib.json b/features/lwipstack/mbed_lib.json index e41f9efb80..b1605eee7a 100644 --- a/features/lwipstack/mbed_lib.json +++ b/features/lwipstack/mbed_lib.json @@ -59,7 +59,7 @@ "value": false }, "socket-max": { - "help": "Maximum number of open TCPServer, TCPSocket and UDPSocket instances allowed, including one used internally for DNS. Each requires 236 bytes of pre-allocated RAM", + "help": "Maximum number of open TCPSocket and UDPSocket instances allowed, including one used internally for DNS. Each requires 236 bytes of pre-allocated RAM", "value": 4 }, "tcp-enabled": { @@ -67,7 +67,7 @@ "value": true }, "tcp-server-max": { - "help": "Maximum number of open TCPServer instances allowed. Each requires 72 bytes of pre-allocated RAM", + "help": "Maximum number of open TCP server instances allowed. Each requires 72 bytes of pre-allocated RAM", "value": 4 }, "tcp-socket-max": { diff --git a/features/netsocket/NetworkStack.h b/features/netsocket/NetworkStack.h index f1f693d775..3fe0ba1cc6 100644 --- a/features/netsocket/NetworkStack.h +++ b/features/netsocket/NetworkStack.h @@ -244,7 +244,6 @@ protected: friend class InternetSocket; friend class InternetDatagramSocket; friend class TCPSocket; - friend class TCPServer; /** Opens a socket * diff --git a/features/netsocket/TCPServer.cpp b/features/netsocket/TCPServer.cpp deleted file mode 100644 index 2ebd250374..0000000000 --- a/features/netsocket/TCPServer.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* Socket - * Copyright (c) 2015 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "TCPServer.h" - -TCPServer::TCPServer() -{ - _socket_stats.stats_update_proto(this, NSAPI_TCP); -} - -nsapi_error_t TCPServer::accept(TCPSocket *connection, SocketAddress *address) -{ - _lock.lock(); - nsapi_error_t ret; - - while (true) { - if (!_socket) { - ret = NSAPI_ERROR_NO_SOCKET; - break; - } - - core_util_atomic_flag_clear(&_pending); - void *socket; - ret = _stack->socket_accept(_socket, &socket, address); - - if (0 == ret) { - connection->_lock.lock(); - - if (connection->_socket) { - connection->close(); - } - - connection->_stack = _stack; - connection->_socket = socket; - connection->_event = { connection, &TCPSocket::event }; - _stack->socket_attach(socket, connection->_event.thunk, &connection->_event); - _socket_stats.stats_update_peer(connection, *address); - _socket_stats.stats_update_socket_state(connection, SOCK_CONNECTED); - connection->_lock.unlock(); - break; - } else if ((_timeout == 0) || (ret != NSAPI_ERROR_WOULD_BLOCK)) { - break; - } else { - uint32_t flag; - - // Release lock before blocking so other threads - // accessing this object aren't blocked - _lock.unlock(); - flag = _event_flag.wait_any(READ_FLAG, _timeout); - _lock.lock(); - - if (flag & osFlagsError) { - // Timeout break - ret = NSAPI_ERROR_WOULD_BLOCK; - break; - } - } - } - - _lock.unlock(); - return ret; -} diff --git a/features/netsocket/TCPServer.h b/features/netsocket/TCPServer.h deleted file mode 100644 index db8665d2a9..0000000000 --- a/features/netsocket/TCPServer.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2015 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** @file TCPServer.h Deprecated TCPServer class */ -/** \addtogroup netsocket - * @{*/ - -#ifndef TCPSERVER_H -#define TCPSERVER_H - -#include "netsocket/InternetSocket.h" -#include "netsocket/TCPSocket.h" -#include "netsocket/NetworkStack.h" -#include "netsocket/NetworkInterface.h" - - -/** TCP socket server - */ -class TCPServer : public TCPSocket { -public: - /** Create an uninitialized socket - * - * Must call open to initialize the socket on a network stack. - */ - MBED_DEPRECATED_SINCE("mbed-os-5.10", - "TCPServer is deprecated, use TCPSocket") - TCPServer(); - - /** Create a socket on a network interface - * - * Creates and opens a socket on the network stack of the given - * network interface. - * - * @param stack Network stack as target for socket - */ - template - MBED_DEPRECATED_SINCE("mbed-os-5.10", - "TCPServer is deprecated, use TCPSocket") - TCPServer(S *stack) - { - open(stack); - } - - // Allow legacy TCPServer::accept() to override inherited Socket::accept() - using TCPSocket::accept; - - /** Accepts a connection on a TCP socket - * - * The server socket must be bound and set to listen for connections. - * On a new connection, creates a network socket using the specified - * socket instance. - * - * By default, accept blocks until data is sent. If socket is set to - * non-blocking or times out, NSAPI_ERROR_WOULD_BLOCK is returned - * immediately. - * - * @param connection TCPSocket instance that will handle the incoming connection. - * @param address Destination for the remote address or NULL - * @return 0 on success, negative error code on failure - */ - MBED_DEPRECATED_SINCE("mbed-os-5.10", - "TCPServer::accept() is deprecated, use Socket *Socket::accept() instead") - nsapi_error_t accept(TCPSocket *connection, SocketAddress *address = NULL); -}; - -#endif - -/** @} */ diff --git a/features/netsocket/TCPSocket.h b/features/netsocket/TCPSocket.h index 7749f671e6..4831f6d535 100644 --- a/features/netsocket/TCPSocket.h +++ b/features/netsocket/TCPSocket.h @@ -177,7 +177,6 @@ public: nsapi_error_t listen(int backlog = 1) override; protected: - friend class TCPServer; nsapi_protocol_t get_proto() override; private: diff --git a/features/netsocket/nsapi.h b/features/netsocket/nsapi.h index 41f2b88dd4..c4a5920819 100644 --- a/features/netsocket/nsapi.h +++ b/features/netsocket/nsapi.h @@ -39,7 +39,6 @@ #include "netsocket/Socket.h" #include "netsocket/UDPSocket.h" #include "netsocket/TCPSocket.h" -#include "netsocket/TCPServer.h" #include "netsocket/TLSSocketWrapper.h" #include "netsocket/DTLSSocketWrapper.h" #include "netsocket/TLSSocket.h"