net.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*
  2. * TCP networking functions
  3. *
  4. * Copyright (C) 2006-2014, Brainspark B.V.
  5. *
  6. * This file is part of PolarSSL (http://www.polarssl.org)
  7. * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
  8. *
  9. * All rights reserved.
  10. *
  11. * This program is free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 2 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License along
  22. * with this program; if not, write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. */
  25. #if !defined(POLARSSL_CONFIG_FILE)
  26. #include "polarssl/config.h"
  27. #else
  28. #include POLARSSL_CONFIG_FILE
  29. #endif
  30. #if defined(POLARSSL_NET_C)
  31. #include "polarssl/net.h"
  32. #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
  33. !defined(EFI32)
  34. #if defined(POLARSSL_HAVE_IPV6)
  35. #ifdef _WIN32_WINNT
  36. #undef _WIN32_WINNT
  37. #endif
  38. /* Enables getaddrinfo() & Co */
  39. #define _WIN32_WINNT 0x0501
  40. #include <ws2tcpip.h>
  41. #endif
  42. #include <winsock2.h>
  43. #include <windows.h>
  44. #if defined(_MSC_VER)
  45. #if defined(_WIN32_WCE)
  46. #pragma comment( lib, "ws2.lib" )
  47. #else
  48. #pragma comment( lib, "ws2_32.lib" )
  49. #endif
  50. #endif /* _MSC_VER */
  51. #define read(fd,buf,len) recv(fd,(char*)buf,(int) len,0)
  52. #define write(fd,buf,len) send(fd,(char*)buf,(int) len,0)
  53. #define close(fd) closesocket(fd)
  54. static int wsa_init_done = 0;
  55. #else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  56. #include <sys/types.h>
  57. #include <sys/socket.h>
  58. #include <netinet/in.h>
  59. #include <arpa/inet.h>
  60. #if defined(POLARSSL_HAVE_TIME)
  61. #include <sys/time.h>
  62. #endif
  63. #include <unistd.h>
  64. #include <signal.h>
  65. #include <fcntl.h>
  66. #include <netdb.h>
  67. #include <errno.h>
  68. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || \
  69. defined(__DragonFly__)
  70. #include <sys/endian.h>
  71. #elif defined(__APPLE__) || defined(HAVE_MACHINE_ENDIAN_H) || \
  72. defined(EFIX64) || defined(EFI32)
  73. #include <machine/endian.h>
  74. #elif defined(sun)
  75. #include <sys/isa_defs.h>
  76. #elif defined(_AIX) || defined(HAVE_ARPA_NAMESER_COMPAT_H)
  77. #include <arpa/nameser_compat.h>
  78. #else
  79. #include <endian.h>
  80. #endif
  81. #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  82. #include <stdlib.h>
  83. #include <stdio.h>
  84. #if defined(_MSC_VER) && !defined snprintf && !defined(EFIX64) && \
  85. !defined(EFI32)
  86. #define snprintf _snprintf
  87. #endif
  88. #if defined(POLARSSL_HAVE_TIME)
  89. #include <time.h>
  90. #endif
  91. #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
  92. #include <basetsd.h>
  93. typedef UINT32 uint32_t;
  94. #else
  95. #include <inttypes.h>
  96. #endif
  97. /*
  98. * htons() is not always available.
  99. * By default go for LITTLE_ENDIAN variant. Otherwise hope for _BYTE_ORDER and
  100. * __BIG_ENDIAN to help determine endianness.
  101. */
  102. #if defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
  103. __BYTE_ORDER == __BIG_ENDIAN
  104. #define POLARSSL_HTONS(n) (n)
  105. #define POLARSSL_HTONL(n) (n)
  106. #else
  107. #define POLARSSL_HTONS(n) ((((unsigned short)(n) & 0xFF ) << 8 ) | \
  108. (((unsigned short)(n) & 0xFF00 ) >> 8 ))
  109. #define POLARSSL_HTONL(n) ((((unsigned long )(n) & 0xFF ) << 24) | \
  110. (((unsigned long )(n) & 0xFF00 ) << 8 ) | \
  111. (((unsigned long )(n) & 0xFF0000 ) >> 8 ) | \
  112. (((unsigned long )(n) & 0xFF000000) >> 24))
  113. #endif
  114. unsigned short net_htons( unsigned short n );
  115. unsigned long net_htonl( unsigned long n );
  116. #define net_htons(n) POLARSSL_HTONS(n)
  117. #define net_htonl(n) POLARSSL_HTONL(n)
  118. /*
  119. * Prepare for using the sockets interface
  120. */
  121. static int net_prepare( void )
  122. {
  123. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  124. !defined(EFI32)
  125. WSADATA wsaData;
  126. if( wsa_init_done == 0 )
  127. {
  128. if( WSAStartup( MAKEWORD(2,0), &wsaData ) != 0 )
  129. return( POLARSSL_ERR_NET_SOCKET_FAILED );
  130. wsa_init_done = 1;
  131. }
  132. #else
  133. #if !defined(EFIX64) && !defined(EFI32)
  134. signal( SIGPIPE, SIG_IGN );
  135. #endif
  136. #endif
  137. return( 0 );
  138. }
  139. /*
  140. * Initiate a TCP connection with host:port
  141. */
  142. int net_connect( int *fd, const char *host, int port )
  143. {
  144. #if defined(POLARSSL_HAVE_IPV6)
  145. int ret;
  146. struct addrinfo hints, *addr_list, *cur;
  147. char port_str[6];
  148. if( ( ret = net_prepare() ) != 0 )
  149. return( ret );
  150. /* getaddrinfo expects port as a string */
  151. memset( port_str, 0, sizeof( port_str ) );
  152. snprintf( port_str, sizeof( port_str ), "%d", port );
  153. /* Do name resolution with both IPv6 and IPv4, but only TCP */
  154. memset( &hints, 0, sizeof( hints ) );
  155. hints.ai_family = AF_UNSPEC;
  156. hints.ai_socktype = SOCK_STREAM;
  157. hints.ai_protocol = IPPROTO_TCP;
  158. if( getaddrinfo( host, port_str, &hints, &addr_list ) != 0 )
  159. return( POLARSSL_ERR_NET_UNKNOWN_HOST );
  160. /* Try the sockaddrs until a connection succeeds */
  161. ret = POLARSSL_ERR_NET_UNKNOWN_HOST;
  162. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  163. {
  164. *fd = (int) socket( cur->ai_family, cur->ai_socktype,
  165. cur->ai_protocol );
  166. if( *fd < 0 )
  167. {
  168. ret = POLARSSL_ERR_NET_SOCKET_FAILED;
  169. continue;
  170. }
  171. if( connect( *fd, cur->ai_addr, cur->ai_addrlen ) == 0 )
  172. {
  173. ret = 0;
  174. break;
  175. }
  176. close( *fd );
  177. ret = POLARSSL_ERR_NET_CONNECT_FAILED;
  178. }
  179. freeaddrinfo( addr_list );
  180. return( ret );
  181. #else
  182. /* Legacy IPv4-only version */
  183. int ret;
  184. struct sockaddr_in server_addr;
  185. struct hostent *server_host;
  186. if( ( ret = net_prepare() ) != 0 )
  187. return( ret );
  188. if( ( server_host = gethostbyname( host ) ) == NULL )
  189. return( POLARSSL_ERR_NET_UNKNOWN_HOST );
  190. if( ( *fd = (int) socket( AF_INET, SOCK_STREAM, IPPROTO_IP ) ) < 0 )
  191. return( POLARSSL_ERR_NET_SOCKET_FAILED );
  192. memcpy( (void *) &server_addr.sin_addr,
  193. (void *) server_host->h_addr,
  194. server_host->h_length );
  195. server_addr.sin_family = AF_INET;
  196. server_addr.sin_port = net_htons( port );
  197. if( connect( *fd, (struct sockaddr *) &server_addr,
  198. sizeof( server_addr ) ) < 0 )
  199. {
  200. close( *fd );
  201. return( POLARSSL_ERR_NET_CONNECT_FAILED );
  202. }
  203. return( 0 );
  204. #endif /* POLARSSL_HAVE_IPV6 */
  205. }
  206. /*
  207. * Create a listening socket on bind_ip:port
  208. */
  209. int net_bind( int *fd, const char *bind_ip, int port )
  210. {
  211. #if defined(POLARSSL_HAVE_IPV6)
  212. int n, ret;
  213. struct addrinfo hints, *addr_list, *cur;
  214. char port_str[6];
  215. if( ( ret = net_prepare() ) != 0 )
  216. return( ret );
  217. /* getaddrinfo expects port as a string */
  218. memset( port_str, 0, sizeof( port_str ) );
  219. snprintf( port_str, sizeof( port_str ), "%d", port );
  220. /* Bind to IPv6 and/or IPv4, but only in TCP */
  221. memset( &hints, 0, sizeof( hints ) );
  222. hints.ai_family = AF_UNSPEC;
  223. hints.ai_socktype = SOCK_STREAM;
  224. hints.ai_protocol = IPPROTO_TCP;
  225. if( bind_ip == NULL )
  226. hints.ai_flags = AI_PASSIVE;
  227. if( getaddrinfo( bind_ip, port_str, &hints, &addr_list ) != 0 )
  228. return( POLARSSL_ERR_NET_UNKNOWN_HOST );
  229. /* Try the sockaddrs until a binding succeeds */
  230. ret = POLARSSL_ERR_NET_UNKNOWN_HOST;
  231. for( cur = addr_list; cur != NULL; cur = cur->ai_next )
  232. {
  233. *fd = (int) socket( cur->ai_family, cur->ai_socktype,
  234. cur->ai_protocol );
  235. if( *fd < 0 )
  236. {
  237. ret = POLARSSL_ERR_NET_SOCKET_FAILED;
  238. continue;
  239. }
  240. n = 1;
  241. if( setsockopt( *fd, SOL_SOCKET, SO_REUSEADDR,
  242. (const char *) &n, sizeof( n ) ) != 0 )
  243. {
  244. close( *fd );
  245. ret = POLARSSL_ERR_NET_SOCKET_FAILED;
  246. continue;
  247. }
  248. if( bind( *fd, cur->ai_addr, cur->ai_addrlen ) != 0 )
  249. {
  250. close( *fd );
  251. ret = POLARSSL_ERR_NET_BIND_FAILED;
  252. continue;
  253. }
  254. if( listen( *fd, POLARSSL_NET_LISTEN_BACKLOG ) != 0 )
  255. {
  256. close( *fd );
  257. ret = POLARSSL_ERR_NET_LISTEN_FAILED;
  258. continue;
  259. }
  260. /* I we ever get there, it's a success */
  261. ret = 0;
  262. break;
  263. }
  264. freeaddrinfo( addr_list );
  265. return( ret );
  266. #else
  267. /* Legacy IPv4-only version */
  268. int ret, n, c[4];
  269. struct sockaddr_in server_addr;
  270. if( ( ret = net_prepare() ) != 0 )
  271. return( ret );
  272. if( ( *fd = (int) socket( AF_INET, SOCK_STREAM, IPPROTO_IP ) ) < 0 )
  273. return( POLARSSL_ERR_NET_SOCKET_FAILED );
  274. n = 1;
  275. setsockopt( *fd, SOL_SOCKET, SO_REUSEADDR,
  276. (const char *) &n, sizeof( n ) );
  277. server_addr.sin_addr.s_addr = net_htonl( INADDR_ANY );
  278. server_addr.sin_family = AF_INET;
  279. server_addr.sin_port = net_htons( port );
  280. if( bind_ip != NULL )
  281. {
  282. memset( c, 0, sizeof( c ) );
  283. sscanf( bind_ip, "%d.%d.%d.%d", &c[0], &c[1], &c[2], &c[3] );
  284. for( n = 0; n < 4; n++ )
  285. if( c[n] < 0 || c[n] > 255 )
  286. break;
  287. if( n == 4 )
  288. server_addr.sin_addr.s_addr = net_htonl(
  289. ( (uint32_t) c[0] << 24 ) |
  290. ( (uint32_t) c[1] << 16 ) |
  291. ( (uint32_t) c[2] << 8 ) |
  292. ( (uint32_t) c[3] ) );
  293. }
  294. if( bind( *fd, (struct sockaddr *) &server_addr,
  295. sizeof( server_addr ) ) < 0 )
  296. {
  297. close( *fd );
  298. return( POLARSSL_ERR_NET_BIND_FAILED );
  299. }
  300. if( listen( *fd, POLARSSL_NET_LISTEN_BACKLOG ) != 0 )
  301. {
  302. close( *fd );
  303. return( POLARSSL_ERR_NET_LISTEN_FAILED );
  304. }
  305. return( 0 );
  306. #endif /* POLARSSL_HAVE_IPV6 */
  307. }
  308. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  309. !defined(EFI32)
  310. /*
  311. * Check if the requested operation would be blocking on a non-blocking socket
  312. * and thus 'failed' with a negative return value.
  313. */
  314. static int net_would_block( int fd )
  315. {
  316. ((void) fd);
  317. return( WSAGetLastError() == WSAEWOULDBLOCK );
  318. }
  319. #else
  320. /*
  321. * Check if the requested operation would be blocking on a non-blocking socket
  322. * and thus 'failed' with a negative return value.
  323. *
  324. * Note: on a blocking socket this function always returns 0!
  325. */
  326. static int net_would_block( int fd )
  327. {
  328. /*
  329. * Never return 'WOULD BLOCK' on a non-blocking socket
  330. */
  331. if( ( fcntl( fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
  332. return( 0 );
  333. switch( errno )
  334. {
  335. #if defined EAGAIN
  336. case EAGAIN:
  337. #endif
  338. #if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
  339. case EWOULDBLOCK:
  340. #endif
  341. return( 1 );
  342. }
  343. return( 0 );
  344. }
  345. #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
  346. /*
  347. * Accept a connection from a remote client
  348. */
  349. int net_accept( int bind_fd, int *client_fd, void *client_ip )
  350. {
  351. #if defined(POLARSSL_HAVE_IPV6)
  352. struct sockaddr_storage client_addr;
  353. #else
  354. struct sockaddr_in client_addr;
  355. #endif
  356. #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \
  357. defined(_SOCKLEN_T_DECLARED)
  358. socklen_t n = (socklen_t) sizeof( client_addr );
  359. #else
  360. int n = (int) sizeof( client_addr );
  361. #endif
  362. *client_fd = (int) accept( bind_fd, (struct sockaddr *)
  363. &client_addr, &n );
  364. if( *client_fd < 0 )
  365. {
  366. if( net_would_block( *client_fd ) != 0 )
  367. return( POLARSSL_ERR_NET_WANT_READ );
  368. return( POLARSSL_ERR_NET_ACCEPT_FAILED );
  369. }
  370. if( client_ip != NULL )
  371. {
  372. #if defined(POLARSSL_HAVE_IPV6)
  373. if( client_addr.ss_family == AF_INET )
  374. {
  375. struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr;
  376. memcpy( client_ip, &addr4->sin_addr.s_addr,
  377. sizeof( addr4->sin_addr.s_addr ) );
  378. }
  379. else
  380. {
  381. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr;
  382. memcpy( client_ip, &addr6->sin6_addr.s6_addr,
  383. sizeof( addr6->sin6_addr.s6_addr ) );
  384. }
  385. #else
  386. memcpy( client_ip, &client_addr.sin_addr.s_addr,
  387. sizeof( client_addr.sin_addr.s_addr ) );
  388. #endif /* POLARSSL_HAVE_IPV6 */
  389. }
  390. return( 0 );
  391. }
  392. /*
  393. * Set the socket blocking or non-blocking
  394. */
  395. int net_set_block( int fd )
  396. {
  397. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  398. !defined(EFI32)
  399. u_long n = 0;
  400. return( ioctlsocket( fd, FIONBIO, &n ) );
  401. #else
  402. return( fcntl( fd, F_SETFL, fcntl( fd, F_GETFL ) & ~O_NONBLOCK ) );
  403. #endif
  404. }
  405. int net_set_nonblock( int fd )
  406. {
  407. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  408. !defined(EFI32)
  409. u_long n = 1;
  410. return( ioctlsocket( fd, FIONBIO, &n ) );
  411. #else
  412. return( fcntl( fd, F_SETFL, fcntl( fd, F_GETFL ) | O_NONBLOCK ) );
  413. #endif
  414. }
  415. #if defined(POLARSSL_HAVE_TIME)
  416. /*
  417. * Portable usleep helper
  418. */
  419. void net_usleep( unsigned long usec )
  420. {
  421. struct timeval tv;
  422. tv.tv_sec = 0;
  423. tv.tv_usec = usec;
  424. select( 0, NULL, NULL, NULL, &tv );
  425. }
  426. #endif /* POLARSSL_HAVE_TIME */
  427. /*
  428. * Read at most 'len' characters
  429. */
  430. int net_recv( void *ctx, unsigned char *buf, size_t len )
  431. {
  432. int fd = *((int *) ctx);
  433. int ret = read( fd, buf, len );
  434. if( ret < 0 )
  435. {
  436. if( net_would_block( fd ) != 0 )
  437. return( POLARSSL_ERR_NET_WANT_READ );
  438. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  439. !defined(EFI32)
  440. if( WSAGetLastError() == WSAECONNRESET )
  441. return( POLARSSL_ERR_NET_CONN_RESET );
  442. #else
  443. if( errno == EPIPE || errno == ECONNRESET )
  444. return( POLARSSL_ERR_NET_CONN_RESET );
  445. if( errno == EINTR )
  446. return( POLARSSL_ERR_NET_WANT_READ );
  447. #endif
  448. return( POLARSSL_ERR_NET_RECV_FAILED );
  449. }
  450. return( ret );
  451. }
  452. /*
  453. * Write at most 'len' characters
  454. */
  455. int net_send( void *ctx, const unsigned char *buf, size_t len )
  456. {
  457. int fd = *((int *) ctx);
  458. int ret = write( fd, buf, len );
  459. if( ret < 0 )
  460. {
  461. if( net_would_block( fd ) != 0 )
  462. return( POLARSSL_ERR_NET_WANT_WRITE );
  463. #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
  464. !defined(EFI32)
  465. if( WSAGetLastError() == WSAECONNRESET )
  466. return( POLARSSL_ERR_NET_CONN_RESET );
  467. #else
  468. if( errno == EPIPE || errno == ECONNRESET )
  469. return( POLARSSL_ERR_NET_CONN_RESET );
  470. if( errno == EINTR )
  471. return( POLARSSL_ERR_NET_WANT_WRITE );
  472. #endif
  473. return( POLARSSL_ERR_NET_SEND_FAILED );
  474. }
  475. return( ret );
  476. }
  477. /*
  478. * Gracefully close the connection
  479. */
  480. void net_close( int fd )
  481. {
  482. shutdown( fd, 2 );
  483. close( fd );
  484. }
  485. #endif /* POLARSSL_NET_C */