net_sockets.c 14 KB

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