Skip to content

Commit

Permalink
Remove old imports and ditch var
Browse files Browse the repository at this point in the history
  • Loading branch information
rtm516 committed Aug 24, 2024
1 parent 115064c commit ed948d7
Show file tree
Hide file tree
Showing 12 changed files with 59 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.io.IOException;

import net.lenni0451.commons.httpclient.HttpClient;
import net.lenni0451.commons.httpclient.requests.HttpContentRequest;
import net.lenni0451.commons.httpclient.requests.impl.PostRequest;
import net.raphimc.minecraftauth.MinecraftAuth;
import net.raphimc.minecraftauth.responsehandler.PlayFabResponseHandler;
Expand Down Expand Up @@ -65,15 +66,15 @@ public static XstsAuthData fromCredentials(String email, String password, ILogge
StepInitialXblSession xblAuth = new StepInitialXblSession(initialAuth, new StepXblDeviceToken("Android"));
StepXblSisuAuthentication xstsAuth = new StepXblSisuAuthentication(xblAuth, MicrosoftConstants.XBL_XSTS_RELYING_PARTY);

var httpClient = MinecraftAuth.createHttpClient();
HttpClient httpClient = MinecraftAuth.createHttpClient();
return new XstsAuthData(xstsAuth.getFromInput(logger, httpClient, new StepCredentialsMsaCode.MsaCredentials(email, password)), xstsAuth);
}

/**
* Follow the auth flow to get the Xbox token and store it
*/
private void initialise() {
var httpClient = MinecraftAuth.createHttpClient();
HttpClient httpClient = MinecraftAuth.createHttpClient();

// Check if we have an old live_token.json file and try to import the refresh token from it
String liveTokenData = "";
Expand Down Expand Up @@ -128,19 +129,19 @@ private void initialise() {

private String fetchPlayfabSessionTicket(HttpClient httpClient) throws IOException, InterruptedException {
// TODO Use minecraftauth library using StepPlayFabToken
var initialSession = xboxToken.getInitialXblSession();
StepInitialXblSession.InitialXblSession initialSession = xboxToken.getInitialXblSession();

var authorizeRequest = new PostRequest(StepXblSisuAuthentication.XBL_SISU_URL)
HttpContentRequest authorizeRequest = new PostRequest(StepXblSisuAuthentication.XBL_SISU_URL)
.setContent(new JsonContent(SisuAuthorizeBody.create(initialSession, MicrosoftConstants.BEDROCK_PLAY_FAB_XSTS_RELYING_PARTY)));
authorizeRequest.setHeader(CryptUtil.getSignatureHeader(authorizeRequest, initialSession.getXblDeviceToken().getPrivateKey()));
var authorizeResponse = httpClient.execute(authorizeRequest, new XblResponseHandler());
JsonObject authorizeResponse = httpClient.execute(authorizeRequest, new XblResponseHandler());

var tokens = XblXstsToken.fromMicrosoftJson(authorizeResponse.getAsJsonObject("AuthorizationToken"), null);
XblXstsToken tokens = XblXstsToken.fromMicrosoftJson(authorizeResponse.getAsJsonObject("AuthorizationToken"), null);

var playfabRequest = new PostRequest(Constants.PLAYFAB_LOGIN)
HttpContentRequest playfabRequest = new PostRequest(Constants.PLAYFAB_LOGIN)
.setContent(new JsonContent(PlayfabLoginBody.create(tokens.getServiceToken())));

var playfabResponse = httpClient.execute(playfabRequest, new PlayFabResponseHandler());
JsonObject playfabResponse = httpClient.execute(playfabRequest, new PlayFabResponseHandler());

return playfabResponse.getAsJsonObject("data").get("SessionTicket").getAsString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
package com.rtm516.mcxboxbroadcast.core;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.rtm516.mcxboxbroadcast.core;

import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonReader;
import com.rtm516.mcxboxbroadcast.core.configs.FriendSyncConfig;
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionCreationException;
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionUpdateException;
Expand All @@ -10,24 +9,17 @@
import com.rtm516.mcxboxbroadcast.core.storage.StorageManager;
import org.java_websocket.util.NamedThreadFactory;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Stream;

/**
* Simple manager to authenticate and create sessions on Xbox
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ private void createSession() throws SessionCreationException, SessionUpdateExcep
// Update the current session XUID
this.sessionInfo.setXuid(tokenInfo.userXUID());

var authorizationHeader = setupSession();
String authorizationHeader = setupSession();

// Create the RTA websocket connection
setupRtaWebsocket(token);
Expand Down Expand Up @@ -355,9 +355,9 @@ protected Future<Void> waitForRTCConnection() {
}

protected String setupSession() {
var playfabTicket = this.authManager.getPlayfabSessionTicket();
String playfabTicket = this.authManager.getPlayfabSessionTicket();

var request = HttpRequest.newBuilder(Constants.START_SESSION)
HttpRequest request = HttpRequest.newBuilder(Constants.START_SESSION)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(SessionStartBody.create(sessionInfo, playfabTicket)))
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

public final class SisuAuthorizeBody {
public static JsonObject create(InitialXblSession initialSession, String relyingParty) {
var content = new JsonObject();
JsonObject content = new JsonObject();
content.addProperty("AccessToken", "t=" + initialSession.getMsaToken().getAccessToken());
content.addProperty("DeviceToken", initialSession.getXblDeviceToken().getToken());
content.addProperty("AppId", "00000000402b5328");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.rtm516.mcxboxbroadcast.core.ExpandedSessionInfo;

import java.util.Collections;
import java.util.UUID;

public class CreateSessionRequest extends JoinSessionRequest {
public SessionProperties properties;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.Constant;
import io.netty.util.concurrent.Promise;
import org.cloudburstmc.netty.channel.raknet.RakChannelFactory;
import org.cloudburstmc.netty.channel.raknet.RakPing;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public DtlsClient(JcaTlsCrypto crypto, String serverFingerprint, Logger logger)
this.logger = logger.prefixed("DtlsClient");

// Generate the RSA key pair
var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
this.keyPair = keyPairGenerator.generateKeyPair();

Expand Down Expand Up @@ -94,8 +94,8 @@ public void notifyServerCertificate(TlsServerCertificate serverCertificate) thro
logger.error("Invalid certificate: " + serverCertificate);
throw new TlsFatalAlert(AlertDescription.bad_certificate);
}
var cert = serverCertificate.getCertificate().getCertificateAt(0).getEncoded();
var fp = fingerprintFor(cert);
byte[] cert = serverCertificate.getCertificate().getCertificateAt(0).getEncoded();
String fp = fingerprintFor(cert);

if (!fp.equals(finalFingerprint)) {
logger.error("Fingerprint does not match! Expected " + finalFingerprint + " got " + fp);
Expand All @@ -116,19 +116,18 @@ protected ProtocolVersion[] getSupportedVersions() {
}

private String fingerprintFor(byte[] input) {
var digest = new SHA256Digest();
SHA256Digest digest = new SHA256Digest();
digest.update(input, 0, input.length);
var result = new byte[digest.getDigestSize()];
byte[] result = new byte[digest.getDigestSize()];
digest.doFinal(result, 0);

var hexBytes = Hex.encode(result);
byte[] hexBytes = Hex.encode(result);
String hex = new String(hexBytes, StandardCharsets.US_ASCII).toUpperCase();

var fp = new StringBuilder();
StringBuilder fp = new StringBuilder();
int i = 0;
fp.append(hex, i, i + 2);
while ((i += 2) < hex.length())
{
while ((i += 2) < hex.length()) {
fp.append(':');
fp.append(hex, i, i + 2);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public void onMessage(SCTPStream sctpStream, byte[] bytes) {
if (bytes.length == 0) {
throw new IllegalStateException("Expected at least 2 bytes");
}
//todo only do this if segmentcount > 0
var buf = Unpooled.buffer(bytes.length);
// TODO Only do this if segmentcount > 0
ByteBuf buf = Unpooled.buffer(bytes.length);
buf.writeBytes(bytes);

byte remainingSegments = buf.readByte();
Expand Down Expand Up @@ -80,14 +80,14 @@ public void onMessage(SCTPStream sctpStream, byte[] bytes) {
// TODO Implement this check
// if (buf.readableBytes() != expectedLength) {
// System.out.println("expected " + expectedLength + " bytes but got " + buf.readableBytes());
// var disconnect = new DisconnectPacket();
// DisconnectPacket disconnect = new DisconnectPacket();
// disconnect.setReason(DisconnectFailReason.BAD_PACKET);
// disconnect.setKickMessage("");
// sendPacket(disconnect);
// return;
// }

var packet = readPacket(buf);
BedrockPacket packet = readPacket(buf);

if (!(packet instanceof LoginPacket)) {
logger.debug("C -> S: " + packet);
Expand All @@ -114,7 +114,7 @@ public void sendPacket(BedrockPacket packet) {
logger.debug("S -> C: " + packet);
try {
ByteBuf dataBuf = Unpooled.buffer(128);
var shiftedBytes = 5; // leave enough room for data length
int shiftedBytes = 5; // leave enough room for data length
dataBuf.writerIndex(shiftedBytes);

int packetId = codec.getPacketDefinition(packet.getClass()).getId();
Expand All @@ -124,10 +124,10 @@ public void sendPacket(BedrockPacket packet) {
);
codec.tryEncode(helper, dataBuf, packet);

var lastPacketByte = dataBuf.writerIndex();
int lastPacketByte = dataBuf.writerIndex();
dataBuf.readerIndex(shiftedBytes);

var packetLength = lastPacketByte - shiftedBytes;
int packetLength = lastPacketByte - shiftedBytes;
// read from the first actual byte
dataBuf.readerIndex(5 - Utils.varintSize(packetLength));
dataBuf.writerIndex(dataBuf.readerIndex());
Expand All @@ -139,7 +139,7 @@ public void sendPacket(BedrockPacket packet) {
dataBuf = compressionHandler.encode(dataBuf);
}

var ri = dataBuf.readerIndex();
int ri = dataBuf.readerIndex();
dataBuf.readerIndex(ri);

if (encryptionEncoder != null) {
Expand All @@ -152,11 +152,11 @@ public void sendPacket(BedrockPacket packet) {
int segmentCount = (int) Math.ceil(dataBuf.readableBytes() / 10_000f);
for (int remainingSegements = segmentCount - 1; remainingSegements >= 0; remainingSegements--) {
int segmentLength = (remainingSegements == 0 ? dataBuf.readableBytes() : 10_000);
var sendBuf = Unpooled.buffer(segmentLength + 1 + 5);
ByteBuf sendBuf = Unpooled.buffer(segmentLength + 1 + 5);
sendBuf.writeByte(remainingSegements);
sendBuf.writeBytes(dataBuf, segmentLength);

var data = encode(sendBuf);
byte[] data = encode(sendBuf);
sctpStream.send(data);
}
} catch (Exception e) {
Expand All @@ -173,7 +173,7 @@ private byte[] encode(ByteBuf buf) {
private BedrockPacket readPacket(ByteBuf buf) {
BedrockPacketWrapper wrapper = BedrockPacketWrapper.create();
packetCodec.decodeHeader(buf, wrapper);
var packet = codec.tryDecode(helper, buf.slice(), wrapper.getPacketId());
BedrockPacket packet = codec.tryDecode(helper, buf.slice(), wrapper.getPacketId());
// release it
wrapper.getHandle().recycle(wrapper);
return packet;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.rtm516.mcxboxbroadcast.core.models.ws.WsToMessage;
import io.jsonwebtoken.lang.Collections;
import org.bouncycastle.tls.DTLSClientProtocol;
import org.bouncycastle.tls.DTLSTransport;
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCryptoProvider;
import org.ice4j.Transport;
import org.ice4j.TransportAddress;
Expand All @@ -21,6 +22,7 @@

import javax.sdp.Attribute;
import javax.sdp.MediaDescription;
import javax.sdp.SessionDescription;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
Expand All @@ -46,16 +48,16 @@ public PeerSession(RtcWebsocketClient rtcWebsocket, List<CandidateHarvester> can

public void receiveOffer(BigInteger from, String sessionId, String message) {
try {
var factory = new NistSdpFactory();
NistSdpFactory factory = new NistSdpFactory();

var offer = factory.createSessionDescription(message);
SessionDescription offer = factory.createSessionDescription(message);

var stream = agent.createMediaStream("application");
IceMediaStream stream = agent.createMediaStream("application");
String fingerprint = null;
for (Object mediaDescription : offer.getMediaDescriptions(false)) {
var description = (MediaDescription) mediaDescription;
MediaDescription description = (MediaDescription) mediaDescription;
for (Object descriptionAttribute : description.getAttributes(false)) {
var attribute = (Attribute) descriptionAttribute;
Attribute attribute = (Attribute) descriptionAttribute;
switch (attribute.getName()) {
case "ice-ufrag":
stream.setRemoteUfrag(attribute.getValue());
Expand All @@ -72,20 +74,20 @@ public void receiveOffer(BigInteger from, String sessionId, String message) {

component = agent.createComponent(stream, KeepAliveStrategy.SELECTED_ONLY, true);

var transport = new CustomDatagramTransport();
CustomDatagramTransport transport = new CustomDatagramTransport();

var client = new DtlsClient(new JcaTlsCryptoProvider().create(SecureRandom.getInstanceStrong()), fingerprint, rtcWebsocket.logger());
DtlsClient client = new DtlsClient(new JcaTlsCryptoProvider().create(SecureRandom.getInstanceStrong()), fingerprint, rtcWebsocket.logger());

var answer = factory.createSessionDescription();
SessionDescription answer = factory.createSessionDescription();
answer.setOrigin(factory.createOrigin("-", Math.abs(new Random().nextLong()), 2L, "IN", "IP4", "127.0.0.1"));

var attributes = new Vector<>();
Vector<Attribute> attributes = new Vector<>();
attributes.add(factory.createAttribute("group", "BUNDLE 0"));
attributes.add(factory.createAttribute("extmap-allow-mixed", ""));
attributes.add(factory.createAttribute("msid-semantic", " WMS"));
answer.setAttributes(attributes);

var media = factory.createMediaDescription("application", 9, 0, "UDP/DTLS/SCTP", new String[]{"webrtc-datachannel"});
MediaDescription media = factory.createMediaDescription("application", 9, 0, "UDP/DTLS/SCTP", new String[]{"webrtc-datachannel"});
media.setConnection(factory.createConnection("IN", "IP4", "0.0.0.0"));
media.setAttribute("ice-ufrag", agent.getLocalUfrag());
media.setAttribute("ice-pwd", agent.getLocalPassword());
Expand All @@ -97,14 +99,14 @@ public void receiveOffer(BigInteger from, String sessionId, String message) {
media.setAttribute("max-message-size", "262144");
answer.setMediaDescriptions(new Vector<>(Collections.of(media)));

var json = Constants.GSON.toJson(new WsToMessage(
String json = Constants.GSON.toJson(new WsToMessage(
1, from, "CONNECTRESPONSE " + sessionId + " " + answer
));
rtcWebsocket.send(json);

int i = 0;
for (LocalCandidate candidate : component.getLocalCandidates()) {
var jsonAdd = Constants.GSON.toJson(new WsToMessage(
String jsonAdd = Constants.GSON.toJson(new WsToMessage(
1, from, "CANDIDATEADD " + sessionId + " " + candidate.toString() + " generation 0 ufrag " + agent.getLocalUfrag() + " network-id " + i + " network-cost 0"
));
i++;
Expand All @@ -115,7 +117,7 @@ public void receiveOffer(BigInteger from, String sessionId, String message) {
if ("IceProcessingState".equals(evt.getPropertyName()) && IceProcessingState.COMPLETED.equals(evt.getNewValue())) {
transport.init(component);
try {
var dtlsTransport = new DTLSClientProtocol().connect(client, transport);
DTLSTransport dtlsTransport = new DTLSClientProtocol().connect(client, transport);
// Log.setLevel(Log.DEBUG);

// Log the remote public IP
Expand Down
Loading

0 comments on commit ed948d7

Please sign in to comment.