net_sockets.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. /*
  2. * TCP/IP or UDP/IP networking functions
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /* Enable definition of getaddrinfo() even when compiling with -std=c99. Must
  20. * be set before config.h, which pulls in glibc's features.h indirectly.
  21. * Harmless on other platforms. */
  22. #ifndef _POSIX_C_SOURCE
  23. #define _POSIX_C_SOURCE 200112L
  24. #endif
  25. #ifndef _XOPEN_SOURCE
  26. #define _XOPEN_SOURCE 600 /* sockaddr_storage */
  27. #endif
  28. #include "common.h"
  29. #if defined(MBEDTLS_NET_C)
  30. #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
  31. !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \
  32. !defined(__HAIKU__) && !defined(__midipix__)
  33. #error "This module only works on Unix and Windows, see MBEDTLS_NET_C in config.h"
  34. #endif
  35. #if defined(MBEDTLS_PLATFORM_C)
  36. #include "mbedtls/platform.h"
  37. #else
  38. #include <stdlib.h>
  39. #endif
  40. #include "mbedtls/net_sockets.h"
  41. #include "mbedtls/error.h"
  42. #include "sys/_timeval.h"
  43. #include <string.h>
  44. #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
  45. !defined(EFI32)
  46. #define IS_EINTR( ret ) ( ( ret ) == WSAEINTR )
  47. #if !defined(_WIN32_WINNT)
  48. /* Enables getaddrinfo() & Co */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #include <ws2tcpip.h>
  52. #include <winsock2.h>
  53. #include <windows.h>
  54. #if (_WIN32_WINNT < 0x0501)
  55. #include <wspiapi.h>
  56. #endif
  57. #if defined(_MSC_VER)
  58. #if defined(_WIN32_WCE)
  59. #pragma comment( lib, "ws2.lib" )
  60. #else
  61. #pragma comment( lib, "ws2_32.lib" )
  62. #endif
  63. #endif /* _MSC_VER */
  64. #define read(fd,buf,len) recv( fd, (char*)( buf ), (int)( len ), 0 )
  65. #define write(fd,buf,len) send( fd, (char*)( buf ), (int)( len ), 0 )
  66. #define close(fd) closesocket(fd)
  67. static int wsa_init_done = 0;
  68. #else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  69. #include <sys/types.h>
  70. #if defined(CONFIG_QUEC_PROJECT_FEATURE_SSL)
  71. //#include <sys/socket.h>
  72. #endif
  73. #include <netinet/in.h>
  74. #include <arpa/inet.h>
  75. #if defined(CONFIG_QUEC_PROJECT_FEATURE_SSL)
  76. //#include <sys/time.h>
  77. #endif
  78. #include <unistd.h>
  79. #include <signal.h>
  80. #include <fcntl.h>
  81. #include <netdb.h>
  82. #include <errno.h>
  83. #define IS_EINTR( ret ) ( ( ret ) == EINTR )
  84. #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  85. /* Some MS functions want int and MSVC warns if we pass size_t,
  86. * but the standard functions use socklen_t, so cast only for MSVC */
  87. #if defined(_MSC_VER)
  88. #define MSVC_INT_CAST (int)
  89. #else
  90. #define MSVC_INT_CAST
  91. #endif
  92. #include <stdio.h>
  93. #include <time.h>
  94. #include <stdint.h>
  95. #ifdef CONFIG_QUEC_PROJECT_FEATURE_SSL
  96. #include "ql_log.h"
  97. #include "ql_api_datacall.h"
  98. #define HTONS(x) ((((x)&0x00ffUL) << 8) | (((x)&0xff00UL) >> 8))
  99. #define Log_d(msg, ...) QL_LOG(QL_LOG_LEVEL_INFO, "net_socket ", msg, ##__VA_ARGS__)
  100. #define Log_i(msg, ...) QL_LOG(QL_LOG_LEVEL_INFO, "net_socket ", msg, ##__VA_ARGS__)
  101. #define Log_w(msg, ...) QL_LOG(QL_LOG_LEVEL_WARN, "net_socket ", msg, ##__VA_ARGS__)
  102. #define Log_e(msg, ...) QL_LOG(QL_LOG_LEVEL_ERROR, "net_socket ", msg, ##__VA_ARGS__)
  103. //如果是小端则返回1,如果是大端则返回0
  104. int JudgeSystem(void)
  105. {
  106. int a = 1;
  107. char *p = (char *)&a;
  108. return *p;
  109. }
  110. #endif
  111. /*
  112. * Prepare for using the sockets interface
  113. */
  114. static int net_prepare( void )
  115. {
  116. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  117. !defined(EFI32)
  118. WSADATA wsaData;
  119. if( wsa_init_done == 0 )
  120. {
  121. if( WSAStartup( MAKEWORD(2,0), &wsaData ) != 0 )
  122. return( MBEDTLS_ERR_NET_SOCKET_FAILED );
  123. wsa_init_done = 1;
  124. }
  125. #else
  126. #if !defined(EFIX64) && !defined(EFI32)
  127. signal( SIGPIPE, SIG_IGN );
  128. #endif
  129. #endif
  130. return( 0 );
  131. }
  132. /*
  133. * Return 0 if the file descriptor is valid, an error otherwise.
  134. * If for_select != 0, check whether the file descriptor is within the range
  135. * allowed for fd_set used for the FD_xxx macros and the select() function.
  136. */
  137. static int check_fd( int fd, int for_select )
  138. {
  139. if( fd < 0 )
  140. return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
  141. #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
  142. !defined(EFI32)
  143. (void) for_select;
  144. #else
  145. /* A limitation of select() is that it only works with file descriptors
  146. * that are strictly less than FD_SETSIZE. This is a limitation of the
  147. * fd_set type. Error out early, because attempting to call FD_SET on a
  148. * large file descriptor is a buffer overflow on typical platforms. */
  149. if( for_select && fd >= FD_SETSIZE )
  150. return( MBEDTLS_ERR_NET_POLL_FAILED );
  151. #endif
  152. return( 0 );
  153. }
  154. /*
  155. * Initialize a context
  156. */
  157. void mbedtls_net_init( mbedtls_net_context *ctx )
  158. {
  159. ctx->fd = -1;
  160. }
  161. /*
  162. * Initiate a TCP connection with host:port and the given protocol
  163. */
  164. #ifdef QUEC_MBEDTLS_NET_CONNECT
  165. int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host, const char *port, int proto, ...)
  166. {
  167. int ret;
  168. uint8_t nSim = 0;
  169. int profile_idx = 0;
  170. ql_data_call_info_s info;
  171. char ip6_addr_str[64] = {0};
  172. char ip4_addr_str[16] = {0};
  173. struct sockaddr_in local4, server_ipv4;
  174. struct sockaddr_in6 local6, server_ipv6;
  175. struct addrinfo hints, *addr_list, *cur;
  176. if ((ret = net_prepare()) != 0)
  177. {
  178. return (ret);
  179. }
  180. //get profile_idx
  181. va_list vp;
  182. va_start(vp, proto);
  183. profile_idx = va_arg(vp, int);
  184. va_end(vp);
  185. Log_d("profile_idx: %d", profile_idx);
  186. memset(&hints, 0, sizeof(hints));
  187. hints.ai_family = AF_UNSPEC;
  188. hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
  189. hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
  190. //get pdp result
  191. memset(&info, 0x00, sizeof(ql_data_call_info_s));
  192. ret = ql_get_data_call_info(nSim, profile_idx, &info);
  193. if (ret != 0)
  194. {
  195. Log_d("ql_get_data_call_info ret: %d", ret);
  196. ql_stop_data_call(nSim, profile_idx);
  197. return MBEDTLS_ERR_NET_UNKNOWN_HOST;
  198. }
  199. //get server ip by dns
  200. #ifdef CONFIG_QUEC_PROJECT_FEATURE_DNS
  201. if (getaddrinfo_with_pcid(host, NULL, &hints, &addr_list, (uint32)profile_idx) != 0)
  202. #else
  203. if (getaddrinfo(host, port, &hints, &addr_list) != 0)
  204. #endif
  205. {
  206. Log_d("getaddrinfo_with_pcid error");
  207. return MBEDTLS_ERR_NET_UNKNOWN_HOST;
  208. }
  209. /* Try the sockaddrs until a connection succeeds */
  210. ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
  211. for (cur = addr_list; cur != NULL; cur = cur->ai_next)
  212. {
  213. //socket
  214. ctx->fd = (int)socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
  215. if (ctx->fd < 0)
  216. {
  217. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  218. continue;
  219. }
  220. if (AF_INET == cur->ai_family || AF_UNSPEC == cur->ai_family)
  221. {
  222. //printf
  223. Log_d("info->v4.state: %d", info.v4.state);
  224. Log_d("info->profile_idx: %d", info.profile_idx);
  225. Log_d("info->ip_version: %d", info.ip_version);
  226. inet_ntop(AF_INET, &info.v4.addr.ip, ip4_addr_str, sizeof(ip4_addr_str));
  227. Log_d("info.v4.addr.ip: %s\r\n", ip4_addr_str);
  228. inet_ntop(AF_INET, &info.v4.addr.pri_dns, ip4_addr_str, sizeof(ip4_addr_str));
  229. Log_d("info.v4.addr.pri_dns: %s\r\n", ip4_addr_str);
  230. inet_ntop(AF_INET, &info.v4.addr.sec_dns, ip4_addr_str, sizeof(ip4_addr_str));
  231. Log_d("info.v4.addr.sec_dns: %s\r\n", ip4_addr_str);
  232. //bind
  233. memset(&local4, 0x00, sizeof(struct sockaddr_in));
  234. local4.sin_family = AF_INET;
  235. local4.sin_port = 0;
  236. inet_aton(ip4addr_ntoa(&info.v4.addr.ip), &local4.sin_addr);
  237. Log_d("local4.sin_por=%d port=%s", local4.sin_port, port);
  238. ret = bind(ctx->fd, (struct sockaddr *)&local4, sizeof(struct sockaddr));
  239. if (ret < 0)
  240. {
  241. close(ctx->fd);
  242. ctx->fd = -1;
  243. ret = MBEDTLS_ERR_NET_BIND_FAILED;
  244. continue;
  245. }
  246. //connect
  247. struct sockaddr_in *sin_res = (struct sockaddr_in *)cur->ai_addr;
  248. memset(&server_ipv4, 0x00, sizeof(struct sockaddr_in));
  249. server_ipv4.sin_family = cur->ai_family;
  250. server_ipv4.sin_addr = sin_res->sin_addr;
  251. if (JudgeSystem())
  252. {
  253. server_ipv4.sin_port = HTONS(atoi(port));
  254. }
  255. else
  256. {
  257. server_ipv4.sin_port = atoi(port);
  258. }
  259. Log_d("server_ipv4.sin_port=%hu ctx->fd=%d", server_ipv4.sin_port, ctx->fd);
  260. ret = connect(ctx->fd, (struct sockaddr *)&server_ipv4, sizeof(server_ipv4));
  261. if (ret == 0)
  262. {
  263. ret = 0;
  264. break;
  265. }
  266. }
  267. else //ipv6
  268. {
  269. //bind
  270. local6.sin6_family = AF_INET6;
  271. local6.sin6_port = 0;
  272. local6.sin6_len = sizeof(struct sockaddr_in6);
  273. inet6_aton(ip6addr_ntoa(&info.v6.addr.ip), &local6.sin6_addr);
  274. ret = bind(ctx->fd, (struct sockaddr *)&local6, sizeof(struct sockaddr));
  275. if (ret != 0)
  276. {
  277. close(ctx->fd);
  278. ctx->fd = -1;
  279. ret = MBEDTLS_ERR_NET_BIND_FAILED;
  280. continue;
  281. }
  282. //connect
  283. memcpy(&server_ipv6, (struct sockaddr_in6 *)cur->ai_addr, sizeof(struct sockaddr_in6));
  284. server_ipv6.sin6_family = AF_INET6;
  285. if (JudgeSystem())
  286. {
  287. server_ipv6.sin6_port = HTONS(atoi(port));
  288. }
  289. else
  290. {
  291. server_ipv6.sin6_port = atoi(port);
  292. }
  293. inet_ntop(AF_INET6, &server_ipv6.sin6_addr, ip6_addr_str, sizeof(ip6_addr_str));
  294. ret = connect(ctx->fd, (struct sockaddr *)&server_ipv6, sizeof(server_ipv6));
  295. if (ret == 0)
  296. {
  297. ret = 0;
  298. break;
  299. }
  300. }
  301. close(ctx->fd);
  302. ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
  303. }
  304. freeaddrinfo(addr_list);
  305. return (ret);
  306. }
  307. #else
  308. int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host,
  309. const char *port, int proto )
  310. {
  311. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  312. struct addrinfo hints, *addr_list, *cur;
  313. if( ( ret = net_prepare() ) != 0 )
  314. return( ret );
  315. /* Do name resolution with both IPv6 and IPv4 */
  316. memset( &hints, 0, sizeof( hints ) );
  317. hints.ai_family = AF_UNSPEC;
  318. hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
  319. hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
  320. if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )
  321. return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
  322. /* Try the sockaddrs until a connection succeeds */
  323. ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
  324. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  325. {
  326. ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
  327. cur->ai_protocol );
  328. if( ctx->fd < 0 )
  329. {
  330. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  331. continue;
  332. }
  333. if( connect( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) == 0 )
  334. {
  335. ret = 0;
  336. break;
  337. }
  338. close( ctx->fd );
  339. ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
  340. }
  341. freeaddrinfo( addr_list );
  342. return( ret );
  343. }
  344. #endif /*QUEC_MBEDTLS_NET_CONNECT*/
  345. /*
  346. * Create a listening socket on bind_ip:port
  347. */
  348. int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )
  349. {
  350. int n, ret;
  351. struct addrinfo hints, *addr_list, *cur;
  352. if( ( ret = net_prepare() ) != 0 )
  353. return( ret );
  354. /* Bind to IPv6 and/or IPv4, but only in the desired protocol */
  355. memset( &hints, 0, sizeof( hints ) );
  356. hints.ai_family = AF_UNSPEC;
  357. hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
  358. hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
  359. if( bind_ip == NULL )
  360. hints.ai_flags = AI_PASSIVE;
  361. if( getaddrinfo( bind_ip, port, &hints, &addr_list ) != 0 )
  362. return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
  363. /* Try the sockaddrs until a binding succeeds */
  364. ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
  365. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  366. {
  367. ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
  368. cur->ai_protocol );
  369. if( ctx->fd < 0 )
  370. {
  371. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  372. continue;
  373. }
  374. n = 1;
  375. if( setsockopt( ctx->fd, SOL_SOCKET, SO_REUSEADDR,
  376. (const char *) &n, sizeof( n ) ) != 0 )
  377. {
  378. close( ctx->fd );
  379. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  380. continue;
  381. }
  382. if( bind( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) != 0 )
  383. {
  384. close( ctx->fd );
  385. ret = MBEDTLS_ERR_NET_BIND_FAILED;
  386. continue;
  387. }
  388. /* Listen only makes sense for TCP */
  389. if( proto == MBEDTLS_NET_PROTO_TCP )
  390. {
  391. if( listen( ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG ) != 0 )
  392. {
  393. close( ctx->fd );
  394. ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
  395. continue;
  396. }
  397. }
  398. /* Bind was successful */
  399. ret = 0;
  400. break;
  401. }
  402. freeaddrinfo( addr_list );
  403. return( ret );
  404. }
  405. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  406. !defined(EFI32)
  407. /*
  408. * Check if the requested operation would be blocking on a non-blocking socket
  409. * and thus 'failed' with a negative return value.
  410. */
  411. static int net_would_block( const mbedtls_net_context *ctx )
  412. {
  413. ((void) ctx);
  414. return( WSAGetLastError() == WSAEWOULDBLOCK );
  415. }
  416. #else
  417. /*
  418. * Check if the requested operation would be blocking on a non-blocking socket
  419. * and thus 'failed' with a negative return value.
  420. *
  421. * Note: on a blocking socket this function always returns 0!
  422. */
  423. static int net_would_block( const mbedtls_net_context *ctx )
  424. {
  425. int err = errno;
  426. /*
  427. * Never return 'WOULD BLOCK' on a blocking socket
  428. */
  429. #ifdef CONFIG_QUEC_PROJECT_FEATURE_SSL
  430. if ((fcntl(ctx->fd, F_GETFL, 0) & O_NONBLOCK) != O_NONBLOCK)
  431. #else
  432. if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
  433. #endif
  434. {
  435. errno = err;
  436. return( 0 );
  437. }
  438. switch( errno = err )
  439. {
  440. #if defined EAGAIN
  441. case EAGAIN:
  442. #endif
  443. #if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
  444. case EWOULDBLOCK:
  445. #endif
  446. return( 1 );
  447. }
  448. return( 0 );
  449. }
  450. #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  451. /*
  452. * Accept a connection from a remote client
  453. */
  454. int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
  455. mbedtls_net_context *client_ctx,
  456. void *client_ip, size_t buf_size, size_t *ip_len )
  457. {
  458. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  459. int type;
  460. struct sockaddr_storage client_addr;
  461. #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \
  462. defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t) || \
  463. defined(socklen_t) || (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L)
  464. socklen_t n = (socklen_t) sizeof( client_addr );
  465. socklen_t type_len = (socklen_t) sizeof( type );
  466. #else
  467. int n = (int) sizeof( client_addr );
  468. int type_len = (int) sizeof( type );
  469. #endif
  470. /* Is this a TCP or UDP socket? */
  471. if( getsockopt( bind_ctx->fd, SOL_SOCKET, SO_TYPE,
  472. (void *) &type, &type_len ) != 0 ||
  473. ( type != SOCK_STREAM && type != SOCK_DGRAM ) )
  474. {
  475. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  476. }
  477. if( type == SOCK_STREAM )
  478. {
  479. /* TCP: actual accept() */
  480. ret = client_ctx->fd = (int) accept( bind_ctx->fd,
  481. (struct sockaddr *) &client_addr, &n );
  482. }
  483. else
  484. {
  485. /* UDP: wait for a message, but keep it in the queue */
  486. char buf[1] = { 0 };
  487. ret = (int) recvfrom( bind_ctx->fd, buf, sizeof( buf ), MSG_PEEK,
  488. (struct sockaddr *) &client_addr, &n );
  489. #if defined(_WIN32)
  490. if( ret == SOCKET_ERROR &&
  491. WSAGetLastError() == WSAEMSGSIZE )
  492. {
  493. /* We know buf is too small, thanks, just peeking here */
  494. ret = 0;
  495. }
  496. #endif
  497. }
  498. if( ret < 0 )
  499. {
  500. if( net_would_block( bind_ctx ) != 0 )
  501. return( MBEDTLS_ERR_SSL_WANT_READ );
  502. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  503. }
  504. /* UDP: hijack the listening socket to communicate with the client,
  505. * then bind a new socket to accept new connections */
  506. if( type != SOCK_STREAM )
  507. {
  508. struct sockaddr_storage local_addr;
  509. int one = 1;
  510. if( connect( bind_ctx->fd, (struct sockaddr *) &client_addr, n ) != 0 )
  511. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  512. client_ctx->fd = bind_ctx->fd;
  513. bind_ctx->fd = -1; /* In case we exit early */
  514. n = sizeof( struct sockaddr_storage );
  515. if( getsockname( client_ctx->fd,
  516. (struct sockaddr *) &local_addr, &n ) != 0 ||
  517. ( bind_ctx->fd = (int) socket( local_addr.ss_family,
  518. SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ||
  519. setsockopt( bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR,
  520. (const char *) &one, sizeof( one ) ) != 0 )
  521. {
  522. return( MBEDTLS_ERR_NET_SOCKET_FAILED );
  523. }
  524. if( bind( bind_ctx->fd, (struct sockaddr *) &local_addr, n ) != 0 )
  525. {
  526. return( MBEDTLS_ERR_NET_BIND_FAILED );
  527. }
  528. }
  529. if( client_ip != NULL )
  530. {
  531. if( client_addr.ss_family == AF_INET )
  532. {
  533. struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr;
  534. *ip_len = sizeof( addr4->sin_addr.s_addr );
  535. if( buf_size < *ip_len )
  536. return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
  537. memcpy( client_ip, &addr4->sin_addr.s_addr, *ip_len );
  538. }
  539. else
  540. {
  541. #ifdef CONFIG_QUEC_PROJECT_FEATURE_SSL
  542. #if LWIP_IPV6
  543. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr;
  544. *ip_len = sizeof( addr6->sin6_addr.s6_addr );
  545. if( buf_size < *ip_len )
  546. return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
  547. memcpy( client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
  548. #endif
  549. #endif/*CONFIG_QUEC_PROJECT_FEATURE_SSL*/
  550. }
  551. }
  552. return( 0 );
  553. }
  554. /*
  555. * Set the socket blocking or non-blocking
  556. */
  557. int mbedtls_net_set_block( mbedtls_net_context *ctx )
  558. {
  559. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  560. !defined(EFI32)
  561. u_long n = 0;
  562. return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
  563. #else
  564. #ifdef CONFIG_QUEC_PROJECT_FEATURE_SSL
  565. return (fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL, 0) & ~O_NONBLOCK));
  566. #else
  567. return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) & ~O_NONBLOCK ) );
  568. #endif /*CONFIG_QUEC_PROJECT_FEATURE_SSL*/
  569. #endif
  570. }
  571. int mbedtls_net_set_nonblock( mbedtls_net_context *ctx )
  572. {
  573. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  574. !defined(EFI32)
  575. u_long n = 1;
  576. return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
  577. #else
  578. #ifdef CONFIG_QUEC_PROJECT_FEATURE_SSL
  579. return (fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL, 0) | O_NONBLOCK));
  580. #else
  581. return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ) );
  582. #endif /*CONFIG_QUEC_PROJECT_FEATURE_SSL*/
  583. #endif
  584. }
  585. /*
  586. * Check if data is available on the socket
  587. */
  588. int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout )
  589. {
  590. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  591. struct timeval tv;
  592. fd_set read_fds;
  593. fd_set write_fds;
  594. int fd = ctx->fd;
  595. ret = check_fd( fd, 1 );
  596. if( ret != 0 )
  597. return( ret );
  598. #if defined(__has_feature)
  599. #if __has_feature(memory_sanitizer)
  600. /* Ensure that memory sanitizers consider read_fds and write_fds as
  601. * initialized even on platforms such as Glibc/x86_64 where FD_ZERO
  602. * is implemented in assembly. */
  603. memset( &read_fds, 0, sizeof( read_fds ) );
  604. memset( &write_fds, 0, sizeof( write_fds ) );
  605. #endif
  606. #endif
  607. FD_ZERO( &read_fds );
  608. if( rw & MBEDTLS_NET_POLL_READ )
  609. {
  610. rw &= ~MBEDTLS_NET_POLL_READ;
  611. FD_SET( fd, &read_fds );
  612. }
  613. FD_ZERO( &write_fds );
  614. if( rw & MBEDTLS_NET_POLL_WRITE )
  615. {
  616. rw &= ~MBEDTLS_NET_POLL_WRITE;
  617. FD_SET( fd, &write_fds );
  618. }
  619. if( rw != 0 )
  620. return( MBEDTLS_ERR_NET_BAD_INPUT_DATA );
  621. tv.tv_sec = timeout / 1000;
  622. tv.tv_usec = ( timeout % 1000 ) * 1000;
  623. do
  624. {
  625. ret = select( fd + 1, &read_fds, &write_fds, NULL,
  626. timeout == (uint32_t) -1 ? NULL : &tv );
  627. }
  628. while( IS_EINTR( ret ) );
  629. if( ret < 0 )
  630. return( MBEDTLS_ERR_NET_POLL_FAILED );
  631. ret = 0;
  632. if( FD_ISSET( fd, &read_fds ) )
  633. ret |= MBEDTLS_NET_POLL_READ;
  634. if( FD_ISSET( fd, &write_fds ) )
  635. ret |= MBEDTLS_NET_POLL_WRITE;
  636. return( ret );
  637. }
  638. /*
  639. * Portable usleep helper
  640. */
  641. void mbedtls_net_usleep( unsigned long usec )
  642. {
  643. #if defined(_WIN32)
  644. Sleep( ( usec + 999 ) / 1000 );
  645. #else
  646. struct timeval tv;
  647. tv.tv_sec = usec / 1000000;
  648. #if defined(__unix__) || defined(__unix) || \
  649. ( defined(__APPLE__) && defined(__MACH__) )
  650. tv.tv_usec = (suseconds_t) usec % 1000000;
  651. #else
  652. tv.tv_usec = usec % 1000000;
  653. #endif
  654. select( 0, NULL, NULL, NULL, &tv );
  655. #endif
  656. }
  657. /*
  658. * Read at most 'len' characters
  659. */
  660. int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )
  661. {
  662. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  663. int fd = ((mbedtls_net_context *) ctx)->fd;
  664. ret = check_fd( fd, 0 );
  665. if( ret != 0 )
  666. return( ret );
  667. ret = (int) read( fd, buf, len );
  668. if( ret < 0 )
  669. {
  670. if( net_would_block( ctx ) != 0 )
  671. return( MBEDTLS_ERR_SSL_WANT_READ );
  672. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  673. !defined(EFI32)
  674. if( WSAGetLastError() == WSAECONNRESET )
  675. return( MBEDTLS_ERR_NET_CONN_RESET );
  676. #else
  677. if( errno == EPIPE || errno == ECONNRESET )
  678. return( MBEDTLS_ERR_NET_CONN_RESET );
  679. if( errno == EINTR )
  680. return( MBEDTLS_ERR_SSL_WANT_READ );
  681. #endif
  682. return( MBEDTLS_ERR_NET_RECV_FAILED );
  683. }
  684. return( ret );
  685. }
  686. /*
  687. * Read at most 'len' characters, blocking for at most 'timeout' ms
  688. */
  689. int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf,
  690. size_t len, uint32_t timeout )
  691. {
  692. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  693. struct timeval tv;
  694. fd_set read_fds;
  695. int fd = ((mbedtls_net_context *) ctx)->fd;
  696. ret = check_fd( fd, 1 );
  697. if( ret != 0 )
  698. return( ret );
  699. FD_ZERO( &read_fds );
  700. FD_SET( fd, &read_fds );
  701. tv.tv_sec = timeout / 1000;
  702. tv.tv_usec = ( timeout % 1000 ) * 1000;
  703. ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );
  704. /* Zero fds ready means we timed out */
  705. if( ret == 0 )
  706. return( MBEDTLS_ERR_SSL_TIMEOUT );
  707. if( ret < 0 )
  708. {
  709. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  710. !defined(EFI32)
  711. if( WSAGetLastError() == WSAEINTR )
  712. return( MBEDTLS_ERR_SSL_WANT_READ );
  713. #else
  714. if( errno == EINTR )
  715. return( MBEDTLS_ERR_SSL_WANT_READ );
  716. #endif
  717. return( MBEDTLS_ERR_NET_RECV_FAILED );
  718. }
  719. /* This call will not block */
  720. return( mbedtls_net_recv( ctx, buf, len ) );
  721. }
  722. /*
  723. * Write at most 'len' characters
  724. */
  725. int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )
  726. {
  727. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  728. int fd = ((mbedtls_net_context *) ctx)->fd;
  729. ret = check_fd( fd, 0 );
  730. if( ret != 0 )
  731. return( ret );
  732. ret = (int) write( fd, buf, len );
  733. if( ret < 0 )
  734. {
  735. if( net_would_block( ctx ) != 0 )
  736. return( MBEDTLS_ERR_SSL_WANT_WRITE );
  737. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  738. !defined(EFI32)
  739. if( WSAGetLastError() == WSAECONNRESET )
  740. return( MBEDTLS_ERR_NET_CONN_RESET );
  741. #else
  742. if( errno == EPIPE || errno == ECONNRESET )
  743. return( MBEDTLS_ERR_NET_CONN_RESET );
  744. if( errno == EINTR )
  745. return( MBEDTLS_ERR_SSL_WANT_WRITE );
  746. #endif
  747. return( MBEDTLS_ERR_NET_SEND_FAILED );
  748. }
  749. return( ret );
  750. }
  751. /*
  752. * Close the connection
  753. */
  754. void mbedtls_net_close( mbedtls_net_context *ctx )
  755. {
  756. if( ctx->fd == -1 )
  757. return;
  758. close( ctx->fd );
  759. ctx->fd = -1;
  760. }
  761. /*
  762. * Gracefully close the connection
  763. */
  764. void mbedtls_net_free( mbedtls_net_context *ctx )
  765. {
  766. if( ctx->fd == -1 )
  767. return;
  768. shutdown( ctx->fd, 2 );
  769. close( ctx->fd );
  770. ctx->fd = -1;
  771. }
  772. #endif /* MBEDTLS_NET_C */