aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/gq/malwarefight/tokenapp/SocketThread.java
blob: 572ca57c01af1f7f0cb2ea13aafdf0e48c711f5a (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
package gq.malwarefight.tokenapp;

import com.mojang.authlib.exceptions.AuthenticationException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class SocketThread extends Thread {
    private final Socket sock;
    public SocketThread(Socket sock) {
        this.sock = sock;
    }

    public void writeResponse(String output, OutputStream outputStream) throws IOException {
        outputStream.write(
                (output + "\n").getBytes(StandardCharsets.UTF_8)
        );
        outputStream.flush();
    }

    @Override
    public void run() {
        try {
            InputStream in = sock.getInputStream();
            OutputStream out = sock.getOutputStream();
            Scanner scanner = new Scanner(in, StandardCharsets.UTF_8.name());
            while (true) {
                if (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    String[] parts = line.split(" ");
                    if ("login".equals(parts[0])) {
                        try {
                            Main.sessionService.joinServer(
                                    Main.gameProfile, Main.authenticationService.getClientToken(), parts[1]
                            );
                        } catch (Exception e) {
                            if (e instanceof ArrayIndexOutOfBoundsException) {
                                writeResponse("400 Bad Request", out);
                            } else if (e instanceof AuthenticationException) {
                                writeResponse("401 Unauthorized", out);
                            } else {
                                writeResponse("500 Internal Server Error", out);
                            }
                            continue;
                        }
                        writeResponse("200 OK", out);
                    } else if ("disconnect".equals(parts[0])) {
                        sock.close();
                    } else if ("fullquit".equals(parts[0])) {
                        Main.running = false;
                        sock.close();
                        return;
                    } else {
                        writeResponse("418 I'm a teapot", out);
                    }
                }
            }
        } catch (IOException ignored) {}
    }
}