Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

312 рядки
7.9 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 <stddef.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <sys/types.h>
  22. #if !defined(OPENSSL_WINDOWS)
  23. #include <arpa/inet.h>
  24. #include <fcntl.h>
  25. #include <netdb.h>
  26. #include <netinet/in.h>
  27. #include <sys/select.h>
  28. #include <sys/socket.h>
  29. #include <unistd.h>
  30. #else
  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, " Resumed session: %s\n",
  145. SSL_session_reused(ssl) ? "yes" : "no");
  146. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_get_name(cipher));
  147. fprintf(stderr, " Secure renegotiation: %s\n",
  148. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  149. const uint8_t *next_proto;
  150. unsigned next_proto_len;
  151. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  152. fprintf(stderr, " Next protocol negotiated: %.*s\n", next_proto_len,
  153. next_proto);
  154. const uint8_t *alpn;
  155. unsigned alpn_len;
  156. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  157. fprintf(stderr, " ALPN protocol: %.*s\n", alpn_len, alpn);
  158. }
  159. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  160. bool ok;
  161. #if defined(OPENSSL_WINDOWS)
  162. u_long arg = is_non_blocking;
  163. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  164. #else
  165. int flags = fcntl(sock, F_GETFL, 0);
  166. if (flags < 0) {
  167. return false;
  168. }
  169. if (is_non_blocking) {
  170. flags |= O_NONBLOCK;
  171. } else {
  172. flags &= ~O_NONBLOCK;
  173. }
  174. ok = 0 == fcntl(sock, F_SETFL, flags);
  175. #endif
  176. if (!ok) {
  177. fprintf(stderr, "Failed to set socket non-blocking.\n");
  178. }
  179. return ok;
  180. }
  181. // PrintErrorCallback is a callback function from OpenSSL's
  182. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  183. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  184. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  185. return 1;
  186. }
  187. bool TransferData(SSL *ssl, int sock) {
  188. bool stdin_open = true;
  189. fd_set read_fds;
  190. FD_ZERO(&read_fds);
  191. if (!SocketSetNonBlocking(sock, true)) {
  192. return false;
  193. }
  194. for (;;) {
  195. if (stdin_open) {
  196. FD_SET(0, &read_fds);
  197. }
  198. FD_SET(sock, &read_fds);
  199. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  200. if (ret <= 0) {
  201. perror("select");
  202. return false;
  203. }
  204. if (FD_ISSET(0, &read_fds)) {
  205. uint8_t buffer[512];
  206. ssize_t n;
  207. do {
  208. n = read(0, buffer, sizeof(buffer));
  209. } while (n == -1 && errno == EINTR);
  210. if (n == 0) {
  211. FD_CLR(0, &read_fds);
  212. stdin_open = false;
  213. #if !defined(OPENSSL_WINDOWS)
  214. shutdown(sock, SHUT_WR);
  215. #else
  216. shutdown(sock, SD_SEND);
  217. #endif
  218. continue;
  219. } else if (n < 0) {
  220. perror("read from stdin");
  221. return false;
  222. }
  223. if (!SocketSetNonBlocking(sock, false)) {
  224. return false;
  225. }
  226. int ssl_ret = SSL_write(ssl, buffer, n);
  227. if (!SocketSetNonBlocking(sock, true)) {
  228. return false;
  229. }
  230. if (ssl_ret <= 0) {
  231. int ssl_err = SSL_get_error(ssl, ssl_ret);
  232. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  233. ERR_print_errors_cb(PrintErrorCallback, stderr);
  234. return false;
  235. } else if (ssl_ret != n) {
  236. fprintf(stderr, "Short write from SSL_write.\n");
  237. return false;
  238. }
  239. }
  240. if (FD_ISSET(sock, &read_fds)) {
  241. uint8_t buffer[512];
  242. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  243. if (ssl_ret < 0) {
  244. int ssl_err = SSL_get_error(ssl, ssl_ret);
  245. if (ssl_err == SSL_ERROR_WANT_READ) {
  246. continue;
  247. }
  248. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  249. ERR_print_errors_cb(PrintErrorCallback, stderr);
  250. return false;
  251. } else if (ssl_ret == 0) {
  252. return true;
  253. }
  254. ssize_t n;
  255. do {
  256. n = write(1, buffer, ssl_ret);
  257. } while (n == -1 && errno == EINTR);
  258. if (n != ssl_ret) {
  259. fprintf(stderr, "Short write to stderr.\n");
  260. return false;
  261. }
  262. }
  263. }
  264. }