first commit

This commit is contained in:
1e99 2024-11-17 13:45:23 +01:00
commit f8777ad035
32 changed files with 1536 additions and 0 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
.gradle
.idea
build
client-fabric/run

347
LICENSE.md Normal file
View file

@ -0,0 +1,347 @@
Mozilla Public License Version 2.0
==================================
### 1. Definitions
**1.1. “Contributor”**
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
**1.2. “Contributor Version”**
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
**1.3. “Contribution”**
means Covered Software of a particular Contributor.
**1.4. “Covered Software”**
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
**1.5. “Incompatible With Secondary Licenses”**
means
* **(a)** that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
* **(b)** that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
**1.6. “Executable Form”**
means any form of the work other than Source Code Form.
**1.7. “Larger Work”**
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
**1.8. “License”**
means this document.
**1.9. “Licensable”**
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
**1.10. “Modifications”**
means any of the following:
* **(a)** any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
* **(b)** any new file in Source Code Form that contains any Covered
Software.
**1.11. “Patent Claims” of a Contributor**
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
**1.12. “Secondary License”**
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
**1.13. “Source Code Form”**
means the form of the work preferred for making modifications.
**1.14. “You” (or “Your”)**
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, “control” means **(a)** the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or **(b)** ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
### 2. License Grants and Conditions
#### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
* **(a)** under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
* **(b)** under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
#### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
#### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
* **(a)** for any code that a Contributor has removed from Covered Software;
or
* **(b)** for infringements caused by: **(i)** Your and any other third party's
modifications of Covered Software, or **(ii)** the combination of its
Contributions with other software (except as part of its Contributor
Version); or
* **(c)** under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
#### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
#### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
#### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
#### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
### 3. Responsibilities
#### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
#### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
* **(a)** such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
* **(b)** You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
#### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
#### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
#### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
### 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: **(a)** comply with
the terms of this License to the maximum extent possible; and **(b)**
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
### 5. Termination
**5.1.** The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated **(a)** provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and **(b)** on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
**5.2.** If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
**5.3.** In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
### 6. Disclaimer of Warranty
> Covered Software is provided under this License on an “as is”
> basis, without warranty of any kind, either expressed, implied, or
> statutory, including, without limitation, warranties that the
> Covered Software is free of defects, merchantable, fit for a
> particular purpose or non-infringing. The entire risk as to the
> quality and performance of the Covered Software is with You.
> Should any Covered Software prove defective in any respect, You
> (not any Contributor) assume the cost of any necessary servicing,
> repair, or correction. This disclaimer of warranty constitutes an
> essential part of this License. No use of any Covered Software is
> authorized under this License except under this disclaimer.
### 7. Limitation of Liability
> Under no circumstances and under no legal theory, whether tort
> (including negligence), contract, or otherwise, shall any
> Contributor, or anyone who distributes Covered Software as
> permitted above, be liable to You for any direct, indirect,
> special, incidental, or consequential damages of any character
> including, without limitation, damages for lost profits, loss of
> goodwill, work stoppage, computer failure or malfunction, or any
> and all other commercial damages or losses, even if such party
> shall have been informed of the possibility of such damages. This
> limitation of liability shall not apply to liability for death or
> personal injury resulting from such party's negligence to the
> extent applicable law prohibits such limitation. Some
> jurisdictions do not allow the exclusion or limitation of
> incidental or consequential damages, so this exclusion and
> limitation may not apply to You.
### 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
### 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
### 10. Versions of the License
#### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
#### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
#### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
#### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

3
build.gradle Normal file
View file

@ -0,0 +1,3 @@
plugins {
id 'java'
}

View file

@ -0,0 +1,45 @@
plugins {
id 'fabric-loom' version '1.8-SNAPSHOT'
}
repositories {
mavenCentral()
}
dependencies {
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
implementation project(':common')
}
sourceSets {
main.java.srcDirs = ['src']
main.resources.srcDirs = ['resources']
}
processResources {
inputs.property "version", version
filesMatching("fabric.mod.json") {
expand "version": version
}
}
tasks.withType(JavaCompile).configureEach {
it.options.release = 21
}
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
jar {
from("LICENSE") {
rename { "${it}_${project.base.archivesName.get()}" }
}
}

View file

@ -0,0 +1,7 @@
org.gradle.jvmargs=-Xmx1G
org.gradle.parallel=true
# https://fabricmc.net/develop
minecraft_version=1.21.3
yarn_mappings=1.21.3+build.2
loader_version=0.16.9
fabric_version=0.108.0+1.21.3

View file

@ -0,0 +1,33 @@
{
"schemaVersion": 1,
"id": "svc",
"version": "${version}",
"name": "Simpler Voice Chat",
"description": "Simpler voice chat for our favorite block game",
"authors": [
"1e99"
],
"contact": {
"sources": "https://git.1e99.eu/1e99/simplervoicechat"
},
"license": "MPL-2.0",
"icon": "assets/svc/icon.png",
"environment": "*",
"entrypoints": {
"client": [
"eu.e99.svc.client.fabric.FabricSimplerVoiceChat"
]
},
"mixins": [
{
"config": "svc.mixins.json",
"environment": "client"
}
],
"depends": {
"fabricloader": ">=0.16.7",
"minecraft": "~1.21.3",
"java": ">=21",
"fabric-api": "*"
}
}

View file

@ -0,0 +1,10 @@
{
"required": true,
"package": "eu.e99.svc.client.fabric.mixin",
"compatibilityLevel": "JAVA_21",
"mixins": [
],
"injectors": {
"defaultRequire": 1
}
}

View file

@ -0,0 +1,18 @@
package eu.e99.svc.client.fabric;
import net.fabricmc.api.ClientModInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FabricSimplerVoiceChat implements ClientModInitializer {
public static final String NAMESPACE = "svc";
public static final Logger LOGGER = LoggerFactory.getLogger(NAMESPACE);
@Override
public void onInitializeClient() {
LOGGER.info("Simpler Voice Chat Running");
}
}

16
common/build.gradle Normal file
View file

@ -0,0 +1,16 @@
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.code.gson:gson:2.11.0'
}
sourceSets {
main.java.srcDirs = ['src']
main.resources.srcDirs = ['resources']
}

View file

@ -0,0 +1,20 @@
package eu.e99.svc;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
public class AllTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}

View file

@ -0,0 +1,41 @@
package eu.e99.svc;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.Reader;
import eu.e99.svc.io.Writer;
import eu.e99.svc.packet.DisconnectPacket;
import java.io.IOException;
import java.net.Socket;
public class Connection {
private final Socket socket;
private final Reader reader;
private final Writer writer;
public Connection(Socket socket) throws IOException {
this.socket = socket;
this.reader = new Reader(this.socket.getInputStream());
this.writer = new Writer(this.socket.getOutputStream());
}
public void writePacket(BinaryMessage packet) throws IOException {
synchronized (this.socket) {
SimplerVoiceChat.PACKETS.writeMessage(packet, this.writer);
}
}
public BinaryMessage readPacket() throws IOException {
synchronized (this.socket) {
return SimplerVoiceChat.PACKETS.readMessage(this.reader);
}
}
public void disconnect(String reason) throws IOException {
DisconnectPacket disconnect = new DisconnectPacket();
disconnect.reason = reason;
this.writePacket(disconnect);
this.socket.close();
}
}

View file

@ -0,0 +1,100 @@
package eu.e99.svc;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.MessageRegistry;
import eu.e99.svc.packet.*;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class SimplerVoiceChat {
public static final int PROTOCOL_VERSION = 0;
public static final MessageRegistry PACKETS = new MessageRegistry();
public static final MessageRegistry MESSAGES = new MessageRegistry();
static {
PACKETS.registerMessage(0, ClientHelloPacket::new);
// TODO: Keep alive?
PACKETS.registerMessage(2, AuthRequestPacket::new);
PACKETS.registerMessage(3, AuthResponsePacket::new);
PACKETS.registerMessage(4, AuthSuccessPacket::new);
PACKETS.registerMessage(100, MessagePacket::new);
PACKETS.registerMessage(255, DisconnectPacket::new);
}
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustManagers = new TrustManager[]{
new AllTrustManager(),
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SimplerVoiceChat voiceChat = new SimplerVoiceChat("localhost", 6969, socketFactory);
voiceChat.start();
}
private final String host;
private final int port;
private final SSLSocketFactory socketFactory;
public SimplerVoiceChat(String host, int port, SSLSocketFactory socketFactory) {
this.host = host;
this.port = port;
this.socketFactory = socketFactory;
}
public void start() {
// Connect and auth
try (Socket socket = this.socketFactory.createSocket()) {
socket.connect(new InetSocketAddress(this.host, this.port));
Connection conn = new Connection(socket);
this.handleHandshake(conn);
} catch (IOException e) {
System.out.printf("Failed to connect.%n");
e.printStackTrace(System.out);
}
}
private void handleHandshake(Connection conn) throws IOException {
ClientHelloPacket clientHello = new ClientHelloPacket();
clientHello.version = PROTOCOL_VERSION;
conn.writePacket(clientHello);
while (true) {
BinaryMessage packet = conn.readPacket();
switch (packet) {
case AuthRequestPacket authRequest -> {
System.out.printf("Joining fake server to authenticate.%n");
AuthResponsePacket authResponse = new AuthResponsePacket();
authResponse.username = "Test";
conn.writePacket(authResponse);
}
case AuthSuccessPacket authComplete -> {
System.out.printf("Successfully authenticated.%n");
return;
}
default -> {
System.out.printf("Got unexpected packet.%n");
}
}
}
}
}

View file

@ -0,0 +1,42 @@
package eu.e99.svc.auth;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;
// https://wiki.vg/Protocol_Encryption
public class MojangAPI {
public static PlayerProfile hasJoined(String username, String serverId) throws IOException, InterruptedException {
try (HttpClient client = HttpClient.newHttpClient()) {
String loc = String.format("https://sessionserver.mojang.com/session/minecraft/hasJoined?username=%s&serverId=%s", username, serverId);
URI uri = URI.create(loc);
HttpRequest req = HttpRequest.newBuilder()
.uri(uri)
.GET()
.build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 204) {
return null;
}
JsonObject object = JsonParser
.parseString(res.body())
.getAsJsonObject();
String name = object.get("name").getAsString();
String rawUuid = object.get("id").getAsString();
UUID uuid = UUID.fromString(rawUuid.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
return new PlayerProfile(name, uuid);
}
}
}

View file

@ -0,0 +1,11 @@
package eu.e99.svc.auth;
import java.util.UUID;
public record PlayerProfile(
String username,
UUID uuid
) {
}

View file

@ -0,0 +1,10 @@
package eu.e99.svc.io;
import java.io.IOException;
public interface BinaryMessage {
void read(Reader reader) throws IOException;
void write(Writer writer) throws IOException;
}

View file

@ -0,0 +1,50 @@
package eu.e99.svc.io;
import eu.e99.svc.packet.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class MessageRegistry {
private final Map<Integer, Supplier<? extends BinaryMessage>> messagesById;
private final Map<Class<? extends BinaryMessage>, Integer> messagesByClass;
public MessageRegistry() {
this.messagesById = new HashMap<>();
this.messagesByClass = new HashMap<>();
}
public BinaryMessage readMessage(Reader reader) throws IOException {
int id = reader.readInt();
Supplier<? extends BinaryMessage> supplier = this.messagesById.get(id);;
if (supplier == null) {
throw new RuntimeException("Failed to find message with id " + id);
}
BinaryMessage msg = supplier.get();
msg.read(reader);
return msg;
}
public void writeMessage(BinaryMessage msg, Writer writer) throws IOException {
Class<? extends BinaryMessage> clazz = msg.getClass();
Integer id = this.messagesByClass.get(clazz);
if (id == null) {
throw new IllegalArgumentException("Unknown message sent.");
}
writer.writeInt(id);
msg.write(writer);
}
public void registerMessage(int id, Supplier<? extends BinaryMessage> supplier) {
BinaryMessage msg = supplier.get();
Class<? extends BinaryMessage> clazz = msg.getClass();
this.messagesById.put(id, supplier);
this.messagesByClass.put(clazz, id);
}
}

View file

@ -0,0 +1,48 @@
package eu.e99.svc.io;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Reader {
private final DataInputStream in;
public Reader(InputStream in) {
this.in = new DataInputStream(in);
}
public int readInt() throws IOException {
return this.in.readInt();
}
public long readLong() throws IOException {
return this.in.readLong();
}
public boolean readBool() throws IOException {
return this.in.readBoolean();
}
public String readString() throws IOException {
byte[] bytes = this.readByteArray();
return new String(bytes, StandardCharsets.UTF_8);
}
public byte[] readByteArray() throws IOException {
int length = this.readInt();
byte[] bytes = new byte[length];
this.in.readFully(bytes);
return bytes;
}
public UUID readUUID() throws IOException {
long most = this.readLong();
long least = this.readLong();
return new UUID(most, least);
}
}

View file

@ -0,0 +1,43 @@
package eu.e99.svc.io;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Writer {
private final DataOutputStream out;
public Writer(OutputStream out) {
this.out = new DataOutputStream(out);
}
public void writeInt(int i) throws IOException {
this.out.writeInt(i);
}
public void writeLong(long l) throws IOException {
this.out.writeLong(l);
}
public void writeBool(boolean bool) throws IOException {
this.out.writeBoolean(bool);
}
public void writeString(String string) throws IOException {
byte[] bytes = string.getBytes(StandardCharsets.UTF_8);
this.writeByteArray(bytes);
}
public void writeByteArray(byte[] bytes) throws IOException {
this.writeInt(bytes.length);
this.out.write(bytes);
}
public void writeUUID(UUID uuid) throws IOException {
this.writeLong(uuid.getMostSignificantBits());
this.writeLong(uuid.getLeastSignificantBits());
}
}

View file

@ -0,0 +1,22 @@
package eu.e99.svc.packet;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.Reader;
import eu.e99.svc.io.Writer;
import java.io.IOException;
public class AuthRequestPacket implements BinaryMessage {
public String serverId;
@Override
public void read(Reader reader) throws IOException {
this.serverId = reader.readString();
}
@Override
public void write(Writer writer) throws IOException {
writer.writeString(this.serverId);
}
}

View file

@ -0,0 +1,22 @@
package eu.e99.svc.packet;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.Reader;
import eu.e99.svc.io.Writer;
import java.io.IOException;
public class AuthResponsePacket implements BinaryMessage {
public String username;
@Override
public void read(Reader reader) throws IOException {
this.username = reader.readString();
}
@Override
public void write(Writer writer) throws IOException {
writer.writeString(this.username);
}
}

View file

@ -0,0 +1,20 @@
package eu.e99.svc.packet;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.Reader;
import eu.e99.svc.io.Writer;
import java.io.IOException;
public class AuthSuccessPacket implements BinaryMessage {
@Override
public void read(Reader reader) throws IOException {
}
@Override
public void write(Writer writer) throws IOException {
}
}

View file

@ -0,0 +1,22 @@
package eu.e99.svc.packet;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.Reader;
import eu.e99.svc.io.Writer;
import java.io.IOException;
public class ClientHelloPacket implements BinaryMessage {
public int version;
@Override
public void read(Reader reader) throws IOException {
this.version = reader.readInt();
}
@Override
public void write(Writer writer) throws IOException {
writer.writeInt(this.version);
}
}

View file

@ -0,0 +1,22 @@
package eu.e99.svc.packet;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.Reader;
import eu.e99.svc.io.Writer;
import java.io.IOException;
public class DisconnectPacket implements BinaryMessage {
public String reason;
@Override
public void read(Reader reader) throws IOException {
this.reason = reader.readString();
}
@Override
public void write(Writer writer) throws IOException {
writer.writeString(this.reason);
}
}

View file

@ -0,0 +1,26 @@
package eu.e99.svc.packet;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.io.Reader;
import eu.e99.svc.io.Writer;
import java.io.IOException;
import java.util.UUID;
public class MessagePacket implements BinaryMessage {
public UUID player;
public byte[] payload;
@Override
public void read(Reader reader) throws IOException {
this.player = reader.readUUID();
this.payload = reader.readByteArray();
}
@Override
public void write(Writer writer) throws IOException {
writer.writeUUID(this.player);
writer.writeByteArray(this.payload);
}
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1 @@
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-bin.zip

176
gradlew vendored Executable file
View file

@ -0,0 +1,176 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
if $JAVACMD --add-opens java.base/java.lang=ALL-UNNAMED -version ; then
DEFAULT_JVM_OPTS="--add-opens java.base/java.lang=ALL-UNNAMED $DEFAULT_JVM_OPTS"
fi
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored Normal file
View file

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

18
server/build.gradle Normal file
View file

@ -0,0 +1,18 @@
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation project(':common')
implementation 'org.slf4j:slf4j-api:2.0.16'
implementation 'org.slf4j:slf4j-simple:2.0.16'
}
sourceSets {
main.java.srcDirs = ['src']
main.resources.srcDirs = ['resources']
}

View file

@ -0,0 +1,65 @@
package eu.e99.svc.server;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.security.KeyStore;
public class Main {
public static void main(String[] args) {
SSLServerSocketFactory socketFactory = createSocketFactory();
if (socketFactory == null) {
System.exit(1);
}
try (ServerSocket socket = socketFactory.createServerSocket()) {
socket.bind(new InetSocketAddress("0.0.0.0", 6969));
Server server = new Server(socket);
server.start();
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
private static SSLServerSocketFactory createSocketFactory() {
try {
// keytool -genkeypair -keyalg RSA -keysize 2048 -validity 365 -alias mykey -keystore keystore.jks
String path = System.getenv("SVC_KEYSTORE_PATH");
if (path == null) {
System.out.printf("Missing SVC_KEYSTORE_PATH env variable.%n");
return null;
}
String password = System.getenv("SVC_KEYSTORE_PASSWORD");
if (password == null) {
System.out.printf("Missing SVC_KEYSTORE_PASSWORD env variable.%n");
return null;
}
KeyStore keyStore = KeyStore.getInstance("JKS");
try (FileInputStream keystoreFile = new FileInputStream(path)) {
keyStore.load(keystoreFile, password.toCharArray());
}
KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509");
managerFactory.init(keyStore, password.toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(managerFactory.getKeyManagers(), null, null);
return context.getServerSocketFactory();
} catch (Exception e) {
System.out.printf("Failed to create SSL Server Socket Factory.%n");
e.printStackTrace(System.out);
return null;
}
}
}

View file

@ -0,0 +1,195 @@
package eu.e99.svc.server;
import eu.e99.svc.Connection;
import eu.e99.svc.SimplerVoiceChat;
import eu.e99.svc.auth.MojangAPI;
import eu.e99.svc.auth.PlayerProfile;
import eu.e99.svc.io.BinaryMessage;
import eu.e99.svc.packet.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class Server {
private final ServerSocket socket;
private final Map<UUID, Connection> connections;
public Server(ServerSocket socket) {
this.socket = socket;
this.connections = new HashMap<>();
}
public void start() {
while (true) {
Thread.ofVirtual().start(() -> {
try (Socket client = this.socket.accept()) {
synchronized (this.socket) {
this.socket.notify();
}
this.handleConnection(client);
} catch (IOException e) {
synchronized (this.socket) {
this.socket.notify();
}
System.out.printf("Failed to accept client.%n");
e.printStackTrace(System.out);
}
});
try {
synchronized (this.socket) {
this.socket.wait();
}
} catch (InterruptedException e) {
System.out.printf("Failed to wait on server socket to accept client.%n");
e.printStackTrace(System.out);
}
}
}
private void handleConnection(Socket client) throws IOException {
System.out.printf("Accepted client %s.%n", client.getInetAddress());
Connection conn = new Connection(client);
PlayerProfile profile = this.handleHandshake(conn);
if (profile == null) {
System.out.printf("Client failed authentication.%n");
return;
}
try {
synchronized (this.connections) {
Connection existingConn = this.connections.get(profile.uuid());
if (existingConn != null) {
existingConn.disconnect("Logged in from another location.");
System.out.printf("Client %s logged in from another location.%n", profile.username());
}
this.connections.put(profile.uuid(), conn);
System.out.printf("Client %s successfully authenticated.%n", profile.username());
}
this.handle(conn, profile);
} finally {
synchronized (this.connections) {
this.connections.remove(profile.uuid());
}
}
}
private PlayerProfile handleHandshake(Connection conn) throws IOException {
/*
1. Client sends ClientHelloPacket
2. Server sends AuthRequestPacket with a random server ID
3. Client joins fake server ID using Mojang's session server
4. Client sends AuthResponsePacket with its username
5. Server checks if player joined the server with Mojang's session server
6. Server sends AuthSuccessPacket
*/
String serverId = this.generateServerId();
while (true) {
BinaryMessage packet = conn.readPacket();
switch (packet) {
case ClientHelloPacket clientHello -> {
if (clientHello.version > SimplerVoiceChat.PROTOCOL_VERSION) {
System.out.printf("Refusing to accept client, outdated server.%n");
conn.disconnect("Outdated server. Please downgrade the mod.");
return null;
}
if (clientHello.version < SimplerVoiceChat.PROTOCOL_VERSION) {
System.out.printf("Refusing to accept client, outdated client.%n");
conn.disconnect("Outdated client. Please update the mode.");
return null;
}
AuthRequestPacket authRequest = new AuthRequestPacket();
authRequest.serverId = serverId;
conn.writePacket(authRequest);
}
case AuthResponsePacket response -> {
PlayerProfile profile;
try {
profile = MojangAPI.hasJoined(response.username, serverId);
} catch (InterruptedException e) {
System.out.printf("Failed to reach Mojang's authentication server.%n");
e.printStackTrace(System.out);
conn.disconnect("Mojang's authentication servers are offline. Please try again later.");
return null;
}
if (profile == null) {
System.out.printf("Client failed authentication.%n");
conn.disconnect("Authentication failed.");
return null;
}
AuthSuccessPacket success = new AuthSuccessPacket();
conn.writePacket(success);
return profile;
}
default -> {
System.out.printf("Received unexpected packet.%n");
}
}
}
}
private void handle(Connection conn, PlayerProfile profile) throws IOException {
while (true) {
BinaryMessage packet = conn.readPacket();
switch (packet) {
case DisconnectPacket disconnect -> {
System.out.printf("Client %s disconnected with the reason \"%s\"%n", profile.username(), disconnect.reason);
return;
}
case MessagePacket message -> {
Connection otherConn;
synchronized (this.connections) {
otherConn = this.connections.get(message.player);
}
if (otherConn == null) {
// TODO: Send error to client?
continue;
}
MessagePacket newMessage = new MessagePacket();
newMessage.player = profile.uuid();
newMessage.payload = message.payload;
otherConn.writePacket(newMessage);
}
default -> {
System.out.printf("Received unexpected packet.%n");
}
}
}
}
private String generateServerId() {
int length = 32;
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int letter = (int) (letters.length() * Math.random());
builder.append(letters.charAt(letter));
}
return builder.toString();
}
}

15
settings.gradle Normal file
View file

@ -0,0 +1,15 @@
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = 'simplervoicechat'
include 'client-fabric'
include 'common'
include 'server'