summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/ui/pages/instance/McClient.cpp
blob: d5ba1e2bc03ed5559a9072fc0869442bc0db7738 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Project Tick
// SPDX-FileContributor: Project Tick Team
/*
 *  ProjT Launcher - Minecraft Launcher
 *  Copyright (C) 2026 Project Tick
 *
 *  This program 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 3.
 *
 *  This program 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.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
#include <qtconcurrentrun.h>
#include <QJsonDocument>
#include <QJsonObject>
#include <QObject>
#include <QTcpSocket>

#include <Exception.h>
#include "Json.h"
#include "McClient.h"

// 7 first bits
#define SEGMENT_BITS 0x7F
// last bit
#define CONTINUE_BIT 0x80

McClient::McClient(QObject* parent, QString domain, QString ip, short port)
	: QObject(parent),
	  m_domain(domain),
	  m_ip(ip),
	  m_port(port)
{}

void McClient::getStatusData()
{
	qDebug() << "Connecting to socket..";

	connect(&m_socket,
			&QTcpSocket::connected,
			this,
			[this]()
			{
				qDebug() << "Connected to socket successfully";
				sendRequest();

				connect(&m_socket, &QTcpSocket::readyRead, this, &McClient::readRawResponse);
			});

	connect(&m_socket,
			&QTcpSocket::errorOccurred,
			this,
			[this]() { emitFail("Socket disconnected: " + m_socket.errorString()); });

	m_socket.connectToHost(m_ip, m_port);
}

void McClient::sendRequest()
{
	QByteArray data;
	writeVarInt(data, 0x00);				   // packet ID
	writeVarInt(data, 763);					   // hardcoded protocol version (763 = 1.20.1)
	writeVarInt(data, m_domain.size());		   // server address length
	writeString(data, m_domain.toStdString()); // server address
	writeFixedInt(data, m_port, 2);			   // server port
	writeVarInt(data, 0x01);				   // next state
	writePacketToSocket(data);				   // send handshake packet

	writeVarInt(data, 0x00);   // packet ID
	writePacketToSocket(data); // send status packet
}

void McClient::readRawResponse()
{
	if (m_responseReadState == 2)
	{
		return;
	}

	m_resp.append(m_socket.readAll());
	if (m_responseReadState == 0 && m_resp.size() >= 5)
	{
		m_wantedRespLength	= readVarInt(m_resp);
		m_responseReadState = 1;
	}

	if (m_responseReadState == 1 && m_resp.size() >= m_wantedRespLength)
	{
		if (m_resp.size() > m_wantedRespLength)
		{
			qDebug() << "Warning: Packet length doesn't match actual packet size (" << m_wantedRespLength
					 << " expected vs " << m_resp.size() << " received)";
		}
		parseResponse();
		m_responseReadState = 2;
	}
}

void McClient::parseResponse()
{
	qDebug() << "Received response successfully";

	int packetID = readVarInt(m_resp);
	if (packetID != 0x00)
	{
		throw Exception(QString("Packet ID doesn't match expected value (0x00 vs 0x%1)").arg(packetID, 0, 16));
	}

	Q_UNUSED(readVarInt(m_resp)); // json length

	// 'resp' should now be the JSON string
	QJsonDocument doc = QJsonDocument::fromJson(m_resp);
	emitSucceed(doc.object());
}

// From https://wiki.vg/Protocol#VarInt_and_VarLong
void McClient::writeVarInt(QByteArray& data, int value)
{
	while ((value & ~SEGMENT_BITS))
	{ // check if the value is too big to fit in 7 bits
		// Write 7 bits
		data.append((value & SEGMENT_BITS) | CONTINUE_BIT);

		// Erase theses 7 bits from the value to write
		// Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone
		value >>= 7;
	}
	data.append(value);
}

// From https://wiki.vg/Protocol#VarInt_and_VarLong
int McClient::readVarInt(QByteArray& data)
{
	int value	 = 0;
	int position = 0;
	char currentByte;

	while (position < 32)
	{
		currentByte = readByte(data);
		value |= (currentByte & SEGMENT_BITS) << position;

		if ((currentByte & CONTINUE_BIT) == 0)
			break;

		position += 7;
	}

	if (position >= 32)
		throw Exception("VarInt is too big");

	return value;
}

char McClient::readByte(QByteArray& data)
{
	if (data.isEmpty())
	{
		throw Exception("No more bytes to read");
	}

	char byte = data.at(0);
	data.remove(0, 1);
	return byte;
}

// write number with specified size in big endian format
void McClient::writeFixedInt(QByteArray& data, int value, int size)
{
	for (int i = size - 1; i >= 0; i--)
	{
		data.append((value >> (i * 8)) & 0xFF);
	}
}

void McClient::writeString(QByteArray& data, const std::string& value)
{
	data.append(value.c_str());
}

void McClient::writePacketToSocket(QByteArray& data)
{
	// we prefix the packet with its length
	QByteArray dataWithSize;
	writeVarInt(dataWithSize, data.size());
	dataWithSize.append(data);

	// write it to the socket
	m_socket.write(dataWithSize);
	m_socket.flush();

	data.clear();
}

void McClient::emitFail(QString error)
{
	qDebug() << "Minecraft server ping for status error:" << error;
	emit failed(error);
	emit finished();
}

void McClient::emitSucceed(QJsonObject data)
{
	emit succeeded(data);
	emit finished();
}