Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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