-
Notifications
You must be signed in to change notification settings - Fork 372
/
connection.cc
718 lines (651 loc) · 19.6 KB
/
connection.cc
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
/**
* @file connection.cpp
* @brief implementation of the connection class
* @author Daniel Schauenberg <d@unwiredcouch.com>
*/
#include "restclient-cpp/connection.h"
#include <curl/curl.h>
#include <cstring>
#include <string>
#include <iostream>
#include <map>
#include <stdexcept>
#include <utility>
#include "restclient-cpp/restclient.h"
#include "restclient-cpp/helpers.h"
#include "restclient-cpp/version.h"
/**
* @brief constructor for the Connection object
*
* @param baseUrl - base URL for the connection to use
*
*/
RestClient::Connection::Connection(const std::string& baseUrl)
: headerFields(), lastRequest() {
this->curlHandle = curl_easy_init();
if (!this->curlHandle) {
throw std::runtime_error("Couldn't initialize curl handle");
}
this->baseUrl = baseUrl;
this->timeout = 0;
this->followRedirects = false;
this->maxRedirects = -1l;
this->noSignal = false;
this->progressFn = NULL;
this->progressFnData = NULL;
this->writeCallback = RestClient::Helpers::write_callback;
this->verifyPeer = true;
}
/**
* @brief Getter used to ensure NULL handle is not used.
*
*/
CURL* RestClient::Connection::getCurlHandle() {
if (this->curlHandle) {
return this->curlHandle;
}
throw std::runtime_error("Connection terminated");
}
void RestClient::Connection::Terminate() {
if (this->curlHandle) {
curl_easy_cleanup(this->curlHandle);
}
this->curlHandle = NULL;
}
RestClient::Connection::~Connection() {
this->Terminate();
}
// getters/setters
/**
* @brief get diagnostic information about the connection object
*
* @return RestClient::Connection::Info struct
*/
RestClient::Connection::Info
RestClient::Connection::GetInfo() {
RestClient::Connection::Info ret;
ret.baseUrl = this->baseUrl;
ret.headers = this->GetHeaders();
ret.timeout = this->timeout;
ret.followRedirects = this->followRedirects;
ret.maxRedirects = this->maxRedirects;
ret.noSignal = this->noSignal;
ret.progressFn = this->progressFn;
ret.progressFnData = this->progressFnData;
ret.basicAuth.username = this->basicAuth.username;
ret.basicAuth.password = this->basicAuth.password;
ret.customUserAgent = this->customUserAgent;
ret.lastRequest = this->lastRequest;
ret.certPath = this->certPath;
ret.certType = this->certType;
ret.keyPath = this->keyPath;
ret.keyPassword = this->keyPassword;
ret.uriProxy = this->uriProxy;
ret.unixSocketPath = this->unixSocketPath;
return ret;
}
/**
* @brief append a header to the internal map
*
* @param key for the header field
* @param value for the header field
*
*/
void
RestClient::Connection::AppendHeader(const std::string& key,
const std::string& value) {
this->headerFields[key] = value;
}
/**
* @brief set the custom headers map. This will replace the currently
* configured headers with the provided ones. If you want to add additional
* headers, use AppendHeader()
*
* @param headers to set
*/
void
RestClient::Connection::SetHeaders(RestClient::HeaderFields headers) {
#if __cplusplus >= 201103L
this->headerFields = std::move(headers);
#else
this->headerFields = headers;
#endif
}
/**
* @brief get all custom headers set on the connection
*
* @returns a RestClient::HeaderFields map containing the custom headers
*/
RestClient::HeaderFields
RestClient::Connection::GetHeaders() {
return this->headerFields;
}
/**
* @brief configure whether to follow redirects on this connection
*
* @param follow - boolean whether to follow redirects
* @param maxRedirects - int indicating the maximum number of redirect to follow (-1 unlimited, default)
*/
void
RestClient::Connection::FollowRedirects(bool follow, int maxRedirects) {
this->followRedirects = follow;
this->maxRedirects = maxRedirects;
}
/**
* @brief set custom user agent for connection. This gets prepended to the
* default restclient-cpp/RESTCLIENT_VERSION string
*
* @param userAgent - custom userAgent prefix
*
*/
void
RestClient::Connection::SetUserAgent(const std::string& userAgent) {
this->customUserAgent = userAgent;
}
/**
* @brief set custom Certificate Authority (CA) path
*
* @param caInfoFilePath - The path to a file holding the certificates used to
* verify the peer with. See CURLOPT_CAINFO
*
*/
void
RestClient::Connection::SetCAInfoFilePath(const std::string& caInfoFilePath) {
this->caInfoFilePath = caInfoFilePath;
}
/**
* @brief get the user agent to add to the request
*
* @return user agent as std::string
*/
std::string
RestClient::Connection::GetUserAgent() {
std::string prefix;
if (this->customUserAgent.length() > 0) {
prefix = this->customUserAgent + " ";
}
return std::string(prefix + "restclient-cpp/" + RESTCLIENT_VERSION);
}
/**
* @brief set timeout for connection
*
* @param seconds - timeout in seconds
*
*/
void
RestClient::Connection::SetTimeout(int seconds) {
this->timeout = seconds;
}
/**
* @brief switch off curl signals for connection (see CURLOPT_NONSIGNAL). By
* default signals are used, except when timeout is given.
*
* @param no - set to true switches signals off
*
*/
void
RestClient::Connection::SetNoSignal(bool no) {
this->noSignal = no;
}
/**
* @brief set file progress callback function
*
* @param callback function pointer
*
*/
void
RestClient::Connection::SetFileProgressCallback(curl_progress_callback
progressFn) {
this->progressFn = progressFn;
}
/**
* @brief set file progress callback data
*
* @param callback data pointer
*
*/
void
RestClient::Connection::SetFileProgressCallbackData(void* data) {
this->progressFnData = data;
}
/**
* @brief set username and password for basic auth
*
* @param username
* @param password
*
*/
void
RestClient::Connection::SetBasicAuth(const std::string& username,
const std::string& password) {
this->basicAuth.username = username;
this->basicAuth.password = password;
}
/**
* @brief set certificate path
*
* @param path to certificate file
*
*/
void
RestClient::Connection::SetCertPath(const std::string& cert) {
this->certPath = cert;
}
/**
* @brief set certificate type
*
* @param certificate type (e.g. "PEM" or "DER")
*
*/
void
RestClient::Connection::SetCertType(const std::string& certType) {
this->certType = certType;
}
/**
* @brief set key path
*
* @param path to key file
*
*/
void
RestClient::Connection::SetKeyPath(const std::string& keyPath) {
this->keyPath = keyPath;
}
/**
* @brief set key password
*
* @param key password
*
*/
void
RestClient::Connection::SetKeyPassword(const std::string& keyPassword) {
this->keyPassword = keyPassword;
}
/**
* @brief set SSL peer verification flag
*
* @param boolean (default is true)
*
*/
void
RestClient::Connection::SetVerifyPeer(bool verifyPeer) {
this->verifyPeer = verifyPeer;
}
/**
* @brief set HTTP proxy address and port
*
* @param proxy address with port number
*
*/
void
RestClient::Connection::SetProxy(const std::string& uriProxy) {
std::string uriProxyUpper = uriProxy;
// check if the provided address is prefixed with "http"
std::transform(uriProxyUpper.begin(), uriProxyUpper.end(),
uriProxyUpper.begin(), ::toupper);
if ((uriProxy.length() > 0) && (uriProxyUpper.compare(0, 4, "HTTP") != 0)) {
this->uriProxy = "http://" + uriProxy;
} else {
this->uriProxy = uriProxy;
}
}
/**
* @brief set custom Unix socket path for connection.
* See https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html
*
* @param unixSocketPath - path to Unix socket (ex: /var/run/docker.sock)
*
*/
void
RestClient::Connection::SetUnixSocketPath(const std::string& unixSocketPath) {
this->unixSocketPath = unixSocketPath;
}
/**
* @brief set callback for writing received data. Last parameter
* to callback (userdata) points to a RestClient::Response. For details,
* see https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
*
* @param write_callback - callback to handle received data
*
*/
void
RestClient::Connection::SetWriteFunction(RestClient::WriteCallback
writeCallback) {
this->writeCallback = writeCallback;
}
/**
* @brief helper function to get called from the actual request methods to
* prepare the curlHandle for transfer with generic options, perform the
* request and record some stats from the last request and then reset the
* handle with curl_easy_reset to its default state. This will keep things
* like connections and session ID intact but makes sure you can change
* parameters on the object for another request.
*
* @param uri URI to query
*
* @return Reference to the Response struct that should be filled
*/
RestClient::Response
RestClient::Connection::performCurlRequest(const std::string& uri) {
// init return type
RestClient::Response ret = {};
performCurlRequest(uri, &ret);
return ret;
}
/**
* @brief helper function to get called from the actual request methods to
* prepare the curlHandle for transfer with generic options, perform the
* request and record some stats from the last request and then reset the
* handle with curl_easy_reset to its default state. This will keep things
* like connections and session ID intact but makes sure you can change
* parameters on the object for another request.
*
* @param uri URI to query
* @param ret Reference to the response struct that should be filled
*
* @return reference to response struct for chaining
*/
RestClient::Response*
RestClient::Connection::performCurlRequest(const std::string& uri,
RestClient::Response* ret) {
// init return type
ret->body.clear();
ret->code = 0;
ret->headers.clear();
std::string url = std::string(this->baseUrl + uri);
std::string headerString;
CURLcode res = CURLE_OK;
curl_slist* headerList = NULL;
/** set query URL */
curl_easy_setopt(getCurlHandle(), CURLOPT_URL, url.c_str());
/** set callback function */
curl_easy_setopt(getCurlHandle(), CURLOPT_WRITEFUNCTION,
this->writeCallback);
/** set data object to pass to callback function */
curl_easy_setopt(getCurlHandle(), CURLOPT_WRITEDATA, ret);
/** set the header callback function */
curl_easy_setopt(getCurlHandle(), CURLOPT_HEADERFUNCTION,
Helpers::header_callback);
/** callback object for headers */
curl_easy_setopt(getCurlHandle(), CURLOPT_HEADERDATA, ret);
/** set http headers */
for (HeaderFields::const_iterator it = this->headerFields.begin();
it != this->headerFields.end(); ++it) {
headerString = it->first;
headerString += ": ";
headerString += it->second;
headerList = curl_slist_append(headerList, headerString.c_str());
}
curl_easy_setopt(getCurlHandle(), CURLOPT_HTTPHEADER,
headerList);
// set basic auth if configured
if (this->basicAuth.username.length() > 0) {
std::string authString = std::string(this->basicAuth.username + ":" +
this->basicAuth.password);
curl_easy_setopt(getCurlHandle(), CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(getCurlHandle(), CURLOPT_USERPWD, authString.c_str());
}
/** set error buffer */
curl_easy_setopt(getCurlHandle(), CURLOPT_ERRORBUFFER,
this->curlErrorBuf);
/** set user agent */
curl_easy_setopt(getCurlHandle(), CURLOPT_USERAGENT,
this->GetUserAgent().c_str());
// set timeout
if (this->timeout) {
curl_easy_setopt(getCurlHandle(), CURLOPT_TIMEOUT, this->timeout);
// dont want to get a sig alarm on timeout
curl_easy_setopt(getCurlHandle(), CURLOPT_NOSIGNAL, 1);
}
// set follow redirect
if (this->followRedirects == true) {
curl_easy_setopt(getCurlHandle(), CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(getCurlHandle(), CURLOPT_MAXREDIRS,
static_cast<int64_t>(this->maxRedirects));
}
if (this->noSignal) {
// multi-threaded and prevent entering foreign signal handler (e.g. JNI)
curl_easy_setopt(getCurlHandle(), CURLOPT_NOSIGNAL, 1);
}
// set file progress callback
if (this->progressFn) {
curl_easy_setopt(getCurlHandle(), CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(getCurlHandle(),
CURLOPT_PROGRESSFUNCTION,
this->progressFn);
if (this->progressFnData) {
curl_easy_setopt(getCurlHandle(),
CURLOPT_PROGRESSDATA,
this->progressFnData);
} else {
curl_easy_setopt(getCurlHandle(),
CURLOPT_PROGRESSDATA,
this);
}
}
// if provided, supply CA path
if (!this->caInfoFilePath.empty()) {
curl_easy_setopt(getCurlHandle(), CURLOPT_CAINFO,
this->caInfoFilePath.c_str());
}
// set cert file path
if (!this->certPath.empty()) {
curl_easy_setopt(getCurlHandle(), CURLOPT_SSLCERT,
this->certPath.c_str());
}
// set cert type
if (!this->certType.empty()) {
curl_easy_setopt(getCurlHandle(), CURLOPT_SSLCERTTYPE,
this->certType.c_str());
}
// set key file path
if (!this->keyPath.empty()) {
curl_easy_setopt(getCurlHandle(), CURLOPT_SSLKEY,
this->keyPath.c_str());
}
// set key password
if (!this->keyPassword.empty()) {
curl_easy_setopt(getCurlHandle(), CURLOPT_KEYPASSWD,
this->keyPassword.c_str());
}
// set peer verification
if (!this->verifyPeer) {
curl_easy_setopt(getCurlHandle(), CURLOPT_SSL_VERIFYPEER,
this->verifyPeer);
}
// set web proxy address
if (!this->uriProxy.empty()) {
curl_easy_setopt(getCurlHandle(), CURLOPT_PROXY,
uriProxy.c_str());
curl_easy_setopt(getCurlHandle(), CURLOPT_HTTPPROXYTUNNEL,
1L);
}
// set Unix socket path, if requested
if (!this->unixSocketPath.empty()) {
curl_easy_setopt(getCurlHandle(), CURLOPT_UNIX_SOCKET_PATH,
this->unixSocketPath.c_str());
}
res = curl_easy_perform(getCurlHandle());
this->lastRequest.curlCode = res;
if (res != CURLE_OK) {
int retCode = res;
if (retCode > 99) {
retCode = -1;
}
ret->code = retCode;
ret->body = curl_easy_strerror(res);
} else {
int64_t http_code = 0;
curl_easy_getinfo(getCurlHandle(), CURLINFO_RESPONSE_CODE, &http_code);
ret->code = static_cast<int>(http_code);
}
this->lastRequest.curlError = std::string(this->curlErrorBuf);
curl_easy_getinfo(getCurlHandle(), CURLINFO_TOTAL_TIME,
&this->lastRequest.totalTime);
curl_easy_getinfo(getCurlHandle(), CURLINFO_NAMELOOKUP_TIME,
&this->lastRequest.nameLookupTime);
curl_easy_getinfo(getCurlHandle(), CURLINFO_CONNECT_TIME,
&this->lastRequest.connectTime);
curl_easy_getinfo(getCurlHandle(), CURLINFO_APPCONNECT_TIME,
&this->lastRequest.appConnectTime);
curl_easy_getinfo(getCurlHandle(), CURLINFO_PRETRANSFER_TIME,
&this->lastRequest.preTransferTime);
curl_easy_getinfo(getCurlHandle(), CURLINFO_STARTTRANSFER_TIME,
&this->lastRequest.startTransferTime);
curl_easy_getinfo(getCurlHandle(), CURLINFO_REDIRECT_TIME,
&this->lastRequest.redirectTime);
curl_easy_getinfo(getCurlHandle(), CURLINFO_REDIRECT_COUNT,
&this->lastRequest.redirectCount);
// free header list
curl_slist_free_all(headerList);
// reset curl handle
curl_easy_reset(getCurlHandle());
return ret;
}
/**
* @brief HTTP GET method
*
* @param url to query
*
* @return response struct
*/
RestClient::Response
RestClient::Connection::get(const std::string& url) {
return this->performCurlRequest(url);
}
/**
* @brief HTTP GET method
*
* @param url to query
* @param response struct
*
* @return response struct ref for chaining
*/
RestClient::Response*
RestClient::Connection::get(const std::string& url,
RestClient::Response* response) {
return this->performCurlRequest(url, response);
}
/**
* @brief HTTP POST method
*
* @param url to query
* @param data HTTP POST body
*
* @return response struct
*/
RestClient::Response
RestClient::Connection::post(const std::string& url,
const std::string& data) {
/** Now specify we want to POST data */
curl_easy_setopt(getCurlHandle(), CURLOPT_POST, 1L);
/** set post fields */
curl_easy_setopt(getCurlHandle(), CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(getCurlHandle(), CURLOPT_POSTFIELDSIZE, data.size());
return this->performCurlRequest(url);
}
/**
* @brief HTTP PUT method
*
* @param url to query
* @param data HTTP PUT body
*
* @return response struct
*/
RestClient::Response
RestClient::Connection::put(const std::string& url,
const std::string& data) {
/** initialize upload object */
RestClient::Helpers::UploadObject up_obj;
up_obj.data = data.c_str();
up_obj.length = data.size();
/** Now specify we want to PUT data */
curl_easy_setopt(getCurlHandle(), CURLOPT_PUT, 1L);
curl_easy_setopt(getCurlHandle(), CURLOPT_UPLOAD, 1L);
/** set read callback function */
curl_easy_setopt(getCurlHandle(), CURLOPT_READFUNCTION,
RestClient::Helpers::read_callback);
/** set data object to pass to callback function */
curl_easy_setopt(getCurlHandle(), CURLOPT_READDATA, &up_obj);
/** set data size */
curl_easy_setopt(getCurlHandle(), CURLOPT_INFILESIZE,
static_cast<int64_t>(up_obj.length));
return this->performCurlRequest(url);
}
/**
* @brief HTTP PATCH method
*
* @param url to query
* @param data HTTP PATCH body
*
* @return response struct
*/
RestClient::Response
RestClient::Connection::patch(const std::string& url,
const std::string& data) {
/** initialize upload object */
RestClient::Helpers::UploadObject up_obj;
up_obj.data = data.c_str();
up_obj.length = data.size();
/** we want HTTP PATCH */
const char* http_patch = "PATCH";
/** set HTTP PATCH METHOD */
curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_patch);
curl_easy_setopt(getCurlHandle(), CURLOPT_UPLOAD, 1L);
/** set read callback function */
curl_easy_setopt(getCurlHandle(), CURLOPT_READFUNCTION,
RestClient::Helpers::read_callback);
/** set data object to pass to callback function */
curl_easy_setopt(getCurlHandle(), CURLOPT_READDATA, &up_obj);
/** set data size */
curl_easy_setopt(getCurlHandle(), CURLOPT_INFILESIZE,
static_cast<int64_t>(up_obj.length));
return this->performCurlRequest(url);
}
/**
* @brief HTTP DELETE method
*
* @param url to query
*
* @return response struct
*/
RestClient::Response
RestClient::Connection::del(const std::string& url) {
/** we want HTTP DELETE */
const char* http_delete = "DELETE";
/** set HTTP DELETE METHOD */
curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_delete);
return this->performCurlRequest(url);
}
/**
* @brief HTTP HEAD method
*
* @param url to query
*
* @return response struct
*/
RestClient::Response
RestClient::Connection::head(const std::string& url) {
/** we want HTTP HEAD */
const char* http_head = "HEAD";
/** set HTTP HEAD METHOD */
curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_head);
curl_easy_setopt(getCurlHandle(), CURLOPT_NOBODY, 1L);
return this->performCurlRequest(url);
}
/**
* @brief HTTP OPTIONS method
*
* @param url to query
*
* @return response struct
*/
RestClient::Response
RestClient::Connection::options(const std::string& url) {
/** we want HTTP OPTIONS */
const char* http_options = "OPTIONS";
/** set HTTP HEAD METHOD */
curl_easy_setopt(getCurlHandle(), CURLOPT_CUSTOMREQUEST, http_options);
curl_easy_setopt(getCurlHandle(), CURLOPT_NOBODY, 1L);
return this->performCurlRequest(url);
}