net_sockets_template.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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, const char *port, int proto )
  113. {
  114. int ret;
  115. struct addrinfo hints, *addr_list, *cur;
  116. if( ( ret = net_prepare() ) != 0 )
  117. return( ret );
  118. /* Do name resolution with both IPv6 and IPv4 */
  119. memset( &hints, 0, sizeof( hints ) );
  120. hints.ai_family = AF_UNSPEC;
  121. hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
  122. hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
  123. if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )
  124. return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
  125. /* Try the sockaddrs until a connection succeeds */
  126. ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
  127. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  128. {
  129. ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
  130. cur->ai_protocol );
  131. if( ctx->fd < 0 )
  132. {
  133. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  134. continue;
  135. }
  136. if( connect( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) == 0 )
  137. {
  138. ret = 0;
  139. break;
  140. }
  141. close( ctx->fd );
  142. ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
  143. }
  144. freeaddrinfo( addr_list );
  145. return( ret );
  146. }
  147. /*
  148. * Create a listening socket on bind_ip:port
  149. */
  150. int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )
  151. {
  152. int n, ret;
  153. struct addrinfo hints, *addr_list, *cur;
  154. if( ( ret = net_prepare() ) != 0 )
  155. return( ret );
  156. /* Bind to IPv6 and/or IPv4, but only in the desired protocol */
  157. memset( &hints, 0, sizeof( hints ) );
  158. hints.ai_family = AF_UNSPEC;
  159. hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
  160. hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
  161. if( bind_ip == NULL )
  162. hints.ai_flags = AI_PASSIVE;
  163. if( getaddrinfo( bind_ip, port, &hints, &addr_list ) != 0 )
  164. return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
  165. /* Try the sockaddrs until a binding succeeds */
  166. ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
  167. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  168. {
  169. ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
  170. cur->ai_protocol );
  171. if( ctx->fd < 0 )
  172. {
  173. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  174. continue;
  175. }
  176. n = 1;
  177. if( setsockopt( ctx->fd, SOL_SOCKET, SO_REUSEADDR,
  178. (const char *) &n, sizeof( n ) ) != 0 )
  179. {
  180. close( ctx->fd );
  181. ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
  182. continue;
  183. }
  184. if( bind( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) != 0 )
  185. {
  186. close( ctx->fd );
  187. ret = MBEDTLS_ERR_NET_BIND_FAILED;
  188. continue;
  189. }
  190. /* Listen only makes sense for TCP */
  191. if( proto == MBEDTLS_NET_PROTO_TCP )
  192. {
  193. if( listen( ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG ) != 0 )
  194. {
  195. close( ctx->fd );
  196. ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
  197. continue;
  198. }
  199. }
  200. /* I we ever get there, it's a success */
  201. ret = 0;
  202. break;
  203. }
  204. freeaddrinfo( addr_list );
  205. return( ret );
  206. }
  207. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  208. !defined(EFI32)
  209. /*
  210. * Check if the requested operation would be blocking on a non-blocking socket
  211. * and thus 'failed' with a negative return value.
  212. */
  213. static int net_would_block( const mbedtls_net_context *ctx )
  214. {
  215. ((void) ctx);
  216. return( WSAGetLastError() == WSAEWOULDBLOCK );
  217. }
  218. #else
  219. /*
  220. * Check if the requested operation would be blocking on a non-blocking socket
  221. * and thus 'failed' with a negative return value.
  222. *
  223. * Note: on a blocking socket this function always returns 0!
  224. */
  225. static int net_would_block( const mbedtls_net_context *ctx )
  226. {
  227. /*
  228. * Never return 'WOULD BLOCK' on a non-blocking socket
  229. */
  230. if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
  231. return( 0 );
  232. switch( errno )
  233. {
  234. #if defined EAGAIN
  235. case EAGAIN:
  236. #endif
  237. #if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
  238. case EWOULDBLOCK:
  239. #endif
  240. return( 1 );
  241. }
  242. return( 0 );
  243. }
  244. #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  245. /*
  246. * Accept a connection from a remote client
  247. */
  248. int mbedtls_net_accept( mbedtls_net_context *bind_ctx,
  249. mbedtls_net_context *client_ctx,
  250. void *client_ip, size_t buf_size, size_t *ip_len )
  251. {
  252. int ret;
  253. int type;
  254. struct sockaddr_storage client_addr;
  255. #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \
  256. defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t)
  257. socklen_t n = (socklen_t) sizeof( client_addr );
  258. socklen_t type_len = (socklen_t) sizeof( type );
  259. #else
  260. int n = (int) sizeof( client_addr );
  261. int type_len = (int) sizeof( type );
  262. #endif
  263. /* Is this a TCP or UDP socket? */
  264. if( getsockopt( bind_ctx->fd, SOL_SOCKET, SO_TYPE,
  265. (void *) &type, &type_len ) != 0 ||
  266. ( type != SOCK_STREAM && type != SOCK_DGRAM ) )
  267. {
  268. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  269. }
  270. if( type == SOCK_STREAM )
  271. {
  272. /* TCP: actual accept() */
  273. ret = client_ctx->fd = (int) accept( bind_ctx->fd,
  274. (struct sockaddr *) &client_addr, &n );
  275. }
  276. else
  277. {
  278. /* UDP: wait for a message, but keep it in the queue */
  279. char buf[1] = { 0 };
  280. ret = (int) recvfrom( bind_ctx->fd, buf, sizeof( buf ), MSG_PEEK,
  281. (struct sockaddr *) &client_addr, &n );
  282. #if defined(_WIN32)
  283. if( ret == SOCKET_ERROR &&
  284. WSAGetLastError() == WSAEMSGSIZE )
  285. {
  286. /* We know buf is too small, thanks, just peeking here */
  287. ret = 0;
  288. }
  289. #endif
  290. }
  291. if( ret < 0 )
  292. {
  293. if( net_would_block( bind_ctx ) != 0 )
  294. return( MBEDTLS_ERR_SSL_WANT_READ );
  295. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  296. }
  297. /* UDP: hijack the listening socket to communicate with the client,
  298. * then bind a new socket to accept new connections */
  299. if( type != SOCK_STREAM )
  300. {
  301. struct sockaddr_storage local_addr;
  302. int one = 1;
  303. if( connect( bind_ctx->fd, (struct sockaddr *) &client_addr, n ) != 0 )
  304. return( MBEDTLS_ERR_NET_ACCEPT_FAILED );
  305. client_ctx->fd = bind_ctx->fd;
  306. bind_ctx->fd = -1; /* In case we exit early */
  307. n = sizeof( struct sockaddr_storage );
  308. if( getsockname( client_ctx->fd,
  309. (struct sockaddr *) &local_addr, &n ) != 0 ||
  310. ( bind_ctx->fd = (int) socket( local_addr.ss_family,
  311. SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ||
  312. setsockopt( bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR,
  313. (const char *) &one, sizeof( one ) ) != 0 )
  314. {
  315. return( MBEDTLS_ERR_NET_SOCKET_FAILED );
  316. }
  317. if( bind( bind_ctx->fd, (struct sockaddr *) &local_addr, n ) != 0 )
  318. {
  319. return( MBEDTLS_ERR_NET_BIND_FAILED );
  320. }
  321. }
  322. if( client_ip != NULL )
  323. {
  324. if( client_addr.ss_family == AF_INET )
  325. {
  326. struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr;
  327. *ip_len = sizeof( addr4->sin_addr.s_addr );
  328. if( buf_size < *ip_len )
  329. return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
  330. memcpy( client_ip, &addr4->sin_addr.s_addr, *ip_len );
  331. }
  332. else
  333. {
  334. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr;
  335. *ip_len = sizeof( addr6->sin6_addr.s6_addr );
  336. if( buf_size < *ip_len )
  337. return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );
  338. memcpy( client_ip, &addr6->sin6_addr.s6_addr, *ip_len);
  339. }
  340. }
  341. return( 0 );
  342. }
  343. /*
  344. * Set the socket blocking or non-blocking
  345. */
  346. int mbedtls_net_set_block( mbedtls_net_context *ctx )
  347. {
  348. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  349. !defined(EFI32)
  350. u_long n = 0;
  351. return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
  352. #else
  353. return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) & ~O_NONBLOCK ) );
  354. #endif
  355. }
  356. int mbedtls_net_set_nonblock( mbedtls_net_context *ctx )
  357. {
  358. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  359. !defined(EFI32)
  360. u_long n = 1;
  361. return( ioctlsocket( ctx->fd, FIONBIO, &n ) );
  362. #else
  363. return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ) );
  364. #endif
  365. }
  366. /*
  367. * Portable usleep helper
  368. */
  369. void mbedtls_net_usleep( unsigned long usec )
  370. {
  371. #if defined(_WIN32)
  372. Sleep( ( usec + 999 ) / 1000 );
  373. #else
  374. struct timeval tv;
  375. tv.tv_sec = usec / 1000000;
  376. #if defined(__unix__) || defined(__unix) || \
  377. ( defined(__APPLE__) && defined(__MACH__) )
  378. tv.tv_usec = (suseconds_t) usec % 1000000;
  379. #else
  380. tv.tv_usec = usec % 1000000;
  381. #endif
  382. select( 0, NULL, NULL, NULL, &tv );
  383. #endif
  384. }
  385. /*
  386. * Read at most 'len' characters
  387. */
  388. int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )
  389. {
  390. int ret;
  391. int fd = ((mbedtls_net_context *) ctx)->fd;
  392. if( fd < 0 )
  393. return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
  394. ret = (int) read( fd, buf, len );
  395. if( ret < 0 )
  396. {
  397. if( net_would_block( ctx ) != 0 )
  398. return( MBEDTLS_ERR_SSL_WANT_READ );
  399. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  400. !defined(EFI32)
  401. if( WSAGetLastError() == WSAECONNRESET )
  402. return( MBEDTLS_ERR_NET_CONN_RESET );
  403. #else
  404. if( errno == EPIPE || errno == ECONNRESET )
  405. return( MBEDTLS_ERR_NET_CONN_RESET );
  406. if( errno == EINTR )
  407. return( MBEDTLS_ERR_SSL_WANT_READ );
  408. #endif
  409. return( MBEDTLS_ERR_NET_RECV_FAILED );
  410. }
  411. return( ret );
  412. }
  413. /*
  414. * Read at most 'len' characters, blocking for at most 'timeout' ms
  415. */
  416. int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
  417. uint32_t timeout )
  418. {
  419. int ret;
  420. struct timeval tv;
  421. fd_set read_fds;
  422. int fd = ((mbedtls_net_context *) ctx)->fd;
  423. if( fd < 0 )
  424. return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
  425. FD_ZERO( &read_fds );
  426. FD_SET( fd, &read_fds );
  427. tv.tv_sec = timeout / 1000;
  428. tv.tv_usec = ( timeout % 1000 ) * 1000;
  429. ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );
  430. /* Zero fds ready means we timed out */
  431. if( ret == 0 )
  432. return( MBEDTLS_ERR_SSL_TIMEOUT );
  433. if( ret < 0 )
  434. {
  435. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  436. !defined(EFI32)
  437. if( WSAGetLastError() == WSAEINTR )
  438. return( MBEDTLS_ERR_SSL_WANT_READ );
  439. #else
  440. if( errno == EINTR )
  441. return( MBEDTLS_ERR_SSL_WANT_READ );
  442. #endif
  443. return( MBEDTLS_ERR_NET_RECV_FAILED );
  444. }
  445. /* This call will not block */
  446. return( mbedtls_net_recv( ctx, buf, len ) );
  447. }
  448. /*
  449. * Write at most 'len' characters
  450. */
  451. int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )
  452. {
  453. int ret;
  454. int fd = ((mbedtls_net_context *) ctx)->fd;
  455. if( fd < 0 )
  456. return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
  457. ret = (int) write( fd, buf, len );
  458. if( ret < 0 )
  459. {
  460. if( net_would_block( ctx ) != 0 )
  461. return( MBEDTLS_ERR_SSL_WANT_WRITE );
  462. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  463. !defined(EFI32)
  464. if( WSAGetLastError() == WSAECONNRESET )
  465. return( MBEDTLS_ERR_NET_CONN_RESET );
  466. #else
  467. if( errno == EPIPE || errno == ECONNRESET )
  468. return( MBEDTLS_ERR_NET_CONN_RESET );
  469. if( errno == EINTR )
  470. return( MBEDTLS_ERR_SSL_WANT_WRITE );
  471. #endif
  472. return( MBEDTLS_ERR_NET_SEND_FAILED );
  473. }
  474. return( ret );
  475. }
  476. /*
  477. * Gracefully close the connection
  478. */
  479. void mbedtls_net_free( mbedtls_net_context *ctx )
  480. {
  481. if( ctx->fd == -1 )
  482. return;
  483. shutdown( ctx->fd, 2 );
  484. close( ctx->fd );
  485. ctx->fd = -1;
  486. }
  487. #endif /* MBEDTLS_NET_C */