Debian Codegraph @

coeurl/lib/request.cpp

raw symbols SCIP
1 #include "coeurl/request.hpp"
2
3 #include "coeurl/client.hpp"
4
5 // for TCP_MAXRT
6 #if __has_include(<winsock2.h>)
7 #include <winsock2.h>
8 #endif
9
10 // for TCP_USER_TIMEOUT
11 #if __has_include(<netinet/tcp.h>)
12 #include <netinet/tcp.h>
13 #endif
14
15 namespace coeurl {
16 /* CURLOPT_WRITEFUNCTION */
17 size_t Request::write_cb(void *ptr, size_t size, size_t nmemb, void *data) {
18 Request *request = (Request *)data;
19 Client::log->trace("Write: {} ({})", request->url_, nmemb);
20 request->response_.insert(request->response_.end(), (uint8_t *)ptr, (uint8_t *)ptr + nmemb);
21
22 return size * nmemb;
23 }
24
25 /* CURLOPT_WRITEFUNCTION */
26 size_t Request::read_cb(char *buffer, size_t size, size_t nitems, void *data) {
27 Request *request = (Request *)data;
28
29 size_t data_left = request->request_.size() - request->readoffset;
30
31 auto data_to_copy = std::min(data_left, nitems * size);
32
33 Client::log->trace("Read: {} ({})", request->url_, data_to_copy);
34
35 if (data_to_copy) {
36 auto read_ptr = request->request_.data() + request->readoffset;
37 Client::log->trace("Copying: {}", std::string_view(read_ptr, data_to_copy));
38 std::copy(read_ptr, read_ptr + data_to_copy, buffer);
39 Client::log->trace("Copied: {}", std::string_view(buffer, data_to_copy));
40
41 request->readoffset += data_to_copy;
42 }
43
44 return data_to_copy;
45 }
46
47 static std::string_view trim(std::string_view val) {
48 while (val.size() && isspace(val.front()))
49 val.remove_prefix(1);
50 while (val.size() && isspace(val.back()))
51 val.remove_suffix(1);
52
53 return val;
54 }
55
56 static char ascii_lower(char c) {
57 if (c >= 'A' && c <= 'Z')
58 c |= 0b00100000;
59 return c;
60 }
61
62 bool header_less::operator()(const std::string &a, const std::string &b) const {
63 if (a.size() != b.size())
64 return a.size() < b.size();
65
66 for (size_t i = 0; i < a.size(); i++) {
67 auto a_c = ascii_lower(a[i]);
68 auto b_c = ascii_lower(b[i]);
69
70 if (a_c != b_c)
71 return a_c < b_c;
72 }
73
74 return false;
75 }
76
77 /* CURLOPT_HEADERFUNCTION */
78 size_t Request::header_cb(char *buffer, size_t, size_t nitems, void *data) {
79 Request *request = (Request *)data;
80 std::string_view header(buffer, nitems);
81
82 if (auto pos = header.find(':'); pos != std::string_view::npos) {
83 auto key = trim(header.substr(0, pos));
84 auto val = trim(header.substr(pos + 1));
85
86 Client::log->debug("Header: {} ({}: {})", request->url_, key, val);
87
88 request->response_headers_.insert({std::string(key), std::string(val)});
89 }
90
91 return nitems;
92 }
93
94 /* CURLOPT_PROGRESSFUNCTION */
95 int Request::prog_cb(void *p, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ult, curl_off_t uln) {
96 Request *r = (Request *)p;
97 (void)ult;
98 (void)uln;
99
100 if (r->on_upload_progress_)
101 r->on_upload_progress_(uln, ult);
102 if (r->on_download_progess_)
103 r->on_download_progess_(dlnow, dltotal);
104
105 Client::log->trace("Progress: {} ({}/{}):({}/{})", r->url_, uln, ult, dlnow, dltotal);
106 return 0;
107 }
108
109 Request::Request(Client *client, Method m, std::string url__) : url_(std::move(url__)), global(client), method(m) {
110 this->easy = curl_easy_init();
111 if (!this->easy) {
112 Client::log->critical("curl_easy_init() failed, exiting!");
113 throw std::bad_alloc();
114 }
115
116 curl_easy_setopt(this->easy, CURLOPT_URL, this->url_.c_str());
117 curl_easy_setopt(this->easy, CURLOPT_WRITEFUNCTION, write_cb);
118 curl_easy_setopt(this->easy, CURLOPT_WRITEDATA, this);
119 curl_easy_setopt(this->easy, CURLOPT_HEADERFUNCTION, header_cb);
120 curl_easy_setopt(this->easy, CURLOPT_HEADERDATA, this);
121 if (this->global->verbose()) {
122 curl_easy_setopt(this->easy, CURLOPT_VERBOSE, 1L);
123 }
124 curl_easy_setopt(this->easy, CURLOPT_ERRORBUFFER, this->error);
125 curl_easy_setopt(this->easy, CURLOPT_PRIVATE, this);
126 curl_easy_setopt(this->easy, CURLOPT_NOPROGRESS, 1L);
127 curl_easy_setopt(this->easy, CURLOPT_XFERINFOFUNCTION, prog_cb);
128 curl_easy_setopt(this->easy, CURLOPT_XFERINFODATA, this);
129 #if CURL_AT_LEAST_VERSION(7, 85, 0)
130 curl_easy_setopt(this->easy, CURLOPT_PROTOCOLS_STR, "HTTPS,HTTP");
131 #else
132 curl_easy_setopt(this->easy, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
133 #endif
134
135 // enable altsvc support, which allows us to switch to http3
136 curl_easy_setopt(this->easy, CURLOPT_ALTSVC_CTRL, CURLALTSVC_H1 | CURLALTSVC_H2 | CURLALTSVC_H3);
137 curl_easy_setopt(this->easy, CURLOPT_ALTSVC, client->alt_svc_cache_path().c_str());
138
139 // default to all supported encodings
140 curl_easy_setopt(this->easy, CURLOPT_ACCEPT_ENCODING, "");
141
142 switch (m) {
143 case Method::Delete:
144 curl_easy_setopt(this->easy, CURLOPT_HTTPGET, 0L);
145 curl_easy_setopt(this->easy, CURLOPT_CUSTOMREQUEST, "DELETE");
146 break;
147 case Method::Get:
148 curl_easy_setopt(this->easy, CURLOPT_HTTPGET, 1L);
149 break;
150 case Method::Head:
151 curl_easy_setopt(this->easy, CURLOPT_NOBODY, 1L);
152 break;
153 case Method::Options:
154 curl_easy_setopt(this->easy, CURLOPT_CUSTOMREQUEST, "OPTIONS");
155 break;
156 case Method::Patch:
157 curl_easy_setopt(this->easy, CURLOPT_CUSTOMREQUEST, "PATCH");
158 break;
159 case Method::Post:
160 curl_easy_setopt(this->easy, CURLOPT_POST, 1L);
161 request("");
162 break;
163 case Method::Put:
164 curl_easy_setopt(this->easy, CURLOPT_CUSTOMREQUEST, "PUT");
165 request("");
166 break;
167 }
168
169 verify_peer(this->global->does_verify_peer());
170 }
171
172 Request::~Request() {
173 curl_easy_cleanup(this->easy);
174 curl_slist_free_all(request_headers_);
175 }
176
177 Request &Request::max_redirects(long amount) {
178 curl_easy_setopt(this->easy, CURLOPT_FOLLOWLOCATION, 1L);
179 curl_easy_setopt(this->easy, CURLOPT_MAXREDIRS, amount);
180 return *this;
181 }
182
183 Request &Request::verify_peer(bool verify) {
184 curl_easy_setopt(this->easy, CURLOPT_SSL_VERIFYPEER, verify ? 1L : 0L);
185 return *this;
186 }
187
188 Request &Request::request(std::string r, std::string contenttype) {
189 this->request_ = std::move(r);
190 this->request_contenttype_ = std::move(contenttype);
191
192 curl_easy_setopt(this->easy, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(request_.size()));
193 curl_easy_setopt(this->easy, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(request_.size()));
194 curl_easy_setopt(this->easy, CURLOPT_READDATA, this);
195 curl_easy_setopt(this->easy, CURLOPT_READFUNCTION, read_cb);
196 curl_easy_setopt(this->easy, CURLOPT_POSTFIELDS, nullptr);
197 return *this;
198 }
199
200 Request &Request::request_headers(const Headers &h) {
201 if (request_headers_)
202 curl_slist_free_all(request_headers_);
203
204 for (const auto &[k, v] : h) {
205 request_headers_ = curl_slist_append(request_headers_, (k + ": " + v).c_str());
206 }
207
208 if (!request_contenttype_.empty())
209 request_headers_ = curl_slist_append(request_headers_, ("content-type: " + request_contenttype_).c_str());
210
211 curl_easy_setopt(this->easy, CURLOPT_HTTPHEADER, request_headers_);
212 return *this;
213 }
214
215 Request &Request::connection_timeout(long t) {
216 // only allow values that are > 0, if they are divided by 3
217 if (t <= 2)
218 return *this;
219
220 // enable keepalive
221 curl_easy_setopt(this->easy, CURLOPT_TCP_KEEPALIVE, 1L);
222
223 // send keepalives every third of the timeout interval. This allows for
224 // retransmission of 2 keepalive while still giving the server a third of the
225 // time to reply
226 curl_easy_setopt(this->easy, CURLOPT_TCP_KEEPIDLE, t / 3);
227 curl_easy_setopt(this->easy, CURLOPT_TCP_KEEPINTVL, t / 3);
228
229 this->connection_timeout_ = t;
230 #ifdef TCP_USER_TIMEOUT
231 // The + is needed to convert this to a function pointer!
232 curl_easy_setopt(
233 this->easy, CURLOPT_SOCKOPTFUNCTION, +[](void *clientp, curl_socket_t curlfd, curlsocktype) -> int {
234 unsigned int val = static_cast<Request *>(clientp)->connection_timeout_ * 1000 /*ms*/;
235 setsockopt(curlfd, SOL_TCP, TCP_USER_TIMEOUT, (const char *)&val, sizeof(val));
236 return CURLE_OK;
237 });
238 #elif defined(TCP_MAXRT)
239 // The + is needed to convert this to a function pointer!
240 curl_easy_setopt(
241 this->easy, CURLOPT_SOCKOPTFUNCTION, +[](void *clientp, curl_socket_t sock, curlsocktype) -> int {
242 unsigned int maxrt = static_cast<Request *>(clientp)->connection_timeout_ /*s*/;
243 setsockopt(sock, IPPROTO_TCP, TCP_MAXRT, (const char *)&maxrt, sizeof(maxrt));
244 return CURLE_OK;
245 });
246 #endif
247 curl_easy_setopt(this->easy, CURLOPT_SOCKOPTDATA, this);
248
249 return *this;
250 }
251
252 Request &Request::on_complete(std::function<void(const Request &)> handler) {
253 on_complete_ = handler;
254 return *this;
255 }
256
257 Request &Request::on_upload_progress(std::function<void(size_t progress, size_t total)> handler) {
258 on_upload_progress_ = handler;
259 curl_easy_setopt(this->easy, CURLOPT_NOPROGRESS, 0L);
260 return *this;
261 }
262 Request &Request::on_download_progess(std::function<void(size_t progress, size_t total)> handler) {
263 on_download_progess_ = handler;
264 curl_easy_setopt(this->easy, CURLOPT_NOPROGRESS, 0L);
265 return *this;
266 }
267
268 int Request::response_code() const {
269 long http_code;
270 curl_easy_getinfo(const_cast<CURL *>(this->easy), CURLINFO_RESPONSE_CODE, &http_code);
271 return static_cast<int>(http_code);
272 }
273 } // namespace coeurl