在C

时间:2017-01-24 20:16:13

标签: c ssl https proxy openssl

我开发了一个程序,我在多线程中发出HTTPS请求。 一切正常,但我需要完全使用代理。

目前,我有HTTPS请求的这个功能:

  struct string_builder* webrequest(const char* DEST_IP, const int DEST_PORT, const char* REQUEST) {
  // Initialize ssl libraries and error messages

  SSL_CTX *ssl_ctx = SSL_CTX_new (SSLv23_client_method());
  // create a socket
  int sockfd = socket(PF_INET, SOCK_STREAM, 0);
  if (sockfd == -1) {
    perror("Unable to create socket");
    return NULL;
  }
  // destination info
  struct sockaddr_in dest_addr;
  dest_addr.sin_family = AF_INET;       // host byte order
  dest_addr.sin_port = htons(DEST_PORT);    // short, network port
  dest_addr.sin_addr.s_addr = inet_addr(DEST_IP); // destination address
  memset(&(dest_addr.sin_zero), '\0', 8);         // zero out the rest of the struct

  // connect to the server
  int status = connect(sockfd, (struct sockaddr*) &dest_addr, sizeof(struct sockaddr_in));
  if (status == -1) {
    perror("Unable to connect to the server");
    close(sockfd);
    return NULL;
  }
  // create SSL connection and attach it to the socket
  SSL *conn = SSL_new(ssl_ctx);
  SSL_set_fd(conn, sockfd);
  SSL_connect(conn);

  // send an encrypted message
  ssize_t sendsize = SSL_write(conn, REQUEST, strlen(REQUEST));
  if (sendsize == -1) {
    perror("Unable to send to the server");
    {
      char *buf = malloc(sizeof(char) * 256);;
      u_long err;

      while ((err = ERR_get_error()) != 0) {
        ERR_error_string_n(err, buf, sizeof(buf));
        printf("*** %s\n", buf);
      }
      free(buf);
    }
    SSL_shutdown(conn);
    ERR_free_strings();
    ERR_remove_state(0);
    SSL_CTX_free(ssl_ctx);
    close(sockfd);
    return NULL;
  }
  size_t i = 1;
  struct string_builder *result = NULL;
  result = string_builder_init();
  while (i) {
    // receive the response
    const int RESPONSE_SIZE = 512;
    char *response = malloc(sizeof(char)*512);
    ssize_t recsize = SSL_read(conn, response, RESPONSE_SIZE-1);
    if (recsize == -1) {
      perror("Unable to send to the server");
      SSL_shutdown(conn);
      ERR_free_strings();
      ERR_remove_state(0);
      SSL_CTX_free(ssl_ctx);
      close(sockfd);
      return NULL;
    }
    response[recsize] = '\0';
    if (recsize <= 0)
    {
      free(response);
      break;
    }
    else if (i > 2 && recsize > 6)
    {
      string_builder_pushs(result, response);
    }
    free(response);
    ++i;
  }
  // close ssl connection
    SSL_shutdown(conn);
    ERR_free_strings();
    ERR_remove_state(0);
    SSL_free(conn);  
    SSL_CTX_free(ssl_ctx);
  close(sockfd);
  return result;
}

我对socket,openssl库使用socket / send / recv函数来处理HTTPS请求。 所有工作都很好,没有代理没有泄漏,但当我尝试使用“CONNECT命令”连接到谷歌(和套接字连接到代理主机)时,我想发送时出错。

提前致谢。

0 个答案:

没有答案