net_sockets.c 15 KB

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