From b544661e81bfe4358e41b001aef79579e1bbd324 Mon Sep 17 00:00:00 2001 From: TheKodeToad Date: Fri, 11 Nov 2022 10:32:54 +0000 Subject: [PATCH] Experimental skin fix, inspired by craftycodie's Signed-off-by: TheKodeToad --- launcher/minecraft/MinecraftInstance.cpp | 5 + .../pages/instance/InstanceSettingsPage.cpp | 7 + .../ui/pages/instance/InstanceSettingsPage.ui | 10 + libraries/launcher/CMakeLists.txt | 4 + .../org/prismlauncher/EntryPoint.java | 3 + .../launcher/org/prismlauncher/fix/Fix.java | 48 ++ .../launcher/org/prismlauncher/fix/Fixes.java | 56 +++ .../org/prismlauncher/fix/skins/SkinFix.java | 107 +++++ .../fix/skins/SkinFixUrlStreamHandler.java | 182 ++++++++ .../org/prismlauncher/utils/JsonParser.java | 433 ++++++++++++++++++ 10 files changed, 855 insertions(+) create mode 100644 libraries/launcher/org/prismlauncher/fix/Fix.java create mode 100644 libraries/launcher/org/prismlauncher/fix/Fixes.java create mode 100644 libraries/launcher/org/prismlauncher/fix/skins/SkinFix.java create mode 100644 libraries/launcher/org/prismlauncher/fix/skins/SkinFixUrlStreamHandler.java create mode 100644 libraries/launcher/org/prismlauncher/utils/JsonParser.java diff --git a/launcher/minecraft/MinecraftInstance.cpp b/launcher/minecraft/MinecraftInstance.cpp index 1d37224aa..91de955ad 100644 --- a/launcher/minecraft/MinecraftInstance.cpp +++ b/launcher/minecraft/MinecraftInstance.cpp @@ -192,6 +192,8 @@ void MinecraftInstance::loadSpecificSettings() m_settings->registerSetting("JoinServerOnLaunch", false); m_settings->registerSetting("JoinServerOnLaunchAddress", ""); + m_settings->registerSetting("LegacySkinFix", true); + qDebug() << "Instance-type specific settings were loaded!"; setSpecificSettingsLoaded(true); @@ -661,6 +663,9 @@ QString MinecraftInstance::createLaunchScript(AuthSessionPtr session, MinecraftS launchScript += "traits " + trait + "\n"; } + if (profile->getTraits().contains("legacySkins") && settings()->get("LegacySkinFix").toBool()) + launchScript += "fixes legacySkinFix\n"; + launchScript += "launcher " + getLauncher() + "\n"; // qDebug() << "Generated launch script:" << launchScript; diff --git a/launcher/ui/pages/instance/InstanceSettingsPage.cpp b/launcher/ui/pages/instance/InstanceSettingsPage.cpp index af2ba7c80..537271a2c 100644 --- a/launcher/ui/pages/instance/InstanceSettingsPage.cpp +++ b/launcher/ui/pages/instance/InstanceSettingsPage.cpp @@ -3,6 +3,7 @@ * PolyMC - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield * Copyright (C) 2022 Sefa Eyeoglu + * Copyright (C) 2022 TheKodeToad * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -275,6 +276,9 @@ void InstanceSettingsPage::applySettings() m_settings->reset("JoinServerOnLaunchAddress"); } + bool legacySkinFix = ui->legacySkinFix->isChecked(); + m_settings->set("LegacySkinFix", legacySkinFix); + // FIXME: This should probably be called by a signal instead m_instance->updateRuntimeContext(); } @@ -372,6 +376,9 @@ void InstanceSettingsPage::loadSettings() ui->serverJoinGroupBox->setChecked(m_settings->get("JoinServerOnLaunch").toBool()); ui->serverJoinAddress->setText(m_settings->get("JoinServerOnLaunchAddress").toString()); + + ui->legacySkinFix->setChecked(m_settings->get("LegacySkinFix").toBool()); + ui->legacySkinFix->setVisible(m_instance->traits().contains("legacySkins")); } void InstanceSettingsPage::on_javaDetectBtn_clicked() diff --git a/launcher/ui/pages/instance/InstanceSettingsPage.ui b/launcher/ui/pages/instance/InstanceSettingsPage.ui index b064367d1..ca49cbbe5 100644 --- a/launcher/ui/pages/instance/InstanceSettingsPage.ui +++ b/launcher/ui/pages/instance/InstanceSettingsPage.ui @@ -608,6 +608,16 @@ + + + + Enables support for modern skins on old versions. + + + Enable legacy skin fix + + + diff --git a/libraries/launcher/CMakeLists.txt b/libraries/launcher/CMakeLists.txt index 55ed58756..1ad398ff5 100644 --- a/libraries/launcher/CMakeLists.txt +++ b/libraries/launcher/CMakeLists.txt @@ -15,6 +15,10 @@ set(SRC org/prismlauncher/launcher/impl/legacy/LegacyFrame.java org/prismlauncher/exception/ParameterNotFoundException.java org/prismlauncher/exception/ParseException.java + org/prismlauncher/fix/Fix.java + org/prismlauncher/fix/Fixes.java + org/prismlauncher/fix/skins/SkinFix.java + org/prismlauncher/fix/skins/SkinFixUrlStreamHandler.java org/prismlauncher/utils/Parameters.java org/prismlauncher/utils/ReflectionUtils.java org/prismlauncher/utils/logging/Level.java diff --git a/libraries/launcher/org/prismlauncher/EntryPoint.java b/libraries/launcher/org/prismlauncher/EntryPoint.java index 78804b3e8..88ecb48ce 100644 --- a/libraries/launcher/org/prismlauncher/EntryPoint.java +++ b/libraries/launcher/org/prismlauncher/EntryPoint.java @@ -59,6 +59,7 @@ import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import org.prismlauncher.exception.ParseException; +import org.prismlauncher.fix.Fixes; import org.prismlauncher.launcher.Launcher; import org.prismlauncher.launcher.impl.StandardLauncher; import org.prismlauncher.launcher.impl.legacy.LegacyLauncher; @@ -107,6 +108,8 @@ public final class EntryPoint { } try { + Fixes.apply(params); + Launcher launcher; String type = params.getString("launcher"); diff --git a/libraries/launcher/org/prismlauncher/fix/Fix.java b/libraries/launcher/org/prismlauncher/fix/Fix.java new file mode 100644 index 000000000..da578c24f --- /dev/null +++ b/libraries/launcher/org/prismlauncher/fix/Fix.java @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2022 TheKodeToad + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * Linking this library statically or dynamically with other modules is + * making a combined work based on this library. Thus, the terms and + * conditions of the GNU General Public License cover the whole + * combination. + * + * As a special exception, the copyright holders of this library give + * you permission to link this library with independent modules to + * produce an executable, regardless of the license terms of these + * independent modules, and to copy and distribute the resulting + * executable under terms of your choice, provided that you also meet, + * for each linked independent module, the terms and conditions of the + * license of that module. An independent module is a module which is + * not derived from or based on this library. If you modify this + * library, you may extend this exception to your version of the + * library, but you are not obliged to do so. If you do not wish to do + * so, delete this exception statement from your version. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.prismlauncher.fix; + +import org.prismlauncher.utils.Parameters; + +public interface Fix { + + String getName(); + + boolean isApplicable(Parameters parameters); + + void apply(); + +} diff --git a/libraries/launcher/org/prismlauncher/fix/Fixes.java b/libraries/launcher/org/prismlauncher/fix/Fixes.java new file mode 100644 index 000000000..ad472fea5 --- /dev/null +++ b/libraries/launcher/org/prismlauncher/fix/Fixes.java @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2022 TheKodeToad + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * Linking this library statically or dynamically with other modules is + * making a combined work based on this library. Thus, the terms and + * conditions of the GNU General Public License cover the whole + * combination. + * + * As a special exception, the copyright holders of this library give + * you permission to link this library with independent modules to + * produce an executable, regardless of the license terms of these + * independent modules, and to copy and distribute the resulting + * executable under terms of your choice, provided that you also meet, + * for each linked independent module, the terms and conditions of the + * license of that module. An independent module is a module which is + * not derived from or based on this library. If you modify this + * library, you may extend this exception to your version of the + * library, but you are not obliged to do so. If you do not wish to do + * so, delete this exception statement from your version. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.prismlauncher.fix; + +import java.util.Collections; +import java.util.List; + +import org.prismlauncher.fix.skins.SkinFix; +import org.prismlauncher.utils.Parameters; + +public final class Fixes { + + private static final Fix[] FIXES = { new SkinFix() }; + + public static void apply(Parameters parameters) { + List fixes = parameters.getList("fixes", Collections.emptyList()); + + for (Fix fix : FIXES) + if (fixes.contains(fix.getName()) && fix.isApplicable(parameters)) + fix.apply(); + } + +} diff --git a/libraries/launcher/org/prismlauncher/fix/skins/SkinFix.java b/libraries/launcher/org/prismlauncher/fix/skins/SkinFix.java new file mode 100644 index 000000000..8d0969a6d --- /dev/null +++ b/libraries/launcher/org/prismlauncher/fix/skins/SkinFix.java @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2022 TheKodeToad + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * Linking this library statically or dynamically with other modules is + * making a combined work based on this library. Thus, the terms and + * conditions of the GNU General Public License cover the whole + * combination. + * + * As a special exception, the copyright holders of this library give + * you permission to link this library with independent modules to + * produce an executable, regardless of the license terms of these + * independent modules, and to copy and distribute the resulting + * executable under terms of your choice, provided that you also meet, + * for each linked independent module, the terms and conditions of the + * license of that module. An independent module is a module which is + * not derived from or based on this library. If you modify this + * library, you may extend this exception to your version of the + * library, but you are not obliged to do so. If you do not wish to do + * so, delete this exception statement from your version. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.prismlauncher.fix.skins; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; + +import org.prismlauncher.fix.Fix; +import org.prismlauncher.utils.Parameters; +import org.prismlauncher.utils.logging.Log; + +public final class SkinFix implements Fix, URLStreamHandlerFactory { + + private static URLStreamHandler http; + private static MethodHandle openConnection; + private static MethodHandle openConnection2; + + static { + try { + Method getURLStreamHandler = URL.class.getDeclaredMethod("getURLStreamHandler", String.class); + getURLStreamHandler.setAccessible(true); + http = (URLStreamHandler) getURLStreamHandler.invoke(null, "http"); + + Method openConnectionReflect = URLStreamHandler.class.getDeclaredMethod("openConnection", URL.class); + openConnectionReflect.setAccessible(true); + openConnection = MethodHandles.lookup().unreflect(openConnectionReflect); + + Method openConnectionReflect2 = URLStreamHandler.class.getDeclaredMethod("openConnection", URL.class, + Proxy.class); + openConnectionReflect2.setAccessible(true); + openConnection2 = MethodHandles.lookup().unreflect(openConnectionReflect2); + } catch (Throwable e) { + Log.error("Could not perform URL reflection; skin fix will not be availble", e); + } + } + + static URLConnection openConnection(URL url) throws Throwable { + return (URLConnection) openConnection.invokeExact(http, url); + } + + static URLConnection openConnection(URL url, Proxy proxy) throws Throwable { + return (URLConnection) openConnection2.invokeExact(http, url, proxy); + } + + @Override + public String getName() { + return "legacySkinFix"; + } + + @Override + public boolean isApplicable(Parameters parameters) { + return http != null && openConnection != null; + } + + @Override + public void apply() { + URL.setURLStreamHandlerFactory(this); + } + + @Override + public URLStreamHandler createURLStreamHandler(String protocol) { + if ("http".equals(protocol)) + return new SkinFixUrlStreamHandler(); + + return null; + } + +} diff --git a/libraries/launcher/org/prismlauncher/fix/skins/SkinFixUrlStreamHandler.java b/libraries/launcher/org/prismlauncher/fix/skins/SkinFixUrlStreamHandler.java new file mode 100644 index 000000000..71af341c5 --- /dev/null +++ b/libraries/launcher/org/prismlauncher/fix/skins/SkinFixUrlStreamHandler.java @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2022 TheKodeToad + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * Linking this library statically or dynamically with other modules is + * making a combined work based on this library. Thus, the terms and + * conditions of the GNU General Public License cover the whole + * combination. + * + * As a special exception, the copyright holders of this library give + * you permission to link this library with independent modules to + * produce an executable, regardless of the license terms of these + * independent modules, and to copy and distribute the resulting + * executable under terms of your choice, provided that you also meet, + * for each linked independent module, the terms and conditions of the + * license of that module. An independent module is a module which is + * not derived from or based on this library. If you modify this + * library, you may extend this exception to your version of the + * library, but you are not obliged to do so. If you do not wish to do + * so, delete this exception statement from your version. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.prismlauncher.fix.skins; + +import java.io.IOException; +import java.io.InputStream; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.util.Map; + +import javax.xml.bind.DatatypeConverter; + +import org.prismlauncher.utils.JsonParser; + +@SuppressWarnings("unchecked") +final class SkinFixUrlStreamHandler extends URLStreamHandler { + + private URL redirect(URL address) throws IOException { + String skinOwner = findSkinOwner(address); + + if (skinOwner != null) + return convertSkin(address, skinOwner); + + String capeOwner = findCapeOwner(address); + + if (capeOwner != null) + return convertCape(address, capeOwner); + + return address; + } + + @Override + protected URLConnection openConnection(URL address) throws IOException { + address = redirect(address); + + try { + return SkinFix.openConnection(address); + } catch (RuntimeException | Error e) { + throw e; + } catch (Throwable e) { + throw new IllegalStateException(e); + } + } + + @Override + protected URLConnection openConnection(URL address, Proxy proxy) throws IOException { + address = redirect(address); + + try { + return SkinFix.openConnection(address, proxy); + } catch (RuntimeException | Error e) { + throw e; + } catch (Throwable e) { + throw new IllegalStateException(e); + } + } + + private URL convertSkin(URL defaultUrl, String owner) throws IOException { + Map textures = getTextures(owner); + + if (textures != null) { + textures = (Map) textures.get("SKIN"); + return new URL((String) textures.get("url")); + } + + return defaultUrl; + } + + private URL convertCape(URL defaultUrl, String owner) throws IOException { + Map textures = getTextures(owner); + + if (textures != null) { + textures = (Map) textures.get("CAPE"); + + if (textures == null) + return defaultUrl; + + return new URL((String) textures.get("url")); + } + + return defaultUrl; + } + + private static Map getTextures(String owner) throws IOException { + try (InputStream in = new URL("https://api.mojang.com/users/profiles/minecraft/" + owner).openStream()) { + Map map = (Map) JsonParser.parse(in); + String id = (String) map.get("id"); + + try (InputStream profileIn = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + id) + .openStream()) { + Map profile = (Map) JsonParser.parse(profileIn); + + for (Map property : (Iterable>) profile.get("properties")) { + if (property.get("name").equals("textures")) { + Map result = (Map) JsonParser + .parse(new String(DatatypeConverter.parseBase64Binary((String) property.get("value")))); + result = (Map) result.get("textures"); + return result; + } + } + + return null; + } + } + } + + private static String findSkinOwner(URL address) { + switch (address.getHost()) { + case "www.minecraft.net": + return stripPng(strip(address.getPath(), "/skin/")); + + case "s3.amazonaws.com": + case "skins.minecraft.net": + return stripPng(strip(address.getPath(), "/MinecraftSkins/")); + } + + return null; + } + + private static String findCapeOwner(URL address) { + switch (address.getHost()) { + case "www.minecraft.net": + return stripPng(strip(address.getQuery(), "user=")); + + case "s3.amazonaws.com": + case "skins.minecraft.net": + return stripPng(strip(address.getPath(), "/MinecraftCloaks/")); + } + + return null; + } + + private static String stripPng(String string) { + if (string != null && string.endsWith(".png")) + return string.substring(0, string.lastIndexOf('.')); + + return string; + } + + private static String strip(String string, String prefix) { + if (string != null && string.startsWith(prefix)) + return string.substring(prefix.length()); + + return null; + } + +} diff --git a/libraries/launcher/org/prismlauncher/utils/JsonParser.java b/libraries/launcher/org/prismlauncher/utils/JsonParser.java new file mode 100644 index 000000000..e1703972b --- /dev/null +++ b/libraries/launcher/org/prismlauncher/utils/JsonParser.java @@ -0,0 +1,433 @@ +// SPDX-License-Identifier: GPL-3.0-only +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2022 TheKodeToad + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * Linking this library statically or dynamically with other modules is + * making a combined work based on this library. Thus, the terms and + * conditions of the GNU General Public License cover the whole + * combination. + * + * As a special exception, the copyright holders of this library give + * you permission to link this library with independent modules to + * produce an executable, regardless of the license terms of these + * independent modules, and to copy and distribute the resulting + * executable under terms of your choice, provided that you also meet, + * for each linked independent module, the terms and conditions of the + * license of that module. An independent module is a module which is + * not derived from or based on this library. If you modify this + * library, you may extend this exception to your version of the + * library, but you are not obliged to do so. If you do not wish to do + * so, delete this exception statement from your version. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * This file incorporates work covered by the following copyright and + * permission notice: + * + * MIT License + * + * Copyright (c) 2022 TheKodeToad + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.prismlauncher.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Single-file JSON parser to allow for usage in versions without GSON. + */ +public final class JsonParser { + + private final Reader in; + private char[] buffer; + private int pos, length; + + public static Object parse(String in) throws JsonParseException, IOException { + return parse(new StringReader(in)); + } + + public static Object parse(InputStream in) throws JsonParseException, IOException { + return parse(new InputStreamReader(in, StandardCharsets.UTF_8)); + } + + public static Object parse(Reader in) throws JsonParseException, IOException { + return new JsonParser(in).readSingleValue(); + } + + private JsonParser(Reader in) throws IOException { + this.in = in; + pos = length = 0; + read(); + } + + private int character() { + if (length == -1) + return -1; + + return buffer[pos]; + } + + private int read() throws IOException { + if (length == -1) + return -1; + + if (buffer == null || pos++ == length - 1) { + pos = 0; + buffer = new char[8192]; + length = in.read(buffer); + } + + return character(); + } + + private void assertCharacter(char character) throws JsonParseException { + if (character() != character) + throw new JsonParseException("Expected '" + character + "' but got " + + (character() != -1 ? ("'" + (char) character() + "'") : "EOF")); + } + + private void assertNoEOF(String expected) throws JsonParseException { + if (character() == -1) + throw new JsonParseException("Expected " + expected + " but got EOF"); + } + + private void skipWhitespace() throws IOException { + while (isWhitespace()) + read(); + } + + private boolean isWhitespace() { + return character() == ' ' || character() == '\n' || character() == '\r' || character() == '\t'; + } + + private Object readSingleValue() throws IOException { + skipWhitespace(); + Object result = readValue(); + + if (!(result instanceof Double)) + read(); + + skipWhitespace(); + + if (character() != -1) + throw new JsonParseException("Found trailing non-whitespace characters"); + + return result; + } + + private Object readValue() throws IOException { + assertNoEOF("a value"); + + int character = character(); + + switch (character) { + case '{': + return readObject(); + + case '[': + return readArray(); + + case '"': + return readString(); + + case 't': + case 'f': + // probably boolean + Boolean bool = readBoolean(); + if (bool != null) + return bool; + + break; + + case 'n': + // probably null + if (readNull()) + return null; + + break; + } + + if (character == '-' || isDigit()) + // probably a number + return readNumber(); + + throw new JsonParseException("Expected a JSON value but got '" + (char) character + "'"); + } + + private Map readObject() throws IOException { + assertCharacter('{'); + Map obj = new HashMap<>(); + boolean comma = false; + + read(); + skipWhitespace(); + + while (character() != '}') { + if (comma) { + assertCharacter(','); + read(); + skipWhitespace(); + } + + String key = readString(); + read(); + skipWhitespace(); + assertCharacter(':'); + read(); + skipWhitespace(); + + Object value = readValue(); + obj.put(key, value); + + if (!(value instanceof Double)) + read(); + + skipWhitespace(); + comma = true; + } + + return obj; + } + + private List readArray() throws IOException { + assertCharacter('['); + List array = new ArrayList<>(); + boolean comma = false; + + read(); + skipWhitespace(); + + while (character() != ']') { + if (comma) { + assertCharacter(','); + read(); + skipWhitespace(); + } + + Object value = readValue(); + array.add(value); + + if (!(value instanceof Double)) + read(); + + skipWhitespace(); + comma = true; + } + + return array; + } + + private String readString() throws IOException { + assertCharacter('"'); + + StringBuilder result = new StringBuilder(); + + while (read() != '"') { + int character = character(); + + if (character >= '\u0000' && character <= '\u001F') + throw new JsonParseException("Found unescaped control character within string"); + + switch (character) { + case -1: + throw new JsonParseException("Expected '\"' but got EOF"); + + case 0x7F: + if (read() == '"') { + return result.toString(); + } + continue; + + case '\\': + int seq = read(); + + switch (seq) { + case -1: + throw new JsonParseException("Expected an escape sequence but got EOF"); + + case '\\': + break; + + case '/': + case '\"': + character = seq; + break; + + case 'b': + character = '\b'; + break; + + case 'f': + character = '\f'; + break; + + case 'n': + character = '\n'; + break; + + case 'r': + character = '\r'; + break; + + case 't': + character = '\t'; + break; + + case 'u': + // char array to allow allocation in advance. + char[] digits = new char[4]; + + for (int index = 0; index < digits.length; index++) { + character = read(); + if (index == 0 && character() == '-') { + throw new JsonParseException("Hex sequence may not be negative"); + } else if (character() == -1) { + throw new JsonParseException("Expected a hex sequence but got EOF"); + } + digits[index] = (char) character; + } + + String digitsString = new String(digits); + + try { + character = Integer.parseInt(digitsString, 16); + } catch (NumberFormatException e) { + throw new JsonParseException("Could not parse hex sequence \"" + digitsString + "\""); + } + + break; + default: + throw new JsonParseException("Invalid escape sequence: \\" + (char) seq); + } + break; + } + + result.append((char) character); + } + + return result.toString(); + } + + private boolean isDigit() { + return character() >= '0' && character() <= '9'; + } + + private Double readNumber() throws IOException { + StringBuilder result = new StringBuilder(); + + if (character() == '-') { + result.append((char) character()); + read(); + } + + if (character() == '0') { + result.append((char) character()); + read(); + if (isDigit()) + throw new JsonParseException("Found superfluous leading zero"); + } else if (!isDigit()) + throw new JsonParseException("Expected digits"); + + while (character() != -1 && isDigit()) { + result.append((char) character()); + read(); + } + + if (character() == '.') { + result.append('.'); + + read(); + assertNoEOF("digits"); + + if (!isDigit()) + throw new JsonParseException("Expected digits after decimal point"); + + while (character() != -1 && isDigit()) { + result.append((char) character()); + read(); + } + } + + if (character() == 'e' || character() == 'E') { + result.append('E'); + + read(); + assertNoEOF("digits"); + + if (character() == '+' || character() == '-') { + result.append((char) character()); + read(); + } + + if (!(character() == '+' || character() == '-' || isDigit())) + throw new JsonParseException("Expected exponent digits"); + + while (character() != -1 && isDigit()) { + result.append((char) character()); + read(); + } + } + + String resultStr = result.toString(); + + try { + return Double.parseDouble(resultStr); + } catch (NumberFormatException e) { + throw new JsonParseException("Failed to parse number '" + resultStr + "'"); + } + } + + private Boolean readBoolean() throws IOException { + if (character() == 't') { + if (read() == 'r' && read() == 'u' && read() == 'e') { + return true; + } + } else if (character() == 'f') { + if (read() == 'a' && read() == 'l' && read() == 's' && read() == 'e') { + return false; + } + } + return null; + } + + private boolean readNull() throws IOException { + return character() == 'n' && read() == 'u' && read() == 'l' && read() == 'l'; + } + + public class JsonParseException extends IOException { + + private static final long serialVersionUID = 1L; + + public JsonParseException(String message) { + super(message); + } + + } + +} \ No newline at end of file