Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "UserReport.h"
21 :
22 : #include "lib/code_annotation.h"
23 : #include "lib/code_generation.h"
24 : #include "lib/debug.h"
25 : #include "lib/external_libraries/curl.h"
26 : #include "lib/external_libraries/zlib.h"
27 : #include "lib/os_path.h"
28 : #include "lib/path.h"
29 : #include "lib/secure_crt.h"
30 : #include "lib/status.h"
31 : #include "lib/sysdep/sysdep.h"
32 : #include "lib/timer.h"
33 : #include "lib/utf8.h"
34 : #include "ps/CStr.h"
35 : #include "ps/ConfigDB.h"
36 : #include "ps/Profiler2.h"
37 : #include "ps/Pyrogenesis.h"
38 : #include "ps/TaskManager.h"
39 : #include "ps/Future.h"
40 : #include "ps/Threading.h"
41 :
42 : #include <algorithm>
43 : #include <cstring>
44 : #include <ctime>
45 : #include <deque>
46 : #include <fmt/format.h>
47 : #include <fstream>
48 : #include <memory>
49 : #include <mutex>
50 : #include <string>
51 : #include <thread>
52 : #include <utility>
53 : #include <functional>
54 :
55 : #define DEBUG_UPLOADS 0
56 :
57 : /*
58 : * The basic idea is that the game submits reports to us, which we send over
59 : * HTTP to a server for storage and analysis.
60 : *
61 : * We can't use libcurl's asynchronous 'multi' API, because DNS resolution can
62 : * be synchronous and slow (which would make the game pause).
63 : * So we use the 'easy' API in a background thread.
64 : * The main thread submits reports, toggles whether uploading is enabled,
65 : * and polls for the current status (typically to display in the GUI);
66 : * the worker thread does all of the uploading.
67 : *
68 : * It'd be nice to extend this in the future to handle things like crash reports.
69 : * The game should store the crashlogs (suitably anonymised) in a directory, and
70 : * we should detect those files and upload them when we're restarted and online.
71 : */
72 :
73 :
74 : /**
75 : * Version number stored in config file when the user agrees to the reporting.
76 : * Reporting will be disabled if the config value is missing or is less than
77 : * this value. If we start reporting a lot more data, we should increase this
78 : * value and get the user to re-confirm.
79 : */
80 : static const int REPORTER_VERSION = 1;
81 :
82 : /**
83 : * Time interval (seconds) at which the worker thread will check its reconnection
84 : * timers. (This should be relatively high so the thread doesn't waste much time
85 : * continually waking up.)
86 : */
87 : static const double TIMER_CHECK_INTERVAL = 10.0;
88 :
89 : /**
90 : * Seconds we should wait before reconnecting to the server after a failure.
91 : */
92 : static const double RECONNECT_INVERVAL = 60.0;
93 :
94 : CUserReporter g_UserReporter;
95 :
96 0 : struct CUserReport
97 : {
98 : time_t m_Time;
99 : std::string m_Type;
100 : int m_Version;
101 : std::string m_Data;
102 : };
103 :
104 : class CUserReporterWorker
105 : {
106 : public:
107 0 : CUserReporterWorker(const std::string& userID, const std::string& url) :
108 0 : m_URL(url), m_UserID(userID), m_Enabled(false), m_Shutdown(false), m_Status("disabled"),
109 0 : m_PauseUntilTime(timer_Time()), m_LastUpdateTime(timer_Time()), m_ProxyInitialised(false)
110 : {
111 : // Set up libcurl:
112 :
113 0 : m_Curl = curl_easy_init();
114 0 : ENSURE(m_Curl);
115 :
116 : #if DEBUG_UPLOADS
117 : curl_easy_setopt(m_Curl, CURLOPT_VERBOSE, 1L);
118 : #endif
119 :
120 : // Capture error messages
121 0 : curl_easy_setopt(m_Curl, CURLOPT_ERRORBUFFER, m_ErrorBuffer);
122 :
123 : // Disable signal handlers (required for multithreaded applications)
124 0 : curl_easy_setopt(m_Curl, CURLOPT_NOSIGNAL, 1L);
125 :
126 : // To minimise security risks, don't support redirects
127 0 : curl_easy_setopt(m_Curl, CURLOPT_FOLLOWLOCATION, 0L);
128 :
129 : // Prevent this thread from blocking the engine shutdown for 5 minutes in case the server is unavailable
130 0 : curl_easy_setopt(m_Curl, CURLOPT_CONNECTTIMEOUT, 10L);
131 :
132 : // Set IO callbacks
133 0 : curl_easy_setopt(m_Curl, CURLOPT_WRITEFUNCTION, ReceiveCallback);
134 0 : curl_easy_setopt(m_Curl, CURLOPT_WRITEDATA, this);
135 0 : curl_easy_setopt(m_Curl, CURLOPT_READFUNCTION, SendCallback);
136 0 : curl_easy_setopt(m_Curl, CURLOPT_READDATA, this);
137 :
138 : // Set URL to POST to
139 0 : curl_easy_setopt(m_Curl, CURLOPT_URL, url.c_str());
140 0 : curl_easy_setopt(m_Curl, CURLOPT_POST, 1L);
141 :
142 : // Set up HTTP headers
143 0 : m_Headers = NULL;
144 : // Set the UA string
145 0 : std::string ua = "User-Agent: 0ad ";
146 0 : ua += curl_version();
147 0 : ua += " (http://play0ad.com/)";
148 0 : m_Headers = curl_slist_append(m_Headers, ua.c_str());
149 : // Override the default application/x-www-form-urlencoded type since we're not using that type
150 0 : m_Headers = curl_slist_append(m_Headers, "Content-Type: application/octet-stream");
151 : // Disable the Accept header because it's a waste of a dozen bytes
152 0 : m_Headers = curl_slist_append(m_Headers, "Accept: ");
153 0 : curl_easy_setopt(m_Curl, CURLOPT_HTTPHEADER, m_Headers);
154 0 : }
155 :
156 0 : ~CUserReporterWorker()
157 : {
158 0 : curl_slist_free_all(m_Headers);
159 0 : curl_easy_cleanup(m_Curl);
160 0 : }
161 :
162 : /**
163 : * Called by main thread, when the online reporting is enabled/disabled.
164 : */
165 0 : void SetEnabled(bool enabled)
166 : {
167 0 : {
168 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
169 0 : m_Enabled = enabled;
170 0 : }
171 :
172 0 : TryStartTask();
173 0 : }
174 :
175 : /**
176 : * Called by main thread to request shutdown.
177 : * Returns true if we've shut down successfully.
178 : * Returns false if shutdown is taking too long (we might be blocked on a
179 : * sync network operation) - you mustn't destroy this object, just leak it
180 : * and terminate.
181 : */
182 0 : bool Shutdown()
183 : {
184 0 : {
185 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
186 0 : m_Shutdown = true;
187 0 : }
188 0 : CleanupFuture();
189 0 : return true;
190 : }
191 :
192 : /**
193 : * Called by main thread to determine the current status of the uploader.
194 : */
195 0 : std::string GetStatus()
196 : {
197 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
198 0 : return m_Status;
199 0 : }
200 :
201 : /**
202 : * Called by main thread to add a new report to the queue.
203 : */
204 0 : void Submit(const std::shared_ptr<CUserReport>& report)
205 : {
206 0 : {
207 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
208 0 : m_ReportQueue.push_back(report);
209 0 : }
210 :
211 0 : TryStartTask();
212 0 : }
213 :
214 : /**
215 : * Called by the main thread every frame, so we can check
216 : * retransmission timers.
217 : */
218 0 : void Update()
219 : {
220 0 : double now = timer_Time();
221 0 : if (now > m_LastUpdateTime + TIMER_CHECK_INTERVAL)
222 : {
223 0 : m_LastUpdateTime = now;
224 0 : TryStartTask();
225 : }
226 0 : }
227 :
228 : private:
229 0 : void CleanupFuture()
230 : {
231 0 : if (m_Future.Valid())
232 0 : m_Future.Get();
233 : }
234 :
235 0 : void TryStartTask()
236 : {
237 0 : if (m_Future.Valid() && !m_Future.IsDone())
238 : return;
239 0 : if (!m_Enabled)
240 : return;
241 0 : if (m_Shutdown)
242 : return;
243 0 : if (timer_Time() < m_PauseUntilTime)
244 : return;
245 :
246 0 : CleanupFuture();
247 :
248 : // Start or replace the future
249 0 : m_Future = {g_TaskManager, std::bind_front(&CUserReporterWorker::RunTask, this)};
250 : }
251 :
252 0 : void RunTask()
253 : {
254 0 : PROFILE2("CUserReporterWorker::RunTask");
255 :
256 0 : InitializeProxyIfNeeded();
257 :
258 0 : while (ShouldRun())
259 : {
260 0 : if (!ProcessReport())
261 : break;
262 : }
263 0 : }
264 :
265 :
266 : private:
267 :
268 0 : void InitializeProxyIfNeeded()
269 : {
270 0 : if (m_ProxyInitialised)
271 0 : return;
272 :
273 0 : PROFILE2("CUserReporterWorker::InitializeProxyIfNeeded");
274 :
275 0 : SetStatus("proxy");
276 0 : std::wstring proxy;
277 0 : {
278 0 : if (sys_get_proxy_config(wstring_from_utf8(m_URL), proxy) == INFO::OK)
279 0 : curl_easy_setopt(m_Curl, CURLOPT_PROXY, utf8_from_wstring(proxy).c_str());
280 : }
281 :
282 0 : m_ProxyInitialised = true;
283 0 : SetStatus("waiting");
284 0 : }
285 :
286 0 : bool ShouldRun()
287 : {
288 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
289 0 : return m_Enabled && !m_Shutdown;
290 0 : }
291 :
292 0 : bool GetShutdown()
293 : {
294 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
295 0 : return m_Shutdown;
296 0 : }
297 :
298 0 : void SetStatus(const std::string& status)
299 : {
300 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
301 0 : m_Status = status;
302 : #if DEBUG_UPLOADS
303 : debug_printf(">>> CUserReporterWorker status: %s\n", status.c_str());
304 : #endif
305 0 : }
306 :
307 0 : bool ProcessReport()
308 : {
309 0 : PROFILE2("CUserReporterWorker::ProcessReport");
310 :
311 0 : std::shared_ptr<CUserReport> report;
312 :
313 0 : {
314 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
315 0 : if (m_ReportQueue.empty())
316 0 : return false;
317 0 : report = m_ReportQueue.front();
318 0 : m_ReportQueue.pop_front();
319 0 : }
320 :
321 0 : ConstructRequestData(*report);
322 0 : m_RequestDataOffset = 0;
323 0 : m_ResponseData.clear();
324 0 : m_ErrorBuffer[0] = '\0';
325 :
326 0 : curl_easy_setopt(m_Curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)m_RequestData.size());
327 :
328 0 : SetStatus("connecting");
329 :
330 0 : CURLcode err = curl_easy_perform(m_Curl);
331 :
332 : #if DEBUG_UPLOADS
333 : printf(">>>\n%s\n<<<\n", m_ResponseData.c_str());
334 : #endif
335 :
336 0 : if (err == CURLE_OK)
337 : {
338 0 : long code = -1;
339 0 : curl_easy_getinfo(m_Curl, CURLINFO_RESPONSE_CODE, &code);
340 0 : SetStatus(fmt::format("completed:{}", code));
341 :
342 : // Check for success code
343 0 : if (code == 200)
344 0 : return true;
345 :
346 : // If the server returns the 410 Gone status, interpret that as meaning
347 : // it no longer supports uploads (at least from this version of the game),
348 : // so shut down and stop talking to it (to avoid wasting bandwidth)
349 0 : if (code == 410)
350 : {
351 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
352 0 : m_Shutdown = true;
353 0 : return false;
354 0 : }
355 : }
356 : else
357 : {
358 0 : std::string errorString(m_ErrorBuffer);
359 :
360 0 : if (errorString.empty())
361 0 : errorString = curl_easy_strerror(err);
362 :
363 0 : SetStatus(fmt::format("failed:{}:{}", static_cast<int>(err), errorString));
364 0 : }
365 :
366 : // We got an unhandled return code or a connection failure;
367 : // push this report back onto the queue and try again after
368 : // a long interval
369 :
370 0 : {
371 0 : std::lock_guard<std::mutex> lock(m_WorkerMutex);
372 0 : m_ReportQueue.push_front(report);
373 0 : }
374 :
375 0 : m_PauseUntilTime = timer_Time() + RECONNECT_INVERVAL;
376 0 : return false;
377 0 : }
378 :
379 0 : void ConstructRequestData(const CUserReport& report)
380 : {
381 : // Construct the POST request data in the application/x-www-form-urlencoded format
382 :
383 0 : std::string r;
384 :
385 0 : r += "user_id=";
386 0 : AppendEscaped(r, m_UserID);
387 :
388 0 : r = fmt::format("{}&time={}", std::move(r), report.m_Time);
389 :
390 0 : r += "&type=";
391 0 : AppendEscaped(r, report.m_Type);
392 :
393 0 : r = fmt::format("{}&version={}", std::move(r), report.m_Version);
394 :
395 0 : r += "&data=";
396 0 : AppendEscaped(r, report.m_Data);
397 :
398 : // Compress the content with zlib to save bandwidth.
399 : // (Note that we send a request with unlabelled compressed data instead
400 : // of using Content-Encoding, because Content-Encoding is a mess and causes
401 : // problems with servers and breaks Content-Length and this is much easier.)
402 0 : std::string compressed;
403 0 : compressed.resize(compressBound(r.size()));
404 0 : uLongf destLen = compressed.size();
405 0 : int ok = compress((Bytef*)compressed.c_str(), &destLen, (const Bytef*)r.c_str(), r.size());
406 0 : ENSURE(ok == Z_OK);
407 0 : compressed.resize(destLen);
408 :
409 0 : m_RequestData.swap(compressed);
410 0 : }
411 :
412 0 : void AppendEscaped(std::string& buffer, const std::string& str)
413 : {
414 0 : char* escaped = curl_easy_escape(m_Curl, str.c_str(), str.size());
415 0 : buffer += escaped;
416 0 : curl_free(escaped);
417 0 : }
418 :
419 0 : static size_t ReceiveCallback(void* buffer, size_t size, size_t nmemb, void* userp)
420 : {
421 0 : CUserReporterWorker* self = static_cast<CUserReporterWorker*>(userp);
422 :
423 0 : if (self->GetShutdown())
424 : return 0; // signals an error
425 :
426 0 : self->m_ResponseData += std::string((char*)buffer, (char*)buffer+size*nmemb);
427 :
428 0 : return size*nmemb;
429 : }
430 :
431 0 : static size_t SendCallback(char* bufptr, size_t size, size_t nmemb, void* userp)
432 : {
433 0 : CUserReporterWorker* self = static_cast<CUserReporterWorker*>(userp);
434 :
435 0 : if (self->GetShutdown())
436 : return CURL_READFUNC_ABORT; // signals an error
437 :
438 : // We can return as much data as available, up to the buffer size
439 0 : size_t amount = std::min(self->m_RequestData.size() - self->m_RequestDataOffset, size*nmemb);
440 :
441 : // ...But restrict to sending a small amount at once, so that we remain
442 : // responsive to shutdown requests even if the network is pretty slow
443 0 : amount = std::min((size_t)1024, amount);
444 :
445 0 : if(amount != 0) // (avoids invalid operator[] call where index=size)
446 : {
447 0 : memcpy(bufptr, &self->m_RequestData[self->m_RequestDataOffset], amount);
448 0 : self->m_RequestDataOffset += amount;
449 : }
450 :
451 0 : self->SetStatus(fmt::format("sending:{:L}",
452 0 : static_cast<double>(self->m_RequestDataOffset) / self->m_RequestData.size()));
453 :
454 0 : return amount;
455 : }
456 :
457 : private:
458 : // Concurrency members:
459 : std::mutex m_WorkerMutex;
460 : Future<void> m_Future;
461 : bool m_ProxyInitialised;
462 :
463 : // Shared by main thread and worker thread:
464 : // These variables are all protected by m_WorkerMutex
465 : std::deque<std::shared_ptr<CUserReport>> m_ReportQueue;
466 : bool m_Enabled;
467 : bool m_Shutdown;
468 : std::string m_Status;
469 :
470 : // Initialised in constructor by main thread; otherwise used only by worker thread:
471 : std::string m_URL;
472 : std::string m_UserID;
473 : CURL* m_Curl;
474 : curl_slist* m_Headers;
475 : double m_PauseUntilTime;
476 :
477 : // Only used by worker thread:
478 : std::string m_ResponseData;
479 : std::string m_RequestData;
480 : size_t m_RequestDataOffset;
481 : char m_ErrorBuffer[CURL_ERROR_SIZE];
482 :
483 : // Only used by main thread:
484 : double m_LastUpdateTime;
485 : };
486 :
487 :
488 :
489 0 : CUserReporter::CUserReporter() :
490 0 : m_Worker(NULL)
491 : {
492 0 : }
493 :
494 1 : CUserReporter::~CUserReporter()
495 : {
496 1 : ENSURE(!m_Worker); // Deinitialize should have been called before shutdown
497 1 : }
498 :
499 0 : std::string CUserReporter::LoadUserID()
500 : {
501 : // Read the user ID from user.cfg (if there is one)
502 0 : std::string userID{g_ConfigDB.Get("userreport.id", std::string{})};
503 :
504 : // If we don't have a validly-formatted user ID, generate a new one
505 0 : if (userID.length() != 16)
506 : {
507 0 : std::uint8_t bytes[8] = {0};
508 0 : sys_generate_random_bytes(bytes, ARRAY_SIZE(bytes));
509 : // ignore failures - there's not much we can do about it
510 :
511 0 : userID = "";
512 0 : for (size_t i = 0; i < ARRAY_SIZE(bytes); ++i)
513 : {
514 0 : char hex[3];
515 0 : sprintf_s(hex, ARRAY_SIZE(hex), "%02x", (unsigned int)bytes[i]);
516 0 : userID += hex;
517 : }
518 :
519 0 : g_ConfigDB.SetValueString(CFG_USER, "userreport.id", userID);
520 0 : g_ConfigDB.WriteValueToFile(CFG_USER, "userreport.id", userID);
521 : }
522 :
523 0 : return userID;
524 0 : }
525 :
526 0 : bool CUserReporter::IsReportingEnabled()
527 : {
528 0 : return g_ConfigDB.Get("userreport.enabledversion", -1) >= REPORTER_VERSION;
529 : }
530 :
531 0 : void CUserReporter::SetReportingEnabled(bool enabled)
532 : {
533 0 : const std::string val{std::to_string(enabled ? REPORTER_VERSION : 0)};
534 0 : g_ConfigDB.SetValueString(CFG_USER, "userreport.enabledversion", val);
535 0 : g_ConfigDB.WriteValueToFile(CFG_USER, "userreport.enabledversion", val);
536 :
537 0 : if (m_Worker)
538 0 : m_Worker->SetEnabled(enabled);
539 0 : }
540 :
541 0 : std::string CUserReporter::GetStatus()
542 : {
543 0 : if (!m_Worker)
544 0 : return "disabled";
545 :
546 0 : return m_Worker->GetStatus();
547 : }
548 :
549 0 : void CUserReporter::Initialize()
550 : {
551 0 : ENSURE(!m_Worker); // must only be called once
552 :
553 0 : m_Worker = new CUserReporterWorker{LoadUserID(),
554 0 : g_ConfigDB.Get("userreport.url_upload", std::string{})};
555 0 : m_Worker->SetEnabled(IsReportingEnabled());
556 0 : }
557 :
558 0 : void CUserReporter::Deinitialize()
559 : {
560 0 : PROFILE2("CUserReporter::Deinitialize");
561 0 : if (!m_Worker)
562 0 : return;
563 :
564 0 : if (m_Worker->Shutdown())
565 : {
566 : // Worker was shut down cleanly
567 0 : SAFE_DELETE(m_Worker);
568 : }
569 : else
570 : {
571 : // Worker failed to shut down in a reasonable time
572 : // Leak the resources (since that's better than hanging or crashing)
573 0 : m_Worker = NULL;
574 : }
575 0 : }
576 :
577 0 : void CUserReporter::Update()
578 : {
579 0 : if (m_Worker)
580 0 : m_Worker->Update();
581 0 : }
582 :
583 0 : void CUserReporter::SubmitReport(const std::string& type, int version, const std::string& data, const std::string& dataHumanReadable)
584 : {
585 : // Write to logfile, enabling users to assess privacy concerns before the data is submitted
586 0 : if (!dataHumanReadable.empty())
587 : {
588 0 : OsPath path = psLogDir() / OsPath("userreport_" + type + ".txt");
589 0 : std::ofstream stream(OsString(path), std::ofstream::trunc);
590 0 : if (stream)
591 : {
592 0 : debug_printf("UserReport written to '%s'\n", path.string8().c_str());
593 0 : stream << dataHumanReadable << std::endl;
594 0 : stream.close();
595 : }
596 : else
597 0 : debug_printf("Failed to write UserReport to '%s'\n", path.string8().c_str());
598 0 : }
599 :
600 : // If not initialised, discard the report
601 0 : if (!m_Worker)
602 0 : return;
603 :
604 : // Actual submit
605 0 : std::shared_ptr<CUserReport> report = std::make_shared<CUserReport>();
606 0 : report->m_Time = time(NULL);
607 0 : report->m_Type = type;
608 0 : report->m_Version = version;
609 0 : report->m_Data = data;
610 :
611 0 : m_Worker->Submit(report);
612 0 : }
|