net_sockets.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. * TCP/IP or UDP/IP networking functions
  3. *
  4. * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  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. * This file is part of mbed TLS (https://tls.mbed.org)
  20. */
  21. #if !defined(MBEDTLS_CONFIG_FILE)
  22. #include "mbedtls/config.h"
  23. #else
  24. #include MBEDTLS_CONFIG_FILE
  25. #endif
  26. #if defined(MBEDTLS_NET_C)
  27. #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
  28. !defined(__APPLE__) && !defined(_WIN32)
  29. #error "This module only works on Unix and Windows, see MBEDTLS_NET_C in config.h"
  30. #endif
  31. #if defined(MBEDTLS_PLATFORM_C)
  32. #include "mbedtls/platform.h"
  33. #else
  34. #include <stdlib.h>
  35. #endif
  36. #include "mbedtls/net_sockets.h"
  37. #include <string.h>
  38. #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
  39. !defined(EFI32)
  40. #ifdef _WIN32_WINNT
  41. #undef _WIN32_WINNT
  42. #endif
  43. /* Enables getaddrinfo() & Co */
  44. #define _WIN32_WINNT 0x0501
  45. #include <ws2tcpip.h>
  46. #include <winsock2.h>
  47. #include <windows.h>
  48. #if defined(_MSC_VER)
  49. #if defined(_WIN32_WCE)
  50. #pragma comment( lib, "ws2.lib" )
  51. #else
  52. #pragma comment( lib, "ws2_32.lib" )
  53. #endif
  54. #endif /* _MSC_VER */
  55. #define read(fd,buf,len) recv(fd,(char*)buf,(int) len,0)
  56. #define write(fd,buf,len) send(fd,(char*)buf,(int) len,0)
  57. #define close(fd) closesocket(fd)
  58. static int wsa_init_done = 0;
  59. #else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  60. #include <sys/types.h>
  61. #include <sys/socket.h>
  62. #include <netinet/in.h>
  63. #include <arpa/inet.h>
  64. #include <sys/time.h>
  65. #include <unistd.h>
  66. #include <signal.h>
  67. #include <fcntl.h>
  68. #include <netdb.h>
  69. #include <errno.h>
  70. #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  71. /* Some MS functions want int and MSVC warns if we pass size_t,
  72. * but the standard fucntions use socklen_t, so cast only for MSVC */
  73. #if defined(_MSC_VER)
  74. #define MSVC_INT_CAST (int)
  75. #else
  76. #define MSVC_INT_CAST
  77. #endif
  78. #include <stdio.h>
  79. #include <time.h>
  80. #include <stdint.h>
  81. /*
  82. * Prepare for using the sockets interface
  83. */
  84. static int net_prepare( void )
  85. {
  86. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  87. !defined(EFI32)
  88. WSADATA wsaData;
  89. if( wsa_init_done == 0 )
  90. {
  91. if( WSAStartup( MAKEWORD(2,0), &wsaData ) != 0 )
  92. return( MBEDTLS_ERR_NET_SOCKET_FAILED );
  93. wsa_init_done = 1;
  94. }
  95. #else
  96. #if !defined(EFIX64) && !defined(EFI32)
  97. signal( SIGPIPE, SIG_IGN );
  98. #endif
  99. #endif
  100. return( 0 );
  101. }
  102. /*
  103. * Initialize a context
  104. */
  105. void mbedtls_net_init( mbedtls_net_context *ctx )
  106. {
  107. ctx->fd = -1;
  108. }
  109. /*
  110. * Initiate a TCP connection with host:port and the given protocol
  111. */
  112. int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host,
  113. const char *port, int proto )
  114. {
  115. int ret;
  116. struct addrinfo hints, *addr_list, *cur;
  117. if( ( ret = net_prepare() ) != 0 )
  118. return( ret );
  119. /* Do name resolution with both IPv6 and IPv4 */
  120. memset( &hints, 0, sizeof( hints ) );
  121. hints.ai_family = AF_UNSPEC;
  122. hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
  123. hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
  124. if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )
  125. return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
  126. /* Try the sockaddrs until a connection succeeds */
  127. ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
  128. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  129. {
  130. ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
  131. cur->ai_protocol );
  132. if( ctx->fd < 0 )
  133. {
  134. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  135. continue;
  136. }
  137. if( connect( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) == 0 )
  138. {
  139. ret = 0;
  140. break;
  141. }
  142. close( ctx->fd );
  143. ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
  144. }
  145. freeaddrinfo( addr_list );
  146. return( ret );
  147. }
  148. /*
  149. * Create a listening socket on bind_ip:port
  150. */
  151. int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )
  152. {
  153. int n, ret;
  154. struct addrinfo hints, *addr_list, *cur;
  155. if( ( ret = net_prepare() ) != 0 )
  156. return( ret );
  157. /* Bind to IPv6 and/or IPv4, but only in the desired protocol */
  158. memset( &hints, 0, sizeof( hints ) );
  159. hints.ai_family = AF_UNSPEC;
  160. hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
  161. hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
  162. if( bind_ip == NULL )
  163. hints.ai_flags = AI_PASSIVE;
  164. if( getaddrinfo( bind_ip, port, &hints, &addr_list ) != 0 )
  165. return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
  166. /* Try the sockaddrs until a binding succeeds */
  167. ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
  168. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  169. {
  170. ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
  171. cur->ai_protocol );
  172. if( ctx->fd < 0 )
  173. {
  174. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  175. continue;
  176. }
  177. n = 1;
  178. if( setsockopt( ctx->fd, SOL_SOCKET, SO_REUSEADDR,
  179. (const char *) &n, sizeof( n ) ) != 0 )
  180. {
  181. close( ctx->fd );
  182. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  183. continue;
  184. }
  185. if( bind( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) != 0 )
  186. {
  187. close( ctx->fd );
  188. ret = MBEDTLS_ERR_NET_BIND_FAILED;
  189. continue;
  190. }
  191. /* Listen only makes sense for TCP */
  192. if( proto == MBEDTLS_NET_PROTO_TCP )
  193. {
  194. if( listen( ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG ) != 0 )
  195. {
  196. close( ctx->fd );
  197. ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
  198. continue;
  199. }
  200. }
  201. /* Bind was successful */
  202. ret = 0;
  203. break;
  204. }
  205. freeaddrinfo( addr_list );
  206. return( ret );
  207. }
  208. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  209. !defined(EFI32)
  210. /*
  211. * Check if the requested operation would be blocking on a non-blocking socket
  212. * and thus 'failed' with a negative return value.
  213. */
  214. static int net_would_block( const mbedtls_net_context *ctx )
  215. {
  216. ((void) ctx);
  217. return( WSAGetLastError() == WSAEWOULDBLOCK );
  218. }
  219. #else
  220. /*
  221. * Check if the requested operation would be blocking on a non-blocking socket
  222. * and thus 'failed' with a negative return value.
  223. *
  224. * Note: on a blocking socket this function always returns 0!
  225. */
  226. static int net_would_block( const mbedtls_net_context *ctx )
  227. {
  228. /*
  229. * Never return 'WOULD BLOCK' on a non-blocking socket
  230. */
  231. if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
  232. return( 0 );
  233. switch( errno )
  234. {
  235. #if defined EAGAIN
  236. case EAGAIN:
  237. #endif
  238. #if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
  239. case EWOULDBLOCK:
  240. #endif
  241. return( 1 );
  242. }
  243. return( 0 );
  244. }
  245. #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  246. /*
  247. * Accept a connection from a remote client
  248. */
  249. int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
  250. mbedtls_net_context *client_ctx,
  251. void *client_ip, size_t buf_size, size_t *ip_len )
  252. {
  253. int ret;
  254. int type;
  255. struct sockaddr_storage client_addr;
  256. #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \
  257. defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t)
  258. socklen_t n = (socklen_t) sizeof( client_addr );
  259. socklen_t type_len = (socklen_t) sizeof( type );
  260. #else
  261. int n = (int) sizeof( client_addr );
  262. int type_len = (int) sizeof( type );
  263. #endif
  264. /* Is this a TCP or UDP socket? */
  265. if( getsockopt( bind_ctx->fd, SOL_SOCKET, SO_TYPE,
  266. (void *) &type, &type_len ) != 0 ||
  267. ( type != SOCK_STREAM && type != SOCK_DGRAM ) )
  268. {
  269. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  270. }
  271. if( type == SOCK_STREAM )
  272. {
  273. /* TCP: actual accept() */
  274. ret = client_ctx->fd = (int) accept( bind_ctx->fd,
  275. (struct sockaddr *) &client_addr, &n );
  276. }
  277. else
  278. {
  279. /* UDP: wait for a message, but keep it in the queue */
  280. char buf[1] = { 0 };
  281. ret = (int) recvfrom( bind_ctx->fd, buf, sizeof( buf ), MSG_PEEK,
  282. (struct sockaddr *) &client_addr, &n );
  283. #if defined(_WIN32)
  284. if( ret == SOCKET_ERROR &&
  285. WSAGetLastError() == WSAEMSGSIZE )
  286. {
  287. /* We know buf is too small, thanks, just peeking here */
  288. ret = 0;
  289. }
  290. #endif
  291. }
  292. if( ret < 0 )
  293. {
  294. if( net_would_block( bind_ctx ) != 0 )
  295. return( MBEDTLS_ERR_SSL_WANT_READ );
  296. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  297. }
  298. /* UDP: hijack the listening socket to communicate with the client,
  299. * then bind a new socket to accept new connections */
  300. if( type != SOCK_STREAM )
  301. {
  302. struct sockaddr_storage local_addr;
  303. int one = 1;
  304. if( connect( bind_ctx->fd, (struct sockaddr *) &client_addr, n ) != 0 )
  305. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  306. client_ctx->fd = bind_ctx->fd;
  307. bind_ctx->fd = -1; /* In case we exit early */
  308. n = sizeof( struct sockaddr_storage );
  309. if( getsockname( client_ctx->fd,
  310. (struct sockaddr *) &local_addr, &n ) != 0 ||
  311. ( bind_ctx->fd = (int) socket( local_addr.ss_family,
  312. SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ||
  313. setsockopt( bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR,
  314. (const char *) &one, sizeof( one ) ) != 0 )
  315. {
  316. return( MBEDTLS_ERR_NET_SOCKET_FAILED );
  317. }
  318. if( bind( bind_ctx->fd, (struct sockaddr *) &local_addr, n ) != 0 )
  319. {
  320. return( MBEDTLS_ERR_NET_BIND_FAILED );
  321. }
  322. }
  323. if( client_ip != NULL )
  324. {
  325. if( client_addr.ss_family == AF_INET )
  326. {
  327. struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr;
  328. *ip_len = sizeof( addr4->sin_addr.s_addr );
  329. if( buf_size < *ip_len )
  330. return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
  331. memcpy( client_ip, &addr4->sin_addr.s_addr, *ip_len );
  332. }
  333. else
  334. {
  335. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr;
  336. *ip_len = sizeof( addr6->sin6_addr.s6_addr );
  337. if( buf_size < *ip_len )
  338. return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
  339. memcpy( client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
  340. }
  341. }
  342. return( 0 );
  343. }
  344. /*
  345. * Set the socket blocking or non-blocking
  346. */
  347. int mbedtls_net_set_block( mbedtls_net_context *ctx )
  348. {
  349. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  350. !defined(EFI32)
  351. u_long n = 0;
  352. return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
  353. #else
  354. return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) & ~O_NONBLOCK ) );
  355. #endif
  356. }
  357. int mbedtls_net_set_nonblock( mbedtls_net_context *ctx )
  358. {
  359. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  360. !defined(EFI32)
  361. u_long n = 1;
  362. return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
  363. #else
  364. return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ) );
  365. #endif
  366. }
  367. /*
  368. * Portable usleep helper
  369. */
  370. void mbedtls_net_usleep( unsigned long usec )
  371. {
  372. #if defined(_WIN32)
  373. Sleep( ( usec + 999 ) / 1000 );
  374. #else
  375. struct timeval tv;
  376. tv.tv_sec = usec / 1000000;
  377. #if defined(__unix__) || defined(__unix) || \
  378. ( defined(__APPLE__) && defined(__MACH__) )
  379. tv.tv_usec = (suseconds_t) usec % 1000000;
  380. #else
  381. tv.tv_usec = usec % 1000000;
  382. #endif
  383. select( 0, NULL, NULL, NULL, &tv );
  384. #endif
  385. }
  386. /*
  387. * Read at most 'len' characters
  388. */
  389. int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )
  390. {
  391. int ret;
  392. int fd = ((mbedtls_net_context *) ctx)->fd;
  393. if( fd < 0 )
  394. return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
  395. ret = (int) read( fd, buf, len );
  396. if( ret < 0 )
  397. {
  398. if( net_would_block( ctx ) != 0 )
  399. return( MBEDTLS_ERR_SSL_WANT_READ );
  400. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  401. !defined(EFI32)
  402. if( WSAGetLastError() == WSAECONNRESET )
  403. return( MBEDTLS_ERR_NET_CONN_RESET );
  404. #else
  405. if( errno == EPIPE || errno == ECONNRESET )
  406. return( MBEDTLS_ERR_NET_CONN_RESET );
  407. if( errno == EINTR )
  408. return( MBEDTLS_ERR_SSL_WANT_READ );
  409. #endif
  410. return( MBEDTLS_ERR_NET_RECV_FAILED );
  411. }
  412. return( ret );
  413. }
  414. /*
  415. * Read at most 'len' characters, blocking for at most 'timeout' ms
  416. */
  417. int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
  418. uint32_t timeout )
  419. {
  420. int ret;
  421. struct timeval tv;
  422. fd_set read_fds;
  423. int fd = ((mbedtls_net_context *) ctx)->fd;
  424. if( fd < 0 )
  425. return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
  426. FD_ZERO( &read_fds );
  427. FD_SET( fd, &read_fds );
  428. tv.tv_sec = timeout / 1000;
  429. tv.tv_usec = ( timeout % 1000 ) * 1000;
  430. ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );
  431. /* Zero fds ready means we timed out */
  432. if( ret == 0 )
  433. return( MBEDTLS_ERR_SSL_TIMEOUT );
  434. if( ret < 0 )
  435. {
  436. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  437. !defined(EFI32)
  438. if( WSAGetLastError() == WSAEINTR )
  439. return( MBEDTLS_ERR_SSL_WANT_READ );
  440. #else
  441. if( errno == EINTR )
  442. return( MBEDTLS_ERR_SSL_WANT_READ );
  443. #endif
  444. return( MBEDTLS_ERR_NET_RECV_FAILED );
  445. }
  446. /* This call will not block */
  447. return( mbedtls_net_recv( ctx, buf, len ) );
  448. }
  449. /*
  450. * Write at most 'len' characters
  451. */
  452. int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )
  453. {
  454. int ret;
  455. int fd = ((mbedtls_net_context *) ctx)->fd;
  456. if( fd < 0 )
  457. return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
  458. ret = (int) write( fd, buf, len );
  459. if( ret < 0 )
  460. {
  461. if( net_would_block( ctx ) != 0 )
  462. return( MBEDTLS_ERR_SSL_WANT_WRITE );
  463. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  464. !defined(EFI32)
  465. if( WSAGetLastError() == WSAECONNRESET )
  466. return( MBEDTLS_ERR_NET_CONN_RESET );
  467. #else
  468. if( errno == EPIPE || errno == ECONNRESET )
  469. return( MBEDTLS_ERR_NET_CONN_RESET );
  470. if( errno == EINTR )
  471. return( MBEDTLS_ERR_SSL_WANT_WRITE );
  472. #endif
  473. return( MBEDTLS_ERR_NET_SEND_FAILED );
  474. }
  475. return( ret );
  476. }
  477. /*
  478. * Gracefully close the connection
  479. */
  480. void mbedtls_net_free( mbedtls_net_context *ctx )
  481. {
  482. if( ctx->fd == -1 )
  483. return;
  484. shutdown( ctx->fd, 2 );
  485. close( ctx->fd );
  486. ctx->fd = -1;
  487. }
  488. #endif /* MBEDTLS_NET_C */