14#if PROTOCOL_VERSION > 758
27 const std::string& address,
28 const std::string& login_or_microsoft_cache_key_or_mc_token,
30 const std::vector<Handler*>& handlers,
31 std::function<
void()> on_disconnect
40 name = login_or_microsoft_cache_key_or_mc_token;
44 if (!
authentifier->AuthMicrosoft(login_or_microsoft_cache_key_or_mc_token))
46 throw std::runtime_error(
"Error trying to authenticate on Mojang server using Microsoft auth flow");
52 if (!
authentifier->AuthMCToken(login_or_microsoft_cache_key_or_mc_token))
54 throw std::runtime_error(
"Error trying to authenticate on Mojang server using provided mc token");
67 state = ConnectionState::Handshake;
70 com = std::make_shared<TCP_Com>(
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);
83 state = ConnectionState::Login;
85 std::shared_ptr<ServerboundHelloPacket> loginstart_packet = std::make_shared<ServerboundHelloPacket>();
86#if PROTOCOL_VERSION < 759
87 loginstart_packet->SetGameProfile(
name);
89 loginstart_packet->SetName_(
name);
92#if PROTOCOL_VERSION < 761
98 loginstart_packet->SetPublicKey(key);
100#if PROTOCOL_VERSION > 759
101 loginstart_packet->SetProfileId(
authentifier->GetPlayerUUID());
105 Send(loginstart_packet);
113 state = constant_connection_state;
126 state = ConnectionState::None;
156 if (!
com ||
state == ConnectionState::None)
162 std::vector<unsigned char> packet_data;
163 packet_data.reserve(256);
164 packet->Write(packet_data);
165 if (compression_threshold == -1)
167 com->SendPacket(packet_data);
171#ifdef USE_COMPRESSION
172 if (packet_data.size() <
static_cast<size_t>(compression_threshold))
174 packet_data.insert(packet_data.begin(), 0x00);
175 com->SendPacket(packet_data);
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);
187 throw std::runtime_error(
"Program compiled without ZLIB. Cannot send compressed message");
204 std::scoped_lock<std::mutex> lock_chat(
chat_mutex);
205#if PROTOCOL_VERSION > 758
206 if (message[0] ==
'/')
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.");
212 std::shared_ptr<ServerboundChatPacket> chat_message = std::make_shared<ServerboundChatPacket>();
213 chat_message->SetMessage(message);
214#if PROTOCOL_VERSION > 758
215#if PROTOCOL_VERSION < 761
216 chat_message->SetSignedPreview(
false);
220 long long int salt, timestamp;
221 std::vector<unsigned char> signature;
222#if PROTOCOL_VERSION == 759
224 signature =
authentifier->GetMessageSignature(message, salt, timestamp);
225#elif PROTOCOL_VERSION == 760
227 signature =
authentifier->GetMessageSignature(message,
chat_context.GetLastSignature(), last_seen_update.GetLastSeen(), salt, timestamp);
230 chat_message->SetLastSeenMessages(last_seen_update);
236 chat_message->SetLastSeenMessages(updates);
238 if (signature.empty())
240 throw std::runtime_error(
"Empty chat message signature.");
242 chat_message->SetTimestamp(timestamp);
244#if PROTOCOL_VERSION < 760
246 salt_signature.SetSalt(salt);
247 salt_signature.SetSignature(signature);
249 chat_message->SetSaltSignature(salt_signature);
251 chat_message->SetSalt(salt);
252 chat_message->SetSignature(signature);
258 chat_message->SetTimestamp(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
266 std::scoped_lock<std::mutex> lock_chat(
chat_mutex);
267#if PROTOCOL_VERSION > 765
270 std::shared_ptr<ServerboundChatCommandPacket> chat_command = std::make_shared<ServerboundChatCommandPacket>();
271 chat_command->SetCommand(command);
276#if PROTOCOL_VERSION > 758
277#if PROTOCOL_VERSION > 765
278 std::shared_ptr<ServerboundChatCommandSignedPacket> chat_command = std::make_shared<ServerboundChatCommandSignedPacket>();
280 std::shared_ptr<ServerboundChatCommandPacket> chat_command = std::make_shared<ServerboundChatCommandPacket>();
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
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));
288#if PROTOCOL_VERSION < 761
289 chat_command->SetSignedPreview(
false);
291#if PROTOCOL_VERSION == 760
297 chat_command->SetLastSeenMessages(last_seen_update);
298#elif PROTOCOL_VERSION > 760
300 chat_command->SetLastSeenMessages(updates);
303 chat_command->SetArgumentSignatures({});
305 std::shared_ptr<ServerboundChatPacket> chat_command = std::make_shared<ServerboundChatPacket>();
306 chat_command->SetMessage(
"/" + command);
321 std::queue<std::vector<unsigned char>> batch;
329 if (
state == ConnectionState::None)
337 while (!batch.empty())
339 std::vector<unsigned char> packet = std::move(batch.front());
354#ifdef USE_COMPRESSION
355 size_t length = packet.size();
357 int data_length = ReadData<VarInt>(iter, length);
360 if (data_length == 0)
363 packet.erase(packet.begin());
369 const int size_varint =
static_cast<int>(packet.size() - length);
371 std::vector<unsigned char> uncompressed_packet =
Decompress(packet, size_varint);
375 throw std::runtime_error(
"Program compiled without USE_COMPRESSION. Cannot read compressed message");
386 catch (
const std::exception& e)
395 state = ConnectionState::None;
413 std::vector<unsigned char>::const_iterator packet_iterator = bytes.begin();
414 size_t length = bytes.size();
416 const int packet_id = ReadData<VarInt>(packet_iterator, length);
420 if (packet !=
nullptr)
424 packet->Read(packet_iterator, length);
426 catch (
const std::exception& e)
428 LOG_FATAL(
"Parsing exception while parsing message \"" << packet->GetName() <<
"\"\n" << e.what());
431 for (
size_t i = 0; i <
subscribed.size(); i++)
453#if PROTOCOL_VERSION < 768
459#if PROTOCOL_VERSION < 764
460 state = ConnectionState::Play;
462 state = ConnectionState::Configuration;
463 std::shared_ptr<ServerboundLoginAcknowledgedPacket> login_ack_packet = std::make_shared<ServerboundLoginAcknowledgedPacket>();
464 Send(login_ack_packet);
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);
473 std::shared_ptr<ServerboundClientInformationConfigurationPacket> client_info_packet = std::make_shared<ServerboundClientInformationConfigurationPacket>();
475 info.SetLanguage(
"fr_FR");
476 info.SetViewDistance(10);
478 info.SetChatColors(
true);
479 info.SetModelCustomisation(0xFF);
481#if PROTOCOL_VERSION > 767
482 info.SetParticleStatus(2);
484 client_info_packet->SetClientInformation(info);
486 Send(client_info_packet);
493#
if PROTOCOL_VERSION > 765
494 && packet.GetShouldAuthenticate()
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");
502 std::shared_ptr<AESEncrypter> encrypter = std::make_shared<AESEncrypter>();
504 std::vector<unsigned char> raw_shared_secret;
505 std::vector<unsigned char> encrypted_shared_secret;
507#if PROTOCOL_VERSION < 759
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
512 std::vector<unsigned char> salted_nonce_signature;
514 encrypter->Init(packet.GetPublicKey(), packet.GetNonce(),
authentifier->GetPrivateKey(),
515 raw_shared_secret, encrypted_shared_secret,
516 salt, salted_nonce_signature);
518 std::vector<unsigned char> encrypted_challenge;
519 encrypter->Init(packet.GetPublicKey(), packet.GetChallenge(),
520 raw_shared_secret, encrypted_shared_secret,
521 encrypted_challenge);
525#if PROTOCOL_VERSION > 765
526 if (packet.GetShouldAuthenticate())
529 authentifier->JoinServer(packet.GetServerId(), raw_shared_secret, packet.GetPublicKey());
532 std::shared_ptr<ServerboundKeyPacket> response_packet = std::make_shared<ServerboundKeyPacket>();
533 response_packet->SetKeyBytes(encrypted_shared_secret);
535#if PROTOCOL_VERSION < 759
537 response_packet->SetNonce(encrypted_nonce);
538#elif PROTOCOL_VERSION < 761
541 salt_signature.SetSalt(salt);
542 salt_signature.SetSignature(salted_nonce_signature);
543 response_packet->SetSaltSignature(salt_signature);
546 response_packet->SetEncryptedChallenge(encrypted_challenge);
549 Send(response_packet);
552 com->SetEncrypter(encrypter);
554 throw std::runtime_error(
"Your version of botcraft doesn't support encryption. Either run your server with online-mode=false or recompile botcraft");
560 std::shared_ptr<ServerboundKeepAlivePacket> keep_alive_packet = std::make_shared<ServerboundKeepAlivePacket>();
561 keep_alive_packet->SetId_(packet.GetId_());
562 Send(keep_alive_packet);
565#if PROTOCOL_VERSION > 754
568 std::shared_ptr<ServerboundPongPacket> pong_packet = std::make_shared<ServerboundPongPacket>();
569 pong_packet->SetId_(packet.GetId_());
574#if PROTOCOL_VERSION > 340
580#if PROTOCOL_VERSION > 753
581 if (packet.GetIdentifier().GetFull() ==
"fabric-networking-api-v1:early_registration")
583#if PROTOCOL_VERSION < 764
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);
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);
592 Send(custom_query_anwser);
599#if PROTOCOL_VERSION > 759
602#if PROTOCOL_VERSION < 761
604#if _MSC_VER || __MINGW32__
605#pragma push_macro("GetMessage")
609 std::scoped_lock<std::mutex> lock_chat(
chat_mutex);
612#if _MSC_VER || __MINGW32__
613#pragma pop_macro("GetMessage")
616 if (packet.GetSignature().has_value())
618 std::scoped_lock<std::mutex> lock_chat(
chat_mutex);
620 chat_context.
AddSeenMessage(std::vector<unsigned char>(packet.GetSignature().value().begin(), packet.GetSignature().value().end()));
624 std::shared_ptr<ServerboundChatAckPacket> ack_packet = std::make_shared<ServerboundChatAckPacket>();
632#if PROTOCOL_VERSION < 761
635 std::scoped_lock<std::mutex> lock_chat(
chat_mutex);
643#if PROTOCOL_VERSION < 764
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);
654#if PROTOCOL_VERSION > 760
657 std::shared_ptr<ServerboundChatSessionUpdatePacket> chat_session_packet = std::make_shared<ServerboundChatSessionUpdatePacket>();
665 chat_session_data.SetProfilePublicKey(key);
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());
677 chat_session_packet->SetChatSession(chat_session_data);
678 Send(chat_session_packet);
684#if PROTOCOL_VERSION > 763
687 state = ConnectionState::Play;
688 std::shared_ptr<ServerboundFinishConfigurationPacket> finish_config_packet = std::make_shared<ServerboundFinishConfigurationPacket>();
689 Send(finish_config_packet);
694 std::shared_ptr<ServerboundKeepAliveConfigurationPacket> keep_alive_packet = std::make_shared<ServerboundKeepAliveConfigurationPacket>();
695 keep_alive_packet->SetId_(packet.GetId_());
696 Send(keep_alive_packet);
701 std::shared_ptr<ServerboundPongConfigurationPacket> pong_packet = std::make_shared<ServerboundPongConfigurationPacket>();
702 pong_packet->SetId_(packet.GetId_());
708 state = ConnectionState::Configuration;
709 std::shared_ptr<ServerboundConfigurationAcknowledgedPacket> config_ack_packet = std::make_shared<ServerboundConfigurationAcknowledgedPacket>();
710 Send(config_ack_packet);
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>();
724 chunk_per_tick_packet->SetDesiredChunksPerTick(packet.GetBatchSize() * 50.0f / time_elapsed_ms);
725 Send(chunk_per_tick_packet);
729#if PROTOCOL_VERSION > 765
732 std::shared_ptr<ServerboundSelectKnownPacksPacket> select_known_packs = std::make_shared<ServerboundSelectKnownPacksPacket>();
734 select_known_packs->SetKnownPacks({});
736 Send(select_known_packs);
740#if PROTOCOL_VERSION < 764
744 std::shared_ptr<ServerboundClientInformationPacket> settings_packet = std::make_shared<ServerboundClientInformationPacket>();
745 settings_packet->SetLanguage(
"fr_FR");
746 settings_packet->SetViewDistance(10);
748 settings_packet->SetChatColors(
true);
749 settings_packet->SetModelCustomisation(0xFF);
750 settings_packet->SetMainHand(1);
752 Send(settings_packet);
#define LOG_INFO(osstream)
#define LOG_FATAL(osstream)
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.
static Logger & GetInstance()
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)
std::thread m_thread_process
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