Update: Translations from eints
[openttd-github.git] / src / network / network_content.cpp
blob560824e8b279bc0ee7fe23275a1dc749c75a831c
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file network_content.cpp Content sending/receiving part of the network protocol. */
10 #include "../stdafx.h"
11 #include "../rev.h"
12 #include "../ai/ai.hpp"
13 #include "../game/game.hpp"
14 #include "../window_func.h"
15 #include "../error.h"
16 #include "../fileio_func.h"
17 #include "../base_media_base.h"
18 #include "../settings_type.h"
19 #include "network_content.h"
21 #include "table/strings.h"
23 #if defined(WITH_ZLIB)
24 #include <zlib.h>
25 #endif
27 #ifdef __EMSCRIPTEN__
28 # include <emscripten.h>
29 #endif
31 #include "../safeguards.h"
33 extern bool HasScenario(const ContentInfo *ci, bool md5sum);
35 /** The client we use to connect to the server. */
36 ClientNetworkContentSocketHandler _network_content_client;
38 /** Wrapper function for the HasProc */
39 static bool HasGRFConfig(const ContentInfo *ci, bool md5sum)
41 return FindGRFConfig(BSWAP32(ci->unique_id), md5sum ? FGCM_EXACT : FGCM_ANY, md5sum ? &ci->md5sum : nullptr) != nullptr;
44 /**
45 * Check whether a function piece of content is locally known.
46 * Matches on the unique ID and possibly the MD5 checksum.
47 * @param ci the content info to search for
48 * @param md5sum also match the MD5 checksum?
49 * @return true iff it's known
51 typedef bool (*HasProc)(const ContentInfo *ci, bool md5sum);
53 bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet &p)
55 ContentInfo *ci = new ContentInfo();
56 ci->type = (ContentType)p.Recv_uint8();
57 ci->id = (ContentID)p.Recv_uint32();
58 ci->filesize = p.Recv_uint32();
60 ci->name = p.Recv_string(NETWORK_CONTENT_NAME_LENGTH);
61 ci->version = p.Recv_string(NETWORK_CONTENT_VERSION_LENGTH);
62 ci->url = p.Recv_string(NETWORK_CONTENT_URL_LENGTH);
63 ci->description = p.Recv_string(NETWORK_CONTENT_DESC_LENGTH, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE);
65 ci->unique_id = p.Recv_uint32();
66 p.Recv_bytes(ci->md5sum);
68 uint dependency_count = p.Recv_uint8();
69 ci->dependencies.reserve(dependency_count);
70 for (uint i = 0; i < dependency_count; i++) {
71 ContentID dependency_cid = (ContentID)p.Recv_uint32();
72 ci->dependencies.push_back(dependency_cid);
73 this->reverse_dependency_map.emplace(dependency_cid, ci->id);
76 uint tag_count = p.Recv_uint8();
77 ci->tags.reserve(tag_count);
78 for (uint i = 0; i < tag_count; i++) ci->tags.push_back(p.Recv_string(NETWORK_CONTENT_TAG_LENGTH));
80 if (!ci->IsValid()) {
81 delete ci;
82 this->CloseConnection();
83 return false;
86 /* Find the appropriate check function */
87 HasProc proc = nullptr;
88 switch (ci->type) {
89 case CONTENT_TYPE_NEWGRF:
90 proc = HasGRFConfig;
91 break;
93 case CONTENT_TYPE_BASE_GRAPHICS:
94 proc = BaseGraphics::HasSet;
95 break;
97 case CONTENT_TYPE_BASE_MUSIC:
98 proc = BaseMusic::HasSet;
99 break;
101 case CONTENT_TYPE_BASE_SOUNDS:
102 proc = BaseSounds::HasSet;
103 break;
105 case CONTENT_TYPE_AI:
106 proc = AI::HasAI; break;
107 break;
109 case CONTENT_TYPE_AI_LIBRARY:
110 proc = AI::HasAILibrary; break;
111 break;
113 case CONTENT_TYPE_GAME:
114 proc = Game::HasGame; break;
115 break;
117 case CONTENT_TYPE_GAME_LIBRARY:
118 proc = Game::HasGameLibrary; break;
119 break;
121 case CONTENT_TYPE_SCENARIO:
122 case CONTENT_TYPE_HEIGHTMAP:
123 proc = HasScenario;
124 break;
126 default:
127 break;
130 if (proc != nullptr) {
131 if (proc(ci, true)) {
132 ci->state = ContentInfo::ALREADY_HERE;
133 } else {
134 ci->state = ContentInfo::UNSELECTED;
135 if (proc(ci, false)) ci->upgrade = true;
137 } else {
138 ci->state = ContentInfo::UNSELECTED;
141 /* Something we don't have and has filesize 0 does not exist in the system */
142 if (ci->state == ContentInfo::UNSELECTED && ci->filesize == 0) ci->state = ContentInfo::DOES_NOT_EXIST;
144 /* Do we already have a stub for this? */
145 for (ContentInfo *ici : this->infos) {
146 if (ici->type == ci->type && ici->unique_id == ci->unique_id && ci->md5sum == ici->md5sum) {
147 /* Preserve the name if possible */
148 if (ci->name.empty()) ci->name = ici->name;
149 if (ici->IsSelected()) ci->state = ici->state;
152 * As ici might be selected by the content window we cannot delete that.
153 * However, we want to keep most of the values of ci, except the values
154 * we (just) already preserved.
156 *ici = *ci;
157 delete ci;
159 this->OnReceiveContentInfo(ici);
160 return true;
164 /* Missing content info? Don't list it */
165 if (ci->filesize == 0) {
166 delete ci;
167 return true;
170 this->infos.push_back(ci);
172 /* Incoming data means that we might need to reconsider dependencies */
173 ConstContentVector parents;
174 this->ReverseLookupTreeDependency(parents, ci);
175 for (const ContentInfo *ici : parents) {
176 this->CheckDependencyState(const_cast<ContentInfo *>(ici));
179 this->OnReceiveContentInfo(ci);
181 return true;
185 * Request the content list for the given type.
186 * @param type The content type to request the list for.
188 void ClientNetworkContentSocketHandler::RequestContentList(ContentType type)
190 if (type == CONTENT_TYPE_END) {
191 this->RequestContentList(CONTENT_TYPE_BASE_GRAPHICS);
192 this->RequestContentList(CONTENT_TYPE_BASE_MUSIC);
193 this->RequestContentList(CONTENT_TYPE_BASE_SOUNDS);
194 this->RequestContentList(CONTENT_TYPE_SCENARIO);
195 this->RequestContentList(CONTENT_TYPE_HEIGHTMAP);
196 this->RequestContentList(CONTENT_TYPE_AI);
197 this->RequestContentList(CONTENT_TYPE_AI_LIBRARY);
198 this->RequestContentList(CONTENT_TYPE_GAME);
199 this->RequestContentList(CONTENT_TYPE_GAME_LIBRARY);
200 this->RequestContentList(CONTENT_TYPE_NEWGRF);
201 return;
204 this->Connect();
206 auto p = std::make_unique<Packet>(this, PACKET_CONTENT_CLIENT_INFO_LIST);
207 p->Send_uint8 ((uint8_t)type);
208 p->Send_uint32(0xffffffff);
209 p->Send_uint8 (1);
210 p->Send_string("vanilla");
211 p->Send_string(_openttd_content_version);
213 /* Patchpacks can extend the list with one. In BaNaNaS metadata you can
214 * add a branch in the 'compatibility' list, to filter on this. If you want
215 * your patchpack to be mentioned in the BaNaNaS web-interface, create an
216 * issue on https://github.com/OpenTTD/bananas-api asking for this.
218 p->Send_string("patchpack"); // Or what-ever the name of your patchpack is.
219 p->Send_string(_openttd_content_version_patchpack);
223 this->SendPacket(std::move(p));
227 * Request the content list for a given number of content IDs.
228 * @param count The number of IDs to request.
229 * @param content_ids The unique identifiers of the content to request information about.
231 void ClientNetworkContentSocketHandler::RequestContentList(uint count, const ContentID *content_ids)
233 this->Connect();
235 while (count > 0) {
236 /* We can "only" send a limited number of IDs in a single packet.
237 * A packet begins with the packet size and a byte for the type.
238 * Then this packet adds a uint16_t for the count in this packet.
239 * The rest of the packet can be used for the IDs. */
240 uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(uint8_t) - sizeof(uint16_t)) / sizeof(uint32_t));
242 auto p = std::make_unique<Packet>(this, PACKET_CONTENT_CLIENT_INFO_ID, TCP_MTU);
243 p->Send_uint16(p_count);
245 for (uint i = 0; i < p_count; i++) {
246 p->Send_uint32(content_ids[i]);
249 this->SendPacket(std::move(p));
250 count -= p_count;
251 content_ids += p_count;
256 * Request the content list for a list of content.
257 * @param cv List with unique IDs and MD5 checksums.
258 * @param send_md5sum Whether we want a MD5 checksum matched set of files or not.
260 void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bool send_md5sum)
262 if (cv == nullptr) return;
264 this->Connect();
266 assert(cv->size() < 255);
267 assert(cv->size() < (TCP_MTU - sizeof(PacketSize) - sizeof(uint8_t) - sizeof(uint8_t)) /
268 (sizeof(uint8_t) + sizeof(uint32_t) + (send_md5sum ? MD5_HASH_BYTES : 0)));
270 auto p = std::make_unique<Packet>(this, send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID, TCP_MTU);
271 p->Send_uint8((uint8_t)cv->size());
273 for (const ContentInfo *ci : *cv) {
274 p->Send_uint8((uint8_t)ci->type);
275 p->Send_uint32(ci->unique_id);
276 if (!send_md5sum) continue;
277 p->Send_bytes(ci->md5sum);
280 this->SendPacket(std::move(p));
282 for (ContentInfo *ci : *cv) {
283 bool found = false;
284 for (ContentInfo *ci2 : this->infos) {
285 if (ci->type == ci2->type && ci->unique_id == ci2->unique_id &&
286 (!send_md5sum || ci->md5sum == ci2->md5sum)) {
287 found = true;
288 break;
291 if (!found) {
292 this->infos.push_back(ci);
293 } else {
294 delete ci;
300 * Actually begin downloading the content we selected.
301 * @param[out] files The number of files we are going to download.
302 * @param[out] bytes The number of bytes we are going to download.
303 * @param fallback Whether to use the fallback or not.
305 void ClientNetworkContentSocketHandler::DownloadSelectedContent(uint &files, uint &bytes, bool fallback)
307 bytes = 0;
309 ContentIDList content;
310 for (const ContentInfo *ci : this->infos) {
311 if (!ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) continue;
313 content.push_back(ci->id);
314 bytes += ci->filesize;
317 files = (uint)content.size();
319 /* If there's nothing to download, do nothing. */
320 if (files == 0) return;
322 this->isCancelled = false;
324 if (fallback) {
325 this->DownloadSelectedContentFallback(content);
326 } else {
327 this->DownloadSelectedContentHTTP(content);
332 * Initiate downloading the content over HTTP.
333 * @param content The content to download.
335 void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const ContentIDList &content)
337 std::string content_request;
338 for (const ContentID &id : content) {
339 content_request += std::to_string(id) + "\n";
342 this->http_response_index = -1;
344 NetworkHTTPSocketHandler::Connect(NetworkContentMirrorUriString(), this, content_request);
348 * Initiate downloading the content over the fallback protocol.
349 * @param content The content to download.
351 void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const ContentIDList &content)
353 uint count = (uint)content.size();
354 const ContentID *content_ids = content.data();
355 this->Connect();
357 while (count > 0) {
358 /* We can "only" send a limited number of IDs in a single packet.
359 * A packet begins with the packet size and a byte for the type.
360 * Then this packet adds a uint16_t for the count in this packet.
361 * The rest of the packet can be used for the IDs. */
362 uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(uint8_t) - sizeof(uint16_t)) / sizeof(uint32_t));
364 auto p = std::make_unique<Packet>(this, PACKET_CONTENT_CLIENT_CONTENT, TCP_MTU);
365 p->Send_uint16(p_count);
367 for (uint i = 0; i < p_count; i++) {
368 p->Send_uint32(content_ids[i]);
371 this->SendPacket(std::move(p));
372 count -= p_count;
373 content_ids += p_count;
378 * Determine the full filename of a piece of content information
379 * @param ci the information to get the filename from
380 * @param compressed should the filename end with .gz?
381 * @return a statically allocated buffer with the filename or
382 * nullptr when no filename could be made.
384 static std::string GetFullFilename(const ContentInfo *ci, bool compressed)
386 Subdirectory dir = GetContentInfoSubDir(ci->type);
387 if (dir == NO_DIRECTORY) return {};
389 std::string buf = FioGetDirectory(SP_AUTODOWNLOAD_DIR, dir);
390 buf += ci->filename;
391 buf += compressed ? ".tar.gz" : ".tar";
393 return buf;
397 * Gunzip a given file and remove the .gz if successful.
398 * @param ci container with filename
399 * @return true if the gunzip completed
401 static bool GunzipFile(const ContentInfo *ci)
403 #if defined(WITH_ZLIB)
404 bool ret = true;
406 /* Need to open the file with fopen() to support non-ASCII on Windows. */
407 auto ftmp = FileHandle::Open(GetFullFilename(ci, true), "rb");
408 if (!ftmp.has_value()) return false;
409 /* Duplicate the handle, and close the FILE*, to avoid double-closing the handle later. */
410 int fdup = dup(fileno(*ftmp));
411 gzFile fin = gzdopen(fdup, "rb");
412 ftmp.reset();
414 auto fout = FileHandle::Open(GetFullFilename(ci, false), "wb");
416 if (fin == nullptr || !fout.has_value()) {
417 ret = false;
418 } else {
419 uint8_t buff[8192];
420 for (;;) {
421 int read = gzread(fin, buff, sizeof(buff));
422 if (read == 0) {
423 /* If gzread() returns 0, either the end-of-file has been
424 * reached or an underlying read error has occurred.
426 * gzeof() can't be used, because:
427 * 1.2.5 - it is safe, 1 means 'everything was OK'
428 * 1.2.3.5, 1.2.4 - 0 or 1 is returned 'randomly'
429 * 1.2.3.3 - 1 is returned for truncated archive
431 * So we use gzerror(). When proper end of archive
432 * has been reached, then:
433 * errnum == Z_STREAM_END in 1.2.3.3,
434 * errnum == 0 in 1.2.4 and 1.2.5 */
435 int errnum;
436 gzerror(fin, &errnum);
437 if (errnum != 0 && errnum != Z_STREAM_END) ret = false;
438 break;
440 if (read < 0 || static_cast<size_t>(read) != fwrite(buff, 1, read, *fout)) {
441 /* If gzread() returns -1, there was an error in archive */
442 ret = false;
443 break;
445 /* DO NOT DO THIS! It will fail to detect broken archive with 1.2.3.3!
446 * if (read < sizeof(buff)) break; */
450 if (fin != nullptr) {
451 gzclose(fin);
452 } else if (fdup != -1) {
453 /* Failing gzdopen does not close the passed file descriptor. */
454 close(fdup);
457 return ret;
458 #else
459 NOT_REACHED();
460 #endif /* defined(WITH_ZLIB) */
464 * Simple wrapper around fwrite to be able to pass it to Packet's TransferOut.
465 * @param file The file to write data to.
466 * @param buffer The buffer to write to the file.
467 * @param amount The number of bytes to write.
468 * @return The number of bytes that were written.
470 static inline ssize_t TransferOutFWrite(std::optional<FileHandle> &file, const char *buffer, size_t amount)
472 return fwrite(buffer, 1, amount, *file);
475 bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet &p)
477 if (!this->curFile.has_value()) {
478 delete this->curInfo;
479 /* When we haven't opened a file this must be our first packet with metadata. */
480 this->curInfo = new ContentInfo;
481 this->curInfo->type = (ContentType)p.Recv_uint8();
482 this->curInfo->id = (ContentID)p.Recv_uint32();
483 this->curInfo->filesize = p.Recv_uint32();
484 this->curInfo->filename = p.Recv_string(NETWORK_CONTENT_FILENAME_LENGTH);
486 if (!this->BeforeDownload()) {
487 this->CloseConnection();
488 return false;
490 } else {
491 /* We have a file opened, thus are downloading internal content */
492 size_t toRead = p.RemainingBytesToTransfer();
493 if (toRead != 0 && static_cast<size_t>(p.TransferOut(TransferOutFWrite, std::ref(this->curFile))) != toRead) {
494 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD);
495 ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
496 this->CloseConnection();
497 this->curFile.reset();
499 return false;
502 this->OnDownloadProgress(this->curInfo, (int)toRead);
504 if (toRead == 0) this->AfterDownload();
507 return true;
511 * Handle the opening of the file before downloading.
512 * @return false on any error.
514 bool ClientNetworkContentSocketHandler::BeforeDownload()
516 if (!this->curInfo->IsValid()) {
517 delete this->curInfo;
518 this->curInfo = nullptr;
519 return false;
522 if (this->curInfo->filesize != 0) {
523 /* The filesize is > 0, so we are going to download it */
524 std::string filename = GetFullFilename(this->curInfo, true);
525 if (filename.empty() || !(this->curFile = FileHandle::Open(filename, "wb")).has_value()) {
526 /* Unless that fails of course... */
527 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD);
528 ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
529 return false;
532 return true;
536 * Handle the closing and extracting of a file after
537 * downloading it has been done.
539 void ClientNetworkContentSocketHandler::AfterDownload()
541 /* We read nothing; that's our marker for end-of-stream.
542 * Now gunzip the tar and make it known. */
543 this->curFile.reset();
545 if (GunzipFile(this->curInfo)) {
546 FioRemove(GetFullFilename(this->curInfo, true));
548 Subdirectory sd = GetContentInfoSubDir(this->curInfo->type);
549 if (sd == NO_DIRECTORY) NOT_REACHED();
551 TarScanner ts;
552 std::string fname = GetFullFilename(this->curInfo, false);
553 ts.AddFile(sd, fname);
555 if (this->curInfo->type == CONTENT_TYPE_BASE_MUSIC) {
556 /* Music can't be in a tar. So extract the tar! */
557 ExtractTar(fname, BASESET_DIR);
558 FioRemove(fname);
561 #ifdef __EMSCRIPTEN__
562 EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
563 #endif
565 this->OnDownloadComplete(this->curInfo->id);
566 } else {
567 ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_EXTRACT, INVALID_STRING_ID, WL_ERROR);
571 bool ClientNetworkContentSocketHandler::IsCancelled() const
573 return this->isCancelled;
576 /* Also called to just clean up the mess. */
577 void ClientNetworkContentSocketHandler::OnFailure()
579 this->http_response.clear();
580 this->http_response.shrink_to_fit();
581 this->http_response_index = -2;
583 if (this->curFile.has_value()) {
584 this->OnDownloadProgress(this->curInfo, -1);
586 this->curFile.reset();
589 /* If we fail, download the rest via the 'old' system. */
590 if (!this->isCancelled) {
591 uint files, bytes;
593 this->DownloadSelectedContent(files, bytes, true);
597 void ClientNetworkContentSocketHandler::OnReceiveData(std::unique_ptr<char[]> data, size_t length)
599 assert(data.get() == nullptr || length != 0);
601 /* Ignore any latent data coming from a connection we closed. */
602 if (this->http_response_index == -2) {
603 return;
606 if (this->http_response_index == -1) {
607 if (data != nullptr) {
608 /* Append the rest of the response. */
609 this->http_response.insert(this->http_response.end(), data.get(), data.get() + length);
610 return;
611 } else {
612 /* Make sure the response is properly terminated. */
613 this->http_response.push_back('\0');
615 /* And prepare for receiving the rest of the data. */
616 this->http_response_index = 0;
620 if (data != nullptr) {
621 /* We have data, so write it to the file. */
622 if (fwrite(data.get(), 1, length, *this->curFile) != length) {
623 /* Writing failed somehow, let try via the old method. */
624 this->OnFailure();
625 } else {
626 /* Just received the data. */
627 this->OnDownloadProgress(this->curInfo, (int)length);
630 /* Nothing more to do now. */
631 return;
634 if (this->curFile.has_value()) {
635 /* We've finished downloading a file. */
636 this->AfterDownload();
639 if ((uint)this->http_response_index >= this->http_response.size()) {
640 /* It's not a real failure, but if there's
641 * nothing more to download it helps with
642 * cleaning up the stuff we allocated. */
643 this->OnFailure();
644 return;
647 delete this->curInfo;
648 /* When we haven't opened a file this must be our first packet with metadata. */
649 this->curInfo = new ContentInfo;
651 /** Check p for not being null and return calling OnFailure if that's not the case. */
652 #define check_not_null(p) { if ((p) == nullptr) { this->OnFailure(); return; } }
653 /** Check p for not being null and then terminate, or return calling OnFailure. */
654 #define check_and_terminate(p) { check_not_null(p); *(p) = '\0'; }
656 for (;;) {
657 char *str = this->http_response.data() + this->http_response_index;
658 char *p = strchr(str, '\n');
659 check_and_terminate(p);
661 /* Update the index for the next one */
662 this->http_response_index += (int)strlen(str) + 1;
664 /* Read the ID */
665 p = strchr(str, ',');
666 check_and_terminate(p);
667 this->curInfo->id = (ContentID)atoi(str);
669 /* Read the type */
670 str = p + 1;
671 p = strchr(str, ',');
672 check_and_terminate(p);
673 this->curInfo->type = (ContentType)atoi(str);
675 /* Read the file size */
676 str = p + 1;
677 p = strchr(str, ',');
678 check_and_terminate(p);
679 this->curInfo->filesize = atoi(str);
681 /* Read the URL */
682 str = p + 1;
683 /* Is it a fallback URL? If so, just continue with the next one. */
684 if (strncmp(str, "ottd", 4) == 0) {
685 if ((uint)this->http_response_index >= this->http_response.size()) {
686 /* Have we gone through all lines? */
687 this->OnFailure();
688 return;
690 continue;
693 p = strrchr(str, '/');
694 check_not_null(p);
695 p++; // Start after the '/'
697 std::string filename = p;
698 /* Remove the extension from the string. */
699 for (uint i = 0; i < 2; i++) {
700 auto pos = filename.find_last_of('.');
701 if (pos == std::string::npos) {
702 this->OnFailure();
703 return;
705 filename.erase(pos);
708 /* Copy the string, without extension, to the filename. */
709 this->curInfo->filename = std::move(filename);
711 /* Request the next file. */
712 if (!this->BeforeDownload()) {
713 this->OnFailure();
714 return;
717 NetworkHTTPSocketHandler::Connect(str, this);
718 return;
721 #undef check
722 #undef check_and_terminate
726 * Create a socket handler to handle the connection.
728 ClientNetworkContentSocketHandler::ClientNetworkContentSocketHandler() :
729 NetworkContentSocketHandler(),
730 http_response_index(-2),
731 curFile(std::nullopt),
732 curInfo(nullptr),
733 isConnecting(false),
734 isCancelled(false)
736 this->lastActivity = std::chrono::steady_clock::now();
739 /** Clear up the mess ;) */
740 ClientNetworkContentSocketHandler::~ClientNetworkContentSocketHandler()
742 delete this->curInfo;
744 for (ContentInfo *ci : this->infos) delete ci;
747 /** Connect to the content server. */
748 class NetworkContentConnecter : public TCPConnecter {
749 public:
751 * Initiate the connecting.
752 * @param address The address of the server.
754 NetworkContentConnecter(const std::string &connection_string) : TCPConnecter(connection_string, NETWORK_CONTENT_SERVER_PORT) {}
756 void OnFailure() override
758 _network_content_client.isConnecting = false;
759 _network_content_client.OnConnect(false);
762 void OnConnect(SOCKET s) override
764 assert(_network_content_client.sock == INVALID_SOCKET);
765 _network_content_client.lastActivity = std::chrono::steady_clock::now();
766 _network_content_client.isConnecting = false;
767 _network_content_client.sock = s;
768 _network_content_client.Reopen();
769 _network_content_client.OnConnect(true);
774 * Connect with the content server.
776 void ClientNetworkContentSocketHandler::Connect()
778 if (this->sock != INVALID_SOCKET || this->isConnecting) return;
780 this->isCancelled = false;
781 this->isConnecting = true;
783 TCPConnecter::Create<NetworkContentConnecter>(NetworkContentServerConnectionString());
787 * Disconnect from the content server.
789 NetworkRecvStatus ClientNetworkContentSocketHandler::CloseConnection(bool)
791 NetworkContentSocketHandler::CloseConnection();
793 if (this->sock == INVALID_SOCKET) return NETWORK_RECV_STATUS_OKAY;
795 this->CloseSocket();
796 this->OnDisconnect();
798 return NETWORK_RECV_STATUS_OKAY;
802 * Cancel the current download.
804 void ClientNetworkContentSocketHandler::Cancel(void)
806 this->isCancelled = true;
807 this->CloseConnection();
811 * Check whether we received/can send some data from/to the content server and
812 * when that's the case handle it appropriately
814 void ClientNetworkContentSocketHandler::SendReceive()
816 if (this->sock == INVALID_SOCKET || this->isConnecting) return;
818 /* Close the connection to the content server after inactivity; there can still be downloads pending via HTTP. */
819 if (std::chrono::steady_clock::now() > this->lastActivity + IDLE_TIMEOUT) {
820 this->CloseConnection();
821 return;
824 if (this->CanSendReceive()) {
825 if (this->ReceivePackets()) {
826 /* Only update activity once a packet is received, instead of every time we try it. */
827 this->lastActivity = std::chrono::steady_clock::now();
831 this->SendPackets();
835 * Download information of a given Content ID if not already tried
836 * @param cid the ID to try
838 void ClientNetworkContentSocketHandler::DownloadContentInfo(ContentID cid)
840 /* When we tried to download it already, don't try again */
841 if (std::ranges::find(this->requested, cid) != this->requested.end()) return;
843 this->requested.push_back(cid);
844 this->RequestContentList(1, &cid);
848 * Get the content info based on a ContentID
849 * @param cid the ContentID to search for
850 * @return the ContentInfo or nullptr if not found
852 ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid) const
854 for (ContentInfo *ci : this->infos) {
855 if (ci->id == cid) return ci;
857 return nullptr;
862 * Select a specific content id.
863 * @param cid the content ID to select
865 void ClientNetworkContentSocketHandler::Select(ContentID cid)
867 ContentInfo *ci = this->GetContent(cid);
868 if (ci == nullptr || ci->state != ContentInfo::UNSELECTED) return;
870 ci->state = ContentInfo::SELECTED;
871 this->CheckDependencyState(ci);
875 * Unselect a specific content id.
876 * @param cid the content ID to deselect
878 void ClientNetworkContentSocketHandler::Unselect(ContentID cid)
880 ContentInfo *ci = this->GetContent(cid);
881 if (ci == nullptr || !ci->IsSelected()) return;
883 ci->state = ContentInfo::UNSELECTED;
884 this->CheckDependencyState(ci);
887 /** Select everything we can select */
888 void ClientNetworkContentSocketHandler::SelectAll()
890 for (ContentInfo *ci : this->infos) {
891 if (ci->state == ContentInfo::UNSELECTED) {
892 ci->state = ContentInfo::SELECTED;
893 this->CheckDependencyState(ci);
898 /** Select everything that's an update for something we've got */
899 void ClientNetworkContentSocketHandler::SelectUpgrade()
901 for (ContentInfo *ci : this->infos) {
902 if (ci->state == ContentInfo::UNSELECTED && ci->upgrade) {
903 ci->state = ContentInfo::SELECTED;
904 this->CheckDependencyState(ci);
909 /** Unselect everything that we've not downloaded so far. */
910 void ClientNetworkContentSocketHandler::UnselectAll()
912 for (ContentInfo *ci : this->infos) {
913 if (ci->IsSelected() && ci->state != ContentInfo::ALREADY_HERE) ci->state = ContentInfo::UNSELECTED;
917 /** Toggle the state of a content info and check its dependencies */
918 void ClientNetworkContentSocketHandler::ToggleSelectedState(const ContentInfo *ci)
920 switch (ci->state) {
921 case ContentInfo::SELECTED:
922 case ContentInfo::AUTOSELECTED:
923 this->Unselect(ci->id);
924 break;
926 case ContentInfo::UNSELECTED:
927 this->Select(ci->id);
928 break;
930 default:
931 break;
936 * Reverse lookup the dependencies of (direct) parents over a given child.
937 * @param parents list to store all parents in (is not cleared)
938 * @param child the child to search the parents' dependencies for
940 void ClientNetworkContentSocketHandler::ReverseLookupDependency(ConstContentVector &parents, const ContentInfo *child) const
942 auto range = this->reverse_dependency_map.equal_range(child->id);
944 for (auto iter = range.first; iter != range.second; ++iter) {
945 parents.push_back(GetContent(iter->second));
950 * Reverse lookup the dependencies of all parents over a given child.
951 * @param tree list to store all parents in (is not cleared)
952 * @param child the child to search the parents' dependencies for
954 void ClientNetworkContentSocketHandler::ReverseLookupTreeDependency(ConstContentVector &tree, const ContentInfo *child) const
956 tree.push_back(child);
958 /* First find all direct parents. We can't use the "normal" iterator as
959 * we are including stuff into the vector and as such the vector's data
960 * store can be reallocated (and thus move), which means out iterating
961 * pointer gets invalid. So fall back to the indices. */
962 for (uint i = 0; i < tree.size(); i++) {
963 ConstContentVector parents;
964 this->ReverseLookupDependency(parents, tree[i]);
966 for (const ContentInfo *ci : parents) {
967 include(tree, ci);
973 * Check the dependencies (recursively) of this content info
974 * @param ci the content info to check the dependencies of
976 void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
978 if (ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) {
979 /* Selection is easy; just walk all children and set the
980 * autoselected state. That way we can see what we automatically
981 * selected and thus can unselect when a dependency is removed. */
982 for (auto &dependency : ci->dependencies) {
983 ContentInfo *c = this->GetContent(dependency);
984 if (c == nullptr) {
985 this->DownloadContentInfo(dependency);
986 } else if (c->state == ContentInfo::UNSELECTED) {
987 c->state = ContentInfo::AUTOSELECTED;
988 this->CheckDependencyState(c);
991 return;
994 if (ci->state != ContentInfo::UNSELECTED) return;
996 /* For unselection we need to find the parents of us. We need to
997 * unselect them. After that we unselect all children that we
998 * depend on and are not used as dependency for us, but only when
999 * we automatically selected them. */
1000 ConstContentVector parents;
1001 this->ReverseLookupDependency(parents, ci);
1002 for (const ContentInfo *c : parents) {
1003 if (!c->IsSelected()) continue;
1005 this->Unselect(c->id);
1008 for (auto &dependency : ci->dependencies) {
1009 const ContentInfo *c = this->GetContent(dependency);
1010 if (c == nullptr) {
1011 DownloadContentInfo(dependency);
1012 continue;
1014 if (c->state != ContentInfo::AUTOSELECTED) continue;
1016 /* Only unselect when WE are the only parent. */
1017 parents.clear();
1018 this->ReverseLookupDependency(parents, c);
1020 /* First check whether anything depends on us */
1021 int sel_count = 0;
1022 bool force_selection = false;
1023 for (const ContentInfo *parent_ci : parents) {
1024 if (parent_ci->IsSelected()) sel_count++;
1025 if (parent_ci->state == ContentInfo::SELECTED) force_selection = true;
1027 if (sel_count == 0) {
1028 /* Nothing depends on us */
1029 this->Unselect(c->id);
1030 continue;
1032 /* Something manually selected depends directly on us */
1033 if (force_selection) continue;
1035 /* "Flood" search to find all items in the dependency graph*/
1036 parents.clear();
1037 this->ReverseLookupTreeDependency(parents, c);
1039 /* Is there anything that is "force" selected?, if so... we're done. */
1040 for (const ContentInfo *parent_ci : parents) {
1041 if (parent_ci->state != ContentInfo::SELECTED) continue;
1043 force_selection = true;
1044 break;
1047 /* So something depended directly on us */
1048 if (force_selection) continue;
1050 /* Nothing depends on us, mark the whole graph as unselected.
1051 * After that's done run over them once again to test their children
1052 * to unselect. Don't do it immediately because it'll do exactly what
1053 * we're doing now. */
1054 for (const ContentInfo *parent : parents) {
1055 if (parent->state == ContentInfo::AUTOSELECTED) this->Unselect(parent->id);
1057 for (const ContentInfo *parent : parents) {
1058 this->CheckDependencyState(this->GetContent(parent->id));
1063 /** Clear all downloaded content information. */
1064 void ClientNetworkContentSocketHandler::Clear()
1066 for (ContentInfo *c : this->infos) delete c;
1068 this->infos.clear();
1069 this->requested.clear();
1070 this->reverse_dependency_map.clear();
1073 /*** CALLBACK ***/
1075 void ClientNetworkContentSocketHandler::OnConnect(bool success)
1077 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1078 ContentCallback *cb = this->callbacks[i];
1079 /* the callback may remove itself from this->callbacks */
1080 cb->OnConnect(success);
1081 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1085 void ClientNetworkContentSocketHandler::OnDisconnect()
1087 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1088 ContentCallback *cb = this->callbacks[i];
1089 cb->OnDisconnect();
1090 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1094 void ClientNetworkContentSocketHandler::OnReceiveContentInfo(const ContentInfo *ci)
1096 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1097 ContentCallback *cb = this->callbacks[i];
1098 /* the callback may add items and/or remove itself from this->callbacks */
1099 cb->OnReceiveContentInfo(ci);
1100 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1104 void ClientNetworkContentSocketHandler::OnDownloadProgress(const ContentInfo *ci, int bytes)
1106 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1107 ContentCallback *cb = this->callbacks[i];
1108 cb->OnDownloadProgress(ci, bytes);
1109 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1113 void ClientNetworkContentSocketHandler::OnDownloadComplete(ContentID cid)
1115 ContentInfo *ci = this->GetContent(cid);
1116 if (ci != nullptr) {
1117 ci->state = ContentInfo::ALREADY_HERE;
1120 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1121 ContentCallback *cb = this->callbacks[i];
1122 /* the callback may remove itself from this->callbacks */
1123 cb->OnDownloadComplete(cid);
1124 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;