OldUsersConverter .java

net.minecraft.server.players.OldUsersConverter (class, 436 lines): members: convertMobOwnerIfNecessary, areOldUserlistsRemoved, convertUserBanlist, LOGGER.

net.minecraft.server.playersclass436 linesserver15.7 KB

API Surface (16)

boolean convertUserBanlist(final MinecraftServer server)
void onProfileLookupSucceeded(final String profileName, final UUID profileId)
void onProfileLookupFailed(final String profileName, final Exception exception)
boolean convertIpBanlist(final MinecraftServer server)
boolean convertOpsList(final MinecraftServer server)
void onProfileLookupSucceeded(final String profileName, final UUID profileId)
void onProfileLookupFailed(final String profileName, final Exception exception)
boolean convertWhiteList(final MinecraftServer server)
void onProfileLookupSucceeded(final String profileName, final UUID profileId)
void onProfileLookupFailed(final String profileName, final Exception exception)
void onProfileLookupSucceeded(final String profileName, final UUID profileIdx)
void onProfileLookupFailed(final String profileName, final Exception exception)
boolean convertPlayers(final DedicatedServer server)
void onProfileLookupSucceeded(final String profileName, final UUID profileId)
void onProfileLookupFailed(final String profileName, final Exception exception)
boolean areOldUserlistsRemoved()

Fields & Constants (5)

LOGGER
OLD_IPBANLIST
OLD_USERBANLIST
OLD_OPLIST
OLD_WHITELIST

String literals (20)

"banned-ips.txt"
"banned-players.txt"
"ops.txt"
"white-list.txt"
"Profile not in the conversionlist"
"Could not request user "
" from backend systems"
"Could not read old user banlist to convert it!"
"Conversion failed, please try again later"
"Could not parse old ip banlist to convert it!"
"Could not read old oplist to convert it!"
"Could not read old whitelist to convert it!"
"unknownplayers"
".dat"
"Could not convert file for "
"Could not find the filename for "
" anymore"
"Can't create directory "
" in world save directory."
".converted"

Code Graph: Dependencies (7)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

OldUsersConverter.java436 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.server.players;
2
3
import com.google.common.collect.Lists;
4
import com.google.common.collect.Maps;
5
import com.google.common.io.Files;
6
import com.mojang.authlib.ProfileLookupCallback;
7
import com.mojang.authlib.services.ProfileNotFoundException;
8
import com.mojang.logging.LogUtils;
9
import java.io.File;
10
import java.io.IOException;
11
import java.nio.charset.StandardCharsets;
12
import java.text.ParseException;
13
import java.util.ArrayList;
14
import java.util.Collection;
15
import java.util.Date;
16
import java.util.List;
17
import java.util.Locale;
18
import java.util.Map;
19
import java.util.Optional;
20
import java.util.UUID;
21
import net.minecraft.core.UUIDUtil;
22
import net.minecraft.server.MinecraftServer;
23
import net.minecraft.server.dedicated.DedicatedServer;
24
import net.minecraft.server.notifications.EmptyNotificationService;
25
import net.minecraft.util.StringUtil;
26
import net.minecraft.world.level.storage.LevelResource;
27
import org.jspecify.annotations.Nullable;
28
import org.slf4j.Logger;
29
30
public class OldUsersConverter {
31
	private static final Logger LOGGER = LogUtils.getLogger();
32
	public static final File OLD_IPBANLIST = new File("banned-ips.txt");
33
	public static final File OLD_USERBANLIST = new File("banned-players.txt");
34
	public static final File OLD_OPLIST = new File("ops.txt");
35
	public static final File OLD_WHITELIST = new File("white-list.txt");
36
37
	private static List<String> readOldListFormat(final File file, final Map<String, String[]> userMap) throws IOException {
38
		List<String> lines = Files.readLines(file, StandardCharsets.UTF_8);
39
40
		for (String line : lines) {
41
			line = line.trim();
42
			if (!line.startsWith("#") && !line.isEmpty()) {
43
				String[] parts = line.split("\\|");
44
				userMap.put(parts[0].toLowerCase(Locale.ROOT), parts);
45
			}
46
		}
47
48
		return lines;
49
	}
50
51
	private static void lookupPlayers(final MinecraftServer server, final Collection<String> names, final ProfileLookupCallback callback) {
52
		String[] filteredNames = names.stream().filter(s -> !StringUtil.isNullOrEmpty(s)).toArray(String[]::new);
53
		if (server.usesAuthentication()) {
54
			server.services().profileRepository().findProfilesByNames(filteredNames, callback);
55
		} else {
56
			for (String name : filteredNames) {
57
				callback.onProfileLookupSucceeded(name, UUIDUtil.createOfflinePlayerUUID(name));
58
			}
59
		}
60
	}
61
62
	public static boolean convertUserBanlist(final MinecraftServer server) {
63
		final UserBanList bans = new UserBanList(PlayerList.USERBANLIST_FILE, new EmptyNotificationService());
64
		if (OLD_USERBANLIST.exists() && OLD_USERBANLIST.isFile()) {
65
			if (bans.getFile().exists()) {
66
				try {
67
					bans.load();
68
				} catch (IOException e) {
69
					LOGGER.warn("Could not load existing file {}", bans.getFile().getName(), e);
70
				}
71
			}
72
73
			try {
74
				final Map<String, String[]> userMap = Maps.newHashMap();
75
				readOldListFormat(OLD_USERBANLIST, userMap);
76
				ProfileLookupCallback callback = new ProfileLookupCallback() {
77
					@Override
78
					public void onProfileLookupSucceeded(final String profileName, final UUID profileId) {
79
						NameAndId profile = new NameAndId(profileId, profileName);
80
						server.services().nameToIdCache().add(profile);
81
						String[] userDef = userMap.get(profile.name().toLowerCase(Locale.ROOT));
82
						if (userDef == null) {
83
							OldUsersConverter.LOGGER.warn("Could not convert user banlist entry for {}", profile.name());
84
							throw new OldUsersConverter.ConversionError("Profile not in the conversionlist");
85
						}
86
87
						Date created = userDef.length > 1 ? OldUsersConverter.parseDate(userDef[1], null) : null;
88
						String source = userDef.length > 2 ? userDef[2] : null;
89
						Date expires = userDef.length > 3 ? OldUsersConverter.parseDate(userDef[3], null) : null;
90
						String reason = userDef.length > 4 ? userDef[4] : null;
91
						bans.add(new UserBanListEntry(profile, created, source, expires, reason));
92
					}
93
94
					@Override
95
					public void onProfileLookupFailed(final String profileName, final Exception exception) {
96
						OldUsersConverter.LOGGER.warn("Could not lookup user banlist entry for {}", profileName, exception);
97
						if (!(exception instanceof ProfileNotFoundException)) {
98
							throw new OldUsersConverter.ConversionError("Could not request user " + profileName + " from backend systems", exception);
99
						}
100
					}
101
				};
102
				lookupPlayers(server, userMap.keySet(), callback);
103
				bans.save();
104
				renameOldFile(OLD_USERBANLIST);
105
				return true;
106
			} catch (IOException e) {
107
				LOGGER.warn("Could not read old user banlist to convert it!", e);
108
				return false;
109
			} catch (OldUsersConverter.ConversionError e) {
110
				LOGGER.error("Conversion failed, please try again later", e);
111
				return false;
112
			}
113
		} else {
114
			return true;
115
		}
116
	}
117
118
	public static boolean convertIpBanlist(final MinecraftServer server) {
119
		IpBanList ipBans = new IpBanList(PlayerList.IPBANLIST_FILE, new EmptyNotificationService());
120
		if (OLD_IPBANLIST.exists() && OLD_IPBANLIST.isFile()) {
121
			if (ipBans.getFile().exists()) {
122
				try {
123
					ipBans.load();
124
				} catch (IOException e) {
125
					LOGGER.warn("Could not load existing file {}", ipBans.getFile().getName(), e);
126
				}
127
			}
128
129
			try {
130
				Map<String, String[]> userMap = Maps.newHashMap();
131
				readOldListFormat(OLD_IPBANLIST, userMap);
132
133
				for (String key : userMap.keySet()) {
134
					String[] userDef = userMap.get(key);
135
					Date created = userDef.length > 1 ? parseDate(userDef[1], null) : null;
136
					String source = userDef.length > 2 ? userDef[2] : null;
137
					Date expires = userDef.length > 3 ? parseDate(userDef[3], null) : null;
138
					String reason = userDef.length > 4 ? userDef[4] : null;
139
					ipBans.add(new IpBanListEntry(key, created, source, expires, reason));
140
				}
141
142
				ipBans.save();
143
				renameOldFile(OLD_IPBANLIST);
144
				return true;
145
			} catch (IOException e) {
146
				LOGGER.warn("Could not parse old ip banlist to convert it!", e);
147
				return false;
148
			}
149
		} else {
150
			return true;
151
		}
152
	}
153
154
	public static boolean convertOpsList(final MinecraftServer server) {
155
		final ServerOpList opsList = new ServerOpList(PlayerList.OPLIST_FILE, new EmptyNotificationService());
156
		if (OLD_OPLIST.exists() && OLD_OPLIST.isFile()) {
157
			if (opsList.getFile().exists()) {
158
				try {
159
					opsList.load();
160
				} catch (IOException e) {
161
					LOGGER.warn("Could not load existing file {}", opsList.getFile().getName(), e);
162
				}
163
			}
164
165
			try {
166
				List<String> lines = Files.readLines(OLD_OPLIST, StandardCharsets.UTF_8);
167
				ProfileLookupCallback callback = new ProfileLookupCallback() {
168
					@Override
169
					public void onProfileLookupSucceeded(final String profileName, final UUID profileId) {
170
						NameAndId profile = new NameAndId(profileId, profileName);
171
						server.services().nameToIdCache().add(profile);
172
						opsList.add(new ServerOpListEntry(profile, server.operatorUserPermissions(), false));
173
					}
174
175
					@Override
176
					public void onProfileLookupFailed(final String profileName, final Exception exception) {
177
						OldUsersConverter.LOGGER.warn("Could not lookup oplist entry for {}", profileName, exception);
178
						if (!(exception instanceof ProfileNotFoundException)) {
179
							throw new OldUsersConverter.ConversionError("Could not request user " + profileName + " from backend systems", exception);
180
						}
181
					}
182
				};
183
				lookupPlayers(server, lines, callback);
184
				opsList.save();
185
				renameOldFile(OLD_OPLIST);
186
				return true;
187
			} catch (IOException e) {
188
				LOGGER.warn("Could not read old oplist to convert it!", e);
189
				return false;
190
			} catch (OldUsersConverter.ConversionError e) {
191
				LOGGER.error("Conversion failed, please try again later", e);
192
				return false;
193
			}
194
		} else {
195
			return true;
196
		}
197
	}
198
199
	public static boolean convertWhiteList(final MinecraftServer server) {
200
		final UserWhiteList whitelist = new UserWhiteList(PlayerList.WHITELIST_FILE, new EmptyNotificationService());
201
		if (OLD_WHITELIST.exists() && OLD_WHITELIST.isFile()) {
202
			if (whitelist.getFile().exists()) {
203
				try {
204
					whitelist.load();
205
				} catch (IOException e) {
206
					LOGGER.warn("Could not load existing file {}", whitelist.getFile().getName(), e);
207
				}
208
			}
209
210
			try {
211
				List<String> lines = Files.readLines(OLD_WHITELIST, StandardCharsets.UTF_8);
212
				ProfileLookupCallback callback = new ProfileLookupCallback() {
213
					@Override
214
					public void onProfileLookupSucceeded(final String profileName, final UUID profileId) {
215
						NameAndId profile = new NameAndId(profileId, profileName);
216
						server.services().nameToIdCache().add(profile);
217
						whitelist.add(new UserWhiteListEntry(profile));
218
					}
219
220
					@Override
221
					public void onProfileLookupFailed(final String profileName, final Exception exception) {
222
						OldUsersConverter.LOGGER.warn("Could not lookup user whitelist entry for {}", profileName, exception);
223
						if (!(exception instanceof ProfileNotFoundException)) {
224
							throw new OldUsersConverter.ConversionError("Could not request user " + profileName + " from backend systems", exception);
225
						}
226
					}
227
				};
228
				lookupPlayers(server, lines, callback);
229
				whitelist.save();
230
				renameOldFile(OLD_WHITELIST);
231
				return true;
232
			} catch (IOException e) {
233
				LOGGER.warn("Could not read old whitelist to convert it!", e);
234
				return false;
235
			} catch (OldUsersConverter.ConversionError e) {
236
				LOGGER.error("Conversion failed, please try again later", e);
237
				return false;
238
			}
239
		} else {
240
			return true;
241
		}
242
	}
243
244
	public static @Nullable UUID convertMobOwnerIfNecessary(final MinecraftServer server, final String owner) {
245
		if (!StringUtil.isNullOrEmpty(owner) && owner.length() <= 16) {
246
			Optional<UUID> profileId = server.services().nameToIdCache().get(owner).map(NameAndId::id);
247
			if (profileId.isPresent()) {
248
				return profileId.get();
249
			} else if (!server.isSingleplayer() && server.usesAuthentication()) {
250
				final List<NameAndId> profiles = new ArrayList<>();
251
				ProfileLookupCallback callback = new ProfileLookupCallback() {
252
					@Override
253
					public void onProfileLookupSucceeded(final String profileName, final UUID profileIdx) {
254
						NameAndId profile = new NameAndId(profileIdx, profileName);
255
						server.services().nameToIdCache().add(profile);
256
						profiles.add(profile);
257
					}
258
259
					@Override
260
					public void onProfileLookupFailed(final String profileName, final Exception exception) {
261
						OldUsersConverter.LOGGER.warn("Could not lookup user whitelist entry for {}", profileName, exception);
262
					}
263
				};
264
				lookupPlayers(server, Lists.newArrayList(owner), callback);
265
				return !profiles.isEmpty() ? profiles.getFirst().id() : null;
266
			} else {
267
				return UUIDUtil.createOfflinePlayerUUID(owner);
268
			}
269
		} else {
270
			try {
271
				return UUID.fromString(owner);
272
			} catch (IllegalArgumentException ignored) {
273
				return null;
274
			}
275
		}
276
	}
277
278
	public static boolean convertPlayers(final DedicatedServer server) {
279
		final File worldPlayerDirectory = server.getWorldPath(LevelResource.PLAYER_OLD_DATA_DIR).toFile();
280
		final File worldNewPlayerDirectory = new File(worldPlayerDirectory.getParentFile(), LevelResource.PLAYER_DATA_DIR.id());
281
		final File unknownPlayerDirectory = new File(worldPlayerDirectory.getParentFile(), "unknownplayers");
282
		if (worldPlayerDirectory.exists() && worldPlayerDirectory.isDirectory()) {
283
			File[] playerFiles = worldPlayerDirectory.listFiles();
284
			List<String> playerNames = Lists.newArrayList();
285
286
			for (File file : playerFiles) {
287
				String fileName = file.getName();
288
				if (fileName.toLowerCase(Locale.ROOT).endsWith(".dat")) {
289
					String playerName = fileName.substring(0, fileName.length() - ".dat".length());
290
					if (!playerName.isEmpty()) {
291
						playerNames.add(playerName);
292
					}
293
				}
294
			}
295
296
			try {
297
				final String[] names = playerNames.toArray(new String[playerNames.size()]);
298
				ProfileLookupCallback callback = new ProfileLookupCallback() {
299
					@Override
300
					public void onProfileLookupSucceeded(final String profileName, final UUID profileId) {
301
						NameAndId profile = new NameAndId(profileId, profileName);
302
						server.services().nameToIdCache().add(profile);
303
						this.movePlayerFile(worldNewPlayerDirectory, this.getFileNameForProfile(profileName), profileId.toString());
304
					}
305
306
					@Override
307
					public void onProfileLookupFailed(final String profileName, final Exception exception) {
308
						OldUsersConverter.LOGGER.warn("Could not lookup user uuid for {}", profileName, exception);
309
						if (exception instanceof ProfileNotFoundException) {
310
							String fileNameForProfile = this.getFileNameForProfile(profileName);
311
							this.movePlayerFile(unknownPlayerDirectory, fileNameForProfile, fileNameForProfile);
312
						} else {
313
							throw new OldUsersConverter.ConversionError("Could not request user " + profileName + " from backend systems", exception);
314
						}
315
					}
316
317
					private void movePlayerFile(final File directory, final String oldName, final String newName) {
318
						File oldFileName = new File(worldPlayerDirectory, oldName + ".dat");
319
						File newFileName = new File(directory, newName + ".dat");
320
						OldUsersConverter.ensureDirectoryExists(directory);
321
						if (!oldFileName.renameTo(newFileName)) {
322
							throw new OldUsersConverter.ConversionError("Could not convert file for " + oldName);
323
						}
324
					}
325
326
					private String getFileNameForProfile(final String profileName) {
327
						String fileName = null;
328
329
						for (String name : names) {
330
							if (name != null && name.equalsIgnoreCase(profileName)) {
331
								fileName = name;
332
								break;
333
							}
334
						}
335
336
						if (fileName == null) {
337
							throw new OldUsersConverter.ConversionError("Could not find the filename for " + profileName + " anymore");
338
						} else {
339
							return fileName;
340
						}
341
					}
342
				};
343
				lookupPlayers(server, Lists.newArrayList(names), callback);
344
				return true;
345
			} catch (OldUsersConverter.ConversionError e) {
346
				LOGGER.error("Conversion failed, please try again later", e);
347
				return false;
348
			}
349
		} else {
350
			return true;
351
		}
352
	}
353
354
	private static void ensureDirectoryExists(final File directory) {
355
		if (directory.exists()) {
356
			if (!directory.isDirectory()) {
357
				throw new OldUsersConverter.ConversionError("Can't create directory " + directory.getName() + " in world save directory.");
358
			}
359
		} else if (!directory.mkdirs()) {
360
			throw new OldUsersConverter.ConversionError("Can't create directory " + directory.getName() + " in world save directory.");
361
		}
362
	}
363
364
	public static boolean areOldUserlistsRemoved() {
365
		boolean foundUserBanlist = false;
366
		if (OLD_USERBANLIST.exists() && OLD_USERBANLIST.isFile()) {
367
			foundUserBanlist = true;
368
		}
369
370
		boolean foundIpBanlist = false;
371
		if (OLD_IPBANLIST.exists() && OLD_IPBANLIST.isFile()) {
372
			foundIpBanlist = true;
373
		}
374
375
		boolean foundOpList = false;
376
		if (OLD_OPLIST.exists() && OLD_OPLIST.isFile()) {
377
			foundOpList = true;
378
		}
379
380
		boolean foundWhitelist = false;
381
		if (OLD_WHITELIST.exists() && OLD_WHITELIST.isFile()) {
382
			foundWhitelist = true;
383
		}
384
385
		if (!foundUserBanlist && !foundIpBanlist && !foundOpList && !foundWhitelist) {
386
			return true;
387
		}
388
389
		LOGGER.warn("**** FAILED TO START THE SERVER AFTER ACCOUNT CONVERSION!");
390
		LOGGER.warn("** please remove the following files and restart the server:");
391
		if (foundUserBanlist) {
392
			LOGGER.warn("* {}", OLD_USERBANLIST.getName());
393
		}
394
395
		if (foundIpBanlist) {
396
			LOGGER.warn("* {}", OLD_IPBANLIST.getName());
397
		}
398
399
		if (foundOpList) {
400
			LOGGER.warn("* {}", OLD_OPLIST.getName());
401
		}
402
403
		if (foundWhitelist) {
404
			LOGGER.warn("* {}", OLD_WHITELIST.getName());
405
		}
406
407
		return false;
408
	}
409
410
	private static void renameOldFile(final File file) {
411
		File newFile = new File(file.getName() + ".converted");
412
		file.renameTo(newFile);
413
	}
414
415
	private static Date parseDate(final String dateString, final Date defaultValue) {
416
		Date parsedDate;
417
		try {
418
			parsedDate = BanListEntry.DATE_FORMAT.parse(dateString);
419
		} catch (ParseException ignored) {
420
			parsedDate = defaultValue;
421
		}
422
423
		return parsedDate;
424
	}
425
426
	private static class ConversionError extends RuntimeException {
427
		private ConversionError(final String message, final Throwable cause) {
428
			super(message, cause);
429
		}
430
431
		private ConversionError(final String message) {
432
			super(message);
433
		}
434
	}
435
}
436

Decompiled Minecraft 26.3 source of OldUsersConverter (net/minecraft/server/players/OldUsersConverter.java) with Mojang official mappings, stored verbatim on the site.