Botcraft 26.3
Loading...
Searching...
No Matches
NetworkManager.cpp
Go to the documentation of this file.
1#include <functional>
2#include <optional>
3#include <utility>
4
10#if USE_COMPRESSION
12#endif
14#if PROTOCOL_VERSION > 758 /* > 1.18.2 */
16#endif
17
18
21
22using namespace ProtocolCraft;
23
24namespace Botcraft
25{
27 const std::string& address,
28 const std::string& login_or_microsoft_cache_key_or_mc_token,
29 const AuthType auth_type,
30 const std::vector<Handler*>& handlers,
31 std::function<void()> on_disconnect
32 )
33 {
34 com = nullptr;
35
36 switch (auth_type)
37 {
39 authentifier = nullptr;
40 name = login_or_microsoft_cache_key_or_mc_token;
41 break;
43 authentifier = std::make_shared<Authentifier>();
44 if (!authentifier->AuthMicrosoft(login_or_microsoft_cache_key_or_mc_token))
45 {
46 throw std::runtime_error("Error trying to authenticate on Mojang server using Microsoft auth flow");
47 }
48 name = authentifier->GetPlayerDisplayName();
49 break;
51 authentifier = std::make_shared<Authentifier>();
52 if (!authentifier->AuthMCToken(login_or_microsoft_cache_key_or_mc_token))
53 {
54 throw std::runtime_error("Error trying to authenticate on Mojang server using provided mc token");
55 }
56 name = authentifier->GetPlayerDisplayName();
57 break;
58 }
59
60 compression = -1;
61 AddHandler(this);
62 for (Handler* p : handlers)
63 {
64 AddHandler(p);
65 }
66
67 state = ConnectionState::Handshake;
68 OnDisconnectCallback = std::move(on_disconnect);
69
70 com = std::make_shared<TCP_Com>(
71 address,
72 std::bind(&NetworkManager::OnNewRawData, this, std::placeholders::_1),
73 [this]() { OnNewRawData({}); }
74 );
75
76 std::shared_ptr<ServerboundClientIntentionPacket> handshake_packet = std::make_shared<ServerboundClientIntentionPacket>();
77 handshake_packet->SetProtocolVersion(PROTOCOL_VERSION);
78 handshake_packet->SetHostName(com->GetIp());
79 handshake_packet->SetPort(com->GetPort());
80 handshake_packet->SetIntention(static_cast<int>(ConnectionState::Login));
81 Send(handshake_packet);
82
83 state = ConnectionState::Login;
84
85 std::shared_ptr<ServerboundHelloPacket> loginstart_packet = std::make_shared<ServerboundHelloPacket>();
86#if PROTOCOL_VERSION < 759 /* < 1.19 */
87 loginstart_packet->SetGameProfile(name);
88#else
89 loginstart_packet->SetName_(name);
90 if (authentifier)
91 {
92#if PROTOCOL_VERSION < 761 /* < 1.19.3 */
94 key.SetTimestamp(authentifier->GetKeyTimestamp());
95 key.SetKey(Utilities::RSAToBytes(authentifier->GetPublicKey()));
96 key.SetSignature(Utilities::DecodeBase64(authentifier->GetKeySignature()));
97
98 loginstart_packet->SetPublicKey(key);
99#endif
100#if PROTOCOL_VERSION > 759 /* > 1.19 */
101 loginstart_packet->SetProfileId(authentifier->GetPlayerUUID());
102#endif
103 }
104#endif
105 Send(loginstart_packet);
106
107 // Start the thread to process the incoming packets
109 }
110
111 NetworkManager::NetworkManager(const ConnectionState constant_connection_state)
112 {
113 state = constant_connection_state;
114 compression = -1;
115 }
116
121
123 {
124 {
125 std::scoped_lock<std::mutex> lock(mutex_process);
126 state = ConnectionState::None;
127 }
128
129 if (com)
130 {
131 com->close();
132 }
133
134 process_condition.notify_all();
135
136 if (m_thread_process.joinable())
137 {
138 m_thread_process.join();
139 }
140 compression = -1;
141
142 {
143 std::lock_guard<std::mutex> lock(mutex_send);
144 com.reset();
145 }
146 }
147
149 {
150 subscribed.push_back(h);
151 }
152
153 void NetworkManager::Send(const std::shared_ptr<Packet> packet)
154 {
155 std::lock_guard<std::mutex> lock(mutex_send);
156 if (!com || state == ConnectionState::None)
157 {
158 return;
159 }
160
161 const int compression_threshold = compression;
162 std::vector<unsigned char> packet_data;
163 packet_data.reserve(256);
164 packet->Write(packet_data);
165 if (compression_threshold == -1)
166 {
167 com->SendPacket(packet_data);
168 }
169 else
170 {
171#ifdef USE_COMPRESSION
172 if (packet_data.size() < static_cast<size_t>(compression_threshold))
173 {
174 packet_data.insert(packet_data.begin(), 0x00);
175 com->SendPacket(packet_data);
176 }
177 else
178 {
179 std::vector<unsigned char> compressed_packet;
180 compressed_packet.reserve(packet_data.size() + 5);
181 WriteData<VarInt>(static_cast<int>(packet_data.size()), compressed_packet);
182 std::vector<unsigned char> compressed_data = Compress(packet_data);
183 compressed_packet.insert(compressed_packet.end(), compressed_data.begin(), compressed_data.end());
184 com->SendPacket(compressed_packet);
185 }
186#else
187 throw std::runtime_error("Program compiled without ZLIB. Cannot send compressed message");
188#endif
189 }
190 }
191
193 {
194 return state;
195 }
196
197 const std::string& NetworkManager::GetMyName() const
198 {
199 return name;
200 }
201
202 void NetworkManager::SendChatMessage(const std::string& message)
203 {
204 std::scoped_lock<std::mutex> lock_chat(chat_mutex);
205#if PROTOCOL_VERSION > 758 /* > 1.18.2 */
206 if (message[0] == '/')
207 {
208 LOG_INFO("You're trying to send a message starting with '/'. Use SendChatCommand instead if you want the server to interprete it as a command.");
209 }
210#endif
211
212 std::shared_ptr<ServerboundChatPacket> chat_message = std::make_shared<ServerboundChatPacket>();
213 chat_message->SetMessage(message);
214#if PROTOCOL_VERSION > 758 /* > 1.18.2 */
215#if PROTOCOL_VERSION < 761 /* < 1.19.3 */
216 chat_message->SetSignedPreview(false);
217#endif
218 if (authentifier)
219 {
220 long long int salt, timestamp;
221 std::vector<unsigned char> signature;
222#if PROTOCOL_VERSION == 759 /* 1.19 */
223 // 1.19
224 signature = authentifier->GetMessageSignature(message, salt, timestamp);
225#elif PROTOCOL_VERSION == 760 /* 1.19.1/2 */
227 signature = authentifier->GetMessageSignature(message, chat_context.GetLastSignature(), last_seen_update.GetLastSeen(), salt, timestamp);
228 // Update last signature with current one for the next message
229 chat_context.SetLastSignature(signature);
230 chat_message->SetLastSeenMessages(last_seen_update);
231#else
232 // 1.19.3+
233 const auto [signatures, updates] = chat_context.GetLastSeenMessagesUpdate();
234 const int current_message_sent_index = message_sent_index++;
235 signature = authentifier->GetMessageSignature(message, current_message_sent_index, chat_session_uuid, signatures, salt, timestamp);
236 chat_message->SetLastSeenMessages(updates);
237#endif
238 if (signature.empty())
239 {
240 throw std::runtime_error("Empty chat message signature.");
241 }
242 chat_message->SetTimestamp(timestamp);
243
244#if PROTOCOL_VERSION < 760 /* < 1.19.1 */
245 SaltSignature salt_signature;
246 salt_signature.SetSalt(salt);
247 salt_signature.SetSignature(signature);
248
249 chat_message->SetSaltSignature(salt_signature);
250#else
251 chat_message->SetSalt(salt);
252 chat_message->SetSignature(signature);
253#endif
254 }
255 // Offline mode, empty signature
256 else
257 {
258 chat_message->SetTimestamp(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
259 }
260#endif
261 Send(chat_message);
262 }
263
264 void NetworkManager::SendChatCommand(const std::string& command)
265 {
266 std::scoped_lock<std::mutex> lock_chat(chat_mutex);
267#if PROTOCOL_VERSION > 765 /* > 1.20.4 */
268 if (authentifier == nullptr)
269 {
270 std::shared_ptr<ServerboundChatCommandPacket> chat_command = std::make_shared<ServerboundChatCommandPacket>();
271 chat_command->SetCommand(command);
272 Send(chat_command);
273 return;
274 }
275#endif
276#if PROTOCOL_VERSION > 758 /* > 1.18.2 */
277#if PROTOCOL_VERSION > 765 /* > 1.20.4 */
278 std::shared_ptr<ServerboundChatCommandSignedPacket> chat_command = std::make_shared<ServerboundChatCommandSignedPacket>();
279#else
280 std::shared_ptr<ServerboundChatCommandPacket> chat_command = std::make_shared<ServerboundChatCommandPacket>();
281#endif
282 chat_command->SetCommand(command);
283 chat_command->SetTimestamp(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
284#if PROTOCOL_VERSION > 759 /* > 1.19 */
285 std::mt19937 rnd(static_cast<unsigned int>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count()));
286 chat_command->SetSalt(std::uniform_int_distribution<long long int>(std::numeric_limits<long long int>::min(), std::numeric_limits<long long int>::max())(rnd));
287#endif
288#if PROTOCOL_VERSION < 761 /* < 1.19.3 */
289 chat_command->SetSignedPreview(false);
290#endif
291#if PROTOCOL_VERSION == 760 /* 1.19.1/2 */
292 LastSeenMessagesUpdate last_seen_update;
293 if (authentifier)
294 {
295 last_seen_update = chat_context.GetLastSeenMessagesUpdate();
296 }
297 chat_command->SetLastSeenMessages(last_seen_update);
298#elif PROTOCOL_VERSION > 760 /* > 1.19.2 */
299 const auto [signatures, updates] = chat_context.GetLastSeenMessagesUpdate();
300 chat_command->SetLastSeenMessages(updates);
301#endif
302 // TODO: when this shouldn't be empty? Can't find a situation where it's filled with something
303 chat_command->SetArgumentSignatures({});
304#else
305 std::shared_ptr<ServerboundChatPacket> chat_command = std::make_shared<ServerboundChatPacket>();
306 chat_command->SetMessage("/" + command);
307#endif
308 Send(chat_command);
309 }
310
312 {
313 return m_thread_process.get_id();
314 }
315
317 {
318 Logger::GetInstance().RegisterThread("NetworkPacketProcessing - " + name);
319 try
320 {
321 std::queue<std::vector<unsigned char>> batch;
322 while (true)
323 {
324 {
325 std::unique_lock<std::mutex> lck(mutex_process);
326 process_condition.wait(lck, [this]() {
327 return !packets_to_process.empty() || state == ConnectionState::None;
328 });
329 if (state == ConnectionState::None)
330 {
331 break;
332 }
333 std::swap(batch, packets_to_process);
334 }
335
336 bool closed = false;
337 while (!batch.empty())
338 {
339 std::vector<unsigned char> packet = std::move(batch.front());
340 batch.pop();
341 if (packet.empty())
342 {
343 closed = true;
344 break;
345 }
346 else
347 {
348 if (compression == -1)
349 {
350 ProcessPacket(packet);
351 }
352 else
353 {
354#ifdef USE_COMPRESSION
355 size_t length = packet.size();
356 ReadIterator iter = packet.begin();
357 int data_length = ReadData<VarInt>(iter, length);
358
359 // Packet not compressed
360 if (data_length == 0)
361 {
362 // Erase the first 0
363 packet.erase(packet.begin());
364 ProcessPacket(packet);
365 }
366 // Packet compressed
367 else
368 {
369 const int size_varint = static_cast<int>(packet.size() - length);
370
371 std::vector<unsigned char> uncompressed_packet = Decompress(packet, size_varint);
372 ProcessPacket(uncompressed_packet);
373 }
374#else
375 throw std::runtime_error("Program compiled without USE_COMPRESSION. Cannot read compressed message");
376#endif
377 }
378 }
379 }
380 if (closed)
381 {
382 break;
383 }
384 }
385 }
386 catch (const std::exception& e)
387 {
388 LOG_FATAL("Exception:\n" << e.what());
389 }
390 catch (...)
391 {
392 LOG_FATAL("Unknown exception");
393 }
394
395 state = ConnectionState::None;
396 if (com)
397 {
398 com->close();
399 }
401 {
403 }
404 }
405
406 void NetworkManager::ProcessPacket(const std::vector<unsigned char>& bytes)
407 {
408 if (bytes.empty())
409 {
410 return;
411 }
412
413 std::vector<unsigned char>::const_iterator packet_iterator = bytes.begin();
414 size_t length = bytes.size();
415
416 const int packet_id = ReadData<VarInt>(packet_iterator, length);
417
418 std::shared_ptr<Packet> packet = CreateClientboundPacket(state, packet_id);
419
420 if (packet != nullptr)
421 {
422 try
423 {
424 packet->Read(packet_iterator, length);
425 }
426 catch (const std::exception& e)
427 {
428 LOG_FATAL("Parsing exception while parsing message \"" << packet->GetName() << "\"\n" << e.what());
429 throw;
430 }
431 for (size_t i = 0; i < subscribed.size(); i++)
432 {
433 packet->Dispatch(subscribed[i]);
434 }
435 }
436 }
437
438 void NetworkManager::OnNewRawData(std::vector<unsigned char> bytes)
439 {
440 {
441 std::unique_lock<std::mutex> lck(mutex_process);
442 packets_to_process.push(std::move(bytes));
443 }
444 process_condition.notify_all();
445 }
446
447
449 {
450 compression = packet.GetCompressionThreshold();
451 }
452
453#if PROTOCOL_VERSION < 768 /* < 1.21.2 */
454 void NetworkManager::Handle(ClientboundGameProfilePacket& packet)
455#else
457#endif
458 {
459#if PROTOCOL_VERSION < 764 /* < 1.20.2 */
460 state = ConnectionState::Play;
461#else
462 state = ConnectionState::Configuration;
463 std::shared_ptr<ServerboundLoginAcknowledgedPacket> login_ack_packet = std::make_shared<ServerboundLoginAcknowledgedPacket>();
464 Send(login_ack_packet);
465
466 std::shared_ptr<ServerboundCustomPayloadConfigurationPacket> custom_payload_packet = std::make_shared<ServerboundCustomPayloadConfigurationPacket>();
467 custom_payload_packet->SetIdentifier("minecraft:brand");
468 std::vector<unsigned char> payload;
469 WriteData<std::string>("vanilla", payload);
470 custom_payload_packet->SetRawData(payload);
471 Send(custom_payload_packet);
472
473 std::shared_ptr<ServerboundClientInformationConfigurationPacket> client_info_packet = std::make_shared<ServerboundClientInformationConfigurationPacket>();
475 info.SetLanguage("fr_FR");
476 info.SetViewDistance(10);
477 info.SetChatVisibility(static_cast<int>(ChatMode::Enabled));
478 info.SetChatColors(true);
479 info.SetModelCustomisation(0xFF);
480 info.SetMainHand(1); // 1 is right handed, 0 is left handed
481#if PROTOCOL_VERSION > 767 /* > 1.21.1 */
482 info.SetParticleStatus(2); // 0 is "all", 1 is "decreased" and 2 is "minimal"
483#endif
484 client_info_packet->SetClientInformation(info);
485
486 Send(client_info_packet);
487#endif
488 }
489
491 {
492 if (authentifier == nullptr
493#if PROTOCOL_VERSION > 765 /* > 1.20.4 */
494 && packet.GetShouldAuthenticate()
495#endif
496 )
497 {
498 throw std::runtime_error("Authentication asked while no valid account has been provided, make sure to connect with a valid Microsoft Account, or to a server with online-mode=false");
499 }
500
501#ifdef USE_ENCRYPTION
502 std::shared_ptr<AESEncrypter> encrypter = std::make_shared<AESEncrypter>();
503
504 std::vector<unsigned char> raw_shared_secret;
505 std::vector<unsigned char> encrypted_shared_secret;
506
507#if PROTOCOL_VERSION < 759 /* < 1.19 */
508 std::vector<unsigned char> encrypted_nonce;
509 encrypter->Init(packet.GetPublicKey(), packet.GetNonce(),
510 raw_shared_secret, encrypted_nonce, encrypted_shared_secret);
511#elif PROTOCOL_VERSION < 761 /* < 1.19.3 */
512 std::vector<unsigned char> salted_nonce_signature;
513 long long int salt;
514 encrypter->Init(packet.GetPublicKey(), packet.GetNonce(), authentifier->GetPrivateKey(),
515 raw_shared_secret, encrypted_shared_secret,
516 salt, salted_nonce_signature);
517#else
518 std::vector<unsigned char> encrypted_challenge;
519 encrypter->Init(packet.GetPublicKey(), packet.GetChallenge(),
520 raw_shared_secret, encrypted_shared_secret,
521 encrypted_challenge);
522#endif
523
524 // In 1.20.5+, encryption can be enabled even in offline mode
525#if PROTOCOL_VERSION > 765 /* > 1.20.4 */
526 if (packet.GetShouldAuthenticate())
527#endif
528 {
529 authentifier->JoinServer(packet.GetServerId(), raw_shared_secret, packet.GetPublicKey());
530 }
531
532 std::shared_ptr<ServerboundKeyPacket> response_packet = std::make_shared<ServerboundKeyPacket>();
533 response_packet->SetKeyBytes(encrypted_shared_secret);
534
535#if PROTOCOL_VERSION < 759 /* < 1.19 */
536 // Pre-1.19 behaviour, send encrypted nonce
537 response_packet->SetNonce(encrypted_nonce);
538#elif PROTOCOL_VERSION < 761 /* < 1.19.3 */
539 // 1.19, 1.19.1, 1.19.2 behaviour, send salted nonce signature
540 SaltSignature salt_signature;
541 salt_signature.SetSalt(salt);
542 salt_signature.SetSignature(salted_nonce_signature);
543 response_packet->SetSaltSignature(salt_signature);
544#else
545 // 1.19.3+ behaviour, send encrypted challenge
546 response_packet->SetEncryptedChallenge(encrypted_challenge);
547#endif
548
549 Send(response_packet);
550
551 // Enable encryption from now on
552 com->SetEncrypter(encrypter);
553#else
554 throw std::runtime_error("Your version of botcraft doesn't support encryption. Either run your server with online-mode=false or recompile botcraft");
555#endif
556 }
557
559 {
560 std::shared_ptr<ServerboundKeepAlivePacket> keep_alive_packet = std::make_shared<ServerboundKeepAlivePacket>();
561 keep_alive_packet->SetId_(packet.GetId_());
562 Send(keep_alive_packet);
563 }
564
565#if PROTOCOL_VERSION > 754 /* > 1.16.5 */
567 {
568 std::shared_ptr<ServerboundPongPacket> pong_packet = std::make_shared<ServerboundPongPacket>();
569 pong_packet->SetId_(packet.GetId_());
570 Send(pong_packet);
571 }
572#endif
573
574#if PROTOCOL_VERSION > 340 /* > 1.12.2 */
576 {
577 // Vanilla like response when asked by fabric API
578 // Not implemented in fabric before December 05 2020,
579 // so not necessary before version 1.16.4
580#if PROTOCOL_VERSION > 753 /* > 1.16.3 */
581 if (packet.GetIdentifier().GetFull() == "fabric-networking-api-v1:early_registration")
582 {
583#if PROTOCOL_VERSION < 764 /* < 1.20.2 */
584 std::shared_ptr<ServerboundCustomQueryPacket> custom_query_anwser = std::make_shared<ServerboundCustomQueryPacket>();
585 custom_query_anwser->SetTransactionId(packet.GetTransactionId());
586 custom_query_anwser->SetData(std::nullopt);
587#else
588 std::shared_ptr<ServerboundCustomQueryAnswerPacket> custom_query_anwser = std::make_shared<ServerboundCustomQueryAnswerPacket>();
589 custom_query_anwser->SetTransactionId(packet.GetTransactionId());
590 custom_query_anwser->SetPayload(std::nullopt);
591#endif
592 Send(custom_query_anwser);
593 return;
594 }
595#endif
596 }
597#endif
598
599#if PROTOCOL_VERSION > 759 /* > 1.19 */
601 {
602#if PROTOCOL_VERSION < 761 /* < 1.19.3 */
603 // Ugly stuff because there is a GetMessage macro in Windows API somewhere :)
604#if _MSC_VER || __MINGW32__
605#pragma push_macro("GetMessage")
606#undef GetMessage
607#endif
608 {
609 std::scoped_lock<std::mutex> lock_chat(chat_mutex);
610 chat_context.AddSeenMessage(packet.GetMessage().GetHeaderSignature(), packet.GetMessage().GetSignedHeader().GetSender());
611 }
612#if _MSC_VER || __MINGW32__
613#pragma pop_macro("GetMessage")
614#endif
615#else
616 if (packet.GetSignature().has_value())
617 {
618 std::scoped_lock<std::mutex> lock_chat(chat_mutex);
619
620 chat_context.AddSeenMessage(std::vector<unsigned char>(packet.GetSignature().value().begin(), packet.GetSignature().value().end()));
621
622 if (chat_context.GetOffset() > 64)
623 {
624 std::shared_ptr<ServerboundChatAckPacket> ack_packet = std::make_shared<ServerboundChatAckPacket>();
625 ack_packet->SetOffset(chat_context.GetAndResetOffset());
626 Send(ack_packet);
627 }
628 }
629#endif
630 }
631
632#if PROTOCOL_VERSION < 761 /* < 1.19.3 */
633 void NetworkManager::Handle(ClientboundPlayerChatHeaderPacket& packet)
634 {
635 std::scoped_lock<std::mutex> lock_chat(chat_mutex);
636 chat_context.AddSeenMessage(packet.GetHeaderSignature(), packet.GetHeader().GetSender());
637 }
638#endif
639#endif
640
642 {
643#if PROTOCOL_VERSION < 764 /* < 1.20.2 */
644 {
645 // In 1.20.2+ it is sent during configuration instead
646 std::shared_ptr<ServerboundCustomPayloadPacket> custom_payload_packet = std::make_shared<ServerboundCustomPayloadPacket>();
647 custom_payload_packet->SetIdentifier("minecraft:brand");
648 std::vector<unsigned char> payload;
649 WriteData<std::string>("vanilla", payload);
650 custom_payload_packet->SetRawData(payload);
651 Send(custom_payload_packet);
652 }
653#endif
654#if PROTOCOL_VERSION > 760 /* > 1.19.2 */
655 if (authentifier)
656 {
657 std::shared_ptr<ServerboundChatSessionUpdatePacket> chat_session_packet = std::make_shared<ServerboundChatSessionUpdatePacket>();
658 RemoteChatSessionData chat_session_data;
659
661 key.SetTimestamp(authentifier->GetKeyTimestamp());
662 key.SetKey(Utilities::RSAToBytes(authentifier->GetPublicKey()));
663 key.SetSignature(Utilities::DecodeBase64(authentifier->GetKeySignature()));
664
665 chat_session_data.SetProfilePublicKey(key);
666 {
667 std::scoped_lock<std::mutex> lock_chat(chat_mutex);
669 std::mt19937 rnd = std::mt19937(static_cast<unsigned int>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count()));
670 std::uniform_int_distribution<int> distrib(std::numeric_limits<unsigned char>::min(), std::numeric_limits<unsigned char>::max());
671 for (size_t i = 0; i < chat_session_uuid.size(); ++i)
672 {
673 chat_session_uuid[i] = static_cast<unsigned char>(distrib(rnd));
674 }
675 chat_session_data.SetUuid(chat_session_uuid);
676
677 chat_session_packet->SetChatSession(chat_session_data);
678 Send(chat_session_packet);
679 }
680 }
681#endif
682 }
683
684#if PROTOCOL_VERSION > 763 /* > 1.20.1 */
686 {
687 state = ConnectionState::Play;
688 std::shared_ptr<ServerboundFinishConfigurationPacket> finish_config_packet = std::make_shared<ServerboundFinishConfigurationPacket>();
689 Send(finish_config_packet);
690 }
691
693 {
694 std::shared_ptr<ServerboundKeepAliveConfigurationPacket> keep_alive_packet = std::make_shared<ServerboundKeepAliveConfigurationPacket>();
695 keep_alive_packet->SetId_(packet.GetId_());
696 Send(keep_alive_packet);
697 }
698
700 {
701 std::shared_ptr<ServerboundPongConfigurationPacket> pong_packet = std::make_shared<ServerboundPongConfigurationPacket>();
702 pong_packet->SetId_(packet.GetId_());
703 Send(pong_packet);
704 }
705
707 {
708 state = ConnectionState::Configuration;
709 std::shared_ptr<ServerboundConfigurationAcknowledgedPacket> config_ack_packet = std::make_shared<ServerboundConfigurationAcknowledgedPacket>();
710 Send(config_ack_packet);
711 }
712
714 {
715 chunk_batch_start_time = std::chrono::steady_clock::now();
716 }
717
719 {
720 using count_return = decltype(std::declval<std::chrono::milliseconds>().count());
721 const count_return time_elapsed_ms = std::max(static_cast<count_return>(1), std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - chunk_batch_start_time).count());
722 std::shared_ptr<ServerboundChunkBatchReceivedPacket> chunk_per_tick_packet = std::make_shared<ServerboundChunkBatchReceivedPacket>();
723 // Ask as many chunks as we can process in one tick (50 ms)
724 chunk_per_tick_packet->SetDesiredChunksPerTick(packet.GetBatchSize() * 50.0f / time_elapsed_ms);
725 Send(chunk_per_tick_packet);
726 }
727#endif
728
729#if PROTOCOL_VERSION > 765 /* > 1.20.4 */
731 {
732 std::shared_ptr<ServerboundSelectKnownPacksPacket> select_known_packs = std::make_shared<ServerboundSelectKnownPacksPacket>();
733 // Datapacks are not supported by Botcraft
734 select_known_packs->SetKnownPacks({});
735
736 Send(select_known_packs);
737 }
738#endif
739
740#if PROTOCOL_VERSION < 764 /* < 1.20.2 */
741 // In 1.20.2+ it is sent during configuration instead
743 {
744 std::shared_ptr<ServerboundClientInformationPacket> settings_packet = std::make_shared<ServerboundClientInformationPacket>();
745 settings_packet->SetLanguage("fr_FR");
746 settings_packet->SetViewDistance(10);
747 settings_packet->SetChatVisibility(static_cast<int>(ChatMode::Enabled));
748 settings_packet->SetChatColors(true);
749 settings_packet->SetModelCustomisation(0xFF);
750 settings_packet->SetMainHand(1); // 1 is right handed, 0 is left handed
751
752 Send(settings_packet);
753 }
754#endif
755}
#define LOG_INFO(osstream)
Definition Logger.hpp:43
#define LOG_FATAL(osstream)
Definition Logger.hpp:46
void AddSeenMessage(const std::vector< unsigned char > &signature)
std::pair< std::vector< std::vector< unsigned char > >, ProtocolCraft::LastSeenMessagesUpdate > GetLastSeenMessagesUpdate()
Get both a vector of previous messages signatures and the LastSeenMessagesUpdate object.
void RegisterThread(const std::string &name)
Register the current thread in the map.
Definition Logger.cpp:104
static Logger & GetInstance()
Definition Logger.cpp:36
std::condition_variable process_condition
void AddHandler(ProtocolCraft::Handler *h)
virtual void Handle(ProtocolCraft::ClientboundLoginCompressionPacket &packet) override
std::thread::id GetProcessingThreadId() const
void SendChatCommand(const std::string &command)
void Send(const std::shared_ptr< ProtocolCraft::Packet > packet)
NetworkManager(const std::string &address, const std::string &login_or_microsoft_cache_key_or_mc_token, const AuthType auth_type, const std::vector< ProtocolCraft::Handler * > &handlers={}, std::function< void()> on_disconnect={})
void SendChatMessage(const std::string &message)
void ProcessPacket(const std::vector< unsigned char > &bytes)
LastSeenMessagesTracker chat_context
std::shared_ptr< TCP_Com > com
std::atomic< ProtocolCraft::ConnectionState > state
void OnNewRawData(std::vector< unsigned char > bytes)
std::chrono::steady_clock::time_point chunk_batch_start_time
const std::string & GetMyName() const
std::shared_ptr< Authentifier > authentifier
const ProtocolCraft::ConnectionState GetConnectionState() const
std::vector< ProtocolCraft::Handler * > subscribed
std::function< void()> OnDisconnectCallback
std::queue< std::vector< unsigned char > > packets_to_process
ProtocolCraft::UUID chat_session_uuid
std::atomic< int > compression
std::vector< unsigned char > RSAToBytes(const std::string &s)
std::vector< unsigned char > DecodeBase64(const std::string &s)
std::vector< unsigned char > Decompress(const std::vector< unsigned char > &compressed, const int start=0)
std::vector< unsigned char > Compress(const std::vector< unsigned char > &raw)
std::shared_ptr< Packet > CreateClientboundPacket(const ConnectionState state, const int id)
std::array< unsigned char, 16 > UUID
std::vector< unsigned char >::const_iterator ReadIterator