-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurlex.cc
301 lines (275 loc) · 12.2 KB
/
curlex.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
/*
* MIT License
*
* Copyright (c) 2024 Piotr Pszczółkowski
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Project: curlex
* Author: Piotr Pszczółkowski ([email protected])
* Created: 2024/09/10
*/
/*------- include files:
-------------------------------------------------------------------*/
#include "curlex.h"
#include "guard.h"
#include <fmt/core.h>
//-------------------------------------------------------------------
/// Execute GET command for the request.
/// \param req - request to execute
/// \return optional response with data received from the server.
//-------------------------------------------------------------------
std::optional<Response> Curlex::GET(Request const& req) const noexcept {
// Guarantees CURL handle reset upon exiting the function.
Guard guard(handle_);
auto body_buffer_ptr = set_data_buffer();
auto headers_buffer_ptr = set_headers_buffer();
struct curl_slist* const headers = set_headers_list(req.headers());
// Set option GET.
if (auto err = curl_easy_setopt(handle_, CURLOPT_HTTPGET, 1); err) {
fmt::print(stderr, "GET.HTTPGET: {}\n", curl_easy_strerror(err));
return {};
}
// Set URL.
if (auto err = curl_easy_setopt(handle_, CURLOPT_URL, req.url().c_str()); err) {
fmt::print(stderr, "GET.URL: {}\n", curl_easy_strerror(err));
return {};
}
// Set the verbose option if the request says so
if (req.is_verbose())
if (auto err = curl_easy_setopt(handle_, CURLOPT_VERBOSE, 1L); err) {
fmt::print(stderr, "GET.VERBOSE: {}\n", curl_easy_strerror(err));
return {};
}
// And run
if (auto err = curl_easy_perform(handle_); err) {
fmt::print(stderr, "GET.PERFORM: {}\n", curl_easy_strerror(err));
return {};
}
// Getting the response code sent by the server.
long code{};
if (auto err = curl_easy_getinfo(handle_, CURLINFO_RESPONSE_CODE, &code); err) {
fmt::print(stderr, "GET.RESPONSE_CODE: {}\n", curl_easy_strerror(err));
return {};
}
// Release manually memory allocated for headers if they were used.
if (headers)
curl_slist_free_all(headers);
// Data and header buffers should free memory automatically.
return Response(code)
.body(std::move(*body_buffer_ptr))
.headers(std::move(*headers_buffer_ptr));
}
//-------------------------------------------------------------------
/// Execute POST command for the request.
/// \param req - request to execute
/// \return optional response with data received from the server.
//-------------------------------------------------------------------
std::optional<Response> Curlex::POST(Request const& req) const noexcept {
// Guarantees CURL handle reset upon exiting the function.
Guard guard(handle_);
auto body_buffer_ptr = set_data_buffer();
auto headers_buffer_ptr = set_headers_buffer();
struct curl_slist* const headers = set_headers_list(req.headers());
// Set option POST.
if (auto err = curl_easy_setopt(handle_, CURLOPT_HTTPPOST, 1); err) {
fmt::print(stderr, "POST.HTTPPOST: {}\n", curl_easy_strerror(err));
return {};
}
// Set option URL.
if (auto err = curl_easy_setopt(handle_, CURLOPT_URL, req.url().c_str()); err) {
fmt::print(stderr, "POST.URL: {}\n", curl_easy_strerror(err));
return {};
}
if (!req.body().empty()) {
if (auto err = curl_easy_setopt(handle_, CURLOPT_POSTFIELDS, req.body().c_str()); err) {
fmt::print(stderr, "POST.POSTFIELDS: {}\n", curl_easy_strerror(err));
return {};
}
}
Data data{};
if (!req.data().empty()) {
data.ptr = req.data().c_str();
data.left = req.data().size();
if (auto const err = curl_easy_setopt(handle_, CURLOPT_READFUNCTION, data_reader); err) {
fmt::print(stderr, "POST.READFUNCTION: {}\n", curl_easy_strerror(err));
return {};
}
if (auto const err = curl_easy_setopt(handle_, CURLOPT_READDATA, &data); err) {
fmt::print(stderr, "POST.READDATA: {}\n", curl_easy_strerror(err));
return {};
}
// if (auto const err = curl_easy_setopt(handle_, CURLOPT_POSTFIELDSIZE, req.data().size()); err) {
// fmt::print(stderr, "{}\n", curl_easy_strerror(err));
// return {};
// }
}
// Set the verbose option if the request says so
if (req.is_verbose())
if (auto err = curl_easy_setopt(handle_, CURLOPT_VERBOSE, 1L); err) {
fmt::print(stderr, "POST.VERBOSE: {}\n", curl_easy_strerror(err));
return {};
}
// And run
if (auto err = curl_easy_perform(handle_); err) {
fmt::print(stderr, "POST.PERFORM: {}\n", curl_easy_strerror(err));
return {};
}
// Getting the response code sent by the server.
long code{};
if (auto err = curl_easy_getinfo(handle_, CURLINFO_RESPONSE_CODE, &code); err) {
fmt::print(stderr, "POST.RESPONSE_CODE: {}\n", curl_easy_strerror(err));
return {};
}
// Release manually memory allocated for headers if they were used.
if (headers)
curl_slist_free_all(headers);
// Data and header buffers should free memory automatically.
return Response(code)
.body(std::move(*body_buffer_ptr))
.headers(std::move(*headers_buffer_ptr));
}
//-------------------------------------------------------------------
/// Execute OPTIONS command for the request.
/// \param req - request to execute
/// \return optional response with data received from the server.
//-------------------------------------------------------------------
std::optional<Response> Curlex::OPTIONS(Request const& req) const noexcept {
// Guarantees CURL handle reset upon exiting the function.
Guard guard(handle_);
auto body_buffer_ptr = set_data_buffer();
auto headers_buffer_ptr = set_headers_buffer();
struct curl_slist* const headers = set_headers_list(req.headers());
// Set option OPTIONS
if (auto err = curl_easy_setopt(handle_, CURLOPT_CUSTOMREQUEST, "OPTIONS"); err) {
fmt::print(stderr, "OPTIONS.CUSTOMREQUEST: {}\n", curl_easy_strerror(err));
return {};
}
// Set URL.
if (auto err = curl_easy_setopt(handle_, CURLOPT_URL, req.url().c_str()); err) {
fmt::print(stderr, "OPTIONS.URL: {}\n", curl_easy_strerror(err));
return {};
}
// Set the verbose option if the request says so
if (req.is_verbose())
if (auto err = curl_easy_setopt(handle_, CURLOPT_VERBOSE, 1L); err) {
fmt::print(stderr, "OPTIONS.VERBOSE: {}\n", curl_easy_strerror(err));
return {};
}
// And run
if (auto err = curl_easy_perform(handle_); err) {
fmt::print(stderr, "OPTIONS.PERFORM: {}\n", curl_easy_strerror(err));
return {};
}
// Getting the response code sent by the server.
long code{};
if (auto err = curl_easy_getinfo(handle_, CURLINFO_RESPONSE_CODE, &code); err) {
fmt::print(stderr, "OPTIONS.RESPONSE_CODE: {}\n", curl_easy_strerror(err));
return {};
}
// Release manually memory allocated for headers if they were used.
if (headers)
curl_slist_free_all(headers);
// Data and header buffers should free memory automatically.
return Response(code)
.body(std::move(*body_buffer_ptr))
.headers(std::move(*headers_buffer_ptr));
}
/********************************************************************
* *
* P R I V A T E *
* *
********************************************************************/
/// Allocation and registration a buffer in the system for received
/// body data and registration of the function for saving them.
/// \return shared pointer to allocated memory.
std::shared_ptr<std::string> Curlex::set_data_buffer() const noexcept {
if (auto err = curl_easy_setopt(handle_, CURLOPT_WRITEFUNCTION, collector); err) {
fmt::print(stderr, "{}\n", curl_easy_strerror(err));
return {};
}
auto ptr = std::make_shared<std::string>();
if (auto err = curl_easy_setopt(handle_, CURLOPT_WRITEDATA, ptr.get()); err) {
fmt::print(stderr, "{}\n", curl_easy_strerror(err));
return {};
}
return ptr;
}
/// Allocation and registration a buffer in the system for received
/// headers data and registration of the function for saving them.
/// \return shared pointer to allocated memory.
std::shared_ptr<std::string> Curlex::set_headers_buffer() const noexcept {
if (auto err = curl_easy_setopt(handle_, CURLOPT_HEADERFUNCTION, collector); err) {
fmt::print(stderr, "{}\n", curl_easy_strerror(err));
return {};
}
auto ptr = std::make_shared<std::string>();
if (auto err = curl_easy_setopt(handle_, CURLOPT_HEADERDATA, ptr.get()); err) {
fmt::print(stderr, "{}\n", curl_easy_strerror(err));
return {};
}
return ptr;
}
/// Create curl's list with headers,
/// \param headers - user defined vector of pairs key-value.
/// \return pointer to internally allocated curl's list.
/// \remark the memory of the list must be manually released.
struct curl_slist* Curlex::set_headers_list(std::vector<std::pair<std::string, std::string>> const& headers) const noexcept {
if (headers.empty()) return {};
struct curl_slist* list = nullptr;
for (auto const& pair : headers) {
auto [k, v] = pair;
auto const text = fmt::format("{}:{}", k, v);
list = curl_slist_append(list, text.c_str());
}
if (auto err = curl_easy_setopt(handle_, CURLOPT_HTTPHEADER, list); err) {
fmt::print(stderr, "{}\n", curl_easy_strerror(err));
return {};
}
return list;
}
/// A static function that adds the specified data to a buffer that is a string.
/// \param src - pointer to the buffer with the data to be saved
/// \param one_item_size - size of one copied item (normally 1 for bytes),
/// \param items_count - how many itams to copy (number of bytes - one_item_size * items_count).
/// \return number of copied bytes.
size_t Curlex::collector(char const *const src, size_t one_item_size, size_t const items_count, void *const dst) noexcept {
auto const string = reinterpret_cast<std::string *>(dst);
auto const n = one_item_size * items_count;
string->append(src, n);
return n;
};
/// Copy data from source to destination.
/// \param dst - copy destination,
/// \param one_item_size - size one item in bytes (normally 1 for bytes),
/// \param items_count - how many items to copy (number of bytes := one_item_size * items_count),
/// \param src - from where copy
/// \return number of copied bytes.
size_t Curlex::data_reader(char* const dst, size_t const one_item_size, size_t const items_count, void* const src) noexcept {
auto data = reinterpret_cast<struct Data*>(src);
size_t const max_bytes_to_copy = one_item_size * items_count;
if (data->left) {
auto const n = (data->left > max_bytes_to_copy) ? max_bytes_to_copy : data->left;
memcpy(dst, data->ptr, n);
data->ptr += n;
data->left -= n;
return n;
}
return 0;
}