You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

299 rivejä
7.4 KiB

  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <openssl/base.h>
  15. #include <string>
  16. #include <vector>
  17. #include <errno.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <sys/types.h>
  21. #if !defined(OPENSSL_WINDOWS)
  22. #include <arpa/inet.h>
  23. #include <fcntl.h>
  24. #include <netdb.h>
  25. #include <netinet/in.h>
  26. #include <sys/select.h>
  27. #include <sys/socket.h>
  28. #include <unistd.h>
  29. #else
  30. #define NOMINMAX
  31. #include <io.h>
  32. #pragma warning(push, 3)
  33. #include <WinSock2.h>
  34. #include <WS2tcpip.h>
  35. #pragma warning(pop)
  36. typedef int ssize_t;
  37. #pragma comment(lib, "Ws2_32.lib")
  38. #endif
  39. #include <openssl/err.h>
  40. #include <openssl/ssl.h>
  41. #include "internal.h"
  42. #if !defined(OPENSSL_WINDOWS)
  43. static int closesocket(int sock) {
  44. return close(sock);
  45. }
  46. #endif
  47. bool InitSocketLibrary() {
  48. #if defined(OPENSSL_WINDOWS)
  49. WSADATA wsaData;
  50. int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
  51. if (err != 0) {
  52. fprintf(stderr, "WSAStartup failed with error %d\n", err);
  53. return false;
  54. }
  55. #endif
  56. return true;
  57. }
  58. // Connect sets |*out_sock| to be a socket connected to the destination given
  59. // in |hostname_and_port|, which should be of the form "www.example.com:123".
  60. // It returns true on success and false otherwise.
  61. bool Connect(int *out_sock, const std::string &hostname_and_port) {
  62. const size_t colon_offset = hostname_and_port.find_last_of(':');
  63. std::string hostname, port;
  64. if (colon_offset == std::string::npos) {
  65. hostname = hostname_and_port;
  66. port = "443";
  67. } else {
  68. hostname = hostname_and_port.substr(0, colon_offset);
  69. port = hostname_and_port.substr(colon_offset + 1);
  70. }
  71. struct addrinfo hint, *result;
  72. memset(&hint, 0, sizeof(hint));
  73. hint.ai_family = AF_UNSPEC;
  74. hint.ai_socktype = SOCK_STREAM;
  75. int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
  76. if (ret != 0) {
  77. fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
  78. return false;
  79. }
  80. bool ok = false;
  81. char buf[256];
  82. *out_sock =
  83. socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  84. if (*out_sock < 0) {
  85. perror("socket");
  86. goto out;
  87. }
  88. switch (result->ai_family) {
  89. case AF_INET: {
  90. struct sockaddr_in *sin =
  91. reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
  92. fprintf(stderr, "Connecting to %s:%d\n",
  93. inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
  94. ntohs(sin->sin_port));
  95. break;
  96. }
  97. case AF_INET6: {
  98. struct sockaddr_in6 *sin6 =
  99. reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
  100. fprintf(stderr, "Connecting to [%s]:%d\n",
  101. inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
  102. ntohs(sin6->sin6_port));
  103. break;
  104. }
  105. }
  106. if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
  107. perror("connect");
  108. goto out;
  109. }
  110. ok = true;
  111. out:
  112. freeaddrinfo(result);
  113. return ok;
  114. }
  115. bool Accept(int *out_sock, const std::string &port) {
  116. struct sockaddr_in addr, cli_addr;
  117. socklen_t cli_addr_len = sizeof(cli_addr);
  118. memset(&addr, 0, sizeof(addr));
  119. addr.sin_family = AF_INET;
  120. addr.sin_addr.s_addr = INADDR_ANY;
  121. addr.sin_port = htons(atoi(port.c_str()));
  122. bool ok = false;
  123. int server_sock = -1;
  124. server_sock =
  125. socket(addr.sin_family, SOCK_STREAM, 0);
  126. if (server_sock < 0) {
  127. perror("socket");
  128. goto out;
  129. }
  130. if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  131. perror("connect");
  132. goto out;
  133. }
  134. listen(server_sock, 1);
  135. *out_sock = accept(server_sock, (struct sockaddr*)&cli_addr, &cli_addr_len);
  136. ok = true;
  137. out:
  138. closesocket(server_sock);
  139. return ok;
  140. }
  141. void PrintConnectionInfo(const SSL *ssl) {
  142. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  143. fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
  144. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_get_name(cipher));
  145. fprintf(stderr, " Secure renegotiation: %s\n",
  146. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  147. }
  148. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  149. bool ok;
  150. #if defined(OPENSSL_WINDOWS)
  151. u_long arg = is_non_blocking;
  152. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  153. #else
  154. int flags = fcntl(sock, F_GETFL, 0);
  155. if (flags < 0) {
  156. return false;
  157. }
  158. if (is_non_blocking) {
  159. flags |= O_NONBLOCK;
  160. } else {
  161. flags &= ~O_NONBLOCK;
  162. }
  163. ok = 0 == fcntl(sock, F_SETFL, flags);
  164. #endif
  165. if (!ok) {
  166. fprintf(stderr, "Failed to set socket non-blocking.\n");
  167. }
  168. return ok;
  169. }
  170. // PrintErrorCallback is a callback function from OpenSSL's
  171. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  172. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  173. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  174. return 1;
  175. }
  176. bool TransferData(SSL *ssl, int sock) {
  177. bool stdin_open = true;
  178. fd_set read_fds;
  179. FD_ZERO(&read_fds);
  180. if (!SocketSetNonBlocking(sock, true)) {
  181. return false;
  182. }
  183. for (;;) {
  184. if (stdin_open) {
  185. FD_SET(0, &read_fds);
  186. }
  187. FD_SET(sock, &read_fds);
  188. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  189. if (ret <= 0) {
  190. perror("select");
  191. return false;
  192. }
  193. if (FD_ISSET(0, &read_fds)) {
  194. uint8_t buffer[512];
  195. ssize_t n;
  196. do {
  197. n = read(0, buffer, sizeof(buffer));
  198. } while (n == -1 && errno == EINTR);
  199. if (n == 0) {
  200. FD_CLR(0, &read_fds);
  201. stdin_open = false;
  202. #if !defined(OPENSSL_WINDOWS)
  203. shutdown(sock, SHUT_WR);
  204. #else
  205. shutdown(sock, SD_SEND);
  206. #endif
  207. continue;
  208. } else if (n < 0) {
  209. perror("read from stdin");
  210. return false;
  211. }
  212. if (!SocketSetNonBlocking(sock, false)) {
  213. return false;
  214. }
  215. int ssl_ret = SSL_write(ssl, buffer, n);
  216. if (!SocketSetNonBlocking(sock, true)) {
  217. return false;
  218. }
  219. if (ssl_ret <= 0) {
  220. int ssl_err = SSL_get_error(ssl, ssl_ret);
  221. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  222. ERR_print_errors_cb(PrintErrorCallback, stderr);
  223. return false;
  224. } else if (ssl_ret != n) {
  225. fprintf(stderr, "Short write from SSL_write.\n");
  226. return false;
  227. }
  228. }
  229. if (FD_ISSET(sock, &read_fds)) {
  230. uint8_t buffer[512];
  231. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  232. if (ssl_ret < 0) {
  233. int ssl_err = SSL_get_error(ssl, ssl_ret);
  234. if (ssl_err == SSL_ERROR_WANT_READ) {
  235. continue;
  236. }
  237. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  238. ERR_print_errors_cb(PrintErrorCallback, stderr);
  239. return false;
  240. } else if (ssl_ret == 0) {
  241. return true;
  242. }
  243. ssize_t n;
  244. do {
  245. n = write(1, buffer, ssl_ret);
  246. } while (n == -1 && errno == EINTR);
  247. if (n != ssl_ret) {
  248. fprintf(stderr, "Short write to stderr.\n");
  249. return false;
  250. }
  251. }
  252. }
  253. }