1#include "http_curl.h"
2#if !defined(CONF_PLATFORM_EMSCRIPTEN)
3
4#include <base/dbg.h>
5#include <base/log.h>
6#include <base/str.h>
7#include <base/thread.h>
8
9#include <engine/shared/config.h>
10#include <engine/storage.h>
11
12#include <cstring>
13#include <limits>
14
15#if !defined(CONF_FAMILY_WINDOWS)
16#include <csignal>
17#endif
18
19#include <curl/curl.h>
20
21static int CurlDebug(CURL *pHandle, curl_infotype Type, char *pData, size_t DataSize, void *pUser)
22{
23 char TypeChar;
24 switch(Type)
25 {
26 case CURLINFO_TEXT:
27 TypeChar = '*';
28 break;
29 case CURLINFO_HEADER_OUT:
30 TypeChar = '<';
31 break;
32 case CURLINFO_HEADER_IN:
33 TypeChar = '>';
34 break;
35 default:
36 return 0;
37 }
38 while(const char *pLineEnd = (const char *)memchr(s: pData, c: '\n', n: DataSize))
39 {
40 int LineLength = pLineEnd - pData;
41 log_debug("curl", "%c %.*s", TypeChar, LineLength, pData);
42 pData += LineLength + 1;
43 DataSize -= LineLength + 1;
44 }
45 return 0;
46}
47
48CHttpRequestCurl::CHttpRequestCurl(const char *pUrl) :
49 IHttpRequest(pUrl)
50{
51}
52
53CHttpRequestCurl::~CHttpRequestCurl()
54{
55 dbg_assert(m_File == nullptr, "HTTP request file was not closed");
56 curl_slist_free_all(list: m_pRequestHeaders);
57}
58
59void CHttpRequestCurl::Header(const char *pNameColonValue)
60{
61 m_pRequestHeaders = curl_slist_append(list: m_pRequestHeaders, data: pNameColonValue);
62}
63
64bool CHttpRequestCurl::ConfigureHandle(CURL *pHandle)
65{
66 if(!BeforeInit())
67 {
68 return false;
69 }
70
71 if(g_Config.m_DbgHttp)
72 {
73 curl_easy_setopt(pHandle, CURLOPT_VERBOSE, 1L);
74 curl_easy_setopt(pHandle, CURLOPT_DEBUGFUNCTION, CurlDebug);
75 }
76 long Protocols = CURLPROTO_HTTPS;
77 if(g_Config.m_HttpAllowInsecure)
78 {
79 Protocols |= CURLPROTO_HTTP;
80 }
81
82 curl_easy_setopt(pHandle, CURLOPT_ERRORBUFFER, m_aErr);
83
84 curl_easy_setopt(pHandle, CURLOPT_CONNECTTIMEOUT_MS, m_Timeout.m_ConnectTimeoutMs);
85 curl_easy_setopt(pHandle, CURLOPT_TIMEOUT_MS, m_Timeout.m_TimeoutMs);
86 curl_easy_setopt(pHandle, CURLOPT_LOW_SPEED_LIMIT, m_Timeout.m_LowSpeedLimit);
87 curl_easy_setopt(pHandle, CURLOPT_LOW_SPEED_TIME, m_Timeout.m_LowSpeedTime);
88 if(m_MaxResponseSize >= 0)
89 {
90 curl_easy_setopt(pHandle, CURLOPT_MAXFILESIZE_LARGE, (curl_off_t)m_MaxResponseSize);
91 }
92 if(m_IfModifiedSince >= 0)
93 {
94 curl_easy_setopt(pHandle, CURLOPT_TIMEVALUE_LARGE, (curl_off_t)m_IfModifiedSince);
95 curl_easy_setopt(pHandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
96 }
97
98 // ‘CURLOPT_PROTOCOLS’ is deprecated: since 7.85.0. Use CURLOPT_PROTOCOLS_STR
99 // Wait until all platforms have 7.85.0
100#ifdef __GNUC__
101#pragma GCC diagnostic push
102#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
103#endif
104 curl_easy_setopt(pHandle, CURLOPT_PROTOCOLS, Protocols);
105 // Note that ‘CURLOPT_REDIR_PROTOCOLS’ does not need to be set explicitly,
106 // as redirects are only allowed for the same protocols specified above.
107#ifdef __GNUC__
108#pragma GCC diagnostic pop
109#endif
110 curl_easy_setopt(pHandle, CURLOPT_FOLLOWLOCATION, 1L);
111 curl_easy_setopt(pHandle, CURLOPT_MAXREDIRS, 4L);
112 if(m_FailOnErrorStatus)
113 {
114 curl_easy_setopt(pHandle, CURLOPT_FAILONERROR, 1L);
115 }
116 curl_easy_setopt(pHandle, CURLOPT_URL, m_aUrl);
117 curl_easy_setopt(pHandle, CURLOPT_NOSIGNAL, 1L);
118 curl_easy_setopt(pHandle, CURLOPT_USERAGENT, USER_AGENT_STRING);
119 curl_easy_setopt(pHandle, CURLOPT_ACCEPT_ENCODING, ""); // Use any compression algorithm supported by libcurl.
120
121 curl_easy_setopt(pHandle, CURLOPT_HEADERDATA, this);
122 curl_easy_setopt(pHandle, CURLOPT_HEADERFUNCTION, HeaderCallback);
123 curl_easy_setopt(pHandle, CURLOPT_WRITEDATA, this);
124 curl_easy_setopt(pHandle, CURLOPT_WRITEFUNCTION, WriteCallback);
125 curl_easy_setopt(pHandle, CURLOPT_NOPROGRESS, 0L);
126 curl_easy_setopt(pHandle, CURLOPT_PROGRESSDATA, this);
127 // ‘CURLOPT_PROGRESSFUNCTION’ is deprecated: since 7.32.0. Use CURLOPT_XFERINFOFUNCTION
128 // See problems with curl_off_t type in header file in https://github.com/ddnet/ddnet/pull/6185/
129#ifdef __GNUC__
130#pragma GCC diagnostic push
131#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
132#endif
133 curl_easy_setopt(pHandle, CURLOPT_PROGRESSFUNCTION, ProgressCallback);
134#ifdef __GNUC__
135#pragma GCC diagnostic pop
136#endif
137 curl_easy_setopt(pHandle, CURLOPT_IPRESOLVE, m_IpResolve == IPRESOLVE::V4 ? CURL_IPRESOLVE_V4 : (m_IpResolve == IPRESOLVE::V6 ? CURL_IPRESOLVE_V6 : CURL_IPRESOLVE_WHATEVER));
138 if(g_Config.m_Bindaddr[0] != '\0')
139 {
140 curl_easy_setopt(pHandle, CURLOPT_INTERFACE, g_Config.m_Bindaddr);
141 }
142
143 if(curl_version_info(CURLVERSION_NOW)->version_num < 0x074400)
144 {
145 // Causes crashes, see https://github.com/ddnet/ddnet/issues/4342.
146 // No longer a problem in curl 7.68 and above, and 0x44 = 68.
147 curl_easy_setopt(pHandle, CURLOPT_FORBID_REUSE, 1L);
148 }
149
150#ifdef CONF_PLATFORM_ANDROID
151 curl_easy_setopt(pHandle, CURLOPT_CAPATH, "/system/etc/security/cacerts");
152#endif
153
154 switch(m_Type)
155 {
156 case REQUEST::GET:
157 break;
158 case REQUEST::HEAD:
159 curl_easy_setopt(pHandle, CURLOPT_NOBODY, 1L);
160 break;
161 case REQUEST::POST:
162 case REQUEST::POST_JSON:
163 if(m_Type == REQUEST::POST_JSON)
164 {
165 Header(pNameColonValue: "Content-Type: application/json");
166 }
167 else
168 {
169 Header(pNameColonValue: "Content-Type:");
170 }
171 curl_easy_setopt(pHandle, CURLOPT_POSTFIELDS, m_pBody);
172 curl_easy_setopt(pHandle, CURLOPT_POSTFIELDSIZE, m_BodyLength);
173 break;
174 }
175
176 curl_easy_setopt(pHandle, CURLOPT_HTTPHEADER, m_pRequestHeaders);
177
178 return true;
179}
180
181size_t CHttpRequestCurl::OnHeader(char *pHeader, size_t HeaderSize)
182{
183 // `pHeader` is NOT null-terminated.
184 // `pHeader` has a trailing newline.
185
186 if(HeaderSize <= 1 || (HeaderSize == 2 && pHeader[0] == '\r' && pHeader[1] == '\n'))
187 {
188 m_ResponseHeadersEnded = true;
189 return HeaderSize;
190 }
191 if(m_ResponseHeadersEnded)
192 {
193 // redirect, clear old headers
194 m_ResponseHeadersEnded = false;
195 m_ResultDate = {};
196 m_ResultLastModified = {};
197 }
198
199 static const char DATE[] = "Date: ";
200 static const char LAST_MODIFIED[] = "Last-Modified: ";
201
202 // Trailing newline and null termination evens out.
203 if(HeaderSize - 1 >= sizeof(DATE) - 1 && str_startswith_nocase(str: pHeader, prefix: DATE))
204 {
205 char aValue[128];
206 str_truncate(dst: aValue, dst_size: sizeof(aValue), src: pHeader + (sizeof(DATE) - 1), truncation_len: HeaderSize - (sizeof(DATE) - 1) - 1);
207 int64_t Value = curl_getdate(p: aValue, unused: nullptr);
208 if(Value != -1)
209 {
210 m_ResultDate = Value;
211 }
212 }
213 if(HeaderSize - 1 >= sizeof(LAST_MODIFIED) - 1 && str_startswith_nocase(str: pHeader, prefix: LAST_MODIFIED))
214 {
215 char aValue[128];
216 str_truncate(dst: aValue, dst_size: sizeof(aValue), src: pHeader + (sizeof(LAST_MODIFIED) - 1), truncation_len: HeaderSize - (sizeof(LAST_MODIFIED) - 1) - 1);
217 int64_t Value = curl_getdate(p: aValue, unused: nullptr);
218 if(Value != -1)
219 {
220 m_ResultLastModified = Value;
221 }
222 }
223
224 return HeaderSize;
225}
226
227void CHttpRequestCurl::OnCompletionInternal(CURL *pHandle, CURLcode Code)
228{
229 if(pHandle)
230 {
231 long StatusCode;
232 curl_easy_getinfo(pHandle, CURLINFO_RESPONSE_CODE, &StatusCode);
233 m_StatusCode = StatusCode;
234 }
235
236 EHttpState State;
237 if(Code != CURLE_OK)
238 {
239 if(g_Config.m_DbgHttp || m_LogProgress >= HTTPLOG::FAILURE)
240 {
241 log_error("http", "%s failed. libcurl error (%u): %s", m_aUrl, Code, m_aErr[0] != '\0' ? m_aErr : curl_easy_strerror(Code));
242 }
243 State = (Code == CURLE_ABORTED_BY_CALLBACK) ? EHttpState::ABORTED : EHttpState::ERROR;
244 }
245 else
246 {
247 if(g_Config.m_DbgHttp || m_LogProgress >= HTTPLOG::ALL)
248 {
249 log_info("http", "task done: %s", m_aUrl);
250 }
251 State = EHttpState::DONE;
252 }
253
254 IHttpRequest::OnCompletionInternal(State);
255}
256
257size_t CHttpRequestCurl::HeaderCallback(char *pData, size_t Size, size_t Number, void *pUser)
258{
259 dbg_assert(Size == 1, "invalid size parameter passed to header callback");
260 return ((CHttpRequestCurl *)pUser)->OnHeader(pHeader: pData, HeaderSize: Number);
261}
262
263size_t CHttpRequestCurl::WriteCallback(char *pData, size_t Size, size_t Number, void *pUser)
264{
265 return ((CHttpRequestCurl *)pUser)->OnData(pData, DataSize: Size * Number);
266}
267
268int CHttpRequestCurl::ProgressCallback(void *pUser, double DlTotal, double DlCurr, double UlTotal, double UlCurr)
269{
270 CHttpRequestCurl *pTask = (CHttpRequestCurl *)pUser;
271 pTask->m_Current.store(t: DlCurr, m: std::memory_order_relaxed);
272 pTask->m_Size.store(t: DlTotal, m: std::memory_order_relaxed);
273 pTask->m_Progress.store(i: DlTotal == 0.0 ? 0 : (100 * DlCurr) / DlTotal, m: std::memory_order_relaxed);
274 if(pTask->m_pProgressCallback != nullptr)
275 {
276 pTask->m_pProgressCallback->OnProgress();
277 }
278 return pTask->m_Abort ? -1 : 0;
279}
280
281std::unique_ptr<IHttpRequest> CreateHttpRequest(const char *pUrl)
282{
283 return std::make_unique<CHttpRequestCurl>(args&: pUrl);
284}
285
286void EscapeUrl(char *pBuf, size_t Size, const char *pStr)
287{
288 char *pEsc = curl_easy_escape(curl: nullptr, string: pStr, length: 0);
289 str_copy(dst: pBuf, src: pEsc, dst_size: Size);
290 curl_free(p: pEsc);
291}
292
293bool CHttpCurl::Init(std::chrono::milliseconds ShutdownDelay)
294{
295 m_ShutdownDelay = ShutdownDelay;
296
297#if !defined(CONF_FAMILY_WINDOWS)
298 // As a multithreaded application we have to tell curl to not install signal
299 // handlers and instead ignore SIGPIPE from OpenSSL ourselves.
300 signal(SIGPIPE, SIG_IGN);
301#endif
302 m_pThread = thread_init(threadfunc: CHttpCurl::ThreadMain, user: this, name: "http");
303
304 std::unique_lock Lock(m_Lock);
305 m_ConditionVariableInit.wait(lock&: Lock, p: [this]() { return m_State != CHttpCurl::UNINITIALIZED; });
306 if(m_State != CHttpCurl::RUNNING)
307 {
308 return false;
309 }
310
311 return true;
312}
313
314void CHttpCurl::Shutdown()
315{
316 std::unique_lock Lock(m_Lock);
317 if(m_Shutdown || m_State != CHttpCurl::RUNNING)
318 return;
319
320 m_Shutdown = true;
321 curl_multi_wakeup(m: m_pMultiH);
322}
323
324CHttpCurl::~CHttpCurl()
325{
326 if(!m_pThread)
327 return;
328
329 Shutdown();
330 thread_wait(thread: m_pThread);
331}
332
333void CHttpCurl::Run(std::shared_ptr<IHttpRequest> pRequest)
334{
335 std::shared_ptr<CHttpRequestCurl> pRequestImpl = std::static_pointer_cast<CHttpRequestCurl>(r: pRequest);
336 std::unique_lock Lock(m_Lock);
337 if(m_Shutdown || m_State == CHttpCurl::ERROR)
338 {
339 str_copy(dst&: pRequestImpl->m_aErr, src: "Shutting down");
340 pRequestImpl->OnCompletionInternal(pHandle: nullptr, Code: CURLE_ABORTED_BY_CALLBACK);
341 return;
342 }
343 m_ConditionVariableInit.wait(lock&: Lock, p: [this]() { return m_State != CHttpCurl::UNINITIALIZED; });
344 m_PendingRequests.emplace_back(args&: pRequestImpl);
345 curl_multi_wakeup(m: m_pMultiH);
346}
347
348bool CHttpCurl::HasIpresolveBug() const
349{
350 // curl < 7.77.0 doesn't use CURLOPT_IPRESOLVE correctly wrt.
351 // connection caches.
352 return curl_version_info(CURLVERSION_NOW)->version_num < 0x074d00;
353}
354
355void CHttpCurl::ThreadMain(void *pUser)
356{
357 static_cast<CHttpCurl *>(pUser)->RunLoop();
358}
359
360void CHttpCurl::RunLoop()
361{
362 std::unique_lock Lock(m_Lock);
363 if(curl_global_init(CURL_GLOBAL_DEFAULT))
364 {
365 log_error("http", "curl_global_init failed");
366 m_State = CHttpCurl::ERROR;
367 m_ConditionVariableInit.notify_all();
368 return;
369 }
370
371 m_pMultiH = curl_multi_init();
372 if(!m_pMultiH)
373 {
374 log_error("http", "curl_multi_init failed");
375 m_State = CHttpCurl::ERROR;
376 m_ConditionVariableInit.notify_all();
377 return;
378 }
379
380 // print curl version
381 {
382 curl_version_info_data *pVersion = curl_version_info(CURLVERSION_NOW);
383 log_info("http", "libcurl version %s (compiled = " LIBCURL_VERSION ")", pVersion->version);
384 }
385
386 m_State = CHttpCurl::RUNNING;
387 m_ConditionVariableInit.notify_all();
388 Lock.unlock();
389 m_NextTimeout = std::numeric_limits<int>::max();
390
391 while(m_State == CHttpCurl::RUNNING)
392 {
393 int Events = 0;
394 const CURLMcode PollCode = curl_multi_poll(m: m_pMultiH, extra_fds: nullptr, extra_nfds: 0, timeout_ms: m_NextTimeout, ret: &Events);
395
396 // We may have been woken up for a shutdown
397 if(m_Shutdown)
398 {
399 if(m_RunningRequests.empty() && m_PendingRequests.empty())
400 break;
401
402 auto Now = std::chrono::steady_clock::now();
403 if(!m_ShutdownTime.has_value())
404 {
405 m_ShutdownTime = Now + m_ShutdownDelay;
406 m_NextTimeout = m_ShutdownDelay.count();
407 }
408 else if(m_ShutdownTime < Now)
409 {
410 break;
411 }
412 }
413
414 if(PollCode != CURLM_OK)
415 {
416 Lock.lock();
417 log_error("http", "curl_multi_poll failed: %s", curl_multi_strerror(PollCode));
418 m_State = CHttpCurl::ERROR;
419 break;
420 }
421
422 const CURLMcode PerformCode = curl_multi_perform(m: m_pMultiH, running_handles: &Events);
423 if(PerformCode != CURLM_OK)
424 {
425 Lock.lock();
426 log_error("http", "curl_multi_perform failed: %s", curl_multi_strerror(PerformCode));
427 m_State = CHttpCurl::ERROR;
428 break;
429 }
430
431 struct CURLMsg *pMsg;
432 while((pMsg = curl_multi_info_read(m: m_pMultiH, msgs_in_queue: &Events)))
433 {
434 if(pMsg->msg == CURLMSG_DONE)
435 {
436 CURL *pEasyHandle = pMsg->easy_handle;
437 auto RequestIt = m_RunningRequests.find(key: pEasyHandle);
438 dbg_assert(RequestIt != m_RunningRequests.end(), "Running handle not added to map");
439 auto pRequest = std::move(RequestIt->second);
440 m_RunningRequests.erase(it: RequestIt);
441
442 pRequest->OnCompletionInternal(pHandle: pEasyHandle, Code: pMsg->data.result);
443 curl_multi_remove_handle(m: m_pMultiH, curl: pEasyHandle);
444 curl_easy_cleanup(curl: pEasyHandle);
445 }
446 }
447
448 decltype(m_PendingRequests) NewRequests = {};
449 Lock.lock();
450 std::swap(lhs&: m_PendingRequests, rhs&: NewRequests);
451 Lock.unlock();
452
453 while(!NewRequests.empty())
454 {
455 auto &pRequest = NewRequests.front();
456 if(g_Config.m_DbgHttp)
457 log_debug("http", "task: %s %s", CHttpRequestCurl::GetRequestType(pRequest->m_Type), pRequest->m_aUrl);
458
459 if(pRequest->ShouldSkipRequest())
460 {
461 if(pRequest->m_pProgressCallback != nullptr)
462 {
463 pRequest->m_pProgressCallback->OnCompletion(State: EHttpState::DONE);
464 }
465 {
466 std::unique_lock WaitLock(pRequest->m_WaitMutex);
467 pRequest->m_State = EHttpState::DONE;
468 }
469 pRequest->m_WaitCondition.notify_all();
470 NewRequests.pop_front();
471 continue;
472 }
473
474 CURL *pEH = curl_easy_init();
475 if(!pEH)
476 {
477 log_error("http", "curl_easy_init failed");
478 goto error_init;
479 }
480
481 if(!pRequest->ConfigureHandle(pHandle: pEH))
482 {
483 curl_easy_cleanup(curl: pEH);
484 str_copy(dst&: pRequest->m_aErr, src: "Failed to initialize request");
485 pRequest->OnCompletionInternal(pHandle: nullptr, Code: CURLE_FAILED_INIT);
486 NewRequests.pop_front();
487 continue;
488 }
489
490 if(curl_multi_add_handle(m: m_pMultiH, curl: pEH) != CURLM_OK)
491 {
492 log_error("http", "curl_multi_add_handle failed");
493 goto error_configure;
494 }
495
496 {
497 std::unique_lock WaitLock(pRequest->m_WaitMutex);
498 pRequest->m_State = EHttpState::RUNNING;
499 }
500 m_RunningRequests.emplace(args&: pEH, args: std::move(pRequest));
501 NewRequests.pop_front();
502 continue;
503
504 error_configure:
505 curl_easy_cleanup(curl: pEH);
506 error_init:
507 Lock.lock();
508 m_State = CHttpCurl::ERROR;
509 break;
510 }
511
512 // Only happens if m_State == ERROR, thus we already hold the lock
513 if(!NewRequests.empty())
514 {
515 m_PendingRequests.insert(position: m_PendingRequests.end(), first: std::make_move_iterator(i: NewRequests.begin()), last: std::make_move_iterator(i: NewRequests.end()));
516 break;
517 }
518 }
519
520 if(!Lock.owns_lock())
521 Lock.lock();
522
523 bool Cleanup = m_State != CHttpCurl::ERROR;
524 for(auto &pRequest : m_PendingRequests)
525 {
526 str_copy(dst&: pRequest->m_aErr, src: "Shutting down");
527 pRequest->OnCompletionInternal(pHandle: nullptr, Code: CURLE_ABORTED_BY_CALLBACK);
528 }
529 m_PendingRequests.clear();
530
531 for(auto &ReqPair : m_RunningRequests)
532 {
533 auto &[pHandle, pRequest] = ReqPair;
534
535 str_copy(dst&: pRequest->m_aErr, src: "Shutting down");
536 pRequest->OnCompletionInternal(pHandle, Code: CURLE_ABORTED_BY_CALLBACK);
537
538 if(Cleanup)
539 {
540 curl_multi_remove_handle(m: m_pMultiH, curl: pHandle);
541 curl_easy_cleanup(curl: pHandle);
542 }
543 }
544 m_RunningRequests.clear();
545
546 if(Cleanup)
547 {
548 curl_multi_cleanup(m: m_pMultiH);
549 curl_global_cleanup();
550 }
551}
552
553IEngineHttp *CreateEngineHttp()
554{
555 return new CHttpCurl;
556}
557
558#endif // !CONF_PLATFORM_EMSCRIPTEN
559