int getPages(const char* host_addr, const int host_port, const char* pObject) { WSADATA wsaData; WSAStartup(MAKEWORD(2, 0), &wsaData); SOCKET sockfd; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { DebugMsg("Socket Error: %s", strerror(errno)); return -1; } struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(host_port); server_addr.sin_addr.s_addr = inet_addr(host_addr); if (connect(sockfd, (struct sockaddr *) (&server_addr), sizeof(struct sockaddr)) == -1) { DebugMsg("Connect Error:%s", strerror(errno)); return -1; } SSL *ssl; SSL_CTX *ctx; // SSL initialize SSL_library_init(); SSL_load_error_strings(); ctx = SSL_CTX_new(SSLv23_client_method()); if (ctx == NULL) { DebugMsg("SSL CTX new failed!"); return -1; } ssl = SSL_new(ctx); if (ssl == NULL) { DebugMsg("SSL new failed!"); return -1; } // link socket & SSL int ret = SSL_set_fd(ssl, sockfd); if (ret == 0) { DebugMsg("SSL link socket failed!"); return -1; } RAND_poll(); while (RAND_status() == 0) { unsigned short rand_ret = rand() % 65536; RAND_seed(&rand_ret, sizeof(rand_ret)); } // SSL connect ret = SSL_connect(ssl); if (ret != 1) { DebugMsg("SSL connect failed!"); return -1; } char getRequest[1024]; sprintf(getRequest, "GET %s HTTP/1.0\r\nHost: %s\r\nCookie: %s\r\n\r\n", pObject, "10.18.4.80", cookie); // send https request int totalsend = 0; int requestLen = strlen(getRequest); while (totalsend < requestLen) { int send = SSL_write(ssl, getRequest + totalsend, requestLen - totalsend); if (send == -1) { DebugMsg("SSL send failed!"); } totalsend += send; DebugMsg("%d bytes send OK!", totalsend); } // receive https response int responseLen = 0; int i = 0; char buffer[8]; memset(buffer, 0, 8); char returnBuffer[1024]; memset(returnBuffer, 0, 1024); int p = 0; while ((responseLen = SSL_read(ssl, buffer, 1)) == 1 && p<1024) { returnBuffer[p] = buffer[0]; p++; if (i < 4) { if (buffer[0] == '\r' || buffer[0] == '\n') i++; else i = 0; } } DebugMsg("%s", returnBuffer); // shutdown community ret = SSL_shutdown(ssl); if (ret != 1) { DebugMsg("SSL shutdown failed!"); return -1; } SSL_free(ssl); SSL_CTX_free(ctx); ERR_free_strings(); closesocket(sockfd); WSACleanup(); return 0; }
|