Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / network / network_content.cpp
blob13172f9ea41da728bede140243826f08ff309a7c
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 "../base_media_base.h"
17 #include "../settings_type.h"
18 #include "network_content.h"
20 #include "table/strings.h"
22 #if defined(WITH_ZLIB)
23 #include <zlib.h>
24 #endif
26 #ifdef __EMSCRIPTEN__
27 # include <emscripten.h>
28 #endif
30 #include "../safeguards.h"
32 extern bool HasScenario(const ContentInfo *ci, bool md5sum);
34 /** The client we use to connect to the server. */
35 ClientNetworkContentSocketHandler _network_content_client;
37 /** Wrapper function for the HasProc */
38 static bool HasGRFConfig(const ContentInfo *ci, bool md5sum)
40 return FindGRFConfig(BSWAP32(ci->unique_id), md5sum ? FGCM_EXACT : FGCM_ANY, md5sum ? ci->md5sum : nullptr) != nullptr;
43 /**
44 * Check whether a function piece of content is locally known.
45 * Matches on the unique ID and possibly the MD5 checksum.
46 * @param ci the content info to search for
47 * @param md5sum also match the MD5 checksum?
48 * @return true iff it's known
50 typedef bool (*HasProc)(const ContentInfo *ci, bool md5sum);
52 bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
54 ContentInfo *ci = new ContentInfo();
55 ci->type = (ContentType)p->Recv_uint8();
56 ci->id = (ContentID)p->Recv_uint32();
57 ci->filesize = p->Recv_uint32();
59 ci->name = p->Recv_string(NETWORK_CONTENT_NAME_LENGTH);
60 ci->version = p->Recv_string(NETWORK_CONTENT_VERSION_LENGTH);
61 ci->url = p->Recv_string(NETWORK_CONTENT_URL_LENGTH);
62 ci->description = p->Recv_string(NETWORK_CONTENT_DESC_LENGTH, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE);
64 ci->unique_id = p->Recv_uint32();
65 for (uint j = 0; j < sizeof(ci->md5sum); j++) {
66 ci->md5sum[j] = p->Recv_uint8();
69 uint dependency_count = p->Recv_uint8();
70 ci->dependencies.reserve(dependency_count);
71 for (uint i = 0; i < dependency_count; i++) ci->dependencies.push_back((ContentID)p->Recv_uint32());
73 uint tag_count = p->Recv_uint8();
74 ci->tags.reserve(tag_count);
75 for (uint i = 0; i < tag_count; i++) ci->tags.push_back(p->Recv_string(NETWORK_CONTENT_TAG_LENGTH));
77 if (!ci->IsValid()) {
78 delete ci;
79 this->CloseConnection();
80 return false;
83 /* Find the appropriate check function */
84 HasProc proc = nullptr;
85 switch (ci->type) {
86 case CONTENT_TYPE_NEWGRF:
87 proc = HasGRFConfig;
88 break;
90 case CONTENT_TYPE_BASE_GRAPHICS:
91 proc = BaseGraphics::HasSet;
92 break;
94 case CONTENT_TYPE_BASE_MUSIC:
95 proc = BaseMusic::HasSet;
96 break;
98 case CONTENT_TYPE_BASE_SOUNDS:
99 proc = BaseSounds::HasSet;
100 break;
102 case CONTENT_TYPE_AI:
103 proc = AI::HasAI; break;
104 break;
106 case CONTENT_TYPE_AI_LIBRARY:
107 proc = AI::HasAILibrary; break;
108 break;
110 case CONTENT_TYPE_GAME:
111 proc = Game::HasGame; break;
112 break;
114 case CONTENT_TYPE_GAME_LIBRARY:
115 proc = Game::HasGameLibrary; break;
116 break;
118 case CONTENT_TYPE_SCENARIO:
119 case CONTENT_TYPE_HEIGHTMAP:
120 proc = HasScenario;
121 break;
123 default:
124 break;
127 if (proc != nullptr) {
128 if (proc(ci, true)) {
129 ci->state = ContentInfo::ALREADY_HERE;
130 } else {
131 ci->state = ContentInfo::UNSELECTED;
132 if (proc(ci, false)) ci->upgrade = true;
134 } else {
135 ci->state = ContentInfo::UNSELECTED;
138 /* Something we don't have and has filesize 0 does not exist in the system */
139 if (ci->state == ContentInfo::UNSELECTED && ci->filesize == 0) ci->state = ContentInfo::DOES_NOT_EXIST;
141 /* Do we already have a stub for this? */
142 for (ContentInfo *ici : this->infos) {
143 if (ici->type == ci->type && ici->unique_id == ci->unique_id &&
144 memcmp(ci->md5sum, ici->md5sum, sizeof(ci->md5sum)) == 0) {
145 /* Preserve the name if possible */
146 if (ci->name.empty()) ci->name = ici->name;
147 if (ici->IsSelected()) ci->state = ici->state;
150 * As ici might be selected by the content window we cannot delete that.
151 * However, we want to keep most of the values of ci, except the values
152 * we (just) already preserved.
154 *ici = *ci;
155 delete ci;
157 this->OnReceiveContentInfo(ici);
158 return true;
162 /* Missing content info? Don't list it */
163 if (ci->filesize == 0) {
164 delete ci;
165 return true;
168 this->infos.push_back(ci);
170 /* Incoming data means that we might need to reconsider dependencies */
171 for (ContentInfo *ici : this->infos) {
172 this->CheckDependencyState(ici);
175 this->OnReceiveContentInfo(ci);
177 return true;
181 * Request the content list for the given type.
182 * @param type The content type to request the list for.
184 void ClientNetworkContentSocketHandler::RequestContentList(ContentType type)
186 if (type == CONTENT_TYPE_END) {
187 this->RequestContentList(CONTENT_TYPE_BASE_GRAPHICS);
188 this->RequestContentList(CONTENT_TYPE_BASE_MUSIC);
189 this->RequestContentList(CONTENT_TYPE_BASE_SOUNDS);
190 this->RequestContentList(CONTENT_TYPE_SCENARIO);
191 this->RequestContentList(CONTENT_TYPE_HEIGHTMAP);
192 this->RequestContentList(CONTENT_TYPE_AI);
193 this->RequestContentList(CONTENT_TYPE_AI_LIBRARY);
194 this->RequestContentList(CONTENT_TYPE_GAME);
195 this->RequestContentList(CONTENT_TYPE_GAME_LIBRARY);
196 this->RequestContentList(CONTENT_TYPE_NEWGRF);
197 return;
200 this->Connect();
202 Packet *p = new Packet(PACKET_CONTENT_CLIENT_INFO_LIST);
203 p->Send_uint8 ((byte)type);
204 p->Send_uint32(_openttd_newgrf_version);
206 this->SendPacket(p);
210 * Request the content list for a given number of content IDs.
211 * @param count The number of IDs to request.
212 * @param content_ids The unique identifiers of the content to request information about.
214 void ClientNetworkContentSocketHandler::RequestContentList(uint count, const ContentID *content_ids)
216 this->Connect();
218 while (count > 0) {
219 /* We can "only" send a limited number of IDs in a single packet.
220 * A packet begins with the packet size and a byte for the type.
221 * Then this packet adds a uint16 for the count in this packet.
222 * The rest of the packet can be used for the IDs. */
223 uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
225 Packet *p = new Packet(PACKET_CONTENT_CLIENT_INFO_ID, TCP_MTU);
226 p->Send_uint16(p_count);
228 for (uint i = 0; i < p_count; i++) {
229 p->Send_uint32(content_ids[i]);
232 this->SendPacket(p);
233 count -= p_count;
234 content_ids += p_count;
239 * Request the content list for a list of content.
240 * @param cv List with unique IDs and MD5 checksums.
241 * @param send_md5sum Whether we want a MD5 checksum matched set of files or not.
243 void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bool send_md5sum)
245 if (cv == nullptr) return;
247 this->Connect();
249 assert(cv->size() < 255);
250 assert(cv->size() < (TCP_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint8)) /
251 (sizeof(uint8) + sizeof(uint32) + (send_md5sum ? /*sizeof(ContentInfo::md5sum)*/16 : 0)));
253 Packet *p = new Packet(send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID, TCP_MTU);
254 p->Send_uint8((uint8)cv->size());
256 for (const ContentInfo *ci : *cv) {
257 p->Send_uint8((byte)ci->type);
258 p->Send_uint32(ci->unique_id);
259 if (!send_md5sum) continue;
261 for (uint j = 0; j < sizeof(ci->md5sum); j++) {
262 p->Send_uint8(ci->md5sum[j]);
266 this->SendPacket(p);
268 for (ContentInfo *ci : *cv) {
269 bool found = false;
270 for (ContentInfo *ci2 : this->infos) {
271 if (ci->type == ci2->type && ci->unique_id == ci2->unique_id &&
272 (!send_md5sum || memcmp(ci->md5sum, ci2->md5sum, sizeof(ci->md5sum)) == 0)) {
273 found = true;
274 break;
277 if (!found) {
278 this->infos.push_back(ci);
279 } else {
280 delete ci;
286 * Actually begin downloading the content we selected.
287 * @param[out] files The number of files we are going to download.
288 * @param[out] bytes The number of bytes we are going to download.
289 * @param fallback Whether to use the fallback or not.
291 void ClientNetworkContentSocketHandler::DownloadSelectedContent(uint &files, uint &bytes, bool fallback)
293 bytes = 0;
295 #ifdef __EMSCRIPTEN__
296 /* Emscripten is loaded via an HTTPS connection. As such, it is very
297 * difficult to make HTTP connections. So always use the TCP method of
298 * downloading content. */
299 fallback = true;
300 #endif
302 ContentIDList content;
303 for (const ContentInfo *ci : this->infos) {
304 if (!ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) continue;
306 content.push_back(ci->id);
307 bytes += ci->filesize;
310 files = (uint)content.size();
312 /* If there's nothing to download, do nothing. */
313 if (files == 0) return;
315 if (_settings_client.network.no_http_content_downloads || fallback) {
316 this->DownloadSelectedContentFallback(content);
317 } else {
318 this->DownloadSelectedContentHTTP(content);
323 * Initiate downloading the content over HTTP.
324 * @param content The content to download.
326 void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const ContentIDList &content)
328 uint count = (uint)content.size();
330 /* Allocate memory for the whole request.
331 * Requests are "id\nid\n..." (as strings), so assume the maximum ID,
332 * which is uint32 so 10 characters long. Then the newlines and
333 * multiply that all with the count and then add the '\0'. */
334 uint bytes = (10 + 1) * count + 1;
335 char *content_request = MallocT<char>(bytes);
336 const char *lastof = content_request + bytes - 1;
338 char *p = content_request;
339 for (const ContentID &id : content) {
340 p += seprintf(p, lastof, "%d\n", id);
343 this->http_response_index = -1;
345 new NetworkHTTPContentConnecter(NetworkContentMirrorConnectionString(), this, NETWORK_CONTENT_MIRROR_URL, content_request);
346 /* NetworkHTTPContentConnecter takes over freeing of content_request! */
350 * Initiate downloading the content over the fallback protocol.
351 * @param content The content to download.
353 void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const ContentIDList &content)
355 uint count = (uint)content.size();
356 const ContentID *content_ids = content.data();
357 this->Connect();
359 while (count > 0) {
360 /* We can "only" send a limited number of IDs in a single packet.
361 * A packet begins with the packet size and a byte for the type.
362 * Then this packet adds a uint16 for the count in this packet.
363 * The rest of the packet can be used for the IDs. */
364 uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
366 Packet *p = new Packet(PACKET_CONTENT_CLIENT_CONTENT, TCP_MTU);
367 p->Send_uint16(p_count);
369 for (uint i = 0; i < p_count; i++) {
370 p->Send_uint32(content_ids[i]);
373 this->SendPacket(p);
374 count -= p_count;
375 content_ids += p_count;
380 * Determine the full filename of a piece of content information
381 * @param ci the information to get the filename from
382 * @param compressed should the filename end with .gz?
383 * @return a statically allocated buffer with the filename or
384 * nullptr when no filename could be made.
386 static std::string GetFullFilename(const ContentInfo *ci, bool compressed)
388 Subdirectory dir = GetContentInfoSubDir(ci->type);
389 if (dir == NO_DIRECTORY) return {};
391 std::string buf = FioGetDirectory(SP_AUTODOWNLOAD_DIR, dir);
392 buf += ci->filename;
393 buf += compressed ? ".tar.gz" : ".tar";
395 return buf;
399 * Gunzip a given file and remove the .gz if successful.
400 * @param ci container with filename
401 * @return true if the gunzip completed
403 static bool GunzipFile(const ContentInfo *ci)
405 #if defined(WITH_ZLIB)
406 bool ret = true;
408 /* Need to open the file with fopen() to support non-ASCII on Windows. */
409 FILE *ftmp = fopen(GetFullFilename(ci, true).c_str(), "rb");
410 if (ftmp == nullptr) return false;
411 /* Duplicate the handle, and close the FILE*, to avoid double-closing the handle later. */
412 int fdup = dup(fileno(ftmp));
413 gzFile fin = gzdopen(fdup, "rb");
414 fclose(ftmp);
416 FILE *fout = fopen(GetFullFilename(ci, false).c_str(), "wb");
418 if (fin == nullptr || fout == nullptr) {
419 ret = false;
420 } else {
421 byte buff[8192];
422 for (;;) {
423 int read = gzread(fin, buff, sizeof(buff));
424 if (read == 0) {
425 /* If gzread() returns 0, either the end-of-file has been
426 * reached or an underlying read error has occurred.
428 * gzeof() can't be used, because:
429 * 1.2.5 - it is safe, 1 means 'everything was OK'
430 * 1.2.3.5, 1.2.4 - 0 or 1 is returned 'randomly'
431 * 1.2.3.3 - 1 is returned for truncated archive
433 * So we use gzerror(). When proper end of archive
434 * has been reached, then:
435 * errnum == Z_STREAM_END in 1.2.3.3,
436 * errnum == 0 in 1.2.4 and 1.2.5 */
437 int errnum;
438 gzerror(fin, &errnum);
439 if (errnum != 0 && errnum != Z_STREAM_END) ret = false;
440 break;
442 if (read < 0 || (size_t)read != fwrite(buff, 1, read, fout)) {
443 /* If gzread() returns -1, there was an error in archive */
444 ret = false;
445 break;
447 /* DO NOT DO THIS! It will fail to detect broken archive with 1.2.3.3!
448 * if (read < sizeof(buff)) break; */
452 if (fin != nullptr) {
453 gzclose(fin);
454 } else if (fdup != -1) {
455 /* Failing gzdopen does not close the passed file descriptor. */
456 close(fdup);
458 if (fout != nullptr) fclose(fout);
460 return ret;
461 #else
462 NOT_REACHED();
463 #endif /* defined(WITH_ZLIB) */
467 * Simple wrapper around fwrite to be able to pass it to Packet's TransferOut.
468 * @param file The file to write data to.
469 * @param buffer The buffer to write to the file.
470 * @param amount The number of bytes to write.
471 * @return The number of bytes that were written.
473 static inline ssize_t TransferOutFWrite(FILE *file, const char *buffer, size_t amount)
475 return fwrite(buffer, 1, amount, file);
478 bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p)
480 if (this->curFile == nullptr) {
481 delete this->curInfo;
482 /* When we haven't opened a file this must be our first packet with metadata. */
483 this->curInfo = new ContentInfo;
484 this->curInfo->type = (ContentType)p->Recv_uint8();
485 this->curInfo->id = (ContentID)p->Recv_uint32();
486 this->curInfo->filesize = p->Recv_uint32();
487 this->curInfo->filename = p->Recv_string(NETWORK_CONTENT_FILENAME_LENGTH);
489 if (!this->BeforeDownload()) {
490 this->CloseConnection();
491 return false;
493 } else {
494 /* We have a file opened, thus are downloading internal content */
495 size_t toRead = p->RemainingBytesToTransfer();
496 if (toRead != 0 && (size_t)p->TransferOut(TransferOutFWrite, this->curFile) != toRead) {
497 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD);
498 ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
499 this->CloseConnection();
500 fclose(this->curFile);
501 this->curFile = nullptr;
503 return false;
506 this->OnDownloadProgress(this->curInfo, (int)toRead);
508 if (toRead == 0) this->AfterDownload();
511 return true;
515 * Handle the opening of the file before downloading.
516 * @return false on any error.
518 bool ClientNetworkContentSocketHandler::BeforeDownload()
520 if (!this->curInfo->IsValid()) {
521 delete this->curInfo;
522 this->curInfo = nullptr;
523 return false;
526 if (this->curInfo->filesize != 0) {
527 /* The filesize is > 0, so we are going to download it */
528 std::string filename = GetFullFilename(this->curInfo, true);
529 if (filename.empty() || (this->curFile = fopen(filename.c_str(), "wb")) == nullptr) {
530 /* Unless that fails of course... */
531 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD);
532 ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
533 return false;
536 return true;
540 * Handle the closing and extracting of a file after
541 * downloading it has been done.
543 void ClientNetworkContentSocketHandler::AfterDownload()
545 /* We read nothing; that's our marker for end-of-stream.
546 * Now gunzip the tar and make it known. */
547 fclose(this->curFile);
548 this->curFile = nullptr;
550 if (GunzipFile(this->curInfo)) {
551 unlink(GetFullFilename(this->curInfo, true).c_str());
553 Subdirectory sd = GetContentInfoSubDir(this->curInfo->type);
554 if (sd == NO_DIRECTORY) NOT_REACHED();
556 TarScanner ts;
557 std::string fname = GetFullFilename(this->curInfo, false);
558 ts.AddFile(sd, fname);
560 if (this->curInfo->type == CONTENT_TYPE_BASE_MUSIC) {
561 /* Music can't be in a tar. So extract the tar! */
562 ExtractTar(fname, BASESET_DIR);
563 unlink(fname.c_str());
566 #ifdef __EMSCRIPTEN__
567 EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
568 #endif
570 this->OnDownloadComplete(this->curInfo->id);
571 } else {
572 ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_EXTRACT, INVALID_STRING_ID, WL_ERROR);
576 /* Also called to just clean up the mess. */
577 void ClientNetworkContentSocketHandler::OnFailure()
579 /* If we fail, download the rest via the 'old' system. */
580 uint files, bytes;
581 this->DownloadSelectedContent(files, bytes, true);
583 this->http_response.clear();
584 this->http_response.shrink_to_fit();
585 this->http_response_index = -2;
587 if (this->curFile != nullptr) {
588 /* Revert the download progress when we are going for the old system. */
589 long size = ftell(this->curFile);
590 if (size > 0) this->OnDownloadProgress(this->curInfo, (int)-size);
592 fclose(this->curFile);
593 this->curFile = nullptr;
597 void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t length)
599 assert(data == nullptr || length != 0);
601 /* Ignore any latent data coming from a connection we closed. */
602 if (this->http_response_index == -2) return;
604 if (this->http_response_index == -1) {
605 if (data != nullptr) {
606 /* Append the rest of the response. */
607 this->http_response.insert(this->http_response.end(), data, data + length);
608 return;
609 } else {
610 /* Make sure the response is properly terminated. */
611 this->http_response.push_back('\0');
613 /* And prepare for receiving the rest of the data. */
614 this->http_response_index = 0;
618 if (data != nullptr) {
619 /* We have data, so write it to the file. */
620 if (fwrite(data, 1, length, this->curFile) != length) {
621 /* Writing failed somehow, let try via the old method. */
622 this->OnFailure();
623 } else {
624 /* Just received the data. */
625 this->OnDownloadProgress(this->curInfo, (int)length);
627 /* Nothing more to do now. */
628 return;
631 if (this->curFile != nullptr) {
632 /* We've finished downloading a file. */
633 this->AfterDownload();
636 if ((uint)this->http_response_index >= this->http_response.size()) {
637 /* It's not a real failure, but if there's
638 * nothing more to download it helps with
639 * cleaning up the stuff we allocated. */
640 this->OnFailure();
641 return;
644 delete this->curInfo;
645 /* When we haven't opened a file this must be our first packet with metadata. */
646 this->curInfo = new ContentInfo;
648 /** Check p for not being null and return calling OnFailure if that's not the case. */
649 #define check_not_null(p) { if ((p) == nullptr) { this->OnFailure(); return; } }
650 /** Check p for not being null and then terminate, or return calling OnFailure. */
651 #define check_and_terminate(p) { check_not_null(p); *(p) = '\0'; }
653 for (;;) {
654 char *str = this->http_response.data() + this->http_response_index;
655 char *p = strchr(str, '\n');
656 check_and_terminate(p);
658 /* Update the index for the next one */
659 this->http_response_index += (int)strlen(str) + 1;
661 /* Read the ID */
662 p = strchr(str, ',');
663 check_and_terminate(p);
664 this->curInfo->id = (ContentID)atoi(str);
666 /* Read the type */
667 str = p + 1;
668 p = strchr(str, ',');
669 check_and_terminate(p);
670 this->curInfo->type = (ContentType)atoi(str);
672 /* Read the file size */
673 str = p + 1;
674 p = strchr(str, ',');
675 check_and_terminate(p);
676 this->curInfo->filesize = atoi(str);
678 /* Read the URL */
679 str = p + 1;
680 /* Is it a fallback URL? If so, just continue with the next one. */
681 if (strncmp(str, "ottd", 4) == 0) {
682 if ((uint)this->http_response_index >= this->http_response.size()) {
683 /* Have we gone through all lines? */
684 this->OnFailure();
685 return;
687 continue;
690 p = strrchr(str, '/');
691 check_not_null(p);
692 p++; // Start after the '/'
694 char tmp[MAX_PATH];
695 if (strecpy(tmp, p, lastof(tmp)) == lastof(tmp)) {
696 this->OnFailure();
697 return;
699 /* Remove the extension from the string. */
700 for (uint i = 0; i < 2; i++) {
701 p = strrchr(tmp, '.');
702 check_and_terminate(p);
705 /* Copy the string, without extension, to the filename. */
706 this->curInfo->filename = tmp;
708 /* Request the next file. */
709 if (!this->BeforeDownload()) {
710 this->OnFailure();
711 return;
714 NetworkHTTPSocketHandler::Connect(str, this);
715 return;
718 #undef check
719 #undef check_and_terminate
723 * Create a socket handler to handle the connection.
725 ClientNetworkContentSocketHandler::ClientNetworkContentSocketHandler() :
726 NetworkContentSocketHandler(),
727 http_response_index(-2),
728 curFile(nullptr),
729 curInfo(nullptr),
730 isConnecting(false)
732 this->lastActivity = std::chrono::steady_clock::now();
735 /** Clear up the mess ;) */
736 ClientNetworkContentSocketHandler::~ClientNetworkContentSocketHandler()
738 delete this->curInfo;
739 if (this->curFile != nullptr) fclose(this->curFile);
741 for (ContentInfo *ci : this->infos) delete ci;
744 /** Connect to the content server. */
745 class NetworkContentConnecter : TCPConnecter {
746 public:
748 * Initiate the connecting.
749 * @param address The address of the server.
751 NetworkContentConnecter(const std::string &connection_string) : TCPConnecter(connection_string, NETWORK_CONTENT_SERVER_PORT) {}
753 void OnFailure() override
755 _network_content_client.isConnecting = false;
756 _network_content_client.OnConnect(false);
759 void OnConnect(SOCKET s) override
761 assert(_network_content_client.sock == INVALID_SOCKET);
762 _network_content_client.lastActivity = std::chrono::steady_clock::now();
763 _network_content_client.isConnecting = false;
764 _network_content_client.sock = s;
765 _network_content_client.Reopen();
766 _network_content_client.OnConnect(true);
771 * Connect with the content server.
773 void ClientNetworkContentSocketHandler::Connect()
775 if (this->sock != INVALID_SOCKET || this->isConnecting) return;
776 this->isConnecting = true;
777 new NetworkContentConnecter(NetworkContentServerConnectionString());
781 * Disconnect from the content server.
783 NetworkRecvStatus ClientNetworkContentSocketHandler::CloseConnection(bool error)
785 NetworkContentSocketHandler::CloseConnection();
787 if (this->sock == INVALID_SOCKET) return NETWORK_RECV_STATUS_OKAY;
789 this->CloseSocket();
790 this->OnDisconnect();
792 return NETWORK_RECV_STATUS_OKAY;
796 * Check whether we received/can send some data from/to the content server and
797 * when that's the case handle it appropriately
799 void ClientNetworkContentSocketHandler::SendReceive()
801 if (this->sock == INVALID_SOCKET || this->isConnecting) return;
803 if (std::chrono::steady_clock::now() > this->lastActivity + IDLE_TIMEOUT) {
804 this->CloseConnection();
805 return;
808 if (this->CanSendReceive()) {
809 if (this->ReceivePackets()) {
810 /* Only update activity once a packet is received, instead of every time we try it. */
811 this->lastActivity = std::chrono::steady_clock::now();
815 this->SendPackets();
819 * Download information of a given Content ID if not already tried
820 * @param cid the ID to try
822 void ClientNetworkContentSocketHandler::DownloadContentInfo(ContentID cid)
824 /* When we tried to download it already, don't try again */
825 if (std::find(this->requested.begin(), this->requested.end(), cid) != this->requested.end()) return;
827 this->requested.push_back(cid);
828 this->RequestContentList(1, &cid);
832 * Get the content info based on a ContentID
833 * @param cid the ContentID to search for
834 * @return the ContentInfo or nullptr if not found
836 ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid)
838 for (ContentInfo *ci : this->infos) {
839 if (ci->id == cid) return ci;
841 return nullptr;
846 * Select a specific content id.
847 * @param cid the content ID to select
849 void ClientNetworkContentSocketHandler::Select(ContentID cid)
851 ContentInfo *ci = this->GetContent(cid);
852 if (ci == nullptr || ci->state != ContentInfo::UNSELECTED) return;
854 ci->state = ContentInfo::SELECTED;
855 this->CheckDependencyState(ci);
859 * Unselect a specific content id.
860 * @param cid the content ID to deselect
862 void ClientNetworkContentSocketHandler::Unselect(ContentID cid)
864 ContentInfo *ci = this->GetContent(cid);
865 if (ci == nullptr || !ci->IsSelected()) return;
867 ci->state = ContentInfo::UNSELECTED;
868 this->CheckDependencyState(ci);
871 /** Select everything we can select */
872 void ClientNetworkContentSocketHandler::SelectAll()
874 for (ContentInfo *ci : this->infos) {
875 if (ci->state == ContentInfo::UNSELECTED) {
876 ci->state = ContentInfo::SELECTED;
877 this->CheckDependencyState(ci);
882 /** Select everything that's an update for something we've got */
883 void ClientNetworkContentSocketHandler::SelectUpgrade()
885 for (ContentInfo *ci : this->infos) {
886 if (ci->state == ContentInfo::UNSELECTED && ci->upgrade) {
887 ci->state = ContentInfo::SELECTED;
888 this->CheckDependencyState(ci);
893 /** Unselect everything that we've not downloaded so far. */
894 void ClientNetworkContentSocketHandler::UnselectAll()
896 for (ContentInfo *ci : this->infos) {
897 if (ci->IsSelected() && ci->state != ContentInfo::ALREADY_HERE) ci->state = ContentInfo::UNSELECTED;
901 /** Toggle the state of a content info and check its dependencies */
902 void ClientNetworkContentSocketHandler::ToggleSelectedState(const ContentInfo *ci)
904 switch (ci->state) {
905 case ContentInfo::SELECTED:
906 case ContentInfo::AUTOSELECTED:
907 this->Unselect(ci->id);
908 break;
910 case ContentInfo::UNSELECTED:
911 this->Select(ci->id);
912 break;
914 default:
915 break;
920 * Reverse lookup the dependencies of (direct) parents over a given child.
921 * @param parents list to store all parents in (is not cleared)
922 * @param child the child to search the parents' dependencies for
924 void ClientNetworkContentSocketHandler::ReverseLookupDependency(ConstContentVector &parents, const ContentInfo *child) const
926 for (const ContentInfo *ci : this->infos) {
927 if (ci == child) continue;
929 for (auto &dependency : ci->dependencies) {
930 if (dependency == child->id) {
931 parents.push_back(ci);
932 break;
939 * Reverse lookup the dependencies of all parents over a given child.
940 * @param tree list to store all parents in (is not cleared)
941 * @param child the child to search the parents' dependencies for
943 void ClientNetworkContentSocketHandler::ReverseLookupTreeDependency(ConstContentVector &tree, const ContentInfo *child) const
945 tree.push_back(child);
947 /* First find all direct parents. We can't use the "normal" iterator as
948 * we are including stuff into the vector and as such the vector's data
949 * store can be reallocated (and thus move), which means out iterating
950 * pointer gets invalid. So fall back to the indices. */
951 for (uint i = 0; i < tree.size(); i++) {
952 ConstContentVector parents;
953 this->ReverseLookupDependency(parents, tree[i]);
955 for (const ContentInfo *ci : parents) {
956 include(tree, ci);
962 * Check the dependencies (recursively) of this content info
963 * @param ci the content info to check the dependencies of
965 void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
967 if (ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) {
968 /* Selection is easy; just walk all children and set the
969 * autoselected state. That way we can see what we automatically
970 * selected and thus can unselect when a dependency is removed. */
971 for (auto &dependency : ci->dependencies) {
972 ContentInfo *c = this->GetContent(dependency);
973 if (c == nullptr) {
974 this->DownloadContentInfo(dependency);
975 } else if (c->state == ContentInfo::UNSELECTED) {
976 c->state = ContentInfo::AUTOSELECTED;
977 this->CheckDependencyState(c);
980 return;
983 if (ci->state != ContentInfo::UNSELECTED) return;
985 /* For unselection we need to find the parents of us. We need to
986 * unselect them. After that we unselect all children that we
987 * depend on and are not used as dependency for us, but only when
988 * we automatically selected them. */
989 ConstContentVector parents;
990 this->ReverseLookupDependency(parents, ci);
991 for (const ContentInfo *c : parents) {
992 if (!c->IsSelected()) continue;
994 this->Unselect(c->id);
997 for (auto &dependency : ci->dependencies) {
998 const ContentInfo *c = this->GetContent(dependency);
999 if (c == nullptr) {
1000 DownloadContentInfo(dependency);
1001 continue;
1003 if (c->state != ContentInfo::AUTOSELECTED) continue;
1005 /* Only unselect when WE are the only parent. */
1006 parents.clear();
1007 this->ReverseLookupDependency(parents, c);
1009 /* First check whether anything depends on us */
1010 int sel_count = 0;
1011 bool force_selection = false;
1012 for (const ContentInfo *parent_ci : parents) {
1013 if (parent_ci->IsSelected()) sel_count++;
1014 if (parent_ci->state == ContentInfo::SELECTED) force_selection = true;
1016 if (sel_count == 0) {
1017 /* Nothing depends on us */
1018 this->Unselect(c->id);
1019 continue;
1021 /* Something manually selected depends directly on us */
1022 if (force_selection) continue;
1024 /* "Flood" search to find all items in the dependency graph*/
1025 parents.clear();
1026 this->ReverseLookupTreeDependency(parents, c);
1028 /* Is there anything that is "force" selected?, if so... we're done. */
1029 for (const ContentInfo *parent_ci : parents) {
1030 if (parent_ci->state != ContentInfo::SELECTED) continue;
1032 force_selection = true;
1033 break;
1036 /* So something depended directly on us */
1037 if (force_selection) continue;
1039 /* Nothing depends on us, mark the whole graph as unselected.
1040 * After that's done run over them once again to test their children
1041 * to unselect. Don't do it immediately because it'll do exactly what
1042 * we're doing now. */
1043 for (const ContentInfo *c : parents) {
1044 if (c->state == ContentInfo::AUTOSELECTED) this->Unselect(c->id);
1046 for (const ContentInfo *c : parents) {
1047 this->CheckDependencyState(this->GetContent(c->id));
1052 /** Clear all downloaded content information. */
1053 void ClientNetworkContentSocketHandler::Clear()
1055 for (ContentInfo *c : this->infos) delete c;
1057 this->infos.clear();
1058 this->requested.clear();
1061 /*** CALLBACK ***/
1063 void ClientNetworkContentSocketHandler::OnConnect(bool success)
1065 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1066 ContentCallback *cb = this->callbacks[i];
1067 /* the callback may remove itself from this->callbacks */
1068 cb->OnConnect(success);
1069 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1073 void ClientNetworkContentSocketHandler::OnDisconnect()
1075 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1076 ContentCallback *cb = this->callbacks[i];
1077 cb->OnDisconnect();
1078 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1082 void ClientNetworkContentSocketHandler::OnReceiveContentInfo(const ContentInfo *ci)
1084 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1085 ContentCallback *cb = this->callbacks[i];
1086 /* the callback may add items and/or remove itself from this->callbacks */
1087 cb->OnReceiveContentInfo(ci);
1088 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1092 void ClientNetworkContentSocketHandler::OnDownloadProgress(const ContentInfo *ci, int bytes)
1094 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1095 ContentCallback *cb = this->callbacks[i];
1096 cb->OnDownloadProgress(ci, bytes);
1097 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
1101 void ClientNetworkContentSocketHandler::OnDownloadComplete(ContentID cid)
1103 ContentInfo *ci = this->GetContent(cid);
1104 if (ci != nullptr) {
1105 ci->state = ContentInfo::ALREADY_HERE;
1108 for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
1109 ContentCallback *cb = this->callbacks[i];
1110 /* the callback may remove itself from this->callbacks */
1111 cb->OnDownloadComplete(cid);
1112 if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;