Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

2075 řádky
80 KiB

  1. /*******************************************************************************
  2. File Name:
  3. socket.h
  4. Summary:
  5. WINC3400 BSD Compatible Socket Interface
  6. Description:
  7. WINC3400 BSD Compatible Socket Interface
  8. *******************************************************************************/
  9. //DOM-IGNORE-BEGIN
  10. /*******************************************************************************
  11. * Copyright (C) 2021 Microchip Technology Inc. and its subsidiaries.
  12. *
  13. * Subject to your compliance with these terms, you may use Microchip software
  14. * and any derivatives exclusively with Microchip products. It is your
  15. * responsibility to comply with third party license terms applicable to your
  16. * use of third party software (including open source software) that may
  17. * accompany Microchip software.
  18. *
  19. * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
  20. * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
  21. * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
  22. * PARTICULAR PURPOSE.
  23. *
  24. * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
  25. * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
  26. * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
  27. * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
  28. * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
  29. * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
  30. * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
  31. *******************************************************************************/
  32. //DOM-IGNORE-END
  33. #ifndef __SOCKET_H__
  34. #define __SOCKET_H__
  35. #ifdef __cplusplus
  36. extern "C" {
  37. #endif
  38. /** @defgroup SOCKETAPI Socket
  39. * BSD compatible socket interface between the host layer and the network
  40. * protocol stacks in the firmware.
  41. * These functions are used by the host application to send or receive
  42. * packets and to do other socket operations.
  43. */
  44. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  45. INCLUDES
  46. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  47. #include "m2m_types.h"
  48. #include "netinet_in.h"
  49. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  50. MACROS
  51. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  52. /**@defgroup SOCKETDEF Defines
  53. * @ingroup SOCKETAPI
  54. * The following list of macros are used to define constants used throughout the socket layer, and SSL Socket options.
  55. */
  56. /**@defgroup IPDefines TCP/IP Defines
  57. * @ingroup SOCKETDEF
  58. * The following list of macros are used to define constants used throughout the socket layer.
  59. * @{
  60. */
  61. /*
  62. * HOSTNAME_MAX_SIZE is defined here and also in host_drv/socket/include/m2m_socket_host_if.h
  63. * The two definitions must match.
  64. */
  65. #define HOSTNAME_MAX_SIZE 100
  66. /*!<
  67. Maximum allowed size for a host domain name passed to the function @ref gethostbyname.
  68. command value. Used with the @ref setsockopt function.
  69. */
  70. #define SOCKET_BUFFER_MAX_LENGTH 1400
  71. /*!<
  72. Maximum allowed size for a socket data buffer. Used with @ref send socket
  73. function to ensure that the buffer sent is within the allowed range.
  74. */
  75. #define AF_INET 2
  76. /*!<
  77. The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure.
  78. (It is the only supported type for the current implementation.)
  79. */
  80. #define SOCK_STREAM 1
  81. /*!<
  82. One of the IPv4 supported socket types for reliable connection-oriented stream connection.
  83. Passed to the @ref socket function for the socket creation operation.
  84. */
  85. #define SOCK_DGRAM 2
  86. /*!<
  87. One of the IPv4 supported socket types for unreliable connectionless datagram connection.
  88. Passed to the @ref socket function for the socket creation operation.
  89. */
  90. #define SOCK_RAW 3
  91. /*!<
  92. Socket type used for sending and receiving raw frames.
  93. Raw socket expects and returns IP header.
  94. Please note that SO_BROADCAST socket option is not currently supported when using RAW socket.
  95. Similarly to SOCK_DGRAM it is oriented towards unreliable connectionless communication.
  96. Passed to the @ref socket function for the socket creation operation.
  97. */
  98. #define SOCKET_FLAGS_SSL 0x01
  99. /*!<
  100. This flag may be set in the u8Config parameter of @ref socket (when the
  101. u8Type parameter is @ref SOCK_STREAM), to create a TLS socket.\n
  102. Note that the number of TLS sockets is limited to 2.\n
  103. This flag is kept for legacy purposes. It is recommended that applications
  104. use @ref SOCKET_CONFIG_SSL_ON instead.
  105. */
  106. #define SOCKET_FLAGS_IPPROTO_RAW 0x02
  107. /*!<
  108. This flag may be set in the u8Config parameter of @ref socket (when the
  109. u8Type parameter is @ref SOCK_RAW), to allow the Application to use a
  110. socket of type raw to send/receive frames.\n
  111. This flag is kept for legacy purposes. It is recommended that applications
  112. use @ref SOCKET_CONFIG_IPPROTO_RAW instead.
  113. */
  114. #define SOCKET_CONFIG_DEFAULT 0
  115. /*!<
  116. This value may be passed in the u8Config parameter of @ref socket to create
  117. a socket with default configuration.
  118. */
  119. #define SOCKET_CONFIG_SSL_OFF 0
  120. /*!<
  121. This value may be passed in the u8Config parameter of @ref socket (when the
  122. u8Type parameter is @ref SOCK_STREAM), to create a socket not capable of
  123. TLS.
  124. */
  125. #define SOCKET_CONFIG_SSL_ON 1
  126. /*!<
  127. This value may be passed in the u8Config parameter of @ref socket (when the
  128. u8Type parameter is @ref SOCK_STREAM), to create a TLS socket.\n
  129. Note that the number of TLS sockets is limited to 2.
  130. */
  131. #define SOCKET_CONFIG_SSL_DELAY 2
  132. /*!<
  133. This value may be passed in the u8Config parameter of @ref socket (when the
  134. u8Type parameter is @ref SOCK_STREAM), to create a TCP socket which has the
  135. potential to upgrade to a TLS socket later (by calling @ref secure).\n
  136. Note that the total number of TLS sockets and potential TLS sockets is
  137. limited to 2.
  138. */
  139. #define SOCKET_CONFIG_IPPROTO_RAW 2
  140. /*!<
  141. This value may be passed in the u8Config parameter of @ref socket (when the u8Type parameter is
  142. @ref SOCK_RAW), to allow the Application to use a socket of type raw to send/receive frames.
  143. This assumes that the application will fill the IP and protocol (UDP, TCP, ICMP) headers.
  144. Typically, when sending ICMP frames via RAW socket, there are two options that can be used:
  145. - IPPROTO_RAW - Raw IP packets, implies that IP_HDRINCL is enabled and therefore
  146. the host application should fill in the corresponding protocol header checksum.
  147. - IPPROTO_ICMP - ICMP packets, the WINC would fill in the ICMP header checksum (not supported).
  148. @warning
  149. Please note that only SOCKET_CONFIG_IPPROTO_RAW is currently supported.
  150. Raw sockets can be used to send TCP/UDP/ICMP packets, however, the current implementation only
  151. supports receiving Raw ICMP frames, which also requires @ref SO_ICMP_FILTER to be set appropriately.
  152. */
  153. #define TCP_SOCK_MAX (7)
  154. /*!<
  155. Maximum number of simultaneous TCP sockets.
  156. */
  157. #define UDP_SOCK_MAX 4
  158. /*!<
  159. Maximum number of simultaneous UDP sockets.
  160. */
  161. #define RAW_SOCK_MAX 1
  162. /*!<
  163. Maximum number of simultaneous RAW sockets.
  164. */
  165. #define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX + RAW_SOCK_MAX)
  166. /*!<
  167. Maximum number of simultaneous sockets.
  168. */
  169. #define SOL_SOCKET 1
  170. /*!<
  171. Socket option.
  172. Used with the @ref setsockopt function
  173. */
  174. #define SOL_SSL_SOCKET 2
  175. /*!<
  176. SSL Socket option level.
  177. Used with the @ref setsockopt function
  178. */
  179. #define SOL_RAW 255
  180. /*!<
  181. Raw Socket option level.
  182. Used with the @ref setsockopt function
  183. */
  184. #define SO_SET_UDP_SEND_CALLBACK 0x00
  185. /*!<
  186. Socket option used by the application to enable/disable
  187. the use of UDP send callbacks.\n
  188. Used with the @ref setsockopt function.\n
  189. The option value should be cast to int type.\n
  190. 0: disable UDP send callbacks.\n
  191. 1: enable UDP send callbacks.\n
  192. Default setting is enable.
  193. @warning @ref connect and @ref bind cause this setting to
  194. be lost, so the application should only set this option
  195. after calling @ref connect or @ref bind.
  196. */
  197. #define IP_ADD_MEMBERSHIP 0x01
  198. /*!<
  199. Set Socket Option Add Membership command value.
  200. Used with the @ref setsockopt function.
  201. */
  202. #define IP_DROP_MEMBERSHIP 0x02
  203. /*!<
  204. Set Socket Option Drop Membership command value.
  205. Used with the @ref setsockopt function.
  206. */
  207. #define SO_TCP_KEEPALIVE 0x04
  208. /*!<
  209. Socket option to enable or disable TCP keep-alive.\n
  210. Used with the @ref setsockopt function.\n
  211. The option value should be cast to int type.\n
  212. 0: disable TCP keep-alive.\n
  213. 1: enable TCP keep-alive.\n
  214. Default setting is disable.
  215. @warning @ref connect and @ref bind cause this setting to
  216. be lost, so the application should only set this option
  217. after calling @ref connect or @ref bind.
  218. */
  219. #define SO_TCP_KEEPIDLE 0x05
  220. /*!<
  221. Socket option to set the time period after which the socket will trigger keep-alive transmissions.\n
  222. Used with the @ref setsockopt function.\n
  223. The option value should be cast to int type.\n
  224. Option value is the time period in units of 500ms. Maximum 2^32 - 1.
  225. Default setting is 120 (60 seconds).
  226. @warning @ref connect and @ref bind cause this setting to
  227. be lost, so the application should only set this option
  228. after calling @ref connect or @ref bind.
  229. */
  230. #define SO_TCP_KEEPINTVL 0x06
  231. /*!<
  232. Socket option to set the time period between keep-alive retransmissions.\n
  233. Used with the @ref setsockopt function.\n
  234. The option value should be cast to int type.\n
  235. Option value is the time period in units of 500ms. Maximum 255.
  236. Default setting is 1 (0.5 seconds).
  237. @warning @ref connect and @ref bind cause this setting to
  238. be lost, so the application should only set this option
  239. after calling @ref connect or @ref bind.
  240. */
  241. #define SO_TCP_KEEPCNT 0x07
  242. /*!<
  243. Socket option to set the number of keep-alive retransmissions to be carried out before declaring that the remote end is not available.\n
  244. Used with the @ref setsockopt function.\n
  245. The option value should be cast to int type.\n
  246. Maximum 255.
  247. Default setting is 20.
  248. @warning @ref connect and @ref bind cause this setting to
  249. be lost, so the application should only set this option
  250. after calling @ref connect or @ref bind.
  251. */
  252. #define SO_ICMP_FILTER 0x01
  253. /*!<
  254. Socket option to set the ICMP filter for raw sockets when receiving.\n
  255. Current implementation allows for a filter none (0) or filter all (anything else).
  256. Filter none means that all ICMP frames will be delivered to the host via raw socket.
  257. Filter all means that all ICMP frames will NOT be delivered to host and handled internally by the WINC (please note that fragmentation is not supported by the WINC).
  258. Used with the @ref setsockopt function.\n
  259. The option value should be cast to int type.\n
  260. Default setting is 0 (filter none).
  261. @warning @ref bind and @ref shutdown will cause this setting to be lost,
  262. so the application should only set this option after @ref bind.
  263. */
  264. #define RAW_SOCK_ID (TCP_SOCK_MAX + UDP_SOCK_MAX)
  265. /*!<
  266. Socket number to be used for RAW socket.
  267. */
  268. /**@}*/ //IPDefines
  269. /**@addtogroup TLSDefines
  270. * @{
  271. */
  272. #define ALPN_LIST_MAX_APP_LENGTH 30
  273. /*!<
  274. Maximum length of ALPN list that can be specified by the application.
  275. This length includes separators (spaces) and terminator (NUL).
  276. */
  277. /**@}*/ // TLSDefines
  278. /**
  279. * @defgroup TLSDefines TLS Defines
  280. * @ingroup SOCKETDEF
  281. * @ingroup SSLAPI
  282. */
  283. /**@defgroup SSLSocketOptions TLS Socket Options
  284. * @ingroup TLSDefines
  285. * The following list of macros are used to define SSL Socket options.
  286. * @{
  287. * @sa setsockopt
  288. */
  289. #define SO_SSL_BYPASS_X509_VERIF 0x01
  290. /*!<
  291. Allow an opened SSL socket to bypass the X509 certificate verification
  292. process.
  293. It is recommended NOT to use this socket option in production software
  294. applications. It is supported for debugging and testing purposes.\n
  295. The option value should be casted to int type.\n
  296. 0: do not bypass the X509 certificate verification process (default,
  297. recommended).\n
  298. 1: bypass the X509 certificate verification process.\n
  299. This option only takes effect if it is set after calling @ref socket and
  300. before calling @ref connect or @ref secure.
  301. */
  302. #define SO_SSL_SNI 0x02
  303. /*!<
  304. Set the Server Name Indicator (SNI) for an SSL socket. The SNI is a NULL-
  305. terminated string containing the server name associated with the
  306. connection. Its size must not exceed @ref HOSTNAME_MAX_SIZE. If the SNI is
  307. not a null string, then TLS Client Hello messages will include the SNI
  308. extension.\n
  309. This option only takes effect if it is set after calling @ref socket and
  310. before calling @ref connect or @ref secure.
  311. */
  312. #define SO_SSL_ENABLE_SESSION_CACHING 0x03
  313. /*!<
  314. This option allow the TLS to cache the session information for fast TLS
  315. session establishment in future connections using the TLS Protocol session
  316. resume features.\n
  317. The option value should be casted to int type.\n
  318. 0: disable TLS session caching (default).\n
  319. 1: enable TLS session caching.\n
  320. Note that TLS session caching is always enabled in TLS Server Mode and this
  321. option is ignored.\n
  322. This option only takes effect if it is set after calling @ref socket and
  323. before calling @ref connect or @ref secure.
  324. */
  325. #define SO_SSL_ENABLE_CERTNAME_VALIDATION 0x04
  326. /*!<
  327. Enable internal validation of server name against the server's
  328. certificate subject common name. If there is no server name
  329. provided (via the @ref SO_SSL_SNI option), setting this option
  330. does nothing.\n
  331. The option value should be casted to int type.\n
  332. 0: disable server certificate name validation (default).\n
  333. 1: enable server certificate name validation (recommended).\n
  334. This option only takes effect if it is set after calling @ref socket and
  335. before calling @ref connect or @ref secure.
  336. */
  337. #define SO_SSL_ALPN 0x05
  338. /*!<
  339. Set the list to use for Application-Layer Protocol Negotiation
  340. for an SSL socket.\n
  341. This option is intended for internal use and should not be
  342. used by the application. Applications should use the API @ref
  343. set_alpn_list.
  344. */
  345. #define SO_SSL_ENABLE_SNI_VALIDATION 0x04
  346. /*!<
  347. Legacy name for @ref SO_SSL_ENABLE_CERTNAME_VALIDATION.\n
  348. */
  349. /**@}*/ //SSLSocketOptions
  350. /**@defgroup SSLCipherSuiteID TLS Cipher Suite IDs
  351. * @ingroup TLSDefines
  352. * The following list of macros defined the list of supported TLS Cipher suites.
  353. * Each MACRO defines a single Cipher suite.
  354. * @sa m2m_ssl_set_active_ciphersuites
  355. * @{
  356. */
  357. #define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0
  358. #define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1
  359. #define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2
  360. #define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3
  361. #define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4
  362. #define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5
  363. #define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6
  364. #define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7
  365. #define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8
  366. #define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9
  367. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10
  368. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11
  369. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12
  370. #define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13
  371. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14
  372. #define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15
  373. #define SSL_ECC_ONLY_CIPHERS \
  374. (\
  375. SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \
  376. SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \
  377. )
  378. /*!<
  379. All supported ciphers which use ECDSA.
  380. */
  381. #define SSL_DEFAULT_CIPHERS \
  382. (\
  383. SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \
  384. SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \
  385. SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \
  386. SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \
  387. SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \
  388. SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \
  389. SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \
  390. SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \
  391. SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \
  392. SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \
  393. )
  394. /*!<
  395. All supported Non-ECC Ciphers. This is the default active group after startup.
  396. Note that firmware may support only a subset of these.
  397. */
  398. /**@}*/ // SSLCipherSuiteID
  399. /**@defgroup SOCKETBYTEORDER Byte Order
  400. * @ingroup SOCKETAPI
  401. * The following list of macros are used to convert between host representation and network byte order.
  402. * @{
  403. */
  404. #ifdef _NM_BSP_BIG_END
  405. #define _htonl(m) (m)
  406. /*!<
  407. Convert a 4-byte integer from the Host representation to Network byte order (Host is BE).
  408. */
  409. #define _htons(A) (A)
  410. /*!<
  411. Convert a 2-byte integer (short) from Host representation to Network byte order (Host is BE).
  412. */
  413. #else
  414. #define _htonl(m) \
  415. (uint32_t)(((uint32_t)(m << 24)) | ((uint32_t)((m & 0x0000FF00) << 8)) | ((uint32_t)((m & 0x00FF0000) >> 8)) | ((uint32_t)(((uint32_t)m) >> 24)))
  416. /*!<
  417. Convert a 4-byte integer from Host representation to Network byte order (Host is LE).
  418. */
  419. #define _htons(A) (uint16_t)((((uint16_t) (A)) << 8) | (((uint16_t) (A)) >> 8))
  420. /*!<
  421. Convert a 2-byte integer (short) from Host representation to Network byte order (Host is LE).
  422. */
  423. #endif
  424. #define _ntohl _htonl
  425. /*!<
  426. Convert a 4-byte integer from Network byte order to Host representation.
  427. */
  428. #define _ntohs _htons
  429. /*!<
  430. Convert a 2-byte integer from Network byte order to Host representation.
  431. */
  432. /**@}*/ // SOCKETBYTEORDER
  433. /**************
  434. Socket Errors
  435. **************/
  436. /**@defgroup SocketErrorCode Error Codes
  437. * @ingroup SOCKETAPI
  438. * The following list of macros are used to define the possible error codes.
  439. * Errors are listed in numerical order with the error macro name.
  440. * @{
  441. */
  442. #define SOCK_ERR_NO_ERROR 0
  443. /*!<
  444. Successful socket operation. This code is also used with event @ref SOCKET_MSG_RECV if a socket connection is closed.
  445. In that case, the application should call @ref shutdown().
  446. */
  447. #define SOCK_ERR_INVALID_ADDRESS -1
  448. /*!<
  449. Socket address is invalid. The socket operation cannot be completed successfully without specifying a valid address
  450. For example: bind is called without specifying a port number
  451. */
  452. #define SOCK_ERR_ADDR_ALREADY_IN_USE -2
  453. /*!<
  454. Socket operation cannot bind on the given address. Only one IP address per socket, and one socket per IP address is permitted -
  455. any attempt for a new socket to bind with an IP address already bound to another open socket will return the following error code.
  456. */
  457. #define SOCK_ERR_MAX_TCP_SOCK -3
  458. /*!<
  459. Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX.
  460. It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed.
  461. */
  462. #define SOCK_ERR_MAX_UDP_SOCK -4
  463. /*!<
  464. Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX.
  465. It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed
  466. */
  467. #define SOCK_ERR_INVALID_ARG -6
  468. /*!<
  469. An invalid argument is passed to a socket function. Identifies that @ref socket operation failed
  470. */
  471. #define SOCK_ERR_MAX_LISTEN_SOCK -7
  472. /*!<
  473. Exceeded the maximum number of TCP passive listening sockets.
  474. Identifies that @ref listen operation failed.
  475. */
  476. #define SOCK_ERR_INVALID -9
  477. /*!<
  478. The requested socket operation is not valid in the current socket state.
  479. For example: @ref accept is called on a TCP socket before @ref bind or @ref listen.
  480. */
  481. #define SOCK_ERR_ADDR_IS_REQUIRED -11
  482. /*!<
  483. Destination address is required. Failure to provide the socket address required for the socket operation to be completed.
  484. The @ref sendto function requires a destination address to send data.
  485. */
  486. #define SOCK_ERR_CONN_ABORTED -12
  487. /*!<
  488. The socket is closed (reset) by the peer. If this error is received, the application should call @ref shutdown().
  489. */
  490. #define SOCK_ERR_TIMEOUT -13
  491. /*!<
  492. The socket pending operation has timed out. The socket remains open.
  493. */
  494. #define SOCK_ERR_BUFFER_FULL -14
  495. /*!<
  496. No buffer space available to be used for the requested socket operation.
  497. */
  498. /**@}*/ // SocketErrorCode
  499. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  500. DATA TYPES
  501. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  502. /** @defgroup SocketEnums Enumeration/Typedefs
  503. * @ingroup SOCKETAPI
  504. * Specific Enumeration-typedefs used for socket operations
  505. * @{
  506. */
  507. /*!
  508. @typedef \
  509. SOCKET
  510. @brief
  511. Definition for socket handler data type.
  512. Socket ID,used with all socket operations to uniquely identify the socket handler.
  513. The ID is uniquely assigned at socket creation when calling @ref socket operation.
  514. */
  515. typedef int8_t SOCKET;
  516. /*!
  517. @enum \
  518. tenuSockErrSource
  519. @brief
  520. Source of socket error (local, remote or unknown).
  521. @see tstrSockErr
  522. */
  523. typedef enum {
  524. SOCKET_ERR_UNKNOWN = 0,
  525. /*!<
  526. No detail available (also used when there is no error).
  527. */
  528. SOCKET_ERR_TLS_REMOTE,
  529. /*!<
  530. TLS Error Alert received from peer.
  531. */
  532. SOCKET_ERR_TLS_LOCAL
  533. /*!<
  534. TLS Error Alert generated locally.
  535. */
  536. } tenuSockErrSource;
  537. /*!
  538. @struct \
  539. sockaddr
  540. @brief
  541. Generic socket address structure.
  542. @see
  543. sockaddr_in
  544. */
  545. struct sockaddr {
  546. uint16_t sa_family;
  547. /*!<
  548. Socket address family.
  549. */
  550. uint8_t sa_data[14];
  551. /*!<
  552. Maximum size of all the different socket address structures.
  553. */
  554. };
  555. /*!
  556. @struct \
  557. tstrSockErr
  558. @brief
  559. Detail about socket failures. Used with @ref get_error_detail.
  560. */
  561. typedef struct {
  562. tenuSockErrSource enuErrSource;
  563. /*!<
  564. Source of socket error (local, remote or unknown).
  565. */
  566. uint8_t u8ErrCode;
  567. /*!<
  568. TLS Alert code as defined in
  569. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-6.
  570. */
  571. } tstrSockErr;
  572. /**@}*/ //SocketEnums
  573. /**@defgroup AsyncCallback Asynchronous Events
  574. * @ingroup SocketEnums
  575. * Specific Enumeration used for asynchronous operations
  576. * @{ */
  577. /*!
  578. @enum \
  579. tenuSocketCallbackMsgType
  580. @brief
  581. Asynchronous APIs make use of callback functions in-order to return back the results once the corresponding socket operation is completed.
  582. Hence resuming the normal execution of the application code while the socket operation returns the results.
  583. Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for.
  584. The following enum identifies the type of events that are received in the callback function.
  585. Application Use:
  586. In order for application developers to handle the pending events from the network controller through the callback functions,
  587. a function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation.
  588. @see bind
  589. @see listen
  590. @see accept
  591. @see connect
  592. @see send
  593. @see recv
  594. */
  595. typedef enum {
  596. SOCKET_MSG_BIND = 1,
  597. /*!<
  598. Bind socket event.
  599. */
  600. SOCKET_MSG_LISTEN,
  601. /*!<
  602. Listen socket event.
  603. */
  604. SOCKET_MSG_DNS_RESOLVE,
  605. /*!<
  606. DNS Resolution event.
  607. */
  608. SOCKET_MSG_ACCEPT,
  609. /*!<
  610. Accept socket event.
  611. */
  612. SOCKET_MSG_CONNECT,
  613. /*!<
  614. Connect socket event.
  615. */
  616. SOCKET_MSG_RECV,
  617. /*!<
  618. Receive socket event.
  619. */
  620. SOCKET_MSG_SEND,
  621. /*!<
  622. Send socket event.
  623. */
  624. SOCKET_MSG_SENDTO,
  625. /*!<
  626. Sendto socket event.
  627. */
  628. SOCKET_MSG_RECVFROM,
  629. /*!<
  630. Recvfrom socket event.
  631. */
  632. SOCKET_MSG_SECURE
  633. /*!<
  634. Existing socket made secure event.
  635. */
  636. } tenuSocketCallbackMsgType;
  637. /*!
  638. @struct \
  639. tstrSocketBindMsg
  640. @brief Socket bind status.
  641. An asynchronous call to the @ref bind socket operation, returns information through this structure in response.
  642. This structure together with the event @ref SOCKET_MSG_BIND are passed in parameters to the callback function.
  643. @see
  644. bind
  645. */
  646. typedef struct {
  647. int8_t status;
  648. /*!<
  649. The result of the bind operation.
  650. Holding a value of ZERO for a successful bind or otherwise a negative
  651. error code corresponding to @ref SocketErrorCode.
  652. */
  653. } tstrSocketBindMsg;
  654. /*!
  655. @struct \
  656. tstrSocketListenMsg
  657. @brief Socket listen status.
  658. Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function.
  659. This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function.
  660. @see
  661. listen
  662. */
  663. typedef struct {
  664. int8_t status;
  665. /*!<
  666. Holding a value of ZERO for a successful listen or otherwise a negative
  667. error code corresponding to @ref SocketErrorCode.
  668. */
  669. } tstrSocketListenMsg;
  670. /*!
  671. @struct \
  672. tstrSocketAcceptMsg
  673. @brief Socket accept status.
  674. Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function.
  675. This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function.
  676. */
  677. typedef struct {
  678. SOCKET sock;
  679. /*!<
  680. On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer.
  681. Otherwise a negative error code is returned to indicate failure of the accept operation.
  682. */
  683. struct sockaddr_in strAddr;
  684. /*!<
  685. Socket address structure for the remote peer.
  686. */
  687. } tstrSocketAcceptMsg;
  688. /*!
  689. @struct \
  690. tstrSocketConnectMsg
  691. @brief Socket connect status.
  692. Socket connect information is returned through this structure in response to an asynchronous call to the @ref connect socket function
  693. or the @ref secure socket function.
  694. This structure and the event @ref SOCKET_MSG_CONNECT or @ref SOCKET_MSG_SECURE are passed in parameters to the callback function.
  695. If the application receives this structure with a negative value in s8Error, the application should call @ref close().
  696. */
  697. typedef struct {
  698. SOCKET sock;
  699. /*!<
  700. Socket ID referring to the socket passed to the @ref connect or @ref secure function call.
  701. */
  702. int8_t s8Error;
  703. /*!<
  704. Connect error code:\n
  705. - ZERO for a successful connect or successful secure. \n
  706. - Otherwise a negative error code corresponding to the type of error.
  707. */
  708. } tstrSocketConnectMsg;
  709. /*!
  710. @struct \
  711. tstrSocketRecvMsg
  712. @brief Socket recv status.
  713. Socket receive information is returned through this structure in response to the asynchronous call to the @ref recv or @ref recvfrom socket functions.
  714. This structure, together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM, is passed-in parameters to the callback function.
  715. @remark
  716. After receiving this structure, the application should issue a new call to @ref recv or @ref recvfrom in order to receive subsequent data.
  717. In the case of @ref SOCKET_MSG_RECVFROM (UDP), any further data in the same datagram is dropped, then subsequent datagrams are buffered on the WINC until the application provides a buffer via a new call to @ref recvfrom.
  718. In the case of @ref SOCKET_MSG_RECV (TCP), all subsequent data is buffered on the WINC until the application provides a buffer via a new call to @ref recv.
  719. A negative or zero buffer size indicates an error with the following code:
  720. @ref SOCK_ERR_NO_ERROR : Socket connection closed. The application should now call @ref shutdown().
  721. @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted. The application should now call @ref shutdown().
  722. @ref SOCK_ERR_TIMEOUT : Socket receive timed out. The socket connection remains open.
  723. */
  724. typedef struct {
  725. uint8_t *pu8Buffer;
  726. /*!<
  727. Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk.
  728. */
  729. int16_t s16BufferSize;
  730. /*!<
  731. The received data chunk size.
  732. Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message.
  733. */
  734. uint16_t u16RemainingSize;
  735. /*!<
  736. This field is used internally by the driver. In normal operation, this field will be 0 when the application receives this structure.
  737. */
  738. struct sockaddr_in strRemoteAddr;
  739. /*!<
  740. Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event.
  741. */
  742. } tstrSocketRecvMsg;
  743. /**@}*/ // AsyncCallback
  744. /**@defgroup SocketCallbacks Callbacks
  745. * @ingroup SOCKETAPI
  746. * @{
  747. */
  748. /*!
  749. @typedef \
  750. tpfAppSocketCb
  751. @brief
  752. The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback.
  753. In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc.
  754. @param [in] sock
  755. Socket ID for the callback.
  756. The socket callback function is called whenever a new event is received in response
  757. to socket operations.
  758. @param [in] u8Msg
  759. Socket event type. Possible values are:
  760. - @ref SOCKET_MSG_BIND
  761. - @ref SOCKET_MSG_LISTEN
  762. - @ref SOCKET_MSG_ACCEPT
  763. - @ref SOCKET_MSG_CONNECT
  764. - @ref SOCKET_MSG_RECV
  765. - @ref SOCKET_MSG_SEND
  766. - @ref SOCKET_MSG_SENDTO
  767. - @ref SOCKET_MSG_RECVFROM
  768. - @ref SOCKET_MSG_SECURE
  769. @param [in] pvMsg
  770. Pointer to message structure. Existing types are:
  771. - tstrSocketBindMsg
  772. - tstrSocketListenMsg
  773. - tstrSocketAcceptMsg
  774. - tstrSocketConnectMsg
  775. - tstrSocketRecvMsg
  776. @see
  777. tenuSocketCallbackMsgType
  778. tstrSocketRecvMsg
  779. tstrSocketConnectMsg
  780. tstrSocketAcceptMsg
  781. tstrSocketListenMsg
  782. tstrSocketBindMsg
  783. */
  784. typedef void (*tpfAppSocketCb)(SOCKET sock, uint8_t u8Msg, void *pvMsg);
  785. /*!
  786. @typedef \
  787. tpfAppResolveCb
  788. @brief
  789. DNS resolution callback function.
  790. Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback.
  791. The following callback is triggered in response to an asynchronous call to the @ref gethostbyname function (DNS Resolution callback).
  792. @param [in] pu8DomainName
  793. Domain name of the host.
  794. @param [in] u32ServerIP
  795. Server IPv4 address encoded in Network byte order format. If it is Zero, then the DNS resolution failed.
  796. */
  797. typedef void (*tpfAppResolveCb)(uint8_t *pu8DomainName, uint32_t u32ServerIP);
  798. /*!
  799. @typedef \
  800. tpfPingCb
  801. @brief PING Callback
  802. The function delivers the ping statistics for the sent ping triggered by calling
  803. @ref m2m_ping_req.
  804. @param [in] u32IPAddr
  805. Destination IP.
  806. @param [in] u32RTT
  807. Round Trip Time.
  808. @param [in] u8ErrorCode
  809. Ping error code. It may be one of:
  810. - PING_ERR_SUCCESS
  811. - PING_ERR_DEST_UNREACH
  812. - PING_ERR_TIMEOUT
  813. */
  814. typedef void (*tpfPingCb)(uint32_t u32IPAddr, uint32_t u32RTT, uint8_t u8ErrorCode);
  815. /**@}*/ //SocketCallbacks
  816. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  817. FUNCTION PROTOTYPES
  818. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  819. /**@defgroup SocketAPI Functions
  820. * @ingroup SOCKETAPI
  821. * The function performs the necessary initializations for the socket library through the following steps:
  822. * - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once,
  823. * in-order to prevent resetting the socket instances already created in the global socket array (gastrSockets).
  824. * - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets.
  825. * - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function.
  826. * This facilitates handling all of the socket related functions received through interrupts from the firmware.
  827. * @{
  828. */
  829. /*!
  830. * @fn void socketInit(void);
  831. The function performs the necessary initialization for the socket library through the following steps:
  832. - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once,
  833. in-order to prevent resetting the socket instances already created in the global socket array (gastrSockets).
  834. - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets.
  835. - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function.
  836. This facilitates handling all of the socket related functions received through interrupts from the firmware.
  837. @return void
  838. @remarks
  839. This initialization function must be invoked before any socket operation is performed.
  840. No error codes from this initialization function since the socket array is statically allocated based on the maximum number of
  841. sockets @ref MAX_SOCKET which is tuned to the systems capability.
  842. \section SocketExample1 Example
  843. This example demonstrates the use of the socketInit for socket initialization for an mqtt chat application.
  844. \code
  845. tstrWifiInitParam param;
  846. tstrNetworkId strNetworkId;
  847. tstrAuthPsk strAuthPsk;
  848. int8_t ret;
  849. char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1];
  850. //Initialize the board.
  851. system_init();
  852. //Initialize the UART console.
  853. configure_console();
  854. // Initialize the BSP.
  855. nm_bsp_init();
  856. ----------
  857. // Initialize socket interface.
  858. socketInit();
  859. registerSocketCallback(socket_event_handler, socket_resolve_handler);
  860. // Connect to router.
  861. strNetworkId.pu8Bssid = NULL;
  862. strNetworkId.pu8Ssid = MAIN_WLAN_SSID;
  863. strNetworkId.u8SsidLen = sizeof(MAIN_WLAN_SSID);
  864. strNetworkId.u8Channel = M2M_WIFI_CH_ALL;
  865. strAuthPsk.pu8Psk = NULL;
  866. strAuthPsk.pu8Passphrase = MAIN_WLAN_PSK;
  867. strAuthPsk.u8PassphraseLen = (uint8_t)strlen((char*)MAIN_WLAN_PSK);
  868. m2m_wifi_connect_psk(WIFI_CRED_SAVE_ENCRYPTED, &strNetworkId, &strAuthPsk);
  869. \endcode
  870. */
  871. void socketInit(void);
  872. /*!
  873. @fn \
  874. void socketDeinit(void);
  875. @brief Socket Layer De-initialization
  876. The function performs the necessary cleanup for the socket library static data
  877. It must be invoked only after all desired socket operations have been performed on any active sockets.
  878. */
  879. void socketDeinit(void);
  880. /*!
  881. @fn \
  882. uint8_t IsSocketReady(void);
  883. @see socketInit
  884. socketDeinit
  885. @return If the socket has been initialized and is ready.
  886. Should return 1 after @ref socketInit and 0 after @ref socketDeinit
  887. */
  888. uint8_t IsSocketReady(void);
  889. /*!
  890. @fn \
  891. void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb);
  892. Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function.
  893. The registered callback functions are used to retrieve information in response to the asynchronous socket functions called.
  894. @param [in] socket_cb
  895. Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers
  896. socket messages to the host application. In response to the asynchronous function calls, such as @ref bind
  897. @ref listen @ref accept @ref connect
  898. @param [in] resolve_cb
  899. Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb.
  900. Used for DNS resolving functionality. The DNS resolving technique is determined by the application
  901. registering the callback.
  902. NULL is assigned when DNS resolution is not required.
  903. @return void
  904. @remarks
  905. If any of the socket functionality is not to be used, NULL is passed in as a parameter.
  906. It must be invoked after @ref socketInit and before other socket layer operations.
  907. \section SocketExample2 Example
  908. This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null
  909. for a simple UDP server example.
  910. \code
  911. tstrWifiInitParam param;
  912. tstrNetworkId strNetworkId;
  913. tstrAuthPsk strAuthPsk;
  914. int8_t ret;
  915. struct sockaddr_in addr;
  916. // Initialize the board
  917. system_init();
  918. //Initialize the UART console.
  919. configure_console();
  920. // Initialize the BSP.
  921. nm_bsp_init();
  922. // Initialize socket address structure.
  923. addr.sin_family = AF_INET;
  924. addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT);
  925. addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP);
  926. // Initialize Wi-Fi parameters structure.
  927. memset((uint8_t *)&param, 0, sizeof(tstrWifiInitParam));
  928. // Initialize Wi-Fi driver with data and status callbacks.
  929. param.pfAppWifiCb = wifi_cb;
  930. ret = m2m_wifi_init(&param);
  931. if (M2M_SUCCESS != ret) {
  932. printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
  933. while (1) {
  934. }
  935. }
  936. // Initialize socket module
  937. socketInit();
  938. registerSocketCallback(socket_cb, NULL);
  939. // Connect to router.
  940. strNetworkId.pu8Bssid = NULL;
  941. strNetworkId.pu8Ssid = MAIN_WLAN_SSID;
  942. strNetworkId.u8SsidLen = sizeof(MAIN_WLAN_SSID);
  943. strNetworkId.u8Channel = M2M_WIFI_CH_ALL;
  944. strAuthPsk.pu8Psk = NULL;
  945. strAuthPsk.pu8Passphrase = MAIN_WLAN_PSK;
  946. strAuthPsk.u8PassphraseLen = (uint8_t)strlen((char*)MAIN_WLAN_PSK);
  947. m2m_wifi_connect_psk(WIFI_CRED_SAVE_ENCRYPTED, &strNetworkId, &strAuthPsk);
  948. \endcode
  949. */
  950. //void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb);
  951. void registerSocketEventCallback(tpfAppSocketCb socket_cb);
  952. void registerSocketResolveCallback(tpfAppResolveCb resolve_cb);
  953. /*!
  954. @fn \
  955. SOCKET socket(uint16_t u16Domain, uint8_t u8Type, uint8_t u8Config);
  956. Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets.
  957. The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets.
  958. @param [in] u16Domain
  959. Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets.
  960. @param [in] u8Type
  961. Socket type. Allowed values are:
  962. - [SOCK_STREAM](@ref SOCK_STREAM)
  963. - [SOCK_DGRAM](@ref SOCK_DGRAM)
  964. - [SOCK_RAW](@ref SOCK_RAW)
  965. @param[in] u8Config
  966. Used to specify the socket configuration. The interpretation of
  967. this parameter depends on the setting of u8Type.\n
  968. - When u8Type is [SOCK_STREAM](@ref SOCK_STREAM) the following configuration values
  969. are defined:\n
  970. - [SOCKET_CONFIG_SSL_OFF](@ref SOCKET_CONFIG_SSL_OFF): The socket is not secured by
  971. TLS.\n
  972. - [SOCKET_CONFIG_SSL_ON](@ref SOCKET_CONFIG_SSL_ON): The socket is secured by TLS.\n
  973. - [SOCKET_CONFIG_SSL_DELAY](@ref SOCKET_CONFIG_SSL_DELAY): The socket is not secured
  974. by TLS, but may be secured later, by calling @ref secure.\n
  975. - When u8Type is [SOCK_RAW](@ref SOCK_RAW), the following configuration values
  976. are defined:\n
  977. - [SOCKET_CONFIG_IPPROTO_RAW](@ref SOCKET_CONFIG_IPPROTO_RAW): The socket is to be
  978. used for raw ICMP frames.\n
  979. - For all values of u8Type, the following configuration values
  980. are defined:\n
  981. - [SOCKET_CONFIG_DEFAULT](@ref SOCKET_CONFIG_DEFAULT): The default configuration.\n
  982. All other configuration values are reserved and should not be
  983. used.
  984. @pre
  985. The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler.
  986. before any call to the @ref socket function can be made.
  987. @see
  988. connect
  989. secure
  990. bind
  991. listen
  992. accept
  993. recv
  994. recvfrom
  995. send
  996. sendto
  997. shutdown
  998. setsockopt
  999. getsockopt
  1000. @return
  1001. On successful socket creation, a non-blocking socket type is created and a socket ID is returned
  1002. In case of failure the function returns a negative value, identifying one of the socket error codes defined.
  1003. For example: @ref SOCK_ERR_INVALID for invalid argument or
  1004. @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets.
  1005. @remarks
  1006. The socket function must be called before any other related socket functions "e.g. send, recv, shutdown ..etc"
  1007. \section SocketExample3 Example
  1008. This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other
  1009. socket operations. Socket creation is dependent on the socket type.
  1010. \subsection sub1 UDP example
  1011. @code
  1012. SOCKET UdpServerSocket = -1;
  1013. UdpServerSocket = socket(AF_INET, SOCK_DGRAM, SOCKET_CONFIG_DEFAULT);
  1014. @endcode
  1015. \subsection sub2 TCP example
  1016. @code
  1017. static SOCKET tcp_client_socket = -1;
  1018. tcp_client_socket = socket(AF_INET, SOCK_STREAM, SOCKET_CONFIG_DEFAULT));
  1019. @endcode
  1020. */
  1021. SOCKET socket(uint16_t u16Domain, uint8_t u8Type, uint8_t u8Config);
  1022. /*!
  1023. \fn \
  1024. int8_t bind(SOCKET sock, struct sockaddr *pstrAddr, uint8_t u8AddrLen);
  1025. Asynchronous bind function associates the provided address and local port to the socket.
  1026. The function can be used with both TCP and UDP sockets. It is mandatory to call the @ref bind function before starting any UDP or TCP server operation.
  1027. Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback.
  1028. @param [in] sock
  1029. Socket ID, must hold a non negative value.
  1030. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1031. @param [in] pstrAddr
  1032. Pointer to socket address structure "sockaddr_in"
  1033. [sockaddr_in](@ref sockaddr_in)
  1034. @param [in] u8AddrLen
  1035. Size of the given socket address structure in bytes.
  1036. @pre
  1037. The socket function must be called to allocate a socket before passing the socket ID to the bind function.
  1038. @see socket
  1039. @see connect
  1040. @see listen
  1041. @see accept
  1042. @see recv
  1043. @see recvfrom
  1044. @see send
  1045. @see sendto
  1046. @return
  1047. The function returns ZERO for successful operations and a negative value otherwise.
  1048. The possible error values are:
  1049. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1050. Indicating that the operation was successful.
  1051. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1052. Indicating passing invalid arguments such as negative socket ID or NULL socket address structure.
  1053. - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID)
  1054. Indicate socket bind failure.
  1055. \section SocketExample4 Example
  1056. This example demonstrates the call of the bind socket operation after a successful socket operation.
  1057. @code
  1058. struct sockaddr_in addr;
  1059. SOCKET udpServerSocket =-1;
  1060. int ret = -1;
  1061. if(udpServerSocket == -1)
  1062. {
  1063. udpServerSocket = socket(AF_INET,SOCK_DGRAM,SOCKET_CONFIG_DEFAULT);
  1064. if(udpServerSocket >= 0)
  1065. {
  1066. addr.sin_family = AF_INET;
  1067. addr.sin_port = _htons(UDP_SERVER_PORT);
  1068. addr.sin_addr.s_addr = 0;
  1069. ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr));
  1070. if(ret == 0)
  1071. printf("Bind success!\n");
  1072. else
  1073. {
  1074. printf("Bind Failed. Error code = %d\n",ret);
  1075. shutdown(udpServerSocket);
  1076. }
  1077. else
  1078. {
  1079. printf("UDP Server Socket Creation Failed\n");
  1080. return;
  1081. }
  1082. }
  1083. @endcode
  1084. */
  1085. int8_t bind(SOCKET sock, struct sockaddr *pstrAddr, uint8_t u8AddrLen);
  1086. /*!
  1087. @fn \
  1088. int8_t listen(SOCKET sock, uint8_t backlog);
  1089. After successfully binding a socket to an IP address and port on the system, start listening passively for incoming connections.
  1090. The socket must be bound on a local port or the listen operation fails.
  1091. Upon the call to the asynchronous listen function, response is received through the event @ref SOCKET_MSG_LISTEN
  1092. in the socket callback.
  1093. A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is
  1094. notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function
  1095. after calling @ref listen.
  1096. After a connection is accepted, the user is then required to call @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection
  1097. termination.
  1098. @param [in] sock
  1099. Socket ID, must hold a non negative value.
  1100. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1101. @param [in] backlog
  1102. Not used by the current implementation.
  1103. @pre
  1104. The bind function must be called to assign the port number and IP address to the socket before the listen operation.
  1105. @see bind
  1106. @see accept
  1107. @see recv
  1108. @see recvfrom
  1109. @see send
  1110. @see sendto
  1111. @return
  1112. The function returns ZERO for successful operations and a negative value otherwise.
  1113. The possible error values are:
  1114. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1115. Indicating that the operation was successful.
  1116. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1117. Indicating invalid arguments were passed, such as negative socket ID.
  1118. - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID)
  1119. Indicate socket listen failure.
  1120. \section SocketExample5 Example
  1121. This example demonstrates the call of the listen socket operation after a successful socket operation.
  1122. @code
  1123. static void TCP_Socketcallback(SOCKET sock, uint8_t u8Msg, void * pvMsg)
  1124. {
  1125. int ret =-1;
  1126. switch(u8Msg)
  1127. {
  1128. case SOCKET_MSG_BIND:
  1129. {
  1130. tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
  1131. if(pstrBind != NULL)
  1132. {
  1133. if(pstrBind->status == 0)
  1134. {
  1135. ret = listen(sock, 0);
  1136. if(ret <0)
  1137. printf("Listen failure! Error = %d\n",ret);
  1138. }
  1139. else
  1140. {
  1141. M2M_ERR("bind Failure!\n");
  1142. shutdown(sock);
  1143. }
  1144. }
  1145. }
  1146. break;
  1147. case SOCKET_MSG_LISTEN:
  1148. {
  1149. tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg;
  1150. if(pstrListen != NULL)
  1151. {
  1152. if(pstrListen->status == 0)
  1153. {
  1154. ret = accept(sock,NULL,0);
  1155. }
  1156. else
  1157. {
  1158. M2M_ERR("listen Failure!\n");
  1159. shutdown(sock);
  1160. }
  1161. }
  1162. }
  1163. break;
  1164. case SOCKET_MSG_ACCEPT:
  1165. {
  1166. tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg;
  1167. if(pstrAccept->sock >= 0)
  1168. {
  1169. TcpNotificationSocket = pstrAccept->sock;
  1170. recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
  1171. }
  1172. else
  1173. {
  1174. M2M_ERR("accept failure\n");
  1175. }
  1176. }
  1177. break;
  1178. default:
  1179. break;
  1180. }
  1181. }
  1182. @endcode
  1183. */
  1184. int8_t listen(SOCKET sock, uint8_t backlog);
  1185. /*!
  1186. @fn \
  1187. int8_t accept(SOCKET sock, struct sockaddr *addr, uint8_t *addrlen);
  1188. The function has no current implementation. An empty declaration is used to prevent errors when legacy application code is used.
  1189. As it has no effect, it can be safely removed from any application using it.
  1190. @param [in] sock
  1191. Socket ID, must hold a non negative value.
  1192. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1193. @param [in] addr
  1194. Not used in the current implementation.
  1195. @param [in] addrlen
  1196. Not used in the current implementation.
  1197. @return
  1198. The function returns ZERO for successful operations and a negative value otherwise.
  1199. The possible error values are:
  1200. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1201. Indicating that the operation was successful.
  1202. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1203. Indicating passing invalid arguments such as negative socket ID.
  1204. */
  1205. int8_t accept(SOCKET sock, struct sockaddr *addr, uint8_t *addrlen);
  1206. /*!
  1207. @fn \
  1208. int8_t connect(SOCKET sock, struct sockaddr *pstrAddr, uint8_t u8AddrLen);
  1209. Establishes a TCP connection with a remote server.
  1210. The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function.
  1211. The application socket callback function is notified of the result of the connection attempt through the event @ref SOCKET_MSG_CONNECT,
  1212. along with a structure @ref tstrSocketConnectMsg.
  1213. If socket connection fails, the application should call @ref shutdown().
  1214. A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv function
  1215. to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection
  1216. termination.
  1217. @param [in] sock
  1218. Socket ID, must hold a non negative value.
  1219. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1220. @param [in] pstrAddr
  1221. Address of the remote server.
  1222. @param [in] u8AddrLen
  1223. Size of the given socket address structure in bytes.
  1224. Not currently used, implemented for BSD compatibility only.
  1225. @pre
  1226. The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function.
  1227. If the socket is not bound, you do NOT have to call bind before the "connect" function.
  1228. @see
  1229. socket
  1230. recv
  1231. send
  1232. shutdown
  1233. @return
  1234. The function returns ZERO for successful operations and a negative value otherwise.
  1235. The possible error values are:
  1236. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1237. Indicating that the operation was successful.
  1238. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1239. Indicating passing invalid arguments such as negative socket ID or NULL socket address structure.
  1240. - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID)
  1241. Indicate socket connect failure.
  1242. \section SocketExample6 Example
  1243. The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the
  1244. callback function handles the @ref SOCKET_MSG_CONNECT event.
  1245. \subsection sub3 Main Function
  1246. @code
  1247. struct sockaddr_in Serv_Addr;
  1248. SOCKET TcpClientSocket =-1;
  1249. int ret = -1
  1250. TcpClientSocket = socket(AF_INET,SOCK_STREAM,SOCKET_CONFIG_DEFAULT);
  1251. Serv_Addr.sin_family = AF_INET;
  1252. Serv_Addr.sin_port = _htons(1234);
  1253. Serv_Addr.sin_addr.s_addr = inet_addr(SERVER);
  1254. printf("Connected to server via socket %u\n",TcpClientSocket);
  1255. do
  1256. {
  1257. ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr));
  1258. if(ret != 0)
  1259. {
  1260. printf("Connection Error\n");
  1261. }
  1262. else
  1263. {
  1264. printf("Connection successful.\n");
  1265. break;
  1266. }
  1267. }while(1)
  1268. @endcode
  1269. \subsection sub4 Socket Callback
  1270. @code
  1271. if(u8Msg == SOCKET_MSG_CONNECT)
  1272. {
  1273. tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
  1274. if(pstrConnect->s8Error == 0)
  1275. {
  1276. uint8_t acBuffer[GROWL_MSG_SIZE];
  1277. uint16_t u16MsgSize;
  1278. printf("Connect success!\n");
  1279. u16MsgSize = FormatMsg(u8ClientID, acBuffer);
  1280. send(sock, acBuffer, u16MsgSize, 0);
  1281. recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT);
  1282. u8Retry = GROWL_CONNECT_RETRY;
  1283. }
  1284. else
  1285. {
  1286. M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error");
  1287. shutdown(pstrNotification->Socket);
  1288. }
  1289. }
  1290. @endcode
  1291. */
  1292. int8_t connect(SOCKET sock, struct sockaddr *pstrAddr, uint8_t u8AddrLen);
  1293. /*!
  1294. @fn \
  1295. int8_t secure(SOCKET sock);
  1296. Converts an (insecure) TCP connection with a remote server into a secure TLS-over-TCP connection.
  1297. It may be called after both of the following:\n
  1298. - a TCP socket has been created by the @ref socket function, with u8Config parameter set to
  1299. @ref SOCKET_CONFIG_SSL_DELAY.\n
  1300. - a successful connection has been made on the socket via the @ref connect function.
  1301. This is an asynchronous API; the application socket callback function is notified of the result
  1302. of the attempt to make the connection secure through the event @ref SOCKET_MSG_SECURE, along
  1303. with a structure @ref tstrSocketConnectMsg.
  1304. If the attempt to make the connection secure fails, the application should call @ref close().
  1305. @param[in] sock
  1306. Socket ID, corresponding to a connected TCP socket.
  1307. @pre
  1308. @ref socket and @ref connect must be called to connect a TCP socket before passing the socket ID to this function.
  1309. Value @ref SOCKET_CONFIG_SSL_DELAY must have been set in the u8Config parameter that was passed to @ref socket.
  1310. @see
  1311. socket
  1312. connect
  1313. @return
  1314. The function returns SOCK_ERR_NO_ERROR for successful operations and a negative error value otherwise.
  1315. The possible error values are:
  1316. - @ref SOCK_ERR_INVALID_ARG
  1317. Indicating passing invalid arguments such as negative socket ID.
  1318. - @ref SOCK_ERR_INVALID
  1319. Indicating failure to process the request.
  1320. */
  1321. int8_t secure(SOCKET sock);
  1322. /*!
  1323. @fn \
  1324. int16_t recv(SOCKET sock, void *pvRecvBuf, uint16_t u16BufLen, uint32_t u32Timeoutmsec);
  1325. An asynchronous receive function, used to retrieve data from a TCP stream.
  1326. Before calling the recv function, a successful socket connection status must have been received through any of the two socket events
  1327. [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote
  1328. host.
  1329. The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the
  1330. socket callback.
  1331. Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following:
  1332. - @ref SOCK_ERR_NO_ERROR : Socket connection closed. The application should now call @ref shutdown().
  1333. - @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted. The application should now call @ref shutdown().
  1334. - @ref SOCK_ERR_TIMEOUT : Socket receive timed out. The socket connection remains open.
  1335. @param [in] sock
  1336. Socket ID, must hold a non negative value.
  1337. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1338. @param [in] pvRecvBuf
  1339. Pointer to a buffer that will hold the received data. The buffer is used
  1340. in the recv callback to deliver the received data to the caller. The buffer must
  1341. be resident in memory (heap or global buffer).
  1342. @param [in] u16BufLen
  1343. The buffer size in bytes.
  1344. @param [in] u32Timeoutmsec
  1345. Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout
  1346. will be set to infinite (the recv function waits forever). If the timeout period is
  1347. elapsed with no data received, the socket will get a timeout error.
  1348. @pre
  1349. - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function.
  1350. - The socket in a connected state is expected to receive data through the socket interface.
  1351. @see socket
  1352. @see connect
  1353. @see bind
  1354. @see listen
  1355. @see recvfrom
  1356. @see shutdown
  1357. @return
  1358. The function returns ZERO for successful operations and a negative value otherwise.
  1359. The possible error values are:
  1360. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1361. Indicating that the operation was successful.
  1362. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1363. Indicating passing invalid arguments such as negative socket ID or NULL receive buffer.
  1364. - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL)
  1365. Indicate socket receive failure.
  1366. \section SocketExample7 Example
  1367. The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the
  1368. received data when the SOCKET_MSG_RECV event is received.
  1369. @code
  1370. switch(u8Msg)
  1371. {
  1372. case SOCKET_MSG_ACCEPT:
  1373. {
  1374. tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg;
  1375. if(pstrAccept->sock >= 0)
  1376. {
  1377. recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
  1378. }
  1379. else
  1380. {
  1381. M2M_ERR("accept\n");
  1382. }
  1383. }
  1384. break;
  1385. case SOCKET_MSG_RECV:
  1386. {
  1387. tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg;
  1388. if(pstrRx->s16BufferSize > 0)
  1389. {
  1390. recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
  1391. }
  1392. else
  1393. {
  1394. printf("Socket recv Error: %d\n",pstrRx->s16BufferSize);
  1395. shutdown(sock);
  1396. }
  1397. }
  1398. break;
  1399. default:
  1400. break;
  1401. }
  1402. @endcode
  1403. */
  1404. int16_t recv(SOCKET sock, void *pvRecvBuf, uint16_t u16BufLen, uint32_t u32Timeoutmsec);
  1405. /*!
  1406. @fn \
  1407. int16_t recvfrom(SOCKET sock, void *pvRecvBuf, uint16_t u16BufLen, uint32_t u32TimeoutSeconds);
  1408. Receives data from a UDP Socket.
  1409. The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to
  1410. a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received
  1411. with successful status in the socket callback).
  1412. Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification
  1413. in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event.
  1414. Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed.
  1415. Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @ref SOCK_ERR_TIMEOUT
  1416. The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by
  1417. using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example)
  1418. @param [in] sock
  1419. Socket ID, must hold a non negative value.
  1420. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1421. @param [in] pvRecvBuf
  1422. Pointer to a buffer that will hold the received data. The buffer shall be used
  1423. in the recv callback to deliver the received data to the caller. The buffer must
  1424. be resident in memory (heap or global buffer).
  1425. @param [in] u16BufLen
  1426. The buffer size in bytes.
  1427. @param [in] u32TimeoutSeconds
  1428. Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout
  1429. will be set to infinite (the recv function waits forever).
  1430. @pre
  1431. - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function.
  1432. - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function.
  1433. @see
  1434. socket
  1435. bind
  1436. shutdown
  1437. @return
  1438. The function returns ZERO for successful operations and a negative value otherwise.
  1439. The possible error values are:
  1440. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1441. Indicating that the operation was successful.
  1442. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1443. Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer.
  1444. - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL)
  1445. Indicate socket receive failure.
  1446. \section SocketExample8 Example
  1447. The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the
  1448. received data when the SOCKET_MSG_RECVFROM event is received.
  1449. @code
  1450. switch(u8Msg)
  1451. {
  1452. case SOCKET_MSG_BIND:
  1453. {
  1454. tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
  1455. if(pstrBind != NULL)
  1456. {
  1457. if(pstrBind->status == 0)
  1458. {
  1459. recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0);
  1460. }
  1461. else
  1462. {
  1463. M2M_ERR("bind\n");
  1464. }
  1465. }
  1466. }
  1467. break;
  1468. case SOCKET_MSG_RECVFROM:
  1469. {
  1470. tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg;
  1471. if(pstrRx->s16BufferSize > 0)
  1472. {
  1473. //get the remote host address and port number
  1474. uint16_t u16port = pstrRx->strRemoteAddr.sin_port;
  1475. uint32_t strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr;
  1476. printf("Received frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port);
  1477. ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT);
  1478. }
  1479. else
  1480. {
  1481. printf("Socket recv Error: %d\n",pstrRx->s16BufferSize);
  1482. ret = shutdown(sock);
  1483. }
  1484. }
  1485. break;
  1486. default:
  1487. break;
  1488. }
  1489. @endcode
  1490. */
  1491. int16_t recvfrom(SOCKET sock, void *pvRecvBuf, uint16_t u16BufLen, uint32_t u32Timeoutmsec);
  1492. /*!
  1493. @fn \
  1494. int16_t send(SOCKET sock, void *pvSendBuffer, uint16_t u16SendLength, uint16_t u16Flags);
  1495. Asynchronous sending function, used to send data on a TCP/UDP socket.
  1496. Called by the application code when there is outgoing data available required to be sent on a specific socket handler.
  1497. The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in.
  1498. @ref send function is most commonly called for sockets in a connected state.
  1499. After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type
  1500. @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent.
  1501. @param [in] sock
  1502. Socket ID, must hold a non negative value.
  1503. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1504. @param [in] pvSendBuffer
  1505. Pointer to a buffer holding data to be transmitted.
  1506. @param [in] u16SendLength
  1507. The buffer size in bytes.
  1508. @param [in] u16Flags
  1509. Not used in the current implementation.
  1510. @pre
  1511. Sockets must be initialized using socketInit. \n
  1512. For TCP Socket:\n
  1513. Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data).
  1514. Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the
  1515. the server case).\n
  1516. For UDP Socket:\n
  1517. UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data
  1518. using the @ref send function, at least one successful call must be made to the @ref sendto function before consecutive calls to the @ref send function,
  1519. to ensure that the destination address is saved in the firmware.
  1520. @see
  1521. socketInit
  1522. recv
  1523. sendto
  1524. socket
  1525. connect
  1526. accept
  1527. sendto
  1528. @warning
  1529. u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n
  1530. Use a valid socket identifier through the prior call to the @ref socket function.
  1531. Must use a valid buffer pointer.
  1532. Successful completion of a call to send() does not guarantee delivery of the message,
  1533. A negative return value indicates only locally-detected errors
  1534. * @return The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value otherwise.
  1535. */
  1536. int16_t send(SOCKET sock, void *pvSendBuffer, uint16_t u16SendLength, uint16_t u16Flags);
  1537. /*!
  1538. * @fn int16_t sendto(SOCKET sock, void *pvSendBuffer, uint16_t u16SendLength, uint16_t flags, struct sockaddr *pstrDestAddr, uint8_t u8AddrLen);
  1539. * @brief Asynchronous sending function, used to send data on a UDP socket.
  1540. * Called by the application code when there is data required to be sent on a UDP socket.
  1541. * @details The application code is expected to receive data from a successfully bound socket node.
  1542. * The only difference between this function and the similar @ref send function, is the type of socket the data is received on.
  1543. * This function works only with UDP sockets.
  1544. * After the data is sent, the socket callback function registered using @ref registerSocketCallback(), is expected to receive an
  1545. * event of type @ref SOCKET_MSG_SENDTO.
  1546. * @param[in] sock
  1547. * Socket ID, must hold a non negative value.
  1548. * A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1549. * @param[in] pvSendBuffer
  1550. * Pointer to a buffer holding data to be transmitted.
  1551. * A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1552. * @param[in] u16SendLength
  1553. * The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH.
  1554. * @param[in] flags
  1555. * Not used in the current implementation
  1556. * @param[in] pstrDestAddr
  1557. * The destination address.
  1558. * @param[in] u8AddrLen
  1559. * Destination address length in bytes.
  1560. * Not used in the current implementation, only included for BSD compatibility.
  1561. * @pre Sockets must be initialized using @ref socketInit.
  1562. * @see
  1563. * socketInit
  1564. * recvfrom
  1565. * sendto
  1566. * socket
  1567. * connect
  1568. * accept
  1569. * send
  1570. * @warning
  1571. * u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH.\n
  1572. * Use a valid socket (returned from socket).
  1573. * A valid buffer pointer must be used (not NULL).\n
  1574. * Successful completion of a call to sendto does not guarantee delivery of the message,
  1575. * A negative return value indicates only locally-detected errors.
  1576. * @return The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.
  1577. */
  1578. int16_t sendto(SOCKET sock, void *pvSendBuffer, uint16_t u16SendLength, uint16_t flags, struct sockaddr *pstrDestAddr, uint8_t u8AddrLen);
  1579. /*!
  1580. * @fn int8_t shutdown(SOCKET sock);
  1581. * @brief Synchronous shutdown function, releases all the socket assigned resources.
  1582. * @param[in] sock
  1583. * Socket ID, must hold a non negative value.
  1584. * A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1585. * @pre
  1586. * Sockets must be initialized through the call of the socketInit function.
  1587. * @ref shutdown is called only for valid socket identifiers created through the @ref socket function.
  1588. * @warning If @ref shutdown is called while there are still pending messages (sent or received ) they will be discarded.
  1589. * @see socketInit, socket
  1590. * @return The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.
  1591. */
  1592. int8_t shutdown(SOCKET sock);
  1593. /*!
  1594. * @fn int8_t gethostbyname(const char *pcHostName);
  1595. * Asynchronous DNS resolving function. This function uses DNS to resolve a domain name to the corresponding IP address.
  1596. * A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback
  1597. * function registered using registerSocketCallback.
  1598. * @param[in] pcHostName
  1599. * NULL terminated string containing the domain name for the remote host.
  1600. * Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE).
  1601. * @see registerSocketCallback
  1602. * @warning
  1603. * Successful completion of a call to gethostbyname() does not guarantee success of the DNS request,
  1604. * a negative return value indicates only locally-detected errors
  1605. * @return
  1606. * - @ref SOCK_ERR_NO_ERROR
  1607. * - @ref SOCK_ERR_INVALID_ARG
  1608. */
  1609. int8_t gethostbyname(const char *pcHostName);
  1610. /*!
  1611. @fn \
  1612. int8_t setsockopt(SOCKET socket, uint8_t u8Level, uint8_t option_name,
  1613. const void *option_value, uint16_t u16OptionLen);
  1614. The setsockopt() function shall set the option specified by the option_name
  1615. argument, at the protocol level specified by the level argument, to the value
  1616. pointed to by the option_value argument for the socket specified by the socket argument.
  1617. @param[in] socket
  1618. Socket handler.
  1619. @param[in] u8Level
  1620. Protocol level.\n
  1621. Supported protocol levels are @ref SOL_SOCKET, @ref SOL_SSL_SOCKET and @ref SOL_RAW.
  1622. @param[in] option_name
  1623. Option to be set.\n
  1624. For protocol level @ref SOL_SOCKET, the supported option names are:\n
  1625. @ref SO_SET_UDP_SEND_CALLBACK\n
  1626. @ref SO_TCP_KEEPALIVE\n
  1627. @ref SO_TCP_KEEPIDLE\n
  1628. @ref SO_TCP_KEEPINTVL\n
  1629. @ref SO_TCP_KEEPCNT\n
  1630. For protocol level @ref SOL_SSL_SOCKET, the supported option names are:\n
  1631. @ref SO_SSL_BYPASS_X509_VERIF\n
  1632. @ref SO_SSL_SNI\n
  1633. @ref SO_SSL_ENABLE_SESSION_CACHING\n
  1634. @ref SO_SSL_ENABLE_CERTNAME_VALIDATION\n
  1635. @ref SO_SSL_ALPN\n
  1636. For protocol level @ref SOL_RAW, the supported option names are:\n
  1637. @ref SO_ICMP_FILTER\n
  1638. @param[in] option_value
  1639. Pointer to user provided value.
  1640. @param[in] u16OptionLen
  1641. Length of the option value in bytes. Refer to each option documentation for the required length.
  1642. @return
  1643. The function shall return \ref SOCK_ERR_NO_ERROR for successful operation
  1644. and a negative value (indicating the error) otherwise.
  1645. */
  1646. int8_t setsockopt(SOCKET socket, uint8_t u8Level, uint8_t option_name,
  1647. const void *option_value, uint16_t u16OptionLen);
  1648. /*!
  1649. * @fn int8_t getsockopt(SOCKET sock, uint8_t u8Level, uint8_t u8OptName, const void *pvOptValue, uint8_t *pu8OptLen);
  1650. * @brief Get socket options retrieves.
  1651. * This Function isn't implemented yet but this is the form that will be released later.
  1652. * @param[in] sock
  1653. * Socket Identifier.
  1654. * @param[in] u8Level
  1655. * The protocol level of the option.
  1656. * @param[in] u8OptName
  1657. * The u8OptName argument specifies a single option to get.
  1658. * @param[out] pvOptValue
  1659. * The pvOptValue argument contains pointer to a buffer containing the option value.
  1660. * @param[out] pu8OptLen
  1661. * Option value buffer length.
  1662. * @return The function shall return ZERO for successful operation and a negative value otherwise.
  1663. */
  1664. int8_t getsockopt(SOCKET sock, uint8_t u8Level, uint8_t u8OptName, const void *pvOptValue, uint8_t *pu8OptLen);
  1665. /*!
  1666. * @fn int8_t m2m_ping_req(uint32_t u32DstIP, uint8_t u8TTL, tpfPingCb fpPingCb);
  1667. * @brief The function request to send ping request to the given IP Address.
  1668. * @param[in] u32DstIP
  1669. * Target Destination IP Address for the ping request. It must be represented in Network byte order.
  1670. * The function @ref nmi_inet_addr could be used to translate the dotted decimal notation IP
  1671. * to its Network bytes order integer representative.
  1672. * @param[in] u8TTL
  1673. * IP TTL value for the ping request. If set to ZERO, the default value SHALL be used.
  1674. * @param[in] fpPingCb
  1675. * Callback will be called to deliver the ping statistics.
  1676. * @warning This API should only be used to request one ping at a time; calling this API invalidates callbacks
  1677. * for previous ping requests.
  1678. * @see nmi_inet_addr
  1679. * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
  1680. */
  1681. int8_t m2m_ping_req(uint32_t u32DstIP, uint8_t u8TTL, tpfPingCb fpPingCb);
  1682. /*!
  1683. * @fn int8_t set_alpn_list(SOCKET sock, const char *pcProtocolList);
  1684. *
  1685. * This function sets the protocol list used for application-layer protocol negotiation (ALPN).
  1686. * If used, it must be called after creating a SSL socket (using @ref socket) and before
  1687. * connecting/binding (using @ref connect or @ref bind) or securing (using @ref secure).
  1688. *
  1689. * @param[in] sock
  1690. * Socket ID obtained by a call to @ref socket. This is the SSL socket to which
  1691. * the ALPN list applies.
  1692. *
  1693. * @param[in] pcProtocolList
  1694. * Pointer to the list of protocols available in the application. \n
  1695. * The entries in the list must: \n
  1696. * - be separated with ' ' (space). \n
  1697. * - not contain ' ' (space) or '\0' (NUL). \n
  1698. * - be non-zero length. \n
  1699. * .
  1700. * The list itself must: \n
  1701. * - be terminated with '\0' (NUL). \n
  1702. * - be no longer than @ref ALPN_LIST_MAX_APP_LENGTH, including separators (spaces) and terminator (NUL). \n
  1703. * - contain at least one entry.
  1704. *
  1705. * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
  1706. *
  1707. * \section SocketExample9 Example
  1708. * The example demonstrates an application using @ref set_alpn_list and @ref get_alpn_index to negotiate secure HTTP/2
  1709. * (with fallback option of HTTP/1.1).
  1710. * \subsection sub5 Main Function
  1711. * @code
  1712. * SOCKET TcpClientSocket = socket(AF_INET, SOCK_STREAM, SOCKET_CONFIG_SSL_ON);
  1713. * if (TcpClientSocket >= 0)
  1714. * {
  1715. * struct sockaddr_in Serv_Addr = {
  1716. * .sin_family = AF_INET,
  1717. * .sin_port = _htons(1234),
  1718. * .sin_addr.s_addr = inet_addr(SERVER)
  1719. * };
  1720. * set_alpn_list(TcpClientSocket, "h2 http/1.1");
  1721. * connect(TcpClientSocket, &Serv_Addr, sizeof(Serv_Addr));
  1722. * }
  1723. * @endcode
  1724. * \subsection sub6 Socket Callback
  1725. * @code
  1726. * if(u8Msg == SOCKET_MSG_CONNECT)
  1727. * {
  1728. * tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
  1729. * if(pstrConnect->s8Error == 0)
  1730. * {
  1731. * uint8_t alpn_index = get_alpn_index(pstrConnect->sock);
  1732. * switch (alpn_index)
  1733. * {
  1734. * case 1:
  1735. * printf("Negotiated HTTP/2\n");
  1736. * break;
  1737. * case 2:
  1738. * printf("Negotiated HTTP/1.1\n");
  1739. * break;
  1740. * case 0:
  1741. * printf("Protocol negotiation did not occur\n");
  1742. * break;
  1743. * }
  1744. * }
  1745. * }
  1746. * @endcode
  1747. */
  1748. int8_t set_alpn_list(SOCKET sock, const char *pcProtocolList);
  1749. /*!
  1750. * @fn int8_t get_alpn_index(SOCKET sock);
  1751. *
  1752. * This function gets the index of the protocol negotiated via ALPN.
  1753. * It should be called when a SSL socket connection succeeds, in order to determine which
  1754. * application-layer protocol must be used.
  1755. *
  1756. * @param[in] sock
  1757. * Socket ID obtained by a call to @ref socket. This is the SSL socket to which
  1758. * the ALPN applies.
  1759. *
  1760. * @return The function returns:\n
  1761. * - >0: 1-based index of negotiated protocol with respect to the list previously provided to @ref set_alpn_list.\n
  1762. * - 0: No negotiation occurred (eg TLS peer did not support ALPN).\n
  1763. * - <0: Invalid parameters (socket is not in use, or not an SSL socket).\n
  1764. *
  1765. * @see @ref SocketExample9
  1766. */
  1767. int8_t get_alpn_index(SOCKET sock);
  1768. /*!
  1769. *@fn int8_t get_error_detail(SOCKET sock, tstrSockErr *pstrErr);
  1770. *
  1771. * This function gets detail about a socket failure. The application can call this when notified
  1772. * of a socket failure via @ref SOCKET_MSG_CONNECT or @ref SOCKET_MSG_RECV.
  1773. * If used, it must be called before @ref shutdown.
  1774. * @param[in] sock
  1775. * Socket ID obtained by a call to @ref socket.
  1776. *
  1777. * @param[out] pstrErr
  1778. * Pointer to structure to be populated with the details of the socket failure.
  1779. *
  1780. * @return The function returns @ref SOCK_ERR_NO_ERROR if the request is successful. In this case pstrErr
  1781. * has been populated.
  1782. * The function returns a negative value if the request is not successful. In this case pstrErr
  1783. * has not been populated.
  1784. */
  1785. int8_t get_error_detail(SOCKET sock, tstrSockErr *pstrErr);
  1786. /**@}*/ // SocketAPI
  1787. #ifdef __cplusplus
  1788. }
  1789. #endif /* __cplusplus */
  1790. #endif /* __SOCKET_H__ */