-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTTPSSession.cpp
227 lines (211 loc) · 5.39 KB
/
HTTPSSession.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#include "HTTPSSession.h"
#include "HTTPMessage.h"
#include "HTTPResponseMessage.h"
#include "HTTPRequestMessage.h"
#include "HTTPMethod.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <fstream>
#define BUFFER_SIZE 100000
/**
* callback to record TLS key
*/
void ctx_callback(const SSL *ssl, const char *line)
{
std::ofstream file;
file.open("log.key");
file << line;
file.close();
}
/**
* Create HTTPS Session object
*/
HTTPSSession::HTTPSSession(const char *host, const char *port)
{
this->host = host;
this->port = port;
this->socket = connectToHost();
if (this->socket < 0)
{
throw std::invalid_argument("Error in port creation");
}
SSL_library_init();
this->ctx = InitCTX();
SSL_CTX_set_keylog_callback(ctx, ctx_callback);
this->ssl = SSL_new(ctx);
SSL_set_fd(this->ssl, this->socket);
if (SSL_connect(ssl) == -1)
{
ERR_print_errors_fp(stderr);
throw std::invalid_argument("Error in SSL Connection");
}
};
/**
* Delete HTTP Session object
*/
HTTPSSession::~HTTPSSession()
{
SSL_free(this->ssl);
SSL_CTX_free(this->ctx);
close(this->socket);
}
/**
* Create socket connection with Host
*/
int HTTPSSession::connectToHost()
{
struct addrinfo hints, *addr;
int sock, err;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
if ((err = getaddrinfo(this->host, this->port, &hints, &addr)) != 0)
{
std::cout << "Error" << err << ": " << gai_strerror(err) << std::endl;
return -1;
}
sock = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (sock < 0)
{
perror("socket");
return -1;
}
if (connect(sock, addr->ai_addr, addr->ai_addrlen) != 0)
{
perror("connect");
return -1;
}
return sock;
}
/**
* Initialize SSL certificate
*/
SSL_CTX *HTTPSSession::InitCTX(void)
{
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
const SSL_METHOD *method = TLS_client_method();
SSL_CTX *ctx = SSL_CTX_new(method);
if (ctx == NULL)
{
ERR_print_errors_fp(stderr);
}
return ctx;
}
/**
* Send Get request to Host
*/
HTTPResponseMessage HTTPSSession::get(std::string path)
{
HTTPMessage::headerMap headers;
HTTPRequestMessage request(1.1, HTTPMethod::Get, path, headers);
return this->send(request);
}
/**
* Send Post request to Host
*/
HTTPResponseMessage HTTPSSession::send(HTTPRequestMessage request)
{
int rc;
char buffer[BUFFER_SIZE];
std::ostringstream input;
memset(buffer, 0, sizeof(buffer));
request.setHeader("HOST", this->host);
request.setHeader("USER-AGENT", "Webcrawler/TS");
if (!this->cookies.empty())
{
request.setHeader("Cookie", this->sendCookies());
}
std::string output = request.format();
rc = SSL_write(ssl, output.c_str(), output.length());
while (rc < output.length())
{
rc += SSL_write(ssl, (char *)output.c_str() + rc, output.length() - rc);
}
rc = 0;
while (input.str().find("\r\n\r\n") == std::string::npos)
{
rc += SSL_read(ssl, buffer + rc, 1);
input << buffer[rc - 1];
}
HTTPResponseMessage response(buffer);
char *content = buffer + rc;
if (response.getHeaders().count("Content-Length"))
{
rc = 0;
while (rc < std::stoi(response.getHeaders().find("Content-Length")->second))
{
rc += SSL_read(ssl, content + rc, std::stoi(response.getHeaders().find("Content-Length")->second) - rc);
}
}
std::string data(content);
response.setData(data);
this->updateSession(response);
if (response.getStatus() == 302 || response.getStatus() == 301)
{
request.setPath(response.getHeaders().find("Location")->second);
response = this->send(request);
}
return response;
}
/**
* Update session state
*/
void HTTPSSession::updateSession(HTTPResponseMessage response)
{
for (auto &[key, value] : response.getHeaders())
{
if (key == "Set-Cookie")
{
this->setCookie(value);
}
}
}
/**
* Set value of cookie
*/
void HTTPSSession::setCookie(std::string cookie)
{
std::string key, value;
int stringPointer;
stringPointer = cookie.find("=");
key = cookie.substr(0, stringPointer);
cookie.erase(0, stringPointer + 1);
stringPointer = cookie.find(";");
value = cookie.substr(0, stringPointer);
this->cookies[key] = value;
}
/**
* Format cookies in string to be sent in headers
*/
std::string HTTPSSession::sendCookies()
{
std::ostringstream buffer;
for (auto &[key, value] : this->cookies)
{
buffer << key << "=" << value << "; ";
}
std::string output = buffer.str();
output.erase(output.rfind(";"));
return output;
}
/**
* Send Post request to Host
*/
HTTPResponseMessage HTTPSSession::post(std::string path, std::string data, std::string type)
{
HTTPMessage::headerMap headers;
headers.insert(std::make_pair("Content-Length", std::to_string(data.length())));
headers.insert(std::make_pair("Content-Type", type));
HTTPRequestMessage request(1.1, HTTPMethod::Post, path, headers, data);
return this->send(request);
}