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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
|
package cuchaz.enigma.network;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import cuchaz.enigma.network.packet.*;
import cuchaz.enigma.translation.mapping.EntryChange;
import cuchaz.enigma.translation.mapping.EntryMapping;
import cuchaz.enigma.translation.mapping.EntryRemapper;
import cuchaz.enigma.translation.representation.entry.Entry;
public abstract class EnigmaServer {
// https://discordapp.com/channels/507304429255393322/566418023372816394/700292322918793347
public static final int DEFAULT_PORT = 34712;
public static final int PROTOCOL_VERSION = 1;
public static final int CHECKSUM_SIZE = 20;
public static final int MAX_PASSWORD_LENGTH = 255; // length is written as a byte in the login packet
private final int port;
private ServerSocket socket;
private List<Socket> clients = new CopyOnWriteArrayList<>();
private Map<Socket, String> usernames = new HashMap<>();
private Set<Socket> unapprovedClients = new HashSet<>();
private final byte[] jarChecksum;
private final char[] password;
public static final int DUMMY_SYNC_ID = 0;
private final EntryRemapper mappings;
private Map<Entry<?>, Integer> syncIds = new HashMap<>();
private Map<Integer, Entry<?>> inverseSyncIds = new HashMap<>();
private Map<Integer, Set<Socket>> clientsNeedingConfirmation = new HashMap<>();
private int nextSyncId = DUMMY_SYNC_ID + 1;
private static int nextIoId = 0;
public EnigmaServer(byte[] jarChecksum, char[] password, EntryRemapper mappings, int port) {
this.jarChecksum = jarChecksum;
this.password = password;
this.mappings = mappings;
this.port = port;
}
public void start() throws IOException {
socket = new ServerSocket(port);
log("Server started on " + socket.getInetAddress() + ":" + port);
Thread thread = new Thread(() -> {
try {
while (!socket.isClosed()) {
acceptClient();
}
} catch (SocketException e) {
System.out.println("Server closed");
} catch (IOException e) {
e.printStackTrace();
}
});
thread.setName("Server client listener");
thread.setDaemon(true);
thread.start();
}
private void acceptClient() throws IOException {
Socket client = socket.accept();
clients.add(client);
Thread thread = new Thread(() -> {
try {
DataInput input = new DataInputStream(client.getInputStream());
while (true) {
int packetId;
try {
packetId = input.readUnsignedByte();
} catch (EOFException | SocketException e) {
break;
}
Packet<ServerPacketHandler> packet = PacketRegistry.createC2SPacket(packetId);
if (packet == null) {
throw new IOException("Received invalid packet id " + packetId);
}
packet.read(input);
runOnThread(() -> packet.handle(new ServerPacketHandler(client, this)));
}
} catch (IOException e) {
kick(client, e.toString());
e.printStackTrace();
return;
}
kick(client, "disconnect.disconnected");
});
thread.setName("Server I/O thread #" + (nextIoId++));
thread.setDaemon(true);
thread.start();
}
public void stop() {
runOnThread(() -> {
if (socket != null && !socket.isClosed()) {
for (Socket client : clients) {
kick(client, "disconnect.server_closed");
}
try {
socket.close();
} catch (IOException e) {
System.err.println("Failed to close server socket");
e.printStackTrace();
}
}
});
}
public void kick(Socket client, String reason) {
if (!clients.remove(client)) return;
sendPacket(client, new KickS2CPacket(reason));
clientsNeedingConfirmation.values().removeIf(list -> {
list.remove(client);
return list.isEmpty();
});
String username = usernames.remove(client);
try {
client.close();
} catch (IOException e) {
System.err.println("Failed to close server client socket");
e.printStackTrace();
}
if (username != null) {
System.out.println("Kicked " + username + " because " + reason);
sendMessage(Message.disconnect(username));
}
sendUsernamePacket();
}
public boolean isUsernameTaken(String username) {
return usernames.containsValue(username);
}
public void setUsername(Socket client, String username) {
usernames.put(client, username);
sendUsernamePacket();
}
private void sendUsernamePacket() {
List<String> usernames = new ArrayList<>(this.usernames.values());
Collections.sort(usernames);
sendToAll(new UserListS2CPacket(usernames));
}
public String getUsername(Socket client) {
return usernames.get(client);
}
public void sendPacket(Socket client, Packet<ClientPacketHandler> packet) {
if (!client.isClosed()) {
int packetId = PacketRegistry.getS2CId(packet);
try {
DataOutput output = new DataOutputStream(client.getOutputStream());
output.writeByte(packetId);
packet.write(output);
} catch (IOException e) {
if (!(packet instanceof KickS2CPacket)) {
kick(client, e.toString());
e.printStackTrace();
}
}
}
}
public void sendToAll(Packet<ClientPacketHandler> packet) {
for (Socket client : clients) {
sendPacket(client, packet);
}
}
public void sendToAllExcept(Socket excluded, Packet<ClientPacketHandler> packet) {
for (Socket client : clients) {
if (client != excluded) {
sendPacket(client, packet);
}
}
}
public boolean canModifyEntry(Socket client, Entry<?> entry) {
if (unapprovedClients.contains(client)) {
return false;
}
Integer syncId = syncIds.get(entry);
if (syncId == null) {
return true;
}
Set<Socket> clients = clientsNeedingConfirmation.get(syncId);
return clients == null || !clients.contains(client);
}
public int lockEntry(Socket exception, Entry<?> entry) {
int syncId = nextSyncId;
nextSyncId++;
// sync id is sent as an unsigned short, can't have more than 65536
if (nextSyncId == 65536) {
nextSyncId = DUMMY_SYNC_ID + 1;
}
Integer oldSyncId = syncIds.get(entry);
if (oldSyncId != null) {
clientsNeedingConfirmation.remove(oldSyncId);
}
syncIds.put(entry, syncId);
inverseSyncIds.put(syncId, entry);
Set<Socket> clients = new HashSet<>(this.clients);
clients.remove(exception);
clientsNeedingConfirmation.put(syncId, clients);
return syncId;
}
public void confirmChange(Socket client, int syncId) {
if (usernames.containsKey(client)) {
unapprovedClients.remove(client);
}
Set<Socket> clients = clientsNeedingConfirmation.get(syncId);
if (clients != null) {
clients.remove(client);
if (clients.isEmpty()) {
clientsNeedingConfirmation.remove(syncId);
syncIds.remove(inverseSyncIds.remove(syncId));
}
}
}
public void sendCorrectMapping(Socket client, Entry<?> entry, boolean refreshClassTree) {
EntryMapping oldMapping = mappings.getDeobfMapping(entry);
String oldName = oldMapping.targetName();
if (oldName == null) {
sendPacket(client, new EntryChangeS2CPacket(DUMMY_SYNC_ID, EntryChange.modify(entry).clearDeobfName()));
} else {
sendPacket(client, new EntryChangeS2CPacket(0, EntryChange.modify(entry).withDeobfName(oldName)));
}
}
protected abstract void runOnThread(Runnable task);
public void log(String message) {
System.out.println(message);
}
protected boolean isRunning() {
return !socket.isClosed();
}
public byte[] getJarChecksum() {
return jarChecksum;
}
public char[] getPassword() {
return password;
}
public EntryRemapper getMappings() {
return mappings;
}
public void sendMessage(Message message) {
log(String.format("[MSG] %s", message.translate()));
sendToAll(new MessageS2CPacket(message));
}
}
|