Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

1741 rinda
57 KiB

  1. /**
  2. *
  3. * \file
  4. *
  5. * \brief BSD compatible socket interface.
  6. *
  7. * Copyright (c) 2017-2018 Microchip Technology Inc. and its subsidiaries.
  8. *
  9. * \asf_license_start
  10. *
  11. * \page License
  12. *
  13. * Subject to your compliance with these terms, you may use Microchip
  14. * software and any derivatives exclusively with Microchip products.
  15. * It is your responsibility to comply with third party license terms applicable
  16. * to your use of third party software (including open source software) that
  17. * may accompany Microchip software.
  18. *
  19. * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES,
  20. * WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE,
  21. * INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,
  22. * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE
  23. * LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL
  24. * LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE
  25. * SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE
  26. * POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT
  27. * ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY
  28. * RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
  29. * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
  30. *
  31. * \asf_license_stop
  32. *
  33. */
  34. /**@defgroup SOCKETAPI SOCKET
  35. */
  36. #ifndef __SOCKET_H__
  37. #define __SOCKET_H__
  38. #ifdef __cplusplus
  39. extern "C" {
  40. #endif
  41. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  42. INCLUDES
  43. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  44. #include "driver/include/m2m_types.h"
  45. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  46. MACROS
  47. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  48. /**@defgroup SOCKETDEF Defines
  49. * @ingroup SOCKETAPI
  50. * The following list of macros are used to define constants used throughout the socket layer, and SSL Socket options.
  51. * @{ */
  52. #define HOSTNAME_MAX_SIZE 100
  53. /*!<
  54. Maximum allowed size for a host domain name passed to the function gethostbyname @ref gethostbyname.
  55. command value. Used with the setsocketopt function.
  56. */
  57. #define SOCKET_BUFFER_MAX_LENGTH 1400
  58. /*!<
  59. Maximum allowed size for a socket data buffer. Used with @ref send socket
  60. function to ensure that the buffer sent is within the allowed range.
  61. */
  62. #define AF_INET 2
  63. /*!<
  64. The AF_INET is the address family used for IPv4. An IPv4 transport address is specified with the @ref sockaddr_in structure.
  65. (It is the only supported type for the current implementation.)
  66. */
  67. #define SOCK_STREAM 1
  68. /*!<
  69. One of the IPv4 supported socket types for reliable connection-oriented stream connection.
  70. Passed to the @ref socket function for the socket creation operation.
  71. */
  72. #define SOCK_DGRAM 2
  73. /*!<
  74. One of the IPv4 supported socket types for unreliable connectionless datagram connection.
  75. Passed to the @ref socket function for the socket creation operation.
  76. */
  77. #define SOCKET_FLAGS_SSL 0x01
  78. /*!<
  79. This flag shall be passed to the socket API for SSL session.
  80. */
  81. #define TCP_SOCK_MAX (7)
  82. /*!<
  83. Maximum number of simultaneous TCP sockets.
  84. */
  85. #define UDP_SOCK_MAX 4
  86. /*!<
  87. Maximum number of simultaneous UDP sockets.
  88. */
  89. #define MAX_SOCKET (TCP_SOCK_MAX + UDP_SOCK_MAX)
  90. /*!<
  91. Maximum number of simultaneous sockets.
  92. */
  93. #define SOL_SOCKET 1
  94. /*!<
  95. Socket option.
  96. Used with the @ref setsockopt function
  97. */
  98. #define SO_SET_UDP_SEND_CALLBACK 0x00
  99. /*!<
  100. Socket option used by the application to enable/disable
  101. the use of UDP send callbacks.
  102. Used with the @ref setsockopt function.
  103. */
  104. #define IP_ADD_MEMBERSHIP 0x01
  105. /*!<
  106. Set Socket Option Add Membership command value.
  107. Used with the @ref setsockopt function.
  108. */
  109. #define IP_DROP_MEMBERSHIP 0x02
  110. /*!<
  111. Set Socket Option Drop Membership command value.
  112. Used with the @ref setsockopt function.
  113. */
  114. // SSL Socket options
  115. #define SOL_SSL_SOCKET 2
  116. /*!<
  117. SSL Socket option level.
  118. Used with the @ref setsockopt function
  119. */
  120. #define SO_SSL_BYPASS_X509_VERIF 0x01
  121. /*!<
  122. Allow an opened SSL socket to bypass the X509 certificate
  123. verification process.
  124. It is highly recommended NOT to use this socket option in production
  125. software applications. It is intended for debugging and testing
  126. purposes only.\n
  127. The option value should be cast to int type and it is handled
  128. as a boolean flag.
  129. */
  130. #define SO_SSL_SNI 0x02
  131. /*!<
  132. Set the Server Name Indicator (SNI) for an SSL socket. The
  133. SNI is a NULL terminated string containing the server name
  134. associated with the connection. It must not exceed the size
  135. of HOSTNAME_MAX_SIZE. If the SNI is not a null string, then
  136. TLS Client Hello messages will include the SNI extension.
  137. */
  138. #define SO_SSL_ENABLE_SESSION_CACHING 0x03
  139. /*!<
  140. Allow the TLS to cache the session information for fast
  141. TLS session establishment in future connections using the
  142. TLS Protocol session resume features.\n
  143. The option value should be cast to int type and it is handled
  144. as a boolean flag.
  145. */
  146. #define SO_SSL_ENABLE_CERTNAME_VALIDATION 0x04
  147. /*!<
  148. Enable internal validation of server name against the server's
  149. certificate subject common name. If there is no server name
  150. provided (via the SO_SSL_SNI option), setting this option does
  151. nothing.\n
  152. The option value should be cast to int type and it is handled
  153. as a boolean flag.
  154. */
  155. #define SO_SSL_ENABLE_SNI_VALIDATION 0x04
  156. /*!<
  157. Legacy name for @ref SO_SSL_ENABLE_CERTNAME_VALIDATION.\n
  158. The option value should be cast to int type and it is handled
  159. as a boolean flag.
  160. */
  161. //@}
  162. /** @defgroup SSLCipherSuiteID TLS Cipher Suite IDs
  163. * @ingroup TLSDefines
  164. * The following list of macros defined the list of supported TLS Cipher suites.
  165. * Each MACRO defines a single Cipher suite.
  166. * @sa m2m_ssl_set_active_ciphersuites
  167. * @{
  168. */
  169. #define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA NBIT0
  170. #define SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 NBIT1
  171. #define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA NBIT2
  172. #define SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 NBIT3
  173. #define SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 NBIT4
  174. #define SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 NBIT5
  175. #define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA NBIT6
  176. #define SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 NBIT7
  177. #define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA NBIT8
  178. #define SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 NBIT9
  179. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA NBIT10
  180. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_256_CBC_SHA NBIT11
  181. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_CBC_SHA256 NBIT12
  182. #define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 NBIT13
  183. #define SSL_CIPHER_ECDHE_RSA_WITH_AES_128_GCM_SHA256 NBIT14
  184. #define SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 NBIT15
  185. #define SSL_ECC_ONLY_CIPHERS \
  186. (\
  187. SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 | \
  188. SSL_CIPHER_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \
  189. )
  190. /*!<
  191. All supported ECC Ciphers. These ciphers are turned off by default at startup.
  192. The application may enable them if it has an ECC math engine (like ATECC508).
  193. */
  194. #define SSL_DEFAULT_CIPHERS \
  195. (\
  196. SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA | \
  197. SSL_CIPHER_RSA_WITH_AES_128_CBC_SHA256 | \
  198. SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA | \
  199. SSL_CIPHER_DHE_RSA_WITH_AES_128_CBC_SHA256 | \
  200. SSL_CIPHER_RSA_WITH_AES_128_GCM_SHA256 | \
  201. SSL_CIPHER_DHE_RSA_WITH_AES_128_GCM_SHA256 | \
  202. SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA | \
  203. SSL_CIPHER_RSA_WITH_AES_256_CBC_SHA256 | \
  204. SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA | \
  205. SSL_CIPHER_DHE_RSA_WITH_AES_256_CBC_SHA256 \
  206. )
  207. /*!<
  208. All supported Non-ECC Ciphers. This is the default active group after startup.
  209. Note that firmware may support only a subset of these.
  210. */
  211. //@}
  212. /**@defgroup SOCKETBYTEORDER Byte Order
  213. * @ingroup SOCKETAPI
  214. * The following list of macros are used to convert between host representation and network byte order.
  215. * @{ */
  216. #ifdef _NM_BSP_BIG_END
  217. #define _htonl(m) (m)
  218. /*!<
  219. Convert a 4-byte integer from the Host representation to Network byte order (Host is BE).
  220. */
  221. #define _htons(A) (A)
  222. /*!<
  223. Convert a 2-byte integer (short) from Host representation to Network byte order (Host is BE).
  224. */
  225. #else
  226. #define _htonl(m) \
  227. (uint32)(((uint32)(m << 24)) | ((uint32)((m & 0x0000FF00) << 8)) | ((uint32)((m & 0x00FF0000) >> 8)) | ((uint32)(((uint32)m) >> 24)))
  228. /*!<
  229. Convert a 4-byte integer from Host representation to Network byte order (Host is LE).
  230. */
  231. #define _htons(A) (uint16)((((uint16) (A)) << 8) | (((uint16) (A)) >> 8))
  232. /*!<
  233. Convert a 2-byte integer (short) from Host representation to Network byte order (Host is LE).
  234. */
  235. #endif
  236. #define _ntohl _htonl
  237. /*!<
  238. Convert a 4-byte integer from Network byte order to Host representation.
  239. */
  240. #define _ntohs _htons
  241. /*!<
  242. Convert a 2-byte integer from Network byte order to Host representation.
  243. */
  244. //@}
  245. /**************
  246. Socket Errors
  247. **************/
  248. /**@defgroup SocketErrorCode Error Codes
  249. * @ingroup SOCKETAPI
  250. * The following list of macros are used to define the possible error codes.
  251. * Errors are listed in numerical order with the error macro name.
  252. * @{
  253. */
  254. #define SOCK_ERR_NO_ERROR 0
  255. /*!<
  256. Successful socket operation. This code is also used with event @ref SOCKET_MSG_RECV if a socket connection is closed.
  257. In that case, the application should call @ref close().
  258. */
  259. #define SOCK_ERR_INVALID_ADDRESS -1
  260. /*!<
  261. Socket address is invalid. The socket operation cannot be completed successfully without specifying a valid address
  262. For example: bind is called without specifying a port number
  263. */
  264. #define SOCK_ERR_ADDR_ALREADY_IN_USE -2
  265. /*!<
  266. Socket operation cannot bind on the given address. Only one IP address per socket, and one socket per IP address is permitted -
  267. any attempt for a new socket to bind with an IP address already bound to another open socket will return the following error code.
  268. */
  269. #define SOCK_ERR_MAX_TCP_SOCK -3
  270. /*!<
  271. Exceeded the maximum number of TCP sockets. A maximum number of TCP sockets opened simultaneously is defined through TCP_SOCK_MAX.
  272. It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed.
  273. */
  274. #define SOCK_ERR_MAX_UDP_SOCK -4
  275. /*!<
  276. Exceeded the maximum number of UDP sockets. A maximum number of UDP sockets opened simultaneously is defined through UDP_SOCK_MAX.
  277. It is not permitted to exceed that number at socket creation. Identifies that @ref socket operation failed
  278. */
  279. #define SOCK_ERR_INVALID_ARG -6
  280. /*!<
  281. An invalid argument is passed to a socket function. Identifies that @ref socket operation failed
  282. */
  283. #define SOCK_ERR_MAX_LISTEN_SOCK -7
  284. /*!<
  285. Exceeded the maximum number of TCP passive listening sockets.
  286. Identifies that @ref listen operation failed.
  287. */
  288. #define SOCK_ERR_INVALID -9
  289. /*!<
  290. The requested socket operation is not valid in the current socket state.
  291. For example: @ref accept is called on a TCP socket before @ref bind or @ref listen.
  292. */
  293. #define SOCK_ERR_ADDR_IS_REQUIRED -11
  294. /*!<
  295. Destination address is required. Failure to provide the socket address required for the socket operation to be completed.
  296. The @ref sendto function requires a destination address to send data.
  297. */
  298. #define SOCK_ERR_CONN_ABORTED -12
  299. /*!<
  300. The socket is closed (reset) by the peer. If this error is received, the application should call @ref close().
  301. */
  302. #define SOCK_ERR_TIMEOUT -13
  303. /*!<
  304. The socket pending operation has timed out. The socket remains open.
  305. */
  306. #define SOCK_ERR_BUFFER_FULL -14
  307. /*!<
  308. No buffer space available to be used for the requested socket operation.
  309. */
  310. //@}
  311. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  312. DATA TYPES
  313. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  314. /** @defgroup SocketEnums Enumeration/Typedefs
  315. * @ingroup SOCKETAPI
  316. * Specific Enumeration-typedefs used for socket operations
  317. * @{ */
  318. /*!
  319. @typedef \
  320. SOCKET
  321. @brief
  322. Definition for socket handler data type.
  323. Socket ID,used with all socket operations to uniquely identify the socket handler.
  324. The ID is uniquely assigned at socket creation when calling @ref socket operation.
  325. */
  326. typedef sint8 SOCKET;
  327. //@}
  328. /*!
  329. @struct \
  330. in_addr
  331. @brief
  332. IPv4 address representation.
  333. This structure is used as a placeholder for IPV4 address in other structures.
  334. @see
  335. sockaddr_in
  336. */
  337. typedef struct{
  338. uint32 s_addr;
  339. /*!<
  340. Network Byte Order representation of the IPv4 address. For example,
  341. the address "192.168.0.10" is represented as 0x0A00A8C0.
  342. */
  343. }in_addr;
  344. /*!
  345. @struct \
  346. sockaddr
  347. @brief
  348. Generic socket address structure.
  349. @see \
  350. sockaddr_in
  351. */
  352. struct sockaddr{
  353. uint16 sa_family;
  354. /*!<
  355. Socket address family.
  356. */
  357. uint8 sa_data[14];
  358. /*!<
  359. Maximum size of all the different socket address structures.
  360. */
  361. };
  362. /*!
  363. @struct \
  364. sockaddr_in
  365. @brief
  366. Socket address structure for IPV4 addresses. Used to specify socket address information to connect to.
  367. Can be cast to @ref sockaddr structure.
  368. */
  369. struct sockaddr_in{
  370. uint16 sin_family;
  371. /*!<
  372. Specifies the address family(AF).
  373. Members of AF_INET address family are IPv4 addresses.
  374. Hence,the only supported value for this is AF_INET.
  375. */
  376. uint16 sin_port;
  377. /*!<
  378. Port number of the socket.
  379. Network sockets are identified by a pair of IP addresses and port number.
  380. Must be set in the Network Byte Order format , @ref _htons (e.g. _htons(80)).
  381. Can NOT have zero value.
  382. */
  383. in_addr sin_addr;
  384. /*!<
  385. IP Address of the socket.
  386. The IP address is of type @ref in_addr structure.
  387. Can be set to "0" to accept any IP address for server operation.
  388. */
  389. uint8 sin_zero[8];
  390. /*!<
  391. Padding to make structure the same size as @ref sockaddr.
  392. */
  393. };
  394. /**@addtogroup SocketEnums
  395. * @{ */
  396. /*!
  397. @enum \
  398. tenuSocketCallbackMsgType
  399. @brief
  400. Asynchronous APIs make use of callback functions in-order to return back the results once the corresponding socket operation is completed.
  401. Hence resuming the normal execution of the application code while the socket operation returns the results.
  402. Callback functions expect event messages to be passed in, in-order to identify the operation they're returning the results for.
  403. The following enum identifies the type of events that are received in the callback function.
  404. Application Use:
  405. In order for application developers to handle the pending events from the network controller through the callback functions,
  406. a function call must be made to the function @ref m2m_wifi_handle_events at least once for each socket operation.
  407. @see bind
  408. @see listen
  409. @see accept
  410. @see connect
  411. @see send
  412. @see recv
  413. */
  414. typedef enum{
  415. SOCKET_MSG_BIND = 1,
  416. /*!<
  417. Bind socket event.
  418. */
  419. SOCKET_MSG_LISTEN,
  420. /*!<
  421. Listen socket event.
  422. */
  423. SOCKET_MSG_DNS_RESOLVE,
  424. /*!<
  425. DNS Resolution event.
  426. */
  427. SOCKET_MSG_ACCEPT,
  428. /*!<
  429. Accept socket event.
  430. */
  431. SOCKET_MSG_CONNECT,
  432. /*!<
  433. Connect socket event.
  434. */
  435. SOCKET_MSG_RECV,
  436. /*!<
  437. Receive socket event.
  438. */
  439. SOCKET_MSG_SEND,
  440. /*!<
  441. Send socket event.
  442. */
  443. SOCKET_MSG_SENDTO,
  444. /*!<
  445. Sendto socket event.
  446. */
  447. SOCKET_MSG_RECVFROM
  448. /*!<
  449. Recvfrom socket event.
  450. */
  451. }tenuSocketCallbackMsgType;
  452. // @}
  453. /*!
  454. @struct \
  455. tstrSocketBindMsg
  456. @brief Socket bind status.
  457. An asynchronous call to the @ref bind socket operation, returns information through this structure in response.
  458. This structure together with the event @ref SOCKET_MSG_BIND are passed in parameters to the callback function.
  459. @see
  460. bind
  461. */
  462. typedef struct{
  463. sint8 status;
  464. /*!<
  465. The result of the bind operation.
  466. Holding a value of ZERO for a successful bind or otherwise a negative
  467. error code corresponding to @ref SocketErrorCode.
  468. */
  469. }tstrSocketBindMsg;
  470. /*!
  471. @struct \
  472. tstrSocketListenMsg
  473. @brief Socket listen status.
  474. Socket listen information is returned through this structure in response to the asynchronous call to the @ref listen function.
  475. This structure together with the event @ref SOCKET_MSG_LISTEN are passed-in parameters to the callback function.
  476. @see
  477. listen
  478. */
  479. typedef struct{
  480. sint8 status;
  481. /*!<
  482. Holding a value of ZERO for a successful listen or otherwise a negative
  483. error code corresponding to @ref SocketErrorCode.
  484. */
  485. }tstrSocketListenMsg;
  486. /*!
  487. @struct \
  488. tstrSocketAcceptMsg
  489. @brief Socket accept status.
  490. Socket accept information is returned through this structure in response to the asynchronous call to the @ref accept function.
  491. This structure together with the event @ref SOCKET_MSG_ACCEPT are passed-in parameters to the callback function.
  492. */
  493. typedef struct{
  494. SOCKET sock;
  495. /*!<
  496. On a successful @ref accept operation, the return information is the socket ID for the accepted connection with the remote peer.
  497. Otherwise a negative error code is returned to indicate failure of the accept operation.
  498. */
  499. struct sockaddr_in strAddr;
  500. /*!<
  501. Socket address structure for the remote peer.
  502. */
  503. }tstrSocketAcceptMsg;
  504. /*!
  505. @struct \
  506. tstrSocketConnectMsg
  507. @brief Socket connect status.
  508. Socket connect information is returned through this structure in response to the asynchronous call to the @ref connect socket function.
  509. This structure together with the event @ref SOCKET_MSG_CONNECT are passed-in parameters to the callback function.
  510. If the application receives this structure with a negative value in s8Error, the application should call @ref close().
  511. */
  512. typedef struct{
  513. SOCKET sock;
  514. /*!<
  515. Socket ID referring to the socket passed to the connect function call.
  516. */
  517. sint8 s8Error;
  518. /*!<
  519. Connect error code.
  520. Holding a value of ZERO for a successful connect or otherwise a negative
  521. error code corresponding to the type of error.
  522. */
  523. }tstrSocketConnectMsg;
  524. /*!
  525. @struct \
  526. tstrSocketRecvMsg
  527. @brief Socket recv status.
  528. Socket receive information is returned through this structure in response to the asynchronous call to the recv or recvfrom socket functions.
  529. This structure together with the events @ref SOCKET_MSG_RECV or @ref SOCKET_MSG_RECVFROM are passed-in parameters to the callback function.
  530. @remark
  531. In case the received data from the remote peer is larger than the USER buffer size defined during the asynchronous call to the @ref recv function,
  532. only data up to the buffer size is delivered to the user. The user must call @ref recv again in order to receive the remaining data.
  533. A negative or zero buffer size indicates an error with the following code:
  534. @ref SOCK_ERR_NO_ERROR : Socket connection closed. The application should now call @ref close().
  535. @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted. The application should now call @ref close().
  536. @ref SOCK_ERR_TIMEOUT : Socket receive timed out. The socket connection remains open.
  537. */
  538. typedef struct{
  539. uint8 *pu8Buffer;
  540. /*!<
  541. Pointer to the USER buffer (passed to @ref recv and @ref recvfrom function) containing the received data chunk.
  542. */
  543. sint16 s16BufferSize;
  544. /*!<
  545. The received data chunk size.
  546. Holds a negative value if there is a receive error or ZERO on success upon reception of close socket message.
  547. */
  548. uint16 u16RemainingSize;
  549. /*!<
  550. The number of bytes remaining in the current @ref recv operation.
  551. */
  552. struct sockaddr_in strRemoteAddr;
  553. /*!<
  554. Socket address structure for the remote peer. It is valid for @ref SOCKET_MSG_RECVFROM event.
  555. */
  556. }tstrSocketRecvMsg;
  557. /**@addtogroup SocketEnums
  558. * @{ */
  559. /*!
  560. @typedef \
  561. tpfAppSocketCb
  562. @brief
  563. The main socket application callback function. Applications register their main socket application callback through this function by calling @ref registerSocketCallback.
  564. In response to events received, the following callback function is called to handle the corresponding asynchronous function called. Example: @ref bind, @ref connect,...etc.
  565. @param [in] sock
  566. Socket ID for the callback.
  567. The socket callback function is called whenever a new event is received in response
  568. to socket operations.
  569. @param [in] u8Msg
  570. Socket event type. Possible values are:
  571. - @ref SOCKET_MSG_BIND
  572. - @ref SOCKET_MSG_LISTEN
  573. - @ref SOCKET_MSG_ACCEPT
  574. - @ref SOCKET_MSG_CONNECT
  575. - @ref SOCKET_MSG_RECV
  576. - @ref SOCKET_MSG_SEND
  577. - @ref SOCKET_MSG_SENDTO
  578. - @ref SOCKET_MSG_RECVFROM
  579. @param [in] pvMsg
  580. Pointer to message structure. Existing types are:
  581. - tstrSocketBindMsg
  582. - tstrSocketListenMsg
  583. - tstrSocketAcceptMsg
  584. - tstrSocketConnectMsg
  585. - tstrSocketRecvMsg
  586. @see
  587. tenuSocketCallbackMsgType
  588. tstrSocketRecvMsg
  589. tstrSocketConnectMsg
  590. tstrSocketAcceptMsg
  591. tstrSocketListenMsg
  592. tstrSocketBindMsg
  593. */
  594. typedef void (*tpfAppSocketCb) (SOCKET sock, uint8 u8Msg, void * pvMsg);
  595. /*!
  596. @typedef \
  597. tpfAppResolveCb
  598. @brief
  599. DNS resolution callback function.
  600. Applications requiring DNS resolution should register their callback through this function by calling @ref registerSocketCallback.
  601. The following callback is triggered in response to an asynchronous call to the @ref gethostbyname function (DNS Resolution callback).
  602. @param [in] pu8DomainName
  603. Domain name of the host.
  604. @param [in] u32ServerIP
  605. Server IPv4 address encoded in Network byte order format. If it is Zero, then the DNS resolution failed.
  606. */
  607. typedef void (*tpfAppResolveCb) (uint8* pu8DomainName, uint32 u32ServerIP);
  608. /*!
  609. @typedef \
  610. tpfPingCb
  611. @brief PING Callback
  612. The function delivers the ping statistics for the sent ping triggered by calling
  613. @ref m2m_ping_req.
  614. @param [in] u32IPAddr
  615. Destination IP.
  616. @param [in] u32RTT
  617. Round Trip Time.
  618. @param [in] u8ErrorCode
  619. Ping error code. It may be one of:
  620. - PING_ERR_SUCCESS
  621. - PING_ERR_DEST_UNREACH
  622. - PING_ERR_TIMEOUT
  623. */
  624. typedef void (*tpfPingCb)(uint32 u32IPAddr, uint32 u32RTT, uint8 u8ErrorCode);
  625. /**@}*/
  626. /*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
  627. FUNCTION PROTOTYPES
  628. *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
  629. /** \defgroup SocketAPI Functions
  630. * @ingroup SOCKETAPI
  631. */
  632. /**@{*/
  633. /*!
  634. @fn \
  635. NMI_API void socketInit(void);
  636. The function performs the necessary initialization for the socket library through the following steps:
  637. - A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once,
  638. in-order to prevent reseting the socket instances already created in the global socket array (gastrSockets).
  639. - Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets.
  640. - Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function.
  641. This facilitates handling all of the socket related functions received through interrupts from the firmware.
  642. @return void
  643. @remarks
  644. This initialization function must be invoked before any socket operation is performed.
  645. No error codes from this initialization function since the socket array is statically allocated based on the maximum number of
  646. sockets @ref MAX_SOCKET which is tuned to the systems capability.
  647. \section SocketExample1 Example
  648. This example demonstrates the use of the socketInit for socket initialization for an mqtt chat application.
  649. \code
  650. tstrWifiInitParam param;
  651. int8_t ret;
  652. char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1];
  653. //Initialize the board.
  654. system_init();
  655. //Initialize the UART console.
  656. configure_console();
  657. // Initialize the BSP.
  658. nm_bsp_init();
  659. ----------
  660. // Initialize socket interface.
  661. socketInit();
  662. registerSocketCallback(socket_event_handler, socket_resolve_handler);
  663. // Connect to router.
  664. m2m_wifi_connect((char *)DEFAULT_SSID, sizeof(DEFAULT_SSID),
  665. DEFAULT_AUTH, (char *)DEFAULT_KEY, M2M_WIFI_CH_ALL);
  666. \endcode
  667. */
  668. NMI_API void socketInit(void);
  669. /*!
  670. @fn \
  671. NMI_API void socketDeinit(void);
  672. @brief Socket Layer De-initialization
  673. The function performs the necessary cleanup for the socket library static data
  674. It must be invoked only after all desired socket operations have been performed on any active sockets.
  675. */
  676. NMI_API void socketDeinit(void);
  677. /*!
  678. @fn \
  679. NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb);
  680. Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function.
  681. The registered callback functions are used to retrieve information in response to the asynchronous socket functions called.
  682. @param [in] socket_cb
  683. Assignment of callback function to the global callback @ref tpfAppSocketCb gpfAppSocketCb. Delivers
  684. socket messages to the host application. In response to the asynchronous function calls, such as @ref bind
  685. @ref listen @ref accept @ref connect
  686. @param [in] resolve_cb
  687. Assignment of callback function to the global callback @ref tpfAppResolveCb gpfAppResolveCb.
  688. Used for DNS resolving functionality. The DNS resolving technique is determined by the application
  689. registering the callback.
  690. NULL is assigned when DNS resolution is not required.
  691. @return void
  692. @remarks
  693. If any of the socket functionality is not to be used, NULL is passed in as a parameter.
  694. It must be invoked after @ref socketInit and before other socket layer operations.
  695. \section SocketExample2 Example
  696. This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null
  697. for a simple UDP server example.
  698. \code
  699. tstrWifiInitParam param;
  700. int8_t ret;
  701. struct sockaddr_in addr;
  702. // Initialize the board
  703. system_init();
  704. //Initialize the UART console.
  705. configure_console();
  706. // Initialize the BSP.
  707. nm_bsp_init();
  708. // Initialize socket address structure.
  709. addr.sin_family = AF_INET;
  710. addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT);
  711. addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP);
  712. // Initialize Wi-Fi parameters structure.
  713. memset((uint8_t *)&param, 0, sizeof(tstrWifiInitParam));
  714. // Initialize Wi-Fi driver with data and status callbacks.
  715. param.pfAppWifiCb = wifi_cb;
  716. ret = m2m_wifi_init(&param);
  717. if (M2M_SUCCESS != ret) {
  718. printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
  719. while (1) {
  720. }
  721. }
  722. // Initialize socket module
  723. socketInit();
  724. registerSocketCallback(socket_cb, NULL);
  725. // Connect to router.
  726. m2m_wifi_connect((char *)DEFAULT_SSID, sizeof(DEFAULT_SSID), DEFAULT_AUTH, (char *)DEFAULT_KEY, M2M_WIFI_CH_ALL);
  727. \endcode
  728. */
  729. NMI_API void registerSocketCallback(tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb);
  730. /*!
  731. @fn \
  732. NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags);
  733. 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.
  734. 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.
  735. @param [in] u16Domain
  736. Socket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets.
  737. @param [in] u8Type
  738. Socket type. Allowed values are:
  739. - [SOCK_STREAM](@ref SOCK_STREAM)
  740. - [SOCK_DGRAM](@ref SOCK_DGRAM)
  741. @param [in] u8Flags
  742. Used to specify the socket creation flags. It shall be set to zero for normal TCP/UDP sockets,
  743. or [SOCKET_FLAGS_SSL](@ref SOCKET_FLAGS_SSL) if the socket is used for SSL session. The use of the flag
  744. [SOCKET_FLAGS_SSL](@ref SOCKET_FLAGS_SSL) has no meaning in case of UDP sockets.
  745. @pre
  746. The @ref socketInit function must be called once at the beginning of the application to initialize the socket handler.
  747. before any call to the socket function can be made.
  748. @see
  749. connect
  750. bind
  751. listen
  752. accept
  753. recv
  754. recvfrom
  755. send
  756. sendto
  757. close
  758. setsockopt
  759. getsockopt
  760. @return
  761. On successful socket creation, a non-blocking socket type is created and a socket ID is returned
  762. In case of failure the function returns a negative value, identifying one of the socket error codes defined.
  763. For example: @ref SOCK_ERR_INVALID for invalid argument or
  764. @ref SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets.
  765. @remarks
  766. The socket function must be called before any other related socket functions "e.g. send, recv, close ..etc"
  767. \section SocketExample3 Example
  768. This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other
  769. socket operations. Socket creation is dependent on the socket type.
  770. \subsection sub1 UDP example
  771. @code
  772. SOCKET UdpServerSocket = -1;
  773. UdpServerSocket = socket(AF_INET, SOCK_DGRAM, 0);
  774. @endcode
  775. \subsection sub2 TCP example
  776. @code
  777. static SOCKET tcp_client_socket = -1;
  778. tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0));
  779. @endcode
  780. */
  781. NMI_API SOCKET socket(uint16 u16Domain, uint8 u8Type, uint8 u8Flags);
  782. /*!
  783. \fn \
  784. NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen);
  785. Asynchronous bind function associates the provided address and local port to the socket.
  786. 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.
  787. Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback.
  788. @param [in] sock
  789. Socket ID, must hold a non negative value.
  790. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  791. @param [in] pstrAddr
  792. Pointer to socket address structure "sockaddr_in"
  793. [sockaddr_in](@ref sockaddr_in)
  794. @param [in] u8AddrLen
  795. Size of the given socket address structure in bytes.
  796. @pre
  797. The socket function must be called to allocate a socket before passing the socket ID to the bind function.
  798. @see socket
  799. @see connect
  800. @see listen
  801. @see accept
  802. @see recv
  803. @see recvfrom
  804. @see send
  805. @see sendto
  806. @return
  807. The function returns ZERO for successful operations and a negative value otherwise.
  808. The possible error values are:
  809. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  810. Indicating that the operation was successful.
  811. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  812. Indicating passing invalid arguments such as negative socket ID or NULL socket address structure.
  813. - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID)
  814. Indicate socket bind failure.
  815. \section SocketExample4 Example
  816. This example demonstrates the call of the bind socket operation after a successful socket operation.
  817. @code
  818. struct sockaddr_in addr;
  819. SOCKET udpServerSocket =-1;
  820. int ret = -1;
  821. if(udpServerSocket == -1)
  822. {
  823. udpServerSocket = socket(AF_INET,SOCK_DGRAM,0);
  824. if(udpServerSocket >= 0)
  825. {
  826. addr.sin_family = AF_INET;
  827. addr.sin_port = _htons(UDP_SERVER_PORT);
  828. addr.sin_addr.s_addr = 0;
  829. ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr));
  830. if(ret == 0)
  831. printf("Bind success!\n");
  832. else
  833. {
  834. printf("Bind Failed. Error code = %d\n",ret);
  835. close(udpServerSocket);
  836. }
  837. else
  838. {
  839. printf("UDP Server Socket Creation Failed\n");
  840. return;
  841. }
  842. }
  843. @endcode
  844. */
  845. NMI_API sint8 bind(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen);
  846. /*!
  847. @fn \
  848. NMI_API sint8 listen(SOCKET sock, uint8 backlog);
  849. After successfully binding a socket to an IP address and port on the system, start listening passively for incoming connections.
  850. The socket must be bound on a local port or the listen operation fails.
  851. Upon the call to the asynchronous listen function, response is received through the event @ref SOCKET_MSG_LISTEN
  852. in the socket callback.
  853. A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is
  854. notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function
  855. after calling @ref listen.
  856. 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 recieve notification of socket connection
  857. termination.
  858. @param [in] sock
  859. Socket ID, must hold a non negative value.
  860. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  861. @param [in] backlog
  862. Not used by the current implementation.
  863. @pre
  864. The bind function must be called to assign the port number and IP address to the socket before the listen operation.
  865. @see bind
  866. @see accept
  867. @see recv
  868. @see recvfrom
  869. @see send
  870. @see sendto
  871. @return
  872. The function returns ZERO for successful operations and a negative value otherwise.
  873. The possible error values are:
  874. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  875. Indicating that the operation was successful.
  876. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  877. Indicating invalid arguments were passed, such as negative socket ID.
  878. - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID)
  879. Indicate socket listen failure.
  880. \section SocketExample5 Example
  881. This example demonstrates the call of the listen socket operation after a successful socket operation.
  882. @code
  883. static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg)
  884. {
  885. int ret =-1;
  886. switch(u8Msg)
  887. {
  888. case SOCKET_MSG_BIND:
  889. {
  890. tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
  891. if(pstrBind != NULL)
  892. {
  893. if(pstrBind->status == 0)
  894. {
  895. ret = listen(sock, 0);
  896. if(ret <0)
  897. printf("Listen failure! Error = %d\n",ret);
  898. }
  899. else
  900. {
  901. M2M_ERR("bind Failure!\n");
  902. close(sock);
  903. }
  904. }
  905. }
  906. break;
  907. case SOCKET_MSG_LISTEN:
  908. {
  909. tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg;
  910. if(pstrListen != NULL)
  911. {
  912. if(pstrListen->status == 0)
  913. {
  914. ret = accept(sock,NULL,0);
  915. }
  916. else
  917. {
  918. M2M_ERR("listen Failure!\n");
  919. close(sock);
  920. }
  921. }
  922. }
  923. break;
  924. case SOCKET_MSG_ACCEPT:
  925. {
  926. tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg;
  927. if(pstrAccept->sock >= 0)
  928. {
  929. TcpNotificationSocket = pstrAccept->sock;
  930. recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
  931. }
  932. else
  933. {
  934. M2M_ERR("accept failure\n");
  935. }
  936. }
  937. break;
  938. default:
  939. break;
  940. }
  941. }
  942. @endcode
  943. */
  944. NMI_API sint8 listen(SOCKET sock, uint8 backlog);
  945. /*!
  946. @fn \
  947. NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen);
  948. The function has no current implementation. An empty deceleration is used to prevent errors when legacy application code is used.
  949. As it has no effect, it can be safely removed from any application using it.
  950. @param [in] sock
  951. Socket ID, must hold a non negative value.
  952. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  953. @param [in] addr
  954. Not used in the current implementation.
  955. @param [in] addrlen
  956. Not used in the current implementation.
  957. @return
  958. The function returns ZERO for successful operations and a negative value otherwise.
  959. The possible error values are:
  960. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  961. Indicating that the operation was successful.
  962. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  963. Indicating passing invalid arguments such as negative socket ID.
  964. */
  965. NMI_API sint8 accept(SOCKET sock, struct sockaddr *addr, uint8 *addrlen);
  966. /*!
  967. @fn \
  968. NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen);
  969. Establishes a TCP connection with a remote server.
  970. The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function.
  971. The application socket callback function is notified of the result of the connection attempt through the event @ref SOCKET_MSG_CONNECT,
  972. along with a structure @ref tstrSocketConnectMsg.
  973. If socket connection fails, the application should call @ref close().
  974. A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv function
  975. to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection
  976. termination.
  977. @param [in] sock
  978. Socket ID, must hold a non negative value.
  979. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  980. @param [in] pstrAddr
  981. Address of the remote server.
  982. @param [in] u8AddrLen
  983. Size of the given socket address structure in bytes.
  984. Not currently used, implemented for BSD compatibility only.
  985. @pre
  986. The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function.
  987. If the socket is not bound, you do NOT have to call bind before the "connect" function.
  988. @see
  989. socket
  990. recv
  991. send
  992. close
  993. @return
  994. The function returns ZERO for successful operations and a negative value otherwise.
  995. The possible error values are:
  996. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  997. Indicating that the operation was successful.
  998. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  999. Indicating passing invalid arguments such as negative socket ID or NULL socket address structure.
  1000. - [SOCK_ERR_INVALID](@ref SOCK_ERR_INVALID)
  1001. Indicate socket connect failure.
  1002. \section SocketExample6 Example
  1003. The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the
  1004. callback function handles the @ref SOCKET_MSG_CONNECT event.
  1005. \subsection sub3 Main Function
  1006. @code
  1007. struct sockaddr_in Serv_Addr;
  1008. SOCKET TcpClientSocket =-1;
  1009. int ret = -1
  1010. TcpClientSocket = socket(AF_INET,SOCK_STREAM,0);
  1011. Serv_Addr.sin_family = AF_INET;
  1012. Serv_Addr.sin_port = _htons(1234);
  1013. Serv_Addr.sin_addr.s_addr = inet_addr(SERVER);
  1014. printf("Connected to server via socket %u\n",TcpClientSocket);
  1015. do
  1016. {
  1017. ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr));
  1018. if(ret != 0)
  1019. {
  1020. printf("Connection Error\n");
  1021. }
  1022. else
  1023. {
  1024. printf("Connection successful.\n");
  1025. break;
  1026. }
  1027. }while(1)
  1028. @endcode
  1029. \subsection sub4 Socket Callback
  1030. @code
  1031. if(u8Msg == SOCKET_MSG_CONNECT)
  1032. {
  1033. tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
  1034. if(pstrConnect->s8Error == 0)
  1035. {
  1036. uint8 acBuffer[GROWL_MSG_SIZE];
  1037. uint16 u16MsgSize;
  1038. printf("Connect success!\n");
  1039. u16MsgSize = FormatMsg(u8ClientID, acBuffer);
  1040. send(sock, acBuffer, u16MsgSize, 0);
  1041. recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT);
  1042. u8Retry = GROWL_CONNECT_RETRY;
  1043. }
  1044. else
  1045. {
  1046. M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error");
  1047. close(pstrNotification->Socket);
  1048. }
  1049. }
  1050. @endcode
  1051. */
  1052. NMI_API sint8 connect(SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen);
  1053. /*!
  1054. @fn \
  1055. NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec);
  1056. An asynchrnonous receive function, used to retrieve data from a TCP stream.
  1057. Before calling the recv function, a successful socket connection status must have been received through any of the two socket events
  1058. [SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote
  1059. host.
  1060. The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the
  1061. socket callback.
  1062. Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following:
  1063. - @ref SOCK_ERR_NO_ERROR : Socket connection closed. The application should now call @ref close().
  1064. - @ref SOCK_ERR_CONN_ABORTED : Socket connection aborted. The application should now call @ref close().
  1065. - @ref SOCK_ERR_TIMEOUT : Socket receive timed out. The socket connection remains open.
  1066. @param [in] sock
  1067. Socket ID, must hold a non negative value.
  1068. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1069. @param [in] pvRecvBuf
  1070. Pointer to a buffer that will hold the received data. The buffer is used
  1071. in the recv callback to deliver the received data to the caller. The buffer must
  1072. be resident in memory (heap or global buffer).
  1073. @param [in] u16BufLen
  1074. The buffer size in bytes.
  1075. @param [in] u32Timeoutmsec
  1076. Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout
  1077. will be set to infinite (the recv function waits forever). If the timeout period is
  1078. elapsed with no data received, the socket will get a timeout error.
  1079. @pre
  1080. - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function.
  1081. - The socket in a connected state is expected to receive data through the socket interface.
  1082. @see socket
  1083. @see connect
  1084. @see bind
  1085. @see listen
  1086. @see recvfrom
  1087. @see close
  1088. @return
  1089. The function returns ZERO for successful operations and a negative value otherwise.
  1090. The possible error values are:
  1091. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1092. Indicating that the operation was successful.
  1093. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1094. Indicating passing invalid arguments such as negative socket ID or NULL Recieve buffer.
  1095. - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL)
  1096. Indicate socket recieve failure.
  1097. \section SocketExample7 Example
  1098. 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
  1099. received data when the SOCKET_MSG_RECV event is received.
  1100. @code
  1101. switch(u8Msg)
  1102. {
  1103. case SOCKET_MSG_ACCEPT:
  1104. {
  1105. tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg*)pvMsg;
  1106. if(pstrAccept->sock >= 0)
  1107. {
  1108. recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
  1109. }
  1110. else
  1111. {
  1112. M2M_ERR("accept\n");
  1113. }
  1114. }
  1115. break;
  1116. case SOCKET_MSG_RECV:
  1117. {
  1118. tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg;
  1119. if(pstrRx->s16BufferSize > 0)
  1120. {
  1121. recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
  1122. }
  1123. else
  1124. {
  1125. printf("Socet recv Error: %d\n",pstrRx->s16BufferSize);
  1126. close(sock);
  1127. }
  1128. }
  1129. break;
  1130. default:
  1131. break;
  1132. }
  1133. @endcode
  1134. */
  1135. NMI_API sint16 recv(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec);
  1136. /*!
  1137. @fn \
  1138. NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32TimeoutSeconds);
  1139. Receives data from a UDP Scoket.
  1140. The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to
  1141. a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received
  1142. with successful status in the socket callback).
  1143. Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification
  1144. in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event.
  1145. Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed.
  1146. Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @ref SOCK_ERR_TIMEOUT
  1147. The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by
  1148. using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example)
  1149. @param [in] sock
  1150. Socket ID, must hold a non negative value.
  1151. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1152. @param [in] pvRecvBuf
  1153. Pointer to a buffer that will hold the received data. The buffer shall be used
  1154. in the recv callback to deliver the received data to the caller. The buffer must
  1155. be resident in memory (heap or global buffer).
  1156. @param [in] u16BufLen
  1157. The buffer size in bytes.
  1158. @param [in] u32TimeoutSeconds
  1159. Timeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout
  1160. will be set to infinite (the recv function waits forever).
  1161. @pre
  1162. - The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function.
  1163. - The socket corresponding to the socket ID must be successfully bound to a local port through the call to a @ref bind function.
  1164. @see
  1165. socket
  1166. bind
  1167. close
  1168. @return
  1169. The function returns ZERO for successful operations and a negative value otherwise.
  1170. The possible error values are:
  1171. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1172. Indicating that the operation was successful.
  1173. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1174. Indicating passing invalid arguments such as negative socket ID or NULL Receive buffer.
  1175. - [SOCK_ERR_BUFFER_FULL](@ref SOCK_ERR_BUFFER_FULL)
  1176. Indicate socket receive failure.
  1177. \section SocketExample8 Example
  1178. 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
  1179. received data when the SOCKET_MSG_RECVFROM event is received.
  1180. @code
  1181. switch(u8Msg)
  1182. {
  1183. case SOCKET_MSG_BIND:
  1184. {
  1185. tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
  1186. if(pstrBind != NULL)
  1187. {
  1188. if(pstrBind->status == 0)
  1189. {
  1190. recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0);
  1191. }
  1192. else
  1193. {
  1194. M2M_ERR("bind\n");
  1195. }
  1196. }
  1197. }
  1198. break;
  1199. case SOCKET_MSG_RECVFROM:
  1200. {
  1201. tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg*)pvMsg;
  1202. if(pstrRx->s16BufferSize > 0)
  1203. {
  1204. //get the remote host address and port number
  1205. uint16 u16port = pstrRx->strRemoteAddr.sin_port;
  1206. uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr;
  1207. printf("Received frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port);
  1208. ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT);
  1209. }
  1210. else
  1211. {
  1212. printf("Socket recv Error: %d\n",pstrRx->s16BufferSize);
  1213. ret = close(sock);
  1214. }
  1215. }
  1216. break;
  1217. default:
  1218. break;
  1219. }
  1220. @endcode
  1221. */
  1222. NMI_API sint16 recvfrom(SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec);
  1223. /*!
  1224. @fn \
  1225. NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags);
  1226. Asynchronous sending function, used to send data on a TCP/UDP socket.
  1227. Called by the application code when there is outgoing data available required to be sent on a specific socket handler.
  1228. 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.
  1229. @ref send function is most commonly called for sockets in a connected state.
  1230. After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type
  1231. @ref SOCKET_MSG_SEND holding information containing the number of data bytes sent.
  1232. @param [in] sock
  1233. Socket ID, must hold a non negative value.
  1234. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1235. @param [in] pvSendBuffer
  1236. Pointer to a buffer holding data to be transmitted.
  1237. @param [in] u16SendLength
  1238. The buffer size in bytes.
  1239. @param [in] u16Flags
  1240. Not used in the current implementation.
  1241. @pre
  1242. Sockets must be initialized using socketInit. \n
  1243. For TCP Socket:\n
  1244. Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data).
  1245. Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the
  1246. the server case).\n
  1247. For UDP Socket:\n
  1248. UDP sockets most commonly use @ref sendto function, where the destination address is defined. However, in-order to send outgoing data
  1249. 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,
  1250. to ensure that the destination address is saved in the firmware.
  1251. @see
  1252. socketInit
  1253. recv
  1254. sendto
  1255. socket
  1256. connect
  1257. accept
  1258. sendto
  1259. @warning
  1260. u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n
  1261. Use a valid socket identifer through the aprior call to the @ref socket function.
  1262. Must use a valid buffer pointer.
  1263. Successful completion of a call to send() does not guarantee delivery of the message,
  1264. A negative return value indicates only locally-detected errors
  1265. @return
  1266. The function shall return @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.
  1267. */
  1268. NMI_API sint16 send(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags);
  1269. /*!
  1270. @fn \
  1271. NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen);
  1272. Asynchronous sending function, used to send data on a UDP socket.
  1273. Called by the application code when there is data required to be sent on a UDP socket.
  1274. The application code is expected to receive data from a successfully bound socket node.
  1275. The only difference between this function and the similar @ref send function, is the type of socket the data is received on. This function works
  1276. only with UDP sockets.
  1277. After the data is sent, the socket callback function registered using @ref registerSocketCallback(), is expected to receive an event of type
  1278. @ref SOCKET_MSG_SENDTO.
  1279. @param [in] sock
  1280. Socket ID, must hold a non negative value.
  1281. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1282. @param [in] pvSendBuffer
  1283. Pointer to a buffer holding data to be transmitted.
  1284. A NULL value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1285. @param [in] u16SendLength
  1286. The buffer size in bytes. It must not exceed @ref SOCKET_BUFFER_MAX_LENGTH.
  1287. @param [in] flags
  1288. Not used in the current implementation
  1289. @param [in] pstrDestAddr
  1290. The destination address.
  1291. @param [in] u8AddrLen
  1292. Destination address length in bytes.
  1293. Not used in the current implementation, only included for BSD compatibility.
  1294. @pre
  1295. Sockets must be initialized using socketInit.
  1296. @see
  1297. socketInit
  1298. recvfrom
  1299. sendto
  1300. socket
  1301. connect
  1302. accept
  1303. send
  1304. @warning
  1305. u16SendLength must not exceed @ref SOCKET_BUFFER_MAX_LENGTH. \n
  1306. Use a valid socket (returned from socket ).
  1307. A valid buffer pointer must be used (not NULL). \n
  1308. Successful completion of a call to sendto() does not guarantee delivery of the message,
  1309. A negative return value indicates only locally-detected errors
  1310. @return
  1311. The function returns @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.
  1312. */
  1313. NMI_API sint16 sendto(SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen);
  1314. /*!
  1315. @fn \
  1316. NMI_API sint8 close(SOCKET sock);
  1317. Synchronous close function, releases all the socket assigned resources.
  1318. @param [in] sock
  1319. Socket ID, must hold a non negative value.
  1320. A negative value will return a socket error @ref SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
  1321. @pre
  1322. Sockets must be initialized through the call of the socketInit function.
  1323. @ref close is called only for valid socket identifiers created through the @ref socket function.
  1324. @warning
  1325. If @ref close is called while there are still pending messages (sent or received ) they will be discarded.
  1326. @see
  1327. socketInit
  1328. socket
  1329. @return
  1330. The function returned @ref SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.
  1331. */
  1332. NMI_API sint8 close(SOCKET sock);
  1333. /*!
  1334. @fn \
  1335. NMI_API uint32 nmi_inet_addr(char *pcIpAddr);
  1336. Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address.
  1337. This IPv4 address in the input string parameter could either be specified as a hostname, or as a numeric string representation like n.n.n.n known as the IPv4 dotted-decimal format
  1338. (i.e. "192.168.10.1").
  1339. This function is used whenever an ip address needs to be set in the proper format
  1340. (i.e. for the @ref tstrM2MIPConfig structure).
  1341. @param [in] pcIpAddr
  1342. A null terminated string containing the IP address in IPv4 dotted-decimal address.
  1343. @return
  1344. Unsigned 32-bit integer representing the IP address in Network byte order
  1345. (eg. "192.168.10.1" will be expressed as 0x010AA8C0).
  1346. */
  1347. NMI_API uint32 nmi_inet_addr(char *pcIpAddr);
  1348. /*!
  1349. @fn \
  1350. NMI_API sint8 gethostbyname(uint8 * pcHostName);
  1351. Asynchronous DNS resolving function. This function uses DNS to resolve a domain name to the corresponding IP address.
  1352. A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback function registered using registerSocketCallback()
  1353. @param [in] pcHostName
  1354. NULL terminated string containing the domain name for the remote host.
  1355. Its size must not exceed [HOSTNAME_MAX_SIZE](@ref HOSTNAME_MAX_SIZE).
  1356. @see
  1357. registerSocketCallback
  1358. @warning
  1359. Successful completion of a call to gethostbyname() does not guarantee success of the DNS request,
  1360. a negative return value indicates only locally-detected errors
  1361. @return
  1362. - [SOCK_ERR_NO_ERROR](@ref SOCK_ERR_NO_ERROR)
  1363. - [SOCK_ERR_INVALID_ARG](@ref SOCK_ERR_INVALID_ARG)
  1364. */
  1365. NMI_API sint8 gethostbyname(uint8 * pcHostName);
  1366. /*!
  1367. @fn \
  1368. NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name,
  1369. const void *option_value, uint16 u16OptionLen);
  1370. The setsockopt() function shall set the option specified by the option_name
  1371. argument, at the protocol level specified by the level argument, to the value
  1372. pointed to by the option_value argument for the socke specified by the socket argument.
  1373. Possible Options:
  1374. SO_SET_UDP_SEND_CALLBACK:
  1375. Enable/Disable callback messages for sendto().Since UDP is unreliable by default the user maybe interested (or not)
  1376. in receiving a message of /ref SOCKET_MSG_SENDTO for each call of sendto().
  1377. Enabled if option_value equals /ref BTRUE Disabled otherwise.
  1378. IP_ADD_MEMBERSHIP:
  1379. valid for UDP sockets,this option is used to receive frames sent to a multicast group.
  1380. option_value shall be a pointer to Unsigned 32 bit integer containing the Multicast ipv4 address.
  1381. IP_DROP_MEMBERSHIP:
  1382. valid for UDP sockets,this option is used to Stop receiving frames sent to a multicast group.
  1383. option_value shall be a pointer to Unsigned 32 bit integer containing the Multicast ipv4 address.
  1384. Possible values for s32Level:
  1385. This argument is ignored.
  1386. @param [in] socket
  1387. Socket handler.
  1388. @param [in] u8Level
  1389. protocol level. always SOL_SOCKET for now.
  1390. @param [in] option_name
  1391. option to be set.
  1392. @param [in] option_value
  1393. pointer to user provided value.
  1394. @param [in] u16OptionLen
  1395. length of the option value.
  1396. @warning
  1397. -Note that sending IGMP packets to Join/Leave multicast groups is not currently implemented. \n
  1398. Calling this function will Pass/Filter packets sent to the Multicast address provided in the option_value
  1399. @return
  1400. The function shall return \ref SOCK_ERR_NO_ERROR for successful operation
  1401. and a negative value (indicating the error) otherwise.
  1402. */
  1403. NMI_API sint8 setsockopt(SOCKET socket, uint8 u8Level, uint8 option_name,
  1404. const void *option_value, uint16 u16OptionLen);
  1405. /*!
  1406. @fn \
  1407. sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 * pu8OptLen);
  1408. Get socket options retrieves
  1409. This Function isn't implemented yet but this is the form that will be released later.
  1410. @brief
  1411. @param [in] sock
  1412. Socket Identifie.
  1413. @param [in] u8Level
  1414. The protocol level of the option.
  1415. @param [in] u8OptName
  1416. The u8OptName argument specifies a single option to get.
  1417. @param [out] pvOptValue
  1418. The pvOptValue argument contains pointer to a buffer containing the option value.
  1419. @param [out] pu8OptLen
  1420. Option value buffer length.
  1421. @return
  1422. The function shall return ZERO for successful operation and a negative value otherwise.
  1423. */
  1424. NMI_API sint8 getsockopt(SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8* pu8OptLen);
  1425. /*!
  1426. * @fn NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb);
  1427. * The function request to send ping request to the given IP Address.
  1428. *
  1429. * @param [in] u32DstIP
  1430. * Target Destination IP Address for the ping request. It must be represented in Network
  1431. * byte order.
  1432. * The function nmi_inet_addr could be used to translate the dotted decimal notation IP
  1433. * to its Network bytes order integer represntative.
  1434. *
  1435. * @param [in] u8TTL
  1436. * IP TTL value for the ping request. If set to ZERO, the default value SHALL be used.
  1437. *
  1438. * @param [in] fpPingCb
  1439. * Callback will be called to deliver the ping statistics.
  1440. *
  1441. * @see nmi_inet_addr
  1442. * @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
  1443. */
  1444. NMI_API sint8 m2m_ping_req(uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb);
  1445. /**@}*/
  1446. #ifdef __cplusplus
  1447. }
  1448. #endif /* __cplusplus */
  1449. #endif /* __SOCKET_H__ */