-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpclientimpl.cpp
351 lines (294 loc) · 9.98 KB
/
httpclientimpl.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
* Copyright 2015–2019 Kullo GmbH
*
* This source code is licensed under the 3-clause BSD license. See LICENSE.txt
* in the root directory of this source tree for details.
*/
#ifdef _MSC_VER
// Stop MSVC from polluting the namespace with min and max macros. These
// collide with std::numeric_limits<T>::max().
#define NOMINMAX
#endif
#include "httpclient/httpclientimpl.h"
#include <cstring>
#include <limits>
#include <regex>
#include <sstream>
#include <kulloclient/http/Request.h>
#include <kulloclient/http/RequestListener.h>
#include <kulloclient/http/Response.h>
#include <kulloclient/http/ResponseError.h>
#include <kulloclient/http/ResponseListener.h>
#include <kulloclient/http/TransferProgress.h>
#include <kulloclient/util/assert.h>
#include <kulloclient/util/librarylogger.h>
#include <kulloclient/util/strings.h>
#include "httpclient/cabundle.h"
#include "httpclient/utils.h"
using namespace Kullo;
using curl::curl_easy;
using curl::curl_easy_exception;
using curl::curl_header;
using curl::curl_pair;
namespace HttpClient {
namespace {
int xferInfoCallback(
void *function,
curl_off_t dltotal,
curl_off_t dlnow,
curl_off_t ultotal,
curl_off_t ulnow)
{
// get bound progress function from ResponseListener
kulloAssert(function);
auto progressFunction = static_cast<ProgressFunctionType*>(function);
// returning non-zero cancels the request
Http::TransferProgress progress = {ulnow, ultotal, dlnow, dltotal};
auto result = (*progressFunction)(progress);
return result == Http::ProgressResult::Cancel ? 1 : 0;
}
size_t readCallback(char *buffer, size_t size, size_t nmemb, void *function)
{
// get bound read function from RequestListener
kulloAssert(function);
auto readFunction = static_cast<ReadFunctionType*>(function);
// get data from listener
auto result = (*readFunction)(size * nmemb);
kulloAssert(result.size() <= size * nmemb);
// pass data to curl
memcpy(buffer, result.data(), result.size());
return result.size();
}
size_t headerCallback(char *buffer, size_t size, size_t nmemb, void *headers)
{
// get headers vector from Result
kulloAssert(headers);
auto headersVec = static_cast<std::vector<Http::HttpHeader>*>(headers);
// get header line from curl
std::string line(buffer, size * nmemb);
const auto keyValuePair = Utils::parseHeader(line);
if (keyValuePair)
{
headersVec->emplace_back(keyValuePair->first, keyValuePair->second);
}
return line.size();
}
size_t writeCallback(char *buffer, size_t size, size_t nmemb, void *function)
{
// get bound dataReceived function from ResponseListener
kulloAssert(function);
auto dataReceivedFunction = static_cast<WriteFunctionType*>(function);
// wrap data from curl in vector
std::vector<uint8_t> data(size * nmemb);
memcpy(data.data(), buffer, size * nmemb);
// pass data to listener
(*dataReceivedFunction)(data);
return data.size();
}
size_t noopWriteCallback(char *buffer, size_t size, size_t nmemb, void *userdata)
{
(void)buffer;
(void)userdata;
return size * nmemb;
}
std::string formattedTraceback(const curl_easy_exception &exception)
{
std::ostringstream out;
bool first = true;
for (const auto &pair : exception.get_traceback())
{
if (!first) out << "\n";
first = false;
out << "'" << pair.first << "' in " << pair.second;
}
return out.str();
}
}
HttpClientImpl::HttpClientImpl(const boost::optional<std::string> &acceptLanguage)
: acceptLanguage_(acceptLanguage),
curlEasy_(new curl_easy),
requestState_(new RequestState)
{
}
HttpClientImpl::~HttpClientImpl()
{
}
Http::Response HttpClientImpl::sendRequest(const Http::Request &request,
int32_t timeoutMs,
const std::shared_ptr<Http::RequestListener> &requestListener,
const std::shared_ptr<Http::ResponseListener> &responseListener)
{
kulloAssert(timeoutMs >= 0);
Http::Response result(
boost::optional<Http::ResponseError>(),
0,
std::vector<Http::HttpHeader>());
// Disable OCSP checking to prevents Kullo from going down when the CA's
// infrastructure does
curlEasy_->add<CURLOPT_SSL_OPTIONS>(CURLSSLOPT_NO_REVOKE);
#ifdef _WIN32
// Disable ALPN which is not supported on Windows < 8.1
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa379340%28v=vs.85%29.aspx
try {
curlEasy_->add<CURLOPT_SSL_ENABLE_ALPN>(0);
} catch (...) {
// Since https://github.com/curl/curl/commit/e91e48161235272ff485ff32bd048c53af731f43,
// if HTTP2 is disabled the above call throws because curlcpp converts
// CURLE_UNKNOWN_OPTION to an exception.
}
#endif
// CA bundle
if (CaBundle::available())
{
curlEasy_->add<CURLOPT_CAINFO>(CaBundle::path().c_str());
}
// timeout
if (timeoutMs > 0)
{
curlEasy_->add<CURLOPT_TIMEOUT_MS>(timeoutMs);
}
// URL
curlEasy_->add<CURLOPT_URL>(request.url.c_str());
// request headers
addHeaders(request.headers);
// register callbacks
setMethod(request.method, requestListener.get());
addResponseHeaderCallback(result.headers);
if (responseListener)
{
addCancelCallback(responseListener.get());
addResponseBodyCallback(responseListener.get());
}
else
{
// disable printing responses to stdout
curlEasy_->add<CURLOPT_WRITEFUNCTION>(&noopWriteCallback);
}
// request more specific error messages from cURL
curlErrorBuffer_[0] = '\0';
curlEasy_->add<CURLOPT_ERRORBUFFER>(curlErrorBuffer_);
try {
curlEasy_->perform();
result.statusCode = *curlEasy_->get_info<long>(CURLINFO_RESPONSE_CODE);
}
catch (curl_easy_exception &ex)
{
switch (ex.get_code())
{
case CURLE_ABORTED_BY_CALLBACK:
result.error = Http::ResponseError::Canceled;
break;
case CURLE_OPERATION_TIMEDOUT:
result.error = Http::ResponseError::Timeout;
Log.e() << "HTTP exception: " << formattedTraceback(ex) << "\n"
<< "Details: " << curlErrorBuffer_;
break;
default:
result.error = Http::ResponseError::NetworkError;
Log.e() << "HTTP exception: " << formattedTraceback(ex) << "\n"
<< "Details: " << curlErrorBuffer_;
}
}
curlEasy_->reset();
requestState_.reset(new RequestState);
return result;
}
void HttpClientImpl::addHeaders(const std::vector<Http::HttpHeader> &headers)
{
bool acceptLanguageSet = false;
requestState_->reqHeaders.reset(new curl_header());
for (const auto &hdr : headers)
{
requestState_->reqHeaders->add(hdr.key + ": " + hdr.value);
auto lcaseKey = Util::Strings::toLower(hdr.key);
if (lcaseKey == "content-length")
{
curlEasy_->add<CURLOPT_INFILESIZE>(std::stol(hdr.value));
}
else if (lcaseKey == "accept-language")
{
acceptLanguageSet = true;
}
}
if (!acceptLanguageSet && acceptLanguage_)
{
requestState_->reqHeaders->add("Accept-Language: " + *acceptLanguage_);
}
curlEasy_->add(curl_pair<CURLoption, curl_header>(
CURLOPT_HTTPHEADER, *requestState_->reqHeaders));
}
void HttpClientImpl::addCancelCallback(Http::ResponseListener *respL)
{
kulloAssert(respL);
requestState_->progressFunction.reset(
new ProgressFunctionType(
std::bind(
&Http::ResponseListener::progressed,
respL,
std::placeholders::_1
)));
curlEasy_->add<CURLOPT_NOPROGRESS>(0);
curlEasy_->add<CURLOPT_XFERINFOFUNCTION>(&xferInfoCallback);
curlEasy_->add<CURLOPT_XFERINFODATA>(requestState_->progressFunction.get());
}
void HttpClientImpl::addRequestBodyCallback(Http::RequestListener *reqL)
{
kulloAssert(reqL);
requestState_->reqBodyReadFunction.reset(
new ReadFunctionType(
std::bind(
&Http::RequestListener::read,
reqL,
std::placeholders::_1
)));
curlEasy_->add<CURLOPT_READFUNCTION>(&readCallback);
curlEasy_->add<CURLOPT_READDATA>(requestState_->reqBodyReadFunction.get());
}
void HttpClientImpl::setMethod(
Http::HttpMethod method, Http::RequestListener *reqL)
{
switch (method)
{
case Http::HttpMethod::Get:
curlEasy_->add<CURLOPT_HTTPGET>(1);
break;
case Http::HttpMethod::Put:
curlEasy_->add<CURLOPT_UPLOAD>(1);
addRequestBodyCallback(reqL);
break;
case Http::HttpMethod::Post:
curlEasy_->add<CURLOPT_UPLOAD>(1);
curlEasy_->add<CURLOPT_CUSTOMREQUEST>("POST");
addRequestBodyCallback(reqL);
break;
case Http::HttpMethod::Patch:
curlEasy_->add<CURLOPT_UPLOAD>(1);
curlEasy_->add<CURLOPT_CUSTOMREQUEST>("PATCH");
addRequestBodyCallback(reqL);
break;
case Http::HttpMethod::Delete:
curlEasy_->add<CURLOPT_HTTPGET>(1);
curlEasy_->add<CURLOPT_CUSTOMREQUEST>("DELETE");
break;
}
}
void HttpClientImpl::addResponseHeaderCallback(
std::vector<Http::HttpHeader> &headers)
{
curlEasy_->add<CURLOPT_HEADERFUNCTION>(&headerCallback);
curlEasy_->add<CURLOPT_HEADERDATA>(&headers);
}
void HttpClientImpl::addResponseBodyCallback(Http::ResponseListener *respL)
{
kulloAssert(respL);
requestState_->respBodyWriteFunction.reset(
new WriteFunctionType(
std::bind(
&Http::ResponseListener::dataReceived,
respL,
std::placeholders::_1
)));
curlEasy_->add<CURLOPT_WRITEFUNCTION>(&writeCallback);
curlEasy_->add<CURLOPT_WRITEDATA>(requestState_->respBodyWriteFunction.get());
}
}